Skip to content
Merged
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
16 changes: 11 additions & 5 deletions packages/metro/src/Bundler.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type EventEmitter from 'node:events';

import Transformer from './DeltaBundler/Transformer';
import DependencyGraph from './node-haste/DependencyGraph';
import nullthrows from 'nullthrows';

export type BundlerOptions = Readonly<{
hasReducedPerformance?: boolean,
Expand All @@ -25,7 +26,7 @@ export type BundlerOptions = Readonly<{
export default class Bundler {
_depGraph: DependencyGraph;
_initializedPromise: Promise<void>;
_transformer: Transformer;
_transformer: ?Transformer;

constructor(config: ConfigT, options?: BundlerOptions) {
this._depGraph = new DependencyGraph(config, options);
Expand Down Expand Up @@ -59,10 +60,15 @@ export default class Bundler {
}

async end(): Promise<void> {
await this.ready();
// Initialization errors are surfaced by ready() and the reporter, and
// shouldn't prevent teardown of whatever was started.
await this._initializedPromise.catch(() => {});

await this._transformer.end();
await this._depGraph.end();
try {
await this._transformer?.end();
} finally {
await this._depGraph.end();
}
}

async getDependencyGraph(): Promise<DependencyGraph> {
Expand All @@ -81,7 +87,7 @@ export default class Bundler {
// TODO: Remove this ugly hack!
await this.ready();

return this._transformer.transformFile(
return nullthrows(this._transformer).transformFile(
filePath,
transformOptions,
fileBuffer,
Expand Down
5 changes: 3 additions & 2 deletions packages/metro/src/DeltaBundler/Transformer.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,6 @@ export default class Transformer {
transformerConfig,
};

this._workerFarm = new WorkerFarm(config, transformerOptions);

const globalCacheKey = this._cache.isDisabled
? ''
: getTransformCacheKey({
Expand All @@ -74,6 +72,9 @@ export default class Transformer {
const baseHashBuffer = stableHash([globalCacheKey]);
this._baseHash = baseHashBuffer.toString('binary');
debug('Base hash: %s', baseHashBuffer.toString('hex'));

// Start workers last - nothing can end them if the constructor throws.
this._workerFarm = new WorkerFarm(config, transformerOptions);
}

async transformFile(
Expand Down
22 changes: 22 additions & 0 deletions packages/metro/src/DeltaBundler/__tests__/Transformer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -215,4 +215,26 @@ describe('Transformer', function () {

expect(require('../getTransformCacheKey')).not.toBeCalled();
});

test('does not start workers if the transformer cache key throws', () => {
const error = new Error("Cannot find module 'babel-preset-expo'");
require('../getTransformCacheKey').mockImplementationOnce(() => {
throw error;
});
const WorkerFarm = require('../WorkerFarm').default;
WorkerFarm.mockClear();

expect(
() =>
new Transformer(
{
...commonOptions,
cacheStores: [{get: jest.fn(), set: jest.fn()}],
watchFolders,
},
{getOrComputeSha1},
),
).toThrow(error);
expect(WorkerFarm).not.toBeCalled();
});
});
39 changes: 39 additions & 0 deletions packages/metro/src/__tests__/Bundler-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,16 @@ const MockDependencyGraph: ClassMock = DependencyGraph;
describe('Bundler', () => {
let config: ConfigT;
let reporter;
let depGraphEnd;

beforeEach(() => {
reporter = {update: jest.fn()};
config = {...getDefaultConfig.getDefaultValues('/'), reporter};

depGraphEnd = jest.fn().mockResolvedValue();
MockDependencyGraph.mockImplementation(() => ({
ready: jest.fn().mockResolvedValue(),
end: depGraphEnd,
}));

jest.spyOn(console, 'error').mockImplementation(() => {});
Expand Down Expand Up @@ -70,6 +73,42 @@ describe('Bundler', () => {
},
);

test('ends the dependency graph when Transformer initialization fails', async () => {
MockTransformer.mockImplementation(() => {
throw new Error('Transformer initialization failed');
});

const bundler = new Bundler(config);

await expect(bundler.end()).resolves.toBeUndefined();
expect(depGraphEnd).toHaveBeenCalledTimes(1);
});

test('ends the Transformer and dependency graph after initialization', async () => {
const transformerEnd = jest.fn().mockResolvedValue();
MockTransformer.mockImplementation(() => ({end: transformerEnd}));

const bundler = new Bundler(config);
await bundler.ready();
await bundler.end();

expect(transformerEnd).toHaveBeenCalledTimes(1);
expect(depGraphEnd).toHaveBeenCalledTimes(1);
});

test('ends the dependency graph when ending the Transformer fails', async () => {
const error = new Error('Farm is ended');
MockTransformer.mockImplementation(() => ({
end: jest.fn().mockRejectedValue(error),
}));

const bundler = new Bundler(config);
await bundler.ready();

await expect(bundler.end()).rejects.toBe(error);
expect(depGraphEnd).toHaveBeenCalledTimes(1);
});

test('does not emit an unhandled rejection before ready is called', async () => {
jest.useRealTimers();

Expand Down
3 changes: 2 additions & 1 deletion packages/metro/src/node-haste/DependencyGraph.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,8 @@ export default class DependencyGraph extends EventEmitter {
}

async end() {
await this.ready();
// A failed build is surfaced by ready(), and shouldn't prevent teardown.
await this._initializedPromise.catch(() => {});
await this._haste.end();
}

Expand Down
56 changes: 56 additions & 0 deletions packages/metro/src/node-haste/__tests__/DependencyGraph-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall react_native
*/

import type {ConfigT} from 'metro-config';

import DependencyGraph from '../DependencyGraph';
import createFileMap from '../DependencyGraph/createFileMap';
import {getDefaultConfig} from 'metro-config';

jest.mock('../DependencyGraph/createFileMap');

type FunctionMock = JestMockFn<ReadonlyArray<unknown>, unknown>;

// $FlowFixMe[incompatible-type] Jest automocks the default export
const mockCreateFileMap: FunctionMock = createFileMap;

describe('DependencyGraph', () => {
let config: ConfigT;
let fileMapEnd;

beforeEach(() => {
config = {
...getDefaultConfig.getDefaultValues('/'),
reporter: {update: jest.fn()},
};
fileMapEnd = jest.fn().mockResolvedValue();
});

test('ends the file map when the build fails', async () => {
const error = new Error('Crawl failed');
mockCreateFileMap.mockReturnValue({
fileMap: {
build: jest.fn().mockRejectedValue(error),
end: fileMapEnd,
on: jest.fn(),
setMaxListeners: jest.fn(),
},
hasteMap: {},
dependencyPlugin: null,
});

const depGraph = new DependencyGraph(config);

await expect(depGraph.ready()).rejects.toBe(error);
await expect(depGraph.end()).resolves.toBeUndefined();
expect(fileMapEnd).toHaveBeenCalledTimes(1);
});
});
Loading