Izmjenjena struktura, dodan backand

This commit is contained in:
GotPPay
2017-10-16 11:19:46 +02:00
parent 1ec88afacb
commit 048e32c4aa
37153 changed files with 2975854 additions and 1 deletions

11
web/node_modules/react-error-overlay/README.md generated vendored Normal file
View File

@@ -0,0 +1,11 @@
# `react-error-overlay`
`react-error-overlay` is an overlay which displays when there is a runtime error.
## Development
When developing within this package, make sure you run `npm start` (or `yarn start`) so that the files are compiled as you work.
This is ran in watch mode by default.
If you would like to build this for production, run `npm run build:prod` (or `yarn build:prod`).<br>
If you would like to build this one-off for development, you can run `NODE_ENV=development npm run build` (or `NODE_ENV=development yarn build`).

View File

@@ -0,0 +1,69 @@
import _regeneratorRuntime from 'babel-runtime/regenerator';
var _this = this;
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { extractSourceMapUrl } from '../utils/getSourceMap';
test('extracts last source map directive', _asyncToGenerator(_regeneratorRuntime.mark(function _callee() {
var res;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return extractSourceMapUrl('test.js', '//# sourceMappingURL=test.js.map\nconsole.log(\'a\')\n//# sourceMappingURL=bundle.js.map');
case 2:
res = _context.sent;
expect(res).toBe('bundle.js.map');
case 4:
case 'end':
return _context.stop();
}
}
}, _callee, _this);
})));
test('errors when no source map', _asyncToGenerator(_regeneratorRuntime.mark(function _callee2() {
var testFileName;
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
expect.assertions(1);
testFileName = 'test.js';
_context2.prev = 2;
_context2.next = 5;
return extractSourceMapUrl(testFileName, 'console.log(\'hi\')\n\nconsole.log(\'bye\')');
case 5:
_context2.next = 10;
break;
case 7:
_context2.prev = 7;
_context2.t0 = _context2['catch'](2);
expect(_context2.t0).toBe('Cannot find a source map directive for ' + testFileName + '.');
case 10:
case 'end':
return _context2.stop();
}
}
}, _callee2, _this, [[2, 7]]);
})));

View File

@@ -0,0 +1,110 @@
import _regeneratorRuntime from 'babel-runtime/regenerator';
var _this = this;
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { getSourceMap } from '../utils/getSourceMap';
import fs from 'fs';
import { resolve } from 'path';
test('finds an external source map', _asyncToGenerator(_regeneratorRuntime.mark(function _callee() {
var file, sm;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
file = fs.readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs')).toString('utf8');
fetch.mockResponseOnce(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs.map')).toString('utf8'));
_context.next = 4;
return getSourceMap('/', file);
case 4:
sm = _context.sent;
expect(sm.getOriginalPosition(26122, 21)).toEqual({
line: 7,
column: 0,
source: 'webpack:///packages/react-scripts/template/src/App.js'
});
case 6:
case 'end':
return _context.stop();
}
}
}, _callee, _this);
})));
test('find an inline source map', _asyncToGenerator(_regeneratorRuntime.mark(function _callee2() {
var sourceName, file, fileO, sm;
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
sourceName = 'test.js';
file = fs.readFileSync(resolve(__dirname, '../../fixtures/inline.mjs')).toString('utf8');
fileO = fs.readFileSync(resolve(__dirname, '../../fixtures/inline.es6.mjs')).toString('utf8');
_context2.next = 5;
return getSourceMap('/', file);
case 5:
sm = _context2.sent;
expect(sm.getSources()).toEqual([sourceName]);
expect(sm.getSource(sourceName)).toBe(fileO);
expect(sm.getGeneratedPosition(sourceName, 5, 10)).toEqual({
line: 10,
column: 8
});
case 9:
case 'end':
return _context2.stop();
}
}
}, _callee2, _this);
})));
test('error on a source map with unsupported encoding', _asyncToGenerator(_regeneratorRuntime.mark(function _callee3() {
var file;
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
expect.assertions(2);
file = fs.readFileSync(resolve(__dirname, '../../fixtures/junk-inline.mjs')).toString('utf8');
_context3.prev = 2;
_context3.next = 5;
return getSourceMap('/', file);
case 5:
_context3.next = 11;
break;
case 7:
_context3.prev = 7;
_context3.t0 = _context3['catch'](2);
expect(_context3.t0 instanceof Error).toBe(true);
expect(_context3.t0.message).toBe('Sorry, non-base64 inline source-map encoding is not supported.');
case 11:
case 'end':
return _context3.stop();
}
}
}, _callee3, _this, [[2, 7]]);
})));

View File

@@ -0,0 +1,20 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { getLinesAround } from '../utils/getLinesAround';
var arr = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
test('should return lines around from a string', function () {
expect(getLinesAround(4, 2, arr)).toMatchSnapshot();
});
test('should return lines around from an array', function () {
expect(getLinesAround(4, 2, arr.join('\n'))).toMatchSnapshot();
});

View File

@@ -0,0 +1,113 @@
import _regeneratorRuntime from 'babel-runtime/regenerator';
var _this = this;
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { map } from '../utils/mapper';
import { parse } from '../utils/parser';
import fs from 'fs';
import { resolve } from 'path';
test('basic error; 0 context', _asyncToGenerator(_regeneratorRuntime.mark(function _callee() {
var error, frames;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
expect.assertions(1);
error = 'TypeError: document.body.missing is not a function\n at App.componentDidMount (http://localhost:3000/static/js/bundle.js:26122:21)\n at http://localhost:3000/static/js/bundle.js:30091:25\n at measureLifeCyclePerf (http://localhost:3000/static/js/bundle.js:29901:12)\n at http://localhost:3000/static/js/bundle.js:30090:11\n at CallbackQueue.notifyAll (http://localhost:3000/static/js/bundle.js:13256:22)\n at ReactReconcileTransaction.close (http://localhost:3000/static/js/bundle.js:35124:26)\n at ReactReconcileTransaction.closeAll (http://localhost:3000/static/js/bundle.js:7390:25)\n at ReactReconcileTransaction.perform (http://localhost:3000/static/js/bundle.js:7337:16)\n at batchedMountComponentIntoNode (http://localhost:3000/static/js/bundle.js:14204:15)\n at ReactDefaultBatchingStrategyTransaction.perform (http://localhost:3000/static/js/bundle.js:7324:20)\n at Object.batchedUpdates (http://localhost:3000/static/js/bundle.js:33900:26)\n at Object.batchedUpdates (http://localhost:3000/static/js/bundle.js:2181:27)\n at Object._renderNewRootComponent (http://localhost:3000/static/js/bundle.js:14398:18)\n at Object._renderSubtreeIntoContainer (http://localhost:3000/static/js/bundle.js:14479:32)\n at Object.render (http://localhost:3000/static/js/bundle.js:14500:23)\n at Object.friendlySyntaxErrorLabel (http://localhost:3000/static/js/bundle.js:17287:20)\n at __webpack_require__ (http://localhost:3000/static/js/bundle.js:660:30)\n at fn (http://localhost:3000/static/js/bundle.js:84:20)\n at Object.<anonymous> (http://localhost:3000/static/js/bundle.js:41219:18)\n at __webpack_require__ (http://localhost:3000/static/js/bundle.js:660:30)\n at validateFormat (http://localhost:3000/static/js/bundle.js:709:39)\n at http://localhost:3000/static/js/bundle.js:712:10';
fetch.mockResponseOnce(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs')).toString('utf8'));
fetch.mockResponseOnce(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs.map')).toString('utf8'));
_context.next = 6;
return map(parse(error), 0);
case 6:
frames = _context.sent;
expect(frames).toEqual(JSON.parse(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle.json')).toString('utf8')));
case 8:
case 'end':
return _context.stop();
}
}
}, _callee, _this);
})));
test('default context (3)', _asyncToGenerator(_regeneratorRuntime.mark(function _callee2() {
var error, frames;
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
expect.assertions(1);
error = 'TypeError: document.body.missing is not a function\n at App.componentDidMount (http://localhost:3000/static/js/bundle.js:26122:21)';
fetch.mockResponseOnce(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs')).toString('utf8'));
fetch.mockResponseOnce(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs.map')).toString('utf8'));
_context2.next = 6;
return map(parse(error));
case 6:
frames = _context2.sent;
expect(frames).toEqual(JSON.parse(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle-default.json')).toString('utf8')));
case 8:
case 'end':
return _context2.stop();
}
}
}, _callee2, _this);
})));
test('bad comes back same', _asyncToGenerator(_regeneratorRuntime.mark(function _callee3() {
var error, orig, frames;
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
expect.assertions(2);
error = 'TypeError: document.body.missing is not a function\n at App.componentDidMount (A:1:2)';
orig = parse(error);
expect(orig).toEqual([{
_originalColumnNumber: null,
_originalFileName: null,
_originalFunctionName: null,
_originalLineNumber: null,
_originalScriptCode: null,
_scriptCode: null,
columnNumber: 2,
fileName: 'A',
functionName: 'App.componentDidMount',
lineNumber: 1
}]);
_context3.next = 6;
return map(orig);
case 6:
frames = _context3.sent;
expect(frames).toEqual(orig);
case 8:
case 'end':
return _context3.stop();
}
}
}, _callee3, _this);
})));

View File

@@ -0,0 +1,14 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { parse } from '../../utils/parser';
test('stack with eval', function () {
expect(parse('TypeError: window[f] is not a function\n at e (file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:25:18)\n at eval (eval at c (file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:12:9), <anonymous>:1:1)\n at a (file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:8:9)\n at file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:32:7')).toMatchSnapshot();
});

View File

@@ -0,0 +1,32 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { parse } from '../../utils/parser';
test('eval 1', function () {
expect(parse('test1@file:///C:/example.html line 7 > eval line 1 > eval:1:1\ntest2@file:///C:/example.html line 7 > eval:1:1\ntest3@file:///C:/example.html:7:6'.split('\n'))).toMatchSnapshot();
});
test('eval 2', function () {
expect(parse({
stack: 'anonymous@file:///C:/example.html line 7 > Function:1:1\n@file:///C:/example.html:7:6'
})).toMatchSnapshot();
});
test('stack with eval', function () {
expect(parse('e@file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:25:9\n@file:///Users/joe/Documents/Development/OSS/stack-frame/index.html line 17 > eval:1:1\na@file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:8:9\n@file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:32:7')).toMatchSnapshot();
});
test('v14 to v29', function () {
expect(parse('trace@file:///C:/example.html:9\nb@file:///C:/example.html:16\na@file:///C:/example.html:19\n@file:///C:/example.html:21')).toMatchSnapshot();
});
test('v30+', function () {
expect(parse('trace@file:///C:/example.html:9:17\nb@file:///C:/example.html:16:13\na@file:///C:/example.html:19:13\n@file:///C:/example.html:21:9')).toMatchSnapshot();
});

View File

@@ -0,0 +1,30 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { parse } from '../../utils/parser';
test('throws on null', function () {
expect.assertions(2);
try {
parse(null);
} catch (e) {
expect(e instanceof Error).toBe(true);
expect(e.message).toBe('You cannot pass a null object.');
}
});
test('throws on unparsable', function () {
expect.assertions(2);
try {
parse({});
} catch (e) {
expect(e instanceof Error).toBe(true);
expect(e.message).toBe('The error you provided does not contain a stack trace.');
}
});

View File

@@ -0,0 +1,14 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { parse } from '../../utils/parser';
test('15.y.z', function () {
expect(parse('Warning: Each child in array should have a unique "key" prop. Check render method of `FileA`.\n in div (at FileA.js:9)\n in FileA (at App.js:9)\n in div (at App.js:8)\n in App (at index.js:7)')).toMatchSnapshot();
});

View File

@@ -0,0 +1,14 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { parse } from '../../utils/parser';
test('stack with eval', function () {
expect(parse('e@file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:25:18\neval code\neval@[native code]\na@file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:8:10\nglobal code@file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:32:8')).toMatchSnapshot();
});

View File

@@ -0,0 +1,18 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { ScriptLine } from '../utils/stack-frame';
test('script line shape', function () {
expect(new ScriptLine(5, 'foobar', true)).toMatchSnapshot();
});
test('script line to provide default highlight', function () {
expect(new ScriptLine(5, 'foobar')).toMatchSnapshot();
});

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
global.fetch = require('jest-fetch-mock');

View File

@@ -0,0 +1,28 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { StackFrame } from '../utils/stack-frame';
test('proper empty shape', function () {
var empty = new StackFrame();
expect(empty).toMatchSnapshot();
expect(empty.getFunctionName()).toBe(null);
expect(empty.getSource()).toBe('');
expect(empty.toString()).toBe('');
});
test('proper full shape', function () {
var empty = new StackFrame('a', 'b.js', 13, 37, undefined, 'apple', 'test.js', 37, 13);
expect(empty).toMatchSnapshot();
expect(empty.getFunctionName()).toBe('a');
expect(empty.getSource()).toBe('b.js:13:37');
expect(empty.toString()).toBe('a (b.js:13:37)');
});

View File

@@ -0,0 +1,87 @@
import _regeneratorRuntime from 'babel-runtime/regenerator';
var _this = this;
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { unmap } from '../utils/unmapper';
import { parse } from '../utils/parser';
import fs from 'fs';
import { resolve } from 'path';
test('basic warning', _asyncToGenerator(_regeneratorRuntime.mark(function _callee() {
var error, frames, expected;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
expect.assertions(2);
error = 'Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `B`. See https://fb.me/react-warning-keys for more information.\n in div (at B.js:8)\n in B (at A.js:6)\n in A (at App.js:8)\n in div (at App.js:10)\n in App (at index.js:6)';
fetch.mockResponseOnce(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle_u.mjs')).toString('utf8'));
fetch.mockResponseOnce(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle_u.mjs.map')).toString('utf8'));
_context.next = 6;
return unmap('/static/js/bundle.js', parse(error), 0);
case 6:
frames = _context.sent;
expected = JSON.parse(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle2.json')).toString('utf8'));
expect(frames).toEqual(expected);
fetch.mockResponseOnce(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle_u.mjs')).toString('utf8'));
fetch.mockResponseOnce(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle_u.mjs.map')).toString('utf8'));
_context.t0 = expect;
_context.next = 14;
return unmap('/static/js/bundle.js', expected);
case 14:
_context.t1 = _context.sent;
_context.t2 = expected;
(0, _context.t0)(_context.t1).toEqual(_context.t2);
case 17:
case 'end':
return _context.stop();
}
}
}, _callee, _this);
})));
test('default context & unfound source', _asyncToGenerator(_regeneratorRuntime.mark(function _callee2() {
var error, frames;
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
expect.assertions(1);
error = 'Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `B`. See https://fb.me/react-warning-keys for more information.\n in div (at B.js:8)\n in unknown (at blabla.js:10)';
fetch.mockResponseOnce(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle_u.mjs')).toString('utf8'));
fetch.mockResponseOnce(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle_u.mjs.map')).toString('utf8'));
_context2.next = 6;
return unmap('/static/js/bundle.js', parse(error));
case 6:
frames = _context2.sent;
expect(frames).toMatchSnapshot();
case 8:
case 'end':
return _context2.stop();
}
}
}, _callee2, _this);
})));

