Modernize platform, structure, and UX
CI / build (push) Canceled after 0s

Phase 3:
- Declare PowerPointApi 1.5 and replace template manifest values
- Remove the dead command pipeline and the tracked Babel/polyfill setup
- Extract constants, status/settings contexts, PowerPoint services, and an error boundary
- Build with ES2020 and strict TypeScript; hash production assets and drop prod source maps
- Add Vitest tests, CI, LICENSE, Node 20 pinning, and prune unused dependencies
- Correct the README, user guide, developer guide, and audit notes

Phase 4:
- Add a persisted 16:9/4:3 slide size setting used by all layout tools
- Add dark mode with Office/system theme detection
- Make sections collapsible and move to accessible Fluent controls
- Announce status through aria-live and add semantic status icons
- Add a progress counter with cooperative cancellation and a Stop button
- Update the tracked dependency tree for the pruned packages
This commit is contained in:
schihei committed 2026-11-25 12:01:40 +01:00
1 parent e57258afe9
commit 89989c04e9
6211 files changed
+7028 -274819

No files matched your search

+192 -176
View File
@@ -18,7 +18,7 @@ More important that WASM version has some optimizations in JS code too. This is
I decided to fork the original source-map and port these optimizations from the article and several others PR from the original source-map.
---------
---
This is a library to generate and consume the source map format
[described here][format].
@@ -33,12 +33,13 @@ This is a library to generate and consume the source map format
<script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script> -->
--------------------------------------------------------------------------------
---
<!-- `npm run toc` to regenerate the Table of Contents -->
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of Contents
- [Examples](#examples)
@@ -58,7 +59,7 @@ This is a library to generate and consume the source map format
- [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
- [SourceMapGenerator](#sourcemapgenerator)
- [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer, sourceMapGeneratorOptions)](#sourcemapgeneratorfromsourcemapsourcemapconsumer-sourcemapgeneratoroptions)
- [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
- [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
@@ -89,7 +90,8 @@ var rawSourceMap = {
names: ['bar', 'baz', 'n'],
sources: ['one.js', 'two.js'],
sourceRoot: 'http://example.com/www/js/',
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
mappings:
'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA',
};
var smc = new SourceMapConsumer(rawSourceMap);
@@ -98,20 +100,24 @@ console.log(smc.sources);
// [ 'http://example.com/www/js/one.js',
// 'http://example.com/www/js/two.js' ]
console.log(smc.originalPositionFor({
line: 2,
column: 28
}));
console.log(
smc.originalPositionFor({
line: 2,
column: 28,
})
);
// { source: 'http://example.com/www/js/two.js',
// line: 2,
// column: 10,
// name: 'n' }
console.log(smc.generatedPositionFor({
source: 'http://example.com/www/js/two.js',
line: 2,
column: 10
}));
console.log(
smc.generatedPositionFor({
source: 'http://example.com/www/js/two.js',
line: 2,
column: 10,
})
);
// { line: 2, column: 28 }
smc.eachMapping(function (m) {
@@ -129,30 +135,32 @@ In depth guide:
```js
function compile(ast) {
switch (ast.type) {
case 'BinaryExpression':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
[compile(ast.left), " + ", compile(ast.right)]
);
case 'Literal':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
String(ast.value)
);
// ...
default:
throw new Error("Bad AST");
case 'BinaryExpression':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
[compile(ast.left), ' + ', compile(ast.right)]
);
case 'Literal':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
String(ast.value)
);
// ...
default:
throw new Error('Bad AST');
}
}
var ast = parse("40 + 2", "add.js");
console.log(compile(ast).toStringWithSourceMap({
file: 'add.js'
}));
var ast = parse('40 + 2', 'add.js');
console.log(
compile(ast).toStringWithSourceMap({
file: 'add.js',
})
);
// { code: '40 + 2',
// map: [object SourceMapGenerator] }
```
@@ -161,20 +169,20 @@ console.log(compile(ast).toStringWithSourceMap({
```js
var map = new SourceMapGenerator({
file: "source-mapped.js"
file: 'source-mapped.js',
});
map.addMapping({
generated: {
line: 10,
column: 35
column: 35,
},
source: "foo.js",
source: 'foo.js',
original: {
line: 33,
column: 2
column: 2,
},
name: "christopher"
name: 'christopher',
});
console.log(map.toString());
@@ -193,7 +201,7 @@ var sourceMap = require('source-map');
var sourceMap = window.sourceMap;
// Inside Firefox
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
const sourceMap = require('devtools/toolkit/sourcemap/source-map.js');
```
### SourceMapConsumer
@@ -208,20 +216,20 @@ 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.
- `version`: Which version of the source map spec this map is following.
* `sources`: An array of URLs to the original source files.
- `sources`: An array of URLs to the original source files.
* `names`: An array of identifiers which can be referenced by individual
- `names`: An array of identifiers which can be referenced by individual
mappings.
* `sourceRoot`: Optional. The URL root from which all sources are relative.
- `sourceRoot`: Optional. The URL root from which all sources are relative.
* `sourcesContent`: Optional. An array of contents of the original source files.
- `sourcesContent`: Optional. An array of contents of the original source files.
* `mappings`: A string of base64 VLQs which contain the actual mappings.
- `mappings`: A string of base64 VLQs which contain the actual mappings.
* `file`: Optional. The generated filename this source map is associated with.
- `file`: Optional. The generated filename this source map is associated with.
```js
var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
@@ -234,7 +242,7 @@ inclusive.
```js
// Before:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
consumer.allGeneratedPositionsFor({ line: 2, source: 'foo.coffee' });
// [ { line: 2,
// column: 1 },
// { line: 2,
@@ -245,7 +253,7 @@ consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
consumer.computeColumnSpans();
// After:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
consumer.allGeneratedPositionsFor({ line: 2, source: 'foo.coffee' });
// [ { line: 2,
// column: 1,
// lastColumn: 9 },
@@ -255,7 +263,6 @@ consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// { line: 2,
// column: 20,
// lastColumn: Infinity } ]
```
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
@@ -264,41 +271,44 @@ 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
- `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
- `column`: The column number in the generated source. Column numbers
in this library are 0-based.
* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
- `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
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
- `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.
- `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.
- `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.
- `name`: The original identifier, or null if this information is not available.
```js
consumer.originalPositionFor({ line: 2, column: 10 })
consumer.originalPositionFor({ line: 2, column: 10 });
// { source: 'foo.coffee',
// line: 2,
// column: 2,
// name: null }
consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
consumer.originalPositionFor({
line: 99999999999999999,
column: 999999999999999,
});
// { source: null,
// line: null,
// column: null,
@@ -311,24 +321,24 @@ 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.
- `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
- `line`: The line number in the original source. The line number is
1-based.
* `column`: The column number in the original source. The column
- `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
- `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`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
consumer.generatedPositionFor({ source: 'example.js', line: 2, column: 10 });
// { line: 1,
// column: 56 }
```
@@ -344,24 +354,24 @@ that has any offsets.
The only argument is an object with the following properties:
* `source`: The filename of the original source.
- `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
- `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`: 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
- `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`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
consumer.allGeneratedpositionsfor({ line: 2, source: 'foo.coffee' });
// [ { line: 2,
// column: 1 },
// { line: 2,
@@ -399,16 +409,16 @@ thrown. Optionally, pass `true` as the second param to have `null` returned
instead.
```js
consumer.sources
consumer.sources;
// [ "my-cool-lib.clj" ]
consumer.sourceContentFor("my-cool-lib.clj")
consumer.sourceContentFor('my-cool-lib.clj');
// "..."
consumer.sourceContentFor("this is not in the source map");
consumer.sourceContentFor('this is not in the source map');
// Error: "this is not in the source map" is not in the source map
consumer.sourceContentFor("this is not in the source map", true);
consumer.sourceContentFor('this is not in the source map', true);
// null
```
@@ -417,21 +427,23 @@ consumer.sourceContentFor("this is not in the source map", true);
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
- `callback`: The function that is called with each mapping. Mappings have the
form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
name }`
name }`
* `context`: Optional. If specified, this object will be the value of `this`
- `context`: Optional. If specified, this object will be the value of `this`
every time that `callback` is called.
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
- `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`.
```js
consumer.eachMapping(function (m) { console.log(m); })
consumer.eachMapping(function (m) {
console.log(m);
});
// ...
// { source: 'illmatic.js',
// generatedLine: 1,
@@ -447,6 +459,7 @@ consumer.eachMapping(function (m) { console.log(m); })
// name: null }
// ...
```
### SourceMapGenerator
An instance of the SourceMapGenerator represents a source map which is being
@@ -456,23 +469,23 @@ built incrementally.
You may pass an object with the following properties:
* `file`: The filename of the generated source that this source map is
- `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.
- `sourceRoot`: A root for all relative URLs in this source map.
* `skipValidation`: Optional. When `true`, disables validation of mappings as
- `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.
* `ignoreInvalidMapping`: Optional. When `true`, instead of throwing error on
- `ignoreInvalidMapping`: Optional. When `true`, instead of throwing error on
invalid mapping, it will be ignored.
```js
var generator = new sourceMap.SourceMapGenerator({
file: "my-generated-javascript-file.js",
sourceRoot: "http://example.com/app/js/"
file: 'my-generated-javascript-file.js',
sourceRoot: 'http://example.com/app/js/',
});
```
@@ -480,9 +493,9 @@ var generator = new sourceMap.SourceMapGenerator({
Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
* `sourceMapConsumer` The SourceMap.
- `sourceMapConsumer` The SourceMap.
* `sourceMapGeneratorOptions` options that will be passed to the SourceMapGenerator constructor which used under the hood.
- `sourceMapGeneratorOptions` options that will be passed to the SourceMapGenerator constructor which used under the hood.
```js
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer, {
@@ -496,33 +509,35 @@ 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.
- `generated`: An object with the generated line and column positions.
* `original`: An object with the original line and column positions.
- `original`: An object with the original line and column positions.
* `source`: The original source file (relative to the sourceRoot).
- `source`: The original source file (relative to the sourceRoot).
* `name`: An optional original token name for this mapping.
- `name`: An optional original token name for this mapping.
```js
generator.addMapping({
source: "module-one.scm",
source: 'module-one.scm',
original: { line: 128, column: 0 },
generated: { line: 3, column: 456 }
})
generated: { line: 3, column: 456 },
});
```
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for an original source file.
* `sourceFile` the URL of the original source file.
- `sourceFile` the URL of the original source file.
* `sourceContent` the content of the source file.
- `sourceContent` the content of the source file.
```js
generator.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
generator.setSourceContent(
'module-one.scm',
fs.readFileSync('path/to/module-one.scm')
);
```
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
@@ -532,13 +547,13 @@ 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.
- `sourceMapConsumer`: The SourceMap to be applied.
* `sourceFile`: Optional. The filename of the source file.
- `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
- `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
@@ -554,7 +569,7 @@ is the minimum of this map and the supplied map.
Renders the source map being generated to a string.
```js
generator.toString()
generator.toString();
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
```
@@ -568,25 +583,25 @@ use before outputting the generated JS and source map.
#### new SourceNode([line, column, source[, chunk[, name]]])
* `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.
- `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
- `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.
- `source`: The original source's filename; null if no filename is provided.
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
- `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
below.
* `name`: Optional. The original identifier.
- `name`: Optional. The original identifier.
```js
var node = new SourceNode(1, 2, "a.cpp", [
new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
var node = new SourceNode(1, 2, 'a.cpp', [
new SourceNode(3, 4, 'b.cpp', 'extern int status;\n'),
new SourceNode(5, 6, 'c.cpp', 'std::string* make_string(size_t n);\n'),
new SourceNode(7, 8, 'd.cpp', 'int main(int argc, char** argv) {}\n'),
]);
```
@@ -594,41 +609,45 @@ var node = new SourceNode(1, 2, "a.cpp", [
Creates a SourceNode from generated code and a SourceMapConsumer.
* `code`: The generated code
- `code`: The generated code
* `sourceMapConsumer` The SourceMap for the generated code
- `sourceMapConsumer` The SourceMap for the generated code
* `relativePath` The optional path that relative sources in `sourceMapConsumer`
- `relativePath` The optional path that relative sources in `sourceMapConsumer`
should be relative to.
```js
var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
consumer);
var consumer = new SourceMapConsumer(
fs.readFileSync('path/to/my-file.js.map', 'utf8')
);
var node = SourceNode.fromStringWithSourceMap(
fs.readFileSync('path/to/my-file.js'),
consumer
);
```
#### SourceNode.prototype.add(chunk)
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.
- `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.add(" + ");
node.add(' + ');
node.add(otherNode);
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
node.add([leftHandOperandNode, ' + ', rightHandOperandNode]);
```
#### SourceNode.prototype.prepend(chunk)
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.
- `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.prepend("/** Build Id: f783haef86324gf **/\n\n");
node.prepend('/** Build Id: f783haef86324gf **/\n\n');
```
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
@@ -636,13 +655,15 @@ node.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
- `sourceFile`: The filename of the source file
* `sourceContent`: The content of the source file
- `sourceContent`: The content of the source file
```js
node.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
node.setSourceContent(
'module-one.scm',
fs.readFileSync('path/to/module-one.scm')
);
```
#### SourceNode.prototype.walk(fn)
@@ -651,19 +672,18 @@ 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.
- `fn`: The traversal function.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
var node = new SourceNode(1, 2, 'a.js', [
new SourceNode(3, 4, 'b.js', 'uno'),
'dos',
['tres', new SourceNode(5, 6, 'c.js', 'quatro')],
]);
node.walk(function (code, loc) { console.log("WALK:", code, loc); })
node.walk(function (code, loc) {
console.log('WALK:', code, loc);
});
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
@@ -675,18 +695,20 @@ node.walk(function (code, loc) { console.log("WALK:", code, loc); })
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.
- `fn`: The traversal function.
```js
var a = new SourceNode(1, 2, "a.js", "generated from a");
a.setSourceContent("a.js", "original a");
var b = new SourceNode(1, 2, "b.js", "generated from b");
b.setSourceContent("b.js", "original b");
var c = new SourceNode(1, 2, "c.js", "generated from c");
c.setSourceContent("c.js", "original c");
var a = new SourceNode(1, 2, 'a.js', 'generated from a');
a.setSourceContent('a.js', 'original a');
var b = new SourceNode(1, 2, 'b.js', 'generated from b');
b.setSourceContent('b.js', 'original b');
var c = new SourceNode(1, 2, 'c.js', 'generated from c');
c.setSourceContent('c.js', 'original c');
var node = new SourceNode(null, null, null, [a, b, c]);
node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
node.walkSourceContents(function (source, contents) {
console.log('WALK:', source, ':', contents);
});
// WALK: a.js : original a
// WALK: b.js : original b
// WALK: c.js : original c
@@ -697,15 +719,15 @@ node.walkSourceContents(function (source, contents) { console.log("WALK:", sourc
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
between each of this source node's children.
* `sep`: The separator.
- `sep`: The separator.
```js
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
var operand = new SourceNode(3, 4, "a.rs", "=");
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
var lhs = new SourceNode(1, 2, 'a.rs', 'my_copy');
var operand = new SourceNode(3, 4, 'a.rs', '=');
var rhs = new SourceNode(5, 6, 'a.rs', 'orig.clone()');
var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
var joinedNode = node.join(" ");
var node = new SourceNode(null, null, null, [lhs, operand, rhs]);
var joinedNode = node.join(' ');
```
#### SourceNode.prototype.replaceRight(pattern, replacement)
@@ -713,13 +735,13 @@ var 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.
- `pattern`: The pattern to replace.
* `replacement`: The thing to replace the pattern with.
- `replacement`: The thing to replace the pattern with.
```js
// Trim trailing white space.
node.replaceRight(/\s*$/, "");
node.replaceRight(/\s*$/, '');
```
#### SourceNode.prototype.toString()
@@ -728,16 +750,13 @@ Return the string representation of this source node. Walks over the tree and
concatenates all the various snippets together to one string.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
var node = new SourceNode(1, 2, 'a.js', [
new SourceNode(3, 4, 'b.js', 'uno'),
'dos',
['tres', new SourceNode(5, 6, 'c.js', 'quatro')],
]);
node.toString()
node.toString();
// 'unodostresquatro'
```
@@ -750,16 +769,13 @@ original sources.
The arguments are the same as those to `new SourceMapGenerator`.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
var node = new SourceNode(1, 2, 'a.js', [
new SourceNode(3, 4, 'b.js', 'uno'),
'dos',
['tres', new SourceNode(5, 6, 'c.js', 'quatro')],
]);
node.toStringWithSourceMap({ file: "my-output-file.js" })
node.toStringWithSourceMap({ file: 'my-output-file.js' });
// { code: 'unodostresquatro',
// map: [object SourceMapGenerator] }
```
+5 -3
View File
@@ -7,7 +7,7 @@
var util = require('./util');
var has = Object.prototype.hasOwnProperty;
var hasNativeMap = typeof Map !== "undefined";
var hasNativeMap = typeof Map !== 'undefined';
/**
* A data structure which is a combination of an array and a set. Adding a new
@@ -38,7 +38,9 @@ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
* @returns Number
*/
ArraySet.prototype.size = function ArraySet_size() {
return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
return hasNativeMap
? this._set.size
: Object.getOwnPropertyNames(this._set).length;
};
/**
@@ -85,7 +87,7 @@ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (hasNativeMap) {
var idx = this._set.get(aStr);
if (idx >= 0) {
return idx;
return idx;
}
} else {
var sStr = util.toSetString(aStr);
+5 -9
View File
@@ -67,9 +67,7 @@ var VLQ_CONTINUATION_BIT = VLQ_BASE;
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
}
/**
@@ -81,16 +79,14 @@ function toVLQSigned(aValue) {
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
return isNegative ? -shifted : shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var encoded = '';
var digit;
var vlq = toVLQSigned(aValue);
@@ -121,12 +117,12 @@ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
do {
if (aIndex >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
throw new Error('Expected more digits in base 64 VLQ value.');
}
digit = base64.decode(aStr.charCodeAt(aIndex++));
if (digit === -1) {
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
throw new Error('Invalid base64 digit: ' + aStr.charAt(aIndex - 1));
}
continuation = !!(digit & VLQ_CONTINUATION_BIT);
+13 -12
View File
@@ -5,7 +5,8 @@
* http://opensource.org/licenses/BSD-3-Clause
*/
var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
var intToCharMap =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
@@ -14,7 +15,7 @@ exports.encode = function (number) {
if (0 <= number && number < intToCharMap.length) {
return intToCharMap[number];
}
throw new TypeError("Must be between 0 and 63: " + number);
throw new TypeError('Must be between 0 and 63: ' + number);
};
/**
@@ -22,34 +23,34 @@ exports.encode = function (number) {
* failure.
*/
exports.decode = function (charCode) {
var bigA = 65; // 'A'
var bigZ = 90; // 'Z'
var bigA = 65; // 'A'
var bigZ = 90; // 'Z'
var littleA = 97; // 'a'
var littleA = 97; // 'a'
var littleZ = 122; // 'z'
var zero = 48; // '0'
var nine = 57; // '9'
var zero = 48; // '0'
var nine = 57; // '9'
var plus = 43; // '+'
var slash = 47; // '/'
var plus = 43; // '+'
var slash = 47; // '/'
var littleOffset = 26;
var numberOffset = 52;
// 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
if (bigA <= charCode && charCode <= bigZ) {
return (charCode - bigA);
return charCode - bigA;
}
// 26 - 51: abcdefghijklmnopqrstuvwxyz
if (littleA <= charCode && charCode <= littleZ) {
return (charCode - littleA + littleOffset);
return charCode - littleA + littleOffset;
}
// 52 - 61: 0123456789
if (zero <= charCode && charCode <= nine) {
return (charCode - zero + numberOffset);
return charCode - zero + numberOffset;
}
// 62: +
+10 -6
View File
@@ -36,8 +36,7 @@ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
if (cmp === 0) {
// Found the element we are looking for.
return mid;
}
else if (cmp > 0) {
} else if (cmp > 0) {
// Our needle is greater than aHaystack[mid].
if (aHigh - mid > 1) {
// The element is in the upper half.
@@ -51,8 +50,7 @@ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
} else {
return mid;
}
}
else {
} else {
// Our needle is less than aHaystack[mid].
if (mid - aLow > 1) {
// The element is in the lower half.
@@ -91,8 +89,14 @@ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
return -1;
}
var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
aCompare, aBias || exports.GREATEST_LOWER_BOUND);
var index = recursiveSearch(
-1,
aHaystack.length,
aNeedle,
aHaystack,
aCompare,
aBias || exports.GREATEST_LOWER_BOUND
);
if (index < 0) {
return -1;
}
+12 -7
View File
@@ -17,8 +17,11 @@ function generatedPositionAfter(mappingA, mappingB) {
var lineB = mappingB.generatedLine;
var columnA = mappingA.generatedColumn;
var columnB = mappingB.generatedColumn;
return lineB > lineA || lineB == lineA && columnB >= columnA ||
util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
return (
lineB > lineA ||
(lineB == lineA && columnB >= columnA) ||
util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0
);
}
/**
@@ -30,7 +33,7 @@ function MappingList() {
this._array = [];
this._sorted = true;
// Serves as infimum
this._last = {generatedLine: -1, generatedColumn: 0};
this._last = { generatedLine: -1, generatedColumn: 0 };
}
/**
@@ -39,10 +42,12 @@ function MappingList() {
*
* NOTE: The order of the mappings is NOT guaranteed.
*/
MappingList.prototype.unsortedForEach =
function MappingList_forEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
};
MappingList.prototype.unsortedForEach = function MappingList_forEach(
aCallback,
aThisArg
) {
this._array.forEach(aCallback, aThisArg);
};
/**
* Add the given source mapping.
+95 -16
View File
@@ -14,8 +14,18 @@
// fact, when sorting with a comparator, these costs outweigh the benefits of
// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
// a ~3500ms mean speed-up in `bench/bench.html`.
function SortTemplate(comparator) {
//
// That only pays off while the JIT can inline the comparator, i.e. while the
// comparator call site in the sort sees a single comparator. The library sorts
// with four different comparators, so each one gets its own copy of the sort
// function (`doQuickSort0` .. `doQuickSort3` below). The copies have to be
// separate function literals in the source: closures created from the same
// literal share type feedback, and so did copies cloned with `new Function`
// from identical source text. Cloning with `new Function` also violates
// Content Security Policies that don't allow 'unsafe-eval', so the copies are
// written out by hand. Keep them identical. See:
// https://github.com/7rulnik/source-map-js/pull/29
// https://github.com/7rulnik/source-map-js/issues/81
/**
* Swap the elements indexed by `x` and `y` in the array `ary`.
@@ -42,7 +52,7 @@ function swap(ary, x, y) {
* The upper bound on the range.
*/
function randomIntInRange(low, high) {
return Math.round(low + (Math.random() * (high - low)));
return Math.round(low + Math.random() * (high - low));
}
/**
@@ -57,7 +67,7 @@ function randomIntInRange(low, high) {
* @param {Number} r
* End index of the array
*/
function doQuickSort(ary, comparator, p, r) {
function doQuickSort0(ary, comparator, p, r) {
// If our lower bound is less than our upper bound, we (1) partition the
// array into two pieces and (2) recurse on each half. If it is not, this is
// the empty array and our base case.
@@ -98,20 +108,86 @@ function doQuickSort(ary, comparator, p, r) {
// (2) Recurse on each half.
doQuickSort(ary, comparator, p, q - 1);
doQuickSort(ary, comparator, q + 1, r);
doQuickSort0(ary, comparator, p, q - 1);
doQuickSort0(ary, comparator, q + 1, r);
}
}
return doQuickSort;
// Identical copies of `doQuickSort0`, see the comment at the top of the file.
function doQuickSort1(ary, comparator, p, r) {
if (p < r) {
var pivotIndex = randomIntInRange(p, r);
var i = p - 1;
swap(ary, pivotIndex, r);
var pivot = ary[r];
for (var j = p; j < r; j++) {
if (comparator(ary[j], pivot, false) <= 0) {
i += 1;
swap(ary, i, j);
}
}
swap(ary, i + 1, j);
var q = i + 1;
doQuickSort1(ary, comparator, p, q - 1);
doQuickSort1(ary, comparator, q + 1, r);
}
}
function cloneSort(comparator) {
let template = SortTemplate.toString();
let templateFn = new Function(`return ${template}`)();
return templateFn(comparator);
function doQuickSort2(ary, comparator, p, r) {
if (p < r) {
var pivotIndex = randomIntInRange(p, r);
var i = p - 1;
swap(ary, pivotIndex, r);
var pivot = ary[r];
for (var j = p; j < r; j++) {
if (comparator(ary[j], pivot, false) <= 0) {
i += 1;
swap(ary, i, j);
}
}
swap(ary, i + 1, j);
var q = i + 1;
doQuickSort2(ary, comparator, p, q - 1);
doQuickSort2(ary, comparator, q + 1, r);
}
}
function doQuickSort3(ary, comparator, p, r) {
if (p < r) {
var pivotIndex = randomIntInRange(p, r);
var i = p - 1;
swap(ary, pivotIndex, r);
var pivot = ary[r];
for (var j = p; j < r; j++) {
if (comparator(ary[j], pivot, false) <= 0) {
i += 1;
swap(ary, i, j);
}
}
swap(ary, i + 1, j);
var q = i + 1;
doQuickSort3(ary, comparator, p, q - 1);
doQuickSort3(ary, comparator, q + 1, r);
}
}
var sortCopies = [doQuickSort0, doQuickSort1, doQuickSort2, doQuickSort3];
var nextSortCopy = 0;
var sortCache = new WeakMap();
/**
* Sort the given array in-place with the given comparator function.
*
@@ -119,13 +195,16 @@ function cloneSort(comparator) {
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
* @param {Number} start
* Index to start sorting from; items before it are left untouched.
*/
let sortCache = new WeakMap();
exports.quickSort = function (ary, comparator, start = 0) {
let doQuickSort = sortCache.get(comparator);
if (doQuickSort === void 0) {
doQuickSort = cloneSort(comparator);
var doQuickSort = sortCache.get(comparator);
if (doQuickSort === undefined) {
// Each comparator claims the next free copy. Should there ever be more
// comparators than copies, the extra ones share the last copy: still
// correct, just slower for the comparators sharing it.
doQuickSort = sortCopies[Math.min(nextSortCopy++, sortCopies.length - 1)];
sortCache.set(comparator, doQuickSort);
}
doQuickSort(ary, comparator, start, ary.length - 1);
+317 -191
View File
@@ -11,6 +11,14 @@ var ArraySet = require('./array-set').ArraySet;
var base64VLQ = require('./base64-vlq');
var quickSort = require('./quick-sort').quickSort;
// Upper bound for a section's `offset.line` in an indexed source map. A flat
// map spends one ';' per generated line, so a tiny indexed map with a huge
// offset.line turns into a huge amount of work and memory once its mappings
// are copied into a SourceMapGenerator (CVE-2026-93749). Ten million lines is
// far beyond any real generated file. Columns are VLQ-encoded as deltas and
// don't amplify, so they only need to be valid integers.
var MAX_SECTION_OFFSET_LINE = 1e7;
function SourceMapConsumer(aSourceMap, aSourceMapURL) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
@@ -22,9 +30,9 @@ function SourceMapConsumer(aSourceMap, aSourceMapURL) {
: new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
}
SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
SourceMapConsumer.fromSourceMap = function (aSourceMap, aSourceMapURL) {
return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
}
};
/**
* The version of the source mapping spec that we are consuming.
@@ -71,7 +79,7 @@ Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
}
return this.__generatedMappings;
}
},
});
SourceMapConsumer.prototype.__originalMappings = null;
@@ -84,13 +92,13 @@ Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
}
return this.__originalMappings;
}
},
});
SourceMapConsumer.prototype._charIsMappingSeparator =
function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
var c = aStr.charAt(index);
return c === ";" || c === ",";
return c === ';' || c === ',';
};
/**
@@ -100,7 +108,7 @@ SourceMapConsumer.prototype._charIsMappingSeparator =
*/
SourceMapConsumer.prototype._parseMappings =
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
throw new Error("Subclasses must implement _parseMappings");
throw new Error('Subclasses must implement _parseMappings');
};
SourceMapConsumer.GENERATED_ORDER = 1;
@@ -132,14 +140,14 @@ SourceMapConsumer.prototype.eachMapping =
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error('Unknown order of iteration.');
}
var sourceRoot = this.sourceRoot;
@@ -151,7 +159,7 @@ SourceMapConsumer.prototype.eachMapping =
for (var i = 0, n = mappings.length; i < n; i++) {
var mapping = mappings[i];
var source = mapping.source === null ? null : sources.at(mapping.source);
if(source !== null) {
if (source !== null) {
source = util.computeSourceURL(sourceRoot, source, sourceMapURL);
}
boundCallback({
@@ -160,7 +168,7 @@ SourceMapConsumer.prototype.eachMapping =
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name === null ? null : names.at(mapping.name)
name: mapping.name === null ? null : names.at(mapping.name),
});
}
};
@@ -198,7 +206,7 @@ SourceMapConsumer.prototype.allGeneratedPositionsFor =
var needle = {
source: util.getArg(aArgs, 'source'),
originalLine: line,
originalColumn: util.getArg(aArgs, 'column', 0)
originalColumn: util.getArg(aArgs, 'column', 0),
};
needle.source = this._findSourceIndex(needle.source);
@@ -208,12 +216,14 @@ SourceMapConsumer.prototype.allGeneratedPositionsFor =
var mappings = [];
var index = this._findMapping(needle,
this._originalMappings,
"originalLine",
"originalColumn",
util.compareByOriginalPositions,
binarySearch.LEAST_UPPER_BOUND);
var index = this._findMapping(
needle,
this._originalMappings,
'originalLine',
'originalColumn',
util.compareByOriginalPositions,
binarySearch.LEAST_UPPER_BOUND
);
if (index >= 0) {
var mapping = this._originalMappings[index];
@@ -221,14 +231,20 @@ SourceMapConsumer.prototype.allGeneratedPositionsFor =
var originalLine = mapping.originalLine;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we found. Since
// mappings are sorted, this is guaranteed to find all mappings for
// the line we found.
while (mapping && mapping.originalLine === originalLine) {
// a mapping for a different source or line than the one we found.
// Since mappings are sorted, this is guaranteed to find all mappings
// for the line we found. The source check also stops the search from
// continuing into the next source's mappings when this source has
// none at or after the requested line.
while (
mapping &&
mapping.source === needle.source &&
mapping.originalLine === originalLine
) {
mappings.push({
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null),
});
mapping = this._originalMappings[++index];
@@ -237,16 +253,19 @@ SourceMapConsumer.prototype.allGeneratedPositionsFor =
var originalColumn = mapping.originalColumn;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we were searching for.
// Since mappings are sorted, this is guaranteed to find all mappings for
// the line we are searching for.
while (mapping &&
mapping.originalLine === line &&
mapping.originalColumn == originalColumn) {
// a mapping for a different source or line than the one we were
// searching for. Since mappings are sorted, this is guaranteed to find
// all mappings for the line we are searching for.
while (
mapping &&
mapping.source === needle.source &&
mapping.originalLine === line &&
mapping.originalColumn == originalColumn
) {
mappings.push({
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null),
});
mapping = this._originalMappings[++index];
@@ -330,7 +349,9 @@ function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
// be particularly problematic when the source root is a prefix of the
// source (valid, but why??). See github issue #199 and bugzil.la/1188982.
.map(function (source) {
return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
return sourceRoot &&
util.isAbsolute(sourceRoot) &&
util.isAbsolute(source)
? util.relative(sourceRoot, source)
: source;
});
@@ -360,7 +381,7 @@ BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
* Utility function to find the index of a source. Returns -1 if not
* found.
*/
BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
BasicSourceMapConsumer.prototype._findSourceIndex = function (aSource) {
var relativeSource = aSource;
if (this.sourceRoot != null) {
relativeSource = util.relative(this.sourceRoot, relativeSource);
@@ -391,55 +412,65 @@ BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
* The URL at which the source map can be found (optional)
* @returns BasicSourceMapConsumer
*/
BasicSourceMapConsumer.fromSourceMap =
function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
var smc = Object.create(BasicSourceMapConsumer.prototype);
BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(
aSourceMap,
aSourceMapURL
) {
var smc = Object.create(BasicSourceMapConsumer.prototype);
var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
smc.sourceRoot);
smc.file = aSourceMap._file;
smc._sourceMapURL = aSourceMapURL;
smc._absoluteSources = smc._sources.toArray().map(function (s) {
return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
});
var names = (smc._names = ArraySet.fromArray(
aSourceMap._names.toArray(),
true
));
var sources = (smc._sources = ArraySet.fromArray(
aSourceMap._sources.toArray(),
true
));
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(
smc._sources.toArray(),
smc.sourceRoot
);
smc.file = aSourceMap._file;
smc._sourceMapURL = aSourceMapURL;
smc._absoluteSources = smc._sources.toArray().map(function (s) {
return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
});
// Because we are modifying the entries (by converting string sources and
// names to indices into the sources and names ArraySets), we have to make
// a copy of the entry or else bad things happen. Shared mutable state
// strikes again! See github issue #191.
// Because we are modifying the entries (by converting string sources and
// names to indices into the sources and names ArraySets), we have to make
// a copy of the entry or else bad things happen. Shared mutable state
// strikes again! See github issue #191.
var generatedMappings = aSourceMap._mappings.toArray().slice();
var destGeneratedMappings = smc.__generatedMappings = [];
var destOriginalMappings = smc.__originalMappings = [];
var generatedMappings = aSourceMap._mappings.toArray().slice();
var destGeneratedMappings = (smc.__generatedMappings = []);
var destOriginalMappings = (smc.__originalMappings = []);
for (var i = 0, length = generatedMappings.length; i < length; i++) {
var srcMapping = generatedMappings[i];
var destMapping = new Mapping;
destMapping.generatedLine = srcMapping.generatedLine;
destMapping.generatedColumn = srcMapping.generatedColumn;
for (var i = 0, length = generatedMappings.length; i < length; i++) {
var srcMapping = generatedMappings[i];
var destMapping = new Mapping();
destMapping.generatedLine = srcMapping.generatedLine;
destMapping.generatedColumn = srcMapping.generatedColumn;
if (srcMapping.source) {
destMapping.source = sources.indexOf(srcMapping.source);
destMapping.originalLine = srcMapping.originalLine;
destMapping.originalColumn = srcMapping.originalColumn;
if (srcMapping.source) {
destMapping.source = sources.indexOf(srcMapping.source);
destMapping.originalLine = srcMapping.originalLine;
destMapping.originalColumn = srcMapping.originalColumn;
if (srcMapping.name) {
destMapping.name = names.indexOf(srcMapping.name);
}
destOriginalMappings.push(destMapping);
if (srcMapping.name) {
destMapping.name = names.indexOf(srcMapping.name);
}
destGeneratedMappings.push(destMapping);
destOriginalMappings.push(destMapping);
}
quickSort(smc.__originalMappings, util.compareByOriginalPositions);
destGeneratedMappings.push(destMapping);
}
return smc;
};
quickSort(smc.__originalMappings, util.compareByOriginalPositions);
return smc;
};
/**
* The version of the source mapping spec that we are consuming.
@@ -452,7 +483,7 @@ BasicSourceMapConsumer.prototype._version = 3;
Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
get: function () {
return this._absoluteSources.slice();
}
},
});
/**
@@ -527,11 +558,9 @@ BasicSourceMapConsumer.prototype._parseMappings =
sortGenerated(generatedMappings, subarrayStart);
subarrayStart = generatedMappings.length;
}
else if (aStr.charAt(index) === ',') {
} else if (aStr.charAt(index) === ',') {
index++;
}
else {
} else {
mapping = new Mapping();
mapping.generatedLine = generatedLine;
@@ -601,12 +630,26 @@ BasicSourceMapConsumer.prototype._parseMappings =
sortGenerated(generatedMappings, subarrayStart);
this.__generatedMappings = generatedMappings;
// Sources without mappings have a null bucket. Leave those out, or the
// nulls end up in __originalMappings.
var sourceBuckets = [];
for (var i = 0; i < originalMappings.length; i++) {
if (originalMappings[i] != null) {
quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource);
sourceBuckets.push(originalMappings[i]);
}
}
this.__originalMappings = [].concat(...originalMappings);
// Spreading every bucket into a single concat call overflows the stack
// once a few hundred thousand sources have mappings, so concat at most
// 4096 buckets at a time. Most maps have fewer, and need a single call.
var sortedOriginalMappings = [];
for (var b = 0; b < sourceBuckets.length; b += 4096) {
sortedOriginalMappings = sortedOriginalMappings.concat(
...sourceBuckets.slice(b, b + 4096)
);
}
this.__originalMappings = sortedOriginalMappings;
};
/**
@@ -614,20 +657,28 @@ BasicSourceMapConsumer.prototype._parseMappings =
* we are searching for in the given "haystack" of mappings.
*/
BasicSourceMapConsumer.prototype._findMapping =
function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
aColumnName, aComparator, aBias) {
function SourceMapConsumer_findMapping(
aNeedle,
aMappings,
aLineName,
aColumnName,
aComparator,
aBias
) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
if (aNeedle[aLineName] <= 0) {
throw new TypeError('Line must be greater than or equal to 1, got '
+ aNeedle[aLineName]);
throw new TypeError(
'Line must be greater than or equal to 1, got ' + aNeedle[aLineName]
);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError('Column must be greater than or equal to 0, got '
+ aNeedle[aColumnName]);
throw new TypeError(
'Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]
);
}
return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
@@ -688,14 +739,14 @@ BasicSourceMapConsumer.prototype.originalPositionFor =
function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
generatedColumn: util.getArg(aArgs, 'column'),
};
var index = this._findMapping(
needle,
this._generatedMappings,
"generatedLine",
"generatedColumn",
'generatedLine',
'generatedColumn',
util.compareByGeneratedPositionsDeflated,
util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
);
@@ -707,7 +758,11 @@ BasicSourceMapConsumer.prototype.originalPositionFor =
var source = util.getArg(mapping, 'source', null);
if (source !== null) {
source = this._sources.at(source);
source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
source = util.computeSourceURL(
this.sourceRoot,
source,
this._sourceMapURL
);
}
var name = util.getArg(mapping, 'name', null);
if (name !== null) {
@@ -717,7 +772,7 @@ BasicSourceMapConsumer.prototype.originalPositionFor =
source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: name
name: name,
};
}
}
@@ -726,7 +781,7 @@ BasicSourceMapConsumer.prototype.originalPositionFor =
source: null,
line: null,
column: null,
name: null
name: null,
};
};
@@ -739,8 +794,12 @@ BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
if (!this.sourcesContent) {
return false;
}
return this.sourcesContent.length >= this._sources.size() &&
!this.sourcesContent.some(function (sc) { return sc == null; });
return (
this.sourcesContent.length >= this._sources.size() &&
!this.sourcesContent.some(function (sc) {
return sc == null;
})
);
};
/**
@@ -765,21 +824,21 @@ BasicSourceMapConsumer.prototype.sourceContentFor =
}
var url;
if (this.sourceRoot != null
&& (url = util.urlParse(this.sourceRoot))) {
if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) {
// XXX: file:// URIs and absolute paths lead to unexpected behavior for
// many users. We can help them out when they expect file:// URIs to
// behave like it would if they were running a local HTTP server. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
if (url.scheme == "file"
&& this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
var fileUriAbsPath = relativeSource.replace(/^file:\/\//, '');
if (url.scheme == 'file' && this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
}
if ((!url.path || url.path == "/")
&& this._sources.has("/" + relativeSource)) {
return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
if (
(!url.path || url.path == '/') &&
this._sources.has('/' + relativeSource)
) {
return this.sourcesContent[this._sources.indexOf('/' + relativeSource)];
}
}
@@ -789,8 +848,7 @@ BasicSourceMapConsumer.prototype.sourceContentFor =
// return null, so we provide a flag to exit gracefully.
if (nullOnMissing) {
return null;
}
else {
} else {
throw new Error('"' + relativeSource + '" is not in the SourceMap.');
}
};
@@ -826,21 +884,21 @@ BasicSourceMapConsumer.prototype.generatedPositionFor =
return {
line: null,
column: null,
lastColumn: null
lastColumn: null,
};
}
var needle = {
source: source,
originalLine: util.getArg(aArgs, 'line'),
originalColumn: util.getArg(aArgs, 'column')
originalColumn: util.getArg(aArgs, 'column'),
};
var index = this._findMapping(
needle,
this._originalMappings,
"originalLine",
"originalColumn",
'originalLine',
'originalColumn',
util.compareByOriginalPositions,
util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
);
@@ -852,7 +910,7 @@ BasicSourceMapConsumer.prototype.generatedPositionFor =
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null),
};
}
}
@@ -860,7 +918,7 @@ BasicSourceMapConsumer.prototype.generatedPositionFor =
return {
line: null,
column: null,
lastColumn: null
lastColumn: null,
};
};
@@ -933,8 +991,9 @@ function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
var lastOffset = {
line: -1,
column: 0
column: 0,
};
var maxOffsetLine = 0;
this._sections = sections.map(function (s) {
if (s.url) {
// The url field will require support for asynchronicity.
@@ -945,22 +1004,68 @@ function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
var offsetLine = util.getArg(offset, 'line');
var offsetColumn = util.getArg(offset, 'column');
if (offsetLine < lastOffset.line ||
(offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
if (!isValidOffset(offsetLine) || !isValidOffset(offsetColumn)) {
throw new Error(
'Section offset line and column must be non-negative integers.'
);
}
if (offsetLine > MAX_SECTION_OFFSET_LINE) {
throw new Error(
'Section offset line must not exceed ' + MAX_SECTION_OFFSET_LINE + '.'
);
}
if (
offsetLine < lastOffset.line ||
(offsetLine === lastOffset.line && offsetColumn < lastOffset.column)
) {
throw new Error('Section offsets must be ordered and non-overlapping.');
}
lastOffset = offset;
var consumer = new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL);
// Offsets of a nested indexed map add up with this one, so apply the
// bound to the total.
var totalOffsetLine = offsetLine + (consumer._maxOffsetLine || 0);
if (totalOffsetLine > MAX_SECTION_OFFSET_LINE) {
throw new Error(
'Section offset line must not exceed ' +
MAX_SECTION_OFFSET_LINE +
', including offsets of nested sections.'
);
}
if (totalOffsetLine > maxOffsetLine) {
maxOffsetLine = totalOffsetLine;
}
return {
generatedOffset: {
// The offset fields are 0-based, but we use 1-based indices when
// encoding/decoding from VLQ.
generatedLine: offsetLine + 1,
generatedColumn: offsetColumn + 1
generatedColumn: offsetColumn + 1,
},
consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
}
consumer: consumer,
};
});
// The largest offset.line of any section, including nested sections.
this._maxOffsetLine = maxOffsetLine;
}
/**
* Section offsets come from untrusted input and are used as line/column
* numbers, so only accept non-negative safe integers (rejects NaN, Infinity,
* strings, fractions, etc).
*/
function isValidOffset(aValue) {
return (
typeof aValue === 'number' &&
aValue >= 0 &&
aValue <= 9007199254740991 && // Number.MAX_SAFE_INTEGER
Math.floor(aValue) === aValue
);
}
IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
@@ -978,12 +1083,16 @@ Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
get: function () {
var sources = [];
for (var i = 0; i < this._sections.length; i++) {
for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
sources.push(this._sections[i].consumer.sources[j]);
// Read the getter once per section: for a nested indexed map it is
// itself this getter, and re-reading it per item is exponential in the
// nesting depth (CVE-2026-93749).
var sectionSources = this._sections[i].consumer.sources;
for (var j = 0; j < sectionSources.length; j++) {
sources.push(sectionSources[j]);
}
}
return sources;
}
},
});
/**
@@ -1009,21 +1118,27 @@ IndexedSourceMapConsumer.prototype.originalPositionFor =
function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
generatedColumn: util.getArg(aArgs, 'column'),
};
// Find the section containing the generated position we're trying to map
// to an original position.
var sectionIndex = binarySearch.search(needle, this._sections,
function(needle, section) {
var sectionIndex = binarySearch.search(
needle,
this._sections,
function (needle, section) {
var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
if (cmp) {
return cmp;
}
return (needle.generatedColumn -
section.generatedOffset.generatedColumn);
});
// The needle's column is 0-based, generatedOffset.generatedColumn is
// 1-based.
return (
needle.generatedColumn - (section.generatedOffset.generatedColumn - 1)
);
}
);
var section = this._sections[sectionIndex];
if (!section) {
@@ -1031,18 +1146,18 @@ IndexedSourceMapConsumer.prototype.originalPositionFor =
source: null,
line: null,
column: null,
name: null
name: null,
};
}
return section.consumer.originalPositionFor({
line: needle.generatedLine -
(section.generatedOffset.generatedLine - 1),
column: needle.generatedColumn -
line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
column:
needle.generatedColumn -
(section.generatedOffset.generatedLine === needle.generatedLine
? section.generatedOffset.generatedColumn - 1
: 0),
bias: aArgs.bias
? section.generatedOffset.generatedColumn - 1
: 0),
bias: aArgs.bias,
});
};
@@ -1074,59 +1189,61 @@ IndexedSourceMapConsumer.prototype.sourceContentFor =
}
if (nullOnMissing) {
return null;
}
else {
} else {
throw new Error('"' + aSource + '" is not in the SourceMap.');
}
};
/**
* 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.
*/
IndexedSourceMapConsumer.prototype.generatedPositionFor =
function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
// SourceMapConsumer.prototype.allGeneratedPositionsFor and
// BasicSourceMapConsumer.prototype.generatedPositionFor search
// this._originalMappings, which holds the mappings of every section with
// their generated positions already shifted by the section offset. They need
// these two methods.
// Only consider this section if the requested source is in the list of
// sources of the consumer.
if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
continue;
}
var generatedPosition = section.consumer.generatedPositionFor(aArgs);
if (generatedPosition) {
var ret = {
line: generatedPosition.line +
(section.generatedOffset.generatedLine - 1),
column: generatedPosition.column +
(section.generatedOffset.generatedLine === generatedPosition.line
? section.generatedOffset.generatedColumn - 1
: 0)
};
return ret;
}
/**
* Returns the index of a source in this._sources, which holds the URLs of
* the sources that have mappings, or -1. Accepts any name a section
* accepts: relative to the section's sourceRoot or a URL from `sources`.
*/
IndexedSourceMapConsumer.prototype._findSourceIndex = function (aSource) {
// this._sources is filled in by _parseMappings, which runs on first access
// to the mappings.
this._generatedMappings;
for (var i = 0; i < this._sections.length; i++) {
var consumer = this._sections[i].consumer;
var index = consumer._findSourceIndex(aSource);
if (index === -1) {
continue;
}
return {
line: null,
column: null
};
};
// The same URL _parseMappings stores the source under.
var url = util.computeSourceURL(
consumer.sourceRoot,
consumer._sources.at(index),
this._sourceMapURL
);
if (this._sources.has(url)) {
return this._sources.indexOf(url);
}
}
return -1;
};
IndexedSourceMapConsumer.prototype._findMapping =
BasicSourceMapConsumer.prototype._findMapping;
// Searching the mappings of all sections at once finds the closest mapping
// across sections, the same as for the map without sections.
IndexedSourceMapConsumer.prototype.generatedPositionFor =
BasicSourceMapConsumer.prototype.generatedPositionFor;
// Computes the spans on this._generatedMappings, the offset-shifted mappings
// of all sections, which the lookups above return. A mapping's span ends
// where the next mapping starts, even if that one is in the next section.
IndexedSourceMapConsumer.prototype.computeColumnSpans =
BasicSourceMapConsumer.prototype.computeColumnSpans;
/**
* Parse the mappings in a string in to a data structure which we can easily
@@ -1144,8 +1261,12 @@ IndexedSourceMapConsumer.prototype._parseMappings =
var mapping = sectionMappings[j];
var source = section.consumer._sources.at(mapping.source);
if(source !== null) {
source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
if (source !== null) {
source = util.computeSourceURL(
section.consumer.sourceRoot,
source,
this._sourceMapURL
);
}
this._sources.add(source);
source = this._sources.indexOf(source);
@@ -1160,18 +1281,20 @@ IndexedSourceMapConsumer.prototype._parseMappings =
// The mappings coming from the consumer for the section have
// generated positions relative to the start of the section, so we
// need to offset them to be relative to the start of the concatenated
// generated file.
// generated file. The column offset only applies to the section's
// first line.
var adjustedMapping = {
source: source,
generatedLine: mapping.generatedLine +
(section.generatedOffset.generatedLine - 1),
generatedColumn: mapping.generatedColumn +
(section.generatedOffset.generatedLine === mapping.generatedLine
? section.generatedOffset.generatedColumn - 1
: 0),
generatedLine:
mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
generatedColumn:
mapping.generatedColumn +
(mapping.generatedLine === 1
? section.generatedOffset.generatedColumn - 1
: 0),
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: name
name: name,
};
this.__generatedMappings.push(adjustedMapping);
@@ -1181,7 +1304,10 @@ IndexedSourceMapConsumer.prototype._parseMappings =
}
}
quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
quickSort(
this.__generatedMappings,
util.compareByGeneratedPositionsDeflated
);
quickSort(this.__originalMappings, util.compareByOriginalPositions);
};
+153 -111
View File
@@ -25,7 +25,11 @@ function SourceMapGenerator(aArgs) {
this._file = util.getArg(aArgs, 'file', null);
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
this._ignoreInvalidMapping = util.getArg(aArgs, 'ignoreInvalidMapping', false);
this._ignoreInvalidMapping = util.getArg(
aArgs,
'ignoreInvalidMapping',
false
);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
@@ -39,56 +43,60 @@ SourceMapGenerator.prototype._version = 3;
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap =
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer, generatorOps) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator(Object.assign(generatorOps || {}, {
SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(
aSourceMapConsumer,
generatorOps
) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator(
Object.assign(generatorOps || {}, {
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
}));
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
sourceRoot: sourceRoot,
})
);
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn,
},
};
if (mapping.source != null) {
newMapping.source = mapping.source;
if (sourceRoot != null) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn,
};
if (mapping.source != null) {
newMapping.source = mapping.source;
if (sourceRoot != null) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name != null) {
newMapping.name = mapping.name;
}
if (mapping.name != null) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var sourceRelative = sourceFile;
if (sourceRoot !== null) {
sourceRelative = util.relative(sourceRoot, sourceFile);
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var sourceRelative = sourceFile;
if (sourceRoot !== null) {
sourceRelative = util.relative(sourceRoot, sourceFile);
}
if (!generator._sources.has(sourceRelative)) {
generator._sources.add(sourceRelative);
}
if (!generator._sources.has(sourceRelative)) {
generator._sources.add(sourceRelative);
}
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
@@ -133,7 +141,7 @@ SourceMapGenerator.prototype.addMapping =
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
name: name,
});
};
@@ -181,14 +189,18 @@ SourceMapGenerator.prototype.setSourceContent =
* relative to the SourceMapGenerator.
*/
SourceMapGenerator.prototype.applySourceMap =
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
function SourceMapGenerator_applySourceMap(
aSourceMapConsumer,
aSourceFile,
aSourceMapPath
) {
var sourceFile = aSourceFile;
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (aSourceFile == null) {
if (aSourceMapConsumer.file == null) {
throw new Error(
'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
'or the source map\'s "file" property. Both were omitted.'
'or the source map\'s "file" property. Both were omitted.'
);
}
sourceFile = aSourceMapConsumer.file;
@@ -209,13 +221,13 @@ SourceMapGenerator.prototype.applySourceMap =
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
column: mapping.originalColumn,
});
if (original.source != null) {
// Copy mapping
mapping.source = original.source;
if (aSourceMapPath != null) {
mapping.source = util.join(aSourceMapPath, mapping.source)
mapping.source = util.join(aSourceMapPath, mapping.source);
}
if (sourceRoot != null) {
mapping.source = util.relative(sourceRoot, mapping.source);
@@ -237,7 +249,6 @@ SourceMapGenerator.prototype.applySourceMap =
if (name != null && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
@@ -269,16 +280,25 @@ SourceMapGenerator.prototype.applySourceMap =
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
function SourceMapGenerator_validateMapping(
aGenerated,
aOriginal,
aSource,
aName
) {
// When aOriginal is truthy but has empty values for .line and .column,
// it is most likely a programmer error. In this case we throw a very
// specific error message to try to guide them the right way.
// For example: https://github.com/Polymer/polymer-bundler/pull/519
if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
var message = 'original.line and original.column are not numbers -- you probably meant to omit ' +
'the original mapping entirely and only map the generated position. If so, pass ' +
'null for the original mapping instead of an object with empty or null values.'
if (
aOriginal &&
typeof aOriginal.line !== 'number' &&
typeof aOriginal.column !== 'number'
) {
var message =
'original.line and original.column are not numbers -- you probably meant to omit ' +
'the original mapping entirely and only map the generated position. If so, pass ' +
'null for the original mapping instead of an object with empty or null values.';
if (this._ignoreInvalidMapping) {
if (typeof console !== 'undefined' && console.warn) {
@@ -290,27 +310,42 @@ SourceMapGenerator.prototype._validateMapping =
}
}
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
if (
aGenerated &&
'line' in aGenerated &&
'column' in aGenerated &&
aGenerated.line > 0 &&
aGenerated.column >= 0 &&
!aOriginal &&
!aSource &&
!aName
) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
} else if (
aGenerated &&
'line' in aGenerated &&
'column' in aGenerated &&
aOriginal &&
'line' in aOriginal &&
'column' in aOriginal &&
aGenerated.line > 0 &&
aGenerated.column >= 0 &&
aOriginal.line > 0 &&
aOriginal.column >= 0 &&
aSource
) {
// Cases 2 and 3.
return;
}
else {
var message = 'Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName
});
} else {
var message =
'Invalid mapping: ' +
JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName,
});
if (this._ignoreInvalidMapping) {
if (typeof console !== 'undefined' && console.warn) {
@@ -318,7 +353,7 @@ SourceMapGenerator.prototype._validateMapping =
}
return false;
} else {
throw new Error(message)
throw new Error(message);
}
}
};
@@ -344,26 +379,30 @@ SourceMapGenerator.prototype._serializeMappings =
var mappings = this._mappings.toArray();
for (var i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
next = ''
next = '';
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
next += ';';
previousGeneratedLine++;
}
}
else {
// One ';' per skipped line. Build large gaps with a single flat
// string: appending ';' one by one creates a rope node per line, which
// can exhaust the heap for a big gap (CVE-2026-93749).
var lineDelta = mapping.generatedLine - previousGeneratedLine;
next += lineDelta === 1 ? ';' : ';'.repeat(lineDelta);
previousGeneratedLine = mapping.generatedLine;
} else {
if (i > 0) {
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
if (
!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])
) {
continue;
}
next += ',';
}
}
next += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
next += base64VLQ.encode(
mapping.generatedColumn - previousGeneratedColumn
);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source != null) {
@@ -372,12 +411,14 @@ SourceMapGenerator.prototype._serializeMappings =
previousSource = sourceIdx;
// lines are stored 0-based in SourceMap spec version 3
next += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
next += base64VLQ.encode(
mapping.originalLine - 1 - previousOriginalLine
);
previousOriginalLine = mapping.originalLine - 1;
next += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
next += base64VLQ.encode(
mapping.originalColumn - previousOriginalColumn
);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name != null) {
@@ -412,33 +453,34 @@ SourceMapGenerator.prototype._generateSourcesContent =
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON =
function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._file != null) {
map.file = this._file;
}
if (this._sourceRoot != null) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings(),
};
if (this._file != null) {
map.file = this._file;
}
if (this._sourceRoot != null) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(
map.sources,
map.sourceRoot
);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
return JSON.stringify(this.toJSON());
};
SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() {
return JSON.stringify(this.toJSON());
};
exports.SourceMapGenerator = SourceMapGenerator;
+151 -118
View File
@@ -18,7 +18,7 @@ var NEWLINE_CODE = 10;
// Private symbol for identifying `SourceNode`s when multiple versions of
// the source-map library are loaded. This MUST NOT CHANGE across
// versions!
var isSourceNode = "$$$isSourceNode$$$";
var isSourceNode = '$$$isSourceNode$$$';
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
@@ -52,7 +52,11 @@ function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
* SourceMapConsumer should be relative to.
*/
SourceNode.fromStringWithSourceMap =
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
function SourceNode_fromStringWithSourceMap(
aGeneratedCode,
aSourceMapConsumer,
aRelativePath
) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
@@ -63,20 +67,22 @@ SourceNode.fromStringWithSourceMap =
// Processed fragments are accessed by calling `shiftNextLine`.
var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
var remainingLinesIndex = 0;
var shiftNextLine = function() {
var shiftNextLine = function () {
var lineContents = getNextLine();
// The last line of a file might not have a newline.
var newLine = getNextLine() || "";
var newLine = getNextLine() || '';
return lineContents + newLine;
function getNextLine() {
return remainingLinesIndex < remainingLines.length ?
remainingLines[remainingLinesIndex++] : undefined;
return remainingLinesIndex < remainingLines.length
? remainingLines[remainingLinesIndex++]
: undefined;
}
};
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
var lastGeneratedLine = 1,
lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
@@ -98,10 +104,13 @@ SourceNode.fromStringWithSourceMap =
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[remainingLinesIndex] || '';
var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
var code = nextLine.substr(
0,
mapping.generatedColumn - lastGeneratedColumn
);
remainingLines[remainingLinesIndex] = nextLine.substr(
mapping.generatedColumn - lastGeneratedColumn
);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
// No more remaining code, continue
@@ -113,13 +122,22 @@ SourceNode.fromStringWithSourceMap =
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
if (remainingLinesIndex >= remainingLines.length) {
// The generated code is exhausted. Skip the rest instead of adding
// empty lines one by one: a mapping may point far past the end of
// the code (e.g. an indexed map section with a huge offset.line).
lastGeneratedLine = mapping.generatedLine;
break;
}
node.add(shiftNextLine());
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[remainingLinesIndex] || '';
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
remainingLines[remainingLinesIndex] = nextLine.substr(
mapping.generatedColumn
);
lastGeneratedColumn = mapping.generatedColumn;
}
lastMapping = mapping;
@@ -131,7 +149,7 @@ SourceNode.fromStringWithSourceMap =
addMappingWithCode(lastMapping, shiftNextLine());
}
// and add the remaining lines without any mapping
node.add(remainingLines.splice(remainingLinesIndex).join(""));
node.add(remainingLines.splice(remainingLinesIndex).join(''));
}
// Copy sourcesContent into SourceNode
@@ -154,11 +172,15 @@ SourceNode.fromStringWithSourceMap =
var source = aRelativePath
? util.join(aRelativePath, mapping.source)
: mapping.source;
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
source,
code,
mapping.name));
node.add(
new SourceNode(
mapping.originalLine,
mapping.originalColumn,
source,
code,
mapping.name
)
);
}
}
};
@@ -174,15 +196,14 @@ SourceNode.prototype.add = function SourceNode_add(aChunk) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
} else if (aChunk[isSourceNode] || typeof aChunk === 'string') {
if (aChunk) {
this.children.push(aChunk);
}
}
else {
} else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
'Expected a SourceNode, string, or an array of SourceNodes and strings. Got ' +
aChunk
);
}
return this;
@@ -196,16 +217,15 @@ SourceNode.prototype.add = function SourceNode_add(aChunk) {
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length-1; i >= 0; i--) {
for (var i = aChunk.length - 1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
}
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
} else if (aChunk[isSourceNode] || typeof aChunk === 'string') {
this.children.unshift(aChunk);
}
else {
} else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
'Expected a SourceNode, string, or an array of SourceNodes and strings. Got ' +
aChunk
);
}
return this;
@@ -224,13 +244,14 @@ SourceNode.prototype.walk = function SourceNode_walk(aFn) {
chunk = this.children[i];
if (chunk[isSourceNode]) {
chunk.walk(aFn);
}
else {
} else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
aFn(chunk, {
source: this.source,
line: this.line,
column: this.column,
name: this.name,
});
}
}
}
@@ -248,7 +269,7 @@ SourceNode.prototype.join = function SourceNode_join(aSep) {
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
for (i = 0; i < len - 1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
@@ -265,15 +286,20 @@ SourceNode.prototype.join = function SourceNode_join(aSep) {
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(
aPattern,
aReplacement
) {
var lastChild = this.children[this.children.length - 1];
if (lastChild[isSourceNode]) {
// Without children, lastChild is undefined and the final branch applies.
if (lastChild && lastChild[isSourceNode]) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
} else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(
aPattern,
aReplacement
);
} else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
@@ -286,10 +312,12 @@ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, a
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent =
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(
aSourceFile,
aSourceContent
) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
@@ -316,7 +344,7 @@ SourceNode.prototype.walkSourceContents =
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
var str = '';
this.walk(function (chunk) {
str += chunk;
});
@@ -327,87 +355,92 @@ SourceNode.prototype.toString = function SourceNode_toString() {
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if(lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
for (var idx = 0, length = chunk.length; idx < length; idx++) {
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
generated.line++;
generated.column = 0;
// Mappings end at eol
if (idx + 1 === length) {
lastOriginalSource = null;
sourceMappingActive = false;
} else if (sourceMappingActive) {
SourceNode.prototype.toStringWithSourceMap =
function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: '',
line: 1,
column: 0,
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (
original.source !== null &&
original.line !== null &&
original.column !== null
) {
if (
lastOriginalSource !== original.source ||
lastOriginalLine !== original.line ||
lastOriginalColumn !== original.column ||
lastOriginalName !== original.name
) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
column: original.column,
},
generated: {
line: generated.line,
column: generated.column
column: generated.column,
},
name: original.name
name: original.name,
});
}
} else {
generated.column++;
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column,
},
});
lastOriginalSource = null;
sourceMappingActive = false;
}
}
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
for (var idx = 0, length = chunk.length; idx < length; idx++) {
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
generated.line++;
generated.column = 0;
// Mappings end at eol
if (idx + 1 === length) {
lastOriginalSource = null;
sourceMappingActive = false;
} else if (sourceMappingActive) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column,
},
generated: {
line: generated.line,
column: generated.column,
},
name: original.name,
});
}
} else {
generated.column++;
}
}
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;
+55 -36
View File
@@ -26,7 +26,8 @@ function getArg(aArgs, aName, aDefaultValue) {
}
exports.getArg = getArg;
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
var urlRegexp =
/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
var dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
@@ -39,7 +40,7 @@ function urlParse(aUrl) {
auth: match[2],
host: match[3],
port: match[4],
path: match[5]
path: match[5],
};
}
exports.urlParse = urlParse;
@@ -57,7 +58,7 @@ function urlGenerate(aParsedUrl) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
url += ':' + aParsedUrl.port;
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
@@ -78,7 +79,7 @@ var MAX_CACHED_INPUTS = 32;
function lruMemoize(f) {
var cache = [];
return function(input) {
return function (input) {
for (var i = 0; i < cache.length; i++) {
if (cache[i].input === input) {
var temp = cache[0];
@@ -131,13 +132,13 @@ var normalize = lruMemoize(function normalize(aPath) {
var i = 0;
while (true) {
start = i;
i = path.indexOf("/", start);
i = path.indexOf('/', start);
if (i === -1) {
parts.push(path.slice(start));
break;
} else {
parts.push(path.slice(start, i));
while (i < path.length && path[i] === "/") {
while (i < path.length && path[i] === '/') {
i++;
}
}
@@ -193,11 +194,11 @@ exports.normalize = normalize;
* - Joining for example 'http://' and 'www.example.com' is also supported.
*/
function join(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
if (aRoot === '') {
aRoot = '.';
}
if (aPath === "") {
aPath = ".";
if (aPath === '') {
aPath = '.';
}
var aPathUrl = urlParse(aPath);
var aRootUrl = urlParse(aRoot);
@@ -223,9 +224,10 @@ function join(aRoot, aPath) {
return urlGenerate(aRootUrl);
}
var joined = aPath.charAt(0) === '/'
? aPath
: normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
var joined =
aPath.charAt(0) === '/'
? aPath
: normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
@@ -246,8 +248,8 @@ exports.isAbsolute = function (aPath) {
* @param aPath The path or URL to be made relative to aRoot.
*/
function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
if (aRoot === '') {
aRoot = '.';
}
aRoot = aRoot.replace(/\/$/, '');
@@ -258,7 +260,7 @@ function relative(aRoot, aPath) {
// a prefix that fits, or we run out of components to remove.
var level = 0;
while (aPath.indexOf(aRoot + '/') !== 0) {
var index = aRoot.lastIndexOf("/");
var index = aRoot.lastIndexOf('/');
if (index < 0) {
return aPath;
}
@@ -275,16 +277,16 @@ function relative(aRoot, aPath) {
}
// Make sure we add a "../" for each component we removed from the root.
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
return Array(level + 1).join('../') + aPath.substr(aRoot.length + 1);
}
exports.relative = relative;
var supportsNullProto = (function () {
var obj = Object.create(null);
return !('__proto__' in obj);
}());
})();
function identity (s) {
function identity(s) {
return s;
}
@@ -326,15 +328,17 @@ function isProtoString(s) {
return false;
}
if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
s.charCodeAt(length - 2) !== 95 /* '_' */ ||
s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
s.charCodeAt(length - 4) !== 116 /* 't' */ ||
s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
s.charCodeAt(length - 8) !== 95 /* '_' */ ||
s.charCodeAt(length - 9) !== 95 /* '_' */) {
if (
s.charCodeAt(length - 1) !== 95 /* '_' */ ||
s.charCodeAt(length - 2) !== 95 /* '_' */ ||
s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
s.charCodeAt(length - 4) !== 116 /* 't' */ ||
s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
s.charCodeAt(length - 8) !== 95 /* '_' */ ||
s.charCodeAt(length - 9) !== 95 /* '_' */
) {
return false;
}
@@ -385,8 +389,12 @@ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
}
exports.compareByOriginalPositions = compareByOriginalPositions;
function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {
var cmp
function compareByOriginalPositionsNoSource(
mappingA,
mappingB,
onlyCompareOriginal
) {
var cmp;
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
@@ -421,7 +429,11 @@ exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
function compareByGeneratedPositionsDeflated(
mappingA,
mappingB,
onlyCompareGenerated
) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
@@ -449,9 +461,14 @@ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGene
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
exports.compareByGeneratedPositionsDeflated =
compareByGeneratedPositionsDeflated;
function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {
function compareByGeneratedPositionsDeflatedNoLine(
mappingA,
mappingB,
onlyCompareGenerated
) {
var cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0 || onlyCompareGenerated) {
return cmp;
@@ -474,7 +491,8 @@ function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompa
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;
exports.compareByGeneratedPositionsDeflatedNoLine =
compareByGeneratedPositionsDeflatedNoLine;
function strcmp(aStr1, aStr2) {
if (aStr1 === aStr2) {
@@ -528,7 +546,8 @@ function compareByGeneratedPositionsInflated(mappingA, mappingB) {
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
exports.compareByGeneratedPositionsInflated =
compareByGeneratedPositionsInflated;
/**
* Strip any JSON XSSI avoidance prefix from the string (as documented
@@ -577,7 +596,7 @@ function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
if (sourceMapURL) {
var parsed = urlParse(sourceMapURL);
if (!parsed) {
throw new Error("sourceMapURL could not be parsed");
throw new Error('sourceMapURL could not be parsed');
}
if (parsed.path) {
// Strip the last path component, but keep the "/".
+14 -7
View File
@@ -1,7 +1,7 @@
{
"name": "source-map-js",
"description": "Generates and consumes source maps",
"version": "1.2.1",
"version": "1.2.4",
"homepage": "https://github.com/7rulnik/source-map-js",
"author": "Valentin 7rulnik Semirulnik <v7rulnik@gmail.com>",
"contributors": [
@@ -51,21 +51,28 @@
"lib/"
],
"engines": {
"node": ">=0.10.0"
"node": ">=6.0.0"
},
"license": "BSD-3-Clause",
"scripts": {
"test": "npm run build && node test/run-tests.js",
"build": "webpack --color",
"toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
"test": "node --test --test-reporter=spec 'test/test-*.js'",
"test:coverage": "node --experimental-config-file=node.config.json --test --test-reporter=spec --experimental-test-coverage 'test/test-*.js'",
"format": "prettier --write .",
"format:check": "prettier --check .",
"toc": "doctoc --title '## Table of Contents' README.md && prettier --write README.md"
},
"devDependencies": {
"clean-publish": "^3.1.0",
"doctoc": "^0.15.0",
"webpack": "^1.12.0"
"prettier": "3.10.1"
},
"prettier": {
"singleQuote": true,
"trailingComma": "es5"
},
"clean-publish": {
"cleanDocs": true
},
"typings": "source-map.d.ts"
"typings": "source-map.d.ts",
"packageManager": "pnpm@12.21.0"
}
+177 -63
View File
@@ -1,104 +1,218 @@
export interface StartOfSourceMap {
file?: string;
sourceRoot?: string;
file?: string;
sourceRoot?: string;
}
/**
* A source map as `SourceMapGenerator#toJSON` returns it. For a source map
* passed to `SourceMapConsumer`, use `RawSourceMapInput`.
*/
export interface RawSourceMap extends StartOfSourceMap {
version: string;
sources: string[];
names: string[];
sourcesContent?: string[];
mappings: string;
/** The number `3` at runtime. Typed as a string for backward compatibility. */
version: string;
sources: string[];
names: string[];
/**
* `null` for each source without content at runtime. Typed as `string[]`
* for backward compatibility.
*/
sourcesContent?: string[];
mappings: string;
}
/**
* A source map as `SourceMapConsumer` accepts it. Unlike `RawSourceMap`, the
* `version` can be a number, `sourcesContent` can have `null` entries, and
* `names` can be left out.
*/
export interface RawSourceMapInput extends StartOfSourceMap {
version: number | string;
sources: string[];
names?: string[];
sourcesContent?: (string | null)[];
mappings: string;
}
export interface RawSection {
/** Where the section starts in the generated code. Both are 0-based. */
offset: Position;
map: RawSourceMapInput | RawIndexMap;
}
/** A source map made of sections, each with its own source map. */
export interface RawIndexMap {
version: number | string;
file?: string;
sections: RawSection[];
}
export interface Position {
line: number;
column: number;
line: number;
column: number;
}
export interface LineRange extends Position {
lastColumn: number;
lastColumn: number;
}
export interface FindPosition extends Position {
// SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND
bias?: number;
// SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND
bias?: number;
}
export interface SourceFindPosition extends FindPosition {
source: string;
source: string;
}
export interface MappedPosition extends Position {
source: string;
name?: string;
source: string;
name?: string;
}
export interface MappingItem {
source: string | null;
generatedLine: number;
generatedColumn: number;
originalLine: number | null;
originalColumn: number | null;
name: string | null;
source: string | null;
generatedLine: number;
generatedColumn: number;
originalLine: number | null;
originalColumn: number | null;
name: string | null;
}
export class SourceMapConsumer {
static GENERATED_ORDER: number;
static ORIGINAL_ORDER: number;
static GENERATED_ORDER: number;
static ORIGINAL_ORDER: number;
static GREATEST_LOWER_BOUND: number;
static LEAST_UPPER_BOUND: number;
static GREATEST_LOWER_BOUND: number;
static LEAST_UPPER_BOUND: number;
constructor(rawSourceMap: RawSourceMap);
readonly file: string | undefined | null;
readonly sourceRoot: string | undefined | null;
readonly sourcesContent: readonly string[] | null | undefined;
readonly sources: readonly string[]
/**
* @param rawSourceMap A source map or an index map, as an object or as a
* JSON string.
* @param sourceMapUrl The URL of the source map. Relative `sources` are
* resolved against it.
*/
constructor(
rawSourceMap: RawSourceMapInput | RawIndexMap | string,
sourceMapUrl?: string
);
static fromSourceMap(
sourceMap: SourceMapGenerator,
sourceMapUrl?: string
): SourceMapConsumer;
readonly file: string | undefined | null;
readonly sourceRoot: string | undefined | null;
/** Can have `null` entries at runtime: one for each source without content. */
readonly sourcesContent: readonly string[] | null | undefined;
readonly sources: readonly string[];
computeColumnSpans(): void;
originalPositionFor(generatedPosition: FindPosition): MappedPosition;
generatedPositionFor(originalPosition: SourceFindPosition): LineRange;
allGeneratedPositionsFor(originalPosition: MappedPosition): Position[];
hasContentsOfAllSources(): boolean;
sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null;
eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void;
computeColumnSpans(): void;
/**
* At runtime, `source`, `line`, `column` and `name` are all `null` when no
* mapping is found, and `name` is `null` when the mapping has no name.
*/
originalPositionFor(generatedPosition: FindPosition): MappedPosition;
/**
* At runtime, `line`, `column` and `lastColumn` are all `null` when no
* mapping is found, and `lastColumn` is `null` until `computeColumnSpans()`
* is called.
*/
generatedPositionFor(originalPosition: SourceFindPosition): LineRange;
/**
* Without a `column`, returns the mappings of the line, or of the next line
* that has mappings. `lastColumn` is `null` until `computeColumnSpans()` is
* called.
*/
allGeneratedPositionsFor(
originalPosition:
MappedPosition | { source: string; line: number; column?: number }
): Array<Position & { lastColumn?: number | null }>;
hasContentsOfAllSources(): boolean;
sourceContentFor(
source: string,
returnNullOnMissing?: boolean
): string | null;
eachMapping(
callback: (mapping: MappingItem) => void,
context?: any,
order?: number
): void;
}
export interface Mapping {
generated: Position;
original?: Position | null;
source?: string | null;
name?: string | null;
generated: Position;
original?: Position | null;
source?: string | null;
name?: string | null;
}
export interface SourceMapGeneratorOptions extends StartOfSourceMap {
/** Don't validate mappings in `addMapping`. */
skipValidation?: boolean;
/** Warn about invalid mappings and skip them, instead of throwing. */
ignoreInvalidMapping?: boolean;
}
export class SourceMapGenerator {
constructor(startOfSourceMap?: StartOfSourceMap);
static fromSourceMap(sourceMapConsumer: SourceMapConsumer, startOfSourceMap?: StartOfSourceMap): SourceMapGenerator;
addMapping(mapping: Mapping): void;
setSourceContent(sourceFile: string, sourceContent: string | null | undefined): void;
applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void;
toString(): string;
toJSON(): RawSourceMap;
constructor(startOfSourceMap?: SourceMapGeneratorOptions);
static fromSourceMap(
sourceMapConsumer: SourceMapConsumer,
startOfSourceMap?: SourceMapGeneratorOptions
): SourceMapGenerator;
addMapping(mapping: Mapping): void;
setSourceContent(
sourceFile: string,
sourceContent: string | null | undefined
): void;
applySourceMap(
sourceMapConsumer: SourceMapConsumer,
sourceFile?: string,
sourceMapPath?: string
): void;
toString(): string;
toJSON(): RawSourceMap;
}
export interface CodeWithSourceMap {
code: string;
map: SourceMapGenerator;
code: string;
map: SourceMapGenerator;
}
/** A string of generated code, a `SourceNode`, or an array of chunks. */
export type SourceNodeChunk = string | SourceNode | SourceNodeChunkArray;
export interface SourceNodeChunkArray extends Array<SourceNodeChunk> {}
export class SourceNode {
constructor();
constructor(line: number, column: number, source: string);
constructor(line: number, column: number, source: string, chunk?: string, name?: string);
static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode;
add(chunk: string): void;
prepend(chunk: string): void;
setSourceContent(sourceFile: string, sourceContent: string): void;
walk(fn: (chunk: string, mapping: MappedPosition) => void): void;
walkSourceContents(fn: (file: string, content: string) => void): void;
join(sep: string): SourceNode;
replaceRight(pattern: string, replacement: string): SourceNode;
toString(): string;
toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap;
constructor();
constructor(
line: number | null,
column: number | null,
source: string | null,
chunks?: SourceNodeChunk,
name?: string | null
);
static fromStringWithSourceMap(
code: string,
sourceMapConsumer: SourceMapConsumer,
relativePath?: string
): SourceNode;
/** Returns this node at runtime. */
add(chunk: SourceNodeChunk): void;
/** Returns this node at runtime. */
prepend(chunk: SourceNodeChunk): void;
setSourceContent(sourceFile: string, sourceContent: string): void;
/**
* At runtime, `source`, `line`, `column` and `name` are `null` for chunks
* without an original position, and `name` is `null` when there's no name.
*/
walk(fn: (chunk: string, mapping: MappedPosition) => void): void;
walkSourceContents(fn: (file: string, content: string) => void): void;
join(sep: string): SourceNode;
replaceRight(
pattern: string | RegExp,
replacement: string | ((substring: string, ...args: any[]) => string)
): SourceNode;
toString(): string;
toStringWithSourceMap(
startOfSourceMap?: SourceMapGeneratorOptions
): CodeWithSourceMap;
}
+4 -2
View File
@@ -3,6 +3,8 @@
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
exports.SourceMapGenerator =
require('./lib/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer =
require('./lib/source-map-consumer').SourceMapConsumer;
exports.SourceNode = require('./lib/source-node').SourceNode;