Make the packager work with babel strict mode transform

Summary:
At the moment we have to disable strict mode for the transform-es2015-modules-commonjs because strict mode leaks to the global scope and breaks the bridge. It was due to the way the polyfills were bundled in the package. To fix it, I wrapped the polyfill modules in an IIFE. Then when strict mode was enabled some polyfills were broken due to strict mode errors so that was fixed too. Also removed the IIFE from the polyfills that included one.

This diff doesn't enable the strict mode transform since some internal facebook modules depend on it not being enabled. When #5214 lands we could make the default babel config shipped with OSS react-native use strict mode modules and facebook could just modify the babel config to disable it if needed.

This will allow removing `"strict": false` from https://github.com/facebook/react-native/blob/master/packager/react-packager/.babelrc#L16

Fixes #5316
Closes https://github.com/facebook/react-native/pull/5422

Reviewed By: svcscm

Differential Revision: D2846422

Pulled By: davidaurelio

fb-gh-sync-id: a3e2f8909aa87dabab2b872c61b887e80220fb56
This commit is contained in:
Janic Duplessis 2016-01-21 07:22:20 -08:00 committed by facebook-github-bot-4
parent d806b75544
commit d33b554f5d
17 changed files with 1032 additions and 1012 deletions

View File

@ -25,11 +25,11 @@
require('regenerator/runtime'); require('regenerator/runtime');
if (typeof GLOBAL === 'undefined') { if (typeof GLOBAL === 'undefined') {
GLOBAL = this; global.GLOBAL = this;
} }
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
window = GLOBAL; global.window = GLOBAL;
} }
function setUpConsole() { function setUpConsole() {
@ -70,6 +70,15 @@ function polyfillGlobal(name, newValue, scope = GLOBAL) {
Object.defineProperty(scope, name, {...descriptor, value: newValue}); Object.defineProperty(scope, name, {...descriptor, value: newValue});
} }
/**
* Polyfill a module if it is not already defined in `scope`.
*/
function polyfillIfNeeded(name, polyfill, scope = GLOBAL, descriptor = {}) {
if (scope[name] === undefined) {
Object.defineProperty(scope, name, {...descriptor, value: polyfill});
}
}
function setUpErrorHandler() { function setUpErrorHandler() {
if (global.__fbDisableExceptionsManager) { if (global.__fbDisableExceptionsManager) {
return; return;
@ -78,7 +87,7 @@ function setUpErrorHandler() {
function handleError(e, isFatal) { function handleError(e, isFatal) {
try { try {
require('ExceptionsManager').handleException(e, isFatal); require('ExceptionsManager').handleException(e, isFatal);
} catch(ee) { } catch (ee) {
console.log('Failed to print error: ', ee.message); console.log('Failed to print error: ', ee.message);
} }
} }
@ -146,7 +155,11 @@ function setUpXHR() {
} }
function setUpGeolocation() { function setUpGeolocation() {
GLOBAL.navigator = GLOBAL.navigator || {}; polyfillIfNeeded('navigator', {}, GLOBAL, {
writable: true,
enumerable: true,
configurable: true,
});
polyfillGlobal('geolocation', require('Geolocation'), GLOBAL.navigator); polyfillGlobal('geolocation', require('Geolocation'), GLOBAL.navigator);
} }
@ -179,9 +192,9 @@ function setUpProcessEnv() {
} }
function setUpNumber() { function setUpNumber() {
Number.EPSILON = Number.EPSILON || Math.pow(2, -52); polyfillIfNeeded('EPSILON', Math.pow(2, -52), Number);
Number.MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1; polyfillIfNeeded('MAX_SAFE_INTEGER', Math.pow(2, 53) - 1, Number);
Number.MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1); polyfillIfNeeded('MIN_SAFE_INTEGER', -(Math.pow(2, 53) - 1), Number);
} }
function setUpDevTools() { function setUpDevTools() {

View File

@ -1,34 +1,30 @@
/* eslint global-strict: 0 */ /* eslint strict: 0 */
(function(GLOBAL) {
/**
* The document must be shimmed before anything else that might define the
* `ExecutionEnvironment` module (which checks for `document.createElement`).
*/
// The browser defines Text and Image globals by default. If you forget to // TODO: Remove document polyfill now that chrome debugging is in a web worker.
// require them, then the error message is very confusing.
function getInvalidGlobalUseError(name) {
return new Error(
'You are trying to render the global ' + name + ' variable as a ' +
'React element. You probably forgot to require ' + name + '.'
);
}
GLOBAL.Text = {
get defaultProps() {
throw getInvalidGlobalUseError('Text');
}
};
GLOBAL.Image = {
get defaultProps() {
throw getInvalidGlobalUseError('Image');
}
};
// Force `ExecutionEnvironment.canUseDOM` to be false.
if (GLOBAL.document) {
GLOBAL.document.createElement = null;
}
// There is no DOM so MutationObserver doesn't make sense. It is used // The browser defines Text and Image globals by default. If you forget to
// as feature detection in Bluebird Promise implementation // require them, then the error message is very confusing.
GLOBAL.MutationObserver = undefined; function getInvalidGlobalUseError(name) {
})(this); return new Error(
'You are trying to render the global ' + name + ' variable as a ' +
'React element. You probably forgot to require ' + name + '.'
);
}
global.Text = {
get defaultProps() {
throw getInvalidGlobalUseError('Text');
}
};
global.Image = {
get defaultProps() {
throw getInvalidGlobalUseError('Image');
}
};
// Force `ExecutionEnvironment.canUseDOM` to be false.
if (global.document) {
global.document.createElement = null;
}
// There is no DOM so MutationObserver doesn't make sense. It is used
// as feature detection in Bluebird Promise implementation
global.MutationObserver = undefined;

View File

@ -49,12 +49,13 @@ var TYPES_KEY = keyOf({__types: true});
*/ */
function mixInEventEmitter(klass, types) { function mixInEventEmitter(klass, types) {
invariant(types, 'Must supply set of valid event types'); invariant(types, 'Must supply set of valid event types');
invariant(!this.__eventEmitter, 'An active emitter is already mixed in');
// If this is a constructor, write to the prototype, otherwise write to the // If this is a constructor, write to the prototype, otherwise write to the
// singleton object. // singleton object.
var target = klass.prototype || klass; var target = klass.prototype || klass;
invariant(!target.__eventEmitter, 'An active emitter is already mixed in');
var ctor = klass.constructor; var ctor = klass.constructor;
if (ctor) { if (ctor) {
invariant( invariant(

View File

@ -58,6 +58,14 @@ describe('Resolver', function() {
return module; return module;
} }
function createPolyfill(id, dependencies) {
var polyfill = new Polyfill({});
polyfill.getName.mockImpl(() => Promise.resolve(id));
polyfill.getDependencies.mockImpl(() => Promise.resolve(dependencies));
polyfill.isPolyfill.mockReturnValue(true);
return polyfill;
}
describe('getDependencies', function() { describe('getDependencies', function() {
pit('should get dependencies with polyfills', function() { pit('should get dependencies with polyfills', function() {
var module = createModule('index'); var module = createModule('index');
@ -1020,5 +1028,26 @@ describe('Resolver', function() {
].join('\n')); ].join('\n'));
}); });
}); });
pit('should resolve polyfills', function () {
const depResolver = new Resolver({
projectRoot: '/root',
});
const polyfill = createPolyfill('test polyfill', []);
const code = [
'global.fetch = () => 1;',
].join('');
return depResolver.wrapModule(
null,
polyfill,
code
).then(processedCode => {
expect(processedCode.code).toEqual([
'(function(global) {',
'global.fetch = () => 1;',
"\n})(typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this);",
].join(''));
});
});
}); });
}); });

View File

@ -214,7 +214,9 @@ class Resolver {
wrapModule(resolutionResponse, module, code) { wrapModule(resolutionResponse, module, code) {
if (module.isPolyfill()) { if (module.isPolyfill()) {
return Promise.resolve({code}); return Promise.resolve({
code: definePolyfillCode(code),
});
} }
return this.resolveRequires(resolutionResponse, module, code).then( return this.resolveRequires(resolutionResponse, module, code).then(
@ -239,4 +241,12 @@ function defineModuleCode(moduleName, code) {
].join(''); ].join('');
} }
function definePolyfillCode(code) {
return [
'(function(global) {',
code,
`\n})(typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this);`,
].join('');
}
module.exports = Resolver; module.exports = Resolver;

View File

@ -5,54 +5,51 @@
* @polyfill * @polyfill
*/ */
/*eslint-disable */ /* eslint-disable */
/*jslint bitwise: true */
(function(undefined) { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex function findIndex(predicate, context) {
function findIndex(predicate, context) { if (this == null) {
if (this == null) { throw new TypeError(
throw new TypeError( 'Array.prototype.findIndex called on null or undefined'
'Array.prototype.findIndex called on null or undefined' );
); }
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
for (var i = 0; i < length; i++) {
if (predicate.call(context, list[i], i, list)) {
return i;
} }
if (typeof predicate !== 'function') { }
throw new TypeError('predicate must be a function'); return -1;
} }
var list = Object(this);
var length = list.length >>> 0; if (!Array.prototype.findIndex) {
for (var i = 0; i < length; i++) { Object.defineProperty(Array.prototype, 'findIndex', {
if (predicate.call(context, list[i], i, list)) { enumerable: false,
return i; writable: true,
configurable: true,
value: findIndex
});
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
enumerable: false,
writable: true,
configurable: true,
value: function(predicate, context) {
if (this == null) {
throw new TypeError(
'Array.prototype.find called on null or undefined'
);
} }
var index = findIndex.call(this, predicate, context);
return index === -1 ? undefined : this[index];
} }
return -1; });
} }
if (!Array.prototype.findIndex) {
Object.defineProperty(Array.prototype, 'findIndex', {
enumerable: false,
writable: true,
configurable: true,
value: findIndex
});
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
enumerable: false,
writable: true,
configurable: true,
value: function(predicate, context) {
if (this == null) {
throw new TypeError(
'Array.prototype.find called on null or undefined'
);
}
var index = findIndex.call(this, predicate, context);
return index === -1 ? undefined : this[index];
}
});
}
})();

