Reviewed By: davidaurelio

Differential Revision: D4627645

fbshipit-source-id: 3cf368c6a24a555b7d0a39045f6ba6fd92ae34e1
This commit is contained in:
Christoph Pojer 2017-02-28 08:58:14 -08:00 коммит произвёл Facebook Github Bot
Родитель 05c36b463b
Коммит 5403946f09
54 изменённых файлов: 521 добавлений и 522 удалений

Просмотреть файл

@ -38,8 +38,8 @@ describe('AssetServer', () => {
imgs: { imgs: {
'b.png': 'b image', 'b.png': 'b image',
'b@2x.png': 'b2 image', 'b@2x.png': 'b2 image',
} },
} },
}); });
return Promise.all([ return Promise.all([
@ -65,8 +65,8 @@ describe('AssetServer', () => {
'b.android.png': 'b android image', 'b.android.png': 'b android image',
'c.png': 'c general image', 'c.png': 'c general image',
'c.android.png': 'c android image', 'c.android.png': 'c android image',
} },
} },
}); });
return Promise.all([ return Promise.all([
@ -100,8 +100,8 @@ describe('AssetServer', () => {
imgs: { imgs: {
'b.png': 'png image', 'b.png': 'png image',
'b.jpg': 'jpeg image', 'b.jpg': 'jpeg image',
} },
} },
}); });
return Promise.all([ return Promise.all([
@ -128,8 +128,8 @@ describe('AssetServer', () => {
'b@2x.png': 'b2 image', 'b@2x.png': 'b2 image',
'b@4x.png': 'b4 image', 'b@4x.png': 'b4 image',
'b@4.5x.png': 'b4.5 image', 'b@4.5x.png': 'b4.5 image',
} },
} },
}); });
return server.get('imgs/b@3x.png').then(data => return server.get('imgs/b@3x.png').then(data =>
@ -154,8 +154,8 @@ describe('AssetServer', () => {
'b@2x.ios.png': 'b2 ios image', 'b@2x.ios.png': 'b2 ios image',
'b@4x.ios.png': 'b4 ios image', 'b@4x.ios.png': 'b4 ios image',
'b@4.5x.ios.png': 'b4.5 ios image', 'b@4.5x.ios.png': 'b4.5 ios image',
} },
} },
}); });
return Promise.all([ return Promise.all([
@ -209,8 +209,8 @@ describe('AssetServer', () => {
'b@2x.png': 'b2 image', 'b@2x.png': 'b2 image',
'b@4x.png': 'b4 image', 'b@4x.png': 'b4 image',
'b@4.5x.png': 'b4.5 image', 'b@4.5x.png': 'b4.5 image',
} },
} },
}); });
return server.getAssetData('imgs/b.png').then(data => { return server.getAssetData('imgs/b.png').then(data => {
@ -241,8 +241,8 @@ describe('AssetServer', () => {
'b@2x.jpg': 'b2 image', 'b@2x.jpg': 'b2 image',
'b@4x.jpg': 'b4 image', 'b@4x.jpg': 'b4 image',
'b@4.5x.jpg': 'b4.5 image', 'b@4.5x.jpg': 'b4.5 image',
} },
} },
}); });
return server.getAssetData('imgs/b.jpg').then(data => { return server.getAssetData('imgs/b.jpg').then(data => {
@ -275,11 +275,11 @@ describe('AssetServer', () => {
'b@2x.jpg': 'b2 image', 'b@2x.jpg': 'b2 image',
'b@4x.jpg': 'b4 image', 'b@4x.jpg': 'b4 image',
'b@4.5x.jpg': 'b4.5 image', 'b@4.5x.jpg': 'b4.5 image',
} },
} },
}; };
fs.__setMockFilesystem(mockFS); fs.__setMockFilesystem(mockFS);
}); });
it('uses the file contents to build the hash', () => { it('uses the file contents to build the hash', () => {

Просмотреть файл

@ -15,14 +15,14 @@ const fs = require('fs');
const getAssetDataFromName = require('../node-haste').getAssetDataFromName; const getAssetDataFromName = require('../node-haste').getAssetDataFromName;
const path = require('path'); const path = require('path');
const createTimeoutPromise = (timeout) => new Promise((resolve, reject) => { const createTimeoutPromise = timeout => new Promise((resolve, reject) => {
setTimeout(reject, timeout, 'fs operation timeout'); setTimeout(reject, timeout, 'fs operation timeout');
}); });
function timeoutableDenodeify(fsFunc, timeout) { function timeoutableDenodeify(fsFunc, timeout) {
return function raceWrapper(...args) { return function raceWrapper(...args) {
return Promise.race([ return Promise.race([
createTimeoutPromise(timeout), createTimeoutPromise(timeout),
denodeify(fsFunc).apply(this, args) denodeify(fsFunc).apply(this, args),
]); ]);
}; };
} }
@ -134,7 +134,7 @@ class AssetServer {
const map = this._buildAssetMap(dir, files, platform); const map = this._buildAssetMap(dir, files, platform);
let record; let record;
if (platform != null){ if (platform != null) {
record = map[getAssetKey(assetData.assetName, platform)] || record = map[getAssetKey(assetData.assetName, platform)] ||
map[assetData.assetName]; map[assetData.assetName];
} else { } else {

Просмотреть файл

@ -229,7 +229,7 @@ class Bundle extends BundleBase {
} }
result.sections.push({ result.sections.push({
offset: { line: line, column: 0 }, offset: {line, column: 0},
map: (map: MixedSourceMap), map: (map: MixedSourceMap),
}); });
line += module.code.split('\n').length; line += module.code.split('\n').length;
@ -324,11 +324,11 @@ function generateSourceMapForVirtualModule(module): SourceMap {
return { return {
version: 3, version: 3,
sources: [ module.sourcePath ], sources: [module.sourcePath],
names: [], names: [],
mappings: mappings, mappings,
file: module.sourcePath, file: module.sourcePath,
sourcesContent: [ module.sourceCode ], sourcesContent: [module.sourceCode],
}; };
} }

Просмотреть файл

@ -94,7 +94,7 @@ class BundleBase {
return this._source; return this._source;
} }
this._source = this._modules.map((module) => module.code).join('\n'); this._source = this._modules.map(module => module.code).join('\n');
return this._source; return this._source;
} }

Просмотреть файл

@ -14,7 +14,7 @@ const ModuleTransport = require('../lib/ModuleTransport');
class HMRBundle extends BundleBase { class HMRBundle extends BundleBase {
constructor({sourceURLFn, sourceMappingURLFn}) { constructor({sourceURLFn, sourceMappingURLFn}) {
super(); super();
this._sourceURLFn = sourceURLFn this._sourceURLFn = sourceURLFn;
this._sourceMappingURLFn = sourceMappingURLFn; this._sourceMappingURLFn = sourceMappingURLFn;
this._sourceURLs = []; this._sourceURLs = [];
this._sourceMappingURLs = []; this._sourceMappingURLs = [];

Просмотреть файл

@ -46,7 +46,7 @@ describe('Bundle', () => {
expect(bundle.getSource({dev: true})).toBe([ expect(bundle.getSource({dev: true})).toBe([
'transformed foo;', 'transformed foo;',
'transformed bar;', 'transformed bar;',
'\/\/# sourceMappingURL=test_url' '\/\/# sourceMappingURL=test_url',
].join('\n')); ].join('\n'));
}); });
}); });
@ -118,7 +118,7 @@ describe('Bundle', () => {
const resolver = { const resolver = {
wrapModule({name}) { wrapModule({name}) {
return new Promise(resolve => resolves[name] = resolve); return new Promise(resolve => resolves[name] = resolve);
} },
}; };
const promise = Promise.all( const promise = Promise.all(
@ -180,49 +180,49 @@ describe('Bundle', () => {
file: 'test_url', file: 'test_url',
version: 3, version: 3,
sections: [ sections: [
{ offset: { line: 0, column: 0 }, map: { name: 'sourcemap foo' } }, {offset: {line: 0, column: 0}, map: {name: 'sourcemap foo'}},
{ offset: { line: 2, column: 0 }, map: { name: 'sourcemap bar' } }, {offset: {line: 2, column: 0}, map: {name: 'sourcemap bar'}},
{ {
offset: { offset: {
column: 0, column: 0,
line: 4 line: 4,
}, },
map: { map: {
file: 'image.png', file: 'image.png',
mappings: 'AAAA;AACA;', mappings: 'AAAA;AACA;',
names: [], names: [],
sources: [ 'image.png' ], sources: ['image.png'],
sourcesContent: ['image module;\nimage module;'], sourcesContent: ['image module;\nimage module;'],
version: 3, version: 3,
} },
}, },
{ {
offset: { offset: {
column: 0, column: 0,
line: 6 line: 6,
}, },
map: { map: {
file: 'require-InitializeCore.js', file: 'require-InitializeCore.js',
mappings: 'AAAA;', mappings: 'AAAA;',
names: [], names: [],
sources: [ 'require-InitializeCore.js' ], sources: ['require-InitializeCore.js'],
sourcesContent: [';require("InitializeCore");'], sourcesContent: [';require("InitializeCore");'],
version: 3, version: 3,
} },
}, },
{ {
offset: { offset: {
column: 0, column: 0,
line: 7 line: 7,
}, },
map: { map: {
file: 'require-foo.js', file: 'require-foo.js',
mappings: 'AAAA;', mappings: 'AAAA;',
names: [], names: [],
sources: [ 'require-foo.js' ], sources: ['require-foo.js'],
sourcesContent: [';require("foo");'], sourcesContent: [';require("foo");'],
version: 3, version: 3,
} },
}, },
], ],
}); });
@ -342,7 +342,7 @@ describe('Bundle', () => {
const {groups} = bundle.getUnbundle(); const {groups} = bundle.getUnbundle();
expect(groups).toEqual(new Map([[ expect(groups).toEqual(new Map([[
idFor('Product1'), idFor('Product1'),
new Set(['React', 'ReactFoo', 'invariant', 'ReactBar', 'cx'].map(idFor)) new Set(['React', 'ReactFoo', 'invariant', 'ReactBar', 'cx'].map(idFor)),
]])); ]]));
}); });

Просмотреть файл

