This commit is contained in:
Yamozha
2021-04-02 02:24:13 +03:00
parent c23950b545
commit 7256d79e2c
31493 changed files with 3036630 additions and 0 deletions

5
node_modules/metro-source-map/README.md generated vendored Normal file
View File

@ -0,0 +1,5 @@
# Metro
🚇 The source map generator for [Metro](https://facebook.github.io/metro/).
(TODO)

28
node_modules/metro-source-map/package.json generated vendored Normal file
View File

@ -0,0 +1,28 @@
{
"version": "0.59.0",
"name": "metro-source-map",
"description": "🚇 Source map generator for Metro.",
"main": "src/source-map.js",
"repository": {
"type": "git",
"url": "git@github.com:facebook/metro.git"
},
"scripts": {
"prepare-release": "test -d build && rm -rf src.real && mv src src.real && mv build src",
"cleanup-release": "test ! -e build && mv src build && mv src.real src"
},
"dependencies": {
"@babel/traverse": "^7.0.0",
"@babel/types": "^7.0.0",
"invariant": "^2.2.4",
"metro-symbolicate": "0.59.0",
"ob1": "0.59.0",
"source-map": "^0.5.6",
"vlq": "^1.0.0"
},
"license": "MIT",
"devDependencies": {
"@babel/parser": "^7.0.0",
"uglify-es": "^3.1.9"
}
}

4
node_modules/metro-source-map/rn-babelrc.json generated vendored Normal file
View File

@ -0,0 +1,4 @@
{
"presets": [ "metro-react-native-babel-preset" ],
"plugins": []
}

107
node_modules/metro-source-map/src/B64Builder.js generated vendored Normal file
View File

@ -0,0 +1,107 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
"use strict";
const encode = require("./encode");
const MAX_SEGMENT_LENGTH = 7;
const ONE_MEG = 1024 * 1024;
const COMMA = 0x2c;
const SEMICOLON = 0x3b;
/**
* Efficient builder for base64 VLQ mappings strings.
*
* This class uses a buffer that is preallocated with one megabyte and is
* reallocated dynamically as needed, doubling its size.
*
* Encoding never creates any complex value types (strings, objects), and only
* writes character values to the buffer.
*
* For details about source map terminology and specification, check
* https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
*/
class B64Builder {
constructor() {
this.buffer = Buffer.alloc(ONE_MEG);
this.pos = 0;
this.hasSegment = false;
}
/**
* Adds `n` markers for generated lines to the mappings.
*/
markLines(n) {
if (n < 1) {
return this;
}
this.hasSegment = false;
if (this.pos + n >= this.buffer.length) {
this._realloc();
}
while (n--) {
this.buffer[this.pos++] = SEMICOLON;
}
return this;
}
/**
* Starts a segment at the specified column offset in the current line.
*/
startSegment(column) {
if (this.hasSegment) {
this._writeByte(COMMA);
} else {
this.hasSegment = true;
}
this.append(column);
return this;
}
/**
* Appends a single number to the mappings.
*/
append(value) {
if (this.pos + MAX_SEGMENT_LENGTH >= this.buffer.length) {
this._realloc();
}
this.pos = encode(value, this.buffer, this.pos);
return this;
}
/**
* Returns the string representation of the mappings.
*/
toString() {
return this.buffer.toString("ascii", 0, this.pos);
}
_writeByte(byte) {
if (this.pos === this.buffer.length) {
this._realloc();
}
this.buffer[this.pos++] = byte;
}
_realloc() {
const buffer = this.buffer;
this.buffer = Buffer.alloc(buffer.length * 2);
buffer.copy(this.buffer);
}
}
module.exports = B64Builder;

107
node_modules/metro-source-map/src/B64Builder.js.flow generated vendored Normal file
View File

@ -0,0 +1,107 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const encode = require('./encode');
const MAX_SEGMENT_LENGTH = 7;
const ONE_MEG = 1024 * 1024;
const COMMA = 0x2c;
const SEMICOLON = 0x3b;
/**
* Efficient builder for base64 VLQ mappings strings.
*
* This class uses a buffer that is preallocated with one megabyte and is
* reallocated dynamically as needed, doubling its size.
*
* Encoding never creates any complex value types (strings, objects), and only
* writes character values to the buffer.
*
* For details about source map terminology and specification, check
* https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
*/
class B64Builder {
buffer: Buffer;
pos: number;
hasSegment: boolean;
constructor() {
this.buffer = Buffer.alloc(ONE_MEG);
this.pos = 0;
this.hasSegment = false;
}
/**
* Adds `n` markers for generated lines to the mappings.
*/
markLines(n: number): this {
if (n < 1) {
return this;
}
this.hasSegment = false;
if (this.pos + n >= this.buffer.length) {
this._realloc();
}
while (n--) {
this.buffer[this.pos++] = SEMICOLON;
}
return this;
}
/**
* Starts a segment at the specified column offset in the current line.
*/
startSegment(column: number): this {
if (this.hasSegment) {
this._writeByte(COMMA);
} else {
this.hasSegment = true;
}
this.append(column);
return this;
}
/**
* Appends a single number to the mappings.
*/
append(value: number): this {
if (this.pos + MAX_SEGMENT_LENGTH >= this.buffer.length) {
this._realloc();
}
this.pos = encode(value, this.buffer, this.pos);
return this;
}
/**
* Returns the string representation of the mappings.
*/
toString(): string {
return this.buffer.toString('ascii', 0, this.pos);
}
_writeByte(byte: number) {
if (this.pos === this.buffer.length) {
this._realloc();
}
this.buffer[this.pos++] = byte;
}
_realloc() {
const {buffer} = this;
this.buffer = Buffer.alloc(buffer.length * 2);
buffer.copy(this.buffer);
}
}
module.exports = B64Builder;

132
node_modules/metro-source-map/src/BundleBuilder.js generated vendored Normal file
View File

@ -0,0 +1,132 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
"use strict";
const EMPTY_MAP = {
version: 3,
sources: [],
names: [],
mappings: "A"
};
/**
* Builds a source-mapped bundle by concatenating strings and their
* corresponding source maps (if any).
*
* Usage:
*
* const builder = new BundleBuilder('bundle.js');
* builder
* .append('foo\n', fooMap)
* .append('bar\n')
* // ...
* const code = builder.getCode();
* const map = builder.getMap();
*/
class BundleBuilder {
constructor(file) {
this._file = file;
this._sections = [];
this._line = 0;
this._column = 0;
this._code = "";
this._afterMappedContent = false;
}
_pushMapSection(map) {
this._sections.push({
map,
offset: {
column: this._column,
line: this._line
}
});
}
_endMappedContent() {
if (this._afterMappedContent) {
this._pushMapSection(EMPTY_MAP);
this._afterMappedContent = false;
}
}
append(code, map) {
if (!code.length) {
return this;
}
const _measureString = measureString(code),
lineBreaks = _measureString.lineBreaks,
lastLineColumns = _measureString.lastLineColumns;
if (map) {
this._pushMapSection(map);
this._afterMappedContent = true;
} else {
this._endMappedContent();
}
this._afterMappedContent = !!map;
this._line = this._line + lineBreaks;
if (lineBreaks > 0) {
this._column = lastLineColumns;
} else {
this._column = this._column + lastLineColumns;
}
this._code = this._code + code;
return this;
}
getMap() {
this._endMappedContent();
return createIndexMap(this._file, this._sections);
}
getCode() {
return this._code;
}
}
const reLineBreak = /\r\n|\r|\n/g;
function measureString(str) {
let lineBreaks = 0;
let match;
let lastLineStart = 0;
while ((match = reLineBreak.exec(str))) {
++lineBreaks;
lastLineStart = match.index + match[0].length;
}
const lastLineColumns = str.length - lastLineStart;
return {
lineBreaks,
lastLineColumns
};
}
function createIndexMap(file, sections) {
return {
version: 3,
file,
sections
};
}
module.exports = {
BundleBuilder,
createIndexMap
};

126
node_modules/metro-source-map/src/BundleBuilder.js.flow generated vendored Normal file
View File

@ -0,0 +1,126 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
import type {IndexMap, IndexMapSection, MixedSourceMap} from './source-map';
const EMPTY_MAP = {
version: 3,
sources: [],
names: [],
mappings: 'A',
};
/**
* Builds a source-mapped bundle by concatenating strings and their
* corresponding source maps (if any).
*
* Usage:
*
* const builder = new BundleBuilder('bundle.js');
* builder
* .append('foo\n', fooMap)
* .append('bar\n')
* // ...
* const code = builder.getCode();
* const map = builder.getMap();
*/
class BundleBuilder {
_file: string;
_sections: Array<IndexMapSection>;
_line: number;
_column: number;
_code: string;
_afterMappedContent: boolean;
constructor(file: string) {
this._file = file;
this._sections = [];
this._line = 0;
this._column = 0;
this._code = '';
this._afterMappedContent = false;
}
_pushMapSection(map: MixedSourceMap) {
this._sections.push({
map,
offset: {column: this._column, line: this._line},
});
}
_endMappedContent() {
if (this._afterMappedContent) {
this._pushMapSection(EMPTY_MAP);
this._afterMappedContent = false;
}
}
append(code: string, map: ?MixedSourceMap): this {
if (!code.length) {
return this;
}
const {lineBreaks, lastLineColumns} = measureString(code);
if (map) {
this._pushMapSection(map);
this._afterMappedContent = true;
} else {
this._endMappedContent();
}
this._afterMappedContent = !!map;
this._line = this._line + lineBreaks;
if (lineBreaks > 0) {
this._column = lastLineColumns;
} else {
this._column = this._column + lastLineColumns;
}
this._code = this._code + code;
return this;
}
getMap(): MixedSourceMap {
this._endMappedContent();
return createIndexMap(this._file, this._sections);
}
getCode(): string {
return this._code;
}
}
const reLineBreak = /\r\n|\r|\n/g;
function measureString(
str: string,
): {|lineBreaks: number, lastLineColumns: number|} {
let lineBreaks = 0;
let match;
let lastLineStart = 0;
while ((match = reLineBreak.exec(str))) {
++lineBreaks;
lastLineStart = match.index + match[0].length;
}
const lastLineColumns = str.length - lastLineStart;
return {lineBreaks, lastLineColumns};
}
function createIndexMap(
file: string,
sections: Array<IndexMapSection>,
): IndexMap {
return {
version: 3,
file,
sections,
};
}
module.exports = {BundleBuilder, createIndexMap};

View File

@ -0,0 +1,54 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
"use strict";
const invariant = require("invariant");
const _require = require("./constants"),
GENERATED_ORDER = _require.GENERATED_ORDER,
iterationOrderToString = _require.iterationOrderToString;
// Implementation details shared between MappingsConsumer and SectionsConsumer
class AbstractConsumer {
constructor(sourceMap) {
this._sourceMap = sourceMap;
}
originalPositionFor(generatedPosition) {
invariant(false, "Not implemented");
}
generatedMappings() {
invariant(false, "Not implemented");
}
eachMapping(callback) {
let context =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
let order =
arguments.length > 2 && arguments[2] !== undefined
? arguments[2]
: GENERATED_ORDER;
invariant(
order === GENERATED_ORDER,
`Iteration order not implemented: ${iterationOrderToString(order)}`
);
for (const mapping of this.generatedMappings()) {
callback.call(context, mapping);
}
} // flowlint unsafe-getters-setters:off
get file() {
return this._sourceMap.file;
}
}
module.exports = AbstractConsumer;

View File

@ -0,0 +1,63 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
const invariant = require('invariant');
const {GENERATED_ORDER, iterationOrderToString} = require('./constants');
import type {
SourcePosition,
GeneratedPositionLookup,
Mapping,
IConsumer,
IterationOrder,
} from './types.flow';
// Implementation details shared between MappingsConsumer and SectionsConsumer
class AbstractConsumer implements IConsumer {
_sourceMap: {+file?: string, ...};
constructor(sourceMap: {+file?: string, ...}) {
this._sourceMap = sourceMap;
}
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition {
invariant(false, 'Not implemented');
}
generatedMappings(): Iterable<Mapping> {
invariant(false, 'Not implemented');
}
eachMapping(
callback: (mapping: Mapping) => mixed,
context?: mixed = null,
order?: IterationOrder = GENERATED_ORDER,
) {
invariant(
order === GENERATED_ORDER,
`Iteration order not implemented: ${iterationOrderToString(order)}`,
);
for (const mapping of this.generatedMappings()) {
callback.call(context, mapping);
}
}
// flowlint unsafe-getters-setters:off
get file(): ?string {
return this._sourceMap.file;
}
}
module.exports = AbstractConsumer;

View File

@ -0,0 +1,74 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
"use strict";
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const createConsumer = require("./createConsumer");
const _require = require("./constants"),
GENERATED_ORDER = _require.GENERATED_ORDER,
ORIGINAL_ORDER = _require.ORIGINAL_ORDER,
GREATEST_LOWER_BOUND = _require.GREATEST_LOWER_BOUND,
LEAST_UPPER_BOUND = _require.LEAST_UPPER_BOUND;
/**
* A source map consumer that supports both "basic" and "indexed" source maps.
* Uses `MappingsConsumer` and `SectionsConsumer` under the hood (via
* `createConsumer`).
*/
class DelegatingConsumer {
constructor(sourceMap) {
this._rootConsumer = createConsumer(sourceMap);
return this._rootConsumer;
}
originalPositionFor(generatedPosition) {
return this._rootConsumer.originalPositionFor(generatedPosition);
}
generatedMappings() {
return this._rootConsumer.generatedMappings();
}
eachMapping(callback, context, order) {
return this._rootConsumer.eachMapping(callback, context, order);
} // flowlint unsafe-getters-setters:off
get file() {
return this._rootConsumer.file;
}
}
_defineProperty(DelegatingConsumer, "GENERATED_ORDER", GENERATED_ORDER);
_defineProperty(DelegatingConsumer, "ORIGINAL_ORDER", ORIGINAL_ORDER);
_defineProperty(
DelegatingConsumer,
"GREATEST_LOWER_BOUND",
GREATEST_LOWER_BOUND
);
_defineProperty(DelegatingConsumer, "LEAST_UPPER_BOUND", LEAST_UPPER_BOUND);
module.exports = DelegatingConsumer;

View File

@ -0,0 +1,73 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
const createConsumer = require('./createConsumer');
const {
GENERATED_ORDER,
ORIGINAL_ORDER,
GREATEST_LOWER_BOUND,
LEAST_UPPER_BOUND,
} = require('./constants');
import type {MixedSourceMap} from '../source-map';
import type {LookupBias} from './constants.js';
import type {
SourcePosition,
GeneratedPositionLookup,
Mapping,
IConsumer,
IterationOrder,
} from './types.flow';
/**
* A source map consumer that supports both "basic" and "indexed" source maps.
* Uses `MappingsConsumer` and `SectionsConsumer` under the hood (via
* `createConsumer`).
*/
class DelegatingConsumer implements IConsumer {
static +GENERATED_ORDER: IterationOrder = GENERATED_ORDER;
static +ORIGINAL_ORDER: IterationOrder = ORIGINAL_ORDER;
static +GREATEST_LOWER_BOUND: LookupBias = GREATEST_LOWER_BOUND;
static +LEAST_UPPER_BOUND: LookupBias = LEAST_UPPER_BOUND;
_rootConsumer: IConsumer;
constructor(sourceMap: MixedSourceMap): IConsumer {
this._rootConsumer = createConsumer(sourceMap);
return this._rootConsumer;
}
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition {
return this._rootConsumer.originalPositionFor(generatedPosition);
}
generatedMappings(): Iterable<Mapping> {
return this._rootConsumer.generatedMappings();
}
eachMapping(
callback: (mapping: Mapping) => mixed,
context?: mixed,
order?: IterationOrder,
): void {
return this._rootConsumer.eachMapping(callback, context, order);
}
// flowlint unsafe-getters-setters:off
get file(): ?string {
return this._rootConsumer.file;
}
}
module.exports = DelegatingConsumer;

View File

@ -0,0 +1,313 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
"use strict";
function _toConsumableArray(arr) {
return (
_arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread()
);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function _iterableToArray(iter) {
if (
Symbol.iterator in Object(iter) ||
Object.prototype.toString.call(iter) === "[object Arguments]"
)
return Array.from(iter);
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++)
arr2[i] = arr[i];
return arr2;
}
}
function _slicedToArray(arr, i) {
return (
_arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest()
);
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (
var _i = arr[Symbol.iterator](), _s;
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
})
);
}
ownKeys.forEach(function(key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const AbstractConsumer = require("./AbstractConsumer");
const invariant = require("invariant");
const normalizeSourcePath = require("./normalizeSourcePath");
const _require = require("./constants"),
FIRST_COLUMN = _require.FIRST_COLUMN,
FIRST_LINE = _require.FIRST_LINE,
GREATEST_LOWER_BOUND = _require.GREATEST_LOWER_BOUND,
EMPTY_POSITION = _require.EMPTY_POSITION,
lookupBiasToString = _require.lookupBiasToString;
const _require2 = require("./search"),
greatestLowerBound = _require2.greatestLowerBound;
const _require3 = require("ob1"),
add = _require3.add,
get0 = _require3.get0,
add0 = _require3.add0,
sub = _require3.sub,
inc = _require3.inc;
const _require4 = require("vlq"),
decodeVlq = _require4.decode;
/**
* A source map consumer that supports "basic" source maps (that have a
* `mappings` field and no sections).
*/
class MappingsConsumer extends AbstractConsumer {
constructor(sourceMap) {
super(sourceMap);
this._sourceMap = sourceMap;
this._decodedMappings = null;
this._normalizedSources = null;
}
originalPositionFor(generatedPosition) {
const line = generatedPosition.line,
column = generatedPosition.column;
if (line == null || column == null) {
return _objectSpread({}, EMPTY_POSITION);
}
if (generatedPosition.bias != null) {
invariant(
generatedPosition.bias === GREATEST_LOWER_BOUND,
`Unimplemented lookup bias: ${lookupBiasToString(
generatedPosition.bias
)}`
);
}
const mappings = this._decodeAndCacheMappings();
const index = greatestLowerBound(
mappings,
{
line,
column
},
(position, mapping) => {
if (position.line === mapping.generatedLine) {
return get0(sub(position.column, mapping.generatedColumn));
}
return get0(sub(position.line, mapping.generatedLine));
}
);
if (
index != null &&
mappings[index].generatedLine === generatedPosition.line
) {
const mapping = mappings[index];
return {
source: mapping.source,
name: mapping.name,
line: mapping.originalLine,
column: mapping.originalColumn
};
}
return _objectSpread({}, EMPTY_POSITION);
}
*_decodeMappings() {
let generatedLine = FIRST_LINE;
let generatedColumn = FIRST_COLUMN;
let originalLine = FIRST_LINE;
let originalColumn = FIRST_COLUMN;
let nameIndex = add0(0);
let sourceIndex = add0(0);
const normalizedSources = this._normalizeAndCacheSources();
const _this$_sourceMap = this._sourceMap,
mappingsRaw = _this$_sourceMap.mappings,
names = _this$_sourceMap.names;
let next;
const vlqCache = new Map();
for (let i = 0; i < mappingsRaw.length; i = next) {
switch (mappingsRaw[i]) {
case ";":
generatedLine = inc(generatedLine);
generatedColumn = FIRST_COLUMN;
/* falls through */
case ",":
next = i + 1;
continue;
}
findNext: for (next = i + 1; next < mappingsRaw.length; ++next) {
switch (mappingsRaw[next]) {
case ";":
/* falls through */
case ",":
break findNext;
}
}
const mappingRaw = mappingsRaw.slice(i, next);
let decodedVlqValues;
if (vlqCache.has(mappingRaw)) {
decodedVlqValues = vlqCache.get(mappingRaw);
} else {
decodedVlqValues = decodeVlq(mappingRaw);
vlqCache.set(mappingRaw, decodedVlqValues);
}
invariant(Array.isArray(decodedVlqValues), "Decoding VLQ tuple failed");
const _decodedVlqValues = decodedVlqValues,
_decodedVlqValues2 = _slicedToArray(_decodedVlqValues, 5),
generatedColumnDelta = _decodedVlqValues2[0],
sourceIndexDelta = _decodedVlqValues2[1],
originalLineDelta = _decodedVlqValues2[2],
originalColumnDelta = _decodedVlqValues2[3],
nameIndexDelta = _decodedVlqValues2[4];
decodeVlq(mappingRaw);
invariant(generatedColumnDelta != null, "Invalid generated column delta");
generatedColumn = add(generatedColumn, generatedColumnDelta);
const mapping = {
generatedLine,
generatedColumn,
source: null,
name: null,
originalLine: null,
originalColumn: null
};
if (sourceIndexDelta != null) {
sourceIndex = add(sourceIndex, sourceIndexDelta);
mapping.source = normalizedSources[get0(sourceIndex)];
invariant(originalLineDelta != null, "Invalid original line delta");
invariant(originalColumnDelta != null, "Invalid original column delta");
originalLine = add(originalLine, originalLineDelta);
originalColumn = add(originalColumn, originalColumnDelta);
mapping.originalLine = originalLine;
mapping.originalColumn = originalColumn;
if (nameIndexDelta != null) {
nameIndex = add(nameIndex, nameIndexDelta);
mapping.name = names[get0(nameIndex)];
}
}
yield mapping;
}
}
_normalizeAndCacheSources() {
if (!this._normalizedSources) {
this._normalizedSources = this._sourceMap.sources.map(source =>
normalizeSourcePath(source, this._sourceMap)
);
}
return this._normalizedSources;
}
_decodeAndCacheMappings() {
if (!this._decodedMappings) {
this._decodedMappings = _toConsumableArray(this._decodeMappings());
}
return this._decodedMappings;
}
generatedMappings() {
return this._decodeAndCacheMappings();
}
}
module.exports = MappingsConsumer;

View File

@ -0,0 +1,197 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const AbstractConsumer = require('./AbstractConsumer');
const invariant = require('invariant');
const normalizeSourcePath = require('./normalizeSourcePath');
const {
FIRST_COLUMN,
FIRST_LINE,
GREATEST_LOWER_BOUND,
EMPTY_POSITION,
lookupBiasToString,
} = require('./constants');
const {greatestLowerBound} = require('./search');
const {add, get0, add0, sub, inc} = require('ob1');
const {decode: decodeVlq} = require('vlq');
import type {BasicSourceMap} from '../source-map';
import type {
SourcePosition,
GeneratedPositionLookup,
Mapping,
IConsumer,
} from './types.flow';
/**
* A source map consumer that supports "basic" source maps (that have a
* `mappings` field and no sections).
*/
class MappingsConsumer extends AbstractConsumer implements IConsumer {
_sourceMap: BasicSourceMap;
_decodedMappings: ?$ReadOnlyArray<Mapping>;
_normalizedSources: ?$ReadOnlyArray<string>;
constructor(sourceMap: BasicSourceMap) {
super(sourceMap);
this._sourceMap = sourceMap;
this._decodedMappings = null;
this._normalizedSources = null;
}
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition {
const {line, column} = generatedPosition;
if (line == null || column == null) {
return {...EMPTY_POSITION};
}
if (generatedPosition.bias != null) {
invariant(
generatedPosition.bias === GREATEST_LOWER_BOUND,
`Unimplemented lookup bias: ${lookupBiasToString(
generatedPosition.bias,
)}`,
);
}
const mappings = this._decodeAndCacheMappings();
const index = greatestLowerBound(
mappings,
{line, column},
(position, mapping) => {
if (position.line === mapping.generatedLine) {
return get0(sub(position.column, mapping.generatedColumn));
}
return get0(sub(position.line, mapping.generatedLine));
},
);
if (
index != null &&
mappings[index].generatedLine === generatedPosition.line
) {
const mapping = mappings[index];
return {
source: mapping.source,
name: mapping.name,
line: mapping.originalLine,
column: mapping.originalColumn,
};
}
return {...EMPTY_POSITION};
}
*_decodeMappings() {
let generatedLine = FIRST_LINE;
let generatedColumn = FIRST_COLUMN;
let originalLine = FIRST_LINE;
let originalColumn = FIRST_COLUMN;
let nameIndex = add0(0);
let sourceIndex = add0(0);
const normalizedSources = this._normalizeAndCacheSources();
const {mappings: mappingsRaw, names} = this._sourceMap;
let next;
const vlqCache = new Map();
for (let i = 0; i < mappingsRaw.length; i = next) {
switch (mappingsRaw[i]) {
case ';':
generatedLine = inc(generatedLine);
generatedColumn = FIRST_COLUMN;
/* falls through */
case ',':
next = i + 1;
continue;
}
findNext: for (next = i + 1; next < mappingsRaw.length; ++next) {
switch (mappingsRaw[next]) {
case ';':
/* falls through */
case ',':
break findNext;
}
}
const mappingRaw = mappingsRaw.slice(i, next);
let decodedVlqValues;
if (vlqCache.has(mappingRaw)) {
decodedVlqValues = vlqCache.get(mappingRaw);
} else {
decodedVlqValues = decodeVlq(mappingRaw);
vlqCache.set(mappingRaw, decodedVlqValues);
}
invariant(Array.isArray(decodedVlqValues), 'Decoding VLQ tuple failed');
const [
generatedColumnDelta,
sourceIndexDelta,
originalLineDelta,
originalColumnDelta,
nameIndexDelta,
] = decodedVlqValues;
decodeVlq(mappingRaw);
invariant(generatedColumnDelta != null, 'Invalid generated column delta');
generatedColumn = add(generatedColumn, generatedColumnDelta);
const mapping: Mapping = {
generatedLine,
generatedColumn,
source: null,
name: null,
originalLine: null,
originalColumn: null,
};
if (sourceIndexDelta != null) {
sourceIndex = add(sourceIndex, sourceIndexDelta);
mapping.source = normalizedSources[get0(sourceIndex)];
invariant(originalLineDelta != null, 'Invalid original line delta');
invariant(originalColumnDelta != null, 'Invalid original column delta');
originalLine = add(originalLine, originalLineDelta);
originalColumn = add(originalColumn, originalColumnDelta);
mapping.originalLine = originalLine;
mapping.originalColumn = originalColumn;
if (nameIndexDelta != null) {
nameIndex = add(nameIndex, nameIndexDelta);
mapping.name = names[get0(nameIndex)];
}
}
yield mapping;
}
}
_normalizeAndCacheSources(): $ReadOnlyArray<string> {
if (!this._normalizedSources) {
this._normalizedSources = this._sourceMap.sources.map(source =>
normalizeSourcePath(source, this._sourceMap),
);
}
return this._normalizedSources;
}
_decodeAndCacheMappings(): $ReadOnlyArray<Mapping> {
if (!this._decodedMappings) {
this._decodedMappings = [...this._decodeMappings()];
}
return this._decodedMappings;
}
generatedMappings(): Iterable<Mapping> {
return this._decodeAndCacheMappings();
}
}
module.exports = MappingsConsumer;

View File

@ -0,0 +1,201 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
"use strict";
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
})
);
}
ownKeys.forEach(function(key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _slicedToArray(arr, i) {
return (
_arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest()
);
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (
var _i = arr[Symbol.iterator](), _s;
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
const AbstractConsumer = require("./AbstractConsumer");
const createConsumer = require("./createConsumer");
const _require = require("./constants"),
FIRST_COLUMN = _require.FIRST_COLUMN,
FIRST_LINE = _require.FIRST_LINE,
EMPTY_POSITION = _require.EMPTY_POSITION;
const _require2 = require("./positionMath"),
subtractOffsetFromPosition = _require2.subtractOffsetFromPosition;
const _require3 = require("./search"),
greatestLowerBound = _require3.greatestLowerBound;
const _require4 = require("ob1"),
add = _require4.add,
get0 = _require4.get0,
get1 = _require4.get1,
add0 = _require4.add0,
sub1 = _require4.sub1,
sub = _require4.sub;
/**
* A source map consumer that supports "indexed" source maps (that have a
* `sections` field and no top-level mappings).
*/
class SectionsConsumer extends AbstractConsumer {
constructor(sourceMap) {
super(sourceMap);
this._consumers = sourceMap.sections.map((section, index) => {
const generatedOffset = {
lines: add0(section.offset.line),
columns: add0(section.offset.column)
};
const consumer = createConsumer(section.map);
return [generatedOffset, consumer];
});
}
originalPositionFor(generatedPosition) {
const _ref = this._consumerForPosition(generatedPosition) || [],
_ref2 = _slicedToArray(_ref, 2),
generatedOffset = _ref2[0],
consumer = _ref2[1];
if (!consumer) {
return EMPTY_POSITION;
}
return consumer.originalPositionFor(
subtractOffsetFromPosition(generatedPosition, generatedOffset)
);
}
*generatedMappings() {
for (const _ref3 of this._consumers) {
var _ref4 = _slicedToArray(_ref3, 2);
const generatedOffset = _ref4[0];
const consumer = _ref4[1];
let first = true;
for (const mapping of consumer.generatedMappings()) {
if (
first &&
(get1(mapping.generatedLine) > 1 || get0(mapping.generatedColumn) > 0)
) {
yield {
generatedLine: FIRST_LINE,
generatedColumn: FIRST_COLUMN,
source: null,
name: null,
originalLine: null,
originalColumn: null
};
}
first = false;
yield _objectSpread({}, mapping, {
generatedLine: add(mapping.generatedLine, generatedOffset.lines),
generatedColumn: add(mapping.generatedColumn, generatedOffset.columns)
});
}
}
}
_consumerForPosition(generatedPosition) {
const line = generatedPosition.line,
column = generatedPosition.column;
if (line == null || column == null) {
return null;
}
const index = greatestLowerBound(
this._consumers,
generatedPosition,
(position, _ref5) => {
let _ref6 = _slicedToArray(_ref5, 1),
offset = _ref6[0];
const line0 = sub1(line);
const column0 = column;
if (line0 === offset.lines) {
return get0(sub(column0, offset.columns));
}
return get0(sub(line0, offset.lines));
}
);
return index != null ? this._consumers[index] : null;
}
}
module.exports = SectionsConsumer;

View File

@ -0,0 +1,116 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
const AbstractConsumer = require('./AbstractConsumer');
const createConsumer = require('./createConsumer');
const {FIRST_COLUMN, FIRST_LINE, EMPTY_POSITION} = require('./constants');
const {subtractOffsetFromPosition} = require('./positionMath');
const {greatestLowerBound} = require('./search');
const {add, get0, get1, add0, sub1, sub} = require('ob1');
import type {IndexMap} from '../source-map';
import type {
GeneratedOffset,
SourcePosition,
GeneratedPositionLookup,
Mapping,
IConsumer,
} from './types.flow';
/**
* A source map consumer that supports "indexed" source maps (that have a
* `sections` field and no top-level mappings).
*/
class SectionsConsumer extends AbstractConsumer implements IConsumer {
_consumers: $ReadOnlyArray<[GeneratedOffset, IConsumer]>;
constructor(sourceMap: IndexMap) {
super(sourceMap);
this._consumers = sourceMap.sections.map((section, index) => {
const generatedOffset = {
lines: add0(section.offset.line),
columns: add0(section.offset.column),
};
const consumer = createConsumer(section.map);
return [generatedOffset, consumer];
});
}
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition {
const [generatedOffset, consumer] =
this._consumerForPosition(generatedPosition) || [];
if (!consumer) {
return EMPTY_POSITION;
}
return consumer.originalPositionFor(
subtractOffsetFromPosition(generatedPosition, generatedOffset),
);
}
*generatedMappings(): Iterable<Mapping> {
for (const [generatedOffset, consumer] of this._consumers) {
let first = true;
for (const mapping of consumer.generatedMappings()) {
if (
first &&
(get1(mapping.generatedLine) > 1 || get0(mapping.generatedColumn) > 0)
) {
yield {
generatedLine: FIRST_LINE,
generatedColumn: FIRST_COLUMN,
source: null,
name: null,
originalLine: null,
originalColumn: null,
};
}
first = false;
yield {
...mapping,
generatedLine: add(mapping.generatedLine, generatedOffset.lines),
generatedColumn: add(
mapping.generatedColumn,
generatedOffset.columns,
),
};
}
}
}
_consumerForPosition(
generatedPosition: GeneratedPositionLookup,
): ?[GeneratedOffset, IConsumer] {
const {line, column} = generatedPosition;
if (line == null || column == null) {
return null;
}
const index = greatestLowerBound(
this._consumers,
generatedPosition,
(position, [offset]) => {
const line0 = sub1(line);
const column0 = column;
if (line0 === offset.lines) {
return get0(sub(column0, offset.columns));
}
return get0(sub(line0, offset.lines));
},
);
return index != null ? this._consumers[index] : null;
}
}
module.exports = SectionsConsumer;

View File

@ -0,0 +1,47 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
"use strict";
const _require = require("ob1"),
add0 = _require.add0,
add1 = _require.add1;
const FIRST_COLUMN = add0(0);
const FIRST_LINE = add1(0);
const GENERATED_ORDER = "GENERATED_ORDER";
const ORIGINAL_ORDER = "ORIGINAL_ORDER";
const GREATEST_LOWER_BOUND = "GREATEST_LOWER_BOUND";
const LEAST_UPPER_BOUND = "LEAST_UPPER_BOUND";
const EMPTY_POSITION = Object.freeze({
source: null,
name: null,
line: null,
column: null
});
function iterationOrderToString(x) {
return x;
}
function lookupBiasToString(x) {
return x;
}
module.exports = {
FIRST_COLUMN,
FIRST_LINE,
GENERATED_ORDER,
ORIGINAL_ORDER,
GREATEST_LOWER_BOUND,
LEAST_UPPER_BOUND,
EMPTY_POSITION,
iterationOrderToString,
lookupBiasToString
};

View File

@ -0,0 +1,52 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
const {add0, add1} = require('ob1');
import type {Number0, Number1} from 'ob1';
const FIRST_COLUMN: Number0 = add0(0);
const FIRST_LINE: Number1 = add1(0);
export opaque type IterationOrder = 'GENERATED_ORDER' | 'ORIGINAL_ORDER';
const GENERATED_ORDER: IterationOrder = 'GENERATED_ORDER';
const ORIGINAL_ORDER: IterationOrder = 'ORIGINAL_ORDER';
export opaque type LookupBias = 'GREATEST_LOWER_BOUND' | 'LEAST_UPPER_BOUND';
const GREATEST_LOWER_BOUND: LookupBias = 'GREATEST_LOWER_BOUND';
const LEAST_UPPER_BOUND: LookupBias = 'LEAST_UPPER_BOUND';
const EMPTY_POSITION = Object.freeze({
source: null,
name: null,
line: null,
column: null,
});
function iterationOrderToString(x: IterationOrder): string {
return x;
}
function lookupBiasToString(x: LookupBias): string {
return x;
}
module.exports = {
FIRST_COLUMN,
FIRST_LINE,
GENERATED_ORDER,
ORIGINAL_ORDER,
GREATEST_LOWER_BOUND,
LEAST_UPPER_BOUND,
EMPTY_POSITION,
iterationOrderToString,
lookupBiasToString,
};

View File

@ -0,0 +1,31 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
"use strict";
const invariant = require("invariant");
function createConsumer(sourceMap) {
invariant(
sourceMap.version === "3" || sourceMap.version === 3,
`Unrecognized source map format version: ${sourceMap.version}`
);
const MappingsConsumer = require("./MappingsConsumer");
const SectionsConsumer = require("./SectionsConsumer"); // eslint-disable-next-line lint/strictly-null
if (sourceMap.mappings === undefined) {
return new SectionsConsumer(sourceMap);
}
return new MappingsConsumer(sourceMap);
}
module.exports = createConsumer;

View File

@ -0,0 +1,33 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
const invariant = require('invariant');
import type {MixedSourceMap} from '../source-map';
import type {IConsumer} from './types.flow';
function createConsumer(sourceMap: MixedSourceMap): IConsumer {
invariant(
(sourceMap.version: mixed) === '3' || sourceMap.version === 3,
`Unrecognized source map format version: ${sourceMap.version}`,
);
const MappingsConsumer = require('./MappingsConsumer');
const SectionsConsumer = require('./SectionsConsumer');
// eslint-disable-next-line lint/strictly-null
if (sourceMap.mappings === undefined) {
return new SectionsConsumer(sourceMap);
}
return new MappingsConsumer(sourceMap);
}
module.exports = createConsumer;

14
node_modules/metro-source-map/src/Consumer/index.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
"use strict"; // Implements an API-compatible subset of source-map's `SourceMapConsumer`.
const DelegatingConsumer = require("./DelegatingConsumer");
module.exports = DelegatingConsumer;

View File

@ -0,0 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
// Implements an API-compatible subset of source-map's `SourceMapConsumer`.
const DelegatingConsumer = require('./DelegatingConsumer');
module.exports = DelegatingConsumer;

View File

@ -0,0 +1,33 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
"use strict"; // flowlint-next-line untyped-import:off
const util = require("source-map/lib/util"); // Extracted from source-map@0.5.6's SourceMapConsumer
function normalizeSourcePath(sourceInput, map) {
const sourceRoot = map.sourceRoot;
let source = sourceInput;
source = String(source); // Some source maps produce relative source paths like "./foo.js" instead of
// "foo.js". Normalize these first so that future comparisons will succeed.
// See bugzil.la/1090768.
source = util.normalize(source); // Always ensure that absolute sources are internally stored relative to
// the source root, if the source root is absolute. Not doing this would
// be particularly problematic when the source root is a prefix of the
// source (valid, but why??). See github issue #199 and bugzil.la/1188982.
source =
sourceRoot != null && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
? util.relative(sourceRoot, source)
: source;
return source;
}
module.exports = normalizeSourcePath;

View File

@ -0,0 +1,41 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
// flowlint-next-line untyped-import:off
const util = require('source-map/lib/util');
// Extracted from source-map@0.5.6's SourceMapConsumer
function normalizeSourcePath(
sourceInput: string,
map: {+sourceRoot?: ?string, ...},
): string {
const {sourceRoot} = map;
let source = sourceInput;
source = String(source);
// Some source maps produce relative source paths like "./foo.js" instead of
// "foo.js". Normalize these first so that future comparisons will succeed.
// See bugzil.la/1090768.
source = util.normalize(source);
// Always ensure that absolute sources are internally stored relative to
// the source root, if the source root is absolute. Not doing this would
// be particularly problematic when the source root is a prefix of the
// source (valid, but why??). See github issue #199 and bugzil.la/1188982.
source =
sourceRoot != null && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
? util.relative(sourceRoot, source)
: source;
return source;
}
module.exports = normalizeSourcePath;

View File

@ -0,0 +1,65 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
"use strict";
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
})
);
}
ownKeys.forEach(function(key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const _require = require("ob1"),
add = _require.add,
neg = _require.neg;
function shiftPositionByOffset(pos, offset) {
return _objectSpread({}, pos, {
line: pos.line != null ? add(pos.line, offset.lines) : null,
column: pos.column != null ? add(pos.column, offset.columns) : null
});
}
function subtractOffsetFromPosition(pos, offset) {
return shiftPositionByOffset(pos, {
lines: neg(offset.lines),
columns: neg(offset.columns)
});
}
module.exports = {
shiftPositionByOffset,
subtractOffsetFromPosition
};

View File

@ -0,0 +1,45 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
const {add, neg} = require('ob1');
import type {GeneratedOffset} from './types.flow';
import type {Number0, Number1} from 'ob1';
function shiftPositionByOffset<
T: {
+line: ?Number1,
+column: ?Number0,
...
},
>(pos: T, offset: GeneratedOffset): T {
return {
...pos,
line: pos.line != null ? add(pos.line, offset.lines) : null,
column: pos.column != null ? add(pos.column, offset.columns) : null,
};
}
function subtractOffsetFromPosition<
T: {
+line: ?Number1,
+column: ?Number0,
...
},
>(pos: T, offset: GeneratedOffset): T {
return shiftPositionByOffset(pos, {
lines: neg(offset.lines),
columns: neg(offset.columns),
});
}
module.exports = {shiftPositionByOffset, subtractOffsetFromPosition};

36
node_modules/metro-source-map/src/Consumer/search.js generated vendored Normal file
View File

@ -0,0 +1,36 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
"use strict";
function greatestLowerBound(elements, target, comparator) {
let first = 0;
let it = 0;
let count = elements.length;
let step;
while (count > 0) {
it = first;
step = Math.floor(count / 2);
it = it + step;
if (comparator(target, elements[it]) >= 0) {
first = ++it;
count = count - (step + 1);
} else {
count = step;
}
}
return first ? first - 1 : null;
}
module.exports = {
greatestLowerBound
};

View File

@ -0,0 +1,36 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
function greatestLowerBound<T, U>(
elements: $ReadOnlyArray<T>,
target: U,
comparator: (U, T) => number,
): ?number {
let first = 0;
let it = 0;
let count = elements.length;
let step;
while (count > 0) {
it = first;
step = Math.floor(count / 2);
it = it + step;
if (comparator(target, elements[it]) >= 0) {
first = ++it;
count = count - (step + 1);
} else {
count = step;
}
}
return first ? first - 1 : null;
}
module.exports = {greatestLowerBound};

View File

@ -0,0 +1,13 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict-local
* @format
*/
// NOTE: The linter and formatter are fighting over the following lint rule.
/* eslint-disable flowtype/object-type-delimiter */
"use strict";

View File

@ -0,0 +1,64 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
// NOTE: The linter and formatter are fighting over the following lint rule.
/* eslint-disable flowtype/object-type-delimiter */
'use strict';
import type {IterationOrder, LookupBias} from './constants';
import type {Number0, Number1} from 'ob1';
export type {IterationOrder, LookupBias};
export type GeneratedOffset = {|+lines: Number0, +columns: Number0|};
export type SourcePosition = {
+source: ?string,
+line: ?Number1,
+column: ?Number0,
+name: ?string,
...
};
export type GeneratedPosition = {
+line: Number1,
+column: Number0,
...
};
export type GeneratedPositionLookup = {
+line: ?Number1,
+column: ?Number0,
+bias?: LookupBias,
...
};
export type Mapping = {
source: ?string,
generatedLine: Number1,
generatedColumn: Number0,
originalLine: ?Number1,
originalColumn: ?Number0,
name: ?string,
...
};
export interface IConsumer {
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition;
generatedMappings(): Iterable<Mapping>;
eachMapping(
callback: (mapping: Mapping) => mixed,
context?: mixed,
order?: IterationOrder,
): void;
// flowlint unsafe-getters-setters:off
get file(): ?string;
}

266
node_modules/metro-source-map/src/Generator.js generated vendored Normal file
View File

@ -0,0 +1,266 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
"use strict";
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
})
);
}
ownKeys.forEach(function(key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const B64Builder = require("./B64Builder");
/**
* Generates a source map from raw mappings.
*
* Raw mappings are a set of 2, 4, or five elements:
*
* - line and column number in the generated source
* - line and column number in the original source
* - symbol name in the original source
*
* Mappings have to be passed in the order appearance in the generated source.
*/
class Generator {
constructor() {
this.builder = new B64Builder();
this.last = {
generatedColumn: 0,
generatedLine: 1,
// lines are passed in 1-indexed
name: 0,
source: 0,
sourceColumn: 0,
sourceLine: 1
};
this.names = new IndexedSet();
this.source = -1;
this.sources = [];
this.sourcesContent = [];
this.x_facebook_sources = [];
}
/**
* Mark the beginning of a new source file.
*/
startFile(file, code, functionMap) {
this.source = this.sources.push(file) - 1;
this.sourcesContent.push(code);
this.x_facebook_sources.push(functionMap ? [functionMap] : null);
}
/**
* Mark the end of the current source file
*/
endFile() {
this.source = -1;
}
/**
* Adds a mapping for generated code without a corresponding source location.
*/
addSimpleMapping(generatedLine, generatedColumn) {
const last = this.last;
if (
this.source === -1 ||
(generatedLine === last.generatedLine &&
generatedColumn < last.generatedColumn) ||
generatedLine < last.generatedLine
) {
const msg =
this.source === -1
? "Cannot add mapping before starting a file with `addFile()`"
: "Mapping is for a position preceding an earlier mapping";
throw new Error(msg);
}
if (generatedLine > last.generatedLine) {
this.builder.markLines(generatedLine - last.generatedLine);
last.generatedLine = generatedLine;
last.generatedColumn = 0;
}
this.builder.startSegment(generatedColumn - last.generatedColumn);
last.generatedColumn = generatedColumn;
}
/**
* Adds a mapping for generated code with a corresponding source location.
*/
addSourceMapping(generatedLine, generatedColumn, sourceLine, sourceColumn) {
this.addSimpleMapping(generatedLine, generatedColumn);
const last = this.last;
this.builder
.append(this.source - last.source)
.append(sourceLine - last.sourceLine)
.append(sourceColumn - last.sourceColumn);
last.source = this.source;
last.sourceColumn = sourceColumn;
last.sourceLine = sourceLine;
}
/**
* Adds a mapping for code with a corresponding source location + symbol name.
*/
addNamedSourceMapping(
generatedLine,
generatedColumn,
sourceLine,
sourceColumn,
name
) {
this.addSourceMapping(
generatedLine,
generatedColumn,
sourceLine,
sourceColumn
);
const last = this.last;
const nameIndex = this.names.indexFor(name);
this.builder.append(nameIndex - last.name);
last.name = nameIndex;
}
/**
* Return the source map as object.
*/
toMap(file, options) {
let content, sourcesMetadata;
if (options && options.excludeSource) {
content = {};
} else {
content = {
sourcesContent: this.sourcesContent.slice()
};
}
if (this.hasSourcesMetadata()) {
sourcesMetadata = {
x_facebook_sources: JSON.parse(JSON.stringify(this.x_facebook_sources))
};
} else {
sourcesMetadata = {};
}
/* $FlowFixMe(>=0.111.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.111 was deployed. To see the error, delete this
* comment and run Flow. */
return _objectSpread(
{
version: 3,
file,
sources: this.sources.slice()
},
content,
sourcesMetadata,
{
names: this.names.items(),
mappings: this.builder.toString()
}
);
}
/**
* Return the source map as string.
*
* This is ~2.5x faster than calling `JSON.stringify(generator.toMap())`
*/
toString(file, options) {
let content, sourcesMetadata;
if (options && options.excludeSource) {
content = "";
} else {
content = `"sourcesContent":${JSON.stringify(this.sourcesContent)},`;
}
if (this.hasSourcesMetadata()) {
sourcesMetadata = `"x_facebook_sources":${JSON.stringify(
this.x_facebook_sources
)},`;
} else {
sourcesMetadata = "";
}
return (
"{" +
'"version":3,' +
(file ? `"file":${JSON.stringify(file)},` : "") +
`"sources":${JSON.stringify(this.sources)},` +
content +
sourcesMetadata +
`"names":${JSON.stringify(this.names.items())},` +
`"mappings":"${this.builder.toString()}"` +
"}"
);
}
/**
* Determine whether we need to write the `x_facebook_sources` field.
* If the metadata is all `null`s, we can omit the field entirely.
*/
hasSourcesMetadata() {
return this.x_facebook_sources.some(
metadata => metadata != null && metadata.some(value => value != null)
);
}
}
class IndexedSet {
constructor() {
this.map = new Map();
this.nextIndex = 0;
}
indexFor(x) {
let index = this.map.get(x);
if (index == null) {
index = this.nextIndex++;
this.map.set(x, index);
}
return index;
}
items() {
return Array.from(this.map.keys());
}
}
module.exports = Generator;

263
node_modules/metro-source-map/src/Generator.js.flow generated vendored Normal file
View File

@ -0,0 +1,263 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const B64Builder = require('./B64Builder');
import type {
BasicSourceMap,
FBSourceMetadata,
FBSourceFunctionMap,
} from './source-map';
/**
* Generates a source map from raw mappings.
*
* Raw mappings are a set of 2, 4, or five elements:
*
* - line and column number in the generated source
* - line and column number in the original source
* - symbol name in the original source
*
* Mappings have to be passed in the order appearance in the generated source.
*/
class Generator {
builder: B64Builder;
last: {|
generatedColumn: number,
generatedLine: number,
name: number,
source: number,
sourceColumn: number,
sourceLine: number,
|};
names: IndexedSet;
source: number;
sources: Array<string>;
sourcesContent: Array<?string>;
x_facebook_sources: Array<?FBSourceMetadata>;
constructor() {
this.builder = new B64Builder();
this.last = {
generatedColumn: 0,
generatedLine: 1, // lines are passed in 1-indexed
name: 0,
source: 0,
sourceColumn: 0,
sourceLine: 1,
};
this.names = new IndexedSet();
this.source = -1;
this.sources = [];
this.sourcesContent = [];
this.x_facebook_sources = [];
}
/**
* Mark the beginning of a new source file.
*/
startFile(file: string, code: string, functionMap: ?FBSourceFunctionMap) {
this.source = this.sources.push(file) - 1;
this.sourcesContent.push(code);
this.x_facebook_sources.push(functionMap ? [functionMap] : null);
}
/**
* Mark the end of the current source file
*/
endFile() {
this.source = -1;
}
/**
* Adds a mapping for generated code without a corresponding source location.
*/
addSimpleMapping(generatedLine: number, generatedColumn: number): void {
const last = this.last;
if (
this.source === -1 ||
(generatedLine === last.generatedLine &&
generatedColumn < last.generatedColumn) ||
generatedLine < last.generatedLine
) {
const msg =
this.source === -1
? 'Cannot add mapping before starting a file with `addFile()`'
: 'Mapping is for a position preceding an earlier mapping';
throw new Error(msg);
}
if (generatedLine > last.generatedLine) {
this.builder.markLines(generatedLine - last.generatedLine);
last.generatedLine = generatedLine;
last.generatedColumn = 0;
}
this.builder.startSegment(generatedColumn - last.generatedColumn);
last.generatedColumn = generatedColumn;
}
/**
* Adds a mapping for generated code with a corresponding source location.
*/
addSourceMapping(
generatedLine: number,
generatedColumn: number,
sourceLine: number,
sourceColumn: number,
): void {
this.addSimpleMapping(generatedLine, generatedColumn);
const last = this.last;
this.builder
.append(this.source - last.source)
.append(sourceLine - last.sourceLine)
.append(sourceColumn - last.sourceColumn);
last.source = this.source;
last.sourceColumn = sourceColumn;
last.sourceLine = sourceLine;
}
/**
* Adds a mapping for code with a corresponding source location + symbol name.
*/
addNamedSourceMapping(
generatedLine: number,
generatedColumn: number,
sourceLine: number,
sourceColumn: number,
name: string,
): void {
this.addSourceMapping(
generatedLine,
generatedColumn,
sourceLine,
sourceColumn,
);
const last = this.last;
const nameIndex = this.names.indexFor(name);
this.builder.append(nameIndex - last.name);
last.name = nameIndex;
}
/**
* Return the source map as object.
*/
toMap(
file?: string,
options?: {excludeSource?: boolean, ...},
): BasicSourceMap {
let content, sourcesMetadata;
if (options && options.excludeSource) {
content = {};
} else {
content = {sourcesContent: this.sourcesContent.slice()};
}
if (this.hasSourcesMetadata()) {
sourcesMetadata = {
x_facebook_sources: JSON.parse(JSON.stringify(this.x_facebook_sources)),
};
} else {
sourcesMetadata = {};
}
/* $FlowFixMe(>=0.111.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.111 was deployed. To see the error, delete this
* comment and run Flow. */
return {
version: 3,
file,
sources: this.sources.slice(),
...content,
/* $FlowFixMe(>=0.111.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.111 was deployed. To see the error, delete
* this comment and run Flow. */
...sourcesMetadata,
names: this.names.items(),
mappings: this.builder.toString(),
};
}
/**
* Return the source map as string.
*
* This is ~2.5x faster than calling `JSON.stringify(generator.toMap())`
*/
toString(file?: string, options?: {excludeSource?: boolean, ...}): string {
let content, sourcesMetadata;
if (options && options.excludeSource) {
content = '';
} else {
content = `"sourcesContent":${JSON.stringify(this.sourcesContent)},`;
}
if (this.hasSourcesMetadata()) {
sourcesMetadata = `"x_facebook_sources":${JSON.stringify(
this.x_facebook_sources,
)},`;
} else {
sourcesMetadata = '';
}
return (
'{' +
'"version":3,' +
(file ? `"file":${JSON.stringify(file)},` : '') +
`"sources":${JSON.stringify(this.sources)},` +
content +
sourcesMetadata +
`"names":${JSON.stringify(this.names.items())},` +
`"mappings":"${this.builder.toString()}"` +
'}'
);
}
/**
* Determine whether we need to write the `x_facebook_sources` field.
* If the metadata is all `null`s, we can omit the field entirely.
*/
hasSourcesMetadata(): boolean {
return this.x_facebook_sources.some(
metadata => metadata != null && metadata.some(value => value != null),
);
}
}
class IndexedSet {
map: Map<string, number>;
nextIndex: number;
constructor() {
this.map = new Map();
this.nextIndex = 0;
}
indexFor(x: string): number {
let index = this.map.get(x);
if (index == null) {
index = this.nextIndex++;
this.map.set(x, index);
}
return index;
}
items(): Array<string> {
return Array.from(this.map.keys());
}
}
module.exports = Generator;

111
node_modules/metro-source-map/src/composeSourceMaps.js generated vendored Normal file
View File

@ -0,0 +1,111 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
"use strict"; // eslint-disable-next-line lint/sort-requires
const Consumer = require("./Consumer");
const _require = require("source-map"),
SourceMapGenerator = _require.SourceMapGenerator;
// Originally based on https://github.com/jakobwesthoff/source-map-merger
function composeSourceMaps(maps) {
// NOTE: require() here to break dependency cycle
const SourceMetadataMapConsumer = require("metro-symbolicate/src/SourceMetadataMapConsumer");
if (maps.length < 1) {
throw new Error("composeSourceMaps: Expected at least one map");
}
const firstMap = maps[0];
const consumers = maps
.map(function(map) {
return new Consumer(map);
})
.reverse();
const generator = new SourceMapGenerator({
file: consumers[0].file
});
consumers[0].eachMapping(mapping => {
const original = findOriginalPosition(
consumers,
mapping.generatedLine,
mapping.generatedColumn
);
generator.addMapping({
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
},
original:
original.line != null
? {
line: original.line,
column: original.column
}
: null,
source: original.source,
name: original.name
});
});
const composedMap = generator.toJSON();
const metadataConsumer = new SourceMetadataMapConsumer(firstMap);
composedMap.x_facebook_sources = metadataConsumer.toArray(
composedMap.sources
);
const function_offsets = maps[maps.length - 1].x_hermes_function_offsets;
if (function_offsets) {
composedMap.x_hermes_function_offsets = function_offsets;
}
return composedMap;
}
function findOriginalPosition(consumers, generatedLine, generatedColumn) {
let currentLine = generatedLine;
let currentColumn = generatedColumn;
let original = {
line: null,
column: null,
source: null,
name: null
};
for (const consumer of consumers) {
if (currentLine == null || currentColumn == null) {
return {
line: null,
column: null,
source: null,
name: null
};
}
original = consumer.originalPositionFor({
line: currentLine,
column: currentColumn
});
currentLine = original.line;
currentColumn = original.column;
if (currentLine == null) {
return {
line: null,
column: null,
source: null,
name: null
};
}
}
return original;
}
module.exports = composeSourceMaps;

View File

@ -0,0 +1,121 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
// eslint-disable-next-line lint/sort-requires
const Consumer = require('./Consumer');
const {SourceMapGenerator} = require('source-map');
import type {IConsumer, MixedSourceMap} from './source-map';
import type {Number0, Number1} from 'ob1';
// Originally based on https://github.com/jakobwesthoff/source-map-merger
function composeSourceMaps(
maps: $ReadOnlyArray<MixedSourceMap>,
): MixedSourceMap {
// NOTE: require() here to break dependency cycle
const SourceMetadataMapConsumer = require('metro-symbolicate/src/SourceMetadataMapConsumer');
if (maps.length < 1) {
throw new Error('composeSourceMaps: Expected at least one map');
}
const firstMap = maps[0];
const consumers = maps
.map(function(map) {
return new Consumer(map);
})
.reverse();
const generator = new SourceMapGenerator({
file: consumers[0].file,
});
consumers[0].eachMapping(mapping => {
const original = findOriginalPosition(
consumers,
mapping.generatedLine,
mapping.generatedColumn,
);
generator.addMapping({
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn,
},
original:
original.line != null
? {
line: original.line,
column: original.column,
}
: null,
source: original.source,
name: original.name,
});
});
const composedMap = generator.toJSON();
const metadataConsumer = new SourceMetadataMapConsumer(firstMap);
composedMap.x_facebook_sources = metadataConsumer.toArray(
composedMap.sources,
);
const function_offsets = maps[maps.length - 1].x_hermes_function_offsets;
if (function_offsets) {
composedMap.x_hermes_function_offsets = function_offsets;
}
return composedMap;
}
function findOriginalPosition(
consumers: $ReadOnlyArray<IConsumer>,
generatedLine: Number1,
generatedColumn: Number0,
): {
line: ?number,
column: ?number,
source: ?string,
name: ?string,
...
} {
let currentLine = generatedLine;
let currentColumn = generatedColumn;
let original = {
line: null,
column: null,
source: null,
name: null,
};
for (const consumer of consumers) {
if (currentLine == null || currentColumn == null) {
return {line: null, column: null, source: null, name: null};
}
original = consumer.originalPositionFor({
line: currentLine,
column: currentColumn,
});
currentLine = original.line;
currentColumn = original.column;
if (currentLine == null) {
return {
line: null,
column: null,
source: null,
name: null,
};
}
}
return original;
}
module.exports = composeSourceMaps;

