Skip to content

Commit e4b3c45

Browse files
fix(platform): zone.js detection, worker-preset externals, per-request SSR fetch (#2772)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent fb28994 commit e4b3c45

4 files changed

Lines changed: 144 additions & 13 deletions

File tree

‎packages/platform/src/lib/nitro/analog-nitro-plugin.spec.ts‎

Lines changed: 72 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
22
import { tmpdir } from 'node:os';
33
import { join } from 'node:path';
4+
import { getProxyRequestHeaders } from 'h3';
45
import { createRouteRulesMatcher } from 'h3/rules';
6+
import { createFetch } from 'ofetch';
57
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
68

79
import {
@@ -303,6 +305,39 @@ describe('analogNitroPlugin', () => {
303305
expect(hookFn).toHaveBeenCalledWith('build:config', expect.any(Function));
304306
});
305307

308+
it.each([
309+
[{ node: true }, true],
310+
[{ node: false, noExternals: true }, false],
311+
[{ node: true, noExternals: true }, false],
312+
[{ node: false }, false],
313+
])(
314+
'externalizes rxjs only for presets with a module resolver (%o)',
315+
async (presetOptions, externalized) => {
316+
const plugin = analogNitroPlugin({ workspaceRoot });
317+
callConfig(plugin, projectRoot);
318+
const hooks: Record<string, (...args: any[]) => unknown> = {};
319+
await (plugin as any).nitro.setup({
320+
options: {
321+
rootDir: projectRoot,
322+
buildDir: join(projectRoot, '.nitro'),
323+
handlers: [],
324+
scanDirs: [],
325+
virtual: {},
326+
renderer: {},
327+
...presetOptions,
328+
},
329+
hooks: { hook: (name: string, fn: any) => (hooks[name] = fn) },
330+
});
331+
332+
const rolldown: any = { plugins: [], output: {} };
333+
hooks['build:config'](undefined, { rolldown });
334+
335+
expect(
336+
(rolldown.external ?? []).some((p: RegExp) => p.test('rxjs')),
337+
).toBe(externalized);
338+
},
339+
);
340+
306341
it('resolves a built SSR entry emitted with a .js extension', async () => {
307342
const buildDir = join(projectRoot, '.nitro');
308343
const ssrDir = join(buildDir, 'vite/services/ssr');
@@ -472,20 +507,54 @@ describe('analogNitroPlugin', () => {
472507
vi.restoreAllMocks();
473508
});
474509

475-
function createEntry(renderer: (...args: any[]) => unknown) {
510+
function createEntry(
511+
renderer: (...args: any[]) => unknown,
512+
nitroServerFetch = vi.fn(),
513+
) {
476514
vi.stubGlobal('$fetch', vi.fn());
477515
const plugin = analogNitroPlugin({ workspaceRoot });
478516
callConfig(plugin, projectRoot, 'serve');
479517
return runModule(
480518
callLoad(plugin, '\0virtual:@analogjs/nitro/ssr-entry'),
481519
{
482-
nitroServerFetch: vi.fn(),
483-
createFetch: () => vi.fn(),
520+
nitroServerFetch,
521+
getProxyRequestHeaders,
522+
createFetch,
484523
renderer,
485524
},
486525
);
487526
}
488527

528+
it('forwards the request headers and signal to in-process fetches', async () => {
529+
const nitroServerFetch = vi.fn(async () => Response.json({}));
530+
const entry = createEntry(async (_url, _template, ctx) => {
531+
await ctx.fetch('/api/data', { headers: { accept: 'text/plain' } });
532+
return '<html></html>';
533+
}, nitroServerFetch);
534+
const abort = new AbortController();
535+
536+
await entry.fetch(
537+
new Request('http://localhost/x', {
538+
headers: {
539+
authorization: 'Bearer token',
540+
accept: 'text/html',
541+
'keep-alive': 'timeout=5',
542+
'if-none-match': '"page"',
543+
},
544+
signal: abort.signal,
545+
}),
546+
);
547+
const [url, init] = nitroServerFetch.mock.calls[0] as any[];
548+
abort.abort();
549+
550+
expect(url).toBe('http://localhost/api/data');
551+
expect(init.headers.get('authorization')).toBe('Bearer token');
552+
expect(init.headers.get('accept')).toBe('text/plain');
553+
expect(init.headers.has('keep-alive')).toBe(false);
554+
expect(init.headers.has('if-none-match')).toBe(false);
555+
expect(init.signal.aborted).toBe(true);
556+
});
557+
489558
it('responds with the status of a failed render', async () => {
490559
const entry = createEntry(() => {
491560
throw Object.assign(new Error('Not found'), { statusCode: 404 });

‎packages/platform/src/lib/nitro/analog-nitro-plugin.ts‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -546,7 +546,11 @@ export function analogNitroPlugin(options: Options = {}): Plugin {
546546
serverFnIdPlugin(resolve(context.workspaceRoot, context.rootDir)),
547547
);
548548
}
549-
applyAnalogNitroExternals(rollupConfig);
549+
// Same rule as Nitro's own externals: worker presets ship a single
550+
// self-contained bundle with no module resolver.
551+
if (nitro.options.node && nitro.options.noExternals !== true) {
552+
applyAnalogNitroExternals(rollupConfig);
553+
}
550554
sanitizeNitroBundlerConfig(rollupConfig);
551555
});
552556

@@ -942,6 +946,7 @@ function generateSsrEntryWrapper(
942946
// as event replay on the server.
943947
import ${JSON.stringify(SERVER_MODE_ID)};
944948
import { serverFetch as nitroServerFetch } from 'nitro';
949+
import { getProxyRequestHeaders } from 'nitro/h3';
945950
import { createFetch } from 'ofetch';
946951
import renderer from ${JSON.stringify(entryServer)};
947952
@@ -980,6 +985,34 @@ if (typeof globalThis.$fetch === 'undefined') {
980985
globalThis.$fetch = ssrOFetch;
981986
}
982987
988+
// Like h3's fetchWithEvent: in-process requests carry the incoming request's
989+
// headers (minus hop-by-hop) and are cancelled with it. Conditional and range
990+
// headers describe the document, not the data it loads.
991+
const DOCUMENT_ONLY_HEADERS = [
992+
'if-match',
993+
'if-none-match',
994+
'if-modified-since',
995+
'if-unmodified-since',
996+
'if-range',
997+
'range',
998+
];
999+
const requestOFetch = (req) =>
1000+
createFetch({
1001+
fetch: (resource, init) => {
1002+
const headers = new Headers(
1003+
getProxyRequestHeaders(
1004+
{ req },
1005+
{ host: true, filterHeaders: DOCUMENT_ONLY_HEADERS },
1006+
),
1007+
);
1008+
new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
1009+
const signal = init?.signal
1010+
? AbortSignal.any([req.signal, init.signal])
1011+
: req.signal;
1012+
return ssrFetch(resource, { ...init, headers, signal });
1013+
},
1014+
});
1015+
9831016
export default {
9841017
async fetch(req) {
9851018
const url = new URL(req.url);
@@ -1024,7 +1057,7 @@ export default {
10241057
// router's request-context interceptor via \`serverFetch.raw(...)\`,
10251058
// which is ofetch's response-shape API. Plain fetch lacks \`.raw\`
10261059
// and throws TypeError during prerender/SSR.
1027-
fetch: ssrOFetch,
1060+
fetch: requestOFetch(req),
10281061
signal: req.signal,
10291062
waitUntil: req.waitUntil?.bind(req),
10301063
renderErrorsAsHtml: true,

‎packages/platform/src/lib/nitro/server-fn-endpoints.spec.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { mkdtempSync } from 'node:fs';
1+
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
2+
import Module from 'node:module';
23
import { tmpdir } from 'node:os';
34
import { join } from 'node:path';
45
import { fileURLToPath } from 'node:url';
@@ -25,4 +26,30 @@ describe('buildServerFnDispatchModule', () => {
2526
expect(src).not.toContain('zone.js');
2627
expect(src).toContain(`import '@angular/platform-server/init';`);
2728
});
29+
30+
it('ignores a zone.js only reachable through NODE_PATH', () => {
31+
const nodePath = mkdtempSync(join(tmpdir(), 'analog-node-path-'));
32+
mkdirSync(join(nodePath, 'zone.js'));
33+
writeFileSync(join(nodePath, 'zone.js/package.json'), '{}');
34+
writeFileSync(join(nodePath, 'zone.js/node.js'), '');
35+
const initPaths = (Module as unknown as { _initPaths: () => void })
36+
._initPaths;
37+
const previous = process.env['NODE_PATH'];
38+
process.env['NODE_PATH'] = nodePath;
39+
initPaths();
40+
try {
41+
const src = buildServerFnDispatchModule({
42+
modules,
43+
root: mkdtempSync(join(tmpdir(), 'analog-zoneless-')),
44+
});
45+
expect(src).not.toContain('zone.js');
46+
} finally {
47+
if (previous === undefined) {
48+
delete process.env['NODE_PATH'];
49+
} else {
50+
process.env['NODE_PATH'] = previous;
51+
}
52+
initPaths();
53+
}
54+
});
2855
});

‎packages/platform/src/lib/nitro/server-fn-endpoints.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { NitroEventHandler } from 'nitro/types';
2-
import { createRequire } from 'node:module';
3-
import { join } from 'node:path';
2+
import { existsSync } from 'node:fs';
3+
import { dirname, join } from 'node:path';
44
import { normalizePath } from 'vite';
55

66
import type { ServerFnHandlerModule } from './get-server-fn-handlers.js';
@@ -107,10 +107,12 @@ export default createServerFnEventHandler(
107107
}
108108

109109
function hasZoneJs(root: string): boolean {
110-
try {
111-
createRequire(join(root, 'noop.js')).resolve('zone.js/node');
112-
return true;
113-
} catch {
114-
return false;
110+
for (let dir = root; ; dir = dirname(dir)) {
111+
if (existsSync(join(dir, 'node_modules/zone.js/package.json'))) {
112+
return true;
113+
}
114+
if (dirname(dir) === dir) {
115+
return false;
116+
}
115117
}
116118
}

0 commit comments

Comments
 (0)