View File

@ -7,8 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory. * of patent rights can be found in the PATENTS file in the same directory.
*/ */
/* global self:true */ /* eslint-disable */
/* eslint-disable strict */
// Created by running: // Created by running:
// require('babel-core').buildExternalHelpers('_extends classCallCheck createClass createRawReactElement defineProperty get inherits interopRequireDefault interopRequireWildcard objectWithoutProperties possibleConstructorReturn slicedToArray taggedTemplateLiteral toArray toConsumableArray '.split(' ')) // require('babel-core').buildExternalHelpers('_extends classCallCheck createClass createRawReactElement defineProperty get inherits interopRequireDefault interopRequireWildcard objectWithoutProperties possibleConstructorReturn slicedToArray taggedTemplateLiteral toArray toConsumableArray '.split(' '))
@ -16,217 +15,215 @@
// //
// actually, that's a lie, because babel6 omits _extends and createRawReactElement // actually, that's a lie, because babel6 omits _extends and createRawReactElement
(function (global) { var babelHelpers = global.babelHelpers = {};
var babelHelpers = global.babelHelpers = {};
babelHelpers.createRawReactElement = (function () { babelHelpers.createRawReactElement = (function () {
var REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol.for && Symbol.for("react.element") || 0xeac7; var REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol.for && Symbol.for("react.element") || 0xeac7;
return function createRawReactElement(type, key, props) { return function createRawReactElement(type, key, props) {
return { return {
$$typeof: REACT_ELEMENT_TYPE, $$typeof: REACT_ELEMENT_TYPE,
type: type, type: type,
key: key, key: key,
ref: null, ref: null,
props: props, props: props,
_owner: null _owner: null
};
}; };
})();
babelHelpers.classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}; };
})();
babelHelpers.createClass = (function () { babelHelpers.classCallCheck = function (instance, Constructor) {
function defineProperties(target, props) { if (!(instance instanceof Constructor)) {
for (var i = 0; i < props.length; i++) { throw new TypeError("Cannot call a class as a function");
var descriptor = props[i]; }
descriptor.enumerable = descriptor.enumerable || false; };
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true; babelHelpers.createClass = (function () {
Object.defineProperty(target, descriptor.key, descriptor); 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) { return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps); if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps); if (staticProps) defineProperties(Constructor, staticProps);
return Constructor; return Constructor;
};
})();
babelHelpers.defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}; };
})();
babelHelpers._extends = babelHelpers.extends = Object.assign || function (target) { babelHelpers.defineProperty = function (obj, key, value) {
for (var i = 1; i < arguments.length; i++) { if (key in obj) {
var source = arguments[i]; Object.defineProperty(obj, key, {
value: value,
for (var key in source) { enumerable: true,
if (Object.prototype.hasOwnProperty.call(source, key)) { configurable: true,
target[key] = source[key]; writable: true
}
}
}
return target;
};
babelHelpers.get = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
babelHelpers.inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
}); });
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } else {
}; obj[key] = value;
}
babelHelpers.interopRequireDefault = function (obj) { return obj;
return obj && obj.__esModule ? obj : { };
default: obj
};
};
babelHelpers.interopRequireWildcard = function (obj) { babelHelpers._extends = babelHelpers.extends = Object.assign || function (target) {
if (obj && obj.__esModule) { for (var i = 1; i < arguments.length; i++) {
return obj; var source = arguments[i];
} else {
var newObj = {};
if (obj != null) { for (var key in source) {
for (var key in obj) { if (Object.prototype.hasOwnProperty.call(source, key)) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; target[key] = source[key];
}
} }
newObj.default = obj;
return newObj;
} }
}; }
babelHelpers.objectWithoutProperties = function (obj, keys) { return target;
var target = {}; };
for (var i in obj) { babelHelpers.get = function get(object, property, receiver) {
if (keys.indexOf(i) >= 0) continue; if (object === null) object = Function.prototype;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; var desc = Object.getOwnPropertyDescriptor(object, property);
target[i] = obj[i];
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
} }
return target; return getter.call(receiver);
}; }
};
babelHelpers.possibleConstructorReturn = function (self, call) { babelHelpers.inherits = function (subClass, superClass) {
if (!self) { if (typeof superClass !== "function" && superClass !== null) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
babelHelpers.interopRequireDefault = function (obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
};
babelHelpers.interopRequireWildcard = function (obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
} }
return call && (typeof call === "object" || typeof call === "function") ? call : self; newObj.default = obj;
}; return newObj;
}
};
babelHelpers.slicedToArray = (function () { babelHelpers.objectWithoutProperties = function (obj, keys) {
function sliceIterator(arr, i) { var target = {};
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
babelHelpers.possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
babelHelpers.slicedToArray = (function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try { try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { if (!_n && _i["return"]) _i["return"]();
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally { } finally {
try { if (_d) throw _e;
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
} }
return _arr;
} }
return function (arr, i) { return _arr;
if (Array.isArray(arr)) { }
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
})();
babelHelpers.taggedTemplateLiteral = function (strings, raw) {
return Object.freeze(Object.defineProperties(strings, {
raw: {
value: Object.freeze(raw)
}
}));
};
babelHelpers.toArray = function (arr) { return function (arr, i) {
return Array.isArray(arr) ? arr : Array.from(arr);
};
babelHelpers.toConsumableArray = function (arr) {
if (Array.isArray(arr)) { if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr;
} else if (Symbol.iterator in Object(arr)) {
return arr2; return sliceIterator(arr, i);
} else { } else {
return Array.from(arr); throw new TypeError("Invalid attempt to destructure non-iterable instance");
} }
}; };
})(typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this); })();
babelHelpers.taggedTemplateLiteral = function (strings, raw) {
return Object.freeze(Object.defineProperties(strings, {
raw: {
value: Object.freeze(raw)
}
}));
};
babelHelpers.toArray = function (arr) {
return Array.isArray(arr) ? arr : Array.from(arr);
};
babelHelpers.toConsumableArray = function (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);
}
};