176
node_modules/metro-source-map/src/encode.js generated vendored Normal file
View File

@ -0,0 +1,176 @@
/**
* Portions Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
/**
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://git.io/vymuA
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @copyright
*/
/* eslint-disable no-bitwise */
"use strict"; // A map of values to characters for the b64 encoding
const CHAR_MAP = [
0x41,
0x42,
0x43,
0x44,
0x45,
0x46,
0x47,
0x48,
0x49,
0x4a,
0x4b,
0x4c,
0x4d,
0x4e,
0x4f,
0x50,
0x51,
0x52,
0x53,
0x54,
0x55,
0x56,
0x57,
0x58,
0x59,
0x5a,
0x61,
0x62,
0x63,
0x64,
0x65,
0x66,
0x67,
0x68,
0x69,
0x6a,
0x6b,
0x6c,
0x6d,
0x6e,
0x6f,
0x70,
0x71,
0x72,
0x73,
0x74,
0x75,
0x76,
0x77,
0x78,
0x79,
0x7a,
0x30,
0x31,
0x32,
0x33,
0x34,
0x35,
0x36,
0x37,
0x38,
0x39,
0x2b,
0x2f
]; // A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
const VLQ_BASE_SHIFT = 5; // binary: 100000
const VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111
const VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000
const VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(value) {
return value < 0 ? (-value << 1) + 1 : (value << 1) + 0;
}
/**
* Encodes a number to base64 VLQ format and appends it to the passed-in buffer
*
* DON'T USE COMPOUND OPERATORS (eg `>>>=`) ON `let`-DECLARED VARIABLES!
* V8 WILL DEOPTIMIZE THIS FUNCTION AND MAP CREATION WILL BE 25% SLOWER!
*
* DON'T ADD MORE COMMENTS TO THIS FUNCTION TO KEEP ITS LENGTH SHORT ENOUGH FOR
* V8 OPTIMIZATION!
*/
function encode(value, buffer, position) {
let vlq = toVLQSigned(value);
let digit;
do {
digit = vlq & VLQ_BASE_MASK;
vlq = vlq >>> VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit = digit | VLQ_CONTINUATION_BIT;
}
buffer[position++] = CHAR_MAP[digit];
} while (vlq > 0);
return position;
}
module.exports = encode;

