code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
unsortedForEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
}
|
Iterate through internal items. This method takes the same arguments that
`Array.prototype.forEach` takes.
NOTE: The order of the mappings is NOT guaranteed.
|
unsortedForEach
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
add(aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.push(aMapping);
} else {
this._sorted = false;
this._array.push(aMapping);
}
}
|
Add the given source mapping.
@param Object aMapping
|
add
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
toArray() {
if (!this._sorted) {
this._array.sort(util.compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
}
|
Returns the flat, sorted array of mappings. The mappings are sorted by
generated position.
WARNING: This method returns internal data without copying, for
performance. The return value must NOT be mutated, and should be treated as
an immutable borrow. If you want to take ownership, you must make your own
copy.
|
toArray
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
static async with(rawSourceMap, sourceMapUrl, f) {
const consumer = await new SourceMapConsumer(rawSourceMap, sourceMapUrl);
try {
return await f(consumer);
} finally {
consumer.destroy();
}
}
|
Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl`
(see the `SourceMapConsumer` constructor for details. Then, invoke the `async
function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait
for `f` to complete, call `destroy` on the consumer, and return `f`'s return
value.
You must not use the consumer after `f` completes!
By using `with`, you do not have to remember to manually call `destroy` on
the consumer, since it will be called automatically once `f` completes.
```js
const xSquared = await SourceMapConsumer.with(
myRawSourceMap,
null,
async function (consumer) {
// Use `consumer` inside here and don't worry about remembering
// to call `destroy`.
const x = await whatever(consumer);
return x * x;
}
);
// You may not use that `consumer` anymore out here; it has
// been destroyed. But you can use `xSquared`.
console.log(xSquared);
```
|
with
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
eachMapping(aCallback, aContext, aOrder) {
throw new Error("Subclasses must implement eachMapping");
}
|
Iterate over each mapping between an original source/line/column and a
generated line/column in this source map.
@param Function aCallback
The function that is called with each mapping.
@param Object aContext
Optional. If specified, this object will be the value of `this` every
time that `aCallback` is called.
@param aOrder
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`.
|
eachMapping
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
allGeneratedPositionsFor(aArgs) {
throw new Error("Subclasses must implement allGeneratedPositionsFor");
}
|
Returns all generated line and column information for the original source,
line, and column provided. If no column is provided, returns all mappings
corresponding to a either the line we are searching for or the next
closest line that has any mappings. Otherwise, returns all mappings
corresponding to the given line and either the column we are searching for
or the next closest column that has any offsets.
The only argument is an object with the following properties:
- source: The filename of the original source.
- line: The line number in the original source. The line number is 1-based.
- column: Optional. the column number in the original source.
The column number is 0-based.
and an array of objects is returned, each with the following properties:
- line: The line number in the generated source, or null. The
line number is 1-based.
- column: The column number in the generated source, or null.
The column number is 0-based.
|
allGeneratedPositionsFor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
destroy() {
throw new Error("Subclasses must implement destroy");
}
|
Returns all generated line and column information for the original source,
line, and column provided. If no column is provided, returns all mappings
corresponding to a either the line we are searching for or the next
closest line that has any mappings. Otherwise, returns all mappings
corresponding to the given line and either the column we are searching for
or the next closest column that has any offsets.
The only argument is an object with the following properties:
- source: The filename of the original source.
- line: The line number in the original source. The line number is 1-based.
- column: Optional. the column number in the original source.
The column number is 0-based.
and an array of objects is returned, each with the following properties:
- line: The line number in the generated source, or null. The
line number is 1-based.
- column: The column number in the generated source, or null.
The column number is 0-based.
|
destroy
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
constructor(aSourceMap, aSourceMapURL) {
return super(INTERNAL).then(that => {
let sourceMap = aSourceMap;
if (typeof aSourceMap === "string") {
sourceMap = util.parseSourceMapInput(aSourceMap);
}
const version = util.getArg(sourceMap, "version");
const sources = util.getArg(sourceMap, "sources").map(String);
// Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
// requires the array) to play nice here.
const names = util.getArg(sourceMap, "names", []);
const sourceRoot = util.getArg(sourceMap, "sourceRoot", null);
const sourcesContent = util.getArg(sourceMap, "sourcesContent", null);
const mappings = util.getArg(sourceMap, "mappings");
const file = util.getArg(sourceMap, "file", null);
// Once again, Sass deviates from the spec and supplies the version as a
// string rather than a number, so we use loose equality checking here.
if (version != that._version) {
throw new Error("Unsupported version: " + version);
}
that._sourceLookupCache = new Map();
// Pass `true` below to allow duplicate names and sources. While source maps
// are intended to be compressed and deduplicated, the TypeScript compiler
// sometimes generates source maps with duplicates in them. See Github issue
// #72 and bugzil.la/889492.
that._names = ArraySet.fromArray(names.map(String), true);
that._sources = ArraySet.fromArray(sources, true);
that._absoluteSources = ArraySet.fromArray(that._sources.toArray().map(function(s) {
return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
}), true);
that.sourceRoot = sourceRoot;
that.sourcesContent = sourcesContent;
that._mappings = mappings;
that._sourceMapURL = aSourceMapURL;
that.file = file;
that._computedColumnSpans = false;
that._mappingsPtr = 0;
that._wasm = null;
return wasm().then(w => {
that._wasm = w;
return that;
});
});
}
|
A BasicSourceMapConsumer instance represents a parsed source map which we can
query for information about the original file positions by giving it a file
position in the generated source.
The first parameter is the raw source map (either as a JSON string, or
already parsed to an object). According to the spec, source maps have the
following attributes:
- version: Which version of the source map spec this map is following.
- sources: An array of URLs to the original source files.
- names: An array of identifiers which can be referenced by individual mappings.
- sourceRoot: Optional. The URL root from which all sources are relative.
- sourcesContent: Optional. An array of contents of the original source files.
- mappings: A string of base64 VLQs which contain the actual mappings.
- file: Optional. The generated file this source map is associated with.
Here is an example source map, taken from the source map spec[0]:
{
version : 3,
file: "out.js",
sourceRoot : "",
sources: ["foo.js", "bar.js"],
names: ["src", "maps", "are", "fun"],
mappings: "AA,AB;;ABCDE;"
}
The second parameter, if given, is a string whose value is the URL
at which the source map was found. This URL is used to compute the
sources array.
[0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
|
constructor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
_findSourceIndex(aSource) {
// In the most common usecases, we'll be constantly looking up the index for the same source
// files, so we cache the index lookup to avoid constantly recomputing the full URLs.
const cachedIndex = this._sourceLookupCache.get(aSource);
if (typeof cachedIndex === "number") {
return cachedIndex;
}
// Treat the source as map-relative overall by default.
const sourceAsMapRelative = util.computeSourceURL(null, aSource, this._sourceMapURL);
if (this._absoluteSources.has(sourceAsMapRelative)) {
const index = this._absoluteSources.indexOf(sourceAsMapRelative);
this._sourceLookupCache.set(aSource, index);
return index;
}
// Fall back to treating the source as sourceRoot-relative.
const sourceAsSourceRootRelative = util.computeSourceURL(this.sourceRoot, aSource, this._sourceMapURL);
if (this._absoluteSources.has(sourceAsSourceRootRelative)) {
const index = this._absoluteSources.indexOf(sourceAsSourceRootRelative);
this._sourceLookupCache.set(aSource, index);
return index;
}
// To avoid this cache growing forever, we do not cache lookup misses.
return -1;
}
|
Utility function to find the index of a source. Returns -1 if not
found.
|
_findSourceIndex
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
static fromSourceMap(aSourceMap, aSourceMapURL) {
return new BasicSourceMapConsumer(aSourceMap.toString());
}
|
Create a BasicSourceMapConsumer from a SourceMapGenerator.
@param SourceMapGenerator aSourceMap
The source map that will be consumed.
@param String aSourceMapURL
The URL at which the source map can be found (optional)
@returns BasicSourceMapConsumer
|
fromSourceMap
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
get sources() {
return this._absoluteSources.toArray();
}
|
Create a BasicSourceMapConsumer from a SourceMapGenerator.
@param SourceMapGenerator aSourceMap
The source map that will be consumed.
@param String aSourceMapURL
The URL at which the source map can be found (optional)
@returns BasicSourceMapConsumer
|
sources
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
_getMappingsPtr() {
if (this._mappingsPtr === 0) {
this._parseMappings();
}
return this._mappingsPtr;
}
|
Create a BasicSourceMapConsumer from a SourceMapGenerator.
@param SourceMapGenerator aSourceMap
The source map that will be consumed.
@param String aSourceMapURL
The URL at which the source map can be found (optional)
@returns BasicSourceMapConsumer
|
_getMappingsPtr
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
_parseMappings() {
const aStr = this._mappings;
const size = aStr.length;
const mappingsBufPtr = this._wasm.exports.allocate_mappings(size);
const mappingsBuf = new Uint8Array(this._wasm.exports.memory.buffer, mappingsBufPtr, size);
for (let i = 0; i < size; i++) {
mappingsBuf[i] = aStr.charCodeAt(i);
}
const mappingsPtr = this._wasm.exports.parse_mappings(mappingsBufPtr);
if (!mappingsPtr) {
const error = this._wasm.exports.get_last_error();
let msg = `Error parsing mappings (code ${error}): `;
// XXX: keep these error codes in sync with `fitzgen/source-map-mappings`.
switch (error) {
case 1:
msg += "the mappings contained a negative line, column, source index, or name index";
break;
case 2:
msg += "the mappings contained a number larger than 2**32";
break;
case 3:
msg += "reached EOF while in the middle of parsing a VLQ";
break;
case 4:
msg += "invalid base 64 character while parsing a VLQ";
break;
default:
msg += "unknown error code";
break;
}
throw new Error(msg);
}
this._mappingsPtr = mappingsPtr;
}
|
Parse the mappings in a string in to a data structure which we can easily
query (the ordered arrays in the `this.__generatedMappings` and
`this.__originalMappings` properties).
|
_parseMappings
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
eachMapping(aCallback, aContext, aOrder) {
const context = aContext || null;
const order = aOrder || SourceMapConsumer.GENERATED_ORDER;
this._wasm.withMappingCallback(
mapping => {
if (mapping.source !== null) {
mapping.source = this._absoluteSources.at(mapping.source);
if (mapping.name !== null) {
mapping.name = this._names.at(mapping.name);
}
}
if (this._computedColumnSpans && mapping.lastGeneratedColumn === null) {
mapping.lastGeneratedColumn = Infinity;
}
aCallback.call(context, mapping);
},
() => {
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
this._wasm.exports.by_generated_location(this._getMappingsPtr());
break;
case SourceMapConsumer.ORIGINAL_ORDER:
this._wasm.exports.by_original_location(this._getMappingsPtr());
break;
default:
throw new Error("Unknown order of iteration.");
}
}
);
}
|
Parse the mappings in a string in to a data structure which we can easily
query (the ordered arrays in the `this.__generatedMappings` and
`this.__originalMappings` properties).
|
eachMapping
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
allGeneratedPositionsFor(aArgs) {
let source = util.getArg(aArgs, "source");
const originalLine = util.getArg(aArgs, "line");
const originalColumn = aArgs.column || 0;
source = this._findSourceIndex(source);
if (source < 0) {
return [];
}
if (originalLine < 1) {
throw new Error("Line numbers must be >= 1");
}
if (originalColumn < 0) {
throw new Error("Column numbers must be >= 0");
}
const mappings = [];
this._wasm.withMappingCallback(
m => {
let lastColumn = m.lastGeneratedColumn;
if (this._computedColumnSpans && lastColumn === null) {
lastColumn = Infinity;
}
mappings.push({
line: m.generatedLine,
column: m.generatedColumn,
lastColumn,
});
}, () => {
this._wasm.exports.all_generated_locations_for(
this._getMappingsPtr(),
source,
originalLine - 1,
"column" in aArgs,
originalColumn
);
}
);
return mappings;
}
|
Parse the mappings in a string in to a data structure which we can easily
query (the ordered arrays in the `this.__generatedMappings` and
`this.__originalMappings` properties).
|
allGeneratedPositionsFor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
destroy() {
if (this._mappingsPtr !== 0) {
this._wasm.exports.free_mappings(this._mappingsPtr);
this._mappingsPtr = 0;
}
}
|
Parse the mappings in a string in to a data structure which we can easily
query (the ordered arrays in the `this.__generatedMappings` and
`this.__originalMappings` properties).
|
destroy
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
computeColumnSpans() {
if (this._computedColumnSpans) {
return;
}
this._wasm.exports.compute_column_spans(this._getMappingsPtr());
this._computedColumnSpans = true;
}
|
Compute the last column for each generated mapping. The last column is
inclusive.
|
computeColumnSpans
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
originalPositionFor(aArgs) {
const needle = {
generatedLine: util.getArg(aArgs, "line"),
generatedColumn: util.getArg(aArgs, "column")
};
if (needle.generatedLine < 1) {
throw new Error("Line numbers must be >= 1");
}
if (needle.generatedColumn < 0) {
throw new Error("Column numbers must be >= 0");
}
let bias = util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND);
if (bias == null) {
bias = SourceMapConsumer.GREATEST_LOWER_BOUND;
}
let mapping;
this._wasm.withMappingCallback(m => mapping = m, () => {
this._wasm.exports.original_location_for(
this._getMappingsPtr(),
needle.generatedLine - 1,
needle.generatedColumn,
bias
);
});
if (mapping) {
if (mapping.generatedLine === needle.generatedLine) {
let source = util.getArg(mapping, "source", null);
if (source !== null) {
source = this._absoluteSources.at(source);
}
let name = util.getArg(mapping, "name", null);
if (name !== null) {
name = this._names.at(name);
}
return {
source,
line: util.getArg(mapping, "originalLine", null),
column: util.getArg(mapping, "originalColumn", null),
name
};
}
}
return {
source: null,
line: null,
column: null,
name: null
};
}
|
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. The line number
is 1-based.
- column: The column number in the generated source. The column
number is 0-based.
- bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
closest element that is smaller than or greater than the one we are
searching for, respectively, if the exact element cannot be found.
Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
and an object is returned with the following properties:
- source: The original source file, or null.
- line: The line number in the original source, or null. The
line number is 1-based.
- column: The column number in the original source, or null. The
column number is 0-based.
- name: The original identifier, or null.
|
originalPositionFor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
hasContentsOfAllSources() {
if (!this.sourcesContent) {
return false;
}
return this.sourcesContent.length >= this._sources.size() &&
!this.sourcesContent.some(function(sc) { return sc == null; });
}
|
Return true if we have the source content for every source in the source
map, false otherwise.
|
hasContentsOfAllSources
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
sourceContentFor(aSource, nullOnMissing) {
if (!this.sourcesContent) {
return null;
}
const index = this._findSourceIndex(aSource);
if (index >= 0) {
return this.sourcesContent[index];
}
// This function is used recursively from
// IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
// don't want to throw if we can't find the source - we just want to
// return null, so we provide a flag to exit gracefully.
if (nullOnMissing) {
return null;
}
throw new Error('"' + aSource + '" is not in the SourceMap.');
}
|
Returns the original source content. The only argument is the url of the
original source file. Returns null if no original source content is
available.
|
sourceContentFor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
generatedPositionFor(aArgs) {
let source = util.getArg(aArgs, "source");
source = this._findSourceIndex(source);
if (source < 0) {
return {
line: null,
column: null,
lastColumn: null
};
}
const needle = {
source,
originalLine: util.getArg(aArgs, "line"),
originalColumn: util.getArg(aArgs, "column")
};
if (needle.originalLine < 1) {
throw new Error("Line numbers must be >= 1");
}
if (needle.originalColumn < 0) {
throw new Error("Column numbers must be >= 0");
}
let bias = util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND);
if (bias == null) {
bias = SourceMapConsumer.GREATEST_LOWER_BOUND;
}
let mapping;
this._wasm.withMappingCallback(m => mapping = m, () => {
this._wasm.exports.generated_location_for(
this._getMappingsPtr(),
needle.source,
needle.originalLine - 1,
needle.originalColumn,
bias
);
});
if (mapping) {
if (mapping.source === needle.source) {
let lastColumn = mapping.lastGeneratedColumn;
if (this._computedColumnSpans && lastColumn === null) {
lastColumn = Infinity;
}
return {
line: util.getArg(mapping, "generatedLine", null),
column: util.getArg(mapping, "generatedColumn", null),
lastColumn,
};
}
}
return {
line: null,
column: null,
lastColumn: null
};
}
|
Returns the generated line and column information for the original source,
line, and column positions provided. The only argument is an object with
the following properties:
- source: The filename of the original source.
- line: The line number in the original source. The line number
is 1-based.
- column: The column number in the original source. The column
number is 0-based.
- bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
closest element that is smaller than or greater than the one we are
searching for, respectively, if the exact element cannot be found.
Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
and an object is returned with the following properties:
- 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.
|
generatedPositionFor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
originalPositionFor(aArgs) {
const needle = {
generatedLine: util.getArg(aArgs, "line"),
generatedColumn: util.getArg(aArgs, "column")
};
// Find the section containing the generated position we're trying to map
// to an original position.
const sectionIndex = binarySearch.search(needle, this._sections,
function(aNeedle, section) {
const cmp = aNeedle.generatedLine - section.generatedOffset.generatedLine;
if (cmp) {
return cmp;
}
return (aNeedle.generatedColumn -
section.generatedOffset.generatedColumn);
});
const section = this._sections[sectionIndex];
if (!section) {
return {
source: null,
line: null,
column: null,
name: null
};
}
return section.consumer.originalPositionFor({
line: needle.generatedLine -
(section.generatedOffset.generatedLine - 1),
column: needle.generatedColumn -
(section.generatedOffset.generatedLine === needle.generatedLine
? section.generatedOffset.generatedColumn - 1
: 0),
bias: aArgs.bias
});
}
|
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. The line number
is 1-based.
- column: The column number in the generated source. The column
number is 0-based.
and an object is returned with the following properties:
- source: The original source file, or null.
- line: The line number in the original source, or null. The
line number is 1-based.
- column: The column number in the original source, or null. The
column number is 0-based.
- name: The original identifier, or null.
|
originalPositionFor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
hasContentsOfAllSources() {
return this._sections.every(function(s) {
return s.consumer.hasContentsOfAllSources();
});
}
|
Return true if we have the source content for every source in the source
map, false otherwise.
|
hasContentsOfAllSources
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
sourceContentFor(aSource, nullOnMissing) {
for (let i = 0; i < this._sections.length; i++) {
const section = this._sections[i];
const content = section.consumer.sourceContentFor(aSource, true);
if (content) {
return content;
}
}
if (nullOnMissing) {
return null;
}
throw new Error('"' + aSource + '" is not in the SourceMap.');
}
|
Returns the original source content. The only argument is the url of the
original source file. Returns null if no original source content is
available.
|
sourceContentFor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
_findSectionIndex(source) {
for (let i = 0; i < this._sections.length; i++) {
const { consumer } = this._sections[i];
if (consumer._findSourceIndex(source) !== -1) {
return i;
}
}
return -1;
}
|
Returns the original source content. The only argument is the url of the
original source file. Returns null if no original source content is
available.
|
_findSectionIndex
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
generatedPositionFor(aArgs) {
const index = this._findSectionIndex(util.getArg(aArgs, "source"));
const section = index >= 0 ? this._sections[index] : null;
const nextSection =
index >= 0 && index + 1 < this._sections.length
? this._sections[index + 1]
: null;
const generatedPosition =
section && section.consumer.generatedPositionFor(aArgs);
if (generatedPosition && generatedPosition.line !== null) {
const lineShift = section.generatedOffset.generatedLine - 1;
const columnShift = section.generatedOffset.generatedColumn - 1;
if (generatedPosition.line === 1) {
generatedPosition.column += columnShift;
if (typeof generatedPosition.lastColumn === "number") {
generatedPosition.lastColumn += columnShift;
}
}
if (
generatedPosition.lastColumn === Infinity &&
nextSection &&
generatedPosition.line === nextSection.generatedOffset.generatedLine
) {
generatedPosition.lastColumn =
nextSection.generatedOffset.generatedColumn - 2;
}
generatedPosition.line += lineShift;
return generatedPosition;
}
return {
line: null,
column: null,
lastColumn: null
};
}
|
Returns the generated line and column information for the original source,
line, and column positions provided. The only argument is an object with
the following properties:
- source: The filename of the original source.
- line: The line number in the original source. The line number
is 1-based.
- column: The column number in the original source. The column
number is 0-based.
and an object is returned with the following properties:
- line: The line number in the generated source, or null. The
line number is 1-based.
- column: The column number in the generated source, or null.
The column number is 0-based.
|
generatedPositionFor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
allGeneratedPositionsFor(aArgs) {
const index = this._findSectionIndex(util.getArg(aArgs, "source"));
const section = index >= 0 ? this._sections[index] : null;
const nextSection =
index >= 0 && index + 1 < this._sections.length
? this._sections[index + 1]
: null;
if (!section) return [];
return section.consumer.allGeneratedPositionsFor(aArgs).map(
generatedPosition => {
const lineShift = section.generatedOffset.generatedLine - 1;
const columnShift = section.generatedOffset.generatedColumn - 1;
if (generatedPosition.line === 1) {
generatedPosition.column += columnShift;
if (typeof generatedPosition.lastColumn === "number") {
generatedPosition.lastColumn += columnShift;
}
}
if (
generatedPosition.lastColumn === Infinity &&
nextSection &&
generatedPosition.line === nextSection.generatedOffset.generatedLine
) {
generatedPosition.lastColumn =
nextSection.generatedOffset.generatedColumn - 2;
}
generatedPosition.line += lineShift;
return generatedPosition;
}
);
}
|
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.
|
allGeneratedPositionsFor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
eachMapping(aCallback, aContext, aOrder) {
this._sections.forEach((section, index) => {
const nextSection =
index + 1 < this._sections.length
? this._sections[index + 1]
: null;
const { generatedOffset } = section;
const lineShift = generatedOffset.generatedLine - 1;
const columnShift = generatedOffset.generatedColumn - 1;
section.consumer.eachMapping(function(mapping) {
if (mapping.generatedLine === 1) {
mapping.generatedColumn += columnShift;
if (typeof mapping.lastGeneratedColumn === "number") {
mapping.lastGeneratedColumn += columnShift;
}
}
if (
mapping.lastGeneratedColumn === Infinity &&
nextSection &&
mapping.generatedLine === nextSection.generatedOffset.generatedLine
) {
mapping.lastGeneratedColumn =
nextSection.generatedOffset.generatedColumn - 2;
}
mapping.generatedLine += lineShift;
aCallback.call(this, mapping);
}, aContext, aOrder);
});
}
|
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.
|
eachMapping
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
computeColumnSpans() {
for (let i = 0; i < this._sections.length; i++) {
this._sections[i].consumer.computeColumnSpans();
}
}
|
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.
|
computeColumnSpans
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
destroy() {
for (let i = 0; i < this._sections.length; i++) {
this._sections[i].consumer.destroy();
}
}
|
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.
|
destroy
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function _factory(aSourceMap, aSourceMapURL) {
let sourceMap = aSourceMap;
if (typeof aSourceMap === "string") {
sourceMap = util.parseSourceMapInput(aSourceMap);
}
const consumer = sourceMap.sections != null
? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
: new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
return Promise.resolve(consumer);
}
|
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.
|
_factory
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function _factoryBSM(aSourceMap, aSourceMapURL) {
return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
}
|
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.
|
_factoryBSM
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
constructor(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util.getArg(aArgs, "file", null);
this._sourceRoot = util.getArg(aArgs, "sourceRoot", null);
this._skipValidation = util.getArg(aArgs, "skipValidation", false);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
this._sourcesContents = null;
}
|
An instance of the SourceMapGenerator represents a source map which is
being built incrementally. You may pass an object with the following
properties:
- file: The filename of the generated source.
- sourceRoot: A root for all relative URLs in this source map.
|
constructor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
static fromSourceMap(aSourceMapConsumer) {
const sourceRoot = aSourceMapConsumer.sourceRoot;
const generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot
});
aSourceMapConsumer.eachMapping(function(mapping) {
const 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.name != null) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function(sourceFile) {
let sourceRelative = sourceFile;
if (sourceRoot !== null) {
sourceRelative = util.relative(sourceRoot, sourceFile);
}
if (!generator._sources.has(sourceRelative)) {
generator._sources.add(sourceRelative);
}
const content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
}
|
Creates a new SourceMapGenerator based on a SourceMapConsumer
@param aSourceMapConsumer The SourceMap.
|
fromSourceMap
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
addMapping(aArgs) {
const generated = util.getArg(aArgs, "generated");
const original = util.getArg(aArgs, "original", null);
let source = util.getArg(aArgs, "source", null);
let name = util.getArg(aArgs, "name", null);
if (!this._skipValidation) {
this._validateMapping(generated, original, source, name);
}
if (source != null) {
source = String(source);
if (!this._sources.has(source)) {
this._sources.add(source);
}
}
if (name != null) {
name = String(name);
if (!this._names.has(name)) {
this._names.add(name);
}
}
this._mappings.add({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source,
name
});
}
|
Add a single mapping from original source line and column to the generated
source's line and column for this source map being created. The mapping
object should have the following properties:
- generated: An object with the generated line and column positions.
- original: An object with the original line and column positions.
- source: The original source file (relative to the sourceRoot).
- name: An optional original token name for this mapping.
|
addMapping
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
setSourceContent(aSourceFile, aSourceContent) {
let source = aSourceFile;
if (this._sourceRoot != null) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent != null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = Object.create(null);
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else if (this._sourcesContents) {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
}
|
Set the source content for a source file.
|
setSourceContent
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
_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") {
throw new Error(
"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 (aGenerated && "line" in aGenerated && "column" in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
} 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.
} else {
throw new Error("Invalid mapping: " + JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName
}));
}
}
|
A mapping can have one of the three levels of data:
1. Just the generated position.
2. The Generated position, original position, and original source.
3. Generated and original position, original source, as well as a name
token.
To maintain consistency, we validate that any new mapping being added falls
in to one of these categories.
|
_validateMapping
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
_serializeMappings() {
let previousGeneratedColumn = 0;
let previousGeneratedLine = 1;
let previousOriginalColumn = 0;
let previousOriginalLine = 0;
let previousName = 0;
let previousSource = 0;
let result = "";
let next;
let mapping;
let nameIdx;
let sourceIdx;
const mappings = this._mappings.toArray();
for (let i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
next = "";
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
next += ";";
previousGeneratedLine++;
}
} else if (i > 0) {
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
continue;
}
next += ",";
}
next += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source != null) {
sourceIdx = this._sources.indexOf(mapping.source);
next += base64VLQ.encode(sourceIdx - previousSource);
previousSource = sourceIdx;
// lines are stored 0-based in SourceMap spec version 3
next += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
next += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name != null) {
nameIdx = this._names.indexOf(mapping.name);
next += base64VLQ.encode(nameIdx - previousName);
previousName = nameIdx;
}
}
result += next;
}
return result;
}
|
Serialize the accumulated mappings in to the stream of base 64 VLQs
specified by the source map format.
|
_serializeMappings
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function(source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot != null) {
source = util.relative(aSourceRoot, source);
}
const key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
? this._sourcesContents[key]
: null;
}, this);
}
|
Serialize the accumulated mappings in to the stream of base 64 VLQs
specified by the source map format.
|
_generateSourcesContent
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
toString() {
return JSON.stringify(this.toJSON());
}
|
Render the source map being generated to a string.
|
toString
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
constructor(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine == null ? null : aLine;
this.column = aColumn == null ? null : aColumn;
this.source = aSource == null ? null : aSource;
this.name = aName == null ? null : aName;
this[isSourceNode] = true;
if (aChunks != null) this.add(aChunks);
}
|
SourceNodes provide a way to abstract over interpolating/concatenating
snippets of generated JavaScript source code while maintaining the line and
column information associated with the original source code.
@param aLine The original line number.
@param aColumn The original column number.
@param aSource The original source's filename.
@param aChunks Optional. An array of strings which are snippets of
generated JS, or other SourceNodes.
@param aName The original identifier.
|
constructor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
static fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
const node = new SourceNode();
// All even indices of this array are one line of the generated code,
// while all odd indices are the newlines between two adjacent lines
// (since `REGEX_NEWLINE` captures its match).
// Processed fragments are accessed by calling `shiftNextLine`.
const remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
let remainingLinesIndex = 0;
const shiftNextLine = function() {
const lineContents = getNextLine();
// The last line of a file might not have a newline.
const newLine = getNextLine() || "";
return lineContents + newLine;
function getNextLine() {
return remainingLinesIndex < remainingLines.length ?
remainingLines[remainingLinesIndex++] : undefined;
}
};
// We need to remember the position of "remainingLines"
let lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
let lastMapping = null;
let nextLine;
aSourceMapConsumer.eachMapping(function(mapping) {
if (lastMapping !== null) {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
// Associate first line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
lastGeneratedLine++;
lastGeneratedColumn = 0;
// The remaining code is added without mapping
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
nextLine = remainingLines[remainingLinesIndex] || "";
const 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
lastMapping = mapping;
return;
}
}
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(shiftNextLine());
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
nextLine = remainingLines[remainingLinesIndex] || "";
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
if (remainingLinesIndex < remainingLines.length) {
if (lastMapping) {
// Associate the remaining code in the current line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
}
// and add the remaining lines without any mapping
node.add(remainingLines.splice(remainingLinesIndex).join(""));
}
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function(sourceFile) {
const content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aRelativePath != null) {
sourceFile = util.join(aRelativePath, sourceFile);
}
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
const source = aRelativePath
? util.join(aRelativePath, mapping.source)
: mapping.source;
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
source,
code,
mapping.name));
}
}
}
|
Creates a SourceNode from generated code and a SourceMapConsumer.
@param aGeneratedCode The generated code
@param aSourceMapConsumer The SourceMap for the generated code
@param aRelativePath Optional. The path that relative sources in the
SourceMapConsumer should be relative to.
|
fromStringWithSourceMap
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
shiftNextLine = function() {
const lineContents = getNextLine();
// The last line of a file might not have a newline.
const newLine = getNextLine() || "";
return lineContents + newLine;
function getNextLine() {
return remainingLinesIndex < remainingLines.length ?
remainingLines[remainingLinesIndex++] : undefined;
}
}
|
Creates a SourceNode from generated code and a SourceMapConsumer.
@param aGeneratedCode The generated code
@param aSourceMapConsumer The SourceMap for the generated code
@param aRelativePath Optional. The path that relative sources in the
SourceMapConsumer should be relative to.
|
shiftNextLine
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
shiftNextLine = function() {
const lineContents = getNextLine();
// The last line of a file might not have a newline.
const newLine = getNextLine() || "";
return lineContents + newLine;
function getNextLine() {
return remainingLinesIndex < remainingLines.length ?
remainingLines[remainingLinesIndex++] : undefined;
}
}
|
Creates a SourceNode from generated code and a SourceMapConsumer.
@param aGeneratedCode The generated code
@param aSourceMapConsumer The SourceMap for the generated code
@param aRelativePath Optional. The path that relative sources in the
SourceMapConsumer should be relative to.
|
shiftNextLine
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function getNextLine() {
return remainingLinesIndex < remainingLines.length ?
remainingLines[remainingLinesIndex++] : undefined;
}
|
Creates a SourceNode from generated code and a SourceMapConsumer.
@param aGeneratedCode The generated code
@param aSourceMapConsumer The SourceMap for the generated code
@param aRelativePath Optional. The path that relative sources in the
SourceMapConsumer should be relative to.
|
getNextLine
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
const source = aRelativePath
? util.join(aRelativePath, mapping.source)
: mapping.source;
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
source,
code,
mapping.name));
}
}
|
Creates a SourceNode from generated code and a SourceMapConsumer.
@param aGeneratedCode The generated code
@param aSourceMapConsumer The SourceMap for the generated code
@param aRelativePath Optional. The path that relative sources in the
SourceMapConsumer should be relative to.
|
addMappingWithCode
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function(chunk) {
this.add(chunk);
}, this);
} else if (aChunk[isSourceNode] || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
} else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
}
|
Add a chunk of generated JS to this source node.
@param aChunk A string snippet of generated JS code, another instance of
SourceNode, or an array where each member is one of those things.
|
add
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (let i = aChunk.length - 1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
} else if (aChunk[isSourceNode] || typeof aChunk === "string") {
this.children.unshift(aChunk);
} else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
}
|
Add a chunk of generated JS to the beginning of this source node.
@param aChunk A string snippet of generated JS code, another instance of
SourceNode, or an array where each member is one of those things.
|
prepend
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
walk(aFn) {
let chunk;
for (let i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk[isSourceNode]) {
chunk.walk(aFn);
} else if (chunk !== "") {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
|
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.
@param aFn The traversal function.
|
walk
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
join(aSep) {
let newChildren;
let i;
const len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len - 1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
}
|
Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
each of `this.children`.
@param aSep The separator.
|
join
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
replaceRight(aPattern, aReplacement) {
const lastChild = this.children[this.children.length - 1];
if (lastChild[isSourceNode]) {
lastChild.replaceRight(aPattern, aReplacement);
} else if (typeof lastChild === "string") {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
} else {
this.children.push("".replace(aPattern, aReplacement));
}
return this;
}
|
Call String.prototype.replace on the very right-most source snippet. Useful
for trimming whitespace from the end of a source node, etc.
@param aPattern The pattern to replace.
@param aReplacement The thing to replace the pattern with.
|
replaceRight
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
}
|
Set the source content for a source file. This will be added to the SourceMapGenerator
in the sourcesContent field.
@param aSourceFile The filename of the source file
@param aSourceContent The content of the source file
|
setSourceContent
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
walkSourceContents(aFn) {
for (let i = 0, len = this.children.length; i < len; i++) {
if (this.children[i][isSourceNode]) {
this.children[i].walkSourceContents(aFn);
}
}
const sources = Object.keys(this.sourceContents);
for (let i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
}
|
Walk over the tree of SourceNodes. The walking function is called for each
source file content and is passed the filename and source content.
@param aFn The traversal function.
|
walkSourceContents
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
toString() {
let str = "";
this.walk(function(chunk) {
str += chunk;
});
return str;
}
|
Return the string representation of this source node. Walks over the tree
and concatenates all the various snippets together to one string.
|
toString
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
toStringWithSourceMap(aArgs) {
const generated = {
code: "",
line: 1,
column: 0
};
const map = new SourceMapGenerator(aArgs);
let sourceMappingActive = false;
let lastOriginalSource = null;
let lastOriginalLine = null;
let lastOriginalColumn = null;
let 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 (let 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 };
}
|
Returns the string representation of this source node along with a source
map.
|
toStringWithSourceMap
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
}
throw new Error('"' + aName + '" is a required argument.');
}
|
This is a helper function for getting values from parameter/options
objects.
@param args The object we are extracting values from
@param name The name of the property we are getting.
@param defaultValue An optional value to return if the property is missing
from the object. If this is not specified and the property is missing, an
error will be thrown.
|
getArg
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function identity(s) {
return s;
}
|
This is a helper function for getting values from parameter/options
objects.
@param args The object we are extracting values from
@param name The name of the property we are getting.
@param defaultValue An optional value to return if the property is missing
from the object. If this is not specified and the property is missing, an
error will be thrown.
|
identity
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
let cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
|
Comparator between two mappings with inflated source and name strings where
the generated positions are compared.
|
compareByGeneratedPositionsInflated
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function parseSourceMapInput(str) {
return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ""));
}
|
Strip any JSON XSSI avoidance prefix from the string (as documented
in the source maps specification), and then parse the string as
JSON.
|
parseSourceMapInput
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function createSafeHandler(cb) {
return input => {
const type = getURLType(input);
const base = buildSafeBase(input);
const url = new URL(input, base);
cb(url);
const result = url.toString();
if (type === "absolute") {
return result;
} else if (type === "scheme-relative") {
return result.slice(PROTOCOL.length);
} else if (type === "path-absolute") {
return result.slice(PROTOCOL_AND_HOST.length);
}
// This assumes that the callback will only change
// the path, search and hash values.
return computeRelativeURL(base, result);
};
}
|
Make it easy to create small utilities that tweak a URL's path.
|
createSafeHandler
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function withBase(url, base) {
return new URL(url, base).toString();
}
|
Make it easy to create small utilities that tweak a URL's path.
|
withBase
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function buildUniqueSegment(prefix, str) {
let id = 0;
do {
const ident = prefix + (id++);
if (str.indexOf(ident) === -1) return ident;
} while (true);
}
|
Make it easy to create small utilities that tweak a URL's path.
|
buildUniqueSegment
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function buildSafeBase(str) {
const maxDotParts = str.split("..").length - 1;
// If we used a segment that also existed in `str`, then we would be unable
// to compute relative paths. For example, if `segment` were just "a":
//
// const url = "../../a/"
// const base = buildSafeBase(url); // http://host/a/a/
// const joined = "http://host/a/";
// const result = relative(base, joined);
//
// Expected: "../../a/";
// Actual: "a/"
//
const segment = buildUniqueSegment("p", str);
let base = `${PROTOCOL_AND_HOST}/`;
for (let i = 0; i < maxDotParts; i++) {
base += `${segment}/`;
}
return base;
}
|
Make it easy to create small utilities that tweak a URL's path.
|
buildSafeBase
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function getURLType(url) {
if (url[0] === "/") {
if (url[1] === "/") return "scheme-relative";
return "path-absolute";
}
return ABSOLUTE_SCHEME.test(url) ? "absolute" : "path-relative";
}
|
Make it easy to create small utilities that tweak a URL's path.
|
getURLType
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function computeRelativeURL(rootURL, targetURL) {
if (typeof rootURL === "string") rootURL = new URL(rootURL);
if (typeof targetURL === "string") targetURL = new URL(targetURL);
const targetParts = targetURL.pathname.split("/");
const rootParts = rootURL.pathname.split("/");
// If we've got a URL path ending with a "/", we remove it since we'd
// otherwise be relative to the wrong location.
if (rootParts.length > 0 && !rootParts[rootParts.length - 1]) {
rootParts.pop();
}
while (
targetParts.length > 0 &&
rootParts.length > 0 &&
targetParts[0] === rootParts[0]
) {
targetParts.shift();
rootParts.shift();
}
const relativePath = rootParts
.map(() => "..")
.concat(targetParts)
.join("/");
return relativePath + targetURL.search + targetURL.hash;
}
|
Given two URLs that are assumed to be on the same
protocol/host/user/password build a relative URL from the
path, params, and hash values.
@param rootURL The root URL that the target will be relative to.
@param targetURL The target that the relative URL points to.
@return A rootURL-relative, normalized URL value.
|
computeRelativeURL
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function join(aRoot, aPath) {
const pathType = getURLType(aPath);
const rootType = getURLType(aRoot);
aRoot = ensureDirectory(aRoot);
if (pathType === "absolute") {
return withBase(aPath, undefined);
}
if (rootType === "absolute") {
return withBase(aPath, aRoot);
}
if (pathType === "scheme-relative") {
return normalize(aPath);
}
if (rootType === "scheme-relative") {
return withBase(aPath, withBase(aRoot, PROTOCOL_AND_HOST)).slice(PROTOCOL.length);
}
if (pathType === "path-absolute") {
return normalize(aPath);
}
if (rootType === "path-absolute") {
return withBase(aPath, withBase(aRoot, PROTOCOL_AND_HOST)).slice(PROTOCOL_AND_HOST.length);
}
const base = buildSafeBase(aPath + aRoot);
const newPath = withBase(aPath, withBase(aRoot, base));
return computeRelativeURL(base, newPath);
}
|
Joins two paths/URLs.
All returned URLs will be normalized.
@param aRoot The root path or URL. Assumed to reference a directory.
@param aPath The path or URL to be joined with the root.
@return A joined and normalized URL value.
|
join
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function relative(rootURL, targetURL) {
const result = relativeIfPossible(rootURL, targetURL);
return typeof result === "string" ? result : normalize(targetURL);
}
|
Make a path relative to a URL or another path. If returning a
relative URL is not possible, the original target will be returned.
All returned URLs will be normalized.
@param aRoot The root path or URL.
@param aPath The path or URL to be made relative to aRoot.
@return A rootURL-relative (if possible), normalized URL value.
|
relative
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function relativeIfPossible(rootURL, targetURL) {
const urlType = getURLType(rootURL);
if (urlType !== getURLType(targetURL)) {
return null;
}
const base = buildSafeBase(rootURL + targetURL);
const root = new URL(rootURL, base);
const target = new URL(targetURL, base);
try {
new URL("", target.toString());
} catch (err) {
// Bail if the URL doesn't support things being relative to it,
// For example, data: and blob: URLs.
return null;
}
if (
target.protocol !== root.protocol ||
target.user !== root.user ||
target.password !== root.password ||
target.hostname !== root.hostname ||
target.port !== root.port
) {
return null;
}
return computeRelativeURL(root, target);
}
|
Make a path relative to a URL or another path. If returning a
relative URL is not possible, the original target will be returned.
All returned URLs will be normalized.
@param aRoot The root path or URL.
@param aPath The path or URL to be made relative to aRoot.
@return A rootURL-relative (if possible), normalized URL value.
|
relativeIfPossible
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
// The source map spec states that "sourceRoot" and "sources" entries are to be appended. While
// that is a little vague, implementations have generally interpreted that as joining the
// URLs with a `/` between then, assuming the "sourceRoot" doesn't already end with one.
// For example,
//
// sourceRoot: "some-dir",
// sources: ["/some-path.js"]
//
// and
//
// sourceRoot: "some-dir/",
// sources: ["/some-path.js"]
//
// must behave as "some-dir/some-path.js".
//
// With this library's the transition to a more URL-focused implementation, that behavior is
// preserved here. To acheive that, we trim the "/" from absolute-path when a sourceRoot value
// is present in order to make the sources entries behave as if they are relative to the
// "sourceRoot", as they would have if the two strings were simply concated.
if (sourceRoot && getURLType(sourceURL) === "path-absolute") {
sourceURL = sourceURL.replace(/^\//, "");
}
let url = normalize(sourceURL || "");
// Parsing URLs can be expensive, so we only perform these joins when needed.
if (sourceRoot) url = join(sourceRoot, url);
if (sourceMapURL) url = join(trimFilename(sourceMapURL), url);
return url;
}
|
Compute the URL of a source given the the source root, the source's
URL, and the source map's URL.
|
computeSourceURL
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function Mapping() {
this.generatedLine = 0;
this.generatedColumn = 0;
this.lastGeneratedColumn = null;
this.source = null;
this.originalLine = null;
this.originalColumn = null;
this.name = null;
}
|
Provide the JIT with a nice shape / hidden class.
|
Mapping
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
mapping_callback(
generatedLine,
generatedColumn,
hasLastGeneratedColumn,
lastGeneratedColumn,
hasOriginal,
source,
originalLine,
originalColumn,
hasName,
name
) {
const mapping = new Mapping();
// JS uses 1-based line numbers, wasm uses 0-based.
mapping.generatedLine = generatedLine + 1;
mapping.generatedColumn = generatedColumn;
if (hasLastGeneratedColumn) {
// JS uses inclusive last generated column, wasm uses exclusive.
mapping.lastGeneratedColumn = lastGeneratedColumn - 1;
}
if (hasOriginal) {
mapping.source = source;
// JS uses 1-based line numbers, wasm uses 0-based.
mapping.originalLine = originalLine + 1;
mapping.originalColumn = originalColumn;
if (hasName) {
mapping.name = name;
}
}
callbackStack[callbackStack.length - 1](mapping);
}
|
Provide the JIT with a nice shape / hidden class.
|
mapping_callback
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
constructor(options = {}) {
this.options = {
shouldIgnorePath: options.shouldIgnorePath ?? defaultShouldIgnorePath,
isSourceMapAsset: options.isSourceMapAsset ?? defaultIsSourceMapAsset,
}
}
|
This plugin adds a field to source maps that identifies which sources are
vendored or runtime-injected (aka third-party) sources. These are consumed by
Chrome DevTools to automatically ignore-list sources.
|
constructor
|
javascript
|
vercel/next.js
|
packages/next/webpack-plugins/devtools-ignore-list-plugin.js
|
https://github.com/vercel/next.js/blob/master/packages/next/webpack-plugins/devtools-ignore-list-plugin.js
|
MIT
|
apply(compiler) {
const { RawSource } = compiler.webpack.sources
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,
additionalAssets: true,
},
(assets) => {
for (const [name, asset] of Object.entries(assets)) {
// Instead of using `asset.map()` to fetch the source maps from
// SourceMapSource assets, process them directly as a RawSource.
// This is because `.map()` is slow and can take several seconds.
if (!this.options.isSourceMapAsset(name)) {
// Ignore non source map files.
continue
}
const mapContent = asset.source().toString()
if (!mapContent) {
continue
}
const sourcemap = JSON.parse(mapContent)
const ignoreList = []
for (const [index, path] of sourcemap.sources.entries()) {
if (this.options.shouldIgnorePath(path)) {
ignoreList.push(index)
}
}
sourcemap[IGNORE_LIST] = ignoreList
compilation.updateAsset(
name,
new RawSource(JSON.stringify(sourcemap))
)
}
}
)
})
}
|
This plugin adds a field to source maps that identifies which sources are
vendored or runtime-injected (aka third-party) sources. These are consumed by
Chrome DevTools to automatically ignore-list sources.
|
apply
|
javascript
|
vercel/next.js
|
packages/next/webpack-plugins/devtools-ignore-list-plugin.js
|
https://github.com/vercel/next.js/blob/master/packages/next/webpack-plugins/devtools-ignore-list-plugin.js
|
MIT
|
function loader(value, bindings, callback) {
const defaults = this.sourceMap ? { SourceMapGenerator } : {}
const options = this.getOptions()
const config = { ...defaults, ...options }
const hash = getOptionsHash(options)
const compiler = this._compiler || marker
let map = cache.get(compiler)
if (!map) {
map = new Map()
cache.set(compiler, map)
}
let process = map.get(hash)
if (!process) {
process = createFormatAwareProcessors(
bindings,
coereceMdxTransformOptions(config)
).compile
map.set(hash, process)
}
process({ value, path: this.resourcePath }).then(
(code) => {
// TODO: no sourcemap
callback(null, code, null)
},
(error) => {
const fpath = path.relative(this.context, this.resourcePath)
error.message = `${fpath}:${error.name}: ${error.message}`
callback(error)
}
)
}
|
A webpack loader for mdx-rs. This is largely based on existing @mdx-js/loader,
replaces internal compilation logic to use mdx-rs instead.
|
loader
|
javascript
|
vercel/next.js
|
packages/next-mdx/mdx-rs-loader.js
|
https://github.com/vercel/next.js/blob/master/packages/next-mdx/mdx-rs-loader.js
|
MIT
|
function getOptionsHash(options) {
const hash = createHash('sha256')
let key
for (key in options) {
if (own.call(options, key)) {
const value = options[key]
if (value !== undefined) {
const valueString = JSON.stringify(value)
hash.update(key + valueString)
}
}
}
return hash.digest('hex').slice(0, 16)
}
|
A webpack loader for mdx-rs. This is largely based on existing @mdx-js/loader,
replaces internal compilation logic to use mdx-rs instead.
|
getOptionsHash
|
javascript
|
vercel/next.js
|
packages/next-mdx/mdx-rs-loader.js
|
https://github.com/vercel/next.js/blob/master/packages/next-mdx/mdx-rs-loader.js
|
MIT
|
function createFormatAwareProcessors(bindings, compileOptions = {}) {
const mdExtensions = compileOptions.mdExtensions || md
const mdxExtensions = compileOptions.mdxExtensions || mdx
let cachedMarkdown
let cachedMdx
return {
extnames:
compileOptions.format === 'md'
? mdExtensions
: compileOptions.format === 'mdx'
? mdxExtensions
: mdExtensions.concat(mdxExtensions),
compile,
}
function compile({ value, path: p }) {
const format =
compileOptions.format === 'md' || compileOptions.format === 'mdx'
? compileOptions.format
: path.extname(p) &&
(compileOptions.mdExtensions || md).includes(path.extname(p))
? 'md'
: 'mdx'
const options = {
parse: compileOptions.parse,
development: compileOptions.development,
providerImportSource: compileOptions.providerImportSource,
jsx: compileOptions.jsx,
jsxRuntime: compileOptions.jsxRuntime,
jsxImportSource: compileOptions.jsxImportSource,
pragma: compileOptions.pragma,
pragmaFrag: compileOptions.pragmaFrag,
pragmaImportSource: compileOptions.pragmaImportSource,
filepath: p,
}
const compileMdx = (input) => bindings.mdx.compile(input, options)
const processor =
format === 'md'
? cachedMarkdown || (cachedMarkdown = compileMdx)
: cachedMdx || (cachedMdx = compileMdx)
return processor(value)
}
}
|
A webpack loader for mdx-rs. This is largely based on existing @mdx-js/loader,
replaces internal compilation logic to use mdx-rs instead.
|
createFormatAwareProcessors
|
javascript
|
vercel/next.js
|
packages/next-mdx/mdx-rs-loader.js
|
https://github.com/vercel/next.js/blob/master/packages/next-mdx/mdx-rs-loader.js
|
MIT
|
function compile({ value, path: p }) {
const format =
compileOptions.format === 'md' || compileOptions.format === 'mdx'
? compileOptions.format
: path.extname(p) &&
(compileOptions.mdExtensions || md).includes(path.extname(p))
? 'md'
: 'mdx'
const options = {
parse: compileOptions.parse,
development: compileOptions.development,
providerImportSource: compileOptions.providerImportSource,
jsx: compileOptions.jsx,
jsxRuntime: compileOptions.jsxRuntime,
jsxImportSource: compileOptions.jsxImportSource,
pragma: compileOptions.pragma,
pragmaFrag: compileOptions.pragmaFrag,
pragmaImportSource: compileOptions.pragmaImportSource,
filepath: p,
}
const compileMdx = (input) => bindings.mdx.compile(input, options)
const processor =
format === 'md'
? cachedMarkdown || (cachedMarkdown = compileMdx)
: cachedMdx || (cachedMdx = compileMdx)
return processor(value)
}
|
A webpack loader for mdx-rs. This is largely based on existing @mdx-js/loader,
replaces internal compilation logic to use mdx-rs instead.
|
compile
|
javascript
|
vercel/next.js
|
packages/next-mdx/mdx-rs-loader.js
|
https://github.com/vercel/next.js/blob/master/packages/next-mdx/mdx-rs-loader.js
|
MIT
|
async function getSchedulerVersion(reactVersion) {
const url = `https://registry.npmjs.org/react-dom/${reactVersion}`
const response = await fetch(url, {
headers: {
Accept: 'application/json',
},
})
if (!response.ok) {
throw new Error(
`${url}: ${response.status} ${response.statusText}\n${await response.text()}`
)
}
const manifest = await response.json()
return manifest.dependencies['scheduler']
}
|
Set to `null` to automatically sync the React version of Pages Router with App Router React version.
Set to a specific version to override the Pages Router React version e.g. `^19.0.0`.
"Active" just refers to our current development practice. While we do support
React 18 in pages router, we don't focus our development process on it considering
it does not receive new features.
@type {string | null}
|
getSchedulerVersion
|
javascript
|
vercel/next.js
|
scripts/sync-react.js
|
https://github.com/vercel/next.js/blob/master/scripts/sync-react.js
|
MIT
|
async function sync({ channel, newVersionStr, noInstall }) {
const useExperimental = channel === 'experimental'
const cwd = process.cwd()
const pkgJson = JSON.parse(
await fsp.readFile(path.join(cwd, 'package.json'), 'utf-8')
)
const devDependencies = pkgJson.devDependencies
const pnpmOverrides = pkgJson.pnpm.overrides
const baseVersionStr = devDependencies[
useExperimental ? 'react-experimental-builtin' : 'react-builtin'
].replace(/^npm:react@/, '')
console.log(`Updating "react@${channel}" to ${newVersionStr}...`)
if (newVersionStr === baseVersionStr) {
console.log('Already up to date.')
return
}
const baseSchedulerVersionStr = devDependencies[
useExperimental ? 'scheduler-experimental-builtin' : 'scheduler-builtin'
].replace(/^npm:scheduler@/, '')
const newSchedulerVersionStr = await getSchedulerVersion(newVersionStr)
console.log(`Updating "scheduler@${channel}" to ${newSchedulerVersionStr}...`)
for (const [dep, version] of Object.entries(devDependencies)) {
if (version.endsWith(baseVersionStr)) {
devDependencies[dep] = version.replace(baseVersionStr, newVersionStr)
} else if (version.endsWith(baseSchedulerVersionStr)) {
devDependencies[dep] = version.replace(
baseSchedulerVersionStr,
newSchedulerVersionStr
)
}
}
for (const [dep, version] of Object.entries(pnpmOverrides)) {
if (version.endsWith(baseVersionStr)) {
pnpmOverrides[dep] = version.replace(baseVersionStr, newVersionStr)
} else if (version.endsWith(baseSchedulerVersionStr)) {
pnpmOverrides[dep] = version.replace(
baseSchedulerVersionStr,
newSchedulerVersionStr
)
}
}
await fsp.writeFile(
path.join(cwd, 'package.json'),
JSON.stringify(pkgJson, null, 2) +
// Prettier would add a newline anyway so do it manually to skip the additional `pnpm prettier-write`
'\n'
)
}
|
Set to `null` to automatically sync the React version of Pages Router with App Router React version.
Set to a specific version to override the Pages Router React version e.g. `^19.0.0`.
"Active" just refers to our current development practice. While we do support
React 18 in pages router, we don't focus our development process on it considering
it does not receive new features.
@type {string | null}
|
sync
|
javascript
|
vercel/next.js
|
scripts/sync-react.js
|
https://github.com/vercel/next.js/blob/master/scripts/sync-react.js
|
MIT
|
function extractInfoFromReactVersion(reactVersion) {
const match = reactVersion.match(
/(?<semverVersion>.*)-(?<releaseLabel>.*)-(?<sha>.*)-(?<dateString>.*)$/
)
return match ? match.groups : null
}
|
Set to `null` to automatically sync the React version of Pages Router with App Router React version.
Set to a specific version to override the Pages Router React version e.g. `^19.0.0`.
"Active" just refers to our current development practice. While we do support
React 18 in pages router, we don't focus our development process on it considering
it does not receive new features.
@type {string | null}
|
extractInfoFromReactVersion
|
javascript
|
vercel/next.js
|
scripts/sync-react.js
|
https://github.com/vercel/next.js/blob/master/scripts/sync-react.js
|
MIT
|
async function getChangelogFromGitHub(baseSha, newSha) {
const pageSize = 50
let changelog = []
for (let currentPage = 1; ; currentPage++) {
const url = `https://api.github.com/repos/facebook/react/compare/${baseSha}...${newSha}?per_page=${pageSize}&page=${currentPage}`
const headers = {}
// GITHUB_TOKEN is optional but helps in case of rate limiting during development.
if (process.env.GITHUB_TOKEN) {
headers.Authorization = `token ${process.env.GITHUB_TOKEN}`
}
const response = await fetch(url, {
headers,
})
if (!response.ok) {
throw new Error(
`${response.url}: Failed to fetch commit log from GitHub:\n${response.statusText}\n${await response.text()}`
)
}
const data = await response.json()
const { commits } = data
for (const { commit, sha } of commits) {
const title = commit.message.split('\n')[0] || ''
const match =
// The "title" looks like "[Fiber][Float] preinitialized stylesheets should support integrity option (#26881)"
/\(#([0-9]+)\)$/.exec(title) ??
// or contains "Pull Request resolved: https://github.com/facebook/react/pull/12345" in the body if merged via ghstack (e.g. https://github.com/facebook/react/commit/0a0a5c02f138b37e93d5d93341b494d0f5d52373)
/^Pull Request resolved: https:\/\/github.com\/facebook\/react\/pull\/([0-9]+)$/m.exec(
commit.message
)
const prNum = match ? match[1] : ''
if (prNum) {
changelog.push(`- https://github.com/facebook/react/pull/${prNum}`)
} else {
changelog.push(
`- [${commit.message.split('\n')[0]} facebook/react@${sha.slice(0, 9)}](https://github.com/facebook/react/commit/${sha}) (${commit.author.name})`
)
}
}
if (commits.length < pageSize) {
// If the number of commits is less than the page size, we've reached
// the end. Otherwise we'll keep fetching until we run out.
break
}
}
changelog.reverse()
return changelog.length > 0 ? changelog.join('\n') : null
}
|
Set to `null` to automatically sync the React version of Pages Router with App Router React version.
Set to a specific version to override the Pages Router React version e.g. `^19.0.0`.
"Active" just refers to our current development practice. While we do support
React 18 in pages router, we don't focus our development process on it considering
it does not receive new features.
@type {string | null}
|
getChangelogFromGitHub
|
javascript
|
vercel/next.js
|
scripts/sync-react.js
|
https://github.com/vercel/next.js/blob/master/scripts/sync-react.js
|
MIT
|
async function findHighestNPMReactVersion(versionLike) {
const { stdout, stderr } = await execa(
'npm',
['--silent', 'view', '--json', `react@${versionLike}`, 'version'],
{
// Avoid "Usage Error: This project is configured to use pnpm".
cwd: '/tmp',
}
)
if (stderr) {
console.error(stderr)
throw new Error(
`Failed to read highest react@${versionLike} version from npm.`
)
}
const result = JSON.parse(stdout)
return typeof result === 'string'
? result
: result.sort((a, b) => {
return SemVer.compare(b, a)
})[0]
}
|
Set to `null` to automatically sync the React version of Pages Router with App Router React version.
Set to a specific version to override the Pages Router React version e.g. `^19.0.0`.
"Active" just refers to our current development practice. While we do support
React 18 in pages router, we don't focus our development process on it considering
it does not receive new features.
@type {string | null}
|
findHighestNPMReactVersion
|
javascript
|
vercel/next.js
|
scripts/sync-react.js
|
https://github.com/vercel/next.js/blob/master/scripts/sync-react.js
|
MIT
|
async function main() {
const cwd = process.cwd()
const errors = []
const argv = await yargs(process.argv.slice(2))
.version(false)
.options('actor', {
type: 'string',
description:
'Required with `--create-pull`. The actor (GitHub username) that runs this script. Will be used for notifications but not commit attribution.',
})
.options('create-pull', {
default: false,
type: 'boolean',
description: 'Create a Pull Request in vercel/next.js',
})
.options('commit', {
default: false,
type: 'boolean',
description:
'Creates commits for each intermediate step. Useful to create better diffs for GitHub.',
})
.options('install', { default: true, type: 'boolean' })
.options('version', { default: null, type: 'string' }).argv
const { actor, createPull, commit, install, version } = argv
async function commitEverything(message) {
await execa('git', ['add', '-A'])
await execa('git', [
'commit',
'--message',
message,
'--no-verify',
// Some steps can be empty, e.g. when we don't sync Pages router
'--allow-empty',
])
}
if (createPull && !actor) {
throw new Error(
`Pull Request cannot be created without a GitHub actor (received '${String(actor)}'). ` +
'Pass an actor via `--actor "some-actor"`.'
)
}
const githubToken = process.env.GITHUB_TOKEN
if (createPull && !githubToken) {
throw new Error(
`Environment variable 'GITHUB_TOKEN' not specified but required when --create-pull is specified.`
)
}
let newVersionStr = version
if (
newVersionStr === null ||
// TODO: Fork arguments in GitHub workflow to ensure `--version ""` is considered a mistake
newVersionStr === ''
) {
newVersionStr = await findHighestNPMReactVersion(defaultLatestChannel)
console.log(
`--version was not provided. Using react@${defaultLatestChannel}: ${newVersionStr}`
)
}
const newVersionInfo = extractInfoFromReactVersion(newVersionStr)
if (!newVersionInfo) {
throw new Error(
`New react version does not match expected format: ${newVersionStr}
Choose a React canary version from npm: https://www.npmjs.com/package/react?activeTab=versions
Or, run this command with no arguments to use the most recently published version.
`
)
}
const { sha: newSha, dateString: newDateString } = newVersionInfo
const branchName = `update/react/${newVersionStr}`
if (createPull) {
const { exitCode, all, command } = await execa(
'git',
[
'ls-remote',
'--exit-code',
'--heads',
'origin',
`refs/heads/${branchName}`,
],
{ reject: false }
)
if (exitCode === 2) {
console.log(
`No sync in progress in branch '${branchName}' according to '${command}'. Starting a new one.`
)
} else if (exitCode === 0) {
console.log(
`An existing sync already exists in branch '${branchName}'. Delete the branch to start a new sync.`
)
return
} else {
throw new Error(
`Failed to check if the branch already existed:\n${command}: ${all}`
)
}
}
const rootManifest = JSON.parse(
await fsp.readFile(path.join(cwd, 'package.json'), 'utf-8')
)
const baseVersionStr = rootManifest.devDependencies['react-builtin'].replace(
/^npm:react@/,
''
)
await sync({
newVersionStr: `0.0.0-experimental-${newSha}-${newDateString}`,
noInstall: !install,
channel: 'experimental',
})
if (commit) {
await commitEverything('Update `react@experimental`')
}
await sync({
newVersionStr,
noInstall: !install,
channel: '<framework-stable>',
})
if (commit) {
await commitEverything('Update `react`')
}
const baseVersionInfo = extractInfoFromReactVersion(baseVersionStr)
if (!baseVersionInfo) {
throw new Error(
'Base react version does not match expected format: ' + baseVersionStr
)
}
const syncPagesRouterReact = activePagesRouterReact === null
const newActivePagesRouterReactVersion = syncPagesRouterReact
? newVersionStr
: activePagesRouterReact
const pagesRouterReactVersion = `^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ${newActivePagesRouterReactVersion}`
const highestPagesRouterReactVersion = await findHighestNPMReactVersion(
pagesRouterReactVersion
)
const { sha: baseSha, dateString: baseDateString } = baseVersionInfo
if (syncPagesRouterReact) {
for (const fileName of filesReferencingReactPeerDependencyVersion) {
const filePath = path.join(cwd, fileName)
const previousSource = await fsp.readFile(filePath, 'utf-8')
const updatedSource = previousSource.replace(
/const nextjsReactPeerVersion = "[^"]+";/,
`const nextjsReactPeerVersion = "${highestPagesRouterReactVersion}";`
)
if (activePagesRouterReact === null && updatedSource === previousSource) {
errors.push(
new Error(
`${fileName}: Failed to update ${baseVersionStr} to ${highestPagesRouterReactVersion}. Is this file still referencing the React peer dependency version?`
)
)
} else {
await fsp.writeFile(filePath, updatedSource)
}
}
}
for (const fileName of appManifestsInstallingNextjsPeerDependencies) {
const packageJsonPath = path.join(cwd, fileName)
const packageJson = await fsp.readFile(packageJsonPath, 'utf-8')
const manifest = JSON.parse(packageJson)
if (manifest.dependencies['react']) {
manifest.dependencies['react'] = highestPagesRouterReactVersion
}
if (manifest.dependencies['react-dom']) {
manifest.dependencies['react-dom'] = highestPagesRouterReactVersion
}
await fsp.writeFile(
packageJsonPath,
JSON.stringify(manifest, null, 2) +
// Prettier would add a newline anyway so do it manually to skip the additional `pnpm prettier-write`
'\n'
)
}
if (commit) {
await commitEverything('Updated peer dependency references in apps')
}
for (const fileName of libraryManifestsSupportingNextjsReact) {
const packageJsonPath = path.join(cwd, fileName)
const packageJson = await fsp.readFile(packageJsonPath, 'utf-8')
const manifest = JSON.parse(packageJson)
// Need to specify last supported RC version to avoid breaking changes.
if (manifest.peerDependencies['react']) {
manifest.peerDependencies['react'] = pagesRouterReactVersion
}
if (manifest.peerDependencies['react-dom']) {
manifest.peerDependencies['react-dom'] = pagesRouterReactVersion
}
await fsp.writeFile(
packageJsonPath,
JSON.stringify(manifest, null, 2) +
// Prettier would add a newline anyway so do it manually to skip the additional `pnpm prettier-write`
'\n'
)
}
if (commit) {
await commitEverything('Updated peer dependency references in libraries')
}
// Install the updated dependencies and build the vendored React files.
if (!install) {
console.log('Skipping install step because --no-install flag was passed.')
} else {
console.log('Installing dependencies...')
const installSubprocess = execa('pnpm', [
'install',
// Pnpm freezes the lockfile by default in CI.
// However, we just changed versions so the lockfile is expected to be changed.
'--no-frozen-lockfile',
])
if (installSubprocess.stdout) {
installSubprocess.stdout.pipe(process.stdout)
}
try {
await installSubprocess
} catch (error) {
console.error(error)
throw new Error('Failed to install updated dependencies.')
}
if (commit) {
await commitEverything('Update lockfile')
}
console.log('Building vendored React files...\n')
const nccSubprocess = execa('pnpm', ['ncc-compiled'], {
cwd: path.join(cwd, 'packages', 'next'),
})
if (nccSubprocess.stdout) {
nccSubprocess.stdout.pipe(process.stdout)
}
try {
await nccSubprocess
} catch (error) {
console.error(error)
throw new Error('Failed to run ncc.')
}
if (commit) {
await commitEverything('ncc-compiled')
}
// Print extra newline after ncc output
console.log()
}
let prDescription = ''
if (syncPagesRouterReact) {
prDescription += `**breaking change for canary users: Bumps peer dependency of React from \`${baseVersionStr}\` to \`${pagesRouterReactVersion}\`**\n\n`
}
// Fetch the changelog from GitHub and print it to the console.
prDescription += `[diff facebook/react@${baseSha}...${newSha}](https://github.com/facebook/react/compare/${baseSha}...${newSha})\n\n`
try {
const changelog = await getChangelogFromGitHub(baseSha, newSha)
if (changelog === null) {
prDescription += `GitHub reported no changes between ${baseSha} and ${newSha}.`
} else {
prDescription += `<details>\n<summary>React upstream changes</summary>\n\n${changelog}\n\n</details>`
}
} catch (error) {
console.error(error)
prDescription +=
'\nFailed to fetch changelog from GitHub. Changes were applied, anyway.\n'
}
if (!install) {
console.log(
`
To finish upgrading, complete the following steps:
- Install the updated dependencies: pnpm install
- Build the vendored React files: (inside packages/next dir) pnpm ncc-compiled
Or run this command again without the --no-install flag to do both automatically.
`
)
}
if (errors.length) {
// eslint-disable-next-line no-undef -- Defined in Node.js
throw new AggregateError(errors)
}
if (createPull) {
const octokit = new Octokit({ auth: githubToken })
const prTitle = `Upgrade React from \`${baseSha}-${baseDateString}\` to \`${newSha}-${newDateString}\``
await execa('git', ['checkout', '-b', branchName])
// We didn't commit intermediate steps yet so now we need to commit to create a PR.
if (!commit) {
commitEverything(prTitle)
}
await execa('git', ['push', 'origin', branchName])
const pullRequest = await octokit.rest.pulls.create({
owner: repoOwner,
repo: repoName,
head: branchName,
base: process.env.GITHUB_REF || 'canary',
draft: false,
title: prTitle,
body: prDescription,
})
console.log('Created pull request %s', pullRequest.data.html_url)
await Promise.all([
actor
? octokit.rest.issues.addAssignees({
owner: repoOwner,
repo: repoName,
issue_number: pullRequest.data.number,
assignees: [actor],
})
: Promise.resolve(),
octokit.rest.pulls.requestReviewers({
owner: repoOwner,
repo: repoName,
pull_number: pullRequest.data.number,
reviewers: pullRequestReviewers,
}),
octokit.rest.issues.addLabels({
owner: repoOwner,
repo: repoName,
issue_number: pullRequest.data.number,
labels: pullRequestLabels,
}),
])
}
console.log(prDescription)
console.log(
`Successfully updated React from \`${baseSha}-${baseDateString}\` to \`${newSha}-${newDateString}\``
)
}
|
Set to `null` to automatically sync the React version of Pages Router with App Router React version.
Set to a specific version to override the Pages Router React version e.g. `^19.0.0`.
"Active" just refers to our current development practice. While we do support
React 18 in pages router, we don't focus our development process on it considering
it does not receive new features.
@type {string | null}
|
main
|
javascript
|
vercel/next.js
|
scripts/sync-react.js
|
https://github.com/vercel/next.js/blob/master/scripts/sync-react.js
|
MIT
|
async function commitEverything(message) {
await execa('git', ['add', '-A'])
await execa('git', [
'commit',
'--message',
message,
'--no-verify',
// Some steps can be empty, e.g. when we don't sync Pages router
'--allow-empty',
])
}
|
Set to `null` to automatically sync the React version of Pages Router with App Router React version.
Set to a specific version to override the Pages Router React version e.g. `^19.0.0`.
"Active" just refers to our current development practice. While we do support
React 18 in pages router, we don't focus our development process on it considering
it does not receive new features.
@type {string | null}
|
commitEverything
|
javascript
|
vercel/next.js
|
scripts/sync-react.js
|
https://github.com/vercel/next.js/blob/master/scripts/sync-react.js
|
MIT
|
formatUnion = (values) =>
values.map((value) => `"${value}"`).join('|')
|
This is an autogenerated file by scripts/update-google-fonts.js
|
formatUnion
|
javascript
|
vercel/next.js
|
scripts/update-google-fonts.js
|
https://github.com/vercel/next.js/blob/master/scripts/update-google-fonts.js
|
MIT
|
formatUnion = (values) =>
values.map((value) => `"${value}"`).join('|')
|
This is an autogenerated file by scripts/update-google-fonts.js
|
formatUnion
|
javascript
|
vercel/next.js
|
scripts/update-google-fonts.js
|
https://github.com/vercel/next.js/blob/master/scripts/update-google-fonts.js
|
MIT
|
function exec(title, file, args) {
logCommand(title, `${file} ${args.join(' ')}`)
return execa(file, args, {
stderr: 'inherit',
})
}
|
@param title {string}
@param file {string}
@param args {readonly string[]}
@returns {execa.ExecaChildProcess}
|
exec
|
javascript
|
vercel/next.js
|
test/update-bundler-manifest.js
|
https://github.com/vercel/next.js/blob/master/test/update-bundler-manifest.js
|
MIT
|
function logCommand(title, command) {
let message = `\n${bold().underline(title)}\n`
if (command) {
message += `> ${bold(command)}\n`
}
console.log(message)
}
|
@param {string} title
@param {string} [command]
|
logCommand
|
javascript
|
vercel/next.js
|
test/update-bundler-manifest.js
|
https://github.com/vercel/next.js/blob/master/test/update-bundler-manifest.js
|
MIT
|
function accountForOverhead(megaBytes) {
// We are sending {megaBytes} - 5% to account for encoding overhead
return Math.floor(1024 * 1024 * megaBytes * 0.95)
}
|
This function accounts for the overhead of encoding the data to be sent
over the network via a multipart request.
@param {number} megaBytes
@returns {number}
|
accountForOverhead
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/actions/account-for-overhead.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/actions/account-for-overhead.js
|
MIT
|
async function middleware(request) {
if (request.nextUrl.pathname === '/searchparams-normalization-bug') {
const headers = new Headers(request.headers)
headers.set('test', request.nextUrl.searchParams.get('val') || '')
const response = NextResponse.next({
request: {
headers,
},
})
return response
}
if (request.nextUrl.pathname === '/exists-but-not-routed') {
return NextResponse.rewrite(new URL('/dashboard', request.url))
}
if (request.nextUrl.pathname === '/middleware-to-dashboard') {
return NextResponse.rewrite(new URL('/dashboard', request.url))
}
// In dev this route will fail to bootstrap because webpack uses eval which is dissallowed by
// this policy. In production this route will work
if (request.nextUrl.pathname === '/bootstrap/with-nonce') {
const nonce = crypto.randomUUID()
return NextResponse.next({
headers: {
'Content-Security-Policy': `script-src 'nonce-${nonce}' 'strict-dynamic';`,
},
})
}
if (request.nextUrl.pathname.startsWith('/internal/test')) {
const method = request.nextUrl.pathname.endsWith('rewrite')
? 'rewrite'
: 'redirect'
const internal = ['RSC', 'Next-Router-State-Tree']
if (internal.some((name) => request.headers.has(name.toLowerCase()))) {
return NextResponse[method](new URL('/internal/failure', request.url))
}
return NextResponse[method](new URL('/internal/success', request.url))
}
if (request.nextUrl.pathname === '/search-params-prop-middleware-rewrite') {
return NextResponse.rewrite(
new URL(
'/search-params-prop?first=value&second=other%20value&third',
request.url
)
)
}
if (
request.nextUrl.pathname === '/search-params-prop-server-middleware-rewrite'
) {
return NextResponse.rewrite(
new URL(
'/search-params-prop/server?first=value&second=other%20value&third',
request.url
)
)
}
if (request.nextUrl.pathname === '/script-nonce') {
const nonce = crypto.randomUUID()
return NextResponse.next({
headers: {
'content-security-policy': `script-src 'nonce-${nonce}' 'strict-dynamic';`,
},
})
}
if (request.nextUrl.pathname === '/script-nonce/with-next-font') {
const nonce = crypto.randomUUID()
return NextResponse.next({
headers: {
'content-security-policy': `script-src 'nonce-${nonce}' 'strict-dynamic';`,
},
})
}
}
|
@param {import('next/server').NextRequest} request
@returns {Promise<NextResponse | undefined>}
|
middleware
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/app/middleware.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/app/middleware.js
|
MIT
|
async function middleware(request) {
const headersFromRequest = new Headers(request.headers)
// It should be able to import and use `headers` inside middleware
const headersFromNext = await nextHeaders()
headersFromRequest.set('x-from-middleware', 'hello-from-middleware')
// make sure headers() from `next/headers` is behaving properly
if (
headersFromRequest.get('x-from-client') &&
headersFromNext.get('x-from-client') !==
headersFromRequest.get('x-from-client')
) {
throw new Error('Expected headers from client to match')
}
if (request.nextUrl.searchParams.get('draft')) {
;(await draftMode()).enable()
}
const removeHeaders = request.nextUrl.searchParams.get('remove-headers')
if (removeHeaders) {
for (const key of removeHeaders.split(',')) {
headersFromRequest.delete(key)
}
}
const updateHeader = request.nextUrl.searchParams.get('update-headers')
if (updateHeader) {
for (const kv of updateHeader.split(',')) {
const [key, value] = kv.split('=')
headersFromRequest.set(key, value)
}
}
if (request.nextUrl.pathname.includes('/rewrite-to-app')) {
request.nextUrl.pathname = '/headers'
return NextResponse.rewrite(request.nextUrl)
}
if (request.nextUrl.pathname === '/rsc-cookies') {
const res = NextResponse.next()
res.cookies.set('rsc-cookie-value-1', `${Math.random()}`)
res.cookies.set('rsc-cookie-value-2', `${Math.random()}`)
return res
}
if (request.nextUrl.pathname === '/rsc-cookies/cookie-options') {
const res = NextResponse.next()
res.cookies.set('rsc-secure-cookie', `${Math.random()}`, {
secure: true,
httpOnly: true,
})
return res
}
if (request.nextUrl.pathname === '/rsc-cookies-delete') {
const res = NextResponse.next()
res.cookies.delete('rsc-cookie-value-1')
return res
}
if (request.nextUrl.pathname === '/preloads') {
const res = NextResponse.next({
headers: {
link: '<https://example.com/page>; rel="alternate"; hreflang="en"',
},
})
return res
}
return NextResponse.next({
request: {
headers: headersFromRequest,
},
})
}
|
@param {import('next/server').NextRequest} request
|
middleware
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/app-middleware/middleware.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/app-middleware/middleware.js
|
MIT
|
function middleware(request) {
if (
request.nextUrl.pathname ===
'/hooks/use-selected-layout-segment/rewritten-middleware'
) {
return NextResponse.rewrite(
new URL(
'/hooks/use-selected-layout-segment/first/slug3/second/catch/all',
request.url
)
)
}
}
|
@param {import('next/server').NextRequest} request
@returns {NextResponse | undefined}
|
middleware
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/hooks/middleware.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/hooks/middleware.js
|
MIT
|
function middleware(request) {
const rscQuery = request.nextUrl.searchParams.get(NEXT_RSC_UNION_QUERY)
// Test that the RSC query is not present in the middleware
if (rscQuery) {
throw new Error('RSC query should not be present in the middleware')
}
if (request.nextUrl.pathname === '/redirect-middleware-to-dashboard') {
return NextResponse.redirect(new URL('/redirect-dest', request.url))
}
if (request.nextUrl.pathname === '/redirect-on-refresh/auth') {
const cookie = request.cookies.get('token')
if (cookie) {
return NextResponse.redirect(
new URL('/redirect-on-refresh/dashboard', request.url)
)
}
}
}
|
@param {import('next/server').NextRequest} request
@returns {NextResponse | undefined}
|
middleware
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/navigation/middleware.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/navigation/middleware.js
|
MIT
|
get() {
return {
waitUntil(/** @type {Promise<any>} */ promise) {
cliLog('waitUntil from "@next/request-context" was called')
promise.catch((err) => {
console.error(err)
})
},
}
}
|
@type {import('next/dist/server/after/builtin-request-context').BuiltinRequestContext}
|
get
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/next-after-app/utils/provided-request-context.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/next-after-app/utils/provided-request-context.js
|
MIT
|
waitUntil(/** @type {Promise<any>} */ promise) {
cliLog('waitUntil from "@next/request-context" was called')
promise.catch((err) => {
console.error(err)
})
}
|
@type {import('next/dist/server/after/builtin-request-context').BuiltinRequestContext}
|
waitUntil
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/next-after-app/utils/provided-request-context.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/next-after-app/utils/provided-request-context.js
|
MIT
|
async get(cacheKey, softTags) {
console.log('ModernCustomCacheHandler::get', cacheKey, softTags)
return defaultCacheHandler.get(cacheKey, softTags)
}
|
@type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2}
|
get
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/use-cache-custom-handler/handler.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/use-cache-custom-handler/handler.js
|
MIT
|
async set(cacheKey, pendingEntry) {
console.log('ModernCustomCacheHandler::set', cacheKey)
return defaultCacheHandler.set(cacheKey, pendingEntry)
}
|
@type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2}
|
set
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/use-cache-custom-handler/handler.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/use-cache-custom-handler/handler.js
|
MIT
|
async refreshTags() {
console.log('ModernCustomCacheHandler::refreshTags')
return defaultCacheHandler.refreshTags()
}
|
@type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2}
|
refreshTags
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/use-cache-custom-handler/handler.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/use-cache-custom-handler/handler.js
|
MIT
|
async getExpiration(...tags) {
console.log('ModernCustomCacheHandler::getExpiration', JSON.stringify(tags))
// Expecting soft tags in `get` to be used by the cache handler for checking
// the expiration of a cache entry, instead of letting Next.js handle it.
return Infinity
}
|
@type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2}
|
getExpiration
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/use-cache-custom-handler/handler.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/use-cache-custom-handler/handler.js
|
MIT
|
async expireTags(...tags) {
console.log('ModernCustomCacheHandler::expireTags', JSON.stringify(tags))
return defaultCacheHandler.expireTags(...tags)
}
|
@type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2}
|
expireTags
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/use-cache-custom-handler/handler.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/use-cache-custom-handler/handler.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.