View File

@ -14,495 +14,492 @@
* @nolint * @nolint
*/ */
(function(global) { /* eslint-disable */
'use strict';
var inspect = (function() { var inspect = (function() {
// Copyright Joyent, Inc. and other Node contributors. // Copyright Joyent, Inc. and other Node contributors.
// //
// Permission is hereby granted, free of charge, to any person obtaining a // Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the // copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including // "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish, // without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit // distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the // persons to whom the Software is furnished to do so, subject to the
// following conditions: // following conditions:
// //
// The above copyright notice and this permission notice shall be included // The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software. // in all copies or substantial portions of the Software.
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
// //
// https://github.com/joyent/node/blob/master/lib/util.js // https://github.com/joyent/node/blob/master/lib/util.js
function inspect(obj, opts) { function inspect(obj, opts) {
var ctx = { var ctx = {
seen: [], seen: [],
stylize: stylizeNoColor stylize: stylizeNoColor
}; };
return formatValue(ctx, obj, opts.depth); return formatValue(ctx, obj, opts.depth);
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
} }
function stylizeNoColor(str, styleType) { // Look up the keys of the object.
return str; var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
} }
function arrayToHash(array) { // Some type of object without properties can be shortcutted.
var hash = {}; if (keys.length === 0) {
if (isFunction(value)) {
array.forEach(function(val, idx) { var name = value.name ? ': ' + value.name : '';
hash[val] = true; return ctx.stylize('[Function' + name + ']', 'special');
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
} }
if (isRegExp(value)) {
// Look up the keys of the object. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
var keys = Object.keys(value); }
var visibleKeys = arrayToHash(keys); if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
// IE doesn't make error fields non-enumerable }
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value)) {
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value); return formatError(value);
} }
}
// Some type of object without properties can be shortcutted. var base = '', array = false, braces = ['{', '}'];
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make Array say that they are Array // Make functions say that they are functions
if (isArray(value)) { if (isFunction(value)) {
array = true; var n = value.name ? ': ' + value.name : '';
braces = ['[', ']']; base = ' [Function' + n + ']';
} }
// Make functions say that they are functions // Make RegExps say that they are RegExps
if (isFunction(value)) { if (isRegExp(value)) {
var n = value.name ? ': ' + value.name : ''; base = ' ' + RegExp.prototype.toString.call(value);
base = ' [Function' + n + ']'; }
}
// Make RegExps say that they are RegExps // Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) { if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value); return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else { } else {
output = keys.map(function(key) { return ctx.stylize('[Object]', 'special');
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
} }
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
} }
ctx.seen.push(value);
function formatPrimitive(ctx, value) { var output;
if (isUndefined(value)) if (array) {
return ctx.stylize('undefined', 'undefined'); output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
if (isString(value)) { } else {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') output = keys.map(function(key) {
.replace(/'/g, "\\'") return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
}); });
return output;
} }
ctx.seen.pop();
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { return reduceToSingleString(output, base, braces);
var name, str, desc; }
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) { function formatPrimitive(ctx, value) {
str = ctx.stylize('[Getter/Setter]', 'special'); if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else { } else {
str = ctx.stylize('[Getter]', 'special'); str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
} }
} else { } else {
if (desc.set) { str = ctx.stylize('[Circular]', 'special');
str = ctx.stylize('[Setter]', 'special');
}
} }
if (!hasOwnProperty(visibleKeys, key)) { }
name = '[' + key + ']'; if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
} }
if (!str) { name = JSON.stringify('' + key);
if (ctx.seen.indexOf(desc.value) < 0) { if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
if (isNull(recurseTimes)) { name = name.substr(1, name.length - 2);
str = formatValue(ctx, desc.value, null); name = ctx.stylize(name, 'name');
} else { } else {
str = formatValue(ctx, desc.value, recurseTimes - 1); name = name.replace(/'/g, "\\'")
} .replace(/\\"/g, '"')
if (str.indexOf('\n') > -1) { .replace(/(^"|"$)/g, "'");
if (array) { name = ctx.stylize(name, 'string');
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
} }
if (isUndefined(name)) { }
if (array && key.match(/^\d+$/)) {
return str; return name + ': ' + str;
} }
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2); function reduceToSingleString(output, base, braces) {
name = ctx.stylize(name, 'name'); var numLinesEst = 0;
} else { var length = output.reduce(function(prev, cur) {
name = name.replace(/'/g, "\\'") numLinesEst++;
.replace(/\\"/g, '"') if (cur.indexOf('\n') >= 0) numLinesEst++;
.replace(/(^"|"$)/g, "'"); return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
name = ctx.stylize(name, 'string'); }, 0);
}
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
function isBoolean(arg) {
return typeof arg === 'boolean';
}
function isNull(arg) {
return arg === null;
}
function isNullOrUndefined(arg) {
return arg == null;
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isString(arg) {
return typeof arg === 'string';
}
function isSymbol(arg) {
return typeof arg === 'symbol';
}
function isUndefined(arg) {
return arg === void 0;
}
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
function isFunction(arg) {
return typeof arg === 'function';
}
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
return inspect;
})();
var OBJECT_COLUMN_NAME = '(index)';
var LOG_LEVELS = {
trace: 0,
info: 1,
warn: 2,
error: 3
};
function setupConsole(global) {
if (!global.nativeLoggingHook) {
return;
}
function getNativeLogFunction(level) {
return function() {
var str;
if (arguments.length === 1 && typeof arguments[0] === 'string') {
str = arguments[0];
} else {
str = Array.prototype.map.call(arguments, function(arg) {
return inspect(arg, {depth: 10});
}).join(', ');
} }
return name + ': ' + str; var logLevel = level;
} if (str.slice(0, 9) === 'Warning: ' && logLevel >= LOG_LEVELS.error) {
// React warnings use console.error so that a stack trace is shown,
// but we don't (currently) want these to show a redbox
function reduceToSingleString(output, base, braces) { // (Note: Logic duplicated in ExceptionsManager.js.)
var numLinesEst = 0; logLevel = LOG_LEVELS.warn;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
} }
global.nativeLoggingHook(str, logLevel);
};
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; var repeat = function(element, n) {
} return Array.apply(null, Array(n)).map(function() { return element; });
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
function isBoolean(arg) {
return typeof arg === 'boolean';
}
function isNull(arg) {
return arg === null;
}
function isNullOrUndefined(arg) {
return arg == null;
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isString(arg) {
return typeof arg === 'string';
}
function isSymbol(arg) {
return typeof arg === 'symbol';
}
function isUndefined(arg) {
return arg === void 0;
}
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
function isFunction(arg) {
return typeof arg === 'function';
}
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
return inspect;
})();
var OBJECT_COLUMN_NAME = '(index)';
var LOG_LEVELS = {
trace: 0,
info: 1,
warn: 2,
error: 3
}; };
function setupConsole(global) { function consoleTablePolyfill(rows) {
if (!global.nativeLoggingHook) { // convert object -> array
if (!Array.isArray(rows)) {
var data = rows;
rows = [];
for (var key in data) {
if (data.hasOwnProperty(key)) {
var row = data[key];
row[OBJECT_COLUMN_NAME] = key;
rows.push(row);
}
}
}
if (rows.length === 0) {
global.nativeLoggingHook('', LOG_LEVELS.info);
return; return;
} }
function getNativeLogFunction(level) { var columns = Object.keys(rows[0]).sort();
return function() { var stringRows = [];
var str; var columnWidths = [];
if (arguments.length === 1 && typeof arguments[0] === 'string') {
str = arguments[0];
} else {
str = Array.prototype.map.call(arguments, function(arg) {
return inspect(arg, {depth: 10});
}).join(', ');
}
var logLevel = level; // Convert each cell to a string. Also
if (str.slice(0, 9) === 'Warning: ' && logLevel >= LOG_LEVELS.error) { // figure out max cell width for each column
// React warnings use console.error so that a stack trace is shown, columns.forEach(function(k, i) {
// but we don't (currently) want these to show a redbox columnWidths[i] = k.length;
// (Note: Logic duplicated in ExceptionsManager.js.) for (var j = 0; j < rows.length; j++) {
logLevel = LOG_LEVELS.warn; var cellStr = rows[j][k].toString();
} stringRows[j] = stringRows[j] || [];
global.nativeLoggingHook(str, logLevel); stringRows[j][i] = cellStr;
}; columnWidths[i] = Math.max(columnWidths[i], cellStr.length);
}
var repeat = function(element, n) {
return Array.apply(null, Array(n)).map(function() { return element; });
};
function consoleTablePolyfill(rows) {
// convert object -> array
if (!Array.isArray(rows)) {
var data = rows;
rows = [];
for (var key in data) {
if (data.hasOwnProperty(key)) {
var row = data[key];
row[OBJECT_COLUMN_NAME] = key;
rows.push(row);
}
}
} }
if (rows.length === 0) {
global.nativeLoggingHook('', LOG_LEVELS.info);
return;
}
var columns = Object.keys(rows[0]).sort();
var stringRows = [];
var columnWidths = [];
// Convert each cell to a string. Also
// figure out max cell width for each column
columns.forEach(function(k, i) {
columnWidths[i] = k.length;
for (var j = 0; j < rows.length; j++) {
var cellStr = rows[j][k].toString();
stringRows[j] = stringRows[j] || [];
stringRows[j][i] = cellStr;
columnWidths[i] = Math.max(columnWidths[i], cellStr.length);
}
});
// Join all elements in the row into a single string with | separators
// (appends extra spaces to each cell to make separators | alligned)
var joinRow = function(row, space) {
var cells = row.map(function(cell, i) {
var extraSpaces = repeat(' ', columnWidths[i] - cell.length).join('');
return cell + extraSpaces;
});
space = space || ' ';
return cells.join(space + '|' + space);
};
var separators = columnWidths.map(function(columnWidth) {
return repeat('-', columnWidth).join('');
});
var separatorRow = joinRow(separators, '-');
var header = joinRow(columns);
var table = [header, separatorRow];
for (var i = 0; i < rows.length; i++) {
table.push(joinRow(stringRows[i]));
}
// Notice extra empty line at the beginning.
// Native logging hook adds "RCTLog >" at the front of every
// logged string, which would shift the header and screw up
// the table
global.nativeLoggingHook('\n' + table.join('\n'), LOG_LEVELS.info);
}
// Preserve the original `console` as `originalConsole`
var originalConsole = global.console;
var descriptor = Object.getOwnPropertyDescriptor(global, 'console');
if (descriptor) {
Object.defineProperty(global, 'originalConsole', descriptor);
}
var console = {
error: getNativeLogFunction(LOG_LEVELS.error),
info: getNativeLogFunction(LOG_LEVELS.info),
log: getNativeLogFunction(LOG_LEVELS.info),
warn: getNativeLogFunction(LOG_LEVELS.warn),
trace: getNativeLogFunction(LOG_LEVELS.trace),
table: consoleTablePolyfill
};
// don't reassign to the original descriptor. breaks on ios7
Object.defineProperty(global, 'console', {
value: console,
configurable: descriptor ? descriptor.configurable : true,
enumerable: descriptor ? descriptor.enumerable : true,
writable: descriptor ? descriptor.writable : true,
}); });
// If available, also call the original `console` method since that is // Join all elements in the row into a single string with | separators
// sometimes useful. Ex: on OS X, this will let you see rich output in // (appends extra spaces to each cell to make separators | alligned)
// the Safari Web Inspector console. var joinRow = function(row, space) {
if (__DEV__ && originalConsole) { var cells = row.map(function(cell, i) {
Object.keys(console).forEach(methodName => { var extraSpaces = repeat(' ', columnWidths[i] - cell.length).join('');
var reactNativeMethod = console[methodName]; return cell + extraSpaces;
if (originalConsole[methodName]) {
console[methodName] = function() {
originalConsole[methodName](...arguments);
reactNativeMethod.apply(console, arguments);
};
}
}); });
space = space || ' ';
return cells.join(space + '|' + space);
};
var separators = columnWidths.map(function(columnWidth) {
return repeat('-', columnWidth).join('');
});
var separatorRow = joinRow(separators, '-');
var header = joinRow(columns);
var table = [header, separatorRow];
for (var i = 0; i < rows.length; i++) {
table.push(joinRow(stringRows[i]));
} }
// Notice extra empty line at the beginning.
// Native logging hook adds "RCTLog >" at the front of every
// logged string, which would shift the header and screw up
// the table
global.nativeLoggingHook('\n' + table.join('\n'), LOG_LEVELS.info);
} }
if (typeof module !== 'undefined') { // Preserve the original `console` as `originalConsole`
module.exports = setupConsole; var originalConsole = global.console;
} else { var descriptor = Object.getOwnPropertyDescriptor(global, 'console');
setupConsole(global); if (descriptor) {
Object.defineProperty(global, 'originalConsole', descriptor);
} }
})(this); var console = {
error: getNativeLogFunction(LOG_LEVELS.error),
info: getNativeLogFunction(LOG_LEVELS.info),
log: getNativeLogFunction(LOG_LEVELS.info),
warn: getNativeLogFunction(LOG_LEVELS.warn),
trace: getNativeLogFunction(LOG_LEVELS.trace),
table: consoleTablePolyfill
};
// don't reassign to the original descriptor. breaks on ios7
Object.defineProperty(global, 'console', {
value: console,
configurable: descriptor ? descriptor.configurable : true,
enumerable: descriptor ? descriptor.enumerable : true,
writable: descriptor ? descriptor.writable : true,
});
// If available, also call the original `console` method since that is
// sometimes useful. Ex: on OS X, this will let you see rich output in
// the Safari Web Inspector console.
if (__DEV__ && originalConsole) {
Object.keys(console).forEach(methodName => {
var reactNativeMethod = console[methodName];
if (originalConsole[methodName]) {
console[methodName] = function() {
originalConsole[methodName](...arguments);
reactNativeMethod.apply(console, arguments);
};
}
});
}
}
if (typeof module !== 'undefined') {
module.exports = setupConsole;
} else {
setupConsole(global);
}