180
node_modules/metro-source-map/src/encode.js.flow generated vendored Normal file
View File

@ -0,0 +1,180 @@
/**
* Portions Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
/**
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://git.io/vymuA
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @copyright
*/
/* eslint-disable no-bitwise */
'use strict';
// A map of values to characters for the b64 encoding
const CHAR_MAP = [
0x41,
0x42,
0x43,
0x44,
0x45,
0x46,
0x47,
0x48,
0x49,
0x4a,
0x4b,
0x4c,
0x4d,
0x4e,
0x4f,
0x50,
0x51,
0x52,
0x53,
0x54,
0x55,
0x56,
0x57,
0x58,
0x59,
0x5a,
0x61,
0x62,
0x63,
0x64,
0x65,
0x66,
0x67,
0x68,
0x69,
0x6a,
0x6b,
0x6c,
0x6d,
0x6e,
0x6f,
0x70,
0x71,
0x72,
0x73,
0x74,
0x75,
0x76,
0x77,
0x78,
0x79,
0x7a,
0x30,
0x31,
0x32,
0x33,
0x34,
0x35,
0x36,
0x37,
0x38,
0x39,
0x2b,
0x2f,
];
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
const VLQ_BASE_SHIFT = 5;
// binary: 100000
const VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
const VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
const VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(value) {
return value < 0 ? (-value << 1) + 1 : (value << 1) + 0;
}
/**
* Encodes a number to base64 VLQ format and appends it to the passed-in buffer
*
* DON'T USE COMPOUND OPERATORS (eg `>>>=`) ON `let`-DECLARED VARIABLES!
* V8 WILL DEOPTIMIZE THIS FUNCTION AND MAP CREATION WILL BE 25% SLOWER!
*
* DON'T ADD MORE COMMENTS TO THIS FUNCTION TO KEEP ITS LENGTH SHORT ENOUGH FOR
* V8 OPTIMIZATION!
*/
function encode(value: number, buffer: Buffer, position: number): number {
let vlq = toVLQSigned(value);
let digit;
do {
digit = vlq & VLQ_BASE_MASK;
vlq = vlq >>> VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit = digit | VLQ_CONTINUATION_BIT;
}
buffer[position++] = CHAR_MAP[digit];
} while (vlq > 0);
return position;
}
module.exports = encode;