View File

@@ -0,0 +1,58 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { applyStyles } from '../utils/dom/css';
import { additionalChildStyle, groupStyle, groupElemLeft, groupElemRight } from '../styles';
import { consumeEvent } from '../utils/dom/consumeEvent';
import { enableTabClick } from '../utils/dom/enableTabClick';
function updateAdditional(document, additionalReference, currentError, totalErrors, switchCallback) {
if (additionalReference.lastChild) {
additionalReference.removeChild(additionalReference.lastChild);
}
if (totalErrors <= 1) {
return;
}
var div = document.createElement('div');
applyStyles(div, additionalChildStyle);
var group = document.createElement('span');
applyStyles(group, groupStyle);
var left = document.createElement('button');
applyStyles(left, groupElemLeft);
left.addEventListener('click', function (e) {
consumeEvent(e);
switchCallback(-1);
});
left.appendChild(document.createTextNode('←'));
enableTabClick(left);
var right = document.createElement('button');
applyStyles(right, groupElemRight);
right.addEventListener('click', function (e) {
consumeEvent(e);
switchCallback(1);
});
right.appendChild(document.createTextNode('→'));
enableTabClick(right);
group.appendChild(left);
group.appendChild(right);
div.appendChild(group);
var text = currentError + ' of ' + totalErrors + ' errors on the page';
div.appendChild(document.createTextNode(text));
additionalReference.appendChild(div);
}
export { updateAdditional };

View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { applyStyles } from '../utils/dom/css';
import { hintsStyle, hintStyle, closeButtonStyle } from '../styles';
function createHint(document, hint, title) {
var span = document.createElement('span');
span.appendChild(document.createTextNode(hint));
span.setAttribute('title', title);
applyStyles(span, hintStyle);
return span;
}
function createClose(document, callback) {
var hints = document.createElement('div');
applyStyles(hints, hintsStyle);
var close = createHint(document, '×', 'Click or press Escape to dismiss.');
close.addEventListener('click', function () {
return callback();
});
applyStyles(close, closeButtonStyle);
hints.appendChild(close);
return hints;
}
export { createClose };

View File

@@ -0,0 +1,90 @@
import { applyStyles } from '../utils/dom/css'; /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { absolutifyCaret } from '../utils/dom/absolutifyCaret';
import { codeStyle, primaryErrorStyle, primaryPreStyle, secondaryErrorStyle, secondaryPreStyle } from '../styles';
import generateAnsiHtml from 'react-dev-utils/ansiHTML';
import codeFrame from 'babel-code-frame';
function createCode(document, sourceLines, lineNum, columnNum, contextSize, main, onSourceClick) {
var sourceCode = [];
var whiteSpace = Infinity;
sourceLines.forEach(function (e) {
var text = e.content;
var m = text.match(/^\s*/);
if (text === '') {
return;
}
if (m && m[0]) {
whiteSpace = Math.min(whiteSpace, m[0].length);
} else {
whiteSpace = 0;
}
});
sourceLines.forEach(function (e) {
var text = e.content;
var line = e.lineNumber;
if (isFinite(whiteSpace)) {
text = text.substring(whiteSpace);
}
sourceCode[line - 1] = text;
});
var ansiHighlight = codeFrame(sourceCode.join('\n'), lineNum, columnNum == null ? 0 : columnNum - (isFinite(whiteSpace) ? whiteSpace : 0), {
forceColor: true,
linesAbove: contextSize,
linesBelow: contextSize
});
var htmlHighlight = generateAnsiHtml(ansiHighlight);
var code = document.createElement('code');
code.innerHTML = htmlHighlight;
absolutifyCaret(code);
applyStyles(code, codeStyle);
var ccn = code.childNodes;
// eslint-disable-next-line
oLoop: for (var index = 0; index < ccn.length; ++index) {
var node = ccn[index];
var ccn2 = node.childNodes;
for (var index2 = 0; index2 < ccn2.length; ++index2) {
var lineNode = ccn2[index2];
var text = lineNode.innerText;
if (text == null) {
continue;
}
if (text.indexOf(' ' + lineNum + ' |') === -1) {
continue;
}
// $FlowFixMe
applyStyles(node, main ? primaryErrorStyle : secondaryErrorStyle);
// eslint-disable-next-line
break oLoop;
}
}
var pre = document.createElement('pre');
applyStyles(pre, main ? primaryPreStyle : secondaryPreStyle);
pre.appendChild(code);
if (typeof onSourceClick === 'function') {
var handler = onSourceClick;
pre.style.cursor = 'pointer';
pre.addEventListener('click', function () {
handler();
});
}
return pre;
}
export { createCode };

View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { applyStyles } from '../utils/dom/css';
import { footerStyle } from '../styles';
function createFooter(document) {
var div = document.createElement('div');
applyStyles(div, footerStyle);
div.appendChild(document.createTextNode('This screen is visible only in development. It will not appear if the app crashes in production.'));
div.appendChild(document.createElement('br'));
div.appendChild(document.createTextNode('Open your browsers developer console to further inspect this error.'));
return div;
}
export { createFooter };

View File

@@ -0,0 +1,241 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { enableTabClick } from '../utils/dom/enableTabClick';
import { createCode } from './code';
import { isInternalFile } from '../utils/isInternalFile';
import { applyStyles } from '../utils/dom/css';
import { omittedFramesExpandedStyle, omittedFramesCollapsedStyle, functionNameStyle, depStyle, linkStyle, anchorStyle, hiddenStyle } from '../styles';
function getGroupToggle(document, omitsCount, omitBundle) {
var omittedFrames = document.createElement('div');
enableTabClick(omittedFrames);
var text1 = document.createTextNode('\u25B6 ' + omitsCount + ' stack frames were collapsed.');
omittedFrames.appendChild(text1);
omittedFrames.addEventListener('click', function () {
var hide = text1.textContent.match(/▲/);
var list = document.getElementsByName('bundle-' + omitBundle);
for (var index = 0; index < list.length; ++index) {
var n = list[index];
if (hide) {
n.style.display = 'none';
} else {
n.style.display = '';
}
}
if (hide) {
text1.textContent = text1.textContent.replace(/▲/, '▶');
text1.textContent = text1.textContent.replace(/expanded/, 'collapsed');
applyStyles(omittedFrames, omittedFramesCollapsedStyle);
} else {
text1.textContent = text1.textContent.replace(/▶/, '▲');
text1.textContent = text1.textContent.replace(/collapsed/, 'expanded');
applyStyles(omittedFrames, omittedFramesExpandedStyle);
}
});
applyStyles(omittedFrames, omittedFramesCollapsedStyle);
return omittedFrames;
}
function insertBeforeBundle(document, parent, omitsCount, omitBundle, actionElement) {
var children = document.getElementsByName('bundle-' + omitBundle);
if (children.length < 1) {
return;
}
var first = children[0];
while (first != null && first.parentNode !== parent) {
first = first.parentNode;
}
var div = document.createElement('div');
enableTabClick(div);
div.setAttribute('name', 'bundle-' + omitBundle);
var text = document.createTextNode('\u25BC ' + omitsCount + ' stack frames were expanded.');
div.appendChild(text);
div.addEventListener('click', function () {
return actionElement.click();
});
applyStyles(div, omittedFramesExpandedStyle);
div.style.display = 'none';
parent.insertBefore(div, first);
}
function frameDiv(document, functionName, url, internalUrl, onSourceClick) {
var frame = document.createElement('div');
var frameFunctionName = document.createElement('div');
var cleanedFunctionName = void 0;
if (!functionName || functionName === 'Object.<anonymous>') {
cleanedFunctionName = '(anonymous function)';
} else {
cleanedFunctionName = functionName;
}
var cleanedUrl = url.replace('webpack://', '.');
if (internalUrl) {
applyStyles(frameFunctionName, Object.assign({}, functionNameStyle, depStyle));
} else {
applyStyles(frameFunctionName, functionNameStyle);
}
frameFunctionName.appendChild(document.createTextNode(cleanedFunctionName));
frame.appendChild(frameFunctionName);
var frameLink = document.createElement('div');
applyStyles(frameLink, linkStyle);
var frameAnchor = document.createElement('a');
applyStyles(frameAnchor, anchorStyle);
frameAnchor.appendChild(document.createTextNode(cleanedUrl));
frameLink.appendChild(frameAnchor);
frame.appendChild(frameLink);
if (typeof onSourceClick === 'function') {
var handler = onSourceClick;
enableTabClick(frameAnchor);
frameAnchor.style.cursor = 'pointer';
frameAnchor.addEventListener('click', function () {
handler();
});
}
return frame;
}
function isBultinErrorName(errorName) {
switch (errorName) {
case 'EvalError':
case 'InternalError':
case 'RangeError':
case 'ReferenceError':
case 'SyntaxError':
case 'TypeError':
case 'URIError':
return true;
default:
return false;
}
}
function getPrettyURL(sourceFileName, sourceLineNumber, sourceColumnNumber, fileName, lineNumber, columnNumber, compiled) {
var prettyURL = void 0;
if (!compiled && sourceFileName && typeof sourceLineNumber === 'number') {
// Remove everything up to the first /src/ or /node_modules/
var trimMatch = /^[/|\\].*?[/|\\]((src|node_modules)[/|\\].*)/.exec(sourceFileName);
if (trimMatch && trimMatch[1]) {
prettyURL = trimMatch[1];
} else {
prettyURL = sourceFileName;
}
prettyURL += ':' + sourceLineNumber;
// Note: we intentionally skip 0's because they're produced by cheap Webpack maps
if (sourceColumnNumber) {
prettyURL += ':' + sourceColumnNumber;
}
} else if (fileName && typeof lineNumber === 'number') {
prettyURL = fileName + ':' + lineNumber;
// Note: we intentionally skip 0's because they're produced by cheap Webpack maps
if (columnNumber) {
prettyURL += ':' + columnNumber;
}
} else {
prettyURL = 'unknown';
}
return prettyURL;
}
function createFrame(document, frameSetting, frame, contextSize, critical, omits, omitBundle, parentContainer, lastElement, errorName) {
var compiled = frameSetting.compiled;
var functionName = frame.functionName,
sourceFileName = frame._originalFileName;
var fileName = frame.fileName,
lineNumber = frame.lineNumber,
columnNumber = frame.columnNumber,
scriptLines = frame._scriptCode,
sourceLineNumber = frame._originalLineNumber,
sourceColumnNumber = frame._originalColumnNumber,
sourceLines = frame._originalScriptCode;
// TODO: find a better place for this.
// Chrome has a bug with inferring function.name:
// https://github.com/facebookincubator/create-react-app/issues/2097
// Let's ignore a meaningless name we get for top-level modules.
if (functionName === 'Object.friendlySyntaxErrorLabel' || functionName === 'Object.exports.__esModule') {
functionName = '(anonymous function)';
}
var prettyURL = getPrettyURL(sourceFileName, sourceLineNumber, sourceColumnNumber, fileName, lineNumber, columnNumber, compiled);
var needsHidden = false;
var isInternalUrl = isInternalFile(sourceFileName, fileName);
var isThrownIntentionally = !isBultinErrorName(errorName);
var shouldCollapse = isInternalUrl && (isThrownIntentionally || omits.hasReachedAppCode);
if (!isInternalUrl) {
omits.hasReachedAppCode = true;
}
if (shouldCollapse) {
++omits.value;
needsHidden = true;
}
var collapseElement = null;
if (!shouldCollapse || lastElement) {
if (omits.value > 0) {
var capV = omits.value;
var omittedFrames = getGroupToggle(document, capV, omitBundle);
window.requestAnimationFrame(function () {
insertBeforeBundle(document, parentContainer, capV, omitBundle, omittedFrames);
});
if (lastElement && shouldCollapse) {
collapseElement = omittedFrames;
} else {
parentContainer.appendChild(omittedFrames);
}
++omits.bundle;
}
omits.value = 0;
}
var onSourceClick = null;
if (sourceFileName) {
// e.g. "/path-to-my-app/webpack/bootstrap eaddeb46b67d75e4dfc1"
var isInternalWebpackBootstrapCode = sourceFileName.trim().indexOf(' ') !== -1;
if (!isInternalWebpackBootstrapCode) {
onSourceClick = function onSourceClick() {
// Keep this in sync with react-error-overlay/middleware.js
fetch('/__open-stack-frame-in-editor?fileName=' + window.encodeURIComponent(sourceFileName) + '&lineNumber=' + window.encodeURIComponent(sourceLineNumber || 1)).then(function () {}, function () {});
};
}
}
var elem = frameDiv(document, functionName, prettyURL, shouldCollapse, onSourceClick);
if (needsHidden) {
applyStyles(elem, hiddenStyle);
elem.setAttribute('name', 'bundle-' + omitBundle);
}
var hasSource = false;
if (!shouldCollapse) {
if (compiled && scriptLines && scriptLines.length !== 0 && lineNumber != null) {
elem.appendChild(createCode(document, scriptLines, lineNumber, columnNumber, contextSize, critical, onSourceClick));
hasSource = true;
} else if (!compiled && sourceLines && sourceLines.length !== 0 && sourceLineNumber != null) {
elem.appendChild(createCode(document, sourceLines, sourceLineNumber, sourceColumnNumber, contextSize, critical, onSourceClick));
hasSource = true;
}
}
return { elem: elem, hasSource: hasSource, collapseElement: collapseElement };
}
export { createFrame };

View File

@@ -0,0 +1,82 @@
import { applyStyles } from '../utils/dom/css'; /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { traceStyle, toggleStyle } from '../styles';
import { enableTabClick } from '../utils/dom/enableTabClick';
import { createFrame } from './frame';
function createFrameWrapper(document, parent, factory, lIndex, frameSettings, contextSize) {
var fac = factory();
if (fac == null) {
return;
}
var hasSource = fac.hasSource,
elem = fac.elem,
collapseElement = fac.collapseElement;
var elemWrapper = document.createElement('div');
elemWrapper.appendChild(elem);
if (hasSource) {
var compiledDiv = document.createElement('div');
enableTabClick(compiledDiv);
applyStyles(compiledDiv, toggleStyle);
var o = frameSettings[lIndex];
var compiledText = document.createTextNode('View ' + (o && o.compiled ? 'source' : 'compiled'));
compiledDiv.addEventListener('click', function () {
if (o) {
o.compiled = !o.compiled;
}
var next = createFrameWrapper(document, parent, factory, lIndex, frameSettings, contextSize);
if (next != null) {
parent.insertBefore(next, elemWrapper);
parent.removeChild(elemWrapper);
}
});
compiledDiv.appendChild(compiledText);
elemWrapper.appendChild(compiledDiv);
}
if (collapseElement != null) {
elemWrapper.appendChild(collapseElement);
}
return elemWrapper;
}
function createFrames(document, resolvedFrames, frameSettings, contextSize, errorName) {
if (resolvedFrames.length !== frameSettings.length) {
throw new Error('You must give a frame settings array of identical length to resolved frames.');
}
var trace = document.createElement('div');
applyStyles(trace, traceStyle);
var index = 0;
var critical = true;
var omits = { value: 0, bundle: 1, hasReachedAppCode: false };
resolvedFrames.forEach(function (frame) {
var lIndex = index++;
var elem = createFrameWrapper(document, trace, createFrame.bind(undefined, document, frameSettings[lIndex], frame, contextSize, critical, omits, omits.bundle, trace, index === resolvedFrames.length, errorName), lIndex, frameSettings, contextSize);
if (elem == null) {
return;
}
critical = false;
trace.appendChild(elem);
});
//TODO: fix this
omits.value = 0;
return trace;
}
export { createFrames };