@ -82,14 +82,14 @@ describe('Bundler', function() {
Resolver.mockImplementation(function() { Resolver.mockImplementation(function() {
return { return {
getDependencies: getDependencies, getDependencies,
getModuleSystemDependencies: getModuleSystemDependencies, getModuleSystemDependencies,
}; };
}); });
fs.statSync.mockImplementation(function() { fs.statSync.mockImplementation(function() {
return { return {
isDirectory: () => true isDirectory: () => true,
}; };
}); });
@ -104,7 +104,7 @@ describe('Bundler', function() {
bundler = new Bundler({ bundler = new Bundler({
...commonOptions, ...commonOptions,
projectRoots, projectRoots,
assetServer: assetServer, assetServer,
}); });
modules = [ modules = [
@ -115,7 +115,7 @@ describe('Bundler', function() {
path: '/root/img/new_image.png', path: '/root/img/new_image.png',
isAsset: true, isAsset: true,
resolution: 2, resolution: 2,
dependencies: [] dependencies: [],
}), }),
createModule({ createModule({
id: 'package/file.json', id: 'package/file.json',
@ -140,14 +140,14 @@ describe('Bundler', function() {
}); });
sizeOf.mockImplementation(function(path, cb) { sizeOf.mockImplementation(function(path, cb) {
cb(null, { width: 50, height: 100 }); cb(null, {width: 50, height: 100});
}); });
}); });
it('create a bundle', function() { it('create a bundle', function() {
assetServer.getAssetData.mockImplementation(() => { assetServer.getAssetData.mockImplementation(() => {
return Promise.resolve({ return Promise.resolve({
scales: [1,2,3], scales: [1, 2, 3],
files: [ files: [
'/root/img/img.png', '/root/img/img.png',
'/root/img/img@2x.png', '/root/img/img@2x.png',
@ -165,39 +165,39 @@ describe('Bundler', function() {
runModule: true, runModule: true,
sourceMapUrl: 'source_map_url', sourceMapUrl: 'source_map_url',
}).then(bundle => { }).then(bundle => {
const ithAddedModule = (i) => bundle.addModule.mock.calls[i][2].path; const ithAddedModule = i => bundle.addModule.mock.calls[i][2].path;
expect(ithAddedModule(0)).toEqual('/root/foo.js'); expect(ithAddedModule(0)).toEqual('/root/foo.js');
expect(ithAddedModule(1)).toEqual('/root/bar.js'); expect(ithAddedModule(1)).toEqual('/root/bar.js');
expect(ithAddedModule(2)).toEqual('/root/img/new_image.png'); expect(ithAddedModule(2)).toEqual('/root/img/new_image.png');
expect(ithAddedModule(3)).toEqual('/root/file.json'); expect(ithAddedModule(3)).toEqual('/root/file.json');
expect(bundle.finalize.mock.calls[0]).toEqual([{ expect(bundle.finalize.mock.calls[0]).toEqual([{
runModule: true, runModule: true,
runBeforeMainModule: [], runBeforeMainModule: [],
allowUpdates: false, allowUpdates: false,
}]); }]);
expect(bundle.addAsset.mock.calls[0]).toEqual([{ expect(bundle.addAsset.mock.calls[0]).toEqual([{
__packager_asset: true, __packager_asset: true,
fileSystemLocation: '/root/img', fileSystemLocation: '/root/img',
httpServerLocation: '/assets/img', httpServerLocation: '/assets/img',
width: 50, width: 50,
height: 100, height: 100,
scales: [1, 2, 3], scales: [1, 2, 3],
files: [ files: [
'/root/img/img.png', '/root/img/img.png',
'/root/img/img@2x.png', '/root/img/img@2x.png',
'/root/img/img@3x.png', '/root/img/img@3x.png',
], ],
hash: 'i am a hash', hash: 'i am a hash',
name: 'img', name: 'img',
type: 'png', type: 'png',
}]); }]);
// TODO(amasad) This fails with 0 != 5 in OSS // TODO(amasad) This fails with 0 != 5 in OSS
//expect(ProgressBar.prototype.tick.mock.calls.length).toEqual(modules.length); //expect(ProgressBar.prototype.tick.mock.calls.length).toEqual(modules.length);
}); });
}); });
it('loads and runs asset plugins', function() { it('loads and runs asset plugins', function() {
@ -211,7 +211,7 @@ describe('Bundler', function() {
jest.mock('asyncMockPlugin2', () => { jest.mock('asyncMockPlugin2', () => {
return asset => { return asset => {
expect(asset.extraReverseHash).toBeDefined(); expect(asset.extraReverseHash).toBeDefined();
return new Promise((resolve) => { return new Promise(resolve => {
asset.extraPixelCount = asset.width * asset.height; asset.extraPixelCount = asset.width * asset.height;
resolve(asset); resolve(asset);
}); });
@ -219,7 +219,7 @@ describe('Bundler', function() {
}, {virtual: true}); }, {virtual: true});
const mockAsset = { const mockAsset = {
scales: [1,2,3], scales: [1, 2, 3],
files: [ files: [
'/root/img/img.png', '/root/img/img.png',
'/root/img/img@2x.png', '/root/img/img@2x.png',
@ -265,15 +265,15 @@ describe('Bundler', function() {
// jest calledWith does not support jasmine.any // jest calledWith does not support jasmine.any
expect(getDependencies.mock.calls[0].slice(0, -2)).toEqual([ expect(getDependencies.mock.calls[0].slice(0, -2)).toEqual([
'/root/foo.js', '/root/foo.js',
{ dev: true, recursive: true }, {dev: true, recursive: true},
{ minify: false, {minify: false,
dev: true, dev: true,
transform: { transform: {
dev: true, dev: true,
hot: false, hot: false,
generateSourceMaps: false, generateSourceMaps: false,
projectRoots, projectRoots,
} },
}, },
]) ])
); );
@ -284,7 +284,7 @@ describe('Bundler', function() {
const b = new Bundler({ const b = new Bundler({
...commonOptions, ...commonOptions,
projectRoots, projectRoots,
assetServer: assetServer, assetServer,
platforms: ['android', 'vr'], platforms: ['android', 'vr'],
}); });
expect(b._opts.platforms).toEqual(['android', 'vr']); expect(b._opts.platforms).toEqual(['android', 'vr']);
@ -295,7 +295,7 @@ describe('Bundler', function() {
assetServer.getAssetData.mockImplementation(function(relPath) { assetServer.getAssetData.mockImplementation(function(relPath) {
if (relPath === 'img/new_image.png') { if (relPath === 'img/new_image.png') {
return Promise.resolve({ return Promise.resolve({
scales: [1,2,3], scales: [1, 2, 3],
files: [ files: [
'/root/img/new_image.png', '/root/img/new_image.png',
'/root/img/new_image@2x.png', '/root/img/new_image@2x.png',
@ -307,7 +307,7 @@ describe('Bundler', function() {
}); });
} else if (relPath === 'img/new_image2.png') { } else if (relPath === 'img/new_image2.png') {
return Promise.resolve({ return Promise.resolve({
scales: [1,2,3], scales: [1, 2, 3],
files: [ files: [
'/root/img/new_image2.png', '/root/img/new_image2.png',
'/root/img/new_image2@2x.png', '/root/img/new_image2@2x.png',
@ -330,12 +330,12 @@ describe('Bundler', function() {
path: '/root/img/new_image2.png', path: '/root/img/new_image2.png',
isAsset: true, isAsset: true,
resolution: 2, resolution: 2,
dependencies: [] dependencies: [],
}), }),
); );
return bundler.getOrderedDependencyPaths('/root/foo.js', true) return bundler.getOrderedDependencyPaths('/root/foo.js', true)
.then((paths) => expect(paths).toEqual([ .then(paths => expect(paths).toEqual([
'/root/foo.js', '/root/foo.js',
'/root/bar.js', '/root/bar.js',
'/root/img/new_image.png', '/root/img/new_image.png',

Просмотреть файл

@ -552,13 +552,13 @@ class Bundler {
}); });
} }
getOrderedDependencyPaths({ entryFile, dev, platform }: { getOrderedDependencyPaths({entryFile, dev, platform}: {
entryFile: string, entryFile: string,
dev: boolean, dev: boolean,
platform: string, platform: string,
}) { }) {
return this.getDependencies({entryFile, dev, platform}).then( return this.getDependencies({entryFile, dev, platform}).then(
({ dependencies }) => { ({dependencies}) => {
const ret = []; const ret = [];
const promises = []; const promises = [];
const placeHolder = {}; const placeHolder = {};
@ -578,7 +578,7 @@ class Bundler {
}); });
return Promise.all(promises).then(assetsData => { return Promise.all(promises).then(assetsData => {
assetsData.forEach(({ files }) => { assetsData.forEach(({files}) => {
const index = ret.indexOf(placeHolder); const index = ret.indexOf(placeHolder);
ret.splice(index, 1, ...files); ret.splice(index, 1, ...files);
}); });
@ -636,7 +636,7 @@ class Bundler {
map, map,
meta: {dependencies, dependencyOffsets, preloaded, dependencyPairs}, meta: {dependencies, dependencyOffsets, preloaded, dependencyPairs},
sourceCode: source, sourceCode: source,
sourcePath: module.path sourcePath: module.path,
}); });
}); });
} }
@ -657,12 +657,12 @@ class Bundler {
// Test extension against all types supported by image-size module. // Test extension against all types supported by image-size module.
// If it's not one of these, we won't treat it as an image. // If it's not one of these, we won't treat it as an image.
const isImage = [ const isImage = [
'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff' 'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff',
].indexOf(extname(module.path).slice(1)) !== -1; ].indexOf(extname(module.path).slice(1)) !== -1;
return this._assetServer.getAssetData(relPath, platform).then((assetData) => { return this._assetServer.getAssetData(relPath, platform).then(assetData => {
return Promise.all([isImage ? sizeOf(assetData.files[0]) : null, assetData]); return Promise.all([isImage ? sizeOf(assetData.files[0]) : null, assetData]);
}).then((res) => { }).then(res => {
const dimensions = res[0]; const dimensions = res[0];
const assetData = res[1]; const assetData = res[1];
const scale = assetData.scales[0]; const scale = assetData.scales[0];
@ -680,7 +680,7 @@ class Bundler {
}; };
return this._applyAssetPlugins(assetPlugins, asset); return this._applyAssetPlugins(assetPlugins, asset);
}).then((asset) => { }).then(asset => {
const json = JSON.stringify(filterObject(asset, assetPropertyBlacklist)); const json = JSON.stringify(filterObject(asset, assetPropertyBlacklist));
const assetRegistryPath = 'react-native/Libraries/Image/AssetRegistry'; const assetRegistryPath = 'react-native/Libraries/Image/AssetRegistry';
const code = const code =
@ -691,7 +691,7 @@ class Bundler {
return { return {
asset, asset,
code, code,
meta: {dependencies, dependencyOffsets} meta: {dependencies, dependencyOffsets},
}; };
}); });
} }
@ -736,7 +736,7 @@ class Bundler {
name, name,
id: moduleId, id: moduleId,
code, code,
meta: meta, meta,
sourceCode: code, sourceCode: code,
sourcePath: module.path, sourcePath: module.path,
virtual: true, virtual: true,

Просмотреть файл

@ -47,7 +47,7 @@ describe('build map from raw mappings', () => {
[1, 2], [1, 2],
[3, 4, 5, 6, 'apples'], [3, 4, 5, 6, 'apples'],
[7, 8, 9, 10], [7, 8, 9, 10],
[11, 12, 13, 14, 'pears'] [11, 12, 13, 14, 'pears'],
], ],
sourceCode: 'code1', sourceCode: 'code1',
sourcePath: 'path1', sourcePath: 'path1',
@ -65,7 +65,7 @@ describe('build map from raw mappings', () => {
[11, 12], [11, 12],
[13, 14, 15, 16, 'bananas'], [13, 14, 15, 16, 'bananas'],
[17, 18, 19, 110], [17, 18, 19, 110],
[21, 112, 113, 114, 'pears'] [21, 112, 113, 114, 'pears'],
], ],
sourceCode: 'code3', sourceCode: 'code3',
sourcePath: 'path3', sourcePath: 'path3',

Просмотреть файл

@ -110,11 +110,11 @@ function encode(value: number, buffer: Buffer, position: number): number {
let digit, vlq = toVLQSigned(value); let digit, vlq = toVLQSigned(value);
do { do {
digit = vlq & VLQ_BASE_MASK; digit = vlq & VLQ_BASE_MASK;
vlq = vlq >>> VLQ_BASE_SHIFT; vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) { if (vlq > 0) {
// There are still more digits in this value, so we must make sure the // There are still more digits in this value, so we must make sure the
// continuation bit is marked. // continuation bit is marked.
digit = digit | VLQ_CONTINUATION_BIT; digit |= VLQ_CONTINUATION_BIT;
} }
buffer[position++] = CHAR_MAP[digit]; buffer[position++] = CHAR_MAP[digit];
} while (vlq > 0); } while (vlq > 0);

Просмотреть файл

@ -44,7 +44,7 @@ function fromRawMappings(modules: Array<ModuleTransport>): Generator {
); );
} }
carryOver = carryOver + countLines(code); carryOver += countLines(code);
} }
return generator; return generator;

Просмотреть файл

@ -8,6 +8,6 @@
*/ */
'use strict'; 'use strict';
module.exports = function (data, callback) { module.exports = function(data, callback) {
callback(null, {}); callback(null, {});
}; };

Просмотреть файл

@ -57,7 +57,7 @@ function makeFarm(worker, methods, timeout) {
{ {
autoStart: true, autoStart: true,
maxConcurrentCallsPerWorker: 1, maxConcurrentCallsPerWorker: 1,
maxConcurrentWorkers: maxConcurrentWorkers, maxConcurrentWorkers,
maxCallsPerWorker: MAX_CALLS_PER_WORKER, maxCallsPerWorker: MAX_CALLS_PER_WORKER,
maxCallTime: timeout, maxCallTime: timeout,
maxRetries: MAX_RETRIES, maxRetries: MAX_RETRIES,

Просмотреть файл

@ -59,7 +59,7 @@ describe('code transformation worker:', () => {
it('calls back with the result of the transform in the cache', done => { it('calls back with the result of the transform in the cache', done => {
const result = { const result = {
code: 'some.other(code)', code: 'some.other(code)',
map: {} map: {},
}; };
transformCode(transformer, 'filename', result.code, {}, (error, data) => { transformCode(transformer, 'filename', result.code, {}, (error, data) => {
@ -76,10 +76,10 @@ describe('code transformation worker:', () => {
const code = '{a:1,b:2}'; const code = '{a:1,b:2}';
const filePath = 'arbitrary/file.json'; const filePath = 'arbitrary/file.json';
transformCode(transformer, filePath, code, {}, (error, data) => { transformCode(transformer, filePath, code, {}, (error, data) => {
expect(error).toBeNull(); expect(error).toBeNull();
expect(data.result.code).toEqual(code); expect(data.result.code).toEqual(code);
done(); done();
}, },
); );
} }
); );
@ -115,7 +115,7 @@ describe('code transformation worker:', () => {
it('passes the transformed code the `extractDependencies`', done => { it('passes the transformed code the `extractDependencies`', done => {
const code = 'arbitrary(code)'; const code = 'arbitrary(code)';
transformCode(transformer, 'filename', code, {}, (error) => { transformCode(transformer, 'filename', code, {}, error => {
expect(error).toBeNull(); expect(error).toBeNull();
expect(extractDependencies).toBeCalledWith(code); expect(extractDependencies).toBeCalledWith(code);
done(); done();
@ -143,25 +143,25 @@ describe('code transformation worker:', () => {
it('does not extract requires if files are marked as "extern"', done => { it('does not extract requires if files are marked as "extern"', done => {
const opts = {extern: true}; const opts = {extern: true};
transformCode(transformer, 'filename', 'code', opts, (error, data) => { transformCode(transformer, 'filename', 'code', opts, (error, data) => {
expect(error).toBeNull(); expect(error).toBeNull();
const {dependencies, dependencyOffsets} = data.result; const {dependencies, dependencyOffsets} = data.result;
expect(extractDependencies).not.toBeCalled(); expect(extractDependencies).not.toBeCalled();
expect(dependencies).toEqual([]); expect(dependencies).toEqual([]);
expect(dependencyOffsets).toEqual([]); expect(dependencyOffsets).toEqual([]);
done(); done();
}); });
}); });
it('does not extract requires of JSON files', done => { it('does not extract requires of JSON files', done => {
const jsonStr = '{"arbitrary":"json"}'; const jsonStr = '{"arbitrary":"json"}';
transformCode(transformer, 'arbitrary.json', jsonStr, {}, (error, data) => { transformCode(transformer, 'arbitrary.json', jsonStr, {}, (error, data) => {
expect(error).toBeNull(); expect(error).toBeNull();
const {dependencies, dependencyOffsets} = data.result; const {dependencies, dependencyOffsets} = data.result;
expect(extractDependencies).not.toBeCalled(); expect(extractDependencies).not.toBeCalled();
expect(dependencies).toEqual([]); expect(dependencies).toEqual([]);
expect(dependencyOffsets).toEqual([]); expect(dependencyOffsets).toEqual([]);
done(); done();
} }
); );
}); });
}); });
@ -182,7 +182,7 @@ describe('code transformation worker:', () => {
options = {minify: true, transform: {generateSourceMaps: true}}; options = {minify: true, transform: {generateSourceMaps: true}};
dependencyData = { dependencyData = {
dependencies: ['a', 'b', 'c'], dependencies: ['a', 'b', 'c'],
dependencyOffsets: [100, 120, 140] dependencyOffsets: [100, 120, 140],
}; };
extractDependencies.mockImplementation( extractDependencies.mockImplementation(

Просмотреть файл

@ -57,7 +57,7 @@ const plugin = {
path.replaceWith(value ? node.right : left); path.replaceWith(value ? node.right : left);
} }
} }
} },
}, },
UnaryExpression: { UnaryExpression: {
exit(path) { exit(path) {
@ -65,7 +65,7 @@ const plugin = {
if (node.operator === '!' && t.isLiteral(node.argument)) { if (node.operator === '!' && t.isLiteral(node.argument)) {
path.replaceWith(t.valueToNode(!node.argument.value)); path.replaceWith(t.valueToNode(!node.argument.value));
} }
} },
}, },
}, },
}; };

Просмотреть файл

@ -38,7 +38,7 @@ function extractDependencies(code: string) {
} }
dependencyOffsets.push(arg.start); dependencyOffsets.push(arg.start);
dependencies.add(arg.value); dependencies.add(arg.value);
} },
}); });
return {dependencyOffsets, dependencies: Array.from(dependencies)}; return {dependencyOffsets, dependencies: Array.from(dependencies)};

Просмотреть файл

@ -32,7 +32,7 @@ const dev = {name: '__DEV__'};
const importMap = new Map([['ReactNative', 'react-native']]); const importMap = new Map([['ReactNative', 'react-native']]);
const isGlobal = (binding) => !binding; const isGlobal = binding => !binding;
const isToplevelBinding = (binding, isWrappedModule) => const isToplevelBinding = (binding, isWrappedModule) =>
isGlobal(binding) || isGlobal(binding) ||
@ -141,7 +141,7 @@ const inlinePlugin = {
path.replaceWith(replacement); path.replaceWith(replacement);
} }
} },
}, },
}; };

Просмотреть файл

@ -125,7 +125,7 @@ function transformCode(
action_name: 'Transforming file', action_name: 'Transforming file',
action_phase: 'end', action_phase: 'end',
file_name: filename, file_name: filename,
duration_ms: duration_ms, duration_ms,
log_entry_label: 'Transforming file', log_entry_label: 'Transforming file',
}; };

Просмотреть файл

@ -36,7 +36,7 @@ describe('Graph:', () => {
}); });
it('calls back an error when called without any entry point', done => { it('calls back an error when called without any entry point', done => {
graph([], anyPlatform, {log: quiet}, (error) => { graph([], anyPlatform, {log: quiet}, error => {
expect(error).toEqual(any(Error)); expect(error).toEqual(any(Error));
done(); done();
}); });
@ -214,11 +214,11 @@ describe('Graph:', () => {
const ids = [ const ids = [
'a', 'a',
'b', 'b',
'c', 'd', 'c', 'd',
'e', 'e',
'f', 'g', 'f', 'g',
'h', 'h',
]; ];
ids.forEach(id => { ids.forEach(id => {
const path = idToPath(id); const path = idToPath(id);
@ -367,7 +367,7 @@ function createFile(id) {
function createModule(id, dependencies = []): Module { function createModule(id, dependencies = []): Module {
return { return {
file: createFile(id), file: createFile(id),
dependencies: dependencies.map(createDependency) dependencies: dependencies.map(createDependency),
}; };
} }

Просмотреть файл

@ -126,14 +126,14 @@ function getReplacements(pkg) {
const main = getMain(pkg); const main = getMain(pkg);
if (typeof rn !== 'object') { if (typeof rn !== 'object') {
rn = { [main]: rn }; rn = {[main]: rn};
} }
if (typeof browser !== 'object') { if (typeof browser !== 'object') {
browser = { [main]: browser }; browser = {[main]: browser};
} }
// merge with "browser" as default, // merge with "browser" as default,
// "react-native" as override // "react-native" as override
return { ...browser, ...rn }; return {...browser, ...rn};
} }

Просмотреть файл

@ -11,90 +11,90 @@
'use strict'; 'use strict';
import type { // eslint-disable-line sort-requires import type { // eslint-disable-line sort-requires
Extensions, Extensions,
Path, Path,
} from './node-haste.flow'; } from './node-haste.flow';
import type { import type {
ResolveFn, ResolveFn,
TransformedFile, TransformedFile,
} from '../types.flow'; } from '../types.flow';
const DependencyGraphHelpers = require('../../node-haste/DependencyGraph/DependencyGraphHelpers'); const DependencyGraphHelpers = require('../../node-haste/DependencyGraph/DependencyGraphHelpers');
const HasteFS = require('./HasteFS'); const HasteFS = require('./HasteFS');
const HasteMap = require('../../node-haste/DependencyGraph/HasteMap'); const HasteMap = require('../../node-haste/DependencyGraph/HasteMap');
const Module = require('./Module'); const Module = require('./Module');
const ModuleCache = require('./ModuleCache'); const ModuleCache = require('./ModuleCache');
const ResolutionRequest = require('../../node-haste/DependencyGraph/ResolutionRequest'); const ResolutionRequest = require('../../node-haste/DependencyGraph/ResolutionRequest');
const defaults = require('../../../defaults'); const defaults = require('../../../defaults');
type ResolveOptions = {| type ResolveOptions = {|
assetExts: Extensions, assetExts: Extensions,
extraNodeModules: {[id: string]: string}, extraNodeModules: {[id: string]: string},
transformedFiles: {[path: Path]: TransformedFile}, transformedFiles: {[path: Path]: TransformedFile},
|}; |};
const platforms = new Set(defaults.platforms); const platforms = new Set(defaults.platforms);
exports.createResolveFn = function(options: ResolveOptions): ResolveFn { exports.createResolveFn = function(options: ResolveOptions): ResolveFn {
const { const {
assetExts, assetExts,
extraNodeModules, extraNodeModules,
transformedFiles, transformedFiles,
} = options; } = options;
const files = Object.keys(transformedFiles); const files = Object.keys(transformedFiles);
const getTransformedFile = const getTransformedFile =
path => Promise.resolve( path => Promise.resolve(
transformedFiles[path] || Promise.reject(new Error(`"${path} does not exist`)) transformedFiles[path] || Promise.reject(new Error(`"${path} does not exist`))
); );
const helpers = new DependencyGraphHelpers({ const helpers = new DependencyGraphHelpers({
assetExts, assetExts,
providesModuleNodeModules: defaults.providesModuleNodeModules, providesModuleNodeModules: defaults.providesModuleNodeModules,
}); });
const hasteFS = new HasteFS(files); const hasteFS = new HasteFS(files);
const moduleCache = new ModuleCache( const moduleCache = new ModuleCache(
filePath => hasteFS.closest(filePath, 'package.json'), filePath => hasteFS.closest(filePath, 'package.json'),
getTransformedFile, getTransformedFile,
); );
const hasteMap = new HasteMap({ const hasteMap = new HasteMap({
extensions: ['js', 'json'], extensions: ['js', 'json'],
files, files,
helpers, helpers,
moduleCache, moduleCache,
platforms, platforms,
preferNativePlatform: true, preferNativePlatform: true,
}); });
const hasteMapBuilt = hasteMap.build(); const hasteMapBuilt = hasteMap.build();
const resolutionRequests = {}; const resolutionRequests = {};
return (id, source, platform, _, callback) => { return (id, source, platform, _, callback) => {
let resolutionRequest = resolutionRequests[platform]; let resolutionRequest = resolutionRequests[platform];
if (!resolutionRequest) { if (!resolutionRequest) {
resolutionRequest = resolutionRequests[platform] = new ResolutionRequest({ resolutionRequest = resolutionRequests[platform] = new ResolutionRequest({
dirExists: filePath => hasteFS.dirExists(filePath), dirExists: filePath => hasteFS.dirExists(filePath),
entryPath: '', entryPath: '',
extraNodeModules, extraNodeModules,
hasteFS, hasteFS,
hasteMap, hasteMap,
helpers, helpers,
moduleCache, moduleCache,
platform, platform,
platforms, platforms,
preferNativePlatform: true, preferNativePlatform: true,
}); });
} }
const from = new Module(source, moduleCache, getTransformedFile(source)); const from = new Module(source, moduleCache, getTransformedFile(source));
hasteMapBuilt hasteMapBuilt
.then(() => resolutionRequest.resolveDependency(from, id)) .then(() => resolutionRequest.resolveDependency(from, id))
.then( .then(
// nextTick to escape promise error handling // nextTick to escape promise error handling
module => process.nextTick(callback, null, module.path), module => process.nextTick(callback, null, module.path),
error => process.nextTick(callback, error), error => process.nextTick(callback, error),
); );
}; };
}; };

Просмотреть файл

@ -31,7 +31,7 @@ module.exports = (
if (file.map) { if (file.map) {
sections.push({ sections.push({
map: file.map, map: file.map,
offset: {column: 0, line} offset: {column: 0, line},
}); });
} }
line += countLines(moduleCode); line += countLines(moduleCode);

Просмотреть файл

@ -80,6 +80,6 @@ function virtualModule(code: string) {
code, code,
path: '', path: '',
type: 'script', type: 'script',
} },
}; };
} }

Просмотреть файл

@ -54,7 +54,7 @@ describe('optimizing JS modules', () => {
const result = optimizeModule(transformResult, optimizationOptions); const result = optimizeModule(transformResult, optimizationOptions);
optimized = result.transformed.default; optimized = result.transformed.default;
injectedVars = optimized.code.match(/function\(([^)]*)/)[1].split(','); injectedVars = optimized.code.match(/function\(([^)]*)/)[1].split(',');
[,requireName,,, dependencyMapName] = injectedVars; [, requireName,,, dependencyMapName] = injectedVars;
}); });
it('optimizes code', () => { it('optimizes code', () => {

Просмотреть файл

@ -224,7 +224,7 @@ function createTestData() {
if (path.node.callee.name === 'some') { if (path.node.callee.name === 'some') {
path.replaceWith(path.node.arguments[0]); path.replaceWith(path.node.arguments[0]);
} }
} },
}); });
return { return {
bodyAst: fileAst.program.body, bodyAst: fileAst.program.body,

Просмотреть файл

@ -101,8 +101,8 @@ describe('Resolver', function() {
.getDependencies(entry, {platform}, transformOptions); .getDependencies(entry, {platform}, transformOptions);
expect(DependencyGraph.prototype.getDependencies).toBeCalledWith({ expect(DependencyGraph.prototype.getDependencies).toBeCalledWith({
entryPath: entry, entryPath: entry,
platform: platform, platform,
transformOptions: transformOptions, transformOptions,
recursive: true, recursive: true,
}); });
}); });
@ -134,7 +134,7 @@ describe('Resolver', function() {
return depResolver return depResolver
.getDependencies( .getDependencies(
'/root/index.js', '/root/index.js',
{ dev: false }, {dev: false},
undefined, undefined,
undefined, undefined,
createGetModuleId() createGetModuleId()
@ -147,34 +147,34 @@ describe('Resolver', function() {
.createPolyfill .createPolyfill
.mock .mock
.calls .calls
.map((call) => call[0])) .map(call => call[0]))
.toEqual([ .toEqual([
{ id: 'polyfills/Object.es6.js', {id: 'polyfills/Object.es6.js',
file: 'polyfills/Object.es6.js', file: 'polyfills/Object.es6.js',
dependencies: [] dependencies: [],
}, },
{ id: 'polyfills/console.js', {id: 'polyfills/console.js',
file: 'polyfills/console.js', file: 'polyfills/console.js',
dependencies: [ dependencies: [
'polyfills/Object.es6.js' 'polyfills/Object.es6.js',
], ],
}, },
{ id: 'polyfills/error-guard.js', {id: 'polyfills/error-guard.js',
file: 'polyfills/error-guard.js', file: 'polyfills/error-guard.js',
dependencies: [ dependencies: [
'polyfills/Object.es6.js', 'polyfills/Object.es6.js',
'polyfills/console.js' 'polyfills/console.js',
], ],
}, },
{ id: 'polyfills/Number.es6.js', {id: 'polyfills/Number.es6.js',
file: 'polyfills/Number.es6.js', file: 'polyfills/Number.es6.js',
dependencies: [ dependencies: [
'polyfills/Object.es6.js', 'polyfills/Object.es6.js',
'polyfills/console.js', 'polyfills/console.js',
'polyfills/error-guard.js' 'polyfills/error-guard.js',
], ],
}, },
{ id: 'polyfills/String.prototype.es6.js', {id: 'polyfills/String.prototype.es6.js',
file: 'polyfills/String.prototype.es6.js', file: 'polyfills/String.prototype.es6.js',
dependencies: [ dependencies: [
'polyfills/Object.es6.js', 'polyfills/Object.es6.js',
@ -183,7 +183,7 @@ describe('Resolver', function() {
'polyfills/Number.es6.js', 'polyfills/Number.es6.js',
], ],
}, },
{ id: 'polyfills/Array.prototype.es6.js', {id: 'polyfills/Array.prototype.es6.js',
file: 'polyfills/Array.prototype.es6.js', file: 'polyfills/Array.prototype.es6.js',
dependencies: [ dependencies: [
'polyfills/Object.es6.js', 'polyfills/Object.es6.js',
@ -193,7 +193,7 @@ describe('Resolver', function() {
'polyfills/String.prototype.es6.js', 'polyfills/String.prototype.es6.js',
], ],
}, },
{ id: 'polyfills/Array.es6.js', {id: 'polyfills/Array.es6.js',
file: 'polyfills/Array.es6.js', file: 'polyfills/Array.es6.js',
dependencies: [ dependencies: [
'polyfills/Object.es6.js', 'polyfills/Object.es6.js',
@ -204,7 +204,7 @@ describe('Resolver', function() {
'polyfills/Array.prototype.es6.js', 'polyfills/Array.prototype.es6.js',
], ],
}, },
{ id: 'polyfills/Object.es7.js', {id: 'polyfills/Object.es7.js',
file: 'polyfills/Object.es7.js', file: 'polyfills/Object.es7.js',
dependencies: [ dependencies: [
'polyfills/Object.es6.js', 'polyfills/Object.es6.js',
@ -216,7 +216,7 @@ describe('Resolver', function() {
'polyfills/Array.es6.js', 'polyfills/Array.es6.js',
], ],
}, },
{ id: 'polyfills/babelHelpers.js', {id: 'polyfills/babelHelpers.js',
file: 'polyfills/babelHelpers.js', file: 'polyfills/babelHelpers.js',
dependencies: [ dependencies: [
'polyfills/Object.es6.js', 'polyfills/Object.es6.js',
@ -232,7 +232,7 @@ describe('Resolver', function() {
].map(({id, file, dependencies}) => ({ ].map(({id, file, dependencies}) => ({
id: pathJoin(__dirname, '..', id), id: pathJoin(__dirname, '..', id),
file: pathJoin(__dirname, '..', file), file: pathJoin(__dirname, '..', file),
dependencies: dependencies.map((d => pathJoin(__dirname, '..', d))), dependencies: dependencies.map(d => pathJoin(__dirname, '..', d)),
}))); })));
}); });
}); });
@ -257,7 +257,7 @@ describe('Resolver', function() {
return depResolver return depResolver
.getDependencies( .getDependencies(
'/root/index.js', '/root/index.js',
{ dev: true }, {dev: true},
undefined, undefined,
undefined, undefined,
createGetModuleId() createGetModuleId()
@ -290,14 +290,14 @@ describe('Resolver', function() {
return depResolver return depResolver
.getDependencies( .getDependencies(
'/root/index.js', '/root/index.js',
{ dev: false }, {dev: false},
undefined, undefined,
undefined, undefined,
createGetModuleId() createGetModuleId()
).then((result) => { ).then(result => {
expect(result.mainModuleId).toEqual('index'); expect(result.mainModuleId).toEqual('index');
expect(DependencyGraph.prototype.createPolyfill.mock.calls[result.dependencies.length - 2]).toEqual([ expect(DependencyGraph.prototype.createPolyfill.mock.calls[result.dependencies.length - 2]).toEqual([
{ file: 'some module', {file: 'some module',
id: 'some module', id: 'some module',
dependencies: [ dependencies: [
'polyfills/Object.es6.js', 'polyfills/Object.es6.js',
@ -309,7 +309,7 @@ describe('Resolver', function() {
'polyfills/Array.es6.js', 'polyfills/Array.es6.js',
'polyfills/Object.es7.js', 'polyfills/Object.es7.js',
'polyfills/babelHelpers.js', 'polyfills/babelHelpers.js',
].map(d => pathJoin(__dirname, '..', d)) ].map(d => pathJoin(__dirname, '..', d)),
}, },
]); ]);
}); });

Просмотреть файл

@ -64,7 +64,7 @@ class Resolver {
forceNodeFilesystemAPI: false, forceNodeFilesystemAPI: false,
getTransformCacheKey: opts.getTransformCacheKey, getTransformCacheKey: opts.getTransformCacheKey,
globalTransformCache: opts.globalTransformCache, globalTransformCache: opts.globalTransformCache,
ignoreFilePath: function(filepath) { ignoreFilePath(filepath) {
return filepath.indexOf('__tests__') !== -1 || return filepath.indexOf('__tests__') !== -1 ||
(opts.blacklistRE != null && opts.blacklistRE.test(filepath)); (opts.blacklistRE != null && opts.blacklistRE.test(filepath));
}, },
@ -253,7 +253,7 @@ function defineModuleCode(moduleName, code, verboseName = '', dev = true) {
return [ return [
`__d(/* ${verboseName} */`, `__d(/* ${verboseName} */`,
'function(global, require, module, exports) {', // module factory 'function(global, require, module, exports) {', // module factory
code, code,
'\n}, ', '\n}, ',
`${JSON.stringify(moduleName)}`, // module id, null = id map. used in ModuleGraph `${JSON.stringify(moduleName)}`, // module id, null = id map. used in ModuleGraph
dev ? `, null, ${JSON.stringify(verboseName)}` : '', dev ? `, null, ${JSON.stringify(verboseName)}` : '',

Просмотреть файл

@ -31,19 +31,19 @@ let _globalHandler = function onError(e) {
* set) globally before requiring anything. * set) globally before requiring anything.
*/ */
const ErrorUtils = { const ErrorUtils = {
setGlobalHandler: function(fun) { setGlobalHandler(fun) {
_globalHandler = fun; _globalHandler = fun;
}, },
getGlobalHandler: function() { getGlobalHandler() {
return _globalHandler; return _globalHandler;
}, },
reportError: function(error) { reportError(error) {
_globalHandler && _globalHandler(error); _globalHandler && _globalHandler(error);
}, },
reportFatalError: function(error) { reportFatalError(error) {
_globalHandler && _globalHandler(error, true); _globalHandler && _globalHandler(error, true);
}, },
applyWithGuard: function(fun, context, args) { applyWithGuard(fun, context, args) {
try { try {
_inGuard++; _inGuard++;
return fun.apply(context, args); return fun.apply(context, args);
@ -53,17 +53,17 @@ const ErrorUtils = {
_inGuard--; _inGuard--;
} }
}, },
applyWithGuardIfNeeded: function(fun, context, args) { applyWithGuardIfNeeded(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() {
return _inGuard; return _inGuard;
}, },
guard: function(fun, name, context) { guard(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;
@ -82,7 +82,7 @@ const ErrorUtils = {
} }
return guarded; return guarded;
} },
}; };
global.ErrorUtils = ErrorUtils; global.ErrorUtils = ErrorUtils;

Просмотреть файл

@ -12,28 +12,28 @@
'use strict'; 'use strict';
declare var __DEV__: boolean; declare var __DEV__: boolean;
type DependencyMap = Array<ModuleID>; type DependencyMap = Array<ModuleID>;
type Exports = any; type Exports = any;
type FactoryFn = ( type FactoryFn = (
global: Object, global: Object,
require: RequireFn, require: RequireFn,
moduleObject: {exports: {}}, moduleObject: {exports: {}},
exports: {}, exports: {},
dependencyMap: ?DependencyMap, dependencyMap: ?DependencyMap,
) => void; ) => void;
type HotModuleReloadingAcceptFn = Function; type HotModuleReloadingAcceptFn = Function;
type HotModuleReloadingData = {| type HotModuleReloadingData = {|
acceptCallback: ?HotModuleReloadingAcceptFn, acceptCallback: ?HotModuleReloadingAcceptFn,
accept: (callback: HotModuleReloadingAcceptFn) => void, accept: (callback: HotModuleReloadingAcceptFn) => void,
|}; |};
type Module = { type Module = {
exports: Exports, exports: Exports,
hot?: HotModuleReloadingData, hot?: HotModuleReloadingData,
}; };
type ModuleID = number; type ModuleID = number;
type ModuleDefinition = {| type ModuleDefinition = {|
dependencyMap: ?DependencyMap, dependencyMap: ?DependencyMap,
exports: Exports, exports: Exports,
factory: FactoryFn, factory: FactoryFn,
@ -42,246 +42,246 @@ type ModuleDefinition = {|
isInitialized: boolean, isInitialized: boolean,
verboseName?: string, verboseName?: string,
|}; |};
type ModuleMap = type ModuleMap =
{[key: ModuleID]: (ModuleDefinition)}; {[key: ModuleID]: (ModuleDefinition)};
type RequireFn = (id: ModuleID | VerboseModuleNameForDev) => Exports; type RequireFn = (id: ModuleID | VerboseModuleNameForDev) => Exports;
type VerboseModuleNameForDev = string; type VerboseModuleNameForDev = string;
global.require = require; global.require = require;
global.__d = define; global.__d = define;
const modules: ModuleMap = Object.create(null); const modules: ModuleMap = Object.create(null);
if (__DEV__) { if (__DEV__) {
var verboseNamesToModuleIds: {[key: string]: number} = Object.create(null); var verboseNamesToModuleIds: {[key: string]: number} = Object.create(null);
} }
function define( function define(
factory: FactoryFn, factory: FactoryFn,
moduleId: number, moduleId: number,
dependencyMap?: DependencyMap, dependencyMap?: DependencyMap,
) { ) {
if (moduleId in modules) { if (moduleId in modules) {
// prevent repeated calls to `global.nativeRequire` to overwrite modules // prevent repeated calls to `global.nativeRequire` to overwrite modules
// that are already loaded // that are already loaded
return; return;
} }
modules[moduleId] = { modules[moduleId] = {
dependencyMap, dependencyMap,
exports: undefined, exports: undefined,
factory, factory,
hasError: false, hasError: false,
isInitialized: false, isInitialized: false,
}; };
if (__DEV__) { if (__DEV__) {
// HMR // HMR
modules[moduleId].hot = createHotReloadingObject(); modules[moduleId].hot = createHotReloadingObject();
// DEBUGGABLE MODULES NAMES // DEBUGGABLE MODULES NAMES
// we take `verboseName` from `arguments` to avoid an unused named parameter // we take `verboseName` from `arguments` to avoid an unused named parameter
// in `define` in production. // in `define` in production.
const verboseName: string | void = arguments[3]; const verboseName: string | void = arguments[3];
if (verboseName) { if (verboseName) {
modules[moduleId].verboseName = verboseName; modules[moduleId].verboseName = verboseName;
verboseNamesToModuleIds[verboseName] = moduleId; verboseNamesToModuleIds[verboseName] = moduleId;
} }
} }
} }
function require(moduleId: ModuleID | VerboseModuleNameForDev) { function require(moduleId: ModuleID | VerboseModuleNameForDev) {
if (__DEV__ && typeof moduleId === 'string') { if (__DEV__ && typeof moduleId === 'string') {
const verboseName = moduleId; const verboseName = moduleId;
moduleId = verboseNamesToModuleIds[moduleId]; moduleId = verboseNamesToModuleIds[moduleId];
if (moduleId == null) { if (moduleId == null) {
throw new Error(`Unknown named module: '${verboseName}'`); throw new Error(`Unknown named module: '${verboseName}'`);
} else { } else {
console.warn( console.warn(
`Requiring module '${verboseName}' by name is only supported for ` + `Requiring module '${verboseName}' by name is only supported for ` +
'debugging purposes and will BREAK IN PRODUCTION!' 'debugging purposes and will BREAK IN PRODUCTION!'
); );
} }
} }
//$FlowFixMe: at this point we know that moduleId is a number //$FlowFixMe: at this point we know that moduleId is a number
const moduleIdReallyIsNumber: number = moduleId; const moduleIdReallyIsNumber: number = moduleId;
const module = modules[moduleIdReallyIsNumber]; const module = modules[moduleIdReallyIsNumber];
return module && module.isInitialized return module && module.isInitialized
? module.exports ? module.exports
: guardedLoadModule(moduleIdReallyIsNumber, module); : guardedLoadModule(moduleIdReallyIsNumber, module);
} }
let inGuard = false; let inGuard = false;
function guardedLoadModule(moduleId: ModuleID , module) { function guardedLoadModule(moduleId: ModuleID, module) {
if (!inGuard && global.ErrorUtils) { if (!inGuard && global.ErrorUtils) {
inGuard = true; inGuard = true;
let returnValue; let returnValue;
try { try {
returnValue = loadModuleImplementation(moduleId, module); returnValue = loadModuleImplementation(moduleId, module);
} catch (e) { } catch (e) {
global.ErrorUtils.reportFatalError(e); global.ErrorUtils.reportFatalError(e);
} }
inGuard = false; inGuard = false;
return returnValue; return returnValue;
} else { } else {
return loadModuleImplementation(moduleId, module); return loadModuleImplementation(moduleId, module);
} }
} }
function loadModuleImplementation(moduleId, module) { function loadModuleImplementation(moduleId, module) {
const nativeRequire = global.nativeRequire; const nativeRequire = global.nativeRequire;
if (!module && nativeRequire) { if (!module && nativeRequire) {
nativeRequire(moduleId); nativeRequire(moduleId);
module = modules[moduleId]; module = modules[moduleId];
} }
if (!module) { if (!module) {
throw unknownModuleError(moduleId); throw unknownModuleError(moduleId);
} }
if (module.hasError) { if (module.hasError) {
throw moduleThrewError(moduleId); throw moduleThrewError(moduleId);
} }
// `require` calls int the require polyfill itself are not analyzed and // `require` calls int the require polyfill itself are not analyzed and
// replaced so that they use numeric module IDs. // replaced so that they use numeric module IDs.
// The systrace module will expose itself on the require function so that // The systrace module will expose itself on the require function so that
// it can be used here. // it can be used here.
// TODO(davidaurelio) Scan polyfills for dependencies, too (t9759686) // TODO(davidaurelio) Scan polyfills for dependencies, too (t9759686)
if (__DEV__) { if (__DEV__) {
var {Systrace} = require; var {Systrace} = require;
} }
// We must optimistically mark module as initialized before running the // We must optimistically mark module as initialized before running the
// factory to keep any require cycles inside the factory from causing an // factory to keep any require cycles inside the factory from causing an
// infinite require loop. // infinite require loop.
module.isInitialized = true; module.isInitialized = true;
const exports = module.exports = {}; const exports = module.exports = {};
const {factory, dependencyMap} = module; const {factory, dependencyMap} = module;
try { try {
if (__DEV__) { if (__DEV__) {
// $FlowFixMe: we know that __DEV__ is const and `Systrace` exists // $FlowFixMe: we know that __DEV__ is const and `Systrace` exists
Systrace.beginEvent('JS_require_' + (module.verboseName || moduleId)); Systrace.beginEvent('JS_require_' + (module.verboseName || moduleId));
} }
const moduleObject: Module = {exports}; const moduleObject: Module = {exports};
if (__DEV__ && module.hot) { if (__DEV__ && module.hot) {
moduleObject.hot = module.hot; moduleObject.hot = module.hot;
} }
// keep args in sync with with defineModuleCode in // keep args in sync with with defineModuleCode in
// packager/src//Resolver/index.js // packager/src//Resolver/index.js
// and packager/src//ModuleGraph/worker.js // and packager/src//ModuleGraph/worker.js
factory(global, require, moduleObject, exports, dependencyMap); factory(global, require, moduleObject, exports, dependencyMap);
// avoid removing factory in DEV mode as it breaks HMR // avoid removing factory in DEV mode as it breaks HMR
if (!__DEV__) { if (!__DEV__) {
// $FlowFixMe: This is only sound because we never access `factory` again // $FlowFixMe: This is only sound because we never access `factory` again
module.factory = undefined; module.factory = undefined;
} }
if (__DEV__) { if (__DEV__) {
// $FlowFixMe: we know that __DEV__ is const and `Systrace` exists // $FlowFixMe: we know that __DEV__ is const and `Systrace` exists
Systrace.endEvent(); Systrace.endEvent();
} }
return (module.exports = moduleObject.exports); return (module.exports = moduleObject.exports);
} catch (e) { } catch (e) {
module.hasError = true; module.hasError = true;
module.isInitialized = false; module.isInitialized = false;
module.exports = undefined; module.exports = undefined;
throw e; throw e;
} }
} }
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 or running "npm install".'; 'If you are sure the module is there, try restarting the packager or running "npm install".';
} }
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.');
} }
if (__DEV__) { if (__DEV__) {
require.Systrace = { beginEvent: () => {}, endEvent: () => {} }; require.Systrace = {beginEvent: () => {}, endEvent: () => {}};
// HOT MODULE RELOADING // HOT MODULE RELOADING
var createHotReloadingObject = function() { var createHotReloadingObject = function() {
const hot: HotModuleReloadingData = { const hot: HotModuleReloadingData = {
acceptCallback: null, acceptCallback: null,
accept: callback => { hot.acceptCallback = callback; }, accept: callback => { hot.acceptCallback = callback; },
}; };
return hot; return hot;
}; };
const acceptAll = function( const acceptAll = function(
dependentModules, dependentModules,
inverseDependencies, inverseDependencies,
) { ) {
if (!dependentModules || dependentModules.length === 0) { if (!dependentModules || dependentModules.length === 0) {
return true; return true;
} }
const notAccepted = dependentModules.filter( const notAccepted = dependentModules.filter(
module => !accept(module, /*factory*/ undefined, inverseDependencies)); module => !accept(module, /*factory*/ undefined, inverseDependencies));
const parents = []; const parents = [];
for (let i = 0; i < notAccepted.length; i++) { for (let i = 0; i < notAccepted.length; i++) {
// if the module has no parents then the change cannot be hot loaded // if the module has no parents then the change cannot be hot loaded
if (inverseDependencies[notAccepted[i]].length === 0) { if (inverseDependencies[notAccepted[i]].length === 0) {
return false; return false;
} }
parents.push(...inverseDependencies[notAccepted[i]]); parents.push(...inverseDependencies[notAccepted[i]]);
} }
return acceptAll(parents, inverseDependencies); return acceptAll(parents, inverseDependencies);
}; };
const accept = function( const accept = function(
id: ModuleID, id: ModuleID,
factory?: FactoryFn, factory?: FactoryFn,
inverseDependencies: {[key: ModuleID]: Array<ModuleID>}, inverseDependencies: {[key: ModuleID]: Array<ModuleID>},
) { ) {
const mod = modules[id]; const mod = modules[id];
if (!mod && factory) { // new modules need a factory if (!mod && factory) { // new modules need a factory
define(factory, id); define(factory, id);
return true; // new modules don't need to be accepted return true; // new modules don't need to be accepted
} }
const {hot} = mod; const {hot} = mod;
if (!hot) { if (!hot) {
console.warn( console.warn(
'Cannot accept module because Hot Module Replacement ' + 'Cannot accept module because Hot Module Replacement ' +
'API was not installed.' 'API was not installed.'
); );
return false; return false;
} }
// replace and initialize factory // replace and initialize factory
if (factory) { if (factory) {
mod.factory = factory; mod.factory = factory;
} }
mod.hasError = false; mod.hasError = false;
mod.isInitialized = false; mod.isInitialized = false;
require(id); require(id);
if (hot.acceptCallback) { if (hot.acceptCallback) {
hot.acceptCallback(); hot.acceptCallback();
return true; return true;
} else { } else {
// need to have inverseDependencies to bubble up accept // need to have inverseDependencies to bubble up accept
if (!inverseDependencies) { if (!inverseDependencies) {
throw new Error('Undefined `inverseDependencies`'); throw new Error('Undefined `inverseDependencies`');
} }
// accept parent modules recursively up until all siblings are accepted // accept parent modules recursively up until all siblings are accepted
return acceptAll(inverseDependencies[id], inverseDependencies); return acceptAll(inverseDependencies[id], inverseDependencies);
} }
}; };
global.__accept = accept; global.__accept = accept;
} }

Просмотреть файл

@ -72,7 +72,7 @@ class MultipartResponse {
static serializeHeaders(headers) { static serializeHeaders(headers) {
return Object.keys(headers) return Object.keys(headers)
.map((key) => `${key}: ${headers[key]}`) .map(key => `${key}: ${headers[key]}`)
.join(CRLF); .join(CRLF);
} }
} }

Просмотреть файл

@ -133,8 +133,8 @@ function mockNodeResponse() {
headers = {...headers, ...hdrs}; headers = {...headers, ...hdrs};
}), }),
setHeader: jest.fn((key, val) => { headers[key] = val; }), setHeader: jest.fn((key, val) => { headers[key] = val; }),
write: jest.fn((data) => { body += data; }), write: jest.fn(data => { body += data; }),
end: jest.fn((data) => { body += (data || ''); }), end: jest.fn(data => { body += (data || ''); }),
// For testing only // For testing only
toString() { toString() {
@ -144,7 +144,6 @@ function mockNodeResponse() {
'', '',
body, body,
].join('\r\n'); ].join('\r\n');
} },
}; };
} }

Просмотреть файл

@ -11,7 +11,7 @@
jest.disableAutomock(); jest.disableAutomock();
jest.mock('worker-farm', () => () => () => {}) jest.mock('worker-farm', () => () => () => {})
.mock('timers', () => ({ setImmediate: (fn) => setTimeout(fn, 0) })) .mock('timers', () => ({setImmediate: fn => setTimeout(fn, 0)}))
.mock('uglify-js') .mock('uglify-js')
.mock('crypto') .mock('crypto')
.mock( .mock(
@ -39,16 +39,16 @@ describe('processRequest', () => {
let server; let server;
const options = { const options = {
projectRoots: ['root'], projectRoots: ['root'],
blacklistRE: null, blacklistRE: null,
cacheVersion: null, cacheVersion: null,
polyfillModuleNames: null, polyfillModuleNames: null,
reporter: require('../../lib/reporting').nullReporter, reporter: require('../../lib/reporting').nullReporter,
}; };
const makeRequest = (reqHandler, requrl, reqOptions) => new Promise(resolve => const makeRequest = (reqHandler, requrl, reqOptions) => new Promise(resolve =>
reqHandler( reqHandler(
{ url: requrl, headers:{}, ...reqOptions }, {url: requrl, headers:{}, ...reqOptions},
{ {
statusCode: 200, statusCode: 200,
headers: {}, headers: {},
@ -60,7 +60,7 @@ describe('processRequest', () => {
resolve(this); resolve(this);
}, },
}, },
{ next: () => {} }, {next: () => {}},
) )
); );
@ -122,7 +122,7 @@ describe('processRequest', () => {
return makeRequest( return makeRequest(
requestHandler, requestHandler,
'mybundle.bundle?runModule=true', 'mybundle.bundle?runModule=true',
{ headers : { 'if-none-match' : 'this is an etag' } } {headers : {'if-none-match' : 'this is an etag'}}
).then(response => { ).then(response => {
expect(response.statusCode).toEqual(304); expect(response.statusCode).toEqual(304);
}); });
@ -328,7 +328,7 @@ describe('processRequest', () => {
expect(bundleFunc.mock.calls.length).toBe(2); expect(bundleFunc.mock.calls.length).toBe(2);
}); });
jest.runAllTicks(); jest.runAllTicks();
}); });
}); });
describe('/onchange endpoint', () => { describe('/onchange endpoint', () => {
@ -342,7 +342,7 @@ describe('processRequest', () => {
req.url = '/onchange'; req.url = '/onchange';
res = { res = {
writeHead: jest.fn(), writeHead: jest.fn(),
end: jest.fn() end: jest.fn(),
}; };
}); });
@ -422,7 +422,7 @@ describe('processRequest', () => {
describe('buildbundle(options)', () => { describe('buildbundle(options)', () => {
it('Calls the bundler with the correct args', () => { it('Calls the bundler with the correct args', () => {
return server.buildBundle({ return server.buildBundle({
entryFile: 'foo file' entryFile: 'foo file',
}).then(() => }).then(() =>
expect(Bundler.prototype.bundle).toBeCalledWith({ expect(Bundler.prototype.bundle).toBeCalledWith({
entryFile: 'foo file', entryFile: 'foo file',
@ -510,7 +510,7 @@ describe('processRequest', () => {
return makeRequest( return makeRequest(
requestHandler, requestHandler,
'/symbolicate', '/symbolicate',
{ rawBody: body } {rawBody: body}
).then(response => { ).then(response => {
expect(response.statusCode).toEqual(500); expect(response.statusCode).toEqual(500);
expect(JSON.parse(response.body)).toEqual({ expect(JSON.parse(response.body)).toEqual({

Просмотреть файл

@ -44,7 +44,7 @@ const {
function debounceAndBatch(fn, delay) { function debounceAndBatch(fn, delay) {
let timeout, args = []; let timeout, args = [];
return (value) => { return value => {
args.push(value); args.push(value);
clearTimeout(timeout); clearTimeout(timeout);
timeout = setTimeout(() => { timeout = setTimeout(() => {
@ -434,7 +434,7 @@ class Server {
watchers.forEach(function(w) { watchers.forEach(function(w) {
w.res.writeHead(205, headers); w.res.writeHead(205, headers);
w.res.end(JSON.stringify({ changed: true })); w.res.end(JSON.stringify({changed: true}));
}); });
this._changeWatchers = []; this._changeWatchers = [];
@ -474,8 +474,8 @@ class Server {
const watchers = this._changeWatchers; const watchers = this._changeWatchers;
watchers.push({ watchers.push({
req: req, req,
res: res, res,
}); });
req.on('close', () => { req.on('close', () => {
@ -548,7 +548,7 @@ class Server {
optionsHash(options: {}) { optionsHash(options: {}) {
// onProgress is a function, can't be serialized // onProgress is a function, can't be serialized
return JSON.stringify(Object.assign({}, options, { onProgress: null })); return JSON.stringify(Object.assign({}, options, {onProgress: null}));
} }
/** /**
@ -670,11 +670,11 @@ class Server {
debug('Successfully updated existing bundle'); debug('Successfully updated existing bundle');
return bundle; return bundle;
});
}).catch(e => {
debug('Failed to update existing bundle, rebuilding...', e.stack || e.message);
return bundleFromScratch();
}); });
}).catch(e => {
debug('Failed to update existing bundle, rebuilding...', e.stack || e.message);
return bundleFromScratch();
});
return this._reportBundlePromise(options, bundlePromise); return this._reportBundlePromise(options, bundlePromise);
} else { } else {
debug('Using cached bundle'); debug('Using cached bundle');
@ -834,7 +834,7 @@ class Server {
}).then( }).then(
stack => { stack => {
debug('Symbolication done'); debug('Symbolication done');
res.end(JSON.stringify({stack: stack})); res.end(JSON.stringify({stack}));
process.nextTick(() => { process.nextTick(() => {
log(createActionEndEntry(symbolicatingLogEntry)); log(createActionEndEntry(symbolicatingLogEntry));
}); });
@ -941,7 +941,7 @@ class Server {
query: urlObj.query, query: urlObj.query,
search: urlObj.search, search: urlObj.search,
}), }),
entryFile: entryFile, entryFile,
dev, dev,
minify, minify,
hot: this._getBoolOptionFromQuery(urlObj.query, 'hot', false), hot: this._getBoolOptionFromQuery(urlObj.query, 'hot', false),
@ -951,7 +951,7 @@ class Server {
'inlineSourceMap', 'inlineSourceMap',
false false
), ),
platform: platform, platform,
entryModuleOnly: this._getBoolOptionFromQuery( entryModuleOnly: this._getBoolOptionFromQuery(
urlObj.query, urlObj.query,
'entryModuleOnly', 'entryModuleOnly',

Просмотреть файл

@ -53,7 +53,7 @@ function startupChild(socket) {
child.removeAllListeners(); child.removeAllListeners();
resolve(child); resolve(child);
}); });
child.send(socket); child.send(socket);
}); });
} }

Просмотреть файл

@ -43,23 +43,23 @@ function symbolicateStack(data) {
} }
function mapFrame(frame, consumers) { function mapFrame(frame, consumers) {
const sourceUrl = frame.file; const sourceUrl = frame.file;
const consumer = consumers.get(sourceUrl); const consumer = consumers.get(sourceUrl);
if (consumer == null) { if (consumer == null) {
return frame; return frame;
} }
const original = consumer.originalPositionFor({ const original = consumer.originalPositionFor({
line: frame.lineNumber, line: frame.lineNumber,
column: frame.column, column: frame.column,
}); });
if (!original) { if (!original) {
return frame; return frame;
} }
return Object.assign({}, frame, { return Object.assign({}, frame, {
file: original.source, file: original.source,
lineNumber: original.line, lineNumber: original.line,
column: original.column, column: original.column,
}); });
} }
function makeErrorMessage(error) { function makeErrorMessage(error) {

Просмотреть файл

@ -72,7 +72,7 @@ class TerminalReporter {
constructor() { constructor() {
this._dependencyGraphHasLoaded = false; this._dependencyGraphHasLoaded = false;
this._activeBundles = new Map(); this._activeBundles = new Map();
this._scheduleUpdateBundleProgress = throttle((data) => { this._scheduleUpdateBundleProgress = throttle(data => {
this.update({...data, type: 'bundle_transform_progressed_throttled'}); this.update({...data, type: 'bundle_transform_progressed_throttled'});
}, 200); }, 200);
} }

Просмотреть файл

@ -42,9 +42,9 @@ export type GetTransformCacheKey = (sourceCode: string, filename: string, option
* will be, for example, installed in a different `node_modules/` folder for * will be, for example, installed in a different `node_modules/` folder for
* different projects. * different projects.
*/ */
const getCacheDirPath = (function () { const getCacheDirPath = (function() {
let dirPath; let dirPath;
return function () { return function() {
if (dirPath == null) { if (dirPath == null) {
dirPath = path.join( dirPath = path.join(
require('os').tmpdir(), require('os').tmpdir(),
@ -351,5 +351,5 @@ module.exports = {
const msg = result ? 'Cache hit: ' : 'Cache miss: '; const msg = result ? 'Cache hit: ' : 'Cache miss: ';
debugRead(msg + props.filePath); debugRead(msg + props.filePath);
return result; return result;
} },
}; };

Просмотреть файл

@ -22,7 +22,7 @@ const mock = {
}, },
}; };
const transformCacheKeyOf = (props) => const transformCacheKeyOf = props =>
props.filePath + '-' + imurmurhash(props.sourceCode) props.filePath + '-' + imurmurhash(props.sourceCode)
.hash(props.getTransformCacheKey(props.sourceCode, props.filePath, props.transformOptions)) .hash(props.getTransformCacheKey(props.sourceCode, props.filePath, props.transformOptions))
.hash(jsonStableStringify(props.transformOptions || {})) .hash(jsonStableStringify(props.transformOptions || {}))

Просмотреть файл

@ -11,7 +11,7 @@
module.exports = function(declared) { module.exports = function(declared) {
return function(opts) { return function(opts) {
for (var p in declared) { for (var p in declared) {
if (opts[p] == null && declared[p].default != null){ if (opts[p] == null && declared[p].default != null) {
opts[p] = declared[p].default; opts[p] = declared[p].default;
} }
} }

Просмотреть файл

@ -29,7 +29,7 @@ describe('BatchProcessor', () => {
const batches = []; const batches = [];
let concurrency = 0; let concurrency = 0;
let maxConcurrency = 0; let maxConcurrency = 0;
const bp = new BatchProcessor(options, (items) => new Promise(resolve => { const bp = new BatchProcessor(options, items => new Promise(resolve => {
++concurrency; ++concurrency;
expect(concurrency).toBeLessThanOrEqual(options.concurrency); expect(concurrency).toBeLessThanOrEqual(options.concurrency);
maxConcurrency = Math.max(maxConcurrency, concurrency); maxConcurrency = Math.max(maxConcurrency, concurrency);
@ -55,7 +55,7 @@ describe('BatchProcessor', () => {
it('report errors', async () => { it('report errors', async () => {
const error = new Error('oh noes'); const error = new Error('oh noes');
const bp = new BatchProcessor(options, (items) => new Promise((_, reject) => { const bp = new BatchProcessor(options, items => new Promise((_, reject) => {
setTimeout(reject.bind(null, error), 0); setTimeout(reject.bind(null, error), 0);
})); }));
let receivedError; let receivedError;

Просмотреть файл

@ -30,7 +30,7 @@ jest.mock('fs', () => ({
readdirSync(dirPath) { readdirSync(dirPath) {
// Not required for it to work. // Not required for it to work.
return []; return [];
} },
})); }));
jest.mock('write-file-atomic', () => ({ jest.mock('write-file-atomic', () => ({

Просмотреть файл

@ -22,13 +22,13 @@ describe('declareOpts', function() {
age: { age: {
type: 'number', type: 'number',
default: 21, default: 21,
} },
}); });
var opts = validate({ name: 'fooer' }); var opts = validate({name: 'fooer'});
expect(opts).toEqual({ expect(opts).toEqual({
name: 'fooer', name: 'fooer',
age: 21 age: 21,
}); });
}); });
@ -41,12 +41,12 @@ describe('declareOpts', function() {
stuff: { stuff: {
type: 'object', type: 'object',
required: true, required: true,
} },
}); });
var opts = validate({ things: [1, 2, 3], stuff: {hai: 1} }); var opts = validate({things: [1, 2, 3], stuff: {hai: 1}});
expect(opts).toEqual({ expect(opts).toEqual({
things: [1,2,3], things: [1, 2, 3],
stuff: {hai: 1}, stuff: {hai: 1},
}); });
}); });
@ -56,7 +56,7 @@ describe('declareOpts', function() {
foo: { foo: {
required: true, required: true,
type: 'number', type: 'number',
} },
}); });
expect(function() { expect(function() {
@ -68,8 +68,8 @@ describe('declareOpts', function() {
var validate = declareOpts({ var validate = declareOpts({
foo: { foo: {
required: true, required: true,
type: 'number' type: 'number',
} },
}); });
expect(function() { expect(function() {
@ -82,7 +82,7 @@ describe('declareOpts', function() {
foo: { foo: {
required: true, required: true,
type: 'number', type: 'number',
} },
}); });
expect(function() { expect(function() {

Просмотреть файл

@ -13,7 +13,7 @@
const path = require('path'); const path = require('path');
import type { MixedSourceMap } from './SourceMap'; import type {MixedSourceMap} from './SourceMap';
function relativizeSourceMapInternal(sourceMap: any, sourcesRoot: string) { function relativizeSourceMapInternal(sourceMap: any, sourcesRoot: string) {
if (sourceMap.sections) { if (sourceMap.sections) {

Просмотреть файл

@ -26,7 +26,7 @@ class AssetModule extends Module {
constructor(args: ConstructorArgs & {dependencies: Array<string>}, platforms: Set<string>) { constructor(args: ConstructorArgs & {dependencies: Array<string>}, platforms: Set<string>) {
super(args); super(args);
const { resolution, name, type } = getAssetDataFromName(this.path, platforms); const {resolution, name, type} = getAssetDataFromName(this.path, platforms);
this.resolution = resolution; this.resolution = resolution;
this._name = name; this._name = name;
this._type = type; this._type = type;

Просмотреть файл

@ -268,7 +268,7 @@ describe('Cache', () => {
}); });
describe('writing cache to disk', () => { describe('writing cache to disk', () => {
it('should write cache to disk', (done) => { it('should write cache to disk', done => {
var index = 0; var index = 0;
var mtimes = [10, 20, 30]; var mtimes = [10, 20, 30];

Просмотреть файл

@ -20,7 +20,7 @@ class DependencyGraphHelpers {
_providesModuleNodeModules: Array<string>; _providesModuleNodeModules: Array<string>;
_assetExts: Array<string>; _assetExts: Array<string>;
constructor({ providesModuleNodeModules, assetExts }: { constructor({providesModuleNodeModules, assetExts}: {
providesModuleNodeModules: Array<string>, providesModuleNodeModules: Array<string>,
assetExts: Array<string>, assetExts: Array<string>,
}) { }) {

Просмотреть файл

@ -83,7 +83,7 @@ class ResolutionRequest {
} }
_tryResolve(action: () => Promise<string>, secondaryAction: () => ?Promise<string>) { _tryResolve(action: () => Promise<string>, secondaryAction: () => ?Promise<string>) {
return action().catch((error) => { return action().catch(error => {
if (error.type !== 'UnableToResolveError') { if (error.type !== 'UnableToResolveError') {
throw error; throw error;
} }
@ -99,7 +99,7 @@ class ResolutionRequest {
return Promise.resolve(this._immediateResolutionCache[resHash]); return Promise.resolve(this._immediateResolutionCache[resHash]);
} }
const cacheResult = (result) => { const cacheResult = result => {
this._immediateResolutionCache[resHash] = result; this._immediateResolutionCache[resHash] = result;
return result; return result;
}; };
@ -229,7 +229,7 @@ class ResolutionRequest {
p = Promise.resolve(toModuleName); p = Promise.resolve(toModuleName);
} }
return p.then((realModuleName) => { return p.then(realModuleName => {
let dep = this._hasteMap.getModule(realModuleName, this._platform); let dep = this._hasteMap.getModule(realModuleName, this._platform);
if (dep && dep.type === 'Module') { if (dep && dep.type === 'Module') {
return dep; return dep;
@ -453,7 +453,7 @@ class ResolutionRequest {
if (this._hasteFS.exists(packageJsonPath)) { if (this._hasteFS.exists(packageJsonPath)) {
return this._moduleCache.getPackage(packageJsonPath) return this._moduleCache.getPackage(packageJsonPath)
.getMain().then( .getMain().then(
(main) => this._tryResolve( main => this._tryResolve(
() => this._loadAsFile(main, fromModule, toModule), () => this._loadAsFile(main, fromModule, toModule),
() => this._loadAsDir(main, fromModule, toModule) () => this._loadAsDir(main, fromModule, toModule)
) )

Просмотреть файл

@ -152,19 +152,19 @@ function getReplacements(pkg) {
if (typeof rn === 'string') { if (typeof rn === 'string') {
/* $FlowFixMe: It is likely unsafe to assume all packages would /* $FlowFixMe: It is likely unsafe to assume all packages would
* contain a "main" */ * contain a "main" */
rn = { [pkg.main]: rn }; rn = {[pkg.main]: rn};
} }
if (typeof browser === 'string') { if (typeof browser === 'string') {
/* $FlowFixMe: It is likely unsafe to assume all packages would /* $FlowFixMe: It is likely unsafe to assume all packages would
* contain a "main" */ * contain a "main" */
browser = { [pkg.main]: browser }; browser = {[pkg.main]: browser};
} }
// merge with "browser" as default, // merge with "browser" as default,
// "react-native" as override // "react-native" as override
// $FlowFixMe(>=0.35.0) browser and rn should be objects // $FlowFixMe(>=0.35.0) browser and rn should be objects
return { ...browser, ...rn }; return {...browser, ...rn};
} }
module.exports = Package; module.exports = Package;

Просмотреть файл

@ -39,7 +39,7 @@ fs.realpath.mockImplementation((filepath, callback) => {
callback(null, filepath); callback(null, filepath);
}); });
fs.readdirSync.mockImplementation((filepath) => Object.keys(getToNode(filepath))); fs.readdirSync.mockImplementation(filepath => Object.keys(getToNode(filepath)));
fs.readdir.mockImplementation((filepath, callback) => { fs.readdir.mockImplementation((filepath, callback) => {
callback = asyncCallback(callback); callback = asyncCallback(callback);
@ -213,7 +213,7 @@ fs.createReadStream.mockImplementation(filepath => {
read() { read() {
this.push(file, 'utf8'); this.push(file, 'utf8');
this.push(null); this.push(null);
} },
}); });
}); });
@ -226,7 +226,7 @@ fs.createWriteStream.mockImplementation(file => {
const writeStream = new stream.Writable({ const writeStream = new stream.Writable({
write(chunk) { write(chunk) {
this.__chunks.push(chunk); this.__chunks.push(chunk);
} },
}); });
writeStream.__file = file; writeStream.__file = file;
writeStream.__chunks = []; writeStream.__chunks = [];
@ -240,7 +240,7 @@ fs.createWriteStream.mockImplementation(file => {
}); });
fs.createWriteStream.mock.returned = []; fs.createWriteStream.mock.returned = [];
fs.__setMockFilesystem = (object) => (filesystem = object); fs.__setMockFilesystem = object => (filesystem = object);
function getToNode(filepath) { function getToNode(filepath) {
// Ignore the drive for Windows paths. // Ignore the drive for Windows paths.
@ -256,7 +256,7 @@ function getToNode(filepath) {
throw new Error('Make sure all paths are absolute.'); throw new Error('Make sure all paths are absolute.');
} }
let node = filesystem; let node = filesystem;
parts.slice(1).forEach((part) => { parts.slice(1).forEach(part => {
if (node && node.SYMLINK) { if (node && node.SYMLINK) {
node = getToNode(node.SYMLINK); node = getToNode(node.SYMLINK);
} }

Просмотреть файл

@ -45,7 +45,7 @@ describe('DependencyGraph', function() {
function getOrderedDependenciesAsJSON(dgraph, entryPath, platform, recursive = true) { function getOrderedDependenciesAsJSON(dgraph, entryPath, platform, recursive = true) {
return dgraph.getDependencies({entryPath, platform, recursive}) return dgraph.getDependencies({entryPath, platform, recursive})
.then(response => response.finalize()) .then(response => response.finalize())
.then(({ dependencies }) => Promise.all(dependencies.map(dep => Promise.all([ .then(({dependencies}) => Promise.all(dependencies.map(dep => Promise.all([
dep.getName(), dep.getName(),
dep.getDependencies(), dep.getDependencies(),
]).then(([name, moduleDependencies]) => ({ ]).then(([name, moduleDependencies]) => ({
@ -273,7 +273,7 @@ describe('DependencyGraph', function() {
...defaults, ...defaults,
roots: [root], roots: [root],
}); });
return getOrderedDependenciesAsJSON(dgraph, '/root/index.js', null, false).then((deps) => { return getOrderedDependenciesAsJSON(dgraph, '/root/index.js', null, false).then(deps => {
expect(deps) expect(deps)
.toEqual([ .toEqual([
{ {
@ -1472,7 +1472,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'aPackage/client.js', {id: 'aPackage/client.js',
path: '/root/aPackage/client.js', path: '/root/aPackage/client.js',
dependencies: [], dependencies: [],
isAsset: false, isAsset: false,
@ -1585,7 +1585,7 @@ describe('DependencyGraph', function() {
return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) {
expect(deps) expect(deps)
.toEqual([ .toEqual([
{ id: 'index', {id: 'index',
path: '/root/index.js', path: '/root/index.js',
dependencies: ['aPackage'], dependencies: ['aPackage'],
isAsset: false, isAsset: false,
@ -1593,7 +1593,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'aPackage/client.js', {id: 'aPackage/client.js',
path: '/root/aPackage/client.js', path: '/root/aPackage/client.js',
dependencies: ['./node', './dir/server.js'], dependencies: ['./node', './dir/server.js'],
isAsset: false, isAsset: false,
@ -1601,7 +1601,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'aPackage/not-node.js', {id: 'aPackage/not-node.js',
path: '/root/aPackage/not-node.js', path: '/root/aPackage/not-node.js',
dependencies: ['./not-browser'], dependencies: ['./not-browser'],
isAsset: false, isAsset: false,
@ -1609,7 +1609,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'aPackage/browser.js', {id: 'aPackage/browser.js',
path: '/root/aPackage/browser.js', path: '/root/aPackage/browser.js',
dependencies: [], dependencies: [],
isAsset: false, isAsset: false,
@ -1680,7 +1680,7 @@ describe('DependencyGraph', function() {
return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) {
expect(deps) expect(deps)
.toEqual([ .toEqual([
{ id: 'index', {id: 'index',
path: '/root/index.js', path: '/root/index.js',
dependencies: ['aPackage'], dependencies: ['aPackage'],
isAsset: false, isAsset: false,
@ -1688,7 +1688,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'aPackage/index.js', {id: 'aPackage/index.js',
path: '/root/aPackage/index.js', path: '/root/aPackage/index.js',
dependencies: ['node-package'], dependencies: ['node-package'],
isAsset: false, isAsset: false,
@ -1696,7 +1696,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'browser-package/index.js', {id: 'browser-package/index.js',
path: '/root/aPackage/browser-package/index.js', path: '/root/aPackage/browser-package/index.js',
dependencies: [], dependencies: [],
isAsset: false, isAsset: false,
@ -1747,7 +1747,7 @@ describe('DependencyGraph', function() {
return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) {
expect(deps) expect(deps)
.toEqual([ .toEqual([
{ id: 'index', {id: 'index',
path: '/root/index.js', path: '/root/index.js',
dependencies: ['aPackage'], dependencies: ['aPackage'],
isAsset: false, isAsset: false,
@ -1755,7 +1755,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'aPackage/index.js', {id: 'aPackage/index.js',
path: '/root/aPackage/index.js', path: '/root/aPackage/index.js',
dependencies: ['./dir/ooga'], dependencies: ['./dir/ooga'],
isAsset: false, isAsset: false,
@ -1763,7 +1763,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'aPackage/dir/ooga.js', {id: 'aPackage/dir/ooga.js',
path: '/root/aPackage/dir/ooga.js', path: '/root/aPackage/dir/ooga.js',
dependencies: ['node-package'], dependencies: ['node-package'],
isAsset: false, isAsset: false,
@ -1771,7 +1771,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'aPackage/dir/browser.js', {id: 'aPackage/dir/browser.js',
path: '/root/aPackage/dir/browser.js', path: '/root/aPackage/dir/browser.js',
dependencies: [], dependencies: [],
isAsset: false, isAsset: false,
@ -1824,7 +1824,7 @@ describe('DependencyGraph', function() {
return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) {
expect(deps) expect(deps)
.toEqual([ .toEqual([
{ id: 'index', {id: 'index',
path: '/root/index.js', path: '/root/index.js',
dependencies: ['aPackage'], dependencies: ['aPackage'],
isAsset: false, isAsset: false,
@ -1832,7 +1832,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'aPackage/index.js', {id: 'aPackage/index.js',
path: '/root/aPackage/index.js', path: '/root/aPackage/index.js',
dependencies: ['node-package'], dependencies: ['node-package'],
isAsset: false, isAsset: false,
@ -1840,7 +1840,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'browser-package/index.js', {id: 'browser-package/index.js',
path: '/root/aPackage/browser-package/index.js', path: '/root/aPackage/browser-package/index.js',
dependencies: [], dependencies: [],
isAsset: false, isAsset: false,
@ -1889,7 +1889,7 @@ describe('DependencyGraph', function() {
return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) {
expect(deps) expect(deps)
.toEqual([ .toEqual([
{ id: 'index', {id: 'index',
path: '/root/index.js', path: '/root/index.js',
dependencies: ['aPackage'], dependencies: ['aPackage'],
isAsset: false, isAsset: false,
@ -1897,7 +1897,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'aPackage/index.js', {id: 'aPackage/index.js',
path: '/root/aPackage/index.js', path: '/root/aPackage/index.js',
dependencies: ['booga'], dependencies: ['booga'],
isAsset: false, isAsset: false,
@ -2035,7 +2035,7 @@ describe('DependencyGraph', function() {
return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) {
expect(deps) expect(deps)
.toEqual([ .toEqual([
{ id: 'index', {id: 'index',
path: '/root/index.js', path: '/root/index.js',
dependencies: ['aPackage'], dependencies: ['aPackage'],
isAsset: false, isAsset: false,
@ -2043,7 +2043,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'aPackage/index.js', {id: 'aPackage/index.js',
path: '/root/aPackage/index.js', path: '/root/aPackage/index.js',
dependencies: ['node-package'], dependencies: ['node-package'],
isAsset: false, isAsset: false,
@ -2051,7 +2051,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'rn-package/index.js', {id: 'rn-package/index.js',
path: '/root/aPackage/node_modules/rn-package/index.js', path: '/root/aPackage/node_modules/rn-package/index.js',
dependencies: ['nested-package'], dependencies: ['nested-package'],
isAsset: false, isAsset: false,
@ -2059,7 +2059,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'nested-browser-package/index.js', {id: 'nested-browser-package/index.js',
path: '/root/aPackage/node_modules/nested-browser-package/index.js', path: '/root/aPackage/node_modules/nested-browser-package/index.js',
dependencies: [], dependencies: [],
isAsset: false, isAsset: false,
@ -2198,7 +2198,7 @@ describe('DependencyGraph', function() {
return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) { return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) {
expect(deps) expect(deps)
.toEqual([ .toEqual([
{ id: 'index', {id: 'index',
path: '/root/index.js', path: '/root/index.js',
dependencies: ['aPackage'], dependencies: ['aPackage'],
isAsset: false, isAsset: false,
@ -2206,7 +2206,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'aPackage/index.js', {id: 'aPackage/index.js',
path: '/root/aPackage/index.js', path: '/root/aPackage/index.js',
dependencies: ['node-package-a', 'node-package-b', 'node-package-c'], dependencies: ['node-package-a', 'node-package-b', 'node-package-c'],
isAsset: false, isAsset: false,
@ -2214,7 +2214,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'rn-package-a/index.js', {id: 'rn-package-a/index.js',
path: '/root/aPackage/node_modules/rn-package-a/index.js', path: '/root/aPackage/node_modules/rn-package-a/index.js',
dependencies: [], dependencies: [],
isAsset: false, isAsset: false,
@ -2222,7 +2222,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'rn-package-b/index.js', {id: 'rn-package-b/index.js',
path: '/root/aPackage/node_modules/rn-package-b/index.js', path: '/root/aPackage/node_modules/rn-package-b/index.js',
dependencies: [], dependencies: [],
isAsset: false, isAsset: false,
@ -2230,7 +2230,7 @@ describe('DependencyGraph', function() {
isPolyfill: false, isPolyfill: false,
resolution: undefined, resolution: undefined,
}, },
{ id: 'rn-package-d/index.js', {id: 'rn-package-d/index.js',
path: '/root/aPackage/node_modules/rn-package-d/index.js', path: '/root/aPackage/node_modules/rn-package-d/index.js',
dependencies: [], dependencies: [],
isAsset: false, isAsset: false,
@ -2308,8 +2308,8 @@ describe('DependencyGraph', function() {
setMockFileSystem({ setMockFileSystem({
[root.slice(1)]: { [root.slice(1)]: {
'index.js': 'require("bar")', 'index.js': 'require("bar")',
'node_modules': { 'bar.js': '' }, 'node_modules': {'bar.js': ''},
'provides-bar': { 'index.js': '' }, 'provides-bar': {'index.js': ''},
}, },
}); });
@ -2437,7 +2437,7 @@ describe('DependencyGraph', function() {
...defaults, ...defaults,
roots: [root], roots: [root],
}); });
return getOrderedDependenciesAsJSON(dgraph, 'C:\\root\\index.js').then((deps) => { return getOrderedDependenciesAsJSON(dgraph, 'C:\\root\\index.js').then(deps => {
expect(deps) expect(deps)
.toEqual([ .toEqual([
{ {
@ -3175,7 +3175,7 @@ describe('DependencyGraph', function() {
resolution: undefined, resolution: undefined,
}, },
]); ]);
}); });
}); });
}); });

Просмотреть файл

@ -58,7 +58,7 @@ describe('Module', () => {
}); });
let transformCacheKey; let transformCacheKey;
const createModule = (options) => const createModule = options =>
new Module({ new Module({
options: { options: {
cacheTransformResults: true, cacheTransformResults: true,
@ -75,7 +75,7 @@ describe('Module', () => {
}); });
const createJSONModule = const createJSONModule =
(options) => createModule({...options, file: '/root/package.json'}); options => createModule({...options, file: '/root/package.json'});
beforeEach(function() { beforeEach(function() {
process.platform = 'linux'; process.platform = 'linux';
@ -284,7 +284,7 @@ describe('Module', () => {
}; };
const module = createModule({transformCode}); const module = createModule({transformCode});
return module.read().then((result) => { return module.read().then(result => {
expect(result).toEqual(jasmine.objectContaining(transformResult)); expect(result).toEqual(jasmine.objectContaining(transformResult));
}); });
}); });
@ -302,7 +302,7 @@ describe('Module', () => {
cacheTransformResults: false, cacheTransformResults: false,
}}); }});
return module.read().then((result) => { return module.read().then(result => {
expect(result).toEqual({ expect(result).toEqual({
dependencies: ['foo', 'bar'], dependencies: ['foo', 'bar'],
}); });
@ -320,8 +320,8 @@ describe('Module', () => {
}; };
const module = createModule({transformCode, options: undefined}); const module = createModule({transformCode, options: undefined});
return module.read().then((result) => { return module.read().then(result => {
expect(result).toEqual({ ...transformResult, source: 'arbitrary(code);'}); expect(result).toEqual({...transformResult, source: 'arbitrary(code);'});
}); });
}); });

Просмотреть файл

@ -137,7 +137,7 @@ class DependencyGraph {
dir = path.dirname(dir); dir = path.dirname(dir);
} while (dir !== '.' && dir !== root); } while (dir !== '.' && dir !== root);
return null; return null;
} },
}, this._opts.platforms); }, this._opts.platforms);
this._hasteMap = new HasteMap({ this._hasteMap = new HasteMap({

Просмотреть файл

@ -28,7 +28,7 @@ describe('getInverseDependencies', () => {
const resolutionResponse = { const resolutionResponse = {
dependencies: [module1, module2, module3, module4], dependencies: [module1, module2, module3, module4],
getResolvedDependencyPairs: (module) => { getResolvedDependencyPairs: module => {
return modulePairs[module.hash()]; return modulePairs[module.hash()];
}, },
}; };

Просмотреть файл

@ -45,8 +45,8 @@ function getAssetDataFromName(filename, platforms) {
assetName = decodeURIComponent(assetName); assetName = decodeURIComponent(assetName);
return { return {
resolution: resolution, resolution,
assetName: assetName, assetName,
type: ext.slice(1), type: ext.slice(1),
name: path.basename(assetName, ext), name: path.basename(assetName, ext),
platform: platformExt, platform: platformExt,