diff --git a/knip.json b/knip.json index 2512539..40b4348 100644 --- a/knip.json +++ b/knip.json @@ -5,6 +5,7 @@ "src/config.ts", "src/internal.ts", "src/node-preload.ts", + "src/ssr.ts", "src/builders/*/builder.ts", "src/schematics/*/schematic.ts", "src/generators/*/generator.ts", diff --git a/package.json b/package.json index 6e78a99..5e4c03b 100644 --- a/package.json +++ b/package.json @@ -60,6 +60,11 @@ "types": "./src/node-preload.d.ts", "import": "./src/node-preload.js", "default": "./src/node-preload.js" + }, + "./ssr": { + "types": "./src/ssr.d.ts", + "import": "./src/ssr.js", + "default": "./src/ssr.js" } }, "homepage": "https://native-federation.com/docs/v4/angular-adapter/", diff --git a/src/ssr.spec.ts b/src/ssr.spec.ts new file mode 100644 index 0000000..6586860 --- /dev/null +++ b/src/ssr.spec.ts @@ -0,0 +1,227 @@ +import { createRequire } from 'module'; +import * as path from 'path'; +import { describe, it, expect } from 'vitest'; +import { rewriteModulePreloads } from './ssr'; + +// Angular's original, loaded by absolute file path because the exports map blocks the +// `@angular/build/src/...` specifier (#153). +const require = createRequire(import.meta.url); +const angularBuildRoot = path.dirname(require.resolve('@angular/build/package.json')); +const { augmentIndexHtml } = require( + path.join(angularBuildRoot, 'src/utils/index-file/augment-index-html.js'), +); + +const NATIVE = ''; +const SHIM = ''; + +function page(esmsOptions: string, preloads: string): string { + return ( + '\n\t\t' + + `${esmsOptions}${preloads}` + ); +} + +function html(body: string, headers: Record = {}): Response { + return new Response(body, { + status: 200, + headers: { + // What `@angular/ssr` sends: no space, upper case. + 'content-type': 'text/html;charset=UTF-8', + 'content-length': String(new TextEncoder().encode(body).length), + ...headers, + }, + }); +} + +describe('rewriteModulePreloads', () => { + it('turns modulepreload hints into script preloads under native import maps', async () => { + const res = html( + page( + NATIVE, + '' + + '', + ), + ); + + const out = await rewriteModulePreloads(res); + const body = await out!.text(); + + expect(body).toContain(''); + expect(body).toContain(''); + expect(body).not.toContain('modulepreload'); + }); + + it('drops content-length, which the rewrite makes wrong, and keeps the rest', async () => { + const res = html(page(NATIVE, ''), { + 'x-custom': 'kept', + }); + + const out = await rewriteModulePreloads(res); + + expect(out!.headers.has('content-length')).toBe(false); + expect(out!.headers.get('x-custom')).toBe('kept'); + expect(out!.headers.get('content-type')).toBe('text/html;charset=UTF-8'); + expect(out!.status).toBe(200); + }); + + it('keeps the status of an error page it rewrites', async () => { + const body = page(NATIVE, ''); + const res = new Response(body, { + status: 404, + statusText: 'Not Found', + headers: { 'content-type': 'text/html' }, + }); + + const out = await rewriteModulePreloads(res); + + expect(await out!.text()).toContain('rel="preload" as="script"'); + expect(out!.status).toBe(404); + expect(out!.statusText).toBe('Not Found'); + }); + + it('leaves shim mode alone, returning the same response with its body unread', async () => { + const body = page(SHIM, ''); + const res = html(body); + + const out = await rewriteModulePreloads(res); + + // The body must still be readable: writeResponseToNodeResponse streams it next. + expect(out).toBe(res); + expect(await out!.text()).toBe(body); + }); + + it('reads native mode from esms-options that carry other keys too', async () => { + const options = ''; + const res = html(page(options, '')); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain(''); + }); + + it('keeps the nonce that ngCspNonce adds to esms-options and to the links', async () => { + // Angular's addNonce appends `nonce` after the attributes already there. + const options = ''; + const res = html( + page(options, ''), + ); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain( + '', + ); + }); + + it('rewrites a streamed body, as the engine returns for server-rendered routes', async () => { + const source = page(NATIVE, ''); + const bytes = new TextEncoder().encode(source); + const stream = new ReadableStream({ + start(controller) { + controller.enqueue(bytes.slice(0, 40)); + controller.enqueue(bytes.slice(40)); + controller.close(); + }, + }); + const res = new Response(stream, { headers: { 'content-type': 'text/html' } }); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain(''); + }); + + it('leaves other links and attributes alone', async () => { + const res = html( + page( + NATIVE, + '' + + '' + + '' + + '' + + '', + ), + ); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain( + '', + ); + expect(body).toContain(''); + expect(body).toContain(''); + expect(body).toContain(''); + expect(body).toContain(''); + }); + + it('ignores a data-type attribute that only looks like esms-options', async () => { + const decoy = ''; + const res = html(page(decoy + SHIM, '')); + + expect(await rewriteModulePreloads(res)).toBe(res); + }); + + it('leaves custom elements whose names start with link or script alone', async () => { + const custom = + '' + + '{"shimMode":true}'; + const res = html(page(NATIVE, custom + '')); + + const body = await (await rewriteModulePreloads(res))!.text(); + + expect(body).toContain(custom); + expect(body).toContain(''); + }); + + it('leaves a page with no esms-options alone', async () => { + const res = html(page('', '')); + + expect(await rewriteModulePreloads(res)).toBe(res); + }); + + it('needs the builder\'s exact {"shimMode":false prefix', async () => { + const res = html( + page( + '', + '', + ), + ); + + expect(await rewriteModulePreloads(res)).toBe(res); + }); + + it('leaves non-HTML responses alone', async () => { + // A body that would be rewritten if it were HTML, so only the content type can stop it. + const res = new Response(page(NATIVE, ''), { + headers: { 'content-type': 'text/plain' }, + }); + + expect(await rewriteModulePreloads(res)).toBe(res); + }); + + it('returns the same response when there is nothing to rewrite', async () => { + const res = html(page(NATIVE, '')); + + expect(await rewriteModulePreloads(res)).toBe(res); + }); + + it('passes null through, for routes the engine does not handle', async () => { + expect(await rewriteModulePreloads(null)).toBeNull(); + }); +}); + +describe("@angular/build's modulepreload hints", () => { + // The helper matches the literal ` { + const { content } = await augmentIndexHtml({ + html: '', + sri: false, + files: [], + entrypoints: [], + loadOutputFile: async () => '', + hints: [{ url: 'chunk-ABC.js', mode: 'modulepreload' }], + }); + + expect(content).toContain(''); + }); +}); diff --git a/src/ssr.ts b/src/ssr.ts new file mode 100644 index 0000000..a65a3a7 --- /dev/null +++ b/src/ssr.ts @@ -0,0 +1,17 @@ +const MODULE_PRELOAD = ']*>\{"shimMode":false/; + +// `crossorigin` keeps the preload in CORS mode, so the module import reuses the response (#171). +export async function rewriteModulePreloads(res: Response | null): Promise { + if (!res?.body || !res.headers.get('content-type')?.includes('text/html')) return res; + + const html = await res.clone().text(); + if (!NATIVE_IMPORT_MAPS.test(html) || !html.includes(MODULE_PRELOAD)) return res; + + const headers = new Headers(res.headers); + headers.delete('content-length'); + return new Response( + html.replaceAll(MODULE_PRELOAD, '