View File

@@ -0,0 +1,71 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { applyStyles } from '../utils/dom/css';
import { containerStyle, overlayStyle, headerStyle } from '../styles';
import { createClose } from './close';
import { createFrames } from './frames';
import { createFooter } from './footer';
import { updateAdditional } from './additional';
function createOverlay(document, name, message, frames, contextSize, currentError, totalErrors, switchCallback, closeCallback) {
var frameSettings = frames.map(function () {
return { compiled: false };
});
// Create overlay
var overlay = document.createElement('div');
applyStyles(overlay, overlayStyle);
// Create container
var container = document.createElement('div');
applyStyles(container, containerStyle);
overlay.appendChild(container);
container.appendChild(createClose(document, closeCallback));
// Create "Errors X of Y" in case of multiple errors
var additional = document.createElement('div');
updateAdditional(document, additional, currentError, totalErrors, switchCallback);
container.appendChild(additional);
// Create header
var header = document.createElement('div');
applyStyles(header, headerStyle);
// Make message prettier
var finalMessage = message.match(/^\w*:/) || !name ? message : name + ': ' + message;
finalMessage = finalMessage
// TODO: maybe remove this prefix from fbjs?
// It's just scaring people
.replace(/^Invariant Violation:\s*/, '')
// This is not helpful either:
.replace(/^Warning:\s*/, '')
// Break the actionable part to the next line.
// AFAIK React 16+ should already do this.
.replace(' Check the render method', '\n\nCheck the render method').replace(' Check your code at', '\n\nCheck your code at');
// Put it in the DOM
header.appendChild(document.createTextNode(finalMessage));
container.appendChild(header);
// Create trace
container.appendChild(createFrames(document, frames, frameSettings, contextSize, name));
// Show message
container.appendChild(createFooter(document));
return {
overlay: overlay,
additional: additional
};
}
export { createOverlay };

View File

@@ -0,0 +1,62 @@
var reactFrameStack = []; /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
// This is a stripped down barebones version of this proposal:
// https://gist.github.com/sebmarkbage/bdefa100f19345229d526d0fdd22830f
// We're implementing just enough to get the invalid element type warnings
// to display the component stack in React 15.6+:
// https://github.com/facebook/react/pull/9679
/// TODO: a more comprehensive implementation.
var registerReactStack = function registerReactStack() {
if (typeof console !== 'undefined') {
// $FlowFixMe
console.reactStack = function (frames) {
return reactFrameStack.push(frames);
};
// $FlowFixMe
console.reactStackEnd = function (frames) {
return reactFrameStack.pop();
};
}
};
var unregisterReactStack = function unregisterReactStack() {
if (typeof console !== 'undefined') {
// $FlowFixMe
console.reactStack = undefined;
// $FlowFixMe
console.reactStackEnd = undefined;
}
};
var permanentRegister = function proxyConsole(type, callback) {
if (typeof console !== 'undefined') {
var orig = console[type];
if (typeof orig === 'function') {
console[type] = function __stack_frame_overlay_proxy_console__() {
try {
var _message = arguments[0];
if (typeof _message === 'string' && reactFrameStack.length > 0) {
callback(_message, reactFrameStack[reactFrameStack.length - 1]);
}
} catch (err) {
// Warnings must never crash. Rethrow with a clean stack.
setTimeout(function () {
throw err;
});
}
return orig.apply(this, arguments);
};
}
}
};
export { permanentRegister, registerReactStack, unregisterReactStack };

View File

@@ -0,0 +1,46 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var SHORTCUT_ESCAPE = 'SHORTCUT_ESCAPE',
SHORTCUT_LEFT = 'SHORTCUT_LEFT',
SHORTCUT_RIGHT = 'SHORTCUT_RIGHT';
var boundKeyHandler = null;
function keyHandler(callback, e) {
var key = e.key,
keyCode = e.keyCode,
which = e.which;
if (key === 'Escape' || keyCode === 27 || which === 27) {
callback(SHORTCUT_ESCAPE);
} else if (key === 'ArrowLeft' || keyCode === 37 || which === 37) {
callback(SHORTCUT_LEFT);
} else if (key === 'ArrowRight' || keyCode === 39 || which === 39) {
callback(SHORTCUT_RIGHT);
}
}
function registerShortcuts(target, callback) {
if (boundKeyHandler !== null) {
return;
}
boundKeyHandler = keyHandler.bind(undefined, callback);
target.addEventListener('keydown', boundKeyHandler);
}
function unregisterShortcuts(target) {
if (boundKeyHandler === null) {
return;
}
target.removeEventListener('keydown', boundKeyHandler);
boundKeyHandler = null;
}
export { SHORTCUT_ESCAPE, SHORTCUT_LEFT, SHORTCUT_RIGHT, registerShortcuts as register, unregisterShortcuts as unregister, keyHandler as handler };

View File

@@ -0,0 +1,43 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var stackTraceRegistered = false;
// Default: https://docs.microsoft.com/en-us/scripting/javascript/reference/stacktracelimit-property-error-javascript
var restoreStackTraceValue = 10;
var MAX_STACK_LENGTH = 50;
function registerStackTraceLimit() {
var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : MAX_STACK_LENGTH;
if (stackTraceRegistered) {
return;
}
try {
restoreStackTraceValue = Error.stackTraceLimit;
Error.stackTraceLimit = limit;
stackTraceRegistered = true;
} catch (e) {
// Not all browsers support this so we don't care if it errors
}
}
function unregisterStackTraceLimit() {
if (!stackTraceRegistered) {
return;
}
try {
Error.stackTraceLimit = restoreStackTraceValue;
stackTraceRegistered = false;
} catch (e) {
// Not all browsers support this so we don't care if it errors
}
}
export { registerStackTraceLimit as register, unregisterStackTraceLimit as unregister };

View File

@@ -0,0 +1,44 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var boundErrorHandler = null;
function errorHandler(callback, e) {
if (!e.error) {
return;
}
// $FlowFixMe
var error = e.error;
if (error instanceof Error) {
callback(error);
} else {
// A non-error was thrown, we don't have a trace. :(
// Look in your browser's devtools for more information
callback(new Error(error));
}
}
function registerUnhandledError(target, callback) {
if (boundErrorHandler !== null) {
return;
}
boundErrorHandler = errorHandler.bind(undefined, callback);
target.addEventListener('error', boundErrorHandler);
}
function unregisterUnhandledError(target) {
if (boundErrorHandler === null) {
return;
}
target.removeEventListener('error', boundErrorHandler);
boundErrorHandler = null;
}
export { registerUnhandledError as register, unregisterUnhandledError as unregister };

View File

@@ -0,0 +1,44 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var boundRejectionHandler = null;
function rejectionHandler(callback, e) {
if (e == null || e.reason == null) {
return callback(new Error('Unknown'));
}
var reason = e.reason;
if (reason instanceof Error) {
return callback(reason);
}
// A non-error was rejected, we don't have a trace :(
// Look in your browser's devtools for more information
return callback(new Error(reason));
}
function registerUnhandledRejection(target, callback) {
if (boundRejectionHandler !== null) {
return;
}
boundRejectionHandler = rejectionHandler.bind(undefined, callback);
// $FlowFixMe
target.addEventListener('unhandledrejection', boundRejectionHandler);
}
function unregisterUnhandledRejection(target) {
if (boundRejectionHandler === null) {
return;
}
// $FlowFixMe
target.removeEventListener('unhandledrejection', boundRejectionHandler);
boundRejectionHandler = null;
}
export { registerUnhandledRejection as register, unregisterUnhandledRejection as unregister };

17
web/node_modules/react-error-overlay/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { inject, uninject } from './overlay';
inject();
if (module.hot && typeof module.hot.dispose === 'function') {
module.hot.dispose(function () {
uninject();
});
}

200
web/node_modules/react-error-overlay/lib/overlay.js generated vendored Normal file
View File

@@ -0,0 +1,200 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { register as registerError, unregister as unregisterError } from './effects/unhandledError';
import { register as registerPromise, unregister as unregisterPromise } from './effects/unhandledRejection';
import { register as registerShortcuts, unregister as unregisterShortcuts, handler as keyEventHandler, SHORTCUT_ESCAPE, SHORTCUT_LEFT, SHORTCUT_RIGHT } from './effects/shortcuts';
import { register as registerStackTraceLimit, unregister as unregisterStackTraceLimit } from './effects/stackTraceLimit';
import { permanentRegister as permanentRegisterConsole, registerReactStack, unregisterReactStack } from './effects/proxyConsole';
import { massage as massageWarning } from './utils/warnings';
import { consume as consumeError, getErrorRecord, drain as drainErrors } from './utils/errorRegister';
import { iframeStyle } from './styles';
import { applyStyles } from './utils/dom/css';
import { createOverlay } from './components/overlay';
import { updateAdditional } from './components/additional';
var CONTEXT_SIZE = 3;
var iframeReference = null;
var additionalReference = null;
var errorReferences = [];
var currReferenceIndex = -1;
function render(name, message, resolvedFrames) {
disposeCurrentView();
var iframe = window.document.createElement('iframe');
applyStyles(iframe, iframeStyle);
iframeReference = iframe;
iframe.onload = function () {
if (iframeReference == null) {
return;
}
var w = iframeReference.contentWindow;
var document = iframeReference.contentDocument;
var _createOverlay = createOverlay(document, name, message, resolvedFrames, CONTEXT_SIZE, currReferenceIndex + 1, errorReferences.length, function (offset) {
switchError(offset);
}, function () {
unmount();
}),
overlay = _createOverlay.overlay,
additional = _createOverlay.additional;
if (w != null) {
w.onkeydown = function (event) {
keyEventHandler(function (type) {
return shortcutHandler(type);
}, event);
};
}
if (document.body != null) {
document.body.style.margin = '0';
// Keep popup within body boundaries for iOS Safari
// $FlowFixMe
document.body.style['max-width'] = '100vw';
document.body.appendChild(overlay);
}
additionalReference = additional;
};
window.document.body.appendChild(iframe);
}
function renderErrorByIndex(index) {
currReferenceIndex = index;
var _getErrorRecord = getErrorRecord(errorReferences[index]),
error = _getErrorRecord.error,
unhandledRejection = _getErrorRecord.unhandledRejection,
enhancedFrames = _getErrorRecord.enhancedFrames;
if (unhandledRejection) {
render('Unhandled Rejection (' + error.name + ')', error.message, enhancedFrames);
} else {
render(error.name, error.message, enhancedFrames);
}
}
function switchError(offset) {
if (errorReferences.length === 0) {
return;
}
var nextView = currReferenceIndex + offset;
if (nextView < 0) {
nextView = errorReferences.length - 1;
} else if (nextView >= errorReferences.length) {
nextView = 0;
}
renderErrorByIndex(nextView);
}
function disposeCurrentView() {
if (iframeReference === null) {
return;
}
window.document.body.removeChild(iframeReference);
iframeReference = null;
additionalReference = null;
}
function unmount() {
disposeCurrentView();
drainErrors();
errorReferences = [];
currReferenceIndex = -1;
}
function crash(error) {
var unhandledRejection = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (module.hot && typeof module.hot.decline === 'function') {
module.hot.decline();
}
consumeError(error, unhandledRejection, CONTEXT_SIZE).then(function (ref) {
if (ref == null) {
return;
}
errorReferences.push(ref);
if (iframeReference !== null && additionalReference !== null) {
updateAdditional(iframeReference.contentDocument, additionalReference, currReferenceIndex + 1, errorReferences.length, function (offset) {
switchError(offset);
});
} else {
if (errorReferences.length !== 1) {
throw new Error('Something is *really* wrong.');
}
renderErrorByIndex(currReferenceIndex = 0);
}
}).catch(function (e) {
console.log('Could not consume error:', e);
});
}
function shortcutHandler(type) {
switch (type) {
case SHORTCUT_ESCAPE:
{
unmount();
break;
}
case SHORTCUT_LEFT:
{
switchError(-1);
break;
}
case SHORTCUT_RIGHT:
{
switchError(1);
break;
}
default:
{
//TODO: this
break;
}
}
}
function inject() {
registerError(window, function (error) {
return crash(error);
});
registerPromise(window, function (error) {
return crash(error, true);
});
registerShortcuts(window, shortcutHandler);
registerStackTraceLimit();
registerReactStack();
permanentRegisterConsole('error', function (warning, stack) {
var data = massageWarning(warning, stack);
crash(
// $FlowFixMe
{
message: data.message,
stack: data.stack,
__unmap_source: '/static/js/bundle.js'
}, false);
});
}
function uninject() {
unregisterStackTraceLimit();
unregisterShortcuts(window);
unregisterPromise(window);
unregisterError(window);
unregisterReactStack();
}
export { inject, uninject };

196
web/node_modules/react-error-overlay/lib/styles.js generated vendored Normal file
View File

