Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 24 additions & 22 deletions packages/metro/src/DeltaBundler/Graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
* nodes and entries in the importBundleNodes set.
*/

import type {RequireContext} from '../lib/contextModule';
import type {RequireContextParams} from '../ModuleGraph/worker/collectDependencies';
import type {
Dependencies,
Expand All @@ -41,6 +40,7 @@ import type {
Options,
ResolvedDependency,
TransformInputOptions,
VirtualSource,
} from './types';

import {fileMatchesContext} from '../lib/contextModule';
Expand Down Expand Up @@ -149,8 +149,11 @@ export class Graph<T = MixedOutput> {
possibleCycleRoots: new Set(),
};

/** Resolved context parameters from `require.context`. */
#resolvedContexts: Map<string, RequireContext> = new Map();
/**
* Sources of the modules in the graph that have no file, keyed by module
* path.
*/
#virtualSources: Map<string, VirtualSource> = new Map();

constructor(options: GraphInputOptions) {
this.entryPoints = options.entryPoints;
Expand Down Expand Up @@ -348,17 +351,17 @@ export class Graph<T = MixedOutput> {
options: InternalOptions<T>,
moduleFilter?: (path: string) => boolean,
): Promise<Delta<T>> {
const subGraph = await buildSubgraph(pathsToVisit, this.#resolvedContexts, {
const subGraph = await buildSubgraph(pathsToVisit, this.#virtualSources, {
resolve: options.resolve,
shouldTraverse: (dependency: ResolvedDependency) => {
if (options.shallow || isWeakOrLazy(dependency, options)) {
return false;
}
return moduleFilter == null || moduleFilter(dependency.absolutePath);
},
transform: async (absolutePath, requireContext) => {
transform: async (absolutePath, virtualSource) => {
options.onDependencyAdd();
const result = await options.transform(absolutePath, requireContext);
const result = await options.transform(absolutePath, virtualSource);
options.onDependencyAdded();
return result;
},
Expand Down Expand Up @@ -394,7 +397,7 @@ export class Graph<T = MixedOutput> {
const previousDependencies = previousModule?.dependencies ?? new Map();
const {
dependencies: currentDependencies,
resolvedContexts,
virtualSources,
...transformResult
} = currentModule;

Expand Down Expand Up @@ -449,7 +452,7 @@ export class Graph<T = MixedOutput> {
nextModule,
key,
curDependency,
resolvedContexts.get(key),
virtualSources.get(key),
delta,
options,
);
Expand Down Expand Up @@ -507,7 +510,7 @@ export class Graph<T = MixedOutput> {
parentModule: Module<T>,
key: string,
dependency: Dependency,
requireContext: ?RequireContext,
virtualSource: ?VirtualSource,
delta: Delta<T>,
options: InternalOptions<T>,
): void {
Expand Down Expand Up @@ -555,12 +558,12 @@ export class Graph<T = MixedOutput> {

if (isResolvedDependency(dependency)) {
const path = dependency.absolutePath;
if (requireContext) {
this.#resolvedContexts.set(path, requireContext);
if (virtualSource) {
this.#virtualSources.set(path, virtualSource);
} else {
// This dependency may have existed previously as a require.context -
// clean it up.
this.#resolvedContexts.delete(path);
this.#virtualSources.delete(path);
}
}

Expand Down Expand Up @@ -623,10 +626,11 @@ export class Graph<T = MixedOutput> {
filePath: string,
modifiedPaths: Set<string> | CountingSet<string>,
) {
for (const [absolutePath, context] of this.#resolvedContexts) {
for (const [absolutePath, virtualSource] of this.#virtualSources) {
if (
virtualSource.type === 'requireContext' &&
!modifiedPaths.has(absolutePath) &&
fileMatchesContext(filePath, context)
fileMatchesContext(filePath, virtualSource.requireContext)
) {
modifiedPaths.add(absolutePath);
}
Expand Down Expand Up @@ -761,23 +765,21 @@ export class Graph<T = MixedOutput> {
const {dependencies, getSource, output, unstable_transformResultKey} =
module;

const resolvedContexts: Map<string, RequireContext> = new Map();
const virtualSources: Map<string, VirtualSource> = new Map();
for (const [key, dependency] of dependencies) {
if (!isResolvedDependency(dependency)) {
continue;
}
const resolvedContext = this.#resolvedContexts.get(
dependency.absolutePath,
);
if (resolvedContext != null) {
resolvedContexts.set(key, resolvedContext);
const virtualSource = this.#virtualSources.get(dependency.absolutePath);
if (virtualSource != null) {
virtualSources.set(key, virtualSource);
}
}
return {
dependencies: new Map(dependencies),
getSource,
output,
resolvedContexts,
virtualSources,
unstable_transformResultKey,
};
}
Expand Down Expand Up @@ -828,7 +830,7 @@ export class Graph<T = MixedOutput> {
this.dependencies.delete(module.path);
this.#gc.possibleCycleRoots.delete(module.path);
this.#gc.color.delete(module.path);
this.#resolvedContexts.delete(module.path);
this.#virtualSources.delete(module.path);
}

// Mark a module as a possible cycle root
Expand Down
34 changes: 20 additions & 14 deletions packages/metro/src/DeltaBundler/__tests__/Graph-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
* boxes/lines as needed).
*/

import type {RequireContext} from '../../lib/contextModule';
import type {RequireContextParams} from '../../ModuleGraph/worker/collectDependencies';
import type {Result} from '../Graph';
import type {
Expand All @@ -46,6 +45,7 @@ import type {
TransformFn,
TransformResultDependency,
TransformResultWithSource,
VirtualSource,
} from '../types';

import {deriveAbsolutePathFromContext} from '../../lib/contextModule';
Expand Down Expand Up @@ -357,10 +357,10 @@ beforeEach(async () => {

mockTransform = jest
.fn<
[string, ?RequireContext],
[string, ?VirtualSource],
Promise<TransformResultWithSource<MixedOutput>>,
>()
.mockImplementation(async (path: string, context: ?RequireContext) => {
.mockImplementation(async (path: string, context: ?VirtualSource) => {
const override = transformOverrides.get(path);
if (override != null) {
return override(path, context);
Expand Down Expand Up @@ -556,7 +556,7 @@ test('should retry traversing dependencies after a transform error', async () =>

const localOptions = {
...options,
transform(path: string, context: ?RequireContext) {
transform(path: string, context: ?VirtualSource) {
if (path === '/bad') {
throw new BadError();
}
Expand Down Expand Up @@ -2351,7 +2351,7 @@ describe('edge cases', () => {
let fastResolved = false;

localMockTransform.mockImplementation(
async (path: string, context: ?RequireContext) => {
async (path: string, context: ?VirtualSource) => {
const result = await mockTransform(path, context);

if (path === slowPath && !fastResolved) {
Expand Down Expand Up @@ -2967,10 +2967,13 @@ describe('require.context', () => {
};

const ctxResolved = {
recursive: true,
mode: 'sync',
filter: /.*/,
from: p('/ctx'),
type: 'requireContext',
requireContext: {
recursive: true,
mode: 'sync',
filter: /.*/,
from: p('/ctx'),
},
};

const ctxPath = deriveAbsolutePathFromContext(p('/ctx'), ctxParams);
Expand Down Expand Up @@ -3301,10 +3304,13 @@ describe('require.context', () => {
};

const narrowCtxResolved = {
recursive: true,
mode: 'sync',
filter: /\.\/narrow\/.*/,
from: p('/ctx'),
type: 'requireContext',
requireContext: {
recursive: true,
mode: 'sync',
filter: /\.\/narrow\/.*/,
from: p('/ctx'),
},
};

const narrowCtxPath = deriveAbsolutePathFromContext(
Expand Down Expand Up @@ -3592,7 +3598,7 @@ describe('optional dependencies', () => {
const createMockTransform = (notOptional?: string[]) => {
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
return async function (path: string, context: ?RequireContext) {
return async function (path: string, context: ?VirtualSource) {
const result = await mockTransform.call(this, path, context);
return {
...result,
Expand Down
18 changes: 12 additions & 6 deletions packages/metro/src/DeltaBundler/__tests__/buildSubgraph-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ describe('GraphTraversal', () => {
]),
getSource: expect.any(Function),
output: [],
resolvedContexts: new Map(),
virtualSources: new Map(),
});
});

Expand All @@ -139,7 +139,7 @@ describe('GraphTraversal', () => {
};
expect(params.transform).toHaveBeenCalledWith(
p('/virtual?ctx=af3bf59b8564d441084c02bdf04c4d662d74d3bd'),
expectedResolvedContext,
{type: 'requireContext', requireContext: expectedResolvedContext},
);
expect(params.transform).toHaveBeenCalledWith(
p('/contextMatch'),
Expand Down Expand Up @@ -167,8 +167,14 @@ describe('GraphTraversal', () => {
},
],
]),
resolvedContexts: new Map([
['key-virtual', expectedResolvedContext],
virtualSources: new Map([
[
'key-virtual',
{
type: 'requireContext',
requireContext: expectedResolvedContext,
},
],
]),
output: [],
getSource: expect.any(Function),
Expand All @@ -178,7 +184,7 @@ describe('GraphTraversal', () => {
p('/contextMatch'),
{
dependencies: new Map(),
resolvedContexts: new Map(),
virtualSources: new Map(),
output: [],
getSource: expect.any(Function),
},
Expand All @@ -201,7 +207,7 @@ describe('GraphTraversal', () => {
},
],
]),
resolvedContexts: new Map(),
virtualSources: new Map(),
output: [],
getSource: expect.any(Function),
},
Expand Down
22 changes: 13 additions & 9 deletions packages/metro/src/DeltaBundler/buildSubgraph.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type {
ResolveFn,
TransformFn,
TransformResultDependency,
VirtualSource,
} from './types';

import {deriveAbsolutePathFromContext} from '../lib/contextModule';
Expand All @@ -34,10 +35,10 @@ function resolveDependencies(
resolve: ResolveFn,
): {
dependencies: Map<string, Dependency>,
resolvedContexts: Map<string, RequireContext>,
virtualSources: Map<string, VirtualSource>,
} {
const maybeResolvedDeps = new Map<string, Dependency>();
const resolvedContexts = new Map<string, RequireContext>();
const virtualSources = new Map<string, VirtualSource>();

for (const dep of dependencies) {
let maybeResolvedDep: Dependency;
Expand All @@ -61,7 +62,10 @@ function resolveDependencies(
recursive: contextParams.recursive,
};

resolvedContexts.set(key, resolvedContext);
virtualSources.set(key, {
type: 'requireContext',
requireContext: resolvedContext,
});

maybeResolvedDep = {
absolutePath,
Expand Down Expand Up @@ -95,13 +99,13 @@ function resolveDependencies(

return {
dependencies: maybeResolvedDeps,
resolvedContexts,
virtualSources,
};
}

export async function buildSubgraph<T>(
entryPaths: ReadonlySet<string>,
resolvedContexts: ReadonlyMap<string, ?RequireContext>,
virtualSources: ReadonlyMap<string, ?VirtualSource>,
{resolve, transform, shouldTraverse}: Parameters<T>,
): Promise<{
moduleData: Map<string, ModuleData<T>>,
Expand All @@ -113,13 +117,13 @@ export async function buildSubgraph<T>(

async function visit(
absolutePath: string,
requireContext: ?RequireContext,
virtualSource: ?VirtualSource,
): Promise<void> {
if (visitedPaths.has(absolutePath)) {
return;
}
visitedPaths.add(absolutePath);
const transformResult = await transform(absolutePath, requireContext);
const transformResult = await transform(absolutePath, virtualSource);

// Get the absolute path of all sub-dependencies (some of them could have been
// moved but maintain the same relative path).
Expand All @@ -143,15 +147,15 @@ export async function buildSubgraph<T>(
.map(dependency =>
visit(
dependency.absolutePath,
resolutionResult.resolvedContexts.get(dependency.data.data.key),
resolutionResult.virtualSources.get(dependency.data.data.key),
).catch(error => errors.set(dependency.absolutePath, error)),
),
);
}

await Promise.all(
[...entryPaths].map(absolutePath =>
visit(absolutePath, resolvedContexts.get(absolutePath)).catch(error =>
visit(absolutePath, virtualSources.get(absolutePath)).catch(error =>
errors.set(absolutePath, error),
),
),
Expand Down
Loading
Loading