Skip to content

Commit

Permalink
Merge pull request #1788 from KingSora/main
Browse files Browse the repository at this point in the history
fix: `absolute: true` source maps will preserve source content
  • Loading branch information
ai committed Oct 12, 2022
2 parents 767c83e + a1c0b8b commit a11d868
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 12 deletions.
29 changes: 17 additions & 12 deletions lib/map-generator.js
Expand Up @@ -16,6 +16,7 @@ class MapGenerator {
this.root = root
this.opts = opts
this.css = cssString
this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute
}

isMap() {
Expand Down Expand Up @@ -97,10 +98,10 @@ class MapGenerator {
let from = node.source.input.from
if (from && !already[from]) {
already[from] = true
this.map.setSourceContent(
this.toUrl(this.path(from)),
node.source.input.css
)
let fromUrl = this.usesFileUrls
? this.toFileUrl(from)
: this.toUrl(this.path(from))
this.map.setSourceContent(fromUrl, node.source.input.css)
}
}
})
Expand Down Expand Up @@ -232,17 +233,21 @@ class MapGenerator {
return encodeURI(path).replace(/[#?]/g, encodeURIComponent)
}

toFileUrl(path) {
if (pathToFileURL) {
return pathToFileURL(path).toString()
} else {
throw new Error(
'`map.absolute` option is not available in this PostCSS build'
)
}
}

sourcePath(node) {
if (this.mapOpts.from) {
return this.toUrl(this.mapOpts.from)
} else if (this.mapOpts.absolute) {
if (pathToFileURL) {
return pathToFileURL(node.source.input.from).toString()
} else {
throw new Error(
'`map.absolute` option is not available in this PostCSS build'
)
}
} else if (this.usesFileUrls) {
return this.toFileUrl(node.source.input.from)
} else {
return this.toUrl(this.path(node.source.input.from))
}
Expand Down
15 changes: 15 additions & 0 deletions test/map.test.ts
Expand Up @@ -2,6 +2,7 @@ import { SourceMapConsumer, SourceMapGenerator } from 'source-map-js'
import { removeSync, outputFileSync } from 'fs-extra'
import { is, type, equal, match } from 'uvu/assert'
import { join, resolve, parse } from 'path'
import { pathToFileURL } from 'url'
import { existsSync } from 'fs'
import { test } from 'uvu'

Expand Down Expand Up @@ -722,4 +723,18 @@ test('supports previous inline map with empty processor', () => {
match((root3.source?.input.origin(1, 0) as any).file, 'a.css')
})

test('absolute sourcemaps have source contents', () => {
let result = postcss([() => {}]).process('a{}', {
from: '/dir/to/a.css',
map: {
inline: false,
absolute: true
}
})
equal(result.map.toJSON().sources, [
pathToFileURL('/dir/to/a.css').toString()
])
equal(result.map.toJSON().sourcesContent, ['a{}'])
})

test.run()

0 comments on commit a11d868

Please sign in to comment.