Gathering detailed insights and metrics for source-map
Gathering detailed insights and metrics for source-map
Gathering detailed insights and metrics for source-map
Gathering detailed insights and metrics for source-map
merge-source-map
Merge old source map and new source map in multi-transform flow
metro-source-map
🚇 Source map generator for Metro.
convert-source-map
Converts a source-map from/to different formats and allows adding/changing properties.
source-map-loader
extracts inlined source map and offers it to webpack
npm install source-map
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
3,570 Stars
706 Commits
360 Forks
70 Watching
6 Branches
96 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
JavaScript (74.64%)
Rust (19.67%)
Python (2.45%)
R (2.41%)
HTML (0.57%)
Shell (0.26%)
Cumulative downloads
Total Downloads
Last day
-7.4%
32,871,663
Compared to previous day
Last week
-0.2%
192,711,247
Compared to previous week
Last month
15.4%
804,923,779
Compared to previous month
Last year
1.9%
8,294,817,114
Compared to previous year
8
This is a library to generate and consume the source map format described here.
$ npm install source-map
1<script src="https://unpkg.com/source-map@0.7.3/dist/source-map.js"></script> 2<script> 3 sourceMap.SourceMapConsumer.initialize({ 4 "lib/mappings.wasm": "https://unpkg.com/source-map@0.7.3/lib/mappings.wasm", 5 }); 6</script>
1const rawSourceMap = { 2 version: 3, 3 file: "min.js", 4 names: ["bar", "baz", "n"], 5 sources: ["one.js", "two.js"], 6 sourceRoot: "http://example.com/www/js/", 7 mappings: 8 "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA", 9}; 10 11const whatever = await SourceMapConsumer.with(rawSourceMap, null, consumer => { 12 console.log(consumer.sources); 13 // [ 'http://example.com/www/js/one.js', 14 // 'http://example.com/www/js/two.js' ] 15 16 console.log( 17 consumer.originalPositionFor({ 18 line: 2, 19 column: 28, 20 }) 21 ); 22 // { source: 'http://example.com/www/js/two.js', 23 // line: 2, 24 // column: 10, 25 // name: 'n' } 26 27 console.log( 28 consumer.generatedPositionFor({ 29 source: "http://example.com/www/js/two.js", 30 line: 2, 31 column: 10, 32 }) 33 ); 34 // { line: 2, column: 28 } 35 36 consumer.eachMapping(function (m) { 37 // ... 38 }); 39 40 return computeWhatever(); 41});
In depth guide: Compiling to JavaScript, and Debugging with Source Maps
1function compile(ast) {
2 switch (ast.type) {
3 case "BinaryExpression":
4 return new SourceNode(
5 ast.location.line,
6 ast.location.column,
7 ast.location.source,
8 [compile(ast.left), " + ", compile(ast.right)]
9 );
10 case "Literal":
11 return new SourceNode(
12 ast.location.line,
13 ast.location.column,
14 ast.location.source,
15 String(ast.value)
16 );
17 // ...
18 default:
19 throw new Error("Bad AST");
20 }
21}
22
23var ast = parse("40 + 2", "add.js");
24console.log(
25 compile(ast).toStringWithSourceMap({
26 file: "add.js",
27 })
28);
29// { code: '40 + 2',
30// map: [object SourceMapGenerator] }
1var map = new SourceMapGenerator({ 2 file: "source-mapped.js", 3}); 4 5map.addMapping({ 6 generated: { 7 line: 10, 8 column: 35, 9 }, 10 source: "foo.js", 11 original: { 12 line: 33, 13 column: 2, 14 }, 15 name: "christopher", 16}); 17 18console.log(map.toString()); 19// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
Get a reference to the module:
1// Node.js 2var sourceMap = require("source-map"); 3 4// Browser builds 5var sourceMap = window.sourceMap; 6 7// Inside Firefox 8const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
A SourceMapConsumer
instance represents a parsed source map which we can query
for information about the original file positions by giving it a file position
in the generated source.
When using SourceMapConsumer
outside of node.js, for example on the Web, it
needs to know from what URL to load lib/mappings.wasm
. You must inform it by
calling initialize
before constructing any SourceMapConsumer
s.
The options object has the following properties:
"lib/mappings.wasm"
: A String
containing the URL of the
lib/mappings.wasm
file, or an ArrayBuffer
with the contents of lib/mappings.wasm
.1sourceMap.SourceMapConsumer.initialize({ 2 "lib/mappings.wasm": "https://example.com/source-map/lib/mappings.wasm", 3});
The only parameter is the raw source map (either as a string which can be
JSON.parse
'd, or an object). According to the spec, source maps have the
following attributes:
version
: Which version of the source map spec this map is following.
sources
: An array of URLs to the original source files.
names
: An array of identifiers which can be referenced by individual
mappings.
sourceRoot
: Optional. The URL root from which all sources are relative.
sourcesContent
: Optional. An array of contents of the original source files.
mappings
: A string of base64 VLQs which contain the actual mappings.
file
: Optional. The generated filename this source map is associated with.
x_google_ignoreList
: Optional. An additional extension field which is an array
of indices refering to urls in the sources array. This is used to identify third-party
sources, that the developer might want to avoid when debugging. Read more
The promise of the constructed souce map consumer is returned.
When the SourceMapConsumer
will no longer be used anymore, you must call its
destroy
method.
1const consumer = await new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
2doStuffWith(consumer);
3consumer.destroy();
Alternatively, you can use SourceMapConsumer.with
to avoid needing to remember
to call destroy
.
Construct a new SourceMapConsumer
from rawSourceMap
and sourceMapUrl
(see the SourceMapConsumer
constructor for details. Then, invoke the async function f(SourceMapConsumer) -> T
with the newly constructed consumer, wait
for f
to complete, call destroy
on the consumer, and return f
's return
value.
You must not use the consumer after f
completes!
By using with
, you do not have to remember to manually call destroy
on
the consumer, since it will be called automatically once f
completes.
1const xSquared = await SourceMapConsumer.with( 2 myRawSourceMap, 3 null, 4 async function (consumer) { 5 // Use `consumer` inside here and don't worry about remembering 6 // to call `destroy`. 7 8 const x = await whatever(consumer); 9 return x * x; 10 } 11); 12 13// You may not use that `consumer` anymore out here; it has 14// been destroyed. But you can use `xSquared`. 15console.log(xSquared);
Free this source map consumer's associated wasm data that is manually-managed.
1consumer.destroy();
Alternatively, you can use SourceMapConsumer.with
to avoid needing to remember
to call destroy
.
Compute the last column for each generated mapping. The last column is inclusive.
1// Before: 2consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }); 3// [ { line: 2, 4// column: 1 }, 5// { line: 2, 6// column: 10 }, 7// { line: 2, 8// column: 20 } ] 9 10consumer.computeColumnSpans(); 11 12// After: 13consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }); 14// [ { line: 2, 15// column: 1, 16// lastColumn: 9 }, 17// { line: 2, 18// column: 10, 19// lastColumn: 19 }, 20// { line: 2, 21// column: 20, 22// lastColumn: Infinity } ]
Returns the original source, line, and column information for the generated source's line and column positions provided. The only argument is an object with the following properties:
line
: The line number in the generated source. Line numbers in
this library are 1-based (note that the underlying source map
specification uses 0-based line numbers -- this library handles the
translation).
column
: The column number in the generated source. Column numbers
in this library are 0-based.
bias
: Either SourceMapConsumer.GREATEST_LOWER_BOUND
or
SourceMapConsumer.LEAST_UPPER_BOUND
. Specifies whether to return the closest
element that is smaller than or greater than the one we are searching for,
respectively, if the exact element cannot be found. Defaults to
SourceMapConsumer.GREATEST_LOWER_BOUND
.
and an object is returned with the following properties:
source
: The original source file, or null if this information is not
available.
line
: The line number in the original source, or null if this information is
not available. The line number is 1-based.
column
: The column number in the original source, or null if this
information is not available. The column number is 0-based.
name
: The original identifier, or null if this information is not available.
1consumer.originalPositionFor({ line: 2, column: 10 }); 2// { source: 'foo.coffee', 3// line: 2, 4// column: 2, 5// name: null } 6 7consumer.originalPositionFor({ 8 line: 99999999999999999, 9 column: 999999999999999, 10}); 11// { source: null, 12// line: null, 13// column: null, 14// name: null }
Returns the generated line and column information for the original source, line, and column positions provided. The only argument is an object with the following properties:
source
: The filename of the original source.
line
: The line number in the original source. The line number is
1-based.
column
: The column number in the original source. The column
number is 0-based.
and an object is returned with the following properties:
line
: The line number in the generated source, or null. The line
number is 1-based.
column
: The column number in the generated source, or null. The
column number is 0-based.
1consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }); 2// { line: 1, 3// column: 56 }
Returns all generated line and column information for the original source, line, and column provided. If no column is provided, returns all mappings corresponding to a either the line we are searching for or the next closest line that has any mappings. Otherwise, returns all mappings corresponding to the given line and either the column we are searching for or the next closest column that has any offsets.
The only argument is an object with the following properties:
source
: The filename of the original source.
line
: The line number in the original source. The line number is
1-based.
column
: Optional. The column number in the original source. The
column number is 0-based.
and an array of objects is returned, each with the following properties:
line
: The line number in the generated source, or null. The line
number is 1-based.
column
: The column number in the generated source, or null. The
column number is 0-based.
1consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }); 2// [ { line: 2, 3// column: 1 }, 4// { line: 2, 5// column: 10 }, 6// { line: 2, 7// column: 20 } ]
Return true if we have the embedded source content for every source listed in the source map, false otherwise.
In other words, if this method returns true
, then
consumer.sourceContentFor(s)
will succeed for every source s
in
consumer.sources
.
1// ...
2if (consumer.hasContentsOfAllSources()) {
3 consumerReadyCallback(consumer);
4} else {
5 fetchSources(consumer, consumerReadyCallback);
6}
7// ...
Returns the original source content for the source provided. The only argument is the URL of the original source file.
If the source content for the given source is not found, then an error is
thrown. Optionally, pass true
as the second param to have null
returned
instead.
1consumer.sources; 2// [ "my-cool-lib.clj" ] 3 4consumer.sourceContentFor("my-cool-lib.clj"); 5// "..." 6 7consumer.sourceContentFor("this is not in the source map"); 8// Error: "this is not in the source map" is not in the source map 9 10consumer.sourceContentFor("this is not in the source map", true); 11// null
Iterate over each mapping between an original source/line/column and a generated line/column in this source map.
callback
: The function that is called with each mapping. Mappings have the
form { source, generatedLine, generatedColumn, originalLine, originalColumn, name }
context
: Optional. If specified, this object will be the value of this
every time that callback
is called.
order
: Either SourceMapConsumer.GENERATED_ORDER
or
SourceMapConsumer.ORIGINAL_ORDER
. Specifies whether you want to iterate over
the mappings sorted by the generated file's line/column order or the
original's source/line/column order, respectively. Defaults to
SourceMapConsumer.GENERATED_ORDER
.
1consumer.eachMapping(function (m) { 2 console.log(m); 3}); 4// ... 5// { source: 'illmatic.js', 6// generatedLine: 1, 7// generatedColumn: 0, 8// originalLine: 1, 9// originalColumn: 0, 10// name: null } 11// { source: 'illmatic.js', 12// generatedLine: 2, 13// generatedColumn: 0, 14// originalLine: 2, 15// originalColumn: 0, 16// name: null } 17// ...
An instance of the SourceMapGenerator represents a source map which is being built incrementally.
You may pass an object with the following properties:
file
: The filename of the generated source that this source map is
associated with.
sourceRoot
: A root for all relative URLs in this source map.
skipValidation
: Optional. When true
, disables validation of mappings as
they are added. This can improve performance but should be used with
discretion, as a last resort. Even then, one should avoid using this flag when
running tests, if possible.
1var generator = new sourceMap.SourceMapGenerator({
2 file: "my-generated-javascript-file.js",
3 sourceRoot: "http://example.com/app/js/",
4});
Creates a new SourceMapGenerator
from an existing SourceMapConsumer
instance.
sourceMapConsumer
The SourceMap.1var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
Add a single mapping from original source line and column to the generated source's line and column for this source map being created. The mapping object should have the following properties:
generated
: An object with the generated line and column positions.
original
: An object with the original line and column positions.
source
: The original source file (relative to the sourceRoot).
name
: An optional original token name for this mapping.
1generator.addMapping({ 2 source: "module-one.scm", 3 original: { line: 128, column: 0 }, 4 generated: { line: 3, column: 456 }, 5});
Set the source content for an original source file.
sourceFile
the URL of the original source file.
sourceContent
the content of the source file.
1generator.setSourceContent(
2 "module-one.scm",
3 fs.readFileSync("path/to/module-one.scm")
4);
Applies a SourceMap for a source file to the SourceMap. Each mapping to the supplied source file is rewritten using the supplied SourceMap. Note: The resolution for the resulting mappings is the minimum of this map and the supplied map.
sourceMapConsumer
: The SourceMap to be applied.
sourceFile
: Optional. The filename of the source file.
If omitted, sourceMapConsumer.file will be used, if it exists.
Otherwise an error will be thrown.
sourceMapPath
: Optional. The dirname of the path to the SourceMap
to be applied. If relative, it is relative to the SourceMap.
This parameter is needed when the two SourceMaps aren't in the same directory, and the SourceMap to be applied contains relative source paths. If so, those relative source paths need to be rewritten relative to the SourceMap.
If omitted, it is assumed that both SourceMaps are in the same directory,
thus not needing any rewriting. (Supplying '.'
has the same effect.)
Renders the source map being generated to a string.
1generator.toString(); 2// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputting the generated JS and source map.
line
: The original line number associated with this source node, or null if
it isn't associated with an original line. The line number is 1-based.
column
: The original column number associated with this source node, or null
if it isn't associated with an original column. The column number
is 0-based.
source
: The original source's filename; null if no filename is provided.
chunk
: Optional. Is immediately passed to SourceNode.prototype.add
, see
below.
name
: Optional. The original identifier.
1var node = new SourceNode(1, 2, "a.cpp", [ 2 new SourceNode(3, 4, "b.cpp", "extern int status;\n"), 3 new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), 4 new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), 5]);
Creates a SourceNode from generated code and a SourceMapConsumer.
code
: The generated code
sourceMapConsumer
The SourceMap for the generated code
relativePath
The optional path that relative sources in sourceMapConsumer
should be relative to.
1const consumer = await new SourceMapConsumer(
2 fs.readFileSync("path/to/my-file.js.map", "utf8")
3);
4const node = SourceNode.fromStringWithSourceMap(
5 fs.readFileSync("path/to/my-file.js"),
6 consumer
7);
Add a chunk of generated JS to this source node.
chunk
: A string snippet of generated JS code, another instance of
SourceNode
, or an array where each member is one of those things.1node.add(" + "); 2node.add(otherNode); 3node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
Prepend a chunk of generated JS to this source node.
chunk
: A string snippet of generated JS code, another instance of
SourceNode
, or an array where each member is one of those things.1node.prepend("/** Build Id: f783haef86324gf **/\n\n");
Set the source content for a source file. This will be added to the
SourceMap
in the sourcesContent
field.
sourceFile
: The filename of the source file
sourceContent
: The content of the source file
1node.setSourceContent(
2 "module-one.scm",
3 fs.readFileSync("path/to/module-one.scm")
4);
Walk over the tree of JS snippets in this node and its children. The walking function is called once for each snippet of JS and is passed that snippet and the its original associated source's line/column location.
fn
: The traversal function.1var node = new SourceNode(1, 2, "a.js", [ 2 new SourceNode(3, 4, "b.js", "uno"), 3 "dos", 4 ["tres", new SourceNode(5, 6, "c.js", "quatro")], 5]); 6 7node.walk(function (code, loc) { 8 console.log("WALK:", code, loc); 9}); 10// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } 11// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } 12// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } 13// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
Walk over the tree of SourceNodes. The walking function is called for each source file content and is passed the filename and source content.
fn
: The traversal function.1var a = new SourceNode(1, 2, "a.js", "generated from a");
2a.setSourceContent("a.js", "original a");
3var b = new SourceNode(1, 2, "b.js", "generated from b");
4b.setSourceContent("b.js", "original b");
5var c = new SourceNode(1, 2, "c.js", "generated from c");
6c.setSourceContent("c.js", "original c");
7
8var node = new SourceNode(null, null, null, [a, b, c]);
9node.walkSourceContents(function (source, contents) {
10 console.log("WALK:", source, ":", contents);
11});
12// WALK: a.js : original a
13// WALK: b.js : original b
14// WALK: c.js : original c
Like Array.prototype.join
except for SourceNodes. Inserts the separator
between each of this source node's children.
sep
: The separator.1var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); 2var operand = new SourceNode(3, 4, "a.rs", "="); 3var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); 4 5var node = new SourceNode(null, null, null, [lhs, operand, rhs]); 6var joinedNode = node.join(" ");
Call String.prototype.replace
on the very right-most source snippet. Useful
for trimming white space from the end of a source node, etc.
pattern
: The pattern to replace.
replacement
: The thing to replace the pattern with.
1// Trim trailing white space. 2node.replaceRight(/\s*$/, "");
Return the string representation of this source node. Walks over the tree and concatenates all the various snippets together to one string.
1var node = new SourceNode(1, 2, "a.js", [ 2 new SourceNode(3, 4, "b.js", "uno"), 3 "dos", 4 ["tres", new SourceNode(5, 6, "c.js", "quatro")], 5]); 6 7node.toString(); 8// 'unodostresquatro'
Returns the string representation of this tree of source nodes, plus a SourceMapGenerator which contains all the mappings between the generated and original sources.
The arguments are the same as those to new SourceMapGenerator
.
1var node = new SourceNode(1, 2, "a.js", [ 2 new SourceNode(3, 4, "b.js", "uno"), 3 "dos", 4 ["tres", new SourceNode(5, 6, "c.js", "quatro")], 5]); 6 7node.toStringWithSourceMap({ file: "my-output-file.js" }); 8// { code: 'unodostresquatro', 9// map: [object SourceMapGenerator] }
No vulnerabilities found.
Reason
all changesets reviewed
Reason
no dangerous workflow patterns detected
Reason
binaries present in source code
Details
Reason
license file detected
Details
Reason
3 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More