map-generator.js 9.4 KB

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