View File

@ -0,0 +1,530 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
"use strict";
var _traverse = _interopRequireDefault(require("@babel/traverse"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _slicedToArray(arr, i) {
return (
_arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest()
);
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (
var _i = arr[Symbol.iterator](), _s;
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _toConsumableArray(arr) {
return (
_arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread()
);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function _iterableToArray(iter) {
if (
Symbol.iterator in Object(iter) ||
Object.prototype.toString.call(iter) === "[object Arguments]"
)
return Array.from(iter);
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++)
arr2[i] = arr[i];
return arr2;
}
}
const B64Builder = require("./B64Builder");
const fsPath = require("path");
const t = require("@babel/types");
/**
* Generate a map of source positions to function names. The names are meant to
* describe the stack frame in an error trace and may contain more contextual
* information than just the actual name of the function.
*
* The output is encoded for use in a source map. For details about the format,
* see MappingEncoder below.
*/
function generateFunctionMap(ast, context) {
const encoder = new MappingEncoder();
forEachMapping(ast, context, mapping => encoder.push(mapping));
return encoder.getResult();
}
/**
* Same as generateFunctionMap, but returns the raw array of mappings instead
* of encoding it for use in a source map.
*
* Lines are 1-based and columns are 0-based.
*/
function generateFunctionMappingsArray(ast, context) {
const mappings = [];
forEachMapping(ast, context, mapping => {
mappings.push(mapping);
});
return mappings;
}
/**
* Traverses a Babel AST and calls the supplied callback with function name
* mappings, one at a time.
*/
function forEachMapping(ast, context, pushMapping) {
const nameStack = [];
let tailPos = {
line: 1,
column: 0
};
let tailName = null;
function advanceToPos(pos) {
if (tailPos && positionGreater(pos, tailPos)) {
const name = nameStack[0].name; // We always have at least Program
if (name !== tailName) {
pushMapping({
name,
start: {
line: tailPos.line,
column: tailPos.column
}
});
tailName = name;
}
}
tailPos = pos;
}
function pushFrame(name, loc) {
advanceToPos(loc.start);
nameStack.unshift({
name,
loc
});
}
function popFrame() {
const top = nameStack[0];
if (top) {
const loc = top.loc;
advanceToPos(loc.end);
nameStack.shift();
}
}
if (!context) {
context = {};
}
const basename = context.filename
? fsPath.basename(context.filename).replace(/\..+$/, "")
: null;
(0, _traverse.default)(ast, {
"Function|Program|Class": {
enter(path) {
let name = getNameForPath(path);
if (basename) {
name = removeNamePrefix(name, basename);
}
pushFrame(name, path.node.loc);
},
exit(path) {
popFrame();
}
}
});
}
const ANONYMOUS_NAME = "<anonymous>";
const CALLEES_TO_SKIP = ["Object.freeze"];
/**
* Derive a contextual name for the given AST node (Function, Program, Class or
* ObjectExpression).
*/
function getNameForPath(path) {
const node = path.node,
parent = path.parent,
parentPath = path.parentPath;
if (t.isProgram(node)) {
return "<global>";
}
let id = path.id; // has an `id` so we don't need to infer one
if (node.id) {
return node.id.name;
}
let propertyPath;
let kind = "";
if (t.isObjectMethod(node) || t.isClassMethod(node)) {
id = node.key;
if (node.kind !== "method" && node.kind !== "constructor") {
kind = node.kind;
}
propertyPath = path;
} else if (t.isObjectProperty(parent) || t.isClassProperty(parent)) {
// { foo() {} };
id = parent.key;
propertyPath = parentPath;
} else if (t.isVariableDeclarator(parent)) {
// let foo = function () {};
id = parent.id;
} else if (t.isAssignmentExpression(parent)) {
// foo = function () {};
id = parent.left;
} else if (t.isJSXExpressionContainer(parent)) {
if (t.isJSXElement(parentPath.parentPath.node)) {
// <foo>{function () {}}</foo>
const openingElement = parentPath.parentPath.node.openingElement;
id = t.JSXMemberExpression(
t.JSXMemberExpression(openingElement.name, t.JSXIdentifier("props")),
t.JSXIdentifier("children")
);
} else if (t.isJSXAttribute(parentPath.parentPath.node)) {
// <foo bar={function () {}} />
const openingElement = parentPath.parentPath.parentPath.node;
const prop = parentPath.parentPath.node;
id = t.JSXMemberExpression(
t.JSXMemberExpression(openingElement.name, t.JSXIdentifier("props")),
prop.name
);
}
}
let name = getNameFromId(id);
if (name == null) {
if (t.isCallExpression(parent) || t.isNewExpression(parent)) {
// foo(function () {})
const argIndex = parent.arguments.indexOf(node);
if (argIndex !== -1) {
const calleeName = getNameFromId(parent.callee); // var f = Object.freeze(function () {})
if (CALLEES_TO_SKIP.indexOf(calleeName) !== -1) {
return getNameForPath(parentPath);
}
if (calleeName) {
return `${calleeName}$argument_${argIndex}`;
}
}
}
return ANONYMOUS_NAME;
}
if (kind) {
name = kind + "__" + name;
}
if (propertyPath) {
if (t.isClassBody(propertyPath.parent)) {
const className = getNameForPath(propertyPath.parentPath.parentPath);
if (className !== ANONYMOUS_NAME) {
const separator = propertyPath.node.static ? "." : "#";
name = className + separator + name;
}
} else if (t.isObjectExpression(propertyPath.parent)) {
const objectName = getNameForPath(propertyPath.parentPath);
if (objectName !== ANONYMOUS_NAME) {
name = objectName + "." + name;
}
}
}
return name;
}
function isAnyMemberExpression(node) {
return t.isMemberExpression(node) || t.isJSXMemberExpression(node);
}
function isAnyIdentifier(node) {
return t.isIdentifier(node) || t.isJSXIdentifier(node);
}
function getNameFromId(id) {
const parts = getNamePartsFromId(id);
if (!parts.length) {
return null;
}
if (parts.length > 5) {
return (
parts[0] +
"." +
parts[1] +
"..." +
parts[parts.length - 2] +
"." +
parts[parts.length - 1]
);
}
return parts.join(".");
}
function getNamePartsFromId(id) {
if (!id) {
return [];
}
if (t.isCallExpression(id) || t.isNewExpression(id)) {
return getNamePartsFromId(id.callee);
}
if (t.isTypeCastExpression(id)) {
return getNamePartsFromId(id.expression);
}
let name;
if (isAnyIdentifier(id)) {
name = id.name;
} else if (t.isNullLiteral(id)) {
name = "null";
} else if (t.isRegExpLiteral(id)) {
name = `_${id.pattern}_${id.flags}`;
} else if (t.isTemplateLiteral(id)) {
name = id.quasis.map(quasi => quasi.value.raw).join("");
} else if (t.isLiteral(id) && id.value != null) {
name = id.value + "";
}
if (name != null) {
return [t.toBindingIdentifierName(name)];
}
if (t.isImport(id)) {
name = "import";
}
if (name != null) {
return [name];
}
if (isAnyMemberExpression(id)) {
if (
isAnyIdentifier(id.object) &&
id.object.name === "Symbol" &&
(isAnyIdentifier(id.property) || t.isLiteral(id.property))
) {
const propertyName = getNameFromId(id.property);
if (propertyName) {
name = "@@" + propertyName;
}
} else {
const propertyName = getNamePartsFromId(id.property);
if (propertyName.length) {
const objectName = getNamePartsFromId(id.object);
if (objectName.length) {
return _toConsumableArray(objectName).concat(
_toConsumableArray(propertyName)
);
} else {
return propertyName;
}
}
}
}
return name ? [name] : [];
}
const DELIMITER_START_RE = /^[^A-Za-z0-9_$@]+/;
/**
* Strip the given prefix from `name`, if it occurs there, plus any delimiter
* characters that follow (of which at least one is required). If an empty
* string would be returned, return the original name instead.
*/
function removeNamePrefix(name, namePrefix) {
if (!namePrefix.length || !name.startsWith(namePrefix)) {
return name;
}
const shortenedName = name.substr(namePrefix.length);
const _ref = shortenedName.match(DELIMITER_START_RE) || [],
_ref2 = _slicedToArray(_ref, 1),
delimiterMatch = _ref2[0];
if (delimiterMatch) {
return shortenedName.substr(delimiterMatch.length) || name;
}
return name;
}
/**
* Encodes function name mappings as deltas in a Base64 VLQ format inspired by
* the standard source map format.
*
* Mappings on different lines are separated with a single `;` (even if there
* are multiple intervening lines).
* Mappings on the same line are separated with `,`.
*
* The first mapping of a line has the fields:
* [column delta, name delta, line delta]
*
* where the column delta is relative to the beginning of the line, the name
* delta is relative to the previously occurring name, and the line delta is
* relative to the previously occurring line.
*
* The 2...nth other mappings of a line have the fields:
* [column delta, name delta]
*
* where both fields are relative to their previous running values. The line
* delta is omitted since it is always 0 by definition.
*
* Lines and columns are both 0-based in the serialised format. In memory,
* lines are 1-based while columns are 0-based.
*/
class MappingEncoder {
constructor() {
this._namesMap = new Map();
this._names = [];
this._line = new RelativeValue(1);
this._column = new RelativeValue(0);
this._nameIndex = new RelativeValue(0);
this._mappings = new B64Builder();
}
getResult() {
return {
names: this._names,
mappings: this._mappings.toString()
};
}
push(_ref3) {
let name = _ref3.name,
start = _ref3.start;
let nameIndex = this._namesMap.get(name);
if (typeof nameIndex !== "number") {
nameIndex = this._names.length;
this._names[nameIndex] = name;
this._namesMap.set(name, nameIndex);
}
const lineDelta = this._line.next(start.line);
const firstOfLine = this._mappings.pos === 0 || lineDelta > 0;
if (lineDelta > 0) {
// The next entry will have the line offset, so emit just one semicolon.
this._mappings.markLines(1);
this._column.reset(0);
}
this._mappings.startSegment(this._column.next(start.column));
this._mappings.append(this._nameIndex.next(nameIndex));
if (firstOfLine) {
this._mappings.append(lineDelta);
}
}
}
class RelativeValue {
constructor() {
let value =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
this.reset(value);
}
next(absoluteValue) {
const delta = absoluteValue - this._value;
this._value = absoluteValue;
return delta;
}
reset() {
let value =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
this._value = value;
}
}
function positionGreater(x, y) {
return x.line > y.line || (x.line === y.line && x.column > y.column);
}
module.exports = {
generateFunctionMap,
generateFunctionMappingsArray
};

View File

@ -0,0 +1,429 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const B64Builder = require('./B64Builder');
const fsPath = require('path');
const t = require('@babel/types');
import type {FBSourceFunctionMap} from './source-map';
import type {Ast} from '@babel/core';
import traverse from '@babel/traverse';
import type {Path} from '@babel/traverse';
type Position = {
line: number,
column: number,
...
};
type RangeMapping = {
name: string,
start: Position,
...
};
type Context = {filename?: string, ...};
/**
* Generate a map of source positions to function names. The names are meant to
* describe the stack frame in an error trace and may contain more contextual
* information than just the actual name of the function.
*
* The output is encoded for use in a source map. For details about the format,
* see MappingEncoder below.
*/
function generateFunctionMap(ast: Ast, context?: Context): FBSourceFunctionMap {
const encoder = new MappingEncoder();
forEachMapping(ast, context, mapping => encoder.push(mapping));
return encoder.getResult();
}
/**
* Same as generateFunctionMap, but returns the raw array of mappings instead
* of encoding it for use in a source map.
*
* Lines are 1-based and columns are 0-based.
*/
function generateFunctionMappingsArray(
ast: Ast,
context?: Context,
): $ReadOnlyArray<RangeMapping> {
const mappings = [];
forEachMapping(ast, context, mapping => {
mappings.push(mapping);
});
return mappings;
}
/**
* Traverses a Babel AST and calls the supplied callback with function name
* mappings, one at a time.
*/
function forEachMapping(
ast: Ast,
context: ?Context,
pushMapping: RangeMapping => void,
) {
const nameStack = [];
let tailPos = {line: 1, column: 0};
let tailName = null;
function advanceToPos(pos) {
if (tailPos && positionGreater(pos, tailPos)) {
const name = nameStack[0].name; // We always have at least Program
if (name !== tailName) {
pushMapping({
name,
start: {line: tailPos.line, column: tailPos.column},
});
tailName = name;
}
}
tailPos = pos;
}
function pushFrame(name, loc) {
advanceToPos(loc.start);
nameStack.unshift({name, loc});
}
function popFrame() {
const top = nameStack[0];
if (top) {
const {loc} = top;
advanceToPos(loc.end);
nameStack.shift();
}
}
if (!context) {
context = {};
}
const basename = context.filename
? fsPath.basename(context.filename).replace(/\..+$/, '')
: null;
traverse(ast, {
'Function|Program|Class': {
enter(path) {
let name = getNameForPath(path);
if (basename) {
name = removeNamePrefix(name, basename);
}
pushFrame(name, path.node.loc);
},
exit(path) {
popFrame();
},
},
});
}
const ANONYMOUS_NAME = '<anonymous>';
const CALLEES_TO_SKIP = ['Object.freeze'];
/**
* Derive a contextual name for the given AST node (Function, Program, Class or
* ObjectExpression).
*/
function getNameForPath(path: Path): string {
const {node, parent, parentPath} = path;
if (t.isProgram(node)) {
return '<global>';
}
let {id} = path;
// has an `id` so we don't need to infer one
if (node.id) {
return node.id.name;
}
let propertyPath;
let kind = '';
if (t.isObjectMethod(node) || t.isClassMethod(node)) {
id = node.key;
if (node.kind !== 'method' && node.kind !== 'constructor') {
kind = node.kind;
}
propertyPath = path;
} else if (t.isObjectProperty(parent) || t.isClassProperty(parent)) {
// { foo() {} };
id = parent.key;
propertyPath = parentPath;
} else if (t.isVariableDeclarator(parent)) {
// let foo = function () {};
id = parent.id;
} else if (t.isAssignmentExpression(parent)) {
// foo = function () {};
id = parent.left;
} else if (t.isJSXExpressionContainer(parent)) {
if (t.isJSXElement(parentPath.parentPath.node)) {
// <foo>{function () {}}</foo>
const openingElement = parentPath.parentPath.node.openingElement;
id = t.JSXMemberExpression(
t.JSXMemberExpression(openingElement.name, t.JSXIdentifier('props')),
t.JSXIdentifier('children'),
);
} else if (t.isJSXAttribute(parentPath.parentPath.node)) {
// <foo bar={function () {}} />
const openingElement = parentPath.parentPath.parentPath.node;
const prop = parentPath.parentPath.node;
id = t.JSXMemberExpression(
t.JSXMemberExpression(openingElement.name, t.JSXIdentifier('props')),
prop.name,
);
}
}
let name = getNameFromId(id);
if (name == null) {
if (t.isCallExpression(parent) || t.isNewExpression(parent)) {
// foo(function () {})
const argIndex = parent.arguments.indexOf(node);
if (argIndex !== -1) {
const calleeName = getNameFromId(parent.callee);
// var f = Object.freeze(function () {})
if (CALLEES_TO_SKIP.indexOf(calleeName) !== -1) {
return getNameForPath(parentPath);
}
if (calleeName) {
return `${calleeName}$argument_${argIndex}`;
}
}
}
return ANONYMOUS_NAME;
}
if (kind) {
name = kind + '__' + name;
}
if (propertyPath) {
if (t.isClassBody(propertyPath.parent)) {
const className = getNameForPath(propertyPath.parentPath.parentPath);
if (className !== ANONYMOUS_NAME) {
const separator = propertyPath.node.static ? '.' : '#';
name = className + separator + name;
}
} else if (t.isObjectExpression(propertyPath.parent)) {
const objectName = getNameForPath(propertyPath.parentPath);
if (objectName !== ANONYMOUS_NAME) {
name = objectName + '.' + name;
}
}
}
return name;
}
function isAnyMemberExpression(node: Ast): boolean {
return t.isMemberExpression(node) || t.isJSXMemberExpression(node);
}
function isAnyIdentifier(node: Ast): boolean {
return t.isIdentifier(node) || t.isJSXIdentifier(node);
}
function getNameFromId(id: Ast): ?string {
const parts = getNamePartsFromId(id);
if (!parts.length) {
return null;
}
if (parts.length > 5) {
return (
parts[0] +
'.' +
parts[1] +
'...' +
parts[parts.length - 2] +
'.' +
parts[parts.length - 1]
);
}
return parts.join('.');
}
function getNamePartsFromId(id: Ast): $ReadOnlyArray<string> {
if (!id) {
return [];
}
if (t.isCallExpression(id) || t.isNewExpression(id)) {
return getNamePartsFromId(id.callee);
}
if (t.isTypeCastExpression(id)) {
return getNamePartsFromId(id.expression);
}
let name;
if (isAnyIdentifier(id)) {
name = id.name;
} else if (t.isNullLiteral(id)) {
name = 'null';
} else if (t.isRegExpLiteral(id)) {
name = `_${id.pattern}_${id.flags}`;
} else if (t.isTemplateLiteral(id)) {
name = id.quasis.map(quasi => quasi.value.raw).join('');
} else if (t.isLiteral(id) && id.value != null) {
name = id.value + '';
}
if (name != null) {
return [t.toBindingIdentifierName(name)];
}
if (t.isImport(id)) {
name = 'import';
}
if (name != null) {
return [name];
}
if (isAnyMemberExpression(id)) {
if (
isAnyIdentifier(id.object) &&
id.object.name === 'Symbol' &&
(isAnyIdentifier(id.property) || t.isLiteral(id.property))
) {
const propertyName = getNameFromId(id.property);
if (propertyName) {
name = '@@' + propertyName;
}
} else {
const propertyName = getNamePartsFromId(id.property);
if (propertyName.length) {
const objectName = getNamePartsFromId(id.object);
if (objectName.length) {
return [...objectName, ...propertyName];
} else {
return propertyName;
}
}
}
}
return name ? [name] : [];
}
const DELIMITER_START_RE = /^[^A-Za-z0-9_$@]+/;
/**
* Strip the given prefix from `name`, if it occurs there, plus any delimiter
* characters that follow (of which at least one is required). If an empty
* string would be returned, return the original name instead.
*/
function removeNamePrefix(name: string, namePrefix: string): string {
if (!namePrefix.length || !name.startsWith(namePrefix)) {
return name;
}
const shortenedName = name.substr(namePrefix.length);
const [delimiterMatch] = shortenedName.match(DELIMITER_START_RE) || [];
if (delimiterMatch) {
return shortenedName.substr(delimiterMatch.length) || name;
}
return name;
}
/**
* Encodes function name mappings as deltas in a Base64 VLQ format inspired by
* the standard source map format.
*
* Mappings on different lines are separated with a single `;` (even if there
* are multiple intervening lines).
* Mappings on the same line are separated with `,`.
*
* The first mapping of a line has the fields:
* [column delta, name delta, line delta]
*
* where the column delta is relative to the beginning of the line, the name
* delta is relative to the previously occurring name, and the line delta is
* relative to the previously occurring line.
*
* The 2...nth other mappings of a line have the fields:
* [column delta, name delta]
*
* where both fields are relative to their previous running values. The line
* delta is omitted since it is always 0 by definition.
*
* Lines and columns are both 0-based in the serialised format. In memory,
* lines are 1-based while columns are 0-based.
*/
class MappingEncoder {
_namesMap: Map<string, number>;
_names: Array<string>;
_line: RelativeValue;
_column: RelativeValue;
_nameIndex: RelativeValue;
_mappings: B64Builder;
constructor() {
this._namesMap = new Map();
this._names = [];
this._line = new RelativeValue(1);
this._column = new RelativeValue(0);
this._nameIndex = new RelativeValue(0);
this._mappings = new B64Builder();
}
getResult(): FBSourceFunctionMap {
return {names: this._names, mappings: this._mappings.toString()};
}
push({name, start}: RangeMapping) {
let nameIndex = this._namesMap.get(name);
if (typeof nameIndex !== 'number') {
nameIndex = this._names.length;
this._names[nameIndex] = name;
this._namesMap.set(name, nameIndex);
}
const lineDelta = this._line.next(start.line);
const firstOfLine = this._mappings.pos === 0 || lineDelta > 0;
if (lineDelta > 0) {
// The next entry will have the line offset, so emit just one semicolon.
this._mappings.markLines(1);
this._column.reset(0);
}
this._mappings.startSegment(this._column.next(start.column));
this._mappings.append(this._nameIndex.next(nameIndex));
if (firstOfLine) {
this._mappings.append(lineDelta);
}
}
}
class RelativeValue {
_value: number;
constructor(value: number = 0) {
this.reset(value);
}
next(absoluteValue: number): number {
const delta = absoluteValue - this._value;
this._value = absoluteValue;
return delta;
}
reset(value: number = 0) {
this._value = value;
}
}
function positionGreater(x, y) {
return x.line > y.line || (x.line === y.line && x.column > y.column);
}
module.exports = {generateFunctionMap, generateFunctionMappingsArray};

252
node_modules/metro-source-map/src/source-map.js generated vendored Normal file
View File

@ -0,0 +1,252 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
"use strict";
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this,
args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
const Consumer = require("./Consumer");
const Generator = require("./Generator");
const SourceMap = require("source-map");
// We need to export this for `metro-symbolicate`
const normalizeSourcePath = require("./Consumer/normalizeSourcePath");
const composeSourceMaps = require("./composeSourceMaps");
const _require = require("./BundleBuilder"),
createIndexMap = _require.createIndexMap,
BundleBuilder = _require.BundleBuilder;
const _require2 = require("./generateFunctionMap"),
generateFunctionMap = _require2.generateFunctionMap;
function fromRawMappingsImpl(isBlocking, onDone, modules, offsetLines) {
const modulesToProcess = modules.slice();
const generator = new Generator();
let carryOver = offsetLines;
function processNextModule() {
if (modulesToProcess.length === 0) {
return true;
}
const mod = modulesToProcess.shift();
const code = mod.code,
map = mod.map;
if (Array.isArray(map)) {
addMappingsForFile(generator, map, mod, carryOver);
} else if (map != null) {
throw new Error(
`Unexpected module with full source map found: ${mod.path}`
);
}
carryOver = carryOver + countLines(code);
return false;
}
function workLoop() {
const time = process.hrtime();
while (true) {
const isDone = processNextModule();
if (isDone) {
onDone(generator);
break;
}
if (!isBlocking) {
// Keep the loop running but try to avoid blocking
// for too long because this is not in a worker yet.
const diff = process.hrtime(time);
const NS_IN_MS = 1000000;
if (diff[1] > 50 * NS_IN_MS) {
// We've blocked for more than 50ms.
// This code currently runs on the main thread,
// so let's give Metro an opportunity to handle requests.
setImmediate(workLoop);
break;
}
}
}
}
workLoop();
}
/**
* Creates a source map from modules with "raw mappings", i.e. an array of
* tuples with either 2, 4, or 5 elements:
* generated line, generated column, source line, source line, symbol name.
* Accepts an `offsetLines` argument in case modules' code is to be offset in
* the resulting bundle, e.g. by some prefix code.
*/
function fromRawMappings(modules) {
let offsetLines =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
let generator;
fromRawMappingsImpl(
true,
g => {
generator = g;
},
modules,
offsetLines
);
if (generator == null) {
throw new Error("Expected fromRawMappingsImpl() to finish synchronously.");
}
return generator;
}
function fromRawMappingsNonBlocking(_x) {
return _fromRawMappingsNonBlocking.apply(this, arguments);
}
/**
* Transforms a standard source map object into a Raw Mappings object, to be
* used across the bundler.
*/
function _fromRawMappingsNonBlocking() {
_fromRawMappingsNonBlocking = _asyncToGenerator(function*(modules) {
let offsetLines =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return new Promise(resolve => {
fromRawMappingsImpl(false, resolve, modules, offsetLines);
});
});
return _fromRawMappingsNonBlocking.apply(this, arguments);
}
function toBabelSegments(sourceMap) {
const rawMappings = [];
new SourceMap.SourceMapConsumer(sourceMap).eachMapping(map => {
rawMappings.push({
generated: {
line: map.generatedLine,
column: map.generatedColumn
},
original: {
line: map.originalLine,
column: map.originalColumn
},
source: map.source,
name: map.name
});
});
return rawMappings;
}
function toSegmentTuple(mapping) {
const _mapping$generated = mapping.generated,
column = _mapping$generated.column,
line = _mapping$generated.line;
const name = mapping.name,
original = mapping.original;
if (original == null) {
return [line, column];
}
if (typeof name !== "string") {
return [line, column, original.line, original.column];
}
return [line, column, original.line, original.column, name];
}
function addMappingsForFile(generator, mappings, module, carryOver) {
generator.startFile(module.path, module.source, module.functionMap);
for (let i = 0, n = mappings.length; i < n; ++i) {
addMapping(generator, mappings[i], carryOver);
}
generator.endFile();
}
function addMapping(generator, mapping, carryOver) {
const n = mapping.length;
const line = mapping[0] + carryOver; // lines start at 1, columns start at 0
const column = mapping[1];
if (n === 2) {
generator.addSimpleMapping(line, column);
} else if (n === 4) {
const sourceMap = mapping;
generator.addSourceMapping(line, column, sourceMap[2], sourceMap[3]);
} else if (n === 5) {
const sourceMap = mapping;
generator.addNamedSourceMapping(
line,
column,
sourceMap[2],
sourceMap[3],
sourceMap[4]
);
} else {
throw new Error(`Invalid mapping: [${mapping.join(", ")}]`);
}
}
function countLines(string) {
return string.split("\n").length;
}
module.exports = {
BundleBuilder,
composeSourceMaps,
Consumer,
createIndexMap,
generateFunctionMap,
fromRawMappings,
fromRawMappingsNonBlocking,
normalizeSourcePath,
toBabelSegments,
toSegmentTuple
};

294
node_modules/metro-source-map/src/source-map.js.flow generated vendored Normal file
View File

@ -0,0 +1,294 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const Consumer = require('./Consumer');
const Generator = require('./Generator');
const SourceMap = require('source-map');
import type {IConsumer} from './Consumer/types.flow';
export type {IConsumer};
// We need to export this for `metro-symbolicate`
const normalizeSourcePath = require('./Consumer/normalizeSourcePath');
const composeSourceMaps = require('./composeSourceMaps');
const {createIndexMap, BundleBuilder} = require('./BundleBuilder');
const {generateFunctionMap} = require('./generateFunctionMap');
import type {BabelSourceMapSegment} from '@babel/generator';
type GeneratedCodeMapping = [number, number];
type SourceMapping = [number, number, number, number];
type SourceMappingWithName = [number, number, number, number, string];
export type MetroSourceMapSegmentTuple =
| SourceMappingWithName
| SourceMapping
| GeneratedCodeMapping;
export type HermesFunctionOffsets = {[number]: $ReadOnlyArray<number>, ...};
export type FBSourcesArray = $ReadOnlyArray<?FBSourceMetadata>;
export type FBSourceMetadata = [?FBSourceFunctionMap];
export type FBSourceFunctionMap = {|
+names: $ReadOnlyArray<string>,
+mappings: string,
|};
export type FBSegmentMap = {[id: string]: MixedSourceMap, ...};
export type BasicSourceMap = {|
+file?: string,
+mappings: string,
+names: Array<string>,
+sourceRoot?: string,
+sources: Array<string>,
+sourcesContent?: Array<?string>,
+version: number,
+x_facebook_offsets?: Array<number>,
+x_metro_module_paths?: Array<string>,
+x_facebook_sources?: FBSourcesArray,
+x_facebook_segments?: FBSegmentMap,
+x_hermes_function_offsets?: HermesFunctionOffsets,
|};
export type IndexMapSection = {
map: IndexMap | BasicSourceMap,
offset: {
line: number,
column: number,
...
},
...
};
export type IndexMap = {|
+file?: string,
+mappings?: void, // avoids SourceMap being a disjoint union
+sections: Array<IndexMapSection>,
+version: number,
+x_facebook_offsets?: Array<number>,
+x_metro_module_paths?: Array<string>,
+x_facebook_sources?: FBSourcesArray,
+x_facebook_segments?: FBSegmentMap,
+x_hermes_function_offsets?: HermesFunctionOffsets,
|};
export type MixedSourceMap = IndexMap | BasicSourceMap;
function fromRawMappingsImpl(
isBlocking: boolean,
onDone: Generator => void,
modules: $ReadOnlyArray<{
+map: ?Array<MetroSourceMapSegmentTuple>,
+functionMap: ?FBSourceFunctionMap,
+path: string,
+source: string,
+code: string,
...
}>,
offsetLines: number,
): void {
const modulesToProcess = modules.slice();
const generator = new Generator();
let carryOver = offsetLines;
function processNextModule() {
if (modulesToProcess.length === 0) {
return true;
}
const mod = modulesToProcess.shift();
const {code, map} = mod;
if (Array.isArray(map)) {
addMappingsForFile(generator, map, mod, carryOver);
} else if (map != null) {
throw new Error(
`Unexpected module with full source map found: ${mod.path}`,
);
}
carryOver = carryOver + countLines(code);
return false;
}
function workLoop() {
const time = process.hrtime();
while (true) {
const isDone = processNextModule();
if (isDone) {
onDone(generator);
break;
}
if (!isBlocking) {
// Keep the loop running but try to avoid blocking
// for too long because this is not in a worker yet.
const diff = process.hrtime(time);
const NS_IN_MS = 1000000;
if (diff[1] > 50 * NS_IN_MS) {
// We've blocked for more than 50ms.
// This code currently runs on the main thread,
// so let's give Metro an opportunity to handle requests.
setImmediate(workLoop);
break;
}
}
}
}
workLoop();
}
/**
* Creates a source map from modules with "raw mappings", i.e. an array of
* tuples with either 2, 4, or 5 elements:
* generated line, generated column, source line, source line, symbol name.
* Accepts an `offsetLines` argument in case modules' code is to be offset in
* the resulting bundle, e.g. by some prefix code.
*/
function fromRawMappings(
modules: $ReadOnlyArray<{
+map: ?Array<MetroSourceMapSegmentTuple>,
+functionMap: ?FBSourceFunctionMap,
+path: string,
+source: string,
+code: string,
...
}>,
offsetLines: number = 0,
): Generator {
let generator: void | Generator;
fromRawMappingsImpl(
true,
g => {
generator = g;
},
modules,
offsetLines,
);
if (generator == null) {
throw new Error('Expected fromRawMappingsImpl() to finish synchronously.');
}
return generator;
}
async function fromRawMappingsNonBlocking(
modules: $ReadOnlyArray<{
+map: ?Array<MetroSourceMapSegmentTuple>,
+functionMap: ?FBSourceFunctionMap,
+path: string,
+source: string,
+code: string,
...
}>,
offsetLines: number = 0,
): Promise<Generator> {
return new Promise(resolve => {
fromRawMappingsImpl(false, resolve, modules, offsetLines);
});
}
/**
* Transforms a standard source map object into a Raw Mappings object, to be
* used across the bundler.
*/
function toBabelSegments(
sourceMap: BasicSourceMap,
): Array<BabelSourceMapSegment> {
const rawMappings = [];
new SourceMap.SourceMapConsumer(sourceMap).eachMapping(map => {
rawMappings.push({
generated: {
line: map.generatedLine,
column: map.generatedColumn,
},
original: {
line: map.originalLine,
column: map.originalColumn,
},
source: map.source,
name: map.name,
});
});
return rawMappings;
}
function toSegmentTuple(
mapping: BabelSourceMapSegment,
): MetroSourceMapSegmentTuple {
const {column, line} = mapping.generated;
const {name, original} = mapping;
if (original == null) {
return [line, column];
}
if (typeof name !== 'string') {
return [line, column, original.line, original.column];
}
return [line, column, original.line, original.column, name];
}
function addMappingsForFile(generator, mappings, module, carryOver) {
generator.startFile(module.path, module.source, module.functionMap);
for (let i = 0, n = mappings.length; i < n; ++i) {
addMapping(generator, mappings[i], carryOver);
}
generator.endFile();
}
function addMapping(generator, mapping, carryOver) {
const n = mapping.length;
const line = mapping[0] + carryOver;
// lines start at 1, columns start at 0
const column = mapping[1];
if (n === 2) {
generator.addSimpleMapping(line, column);
} else if (n === 4) {
const sourceMap: SourceMapping = (mapping: any);
generator.addSourceMapping(line, column, sourceMap[2], sourceMap[3]);
} else if (n === 5) {
const sourceMap: SourceMappingWithName = (mapping: any);
generator.addNamedSourceMapping(
line,
column,
sourceMap[2],
sourceMap[3],
sourceMap[4],
);
} else {
throw new Error(`Invalid mapping: [${mapping.join(', ')}]`);
}
}
function countLines(string) {
return string.split('\n').length;
}
module.exports = {
BundleBuilder,
composeSourceMaps,
Consumer,
createIndexMap,
generateFunctionMap,
fromRawMappings,
fromRawMappingsNonBlocking,
normalizeSourcePath,
toBabelSegments,
toSegmentTuple,
};