@@ -0,0 +1,196 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var black = '#293238',
darkGray = '#878e91',
red = '#ce1126',
redTransparent = 'rgba(206, 17, 38, 0.05)',
lightRed = '#fccfcf',
yellow = '#fbf5b4',
yellowTransparent = 'rgba(251, 245, 180, 0.3)',
white = '#ffffff';
var iframeStyle = {
position: 'fixed',
top: '0',
left: '0',
width: '100%',
height: '100%',
border: 'none',
'z-index': 2147483647 - 1 // below the compile error overlay
};
var overlayStyle = {
width: '100%',
height: '100%',
'box-sizing': 'border-box',
'text-align': 'center',
'background-color': white
};
var containerStyle = {
position: 'relative',
display: 'inline-flex',
'flex-direction': 'column',
height: '100%',
width: '1024px',
'max-width': '100%',
'overflow-x': 'hidden',
'overflow-y': 'auto',
padding: '0.5rem',
'box-sizing': 'border-box',
'text-align': 'left',
'font-family': 'Consolas, Menlo, monospace',
'font-size': '11px',
'white-space': 'pre-wrap',
'word-break': 'break-word',
'line-height': 1.5,
color: black
};
var hintsStyle = {
color: darkGray
};
var hintStyle = {
padding: '0.5em 1em',
cursor: 'pointer'
};
var closeButtonStyle = {
color: black,
'line-height': '1rem',
'font-size': '1.5rem',
padding: '1rem',
cursor: 'pointer',
position: 'absolute',
right: 0,
top: 0
};
var additionalChildStyle = {
'margin-bottom': '0.5rem'
};
var headerStyle = {
'font-size': '2em',
'font-family': 'sans-serif',
color: red,
'white-space': 'pre-wrap',
// Top bottom margin spaces header
// Right margin revents overlap with close button
margin: '0 2rem 0.75rem 0',
flex: '0 0 auto',
'max-height': '50%',
overflow: 'auto'
};
var functionNameStyle = {};
var linkStyle = {
'font-size': '0.9em',
'margin-bottom': '0.9em'
};
var anchorStyle = {
'text-decoration': 'none',
color: darkGray
};
var traceStyle = {
'font-size': '1em',
flex: '0 1 auto',
'min-height': '0px',
overflow: 'auto'
};
var depStyle = {};
var primaryErrorStyle = {
'background-color': lightRed
};
var secondaryErrorStyle = {
'background-color': yellow
};
var omittedFramesCollapsedStyle = {
color: black,
cursor: 'pointer',
'margin-bottom': '1.5em'
};
var omittedFramesExpandedStyle = {
color: black,
cursor: 'pointer',
'margin-bottom': '0.6em'
};
var _preStyle = {
display: 'block',
padding: '0.5em',
'margin-top': '0.5em',
'margin-bottom': '0.5em',
'overflow-x': 'auto',
'white-space': 'pre-wrap',
'border-radius': '0.25rem'
};
var primaryPreStyle = Object.assign({}, _preStyle, {
'background-color': redTransparent
});
var secondaryPreStyle = Object.assign({}, _preStyle, {
'background-color': yellowTransparent
});
var toggleStyle = {
'margin-bottom': '1.5em',
color: darkGray,
cursor: 'pointer'
};
var codeStyle = {
'font-family': 'Consolas, Menlo, monospace'
};
var hiddenStyle = {
display: 'none'
};
var groupStyle = {
'margin-right': '1em'
};
var _groupElemStyle = {
'background-color': redTransparent,
color: red,
border: 'none',
'border-radius': '4px',
padding: '3px 6px',
cursor: 'pointer'
};
var groupElemLeft = Object.assign({}, _groupElemStyle, {
'border-top-right-radius': '0px',
'border-bottom-right-radius': '0px',
'margin-right': '1px'
});
var groupElemRight = Object.assign({}, _groupElemStyle, {
'border-top-left-radius': '0px',
'border-bottom-left-radius': '0px'
});
var footerStyle = {
'font-family': 'sans-serif',
color: darkGray,
'margin-top': '0.5rem',
flex: '0 0 auto'
};
export { containerStyle, iframeStyle, overlayStyle, hintsStyle, hintStyle, closeButtonStyle, additionalChildStyle, headerStyle, functionNameStyle, linkStyle, anchorStyle, traceStyle, depStyle, primaryErrorStyle, primaryPreStyle, secondaryErrorStyle, secondaryPreStyle, omittedFramesCollapsedStyle, omittedFramesExpandedStyle, toggleStyle, codeStyle, hiddenStyle, groupStyle, groupElemLeft, groupElemRight, footerStyle };

View File

@@ -0,0 +1,42 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function removeNextBr(parent, component) {
while (component != null && component.tagName.toLowerCase() !== 'br') {
component = component.nextElementSibling;
}
if (component != null) {
parent.removeChild(component);
}
}
function absolutifyCaret(component) {
var ccn = component.childNodes;
for (var index = 0; index < ccn.length; ++index) {
var c = ccn[index];
// $FlowFixMe
if (c.tagName.toLowerCase() !== 'span') {
continue;
}
var _text = c.innerText;
if (_text == null) {
continue;
}
var text = _text.replace(/\s/g, '');
if (text !== '|^') {
continue;
}
// $FlowFixMe
c.style.position = 'absolute';
// $FlowFixMe
removeNextBr(component, c);
}
}
export { absolutifyCaret };

View File

@@ -0,0 +1,17 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function consumeEvent(e) {
e.preventDefault();
if (typeof e.target.blur === 'function') {
e.target.blur();
}
}
export { consumeEvent };

View File

@@ -0,0 +1,48 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var injectedCount = 0;
var injectedCache = {};
function getHead(document) {
return document.head || document.getElementsByTagName('head')[0];
}
function injectCss(document, css) {
var head = getHead(document);
var style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(css));
head.appendChild(style);
injectedCache[++injectedCount] = style;
return injectedCount;
}
function removeCss(document, ref) {
if (injectedCache[ref] == null) {
return;
}
var head = getHead(document);
head.removeChild(injectedCache[ref]);
delete injectedCache[ref];
}
function applyStyles(element, styles) {
element.setAttribute('style', '');
for (var key in styles) {
if (!styles.hasOwnProperty(key)) {
continue;
}
// $FlowFixMe
element.style[key] = styles[key];
}
}
export { getHead, injectCss, removeCss, applyStyles };

View File

@@ -0,0 +1,26 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function enableTabClick(node) {
node.setAttribute('tabindex', '0');
node.addEventListener('keydown', function (e) {
var key = e.key,
which = e.which,
keyCode = e.keyCode;
if (key === 'Enter' || which === 13 || keyCode === 13) {
e.preventDefault();
if (typeof e.target.click === 'function') {
e.target.click();
}
}
});
}
export { enableTabClick };

View File

@@ -0,0 +1,65 @@
import { parse } from './parser'; /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { map } from './mapper';
import { unmap } from './unmapper';
var recorded = [];
var errorsConsumed = 0;
function consume(error) {
var unhandledRejection = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var contextSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3;
var parsedFrames = parse(error);
var enhancedFramesPromise = void 0;
if (error.__unmap_source) {
enhancedFramesPromise = unmap(
// $FlowFixMe
error.__unmap_source, parsedFrames, contextSize);
} else {
enhancedFramesPromise = map(parsedFrames, contextSize);
}
return enhancedFramesPromise.then(function (enhancedFrames) {
if (enhancedFrames.map(function (f) {
return f._originalFileName;
}).filter(function (f) {
return f != null && f.indexOf('node_modules') === -1;
}).length === 0) {
return null;
}
enhancedFrames = enhancedFrames.filter(function (_ref) {
var functionName = _ref.functionName;
return functionName == null || functionName.indexOf('__stack_frame_overlay_proxy_console__') === -1;
});
recorded[++errorsConsumed] = {
error: error,
unhandledRejection: unhandledRejection,
contextSize: contextSize,
enhancedFrames: enhancedFrames
};
return errorsConsumed;
});
}
function getErrorRecord(ref) {
return recorded[ref];
}
function drain() {
// $FlowFixMe
var keys = Object.keys(recorded);
for (var index = 0; index < keys.length; ++index) {
delete recorded[keys[index]];
}
}
export { consume, getErrorRecord, drain };

View File

@@ -0,0 +1,30 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { ScriptLine } from './stack-frame';
/**
*
* @param {number} line The line number to provide context around.
* @param {number} count The number of lines you'd like for context.
* @param {string[] | string} lines The source code.
*/
function getLinesAround(line, count, lines) {
if (typeof lines === 'string') {
lines = lines.split('\n');
}
var result = [];
for (var index = Math.max(0, line - 1 - count); index <= Math.min(lines.length - 1, line - 1 + count); ++index) {
result.push(new ScriptLine(index + 1, lines[index], index === line - 1));
}
return result;
}
export { getLinesAround };
export default getLinesAround;

View File

