From 836da1ea0de68f412e2f6d1761bd8cd2e24e807e Mon Sep 17 00:00:00 2001
From: naoki <0512.naoki.job@gmail.com>
Date: Fri, 20 Nov 2026 21:35:43 +0900
Subject: [PATCH] fix(vite): preserve SSR entry import order when registering
manifests
---
.../test/ssr-manifest.test.ts | 84 +++++++++++++++++--
.../angular-ssr-manifest-plugin.ts | 79 +++++++++++------
2 files changed, 131 insertions(+), 32 deletions(-)
diff --git a/napi/angular-compiler/test/ssr-manifest.test.ts b/napi/angular-compiler/test/ssr-manifest.test.ts
index b5f51e376..309700566 100644
--- a/napi/angular-compiler/test/ssr-manifest.test.ts
+++ b/napi/angular-compiler/test/ssr-manifest.test.ts
@@ -1,9 +1,11 @@
+import { execFileSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, dirname, join } from 'node:path'
import { runInNewContext } from 'node:vm'
-import { afterAll, describe, it, expect } from 'vitest'
+import { createBuilder } from 'vite'
+import { afterAll, describe, it, expect, onTestFinished } from 'vitest'
/**
* Tests for SSR manifest generation.
*
@@ -21,6 +23,8 @@ import {
generateAppEngineManifestCode,
} from '../vite-plugin/angular-ssr-manifest-plugin.js'
+const manifestId = 'virtual:oxc-angular/ssr-manifest'
+
describe('SSR Manifest Generation (Issue #60)', () => {
describe('generateAppManifestCode', () => {
it('should generate valid app manifest code with bootstrap import', () => {
@@ -128,7 +132,72 @@ describe('SSR Manifest Generation (Issue #60)', () => {
)
expect(transform('client')).toBeUndefined()
- expect(transform('server')?.code).toContain('ɵsetAngularAppManifest')
+ expect(transform('server')?.code).toContain(manifestId)
+ })
+
+ it('evaluates entry imports, registers both manifests, then constructs the engine', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'oxc-angular-ssr-order-'))
+ onTestFinished(() => rmSync(root, { recursive: true, force: true }))
+ writeFileSync(join(root, 'trace.mjs'), 'export const events = []')
+ writeFileSync(
+ join(root, 'compiler.mjs'),
+ "import { events } from './trace.mjs'; events.push('compiler')",
+ )
+ writeFileSync(join(root, 'main.server.ts'), 'export default () => {}')
+ writeFileSync(
+ join(root, 'ssr.mjs'),
+ `
+ import { events } from './trace.mjs'
+ events.push('ssr')
+ export function ɵsetAngularAppManifest() { events.push('app manifest') }
+ export function ɵsetAngularAppEngineManifest() { events.push('engine manifest') }
+ export function ɵgetOrCreateAngularServerApp() {}
+ export function ɵdestroyAngularServerApp() {}
+ export function ɵextractRoutesAndCreateRouteTree() {}
+ `,
+ )
+ writeFileSync(
+ join(root, 'server.js'),
+ `
+ import './compiler.mjs'
+ import { events } from './trace.mjs'
+ class AngularNodeAppEngine { constructor() { events.push('engine') } }
+ new AngularNodeAppEngine()
+ export function view() { return
}
+ console.log(JSON.stringify(events))
+ `,
+ )
+
+ const builder = await createBuilder({
+ configFile: false,
+ root,
+ logLevel: 'silent',
+ plugins: [ssrManifestPlugin({ ssrEntry: 'main.server.ts' })],
+ resolve: { alias: { '@angular/ssr': join(root, 'ssr.mjs') } },
+ environments: {
+ ssr: {
+ build: {
+ rolldownOptions: {
+ input: join(root, 'server.js'),
+ moduleTypes: { '.js': 'jsx' },
+ transform: { jsx: { runtime: 'classic' } },
+ output: { entryFileNames: 'server.mjs' },
+ },
+ },
+ },
+ },
+ })
+ await builder.build(builder.environments.ssr)
+ const output = execFileSync(process.execPath, [join(root, 'dist/server.mjs')], {
+ encoding: 'utf8',
+ })
+ expect(JSON.parse(output)).toEqual([
+ 'compiler',
+ 'ssr',
+ 'app manifest',
+ 'engine manifest',
+ 'engine',
+ ])
})
it('should not inject the manifests twice', () => {
@@ -245,10 +314,13 @@ describe('SSR Manifest Generation (Issue #60)', () => {
/** The server's buildStart, then a transform of each module. */
async server(...modules: string[]): Promise<(string | undefined)[]> {
await plugin.buildStart.handler.call(context('ssr'))
- return modules.map(
- (code, i) =>
- plugin.transform.call(context('ssr'), code, join(root, `src/server${i}.ts`))?.code,
- )
+ const ctx = context('ssr')
+ return modules.map((code, i) => {
+ const id = join(root, `src/server${i}.ts`)
+ if (!plugin.transform.call(ctx, code, id)) return
+ const manifest = plugin.resolveId.call(ctx, manifestId, id)
+ return plugin.load.call(ctx, manifest.id)
+ })
},
/** The server's renderChunk of a chunk with `code`. */
async render(code: string): Promise {
diff --git a/napi/angular-compiler/vite-plugin/angular-ssr-manifest-plugin.ts b/napi/angular-compiler/vite-plugin/angular-ssr-manifest-plugin.ts
index 24fe9bf10..6be9accf6 100644
--- a/napi/angular-compiler/vite-plugin/angular-ssr-manifest-plugin.ts
+++ b/napi/angular-compiler/vite-plugin/angular-ssr-manifest-plugin.ts
@@ -116,6 +116,10 @@ export interface SsrManifestPluginOptions {
const PAGE_TOKEN = '__oxc_angular_index_server_html__'
const PAGE_SIZE_TOKEN = '__oxc_angular_index_server_html_size__'
+const MANIFEST_ID = 'virtual:oxc-angular/ssr-manifest'
+const MANIFEST_IMPORT = `import '${MANIFEST_ID}';`
+const MANIFEST_PREFIX = '\0' + MANIFEST_ID + '.js?entry='
+
const MINIMAL_PAGE = ''
type Environment = NonNullable
@@ -292,6 +296,9 @@ export function ssrManifestPlugin(options: SsrManifestPluginOptions): Plugin {
let stampFailed = false
const servers = new Map()
+ const manifestEntry = (id: string) =>
+ resolve(resolvedConfig.root, decodeURIComponent(id.slice(MANIFEST_PREFIX.length)))
+
const serverState = (name: string): ServerState => {
let state = servers.get(name)
if (!state) servers.set(name, (state = { waiting: 0, building: false, warned: false }))
@@ -486,32 +493,9 @@ export function ssrManifestPlugin(options: SsrManifestPluginOptions): Plugin {
!id.includes('node_modules') &&
!id.startsWith('\0') &&
(code.includes('AngularNodeAppEngine') || code.includes('AngularAppEngine')) &&
- !code.includes('ɵsetAngularAppManifest')
+ !code.includes('ɵsetAngularAppManifest') &&
+ !code.includes(MANIFEST_IMPORT)
) {
- const baseHref = resolvedConfig.base || '/'
-
- // Compute the import path for main.server.ts relative to the current file
- const fileDir = dirname(id)
- let ssrEntryImport = normalizePath(relative(fileDir, ssrEntryPath)).replace(/\.ts$/, '')
- if (!ssrEntryImport.startsWith('.')) {
- ssrEntryImport = './' + ssrEntryImport
- }
-
- // In `vite build --app --watch`, renderChunk fills in the page.
- const appManifest = isAppWatchServer(this.environment, this.meta)
- ? generateAppManifestCode({ ssrEntryImport, baseHref, indexHtmlContent: '' })
- .replace('size: 0,', `size: ${PAGE_SIZE_TOKEN},`)
- .replace('Promise.resolve(``)', `Promise.resolve(${PAGE_TOKEN})`)
- : generateAppManifestCode({
- ssrEntryImport,
- baseHref,
- indexHtmlContent: indexHtmlContent || '',
- })
-
- const engineManifest = generateAppEngineManifestCode({
- basePath: baseHref,
- })
-
// Only warn about the page when a manifest embeds it, once per build.
const warning = fallbackWarnings.get(this.environment.name)
if (warning) {
@@ -520,12 +504,55 @@ export function ssrManifestPlugin(options: SsrManifestPluginOptions): Plugin {
}
return {
- code: appManifest + engineManifest + code,
+ // ESM evaluates this last dependency after the user's imports (including
+ // @angular/compiler), but before the entry constructs its app engine.
+ code: `${code}\n${MANIFEST_IMPORT}\n`,
map: null,
}
}
},
+ resolveId(source, importer, options) {
+ if (!importer || this.environment?.config.consumer !== 'server') return
+ if (source === MANIFEST_ID) {
+ const entry = normalizePath(relative(resolvedConfig.root, importer))
+ return { id: MANIFEST_PREFIX + encodeURIComponent(entry), moduleSideEffects: true }
+ }
+ // Resolve Angular and the bootstrap from the same entry as before injection.
+ if (importer.startsWith(MANIFEST_PREFIX)) {
+ return this.resolve(source, normalizePath(manifestEntry(importer)), options)
+ }
+ },
+
+ load(id) {
+ if (!id.startsWith(MANIFEST_PREFIX) || this.environment?.config.consumer !== 'server') return
+ const baseHref = resolvedConfig.base || '/'
+
+ // Compute the import path for main.server.ts relative to the current file
+ const fileDir = dirname(manifestEntry(id))
+ let ssrEntryImport = normalizePath(relative(fileDir, ssrEntryPath)).replace(/\.ts$/, '')
+ if (!ssrEntryImport.startsWith('.')) {
+ ssrEntryImport = './' + ssrEntryImport
+ }
+
+ // In `vite build --app --watch`, renderChunk fills in the page.
+ const appManifest = isAppWatchServer(this.environment, this.meta)
+ ? generateAppManifestCode({ ssrEntryImport, baseHref, indexHtmlContent: '' })
+ .replace('size: 0,', `size: ${PAGE_SIZE_TOKEN},`)
+ .replace('Promise.resolve(``)', `Promise.resolve(${PAGE_TOKEN})`)
+ : generateAppManifestCode({
+ ssrEntryImport,
+ baseHref,
+ indexHtmlContent: indexHtmlContent || '',
+ })
+
+ const engineManifest = generateAppEngineManifestCode({
+ basePath: baseHref,
+ })
+
+ return appManifest + engineManifest
+ },
+
async renderChunk(code) {
const environment = this.environment
if (environment?.config.consumer !== 'server' || !code.includes(PAGE_TOKEN)) return null