map-generator.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. 'use strict'
  2. let { dirname, relative, resolve, sep } = require('path')
  3. let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
  4. let { pathToFileURL } = require('url')
  5. let Input = require('./input')
  6. let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator)
  7. let pathAvailable = Boolean(dirname && resolve && relative && sep)
  8. class MapGenerator {
  9. constructor(stringify, root, opts, cssString) {
  10. this.stringify = stringify
  11. this.mapOpts = opts.map || {}
  12. this.root = root
  13. this.opts = opts
  14. this.css = cssString
  15. this.originalCSS = cssString
  16. this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute
  17. this.memoizedFileURLs = new Map()
  18. this.memoizedPaths = new Map()
  19. this.memoizedURLs = new Map()
  20. }
  21. addAnnotation() {
  22. let content
  23. if (this.isInline()) {
  24. content =
  25. 'data:application/json;base64,' + this.toBase64(this.map.toString())
  26. } else if (typeof this.mapOpts.annotation === 'string') {
  27. content = this.mapOpts.annotation
  28. } else if (typeof this.mapOpts.annotation === 'function') {
  29. content = this.mapOpts.annotation(this.opts.to, this.root)
  30. } else {
  31. content = this.outputFile() + '.map'
  32. }
  33. let eol = '\n'
  34. if (this.css.includes('\r\n')) eol = '\r\n'
  35. this.css += eol + '/*# sourceMappingURL=' + content + ' */'
  36. }
  37. applyPrevMaps() {
  38. for (let prev of this.previous()) {
  39. let from = this.toUrl(this.path(prev.file))
  40. let root = prev.root || dirname(prev.file)
  41. let map
  42. if (this.mapOpts.sourcesContent === false) {
  43. map = new SourceMapConsumer(prev.text)
  44. if (map.sourcesContent) {
  45. map.sourcesContent = null
  46. }
  47. } else {
  48. map = prev.consumer()
  49. }
  50. this.map.applySourceMap(map, from, this.toUrl(this.path(root)))
  51. }
  52. }
  53. clearAnnotation() {
  54. if (this.mapOpts.annotation === false) return
  55. if (this.root) {
  56. let node
  57. for (let i = this.root.nodes.length - 1; i >= 0; i--) {
  58. node = this.root.nodes[i]
  59. if (node.type !== 'comment') continue
  60. if (node.text.startsWith('# sourceMappingURL=')) {
  61. this.root.removeChild(i)
  62. }
  63. }
  64. } else if (this.css) {
  65. let startIndex
  66. while ((startIndex = this.css.lastIndexOf('/*#')) !== -1) {
  67. let endIndex = this.css.indexOf('*/', startIndex + 3)
  68. if (endIndex === -1) break
  69. while (startIndex > 0 && this.css[startIndex - 1] === '\n') {
  70. startIndex--
  71. }
  72. this.css = this.css.slice(0, startIndex) + this.css.slice(endIndex + 2)
  73. }
  74. }
  75. }
  76. generate() {
  77. this.clearAnnotation()
  78. if (pathAvailable && sourceMapAvailable && this.isMap()) {
  79. return this.generateMap()
  80. } else {
  81. let result = ''
  82. this.stringify(this.root, i => {
  83. result += i
  84. })
  85. return [result]
  86. }
  87. }
  88. generateMap() {
  89. if (this.root) {
  90. this.generateString()
  91. } else if (this.previous().length === 1) {
  92. let prev = this.previous()[0].consumer()
  93. prev.file = this.outputFile()
  94. this.map = SourceMapGenerator.fromSourceMap(prev, {
  95. ignoreInvalidMapping: true
  96. })
  97. } else {
  98. this.map = new SourceMapGenerator({
  99. file: this.outputFile(),
  100. ignoreInvalidMapping: true
  101. })
  102. this.map.addMapping({
  103. generated: { column: 0, line: 1 },
  104. original: { column: 0, line: 1 },
  105. source: this.opts.from
  106. ? this.toUrl(this.path(this.opts.from))
  107. : '<no source>'
  108. })
  109. }
  110. if (this.isSourcesContent()) this.setSourcesContent()
  111. if (this.root && this.previous().length > 0) this.applyPrevMaps()
  112. if (this.isAnnotation()) this.addAnnotation()
  113. if (this.isInline()) {
  114. return [this.css]
  115. } else {
  116. return [this.css, this.map]
  117. }
  118. }
  119. generateString() {
  120. this.css = ''
  121. this.map = new SourceMapGenerator({
  122. file: this.outputFile(),
  123. ignoreInvalidMapping: true
  124. })
  125. let line = 1
  126. let column = 1
  127. let noSource = '<no source>'
  128. let mapping = {
  129. generated: { column: 0, line: 0 },
  130. original: { column: 0, line: 0 },
  131. source: ''
  132. }
  133. let last, lines
  134. this.stringify(this.root, (str, node, type) => {
  135. this.css += str
  136. if (node && type !== 'end') {
  137. mapping.generated.line = line
  138. mapping.generated.column = column - 1
  139. if (node.source && node.source.start) {
  140. mapping.source = this.sourcePath(node)
  141. mapping.original.line = node.source.start.line
  142. mapping.original.column = node.source.start.column - 1
  143. this.map.addMapping(mapping)
  144. } else {
  145. mapping.source = noSource
  146. mapping.original.line = 1
  147. mapping.original.column = 0
  148. this.map.addMapping(mapping)
  149. }
  150. }
  151. lines = str.match(/\n/g)
  152. if (lines) {
  153. line += lines.length
  154. last = str.lastIndexOf('\n')
  155. column = str.length - last
  156. } else {
  157. column += str.length
  158. }
  159. if (node && type !== 'start') {
  160. let p = node.parent || { raws: {} }
  161. let childless =
  162. node.type === 'decl' || (node.type === 'atrule' && !node.nodes)
  163. if (!childless || node !== p.last || p.raws.semicolon) {
  164. if (node.source && node.source.end) {
  165. mapping.source = this.sourcePath(node)
  166. mapping.original.line = node.source.end.line
  167. mapping.original.column = node.source.end.column - 1
  168. mapping.generated.line = line
  169. mapping.generated.column = column - 2
  170. this.map.addMapping(mapping)
  171. } else {
  172. mapping.source = noSource
  173. mapping.original.line = 1
  174. mapping.original.column = 0
  175. mapping.generated.line = line
  176. mapping.generated.column = column - 1
  177. this.map.addMapping(mapping)
  178. }
  179. }
  180. }
  181. })
  182. }
  183. isAnnotation() {
  184. if (this.isInline()) {
  185. return true
  186. }
  187. if (typeof this.mapOpts.annotation !== 'undefined') {
  188. return this.mapOpts.annotation
  189. }
  190. if (this.previous().length) {
  191. return this.previous().some(i => i.annotation)
  192. }
  193. return true
  194. }
  195. isInline() {
  196. if (typeof this.mapOpts.inline !== 'undefined') {
  197. return this.mapOpts.inline
  198. }
  199. let annotation = this.mapOpts.annotation
  200. if (typeof annotation !== 'undefined' && annotation !== true) {
  201. return false
  202. }
  203. if (this.previous().length) {
  204. return this.previous().some(i => i.inline)
  205. }
  206. return true
  207. }
  208. isMap() {
  209. if (typeof this.opts.map !== 'undefined') {
  210. return !!this.opts.map
  211. }
  212. return this.previous().length > 0
  213. }
  214. isSourcesContent() {
  215. if (typeof this.mapOpts.sourcesContent !== 'undefined') {
  216. return this.mapOpts.sourcesContent
  217. }
  218. if (this.previous().length) {
  219. return this.previous().some(i => i.withContent())
  220. }
  221. return true
  222. }
  223. outputFile() {
  224. if (this.opts.to) {
  225. return this.path(this.opts.to)
  226. } else if (this.opts.from) {
  227. return this.path(this.opts.from)
  228. } else {
  229. return 'to.css'
  230. }
  231. }
  232. path(file) {
  233. if (this.mapOpts.absolute) return file
  234. if (file.charCodeAt(0) === 60 /* `<` */) return file
  235. if (/^\w+:\/\//.test(file)) return file
  236. let cached = this.memoizedPaths.get(file)
  237. if (cached) return cached
  238. let from = this.opts.to ? dirname(this.opts.to) : '.'
  239. if (typeof this.mapOpts.annotation === 'string') {
  240. from = dirname(resolve(from, this.mapOpts.annotation))
  241. }
  242. let path = relative(from, file)
  243. this.memoizedPaths.set(file, path)
  244. return path
  245. }
  246. previous() {
  247. if (!this.previousMaps) {
  248. this.previousMaps = []
  249. if (this.root) {
  250. this.root.walk(node => {
  251. if (node.source && node.source.input.map) {
  252. let map = node.source.input.map
  253. if (!this.previousMaps.includes(map)) {
  254. this.previousMaps.push(map)
  255. }
  256. }
  257. })
  258. } else {
  259. let input = new Input(this.originalCSS, this.opts)
  260. if (input.map) this.previousMaps.push(input.map)
  261. }
  262. }
  263. return this.previousMaps
  264. }
  265. setSourcesContent() {
  266. let already = {}
  267. if (this.root) {
  268. this.root.walk(node => {
  269. if (node.source) {
  270. let from = node.source.input.from
  271. if (from && !already[from]) {
  272. already[from] = true
  273. let fromUrl = this.usesFileUrls
  274. ? this.toFileUrl(from)
  275. : this.toUrl(this.path(from))
  276. this.map.setSourceContent(fromUrl, node.source.input.css)
  277. }
  278. }
  279. })
  280. } else if (this.css) {
  281. let from = this.opts.from
  282. ? this.toUrl(this.path(this.opts.from))
  283. : '<no source>'
  284. this.map.setSourceContent(from, this.css)
  285. }
  286. }
  287. sourcePath(node) {
  288. if (this.mapOpts.from) {
  289. return this.toUrl(this.mapOpts.from)
  290. } else if (this.usesFileUrls) {
  291. return this.toFileUrl(node.source.input.from)
  292. } else {
  293. return this.toUrl(this.path(node.source.input.from))
  294. }
  295. }
  296. toBase64(str) {
  297. if (Buffer) {
  298. return Buffer.from(str).toString('base64')
  299. } else {
  300. return window.btoa(unescape(encodeURIComponent(str)))
  301. }
  302. }
  303. toFileUrl(path) {
  304. let cached = this.memoizedFileURLs.get(path)
  305. if (cached) return cached
  306. if (pathToFileURL) {
  307. let fileURL = pathToFileURL(path).toString()
  308. this.memoizedFileURLs.set(path, fileURL)
  309. return fileURL
  310. } else {
  311. throw new Error(
  312. '`map.absolute` option is not available in this PostCSS build'
  313. )
  314. }
  315. }
  316. toUrl(path) {
  317. let cached = this.memoizedURLs.get(path)
  318. if (cached) return cached
  319. if (sep === '\\') {
  320. path = path.replace(/\\/g, '/')
  321. }
  322. let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent)
  323. this.memoizedURLs.set(path, url)
  324. return url
  325. }
  326. }
  327. module.exports = MapGenerator