@@ -0,0 +1,179 @@
import _regeneratorRuntime from 'babel-runtime/regenerator';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
/**
* Returns an instance of <code>{@link SourceMap}</code> for a given fileUri and fileContents.
* @param {string} fileUri The URI of the source file.
* @param {string} fileContents The contents of the source file.
*/
var getSourceMap = function () {
var _ref = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(fileUri, fileContents) {
var sm, base64, match2, index, url, obj;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return extractSourceMapUrl(fileUri, fileContents);
case 2:
sm = _context.sent;
if (!(sm.indexOf('data:') === 0)) {
_context.next = 14;
break;
}
base64 = /^data:application\/json;([\w=:"-]+;)*base64,/;
match2 = sm.match(base64);
if (match2) {
_context.next = 8;
break;
}
throw new Error('Sorry, non-base64 inline source-map encoding is not supported.');
case 8:
sm = sm.substring(match2[0].length);
sm = window.atob(sm);
sm = JSON.parse(sm);
return _context.abrupt('return', new SourceMap(new SourceMapConsumer(sm)));
case 14:
index = fileUri.lastIndexOf('/');
url = fileUri.substring(0, index + 1) + sm;
_context.next = 18;
return fetch(url).then(function (res) {
return res.json();
});
case 18:
obj = _context.sent;
return _context.abrupt('return', new SourceMap(new SourceMapConsumer(obj)));
case 20:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function getSourceMap(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { SourceMapConsumer } from 'source-map';
/**
* A wrapped instance of a <code>{@link https://github.com/mozilla/source-map SourceMapConsumer}</code>.
*
* This exposes methods which will be indifferent to changes made in <code>{@link https://github.com/mozilla/source-map source-map}</code>.
*/
var SourceMap = function () {
function SourceMap(sourceMap) {
_classCallCheck(this, SourceMap);
this.__source_map = sourceMap;
}
/**
* Returns the original code position for a generated code position.
* @param {number} line The line of the generated code position.
* @param {number} column The column of the generated code position.
*/
_createClass(SourceMap, [{
key: 'getOriginalPosition',
value: function getOriginalPosition(line, column) {
var _source_map$original = this.__source_map.originalPositionFor({
line: line,
column: column
}),
l = _source_map$original.line,
c = _source_map$original.column,
s = _source_map$original.source;
return { line: l, column: c, source: s };
}
/**
* Returns the generated code position for an original position.
* @param {string} source The source file of the original code position.
* @param {number} line The line of the original code position.
* @param {number} column The column of the original code position.
*/
}, {
key: 'getGeneratedPosition',
value: function getGeneratedPosition(source, line, column) {
var _source_map$generate = this.__source_map.generatedPositionFor({
source: source,
line: line,
column: column
}),
l = _source_map$generate.line,
c = _source_map$generate.column;
return {
line: l,
column: c
};
}
/**
* Returns the code for a given source file name.
* @param {string} sourceName The name of the source file.
*/
}, {
key: 'getSource',
value: function getSource(sourceName) {
return this.__source_map.sourceContentFor(sourceName);
}
}, {
key: 'getSources',
value: function getSources() {
return this.__source_map.sources;
}
}]);
return SourceMap;
}();
function extractSourceMapUrl(fileUri, fileContents) {
var regex = /\/\/[#@] ?sourceMappingURL=([^\s'"]+)\s*$/gm;
var match = null;
for (;;) {
var next = regex.exec(fileContents);
if (next == null) {
break;
}
match = next;
}
if (!(match && match[1])) {
return Promise.reject('Cannot find a source map directive for ' + fileUri + '.');
}
return Promise.resolve(match[1].toString());
}
export { extractSourceMapUrl, getSourceMap };
export default getSourceMap;

View File

@@ -0,0 +1,14 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function isInternalFile(sourceFileName, fileName) {
return sourceFileName == null || sourceFileName === '' || sourceFileName.indexOf('/~/') !== -1 || sourceFileName.indexOf('/node_modules/') !== -1 || sourceFileName.trim().indexOf(' ') !== -1 || fileName == null || fileName === '';
}
export { isInternalFile };

View File

@@ -0,0 +1,122 @@
import _regeneratorRuntime from 'babel-runtime/regenerator';
/**
* Enhances a set of <code>StackFrame</code>s with their original positions and code (when available).
* @param {StackFrame[]} frames A set of <code>StackFrame</code>s which contain (generated) code positions.
* @param {number} [contextLines=3] The number of lines to provide before and after the line specified in the <code>StackFrame</code>.
*/
var map = function () {
var _ref = _asyncToGenerator(_regeneratorRuntime.mark(function _callee2(frames) {
var _this = this;
var contextLines = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
var cache, files;
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
cache = {};
files = [];
frames.forEach(function (frame) {
var fileName = frame.fileName;
if (fileName == null) {
return;
}
if (files.indexOf(fileName) !== -1) {
return;
}
files.push(fileName);
});
_context2.next = 5;
return settle(files.map(function () {
var _ref2 = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(fileName) {
var fileSource, map;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return fetch(fileName).then(function (r) {
return r.text();
});
case 2:
fileSource = _context.sent;
_context.next = 5;
return getSourceMap(fileName, fileSource);
case 5:
map = _context.sent;
cache[fileName] = { fileSource: fileSource, map: map };
case 7:
case 'end':
return _context.stop();
}
}
}, _callee, _this);
}));
return function (_x3) {
return _ref2.apply(this, arguments);
};
}()));
case 5:
return _context2.abrupt('return', frames.map(function (frame) {
var functionName = frame.functionName,
fileName = frame.fileName,
lineNumber = frame.lineNumber,
columnNumber = frame.columnNumber;
var _ref3 = cache[fileName] || {},
map = _ref3.map,
fileSource = _ref3.fileSource;
if (map == null || lineNumber == null) {
return frame;
}
var _map$getOriginalPosit = map.getOriginalPosition(lineNumber, columnNumber),
source = _map$getOriginalPosit.source,
line = _map$getOriginalPosit.line,
column = _map$getOriginalPosit.column;
var originalSource = source == null ? [] : map.getSource(source);
return new StackFrame(functionName, fileName, lineNumber, columnNumber, getLinesAround(lineNumber, contextLines, fileSource), functionName, source, line, column, getLinesAround(line, contextLines, originalSource));
}));
case 6:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
return function map(_x2) {
return _ref.apply(this, arguments);
};
}();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import StackFrame from './stack-frame';
import { getSourceMap } from './getSourceMap';
import { getLinesAround } from './getLinesAround';
import { settle } from 'settle-promise';
export { map };
export default map;

View File

@@ -0,0 +1,80 @@
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import StackFrame from './stack-frame';
var regexExtractLocation = /\(?(.+?)(?::(\d+))?(?::(\d+))?\)?$/;
function extractLocation(token) {
return regexExtractLocation.exec(token).slice(1).map(function (v) {
var p = Number(v);
if (!isNaN(p)) {
return p;
}
return v;
});
}
var regexValidFrame_Chrome = /^\s*(at|in)\s.+(:\d+)/;
var regexValidFrame_FireFox = /(^|@)\S+:\d+|.+line\s+\d+\s+>\s+(eval|Function).+/;
function parseStack(stack) {
var frames = stack.filter(function (e) {
return regexValidFrame_Chrome.test(e) || regexValidFrame_FireFox.test(e);
}).map(function (e) {
if (regexValidFrame_FireFox.test(e)) {
// Strip eval, we don't care about it
var isEval = false;
if (/ > (eval|Function)/.test(e)) {
e = e.replace(/ line (\d+)(?: > eval line \d+)* > (eval|Function):\d+:\d+/g, ':$1');
isEval = true;
}
var data = e.split(/[@]/g);
var last = data.pop();
return new (Function.prototype.bind.apply(StackFrame, [null].concat([data.join('@') || (isEval ? 'eval' : null)], _toConsumableArray(extractLocation(last)))))();
} else {
// Strip eval, we don't care about it
if (e.indexOf('(eval ') !== -1) {
e = e.replace(/(\(eval at [^()]*)|(\),.*$)/g, '');
}
if (e.indexOf('(at ') !== -1) {
e = e.replace(/\(at /, '(');
}
var _data = e.trim().split(/\s+/g).slice(1);
var _last = _data.pop();
return new (Function.prototype.bind.apply(StackFrame, [null].concat([_data.join(' ') || null], _toConsumableArray(extractLocation(_last)))))();
}
});
return frames;
}
/**
* Turns an <code>Error</code>, or similar object, into a set of <code>StackFrame</code>s.
* @alias parse
*/
function parseError(error) {
if (error == null) {
throw new Error('You cannot pass a null object.');
}
if (typeof error === 'string') {
return parseStack(error.split('\n'));
}
if (Array.isArray(error)) {
return parseStack(error);
}
if (typeof error.stack === 'string') {
return parseStack(error.stack.split('\n'));
}
throw new Error('The error you provided does not contain a stack trace.');
}
export { parseError as parse };
export default parseError;

View File

@@ -0,0 +1,117 @@
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/** A container holding a script line. */
var ScriptLine =
/** The content (or value) of this line of source. */
function ScriptLine(lineNumber, content) {
var highlight = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
_classCallCheck(this, ScriptLine);
this.lineNumber = lineNumber;
this.content = content;
this.highlight = highlight;
}
/** Whether or not this line should be highlighted. Particularly useful for error reporting with context. */
/** The line number of this line of source. */
;
/**
* A representation of a stack frame.
*/
var StackFrame = function () {
function StackFrame() {
var functionName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var fileName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var lineNumber = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var columnNumber = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var scriptCode = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
var sourceFunctionName = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null;
var sourceFileName = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null;
var sourceLineNumber = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null;
var sourceColumnNumber = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null;
var sourceScriptCode = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : null;
_classCallCheck(this, StackFrame);
this.functionName = functionName;
this.fileName = fileName;
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this._originalFunctionName = sourceFunctionName;
this._originalFileName = sourceFileName;
this._originalLineNumber = sourceLineNumber;
this._originalColumnNumber = sourceColumnNumber;
this._scriptCode = scriptCode;
this._originalScriptCode = sourceScriptCode;
}
/**
* Returns the name of this function.
*/
_createClass(StackFrame, [{
key: 'getFunctionName',
value: function getFunctionName() {
return this.functionName;
}
/**
* Returns the source of the frame.
* This contains the file name, line number, and column number when available.
*/
}, {
key: 'getSource',
value: function getSource() {
var str = '';
if (this.fileName != null) {
str += this.fileName + ':';
}
if (this.lineNumber != null) {
str += this.lineNumber + ':';
}
if (this.columnNumber != null) {
str += this.columnNumber + ':';
}
return str.slice(0, -1);
}
/**
* Returns a pretty version of this stack frame.
*/
}, {
key: 'toString',
value: function toString() {
var f = this.getFunctionName();
if (f == null) {
return this.getSource();
}
return f + ' (' + this.getSource() + ')';
}
}]);
return StackFrame;
}();
export { StackFrame, ScriptLine };
export default StackFrame;

View File

@@ -0,0 +1,137 @@
import _regeneratorRuntime from 'babel-runtime/regenerator';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/**
* Turns a set of mapped <code>StackFrame</code>s back into their generated code position and enhances them with code.
* @param {string} fileUri The URI of the <code>bundle.js</code> file.
* @param {StackFrame[]} frames A set of <code>StackFrame</code>s which are already mapped and missing their generated positions.
* @param {number} [fileContents=3] The number of lines to provide before and after the line specified in the <code>StackFrame</code>.
*/
var unmap = function () {
var _ref = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(_fileUri, frames) {
var contextLines = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3;
var fileContents, fileUri, map;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
fileContents = (typeof _fileUri === 'undefined' ? 'undefined' : _typeof(_fileUri)) === 'object' ? _fileUri.contents : null;
fileUri = (typeof _fileUri === 'undefined' ? 'undefined' : _typeof(_fileUri)) === 'object' ? _fileUri.uri : _fileUri;
if (!(fileContents == null)) {
_context.next = 6;
break;
}
_context.next = 5;
return fetch(fileUri).then(function (res) {
return res.text();
});
case 5:
fileContents = _context.sent;
case 6:
_context.next = 8;
return getSourceMap(fileUri, fileContents);
case 8:
map = _context.sent;
return _context.abrupt('return', frames.map(function (frame) {
var functionName = frame.functionName,
lineNumber = frame.lineNumber,
columnNumber = frame.columnNumber,
_originalLineNumber = frame._originalLineNumber;
if (_originalLineNumber != null) {
return frame;
}
var fileName = frame.fileName;
if (fileName) {
fileName = path.normalize(fileName);
}
if (fileName == null) {
return frame;
}
var fN = fileName;
var source = map.getSources().map(function (s) {
return s.replace(/[\\]+/g, '/');
}).filter(function (p) {
p = path.normalize(p);
var i = p.lastIndexOf(fN);
return i !== -1 && i === p.length - fN.length;
}).map(function (p) {
return {
token: p,
seps: count(path.sep, path.normalize(p)),
penalties: count('node_modules', p) + count('~', p)
};
}).sort(function (a, b) {
var s = Math.sign(a.seps - b.seps);
if (s !== 0) {
return s;
}
return Math.sign(a.penalties - b.penalties);
});
if (source.length < 1 || lineNumber == null) {
return new StackFrame(null, null, null, null, null, functionName, fN, lineNumber, columnNumber, null);
}
var sourceT = source[0].token;
var _map$getGeneratedPosi = map.getGeneratedPosition(sourceT, lineNumber,
// $FlowFixMe
columnNumber),
line = _map$getGeneratedPosi.line,
column = _map$getGeneratedPosi.column;
var originalSource = map.getSource(sourceT);
return new StackFrame(functionName, fileUri, line, column || null, getLinesAround(line, contextLines, fileContents || []), functionName, fN, lineNumber, columnNumber, getLinesAround(lineNumber, contextLines, originalSource));
}));
case 10:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function unmap(_x2, _x3) {
return _ref.apply(this, arguments);
};
}();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import StackFrame from './stack-frame';
import { getSourceMap } from './getSourceMap';
import { getLinesAround } from './getLinesAround';
import path from 'path';
function count(search, string) {
// Count starts at -1 becuse a do-while loop always runs at least once
var count = -1,
index = -1;
do {
// First call or the while case evaluated true, meaning we have to make
// count 0 or we found a character
++count;
// Find the index of our search string, starting after the previous index
index = string.indexOf(search, index + 1);
} while (index !== -1);
return count;
}
export { unmap };
export default unmap;

View File

@@ -0,0 +1,48 @@
function stripInlineStacktrace(message) {
return message.split('\n').filter(function (line) {
return !line.match(/^\s*in/);
}).join('\n'); // " in Foo"
} /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function massage(warning, frames) {
var message = stripInlineStacktrace(warning);
// Reassemble the stack with full filenames provided by React
var stack = '';
var lastFilename = void 0;
var lastLineNumber = void 0;
for (var index = 0; index < frames.length; ++index) {
var _frames$index = frames[index],
fileName = _frames$index.fileName,
lineNumber = _frames$index.lineNumber;
if (fileName == null || lineNumber == null) {
continue;
}
// TODO: instead, collapse them in the UI
if (fileName === lastFilename && typeof lineNumber === 'number' && typeof lastLineNumber === 'number' && Math.abs(lineNumber - lastLineNumber) < 3) {
continue;
}
lastFilename = fileName;
lastLineNumber = lineNumber;
var name = frames[index].name;
name = name || '(anonymous function)';
stack += 'in ' + name + ' (at ' + fileName + ':' + lineNumber + ')\n';
}
return { message: message, stack: stack };
}
export { massage };

23
web/node_modules/react-error-overlay/middleware.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
const launchEditor = require('react-dev-utils/launchEditor');
module.exports = function createLaunchEditorMiddleware() {
return function launchEditorMiddleware(req, res, next) {
// Keep this in sync with react-error-overlay
if (req.url.startsWith('/__open-stack-frame-in-editor')) {
launchEditor(req.query.fileName, req.query.lineNumber);
res.end();
} else {
next();
}
};
};

View File

@@ -0,0 +1,3 @@
src
test
node_modules

View File

@@ -0,0 +1,43 @@
# babel-code-frame
> Generate errors that contain a code frame that point to source locations.
## Install
```sh
npm install --save-dev babel-code-frame
```
## Usage
```js
import codeFrame from 'babel-code-frame';
const rawLines = `class Foo {
constructor()
}`;
const lineNumber = 2;
const colNumber = 16;
const result = codeFrame(rawLines, lineNumber, colNumber, { /* options */ });
console.log(result);
```
```sh
1 | class Foo {
> 2 | constructor()
| ^
3 | }
```
If the column number is not known, you may pass `null` instead.
## Options
name | type | default | description
-----------------------|----------|-----------------|------------------------------------------------------
highlightCode | boolean | `false` | Syntax highlight the code as JavaScript for terminals
linesAbove | number | 2 | The number of lines to show above the error
linesBelow | number | 3 | The number of lines to show below the error
forceColor | boolean | `false` | Forcibly syntax highlight the code as JavaScript (for non-terminals); overrides highlightCode

View File

@@ -0,0 +1,141 @@
"use strict";
exports.__esModule = true;
exports.default = function (rawLines, lineNumber, colNumber) {
var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
colNumber = Math.max(colNumber, 0);
var highlighted = opts.highlightCode && _chalk2.default.supportsColor || opts.forceColor;
var chalk = _chalk2.default;
if (opts.forceColor) {
chalk = new _chalk2.default.constructor({ enabled: true });
}
var maybeHighlight = function maybeHighlight(chalkFn, string) {
return highlighted ? chalkFn(string) : string;
};
var defs = getDefs(chalk);
if (highlighted) rawLines = highlight(defs, rawLines);
var linesAbove = opts.linesAbove || 2;
var linesBelow = opts.linesBelow || 3;
var lines = rawLines.split(NEWLINE);
var start = Math.max(lineNumber - (linesAbove + 1), 0);
var end = Math.min(lines.length, lineNumber + linesBelow);
if (!lineNumber && !colNumber) {
start = 0;
end = lines.length;
}
var numberMaxWidth = String(end).length;
var frame = lines.slice(start, end).map(function (line, index) {
var number = start + 1 + index;
var paddedNumber = (" " + number).slice(-numberMaxWidth);
var gutter = " " + paddedNumber + " | ";
if (number === lineNumber) {
var markerLine = "";
if (colNumber) {
var markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " ");
markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^")].join("");
}
return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
} else {
return " " + maybeHighlight(defs.gutter, gutter) + line;
}
}).join("\n");
if (highlighted) {
return chalk.reset(frame);
} else {
return frame;
}
};
var _jsTokens = require("js-tokens");
var _jsTokens2 = _interopRequireDefault(_jsTokens);
var _esutils = require("esutils");
var _esutils2 = _interopRequireDefault(_esutils);
var _chalk = require("chalk");
var _chalk2 = _interopRequireDefault(_chalk);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getDefs(chalk) {
return {
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsx_tag: chalk.yellow,
punctuator: chalk.yellow,
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold,
gutter: chalk.grey,
marker: chalk.red.bold
};
}
var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
var JSX_TAG = /^[a-z][\w-]*$/i;
var BRACKET = /^[()\[\]{}]$/;
function getTokenType(match) {
var _match$slice = match.slice(-2),
offset = _match$slice[0],
text = _match$slice[1];
var token = (0, _jsTokens.matchToToken)(match);
if (token.type === "name") {
if (_esutils2.default.keyword.isReservedWordES6(token.value)) {
return "keyword";
}
if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
return "jsx_tag";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
return token.type;
}
function highlight(defs, text) {
return text.replace(_jsTokens2.default, function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var type = getTokenType(args);
var colorize = defs[type];
if (colorize) {
return args[0].split(NEWLINE).map(function (str) {
return colorize(str);
}).join("\n");
} else {
return args[0];
}
});
}
module.exports = exports["default"];

View File

@@ -0,0 +1,46 @@
{
"_from": "babel-code-frame@6.22.0",
"_id": "babel-code-frame@6.22.0",
"_inBundle": false,
"_integrity": "sha1-AnYgvuVnqIwyVhV05/0IAdMxGOQ=",
"_location": "/react-error-overlay/babel-code-frame",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "babel-code-frame@6.22.0",
"name": "babel-code-frame",
"escapedName": "babel-code-frame",
"rawSpec": "6.22.0",
"saveSpec": null,
"fetchSpec": "6.22.0"
},
"_requiredBy": [
"/react-error-overlay"
],
"_resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.22.0.tgz",
"_shasum": "027620bee567a88c32561574e7fd0801d33118e4",
"_spec": "babel-code-frame@6.22.0",
"_where": "/home/bilal/Saburly/slucajna-televizija/node_modules/react-error-overlay",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"chalk": "^1.1.0",
"esutils": "^2.0.2",
"js-tokens": "^3.0.0"
},
"deprecated": false,
"description": "Generate errors that contain a code frame that point to source locations.",
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"name": "babel-code-frame",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-code-frame"
},
"version": "6.22.0"
}

View File

@@ -0,0 +1,301 @@
# Change Log
## 0.5.6
* Fix for regression when people were using numbers as names in source maps. See
#236.
## 0.5.5
* Fix "regression" of unsupported, implementation behavior that half the world
happens to have come to depend on. See #235.
* Fix regression involving function hoisting in SpiderMonkey. See #233.
## 0.5.4
* Large performance improvements to source-map serialization. See #228 and #229.
## 0.5.3
* Do not include unnecessary distribution files. See
commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86.
## 0.5.2
* Include browser distributions of the library in package.json's `files`. See
issue #212.
## 0.5.1
* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See
ff05274becc9e6e1295ed60f3ea090d31d843379.
## 0.5.0
* Node 0.8 is no longer supported.
* Use webpack instead of dryice for bundling.
* Big speedups serializing source maps. See pull request #203.
* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that
explicitly start with the source root. See issue #199.
## 0.4.4
* Fix an issue where using a `SourceMapGenerator` after having created a
`SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See
issue #191.
* Fix an issue with where `SourceMapGenerator` would mistakenly consider
different mappings as duplicates of each other and avoid generating them. See
issue #192.
## 0.4.3
* A very large number of performance improvements, particularly when parsing
source maps. Collectively about 75% of time shaved off of the source map
parsing benchmark!
* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy
searching in the presence of a column option. See issue #177.
* Fix a bug with joining a source and its source root when the source is above
the root. See issue #182.
* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to
determine when all sources' contents are inlined into the source map. See
issue #190.
## 0.4.2
* Add an `.npmignore` file so that the benchmarks aren't pulled down by
dependent projects. Issue #169.
* Add an optional `column` argument to
`SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines
with no mappings. Issues #172 and #173.
## 0.4.1
* Fix accidentally defining a global variable. #170.
## 0.4.0
* The default direction for fuzzy searching was changed back to its original
direction. See #164.
* There is now a `bias` option you can supply to `SourceMapConsumer` to control
the fuzzy searching direction. See #167.
* About an 8% speed up in parsing source maps. See #159.
* Added a benchmark for parsing and generating source maps.
## 0.3.0
* Change the default direction that searching for positions fuzzes when there is
not an exact match. See #154.
* Support for environments using json2.js for JSON serialization. See #156.
## 0.2.0
* Support for consuming "indexed" source maps which do not have any remote
sections. See pull request #127. This introduces a minor backwards
incompatibility if you are monkey patching `SourceMapConsumer.prototype`
methods.
## 0.1.43
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
#148 for some discussion and issues #150, #151, and #152 for implementations.
## 0.1.42
* Fix an issue where `SourceNode`s from different versions of the source-map
library couldn't be used in conjunction with each other. See issue #142.
## 0.1.41
* Fix a bug with getting the source content of relative sources with a "./"
prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).
* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
column span of each mapping.
* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
all generated positions associated with a given original source and line.
## 0.1.40
* Performance improvements for parsing source maps in SourceMapConsumer.
## 0.1.39
* Fix a bug where setting a source's contents to null before any source content
had been set before threw a TypeError. See issue #131.
## 0.1.38
* Fix a bug where finding relative paths from an empty path were creating
absolute paths. See issue #129.
## 0.1.37
* Fix a bug where if the source root was an empty string, relative source paths
would turn into absolute source paths. Issue #124.
## 0.1.36
* Allow the `names` mapping property to be an empty string. Issue #121.
## 0.1.35
* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
to specify a path that relative sources in the second parameter should be
relative to. Issue #105.
* If no file property is given to a `SourceMapGenerator`, then the resulting
source map will no longer have a `null` file property. The property will
simply not exist. Issue #104.
* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
Issue #116.
## 0.1.34
* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.
* Fix bug involving source contents and the
`SourceMapGenerator.prototype.applySourceMap`. Issue #100.
## 0.1.33
* Fix some edge cases surrounding path joining and URL resolution.
* Add a third parameter for relative path to
`SourceMapGenerator.prototype.applySourceMap`.
* Fix issues with mappings and EOLs.
## 0.1.32
* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
(issue 92).
* Fixed test runner to actually report number of failed tests as its process
exit code.
* Fixed a typo when reporting bad mappings (issue 87).
## 0.1.31
* Delay parsing the mappings in SourceMapConsumer until queried for a source
location.
* Support Sass source maps (which at the time of writing deviate from the spec
in small ways) in SourceMapConsumer.
## 0.1.30
* Do not join source root with a source, when the source is a data URI.
* Extend the test runner to allow running single specific test files at a time.
* Performance improvements in `SourceNode.prototype.walk` and
`SourceMapConsumer.prototype.eachMapping`.
* Source map browser builds will now work inside Workers.
* Better error messages when attempting to add an invalid mapping to a
`SourceMapGenerator`.
## 0.1.29
* Allow duplicate entries in the `names` and `sources` arrays of source maps
(usually from TypeScript) we are parsing. Fixes github issue 72.
## 0.1.28
* Skip duplicate mappings when creating source maps from SourceNode; github
issue 75.
## 0.1.27
* Don't throw an error when the `file` property is missing in SourceMapConsumer,
we don't use it anyway.
## 0.1.26
* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.
## 0.1.25
* Make compatible with browserify
## 0.1.24
* Fix issue with absolute paths and `file://` URIs. See
https://bugzilla.mozilla.org/show_bug.cgi?id=885597
## 0.1.23
* Fix issue with absolute paths and sourcesContent, github issue 64.
## 0.1.22
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
## 0.1.21
* Fixed handling of sources that start with a slash so that they are relative to
the source root's host.
## 0.1.20
* Fixed github issue #43: absolute URLs aren't joined with the source root
anymore.
## 0.1.19
* Using Travis CI to run tests.
## 0.1.18
* Fixed a bug in the handling of sourceRoot.
## 0.1.17
* Added SourceNode.fromStringWithSourceMap.
## 0.1.16
* Added missing documentation.
* Fixed the generating of empty mappings in SourceNode.
## 0.1.15
* Added SourceMapGenerator.applySourceMap.
## 0.1.14
* The sourceRoot is now handled consistently.
## 0.1.13
* Added SourceMapGenerator.fromSourceMap.
## 0.1.12
* SourceNode now generates empty mappings too.
## 0.1.11
* Added name support to SourceNode.
## 0.1.10
* Added sourcesContent support to the customer and generator.

