From 1e8e79eb7e2314bdbdfa64cb90a1711cc79cf4f7 Mon Sep 17 00:00:00 2001 From: connectdotz Date: Wed, 4 Mar 2020 12:05:06 -0500 Subject: [PATCH 1/4] add optional dependencies transform, resolve and config --- .../__snapshots__/loadConfig-test.js.snap | 2 + packages/metro-config/src/configTypes.flow.js | 2 +- packages/metro-config/src/defaults/index.js | 1 + .../__tests__/traverseDependencies-test.js | 110 +++++++++++++ .../src/DeltaBundler/traverseDependencies.js | 49 ++++-- packages/metro/src/DeltaBundler/types.flow.js | 11 ++ packages/metro/src/IncrementalBundler.js | 2 + packages/metro/src/JSTransformer/worker.js | 3 + .../__tests__/collectDependencies-test.js | 152 +++++++++++++++++- .../ModuleGraph/worker/collectDependencies.js | 49 +++++- .../metro/src/Server/__tests__/Server-test.js | 2 + packages/metro/src/lib/getPrependedScripts.js | 1 + packages/metro/src/lib/transformHelpers.js | 1 + 13 files changed, 367 insertions(+), 18 deletions(-) diff --git a/packages/metro-config/src/__tests__/__snapshots__/loadConfig-test.js.snap b/packages/metro-config/src/__tests__/__snapshots__/loadConfig-test.js.snap index 7a102fe975..540414fd04 100644 --- a/packages/metro-config/src/__tests__/__snapshots__/loadConfig-test.js.snap +++ b/packages/metro-config/src/__tests__/__snapshots__/loadConfig-test.js.snap @@ -91,6 +91,7 @@ Object { "customizeFrame": [Function], }, "transformer": Object { + "allowOptionalDependencies": false, "assetPlugins": Array [], "assetRegistryPath": "missing-asset-registry-path", "asyncRequireModulePath": "metro/src/lib/bundle-modules/asyncRequire", @@ -224,6 +225,7 @@ Object { "customizeFrame": [Function], }, "transformer": Object { + "allowOptionalDependencies": false, "assetPlugins": Array [], "assetRegistryPath": "missing-asset-registry-path", "asyncRequireModulePath": "metro/src/lib/bundle-modules/asyncRequire", diff --git a/packages/metro-config/src/configTypes.flow.js b/packages/metro-config/src/configTypes.flow.js index 343dd0f10d..46e8cac6f8 100644 --- a/packages/metro-config/src/configTypes.flow.js +++ b/packages/metro-config/src/configTypes.flow.js @@ -18,8 +18,8 @@ import type { DeltaResult, Graph, Module, + SerializerOptions, } from 'metro/src/DeltaBundler/types.flow.js'; -import type {SerializerOptions} from 'metro/src/DeltaBundler/types.flow'; import type {TransformResult} from 'metro/src/DeltaBundler'; import type {JsTransformerConfig} from 'metro/src/JSTransformer/worker'; import type {TransformVariants} from 'metro/src/ModuleGraph/types.flow.js'; diff --git a/packages/metro-config/src/defaults/index.js b/packages/metro-config/src/defaults/index.js index 749bf3bd8f..672f0c16dc 100644 --- a/packages/metro-config/src/defaults/index.js +++ b/packages/metro-config/src/defaults/index.js @@ -111,6 +111,7 @@ const getDefaultValues = (projectRoot: ?string): ConfigT => ({ transformVariants: {default: {}}, workerPath: 'metro/src/DeltaBundler/Worker', publicPath: '/assets', + allowOptionalDependencies: false, }, cacheStores: [ new FileStore({ diff --git a/packages/metro/src/DeltaBundler/__tests__/traverseDependencies-test.js b/packages/metro/src/DeltaBundler/__tests__/traverseDependencies-test.js index c4a3b39d60..26209a079d 100644 --- a/packages/metro/src/DeltaBundler/__tests__/traverseDependencies-test.js +++ b/packages/metro/src/DeltaBundler/__tests__/traverseDependencies-test.js @@ -870,3 +870,113 @@ describe('reorderGraph', () => { ]); }); }); + +describe('optional dependencies', () => { + let localGraph; + let localOptions; + const getAllDependencies = () => { + const all = new Set(); + mockedDependencyTree.forEach(deps => { + deps.forEach(r => all.add(r.name)); + }); + return all; + }; + const assertResults = (dependencies, expectedMissing) => { + let count = 0; + const allDependency = getAllDependencies(); + allDependency.forEach(m => { + const data = dependencies.get(`/${m}`); + if (expectedMissing.includes(m)) { + expect(data).toBeUndefined(); + } else { + expect(data).not.toBeUndefined(); + } + count += 1; + }); + expect(count).toBeGreaterThan(0); + expect(count).toBe(allDependency.size); + }; + + beforeEach(() => { + mockedDependencies = new Set(); + mockedDependencyTree = new Map(); + + entryModule = Actions.createFile('/bundle-o'); + entryModule = Actions.createFile('/optional-c'); + + Actions.addDependency('/bundle-o', '/regular-a'); + Actions.addDependency('/bundle-o', '/optional-b'); + Actions.addDependency('/bundle-o', '/optional-c'); + Actions.addDependency('/optional-c', '/optional-d'); + Actions.addDependency('/optional-c', '/regular-e'); + + Actions.deleteFile('/optional-b'); + + localOptions = { + ...options, + transform(path) { + const result = options.transform.apply(this, arguments); + result.dependencies.forEach(dep => { + if (dep.name.includes('optional-')) { + dep.data.isOptional = true; + } + }); + return result; + }, + }; + localGraph = { + dependencies: new Map(), + entryPoints: ['/bundle-o'], + }; + }); + describe('when allowOptionalDependencies config is true', () => { + beforeEach(() => { + localOptions.allowOptionalDependencies = true; + }); + it('will ignore only the failed optional dependency', async () => { + const result = await initialTraverseDependencies( + localGraph, + localOptions, + ); + + const dependencies = result.added; + + // Only `optional-b` is actually missing, + // the other optional modules `optional-c` and `optional-d` will + // still be included. + assertResults(dependencies, ['optional-b']); + }); + }); + describe('when allowOptionalDependencies config is false', () => { + beforeEach(() => { + localOptions.allowOptionalDependencies = false; + }); + it('will not ignore failed optional dependency', async () => { + await expect( + initialTraverseDependencies(localGraph, localOptions), + ).rejects.toThrow('Dependency not found: /optional-b->optional-b'); + }); + }); + describe('when allowOptionalDependencies with exclude', () => { + it('will not ignore the excluded optional dependency', async () => { + localOptions.allowOptionalDependencies = {exclude: ['optional-b']}; + await expect( + initialTraverseDependencies(localGraph, localOptions), + ).rejects.toThrow('Dependency not found: /optional-b->optional-b'); + }); + it('but will still ignore the non-excluded optional dependency', async () => { + localOptions.allowOptionalDependencies = {exclude: ['optional-d']}; + const result = await initialTraverseDependencies( + localGraph, + localOptions, + ); + + const dependencies = result.added; + + // Only `optional-b` is actually missing, + // the other optional modules `optional-c` and `optional-d` will + // still be included. + assertResults(dependencies, ['optional-b']); + }); + }); +}); diff --git a/packages/metro/src/DeltaBundler/traverseDependencies.js b/packages/metro/src/DeltaBundler/traverseDependencies.js index eb98d40771..a4eaf05fb3 100644 --- a/packages/metro/src/DeltaBundler/traverseDependencies.js +++ b/packages/metro/src/DeltaBundler/traverseDependencies.js @@ -18,6 +18,7 @@ import type { Module, Options, TransformResultDependency, + AllowOptionalDependencies, } from './types.flow'; type Result = { @@ -46,6 +47,7 @@ type InternalOptions = $ReadOnly<{| resolve: $PropertyType, 'resolve'>, transform: $PropertyType, 'transform'>, shallow: boolean, + allowOptionalDependencies: AllowOptionalDependencies, |}>; function getInternalOptions({ @@ -53,6 +55,7 @@ function getInternalOptions({ resolve, onProgress, experimentalImportBundleSupport, + allowOptionalDependencies, shallow, }: Options): InternalOptions { let numProcessed = 0; @@ -60,6 +63,7 @@ function getInternalOptions({ return { experimentalImportBundleSupport, + allowOptionalDependencies, transform, resolve, onDependencyAdd: () => onProgress && onProgress(numProcessed, ++total), @@ -471,18 +475,43 @@ function resolveDependencies( dependencies: $ReadOnlyArray, options: InternalOptions, ): Map { - return new Map( - dependencies.map((result: TransformResultDependency) => { - const relativePath = result.name; - - const dependency = { - absolutePath: options.resolve(parentPath, result.name), - data: result, - }; + const {allowOptionalDependencies} = options; + const required = (path: string) => + allowOptionalDependencies === false || + (Array.isArray(allowOptionalDependencies.exclude) && + allowOptionalDependencies.exclude.includes(path)); + + const resolve = (parentPath: string, result: TransformResultDependency) => { + const relativePath = result.name; + try { + return [ + relativePath, + { + absolutePath: options.resolve(parentPath, relativePath), + data: result, + }, + ]; + } catch (e) { + // If this is an optional dependency, ignore the resolution error + if (result.data.isOptional === true && !required(relativePath)) { + // should we output some warning? verbose mode? + return undefined; + } + throw e; + } + }; - return [relativePath, dependency]; - }), + const resolved = dependencies.reduce( + (list: Array<[string, Dependency]>, result: TransformResultDependency) => { + const resolvedPath = resolve(parentPath, result); + if (resolvedPath) { + list.push(resolvedPath); + } + return list; + }, + [], ); + return new Map(resolved); } /** diff --git a/packages/metro/src/DeltaBundler/types.flow.js b/packages/metro/src/DeltaBundler/types.flow.js index 6d6c2151d9..bd6a1060f2 100644 --- a/packages/metro/src/DeltaBundler/types.flow.js +++ b/packages/metro/src/DeltaBundler/types.flow.js @@ -42,6 +42,10 @@ export type TransformResultDependency = {| +splitCondition?: {| +mobileConfigName: string, |}, + /** + * The dependency is enclosed in a try/catch block, indicated optional + */ + +isOptional?: boolean, +locs: $ReadOnlyArray, |}, @@ -79,12 +83,19 @@ export type TransformResultWithSource = $ReadOnly<{| export type TransformFn = string => Promise< TransformResultWithSource, >; +export type AllowOptionalDependenciesWithOptions = {| + +exclude: Array, +|}; +export type AllowOptionalDependencies = + | boolean + | AllowOptionalDependenciesWithOptions; export type Options = {| +resolve: (from: string, to: string) => string, +transform: TransformFn, +onProgress: ?(numProcessed: number, total: number) => mixed, +experimentalImportBundleSupport: boolean, + +allowOptionalDependencies: AllowOptionalDependencies, +shallow: boolean, |}; diff --git a/packages/metro/src/IncrementalBundler.js b/packages/metro/src/IncrementalBundler.js index e1475c62f7..27b6063f47 100644 --- a/packages/metro/src/IncrementalBundler.js +++ b/packages/metro/src/IncrementalBundler.js @@ -139,6 +139,8 @@ class IncrementalBundler { onProgress: otherOptions.onProgress, experimentalImportBundleSupport: this._config.transformer .experimentalImportBundleSupport, + allowOptionalDependencies: this._config.transformer + .allowOptionalDependencies, shallow: otherOptions.shallow, }); diff --git a/packages/metro/src/JSTransformer/worker.js b/packages/metro/src/JSTransformer/worker.js index 02bbe7d2be..f214eb4e4c 100644 --- a/packages/metro/src/JSTransformer/worker.js +++ b/packages/metro/src/JSTransformer/worker.js @@ -35,6 +35,7 @@ const { toSegmentTuple, } = require('metro-source-map'); import type {TransformResultDependency} from 'metro/src/DeltaBundler'; +import type {AllowOptionalDependencies} from 'metro/src/DeltaBundler/types.flow.js'; import type {DynamicRequiresBehavior} from '../ModuleGraph/worker/collectDependencies'; import type { BasicSourceMap, @@ -68,6 +69,7 @@ export type JsTransformerConfig = $ReadOnly<{| minifierPath: string, optimizationSizeLimit: number, publicPath: string, + allowOptionalDependencies: AllowOptionalDependencies, |}>; import type {CustomTransformOptions} from 'metro-babel-transformer'; @@ -280,6 +282,7 @@ class JsTransformer { ), inlineableCalls: [importDefault, importAll], keepRequireNames: options.dev, + allowOptionalDependencies: this._config.allowOptionalDependencies, }; ({ast, dependencies, dependencyMapName} = collectDependencies( ast, diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index 29ccbcce9e..c1f0e98150 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -18,6 +18,8 @@ const dedent = require('dedent'); const {codeFromAst, comparableCode} = require('../../test-helpers'); const {codeFrameColumns} = require('@babel/code-frame'); +import type {Options} from '../collectDependencies'; + const {any, objectContaining} = expect; const {InvalidRequireCallError} = collectDependencies; @@ -26,6 +28,7 @@ const opts = { dynamicRequires: 'reject', inlineableCalls: [], keepRequireNames: true, + allowOptionalDependencies: false, }; it('collects unique dependency identifiers and transforms the AST', () => { @@ -240,7 +243,7 @@ describe('Evaluating static arguments', () => { }); it('supports using static variables in require statements', () => { - const ast = astFromCode('const myVar="my";require("foo_" + myVar)'); + const ast = astFromCode('const myVar="my"; require("foo_" + myVar)'); const {dependencies, dependencyMapName} = collectDependencies(ast, opts); expect(dependencies).toEqual([ {name: 'foo_my', data: objectContaining({isAsync: false})}, @@ -272,6 +275,7 @@ describe('Evaluating static arguments', () => { dynamicRequires: 'throwAtRuntime', inlineableCalls: [], keepRequireNames: true, + allowOptionalDependencies: false, }; const {dependencies} = collectDependencies(ast, opts); expect(dependencies).toEqual([]); @@ -393,6 +397,152 @@ it('records locations of dependencies', () => { `); }); +describe('optional dependencies', () => { + const opts: Options = { + asyncRequireModulePath: 'asyncRequire', + dynamicRequires: 'reject', + inlineableCalls: [], + keepRequireNames: true, + allowOptionalDependencies: true, + }; + const validateDependencies = (dependencies, expectedCount) => { + let hasAsync = false; + let checked = 0; + dependencies.forEach(d => { + if (d.name.includes('-async')) { + expect(d.data.isAsync).toBeTruthy(); + hasAsync = true; + } else { + expect(d.data.isAsync).toBeFalsy(); + } + if ( + d.name.startsWith('optional') || + d.name.startsWith('@somescope/optional') + ) { + checked += 1; + expect(d.data.isOptional).toBeTruthy(); + } else if ( + d.name.startsWith('not-optional') || + d.name.startsWith('@somescope/not-optional') + ) { + checked += 1; + expect(d.data.isOptional).toBeFalsy(); + } + }); + expect(dependencies).toHaveLength(checked + (hasAsync ? 1 : 0)); + expect(dependencies).toHaveLength(expectedCount); + }; + it('dependency in try-block within 1-level will be optional', () => { + const ast = astFromCode(` + function fFunc() { + import('not-optional-async-f').then(); + } + try { + const a = require('optional-a'); + if(true) { + const b = require('not-optional-b'); + } + const cFunc = () => { + const c = require('not-optional-c'); + } + fFunc(); + cFunc(); + + import('optional-async-d'); + } catch(e) { + require('not-optional-e'); + } finally { + require('not-optional-g'); + } + `); + + const {dependencies} = collectDependencies(ast, opts); + validateDependencies(dependencies, 8); + }); + it('nested try-block follows the inner-most scope', () => { + const ast = astFromCode(` + try { + const a = require('optional-a'); + try{ + const b = import('optional-async-b'); + } finally {} + const c = require('optional-c'); + } catch(e) {} + `); + + const {dependencies} = collectDependencies(ast, opts); + validateDependencies(dependencies, 4); + }); + it('can handle single-line statement', () => { + const ast = astFromCode( + "try { const a = require('optional-a') } catch (e) {}", + ); + const {dependencies} = collectDependencies(ast, opts); + validateDependencies(dependencies, 1); + }); + it('independent of sibiling context', () => { + const ast = astFromCode(` + try { + const x = whatever; + const a = x ? require('optional-a') : require('optional-b'); + } catch (e) {} + `); + const {dependencies} = collectDependencies(ast, opts); + validateDependencies(dependencies, 2); + }); + it('ignores require functions defined by lower scopes', () => { + const ast = astFromCode(` + const f = (require) => { + try { + const c = require('not-dependency'); + } catch (e) {} + }; + `); + const {dependencies} = collectDependencies(ast, opts); + expect(dependencies).toHaveLength(0); + }); + it('supports using static variables in require statements', () => { + const ast = astFromCode(` + const myVar="my"; + try { + require("foo_" + myVar); + } catch (e) {} + `); + const {dependencies} = collectDependencies(ast, opts); + expect(dependencies).toEqual([ + { + name: 'foo_my', + data: objectContaining({isAsync: false, isOptional: true}), + }, + ]); + }); + it('controls optional dependency analysis by allowOptionalDependencies flag', () => { + const code = ` + try { + const a = require('a'); + } catch (e) {} + `; + + let options = {...opts, allowOptionalDependencies: true}; + const {dependencies: depOn} = collectDependencies( + astFromCode(code), + options, + ); + expect(depOn).toEqual([ + {name: 'a', data: objectContaining({isOptional: true})}, + ]); + + options = {...opts, allowOptionalDependencies: false}; + const {dependencies: depOff} = collectDependencies( + astFromCode(code), + options, + ); + expect(depOff).toEqual([ + {name: 'a', data: expect.not.objectContaining({isOptional: true})}, + ]); + }); +}); + function formatDependencyLocs(dependencies, code) { return ( '\n' + diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index d83fadddc2..ad5f6957f0 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -24,6 +24,7 @@ const traverse = require('@babel/traverse').default; const types = require('@babel/types'); import type {Ast} from '@babel/core'; +import type {AllowOptionalDependencies} from 'metro/src/DeltaBundler/types.flow.js'; opaque type Identifier = any; opaque type Path = any; @@ -31,6 +32,7 @@ opaque type Path = any; type DepOptions = {| +prefetchOnly: boolean, +jsResource?: boolean, + +isOptional?: boolean, |}; type InternalDependency = {| @@ -41,6 +43,7 @@ type InternalDependency = {| type InternalDependencyData = {| isAsync: boolean, isPrefetchOnly?: true, + isOptional?: boolean, locs: Array, |}; @@ -59,6 +62,7 @@ type State = {| dependencyMapIdentifier: ?Identifier, keepRequireNames: boolean, disableRequiresTransform: boolean, + allowOptionalDependencies: AllowOptionalDependencies, |}; export type Options = {| @@ -67,6 +71,7 @@ export type Options = {| +inlineableCalls: $ReadOnlyArray, +keepRequireNames: boolean, +disableRequiresTransform?: boolean, + +allowOptionalDependencies: AllowOptionalDependencies, |}; export type CollectedDependencies = {| @@ -135,6 +140,7 @@ function collectDependencies( dynamicRequires: options.dynamicRequires, keepRequireNames: options.keepRequireNames, disableRequiresTransform: !!options.disableRequiresTransform, + allowOptionalDependencies: options.allowOptionalDependencies, }; const visitor = { @@ -219,17 +225,15 @@ function collectDependencies( }; } -function processImportCall( - path: Path, - state: State, - options: DepOptions, -): Path { +function processImportCall(path: Path, state: State, opts: DepOptions): Path { const name = getModuleNameFromCallArgs(path); if (name == null) { throw new InvalidRequireCallError(path); } + const isOptional = isOptionalDependency(path, state); + const options = {...opts, isOptional}; const dep = getDependency(state, name, options, path.node.loc); if (!options.prefetchOnly) { delete dep.data.isPrefetchOnly; @@ -291,7 +295,13 @@ function processRequireCall(path: Path, state: State): Path { return path; } - const dep = getDependency(state, name, {prefetchOnly: false}, path.node.loc); + const isOptional = isOptionalDependency(path, state); + const dep = getDependency( + state, + name, + {prefetchOnly: false, isOptional}, + path.node.loc, + ); dep.data.isAsync = false; delete dep.data.isPrefetchOnly; @@ -329,6 +339,10 @@ function getDependency( data.isPrefetchOnly = true; } + if (options.isOptional) { + data.isOptional = true; + } + state.dependencyIndexes.set(name, index); state.dependencyData.set(name, data); } @@ -340,6 +354,29 @@ function getDependency( return {index: nullthrows(index), data: nullthrows(data)}; } +const isOptionalDependency = (path: Path, state: State): boolean => { + if (!state.allowOptionalDependencies) { + return false; + } + + // Valid statement stack for single-level try-block: expressionStatement -> blockStatement -> tryStatement + let sCount = 0; + let p = path; + while (p && sCount < 3) { + if (p.isStatement()) { + if (p.node.type === 'BlockStatement') { + // A single-level should have the tryStatement immediately followed BlockStatement + // with the key 'block' to distinguish from the finally block, which has key = 'finalizer' + return p.parentPath.node.type === 'TryStatement' && p.key === 'block'; + } + sCount += 1; + } + p = p.parentPath; + } + + return false; +}; + function getModuleNameFromCallArgs(path: Path): ?string { const expectedCount = path.node.callee.name === '__conditionallySplitJSResource' ? 2 : 1; diff --git a/packages/metro/src/Server/__tests__/Server-test.js b/packages/metro/src/Server/__tests__/Server-test.js index b0458b8486..95f5f10133 100644 --- a/packages/metro/src/Server/__tests__/Server-test.js +++ b/packages/metro/src/Server/__tests__/Server-test.js @@ -460,6 +460,7 @@ describe('processRequest', () => { resolve: expect.any(Function), shallow: false, transform: expect.any(Function), + allowOptionalDependencies: false, }, ); }); @@ -594,6 +595,7 @@ describe('processRequest', () => { resolve: expect.any(Function), shallow: false, transform: expect.any(Function), + allowOptionalDependencies: false, }, ); }); diff --git a/packages/metro/src/lib/getPrependedScripts.js b/packages/metro/src/lib/getPrependedScripts.js index 01e9c22202..385f522cef 100644 --- a/packages/metro/src/lib/getPrependedScripts.js +++ b/packages/metro/src/lib/getPrependedScripts.js @@ -59,6 +59,7 @@ async function getPrependedScripts( onProgress: null, experimentalImportBundleSupport: config.transformer.experimentalImportBundleSupport, + allowOptionalDependencies: config.transformer.allowOptionalDependencies, shallow: false, }, ); diff --git a/packages/metro/src/lib/transformHelpers.js b/packages/metro/src/lib/transformHelpers.js index cd437ea0f6..d77f19b480 100644 --- a/packages/metro/src/lib/transformHelpers.js +++ b/packages/metro/src/lib/transformHelpers.js @@ -73,6 +73,7 @@ async function calcTransformerOptions( onProgress: null, experimentalImportBundleSupport: config.transformer.experimentalImportBundleSupport, + allowOptionalDependencies: config.transformer.allowOptionalDependencies, shallow: false, }); From a76ea774ca7d5112d3d61652252c527d3b9541b7 Mon Sep 17 00:00:00 2001 From: connectdotz Date: Wed, 4 Mar 2020 17:30:48 -0500 Subject: [PATCH 2/4] consolidate all optional dependency check into collectDependencies --- .../__tests__/traverseDependencies-test.js | 97 +++++++------------ .../src/DeltaBundler/traverseDependencies.js | 13 +-- packages/metro/src/DeltaBundler/types.flow.js | 1 - packages/metro/src/IncrementalBundler.js | 2 - .../__tests__/collectDependencies-test.js | 55 +++++++---- .../ModuleGraph/worker/collectDependencies.js | 23 +++-- .../metro/src/Server/__tests__/Server-test.js | 2 - packages/metro/src/lib/getPrependedScripts.js | 1 - packages/metro/src/lib/transformHelpers.js | 1 - 9 files changed, 85 insertions(+), 110 deletions(-) diff --git a/packages/metro/src/DeltaBundler/__tests__/traverseDependencies-test.js b/packages/metro/src/DeltaBundler/__tests__/traverseDependencies-test.js index 26209a079d..9259132622 100644 --- a/packages/metro/src/DeltaBundler/__tests__/traverseDependencies-test.js +++ b/packages/metro/src/DeltaBundler/__tests__/traverseDependencies-test.js @@ -897,86 +897,55 @@ describe('optional dependencies', () => { expect(count).toBe(allDependency.size); }; + const mockTransform = (notOptional?: string[]) => { + return function(path) { + const result = options.transform.apply(this, arguments); + result.dependencies.forEach(dep => { + if (notOptional && notOptional.includes(dep.name)) { + dep.data.isOptional = false; + } else { + dep.data.isOptional = dep.name.includes('optional-'); + } + }); + return result; + }; + }; + beforeEach(() => { mockedDependencies = new Set(); mockedDependencyTree = new Map(); entryModule = Actions.createFile('/bundle-o'); - entryModule = Actions.createFile('/optional-c'); Actions.addDependency('/bundle-o', '/regular-a'); Actions.addDependency('/bundle-o', '/optional-b'); - Actions.addDependency('/bundle-o', '/optional-c'); - Actions.addDependency('/optional-c', '/optional-d'); - Actions.addDependency('/optional-c', '/regular-e'); Actions.deleteFile('/optional-b'); - localOptions = { - ...options, - transform(path) { - const result = options.transform.apply(this, arguments); - result.dependencies.forEach(dep => { - if (dep.name.includes('optional-')) { - dep.data.isOptional = true; - } - }); - return result; - }, - }; localGraph = { dependencies: new Map(), entryPoints: ['/bundle-o'], }; }); - describe('when allowOptionalDependencies config is true', () => { - beforeEach(() => { - localOptions.allowOptionalDependencies = true; - }); - it('will ignore only the failed optional dependency', async () => { - const result = await initialTraverseDependencies( - localGraph, - localOptions, - ); - - const dependencies = result.added; - - // Only `optional-b` is actually missing, - // the other optional modules `optional-c` and `optional-d` will - // still be included. - assertResults(dependencies, ['optional-b']); - }); - }); - describe('when allowOptionalDependencies config is false', () => { - beforeEach(() => { - localOptions.allowOptionalDependencies = false; - }); - it('will not ignore failed optional dependency', async () => { - await expect( - initialTraverseDependencies(localGraph, localOptions), - ).rejects.toThrow('Dependency not found: /optional-b->optional-b'); - }); + + it('missing optional dependency will be skipped', async () => { + localOptions = { + ...options, + transform: mockTransform(), + }; + + const result = await initialTraverseDependencies(localGraph, localOptions); + + const dependencies = result.added; + assertResults(dependencies, ['optional-b']); }); - describe('when allowOptionalDependencies with exclude', () => { - it('will not ignore the excluded optional dependency', async () => { - localOptions.allowOptionalDependencies = {exclude: ['optional-b']}; - await expect( - initialTraverseDependencies(localGraph, localOptions), - ).rejects.toThrow('Dependency not found: /optional-b->optional-b'); - }); - it('but will still ignore the non-excluded optional dependency', async () => { - localOptions.allowOptionalDependencies = {exclude: ['optional-d']}; - const result = await initialTraverseDependencies( - localGraph, - localOptions, - ); - - const dependencies = result.added; - - // Only `optional-b` is actually missing, - // the other optional modules `optional-c` and `optional-d` will - // still be included. - assertResults(dependencies, ['optional-b']); - }); + it('missing non-optional dependency will throw', async () => { + localOptions = { + ...options, + transform: mockTransform(['optional-b']), + }; + await expect( + initialTraverseDependencies(localGraph, localOptions), + ).rejects.toThrow(); }); }); diff --git a/packages/metro/src/DeltaBundler/traverseDependencies.js b/packages/metro/src/DeltaBundler/traverseDependencies.js index a4eaf05fb3..8e154b0617 100644 --- a/packages/metro/src/DeltaBundler/traverseDependencies.js +++ b/packages/metro/src/DeltaBundler/traverseDependencies.js @@ -18,7 +18,6 @@ import type { Module, Options, TransformResultDependency, - AllowOptionalDependencies, } from './types.flow'; type Result = { @@ -47,7 +46,6 @@ type InternalOptions = $ReadOnly<{| resolve: $PropertyType, 'resolve'>, transform: $PropertyType, 'transform'>, shallow: boolean, - allowOptionalDependencies: AllowOptionalDependencies, |}>; function getInternalOptions({ @@ -55,7 +53,6 @@ function getInternalOptions({ resolve, onProgress, experimentalImportBundleSupport, - allowOptionalDependencies, shallow, }: Options): InternalOptions { let numProcessed = 0; @@ -63,7 +60,6 @@ function getInternalOptions({ return { experimentalImportBundleSupport, - allowOptionalDependencies, transform, resolve, onDependencyAdd: () => onProgress && onProgress(numProcessed, ++total), @@ -475,12 +471,6 @@ function resolveDependencies( dependencies: $ReadOnlyArray, options: InternalOptions, ): Map { - const {allowOptionalDependencies} = options; - const required = (path: string) => - allowOptionalDependencies === false || - (Array.isArray(allowOptionalDependencies.exclude) && - allowOptionalDependencies.exclude.includes(path)); - const resolve = (parentPath: string, result: TransformResultDependency) => { const relativePath = result.name; try { @@ -492,8 +482,7 @@ function resolveDependencies( }, ]; } catch (e) { - // If this is an optional dependency, ignore the resolution error - if (result.data.isOptional === true && !required(relativePath)) { + if (result.data.isOptional === true) { // should we output some warning? verbose mode? return undefined; } diff --git a/packages/metro/src/DeltaBundler/types.flow.js b/packages/metro/src/DeltaBundler/types.flow.js index bd6a1060f2..d70e53b04e 100644 --- a/packages/metro/src/DeltaBundler/types.flow.js +++ b/packages/metro/src/DeltaBundler/types.flow.js @@ -95,7 +95,6 @@ export type Options = {| +transform: TransformFn, +onProgress: ?(numProcessed: number, total: number) => mixed, +experimentalImportBundleSupport: boolean, - +allowOptionalDependencies: AllowOptionalDependencies, +shallow: boolean, |}; diff --git a/packages/metro/src/IncrementalBundler.js b/packages/metro/src/IncrementalBundler.js index 27b6063f47..e1475c62f7 100644 --- a/packages/metro/src/IncrementalBundler.js +++ b/packages/metro/src/IncrementalBundler.js @@ -139,8 +139,6 @@ class IncrementalBundler { onProgress: otherOptions.onProgress, experimentalImportBundleSupport: this._config.transformer .experimentalImportBundleSupport, - allowOptionalDependencies: this._config.transformer - .allowOptionalDependencies, shallow: otherOptions.shallow, }); diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index c1f0e98150..e49cf156c7 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -506,6 +506,7 @@ describe('optional dependencies', () => { const myVar="my"; try { require("foo_" + myVar); + require(\`bar_\${5 + 2}\`); } catch (e) {} `); const {dependencies} = collectDependencies(ast, opts); @@ -514,31 +515,43 @@ describe('optional dependencies', () => { name: 'foo_my', data: objectContaining({isAsync: false, isOptional: true}), }, + { + name: 'bar_7', + data: objectContaining({isAsync: false, isOptional: true}), + }, ]); }); - it('controls optional dependency analysis by allowOptionalDependencies flag', () => { - const code = ` - try { - const a = require('a'); - } catch (e) {} - `; - - let options = {...opts, allowOptionalDependencies: true}; - const {dependencies: depOn} = collectDependencies( - astFromCode(code), - options, - ); - expect(depOn).toEqual([ - {name: 'a', data: objectContaining({isOptional: true})}, + it('can exclude optional dependency', () => { + const ast = () => + astFromCode(` + const n = 2; + try { + const a = require(\`A-\${1 + n}\`); + const b = require(\`A-\${3 + n}\`); + } catch (e) {} + `); + const {dependencies: deps1} = collectDependencies(ast(), opts); + expect(deps1).toEqual([ + {name: 'A-3', data: objectContaining({isOptional: true})}, + {name: 'A-5', data: objectContaining({isOptional: true})}, ]); - options = {...opts, allowOptionalDependencies: false}; - const {dependencies: depOff} = collectDependencies( - astFromCode(code), - options, - ); - expect(depOff).toEqual([ - {name: 'a', data: expect.not.objectContaining({isOptional: true})}, + const {dependencies: deps2} = collectDependencies(ast(), { + ...opts, + allowOptionalDependencies: false, + }); + expect(deps2).toEqual([ + {name: 'A-3', data: expect.not.objectContaining({isOptional: true})}, + {name: 'A-5', data: expect.not.objectContaining({isOptional: true})}, + ]); + + const {dependencies: deps3} = collectDependencies(ast(), { + ...opts, + allowOptionalDependencies: {exclude: ['A-5']}, + }); + expect(deps3).toEqual([ + {name: 'A-3', data: objectContaining({isOptional: true})}, + {name: 'A-5', data: expect.not.objectContaining({isOptional: true})}, ]); }); }); diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index ad5f6957f0..6c569981d8 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -232,8 +232,10 @@ function processImportCall(path: Path, state: State, opts: DepOptions): Path { throw new InvalidRequireCallError(path); } - const isOptional = isOptionalDependency(path, state); - const options = {...opts, isOptional}; + const options = { + ...opts, + isOptional: isOptionalDependency(name, path, state), + }; const dep = getDependency(state, name, options, path.node.loc); if (!options.prefetchOnly) { delete dep.data.isPrefetchOnly; @@ -295,11 +297,10 @@ function processRequireCall(path: Path, state: State): Path { return path; } - const isOptional = isOptionalDependency(path, state); const dep = getDependency( state, name, - {prefetchOnly: false, isOptional}, + {prefetchOnly: false, isOptional: isOptionalDependency(name, path, state)}, path.node.loc, ); dep.data.isAsync = false; @@ -354,8 +355,18 @@ function getDependency( return {index: nullthrows(index), data: nullthrows(data)}; } -const isOptionalDependency = (path: Path, state: State): boolean => { - if (!state.allowOptionalDependencies) { +const isOptionalDependency = ( + name: string, + path: Path, + state: State, +): boolean => { + const {allowOptionalDependencies} = state; + + const isExcluded = () => + Array.isArray(allowOptionalDependencies.exclude) && + allowOptionalDependencies.exclude.includes(name); + + if (!allowOptionalDependencies || isExcluded()) { return false; } diff --git a/packages/metro/src/Server/__tests__/Server-test.js b/packages/metro/src/Server/__tests__/Server-test.js index 95f5f10133..b0458b8486 100644 --- a/packages/metro/src/Server/__tests__/Server-test.js +++ b/packages/metro/src/Server/__tests__/Server-test.js @@ -460,7 +460,6 @@ describe('processRequest', () => { resolve: expect.any(Function), shallow: false, transform: expect.any(Function), - allowOptionalDependencies: false, }, ); }); @@ -595,7 +594,6 @@ describe('processRequest', () => { resolve: expect.any(Function), shallow: false, transform: expect.any(Function), - allowOptionalDependencies: false, }, ); }); diff --git a/packages/metro/src/lib/getPrependedScripts.js b/packages/metro/src/lib/getPrependedScripts.js index 385f522cef..01e9c22202 100644 --- a/packages/metro/src/lib/getPrependedScripts.js +++ b/packages/metro/src/lib/getPrependedScripts.js @@ -59,7 +59,6 @@ async function getPrependedScripts( onProgress: null, experimentalImportBundleSupport: config.transformer.experimentalImportBundleSupport, - allowOptionalDependencies: config.transformer.allowOptionalDependencies, shallow: false, }, ); diff --git a/packages/metro/src/lib/transformHelpers.js b/packages/metro/src/lib/transformHelpers.js index d77f19b480..cd437ea0f6 100644 --- a/packages/metro/src/lib/transformHelpers.js +++ b/packages/metro/src/lib/transformHelpers.js @@ -73,7 +73,6 @@ async function calcTransformerOptions( onProgress: null, experimentalImportBundleSupport: config.transformer.experimentalImportBundleSupport, - allowOptionalDependencies: config.transformer.allowOptionalDependencies, shallow: false, }); From 96c5663e8f33ca67fa6ce78fe5108461f76379c6 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Thu, 5 Mar 2020 10:23:33 +0000 Subject: [PATCH 3/4] Update types.flow.js --- packages/metro/src/DeltaBundler/types.flow.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/metro/src/DeltaBundler/types.flow.js b/packages/metro/src/DeltaBundler/types.flow.js index d70e53b04e..5603783b80 100644 --- a/packages/metro/src/DeltaBundler/types.flow.js +++ b/packages/metro/src/DeltaBundler/types.flow.js @@ -43,7 +43,7 @@ export type TransformResultDependency = {| +mobileConfigName: string, |}, /** - * The dependency is enclosed in a try/catch block, indicated optional + * The dependency is enclosed in a try/catch block. */ +isOptional?: boolean, From 58ac257042b5c3493e1ab48c3524e3db274abb23 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Thu, 5 Mar 2020 12:03:31 +0000 Subject: [PATCH 4/4] Update traverseDependencies.js --- .../metro/src/DeltaBundler/traverseDependencies.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/metro/src/DeltaBundler/traverseDependencies.js b/packages/metro/src/DeltaBundler/traverseDependencies.js index 8e154b0617..a7aab8c960 100644 --- a/packages/metro/src/DeltaBundler/traverseDependencies.js +++ b/packages/metro/src/DeltaBundler/traverseDependencies.js @@ -481,12 +481,12 @@ function resolveDependencies( data: result, }, ]; - } catch (e) { - if (result.data.isOptional === true) { - // should we output some warning? verbose mode? - return undefined; + } catch (error) { + // Ignore unavailable optional dependencies. They are guarded + // with a try-catch block and will be handled during runtime. + if (result.data.isOptional !== true) { + throw error; } - throw e; } };