View File

@ -13,74 +13,72 @@
* before any of the modules, this ErrorUtils must be defined (and the handler * before any of the modules, this ErrorUtils must be defined (and the handler
* set) globally before requiring anything. * set) globally before requiring anything.
*/ */
/* eslint global-strict:0 */ /* eslint strict:0 */
(function(global) { var ErrorUtils = {
var ErrorUtils = { _inGuard: 0,
_inGuard: 0, _globalHandler: null,
_globalHandler: null, setGlobalHandler: function(fun) {
setGlobalHandler: function(fun) { ErrorUtils._globalHandler = fun;
ErrorUtils._globalHandler = fun; },
}, reportError: function(error) {
reportError: function(error) { ErrorUtils._globalHandler && ErrorUtils._globalHandler(error);
ErrorUtils._globalHandler && ErrorUtils._globalHandler(error); },
}, reportFatalError: function(error) {
reportFatalError: function(error) { ErrorUtils._globalHandler && ErrorUtils._globalHandler(error, true);
ErrorUtils._globalHandler && ErrorUtils._globalHandler(error, true); },
}, applyWithGuard: function(fun, context, args) {
applyWithGuard: function(fun, context, args) { try {
try { ErrorUtils._inGuard++;
ErrorUtils._inGuard++; return fun.apply(context, args);
return fun.apply(context, args); } catch (e) {
} catch (e) { ErrorUtils.reportError(e);
ErrorUtils.reportError(e); } finally {
} finally { ErrorUtils._inGuard--;
ErrorUtils._inGuard--; }
} },
}, applyWithGuardIfNeeded: function(fun, context, args) {
applyWithGuardIfNeeded: function(fun, context, args) { if (ErrorUtils.inGuard()) {
if (ErrorUtils.inGuard()) { return fun.apply(context, args);
return fun.apply(context, args); } else {
} else { ErrorUtils.applyWithGuard(fun, context, args);
ErrorUtils.applyWithGuard(fun, context, args); }
} },
}, inGuard: function() {
inGuard: function() { return ErrorUtils._inGuard;
return ErrorUtils._inGuard; },
}, guard: function(fun, name, context) {
guard: function(fun, name, context) { if (typeof fun !== 'function') {
if (typeof fun !== 'function') { console.warn('A function must be passed to ErrorUtils.guard, got ', fun);
console.warn('A function must be passed to ErrorUtils.guard, got ', fun); return null;
return null; }
} name = name || fun.name || '<generated guard>';
name = name || fun.name || '<generated guard>'; function guarded() {
function guarded() { return (
return ( ErrorUtils.applyWithGuard(
ErrorUtils.applyWithGuard( fun,
fun, context || this,
context || this, arguments,
arguments, null,
null, name
name )
) );
);
}
return guarded;
} }
};
global.ErrorUtils = ErrorUtils;
/** return guarded;
* This is the error handler that is called when we encounter an exception
* when loading a module. This will report any errors encountered before
* ExceptionsManager is configured.
*/
function setupErrorGuard() {
var onError = function(e) {
global.console.error('Error: ' + e.message + ', stack:\n' + e.stack);
};
global.ErrorUtils.setGlobalHandler(onError);
} }
};
global.ErrorUtils = ErrorUtils;
setupErrorGuard(); /**
})(this); * This is the error handler that is called when we encounter an exception
* when loading a module. This will report any errors encountered before
* ExceptionsManager is configured.
*/
function setupErrorGuard() {
var onError = function(e) {
global.console.error('Error: ' + e.message + ', stack:\n' + e.stack);
};
global.ErrorUtils.setGlobalHandler(onError);
}
setupErrorGuard();

View File

@ -1,50 +1,34 @@
/* eslint global-strict:0 */ /* eslint strict:0 */
(global => {
let loadBundlesOnNative = (bundles) =>
new Promise((resolve) =>
require('NativeModules').RCTBundlesLoader.loadBundles(bundles, resolve));
let requestedBundles = Object.create(null); let loadBundlesOnNative = (bundles) =>
new Promise((resolve) =>
require('NativeModules').RCTBundlesLoader.loadBundles(bundles, resolve));
/** let requestedBundles = Object.create(null);
* Returns a promise that is fulfilled once all the indicated bundles are
* loaded into memory and injected into the JS engine.
* This invokation might need to go through the bridge
* and run native code to load some, if not all, the requested bundles.
* If all the bundles have already been loaded, the promise is resolved
* immediately. Otherwise, we'll determine which bundles still need to get
* loaded considering both, the ones already loaded, and the ones being
* currently asynchronously loaded by other invocations to `__loadBundles`,
* and return a promise that will get fulfilled once all these are finally
* loaded.
*
* Note this function should only be invoked by generated code.
*/
global.__loadBundles = function(bundles) {
// split bundles by whether they've already been requested or not
const bundlesToRequest = bundles.filter(b => !requestedBundles[b]);
const bundlesAlreadyRequested = bundles.filter(b => !!requestedBundles[b]);
// keep a reference to the promise loading each bundle /**
if (bundlesToRequest.length > 0) { * Returns a promise that is fulfilled once all the indicated bundles are
const nativePromise = loadBundlesOnNative(bundlesToRequest); * loaded into memory and injected into the JS engine.
bundlesToRequest.forEach(b => requestedBundles[b] = nativePromise); * This invokation might need to go through the bridge
} * and run native code to load some, if not all, the requested bundles.
* If all the bundles have already been loaded, the promise is resolved
* immediately. Otherwise, we'll determine which bundles still need to get
* loaded considering both, the ones already loaded, and the ones being
* currently asynchronously loaded by other invocations to `__loadBundles`,
* and return a promise that will get fulfilled once all these are finally
* loaded.
*
* Note this function should only be invoked by generated code.
*/
global.__loadBundles = function(bundles) {
// split bundles by whether they've already been requested or not
const bundlesToRequest = bundles.filter(b => !requestedBundles[b]);
return Promise.all(bundles.map(bundle => requestedBundles[bundle])); // keep a reference to the promise loading each bundle
}; if (bundlesToRequest.length > 0) {
})(global); const nativePromise = loadBundlesOnNative(bundlesToRequest);
bundlesToRequest.forEach(b => requestedBundles[b] = nativePromise);
}
return Promise.all(bundles.map(bundle => requestedBundles[bundle]));
// turns a callback async based function into a promised based one };
function promisify(fn) {
return function() {
var self = this;
var args = Array.prototype.slice.call(arguments);
return new Promise((resolve, reject) => {
args.push(resolve);
fn.apply(self, args);
});
};
}

View File

@ -15,7 +15,7 @@
// WARNING: This is an optimized version that fails on hasOwnProperty checks // WARNING: This is an optimized version that fails on hasOwnProperty checks
// and non objects. It's not spec-compliant. It's a perf optimization. // and non objects. It's not spec-compliant. It's a perf optimization.
/* eslint global-strict:0 */ /* eslint strict:0 */
Object.assign = function(target, sources) { Object.assign = function(target, sources) {
if (__DEV__) { if (__DEV__) {
if (target == null) { if (target == null) {

View File

@ -1,5 +1,4 @@
/* eslint global-strict:0 */ /* eslint strict:0 */
__DEV__ = false; global.__DEV__ = false;
/* global __BUNDLE_START_TIME__:true */ global.__BUNDLE_START_TIME__ = Date.now();
__BUNDLE_START_TIME__ = Date.now();

View File

@ -1,5 +1,4 @@
/* eslint global-strict:0 */ /* eslint strict:0 */
__DEV__ = true; global.__DEV__ = true;
/* global __BUNDLE_START_TIME__:true */ global.__BUNDLE_START_TIME__ = Date.now();
__BUNDLE_START_TIME__ = Date.now();

View File

@ -1,73 +1,70 @@
'use strict'; 'use strict';
((global) => { const {ErrorUtils, __nativeRequire} = global;
const {ErrorUtils, __nativeRequire} = global; global.require = require;
global.require = require; global.__d = define;
global.__d = define;
const modules = Object.create(null); const modules = Object.create(null);
const loadModule = ErrorUtils ? const loadModule = ErrorUtils ?
guardedLoadModule : loadModuleImplementation; guardedLoadModule : loadModuleImplementation;
function define(moduleId, factory) { function define(moduleId, factory) {
modules[moduleId] = { modules[moduleId] = {
factory, factory,
hasError: false, hasError: false,
exports: undefined, exports: undefined,
}; };
}
function require(moduleId) {
const module = modules[moduleId];
return module && module.exports || loadModule(moduleId, module);
}
function guardedLoadModule(moduleId, module) {
try {
return loadModuleImplementation(moduleId, module);
} catch (e) {
ErrorUtils.reportFatalError(e);
}
}
function loadModuleImplementation(moduleId, module) {
if (!module) {
__nativeRequire(moduleId);
module = modules[moduleId];
} }
function require(moduleId) { if (!module) {
const module = modules[moduleId]; throw unknownModuleError(moduleId);
return module && module.exports || loadModule(moduleId, module);
} }
function guardedLoadModule(moduleId, module) { if (module.hasError) {
try { throw moduleThrewError(moduleId);
return loadModuleImplementation(moduleId, module);
} catch (e) {
ErrorUtils.reportFatalError(e);
}
} }
function loadModuleImplementation(moduleId, module) { const exports = module.exports = {};
if (!module) { const {factory} = module;
__nativeRequire(moduleId); try {
module = modules[moduleId]; const moduleObject = {exports};
} factory(global, require, moduleObject, exports);
return (module.exports = moduleObject.exports);
if (!module) { } catch (e) {
throw unknownModuleError(moduleId); module.hasError = true;
} module.exports = undefined;
if (module.hasError) {
throw moduleThrewError(moduleId);
}
const exports = module.exports = {};
const {factory} = module;
try {
const moduleObject = {exports};
factory(global, require, moduleObject, exports);
return (module.exports = moduleObject.exports);
} catch(e) {
module.hasError = true;
module.exports = undefined;
}
} }
}
function unknownModuleError(id) { function unknownModuleError(id) {
let message = 'Requiring unknown module "' + id + '".'; let message = 'Requiring unknown module "' + id + '".';
if (__DEV__) { if (__DEV__) {
message += message +=
'If you are sure the module is there, try restarting the packager.'; 'If you are sure the module is there, try restarting the packager.';
}
return Error(message);
} }
return Error(message);
}
function moduleThrewError(id) { function moduleThrewError(id) {
return Error('Requiring module "' + id + '", which threw an exception.'); return Error('Requiring module "' + id + '", which threw an exception.');
} }
})(this);

View File

@ -1,130 +1,128 @@
/* eslint strict:0 */ /* eslint strict:0 */
(function(global) { var modules = Object.create(null);
var modules = Object.create(null); var inGuard = false;
var inGuard = false;
function define(id, factory) { function define(id, factory) {
modules[id] = { modules[id] = {
factory, factory,
module: {exports: {}}, module: {exports: {}},
isInitialized: false, isInitialized: false,
hasError: false, hasError: false,
}; };
if (__DEV__) { // HMR if (__DEV__) { // HMR
Object.assign(modules[id].module, { Object.assign(modules[id].module, {
hot: { hot: {
acceptCallback: null, acceptCallback: null,
accept: function(callback) { accept: function(callback) {
modules[id].module.hot.acceptCallback = callback; modules[id].module.hot.acceptCallback = callback;
}
} }
});
}
}
function require(id) {
var mod = modules[id];
if (mod && mod.isInitialized) {
return mod.module.exports;
}
return requireImpl(id);
}
function requireImpl(id) {
if (global.ErrorUtils && !inGuard) {
inGuard = true;
var returnValue;
try {
returnValue = requireImpl.apply(this, arguments);
} catch (e) {
global.ErrorUtils.reportFatalError(e);
} }
inGuard = false; });
return returnValue; }
} }
var mod = modules[id];
if (!mod) {
var msg = 'Requiring unknown module "' + id + '"';
if (__DEV__) {
msg += '. If you are sure the module is there, try restarting the packager.';
}
throw new Error(msg);
}
if (mod.hasError) {
throw new Error(
'Requiring module "' + id + '" which threw an exception'
);
}
try {
// We must optimistically mark mod as initialized before running the factory to keep any
// require cycles inside the factory from causing an infinite require loop.
mod.isInitialized = true;
__DEV__ && Systrace().beginEvent('JS_require_' + id);
// keep args in sync with with defineModuleCode in
// packager/react-packager/src/Resolver/index.js
mod.factory.call(global, global, require, mod.module, mod.module.exports);
__DEV__ && Systrace().endEvent();
} catch (e) {
mod.hasError = true;
mod.isInitialized = false;
throw e;
}
function require(id) {
var mod = modules[id];
if (mod && mod.isInitialized) {
return mod.module.exports; return mod.module.exports;
} }
const Systrace = __DEV__ && (() => { return requireImpl(id);
var _Systrace; }
function requireImpl(id) {
if (global.ErrorUtils && !inGuard) {
inGuard = true;
var returnValue;
try { try {
_Systrace = require('Systrace'); returnValue = requireImpl.apply(this, arguments);
} catch(e) {} } catch (e) {
global.ErrorUtils.reportFatalError(e);
}
inGuard = false;
return returnValue;
}
return _Systrace && _Systrace.beginEvent ? var mod = modules[id];
_Systrace : { beginEvent: () => {}, endEvent: () => {} }; if (!mod) {
}); var msg = 'Requiring unknown module "' + id + '"';
if (__DEV__) {
msg += '. If you are sure the module is there, try restarting the packager.';
}
throw new Error(msg);
}
global.__d = define; if (mod.hasError) {
global.require = require; throw new Error(
'Requiring module "' + id + '" which threw an exception'
);
}
if (__DEV__) { // HMR try {
function accept(id, factory) { // We must optimistically mark mod as initialized before running the factory to keep any
var mod = modules[id]; // require cycles inside the factory from causing an infinite require loop.
mod.isInitialized = true;
if (!mod) { __DEV__ && Systrace().beginEvent('JS_require_' + id);
define(id, factory);
return; // new modules don't need to be accepted
}
if (!mod.module.hot) { // keep args in sync with with defineModuleCode in
console.warn( // packager/react-packager/src/Resolver/index.js
'Cannot accept module because Hot Module Replacement ' + mod.factory.call(global, global, require, mod.module, mod.module.exports);
'API was not installed.'
);
return;
}
if (mod.module.hot.acceptCallback) { __DEV__ && Systrace().endEvent();
mod.factory = factory; } catch (e) {
mod.isInitialized = false; mod.hasError = true;
require(id); mod.isInitialized = false;
throw e;
}
mod.module.hot.acceptCallback(); return mod.module.exports;
} else { }
console.warn(
'[HMR] Module `' + id + '` can\'t be hot reloaded because it ' + const Systrace = __DEV__ && (() => {
'doesn\'t provide accept callback hook. Reload the app to get the updates.' var _Systrace;
); try {
} _Systrace = require('Systrace');
} catch (e) {}
return _Systrace && _Systrace.beginEvent ?
_Systrace : { beginEvent: () => {}, endEvent: () => {} };
});
global.__d = define;
global.require = require;
if (__DEV__) { // HMR
function accept(id, factory) {
var mod = modules[id];
if (!mod) {
define(id, factory);
return; // new modules don't need to be accepted
} }
global.__accept = accept; if (!mod.module.hot) {
console.warn(
'Cannot accept module because Hot Module Replacement ' +
'API was not installed.'
);
return;
}
if (mod.module.hot.acceptCallback) {
mod.factory = factory;
mod.isInitialized = false;
require(id);
mod.module.hot.acceptCallback();
} else {
console.warn(
'[HMR] Module `' + id + '` can\'t be hot reloaded because it ' +
'doesn\'t provide accept callback hook. Reload the app to get the updates.'
);
}
} }
})(this);
global.__accept = accept;
}

View File

@ -33,7 +33,7 @@ const trim = (str) =>
describe('dead-module-elimination', () => { describe('dead-module-elimination', () => {
it('should inline __DEV__', () => { it('should inline __DEV__', () => {
compare( compare(
`__DEV__ = false; `global.__DEV__ = false;
var foo = __DEV__;`, var foo = __DEV__;`,
`var foo = false;` `var foo = false;`
); );
@ -41,7 +41,7 @@ describe('dead-module-elimination', () => {
it('should accept unary operators with literals', () => { it('should accept unary operators with literals', () => {
compare( compare(
`__DEV__ = !1; `global.__DEV__ = !1;
var foo = __DEV__;`, var foo = __DEV__;`,
`var foo = false;` `var foo = false;`
); );
@ -49,7 +49,7 @@ describe('dead-module-elimination', () => {
it('should kill dead branches', () => { it('should kill dead branches', () => {
compare( compare(
`__DEV__ = false; `global.__DEV__ = false;
if (__DEV__) { if (__DEV__) {
doSomething(); doSomething();
}`, }`,
@ -74,7 +74,7 @@ describe('dead-module-elimination', () => {
it('should kill modules referenced only from dead branches', () => { it('should kill modules referenced only from dead branches', () => {
compare( compare(
`__DEV__ = false; `global.__DEV__ = false;
__d('bar', function() {}); __d('bar', function() {});
if (__DEV__) { require('bar'); }`, if (__DEV__) { require('bar'); }`,
`` ``
@ -83,7 +83,7 @@ describe('dead-module-elimination', () => {
it('should replace logical expressions with the result', () => { it('should replace logical expressions with the result', () => {
compare( compare(
`__DEV__ = false; `global.__DEV__ = false;
__d('bar', function() {}); __d('bar', function() {});
__DEV__ && require('bar');`, __DEV__ && require('bar');`,
`false;` `false;`
@ -92,7 +92,7 @@ describe('dead-module-elimination', () => {
it('should keep if result branch', () => { it('should keep if result branch', () => {
compare( compare(
`__DEV__ = false; `global.__DEV__ = false;
__d('bar', function() {}); __d('bar', function() {});
if (__DEV__) { if (__DEV__) {
killWithFire(); killWithFire();
@ -106,7 +106,7 @@ describe('dead-module-elimination', () => {
it('should replace falsy ternaries with alternate expression', () => { it('should replace falsy ternaries with alternate expression', () => {
compare( compare(
`__DEV__ = false; `global.__DEV__ = false;
__DEV__ ? foo() : bar(); __DEV__ ? foo() : bar();
`, `,
`bar();` `bar();`

View File

@ -60,7 +60,12 @@ module.exports = function () {
AssignmentExpression(path) { AssignmentExpression(path) {
const { node } = path; const { node } = path;
if (node.left.type === 'Identifier' && node.left.name === '__DEV__') { if (
node.left.type === 'MemberExpression' &&
node.left.object.name === 'global' &&
node.left.property.type === 'Identifier' &&
node.left.property.name === '__DEV__'
) {
var value; var value;
if (node.right.type === 'BooleanLiteral') { if (node.right.type === 'BooleanLiteral') {
value = node.right.value; value = node.right.value;
@ -73,7 +78,7 @@ module.exports = function () {
} else { } else {
return; return;
} }
globals[node.left.name] = value; globals[node.left.property.name] = value;
// workaround babel/source map bug - the minifier should strip it // workaround babel/source map bug - the minifier should strip it
path.replaceWith(t.booleanLiteral(value)); path.replaceWith(t.booleanLiteral(value));