@angular/ssr 20.0.0-next.1 → 20.0.0-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/fesm2022/node.mjs CHANGED
@@ -199,7 +199,6 @@ const HTTP2_PSEUDO_HEADERS = new Set([':method', ':scheme', ':authority', ':path
199
199
  *
200
200
  * @param nodeRequest - The Node.js request object (`IncomingMessage` or `Http2ServerRequest`) to convert.
201
201
  * @returns A Web Standard `Request` object.
202
- * @developerPreview
203
202
  */
204
203
  function createWebRequestFromNodeRequest(nodeRequest) {
205
204
  const { headers, method = 'GET' } = nodeRequest;
@@ -282,8 +281,6 @@ function getFirstHeaderValue(value) {
282
281
  *
283
282
  * @remarks This class should be instantiated once and used as a singleton across the server-side
284
283
  * application to ensure consistent handling of rendering requests and resource management.
285
- *
286
- * @developerPreview
287
284
  */
288
285
  class AngularNodeAppEngine {
289
286
  angularAppEngine = new AngularAppEngine();
@@ -349,7 +346,6 @@ class AngularNodeAppEngine {
349
346
  * res.send('Hello from Fastify with Node Next Handler!');
350
347
  * }));
351
348
  * ```
352
- * @developerPreview
353
349
  */
354
350
  function createNodeRequestHandler(handler) {
355
351
  handler['__ng_node_request_handler__'] = true;
@@ -366,7 +362,6 @@ function createNodeRequestHandler(handler) {
366
362
  * @param source - The web-standard `Response` object to stream from.
367
363
  * @param destination - The Node.js response object (`ServerResponse` or `Http2ServerResponse`) to stream into.
368
364
  * @returns A promise that resolves once the streaming operation is complete.
369
- * @developerPreview
370
365
  */
371
366
  async function writeResponseToNodeResponse(source, destination) {
372
367
  const { status, headers, body } = source;
@@ -435,7 +430,6 @@ async function writeResponseToNodeResponse(source, destination) {
435
430
  *
436
431
  * @param url The URL of the module to check. This should typically be `import.meta.url`.
437
432
  * @returns `true` if the provided URL represents the main entry point, otherwise `false`.
438
- * @developerPreview
439
433
  */
440
434
  function isMainModule(url) {
441
435
  return url.startsWith('file:') && argv[1] === fileURLToPath(url);
@@ -1 +1 @@
1
- {"version":3,"file":"node.mjs","sources":["../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/common-engine/inline-css-processor.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/common-engine/peformance-profiler.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/common-engine/common-engine.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/request.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/app-engine.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/handler.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/response.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/module.ts"],"sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { ɵInlineCriticalCssProcessor as InlineCriticalCssProcessor } from '@angular/ssr';\nimport { readFile } from 'node:fs/promises';\n\nexport class CommonEngineInlineCriticalCssProcessor {\n private readonly resourceCache = new Map<string, string>();\n\n async process(html: string, outputPath: string | undefined): Promise<string> {\n const beasties = new InlineCriticalCssProcessor(async (path) => {\n let resourceContent = this.resourceCache.get(path);\n if (resourceContent === undefined) {\n resourceContent = await readFile(path, 'utf-8');\n this.resourceCache.set(path, resourceContent);\n }\n\n return resourceContent;\n }, outputPath);\n\n return beasties.process(html);\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nconst PERFORMANCE_MARK_PREFIX = '🅰️';\n\nexport function printPerformanceLogs(): void {\n let maxWordLength = 0;\n const benchmarks: [step: string, value: string][] = [];\n\n for (const { name, duration } of performance.getEntriesByType('measure')) {\n if (!name.startsWith(PERFORMANCE_MARK_PREFIX)) {\n continue;\n }\n\n // `🅰️:Retrieve SSG Page` -> `Retrieve SSG Page:`\n const step = name.slice(PERFORMANCE_MARK_PREFIX.length + 1) + ':';\n if (step.length > maxWordLength) {\n maxWordLength = step.length;\n }\n\n benchmarks.push([step, `${duration.toFixed(1)}ms`]);\n performance.clearMeasures(name);\n }\n\n /* eslint-disable no-console */\n console.log('********** Performance results **********');\n for (const [step, value] of benchmarks) {\n const spaces = maxWordLength - step.length + 5;\n console.log(step + ' '.repeat(spaces) + value);\n }\n console.log('*****************************************');\n /* eslint-enable no-console */\n}\n\nexport async function runMethodAndMeasurePerf<T>(\n label: string,\n asyncMethod: () => Promise<T>,\n): Promise<T> {\n const labelName = `${PERFORMANCE_MARK_PREFIX}:${label}`;\n const startLabel = `start:${labelName}`;\n const endLabel = `end:${labelName}`;\n\n try {\n performance.mark(startLabel);\n\n return await asyncMethod();\n } finally {\n performance.mark(endLabel);\n performance.measure(labelName, startLabel, endLabel);\n performance.clearMarks(startLabel);\n performance.clearMarks(endLabel);\n }\n}\n\nexport function noopRunMethodAndMeasurePerf<T>(\n label: string,\n asyncMethod: () => Promise<T>,\n): Promise<T> {\n return asyncMethod();\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { ApplicationRef, StaticProvider, Type } from '@angular/core';\nimport { renderApplication, renderModule, ɵSERVER_CONTEXT } from '@angular/platform-server';\nimport * as fs from 'node:fs';\nimport { dirname, join, normalize, resolve } from 'node:path';\nimport { URL } from 'node:url';\nimport { CommonEngineInlineCriticalCssProcessor } from './inline-css-processor';\nimport {\n noopRunMethodAndMeasurePerf,\n printPerformanceLogs,\n runMethodAndMeasurePerf,\n} from './peformance-profiler';\n\nconst SSG_MARKER_REGEXP = /ng-server-context=[\"']\\w*\\|?ssg\\|?\\w*[\"']/;\n\nexport interface CommonEngineOptions {\n /** A method that when invoked returns a promise that returns an `ApplicationRef` instance once resolved or an NgModule. */\n bootstrap?: Type<{}> | (() => Promise<ApplicationRef>);\n\n /** A set of platform level providers for all requests. */\n providers?: StaticProvider[];\n\n /** Enable request performance profiling data collection and printing the results in the server console. */\n enablePerformanceProfiler?: boolean;\n}\n\nexport interface CommonEngineRenderOptions {\n /** A method that when invoked returns a promise that returns an `ApplicationRef` instance once resolved or an NgModule. */\n bootstrap?: Type<{}> | (() => Promise<ApplicationRef>);\n\n /** A set of platform level providers for the current request. */\n providers?: StaticProvider[];\n url?: string;\n document?: string;\n documentFilePath?: string;\n\n /**\n * Reduce render blocking requests by inlining critical CSS.\n * Defaults to true.\n */\n inlineCriticalCss?: boolean;\n\n /**\n * Base path location of index file.\n * Defaults to the 'documentFilePath' dirname when not provided.\n */\n publicPath?: string;\n}\n\n/**\n * A common engine to use to server render an application.\n */\n\nexport class CommonEngine {\n private readonly templateCache = new Map<string, string>();\n private readonly inlineCriticalCssProcessor = new CommonEngineInlineCriticalCssProcessor();\n private readonly pageIsSSG = new Map<string, boolean>();\n\n constructor(private options?: CommonEngineOptions) {}\n\n /**\n * Render an HTML document for a specific URL with specified\n * render options\n */\n async render(opts: CommonEngineRenderOptions): Promise<string> {\n const enablePerformanceProfiler = this.options?.enablePerformanceProfiler;\n\n const runMethod = enablePerformanceProfiler\n ? runMethodAndMeasurePerf\n : noopRunMethodAndMeasurePerf;\n\n let html = await runMethod('Retrieve SSG Page', () => this.retrieveSSGPage(opts));\n\n if (html === undefined) {\n html = await runMethod('Render Page', () => this.renderApplication(opts));\n\n if (opts.inlineCriticalCss !== false) {\n const content = await runMethod('Inline Critical CSS', () =>\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.inlineCriticalCss(html!, opts),\n );\n\n html = content;\n }\n }\n\n if (enablePerformanceProfiler) {\n printPerformanceLogs();\n }\n\n return html;\n }\n\n private inlineCriticalCss(html: string, opts: CommonEngineRenderOptions): Promise<string> {\n const outputPath =\n opts.publicPath ?? (opts.documentFilePath ? dirname(opts.documentFilePath) : '');\n\n return this.inlineCriticalCssProcessor.process(html, outputPath);\n }\n\n private async retrieveSSGPage(opts: CommonEngineRenderOptions): Promise<string | undefined> {\n const { publicPath, documentFilePath, url } = opts;\n if (!publicPath || !documentFilePath || url === undefined) {\n return undefined;\n }\n\n const { pathname } = new URL(url, 'resolve://');\n // Do not use `resolve` here as otherwise it can lead to path traversal vulnerability.\n // See: https://portswigger.net/web-security/file-path-traversal\n const pagePath = join(publicPath, pathname, 'index.html');\n\n if (this.pageIsSSG.get(pagePath)) {\n // Serve pre-rendered page.\n return fs.promises.readFile(pagePath, 'utf-8');\n }\n\n if (!pagePath.startsWith(normalize(publicPath))) {\n // Potential path traversal detected.\n return undefined;\n }\n\n if (pagePath === resolve(documentFilePath) || !(await exists(pagePath))) {\n // View matches with prerender path or file does not exist.\n this.pageIsSSG.set(pagePath, false);\n\n return undefined;\n }\n\n // Static file exists.\n const content = await fs.promises.readFile(pagePath, 'utf-8');\n const isSSG = SSG_MARKER_REGEXP.test(content);\n this.pageIsSSG.set(pagePath, isSSG);\n\n return isSSG ? content : undefined;\n }\n\n private async renderApplication(opts: CommonEngineRenderOptions): Promise<string> {\n const moduleOrFactory = this.options?.bootstrap ?? opts.bootstrap;\n if (!moduleOrFactory) {\n throw new Error('A module or bootstrap option must be provided.');\n }\n\n const extraProviders: StaticProvider[] = [\n { provide: ɵSERVER_CONTEXT, useValue: 'ssr' },\n ...(opts.providers ?? []),\n ...(this.options?.providers ?? []),\n ];\n\n let document = opts.document;\n if (!document && opts.documentFilePath) {\n document = await this.getDocument(opts.documentFilePath);\n }\n\n const commonRenderingOptions = {\n url: opts.url,\n document,\n };\n\n return isBootstrapFn(moduleOrFactory)\n ? renderApplication(moduleOrFactory, {\n platformProviders: extraProviders,\n ...commonRenderingOptions,\n })\n : renderModule(moduleOrFactory, { extraProviders, ...commonRenderingOptions });\n }\n\n /** Retrieve the document from the cache or the filesystem */\n private async getDocument(filePath: string): Promise<string> {\n let doc = this.templateCache.get(filePath);\n\n if (!doc) {\n doc = await fs.promises.readFile(filePath, 'utf-8');\n this.templateCache.set(filePath, doc);\n }\n\n return doc;\n }\n}\n\nasync function exists(path: fs.PathLike): Promise<boolean> {\n try {\n await fs.promises.access(path, fs.constants.F_OK);\n\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isBootstrapFn(value: unknown): value is () => Promise<ApplicationRef> {\n // We can differentiate between a module and a bootstrap function by reading compiler-generated `ɵmod` static property:\n return typeof value === 'function' && !('ɵmod' in value);\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type { IncomingHttpHeaders, IncomingMessage } from 'node:http';\nimport type { Http2ServerRequest } from 'node:http2';\n\n/**\n * A set containing all the pseudo-headers defined in the HTTP/2 specification.\n *\n * This set can be used to filter out pseudo-headers from a list of headers,\n * as they are not allowed to be set directly using the `Node.js` Undici API or\n * the web `Headers` API.\n */\nconst HTTP2_PSEUDO_HEADERS = new Set([':method', ':scheme', ':authority', ':path', ':status']);\n\n/**\n * Converts a Node.js `IncomingMessage` or `Http2ServerRequest` into a\n * Web Standard `Request` object.\n *\n * This function adapts the Node.js request objects to a format that can\n * be used by web platform APIs.\n *\n * @param nodeRequest - The Node.js request object (`IncomingMessage` or `Http2ServerRequest`) to convert.\n * @returns A Web Standard `Request` object.\n * @developerPreview\n */\nexport function createWebRequestFromNodeRequest(\n nodeRequest: IncomingMessage | Http2ServerRequest,\n): Request {\n const { headers, method = 'GET' } = nodeRequest;\n const withBody = method !== 'GET' && method !== 'HEAD';\n\n return new Request(createRequestUrl(nodeRequest), {\n method,\n headers: createRequestHeaders(headers),\n body: withBody ? nodeRequest : undefined,\n duplex: withBody ? 'half' : undefined,\n });\n}\n\n/**\n * Creates a `Headers` object from Node.js `IncomingHttpHeaders`.\n *\n * @param nodeHeaders - The Node.js `IncomingHttpHeaders` object to convert.\n * @returns A `Headers` object containing the converted headers.\n */\nfunction createRequestHeaders(nodeHeaders: IncomingHttpHeaders): Headers {\n const headers = new Headers();\n\n for (const [name, value] of Object.entries(nodeHeaders)) {\n if (HTTP2_PSEUDO_HEADERS.has(name)) {\n continue;\n }\n\n if (typeof value === 'string') {\n headers.append(name, value);\n } else if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n }\n }\n\n return headers;\n}\n\n/**\n * Creates a `URL` object from a Node.js `IncomingMessage`, taking into account the protocol, host, and port.\n *\n * @param nodeRequest - The Node.js `IncomingMessage` or `Http2ServerRequest` object to extract URL information from.\n * @returns A `URL` object representing the request URL.\n */\nfunction createRequestUrl(nodeRequest: IncomingMessage | Http2ServerRequest): URL {\n const {\n headers,\n socket,\n url = '',\n originalUrl,\n } = nodeRequest as IncomingMessage & { originalUrl?: string };\n const protocol =\n getFirstHeaderValue(headers['x-forwarded-proto']) ??\n ('encrypted' in socket && socket.encrypted ? 'https' : 'http');\n const hostname =\n getFirstHeaderValue(headers['x-forwarded-host']) ?? headers.host ?? headers[':authority'];\n\n if (Array.isArray(hostname)) {\n throw new Error('host value cannot be an array.');\n }\n\n let hostnameWithPort = hostname;\n if (!hostname?.includes(':')) {\n const port = getFirstHeaderValue(headers['x-forwarded-port']);\n if (port) {\n hostnameWithPort += `:${port}`;\n }\n }\n\n return new URL(originalUrl ?? url, `${protocol}://${hostnameWithPort}`);\n}\n\n/**\n * Extracts the first value from a multi-value header string.\n *\n * @param value - A string or an array of strings representing the header values.\n * If it's a string, values are expected to be comma-separated.\n * @returns The first trimmed value from the multi-value header, or `undefined` if the input is invalid or empty.\n *\n * @example\n * ```typescript\n * getFirstHeaderValue(\"value1, value2, value3\"); // \"value1\"\n * getFirstHeaderValue([\"value1\", \"value2\"]); // \"value1\"\n * getFirstHeaderValue(undefined); // undefined\n * ```\n */\nfunction getFirstHeaderValue(value: string | string[] | undefined): string | undefined {\n return value?.toString().split(',', 1)[0]?.trim();\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { AngularAppEngine } from '@angular/ssr';\nimport type { IncomingMessage } from 'node:http';\nimport type { Http2ServerRequest } from 'node:http2';\nimport { createWebRequestFromNodeRequest } from './request';\n\n/**\n * Angular server application engine.\n * Manages Angular server applications (including localized ones), handles rendering requests,\n * and optionally transforms index HTML before rendering.\n *\n * @remarks This class should be instantiated once and used as a singleton across the server-side\n * application to ensure consistent handling of rendering requests and resource management.\n *\n * @developerPreview\n */\nexport class AngularNodeAppEngine {\n private readonly angularAppEngine = new AngularAppEngine();\n\n /**\n * Handles an incoming HTTP request by serving prerendered content, performing server-side rendering,\n * or delivering a static file for client-side rendered routes based on the `RenderMode` setting.\n *\n * This method adapts Node.js's `IncomingMessage` or `Http2ServerRequest`\n * to a format compatible with the `AngularAppEngine` and delegates the handling logic to it.\n *\n * @param request - The incoming HTTP request (`IncomingMessage` or `Http2ServerRequest`).\n * @param requestContext - Optional context for rendering, such as metadata associated with the request.\n * @returns A promise that resolves to the resulting HTTP response object, or `null` if no matching Angular route is found.\n *\n * @remarks A request to `https://www.example.com/page/index.html` will serve or render the Angular route\n * corresponding to `https://www.example.com/page`.\n */\n async handle(\n request: IncomingMessage | Http2ServerRequest,\n requestContext?: unknown,\n ): Promise<Response | null> {\n const webRequest = createWebRequestFromNodeRequest(request);\n\n return this.angularAppEngine.handle(webRequest, requestContext);\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\n/**\n * Represents a middleware function for handling HTTP requests in a Node.js environment.\n *\n * @param req - The incoming HTTP request object.\n * @param res - The outgoing HTTP response object.\n * @param next - A callback function that signals the completion of the middleware or forwards the error if provided.\n *\n * @returns A Promise that resolves to void or simply void. The handler can be asynchronous.\n * @developerPreview\n */\nexport type NodeRequestHandlerFunction = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (err?: unknown) => void,\n) => Promise<void> | void;\n\n/**\n * Attaches metadata to the handler function to mark it as a special handler for Node.js environments.\n *\n * @typeParam T - The type of the handler function.\n * @param handler - The handler function to be defined and annotated.\n * @returns The same handler function passed as an argument, with metadata attached.\n *\n * @example\n * Usage in an Express application:\n * ```ts\n * const app = express();\n * export default createNodeRequestHandler(app);\n * ```\n *\n * @example\n * Usage in a Hono application:\n * ```ts\n * const app = new Hono();\n * export default createNodeRequestHandler(async (req, res, next) => {\n * try {\n * const webRes = await app.fetch(createWebRequestFromNodeRequest(req));\n * if (webRes) {\n * await writeResponseToNodeResponse(webRes, res);\n * } else {\n * next();\n * }\n * } catch (error) {\n * next(error);\n * }\n * }));\n * ```\n *\n * @example\n * Usage in a Fastify application:\n * ```ts\n * const app = Fastify();\n * export default createNodeRequestHandler(async (req, res) => {\n * await app.ready();\n * app.server.emit('request', req, res);\n * res.send('Hello from Fastify with Node Next Handler!');\n * }));\n * ```\n * @developerPreview\n */\nexport function createNodeRequestHandler<T extends NodeRequestHandlerFunction>(handler: T): T {\n (handler as T & { __ng_node_request_handler__?: boolean })['__ng_node_request_handler__'] = true;\n\n return handler;\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type { ServerResponse } from 'node:http';\nimport type { Http2ServerResponse } from 'node:http2';\n\n/**\n * Streams a web-standard `Response` into a Node.js `ServerResponse`\n * or `Http2ServerResponse`.\n *\n * This function adapts the web `Response` object to write its content\n * to a Node.js response object, handling both HTTP/1.1 and HTTP/2.\n *\n * @param source - The web-standard `Response` object to stream from.\n * @param destination - The Node.js response object (`ServerResponse` or `Http2ServerResponse`) to stream into.\n * @returns A promise that resolves once the streaming operation is complete.\n * @developerPreview\n */\nexport async function writeResponseToNodeResponse(\n source: Response,\n destination: ServerResponse | Http2ServerResponse,\n): Promise<void> {\n const { status, headers, body } = source;\n destination.statusCode = status;\n\n let cookieHeaderSet = false;\n for (const [name, value] of headers.entries()) {\n if (name === 'set-cookie') {\n if (cookieHeaderSet) {\n continue;\n }\n\n // Sets the 'set-cookie' header only once to ensure it is correctly applied.\n // Concatenating 'set-cookie' values can lead to incorrect behavior, so we use a single value from `headers.getSetCookie()`.\n destination.setHeader(name, headers.getSetCookie());\n cookieHeaderSet = true;\n } else {\n destination.setHeader(name, value);\n }\n }\n\n if ('flushHeaders' in destination) {\n destination.flushHeaders();\n }\n\n if (!body) {\n destination.end();\n\n return;\n }\n\n try {\n const reader = body.getReader();\n\n destination.on('close', () => {\n reader.cancel().catch((error) => {\n // eslint-disable-next-line no-console\n console.error(\n `An error occurred while writing the response body for: ${destination.req.url}.`,\n error,\n );\n });\n });\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n destination.end();\n break;\n }\n\n const canContinue = (destination as ServerResponse).write(value);\n if (canContinue === false) {\n // Explicitly check for `false`, as AWS may return `undefined` even though this is not valid.\n // See: https://github.com/CodeGenieApp/serverless-express/issues/683\n await new Promise<void>((resolve) => destination.once('drain', resolve));\n }\n }\n } catch {\n destination.end('Internal server error.');\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { argv } from 'node:process';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Determines whether the provided URL represents the main entry point module.\n *\n * This function checks if the provided URL corresponds to the main ESM module being executed directly.\n * It's useful for conditionally executing code that should only run when a module is the entry point,\n * such as starting a server or initializing an application.\n *\n * It performs two key checks:\n * 1. Verifies if the URL starts with 'file:', ensuring it is a local file.\n * 2. Compares the URL's resolved file path with the first command-line argument (`process.argv[1]`),\n * which points to the file being executed.\n *\n * @param url The URL of the module to check. This should typically be `import.meta.url`.\n * @returns `true` if the provided URL represents the main entry point, otherwise `false`.\n * @developerPreview\n */\nexport function isMainModule(url: string): boolean {\n return url.startsWith('file:') && argv[1] === fileURLToPath(url);\n}\n"],"names":["InlineCriticalCssProcessor","URL","ɵSERVER_CONTEXT"],"mappings":";;;;;;;;MAWa,sCAAsC,CAAA;AAChC,IAAA,aAAa,GAAG,IAAI,GAAG,EAAkB;AAE1D,IAAA,MAAM,OAAO,CAAC,IAAY,EAAE,UAA8B,EAAA;QACxD,MAAM,QAAQ,GAAG,IAAIA,2BAA0B,CAAC,OAAO,IAAI,KAAI;YAC7D,IAAI,eAAe,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC;AAClD,YAAA,IAAI,eAAe,KAAK,SAAS,EAAE;gBACjC,eAAe,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;gBAC/C,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,EAAE,eAAe,CAAC;;AAG/C,YAAA,OAAO,eAAe;SACvB,EAAE,UAAU,CAAC;AAEd,QAAA,OAAO,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC;;AAEhC;;ACnBD,MAAM,uBAAuB,GAAG,KAAK;SAErB,oBAAoB,GAAA;IAClC,IAAI,aAAa,GAAG,CAAC;IACrB,MAAM,UAAU,GAAoC,EAAE;AAEtD,IAAA,KAAK,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,WAAW,CAAC,gBAAgB,CAAC,SAAS,CAAC,EAAE;QACxE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,uBAAuB,CAAC,EAAE;YAC7C;;;AAIF,QAAA,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,uBAAuB,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,GAAG;AACjE,QAAA,IAAI,IAAI,CAAC,MAAM,GAAG,aAAa,EAAE;AAC/B,YAAA,aAAa,GA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AW,EAAE;QACjC,WAAW,CAAC,YAAY,EAAE;;IAG5B,IAAI,CAAC,IAAI,EAAE;QACT,WAAW,CAAC,GAAG,EAAE;QAEjB;;AAGF,IAAA,IAAI;AACF,QAAA,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE;AAE/B,QAAA,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,MAAK;YAC3B,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,KAAI;;AAE9B,gBAAA,OAAO,CAAC,KAAK,CACX,CAAA,uDAAA,EAA0D,WAAW,CAAC,GAAG,CAAC,GAAG,CAAA,CAAA,CAAG,EAChF,KAAK,CACN;AACH,aAAC,CAAC;AACJ,SAAC,CAAC;;QAGF,OAAO,IAAI,EAAE;YACX,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE;YAC3C,IAAI,IAAI,EAAE;gBACR,WAAW,CAAC,GAAG,EAAE;gBACjB;;YAGF,MAAM,WAAW,GAAI,WAA8B,CAAC,KAAK,CAAC,KAAK,CAAC;AAChE,YAAA,IAAI,WAAW,KAAK,KAAK,EAAE;;;AAGzB,gBAAA,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,KAAK,WAAW,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;;;;AAG5E,IAAA,MAAM;AACN,QAAA,WAAW,CAAC,GAAG,CAAC,wBAAwB,CAAC;;AAE7C;;AC5EA;;;;;;;;;;;;;;;AAeG;AACG,SAAU,YAAY,CAAC,GAAW,EAAA;AACtC,IAAA,OAAO,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,aAAa,CAAC,GAAG,CAAC;AAClE;;;;"}
1
+ {"version":3,"file":"node.mjs","sources":["../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/common-engine/inline-css-processor.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/common-engine/peformance-profiler.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/common-engine/common-engine.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/request.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/app-engine.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/handler.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/response.ts","../../../../../../../k8-fastbuild-ST-70f2edae98f4/bin/packages/angular/ssr/node/src/module.ts"],"sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { ɵInlineCriticalCssProcessor as InlineCriticalCssProcessor } from '@angular/ssr';\nimport { readFile } from 'node:fs/promises';\n\nexport class CommonEngineInlineCriticalCssProcessor {\n private readonly resourceCache = new Map<string, string>();\n\n async process(html: string, outputPath: string | undefined): Promise<string> {\n const beasties = new InlineCriticalCssProcessor(async (path) => {\n let resourceContent = this.resourceCache.get(path);\n if (resourceContent === undefined) {\n resourceContent = await readFile(path, 'utf-8');\n this.resourceCache.set(path, resourceContent);\n }\n\n return resourceContent;\n }, outputPath);\n\n return beasties.process(html);\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nconst PERFORMANCE_MARK_PREFIX = '🅰️';\n\nexport function printPerformanceLogs(): void {\n let maxWordLength = 0;\n const benchmarks: [step: string, value: string][] = [];\n\n for (const { name, duration } of performance.getEntriesByType('measure')) {\n if (!name.startsWith(PERFORMANCE_MARK_PREFIX)) {\n continue;\n }\n\n // `🅰️:Retrieve SSG Page` -> `Retrieve SSG Page:`\n const step = name.slice(PERFORMANCE_MARK_PREFIX.length + 1) + ':';\n if (step.length > maxWordLength) {\n maxWordLength = step.length;\n }\n\n benchmarks.push([step, `${duration.toFixed(1)}ms`]);\n performance.clearMeasures(name);\n }\n\n /* eslint-disable no-console */\n console.log('********** Performance results **********');\n for (const [step, value] of benchmarks) {\n const spaces = maxWordLength - step.length + 5;\n console.log(step + ' '.repeat(spaces) + value);\n }\n console.log('*****************************************');\n /* eslint-enable no-console */\n}\n\nexport async function runMethodAndMeasurePerf<T>(\n label: string,\n asyncMethod: () => Promise<T>,\n): Promise<T> {\n const labelName = `${PERFORMANCE_MARK_PREFIX}:${label}`;\n const startLabel = `start:${labelName}`;\n const endLabel = `end:${labelName}`;\n\n try {\n performance.mark(startLabel);\n\n return await asyncMethod();\n } finally {\n performance.mark(endLabel);\n performance.measure(labelName, startLabel, endLabel);\n performance.clearMarks(startLabel);\n performance.clearMarks(endLabel);\n }\n}\n\nexport function noopRunMethodAndMeasurePerf<T>(\n label: string,\n asyncMethod: () => Promise<T>,\n): Promise<T> {\n return asyncMethod();\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { ApplicationRef, StaticProvider, Type } from '@angular/core';\nimport { renderApplication, renderModule, ɵSERVER_CONTEXT } from '@angular/platform-server';\nimport * as fs from 'node:fs';\nimport { dirname, join, normalize, resolve } from 'node:path';\nimport { URL } from 'node:url';\nimport { CommonEngineInlineCriticalCssProcessor } from './inline-css-processor';\nimport {\n noopRunMethodAndMeasurePerf,\n printPerformanceLogs,\n runMethodAndMeasurePerf,\n} from './peformance-profiler';\n\nconst SSG_MARKER_REGEXP = /ng-server-context=[\"']\\w*\\|?ssg\\|?\\w*[\"']/;\n\nexport interface CommonEngineOptions {\n /** A method that when invoked returns a promise that returns an `ApplicationRef` instance once resolved or an NgModule. */\n bootstrap?: Type<{}> | (() => Promise<ApplicationRef>);\n\n /** A set of platform level providers for all requests. */\n providers?: StaticProvider[];\n\n /** Enable request performance profiling data collection and printing the results in the server console. */\n enablePerformanceProfiler?: boolean;\n}\n\nexport interface CommonEngineRenderOptions {\n /** A method that when invoked returns a promise that returns an `ApplicationRef` instance once resolved or an NgModule. */\n bootstrap?: Type<{}> | (() => Promise<ApplicationRef>);\n\n /** A set of platform level providers for the current request. */\n providers?: StaticProvider[];\n url?: string;\n document?: string;\n documentFilePath?: string;\n\n /**\n * Reduce render blocking requests by inlining critical CSS.\n * Defaults to true.\n */\n inlineCriticalCss?: boolean;\n\n /**\n * Base path location of index file.\n * Defaults to the 'documentFilePath' dirname when not provided.\n */\n publicPath?: string;\n}\n\n/**\n * A common engine to use to server render an application.\n */\n\nexport class CommonEngine {\n private readonly templateCache = new Map<string, string>();\n private readonly inlineCriticalCssProcessor = new CommonEngineInlineCriticalCssProcessor();\n private readonly pageIsSSG = new Map<string, boolean>();\n\n constructor(private options?: CommonEngineOptions) {}\n\n /**\n * Render an HTML document for a specific URL with specified\n * render options\n */\n async render(opts: CommonEngineRenderOptions): Promise<string> {\n const enablePerformanceProfiler = this.options?.enablePerformanceProfiler;\n\n const runMethod = enablePerformanceProfiler\n ? runMethodAndMeasurePerf\n : noopRunMethodAndMeasurePerf;\n\n let html = await runMethod('Retrieve SSG Page', () => this.retrieveSSGPage(opts));\n\n if (html === undefined) {\n html = await runMethod('Render Page', () => this.renderApplication(opts));\n\n if (opts.inlineCriticalCss !== false) {\n const content = await runMethod('Inline Critical CSS', () =>\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.inlineCriticalCss(html!, opts),\n );\n\n html = content;\n }\n }\n\n if (enablePerformanceProfiler) {\n printPerformanceLogs();\n }\n\n return html;\n }\n\n private inlineCriticalCss(html: string, opts: CommonEngineRenderOptions): Promise<string> {\n const outputPath =\n opts.publicPath ?? (opts.documentFilePath ? dirname(opts.documentFilePath) : '');\n\n return this.inlineCriticalCssProcessor.process(html, outputPath);\n }\n\n private async retrieveSSGPage(opts: CommonEngineRenderOptions): Promise<string | undefined> {\n const { publicPath, documentFilePath, url } = opts;\n if (!publicPath || !documentFilePath || url === undefined) {\n return undefined;\n }\n\n const { pathname } = new URL(url, 'resolve://');\n // Do not use `resolve` here as otherwise it can lead to path traversal vulnerability.\n // See: https://portswigger.net/web-security/file-path-traversal\n const pagePath = join(publicPath, pathname, 'index.html');\n\n if (this.pageIsSSG.get(pagePath)) {\n // Serve pre-rendered page.\n return fs.promises.readFile(pagePath, 'utf-8');\n }\n\n if (!pagePath.startsWith(normalize(publicPath))) {\n // Potential path traversal detected.\n return undefined;\n }\n\n if (pagePath === resolve(documentFilePath) || !(await exists(pagePath))) {\n // View matches with prerender path or file does not exist.\n this.pageIsSSG.set(pagePath, false);\n\n return undefined;\n }\n\n // Static file exists.\n const content = await fs.promises.readFile(pagePath, 'utf-8');\n const isSSG = SSG_MARKER_REGEXP.test(content);\n this.pageIsSSG.set(pagePath, isSSG);\n\n return isSSG ? content : undefined;\n }\n\n private async renderApplication(opts: CommonEngineRenderOptions): Promise<string> {\n const moduleOrFactory = this.options?.bootstrap ?? opts.bootstrap;\n if (!moduleOrFactory) {\n throw new Error('A module or bootstrap option must be provided.');\n }\n\n const extraProviders: StaticProvider[] = [\n { provide: ɵSERVER_CONTEXT, useValue: 'ssr' },\n ...(opts.providers ?? []),\n ...(this.options?.providers ?? []),\n ];\n\n let document = opts.document;\n if (!document && opts.documentFilePath) {\n document = await this.getDocument(opts.documentFilePath);\n }\n\n const commonRenderingOptions = {\n url: opts.url,\n document,\n };\n\n return isBootstrapFn(moduleOrFactory)\n ? renderApplication(moduleOrFactory, {\n platformProviders: extraProviders,\n ...commonRenderingOptions,\n })\n : renderModule(moduleOrFactory, { extraProviders, ...commonRenderingOptions });\n }\n\n /** Retrieve the document from the cache or the filesystem */\n private async getDocument(filePath: string): Promise<string> {\n let doc = this.templateCache.get(filePath);\n\n if (!doc) {\n doc = await fs.promises.readFile(filePath, 'utf-8');\n this.templateCache.set(filePath, doc);\n }\n\n return doc;\n }\n}\n\nasync function exists(path: fs.PathLike): Promise<boolean> {\n try {\n await fs.promises.access(path, fs.constants.F_OK);\n\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isBootstrapFn(value: unknown): value is () => Promise<ApplicationRef> {\n // We can differentiate between a module and a bootstrap function by reading compiler-generated `ɵmod` static property:\n return typeof value === 'function' && !('ɵmod' in value);\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type { IncomingHttpHeaders, IncomingMessage } from 'node:http';\nimport type { Http2ServerRequest } from 'node:http2';\n\n/**\n * A set containing all the pseudo-headers defined in the HTTP/2 specification.\n *\n * This set can be used to filter out pseudo-headers from a list of headers,\n * as they are not allowed to be set directly using the `Node.js` Undici API or\n * the web `Headers` API.\n */\nconst HTTP2_PSEUDO_HEADERS = new Set([':method', ':scheme', ':authority', ':path', ':status']);\n\n/**\n * Converts a Node.js `IncomingMessage` or `Http2ServerRequest` into a\n * Web Standard `Request` object.\n *\n * This function adapts the Node.js request objects to a format that can\n * be used by web platform APIs.\n *\n * @param nodeRequest - The Node.js request object (`IncomingMessage` or `Http2ServerRequest`) to convert.\n * @returns A Web Standard `Request` object.\n */\nexport function createWebRequestFromNodeRequest(\n nodeRequest: IncomingMessage | Http2ServerRequest,\n): Request {\n const { headers, method = 'GET' } = nodeRequest;\n const withBody = method !== 'GET' && method !== 'HEAD';\n\n return new Request(createRequestUrl(nodeRequest), {\n method,\n headers: createRequestHeaders(headers),\n body: withBody ? nodeRequest : undefined,\n duplex: withBody ? 'half' : undefined,\n });\n}\n\n/**\n * Creates a `Headers` object from Node.js `IncomingHttpHeaders`.\n *\n * @param nodeHeaders - The Node.js `IncomingHttpHeaders` object to convert.\n * @returns A `Headers` object containing the converted headers.\n */\nfunction createRequestHeaders(nodeHeaders: IncomingHttpHeaders): Headers {\n const headers = new Headers();\n\n for (const [name, value] of Object.entries(nodeHeaders)) {\n if (HTTP2_PSEUDO_HEADERS.has(name)) {\n continue;\n }\n\n if (typeof value === 'string') {\n headers.append(name, value);\n } else if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n }\n }\n\n return headers;\n}\n\n/**\n * Creates a `URL` object from a Node.js `IncomingMessage`, taking into account the protocol, host, and port.\n *\n * @param nodeRequest - The Node.js `IncomingMessage` or `Http2ServerRequest` object to extract URL information from.\n * @returns A `URL` object representing the request URL.\n */\nfunction createRequestUrl(nodeRequest: IncomingMessage | Http2ServerRequest): URL {\n const {\n headers,\n socket,\n url = '',\n originalUrl,\n } = nodeRequest as IncomingMessage & { originalUrl?: string };\n const protocol =\n getFirstHeaderValue(headers['x-forwarded-proto']) ??\n ('encrypted' in socket && socket.encrypted ? 'https' : 'http');\n const hostname =\n getFirstHeaderValue(headers['x-forwarded-host']) ?? headers.host ?? headers[':authority'];\n\n if (Array.isArray(hostname)) {\n throw new Error('host value cannot be an array.');\n }\n\n let hostnameWithPort = hostname;\n if (!hostname?.includes(':')) {\n const port = getFirstHeaderValue(headers['x-forwarded-port']);\n if (port) {\n hostnameWithPort += `:${port}`;\n }\n }\n\n return new URL(originalUrl ?? url, `${protocol}://${hostnameWithPort}`);\n}\n\n/**\n * Extracts the first value from a multi-value header string.\n *\n * @param value - A string or an array of strings representing the header values.\n * If it's a string, values are expected to be comma-separated.\n * @returns The first trimmed value from the multi-value header, or `undefined` if the input is invalid or empty.\n *\n * @example\n * ```typescript\n * getFirstHeaderValue(\"value1, value2, value3\"); // \"value1\"\n * getFirstHeaderValue([\"value1\", \"value2\"]); // \"value1\"\n * getFirstHeaderValue(undefined); // undefined\n * ```\n */\nfunction getFirstHeaderValue(value: string | string[] | undefined): string | undefined {\n return value?.toString().split(',', 1)[0]?.trim();\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { AngularAppEngine } from '@angular/ssr';\nimport type { IncomingMessage } from 'node:http';\nimport type { Http2ServerRequest } from 'node:http2';\nimport { createWebRequestFromNodeRequest } from './request';\n\n/**\n * Angular server application engine.\n * Manages Angular server applications (including localized ones), handles rendering requests,\n * and optionally transforms index HTML before rendering.\n *\n * @remarks This class should be instantiated once and used as a singleton across the server-side\n * application to ensure consistent handling of rendering requests and resource management.\n */\nexport class AngularNodeAppEngine {\n private readonly angularAppEngine = new AngularAppEngine();\n\n /**\n * Handles an incoming HTTP request by serving prerendered content, performing server-side rendering,\n * or delivering a static file for client-side rendered routes based on the `RenderMode` setting.\n *\n * This method adapts Node.js's `IncomingMessage` or `Http2ServerRequest`\n * to a format compatible with the `AngularAppEngine` and delegates the handling logic to it.\n *\n * @param request - The incoming HTTP request (`IncomingMessage` or `Http2ServerRequest`).\n * @param requestContext - Optional context for rendering, such as metadata associated with the request.\n * @returns A promise that resolves to the resulting HTTP response object, or `null` if no matching Angular route is found.\n *\n * @remarks A request to `https://www.example.com/page/index.html` will serve or render the Angular route\n * corresponding to `https://www.example.com/page`.\n */\n async handle(\n request: IncomingMessage | Http2ServerRequest,\n requestContext?: unknown,\n ): Promise<Response | null> {\n const webRequest = createWebRequestFromNodeRequest(request);\n\n return this.angularAppEngine.handle(webRequest, requestContext);\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\n/**\n * Represents a middleware function for handling HTTP requests in a Node.js environment.\n *\n * @param req - The incoming HTTP request object.\n * @param res - The outgoing HTTP response object.\n * @param next - A callback function that signals the completion of the middleware or forwards the error if provided.\n *\n * @returns A Promise that resolves to void or simply void. The handler can be asynchronous.\n */\nexport type NodeRequestHandlerFunction = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (err?: unknown) => void,\n) => Promise<void> | void;\n\n/**\n * Attaches metadata to the handler function to mark it as a special handler for Node.js environments.\n *\n * @typeParam T - The type of the handler function.\n * @param handler - The handler function to be defined and annotated.\n * @returns The same handler function passed as an argument, with metadata attached.\n *\n * @example\n * Usage in an Express application:\n * ```ts\n * const app = express();\n * export default createNodeRequestHandler(app);\n * ```\n *\n * @example\n * Usage in a Hono application:\n * ```ts\n * const app = new Hono();\n * export default createNodeRequestHandler(async (req, res, next) => {\n * try {\n * const webRes = await app.fetch(createWebRequestFromNodeRequest(req));\n * if (webRes) {\n * await writeResponseToNodeResponse(webRes, res);\n * } else {\n * next();\n * }\n * } catch (error) {\n * next(error);\n * }\n * }));\n * ```\n *\n * @example\n * Usage in a Fastify application:\n * ```ts\n * const app = Fastify();\n * export default createNodeRequestHandler(async (req, res) => {\n * await app.ready();\n * app.server.emit('request', req, res);\n * res.send('Hello from Fastify with Node Next Handler!');\n * }));\n * ```\n */\nexport function createNodeRequestHandler<T extends NodeRequestHandlerFunction>(handler: T): T {\n (handler as T & { __ng_node_request_handler__?: boolean })['__ng_node_request_handler__'] = true;\n\n return handler;\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type { ServerResponse } from 'node:http';\nimport type { Http2ServerResponse } from 'node:http2';\n\n/**\n * Streams a web-standard `Response` into a Node.js `ServerResponse`\n * or `Http2ServerResponse`.\n *\n * This function adapts the web `Response` object to write its content\n * to a Node.js response object, handling both HTTP/1.1 and HTTP/2.\n *\n * @param source - The web-standard `Response` object to stream from.\n * @param destination - The Node.js response object (`ServerResponse` or `Http2ServerResponse`) to stream into.\n * @returns A promise that resolves once the streaming operation is complete.\n */\nexport async function writeResponseToNodeResponse(\n source: Response,\n destination: ServerResponse | Http2ServerResponse,\n): Promise<void> {\n const { status, headers, body } = source;\n destination.statusCode = status;\n\n let cookieHeaderSet = false;\n for (const [name, value] of headers.entries()) {\n if (name === 'set-cookie') {\n if (cookieHeaderSet) {\n continue;\n }\n\n // Sets the 'set-cookie' header only once to ensure it is correctly applied.\n // Concatenating 'set-cookie' values can lead to incorrect behavior, so we use a single value from `headers.getSetCookie()`.\n destination.setHeader(name, headers.getSetCookie());\n cookieHeaderSet = true;\n } else {\n destination.setHeader(name, value);\n }\n }\n\n if ('flushHeaders' in destination) {\n destination.flushHeaders();\n }\n\n if (!body) {\n destination.end();\n\n return;\n }\n\n try {\n const reader = body.getReader();\n\n destination.on('close', () => {\n reader.cancel().catch((error) => {\n // eslint-disable-next-line no-console\n console.error(\n `An error occurred while writing the response body for: ${destination.req.url}.`,\n error,\n );\n });\n });\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n destination.end();\n break;\n }\n\n const canContinue = (destination as ServerResponse).write(value);\n if (canContinue === false) {\n // Explicitly check for `false`, as AWS may return `undefined` even though this is not valid.\n // See: https://github.com/CodeGenieApp/serverless-express/issues/683\n await new Promise<void>((resolve) => destination.once('drain', resolve));\n }\n }\n } catch {\n destination.end('Internal server error.');\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { argv } from 'node:process';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Determines whether the provided URL represents the main entry point module.\n *\n * This function checks if the provided URL corresponds to the main ESM module being executed directly.\n * It's useful for conditionally executing code that should only run when a module is the entry point,\n * such as starting a server or initializing an application.\n *\n * It performs two key checks:\n * 1. Verifies if the URL starts with 'file:', ensuring it is a local file.\n * 2. Compares the URL's resolved file path with the first command-line argument (`process.argv[1]`),\n * which points to the file being executed.\n *\n * @param url The URL of the module to check. This should typically be `import.meta.url`.\n * @returns `true` if the provided URL represents the main entry point, otherwise `false`.\n */\nexport function isMainModule(url: string): boolean {\n return url.startsWith('file:') && argv[1] === fileURLToPath(url);\n}\n"],"names":["InlineCriticalCssProcessor","URL","ɵSERVER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AAA,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,MAAK;YAC3B,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,KAAI;;AAE9B,gBAAA,OAAO,CAAC,KAAK,CACX,CAAA,uDAAA,EAA0D,WAAW,CAAC,GAAG,CAAC,GAAG,CAAA,CAAA,CAAG,EAChF,KAAK,CACN;AACH,aAAC,CAAC;AACJ,SAAC,CAAC;;QAGF,OAAO,IAAI,EAAE;YACX,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE;YAC3C,IAAI,IAAI,EAAE;gBACR,WAAW,CAAC,GAAG,EAAE;gBACjB;;YAGF,MAAM,WAAW,GAAI,WAA8B,CAAC,KAAK,CAAC,KAAK,CAAC;AAChE,YAAA,IAAI,WAAW,KAAK,KAAK,EAAE;;;AAGzB,gBAAA,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,KAAK,WAAW,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;;;;AAG5E,IAAA,MAAM;AACN,QAAA,WAAW,CAAC,GAAG,CAAC,wBAAwB,CAAC;;AAE7C;;AC3EA;;;;;;;;;;;;;;AAcG;AACG,SAAU,YAAY,CAAC,GAAW,EAAA;AACtC,IAAA,OAAO,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,aAAa,CAAC,GAAG,CAAC;AAClE;;;;"}
package/fesm2022/ssr.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { ɵConsole as _Console, makeEnvironmentProviders, InjectionToken, ɵENABLE_ROOT_COMPONENT_BOOTSTRAP as _ENABLE_ROOT_COMPONENT_BOOTSTRAP, ApplicationRef, Compiler, runInInjectionContext, ɵresetCompiledComponents as _resetCompiledComponents, REQUEST, REQUEST_CONTEXT, RESPONSE_INIT, LOCALE_ID } from '@angular/core';
1
+ import { ɵConsole as _Console, ApplicationRef, makeEnvironmentProviders, provideEnvironmentInitializer, inject, InjectionToken, ɵENABLE_ROOT_COMPONENT_BOOTSTRAP as _ENABLE_ROOT_COMPONENT_BOOTSTRAP, Compiler, runInInjectionContext, ɵresetCompiledComponents as _resetCompiledComponents, REQUEST, REQUEST_CONTEXT, RESPONSE_INIT, LOCALE_ID } from '@angular/core';
2
+ import { platformServer, INITIAL_CONFIG, ɵSERVER_CONTEXT as _SERVER_CONTEXT, ɵrenderInternal as _renderInternal, provideServerRendering as provideServerRendering$1 } from '@angular/platform-server';
2
3
  import { ROUTES, Router, ɵloadChildren as _loadChildren } from '@angular/router';
3
4
  import { APP_BASE_HREF, PlatformLocation } from '@angular/common';
4
- import { renderModule, renderApplication, ɵSERVER_CONTEXT as _SERVER_CONTEXT, platformServer, INITIAL_CONFIG } from '@angular/platform-server';
5
5
  import Beasties from '../third_party/beasties/index.js';
6
6
 
7
7
  /**
@@ -318,10 +318,20 @@ function buildPathWithParams(toPath, fromPath) {
318
318
  * rendering process.
319
319
  * @param serverContext - A string representing the server context, used to provide additional
320
320
  * context or metadata during server-side rendering.
321
- * @returns A promise that resolves to a string containing the rendered HTML.
321
+ * @returns A promise resolving to an object containing a `content` method, which returns a
322
+ * promise that resolves to the rendered HTML string.
322
323
  */
323
- function renderAngular(html, bootstrap, url, platformProviders, serverContext) {
324
- const providers = [
324
+ async function renderAngular(html, bootstrap, url, platformProviders, serverContext) {
325
+ // A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.
326
+ const urlToRender = stripIndexHtmlFromURL(url).toString();
327
+ const platformRef = platformServer([
328
+ {
329
+ provide: INITIAL_CONFIG,
330
+ useValue: {
331
+ url: urlToRender,
332
+ document: html,
333
+ },
334
+ },
325
335
  {
326
336
  provide: _SERVER_CONTEXT,
327
337
  useValue: serverContext,
@@ -335,20 +345,34 @@ function renderAngular(html, bootstrap, url, platformProviders, serverContext) {
335
345
  useFactory: () => new Console(),
336
346
  },
337
347
  ...platformProviders,
338
- ];
339
- // A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.
340
- const urlToRender = stripIndexHtmlFromURL(url).toString();
341
- return isNgModule(bootstrap)
342
- ? renderModule(bootstrap, {
343
- url: urlToRender,
344
- document: html,
345
- extraProviders: providers,
346
- })
347
- : renderApplication(bootstrap, {
348
- url: urlToRender,
349
- document: html,
350
- platformProviders: providers,
351
- });
348
+ ]);
349
+ try {
350
+ let applicationRef;
351
+ if (isNgModule(bootstrap)) {
352
+ const moduleRef = await platformRef.bootstrapModule(bootstrap);
353
+ applicationRef = moduleRef.injector.get(ApplicationRef);
354
+ }
355
+ else {
356
+ applicationRef = await bootstrap();
357
+ }
358
+ // Block until application is stable.
359
+ await applicationRef.whenStable();
360
+ return {
361
+ content: () => new Promise((resolve, reject) => {
362
+ // Defer rendering to the next event loop iteration to avoid blocking, as most operations in `renderInternal` are synchronous.
363
+ setTimeout(() => {
364
+ _renderInternal(platformRef, applicationRef)
365
+ .then(resolve)
366
+ .catch(reject)
367
+ .finally(() => void asyncDestroyPlatform(platformRef));
368
+ }, 0);
369
+ }),
370
+ };
371
+ }
372
+ catch (error) {
373
+ await asyncDestroyPlatform(platformRef);
374
+ throw error;
375
+ }
352
376
  }
353
377
  /**
354
378
  * Type guard to determine if a given value is an Angular module.
@@ -361,6 +385,20 @@ function renderAngular(html, bootstrap, url, platformProviders, serverContext) {
361
385
  function isNgModule(value) {
362
386
  return 'ɵmod' in value;
363
387
  }
388
+ /**
389
+ * Gracefully destroys the application in a macrotask, allowing pending promises to resolve
390
+ * and surfacing any potential errors to the user.
391
+ *
392
+ * @param platformRef - The platform reference to be destroyed.
393
+ */
394
+ function asyncDestroyPlatform(platformRef) {
395
+ return new Promise((resolve) => {
396
+ setTimeout(() => {
397
+ platformRef.destroy();
398
+ resolve();
399
+ }, 0);
400
+ });
401
+ }
364
402
 
365
403
  /**
366
404
  * Creates a promise that resolves with the result of the provided `promise` or rejects with an
@@ -401,19 +439,18 @@ function promiseWithAbort(promise, signal, errorMessagePrefix) {
401
439
  */
402
440
  const APP_SHELL_ROUTE = 'ng-app-shell';
403
441
  /**
404
- * Identifies a particular kind of `ServerRoutesFeatureKind`.
405
- * @see {@link ServerRoutesFeature}
406
- * @developerPreview
442
+ * Identifies a particular kind of `ServerRenderingFeatureKind`.
443
+ * @see {@link ServerRenderingFeature}
407
444
  */
408
- var ServerRoutesFeatureKind;
409
- (function (ServerRoutesFeatureKind) {
410
- ServerRoutesFeatureKind[ServerRoutesFeatureKind["AppShell"] = 0] = "AppShell";
411
- })(ServerRoutesFeatureKind || (ServerRoutesFeatureKind = {}));
445
+ var ServerRenderingFeatureKind;
446
+ (function (ServerRenderingFeatureKind) {
447
+ ServerRenderingFeatureKind[ServerRenderingFeatureKind["AppShell"] = 0] = "AppShell";
448
+ ServerRenderingFeatureKind[ServerRenderingFeatureKind["ServerRoutes"] = 1] = "ServerRoutes";
449
+ })(ServerRenderingFeatureKind || (ServerRenderingFeatureKind = {}));
412
450
  /**
413
451
  * Different rendering modes for server routes.
414
- * @see {@link provideServerRouting}
452
+ * @see {@link withRoutes}
415
453
  * @see {@link ServerRoute}
416
- * @developerPreview
417
454
  */
418
455
  var RenderMode;
419
456
  (function (RenderMode) {
@@ -428,7 +465,6 @@ var RenderMode;
428
465
  * Defines the fallback strategies for Static Site Generation (SSG) routes when a pre-rendered path is not available.
429
466
  * This is particularly relevant for routes with parameterized URLs where some paths might not be pre-rendered at build time.
430
467
  * @see {@link ServerRoutePrerenderWithParams}
431
- * @developerPreview
432
468
  */
433
469
  var PrerenderFallback;
434
470
  (function (PrerenderFallback) {
@@ -454,52 +490,95 @@ var PrerenderFallback;
454
490
  */
455
491
  const SERVER_ROUTES_CONFIG = new InjectionToken('SERVER_ROUTES_CONFIG');
456
492
  /**
457
- * Sets up the necessary providers for configuring server routes.
458
- * This function accepts an array of server routes and optional configuration
459
- * options, returning an `EnvironmentProviders` object that encapsulates
460
- * the server routes and configuration settings.
493
+ * Configures server-side routing for the application.
461
494
  *
462
- * @param routes - An array of server routes to be provided.
463
- * @param features - (Optional) server routes features.
464
- * @returns An `EnvironmentProviders` instance with the server routes configuration.
495
+ * This function registers an array of `ServerRoute` definitions, enabling server-side rendering
496
+ * for specific URL paths. These routes are used to pre-render content on the server, improving
497
+ * initial load performance and SEO.
465
498
  *
499
+ * @param routes - An array of `ServerRoute` objects, each defining a server-rendered route.
500
+ * @returns A `ServerRenderingFeature` object configuring server-side routes.
501
+ *
502
+ * @example
503
+ * ```ts
504
+ * import { provideServerRendering, withRoutes, ServerRoute, RenderMode } from '@angular/ssr';
505
+ *
506
+ * const serverRoutes: ServerRoute[] = [
507
+ * {
508
+ * route: '', // This renders the "/" route on the client (CSR)
509
+ * renderMode: RenderMode.Client,
510
+ * },
511
+ * {
512
+ * route: 'about', // This page is static, so we prerender it (SSG)
513
+ * renderMode: RenderMode.Prerender,
514
+ * },
515
+ * {
516
+ * route: 'profile', // This page requires user-specific data, so we use SSR
517
+ * renderMode: RenderMode.Server,
518
+ * },
519
+ * {
520
+ * route: '**', // All other routes will be rendered on the server (SSR)
521
+ * renderMode: RenderMode.Server,
522
+ * },
523
+ * ];
524
+ *
525
+ * provideServerRendering(withRoutes(serverRoutes));
526
+ * ```
527
+ *
528
+ * @see {@link provideServerRendering}
466
529
  * @see {@link ServerRoute}
467
- * @see {@link withAppShell}
468
- * @developerPreview
469
530
  */
470
- function provideServerRouting(routes, ...features) {
531
+ function withRoutes(routes) {
471
532
  const config = { routes };
472
- const hasAppShell = features.some((f) => f.ɵkind === ServerRoutesFeatureKind.AppShell);
473
- if (hasAppShell) {
474
- config.appShellRoute = APP_SHELL_ROUTE;
475
- }
476
- const providers = [
477
- {
478
- provide: SERVER_ROUTES_CONFIG,
479
- useValue: config,
480
- },
481
- ];
482
- for (const feature of features) {
483
- providers.push(...feature.ɵproviders);
484
- }
485
- return makeEnvironmentProviders(providers);
533
+ return {
534
+ ɵkind: ServerRenderingFeatureKind.ServerRoutes,
535
+ ɵproviders: [
536
+ {
537
+ provide: SERVER_ROUTES_CONFIG,
538
+ useValue: config,
539
+ },
540
+ ],
541
+ };
486
542
  }
487
543
  /**
488
- * Configures the app shell route with the provided component.
544
+ * Configures the shell of the application.
489
545
  *
490
- * The app shell serves as the main entry point for the application and is commonly used
491
- * to enable server-side rendering (SSR) of the application shell. It handles requests
492
- * that do not match any specific server route, providing a fallback mechanism and improving
493
- * perceived performance during navigation.
546
+ * The app shell is a minimal, static HTML page that is served immediately, while the
547
+ * full Angular application loads in the background. This improves perceived performance
548
+ * by providing instant feedback to the user.
494
549
  *
495
- * This configuration is particularly useful in applications leveraging Progressive Web App (PWA)
496
- * patterns, such as service workers, to deliver a seamless user experience.
550
+ * This function configures the app shell route, which serves the provided component for
551
+ * requests that do not match any defined server routes.
497
552
  *
498
- * @param component The Angular component to render for the app shell route.
499
- * @returns A server routes feature configuration for the app shell.
553
+ * @param component - The Angular component to render for the app shell. Can be a direct
554
+ * component type or a dynamic import function.
555
+ * @returns A `ServerRenderingFeature` object configuring the app shell.
500
556
  *
501
- * @see {@link provideServerRouting}
502
- * @see {@link https://angular.dev/ecosystem/service-workers/app-shell | App shell pattern on Angular.dev}
557
+ * @example
558
+ * ```ts
559
+ * import { provideServerRendering, withAppShell, withRoutes } from '@angular/ssr';
560
+ * import { AppShellComponent } from './app-shell.component';
561
+ *
562
+ * provideServerRendering(
563
+ * withRoutes(serverRoutes),
564
+ * withAppShell(AppShellComponent)
565
+ * );
566
+ * ```
567
+ *
568
+ * @example
569
+ * ```ts
570
+ * import { provideServerRendering, withAppShell, withRoutes } from '@angular/ssr';
571
+ *
572
+ * provideServerRendering(
573
+ * withRoutes(serverRoutes),
574
+ * withAppShell(() =>
575
+ * import('./app-shell.component').then((m) => m.AppShellComponent)
576
+ * )
577
+ * );
578
+ * ```
579
+ *
580
+ * @see {@link provideServerRendering}
581
+ * @see {@link https://angular.dev/ecosystem/service-workers/app-shell App shell pattern on Angular.dev}
503
582
  */
504
583
  function withAppShell(component) {
505
584
  const routeConfig = {
@@ -512,16 +591,68 @@ function withAppShell(component) {
512
591
  routeConfig.loadComponent = component;
513
592
  }
514
593
  return {
515
- ɵkind: ServerRoutesFeatureKind.AppShell,
594
+ ɵkind: ServerRenderingFeatureKind.AppShell,
516
595
  ɵproviders: [
517
596
  {
518
597
  provide: ROUTES,
519
598
  useValue: routeConfig,
520
599
  multi: true,
521
600
  },
601
+ provideEnvironmentInitializer(() => {
602
+ const config = inject(SERVER_ROUTES_CONFIG);
603
+ config.appShellRoute = APP_SHELL_ROUTE;
604
+ }),
522
605
  ],
523
606
  };
524
607
  }
608
+ /**
609
+ * Configures server-side rendering for an Angular application.
610
+ *
611
+ * This function sets up the necessary providers for server-side rendering, including
612
+ * support for server routes and app shell. It combines features configured using
613
+ * `withRoutes` and `withAppShell` to provide a comprehensive server-side rendering setup.
614
+ *
615
+ * @param features - Optional features to configure additional server rendering behaviors.
616
+ * @returns An `EnvironmentProviders` instance with the server-side rendering configuration.
617
+ *
618
+ * @example
619
+ * Basic example of how you can enable server-side rendering in your application
620
+ * when using the `bootstrapApplication` function:
621
+ *
622
+ * ```ts
623
+ * import { bootstrapApplication } from '@angular/platform-browser';
624
+ * import { provideServerRendering, withRoutes, withAppShell } from '@angular/ssr';
625
+ * import { AppComponent } from './app/app.component';
626
+ * import { SERVER_ROUTES } from './app/app.server.routes';
627
+ * import { AppShellComponent } from './app/app-shell.component';
628
+ *
629
+ * bootstrapApplication(AppComponent, {
630
+ * providers: [
631
+ * provideServerRendering(
632
+ * withRoutes(SERVER_ROUTES),
633
+ * withAppShell(AppShellComponent)
634
+ * )
635
+ * ]
636
+ * });
637
+ * ```
638
+ * @see {@link withRoutes} configures server-side routing
639
+ * @see {@link withAppShell} configures the application shell
640
+ */
641
+ function provideServerRendering(...features) {
642
+ let hasAppShell = false;
643
+ let hasServerRoutes = false;
644
+ const providers = [provideServerRendering$1()];
645
+ for (const { ɵkind, ɵproviders } of features) {
646
+ hasAppShell ||= ɵkind === ServerRenderingFeatureKind.AppShell;
647
+ hasServerRoutes ||= ɵkind === ServerRenderingFeatureKind.ServerRoutes;
648
+ providers.push(...ɵproviders);
649
+ }
650
+ if (!hasServerRoutes && hasAppShell) {
651
+ throw new Error(`Configuration error: found 'withAppShell()' without 'withRoutes()' in the same call to 'provideServerRendering()'.` +
652
+ `The 'withAppShell()' function requires 'withRoutes()' to be used.`);
653
+ }
654
+ return makeEnvironmentProviders(providers);
655
+ }
525
656
 
526
657
  /**
527
658
  * A route tree implementation that supports efficient route matching, including support for wildcard routes.
@@ -1720,6 +1851,12 @@ class AngularServerApp {
1720
1851
  this.options = options;
1721
1852
  this.allowStaticRouteRender = this.options.allowStaticRouteRender ?? false;
1722
1853
  this.hooks = options.hooks ?? new Hooks();
1854
+ if (this.manifest.inlineCriticalCss) {
1855
+ this.inlineCriticalCssProcessor = new InlineCriticalCssProcessor((path) => {
1856
+ const fileName = path.split('/').pop() ?? path;
1857
+ return this.assets.getServerAsset(fileName).text();
1858
+ });
1859
+ }
1723
1860
  }
1724
1861
  /**
1725
1862
  * The manifest associated with this server application.
@@ -1848,7 +1985,7 @@ class AngularServerApp {
1848
1985
  }
1849
1986
  const url = new URL(request.url);
1850
1987
  const platformProviders = [];
1851
- const { manifest: { bootstrap, inlineCriticalCss, locale }, assets, } = this;
1988
+ const { manifest: { bootstrap, locale }, assets, } = this;
1852
1989
  // Initialize the response with status and headers if available.
1853
1990
  const responseInit = {
1854
1991
  status,
@@ -1886,37 +2023,36 @@ class AngularServerApp {
1886
2023
  this.boostrap ??= await bootstrap();
1887
2024
  let html = await assets.getIndexServerHtml().text();
1888
2025
  html = await this.runTransformsOnHtml(html, url, preload);
1889
- html = await renderAngular(html, this.boostrap, url, platformProviders, SERVER_CONTEXT_VALUE[renderMode]);
1890
- if (!inlineCriticalCss) {
1891
- return new Response(html, responseInit);
1892
- }
1893
- this.inlineCriticalCssProcessor ??= new InlineCriticalCssProcessor((path) => {
1894
- const fileName = path.split('/').pop() ?? path;
1895
- return this.assets.getServerAsset(fileName).text();
1896
- });
2026
+ const { content } = await renderAngular(html, this.boostrap, url, platformProviders, SERVER_CONTEXT_VALUE[renderMode]);
1897
2027
  const { inlineCriticalCssProcessor, criticalCssLRUCache, textDecoder } = this;
1898
- // Use a stream to send the response before inlining critical CSS, improving performance via header flushing.
2028
+ // Use a stream to send the response before finishing rendering and inling critical CSS, improving performance via header flushing.
1899
2029
  const stream = new ReadableStream({
1900
2030
  async start(controller) {
2031
+ const renderedHtml = await content();
2032
+ if (!inlineCriticalCssProcessor) {
2033
+ controller.enqueue(textDecoder.encode(renderedHtml));
2034
+ controller.close();
2035
+ return;
2036
+ }
1901
2037
  let htmlWithCriticalCss;
1902
2038
  try {
1903
2039
  if (renderMode === RenderMode.Server) {
1904
- const cacheKey = await sha256(html);
2040
+ const cacheKey = await sha256(renderedHtml);
1905
2041
  htmlWithCriticalCss = criticalCssLRUCache.get(cacheKey);
1906
2042
  if (!htmlWithCriticalCss) {
1907
- htmlWithCriticalCss = await inlineCriticalCssProcessor.process(html);
2043
+ htmlWithCriticalCss = await inlineCriticalCssProcessor.process(renderedHtml);
1908
2044
  criticalCssLRUCache.put(cacheKey, htmlWithCriticalCss);
1909
2045
  }
1910
2046
  }
1911
2047
  else {
1912
- htmlWithCriticalCss = await inlineCriticalCssProcessor.process(html);
2048
+ htmlWithCriticalCss = await inlineCriticalCssProcessor.process(renderedHtml);
1913
2049
  }
1914
2050
  }
1915
2051
  catch (error) {
1916
2052
  // eslint-disable-next-line no-console
1917
2053
  console.error(`An error occurred while inlining critical CSS for: ${url}.`, error);
1918
2054
  }
1919
- controller.enqueue(textDecoder.encode(htmlWithCriticalCss ?? html));
2055
+ controller.enqueue(textDecoder.encode(htmlWithCriticalCss ?? renderedHtml));
1920
2056
  controller.close();
1921
2057
  },
1922
2058
  });
@@ -2199,8 +2335,6 @@ function normalizeLocale(locale) {
2199
2335
  *
2200
2336
  * @remarks This class should be instantiated once and used as a singleton across the server-side
2201
2337
  * application to ensure consistent handling of rendering requests and resource management.
2202
- *
2203
- * @developerPreview
2204
2338
  */
2205
2339
  class AngularAppEngine {
2206
2340
  /**
@@ -2375,12 +2509,11 @@ class AngularAppEngine {
2375
2509
  * const handler = toWebHandler(app);
2376
2510
  * export default createRequestHandler(handler);
2377
2511
  * ```
2378
- * @developerPreview
2379
2512
  */
2380
2513
  function createRequestHandler(handler) {
2381
2514
  handler['__ng_request_handler__'] = true;
2382
2515
  return handler;
2383
2516
  }
2384
2517
 
2385
- export { AngularAppEngine, PrerenderFallback, RenderMode, createRequestHandler, provideServerRouting, withAppShell, InlineCriticalCssProcessor as ɵInlineCriticalCssProcessor, destroyAngularServerApp as ɵdestroyAngularServerApp, extractRoutesAndCreateRouteTree as ɵextractRoutesAndCreateRouteTree, getOrCreateAngularServerApp as ɵgetOrCreateAngularServerApp, getRoutesFromAngularRouterConfig as ɵgetRoutesFromAngularRouterConfig, setAngularAppEngineManifest as ɵsetAngularAppEngineManifest, setAngularAppManifest as ɵsetAngularAppManifest };
2518
+ export { AngularAppEngine, PrerenderFallback, RenderMode, createRequestHandler, provideServerRendering, withAppShell, withRoutes, InlineCriticalCssProcessor as ɵInlineCriticalCssProcessor, destroyAngularServerApp as ɵdestroyAngularServerApp, extractRoutesAndCreateRouteTree as ɵextractRoutesAndCreateRouteTree, getOrCreateAngularServerApp as ɵgetOrCreateAngularServerApp, getRoutesFromAngularRouterConfig as ɵgetRoutesFromAngularRouterConfig, setAngularAppEngineManifest as ɵsetAngularAppEngineManifest, setAngularAppManifest as ɵsetAngularAppManifest };
2386
2519
  //# sourceMappingURL=ssr.mjs.map