View File

@@ -0,0 +1,28 @@
Copyright (c) 2009-2011, Mozilla Foundation and contributors
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 names of the Mozilla Foundation nor the names of project
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 HOLDER 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.

View File

@@ -0,0 +1,729 @@
# Source Map
[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)
[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map)
This is a library to generate and consume the source map format
[described here][format].
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
## Use with Node
$ npm install source-map
## Use on the Web
<script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script>
--------------------------------------------------------------------------------
<!-- `npm run toc` to regenerate the Table of Contents -->
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of Contents
- [Examples](#examples)
- [Consuming a source map](#consuming-a-source-map)
- [Generating a source map](#generating-a-source-map)
- [With SourceNode (high level API)](#with-sourcenode-high-level-api)
- [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
- [API](#api)
- [SourceMapConsumer](#sourcemapconsumer)
- [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
- [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
- [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
- [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
- [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
- [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
- [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
- [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
- [SourceMapGenerator](#sourcemapgenerator)
- [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
- [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
- [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
- [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
- [SourceNode](#sourcenode)
- [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
- [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
- [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
- [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
- [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
- [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
- [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
- [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
- [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
- [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Examples
### Consuming a source map
```js
var rawSourceMap = {
version: 3,
file: 'min.js',
names: ['bar', 'baz', 'n'],
sources: ['one.js', 'two.js'],
sourceRoot: 'http://example.com/www/js/',
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
};
var smc = new SourceMapConsumer(rawSourceMap);
console.log(smc.sources);
// [ 'http://example.com/www/js/one.js',
// 'http://example.com/www/js/two.js' ]
console.log(smc.originalPositionFor({
line: 2,
column: 28
}));
// { source: 'http://example.com/www/js/two.js',
// line: 2,
// column: 10,
// name: 'n' }
console.log(smc.generatedPositionFor({
source: 'http://example.com/www/js/two.js',
line: 2,
column: 10
}));
// { line: 2, column: 28 }
smc.eachMapping(function (m) {
// ...
});
```
### Generating a source map
In depth guide:
[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
#### With SourceNode (high level API)
```js
function compile(ast) {
switch (ast.type) {
case 'BinaryExpression':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
[compile(ast.left), " + ", compile(ast.right)]
);
case 'Literal':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
String(ast.value)
);
// ...
default:
throw new Error("Bad AST");
}
}
var ast = parse("40 + 2", "add.js");
console.log(compile(ast).toStringWithSourceMap({
file: 'add.js'
}));
// { code: '40 + 2',
// map: [object SourceMapGenerator] }
```
#### With SourceMapGenerator (low level API)
```js
var map = new SourceMapGenerator({
file: "source-mapped.js"
});
map.addMapping({
generated: {
line: 10,
column: 35
},
source: "foo.js",
original: {
line: 33,
column: 2
},
name: "christopher"
});
console.log(map.toString());
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
```
## API
Get a reference to the module:
```js
// Node.js
var sourceMap = require('source-map');
// Browser builds
var sourceMap = window.sourceMap;
// Inside Firefox
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
```
### SourceMapConsumer
A SourceMapConsumer instance represents a parsed source map which we can query
for information about the original file positions by giving it a file position
in the generated source.
#### new SourceMapConsumer(rawSourceMap)
The only parameter is the raw source map (either as a string which can be
`JSON.parse`'d, or an object). According to the spec, source maps have the
following attributes:
* `version`: Which version of the source map spec this map is following.
* `sources`: An array of URLs to the original source files.
* `names`: An array of identifiers which can be referenced by individual
mappings.
* `sourceRoot`: Optional. The URL root from which all sources are relative.
* `sourcesContent`: Optional. An array of contents of the original source files.
* `mappings`: A string of base64 VLQs which contain the actual mappings.
* `file`: Optional. The generated filename this source map is associated with.
```js
var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
```
#### SourceMapConsumer.prototype.computeColumnSpans()
Compute the last column for each generated mapping. The last column is
inclusive.
```js
// Before:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
consumer.computeColumnSpans();
// After:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1,
// lastColumn: 9 },
// { line: 2,
// column: 10,
// lastColumn: 19 },
// { line: 2,
// column: 20,
// lastColumn: Infinity } ]
```
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
Returns the original source, line, and column information for the generated
source's line and column positions provided. The only argument is an object with
the following properties:
* `line`: The line number in the generated source.
* `column`: The column number in the generated source.
* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
`SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
element that is smaller than or greater than the one we are searching for,
respectively, if the exact element cannot be found. Defaults to
`SourceMapConsumer.GREATEST_LOWER_BOUND`.
and an object is returned with the following properties:
* `source`: The original source file, or null if this information is not
available.
* `line`: The line number in the original source, or null if this information is
not available.
* `column`: The column number in the original source, or null or null if this
information is not available.
* `name`: The original identifier, or null if this information is not available.
```js
consumer.originalPositionFor({ line: 2, column: 10 })
// { source: 'foo.coffee',
// line: 2,
// column: 2,
// name: null }
consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
// { source: null,
// line: null,
// column: null,
// name: null }
```
#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
Returns the generated line and column information for the original source,
line, and column positions provided. The only argument is an object with
the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source.
* `column`: The column number in the original source.
and an object is returned with the following properties:
* `line`: The line number in the generated source, or null.
* `column`: The column number in the generated source, or null.
```js
consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
// { line: 1,
// column: 56 }
```
#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
Returns all generated line and column information for the original source, line,
and column provided. If no column is provided, returns all mappings
corresponding to a either the line we are searching for or the next closest line
that has any mappings. Otherwise, returns all mappings corresponding to the
given line and either the column we are searching for or the next closest column
that has any offsets.
The only argument is an object with the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source.
* `column`: Optional. The column number in the original source.
and an array of objects is returned, each with the following properties:
* `line`: The line number in the generated source, or null.
* `column`: The column number in the generated source, or null.
```js
consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
```
#### SourceMapConsumer.prototype.hasContentsOfAllSources()
Return true if we have the embedded source content for every source listed in
the source map, false otherwise.
In other words, if this method returns `true`, then
`consumer.sourceContentFor(s)` will succeed for every source `s` in
`consumer.sources`.
```js
// ...
if (consumer.hasContentsOfAllSources()) {
consumerReadyCallback(consumer);
} else {
fetchSources(consumer, consumerReadyCallback);
}
// ...
```
#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
Returns the original source content for the source provided. The only
argument is the URL of the original source file.
If the source content for the given source is not found, then an error is
thrown. Optionally, pass `true` as the second param to have `null` returned
instead.
```js
consumer.sources
// [ "my-cool-lib.clj" ]
consumer.sourceContentFor("my-cool-lib.clj")
// "..."
consumer.sourceContentFor("this is not in the source map");
// Error: "this is not in the source map" is not in the source map
consumer.sourceContentFor("this is not in the source map", true);
// null
```
#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
Iterate over each mapping between an original source/line/column and a
generated line/column in this source map.
* `callback`: The function that is called with each mapping. Mappings have the
form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
name }`
* `context`: Optional. If specified, this object will be the value of `this`
every time that `callback` is called.
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
`SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
the mappings sorted by the generated file's line/column order or the
original's source/line/column order, respectively. Defaults to
`SourceMapConsumer.GENERATED_ORDER`.
```js
consumer.eachMapping(function (m) { console.log(m); })
// ...
// { source: 'illmatic.js',
// generatedLine: 1,
// generatedColumn: 0,
// originalLine: 1,
// originalColumn: 0,
// name: null }
// { source: 'illmatic.js',
// generatedLine: 2,
// generatedColumn: 0,
// originalLine: 2,
// originalColumn: 0,
// name: null }
// ...
```
### SourceMapGenerator
An instance of the SourceMapGenerator represents a source map which is being
built incrementally.
#### new SourceMapGenerator([startOfSourceMap])
You may pass an object with the following properties:
* `file`: The filename of the generated source that this source map is
associated with.
* `sourceRoot`: A root for all relative URLs in this source map.
* `skipValidation`: Optional. When `true`, disables validation of mappings as
they are added. This can improve performance but should be used with
discretion, as a last resort. Even then, one should avoid using this flag when
running tests, if possible.
```js
var generator = new sourceMap.SourceMapGenerator({
file: "my-generated-javascript-file.js",
sourceRoot: "http://example.com/app/js/"
});
```
#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
* `sourceMapConsumer` The SourceMap.
```js
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
```
#### SourceMapGenerator.prototype.addMapping(mapping)
Add a single mapping from original source line and column to the generated
source's line and column for this source map being created. The mapping object
should have the following properties:
* `generated`: An object with the generated line and column positions.
* `original`: An object with the original line and column positions.
* `source`: The original source file (relative to the sourceRoot).
* `name`: An optional original token name for this mapping.
```js
generator.addMapping({
source: "module-one.scm",
original: { line: 128, column: 0 },
generated: { line: 3, column: 456 }
})
```
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for an original source file.
* `sourceFile` the URL of the original source file.
* `sourceContent` the content of the source file.
```js
generator.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
Applies a SourceMap for a source file to the SourceMap.
Each mapping to the supplied source file is rewritten using the
supplied SourceMap. Note: The resolution for the resulting mappings
is the minimum of this map and the supplied map.
* `sourceMapConsumer`: The SourceMap to be applied.
* `sourceFile`: Optional. The filename of the source file.
If omitted, sourceMapConsumer.file will be used, if it exists.
Otherwise an error will be thrown.
* `sourceMapPath`: Optional. The dirname of the path to the SourceMap
to be applied. If relative, it is relative to the SourceMap.
This parameter is needed when the two SourceMaps aren't in the same
directory, and the SourceMap to be applied contains relative source
paths. If so, those relative source paths need to be rewritten
relative to the SourceMap.
If omitted, it is assumed that both SourceMaps are in the same directory,
thus not needing any rewriting. (Supplying `'.'` has the same effect.)
#### SourceMapGenerator.prototype.toString()
Renders the source map being generated to a string.
```js
generator.toString()
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
```
### SourceNode
SourceNodes provide a way to abstract over interpolating and/or concatenating
snippets of generated JavaScript source code, while maintaining the line and
column information associated between those snippets and the original source
code. This is useful as the final intermediate representation a compiler might
use before outputting the generated JS and source map.
#### new SourceNode([line, column, source[, chunk[, name]]])
* `line`: The original line number associated with this source node, or null if
it isn't associated with an original line.
* `column`: The original column number associated with this source node, or null
if it isn't associated with an original column.
* `source`: The original source's filename; null if no filename is provided.
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
below.
* `name`: Optional. The original identifier.
```js
var node = new SourceNode(1, 2, "a.cpp", [
new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
]);
```
#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
Creates a SourceNode from generated code and a SourceMapConsumer.
* `code`: The generated code
* `sourceMapConsumer` The SourceMap for the generated code
* `relativePath` The optional path that relative sources in `sourceMapConsumer`
should be relative to.
```js
var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map"));
var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
consumer);
```
#### SourceNode.prototype.add(chunk)
Add a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.add(" + ");
node.add(otherNode);
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
```
#### SourceNode.prototype.prepend(chunk)
Prepend a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.prepend("/** Build Id: f783haef86324gf **/\n\n");
```
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for a source file. This will be added to the
`SourceMap` in the `sourcesContent` field.
* `sourceFile`: The filename of the source file
* `sourceContent`: The content of the source file
```js
node.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceNode.prototype.walk(fn)
Walk over the tree of JS snippets in this node and its children. The walking
function is called once for each snippet of JS and is passed that snippet and
the its original associated source's line/column location.
* `fn`: The traversal function.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.walk(function (code, loc) { console.log("WALK:", code, loc); })
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
```
#### SourceNode.prototype.walkSourceContents(fn)
Walk over the tree of SourceNodes. The walking function is called for each
source file content and is passed the filename and source content.
* `fn`: The traversal function.
```js
var a = new SourceNode(1, 2, "a.js", "generated from a");
a.setSourceContent("a.js", "original a");
var b = new SourceNode(1, 2, "b.js", "generated from b");
b.setSourceContent("b.js", "original b");
var c = new SourceNode(1, 2, "c.js", "generated from c");
c.setSourceContent("c.js", "original c");
var node = new SourceNode(null, null, null, [a, b, c]);
node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
// WALK: a.js : original a
// WALK: b.js : original b
// WALK: c.js : original c
```
#### SourceNode.prototype.join(sep)
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
between each of this source node's children.
* `sep`: The separator.
```js
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
var operand = new SourceNode(3, 4, "a.rs", "=");
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
var joinedNode = node.join(" ");
```
#### SourceNode.prototype.replaceRight(pattern, replacement)
Call `String.prototype.replace` on the very right-most source snippet. Useful
for trimming white space from the end of a source node, etc.
* `pattern`: The pattern to replace.
* `replacement`: The thing to replace the pattern with.
```js
// Trim trailing white space.
node.replaceRight(/\s*$/, "");
```
#### SourceNode.prototype.toString()
Return the string representation of this source node. Walks over the tree and
concatenates all the various snippets together to one string.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toString()
// 'unodostresquatro'
```
#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
Returns the string representation of this tree of source nodes, plus a
SourceMapGenerator which contains all the mappings between the generated and
original sources.
The arguments are the same as those to `new SourceMapGenerator`.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toStringWithSourceMap({ file: "my-output-file.js" })
// { code: 'unodostresquatro',
// map: [object SourceMapGenerator] }
```

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,104 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
var has = Object.prototype.hasOwnProperty;
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = Object.create(null);
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Return how many unique items are in this ArraySet. If duplicates have been
* added, than those do not count towards the size.
*
* @returns Number
*/
ArraySet.prototype.size = function ArraySet_size() {
return Object.getOwnPropertyNames(this._set).length;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var sStr = util.toSetString(aStr);
var isDuplicate = has.call(this._set, sStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set[sStr] = idx;
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
var sStr = util.toSetString(aStr);
return has.call(this._set, sStr);
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
var sStr = util.toSetString(aStr);
if (has.call(this._set, sStr)) {
return this._set[sStr];
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;

View File

@@ -0,0 +1,140 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* 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://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* 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.
*/
var base64 = require('./base64');
// 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
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var 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(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
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 |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string via the out parameter.
*/
exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (aIndex >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charCodeAt(aIndex++));
if (digit === -1) {
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
}
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
aOutParam.value = fromVLQSigned(result);
aOutParam.rest = aIndex;
};

View File

@@ -0,0 +1,67 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function (number) {
if (0 <= number && number < intToCharMap.length) {
return intToCharMap[number];
}
throw new TypeError("Must be between 0 and 63: " + number);
};
/**
* Decode a single base 64 character code digit to an integer. Returns -1 on
* failure.
*/
exports.decode = function (charCode) {
var bigA = 65; // 'A'
var bigZ = 90; // 'Z'
var littleA = 97; // 'a'
var littleZ = 122; // 'z'
var zero = 48; // '0'
var nine = 57; // '9'
var plus = 43; // '+'
var slash = 47; // '/'
var littleOffset = 26;
var numberOffset = 52;
// 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
if (bigA <= charCode && charCode <= bigZ) {
return (charCode - bigA);
}
// 26 - 51: abcdefghijklmnopqrstuvwxyz
if (littleA <= charCode && charCode <= littleZ) {
return (charCode - littleA + littleOffset);
}
// 52 - 61: 0123456789
if (zero <= charCode && charCode <= nine) {
return (charCode - zero + numberOffset);
}
// 62: +
if (charCode == plus) {
return 62;
}
// 63: /
if (charCode == slash) {
return 63;
}
// Invalid base64 digit.
return -1;
};

View File

@@ -0,0 +1,111 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.GREATEST_LOWER_BOUND = 1;
exports.LEAST_UPPER_BOUND = 2;
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the index of
// the next-closest element.
//
// 3. We did not find the exact element, and there is no next-closest
// element than the one we are searching for, so we return -1.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
}
else if (cmp > 0) {
// Our needle is greater than aHaystack[mid].
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return aHigh < aHaystack.length ? aHigh : -1;
} else {
return mid;
}
}
else {
// Our needle is less than aHaystack[mid].
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
}
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return mid;
} else {
return aLow < 0 ? -1 : aLow;
}
}
}
/**
* This is an implementation of binary search which will always try and return
* the index of the closest element if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
*/
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
if (aHaystack.length === 0) {
return -1;
}
var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
aCompare, aBias || exports.GREATEST_LOWER_BOUND);
if (index < 0) {
return -1;
}
// We have found either the exact element, or the next-closest element than
// the one we are searching for. However, there may be more than one such
// element. Make sure we always return the smallest of these.
while (index - 1 >= 0) {
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
break;
}
--index;
}
return index;
};

View File

@@ -0,0 +1,79 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2014 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
/**
* Determine whether mappingB is after mappingA with respect to generated
* position.
*/
function generatedPositionAfter(mappingA, mappingB) {
// Optimized for most common case
var lineA = mappingA.generatedLine;
var lineB = mappingB.generatedLine;
var columnA = mappingA.generatedColumn;
var columnB = mappingB.generatedColumn;
return lineB > lineA || lineB == lineA && columnB >= columnA ||
util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}
/**
* A data structure to provide a sorted view of accumulated mappings in a
* performance conscious manner. It trades a neglibable overhead in general
* case for a large speedup in case of mappings being added in order.
*/
function MappingList() {
this._array = [];
this._sorted = true;
// Serves as infimum
this._last = {generatedLine: -1, generatedColumn: 0};
}
/**
* Iterate through internal items. This method takes the same arguments that
* `Array.prototype.forEach` takes.
*
* NOTE: The order of the mappings is NOT guaranteed.
*/
MappingList.prototype.unsortedForEach =
function MappingList_forEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
};
/**
* Add the given source mapping.
*
* @param Object aMapping
*/
MappingList.prototype.add = function MappingList_add(aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.push(aMapping);
} else {
this._sorted = false;
this._array.push(aMapping);
}
};
/**
* Returns the flat, sorted array of mappings. The mappings are sorted by
* generated position.
*
* WARNING: This method returns internal data without copying, for
* performance. The return value must NOT be mutated, and should be treated as
* an immutable borrow. If you want to take ownership, you must make your own
* copy.
*/
MappingList.prototype.toArray = function MappingList_toArray() {
if (!this._sorted) {
this._array.sort(util.compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
};
exports.MappingList = MappingList;

View File

@@ -0,0 +1,114 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
// It turns out that some (most?) JavaScript engines don't self-host
// `Array.prototype.sort`. This makes sense because C++ will likely remain
// faster than JS when doing raw CPU-intensive sorting. However, when using a
// custom comparator function, calling back and forth between the VM's C++ and
// JIT'd JS is rather slow *and* loses JIT type information, resulting in
// worse generated code for the comparator function than would be optimal. In
// fact, when sorting with a comparator, these costs outweigh the benefits of
// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
// a ~3500ms mean speed-up in `bench/bench.html`.
/**
* Swap the elements indexed by `x` and `y` in the array `ary`.
*
* @param {Array} ary
* The array.
* @param {Number} x
* The index of the first item.
* @param {Number} y
* The index of the second item.
*/
function swap(ary, x, y) {
var temp = ary[x];
ary[x] = ary[y];
ary[y] = temp;
}
/**
* Returns a random integer within the range `low .. high` inclusive.
*
* @param {Number} low
* The lower bound on the range.
* @param {Number} high
* The upper bound on the range.
*/
function randomIntInRange(low, high) {
return Math.round(low + (Math.random() * (high - low)));
}
/**
* The Quick Sort algorithm.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
* @param {Number} p
* Start index of the array
* @param {Number} r
* End index of the array
*/
function doQuickSort(ary, comparator, p, r) {
// If our lower bound is less than our upper bound, we (1) partition the
// array into two pieces and (2) recurse on each half. If it is not, this is
// the empty array and our base case.
if (p < r) {
// (1) Partitioning.
//
// The partitioning chooses a pivot between `p` and `r` and moves all
// elements that are less than or equal to the pivot to the before it, and
// all the elements that are greater than it after it. The effect is that
// once partition is done, the pivot is in the exact place it will be when
// the array is put in sorted order, and it will not need to be moved
// again. This runs in O(n) time.
// Always choose a random pivot so that an input array which is reverse
// sorted does not cause O(n^2) running time.
var pivotIndex = randomIntInRange(p, r);
var i = p - 1;
swap(ary, pivotIndex, r);
var pivot = ary[r];
// Immediately after `j` is incremented in this loop, the following hold
// true:
//
// * Every element in `ary[p .. i]` is less than or equal to the pivot.
//
// * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
for (var j = p; j < r; j++) {
if (comparator(ary[j], pivot) <= 0) {
i += 1;
swap(ary, i, j);
}
}
swap(ary, i + 1, j);
var q = i + 1;
// (2) Recurse on each half.
doQuickSort(ary, comparator, p, q - 1);
doQuickSort(ary, comparator, q + 1, r);
}
}
/**
* Sort the given array in-place with the given comparator function.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
*/
exports.quickSort = function (ary, comparator) {
doQuickSort(ary, comparator, 0, ary.length - 1);
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,404 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var base64VLQ = require('./base64-vlq');
var util = require('./util');
var ArraySet = require('./array-set').ArraySet;
var MappingList = require('./mapping-list').MappingList;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. You may pass an object with the following
* properties:
*
* - file: The filename of the generated source.
* - sourceRoot: A root for all relative URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util.getArg(aArgs, 'file', null);
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap =
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source != null) {
newMapping.source = mapping.source;
if (sourceRoot != null) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name != null) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping =
function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
if (!this._skipValidation) {
this._validateMapping(generated, original, source, name);
}
if (source != null) {
source = String(source);
if (!this._sources.has(source)) {
this._sources.add(source);
}
}
if (name != null) {
name = String(name);
if (!this._names.has(name)) {
this._names.add(name);
}
}
this._mappings.add({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent =
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot != null) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent != null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = Object.create(null);
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else if (this._sourcesContents) {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
* @param aSourceMapPath Optional. The dirname of the path to the source map
* to be applied. If relative, it is relative to the SourceMapConsumer.
* This parameter is needed when the two source maps aren't in the same
* directory, and the source map to be applied contains relative source
* paths. If so, those relative source paths need to be rewritten
* relative to the SourceMapGenerator.
*/
SourceMapGenerator.prototype.applySourceMap =
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
var sourceFile = aSourceFile;
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (aSourceFile == null) {
if (aSourceMapConsumer.file == null) {
throw new Error(
'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
'or the source map\'s "file" property. Both were omitted.'
);
}
sourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "sourceFile" relative if an absolute Url is passed.
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "sourceFile"
this._mappings.unsortedForEach(function (mapping) {
if (mapping.source === sourceFile && mapping.originalLine != null) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source != null) {
// Copy mapping
mapping.source = original.source;
if (aSourceMapPath != null) {
mapping.source = util.join(aSourceMapPath, mapping.source)
}
if (sourceRoot != null) {
mapping.source = util.relative(sourceRoot, mapping.source);
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name != null) {
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source != null && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name != null && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aSourceMapPath != null) {
sourceFile = util.join(aSourceMapPath, sourceFile);
}
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
return;
}
else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings =
function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var next;
var mapping;
var nameIdx;
var sourceIdx;
var mappings = this._mappings.toArray();
for (var i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
next = ''
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
next += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
continue;
}
next += ',';
}
}
next += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source != null) {
sourceIdx = this._sources.indexOf(mapping.source);
next += base64VLQ.encode(sourceIdx - previousSource);
previousSource = sourceIdx;
// lines are stored 0-based in SourceMap spec version 3
next += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
next += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name != null) {
nameIdx = this._names.indexOf(mapping.name);
next += base64VLQ.encode(nameIdx - previousName);
previousName = nameIdx;
}
}
result += next;
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent =
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot != null) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
? this._sourcesContents[key]
: null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON =
function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._file != null) {
map.file = this._file;
}
if (this._sourceRoot != null) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
return JSON.stringify(this.toJSON());
};
exports.SourceMapGenerator = SourceMapGenerator;

View File

@@ -0,0 +1,407 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
var util = require('./util');
// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
// operating systems these days (capturing the result).
var REGEX_NEWLINE = /(\r?\n)/;
// Newline character code for charCodeAt() comparisons
var NEWLINE_CODE = 10;
// Private symbol for identifying `SourceNode`s when multiple versions of
// the source-map library are loaded. This MUST NOT CHANGE across
// versions!
var isSourceNode = "$$$isSourceNode$$$";
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine == null ? null : aLine;
this.column = aColumn == null ? null : aColumn;
this.source = aSource == null ? null : aSource;
this.name = aName == null ? null : aName;
this[isSourceNode] = true;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
* @param aRelativePath Optional. The path that relative sources in the
* SourceMapConsumer should be relative to.
*/
SourceNode.fromStringWithSourceMap =
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// All even indices of this array are one line of the generated code,
// while all odd indices are the newlines between two adjacent lines
// (since `REGEX_NEWLINE` captures its match).
// Processed fragments are removed from this array, by calling `shiftNextLine`.
var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
var shiftNextLine = function() {
var lineContents = remainingLines.shift();
// The last line of a file might not have a newline.
var newLine = remainingLines.shift() || "";
return lineContents + newLine;
};
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping !== null) {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
// Associate first line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
lastGeneratedLine++;
lastGeneratedColumn = 0;
// The remaining code is added without mapping
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[0];
var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
// No more remaining code, continue
lastMapping = mapping;
return;
}
}
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(shiftNextLine());
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
if (remainingLines.length > 0) {
if (lastMapping) {
// Associate the remaining code in the current line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
}
// and add the remaining lines without any mapping
node.add(remainingLines.join(""));
}
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aRelativePath != null) {
sourceFile = util.join(aRelativePath, sourceFile);
}
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
var source = aRelativePath
? util.join(aRelativePath, mapping.source)
: mapping.source;
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
source,
code,
mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length-1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
}
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
this.children.unshift(aChunk);
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk[isSourceNode]) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild[isSourceNode]) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent =
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents =
function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i][isSourceNode]) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if(lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
for (var idx = 0, length = chunk.length; idx < length; idx++) {
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
generated.line++;
generated.column = 0;
// Mappings end at eol
if (idx + 1 === length) {
lastOriginalSource = null;
sourceMappingActive = false;
} else if (sourceMappingActive) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
} else {
generated.column++;
}
}
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;

View File

@@ -0,0 +1,417 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
var dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[2],
host: match[3],
port: match[4],
path: match[5]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = '';
if (aParsedUrl.scheme) {
url += aParsedUrl.scheme + ':';
}
url += '//';
if (aParsedUrl.auth) {
url += aParsedUrl.auth + '@';
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
/**
* Normalizes a path, or the path portion of a URL:
*
* - Replaces consecutive slashes with one slash.
* - Removes unnecessary '.' parts.
* - Removes unnecessary '<dir>/..' parts.
*
* Based on code in the Node.js 'path' core module.
*
* @param aPath The path or url to normalize.
*/
function normalize(aPath) {
var path = aPath;
var url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path = url.path;
}
var isAbsolute = exports.isAbsolute(path);
var parts = path.split(/\/+/);
for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
part = parts[i];
if (part === '.') {
parts.splice(i, 1);
} else if (part === '..') {
up++;
} else if (up > 0) {
if (part === '') {
// The first part is blank if the path is absolute. Trying to go
// above the root is a no-op. Therefore we can remove all '..' parts
// directly after the root.
parts.splice(i + 1, up);
up = 0;
} else {
parts.splice(i, 2);
up--;
}
}
}
path = parts.join('/');
if (path === '') {
path = isAbsolute ? '/' : '.';
}
if (url) {
url.path = path;
return urlGenerate(url);
}
return path;
}
exports.normalize = normalize;
/**
* Joins two paths/URLs.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be joined with the root.
*
* - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
* scheme-relative URL: Then the scheme of aRoot, if any, is prepended
* first.
* - Otherwise aPath is a path. If aRoot is a URL, then its path portion
* is updated with the result and aRoot is returned. Otherwise the result
* is returned.
* - If aPath is absolute, the result is aPath.
* - Otherwise the two paths are joined with a slash.
* - Joining for example 'http://' and 'www.example.com' is also supported.
*/
function join(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
if (aPath === "") {
aPath = ".";
}
var aPathUrl = urlParse(aPath);
var aRootUrl = urlParse(aRoot);
if (aRootUrl) {
aRoot = aRootUrl.path || '/';
}
// `join(foo, '//www.example.org')`
if (aPathUrl && !aPathUrl.scheme) {
if (aRootUrl) {
aPathUrl.scheme = aRootUrl.scheme;
}
return urlGenerate(aPathUrl);
}
if (aPathUrl || aPath.match(dataUrlRegexp)) {
return aPath;
}
// `join('http://', 'www.example.com')`
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
aRootUrl.host = aPath;
return urlGenerate(aRootUrl);
}
var joined = aPath.charAt(0) === '/'
? aPath
: normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
return urlGenerate(aRootUrl);
}
return joined;
}
exports.join = join;
exports.isAbsolute = function (aPath) {
return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
};
/**
* Make a path relative to a URL or another path.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be made relative to aRoot.
*/
function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
aRoot = aRoot.replace(/\/$/, '');
// It is possible for the path to be above the root. In this case, simply
// checking whether the root is a prefix of the path won't work. Instead, we
// need to remove components from the root one by one, until either we find
// a prefix that fits, or we run out of components to remove.
var level = 0;
while (aPath.indexOf(aRoot + '/') !== 0) {
var index = aRoot.lastIndexOf("/");
if (index < 0) {
return aPath;
}
// If the only part of the root that is left is the scheme (i.e. http://,
// file:///, etc.), one or more slashes (/), or simply nothing at all, we
// have exhausted all components, so the path is not relative to the root.
aRoot = aRoot.slice(0, index);
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
return aPath;
}
++level;
}
// Make sure we add a "../" for each component we removed from the root.
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
}
exports.relative = relative;
var supportsNullProto = (function () {
var obj = Object.create(null);
return !('__proto__' in obj);
}());
function identity (s) {
return s;
}
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
if (isProtoString(aStr)) {
return '$' + aStr;
}
return aStr;
}
exports.toSetString = supportsNullProto ? identity : toSetString;
function fromSetString(aStr) {
if (isProtoString(aStr)) {
return aStr.slice(1);
}
return aStr;
}
exports.fromSetString = supportsNullProto ? identity : fromSetString;
function isProtoString(s) {
if (!s) {
return false;
}
var length = s.length;
if (length < 9 /* "__proto__".length */) {
return false;
}
if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
s.charCodeAt(length - 2) !== 95 /* '_' */ ||
s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
s.charCodeAt(length - 4) !== 116 /* 't' */ ||
s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
s.charCodeAt(length - 8) !== 95 /* '_' */ ||
s.charCodeAt(length - 9) !== 95 /* '_' */) {
return false;
}
for (var i = length - 10; i >= 0; i--) {
if (s.charCodeAt(i) !== 36 /* '$' */) {
return false;
}
}
return true;
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp = mappingA.source - mappingB.source;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0 || onlyCompareOriginal) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
return mappingA.name - mappingB.name;
}
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings with deflated source and name indices where
* the generated positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0 || onlyCompareGenerated) {
return cmp;
}
cmp = mappingA.source - mappingB.source;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return mappingA.name - mappingB.name;
}
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
function strcmp(aStr1, aStr2) {
if (aStr1 === aStr2) {
return 0;
}
if (aStr1 > aStr2) {
return 1;
}
return -1;
}
/**
* Comparator between two mappings with inflated source and name strings where
* the generated positions are compared.
*/
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;

View File

@@ -0,0 +1,210 @@
{
"_from": "source-map@0.5.6",
"_id": "source-map@0.5.6",
"_inBundle": false,
"_integrity": "sha1-dc449SvwczxafwwRjYEzSiu19BI=",
"_location": "/react-error-overlay/source-map",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "source-map@0.5.6",
"name": "source-map",
"escapedName": "source-map",
"rawSpec": "0.5.6",
"saveSpec": null,
"fetchSpec": "0.5.6"
},
"_requiredBy": [
"/react-error-overlay"
],
"_resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.6.tgz",
"_shasum": "75ce38f52bf0733c5a7f0c118d81334a2bb5f412",
"_spec": "source-map@0.5.6",
"_where": "/home/bilal/Saburly/slucajna-televizija/node_modules/react-error-overlay",
"author": {
"name": "Nick Fitzgerald",
"email": "nfitzgerald@mozilla.com"
},
"bugs": {
"url": "https://github.com/mozilla/source-map/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Tobias Koppers",
"email": "tobias.koppers@googlemail.com"
},
{
"name": "Duncan Beevers",
"email": "duncan@dweebd.com"
},
{
"name": "Stephen Crane",
"email": "scrane@mozilla.com"
},
{
"name": "Ryan Seddon",
"email": "seddon.ryan@gmail.com"
},
{
"name": "Miles Elam",
"email": "miles.elam@deem.com"
},
{
"name": "Mihai Bazon",
"email": "mihai.bazon@gmail.com"
},
{
"name": "Michael Ficarra",
"email": "github.public.email@michael.ficarra.me"
},
{
"name": "Todd Wolfson",
"email": "todd@twolfson.com"
},
{
"name": "Alexander Solovyov",
"email": "alexander@solovyov.net"
},
{
"name": "Felix Gnass",
"email": "fgnass@gmail.com"
},
{
"name": "Conrad Irwin",
"email": "conrad.irwin@gmail.com"
},
{
"name": "usrbincc",
"email": "usrbincc@yahoo.com"
},
{
"name": "David Glasser",
"email": "glasser@davidglasser.net"
},
{
"name": "Chase Douglas",
"email": "chase@newrelic.com"
},
{
"name": "Evan Wallace",
"email": "evan.exe@gmail.com"
},
{
"name": "Heather Arthur",
"email": "fayearthur@gmail.com"
},
{
"name": "Hugh Kennedy",
"email": "hughskennedy@gmail.com"
},
{
"name": "David Glasser",
"email": "glasser@davidglasser.net"
},
{
"name": "Simon Lydell",
"email": "simon.lydell@gmail.com"
},
{
"name": "Jmeas Smith",
"email": "jellyes2@gmail.com"
},
{
"name": "Michael Z Goddard",
"email": "mzgoddard@gmail.com"
},
{
"name": "azu",
"email": "azu@users.noreply.github.com"
},
{
"name": "John Gozde",
"email": "john@gozde.ca"
},
{
"name": "Adam Kirkton",
"email": "akirkton@truefitinnovation.com"
},
{
"name": "Chris Montgomery",
"email": "christopher.montgomery@dowjones.com"
},
{
"name": "J. Ryan Stinnett",
"email": "jryans@gmail.com"
},
{
"name": "Jack Herrington",
"email": "jherrington@walmartlabs.com"
},
{
"name": "Chris Truter",
"email": "jeffpalentine@gmail.com"
},
{
"name": "Daniel Espeset",
"email": "daniel@danielespeset.com"
},
{
"name": "Jamie Wong",
"email": "jamie.lf.wong@gmail.com"
},
{
"name": "Eddy Bruël",
"email": "ejpbruel@mozilla.com"
},
{
"name": "Hawken Rives",
"email": "hawkrives@gmail.com"
},
{
"name": "Gilad Peleg",
"email": "giladp007@gmail.com"
},
{
"name": "djchie",
"email": "djchie.dev@gmail.com"
},
{
"name": "Gary Ye",
"email": "garysye@gmail.com"
},
{
"name": "Nicolas Lalevée",
"email": "nicolas.lalevee@hibnet.org"
}
],
"deprecated": false,
"description": "Generates and consumes source maps",
"devDependencies": {
"doctoc": "^0.15.0",
"webpack": "^1.12.0"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"source-map.js",
"lib/",
"dist/source-map.debug.js",
"dist/source-map.js",
"dist/source-map.min.js",
"dist/source-map.min.js.map"
],
"homepage": "https://github.com/mozilla/source-map",
"license": "BSD-3-Clause",
"main": "./source-map.js",
"name": "source-map",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/mozilla/source-map.git"
},
"scripts": {
"build": "webpack --color",
"test": "npm run build && node test/run-tests.js",
"toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
},
"version": "0.5.6"
}

View File

@@ -0,0 +1,8 @@
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
exports.SourceNode = require('./lib/source-node').SourceNode;

110
web/node_modules/react-error-overlay/package.json generated vendored Normal file
View File

@@ -0,0 +1,110 @@
{
"_from": "react-error-overlay@^1.0.7",
"_id": "react-error-overlay@1.0.10",
"_inBundle": false,
"_integrity": "sha512-/fzpqRGPWlpDvvBwLN7vjE4FAI81ajbWowkrycY8P5RGqE49WIUMIdFjTS5htqJfzxcM599k/x1lCayaq+4qEw==",
"_location": "/react-error-overlay",
"_phantomChildren": {
"chalk": "1.1.3",
"esutils": "2.0.2",
"js-tokens": "3.0.2"
},
"_requested": {
"type": "range",
"registry": true,
"raw": "react-error-overlay@^1.0.7",
"name": "react-error-overlay",
"escapedName": "react-error-overlay",
"rawSpec": "^1.0.7",
"saveSpec": null,
"fetchSpec": "^1.0.7"
},
"_requiredBy": [
"/react-scripts"
],
"_resolved": "https://registry.npmjs.org/react-error-overlay/-/react-error-overlay-1.0.10.tgz",
"_shasum": "da8cd1eafac41afdca2a33792b23694ef6c528f1",
"_spec": "react-error-overlay@^1.0.7",
"_where": "/home/bilal/Saburly/slucajna-televizija/node_modules/react-scripts",
"author": {
"name": "Joe Haddad",
"email": "timer150@gmail.com"
},
"bugs": {
"url": "https://github.com/facebookincubator/create-react-app/issues"
},
"bundleDependencies": false,
"dependencies": {
"anser": "1.4.1",
"babel-code-frame": "6.22.0",
"babel-runtime": "6.23.0",
"react-dev-utils": "^3.1.0",
"settle-promise": "1.0.0",
"source-map": "0.5.6"
},
"deprecated": false,
"description": "An overlay for displaying stack frames.",
"devDependencies": {
"babel-cli": "6.24.1",
"babel-eslint": "7.2.3",
"babel-preset-react-app": "^3.0.2",
"cross-env": "5.0.5",
"eslint": "4.4.1",
"eslint-config-react-app": "^2.0.0",
"eslint-plugin-flowtype": "2.35.0",
"eslint-plugin-import": "2.7.0",
"eslint-plugin-jsx-a11y": "5.1.1",
"eslint-plugin-react": "7.1.0",
"flow-bin": "0.52.0",
"jest": "20.0.4",
"jest-fetch-mock": "1.2.1"
},
"files": [
"lib/",
"middleware.js"
],
"homepage": "https://github.com/facebookincubator/create-react-app#readme",
"jest": {
"setupFiles": [
"./src/__tests__/setupJest.js"
],
"collectCoverage": true,
"coverageReporters": [
"json"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.js?(x)",
"<rootDir>/src/**/?(*.)(spec|test).js?(x)"
],
"testPathIgnorePatterns": [
"/node_modules/",
"/fixtures/",
"setupJest.js"
]
},
"keywords": [
"overlay",
"syntax",
"error",
"red",
"box",
"redbox",
"crash",
"warning"
],
"license": "BSD-3-Clause",
"main": "lib/index.js",
"name": "react-error-overlay",
"repository": {
"type": "git",
"url": "git+https://github.com/facebookincubator/create-react-app.git"
},
"scripts": {
"build": "babel src/ -d lib/",
"build:prod": "cross-env NODE_ENV=production babel src/ -d lib/",
"prepublishOnly": "npm run build:prod && npm test",
"start": "cross-env NODE_ENV=development npm run build -- --watch",
"test": "flow && jest"
},
"version": "1.0.10"
}