Skip to content

fix(node): enhance error messaging for fetchAndRun with url #3729

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
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
5 changes: 5 additions & 0 deletions .changeset/late-maps-exist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@module-federation/node': minor
---

enhance error messaging for fetchAndRun with url
Binary file added __mocks__/remotes/fsevents-X6WP4TKM.node
Binary file not shown.
273,121 changes: 273,121 additions & 0 deletions __mocks__/remotes/index.js

Large diffs are not rendered by default.

58 changes: 53 additions & 5 deletions packages/node/src/__tests__/runtimePlugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@ jest.mock('vm', () => ({
},
}));

global.fetch = jest.fn().mockResolvedValue({
(global as unknown as any).fetch = jest.fn().mockResolvedValue({
text: jest.fn().mockResolvedValue('// mock chunk content'),
});
const globalFetch = (global as unknown as any).fetch as jest.Mock;

const mockWebpackRequire = {
u: jest.fn((chunkId: string) => `/chunks/${chunkId}.js`),
Expand Down Expand Up @@ -77,7 +78,7 @@ const mockNonWebpackRequire = jest.fn().mockImplementation((id: string) => {
if (id === 'path') return require('path');
if (id === 'fs') return require('fs');
if (id === 'vm') return require('vm');
if (id === 'node-fetch') return { default: global.fetch };
if (id === 'node-fetch') return { default: globalFetch };
return {};
});

Expand Down Expand Up @@ -343,11 +344,11 @@ describe('runtimePlugin', () => {

describe('fetchAndRun', () => {
beforeEach(() => {
(global.fetch as jest.Mock).mockReset();
(globalFetch as jest.Mock).mockReset();
});

it('should fetch and execute remote content', async () => {
(global.fetch as jest.Mock).mockResolvedValue({
(globalFetch as jest.Mock).mockResolvedValue({
text: jest.fn().mockResolvedValue('// mock script content'),
});

Expand Down Expand Up @@ -381,7 +382,7 @@ describe('runtimePlugin', () => {

it('should handle fetch errors', async () => {
const fetchError = new Error('Fetch failed');
(global.fetch as jest.Mock).mockRejectedValue(fetchError);
(globalFetch as jest.Mock).mockRejectedValue(fetchError);

const url = new URL('http://example.com/chunk.js');
const callback = jest.fn();
Expand All @@ -403,6 +404,9 @@ describe('runtimePlugin', () => {
await new Promise((resolve) => setTimeout(resolve, 10));

expect(callback).toHaveBeenCalledWith(expect.any(Error), null);
expect(callback.mock.calls[0][0].message.includes(url.href)).toEqual(
true,
);
});
});

Expand Down Expand Up @@ -746,6 +750,50 @@ describe('runtimePlugin', () => {
// The original promise should be reused
expect(promises[0]).toBe(originalPromise);
});

it('should delete chunks from the installedChunks when loadChunk fails', async () => {
// mock loadChunk to fail
jest
.spyOn(runtimePluginModule, 'loadChunk')
.mockImplementationOnce((strategy, chunkId, root, callback, args) => {
Promise.resolve().then(() => {
callback(new Error('failed to load'), undefined);
});
});

jest
.spyOn(runtimePluginModule, 'installChunk')
.mockImplementationOnce((chunk, installedChunks) => {
// Mock implementation that doesn't rely on iterating chunk.ids
installedChunks['test-chunk'] = 0;
});

// Mock installedChunks
const installedChunks: Record<string, any> = {};

// Call the function under test - returns the handler function, doesn't set webpack_require.f.require
const handler = setupChunkHandler(installedChunks, {});

const promises: Promise<any>[] = [];
let res, err;

try {
// Call the handler with mock chunk ID and promises array
handler('test-chunk', promises);
// Verify that installedChunks has test-chunk before the promise rejects
expect(installedChunks['test-chunk']).toBeDefined();
res = await promises[0];
} catch (e) {
err = e;
}

// Verify that an error was thrown, and the response is undefined
expect(res).not.toBeDefined();
expect(err instanceof Error).toEqual(true);

// Verify the chunk data was properly removed
expect(installedChunks['test-chunk']).not.toBeDefined();
});
});

describe('setupWebpackRequirePatching', () => {
Expand Down
17 changes: 11 additions & 6 deletions packages/node/src/runtimePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import type {
FederationRuntimePlugin,
FederationHost,
} from '@module-federation/runtime';
import { Response } from 'node-fetch';

type WebpackRequire = {
(id: string): any;
u: (chunkId: string) => string;
Expand Down Expand Up @@ -125,26 +127,29 @@ export const loadFromFs = (
callback(new Error(`File ${filename} does not exist`), null);
}
};

// Hoisted utility function to fetch and execute chunks from remote URLs
export const fetchAndRun = (
url: URL,
chunkName: string,
callback: (err: Error | null, chunk: any) => void,
args: any,
): void => {
(typeof fetch === 'undefined'
const createFetchError = (e: Error) =>
new Error(`Error while fetching from URL: ${url}`, { cause: e });
(typeof (global as any).fetch === 'undefined'
? importNodeModule<typeof import('node-fetch')>('node-fetch').then(
(mod) => mod.default,
)
: Promise.resolve(fetch)
: Promise.resolve((global as any).fetch)
)
.then((fetchFunction) => {
return args.origin.loaderHook.lifecycle.fetch
.emit(url.href, {})
.then((res: Response | null) => {
if (!res || !(res instanceof Response)) {
return fetchFunction(url.href).then((response) => response.text());
return fetchFunction(url.href).then((response: Response) =>
response.text(),
);
}
return res.text();
});
Expand All @@ -160,10 +165,10 @@ export const fetchAndRun = (
);
callback(null, chunk);
} catch (e) {
callback(e as Error, null);
callback(createFetchError(e as Error), null);
}
})
.catch((err: Error) => callback(err, null));
.catch((err: Error) => callback(createFetchError(err as Error), null));
};

// Hoisted utility function to resolve URLs for chunks
Expand Down
6 changes: 5 additions & 1 deletion packages/node/src/utils/flush-chunks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/* eslint-disable no-undef */

import { Response } from 'node-fetch';

// @ts-ignore
if (!globalThis.usedChunks) {
// @ts-ignore
Expand Down Expand Up @@ -121,7 +123,9 @@ const processChunk = async (chunk, shareMap, hostStats) => {
let stats = {};

try {
stats = await fetch(statsFile).then((res) => res.json());
stats = await (global as any)
.fetch(statsFile)
.then((res: Response) => res.json());
} catch (e) {
console.error('flush error', e);
}
Expand Down
1 change: 1 addition & 0 deletions packages/node/src/utils/hot-reload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { getAllKnownRemotes } from './flush-chunks';
import crypto from 'crypto';
import helpers from '@module-federation/runtime/helpers';
import path from 'path';
import { Response } from 'node-fetch';

declare global {
var mfHashMap: Record<string, string> | undefined;
Expand Down
1 change: 1 addition & 0 deletions packages/node/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"target": "ES2021",
"lib": ["es2022.error"],
"moduleResolution": "node",
"resolveJsonModule": true,
"skipLibCheck": true,
Expand Down
Loading