@angular/ssr 21.0.3 → 21.0.5

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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  The MIT License
2
2
 
3
- Copyright (c) 2010-2025 Google LLC. https://angular.dev/license
3
+ Copyright (c) 2010-2026 Google LLC. https://angular.dev/license
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/fesm2022/ssr.mjs CHANGED
@@ -234,6 +234,22 @@ function promiseWithAbort(promise, signal, errorMessagePrefix) {
234
234
  });
235
235
  }
236
236
 
237
+ const VALID_REDIRECT_RESPONSE_CODES = new Set([301, 302, 303, 307, 308]);
238
+ function isValidRedirectResponseCode(code) {
239
+ return VALID_REDIRECT_RESPONSE_CODES.has(code);
240
+ }
241
+ function createRedirectResponse(location, status = 302) {
242
+ if (ngDevMode && !isValidRedirectResponseCode(status)) {
243
+ throw new Error(`Invalid redirect status code: ${status}. ` + `Please use one of the following redirect response codes: ${[...VALID_REDIRECT_RESPONSE_CODES.values()].join(', ')}.`);
244
+ }
245
+ return new Response(null, {
246
+ status,
247
+ headers: {
248
+ 'Location': location
249
+ }
250
+ });
251
+ }
252
+
237
253
  const APP_SHELL_ROUTE = 'ng-app-shell';
238
254
  var ServerRenderingFeatureKind;
239
255
  (function (ServerRenderingFeatureKind) {
@@ -387,7 +403,6 @@ class RouteTree {
387
403
  const MODULE_PRELOAD_MAX = 10;
388
404
  const CATCH_ALL_REGEXP = /\/(\*\*)$/;
389
405
  const URL_PARAMETER_REGEXP = /(?<!\\):([^/]+)/g;
390
- const VALID_REDIRECT_RESPONSE_CODES = new Set([301, 302, 303, 307, 308]);
391
406
  async function* handleRoute(options) {
392
407
  try {
393
408
  const {
@@ -414,7 +429,7 @@ async function* handleRoute(options) {
414
429
  if (metadata.renderMode === RenderMode.Prerender) {
415
430
  yield* handleSSGRoute(serverConfigRouteTree, typeof redirectTo === 'string' ? redirectTo : undefined, metadata, parentInjector, invokeGetPrerenderParams, includePrerenderFallbackRoutes);
416
431
  } else if (redirectTo !== undefined) {
417
- if (metadata.status && !VALID_REDIRECT_RESPONSE_CODES.has(metadata.status)) {
432
+ if (metadata.status && !isValidRedirectResponseCode(metadata.status)) {
418
433
  yield {
419
434
  error: `The '${metadata.status}' status code is not a valid redirect response code. ` + `Please use one of the following redirect response codes: ${[...VALID_REDIRECT_RESPONSE_CODES.values()].join(', ')}.`
420
435
  };
@@ -1092,6 +1107,7 @@ class LRUCache {
1092
1107
  }
1093
1108
  }
1094
1109
 
1110
+ const WELL_KNOWN_NON_ANGULAR_URLS = new Set(['/favicon.ico', '/.well-known/appspecific/com.chrome.devtools.json']);
1095
1111
  const MAX_INLINE_CSS_CACHE_ENTRIES = 50;
1096
1112
  const SERVER_CONTEXT_VALUE = {
1097
1113
  [RenderMode.Prerender]: 'ssg',
@@ -1122,6 +1138,9 @@ class AngularServerApp {
1122
1138
  criticalCssLRUCache = new LRUCache(MAX_INLINE_CSS_CACHE_ENTRIES);
1123
1139
  async handle(request, requestContext) {
1124
1140
  const url = new URL(request.url);
1141
+ if (WELL_KNOWN_NON_ANGULAR_URLS.has(url.pathname)) {
1142
+ return null;
1143
+ }
1125
1144
  this.router ??= await ServerRouter.from(this.manifest, url);
1126
1145
  const matchedRoute = this.router.match(url);
1127
1146
  if (!matchedRoute) {
@@ -1247,7 +1266,7 @@ class AngularServerApp {
1247
1266
  return null;
1248
1267
  }
1249
1268
  if (result.redirectTo) {
1250
- return createRedirectResponse(result.redirectTo, status);
1269
+ return createRedirectResponse(result.redirectTo, responseInit.status);
1251
1270
  }
1252
1271
  if (renderMode === RenderMode.Prerender) {
1253
1272
  const renderedHtml = await result.content();
@@ -1346,14 +1365,6 @@ function appendPreloadHintsToHtml(html, preload) {
1346
1365
  }
1347
1366
  return [html.slice(0, bodyCloseIdx), ...preload.map(val => `<link rel="modulepreload" href="${val}">`), html.slice(bodyCloseIdx)].join('\n');
1348
1367
  }
1349
- function createRedirectResponse(location, status = 302) {
1350
- return new Response(null, {
1351
- status,
1352
- headers: {
1353
- 'Location': location
1354
- }
1355
- });
1356
- }
1357
1368
 
1358
1369
  function getPotentialLocaleIdFromUrl(url, basePath) {
1359
1370
  const {
@@ -1 +1 @@
1
- {"version":3,"file":"ssr.mjs","sources":["../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/assets.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/console.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/manifest.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/url.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/ng.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/promise.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/routes/route-config.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/routes/route-tree.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/routes/ng-routes.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/hooks.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/routes/router.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/crypto.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/inline-critical-css.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/lru-cache.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/app.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/i18n.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/app-engine.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/handler.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 { AngularAppManifest, ServerAsset } from './manifest';\n\n/**\n * Manages server-side assets.\n */\nexport class ServerAssets {\n /**\n * Creates an instance of ServerAsset.\n *\n * @param manifest - The manifest containing the server assets.\n */\n constructor(private readonly manifest: AngularAppManifest) {}\n\n /**\n * Retrieves the content of a server-side asset using its path.\n *\n * @param path - The path to the server asset within the manifest.\n * @returns The server asset associated with the provided path, as a `ServerAsset` object.\n * @throws Error - Throws an error if the asset does not exist.\n */\n getServerAsset(path: string): ServerAsset {\n const asset = this.manifest.assets[path];\n if (!asset) {\n throw new Error(`Server asset '${path}' does not exist.`);\n }\n\n return asset;\n }\n\n /**\n * Checks if a specific server-side asset exists.\n *\n * @param path - The path to the server asset.\n * @returns A boolean indicating whether the asset exists.\n */\n hasServerAsset(path: string): boolean {\n return !!this.manifest.assets[path];\n }\n\n /**\n * Retrieves the asset for 'index.server.html'.\n *\n * @returns The `ServerAsset` object for 'index.server.html'.\n * @throws Error - Throws an error if 'index.server.html' does not exist.\n */\n getIndexServerHtml(): ServerAsset {\n return this.getServerAsset('index.server.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\nimport { ɵConsole } from '@angular/core';\n\n/**\n * A set of log messages that should be ignored and not printed to the console.\n */\nconst IGNORED_LOGS = new Set(['Angular is running in development mode.']);\n\n/**\n * Custom implementation of the Angular Console service that filters out specific log messages.\n *\n * This class extends the internal Angular `ɵConsole` class to provide customized logging behavior.\n * It overrides the `log` method to suppress logs that match certain predefined messages.\n */\nexport class Console extends ɵConsole {\n /**\n * Logs a message to the console if it is not in the set of ignored messages.\n *\n * @param message - The message to log to the console.\n *\n * This method overrides the `log` method of the `ɵConsole` class. It checks if the\n * message is in the `IGNORED_LOGS` set. If it is not, it delegates the logging to\n * the parent class's `log` method. Otherwise, the message is suppressed.\n */\n override log(message: string): void {\n if (!IGNORED_LOGS.has(message)) {\n super.log(message);\n }\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 { BootstrapContext } from '@angular/platform-browser';\nimport type { SerializableRouteTreeNode } from './routes/route-tree';\nimport { AngularBootstrap } from './utils/ng';\n\n/**\n * Represents a server asset stored in the manifest.\n */\nexport interface ServerAsset {\n /**\n * Retrieves the text content of the asset.\n *\n * @returns A promise that resolves to the asset's content as a string.\n */\n text: () => Promise<string>;\n\n /**\n * A hash string representing the asset's content.\n */\n hash: string;\n\n /**\n * The size of the asset's content in bytes.\n */\n size: number;\n}\n\n/**\n * Represents the exports of an Angular server application entry point.\n */\nexport interface EntryPointExports {\n /**\n * A reference to the function that creates an Angular server application instance.\n *\n * @remarks The return type is `unknown` to prevent circular dependency issues.\n */\n ɵgetOrCreateAngularServerApp: () => unknown;\n\n /**\n * A reference to the function that destroys the `AngularServerApp` instance.\n */\n ɵdestroyAngularServerApp: () => void;\n}\n\n/**\n * Manifest for the Angular server application engine, defining entry points.\n */\nexport interface AngularAppEngineManifest {\n /**\n * A readonly record of entry points for the server application.\n * Each entry consists of:\n * - `key`: The url segment for the entry point.\n * - `value`: A function that returns a promise resolving to an object of type `EntryPointExports`.\n */\n readonly entryPoints: Readonly<Record<string, (() => Promise<EntryPointExports>) | undefined>>;\n\n /**\n * The base path for the server application.\n * This is used to determine the root path of the application.\n */\n readonly basePath: string;\n\n /**\n * A readonly record mapping supported locales to their respective entry-point paths.\n * Each entry consists of:\n * - `key`: The locale identifier (e.g., 'en', 'fr').\n * - `value`: The url segment associated with that locale.\n */\n readonly supportedLocales: Readonly<Record<string, string>>;\n}\n\n/**\n * Manifest for a specific Angular server application, defining assets and bootstrap logic.\n */\nexport interface AngularAppManifest {\n /**\n * The base href for the application.\n * This is used to determine the root path of the application.\n */\n readonly baseHref: string;\n\n /**\n * A readonly record of assets required by the server application.\n * Each entry consists of:\n * - `key`: The path of the asset.\n * - `value`: An object of type `ServerAsset`.\n */\n readonly assets: Readonly<Record<string, ServerAsset | undefined>>;\n\n /**\n * The bootstrap mechanism for the server application.\n * A function that returns a promise that resolves to an `NgModule` or a function\n * returning a promise that resolves to an `ApplicationRef`.\n */\n readonly bootstrap: () => Promise<AngularBootstrap>;\n\n /**\n * Indicates whether critical CSS should be inlined into the HTML.\n * If set to `true`, critical CSS will be inlined for faster page rendering.\n */\n readonly inlineCriticalCss?: boolean;\n\n /**\n * The route tree representation for the routing configuration of the application.\n * This represents the routing information of the application, mapping route paths to their corresponding metadata.\n * It is used for route matching and navigation within the server application.\n */\n readonly routes?: SerializableRouteTreeNode;\n\n /**\n * An optional string representing the locale or language code to be used for\n * the application, aiding with localization and rendering content specific to the locale.\n */\n readonly locale?: string;\n\n /**\n * Maps entry-point names to their corresponding browser bundles and loading strategies.\n *\n * - **Key**: The entry-point name, typically the value of `ɵentryName`.\n * - **Value**: A readonly array of JavaScript bundle paths or `undefined` if no bundles are associated.\n *\n * ### Example\n * ```ts\n * {\n * 'src/app/lazy/lazy.ts': ['src/app/lazy/lazy.js']\n * }\n * ```\n */\n readonly entryPointToBrowserMapping?: Readonly<Record<string, readonly string[] | undefined>>;\n}\n\n/**\n * The Angular app manifest object.\n * This is used internally to store the current Angular app manifest.\n */\nlet angularAppManifest: AngularAppManifest | undefined;\n\n/**\n * Sets the Angular app manifest.\n *\n * @param manifest - The manifest object to set for the Angular application.\n */\nexport function setAngularAppManifest(manifest: AngularAppManifest): void {\n angularAppManifest = manifest;\n}\n\n/**\n * Gets the Angular app manifest.\n *\n * @returns The Angular app manifest.\n * @throws Will throw an error if the Angular app manifest is not set.\n */\nexport function getAngularAppManifest(): AngularAppManifest {\n if (!angularAppManifest) {\n throw new Error(\n 'Angular app manifest is not set. ' +\n `Please ensure you are using the '@angular/build:application' builder to build your server application.`,\n );\n }\n\n return angularAppManifest;\n}\n\n/**\n * The Angular app engine manifest object.\n * This is used internally to store the current Angular app engine manifest.\n */\nlet angularAppEngineManifest: AngularAppEngineManifest | undefined;\n\n/**\n * Sets the Angular app engine manifest.\n *\n * @param manifest - The engine manifest object to set.\n */\nexport function setAngularAppEngineManifest(manifest: AngularAppEngineManifest): void {\n angularAppEngineManifest = manifest;\n}\n\n/**\n * Gets the Angular app engine manifest.\n *\n * @returns The Angular app engine manifest.\n * @throws Will throw an error if the Angular app engine manifest is not set.\n */\nexport function getAngularAppEngineManifest(): AngularAppEngineManifest {\n if (!angularAppEngineManifest) {\n throw new Error(\n 'Angular app engine manifest is not set. ' +\n `Please ensure you are using the '@angular/build:application' builder to build your server application.`,\n );\n }\n\n return angularAppEngineManifest;\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\n/**\n * Removes the trailing slash from a URL if it exists.\n *\n * @param url - The URL string from which to remove the trailing slash.\n * @returns The URL string without a trailing slash.\n *\n * @example\n * ```js\n * stripTrailingSlash('path/'); // 'path'\n * stripTrailingSlash('/path'); // '/path'\n * stripTrailingSlash('/'); // '/'\n * stripTrailingSlash(''); // ''\n * ```\n */\nexport function stripTrailingSlash(url: string): string {\n // Check if the last character of the URL is a slash\n return url.length > 1 && url.at(-1) === '/' ? url.slice(0, -1) : url;\n}\n\n/**\n * Removes the leading slash from a URL if it exists.\n *\n * @param url - The URL string from which to remove the leading slash.\n * @returns The URL string without a leading slash.\n *\n * @example\n * ```js\n * stripLeadingSlash('/path'); // 'path'\n * stripLeadingSlash('/path/'); // 'path/'\n * stripLeadingSlash('/'); // '/'\n * stripLeadingSlash(''); // ''\n * ```\n */\nexport function stripLeadingSlash(url: string): string {\n // Check if the first character of the URL is a slash\n return url.length > 1 && url[0] === '/' ? url.slice(1) : url;\n}\n\n/**\n * Adds a leading slash to a URL if it does not already have one.\n *\n * @param url - The URL string to which the leading slash will be added.\n * @returns The URL string with a leading slash.\n *\n * @example\n * ```js\n * addLeadingSlash('path'); // '/path'\n * addLeadingSlash('/path'); // '/path'\n * ```\n */\nexport function addLeadingSlash(url: string): string {\n // Check if the URL already starts with a slash\n return url[0] === '/' ? url : `/${url}`;\n}\n\n/**\n * Adds a trailing slash to a URL if it does not already have one.\n *\n * @param url - The URL string to which the trailing slash will be added.\n * @returns The URL string with a trailing slash.\n *\n * @example\n * ```js\n * addTrailingSlash('path'); // 'path/'\n * addTrailingSlash('path/'); // 'path/'\n * ```\n */\nexport function addTrailingSlash(url: string): string {\n // Check if the URL already end with a slash\n return url.at(-1) === '/' ? url : `${url}/`;\n}\n\n/**\n * Joins URL parts into a single URL string.\n *\n * This function takes multiple URL segments, normalizes them by removing leading\n * and trailing slashes where appropriate, and then joins them into a single URL.\n *\n * @param parts - The parts of the URL to join. Each part can be a string with or without slashes.\n * @returns The joined URL string, with normalized slashes.\n *\n * @example\n * ```js\n * joinUrlParts('path/', '/to/resource'); // '/path/to/resource'\n * joinUrlParts('/path/', 'to/resource'); // '/path/to/resource'\n * joinUrlParts('', ''); // '/'\n * ```\n */\nexport function joinUrlParts(...parts: string[]): string {\n const normalizeParts: string[] = [];\n for (const part of parts) {\n if (part === '') {\n // Skip any empty parts\n continue;\n }\n\n let normalizedPart = part;\n if (part[0] === '/') {\n normalizedPart = normalizedPart.slice(1);\n }\n if (part.at(-1) === '/') {\n normalizedPart = normalizedPart.slice(0, -1);\n }\n if (normalizedPart !== '') {\n normalizeParts.push(normalizedPart);\n }\n }\n\n return addLeadingSlash(normalizeParts.join('/'));\n}\n\n/**\n * Strips `/index.html` from the end of a URL's path, if present.\n *\n * This function is used to convert URLs pointing to an `index.html` file into their directory\n * equivalents. For example, it transforms a URL like `http://www.example.com/page/index.html`\n * into `http://www.example.com/page`.\n *\n * @param url - The URL object to process.\n * @returns A new URL object with `/index.html` removed from the path, if it was present.\n *\n * @example\n * ```typescript\n * const originalUrl = new URL('http://www.example.com/page/index.html');\n * const cleanedUrl = stripIndexHtmlFromURL(originalUrl);\n * console.log(cleanedUrl.href); // Output: 'http://www.example.com/page'\n * ```\n */\nexport function stripIndexHtmlFromURL(url: URL): URL {\n if (url.pathname.endsWith('/index.html')) {\n const modifiedURL = new URL(url);\n // Remove '/index.html' from the pathname\n modifiedURL.pathname = modifiedURL.pathname.slice(0, /** '/index.html'.length */ -11);\n\n return modifiedURL;\n }\n\n return url;\n}\n\n/**\n * Resolves `*` placeholders in a path template by mapping them to corresponding segments\n * from a base path. This is useful for constructing paths dynamically based on a given base path.\n *\n * The function processes the `toPath` string, replacing each `*` placeholder with\n * the corresponding segment from the `fromPath`. If the `toPath` contains no placeholders,\n * it is returned as-is. Invalid `toPath` formats (not starting with `/`) will throw an error.\n *\n * @param toPath - A path template string that may contain `*` placeholders. Each `*` is replaced\n * by the corresponding segment from the `fromPath`. Static paths (e.g., `/static/path`) are returned\n * directly without placeholder replacement.\n * @param fromPath - A base path string, split into segments, that provides values for\n * replacing `*` placeholders in the `toPath`.\n * @returns A resolved path string with `*` placeholders replaced by segments from the `fromPath`,\n * or the `toPath` returned unchanged if it contains no placeholders.\n *\n * @throws If the `toPath` does not start with a `/`, indicating an invalid path format.\n *\n * @example\n * ```typescript\n * // Example with placeholders resolved\n * const resolvedPath = buildPathWithParams('/*\\/details', '/123/abc');\n * console.log(resolvedPath); // Outputs: '/123/details'\n *\n * // Example with a static path\n * const staticPath = buildPathWithParams('/static/path', '/base/unused');\n * console.log(staticPath); // Outputs: '/static/path'\n * ```\n */\nexport function buildPathWithParams(toPath: string, fromPath: string): string {\n if (toPath[0] !== '/') {\n throw new Error(`Invalid toPath: The string must start with a '/'. Received: '${toPath}'`);\n }\n\n if (fromPath[0] !== '/') {\n throw new Error(`Invalid fromPath: The string must start with a '/'. Received: '${fromPath}'`);\n }\n\n if (!toPath.includes('/*')) {\n return toPath;\n }\n\n const fromPathParts = fromPath.split('/');\n const toPathParts = toPath.split('/');\n const resolvedParts = toPathParts.map((part, index) =>\n toPathParts[index] === '*' ? fromPathParts[index] : part,\n );\n\n return joinUrlParts(...resolvedParts);\n}\n\nconst MATRIX_PARAMS_REGEX = /;[^/]+/g;\n\n/**\n * Removes Angular matrix parameters from a given URL path.\n *\n * This function takes a URL path string and removes any matrix parameters.\n * Matrix parameters are parts of a URL segment that start with a semicolon `;`.\n *\n * @param pathname - The URL path to remove matrix parameters from.\n * @returns The URL path with matrix parameters removed.\n *\n * @example\n * ```ts\n * stripMatrixParams('/path;param=value'); // returns '/path'\n * stripMatrixParams('/path;param=value/to;p=1/resource'); // returns '/path/to/resource'\n * stripMatrixParams('/path/to/resource'); // returns '/path/to/resource'\n * ```\n */\nexport function stripMatrixParams(pathname: string): string {\n // Use a regular expression to remove matrix parameters.\n // This regex finds all occurrences of a semicolon followed by any characters\n return pathname.includes(';') ? pathname.replace(MATRIX_PARAMS_REGEX, '') : pathname;\n}\n\n/**\n * Constructs a decoded URL string from its components.\n *\n * This function joins the pathname (with trailing slash removed), search, and hash,\n * and then decodes the result.\n *\n * @param pathname - The path of the URL.\n * @param search - The query string of the URL (including '?').\n * @param hash - The hash fragment of the URL (including '#').\n * @returns The constructed and decoded URL string.\n */\nexport function constructUrl(pathname: string, search: string, hash: string): string {\n return decodeURIComponent([stripTrailingSlash(pathname), search, hash].join(''));\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 { APP_BASE_HREF, PlatformLocation } from '@angular/common';\nimport {\n ApplicationRef,\n type PlatformRef,\n REQUEST,\n type StaticProvider,\n type Type,\n ɵConsole,\n} from '@angular/core';\nimport { BootstrapContext } from '@angular/platform-browser';\nimport {\n INITIAL_CONFIG,\n ɵSERVER_CONTEXT as SERVER_CONTEXT,\n platformServer,\n ɵrenderInternal as renderInternal,\n} from '@angular/platform-server';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { Console } from '../console';\nimport { addTrailingSlash, joinUrlParts, stripIndexHtmlFromURL, stripTrailingSlash } from './url';\n\n/**\n * Represents the bootstrap mechanism for an Angular application.\n *\n * This type can either be:\n * - A reference to an Angular component or module (`Type<unknown>`) that serves as the root of the application.\n * - A function that returns a `Promise<ApplicationRef>`, which resolves with the root application reference.\n */\nexport type AngularBootstrap =\n | Type<unknown>\n | ((context: BootstrapContext) => Promise<ApplicationRef>);\n\n/**\n * Renders an Angular application or module to an HTML string.\n *\n * This function determines whether the provided `bootstrap` value is an Angular module\n * or a bootstrap function and invokes the appropriate rendering method (`renderModule` or `renderApplication`).\n *\n * @param html - The initial HTML document content.\n * @param bootstrap - An Angular module type or a function returning a promise that resolves to an `ApplicationRef`.\n * @param url - The application URL, used for route-based rendering in SSR.\n * @param platformProviders - An array of platform providers for the rendering process.\n * @param serverContext - A string representing the server context, providing additional metadata for SSR.\n * @returns A promise resolving to an object containing:\n * - `hasNavigationError`: Indicates if a navigation error occurred.\n * - `redirectTo`: (Optional) The redirect URL if a navigation redirect occurred.\n * - `content`: A function returning a promise that resolves to the rendered HTML string.\n */\nexport async function renderAngular(\n html: string,\n bootstrap: AngularBootstrap,\n url: URL,\n platformProviders: StaticProvider[],\n serverContext: string,\n): Promise<{ hasNavigationError: boolean; redirectTo?: string; content: () => Promise<string> }> {\n // A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.\n const urlToRender = stripIndexHtmlFromURL(url);\n const platformRef = platformServer([\n {\n provide: INITIAL_CONFIG,\n useValue: {\n url: urlToRender.href,\n document: html,\n },\n },\n {\n provide: SERVER_CONTEXT,\n useValue: serverContext,\n },\n {\n // An Angular Console Provider that does not print a set of predefined logs.\n provide: ɵConsole,\n // Using `useClass` would necessitate decorating `Console` with `@Injectable`,\n // which would require switching from `ts_library` to `ng_module`. This change\n // would also necessitate various patches of `@angular/bazel` to support ESM.\n useFactory: () => new Console(),\n },\n ...platformProviders,\n ]);\n\n let redirectTo: string | undefined;\n let hasNavigationError = true;\n\n try {\n let applicationRef: ApplicationRef;\n if (isNgModule(bootstrap)) {\n const moduleRef = await platformRef.bootstrapModule(bootstrap);\n applicationRef = moduleRef.injector.get(ApplicationRef);\n } else {\n applicationRef = await bootstrap({ platformRef });\n }\n\n // Block until application is stable.\n await applicationRef.whenStable();\n\n // TODO(alanagius): Find a way to avoid rendering here especially for redirects as any output will be discarded.\n const envInjector = applicationRef.injector;\n const routerIsProvided = !!envInjector.get(ActivatedRoute, null);\n const router = envInjector.get(Router);\n const lastSuccessfulNavigation = router.lastSuccessfulNavigation();\n\n if (!routerIsProvided) {\n hasNavigationError = false;\n } else if (lastSuccessfulNavigation?.finalUrl) {\n hasNavigationError = false;\n\n const requestPrefix =\n envInjector.get(APP_BASE_HREF, null, { optional: true }) ??\n envInjector.get(REQUEST, null, { optional: true })?.headers.get('X-Forwarded-Prefix');\n\n const { pathname, search, hash } = envInjector.get(PlatformLocation);\n const finalUrl = constructDecodedUrl({ pathname, search, hash }, requestPrefix);\n const urlToRenderString = constructDecodedUrl(urlToRender, requestPrefix);\n\n if (urlToRenderString !== finalUrl) {\n redirectTo = [pathname, search, hash].join('');\n }\n }\n\n return {\n hasNavigationError,\n redirectTo,\n content: () =>\n new Promise<string>((resolve, reject) => {\n // Defer rendering to the next event loop iteration to avoid blocking, as most operations in `renderInternal` are synchronous.\n setTimeout(() => {\n renderInternal(platformRef, applicationRef)\n .then(resolve)\n .catch(reject)\n .finally(() => void asyncDestroyPlatform(platformRef));\n }, 0);\n }),\n };\n } catch (error) {\n await asyncDestroyPlatform(platformRef);\n\n throw error;\n } finally {\n if (hasNavigationError || redirectTo) {\n void asyncDestroyPlatform(platformRef);\n }\n }\n}\n\n/**\n * Type guard to determine if a given value is an Angular module.\n * Angular modules are identified by the presence of the `ɵmod` static property.\n * This function helps distinguish between Angular modules and bootstrap functions.\n *\n * @param value - The value to be checked.\n * @returns True if the value is an Angular module (i.e., it has the `ɵmod` property), false otherwise.\n */\nexport function isNgModule(value: AngularBootstrap): value is Type<unknown> {\n return 'ɵmod' in value;\n}\n\n/**\n * Gracefully destroys the application in a macrotask, allowing pending promises to resolve\n * and surfacing any potential errors to the user.\n *\n * @param platformRef - The platform reference to be destroyed.\n */\nfunction asyncDestroyPlatform(platformRef: PlatformRef): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(() => {\n if (!platformRef.destroyed) {\n platformRef.destroy();\n }\n\n resolve();\n }, 0);\n });\n}\n\n/**\n * Constructs a decoded URL string from its components, ensuring consistency for comparison.\n *\n * This function takes a URL-like object (containing `pathname`, `search`, and `hash`),\n * strips the trailing slash from the pathname, joins the components, and then decodes\n * the entire string. This normalization is crucial for accurately comparing URLs\n * that might differ only in encoding or trailing slashes.\n *\n * @param url - An object containing the URL components:\n * - `pathname`: The path of the URL.\n * - `search`: The query string of the URL (including '?').\n * - `hash`: The hash fragment of the URL (including '#').\n * @param prefix - An optional prefix (e.g., `APP_BASE_HREF`) to prepend to the pathname\n * if it is not already present.\n * @returns The constructed and decoded URL string.\n */\nfunction constructDecodedUrl(\n url: { pathname: string; search: string; hash: string },\n prefix?: string | null,\n): string {\n const { pathname, hash, search } = url;\n const urlParts: string[] = [];\n if (prefix && !addTrailingSlash(pathname).startsWith(addTrailingSlash(prefix))) {\n urlParts.push(joinUrlParts(prefix, pathname));\n } else {\n urlParts.push(stripTrailingSlash(pathname));\n }\n\n urlParts.push(search, hash);\n\n return decodeURIComponent(urlParts.join(''));\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\n/**\n * Creates a promise that resolves with the result of the provided `promise` or rejects with an\n * `AbortError` if the `AbortSignal` is triggered before the promise resolves.\n *\n * @param promise - The promise to monitor for completion.\n * @param signal - An `AbortSignal` used to monitor for an abort event. If the signal is aborted,\n * the returned promise will reject.\n * @param errorMessagePrefix - A custom message prefix to include in the error message when the operation is aborted.\n * @returns A promise that either resolves with the value of the provided `promise` or rejects with\n * an `AbortError` if the `AbortSignal` is triggered.\n *\n * @throws {AbortError} If the `AbortSignal` is triggered before the `promise` resolves.\n */\nexport function promiseWithAbort<T>(\n promise: Promise<T>,\n signal: AbortSignal,\n errorMessagePrefix: string,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const abortHandler = () => {\n reject(\n new DOMException(`${errorMessagePrefix} was aborted.\\n${signal.reason}`, 'AbortError'),\n );\n };\n\n // Check for abort signal\n if (signal.aborted) {\n abortHandler();\n\n return;\n }\n\n signal.addEventListener('abort', abortHandler, { once: true });\n\n promise\n .then(resolve)\n .catch(reject)\n .finally(() => {\n signal.removeEventListener('abort', abortHandler);\n });\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 {\n EnvironmentProviders,\n InjectionToken,\n Provider,\n Type,\n inject,\n makeEnvironmentProviders,\n provideEnvironmentInitializer,\n} from '@angular/core';\nimport { provideServerRendering as provideServerRenderingPlatformServer } from '@angular/platform-server';\nimport { type DefaultExport, ROUTES, type Route } from '@angular/router';\n\n/**\n * The internal path used for the app shell route.\n * @internal\n */\nconst APP_SHELL_ROUTE = 'ng-app-shell';\n\n/**\n * Identifies a particular kind of `ServerRenderingFeatureKind`.\n * @see {@link ServerRenderingFeature}\n */\nenum ServerRenderingFeatureKind {\n AppShell,\n ServerRoutes,\n}\n\n/**\n * Helper type to represent a server routes feature.\n * @see {@link ServerRenderingFeatureKind}\n */\ninterface ServerRenderingFeature<FeatureKind extends ServerRenderingFeatureKind> {\n ɵkind: FeatureKind;\n ɵproviders: (Provider | EnvironmentProviders)[];\n}\n\n/**\n * Different rendering modes for server routes.\n * @see {@link withRoutes}\n * @see {@link ServerRoute}\n */\nexport enum RenderMode {\n /** Server-Side Rendering (SSR) mode, where content is rendered on the server for each request. */\n Server,\n\n /** Client-Side Rendering (CSR) mode, where content is rendered on the client side in the browser. */\n Client,\n\n /** Static Site Generation (SSG) mode, where content is pre-rendered at build time and served as static files. */\n Prerender,\n}\n\n/**\n * Defines the fallback strategies for Static Site Generation (SSG) routes when a pre-rendered path is not available.\n * This is particularly relevant for routes with parameterized URLs where some paths might not be pre-rendered at build time.\n * @see {@link ServerRoutePrerenderWithParams}\n */\nexport enum PrerenderFallback {\n /**\n * Fallback to Server-Side Rendering (SSR) if the pre-rendered path is not available.\n * This strategy dynamically generates the page on the server at request time.\n */\n Server,\n\n /**\n * Fallback to Client-Side Rendering (CSR) if the pre-rendered path is not available.\n * This strategy allows the page to be rendered on the client side.\n */\n Client,\n\n /**\n * No fallback; if the path is not pre-rendered, the server will not handle the request.\n * This means the application will not provide any response for paths that are not pre-rendered.\n */\n None,\n}\n\n/**\n * Common interface for server routes, providing shared properties.\n */\nexport interface ServerRouteCommon {\n /** The path associated with this route. */\n path: string;\n\n /** Optional additional headers to include in the response for this route. */\n headers?: Record<string, string>;\n\n /** Optional status code to return for this route. */\n status?: number;\n}\n\n/**\n * A server route that uses Client-Side Rendering (CSR) mode.\n * @see {@link RenderMode}\n */\nexport interface ServerRouteClient extends ServerRouteCommon {\n /** Specifies that the route uses Client-Side Rendering (CSR) mode. */\n renderMode: RenderMode.Client;\n}\n\n/**\n * A server route that uses Static Site Generation (SSG) mode.\n * @see {@link RenderMode}\n */\nexport interface ServerRoutePrerender extends Omit<ServerRouteCommon, 'status'> {\n /** Specifies that the route uses Static Site Generation (SSG) mode. */\n renderMode: RenderMode.Prerender;\n\n /** Fallback cannot be specified unless `getPrerenderParams` is used. */\n fallback?: never;\n}\n\n/**\n * A server route configuration that uses Static Site Generation (SSG) mode, including support for routes with parameters.\n * @see {@link RenderMode}\n * @see {@link ServerRoutePrerender}\n * @see {@link PrerenderFallback}\n */\nexport interface ServerRoutePrerenderWithParams extends Omit<ServerRoutePrerender, 'fallback'> {\n /**\n * Optional strategy to use if the SSG path is not pre-rendered.\n * This is especially relevant for routes with parameterized URLs, where some paths may not be pre-rendered at build time.\n *\n * This property determines how to handle requests for paths that are not pre-rendered:\n * - `PrerenderFallback.Server`: Use Server-Side Rendering (SSR) to dynamically generate the page at request time.\n * - `PrerenderFallback.Client`: Use Client-Side Rendering (CSR) to fetch and render the page on the client side.\n * - `PrerenderFallback.None`: No fallback; if the path is not pre-rendered, the server will not handle the request.\n *\n * @default `PrerenderFallback.Server` if not provided.\n */\n fallback?: PrerenderFallback;\n\n /**\n * A function that returns a Promise resolving to an array of objects, each representing a route path with URL parameters.\n * This function runs in the injector context, allowing access to Angular services and dependencies.\n *\n * It also works for catch-all routes (e.g., `/**`), where the parameter name will be `**` and the return value will be\n * the segments of the path, such as `/foo/bar`. These routes can also be combined, e.g., `/product/:id/**`,\n * where both a parameterized segment (`:id`) and a catch-all segment (`**`) can be used together to handle more complex paths.\n *\n * @returns A Promise resolving to an array where each element is an object with string keys (representing URL parameter names)\n * and string values (representing the corresponding values for those parameters in the route path).\n *\n * @example\n * ```typescript\n * export const serverRouteConfig: ServerRoutes[] = [\n * {\n * path: '/product/:id',\n * renderMode: RenderMode.Prerender,\n * async getPrerenderParams() {\n * const productService = inject(ProductService);\n * const ids = await productService.getIds(); // Assuming this returns ['1', '2', '3']\n *\n * return ids.map(id => ({ id })); // Generates paths like: ['product/1', 'product/2', 'product/3']\n * },\n * },\n * {\n * path: '/product/:id/**',\n * renderMode: RenderMode.Prerender,\n * async getPrerenderParams() {\n * return [\n * { id: '1', '**': 'laptop/3' },\n * { id: '2', '**': 'laptop/4' }\n * ]; // Generates paths like: ['product/1/laptop/3', 'product/2/laptop/4']\n * },\n * },\n * ];\n * ```\n */\n getPrerenderParams: () => Promise<Record<string, string>[]>;\n}\n\n/**\n * A server route that uses Server-Side Rendering (SSR) mode.\n * @see {@link RenderMode}\n */\nexport interface ServerRouteServer extends ServerRouteCommon {\n /** Specifies that the route uses Server-Side Rendering (SSR) mode. */\n renderMode: RenderMode.Server;\n}\n\n/**\n * Server route configuration.\n * @see {@link withRoutes}\n */\nexport type ServerRoute =\n | ServerRouteClient\n | ServerRoutePrerender\n | ServerRoutePrerenderWithParams\n | ServerRouteServer;\n\n/**\n * Configuration value for server routes configuration.\n * @internal\n */\nexport interface ServerRoutesConfig {\n /**\n * Defines the route to be used as the app shell.\n */\n appShellRoute?: string;\n\n /** List of server routes for the application. */\n routes: ServerRoute[];\n}\n\n/**\n * Token for providing the server routes configuration.\n * @internal\n */\nexport const SERVER_ROUTES_CONFIG = new InjectionToken<ServerRoutesConfig>('SERVER_ROUTES_CONFIG');\n\n/**\n * Configures server-side routing for the application.\n *\n * This function registers an array of `ServerRoute` definitions, enabling server-side rendering\n * for specific URL paths. These routes are used to pre-render content on the server, improving\n * initial load performance and SEO.\n *\n * @param routes - An array of `ServerRoute` objects, each defining a server-rendered route.\n * @returns A `ServerRenderingFeature` object configuring server-side routes.\n *\n * @example\n * ```ts\n * import { provideServerRendering, withRoutes, ServerRoute, RenderMode } from '@angular/ssr';\n *\n * const serverRoutes: ServerRoute[] = [\n * {\n * path: '', // This renders the \"/\" route on the client (CSR)\n * renderMode: RenderMode.Client,\n * },\n * {\n * path: 'about', // This page is static, so we prerender it (SSG)\n * renderMode: RenderMode.Prerender,\n * },\n * {\n * path: 'profile', // This page requires user-specific data, so we use SSR\n * renderMode: RenderMode.Server,\n * },\n * {\n * path: '**', // All other routes will be rendered on the server (SSR)\n * renderMode: RenderMode.Server,\n * },\n * ];\n *\n * provideServerRendering(withRoutes(serverRoutes));\n * ```\n *\n * @see {@link provideServerRendering}\n * @see {@link ServerRoute}\n */\nexport function withRoutes(\n routes: ServerRoute[],\n): ServerRenderingFeature<ServerRenderingFeatureKind.ServerRoutes> {\n const config: ServerRoutesConfig = { routes };\n\n return {\n ɵkind: ServerRenderingFeatureKind.ServerRoutes,\n ɵproviders: [\n {\n provide: SERVER_ROUTES_CONFIG,\n useValue: config,\n },\n ],\n };\n}\n\n/**\n * Configures the shell of the application.\n *\n * The app shell is a minimal, static HTML page that is served immediately, while the\n * full Angular application loads in the background. This improves perceived performance\n * by providing instant feedback to the user.\n *\n * This function configures the app shell route, which serves the provided component for\n * requests that do not match any defined server routes.\n *\n * @param component - The Angular component to render for the app shell. Can be a direct\n * component type or a dynamic import function.\n * @returns A `ServerRenderingFeature` object configuring the app shell.\n *\n * @example\n * ```ts\n * import { provideServerRendering, withAppShell, withRoutes } from '@angular/ssr';\n * import { AppShellComponent } from './app-shell.component';\n *\n * provideServerRendering(\n * withRoutes(serverRoutes),\n * withAppShell(AppShellComponent)\n * );\n * ```\n *\n * @example\n * ```ts\n * import { provideServerRendering, withAppShell, withRoutes } from '@angular/ssr';\n *\n * provideServerRendering(\n * withRoutes(serverRoutes),\n * withAppShell(() =>\n * import('./app-shell.component').then((m) => m.AppShellComponent)\n * )\n * );\n * ```\n *\n * @see {@link provideServerRendering}\n * @see {@link https://angular.dev/ecosystem/service-workers/app-shell App shell pattern on Angular.dev}\n */\nexport function withAppShell(\n component: Type<unknown> | (() => Promise<Type<unknown> | DefaultExport<Type<unknown>>>),\n): ServerRenderingFeature<ServerRenderingFeatureKind.AppShell> {\n const routeConfig: Route = {\n path: APP_SHELL_ROUTE,\n };\n\n if ('ɵcmp' in component) {\n routeConfig.component = component as Type<unknown>;\n } else {\n routeConfig.loadComponent = component as () => Promise<Type<unknown>>;\n }\n\n return {\n ɵkind: ServerRenderingFeatureKind.AppShell,\n ɵproviders: [\n {\n provide: ROUTES,\n useValue: routeConfig,\n multi: true,\n },\n provideEnvironmentInitializer(() => {\n const config = inject(SERVER_ROUTES_CONFIG);\n config.appShellRoute = APP_SHELL_ROUTE;\n }),\n ],\n };\n}\n\n/**\n * Configures server-side rendering for an Angular application.\n *\n * This function sets up the necessary providers for server-side rendering, including\n * support for server routes and app shell. It combines features configured using\n * `withRoutes` and `withAppShell` to provide a comprehensive server-side rendering setup.\n *\n * @param features - Optional features to configure additional server rendering behaviors.\n * @returns An `EnvironmentProviders` instance with the server-side rendering configuration.\n *\n * @example\n * Basic example of how you can enable server-side rendering in your application\n * when using the `bootstrapApplication` function:\n *\n * ```ts\n * import { bootstrapApplication, BootstrapContext } from '@angular/platform-browser';\n * import { provideServerRendering, withRoutes, withAppShell } from '@angular/ssr';\n * import { AppComponent } from './app/app.component';\n * import { SERVER_ROUTES } from './app/app.server.routes';\n * import { AppShellComponent } from './app/app-shell.component';\n *\n * const bootstrap = (context: BootstrapContext) =>\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideServerRendering(\n * withRoutes(SERVER_ROUTES),\n * withAppShell(AppShellComponent),\n * ),\n * ],\n * }, context);\n *\n * export default bootstrap;\n * ```\n * @see {@link withRoutes} configures server-side routing\n * @see {@link withAppShell} configures the application shell\n */\nexport function provideServerRendering(\n ...features: ServerRenderingFeature<ServerRenderingFeatureKind>[]\n): EnvironmentProviders {\n let hasAppShell = false;\n let hasServerRoutes = false;\n const providers: (Provider | EnvironmentProviders)[] = [provideServerRenderingPlatformServer()];\n\n for (const { ɵkind, ɵproviders } of features) {\n hasAppShell ||= ɵkind === ServerRenderingFeatureKind.AppShell;\n hasServerRoutes ||= ɵkind === ServerRenderingFeatureKind.ServerRoutes;\n providers.push(...ɵproviders);\n }\n\n if (!hasServerRoutes && hasAppShell) {\n throw new Error(\n `Configuration error: found 'withAppShell()' without 'withRoutes()' in the same call to 'provideServerRendering()'.` +\n `The 'withAppShell()' function requires 'withRoutes()' to be used.`,\n );\n }\n\n return makeEnvironmentProviders(providers);\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 { addLeadingSlash } from '../utils/url';\nimport { RenderMode } from './route-config';\n\n/**\n * Represents the serialized format of a route tree as an array of node metadata objects.\n * Each entry in the array corresponds to a specific node's metadata within the route tree.\n */\nexport type SerializableRouteTreeNode = ReadonlyArray<RouteTreeNodeMetadata>;\n\n/**\n * Represents metadata for a route tree node, excluding the 'route' path segment.\n */\nexport type RouteTreeNodeMetadataWithoutRoute = Omit<RouteTreeNodeMetadata, 'route'>;\n\n/**\n * Describes metadata associated with a node in the route tree.\n * This metadata includes information such as the route path and optional redirect instructions.\n */\nexport interface RouteTreeNodeMetadata {\n /**\n * Optional redirect path associated with this node.\n * This defines where to redirect if this route is matched.\n */\n redirectTo?: string;\n\n /**\n * The route path for this node.\n *\n * A \"route\" is a URL path or pattern that is used to navigate to different parts of a web application.\n * It is made up of one or more segments separated by slashes `/`. For instance, in the URL `/products/details/42`,\n * the full route is `/products/details/42`, with segments `products`, `details`, and `42`.\n *\n * Routes define how URLs map to views or components in an application. Each route segment contributes to\n * the overall path that determines which view or component is displayed.\n *\n * - **Static Routes**: These routes have fixed segments. For example, `/about` or `/contact`.\n * - **Parameterized Routes**: These include dynamic segments that act as placeholders, such as `/users/:id`,\n * where `:id` could be any user ID.\n *\n * In the context of `RouteTreeNodeMetadata`, the `route` property represents the complete path that this node\n * in the route tree corresponds to. This path is used to determine how a specific URL in the browser maps to the\n * structure and content of the application.\n */\n route: string;\n\n /**\n * Optional status code to return for this route.\n */\n status?: number;\n\n /**\n * Optional additional headers to include in the response for this route.\n */\n headers?: Record<string, string>;\n\n /**\n * Specifies the rendering mode used for this route.\n */\n renderMode: RenderMode;\n\n /**\n * A list of resource that should be preloaded by the browser.\n */\n preload?: readonly string[];\n}\n\n/**\n * Represents a node within the route tree structure.\n * Each node corresponds to a route segment and may have associated metadata and child nodes.\n * The `AdditionalMetadata` type parameter allows for extending the node metadata with custom data.\n */\ninterface RouteTreeNode<AdditionalMetadata extends Record<string, unknown>> {\n /**\n * A map of child nodes, keyed by their corresponding route segment or wildcard.\n */\n children: Map<string, RouteTreeNode<AdditionalMetadata>>;\n\n /**\n * Optional metadata associated with this node, providing additional information such as redirects.\n */\n metadata?: RouteTreeNodeMetadata & AdditionalMetadata;\n}\n\n/**\n * A route tree implementation that supports efficient route matching, including support for wildcard routes.\n * This structure is useful for organizing and retrieving routes in a hierarchical manner,\n * enabling complex routing scenarios with nested paths.\n *\n * @typeParam AdditionalMetadata - Type of additional metadata that can be associated with route nodes.\n */\nexport class RouteTree<AdditionalMetadata extends Record<string, unknown> = {}> {\n /**\n * The root node of the route tree.\n * All routes are stored and accessed relative to this root node.\n */\n private readonly root = this.createEmptyRouteTreeNode();\n\n /**\n * Inserts a new route into the route tree.\n * The route is broken down into segments, and each segment is added to the tree.\n * Parameterized segments (e.g., :id) are normalized to wildcards (*) for matching purposes.\n *\n * @param route - The route path to insert into the tree.\n * @param metadata - Metadata associated with the route, excluding the route path itself.\n */\n insert(route: string, metadata: RouteTreeNodeMetadataWithoutRoute & AdditionalMetadata): void {\n let node = this.root;\n const segments = this.getPathSegments(route);\n const normalizedSegments: string[] = [];\n\n for (const segment of segments) {\n // Replace parameterized segments (e.g., :id) with a wildcard (*) for matching\n const normalizedSegment = segment[0] === ':' ? '*' : segment;\n let childNode = node.children.get(normalizedSegment);\n if (!childNode) {\n childNode = this.createEmptyRouteTreeNode();\n node.children.set(normalizedSegment, childNode);\n }\n\n node = childNode;\n normalizedSegments.push(normalizedSegment);\n }\n\n // At the leaf node, store the full route and its associated metadata\n node.metadata = {\n ...metadata,\n route: addLeadingSlash(normalizedSegments.join('/')),\n };\n }\n\n /**\n * Matches a given route against the route tree and returns the best matching route's metadata.\n * The best match is determined by the lowest insertion index, meaning the earliest defined route\n * takes precedence.\n *\n * @param route - The route path to match against the route tree.\n * @returns The metadata of the best matching route or `undefined` if no match is found.\n */\n match(route: string): (RouteTreeNodeMetadata & AdditionalMetadata) | undefined {\n const segments = this.getPathSegments(route);\n\n return this.traverseBySegments(segments)?.metadata;\n }\n\n /**\n * Converts the route tree into a serialized format representation.\n * This method converts the route tree into an array of metadata objects that describe the structure of the tree.\n * The array represents the routes in a nested manner where each entry includes the route and its associated metadata.\n *\n * @returns An array of `RouteTreeNodeMetadata` objects representing the route tree structure.\n * Each object includes the `route` and associated metadata of a route.\n */\n toObject(): SerializableRouteTreeNode {\n return Array.from(this.traverse());\n }\n\n /**\n * Constructs a `RouteTree` from an object representation.\n * This method is used to recreate a `RouteTree` instance from an array of metadata objects.\n * The array should be in the format produced by `toObject`, allowing for the reconstruction of the route tree\n * with the same routes and metadata.\n *\n * @param value - An array of `RouteTreeNodeMetadata` objects that represent the serialized format of the route tree.\n * Each object should include a `route` and its associated metadata.\n * @returns A new `RouteTree` instance constructed from the provided metadata objects.\n */\n static fromObject(value: SerializableRouteTreeNode): RouteTree {\n const tree = new RouteTree();\n\n for (const { route, ...metadata } of value) {\n tree.insert(route, metadata);\n }\n\n return tree;\n }\n\n /**\n * A generator function that recursively traverses the route tree and yields the metadata of each node.\n * This allows for easy and efficient iteration over all nodes in the tree.\n *\n * @param node - The current node to start the traversal from. Defaults to the root node of the tree.\n */\n *traverse(node = this.root): Generator<RouteTreeNodeMetadata & AdditionalMetadata> {\n if (node.metadata) {\n yield node.metadata;\n }\n\n for (const childNode of node.children.values()) {\n yield* this.traverse(childNode);\n }\n }\n\n /**\n * Extracts the path segments from a given route string.\n *\n * @param route - The route string from which to extract segments.\n * @returns An array of path segments.\n */\n private getPathSegments(route: string): string[] {\n return route.split('/').filter(Boolean);\n }\n\n /**\n * Recursively traverses the route tree from a given node, attempting to match the remaining route segments.\n * If the node is a leaf node (no more segments to match) and contains metadata, the node is yielded.\n *\n * This function prioritizes exact segment matches first, followed by wildcard matches (`*`),\n * and finally deep wildcard matches (`**`) that consume all segments.\n *\n * @param segments - The array of route path segments to match against the route tree.\n * @param node - The current node in the route tree to start traversal from. Defaults to the root node.\n * @param currentIndex - The index of the segment in `remainingSegments` currently being matched.\n * Defaults to `0` (the first segment).\n *\n * @returns The node that best matches the remaining segments or `undefined` if no match is found.\n */\n private traverseBySegments(\n segments: string[],\n node = this.root,\n currentIndex = 0,\n ): RouteTreeNode<AdditionalMetadata> | undefined {\n if (currentIndex >= segments.length) {\n return node.metadata ? node : node.children.get('**');\n }\n\n if (!node.children.size) {\n return undefined;\n }\n\n const segment = segments[currentIndex];\n\n // 1. Attempt exact match with the current segment.\n const exactMatch = node.children.get(segment);\n if (exactMatch) {\n const match = this.traverseBySegments(segments, exactMatch, currentIndex + 1);\n if (match) {\n return match;\n }\n }\n\n // 2. Attempt wildcard match ('*').\n const wildcardMatch = node.children.get('*');\n if (wildcardMatch) {\n const match = this.traverseBySegments(segments, wildcardMatch, currentIndex + 1);\n if (match) {\n return match;\n }\n }\n\n // 3. Attempt double wildcard match ('**').\n return node.children.get('**');\n }\n\n /**\n * Creates an empty route tree node.\n * This helper function is used during the tree construction.\n *\n * @returns A new, empty route tree node.\n */\n private createEmptyRouteTreeNode(): RouteTreeNode<AdditionalMetadata> {\n return {\n children: new Map(),\n };\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 { APP_BASE_HREF, PlatformLocation } from '@angular/common';\nimport {\n ApplicationRef,\n Compiler,\n EnvironmentInjector,\n Injector,\n createEnvironmentInjector,\n runInInjectionContext,\n ɵConsole,\n ɵENABLE_ROOT_COMPONENT_BOOTSTRAP,\n} from '@angular/core';\nimport { INITIAL_CONFIG, platformServer } from '@angular/platform-server';\nimport {\n Route as AngularRoute,\n Router,\n ɵloadChildren as loadChildrenHelper,\n} from '@angular/router';\nimport { ServerAssets } from '../assets';\nimport { Console } from '../console';\nimport { AngularAppManifest, getAngularAppManifest } from '../manifest';\nimport { AngularBootstrap, isNgModule } from '../utils/ng';\nimport { promiseWithAbort } from '../utils/promise';\nimport { addTrailingSlash, joinUrlParts, stripLeadingSlash } from '../utils/url';\nimport {\n PrerenderFallback,\n RenderMode,\n SERVER_ROUTES_CONFIG,\n ServerRoute,\n ServerRoutesConfig,\n} from './route-config';\nimport { RouteTree, RouteTreeNodeMetadata } from './route-tree';\n\ninterface Route extends AngularRoute {\n ɵentryName?: string;\n}\n\n/**\n * The maximum number of module preload link elements that should be added for\n * initial scripts.\n */\nconst MODULE_PRELOAD_MAX = 10;\n\n/**\n * Regular expression to match a catch-all route pattern in a URL path,\n * specifically one that ends with '/**'.\n */\nconst CATCH_ALL_REGEXP = /\\/(\\*\\*)$/;\n\n/**\n * Regular expression to match segments preceded by a colon in a string.\n */\nconst URL_PARAMETER_REGEXP = /(?<!\\\\):([^/]+)/g;\n\n/**\n * An set of HTTP status codes that are considered valid for redirect responses.\n */\nconst VALID_REDIRECT_RESPONSE_CODES = new Set([301, 302, 303, 307, 308]);\n\n/**\n * Additional metadata for a server configuration route tree.\n */\ntype ServerConfigRouteTreeAdditionalMetadata = Partial<ServerRoute> & {\n /** Indicates if the route has been matched with the Angular router routes. */\n presentInClientRouter?: boolean;\n};\n\n/**\n * Metadata for a server configuration route tree node.\n */\ntype ServerConfigRouteTreeNodeMetadata = RouteTreeNodeMetadata &\n ServerConfigRouteTreeAdditionalMetadata;\n\n/**\n * Result of extracting routes from an Angular application.\n */\ninterface AngularRouterConfigResult {\n /**\n * The base URL for the application.\n * This is the base href that is used for resolving relative paths within the application.\n */\n baseHref: string;\n\n /**\n * An array of `RouteTreeNodeMetadata` objects representing the application's routes.\n *\n * Each `RouteTreeNodeMetadata` contains details about a specific route, such as its path and any\n * associated redirection targets. This array is asynchronously generated and\n * provides information on how routes are structured and resolved.\n */\n routes: RouteTreeNodeMetadata[];\n\n /**\n * Optional configuration for server routes.\n *\n * This property allows you to specify an array of server routes for configuration.\n * If not provided, the default configuration or behavior will be used.\n */\n serverRoutesConfig?: ServerRoute[] | null;\n\n /**\n * A list of errors encountered during the route extraction process.\n */\n errors: string[];\n\n /**\n * The specified route for the app-shell, if configured.\n */\n appShellRoute?: string;\n}\n\ntype EntryPointToBrowserMapping = AngularAppManifest['entryPointToBrowserMapping'];\n\n/**\n * Handles a single route within the route tree and yields metadata or errors.\n *\n * @param options - Configuration options for handling the route.\n * @returns An async iterable iterator yielding `RouteTreeNodeMetadata` or an error object.\n */\nasync function* handleRoute(options: {\n metadata: ServerConfigRouteTreeNodeMetadata;\n currentRoutePath: string;\n route: Route;\n compiler: Compiler;\n parentInjector: Injector;\n serverConfigRouteTree?: RouteTree<ServerConfigRouteTreeAdditionalMetadata>;\n invokeGetPrerenderParams: boolean;\n includePrerenderFallbackRoutes: boolean;\n entryPointToBrowserMapping?: EntryPointToBrowserMapping;\n}): AsyncIterableIterator<RouteTreeNodeMetadata | { error: string }> {\n try {\n const {\n metadata,\n currentRoutePath,\n route,\n compiler,\n parentInjector,\n serverConfigRouteTree,\n entryPointToBrowserMapping,\n invokeGetPrerenderParams,\n includePrerenderFallbackRoutes,\n } = options;\n\n const { redirectTo, loadChildren, loadComponent, children, ɵentryName } = route;\n if (ɵentryName && loadComponent) {\n appendPreloadToMetadata(ɵentryName, entryPointToBrowserMapping, metadata);\n }\n\n if (metadata.renderMode === RenderMode.Prerender) {\n yield* handleSSGRoute(\n serverConfigRouteTree,\n typeof redirectTo === 'string' ? redirectTo : undefined,\n metadata,\n parentInjector,\n invokeGetPrerenderParams,\n includePrerenderFallbackRoutes,\n );\n } else if (redirectTo !== undefined) {\n if (metadata.status && !VALID_REDIRECT_RESPONSE_CODES.has(metadata.status)) {\n yield {\n error:\n `The '${metadata.status}' status code is not a valid redirect response code. ` +\n `Please use one of the following redirect response codes: ${[...VALID_REDIRECT_RESPONSE_CODES.values()].join(', ')}.`,\n };\n } else if (typeof redirectTo === 'string') {\n yield {\n ...metadata,\n redirectTo: resolveRedirectTo(metadata.route, redirectTo),\n };\n } else {\n yield metadata;\n }\n } else {\n yield metadata;\n }\n\n // Recursively process child routes\n if (children?.length) {\n yield* traverseRoutesConfig({\n ...options,\n routes: children,\n parentRoute: currentRoutePath,\n parentPreloads: metadata.preload,\n });\n }\n\n // Load and process lazy-loaded child routes\n if (loadChildren) {\n if (ɵentryName) {\n appendPreloadToMetadata(ɵentryName, entryPointToBrowserMapping, metadata);\n }\n\n const routeInjector = route.providers\n ? createEnvironmentInjector(\n route.providers,\n parentInjector.get(EnvironmentInjector),\n `Route: ${route.path}`,\n )\n : parentInjector;\n\n const loadedChildRoutes = await loadChildrenHelper(route, compiler, routeInjector);\n if (loadedChildRoutes) {\n const { routes: childRoutes, injector = routeInjector } = loadedChildRoutes;\n yield* traverseRoutesConfig({\n ...options,\n routes: childRoutes,\n parentInjector: injector,\n parentRoute: currentRoutePath,\n parentPreloads: metadata.preload,\n });\n }\n }\n } catch (error) {\n yield {\n error: `Error in handleRoute for '${options.currentRoutePath}': ${(error as Error).message}`,\n };\n }\n}\n\n/**\n * Traverses an array of route configurations to generate route tree node metadata.\n *\n * This function processes each route and its children, handling redirects, SSG (Static Site Generation) settings,\n * and lazy-loaded routes. It yields route metadata for each route and its potential variants.\n *\n * @param options - The configuration options for traversing routes.\n * @returns An async iterable iterator yielding either route tree node metadata or an error object with an error message.\n */\nasync function* traverseRoutesConfig(options: {\n routes: Route[];\n compiler: Compiler;\n parentInjector: Injector;\n parentRoute: string;\n serverConfigRouteTree?: RouteTree<ServerConfigRouteTreeAdditionalMetadata>;\n invokeGetPrerenderParams: boolean;\n includePrerenderFallbackRoutes: boolean;\n entryPointToBrowserMapping?: EntryPointToBrowserMapping;\n parentPreloads?: readonly string[];\n}): AsyncIterableIterator<RouteTreeNodeMetadata | { error: string }> {\n const { routes: routeConfigs, parentPreloads, parentRoute, serverConfigRouteTree } = options;\n\n for (const route of routeConfigs) {\n const { matcher, path = matcher ? '**' : '' } = route;\n const currentRoutePath = joinUrlParts(parentRoute, path);\n\n if (matcher && serverConfigRouteTree) {\n const matches: (RouteTreeNodeMetadata & ServerConfigRouteTreeAdditionalMetadata)[] = [];\n for (const matchedMetaData of serverConfigRouteTree.traverse()) {\n if (matchedMetaData.route.startsWith(currentRoutePath)) {\n matches.push(matchedMetaData);\n }\n }\n\n if (!matches.length) {\n const matchedMetaData = serverConfigRouteTree.match(currentRoutePath);\n if (matchedMetaData) {\n matches.push(matchedMetaData);\n }\n }\n\n for (const matchedMetaData of matches) {\n matchedMetaData.presentInClientRouter = true;\n if (matchedMetaData.renderMode === RenderMode.Prerender) {\n yield {\n error:\n `The route '${stripLeadingSlash(currentRoutePath)}' is set for prerendering but has a defined matcher. ` +\n `Routes with matchers cannot use prerendering. Please specify a different 'renderMode'.`,\n };\n continue;\n }\n\n yield* handleRoute({\n ...options,\n currentRoutePath,\n route,\n metadata: {\n ...matchedMetaData,\n preload: parentPreloads,\n route: matchedMetaData.route,\n presentInClientRouter: undefined,\n },\n });\n }\n\n if (!matches.length) {\n yield {\n error:\n `The route '${stripLeadingSlash(currentRoutePath)}' has a defined matcher but does not ` +\n 'match any route in the server routing configuration. Please ensure this route is added to the server routing configuration.',\n };\n }\n\n continue;\n }\n\n let matchedMetaData: ServerConfigRouteTreeNodeMetadata | undefined;\n if (serverConfigRouteTree) {\n matchedMetaData = serverConfigRouteTree.match(currentRoutePath);\n if (!matchedMetaData) {\n yield {\n error:\n `The '${stripLeadingSlash(currentRoutePath)}' route does not match any route defined in the server routing configuration. ` +\n 'Please ensure this route is added to the server routing configuration.',\n };\n continue;\n }\n\n matchedMetaData.presentInClientRouter = true;\n }\n\n yield* handleRoute({\n ...options,\n metadata: {\n renderMode: RenderMode.Prerender,\n ...matchedMetaData,\n preload: parentPreloads,\n // Match Angular router behavior\n // ['one', 'two', ''] -> 'one/two/'\n // ['one', 'two', 'three'] -> 'one/two/three'\n route: path === '' ? addTrailingSlash(currentRoutePath) : currentRoutePath,\n presentInClientRouter: undefined,\n },\n currentRoutePath,\n route,\n });\n }\n}\n\n/**\n * Appends preload information to the metadata object based on the specified entry-point and chunk mappings.\n *\n * This function extracts preload data for a given entry-point from the provided chunk mappings. It adds the\n * corresponding browser bundles to the metadata's preload list, ensuring no duplicates and limiting the total\n * preloads to a predefined maximum.\n */\nfunction appendPreloadToMetadata(\n entryName: string,\n entryPointToBrowserMapping: EntryPointToBrowserMapping,\n metadata: ServerConfigRouteTreeNodeMetadata,\n): void {\n const existingPreloads = metadata.preload ?? [];\n if (!entryPointToBrowserMapping || existingPreloads.length >= MODULE_PRELOAD_MAX) {\n return;\n }\n\n const preload = entryPointToBrowserMapping[entryName];\n if (!preload?.length) {\n return;\n }\n\n // Merge existing preloads with new ones, ensuring uniqueness and limiting the total to the maximum allowed.\n const combinedPreloads: Set<string> = new Set(existingPreloads);\n for (const href of preload) {\n combinedPreloads.add(href);\n if (combinedPreloads.size === MODULE_PRELOAD_MAX) {\n break;\n }\n }\n\n metadata.preload = Array.from(combinedPreloads);\n}\n\n/**\n * Handles SSG (Static Site Generation) routes by invoking `getPrerenderParams` and yielding\n * all parameterized paths, returning any errors encountered.\n *\n * @param serverConfigRouteTree - The tree representing the server's routing setup.\n * @param redirectTo - Optional path to redirect to, if specified.\n * @param metadata - The metadata associated with the route tree node.\n * @param parentInjector - The dependency injection container for the parent route.\n * @param invokeGetPrerenderParams - A flag indicating whether to invoke the `getPrerenderParams` function.\n * @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result.\n * @returns An async iterable iterator that yields route tree node metadata for each SSG path or errors.\n */\nasync function* handleSSGRoute(\n serverConfigRouteTree: RouteTree<ServerConfigRouteTreeAdditionalMetadata> | undefined,\n redirectTo: string | undefined,\n metadata: ServerConfigRouteTreeNodeMetadata,\n parentInjector: Injector,\n invokeGetPrerenderParams: boolean,\n includePrerenderFallbackRoutes: boolean,\n): AsyncIterableIterator<RouteTreeNodeMetadata | { error: string }> {\n if (metadata.renderMode !== RenderMode.Prerender) {\n throw new Error(\n `'handleSSGRoute' was called for a route which rendering mode is not prerender.`,\n );\n }\n\n const { route: currentRoutePath, fallback, ...meta } = metadata;\n const getPrerenderParams = 'getPrerenderParams' in meta ? meta.getPrerenderParams : undefined;\n\n if ('getPrerenderParams' in meta) {\n delete meta['getPrerenderParams'];\n }\n\n if (redirectTo !== undefined) {\n meta.redirectTo = resolveRedirectTo(currentRoutePath, redirectTo);\n }\n\n const isCatchAllRoute = CATCH_ALL_REGEXP.test(currentRoutePath);\n if (\n (isCatchAllRoute && !getPrerenderParams) ||\n (!isCatchAllRoute && !URL_PARAMETER_REGEXP.test(currentRoutePath))\n ) {\n // Route has no parameters\n yield {\n ...meta,\n route: currentRoutePath,\n };\n\n return;\n }\n\n if (invokeGetPrerenderParams) {\n if (!getPrerenderParams) {\n yield {\n error:\n `The '${stripLeadingSlash(currentRoutePath)}' route uses prerendering and includes parameters, but 'getPrerenderParams' ` +\n `is missing. Please define 'getPrerenderParams' function for this route in your server routing configuration ` +\n `or specify a different 'renderMode'.`,\n };\n\n return;\n }\n\n if (serverConfigRouteTree) {\n // Automatically resolve dynamic parameters for nested routes.\n const catchAllRoutePath = isCatchAllRoute\n ? currentRoutePath\n : joinUrlParts(currentRoutePath, '**');\n const match = serverConfigRouteTree.match(catchAllRoutePath);\n if (match && match.renderMode === RenderMode.Prerender && !('getPrerenderParams' in match)) {\n serverConfigRouteTree.insert(catchAllRoutePath, {\n ...match,\n presentInClientRouter: true,\n getPrerenderParams,\n });\n }\n }\n\n const parameters = await runInInjectionContext(parentInjector, () => getPrerenderParams());\n try {\n for (const params of parameters) {\n const replacer = handlePrerenderParamsReplacement(params, currentRoutePath);\n const routeWithResolvedParams = currentRoutePath\n .replace(URL_PARAMETER_REGEXP, replacer)\n .replace(CATCH_ALL_REGEXP, replacer);\n\n yield {\n ...meta,\n route: routeWithResolvedParams,\n redirectTo:\n redirectTo === undefined\n ? undefined\n : resolveRedirectTo(routeWithResolvedParams, redirectTo),\n };\n }\n } catch (error) {\n yield { error: `${(error as Error).message}` };\n\n return;\n }\n }\n\n // Handle fallback render modes\n if (\n includePrerenderFallbackRoutes &&\n (fallback !== PrerenderFallback.None || !invokeGetPrerenderParams)\n ) {\n yield {\n ...meta,\n route: currentRoutePath,\n renderMode: fallback === PrerenderFallback.Client ? RenderMode.Client : RenderMode.Server,\n };\n }\n}\n\n/**\n * Creates a replacer function used for substituting parameter placeholders in a route path\n * with their corresponding values provided in the `params` object.\n *\n * @param params - An object mapping parameter names to their string values.\n * @param currentRoutePath - The current route path, used for constructing error messages.\n * @returns A function that replaces a matched parameter placeholder (e.g., ':id') with its corresponding value.\n */\nfunction handlePrerenderParamsReplacement(\n params: Record<string, string>,\n currentRoutePath: string,\n): (substring: string, ...args: unknown[]) => string {\n return (match) => {\n const parameterName = match.slice(1);\n const value = params[parameterName];\n if (typeof value !== 'string') {\n throw new Error(\n `The 'getPrerenderParams' function defined for the '${stripLeadingSlash(currentRoutePath)}' route ` +\n `returned a non-string value for parameter '${parameterName}'. ` +\n `Please make sure the 'getPrerenderParams' function returns values for all parameters ` +\n 'specified in this route.',\n );\n }\n\n return parameterName === '**' ? `/${value}` : value;\n };\n}\n\n/**\n * Resolves the `redirectTo` property for a given route.\n *\n * This function processes the `redirectTo` property to ensure that it correctly\n * resolves relative to the current route path. If `redirectTo` is an absolute path,\n * it is returned as is. If it is a relative path, it is resolved based on the current route path.\n *\n * @param routePath - The current route path.\n * @param redirectTo - The target path for redirection.\n * @returns The resolved redirect path as a string.\n */\nfunction resolveRedirectTo(routePath: string, redirectTo: string): string {\n if (redirectTo[0] === '/') {\n // If the redirectTo path is absolute, return it as is.\n return redirectTo;\n }\n\n // Resolve relative redirectTo based on the current route path.\n const segments = routePath.replace(URL_PARAMETER_REGEXP, '*').split('/');\n segments.pop(); // Remove the last segment to make it relative.\n\n return joinUrlParts(...segments, redirectTo);\n}\n\n/**\n * Builds a server configuration route tree from the given server routes configuration.\n *\n * @param serverRoutesConfig - The server routes to be used for configuration.\n\n * @returns An object containing:\n * - `serverConfigRouteTree`: A populated `RouteTree` instance, which organizes the server routes\n * along with their additional metadata.\n * - `errors`: An array of strings that list any errors encountered during the route tree construction\n * process, such as invalid paths.\n */\nfunction buildServerConfigRouteTree({ routes, appShellRoute }: ServerRoutesConfig): {\n errors: string[];\n serverConfigRouteTree: RouteTree<ServerConfigRouteTreeAdditionalMetadata>;\n} {\n const serverRoutes: ServerRoute[] = [...routes];\n if (appShellRoute !== undefined) {\n serverRoutes.unshift({\n path: appShellRoute,\n renderMode: RenderMode.Prerender,\n });\n }\n\n const serverConfigRouteTree = new RouteTree<ServerConfigRouteTreeAdditionalMetadata>();\n const errors: string[] = [];\n\n for (const { path, ...metadata } of serverRoutes) {\n if (path[0] === '/') {\n errors.push(`Invalid '${path}' route configuration: the path cannot start with a slash.`);\n\n continue;\n }\n\n if ('getPrerenderParams' in metadata && (path.includes('/*/') || path.endsWith('/*'))) {\n errors.push(\n `Invalid '${path}' route configuration: 'getPrerenderParams' cannot be used with a '*' route.`,\n );\n continue;\n }\n\n serverConfigRouteTree.insert(path, metadata);\n }\n\n return { serverConfigRouteTree, errors };\n}\n\n/**\n * Retrieves routes from the given Angular application.\n *\n * This function initializes an Angular platform, bootstraps the application or module,\n * and retrieves routes from the Angular router configuration. It handles both module-based\n * and function-based bootstrapping. It yields the resulting routes as `RouteTreeNodeMetadata` objects or errors.\n *\n * @param bootstrap - A function that returns a promise resolving to an `ApplicationRef` or an Angular module to bootstrap.\n * @param document - The initial HTML document used for server-side rendering.\n * This document is necessary to render the application on the server.\n * @param url - The URL for server-side rendering. The URL is used to configure `ServerPlatformLocation`. This configuration is crucial\n * for ensuring that API requests for relative paths succeed, which is essential for accurate route extraction.\n * @param invokeGetPrerenderParams - A boolean flag indicating whether to invoke `getPrerenderParams` for parameterized SSG routes\n * to handle prerendering paths. Defaults to `false`.\n * @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result. Defaults to `true`.\n * @param entryPointToBrowserMapping - Maps the entry-point name to the associated JavaScript browser bundles.\n *\n * @returns A promise that resolves to an object of type `AngularRouterConfigResult` or errors.\n */\nexport async function getRoutesFromAngularRouterConfig(\n bootstrap: AngularBootstrap,\n document: string,\n url: URL,\n invokeGetPrerenderParams = false,\n includePrerenderFallbackRoutes = true,\n entryPointToBrowserMapping: EntryPointToBrowserMapping | undefined = undefined,\n): Promise<AngularRouterConfigResult> {\n const { protocol, host } = url;\n\n // Create and initialize the Angular platform for server-side rendering.\n const platformRef = platformServer([\n {\n provide: INITIAL_CONFIG,\n useValue: { document, url: `${protocol}//${host}/` },\n },\n {\n // An Angular Console Provider that does not print a set of predefined logs.\n provide: ɵConsole,\n // Using `useClass` would necessitate decorating `Console` with `@Injectable`,\n // which would require switching from `ts_library` to `ng_module`. This change\n // would also necessitate various patches of `@angular/bazel` to support ESM.\n useFactory: () => new Console(),\n },\n {\n provide: ɵENABLE_ROOT_COMPONENT_BOOTSTRAP,\n useValue: false,\n },\n ]);\n\n try {\n let applicationRef: ApplicationRef;\n\n if (isNgModule(bootstrap)) {\n const moduleRef = await platformRef.bootstrapModule(bootstrap);\n applicationRef = moduleRef.injector.get(ApplicationRef);\n } else {\n applicationRef = await bootstrap({ platformRef });\n }\n\n const injector = applicationRef.injector;\n const router = injector.get(Router);\n\n // Workaround to unblock navigation when `withEnabledBlockingInitialNavigation()` is used.\n // This is necessary because route extraction disables component bootstrapping.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (router as any).navigationTransitions.afterPreactivation()?.next?.();\n\n // Wait until the application is stable.\n await applicationRef.whenStable();\n\n const errors: string[] = [];\n\n const rawBaseHref =\n injector.get(APP_BASE_HREF, null, { optional: true }) ??\n injector.get(PlatformLocation).getBaseHrefFromDOM();\n const { pathname: baseHref } = new URL(rawBaseHref, 'http://localhost');\n\n const compiler = injector.get(Compiler);\n const serverRoutesConfig = injector.get(SERVER_ROUTES_CONFIG, null, { optional: true });\n let serverConfigRouteTree: RouteTree<ServerConfigRouteTreeAdditionalMetadata> | undefined;\n\n if (serverRoutesConfig) {\n const result = buildServerConfigRouteTree(serverRoutesConfig);\n serverConfigRouteTree = result.serverConfigRouteTree;\n errors.push(...result.errors);\n }\n\n if (errors.length) {\n return {\n baseHref,\n routes: [],\n errors,\n };\n }\n\n const routesResults: RouteTreeNodeMetadata[] = [];\n if (router.config.length) {\n // Retrieve all routes from the Angular router configuration.\n const traverseRoutes = traverseRoutesConfig({\n routes: router.config,\n compiler,\n parentInjector: injector,\n parentRoute: '',\n serverConfigRouteTree,\n invokeGetPrerenderParams,\n includePrerenderFallbackRoutes,\n entryPointToBrowserMapping,\n });\n\n const seenRoutes: Set<string> = new Set();\n for await (const routeMetadata of traverseRoutes) {\n if ('error' in routeMetadata) {\n errors.push(routeMetadata.error);\n continue;\n }\n\n // If a result already exists for the exact same route, subsequent matches should be ignored.\n // This aligns with Angular's app router behavior, which prioritizes the first route.\n const routePath = routeMetadata.route;\n if (!seenRoutes.has(routePath)) {\n routesResults.push(routeMetadata);\n seenRoutes.add(routePath);\n }\n }\n\n // This timeout is necessary to prevent 'adev' from hanging in production builds.\n // The exact cause is unclear, but removing it leads to the issue.\n await new Promise((resolve) => setTimeout(resolve, 0));\n\n if (serverConfigRouteTree) {\n for (const { route, presentInClientRouter } of serverConfigRouteTree.traverse()) {\n if (presentInClientRouter || route.endsWith('/**')) {\n // Skip if matched or it's the catch-all route.\n continue;\n }\n\n errors.push(\n `The '${stripLeadingSlash(route)}' server route does not match any routes defined in the Angular ` +\n `routing configuration (typically provided as a part of the 'provideRouter' call). ` +\n 'Please make sure that the mentioned server route is present in the Angular routing configuration.',\n );\n }\n }\n } else {\n const rootRouteMetadata = serverConfigRouteTree?.match('') ?? {\n route: '',\n renderMode: RenderMode.Prerender,\n };\n\n routesResults.push({\n ...rootRouteMetadata,\n // Matched route might be `/*` or `/**`, which would make Angular serve all routes rather than just `/`.\n // So we limit to just `/` for the empty app router case.\n route: '',\n });\n }\n\n return {\n baseHref,\n routes: routesResults,\n errors,\n appShellRoute: serverRoutesConfig?.appShellRoute,\n };\n } finally {\n platformRef.destroy();\n }\n}\n\n/**\n * Asynchronously extracts routes from the Angular application configuration\n * and creates a `RouteTree` to manage server-side routing.\n *\n * @param options - An object containing the following options:\n * - `url`: The URL for server-side rendering. The URL is used to configure `ServerPlatformLocation`. This configuration is crucial\n * for ensuring that API requests for relative paths succeed, which is essential for accurate route extraction.\n * See:\n * - https://github.com/angular/angular/blob/d608b857c689d17a7ffa33bbb510301014d24a17/packages/platform-server/src/location.ts#L51\n * - https://github.com/angular/angular/blob/6882cc7d9eed26d3caeedca027452367ba25f2b9/packages/platform-server/src/http.ts#L44\n * - `manifest`: An optional `AngularAppManifest` that contains the application's routing and configuration details.\n * If not provided, the default manifest is retrieved using `getAngularAppManifest()`.\n * - `invokeGetPrerenderParams`: A boolean flag indicating whether to invoke `getPrerenderParams` for parameterized SSG routes\n * to handle prerendering paths. Defaults to `false`.\n * - `includePrerenderFallbackRoutes`: A flag indicating whether to include fallback routes in the result. Defaults to `true`.\n * - `signal`: An optional `AbortSignal` that can be used to abort the operation.\n *\n * @returns A promise that resolves to an object containing:\n * - `routeTree`: A populated `RouteTree` containing all extracted routes from the Angular application.\n * - `appShellRoute`: The specified route for the app-shell, if configured.\n * - `errors`: An array of strings representing any errors encountered during the route extraction process.\n */\nexport function extractRoutesAndCreateRouteTree(options: {\n url: URL;\n manifest?: AngularAppManifest;\n invokeGetPrerenderParams?: boolean;\n includePrerenderFallbackRoutes?: boolean;\n signal?: AbortSignal;\n}): Promise<{ routeTree: RouteTree; appShellRoute?: string; errors: string[] }> {\n const {\n url,\n manifest = getAngularAppManifest(),\n invokeGetPrerenderParams = false,\n includePrerenderFallbackRoutes = true,\n signal,\n } = options;\n\n async function extract(): Promise<{\n appShellRoute: string | undefined;\n routeTree: RouteTree<{}>;\n errors: string[];\n }> {\n const routeTree = new RouteTree();\n const document = await new ServerAssets(manifest).getIndexServerHtml().text();\n const bootstrap = await manifest.bootstrap();\n const { baseHref, appShellRoute, routes, errors } = await getRoutesFromAngularRouterConfig(\n bootstrap,\n document,\n url,\n invokeGetPrerenderParams,\n includePrerenderFallbackRoutes,\n manifest.entryPointToBrowserMapping,\n );\n\n for (const { route, ...metadata } of routes) {\n if (metadata.redirectTo !== undefined) {\n metadata.redirectTo = joinUrlParts(baseHref, metadata.redirectTo);\n }\n\n // Remove undefined fields\n // Helps avoid unnecessary test updates\n for (const [key, value] of Object.entries(metadata)) {\n if (value === undefined) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delete (metadata as any)[key];\n }\n }\n\n const fullRoute = joinUrlParts(baseHref, route);\n routeTree.insert(fullRoute, metadata);\n }\n\n return {\n appShellRoute,\n routeTree,\n errors,\n };\n }\n\n return signal ? promiseWithAbort(extract(), signal, 'Routes extraction') : extract();\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\n/**\n * Defines a handler function type for transforming HTML content.\n * This function receives an object with the HTML to be processed.\n *\n * @param ctx - An object containing the URL and HTML content to be transformed.\n * @returns The transformed HTML as a string or a promise that resolves to the transformed HTML.\n */\ntype HtmlTransformHandler = (ctx: { url: URL; html: string }) => string | Promise<string>;\n\n/**\n * Defines the names of available hooks for registering and triggering custom logic within the application.\n */\ntype HookName = keyof HooksMapping;\n\n/**\n * Mapping of hook names to their corresponding handler types.\n */\ninterface HooksMapping {\n 'html:transform:pre': HtmlTransformHandler;\n}\n\n/**\n * Manages a collection of hooks and provides methods to register and execute them.\n * Hooks are functions that can be invoked with specific arguments to allow modifications or enhancements.\n */\nexport class Hooks {\n /**\n * A map of hook names to arrays of hook functions.\n * Each hook name can have multiple associated functions, which are executed in sequence.\n */\n private readonly store = new Map<HookName, Function[]>();\n\n /**\n * Executes all hooks associated with the specified name, passing the given argument to each hook function.\n * The hooks are invoked sequentially, and the argument may be modified by each hook.\n *\n * @template Hook - The type of the hook name. It should be one of the keys of `HooksMapping`.\n * @param name - The name of the hook whose functions will be executed.\n * @param context - The input value to be passed to each hook function. The value is mutated by each hook function.\n * @returns A promise that resolves once all hook functions have been executed.\n *\n * @example\n * ```typescript\n * const hooks = new Hooks();\n * hooks.on('html:transform:pre', async (ctx) => {\n * ctx.html = ctx.html.replace(/foo/g, 'bar');\n * return ctx.html;\n * });\n * const result = await hooks.run('html:transform:pre', { html: '<div>foo</div>' });\n * console.log(result); // '<div>bar</div>'\n * ```\n * @internal\n */\n async run<Hook extends keyof HooksMapping>(\n name: Hook,\n context: Parameters<HooksMapping[Hook]>[0],\n ): Promise<Awaited<ReturnType<HooksMapping[Hook]>>> {\n const hooks = this.store.get(name);\n switch (name) {\n case 'html:transform:pre': {\n if (!hooks) {\n return context.html as Awaited<ReturnType<HooksMapping[Hook]>>;\n }\n\n const ctx = { ...context };\n for (const hook of hooks) {\n ctx.html = await hook(ctx);\n }\n\n return ctx.html as Awaited<ReturnType<HooksMapping[Hook]>>;\n }\n default:\n throw new Error(`Running hook \"${name}\" is not supported.`);\n }\n }\n\n /**\n * Registers a new hook function under the specified hook name.\n * This function should be a function that takes an argument of type `T` and returns a `string` or `Promise<string>`.\n *\n * @template Hook - The type of the hook name. It should be one of the keys of `HooksMapping`.\n * @param name - The name of the hook under which the function will be registered.\n * @param handler - A function to be executed when the hook is triggered. The handler will be called with an argument\n * that may be modified by the hook functions.\n *\n * @remarks\n * - If there are existing handlers registered under the given hook name, the new handler will be added to the list.\n * - If no handlers are registered under the given hook name, a new list will be created with the handler as its first element.\n *\n * @example\n * ```typescript\n * hooks.on('html:transform:pre', async (ctx) => {\n * return ctx.html.replace(/foo/g, 'bar');\n * });\n * ```\n */\n on<Hook extends HookName>(name: Hook, handler: HooksMapping[Hook]): void {\n const hooks = this.store.get(name);\n if (hooks) {\n hooks.push(handler);\n } else {\n this.store.set(name, [handler]);\n }\n }\n\n /**\n * Checks if there are any hooks registered under the specified name.\n *\n * @param name - The name of the hook to check.\n * @returns `true` if there are hooks registered under the specified name, otherwise `false`.\n */\n has(name: HookName): boolean {\n return !!this.store.get(name)?.length;\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 { AngularAppManifest } from '../manifest';\nimport { stripIndexHtmlFromURL, stripMatrixParams } from '../utils/url';\nimport { extractRoutesAndCreateRouteTree } from './ng-routes';\nimport { RouteTree, RouteTreeNodeMetadata } from './route-tree';\n\n/**\n * Manages the application's server routing logic by building and maintaining a route tree.\n *\n * This class is responsible for constructing the route tree from the Angular application\n * configuration and using it to match incoming requests to the appropriate routes.\n */\nexport class ServerRouter {\n /**\n * Creates an instance of the `ServerRouter`.\n *\n * @param routeTree - An instance of `RouteTree` that holds the routing information.\n * The `RouteTree` is used to match request URLs to the appropriate route metadata.\n */\n private constructor(private readonly routeTree: RouteTree) {}\n\n /**\n * Static property to track the ongoing build promise.\n */\n static #extractionPromise: Promise<ServerRouter> | undefined;\n\n /**\n * Creates or retrieves a `ServerRouter` instance based on the provided manifest and URL.\n *\n * If the manifest contains pre-built routes, a new `ServerRouter` is immediately created.\n * Otherwise, it builds the router by extracting routes from the Angular configuration\n * asynchronously. This method ensures that concurrent builds are prevented by re-using\n * the same promise.\n *\n * @param manifest - An instance of `AngularAppManifest` that contains the route information.\n * @param url - The URL for server-side rendering. The URL is needed to configure `ServerPlatformLocation`.\n * This is necessary to ensure that API requests for relative paths succeed, which is crucial for correct route extraction.\n * [Reference](https://github.com/angular/angular/blob/d608b857c689d17a7ffa33bbb510301014d24a17/packages/platform-server/src/location.ts#L51)\n * @returns A promise resolving to a `ServerRouter` instance.\n */\n static from(manifest: AngularAppManifest, url: URL): Promise<ServerRouter> {\n if (manifest.routes) {\n const routeTree = RouteTree.fromObject(manifest.routes);\n\n return Promise.resolve(new ServerRouter(routeTree));\n }\n\n // Create and store a new promise for the build process.\n // This prevents concurrent builds by re-using the same promise.\n ServerRouter.#extractionPromise ??= extractRoutesAndCreateRouteTree({ url, manifest })\n .then(({ routeTree, errors }) => {\n if (errors.length > 0) {\n throw new Error(\n 'Error(s) occurred while extracting routes:\\n' +\n errors.map((error) => `- ${error}`).join('\\n'),\n );\n }\n\n return new ServerRouter(routeTree);\n })\n .finally(() => {\n ServerRouter.#extractionPromise = undefined;\n });\n\n return ServerRouter.#extractionPromise;\n }\n\n /**\n * Matches a request URL against the route tree to retrieve route metadata.\n *\n * This method strips 'index.html' from the URL if it is present and then attempts\n * to find a match in the route tree. If a match is found, it returns the associated\n * route metadata; otherwise, it returns `undefined`.\n *\n * @param url - The URL to be matched against the route tree.\n * @returns The metadata for the matched route or `undefined` if no match is found.\n */\n match(url: URL): RouteTreeNodeMetadata | undefined {\n // Strip 'index.html' from URL if present.\n // A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.\n let { pathname } = stripIndexHtmlFromURL(url);\n pathname = stripMatrixParams(pathname);\n pathname = decodeURIComponent(pathname);\n\n return this.routeTree.match(pathname);\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\n/**\n * Generates a SHA-256 hash of the provided string.\n *\n * @param data - The input string to be hashed.\n * @returns A promise that resolves to the SHA-256 hash of the input,\n * represented as a hexadecimal string.\n */\nexport async function sha256(data: string): Promise<string> {\n const encodedData = new TextEncoder().encode(data);\n const hashBuffer = await crypto.subtle.digest('SHA-256', encodedData);\n const hashParts: string[] = [];\n\n for (const h of new Uint8Array(hashBuffer)) {\n hashParts.push(h.toString(16).padStart(2, '0'));\n }\n\n return hashParts.join('');\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 Beasties from '../.../third_party/beasties';\n\n/**\n * Pattern used to extract the media query set by Beasties in an `onload` handler.\n */\nconst MEDIA_SET_HANDLER_PATTERN = /^this\\.media=[\"'](.*)[\"'];?$/;\n\n/**\n * Name of the attribute used to save the Beasties media query so it can be re-assigned on load.\n */\nconst CSP_MEDIA_ATTR = 'ngCspMedia';\n\n/**\n * Script that dynamically updates the `media` attribute of `<link>` tags based on a custom attribute (`CSP_MEDIA_ATTR`).\n *\n * NOTE:\n * We do not use `document.querySelectorAll('link').forEach((s) => s.addEventListener('load', ...)`\n * because load events are not always triggered reliably on Chrome.\n * See: https://github.com/angular/angular-cli/issues/26932 and https://crbug.com/1521256\n *\n * The script:\n * - Ensures the event target is a `<link>` tag with the `CSP_MEDIA_ATTR` attribute.\n * - Updates the `media` attribute with the value of `CSP_MEDIA_ATTR` and then removes the attribute.\n * - Removes the event listener when all relevant `<link>` tags have been processed.\n * - Uses event capturing (the `true` parameter) since load events do not bubble up the DOM.\n */\nconst LINK_LOAD_SCRIPT_CONTENT = /* @__PURE__ */ (() => `(() => {\n const CSP_MEDIA_ATTR = '${CSP_MEDIA_ATTR}';\n const documentElement = document.documentElement;\n\n // Listener for load events on link tags.\n const listener = (e) => {\n const target = e.target;\n if (\n !target ||\n target.tagName !== 'LINK' ||\n !target.hasAttribute(CSP_MEDIA_ATTR)\n ) {\n return;\n }\n\n target.media = target.getAttribute(CSP_MEDIA_ATTR);\n target.removeAttribute(CSP_MEDIA_ATTR);\n\n if (!document.head.querySelector(\\`link[\\${CSP_MEDIA_ATTR}]\\`)) {\n documentElement.removeEventListener('load', listener);\n }\n };\n\n documentElement.addEventListener('load', listener, true);\n})();`)();\n\n/** Partial representation of an `HTMLElement`. */\ninterface PartialHTMLElement {\n getAttribute(name: string): string | null;\n setAttribute(name: string, value: string): void;\n hasAttribute(name: string): boolean;\n removeAttribute(name: string): void;\n appendChild(child: PartialHTMLElement): void;\n insertBefore(newNode: PartialHTMLElement, referenceNode?: PartialHTMLElement): void;\n remove(): void;\n name: string;\n textContent: string;\n tagName: string | null;\n children: PartialHTMLElement[];\n next: PartialHTMLElement | null;\n prev: PartialHTMLElement | null;\n}\n\n/** Partial representation of an HTML `Document`. */\ninterface PartialDocument {\n head: PartialHTMLElement;\n createElement(tagName: string): PartialHTMLElement;\n querySelector(selector: string): PartialHTMLElement | null;\n}\n\n/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\n\n// We use Typescript declaration merging because `embedLinkedStylesheet` it's not declared in\n// the `Beasties` types which means that we can't call the `super` implementation.\ninterface BeastiesBase {\n embedLinkedStylesheet(link: PartialHTMLElement, document: PartialDocument): Promise<unknown>;\n}\nclass BeastiesBase extends Beasties {}\n/* eslint-enable @typescript-eslint/no-unsafe-declaration-merging */\n\nexport class InlineCriticalCssProcessor extends BeastiesBase {\n private addedCspScriptsDocuments = new WeakSet<PartialDocument>();\n private documentNonces = new WeakMap<PartialDocument, string | null>();\n\n constructor(\n public override readFile: (path: string) => Promise<string>,\n readonly outputPath?: string,\n ) {\n super({\n logger: {\n // eslint-disable-next-line no-console\n warn: (s: string) => console.warn(s),\n // eslint-disable-next-line no-console\n error: (s: string) => console.error(s),\n info: () => {},\n },\n logLevel: 'warn',\n path: outputPath,\n publicPath: undefined,\n compress: false,\n pruneSource: false,\n reduceInlineStyles: false,\n mergeStylesheets: false,\n // Note: if `preload` changes to anything other than `media`, the logic in\n // `embedLinkedStylesheet` will have to be updated.\n preload: 'media',\n noscriptFallback: true,\n inlineFonts: true,\n });\n }\n\n /**\n * Override of the Beasties `embedLinkedStylesheet` method\n * that makes it work with Angular's CSP APIs.\n */\n override async embedLinkedStylesheet(\n link: PartialHTMLElement,\n document: PartialDocument,\n ): Promise<unknown> {\n if (link.getAttribute('media') === 'print' && link.next?.name === 'noscript') {\n // Workaround for https://github.com/GoogleChromeLabs/critters/issues/64\n // NB: this is only needed for the webpack based builders.\n const media = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);\n if (media) {\n link.removeAttribute('onload');\n link.setAttribute('media', media[1]);\n link?.next?.remove();\n }\n }\n\n const returnValue = await super.embedLinkedStylesheet(link, document);\n const cspNonce = this.findCspNonce(document);\n\n if (cspNonce) {\n const beastiesMedia = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);\n\n if (beastiesMedia) {\n // If there's a Beasties-generated `onload` handler and the file has an Angular CSP nonce,\n // we have to remove the handler, because it's incompatible with CSP. We save the value\n // in a different attribute and we generate a script tag with the nonce that uses\n // `addEventListener` to apply the media query instead.\n link.removeAttribute('onload');\n link.setAttribute(CSP_MEDIA_ATTR, beastiesMedia[1]);\n this.conditionallyInsertCspLoadingScript(document, cspNonce, link);\n }\n\n // Ideally we would hook in at the time Beasties inserts the `style` tags, but there isn't\n // a way of doing that at the moment so we fall back to doing it any time a `link` tag is\n // inserted. We mitigate it by only iterating the direct children of the `<head>` which\n // should be pretty shallow.\n document.head.children.forEach((child) => {\n if (child.tagName === 'style' && !child.hasAttribute('nonce')) {\n child.setAttribute('nonce', cspNonce);\n }\n });\n }\n\n return returnValue;\n }\n\n /**\n * Finds the CSP nonce for a specific document.\n */\n private findCspNonce(document: PartialDocument): string | null {\n if (this.documentNonces.has(document)) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.documentNonces.get(document)!;\n }\n\n // HTML attribute are case-insensitive, but the parser used by Beasties is case-sensitive.\n const nonceElement = document.querySelector('[ngCspNonce], [ngcspnonce]');\n const cspNonce =\n nonceElement?.getAttribute('ngCspNonce') || nonceElement?.getAttribute('ngcspnonce') || null;\n\n this.documentNonces.set(document, cspNonce);\n\n return cspNonce;\n }\n\n /**\n * Inserts the `script` tag that swaps the critical CSS at runtime,\n * if one hasn't been inserted into the document already.\n */\n private conditionallyInsertCspLoadingScript(\n document: PartialDocument,\n nonce: string,\n link: PartialHTMLElement,\n ): void {\n if (this.addedCspScriptsDocuments.has(document)) {\n return;\n }\n\n if (document.head.textContent.includes(LINK_LOAD_SCRIPT_CONTENT)) {\n // Script was already added during the build.\n this.addedCspScriptsDocuments.add(document);\n\n return;\n }\n\n const script = document.createElement('script');\n script.setAttribute('nonce', nonce);\n script.textContent = LINK_LOAD_SCRIPT_CONTENT;\n // Prepend the script to the head since it needs to\n // run as early as possible, before the `link` tags.\n document.head.insertBefore(script, link);\n this.addedCspScriptsDocuments.add(document);\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\n/**\n * Represents a node in the doubly linked list.\n */\ninterface Node<Key, Value> {\n key: Key;\n value: Value;\n prev: Node<Key, Value> | undefined;\n next: Node<Key, Value> | undefined;\n}\n\n/**\n * A Least Recently Used (LRU) cache implementation.\n *\n * This cache stores a fixed number of key-value pairs, and when the cache exceeds its capacity,\n * the least recently accessed items are evicted.\n *\n * @template Key - The type of the cache keys.\n * @template Value - The type of the cache values.\n */\nexport class LRUCache<Key, Value> {\n /**\n * The maximum number of items the cache can hold.\n */\n capacity: number;\n\n /**\n * Internal storage for the cache, mapping keys to their associated nodes in the linked list.\n */\n private readonly cache = new Map<Key, Node<Key, Value>>();\n\n /**\n * Head of the doubly linked list, representing the most recently used item.\n */\n private head: Node<Key, Value> | undefined;\n\n /**\n * Tail of the doubly linked list, representing the least recently used item.\n */\n private tail: Node<Key, Value> | undefined;\n\n /**\n * Creates a new LRUCache instance.\n * @param capacity The maximum number of items the cache can hold.\n */\n constructor(capacity: number) {\n this.capacity = capacity;\n }\n\n /**\n * Gets the value associated with the given key.\n * @param key The key to retrieve the value for.\n * @returns The value associated with the key, or undefined if the key is not found.\n */\n get(key: Key): Value | undefined {\n const node = this.cache.get(key);\n if (node) {\n this.moveToHead(node);\n\n return node.value;\n }\n\n return undefined;\n }\n\n /**\n * Puts a key-value pair into the cache.\n * If the key already exists, the value is updated.\n * If the cache is full, the least recently used item is evicted.\n * @param key The key to insert or update.\n * @param value The value to associate with the key.\n */\n put(key: Key, value: Value): void {\n const cachedNode = this.cache.get(key);\n if (cachedNode) {\n // Update existing node\n cachedNode.value = value;\n this.moveToHead(cachedNode);\n\n return;\n }\n\n // Create a new node\n const newNode: Node<Key, Value> = { key, value, prev: undefined, next: undefined };\n this.cache.set(key, newNode);\n this.addToHead(newNode);\n\n if (this.cache.size > this.capacity) {\n // Evict the LRU item\n const tail = this.removeTail();\n if (tail) {\n this.cache.delete(tail.key);\n }\n }\n }\n\n /**\n * Adds a node to the head of the linked list.\n * @param node The node to add.\n */\n private addToHead(node: Node<Key, Value>): void {\n node.next = this.head;\n node.prev = undefined;\n\n if (this.head) {\n this.head.prev = node;\n }\n\n this.head = node;\n\n if (!this.tail) {\n this.tail = node;\n }\n }\n\n /**\n * Removes a node from the linked list.\n * @param node The node to remove.\n */\n private removeNode(node: Node<Key, Value>): void {\n if (node.prev) {\n node.prev.next = node.next;\n } else {\n this.head = node.next;\n }\n\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n this.tail = node.prev;\n }\n }\n\n /**\n * Moves a node to the head of the linked list.\n * @param node The node to move.\n */\n private moveToHead(node: Node<Key, Value>): void {\n this.removeNode(node);\n this.addToHead(node);\n }\n\n /**\n * Removes the tail node from the linked list.\n * @returns The removed tail node, or undefined if the list is empty.\n */\n private removeTail(): Node<Key, Value> | undefined {\n const node = this.tail;\n if (node) {\n this.removeNode(node);\n }\n\n return node;\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 {\n LOCALE_ID,\n REQUEST,\n REQUEST_CONTEXT,\n RESPONSE_INIT,\n StaticProvider,\n ɵresetCompiledComponents,\n} from '@angular/core';\nimport { ServerAssets } from './assets';\nimport { Hooks } from './hooks';\nimport { getAngularAppManifest } from './manifest';\nimport { RenderMode } from './routes/route-config';\nimport { RouteTreeNodeMetadata } from './routes/route-tree';\nimport { ServerRouter } from './routes/router';\nimport { sha256 } from './utils/crypto';\nimport { InlineCriticalCssProcessor } from './utils/inline-critical-css';\nimport { LRUCache } from './utils/lru-cache';\nimport { AngularBootstrap, renderAngular } from './utils/ng';\nimport { promiseWithAbort } from './utils/promise';\nimport { buildPathWithParams, joinUrlParts, stripLeadingSlash } from './utils/url';\n\n/**\n * Maximum number of critical CSS entries the cache can store.\n * This value determines the capacity of the LRU (Least Recently Used) cache, which stores critical CSS for pages.\n */\nconst MAX_INLINE_CSS_CACHE_ENTRIES = 50;\n\n/**\n * A mapping of `RenderMode` enum values to corresponding string representations.\n *\n * This record is used to map each `RenderMode` to a specific string value that represents\n * the server context. The string values are used internally to differentiate\n * between various rendering strategies when processing routes.\n *\n * - `RenderMode.Prerender` maps to `'ssg'` (Static Site Generation).\n * - `RenderMode.Server` maps to `'ssr'` (Server-Side Rendering).\n * - `RenderMode.Client` maps to an empty string `''` (Client-Side Rendering, no server context needed).\n */\nconst SERVER_CONTEXT_VALUE: Record<RenderMode, string> = {\n [RenderMode.Prerender]: 'ssg',\n [RenderMode.Server]: 'ssr',\n [RenderMode.Client]: '',\n};\n\n/**\n * Options for configuring an `AngularServerApp`.\n */\ninterface AngularServerAppOptions {\n /**\n * Whether to allow rendering of prerendered routes.\n *\n * When enabled, prerendered routes will be served directly. When disabled, they will be\n * rendered on demand.\n *\n * Defaults to `false`.\n */\n allowStaticRouteRender?: boolean;\n\n /**\n * Hooks for extending or modifying server behavior.\n *\n * This allows customization of the server's rendering process and other lifecycle events.\n *\n * If not provided, a new `Hooks` instance is created.\n */\n hooks?: Hooks;\n}\n\n/**\n * Represents a locale-specific Angular server application managed by the server application engine.\n *\n * The `AngularServerApp` class handles server-side rendering and asset management for a specific locale.\n */\nexport class AngularServerApp {\n /**\n * Whether prerendered routes should be rendered on demand or served directly.\n *\n * @see {@link AngularServerAppOptions.allowStaticRouteRender} for more details.\n */\n private readonly allowStaticRouteRender: boolean;\n\n /**\n * Hooks for extending or modifying server behavior.\n *\n * @see {@link AngularServerAppOptions.hooks} for more details.\n */\n readonly hooks: Hooks;\n\n /**\n * Constructs an instance of `AngularServerApp`.\n *\n * @param options Optional configuration options for the server application.\n */\n constructor(private readonly options: Readonly<AngularServerAppOptions> = {}) {\n this.allowStaticRouteRender = this.options.allowStaticRouteRender ?? false;\n this.hooks = options.hooks ?? new Hooks();\n\n if (this.manifest.inlineCriticalCss) {\n this.inlineCriticalCssProcessor = new InlineCriticalCssProcessor((path: string) => {\n const fileName = path.split('/').pop() ?? path;\n\n return this.assets.getServerAsset(fileName).text();\n });\n }\n }\n\n /**\n * The manifest associated with this server application.\n */\n private readonly manifest = getAngularAppManifest();\n\n /**\n * An instance of ServerAsset that handles server-side asset.\n */\n private readonly assets = new ServerAssets(this.manifest);\n\n /**\n * The router instance used for route matching and handling.\n */\n private router: ServerRouter | undefined;\n\n /**\n * The `inlineCriticalCssProcessor` is responsible for handling critical CSS inlining.\n */\n private inlineCriticalCssProcessor: InlineCriticalCssProcessor | undefined;\n\n /**\n * The bootstrap mechanism for the server application.\n */\n private boostrap: AngularBootstrap | undefined;\n\n /**\n * Decorder used to convert a string to a Uint8Array.\n */\n private readonly textDecoder = new TextEncoder();\n\n /**\n * A cache that stores critical CSS to avoid re-processing for every request, improving performance.\n * This cache uses a Least Recently Used (LRU) eviction policy.\n *\n * @see {@link MAX_INLINE_CSS_CACHE_ENTRIES} for the maximum number of entries this cache can hold.\n */\n private readonly criticalCssLRUCache = new LRUCache<\n string,\n { shaOfContentPreInlinedCss: string; contentWithCriticialCSS: Uint8Array<ArrayBufferLike> }\n >(MAX_INLINE_CSS_CACHE_ENTRIES);\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 * @param request - The HTTP request to handle.\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(request: Request, requestContext?: unknown): Promise<Response | null> {\n const url = new URL(request.url);\n this.router ??= await ServerRouter.from(this.manifest, url);\n const matchedRoute = this.router.match(url);\n\n if (!matchedRoute) {\n // Not a known Angular route.\n return null;\n }\n\n const { redirectTo, status, renderMode } = matchedRoute;\n\n if (redirectTo !== undefined) {\n return createRedirectResponse(\n joinUrlParts(\n request.headers.get('X-Forwarded-Prefix') ?? '',\n buildPathWithParams(redirectTo, url.pathname),\n ),\n status,\n );\n }\n\n if (renderMode === RenderMode.Prerender) {\n const response = await this.handleServe(request, matchedRoute);\n if (response) {\n return response;\n }\n }\n\n return promiseWithAbort(\n this.handleRendering(request, matchedRoute, requestContext),\n request.signal,\n `Request for: ${request.url}`,\n );\n }\n\n /**\n * Handles serving a prerendered static asset if available for the matched route.\n *\n * This method only supports `GET` and `HEAD` requests.\n *\n * @param request - The incoming HTTP request for serving a static page.\n * @param matchedRoute - The metadata of the matched route for rendering.\n * @returns A promise that resolves to a `Response` object if the prerendered page is found, or `null`.\n */\n private async handleServe(\n request: Request,\n matchedRoute: RouteTreeNodeMetadata,\n ): Promise<Response | null> {\n const { headers, renderMode } = matchedRoute;\n if (renderMode !== RenderMode.Prerender) {\n return null;\n }\n\n const { method } = request;\n if (method !== 'GET' && method !== 'HEAD') {\n return null;\n }\n\n const assetPath = this.buildServerAssetPathFromRequest(request);\n const {\n manifest: { locale },\n assets,\n } = this;\n\n if (!assets.hasServerAsset(assetPath)) {\n return null;\n }\n\n const { text, hash, size } = assets.getServerAsset(assetPath);\n const etag = `\"${hash}\"`;\n\n return request.headers.get('if-none-match') === etag\n ? new Response(undefined, { status: 304, statusText: 'Not Modified' })\n : new Response(await text(), {\n headers: {\n 'Content-Length': size.toString(),\n 'ETag': etag,\n 'Content-Type': 'text/html;charset=UTF-8',\n ...(locale !== undefined ? { 'Content-Language': locale } : {}),\n ...headers,\n },\n });\n }\n\n /**\n * Handles the server-side rendering process for the given HTTP request.\n * This method matches the request URL to a route and performs rendering if a matching route is found.\n *\n * @param request - The incoming HTTP request to be processed.\n * @param matchedRoute - The metadata of the matched route for rendering.\n * @param requestContext - Optional additional context for rendering, such as request metadata.\n *\n * @returns A promise that resolves to the rendered response, or null if no matching route is found.\n */\n private async handleRendering(\n request: Request,\n matchedRoute: RouteTreeNodeMetadata,\n requestContext?: unknown,\n ): Promise<Response | null> {\n const { renderMode, headers, status, preload } = matchedRoute;\n\n if (!this.allowStaticRouteRender && renderMode === RenderMode.Prerender) {\n return null;\n }\n\n const url = new URL(request.url);\n const platformProviders: StaticProvider[] = [];\n\n const {\n manifest: { bootstrap, locale },\n assets,\n } = this;\n\n // Initialize the response with status and headers if available.\n const responseInit = {\n status,\n headers: new Headers({\n 'Content-Type': 'text/html;charset=UTF-8',\n ...(locale !== undefined ? { 'Content-Language': locale } : {}),\n ...headers,\n }),\n };\n\n if (renderMode === RenderMode.Server) {\n // Configure platform providers for request and response only for SSR.\n platformProviders.push(\n {\n provide: REQUEST,\n useValue: request,\n },\n {\n provide: REQUEST_CONTEXT,\n useValue: requestContext,\n },\n {\n provide: RESPONSE_INIT,\n useValue: responseInit,\n },\n );\n } else if (renderMode === RenderMode.Client) {\n // Serve the client-side rendered version if the route is configured for CSR.\n let html = await this.assets.getServerAsset('index.csr.html').text();\n html = await this.runTransformsOnHtml(html, url, preload);\n\n return new Response(html, responseInit);\n }\n\n if (locale !== undefined) {\n platformProviders.push({\n provide: LOCALE_ID,\n useValue: locale,\n });\n }\n\n this.boostrap ??= await bootstrap();\n let html = await assets.getIndexServerHtml().text();\n html = await this.runTransformsOnHtml(html, url, preload);\n\n const result = await renderAngular(\n html,\n this.boostrap,\n url,\n platformProviders,\n SERVER_CONTEXT_VALUE[renderMode],\n );\n\n if (result.hasNavigationError) {\n return null;\n }\n\n if (result.redirectTo) {\n return createRedirectResponse(result.redirectTo, status);\n }\n\n if (renderMode === RenderMode.Prerender) {\n const renderedHtml = await result.content();\n const finalHtml = await this.inlineCriticalCss(renderedHtml, url);\n\n return new Response(finalHtml, responseInit);\n }\n\n // Use a stream to send the response before finishing rendering and inling critical CSS, improving performance via header flushing.\n const stream = new ReadableStream({\n start: async (controller) => {\n const renderedHtml = await result.content();\n const finalHtml = await this.inlineCriticalCssWithCache(renderedHtml, url);\n controller.enqueue(finalHtml);\n controller.close();\n },\n });\n\n return new Response(stream, responseInit);\n }\n\n /**\n * Inlines critical CSS into the given HTML content.\n *\n * @param html The HTML content to process.\n * @param url The URL associated with the request, for logging purposes.\n * @returns A promise that resolves to the HTML with inlined critical CSS.\n */\n private async inlineCriticalCss(html: string, url: URL): Promise<string> {\n const { inlineCriticalCssProcessor } = this;\n\n if (!inlineCriticalCssProcessor) {\n return html;\n }\n\n try {\n return await inlineCriticalCssProcessor.process(html);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(`An error occurred while inlining critical CSS for: ${url}.`, error);\n\n return html;\n }\n }\n\n /**\n * Inlines critical CSS into the given HTML content.\n * This method uses a cache to avoid reprocessing the same HTML content multiple times.\n *\n * @param html The HTML content to process.\n * @param url The URL associated with the request, for logging purposes.\n * @returns A promise that resolves to the HTML with inlined critical CSS.\n */\n private async inlineCriticalCssWithCache(\n html: string,\n url: URL,\n ): Promise<Uint8Array<ArrayBufferLike>> {\n const { inlineCriticalCssProcessor, criticalCssLRUCache, textDecoder } = this;\n\n if (!inlineCriticalCssProcessor) {\n return textDecoder.encode(html);\n }\n\n const cacheKey = url.toString();\n const cached = criticalCssLRUCache.get(cacheKey);\n const shaOfContentPreInlinedCss = await sha256(html);\n if (cached?.shaOfContentPreInlinedCss === shaOfContentPreInlinedCss) {\n return cached.contentWithCriticialCSS;\n }\n\n const processedHtml = await this.inlineCriticalCss(html, url);\n const finalHtml = textDecoder.encode(processedHtml);\n criticalCssLRUCache.put(cacheKey, {\n shaOfContentPreInlinedCss,\n contentWithCriticialCSS: finalHtml,\n });\n\n return finalHtml;\n }\n\n /**\n * Constructs the asset path on the server based on the provided HTTP request.\n *\n * This method processes the incoming request URL to derive a path corresponding\n * to the requested asset. It ensures the path points to the correct file (e.g.,\n * `index.html`) and removes any base href if it is not part of the asset path.\n *\n * @param request - The incoming HTTP request object.\n * @returns The server-relative asset path derived from the request.\n */\n private buildServerAssetPathFromRequest(request: Request): string {\n let { pathname: assetPath } = new URL(request.url);\n if (!assetPath.endsWith('/index.html')) {\n // Append \"index.html\" to build the default asset path.\n assetPath = joinUrlParts(assetPath, 'index.html');\n }\n\n const { baseHref } = this.manifest;\n // Check if the asset path starts with the base href and the base href is not (`/` or ``).\n if (baseHref.length > 1 && assetPath.startsWith(baseHref)) {\n // Remove the base href from the start of the asset path to align with server-asset expectations.\n assetPath = assetPath.slice(baseHref.length);\n }\n\n return stripLeadingSlash(assetPath);\n }\n\n /**\n * Runs the registered transform hooks on the given HTML content.\n *\n * @param html - The raw HTML content to be transformed.\n * @param url - The URL associated with the HTML content, used for context during transformations.\n * @param preload - An array of URLs representing the JavaScript resources to preload.\n * @returns A promise that resolves to the transformed HTML string.\n */\n private async runTransformsOnHtml(\n html: string,\n url: URL,\n preload: readonly string[] | undefined,\n ): Promise<string> {\n if (this.hooks.has('html:transform:pre')) {\n html = await this.hooks.run('html:transform:pre', { html, url });\n }\n\n if (preload?.length) {\n html = appendPreloadHintsToHtml(html, preload);\n }\n\n return html;\n }\n}\n\nlet angularServerApp: AngularServerApp | undefined;\n\n/**\n * Retrieves or creates an instance of `AngularServerApp`.\n * - If an instance of `AngularServerApp` already exists, it will return the existing one.\n * - If no instance exists, it will create a new one with the provided options.\n *\n * @param options Optional configuration options for the server application.\n *\n * @returns The existing or newly created instance of `AngularServerApp`.\n */\nexport function getOrCreateAngularServerApp(\n options?: Readonly<AngularServerAppOptions>,\n): AngularServerApp {\n return (angularServerApp ??= new AngularServerApp(options));\n}\n\n/**\n * Destroys the existing `AngularServerApp` instance, releasing associated resources and resetting the\n * reference to `undefined`.\n *\n * This function is primarily used to enable the recreation of the `AngularServerApp` instance,\n * typically when server configuration or application state needs to be refreshed.\n */\nexport function destroyAngularServerApp(): void {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n // Need to clean up GENERATED_COMP_IDS map in `@angular/core`.\n // Otherwise an incorrect component ID generation collision detected warning will be displayed in development.\n // See: https://github.com/angular/angular-cli/issues/25924\n ɵresetCompiledComponents();\n }\n\n angularServerApp = undefined;\n}\n\n/**\n * Appends module preload hints to an HTML string for specified JavaScript resources.\n * This function enhances the HTML by injecting `<link rel=\"modulepreload\">` elements\n * for each provided resource, allowing browsers to preload the specified JavaScript\n * modules for better performance.\n *\n * @param html - The original HTML string to which preload hints will be added.\n * @param preload - An array of URLs representing the JavaScript resources to preload.\n * @returns The modified HTML string with the preload hints injected before the closing `</body>` tag.\n * If `</body>` is not found, the links are not added.\n */\nfunction appendPreloadHintsToHtml(html: string, preload: readonly string[]): string {\n const bodyCloseIdx = html.lastIndexOf('</body>');\n if (bodyCloseIdx === -1) {\n return html;\n }\n\n // Note: Module preloads should be placed at the end before the closing body tag to avoid a performance penalty.\n // Placing them earlier can cause the browser to prioritize downloading these modules\n // over other critical page resources like images, CSS, and fonts.\n return [\n html.slice(0, bodyCloseIdx),\n ...preload.map((val) => `<link rel=\"modulepreload\" href=\"${val}\">`),\n html.slice(bodyCloseIdx),\n ].join('\\n');\n}\n\n/**\n * Creates an HTTP redirect response with a specified location and status code.\n *\n * @param location - The URL to which the response should redirect.\n * @param status - The HTTP status code for the redirection. Defaults to 302 (Found).\n * See: https://developer.mozilla.org/en-US/docs/Web/API/Response/redirect_static#status\n * @returns A `Response` object representing the HTTP redirect.\n */\nfunction createRedirectResponse(location: string, status = 302): Response {\n return new Response(null, {\n status,\n headers: {\n 'Location': location,\n },\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\n/**\n * Extracts a potential locale ID from a given URL based on the specified base path.\n *\n * This function parses the URL to locate a potential locale identifier that immediately\n * follows the base path segment in the URL's pathname. If the URL does not contain a valid\n * locale ID, an empty string is returned.\n *\n * @param url - The full URL from which to extract the locale ID.\n * @param basePath - The base path used as the reference point for extracting the locale ID.\n * @returns The extracted locale ID if present, or an empty string if no valid locale ID is found.\n *\n * @example\n * ```js\n * const url = new URL('https://example.com/base/en/page');\n * const basePath = '/base';\n * const localeId = getPotentialLocaleIdFromUrl(url, basePath);\n * console.log(localeId); // Output: 'en'\n * ```\n */\nexport function getPotentialLocaleIdFromUrl(url: URL, basePath: string): string {\n const { pathname } = url;\n\n // Move forward of the base path section.\n let start = basePath.length;\n if (pathname[start] === '/') {\n start++;\n }\n\n // Find the next forward slash.\n let end = pathname.indexOf('/', start);\n if (end === -1) {\n end = pathname.length;\n }\n\n // Extract the potential locale id.\n return pathname.slice(start, end);\n}\n\n/**\n * Parses the `Accept-Language` header and returns a list of locale preferences with their respective quality values.\n *\n * The `Accept-Language` header is typically a comma-separated list of locales, with optional quality values\n * in the form of `q=<value>`. If no quality value is specified, a default quality of `1` is assumed.\n * Special case: if the header is `*`, it returns the default locale with a quality of `1`.\n *\n * @param header - The value of the `Accept-Language` header, typically a comma-separated list of locales\n * with optional quality values (e.g., `en-US;q=0.8,fr-FR;q=0.9`). If the header is `*`,\n * it represents a wildcard for any language, returning the default locale.\n *\n * @returns A `ReadonlyMap` where the key is the locale (e.g., `en-US`, `fr-FR`), and the value is\n * the associated quality value (a number between 0 and 1). If no quality value is provided,\n * a default of `1` is used.\n *\n * @example\n * ```js\n * parseLanguageHeader('en-US;q=0.8,fr-FR;q=0.9')\n * // returns new Map([['en-US', 0.8], ['fr-FR', 0.9]])\n\n * parseLanguageHeader('*')\n * // returns new Map([['*', 1]])\n * ```\n */\nfunction parseLanguageHeader(header: string): ReadonlyMap<string, number> {\n if (header === '*') {\n return new Map([['*', 1]]);\n }\n\n const parsedValues = header\n .split(',')\n .map((item) => {\n const [locale, qualityValue] = item.split(';', 2).map((v) => v.trim());\n\n let quality = qualityValue?.startsWith('q=') ? parseFloat(qualityValue.slice(2)) : undefined;\n if (typeof quality !== 'number' || isNaN(quality) || quality < 0 || quality > 1) {\n quality = 1; // Invalid quality value defaults to 1\n }\n\n return [locale, quality] as const;\n })\n .sort(([_localeA, qualityA], [_localeB, qualityB]) => qualityB - qualityA);\n\n return new Map(parsedValues);\n}\n\n/**\n * Gets the preferred locale based on the highest quality value from the provided `Accept-Language` header\n * and the set of available locales.\n *\n * This function adheres to the HTTP `Accept-Language` header specification as defined in\n * [RFC 7231](https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.5), including:\n * - Case-insensitive matching of language tags.\n * - Quality value handling (e.g., `q=1`, `q=0.8`). If no quality value is provided, it defaults to `q=1`.\n * - Prefix matching (e.g., `en` matching `en-US` or `en-GB`).\n *\n * @param header - The `Accept-Language` header string to parse and evaluate. It may contain multiple\n * locales with optional quality values, for example: `'en-US;q=0.8,fr-FR;q=0.9'`.\n * @param supportedLocales - An array of supported locales (e.g., `['en-US', 'fr-FR']`),\n * representing the locales available in the application.\n * @returns The best matching locale from the supported languages, or `undefined` if no match is found.\n *\n * @example\n * ```js\n * getPreferredLocale('en-US;q=0.8,fr-FR;q=0.9', ['en-US', 'fr-FR', 'de-DE'])\n * // returns 'fr-FR'\n *\n * getPreferredLocale('en;q=0.9,fr-FR;q=0.8', ['en-US', 'fr-FR', 'de-DE'])\n * // returns 'en-US'\n *\n * getPreferredLocale('es-ES;q=0.7', ['en-US', 'fr-FR', 'de-DE'])\n * // returns undefined\n * ```\n */\nexport function getPreferredLocale(\n header: string,\n supportedLocales: ReadonlyArray<string>,\n): string | undefined {\n if (supportedLocales.length < 2) {\n return supportedLocales[0];\n }\n\n const parsedLocales = parseLanguageHeader(header);\n\n // Handle edge cases:\n // - No preferred locales provided.\n // - Only one supported locale.\n // - Wildcard preference.\n if (parsedLocales.size === 0 || (parsedLocales.size === 1 && parsedLocales.has('*'))) {\n return supportedLocales[0];\n }\n\n // Create a map for case-insensitive lookup of supported locales.\n // Keys are normalized (lowercase) locale values, values are original casing.\n const normalizedSupportedLocales = new Map<string, string>();\n for (const locale of supportedLocales) {\n normalizedSupportedLocales.set(normalizeLocale(locale), locale);\n }\n\n // Iterate through parsed locales in descending order of quality.\n let bestMatch: string | undefined;\n const qualityZeroNormalizedLocales = new Set<string>();\n for (const [locale, quality] of parsedLocales) {\n const normalizedLocale = normalizeLocale(locale);\n if (quality === 0) {\n qualityZeroNormalizedLocales.add(normalizedLocale);\n continue; // Skip locales with quality value of 0.\n }\n\n // Exact match found.\n if (normalizedSupportedLocales.has(normalizedLocale)) {\n return normalizedSupportedLocales.get(normalizedLocale);\n }\n\n // If an exact match is not found, try prefix matching (e.g., \"en\" matches \"en-US\").\n // Store the first prefix match encountered, as it has the highest quality value.\n if (bestMatch !== undefined) {\n continue;\n }\n\n const [languagePrefix] = normalizedLocale.split('-', 1);\n for (const supportedLocale of normalizedSupportedLocales.keys()) {\n if (supportedLocale.startsWith(languagePrefix)) {\n bestMatch = normalizedSupportedLocales.get(supportedLocale);\n break; // No need to continue searching for this locale.\n }\n }\n }\n\n if (bestMatch !== undefined) {\n return bestMatch;\n }\n\n // Return the first locale that is not quality zero.\n for (const [normalizedLocale, locale] of normalizedSupportedLocales) {\n if (!qualityZeroNormalizedLocales.has(normalizedLocale)) {\n return locale;\n }\n }\n}\n\n/**\n * Normalizes a locale string by converting it to lowercase.\n *\n * @param locale - The locale string to normalize.\n * @returns The normalized locale string in lowercase.\n *\n * @example\n * ```ts\n * const normalized = normalizeLocale('EN-US');\n * console.log(normalized); // Output: \"en-us\"\n * ```\n */\nfunction normalizeLocale(locale: string): string {\n return locale.toLowerCase();\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 { AngularServerApp, getOrCreateAngularServerApp } from './app';\nimport { Hooks } from './hooks';\nimport { getPotentialLocaleIdFromUrl, getPreferredLocale } from './i18n';\nimport { EntryPointExports, getAngularAppEngineManifest } from './manifest';\nimport { joinUrlParts } from './utils/url';\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 AngularAppEngine {\n /**\n * A flag to enable or disable the rendering of prerendered routes.\n *\n * Typically used during development to avoid prerendering all routes ahead of time,\n * allowing them to be rendered on the fly as requested.\n *\n * @private\n */\n static ɵallowStaticRouteRender = false;\n\n /**\n * Hooks for extending or modifying the behavior of the server application.\n * These hooks are used by the Angular CLI when running the development server and\n * provide extensibility points for the application lifecycle.\n *\n * @private\n */\n static ɵhooks = /* #__PURE__*/ new Hooks();\n\n /**\n * The manifest for the server application.\n */\n private readonly manifest = getAngularAppEngineManifest();\n\n /**\n * A map of supported locales from the server application's manifest.\n */\n private readonly supportedLocales: ReadonlyArray<string> = Object.keys(\n this.manifest.supportedLocales,\n );\n\n /**\n * A cache that holds entry points, keyed by their potential locale string.\n */\n private readonly entryPointsCache = new Map<string, Promise<EntryPointExports>>();\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 * @param request - The HTTP request to handle.\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(request: Request, requestContext?: unknown): Promise<Response | null> {\n const serverApp = await this.getAngularServerAppForRequest(request);\n\n if (serverApp) {\n return serverApp.handle(request, requestContext);\n }\n\n if (this.supportedLocales.length > 1) {\n // Redirect to the preferred language if i18n is enabled.\n return this.redirectBasedOnAcceptLanguage(request);\n }\n\n return null;\n }\n\n /**\n * Handles requests for the base path when i18n is enabled.\n * Redirects the user to a locale-specific path based on the `Accept-Language` header.\n *\n * @param request The incoming request.\n * @returns A `Response` object with a 302 redirect, or `null` if i18n is not enabled\n * or the request is not for the base path.\n */\n private redirectBasedOnAcceptLanguage(request: Request): Response | null {\n const { basePath, supportedLocales } = this.manifest;\n\n // If the request is not for the base path, it's not our responsibility to handle it.\n const { pathname } = new URL(request.url);\n if (pathname !== basePath) {\n return null;\n }\n\n // For requests to the base path (typically '/'), attempt to extract the preferred locale\n // from the 'Accept-Language' header.\n const preferredLocale = getPreferredLocale(\n request.headers.get('Accept-Language') || '*',\n this.supportedLocales,\n );\n\n if (preferredLocale) {\n const subPath = supportedLocales[preferredLocale];\n if (subPath !== undefined) {\n return new Response(null, {\n status: 302, // Use a 302 redirect as language preference may change.\n headers: {\n 'Location': joinUrlParts(pathname, subPath),\n 'Vary': 'Accept-Language',\n },\n });\n }\n }\n\n return null;\n }\n\n /**\n * Retrieves the Angular server application instance for a given request.\n *\n * This method checks if the request URL corresponds to an Angular application entry point.\n * If so, it initializes or retrieves an instance of the Angular server application for that entry point.\n * Requests that resemble file requests (except for `/index.html`) are skipped.\n *\n * @param request - The incoming HTTP request object.\n * @returns A promise that resolves to an `AngularServerApp` instance if a valid entry point is found,\n * or `null` if no entry point matches the request URL.\n */\n private async getAngularServerAppForRequest(request: Request): Promise<AngularServerApp | null> {\n // Skip if the request looks like a file but not `/index.html`.\n const url = new URL(request.url);\n const entryPoint = await this.getEntryPointExportsForUrl(url);\n if (!entryPoint) {\n return null;\n }\n\n // Note: Using `instanceof` is not feasible here because `AngularServerApp` will\n // be located in separate bundles, making `instanceof` checks unreliable.\n const ɵgetOrCreateAngularServerApp =\n entryPoint.ɵgetOrCreateAngularServerApp as typeof getOrCreateAngularServerApp;\n\n const serverApp = ɵgetOrCreateAngularServerApp({\n allowStaticRouteRender: AngularAppEngine.ɵallowStaticRouteRender,\n hooks: AngularAppEngine.ɵhooks,\n });\n\n return serverApp;\n }\n\n /**\n * Retrieves the exports for a specific entry point, caching the result.\n *\n * @param potentialLocale - The locale string used to find the corresponding entry point.\n * @returns A promise that resolves to the entry point exports or `undefined` if not found.\n */\n private getEntryPointExports(potentialLocale: string): Promise<EntryPointExports> | undefined {\n const cachedEntryPoint = this.entryPointsCache.get(potentialLocale);\n if (cachedEntryPoint) {\n return cachedEntryPoint;\n }\n\n const { entryPoints } = this.manifest;\n const entryPoint = entryPoints[potentialLocale];\n if (!entryPoint) {\n return undefined;\n }\n\n const entryPointExports = entryPoint();\n this.entryPointsCache.set(potentialLocale, entryPointExports);\n\n return entryPointExports;\n }\n\n /**\n * Retrieves the entry point for a given URL by determining the locale and mapping it to\n * the appropriate application bundle.\n *\n * This method determines the appropriate entry point and locale for rendering the application by examining the URL.\n * If there is only one entry point available, it is returned regardless of the URL.\n * Otherwise, the method extracts a potential locale identifier from the URL and looks up the corresponding entry point.\n *\n * @param url - The URL of the request.\n * @returns A promise that resolves to the entry point exports or `undefined` if not found.\n */\n private getEntryPointExportsForUrl(url: URL): Promise<EntryPointExports> | undefined {\n const { basePath, supportedLocales } = this.manifest;\n\n if (this.supportedLocales.length === 1) {\n return this.getEntryPointExports(supportedLocales[this.supportedLocales[0]]);\n }\n\n const potentialLocale = getPotentialLocaleIdFromUrl(url, basePath);\n\n return this.getEntryPointExports(potentialLocale) ?? this.getEntryPointExports('');\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\n/**\n * Function for handling HTTP requests in a web environment.\n *\n * @param request - The incoming HTTP request object.\n * @returns A Promise resolving to a `Response` object, `null`, or directly a `Response`,\n * supporting both synchronous and asynchronous handling.\n */\nexport type RequestHandlerFunction = (\n request: Request,\n) => Promise<Response | null> | null | Response;\n\n/**\n * Annotates a request handler function with metadata, marking it as a special\n * handler.\n *\n * @param handler - The request handler function to be annotated.\n * @returns The same handler function passed in, with metadata attached.\n *\n * @example\n * Example usage in a Hono application:\n * ```ts\n * const app = new Hono();\n * export default createRequestHandler(app.fetch);\n * ```\n *\n * @example\n * Example usage in a H3 application:\n * ```ts\n * const app = createApp();\n * const handler = toWebHandler(app);\n * export default createRequestHandler(handler);\n * ```\n */\nexport function createRequestHandler(handler: RequestHandlerFunction): RequestHandlerFunction {\n (handler as RequestHandlerFunction & { __ng_request_handler__?: boolean })[\n '__ng_request_handler__'\n ] = true;\n\n return handler;\n}\n"],"names":["ServerAssets","manifest","constructor","getServerAsset","path","asset","assets","Error","hasServerAsset","getIndexServerHtml","IGNORED_LOGS","Set","Console","ɵConsole","log","message","has","angularAppManifest","setAngularAppManifest","getAngularAppManifest","angularAppEngineManifest","setAngularAppEngineManifest","getAngularAppEngineManifest","stripTrailingSlash","url","length","at","slice","stripLeadingSlash","addLeadingSlash","addTrailingSlash","joinUrlParts","parts","normalizeParts","part","normalizedPart","push","join","stripIndexHtmlFromURL","pathname","endsWith","modifiedURL","URL","buildPathWithParams","toPath","fromPath","includes","fromPathParts","split","toPathParts","resolvedParts","map","index","MATRIX_PARAMS_REGEX","stripMatrixParams","replace","renderAngular","html","bootstrap","platformProviders","serverContext","urlToRender","platformRef","platformServer","provide","INITIAL_CONFIG","useValue","href","document","SERVER_CONTEXT","useFactory","redirectTo","hasNavigationError","applicationRef","isNgModule","moduleRef","bootstrapModule","injector","get","ApplicationRef","whenStable","envInjector","routerIsProvided","ActivatedRoute","router","Router","lastSuccessfulNavigation","finalUrl","requestPrefix","APP_BASE_HREF","optional","REQUEST","headers","search","hash","PlatformLocation","constructDecodedUrl","urlToRenderString","content","Promise","resolve","reject","setTimeout","renderInternal","then","catch","finally","asyncDestroyPlatform","error","value","destroyed","destroy","prefix","urlParts","startsWith","decodeURIComponent","promiseWithAbort","promise","signal","errorMessagePrefix","abortHandler","DOMException","reason","aborted","addEventListener","once","removeEventListener","APP_SHELL_ROUTE","ServerRenderingFeatureKind","RenderMode","PrerenderFallback","SERVER_ROUTES_CONFIG","InjectionToken","withRoutes","routes","config","ɵkind","ServerRoutes","ɵproviders","withAppShell","component","routeConfig","loadComponent","AppShell","ROUTES","multi","provideEnvironmentInitializer","inject","appShellRoute","provideServerRendering","features","hasAppShell","hasServerRoutes","providers","provideServerRenderingPlatformServer","makeEnvironmentProviders","RouteTree","root","createEmptyRouteTreeNode","insert","route","metadata","node","segments","getPathSegments","normalizedSegments","segment","normalizedSegment","childNode","children","set","match","traverseBySegments","toObject","Array","from","traverse","fromObject","tree","values","filter","Boolean","currentIndex","size","undefined","exactMatch","wildcardMatch","Map","MODULE_PRELOAD_MAX","CATCH_ALL_REGEXP","URL_PARAMETER_REGEXP","VALID_REDIRECT_RESPONSE_CODES","handleRoute","options","currentRoutePath","compiler","parentInjector","serverConfigRouteTree","entryPointToBrowserMapping","invokeGetPrerenderParams","includePrerenderFallbackRoutes","loadChildren","ɵentryName","appendPreloadToMetadata","renderMode","Prerender","handleSSGRoute","status","resolveRedirectTo","traverseRoutesConfig","parentRoute","parentPreloads","preload","routeInjector","createEnvironmentInjector","EnvironmentInjector","loadedChildRoutes","loadChildrenHelper","childRoutes","routeConfigs","matcher","matches","matchedMetaData","presentInClientRouter","entryName","existingPreloads","combinedPreloads","add","fallback","meta","getPrerenderParams","isCatchAllRoute","test","catchAllRoutePath","parameters","runInInjectionContext","params","replacer","handlePrerenderParamsReplacement","routeWithResolvedParams","None","Client","Server","parameterName","routePath","pop","buildServerConfigRouteTree","serverRoutes","unshift","errors","getRoutesFromAngularRouterConfig","protocol","host","ɵENABLE_ROOT_COMPONENT_BOOTSTRAP","navigationTransitions","afterPreactivation","next","rawBaseHref","getBaseHrefFromDOM","baseHref","Compiler","serverRoutesConfig","result","routesResults","traverseRoutes","seenRoutes","routeMetadata","rootRouteMetadata","extractRoutesAndCreateRouteTree","extract","routeTree","text","key","Object","entries","fullRoute","Hooks","store","run","name","context","hooks","ctx","hook","on","handler","ServerRouter","sha256","data","encodedData","TextEncoder","encode","hashBuffer","crypto","subtle","digest","hashParts","h","Uint8Array","toString","padStart","MEDIA_SET_HANDLER_PATTERN","CSP_MEDIA_ATTR","LINK_LOAD_SCRIPT_CONTENT","BeastiesBase","Beasties","InlineCriticalCssProcessor","readFile","outputPath","addedCspScriptsDocuments","WeakSet","documentNonces","WeakMap","logger","warn","s","console","info","logLevel","publicPath","compress","pruneSource","reduceInlineStyles","mergeStylesheets","noscriptFallback","inlineFonts","embedLinkedStylesheet","link","getAttribute","media","removeAttribute","setAttribute","remove","returnValue","cspNonce","findCspNonce","beastiesMedia","conditionallyInsertCspLoadingScript","head","forEach","child","tagName","hasAttribute","nonceElement","querySelector","nonce","textContent","script","createElement","insertBefore","LRUCache","capacity","cache","tail","moveToHead","put","cachedNode","newNode","prev","addToHead","removeTail","delete","removeNode","MAX_INLINE_CSS_CACHE_ENTRIES","SERVER_CONTEXT_VALUE","AngularServerApp","allowStaticRouteRender","inlineCriticalCss","inlineCriticalCssProcessor","fileName","boostrap","textDecoder","criticalCssLRUCache","handle","request","requestContext","matchedRoute","createRedirectResponse","response","handleServe","handleRendering","method","assetPath","buildServerAssetPathFromRequest","locale","etag","Response","statusText","responseInit","Headers","REQUEST_CONTEXT","RESPONSE_INIT","runTransformsOnHtml","LOCALE_ID","renderedHtml","finalHtml","stream","ReadableStream","start","controller","inlineCriticalCssWithCache","enqueue","close","process","cacheKey","cached","shaOfContentPreInlinedCss","contentWithCriticialCSS","processedHtml","appendPreloadHintsToHtml","angularServerApp","getOrCreateAngularServerApp","destroyAngularServerApp","ngDevMode","ɵresetCompiledComponents","bodyCloseIdx","lastIndexOf","val","location","getPotentialLocaleIdFromUrl","basePath","end","indexOf","parseLanguageHeader","header","parsedValues","item","qualityValue","v","trim","quality","parseFloat","isNaN","sort","_localeA","qualityA","_localeB","qualityB","getPreferredLocale","supportedLocales","parsedLocales","normalizedSupportedLocales","normalizeLocale","bestMatch","qualityZeroNormalizedLocales","normalizedLocale","languagePrefix","supportedLocale","keys","toLowerCase","AngularAppEngine","ɵallowStaticRouteRender","ɵhooks","entryPointsCache","serverApp","getAngularServerAppForRequest","redirectBasedOnAcceptLanguage","preferredLocale","subPath","entryPoint","getEntryPointExportsForUrl","ɵgetOrCreateAngularServerApp","getEntryPointExports","potentialLocale","cachedEntryPoint","entryPoints","entryPointExports","createRequestHandler"],"mappings":";;;;;;MAaaA,YAAY,CAAA;EAMMC,QAAA;EAA7BC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A,CAACpb,GAAQ,EAAA;IACzC,MAAM;MAAE4Y,QAAQ;AAAEmB,MAAAA;KAAkB,GAAG,IAAI,CAACtb,QAAQ;AAEpD,IAAA,IAAI,IAAI,CAACsb,gBAAgB,CAAC9Z,MAAM,KAAK,CAAC,EAAE;AACtC,MAAA,OAAO,IAAI,CAACqb,oBAAoB,CAACvB,gBAAgB,CAAC,IAAI,CAACA,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9E;AAEA,IAAA,MAAMwB,eAAe,GAAG5C,2BAA2B,CAAC3Y,GAAG,EAAE4Y,QAAQ,CAAC;AAElE,IAAA,OAAO,IAAI,CAAC0C,oBAAoB,CAACC,eAAe,CAAC,IAAI,IAAI,CAACD,oBAAoB,CAAC,EAAE,CAAC;AACpF;;;ACjKI,SAAUK,oBAAoBA,CAACtL,OAA+B,EAAA;AACjEA,EAAAA,OAAyE,CACxE,wBAAwB,CACzB,GAAG,IAAI;AAER,EAAA,OAAOA,OAAO;AAChB;;;;"}
1
+ {"version":3,"file":"ssr.mjs","sources":["../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/assets.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/console.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/manifest.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/url.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/ng.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/promise.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/redirect.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/routes/route-config.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/routes/route-tree.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/routes/ng-routes.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/hooks.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/routes/router.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/crypto.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/inline-critical-css.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/lru-cache.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/app.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/i18n.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/app-engine.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/handler.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 { AngularAppManifest, ServerAsset } from './manifest';\n\n/**\n * Manages server-side assets.\n */\nexport class ServerAssets {\n /**\n * Creates an instance of ServerAsset.\n *\n * @param manifest - The manifest containing the server assets.\n */\n constructor(private readonly manifest: AngularAppManifest) {}\n\n /**\n * Retrieves the content of a server-side asset using its path.\n *\n * @param path - The path to the server asset within the manifest.\n * @returns The server asset associated with the provided path, as a `ServerAsset` object.\n * @throws Error - Throws an error if the asset does not exist.\n */\n getServerAsset(path: string): ServerAsset {\n const asset = this.manifest.assets[path];\n if (!asset) {\n throw new Error(`Server asset '${path}' does not exist.`);\n }\n\n return asset;\n }\n\n /**\n * Checks if a specific server-side asset exists.\n *\n * @param path - The path to the server asset.\n * @returns A boolean indicating whether the asset exists.\n */\n hasServerAsset(path: string): boolean {\n return !!this.manifest.assets[path];\n }\n\n /**\n * Retrieves the asset for 'index.server.html'.\n *\n * @returns The `ServerAsset` object for 'index.server.html'.\n * @throws Error - Throws an error if 'index.server.html' does not exist.\n */\n getIndexServerHtml(): ServerAsset {\n return this.getServerAsset('index.server.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\nimport { ɵConsole } from '@angular/core';\n\n/**\n * A set of log messages that should be ignored and not printed to the console.\n */\nconst IGNORED_LOGS = new Set(['Angular is running in development mode.']);\n\n/**\n * Custom implementation of the Angular Console service that filters out specific log messages.\n *\n * This class extends the internal Angular `ɵConsole` class to provide customized logging behavior.\n * It overrides the `log` method to suppress logs that match certain predefined messages.\n */\nexport class Console extends ɵConsole {\n /**\n * Logs a message to the console if it is not in the set of ignored messages.\n *\n * @param message - The message to log to the console.\n *\n * This method overrides the `log` method of the `ɵConsole` class. It checks if the\n * message is in the `IGNORED_LOGS` set. If it is not, it delegates the logging to\n * the parent class's `log` method. Otherwise, the message is suppressed.\n */\n override log(message: string): void {\n if (!IGNORED_LOGS.has(message)) {\n super.log(message);\n }\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 { BootstrapContext } from '@angular/platform-browser';\nimport type { SerializableRouteTreeNode } from './routes/route-tree';\nimport { AngularBootstrap } from './utils/ng';\n\n/**\n * Represents a server asset stored in the manifest.\n */\nexport interface ServerAsset {\n /**\n * Retrieves the text content of the asset.\n *\n * @returns A promise that resolves to the asset's content as a string.\n */\n text: () => Promise<string>;\n\n /**\n * A hash string representing the asset's content.\n */\n hash: string;\n\n /**\n * The size of the asset's content in bytes.\n */\n size: number;\n}\n\n/**\n * Represents the exports of an Angular server application entry point.\n */\nexport interface EntryPointExports {\n /**\n * A reference to the function that creates an Angular server application instance.\n *\n * @remarks The return type is `unknown` to prevent circular dependency issues.\n */\n ɵgetOrCreateAngularServerApp: () => unknown;\n\n /**\n * A reference to the function that destroys the `AngularServerApp` instance.\n */\n ɵdestroyAngularServerApp: () => void;\n}\n\n/**\n * Manifest for the Angular server application engine, defining entry points.\n */\nexport interface AngularAppEngineManifest {\n /**\n * A readonly record of entry points for the server application.\n * Each entry consists of:\n * - `key`: The url segment for the entry point.\n * - `value`: A function that returns a promise resolving to an object of type `EntryPointExports`.\n */\n readonly entryPoints: Readonly<Record<string, (() => Promise<EntryPointExports>) | undefined>>;\n\n /**\n * The base path for the server application.\n * This is used to determine the root path of the application.\n */\n readonly basePath: string;\n\n /**\n * A readonly record mapping supported locales to their respective entry-point paths.\n * Each entry consists of:\n * - `key`: The locale identifier (e.g., 'en', 'fr').\n * - `value`: The url segment associated with that locale.\n */\n readonly supportedLocales: Readonly<Record<string, string>>;\n}\n\n/**\n * Manifest for a specific Angular server application, defining assets and bootstrap logic.\n */\nexport interface AngularAppManifest {\n /**\n * The base href for the application.\n * This is used to determine the root path of the application.\n */\n readonly baseHref: string;\n\n /**\n * A readonly record of assets required by the server application.\n * Each entry consists of:\n * - `key`: The path of the asset.\n * - `value`: An object of type `ServerAsset`.\n */\n readonly assets: Readonly<Record<string, ServerAsset | undefined>>;\n\n /**\n * The bootstrap mechanism for the server application.\n * A function that returns a promise that resolves to an `NgModule` or a function\n * returning a promise that resolves to an `ApplicationRef`.\n */\n readonly bootstrap: () => Promise<AngularBootstrap>;\n\n /**\n * Indicates whether critical CSS should be inlined into the HTML.\n * If set to `true`, critical CSS will be inlined for faster page rendering.\n */\n readonly inlineCriticalCss?: boolean;\n\n /**\n * The route tree representation for the routing configuration of the application.\n * This represents the routing information of the application, mapping route paths to their corresponding metadata.\n * It is used for route matching and navigation within the server application.\n */\n readonly routes?: SerializableRouteTreeNode;\n\n /**\n * An optional string representing the locale or language code to be used for\n * the application, aiding with localization and rendering content specific to the locale.\n */\n readonly locale?: string;\n\n /**\n * Maps entry-point names to their corresponding browser bundles and loading strategies.\n *\n * - **Key**: The entry-point name, typically the value of `ɵentryName`.\n * - **Value**: A readonly array of JavaScript bundle paths or `undefined` if no bundles are associated.\n *\n * ### Example\n * ```ts\n * {\n * 'src/app/lazy/lazy.ts': ['src/app/lazy/lazy.js']\n * }\n * ```\n */\n readonly entryPointToBrowserMapping?: Readonly<Record<string, readonly string[] | undefined>>;\n}\n\n/**\n * The Angular app manifest object.\n * This is used internally to store the current Angular app manifest.\n */\nlet angularAppManifest: AngularAppManifest | undefined;\n\n/**\n * Sets the Angular app manifest.\n *\n * @param manifest - The manifest object to set for the Angular application.\n */\nexport function setAngularAppManifest(manifest: AngularAppManifest): void {\n angularAppManifest = manifest;\n}\n\n/**\n * Gets the Angular app manifest.\n *\n * @returns The Angular app manifest.\n * @throws Will throw an error if the Angular app manifest is not set.\n */\nexport function getAngularAppManifest(): AngularAppManifest {\n if (!angularAppManifest) {\n throw new Error(\n 'Angular app manifest is not set. ' +\n `Please ensure you are using the '@angular/build:application' builder to build your server application.`,\n );\n }\n\n return angularAppManifest;\n}\n\n/**\n * The Angular app engine manifest object.\n * This is used internally to store the current Angular app engine manifest.\n */\nlet angularAppEngineManifest: AngularAppEngineManifest | undefined;\n\n/**\n * Sets the Angular app engine manifest.\n *\n * @param manifest - The engine manifest object to set.\n */\nexport function setAngularAppEngineManifest(manifest: AngularAppEngineManifest): void {\n angularAppEngineManifest = manifest;\n}\n\n/**\n * Gets the Angular app engine manifest.\n *\n * @returns The Angular app engine manifest.\n * @throws Will throw an error if the Angular app engine manifest is not set.\n */\nexport function getAngularAppEngineManifest(): AngularAppEngineManifest {\n if (!angularAppEngineManifest) {\n throw new Error(\n 'Angular app engine manifest is not set. ' +\n `Please ensure you are using the '@angular/build:application' builder to build your server application.`,\n );\n }\n\n return angularAppEngineManifest;\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\n/**\n * Removes the trailing slash from a URL if it exists.\n *\n * @param url - The URL string from which to remove the trailing slash.\n * @returns The URL string without a trailing slash.\n *\n * @example\n * ```js\n * stripTrailingSlash('path/'); // 'path'\n * stripTrailingSlash('/path'); // '/path'\n * stripTrailingSlash('/'); // '/'\n * stripTrailingSlash(''); // ''\n * ```\n */\nexport function stripTrailingSlash(url: string): string {\n // Check if the last character of the URL is a slash\n return url.length > 1 && url.at(-1) === '/' ? url.slice(0, -1) : url;\n}\n\n/**\n * Removes the leading slash from a URL if it exists.\n *\n * @param url - The URL string from which to remove the leading slash.\n * @returns The URL string without a leading slash.\n *\n * @example\n * ```js\n * stripLeadingSlash('/path'); // 'path'\n * stripLeadingSlash('/path/'); // 'path/'\n * stripLeadingSlash('/'); // '/'\n * stripLeadingSlash(''); // ''\n * ```\n */\nexport function stripLeadingSlash(url: string): string {\n // Check if the first character of the URL is a slash\n return url.length > 1 && url[0] === '/' ? url.slice(1) : url;\n}\n\n/**\n * Adds a leading slash to a URL if it does not already have one.\n *\n * @param url - The URL string to which the leading slash will be added.\n * @returns The URL string with a leading slash.\n *\n * @example\n * ```js\n * addLeadingSlash('path'); // '/path'\n * addLeadingSlash('/path'); // '/path'\n * ```\n */\nexport function addLeadingSlash(url: string): string {\n // Check if the URL already starts with a slash\n return url[0] === '/' ? url : `/${url}`;\n}\n\n/**\n * Adds a trailing slash to a URL if it does not already have one.\n *\n * @param url - The URL string to which the trailing slash will be added.\n * @returns The URL string with a trailing slash.\n *\n * @example\n * ```js\n * addTrailingSlash('path'); // 'path/'\n * addTrailingSlash('path/'); // 'path/'\n * ```\n */\nexport function addTrailingSlash(url: string): string {\n // Check if the URL already end with a slash\n return url.at(-1) === '/' ? url : `${url}/`;\n}\n\n/**\n * Joins URL parts into a single URL string.\n *\n * This function takes multiple URL segments, normalizes them by removing leading\n * and trailing slashes where appropriate, and then joins them into a single URL.\n *\n * @param parts - The parts of the URL to join. Each part can be a string with or without slashes.\n * @returns The joined URL string, with normalized slashes.\n *\n * @example\n * ```js\n * joinUrlParts('path/', '/to/resource'); // '/path/to/resource'\n * joinUrlParts('/path/', 'to/resource'); // '/path/to/resource'\n * joinUrlParts('', ''); // '/'\n * ```\n */\nexport function joinUrlParts(...parts: string[]): string {\n const normalizeParts: string[] = [];\n for (const part of parts) {\n if (part === '') {\n // Skip any empty parts\n continue;\n }\n\n let normalizedPart = part;\n if (part[0] === '/') {\n normalizedPart = normalizedPart.slice(1);\n }\n if (part.at(-1) === '/') {\n normalizedPart = normalizedPart.slice(0, -1);\n }\n if (normalizedPart !== '') {\n normalizeParts.push(normalizedPart);\n }\n }\n\n return addLeadingSlash(normalizeParts.join('/'));\n}\n\n/**\n * Strips `/index.html` from the end of a URL's path, if present.\n *\n * This function is used to convert URLs pointing to an `index.html` file into their directory\n * equivalents. For example, it transforms a URL like `http://www.example.com/page/index.html`\n * into `http://www.example.com/page`.\n *\n * @param url - The URL object to process.\n * @returns A new URL object with `/index.html` removed from the path, if it was present.\n *\n * @example\n * ```typescript\n * const originalUrl = new URL('http://www.example.com/page/index.html');\n * const cleanedUrl = stripIndexHtmlFromURL(originalUrl);\n * console.log(cleanedUrl.href); // Output: 'http://www.example.com/page'\n * ```\n */\nexport function stripIndexHtmlFromURL(url: URL): URL {\n if (url.pathname.endsWith('/index.html')) {\n const modifiedURL = new URL(url);\n // Remove '/index.html' from the pathname\n modifiedURL.pathname = modifiedURL.pathname.slice(0, /** '/index.html'.length */ -11);\n\n return modifiedURL;\n }\n\n return url;\n}\n\n/**\n * Resolves `*` placeholders in a path template by mapping them to corresponding segments\n * from a base path. This is useful for constructing paths dynamically based on a given base path.\n *\n * The function processes the `toPath` string, replacing each `*` placeholder with\n * the corresponding segment from the `fromPath`. If the `toPath` contains no placeholders,\n * it is returned as-is. Invalid `toPath` formats (not starting with `/`) will throw an error.\n *\n * @param toPath - A path template string that may contain `*` placeholders. Each `*` is replaced\n * by the corresponding segment from the `fromPath`. Static paths (e.g., `/static/path`) are returned\n * directly without placeholder replacement.\n * @param fromPath - A base path string, split into segments, that provides values for\n * replacing `*` placeholders in the `toPath`.\n * @returns A resolved path string with `*` placeholders replaced by segments from the `fromPath`,\n * or the `toPath` returned unchanged if it contains no placeholders.\n *\n * @throws If the `toPath` does not start with a `/`, indicating an invalid path format.\n *\n * @example\n * ```typescript\n * // Example with placeholders resolved\n * const resolvedPath = buildPathWithParams('/*\\/details', '/123/abc');\n * console.log(resolvedPath); // Outputs: '/123/details'\n *\n * // Example with a static path\n * const staticPath = buildPathWithParams('/static/path', '/base/unused');\n * console.log(staticPath); // Outputs: '/static/path'\n * ```\n */\nexport function buildPathWithParams(toPath: string, fromPath: string): string {\n if (toPath[0] !== '/') {\n throw new Error(`Invalid toPath: The string must start with a '/'. Received: '${toPath}'`);\n }\n\n if (fromPath[0] !== '/') {\n throw new Error(`Invalid fromPath: The string must start with a '/'. Received: '${fromPath}'`);\n }\n\n if (!toPath.includes('/*')) {\n return toPath;\n }\n\n const fromPathParts = fromPath.split('/');\n const toPathParts = toPath.split('/');\n const resolvedParts = toPathParts.map((part, index) =>\n toPathParts[index] === '*' ? fromPathParts[index] : part,\n );\n\n return joinUrlParts(...resolvedParts);\n}\n\nconst MATRIX_PARAMS_REGEX = /;[^/]+/g;\n\n/**\n * Removes Angular matrix parameters from a given URL path.\n *\n * This function takes a URL path string and removes any matrix parameters.\n * Matrix parameters are parts of a URL segment that start with a semicolon `;`.\n *\n * @param pathname - The URL path to remove matrix parameters from.\n * @returns The URL path with matrix parameters removed.\n *\n * @example\n * ```ts\n * stripMatrixParams('/path;param=value'); // returns '/path'\n * stripMatrixParams('/path;param=value/to;p=1/resource'); // returns '/path/to/resource'\n * stripMatrixParams('/path/to/resource'); // returns '/path/to/resource'\n * ```\n */\nexport function stripMatrixParams(pathname: string): string {\n // Use a regular expression to remove matrix parameters.\n // This regex finds all occurrences of a semicolon followed by any characters\n return pathname.includes(';') ? pathname.replace(MATRIX_PARAMS_REGEX, '') : pathname;\n}\n\n/**\n * Constructs a decoded URL string from its components.\n *\n * This function joins the pathname (with trailing slash removed), search, and hash,\n * and then decodes the result.\n *\n * @param pathname - The path of the URL.\n * @param search - The query string of the URL (including '?').\n * @param hash - The hash fragment of the URL (including '#').\n * @returns The constructed and decoded URL string.\n */\nexport function constructUrl(pathname: string, search: string, hash: string): string {\n return decodeURIComponent([stripTrailingSlash(pathname), search, hash].join(''));\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 { APP_BASE_HREF, PlatformLocation } from '@angular/common';\nimport {\n ApplicationRef,\n type PlatformRef,\n REQUEST,\n type StaticProvider,\n type Type,\n ɵConsole,\n} from '@angular/core';\nimport { BootstrapContext } from '@angular/platform-browser';\nimport {\n INITIAL_CONFIG,\n ɵSERVER_CONTEXT as SERVER_CONTEXT,\n platformServer,\n ɵrenderInternal as renderInternal,\n} from '@angular/platform-server';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { Console } from '../console';\nimport { addTrailingSlash, joinUrlParts, stripIndexHtmlFromURL, stripTrailingSlash } from './url';\n\n/**\n * Represents the bootstrap mechanism for an Angular application.\n *\n * This type can either be:\n * - A reference to an Angular component or module (`Type<unknown>`) that serves as the root of the application.\n * - A function that returns a `Promise<ApplicationRef>`, which resolves with the root application reference.\n */\nexport type AngularBootstrap =\n | Type<unknown>\n | ((context: BootstrapContext) => Promise<ApplicationRef>);\n\n/**\n * Renders an Angular application or module to an HTML string.\n *\n * This function determines whether the provided `bootstrap` value is an Angular module\n * or a bootstrap function and invokes the appropriate rendering method (`renderModule` or `renderApplication`).\n *\n * @param html - The initial HTML document content.\n * @param bootstrap - An Angular module type or a function returning a promise that resolves to an `ApplicationRef`.\n * @param url - The application URL, used for route-based rendering in SSR.\n * @param platformProviders - An array of platform providers for the rendering process.\n * @param serverContext - A string representing the server context, providing additional metadata for SSR.\n * @returns A promise resolving to an object containing:\n * - `hasNavigationError`: Indicates if a navigation error occurred.\n * - `redirectTo`: (Optional) The redirect URL if a navigation redirect occurred.\n * - `content`: A function returning a promise that resolves to the rendered HTML string.\n */\nexport async function renderAngular(\n html: string,\n bootstrap: AngularBootstrap,\n url: URL,\n platformProviders: StaticProvider[],\n serverContext: string,\n): Promise<{ hasNavigationError: boolean; redirectTo?: string; content: () => Promise<string> }> {\n // A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.\n const urlToRender = stripIndexHtmlFromURL(url);\n const platformRef = platformServer([\n {\n provide: INITIAL_CONFIG,\n useValue: {\n url: urlToRender.href,\n document: html,\n },\n },\n {\n provide: SERVER_CONTEXT,\n useValue: serverContext,\n },\n {\n // An Angular Console Provider that does not print a set of predefined logs.\n provide: ɵConsole,\n // Using `useClass` would necessitate decorating `Console` with `@Injectable`,\n // which would require switching from `ts_library` to `ng_module`. This change\n // would also necessitate various patches of `@angular/bazel` to support ESM.\n useFactory: () => new Console(),\n },\n ...platformProviders,\n ]);\n\n let redirectTo: string | undefined;\n let hasNavigationError = true;\n\n try {\n let applicationRef: ApplicationRef;\n if (isNgModule(bootstrap)) {\n const moduleRef = await platformRef.bootstrapModule(bootstrap);\n applicationRef = moduleRef.injector.get(ApplicationRef);\n } else {\n applicationRef = await bootstrap({ platformRef });\n }\n\n // Block until application is stable.\n await applicationRef.whenStable();\n\n // TODO(alanagius): Find a way to avoid rendering here especially for redirects as any output will be discarded.\n const envInjector = applicationRef.injector;\n const routerIsProvided = !!envInjector.get(ActivatedRoute, null);\n const router = envInjector.get(Router);\n const lastSuccessfulNavigation = router.lastSuccessfulNavigation();\n\n if (!routerIsProvided) {\n hasNavigationError = false;\n } else if (lastSuccessfulNavigation?.finalUrl) {\n hasNavigationError = false;\n\n const requestPrefix =\n envInjector.get(APP_BASE_HREF, null, { optional: true }) ??\n envInjector.get(REQUEST, null, { optional: true })?.headers.get('X-Forwarded-Prefix');\n\n const { pathname, search, hash } = envInjector.get(PlatformLocation);\n const finalUrl = constructDecodedUrl({ pathname, search, hash }, requestPrefix);\n const urlToRenderString = constructDecodedUrl(urlToRender, requestPrefix);\n\n if (urlToRenderString !== finalUrl) {\n redirectTo = [pathname, search, hash].join('');\n }\n }\n\n return {\n hasNavigationError,\n redirectTo,\n content: () =>\n new Promise<string>((resolve, reject) => {\n // Defer rendering to the next event loop iteration to avoid blocking, as most operations in `renderInternal` are synchronous.\n setTimeout(() => {\n renderInternal(platformRef, applicationRef)\n .then(resolve)\n .catch(reject)\n .finally(() => void asyncDestroyPlatform(platformRef));\n }, 0);\n }),\n };\n } catch (error) {\n await asyncDestroyPlatform(platformRef);\n\n throw error;\n } finally {\n if (hasNavigationError || redirectTo) {\n void asyncDestroyPlatform(platformRef);\n }\n }\n}\n\n/**\n * Type guard to determine if a given value is an Angular module.\n * Angular modules are identified by the presence of the `ɵmod` static property.\n * This function helps distinguish between Angular modules and bootstrap functions.\n *\n * @param value - The value to be checked.\n * @returns True if the value is an Angular module (i.e., it has the `ɵmod` property), false otherwise.\n */\nexport function isNgModule(value: AngularBootstrap): value is Type<unknown> {\n return 'ɵmod' in value;\n}\n\n/**\n * Gracefully destroys the application in a macrotask, allowing pending promises to resolve\n * and surfacing any potential errors to the user.\n *\n * @param platformRef - The platform reference to be destroyed.\n */\nfunction asyncDestroyPlatform(platformRef: PlatformRef): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(() => {\n if (!platformRef.destroyed) {\n platformRef.destroy();\n }\n\n resolve();\n }, 0);\n });\n}\n\n/**\n * Constructs a decoded URL string from its components, ensuring consistency for comparison.\n *\n * This function takes a URL-like object (containing `pathname`, `search`, and `hash`),\n * strips the trailing slash from the pathname, joins the components, and then decodes\n * the entire string. This normalization is crucial for accurately comparing URLs\n * that might differ only in encoding or trailing slashes.\n *\n * @param url - An object containing the URL components:\n * - `pathname`: The path of the URL.\n * - `search`: The query string of the URL (including '?').\n * - `hash`: The hash fragment of the URL (including '#').\n * @param prefix - An optional prefix (e.g., `APP_BASE_HREF`) to prepend to the pathname\n * if it is not already present.\n * @returns The constructed and decoded URL string.\n */\nfunction constructDecodedUrl(\n url: { pathname: string; search: string; hash: string },\n prefix?: string | null,\n): string {\n const { pathname, hash, search } = url;\n const urlParts: string[] = [];\n if (prefix && !addTrailingSlash(pathname).startsWith(addTrailingSlash(prefix))) {\n urlParts.push(joinUrlParts(prefix, pathname));\n } else {\n urlParts.push(stripTrailingSlash(pathname));\n }\n\n urlParts.push(search, hash);\n\n return decodeURIComponent(urlParts.join(''));\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\n/**\n * Creates a promise that resolves with the result of the provided `promise` or rejects with an\n * `AbortError` if the `AbortSignal` is triggered before the promise resolves.\n *\n * @param promise - The promise to monitor for completion.\n * @param signal - An `AbortSignal` used to monitor for an abort event. If the signal is aborted,\n * the returned promise will reject.\n * @param errorMessagePrefix - A custom message prefix to include in the error message when the operation is aborted.\n * @returns A promise that either resolves with the value of the provided `promise` or rejects with\n * an `AbortError` if the `AbortSignal` is triggered.\n *\n * @throws {AbortError} If the `AbortSignal` is triggered before the `promise` resolves.\n */\nexport function promiseWithAbort<T>(\n promise: Promise<T>,\n signal: AbortSignal,\n errorMessagePrefix: string,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const abortHandler = () => {\n reject(\n new DOMException(`${errorMessagePrefix} was aborted.\\n${signal.reason}`, 'AbortError'),\n );\n };\n\n // Check for abort signal\n if (signal.aborted) {\n abortHandler();\n\n return;\n }\n\n signal.addEventListener('abort', abortHandler, { once: true });\n\n promise\n .then(resolve)\n .catch(reject)\n .finally(() => {\n signal.removeEventListener('abort', abortHandler);\n });\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\n/**\n * An set of HTTP status codes that are considered valid for redirect responses.\n */\nexport const VALID_REDIRECT_RESPONSE_CODES = new Set([301, 302, 303, 307, 308]);\n\n/**\n * Checks if the given HTTP status code is a valid redirect response code.\n *\n * @param code The HTTP status code to check.\n * @returns `true` if the code is a valid redirect response code, `false` otherwise.\n */\nexport function isValidRedirectResponseCode(code: number): boolean {\n return VALID_REDIRECT_RESPONSE_CODES.has(code);\n}\n\n/**\n * Creates an HTTP redirect response with a specified location and status code.\n *\n * @param location - The URL to which the response should redirect.\n * @param status - The HTTP status code for the redirection. Defaults to 302 (Found).\n * See: https://developer.mozilla.org/en-US/docs/Web/API/Response/redirect_static#status\n * @returns A `Response` object representing the HTTP redirect.\n */\nexport function createRedirectResponse(location: string, status = 302): Response {\n if (ngDevMode && !isValidRedirectResponseCode(status)) {\n throw new Error(\n `Invalid redirect status code: ${status}. ` +\n `Please use one of the following redirect response codes: ${[...VALID_REDIRECT_RESPONSE_CODES.values()].join(', ')}.`,\n );\n }\n\n return new Response(null, {\n status,\n headers: {\n 'Location': location,\n },\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 {\n EnvironmentProviders,\n InjectionToken,\n Provider,\n Type,\n inject,\n makeEnvironmentProviders,\n provideEnvironmentInitializer,\n} from '@angular/core';\nimport { provideServerRendering as provideServerRenderingPlatformServer } from '@angular/platform-server';\nimport { type DefaultExport, ROUTES, type Route } from '@angular/router';\n\n/**\n * The internal path used for the app shell route.\n * @internal\n */\nconst APP_SHELL_ROUTE = 'ng-app-shell';\n\n/**\n * Identifies a particular kind of `ServerRenderingFeatureKind`.\n * @see {@link ServerRenderingFeature}\n */\nenum ServerRenderingFeatureKind {\n AppShell,\n ServerRoutes,\n}\n\n/**\n * Helper type to represent a server routes feature.\n * @see {@link ServerRenderingFeatureKind}\n */\ninterface ServerRenderingFeature<FeatureKind extends ServerRenderingFeatureKind> {\n ɵkind: FeatureKind;\n ɵproviders: (Provider | EnvironmentProviders)[];\n}\n\n/**\n * Different rendering modes for server routes.\n * @see {@link withRoutes}\n * @see {@link ServerRoute}\n */\nexport enum RenderMode {\n /** Server-Side Rendering (SSR) mode, where content is rendered on the server for each request. */\n Server,\n\n /** Client-Side Rendering (CSR) mode, where content is rendered on the client side in the browser. */\n Client,\n\n /** Static Site Generation (SSG) mode, where content is pre-rendered at build time and served as static files. */\n Prerender,\n}\n\n/**\n * Defines the fallback strategies for Static Site Generation (SSG) routes when a pre-rendered path is not available.\n * This is particularly relevant for routes with parameterized URLs where some paths might not be pre-rendered at build time.\n * @see {@link ServerRoutePrerenderWithParams}\n */\nexport enum PrerenderFallback {\n /**\n * Fallback to Server-Side Rendering (SSR) if the pre-rendered path is not available.\n * This strategy dynamically generates the page on the server at request time.\n */\n Server,\n\n /**\n * Fallback to Client-Side Rendering (CSR) if the pre-rendered path is not available.\n * This strategy allows the page to be rendered on the client side.\n */\n Client,\n\n /**\n * No fallback; if the path is not pre-rendered, the server will not handle the request.\n * This means the application will not provide any response for paths that are not pre-rendered.\n */\n None,\n}\n\n/**\n * Common interface for server routes, providing shared properties.\n */\nexport interface ServerRouteCommon {\n /** The path associated with this route. */\n path: string;\n\n /** Optional additional headers to include in the response for this route. */\n headers?: Record<string, string>;\n\n /** Optional status code to return for this route. */\n status?: number;\n}\n\n/**\n * A server route that uses Client-Side Rendering (CSR) mode.\n * @see {@link RenderMode}\n */\nexport interface ServerRouteClient extends ServerRouteCommon {\n /** Specifies that the route uses Client-Side Rendering (CSR) mode. */\n renderMode: RenderMode.Client;\n}\n\n/**\n * A server route that uses Static Site Generation (SSG) mode.\n * @see {@link RenderMode}\n */\nexport interface ServerRoutePrerender extends Omit<ServerRouteCommon, 'status'> {\n /** Specifies that the route uses Static Site Generation (SSG) mode. */\n renderMode: RenderMode.Prerender;\n\n /** Fallback cannot be specified unless `getPrerenderParams` is used. */\n fallback?: never;\n}\n\n/**\n * A server route configuration that uses Static Site Generation (SSG) mode, including support for routes with parameters.\n * @see {@link RenderMode}\n * @see {@link ServerRoutePrerender}\n * @see {@link PrerenderFallback}\n */\nexport interface ServerRoutePrerenderWithParams extends Omit<ServerRoutePrerender, 'fallback'> {\n /**\n * Optional strategy to use if the SSG path is not pre-rendered.\n * This is especially relevant for routes with parameterized URLs, where some paths may not be pre-rendered at build time.\n *\n * This property determines how to handle requests for paths that are not pre-rendered:\n * - `PrerenderFallback.Server`: Use Server-Side Rendering (SSR) to dynamically generate the page at request time.\n * - `PrerenderFallback.Client`: Use Client-Side Rendering (CSR) to fetch and render the page on the client side.\n * - `PrerenderFallback.None`: No fallback; if the path is not pre-rendered, the server will not handle the request.\n *\n * @default `PrerenderFallback.Server` if not provided.\n */\n fallback?: PrerenderFallback;\n\n /**\n * A function that returns a Promise resolving to an array of objects, each representing a route path with URL parameters.\n * This function runs in the injector context, allowing access to Angular services and dependencies.\n *\n * It also works for catch-all routes (e.g., `/**`), where the parameter name will be `**` and the return value will be\n * the segments of the path, such as `/foo/bar`. These routes can also be combined, e.g., `/product/:id/**`,\n * where both a parameterized segment (`:id`) and a catch-all segment (`**`) can be used together to handle more complex paths.\n *\n * @returns A Promise resolving to an array where each element is an object with string keys (representing URL parameter names)\n * and string values (representing the corresponding values for those parameters in the route path).\n *\n * @example\n * ```typescript\n * export const serverRouteConfig: ServerRoutes[] = [\n * {\n * path: '/product/:id',\n * renderMode: RenderMode.Prerender,\n * async getPrerenderParams() {\n * const productService = inject(ProductService);\n * const ids = await productService.getIds(); // Assuming this returns ['1', '2', '3']\n *\n * return ids.map(id => ({ id })); // Generates paths like: ['product/1', 'product/2', 'product/3']\n * },\n * },\n * {\n * path: '/product/:id/**',\n * renderMode: RenderMode.Prerender,\n * async getPrerenderParams() {\n * return [\n * { id: '1', '**': 'laptop/3' },\n * { id: '2', '**': 'laptop/4' }\n * ]; // Generates paths like: ['product/1/laptop/3', 'product/2/laptop/4']\n * },\n * },\n * ];\n * ```\n */\n getPrerenderParams: () => Promise<Record<string, string>[]>;\n}\n\n/**\n * A server route that uses Server-Side Rendering (SSR) mode.\n * @see {@link RenderMode}\n */\nexport interface ServerRouteServer extends ServerRouteCommon {\n /** Specifies that the route uses Server-Side Rendering (SSR) mode. */\n renderMode: RenderMode.Server;\n}\n\n/**\n * Server route configuration.\n * @see {@link withRoutes}\n */\nexport type ServerRoute =\n | ServerRouteClient\n | ServerRoutePrerender\n | ServerRoutePrerenderWithParams\n | ServerRouteServer;\n\n/**\n * Configuration value for server routes configuration.\n * @internal\n */\nexport interface ServerRoutesConfig {\n /**\n * Defines the route to be used as the app shell.\n */\n appShellRoute?: string;\n\n /** List of server routes for the application. */\n routes: ServerRoute[];\n}\n\n/**\n * Token for providing the server routes configuration.\n * @internal\n */\nexport const SERVER_ROUTES_CONFIG = new InjectionToken<ServerRoutesConfig>('SERVER_ROUTES_CONFIG');\n\n/**\n * Configures server-side routing for the application.\n *\n * This function registers an array of `ServerRoute` definitions, enabling server-side rendering\n * for specific URL paths. These routes are used to pre-render content on the server, improving\n * initial load performance and SEO.\n *\n * @param routes - An array of `ServerRoute` objects, each defining a server-rendered route.\n * @returns A `ServerRenderingFeature` object configuring server-side routes.\n *\n * @example\n * ```ts\n * import { provideServerRendering, withRoutes, ServerRoute, RenderMode } from '@angular/ssr';\n *\n * const serverRoutes: ServerRoute[] = [\n * {\n * path: '', // This renders the \"/\" route on the client (CSR)\n * renderMode: RenderMode.Client,\n * },\n * {\n * path: 'about', // This page is static, so we prerender it (SSG)\n * renderMode: RenderMode.Prerender,\n * },\n * {\n * path: 'profile', // This page requires user-specific data, so we use SSR\n * renderMode: RenderMode.Server,\n * },\n * {\n * path: '**', // All other routes will be rendered on the server (SSR)\n * renderMode: RenderMode.Server,\n * },\n * ];\n *\n * provideServerRendering(withRoutes(serverRoutes));\n * ```\n *\n * @see {@link provideServerRendering}\n * @see {@link ServerRoute}\n */\nexport function withRoutes(\n routes: ServerRoute[],\n): ServerRenderingFeature<ServerRenderingFeatureKind.ServerRoutes> {\n const config: ServerRoutesConfig = { routes };\n\n return {\n ɵkind: ServerRenderingFeatureKind.ServerRoutes,\n ɵproviders: [\n {\n provide: SERVER_ROUTES_CONFIG,\n useValue: config,\n },\n ],\n };\n}\n\n/**\n * Configures the shell of the application.\n *\n * The app shell is a minimal, static HTML page that is served immediately, while the\n * full Angular application loads in the background. This improves perceived performance\n * by providing instant feedback to the user.\n *\n * This function configures the app shell route, which serves the provided component for\n * requests that do not match any defined server routes.\n *\n * @param component - The Angular component to render for the app shell. Can be a direct\n * component type or a dynamic import function.\n * @returns A `ServerRenderingFeature` object configuring the app shell.\n *\n * @example\n * ```ts\n * import { provideServerRendering, withAppShell, withRoutes } from '@angular/ssr';\n * import { AppShellComponent } from './app-shell.component';\n *\n * provideServerRendering(\n * withRoutes(serverRoutes),\n * withAppShell(AppShellComponent)\n * );\n * ```\n *\n * @example\n * ```ts\n * import { provideServerRendering, withAppShell, withRoutes } from '@angular/ssr';\n *\n * provideServerRendering(\n * withRoutes(serverRoutes),\n * withAppShell(() =>\n * import('./app-shell.component').then((m) => m.AppShellComponent)\n * )\n * );\n * ```\n *\n * @see {@link provideServerRendering}\n * @see {@link https://angular.dev/ecosystem/service-workers/app-shell App shell pattern on Angular.dev}\n */\nexport function withAppShell(\n component: Type<unknown> | (() => Promise<Type<unknown> | DefaultExport<Type<unknown>>>),\n): ServerRenderingFeature<ServerRenderingFeatureKind.AppShell> {\n const routeConfig: Route = {\n path: APP_SHELL_ROUTE,\n };\n\n if ('ɵcmp' in component) {\n routeConfig.component = component as Type<unknown>;\n } else {\n routeConfig.loadComponent = component as () => Promise<Type<unknown>>;\n }\n\n return {\n ɵkind: ServerRenderingFeatureKind.AppShell,\n ɵproviders: [\n {\n provide: ROUTES,\n useValue: routeConfig,\n multi: true,\n },\n provideEnvironmentInitializer(() => {\n const config = inject(SERVER_ROUTES_CONFIG);\n config.appShellRoute = APP_SHELL_ROUTE;\n }),\n ],\n };\n}\n\n/**\n * Configures server-side rendering for an Angular application.\n *\n * This function sets up the necessary providers for server-side rendering, including\n * support for server routes and app shell. It combines features configured using\n * `withRoutes` and `withAppShell` to provide a comprehensive server-side rendering setup.\n *\n * @param features - Optional features to configure additional server rendering behaviors.\n * @returns An `EnvironmentProviders` instance with the server-side rendering configuration.\n *\n * @example\n * Basic example of how you can enable server-side rendering in your application\n * when using the `bootstrapApplication` function:\n *\n * ```ts\n * import { bootstrapApplication, BootstrapContext } from '@angular/platform-browser';\n * import { provideServerRendering, withRoutes, withAppShell } from '@angular/ssr';\n * import { AppComponent } from './app/app.component';\n * import { SERVER_ROUTES } from './app/app.server.routes';\n * import { AppShellComponent } from './app/app-shell.component';\n *\n * const bootstrap = (context: BootstrapContext) =>\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideServerRendering(\n * withRoutes(SERVER_ROUTES),\n * withAppShell(AppShellComponent),\n * ),\n * ],\n * }, context);\n *\n * export default bootstrap;\n * ```\n * @see {@link withRoutes} configures server-side routing\n * @see {@link withAppShell} configures the application shell\n */\nexport function provideServerRendering(\n ...features: ServerRenderingFeature<ServerRenderingFeatureKind>[]\n): EnvironmentProviders {\n let hasAppShell = false;\n let hasServerRoutes = false;\n const providers: (Provider | EnvironmentProviders)[] = [provideServerRenderingPlatformServer()];\n\n for (const { ɵkind, ɵproviders } of features) {\n hasAppShell ||= ɵkind === ServerRenderingFeatureKind.AppShell;\n hasServerRoutes ||= ɵkind === ServerRenderingFeatureKind.ServerRoutes;\n providers.push(...ɵproviders);\n }\n\n if (!hasServerRoutes && hasAppShell) {\n throw new Error(\n `Configuration error: found 'withAppShell()' without 'withRoutes()' in the same call to 'provideServerRendering()'.` +\n `The 'withAppShell()' function requires 'withRoutes()' to be used.`,\n );\n }\n\n return makeEnvironmentProviders(providers);\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 { addLeadingSlash } from '../utils/url';\nimport { RenderMode } from './route-config';\n\n/**\n * Represents the serialized format of a route tree as an array of node metadata objects.\n * Each entry in the array corresponds to a specific node's metadata within the route tree.\n */\nexport type SerializableRouteTreeNode = ReadonlyArray<RouteTreeNodeMetadata>;\n\n/**\n * Represents metadata for a route tree node, excluding the 'route' path segment.\n */\nexport type RouteTreeNodeMetadataWithoutRoute = Omit<RouteTreeNodeMetadata, 'route'>;\n\n/**\n * Describes metadata associated with a node in the route tree.\n * This metadata includes information such as the route path and optional redirect instructions.\n */\nexport interface RouteTreeNodeMetadata {\n /**\n * Optional redirect path associated with this node.\n * This defines where to redirect if this route is matched.\n */\n redirectTo?: string;\n\n /**\n * The route path for this node.\n *\n * A \"route\" is a URL path or pattern that is used to navigate to different parts of a web application.\n * It is made up of one or more segments separated by slashes `/`. For instance, in the URL `/products/details/42`,\n * the full route is `/products/details/42`, with segments `products`, `details`, and `42`.\n *\n * Routes define how URLs map to views or components in an application. Each route segment contributes to\n * the overall path that determines which view or component is displayed.\n *\n * - **Static Routes**: These routes have fixed segments. For example, `/about` or `/contact`.\n * - **Parameterized Routes**: These include dynamic segments that act as placeholders, such as `/users/:id`,\n * where `:id` could be any user ID.\n *\n * In the context of `RouteTreeNodeMetadata`, the `route` property represents the complete path that this node\n * in the route tree corresponds to. This path is used to determine how a specific URL in the browser maps to the\n * structure and content of the application.\n */\n route: string;\n\n /**\n * Optional status code to return for this route.\n */\n status?: number;\n\n /**\n * Optional additional headers to include in the response for this route.\n */\n headers?: Record<string, string>;\n\n /**\n * Specifies the rendering mode used for this route.\n */\n renderMode: RenderMode;\n\n /**\n * A list of resource that should be preloaded by the browser.\n */\n preload?: readonly string[];\n}\n\n/**\n * Represents a node within the route tree structure.\n * Each node corresponds to a route segment and may have associated metadata and child nodes.\n * The `AdditionalMetadata` type parameter allows for extending the node metadata with custom data.\n */\ninterface RouteTreeNode<AdditionalMetadata extends Record<string, unknown>> {\n /**\n * A map of child nodes, keyed by their corresponding route segment or wildcard.\n */\n children: Map<string, RouteTreeNode<AdditionalMetadata>>;\n\n /**\n * Optional metadata associated with this node, providing additional information such as redirects.\n */\n metadata?: RouteTreeNodeMetadata & AdditionalMetadata;\n}\n\n/**\n * A route tree implementation that supports efficient route matching, including support for wildcard routes.\n * This structure is useful for organizing and retrieving routes in a hierarchical manner,\n * enabling complex routing scenarios with nested paths.\n *\n * @typeParam AdditionalMetadata - Type of additional metadata that can be associated with route nodes.\n */\nexport class RouteTree<AdditionalMetadata extends Record<string, unknown> = {}> {\n /**\n * The root node of the route tree.\n * All routes are stored and accessed relative to this root node.\n */\n private readonly root = this.createEmptyRouteTreeNode();\n\n /**\n * Inserts a new route into the route tree.\n * The route is broken down into segments, and each segment is added to the tree.\n * Parameterized segments (e.g., :id) are normalized to wildcards (*) for matching purposes.\n *\n * @param route - The route path to insert into the tree.\n * @param metadata - Metadata associated with the route, excluding the route path itself.\n */\n insert(route: string, metadata: RouteTreeNodeMetadataWithoutRoute & AdditionalMetadata): void {\n let node = this.root;\n const segments = this.getPathSegments(route);\n const normalizedSegments: string[] = [];\n\n for (const segment of segments) {\n // Replace parameterized segments (e.g., :id) with a wildcard (*) for matching\n const normalizedSegment = segment[0] === ':' ? '*' : segment;\n let childNode = node.children.get(normalizedSegment);\n if (!childNode) {\n childNode = this.createEmptyRouteTreeNode();\n node.children.set(normalizedSegment, childNode);\n }\n\n node = childNode;\n normalizedSegments.push(normalizedSegment);\n }\n\n // At the leaf node, store the full route and its associated metadata\n node.metadata = {\n ...metadata,\n route: addLeadingSlash(normalizedSegments.join('/')),\n };\n }\n\n /**\n * Matches a given route against the route tree and returns the best matching route's metadata.\n * The best match is determined by the lowest insertion index, meaning the earliest defined route\n * takes precedence.\n *\n * @param route - The route path to match against the route tree.\n * @returns The metadata of the best matching route or `undefined` if no match is found.\n */\n match(route: string): (RouteTreeNodeMetadata & AdditionalMetadata) | undefined {\n const segments = this.getPathSegments(route);\n\n return this.traverseBySegments(segments)?.metadata;\n }\n\n /**\n * Converts the route tree into a serialized format representation.\n * This method converts the route tree into an array of metadata objects that describe the structure of the tree.\n * The array represents the routes in a nested manner where each entry includes the route and its associated metadata.\n *\n * @returns An array of `RouteTreeNodeMetadata` objects representing the route tree structure.\n * Each object includes the `route` and associated metadata of a route.\n */\n toObject(): SerializableRouteTreeNode {\n return Array.from(this.traverse());\n }\n\n /**\n * Constructs a `RouteTree` from an object representation.\n * This method is used to recreate a `RouteTree` instance from an array of metadata objects.\n * The array should be in the format produced by `toObject`, allowing for the reconstruction of the route tree\n * with the same routes and metadata.\n *\n * @param value - An array of `RouteTreeNodeMetadata` objects that represent the serialized format of the route tree.\n * Each object should include a `route` and its associated metadata.\n * @returns A new `RouteTree` instance constructed from the provided metadata objects.\n */\n static fromObject(value: SerializableRouteTreeNode): RouteTree {\n const tree = new RouteTree();\n\n for (const { route, ...metadata } of value) {\n tree.insert(route, metadata);\n }\n\n return tree;\n }\n\n /**\n * A generator function that recursively traverses the route tree and yields the metadata of each node.\n * This allows for easy and efficient iteration over all nodes in the tree.\n *\n * @param node - The current node to start the traversal from. Defaults to the root node of the tree.\n */\n *traverse(node = this.root): Generator<RouteTreeNodeMetadata & AdditionalMetadata> {\n if (node.metadata) {\n yield node.metadata;\n }\n\n for (const childNode of node.children.values()) {\n yield* this.traverse(childNode);\n }\n }\n\n /**\n * Extracts the path segments from a given route string.\n *\n * @param route - The route string from which to extract segments.\n * @returns An array of path segments.\n */\n private getPathSegments(route: string): string[] {\n return route.split('/').filter(Boolean);\n }\n\n /**\n * Recursively traverses the route tree from a given node, attempting to match the remaining route segments.\n * If the node is a leaf node (no more segments to match) and contains metadata, the node is yielded.\n *\n * This function prioritizes exact segment matches first, followed by wildcard matches (`*`),\n * and finally deep wildcard matches (`**`) that consume all segments.\n *\n * @param segments - The array of route path segments to match against the route tree.\n * @param node - The current node in the route tree to start traversal from. Defaults to the root node.\n * @param currentIndex - The index of the segment in `remainingSegments` currently being matched.\n * Defaults to `0` (the first segment).\n *\n * @returns The node that best matches the remaining segments or `undefined` if no match is found.\n */\n private traverseBySegments(\n segments: string[],\n node = this.root,\n currentIndex = 0,\n ): RouteTreeNode<AdditionalMetadata> | undefined {\n if (currentIndex >= segments.length) {\n return node.metadata ? node : node.children.get('**');\n }\n\n if (!node.children.size) {\n return undefined;\n }\n\n const segment = segments[currentIndex];\n\n // 1. Attempt exact match with the current segment.\n const exactMatch = node.children.get(segment);\n if (exactMatch) {\n const match = this.traverseBySegments(segments, exactMatch, currentIndex + 1);\n if (match) {\n return match;\n }\n }\n\n // 2. Attempt wildcard match ('*').\n const wildcardMatch = node.children.get('*');\n if (wildcardMatch) {\n const match = this.traverseBySegments(segments, wildcardMatch, currentIndex + 1);\n if (match) {\n return match;\n }\n }\n\n // 3. Attempt double wildcard match ('**').\n return node.children.get('**');\n }\n\n /**\n * Creates an empty route tree node.\n * This helper function is used during the tree construction.\n *\n * @returns A new, empty route tree node.\n */\n private createEmptyRouteTreeNode(): RouteTreeNode<AdditionalMetadata> {\n return {\n children: new Map(),\n };\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 { APP_BASE_HREF, PlatformLocation } from '@angular/common';\nimport {\n ApplicationRef,\n Compiler,\n EnvironmentInjector,\n Injector,\n createEnvironmentInjector,\n runInInjectionContext,\n ɵConsole,\n ɵENABLE_ROOT_COMPONENT_BOOTSTRAP,\n} from '@angular/core';\nimport { INITIAL_CONFIG, platformServer } from '@angular/platform-server';\nimport {\n Route as AngularRoute,\n Router,\n ɵloadChildren as loadChildrenHelper,\n} from '@angular/router';\nimport { ServerAssets } from '../assets';\nimport { Console } from '../console';\nimport { AngularAppManifest, getAngularAppManifest } from '../manifest';\nimport { AngularBootstrap, isNgModule } from '../utils/ng';\nimport { promiseWithAbort } from '../utils/promise';\nimport { VALID_REDIRECT_RESPONSE_CODES, isValidRedirectResponseCode } from '../utils/redirect';\nimport { addTrailingSlash, joinUrlParts, stripLeadingSlash } from '../utils/url';\nimport {\n PrerenderFallback,\n RenderMode,\n SERVER_ROUTES_CONFIG,\n ServerRoute,\n ServerRoutesConfig,\n} from './route-config';\nimport { RouteTree, RouteTreeNodeMetadata } from './route-tree';\n\ninterface Route extends AngularRoute {\n ɵentryName?: string;\n}\n\n/**\n * The maximum number of module preload link elements that should be added for\n * initial scripts.\n */\nconst MODULE_PRELOAD_MAX = 10;\n\n/**\n * Regular expression to match a catch-all route pattern in a URL path,\n * specifically one that ends with '/**'.\n */\nconst CATCH_ALL_REGEXP = /\\/(\\*\\*)$/;\n\n/**\n * Regular expression to match segments preceded by a colon in a string.\n */\nconst URL_PARAMETER_REGEXP = /(?<!\\\\):([^/]+)/g;\n\n/**\n * Additional metadata for a server configuration route tree.\n */\ntype ServerConfigRouteTreeAdditionalMetadata = Partial<ServerRoute> & {\n /** Indicates if the route has been matched with the Angular router routes. */\n presentInClientRouter?: boolean;\n};\n\n/**\n * Metadata for a server configuration route tree node.\n */\ntype ServerConfigRouteTreeNodeMetadata = RouteTreeNodeMetadata &\n ServerConfigRouteTreeAdditionalMetadata;\n\n/**\n * Result of extracting routes from an Angular application.\n */\ninterface AngularRouterConfigResult {\n /**\n * The base URL for the application.\n * This is the base href that is used for resolving relative paths within the application.\n */\n baseHref: string;\n\n /**\n * An array of `RouteTreeNodeMetadata` objects representing the application's routes.\n *\n * Each `RouteTreeNodeMetadata` contains details about a specific route, such as its path and any\n * associated redirection targets. This array is asynchronously generated and\n * provides information on how routes are structured and resolved.\n */\n routes: RouteTreeNodeMetadata[];\n\n /**\n * Optional configuration for server routes.\n *\n * This property allows you to specify an array of server routes for configuration.\n * If not provided, the default configuration or behavior will be used.\n */\n serverRoutesConfig?: ServerRoute[] | null;\n\n /**\n * A list of errors encountered during the route extraction process.\n */\n errors: string[];\n\n /**\n * The specified route for the app-shell, if configured.\n */\n appShellRoute?: string;\n}\n\ntype EntryPointToBrowserMapping = AngularAppManifest['entryPointToBrowserMapping'];\n\n/**\n * Handles a single route within the route tree and yields metadata or errors.\n *\n * @param options - Configuration options for handling the route.\n * @returns An async iterable iterator yielding `RouteTreeNodeMetadata` or an error object.\n */\nasync function* handleRoute(options: {\n metadata: ServerConfigRouteTreeNodeMetadata;\n currentRoutePath: string;\n route: Route;\n compiler: Compiler;\n parentInjector: Injector;\n serverConfigRouteTree?: RouteTree<ServerConfigRouteTreeAdditionalMetadata>;\n invokeGetPrerenderParams: boolean;\n includePrerenderFallbackRoutes: boolean;\n entryPointToBrowserMapping?: EntryPointToBrowserMapping;\n}): AsyncIterableIterator<RouteTreeNodeMetadata | { error: string }> {\n try {\n const {\n metadata,\n currentRoutePath,\n route,\n compiler,\n parentInjector,\n serverConfigRouteTree,\n entryPointToBrowserMapping,\n invokeGetPrerenderParams,\n includePrerenderFallbackRoutes,\n } = options;\n\n const { redirectTo, loadChildren, loadComponent, children, ɵentryName } = route;\n if (ɵentryName && loadComponent) {\n appendPreloadToMetadata(ɵentryName, entryPointToBrowserMapping, metadata);\n }\n\n if (metadata.renderMode === RenderMode.Prerender) {\n yield* handleSSGRoute(\n serverConfigRouteTree,\n typeof redirectTo === 'string' ? redirectTo : undefined,\n metadata,\n parentInjector,\n invokeGetPrerenderParams,\n includePrerenderFallbackRoutes,\n );\n } else if (redirectTo !== undefined) {\n if (metadata.status && !isValidRedirectResponseCode(metadata.status)) {\n yield {\n error:\n `The '${metadata.status}' status code is not a valid redirect response code. ` +\n `Please use one of the following redirect response codes: ${[...VALID_REDIRECT_RESPONSE_CODES.values()].join(', ')}.`,\n };\n } else if (typeof redirectTo === 'string') {\n yield {\n ...metadata,\n redirectTo: resolveRedirectTo(metadata.route, redirectTo),\n };\n } else {\n yield metadata;\n }\n } else {\n yield metadata;\n }\n\n // Recursively process child routes\n if (children?.length) {\n yield* traverseRoutesConfig({\n ...options,\n routes: children,\n parentRoute: currentRoutePath,\n parentPreloads: metadata.preload,\n });\n }\n\n // Load and process lazy-loaded child routes\n if (loadChildren) {\n if (ɵentryName) {\n appendPreloadToMetadata(ɵentryName, entryPointToBrowserMapping, metadata);\n }\n\n const routeInjector = route.providers\n ? createEnvironmentInjector(\n route.providers,\n parentInjector.get(EnvironmentInjector),\n `Route: ${route.path}`,\n )\n : parentInjector;\n\n const loadedChildRoutes = await loadChildrenHelper(route, compiler, routeInjector);\n if (loadedChildRoutes) {\n const { routes: childRoutes, injector = routeInjector } = loadedChildRoutes;\n yield* traverseRoutesConfig({\n ...options,\n routes: childRoutes,\n parentInjector: injector,\n parentRoute: currentRoutePath,\n parentPreloads: metadata.preload,\n });\n }\n }\n } catch (error) {\n yield {\n error: `Error in handleRoute for '${options.currentRoutePath}': ${(error as Error).message}`,\n };\n }\n}\n\n/**\n * Traverses an array of route configurations to generate route tree node metadata.\n *\n * This function processes each route and its children, handling redirects, SSG (Static Site Generation) settings,\n * and lazy-loaded routes. It yields route metadata for each route and its potential variants.\n *\n * @param options - The configuration options for traversing routes.\n * @returns An async iterable iterator yielding either route tree node metadata or an error object with an error message.\n */\nasync function* traverseRoutesConfig(options: {\n routes: Route[];\n compiler: Compiler;\n parentInjector: Injector;\n parentRoute: string;\n serverConfigRouteTree?: RouteTree<ServerConfigRouteTreeAdditionalMetadata>;\n invokeGetPrerenderParams: boolean;\n includePrerenderFallbackRoutes: boolean;\n entryPointToBrowserMapping?: EntryPointToBrowserMapping;\n parentPreloads?: readonly string[];\n}): AsyncIterableIterator<RouteTreeNodeMetadata | { error: string }> {\n const { routes: routeConfigs, parentPreloads, parentRoute, serverConfigRouteTree } = options;\n\n for (const route of routeConfigs) {\n const { matcher, path = matcher ? '**' : '' } = route;\n const currentRoutePath = joinUrlParts(parentRoute, path);\n\n if (matcher && serverConfigRouteTree) {\n const matches: (RouteTreeNodeMetadata & ServerConfigRouteTreeAdditionalMetadata)[] = [];\n for (const matchedMetaData of serverConfigRouteTree.traverse()) {\n if (matchedMetaData.route.startsWith(currentRoutePath)) {\n matches.push(matchedMetaData);\n }\n }\n\n if (!matches.length) {\n const matchedMetaData = serverConfigRouteTree.match(currentRoutePath);\n if (matchedMetaData) {\n matches.push(matchedMetaData);\n }\n }\n\n for (const matchedMetaData of matches) {\n matchedMetaData.presentInClientRouter = true;\n if (matchedMetaData.renderMode === RenderMode.Prerender) {\n yield {\n error:\n `The route '${stripLeadingSlash(currentRoutePath)}' is set for prerendering but has a defined matcher. ` +\n `Routes with matchers cannot use prerendering. Please specify a different 'renderMode'.`,\n };\n continue;\n }\n\n yield* handleRoute({\n ...options,\n currentRoutePath,\n route,\n metadata: {\n ...matchedMetaData,\n preload: parentPreloads,\n route: matchedMetaData.route,\n presentInClientRouter: undefined,\n },\n });\n }\n\n if (!matches.length) {\n yield {\n error:\n `The route '${stripLeadingSlash(currentRoutePath)}' has a defined matcher but does not ` +\n 'match any route in the server routing configuration. Please ensure this route is added to the server routing configuration.',\n };\n }\n\n continue;\n }\n\n let matchedMetaData: ServerConfigRouteTreeNodeMetadata | undefined;\n if (serverConfigRouteTree) {\n matchedMetaData = serverConfigRouteTree.match(currentRoutePath);\n if (!matchedMetaData) {\n yield {\n error:\n `The '${stripLeadingSlash(currentRoutePath)}' route does not match any route defined in the server routing configuration. ` +\n 'Please ensure this route is added to the server routing configuration.',\n };\n continue;\n }\n\n matchedMetaData.presentInClientRouter = true;\n }\n\n yield* handleRoute({\n ...options,\n metadata: {\n renderMode: RenderMode.Prerender,\n ...matchedMetaData,\n preload: parentPreloads,\n // Match Angular router behavior\n // ['one', 'two', ''] -> 'one/two/'\n // ['one', 'two', 'three'] -> 'one/two/three'\n route: path === '' ? addTrailingSlash(currentRoutePath) : currentRoutePath,\n presentInClientRouter: undefined,\n },\n currentRoutePath,\n route,\n });\n }\n}\n\n/**\n * Appends preload information to the metadata object based on the specified entry-point and chunk mappings.\n *\n * This function extracts preload data for a given entry-point from the provided chunk mappings. It adds the\n * corresponding browser bundles to the metadata's preload list, ensuring no duplicates and limiting the total\n * preloads to a predefined maximum.\n */\nfunction appendPreloadToMetadata(\n entryName: string,\n entryPointToBrowserMapping: EntryPointToBrowserMapping,\n metadata: ServerConfigRouteTreeNodeMetadata,\n): void {\n const existingPreloads = metadata.preload ?? [];\n if (!entryPointToBrowserMapping || existingPreloads.length >= MODULE_PRELOAD_MAX) {\n return;\n }\n\n const preload = entryPointToBrowserMapping[entryName];\n if (!preload?.length) {\n return;\n }\n\n // Merge existing preloads with new ones, ensuring uniqueness and limiting the total to the maximum allowed.\n const combinedPreloads: Set<string> = new Set(existingPreloads);\n for (const href of preload) {\n combinedPreloads.add(href);\n if (combinedPreloads.size === MODULE_PRELOAD_MAX) {\n break;\n }\n }\n\n metadata.preload = Array.from(combinedPreloads);\n}\n\n/**\n * Handles SSG (Static Site Generation) routes by invoking `getPrerenderParams` and yielding\n * all parameterized paths, returning any errors encountered.\n *\n * @param serverConfigRouteTree - The tree representing the server's routing setup.\n * @param redirectTo - Optional path to redirect to, if specified.\n * @param metadata - The metadata associated with the route tree node.\n * @param parentInjector - The dependency injection container for the parent route.\n * @param invokeGetPrerenderParams - A flag indicating whether to invoke the `getPrerenderParams` function.\n * @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result.\n * @returns An async iterable iterator that yields route tree node metadata for each SSG path or errors.\n */\nasync function* handleSSGRoute(\n serverConfigRouteTree: RouteTree<ServerConfigRouteTreeAdditionalMetadata> | undefined,\n redirectTo: string | undefined,\n metadata: ServerConfigRouteTreeNodeMetadata,\n parentInjector: Injector,\n invokeGetPrerenderParams: boolean,\n includePrerenderFallbackRoutes: boolean,\n): AsyncIterableIterator<RouteTreeNodeMetadata | { error: string }> {\n if (metadata.renderMode !== RenderMode.Prerender) {\n throw new Error(\n `'handleSSGRoute' was called for a route which rendering mode is not prerender.`,\n );\n }\n\n const { route: currentRoutePath, fallback, ...meta } = metadata;\n const getPrerenderParams = 'getPrerenderParams' in meta ? meta.getPrerenderParams : undefined;\n\n if ('getPrerenderParams' in meta) {\n delete meta['getPrerenderParams'];\n }\n\n if (redirectTo !== undefined) {\n meta.redirectTo = resolveRedirectTo(currentRoutePath, redirectTo);\n }\n\n const isCatchAllRoute = CATCH_ALL_REGEXP.test(currentRoutePath);\n if (\n (isCatchAllRoute && !getPrerenderParams) ||\n (!isCatchAllRoute && !URL_PARAMETER_REGEXP.test(currentRoutePath))\n ) {\n // Route has no parameters\n yield {\n ...meta,\n route: currentRoutePath,\n };\n\n return;\n }\n\n if (invokeGetPrerenderParams) {\n if (!getPrerenderParams) {\n yield {\n error:\n `The '${stripLeadingSlash(currentRoutePath)}' route uses prerendering and includes parameters, but 'getPrerenderParams' ` +\n `is missing. Please define 'getPrerenderParams' function for this route in your server routing configuration ` +\n `or specify a different 'renderMode'.`,\n };\n\n return;\n }\n\n if (serverConfigRouteTree) {\n // Automatically resolve dynamic parameters for nested routes.\n const catchAllRoutePath = isCatchAllRoute\n ? currentRoutePath\n : joinUrlParts(currentRoutePath, '**');\n const match = serverConfigRouteTree.match(catchAllRoutePath);\n if (match && match.renderMode === RenderMode.Prerender && !('getPrerenderParams' in match)) {\n serverConfigRouteTree.insert(catchAllRoutePath, {\n ...match,\n presentInClientRouter: true,\n getPrerenderParams,\n });\n }\n }\n\n const parameters = await runInInjectionContext(parentInjector, () => getPrerenderParams());\n try {\n for (const params of parameters) {\n const replacer = handlePrerenderParamsReplacement(params, currentRoutePath);\n const routeWithResolvedParams = currentRoutePath\n .replace(URL_PARAMETER_REGEXP, replacer)\n .replace(CATCH_ALL_REGEXP, replacer);\n\n yield {\n ...meta,\n route: routeWithResolvedParams,\n redirectTo:\n redirectTo === undefined\n ? undefined\n : resolveRedirectTo(routeWithResolvedParams, redirectTo),\n };\n }\n } catch (error) {\n yield { error: `${(error as Error).message}` };\n\n return;\n }\n }\n\n // Handle fallback render modes\n if (\n includePrerenderFallbackRoutes &&\n (fallback !== PrerenderFallback.None || !invokeGetPrerenderParams)\n ) {\n yield {\n ...meta,\n route: currentRoutePath,\n renderMode: fallback === PrerenderFallback.Client ? RenderMode.Client : RenderMode.Server,\n };\n }\n}\n\n/**\n * Creates a replacer function used for substituting parameter placeholders in a route path\n * with their corresponding values provided in the `params` object.\n *\n * @param params - An object mapping parameter names to their string values.\n * @param currentRoutePath - The current route path, used for constructing error messages.\n * @returns A function that replaces a matched parameter placeholder (e.g., ':id') with its corresponding value.\n */\nfunction handlePrerenderParamsReplacement(\n params: Record<string, string>,\n currentRoutePath: string,\n): (substring: string, ...args: unknown[]) => string {\n return (match) => {\n const parameterName = match.slice(1);\n const value = params[parameterName];\n if (typeof value !== 'string') {\n throw new Error(\n `The 'getPrerenderParams' function defined for the '${stripLeadingSlash(currentRoutePath)}' route ` +\n `returned a non-string value for parameter '${parameterName}'. ` +\n `Please make sure the 'getPrerenderParams' function returns values for all parameters ` +\n 'specified in this route.',\n );\n }\n\n return parameterName === '**' ? `/${value}` : value;\n };\n}\n\n/**\n * Resolves the `redirectTo` property for a given route.\n *\n * This function processes the `redirectTo` property to ensure that it correctly\n * resolves relative to the current route path. If `redirectTo` is an absolute path,\n * it is returned as is. If it is a relative path, it is resolved based on the current route path.\n *\n * @param routePath - The current route path.\n * @param redirectTo - The target path for redirection.\n * @returns The resolved redirect path as a string.\n */\nfunction resolveRedirectTo(routePath: string, redirectTo: string): string {\n if (redirectTo[0] === '/') {\n // If the redirectTo path is absolute, return it as is.\n return redirectTo;\n }\n\n // Resolve relative redirectTo based on the current route path.\n const segments = routePath.replace(URL_PARAMETER_REGEXP, '*').split('/');\n segments.pop(); // Remove the last segment to make it relative.\n\n return joinUrlParts(...segments, redirectTo);\n}\n\n/**\n * Builds a server configuration route tree from the given server routes configuration.\n *\n * @param serverRoutesConfig - The server routes to be used for configuration.\n\n * @returns An object containing:\n * - `serverConfigRouteTree`: A populated `RouteTree` instance, which organizes the server routes\n * along with their additional metadata.\n * - `errors`: An array of strings that list any errors encountered during the route tree construction\n * process, such as invalid paths.\n */\nfunction buildServerConfigRouteTree({ routes, appShellRoute }: ServerRoutesConfig): {\n errors: string[];\n serverConfigRouteTree: RouteTree<ServerConfigRouteTreeAdditionalMetadata>;\n} {\n const serverRoutes: ServerRoute[] = [...routes];\n if (appShellRoute !== undefined) {\n serverRoutes.unshift({\n path: appShellRoute,\n renderMode: RenderMode.Prerender,\n });\n }\n\n const serverConfigRouteTree = new RouteTree<ServerConfigRouteTreeAdditionalMetadata>();\n const errors: string[] = [];\n\n for (const { path, ...metadata } of serverRoutes) {\n if (path[0] === '/') {\n errors.push(`Invalid '${path}' route configuration: the path cannot start with a slash.`);\n\n continue;\n }\n\n if ('getPrerenderParams' in metadata && (path.includes('/*/') || path.endsWith('/*'))) {\n errors.push(\n `Invalid '${path}' route configuration: 'getPrerenderParams' cannot be used with a '*' route.`,\n );\n continue;\n }\n\n serverConfigRouteTree.insert(path, metadata);\n }\n\n return { serverConfigRouteTree, errors };\n}\n\n/**\n * Retrieves routes from the given Angular application.\n *\n * This function initializes an Angular platform, bootstraps the application or module,\n * and retrieves routes from the Angular router configuration. It handles both module-based\n * and function-based bootstrapping. It yields the resulting routes as `RouteTreeNodeMetadata` objects or errors.\n *\n * @param bootstrap - A function that returns a promise resolving to an `ApplicationRef` or an Angular module to bootstrap.\n * @param document - The initial HTML document used for server-side rendering.\n * This document is necessary to render the application on the server.\n * @param url - The URL for server-side rendering. The URL is used to configure `ServerPlatformLocation`. This configuration is crucial\n * for ensuring that API requests for relative paths succeed, which is essential for accurate route extraction.\n * @param invokeGetPrerenderParams - A boolean flag indicating whether to invoke `getPrerenderParams` for parameterized SSG routes\n * to handle prerendering paths. Defaults to `false`.\n * @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result. Defaults to `true`.\n * @param entryPointToBrowserMapping - Maps the entry-point name to the associated JavaScript browser bundles.\n *\n * @returns A promise that resolves to an object of type `AngularRouterConfigResult` or errors.\n */\nexport async function getRoutesFromAngularRouterConfig(\n bootstrap: AngularBootstrap,\n document: string,\n url: URL,\n invokeGetPrerenderParams = false,\n includePrerenderFallbackRoutes = true,\n entryPointToBrowserMapping: EntryPointToBrowserMapping | undefined = undefined,\n): Promise<AngularRouterConfigResult> {\n const { protocol, host } = url;\n\n // Create and initialize the Angular platform for server-side rendering.\n const platformRef = platformServer([\n {\n provide: INITIAL_CONFIG,\n useValue: { document, url: `${protocol}//${host}/` },\n },\n {\n // An Angular Console Provider that does not print a set of predefined logs.\n provide: ɵConsole,\n // Using `useClass` would necessitate decorating `Console` with `@Injectable`,\n // which would require switching from `ts_library` to `ng_module`. This change\n // would also necessitate various patches of `@angular/bazel` to support ESM.\n useFactory: () => new Console(),\n },\n {\n provide: ɵENABLE_ROOT_COMPONENT_BOOTSTRAP,\n useValue: false,\n },\n ]);\n\n try {\n let applicationRef: ApplicationRef;\n\n if (isNgModule(bootstrap)) {\n const moduleRef = await platformRef.bootstrapModule(bootstrap);\n applicationRef = moduleRef.injector.get(ApplicationRef);\n } else {\n applicationRef = await bootstrap({ platformRef });\n }\n\n const injector = applicationRef.injector;\n const router = injector.get(Router);\n\n // Workaround to unblock navigation when `withEnabledBlockingInitialNavigation()` is used.\n // This is necessary because route extraction disables component bootstrapping.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (router as any).navigationTransitions.afterPreactivation()?.next?.();\n\n // Wait until the application is stable.\n await applicationRef.whenStable();\n\n const errors: string[] = [];\n\n const rawBaseHref =\n injector.get(APP_BASE_HREF, null, { optional: true }) ??\n injector.get(PlatformLocation).getBaseHrefFromDOM();\n const { pathname: baseHref } = new URL(rawBaseHref, 'http://localhost');\n\n const compiler = injector.get(Compiler);\n const serverRoutesConfig = injector.get(SERVER_ROUTES_CONFIG, null, { optional: true });\n let serverConfigRouteTree: RouteTree<ServerConfigRouteTreeAdditionalMetadata> | undefined;\n\n if (serverRoutesConfig) {\n const result = buildServerConfigRouteTree(serverRoutesConfig);\n serverConfigRouteTree = result.serverConfigRouteTree;\n errors.push(...result.errors);\n }\n\n if (errors.length) {\n return {\n baseHref,\n routes: [],\n errors,\n };\n }\n\n const routesResults: RouteTreeNodeMetadata[] = [];\n if (router.config.length) {\n // Retrieve all routes from the Angular router configuration.\n const traverseRoutes = traverseRoutesConfig({\n routes: router.config,\n compiler,\n parentInjector: injector,\n parentRoute: '',\n serverConfigRouteTree,\n invokeGetPrerenderParams,\n includePrerenderFallbackRoutes,\n entryPointToBrowserMapping,\n });\n\n const seenRoutes: Set<string> = new Set();\n for await (const routeMetadata of traverseRoutes) {\n if ('error' in routeMetadata) {\n errors.push(routeMetadata.error);\n continue;\n }\n\n // If a result already exists for the exact same route, subsequent matches should be ignored.\n // This aligns with Angular's app router behavior, which prioritizes the first route.\n const routePath = routeMetadata.route;\n if (!seenRoutes.has(routePath)) {\n routesResults.push(routeMetadata);\n seenRoutes.add(routePath);\n }\n }\n\n // This timeout is necessary to prevent 'adev' from hanging in production builds.\n // The exact cause is unclear, but removing it leads to the issue.\n await new Promise((resolve) => setTimeout(resolve, 0));\n\n if (serverConfigRouteTree) {\n for (const { route, presentInClientRouter } of serverConfigRouteTree.traverse()) {\n if (presentInClientRouter || route.endsWith('/**')) {\n // Skip if matched or it's the catch-all route.\n continue;\n }\n\n errors.push(\n `The '${stripLeadingSlash(route)}' server route does not match any routes defined in the Angular ` +\n `routing configuration (typically provided as a part of the 'provideRouter' call). ` +\n 'Please make sure that the mentioned server route is present in the Angular routing configuration.',\n );\n }\n }\n } else {\n const rootRouteMetadata = serverConfigRouteTree?.match('') ?? {\n route: '',\n renderMode: RenderMode.Prerender,\n };\n\n routesResults.push({\n ...rootRouteMetadata,\n // Matched route might be `/*` or `/**`, which would make Angular serve all routes rather than just `/`.\n // So we limit to just `/` for the empty app router case.\n route: '',\n });\n }\n\n return {\n baseHref,\n routes: routesResults,\n errors,\n appShellRoute: serverRoutesConfig?.appShellRoute,\n };\n } finally {\n platformRef.destroy();\n }\n}\n\n/**\n * Asynchronously extracts routes from the Angular application configuration\n * and creates a `RouteTree` to manage server-side routing.\n *\n * @param options - An object containing the following options:\n * - `url`: The URL for server-side rendering. The URL is used to configure `ServerPlatformLocation`. This configuration is crucial\n * for ensuring that API requests for relative paths succeed, which is essential for accurate route extraction.\n * See:\n * - https://github.com/angular/angular/blob/d608b857c689d17a7ffa33bbb510301014d24a17/packages/platform-server/src/location.ts#L51\n * - https://github.com/angular/angular/blob/6882cc7d9eed26d3caeedca027452367ba25f2b9/packages/platform-server/src/http.ts#L44\n * - `manifest`: An optional `AngularAppManifest` that contains the application's routing and configuration details.\n * If not provided, the default manifest is retrieved using `getAngularAppManifest()`.\n * - `invokeGetPrerenderParams`: A boolean flag indicating whether to invoke `getPrerenderParams` for parameterized SSG routes\n * to handle prerendering paths. Defaults to `false`.\n * - `includePrerenderFallbackRoutes`: A flag indicating whether to include fallback routes in the result. Defaults to `true`.\n * - `signal`: An optional `AbortSignal` that can be used to abort the operation.\n *\n * @returns A promise that resolves to an object containing:\n * - `routeTree`: A populated `RouteTree` containing all extracted routes from the Angular application.\n * - `appShellRoute`: The specified route for the app-shell, if configured.\n * - `errors`: An array of strings representing any errors encountered during the route extraction process.\n */\nexport function extractRoutesAndCreateRouteTree(options: {\n url: URL;\n manifest?: AngularAppManifest;\n invokeGetPrerenderParams?: boolean;\n includePrerenderFallbackRoutes?: boolean;\n signal?: AbortSignal;\n}): Promise<{ routeTree: RouteTree; appShellRoute?: string; errors: string[] }> {\n const {\n url,\n manifest = getAngularAppManifest(),\n invokeGetPrerenderParams = false,\n includePrerenderFallbackRoutes = true,\n signal,\n } = options;\n\n async function extract(): Promise<{\n appShellRoute: string | undefined;\n routeTree: RouteTree<{}>;\n errors: string[];\n }> {\n const routeTree = new RouteTree();\n const document = await new ServerAssets(manifest).getIndexServerHtml().text();\n const bootstrap = await manifest.bootstrap();\n const { baseHref, appShellRoute, routes, errors } = await getRoutesFromAngularRouterConfig(\n bootstrap,\n document,\n url,\n invokeGetPrerenderParams,\n includePrerenderFallbackRoutes,\n manifest.entryPointToBrowserMapping,\n );\n\n for (const { route, ...metadata } of routes) {\n if (metadata.redirectTo !== undefined) {\n metadata.redirectTo = joinUrlParts(baseHref, metadata.redirectTo);\n }\n\n // Remove undefined fields\n // Helps avoid unnecessary test updates\n for (const [key, value] of Object.entries(metadata)) {\n if (value === undefined) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delete (metadata as any)[key];\n }\n }\n\n const fullRoute = joinUrlParts(baseHref, route);\n routeTree.insert(fullRoute, metadata);\n }\n\n return {\n appShellRoute,\n routeTree,\n errors,\n };\n }\n\n return signal ? promiseWithAbort(extract(), signal, 'Routes extraction') : extract();\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\n/**\n * Defines a handler function type for transforming HTML content.\n * This function receives an object with the HTML to be processed.\n *\n * @param ctx - An object containing the URL and HTML content to be transformed.\n * @returns The transformed HTML as a string or a promise that resolves to the transformed HTML.\n */\ntype HtmlTransformHandler = (ctx: { url: URL; html: string }) => string | Promise<string>;\n\n/**\n * Defines the names of available hooks for registering and triggering custom logic within the application.\n */\ntype HookName = keyof HooksMapping;\n\n/**\n * Mapping of hook names to their corresponding handler types.\n */\ninterface HooksMapping {\n 'html:transform:pre': HtmlTransformHandler;\n}\n\n/**\n * Manages a collection of hooks and provides methods to register and execute them.\n * Hooks are functions that can be invoked with specific arguments to allow modifications or enhancements.\n */\nexport class Hooks {\n /**\n * A map of hook names to arrays of hook functions.\n * Each hook name can have multiple associated functions, which are executed in sequence.\n */\n private readonly store = new Map<HookName, Function[]>();\n\n /**\n * Executes all hooks associated with the specified name, passing the given argument to each hook function.\n * The hooks are invoked sequentially, and the argument may be modified by each hook.\n *\n * @template Hook - The type of the hook name. It should be one of the keys of `HooksMapping`.\n * @param name - The name of the hook whose functions will be executed.\n * @param context - The input value to be passed to each hook function. The value is mutated by each hook function.\n * @returns A promise that resolves once all hook functions have been executed.\n *\n * @example\n * ```typescript\n * const hooks = new Hooks();\n * hooks.on('html:transform:pre', async (ctx) => {\n * ctx.html = ctx.html.replace(/foo/g, 'bar');\n * return ctx.html;\n * });\n * const result = await hooks.run('html:transform:pre', { html: '<div>foo</div>' });\n * console.log(result); // '<div>bar</div>'\n * ```\n * @internal\n */\n async run<Hook extends keyof HooksMapping>(\n name: Hook,\n context: Parameters<HooksMapping[Hook]>[0],\n ): Promise<Awaited<ReturnType<HooksMapping[Hook]>>> {\n const hooks = this.store.get(name);\n switch (name) {\n case 'html:transform:pre': {\n if (!hooks) {\n return context.html as Awaited<ReturnType<HooksMapping[Hook]>>;\n }\n\n const ctx = { ...context };\n for (const hook of hooks) {\n ctx.html = await hook(ctx);\n }\n\n return ctx.html as Awaited<ReturnType<HooksMapping[Hook]>>;\n }\n default:\n throw new Error(`Running hook \"${name}\" is not supported.`);\n }\n }\n\n /**\n * Registers a new hook function under the specified hook name.\n * This function should be a function that takes an argument of type `T` and returns a `string` or `Promise<string>`.\n *\n * @template Hook - The type of the hook name. It should be one of the keys of `HooksMapping`.\n * @param name - The name of the hook under which the function will be registered.\n * @param handler - A function to be executed when the hook is triggered. The handler will be called with an argument\n * that may be modified by the hook functions.\n *\n * @remarks\n * - If there are existing handlers registered under the given hook name, the new handler will be added to the list.\n * - If no handlers are registered under the given hook name, a new list will be created with the handler as its first element.\n *\n * @example\n * ```typescript\n * hooks.on('html:transform:pre', async (ctx) => {\n * return ctx.html.replace(/foo/g, 'bar');\n * });\n * ```\n */\n on<Hook extends HookName>(name: Hook, handler: HooksMapping[Hook]): void {\n const hooks = this.store.get(name);\n if (hooks) {\n hooks.push(handler);\n } else {\n this.store.set(name, [handler]);\n }\n }\n\n /**\n * Checks if there are any hooks registered under the specified name.\n *\n * @param name - The name of the hook to check.\n * @returns `true` if there are hooks registered under the specified name, otherwise `false`.\n */\n has(name: HookName): boolean {\n return !!this.store.get(name)?.length;\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 { AngularAppManifest } from '../manifest';\nimport { stripIndexHtmlFromURL, stripMatrixParams } from '../utils/url';\nimport { extractRoutesAndCreateRouteTree } from './ng-routes';\nimport { RouteTree, RouteTreeNodeMetadata } from './route-tree';\n\n/**\n * Manages the application's server routing logic by building and maintaining a route tree.\n *\n * This class is responsible for constructing the route tree from the Angular application\n * configuration and using it to match incoming requests to the appropriate routes.\n */\nexport class ServerRouter {\n /**\n * Creates an instance of the `ServerRouter`.\n *\n * @param routeTree - An instance of `RouteTree` that holds the routing information.\n * The `RouteTree` is used to match request URLs to the appropriate route metadata.\n */\n private constructor(private readonly routeTree: RouteTree) {}\n\n /**\n * Static property to track the ongoing build promise.\n */\n static #extractionPromise: Promise<ServerRouter> | undefined;\n\n /**\n * Creates or retrieves a `ServerRouter` instance based on the provided manifest and URL.\n *\n * If the manifest contains pre-built routes, a new `ServerRouter` is immediately created.\n * Otherwise, it builds the router by extracting routes from the Angular configuration\n * asynchronously. This method ensures that concurrent builds are prevented by re-using\n * the same promise.\n *\n * @param manifest - An instance of `AngularAppManifest` that contains the route information.\n * @param url - The URL for server-side rendering. The URL is needed to configure `ServerPlatformLocation`.\n * This is necessary to ensure that API requests for relative paths succeed, which is crucial for correct route extraction.\n * [Reference](https://github.com/angular/angular/blob/d608b857c689d17a7ffa33bbb510301014d24a17/packages/platform-server/src/location.ts#L51)\n * @returns A promise resolving to a `ServerRouter` instance.\n */\n static from(manifest: AngularAppManifest, url: URL): Promise<ServerRouter> {\n if (manifest.routes) {\n const routeTree = RouteTree.fromObject(manifest.routes);\n\n return Promise.resolve(new ServerRouter(routeTree));\n }\n\n // Create and store a new promise for the build process.\n // This prevents concurrent builds by re-using the same promise.\n ServerRouter.#extractionPromise ??= extractRoutesAndCreateRouteTree({ url, manifest })\n .then(({ routeTree, errors }) => {\n if (errors.length > 0) {\n throw new Error(\n 'Error(s) occurred while extracting routes:\\n' +\n errors.map((error) => `- ${error}`).join('\\n'),\n );\n }\n\n return new ServerRouter(routeTree);\n })\n .finally(() => {\n ServerRouter.#extractionPromise = undefined;\n });\n\n return ServerRouter.#extractionPromise;\n }\n\n /**\n * Matches a request URL against the route tree to retrieve route metadata.\n *\n * This method strips 'index.html' from the URL if it is present and then attempts\n * to find a match in the route tree. If a match is found, it returns the associated\n * route metadata; otherwise, it returns `undefined`.\n *\n * @param url - The URL to be matched against the route tree.\n * @returns The metadata for the matched route or `undefined` if no match is found.\n */\n match(url: URL): RouteTreeNodeMetadata | undefined {\n // Strip 'index.html' from URL if present.\n // A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.\n let { pathname } = stripIndexHtmlFromURL(url);\n pathname = stripMatrixParams(pathname);\n pathname = decodeURIComponent(pathname);\n\n return this.routeTree.match(pathname);\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\n/**\n * Generates a SHA-256 hash of the provided string.\n *\n * @param data - The input string to be hashed.\n * @returns A promise that resolves to the SHA-256 hash of the input,\n * represented as a hexadecimal string.\n */\nexport async function sha256(data: string): Promise<string> {\n const encodedData = new TextEncoder().encode(data);\n const hashBuffer = await crypto.subtle.digest('SHA-256', encodedData);\n const hashParts: string[] = [];\n\n for (const h of new Uint8Array(hashBuffer)) {\n hashParts.push(h.toString(16).padStart(2, '0'));\n }\n\n return hashParts.join('');\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 Beasties from '../.../third_party/beasties';\n\n/**\n * Pattern used to extract the media query set by Beasties in an `onload` handler.\n */\nconst MEDIA_SET_HANDLER_PATTERN = /^this\\.media=[\"'](.*)[\"'];?$/;\n\n/**\n * Name of the attribute used to save the Beasties media query so it can be re-assigned on load.\n */\nconst CSP_MEDIA_ATTR = 'ngCspMedia';\n\n/**\n * Script that dynamically updates the `media` attribute of `<link>` tags based on a custom attribute (`CSP_MEDIA_ATTR`).\n *\n * NOTE:\n * We do not use `document.querySelectorAll('link').forEach((s) => s.addEventListener('load', ...)`\n * because load events are not always triggered reliably on Chrome.\n * See: https://github.com/angular/angular-cli/issues/26932 and https://crbug.com/1521256\n *\n * The script:\n * - Ensures the event target is a `<link>` tag with the `CSP_MEDIA_ATTR` attribute.\n * - Updates the `media` attribute with the value of `CSP_MEDIA_ATTR` and then removes the attribute.\n * - Removes the event listener when all relevant `<link>` tags have been processed.\n * - Uses event capturing (the `true` parameter) since load events do not bubble up the DOM.\n */\nconst LINK_LOAD_SCRIPT_CONTENT = /* @__PURE__ */ (() => `(() => {\n const CSP_MEDIA_ATTR = '${CSP_MEDIA_ATTR}';\n const documentElement = document.documentElement;\n\n // Listener for load events on link tags.\n const listener = (e) => {\n const target = e.target;\n if (\n !target ||\n target.tagName !== 'LINK' ||\n !target.hasAttribute(CSP_MEDIA_ATTR)\n ) {\n return;\n }\n\n target.media = target.getAttribute(CSP_MEDIA_ATTR);\n target.removeAttribute(CSP_MEDIA_ATTR);\n\n if (!document.head.querySelector(\\`link[\\${CSP_MEDIA_ATTR}]\\`)) {\n documentElement.removeEventListener('load', listener);\n }\n };\n\n documentElement.addEventListener('load', listener, true);\n})();`)();\n\n/** Partial representation of an `HTMLElement`. */\ninterface PartialHTMLElement {\n getAttribute(name: string): string | null;\n setAttribute(name: string, value: string): void;\n hasAttribute(name: string): boolean;\n removeAttribute(name: string): void;\n appendChild(child: PartialHTMLElement): void;\n insertBefore(newNode: PartialHTMLElement, referenceNode?: PartialHTMLElement): void;\n remove(): void;\n name: string;\n textContent: string;\n tagName: string | null;\n children: PartialHTMLElement[];\n next: PartialHTMLElement | null;\n prev: PartialHTMLElement | null;\n}\n\n/** Partial representation of an HTML `Document`. */\ninterface PartialDocument {\n head: PartialHTMLElement;\n createElement(tagName: string): PartialHTMLElement;\n querySelector(selector: string): PartialHTMLElement | null;\n}\n\n/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\n\n// We use Typescript declaration merging because `embedLinkedStylesheet` it's not declared in\n// the `Beasties` types which means that we can't call the `super` implementation.\ninterface BeastiesBase {\n embedLinkedStylesheet(link: PartialHTMLElement, document: PartialDocument): Promise<unknown>;\n}\nclass BeastiesBase extends Beasties {}\n/* eslint-enable @typescript-eslint/no-unsafe-declaration-merging */\n\nexport class InlineCriticalCssProcessor extends BeastiesBase {\n private addedCspScriptsDocuments = new WeakSet<PartialDocument>();\n private documentNonces = new WeakMap<PartialDocument, string | null>();\n\n constructor(\n public override readFile: (path: string) => Promise<string>,\n readonly outputPath?: string,\n ) {\n super({\n logger: {\n // eslint-disable-next-line no-console\n warn: (s: string) => console.warn(s),\n // eslint-disable-next-line no-console\n error: (s: string) => console.error(s),\n info: () => {},\n },\n logLevel: 'warn',\n path: outputPath,\n publicPath: undefined,\n compress: false,\n pruneSource: false,\n reduceInlineStyles: false,\n mergeStylesheets: false,\n // Note: if `preload` changes to anything other than `media`, the logic in\n // `embedLinkedStylesheet` will have to be updated.\n preload: 'media',\n noscriptFallback: true,\n inlineFonts: true,\n });\n }\n\n /**\n * Override of the Beasties `embedLinkedStylesheet` method\n * that makes it work with Angular's CSP APIs.\n */\n override async embedLinkedStylesheet(\n link: PartialHTMLElement,\n document: PartialDocument,\n ): Promise<unknown> {\n if (link.getAttribute('media') === 'print' && link.next?.name === 'noscript') {\n // Workaround for https://github.com/GoogleChromeLabs/critters/issues/64\n // NB: this is only needed for the webpack based builders.\n const media = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);\n if (media) {\n link.removeAttribute('onload');\n link.setAttribute('media', media[1]);\n link?.next?.remove();\n }\n }\n\n const returnValue = await super.embedLinkedStylesheet(link, document);\n const cspNonce = this.findCspNonce(document);\n\n if (cspNonce) {\n const beastiesMedia = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);\n\n if (beastiesMedia) {\n // If there's a Beasties-generated `onload` handler and the file has an Angular CSP nonce,\n // we have to remove the handler, because it's incompatible with CSP. We save the value\n // in a different attribute and we generate a script tag with the nonce that uses\n // `addEventListener` to apply the media query instead.\n link.removeAttribute('onload');\n link.setAttribute(CSP_MEDIA_ATTR, beastiesMedia[1]);\n this.conditionallyInsertCspLoadingScript(document, cspNonce, link);\n }\n\n // Ideally we would hook in at the time Beasties inserts the `style` tags, but there isn't\n // a way of doing that at the moment so we fall back to doing it any time a `link` tag is\n // inserted. We mitigate it by only iterating the direct children of the `<head>` which\n // should be pretty shallow.\n document.head.children.forEach((child) => {\n if (child.tagName === 'style' && !child.hasAttribute('nonce')) {\n child.setAttribute('nonce', cspNonce);\n }\n });\n }\n\n return returnValue;\n }\n\n /**\n * Finds the CSP nonce for a specific document.\n */\n private findCspNonce(document: PartialDocument): string | null {\n if (this.documentNonces.has(document)) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.documentNonces.get(document)!;\n }\n\n // HTML attribute are case-insensitive, but the parser used by Beasties is case-sensitive.\n const nonceElement = document.querySelector('[ngCspNonce], [ngcspnonce]');\n const cspNonce =\n nonceElement?.getAttribute('ngCspNonce') || nonceElement?.getAttribute('ngcspnonce') || null;\n\n this.documentNonces.set(document, cspNonce);\n\n return cspNonce;\n }\n\n /**\n * Inserts the `script` tag that swaps the critical CSS at runtime,\n * if one hasn't been inserted into the document already.\n */\n private conditionallyInsertCspLoadingScript(\n document: PartialDocument,\n nonce: string,\n link: PartialHTMLElement,\n ): void {\n if (this.addedCspScriptsDocuments.has(document)) {\n return;\n }\n\n if (document.head.textContent.includes(LINK_LOAD_SCRIPT_CONTENT)) {\n // Script was already added during the build.\n this.addedCspScriptsDocuments.add(document);\n\n return;\n }\n\n const script = document.createElement('script');\n script.setAttribute('nonce', nonce);\n script.textContent = LINK_LOAD_SCRIPT_CONTENT;\n // Prepend the script to the head since it needs to\n // run as early as possible, before the `link` tags.\n document.head.insertBefore(script, link);\n this.addedCspScriptsDocuments.add(document);\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\n/**\n * Represents a node in the doubly linked list.\n */\ninterface Node<Key, Value> {\n key: Key;\n value: Value;\n prev: Node<Key, Value> | undefined;\n next: Node<Key, Value> | undefined;\n}\n\n/**\n * A Least Recently Used (LRU) cache implementation.\n *\n * This cache stores a fixed number of key-value pairs, and when the cache exceeds its capacity,\n * the least recently accessed items are evicted.\n *\n * @template Key - The type of the cache keys.\n * @template Value - The type of the cache values.\n */\nexport class LRUCache<Key, Value> {\n /**\n * The maximum number of items the cache can hold.\n */\n capacity: number;\n\n /**\n * Internal storage for the cache, mapping keys to their associated nodes in the linked list.\n */\n private readonly cache = new Map<Key, Node<Key, Value>>();\n\n /**\n * Head of the doubly linked list, representing the most recently used item.\n */\n private head: Node<Key, Value> | undefined;\n\n /**\n * Tail of the doubly linked list, representing the least recently used item.\n */\n private tail: Node<Key, Value> | undefined;\n\n /**\n * Creates a new LRUCache instance.\n * @param capacity The maximum number of items the cache can hold.\n */\n constructor(capacity: number) {\n this.capacity = capacity;\n }\n\n /**\n * Gets the value associated with the given key.\n * @param key The key to retrieve the value for.\n * @returns The value associated with the key, or undefined if the key is not found.\n */\n get(key: Key): Value | undefined {\n const node = this.cache.get(key);\n if (node) {\n this.moveToHead(node);\n\n return node.value;\n }\n\n return undefined;\n }\n\n /**\n * Puts a key-value pair into the cache.\n * If the key already exists, the value is updated.\n * If the cache is full, the least recently used item is evicted.\n * @param key The key to insert or update.\n * @param value The value to associate with the key.\n */\n put(key: Key, value: Value): void {\n const cachedNode = this.cache.get(key);\n if (cachedNode) {\n // Update existing node\n cachedNode.value = value;\n this.moveToHead(cachedNode);\n\n return;\n }\n\n // Create a new node\n const newNode: Node<Key, Value> = { key, value, prev: undefined, next: undefined };\n this.cache.set(key, newNode);\n this.addToHead(newNode);\n\n if (this.cache.size > this.capacity) {\n // Evict the LRU item\n const tail = this.removeTail();\n if (tail) {\n this.cache.delete(tail.key);\n }\n }\n }\n\n /**\n * Adds a node to the head of the linked list.\n * @param node The node to add.\n */\n private addToHead(node: Node<Key, Value>): void {\n node.next = this.head;\n node.prev = undefined;\n\n if (this.head) {\n this.head.prev = node;\n }\n\n this.head = node;\n\n if (!this.tail) {\n this.tail = node;\n }\n }\n\n /**\n * Removes a node from the linked list.\n * @param node The node to remove.\n */\n private removeNode(node: Node<Key, Value>): void {\n if (node.prev) {\n node.prev.next = node.next;\n } else {\n this.head = node.next;\n }\n\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n this.tail = node.prev;\n }\n }\n\n /**\n * Moves a node to the head of the linked list.\n * @param node The node to move.\n */\n private moveToHead(node: Node<Key, Value>): void {\n this.removeNode(node);\n this.addToHead(node);\n }\n\n /**\n * Removes the tail node from the linked list.\n * @returns The removed tail node, or undefined if the list is empty.\n */\n private removeTail(): Node<Key, Value> | undefined {\n const node = this.tail;\n if (node) {\n this.removeNode(node);\n }\n\n return node;\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 {\n LOCALE_ID,\n REQUEST,\n REQUEST_CONTEXT,\n RESPONSE_INIT,\n StaticProvider,\n ɵresetCompiledComponents,\n} from '@angular/core';\nimport { ServerAssets } from './assets';\nimport { Hooks } from './hooks';\nimport { getAngularAppManifest } from './manifest';\nimport { RenderMode } from './routes/route-config';\nimport { RouteTreeNodeMetadata } from './routes/route-tree';\nimport { ServerRouter } from './routes/router';\nimport { sha256 } from './utils/crypto';\nimport { InlineCriticalCssProcessor } from './utils/inline-critical-css';\nimport { LRUCache } from './utils/lru-cache';\nimport { AngularBootstrap, renderAngular } from './utils/ng';\nimport { promiseWithAbort } from './utils/promise';\nimport { createRedirectResponse } from './utils/redirect';\nimport { buildPathWithParams, joinUrlParts, stripLeadingSlash } from './utils/url';\n\n/**\n * A set of well-known URLs that are not handled by Angular.\n *\n * These URLs are typically for static assets or endpoints that should\n * bypass the Angular routing and rendering process.\n */\nconst WELL_KNOWN_NON_ANGULAR_URLS: ReadonlySet<string> = new Set<string>([\n '/favicon.ico',\n '/.well-known/appspecific/com.chrome.devtools.json',\n]);\n\n/**\n * Maximum number of critical CSS entries the cache can store.\n * This value determines the capacity of the LRU (Least Recently Used) cache, which stores critical CSS for pages.\n */\nconst MAX_INLINE_CSS_CACHE_ENTRIES = 50;\n\n/**\n * A mapping of `RenderMode` enum values to corresponding string representations.\n *\n * This record is used to map each `RenderMode` to a specific string value that represents\n * the server context. The string values are used internally to differentiate\n * between various rendering strategies when processing routes.\n *\n * - `RenderMode.Prerender` maps to `'ssg'` (Static Site Generation).\n * - `RenderMode.Server` maps to `'ssr'` (Server-Side Rendering).\n * - `RenderMode.Client` maps to an empty string `''` (Client-Side Rendering, no server context needed).\n */\nconst SERVER_CONTEXT_VALUE: Record<RenderMode, string> = {\n [RenderMode.Prerender]: 'ssg',\n [RenderMode.Server]: 'ssr',\n [RenderMode.Client]: '',\n};\n\n/**\n * Options for configuring an `AngularServerApp`.\n */\ninterface AngularServerAppOptions {\n /**\n * Whether to allow rendering of prerendered routes.\n *\n * When enabled, prerendered routes will be served directly. When disabled, they will be\n * rendered on demand.\n *\n * Defaults to `false`.\n */\n allowStaticRouteRender?: boolean;\n\n /**\n * Hooks for extending or modifying server behavior.\n *\n * This allows customization of the server's rendering process and other lifecycle events.\n *\n * If not provided, a new `Hooks` instance is created.\n */\n hooks?: Hooks;\n}\n\n/**\n * Represents a locale-specific Angular server application managed by the server application engine.\n *\n * The `AngularServerApp` class handles server-side rendering and asset management for a specific locale.\n */\nexport class AngularServerApp {\n /**\n * Whether prerendered routes should be rendered on demand or served directly.\n *\n * @see {@link AngularServerAppOptions.allowStaticRouteRender} for more details.\n */\n private readonly allowStaticRouteRender: boolean;\n\n /**\n * Hooks for extending or modifying server behavior.\n *\n * @see {@link AngularServerAppOptions.hooks} for more details.\n */\n readonly hooks: Hooks;\n\n /**\n * Constructs an instance of `AngularServerApp`.\n *\n * @param options Optional configuration options for the server application.\n */\n constructor(private readonly options: Readonly<AngularServerAppOptions> = {}) {\n this.allowStaticRouteRender = this.options.allowStaticRouteRender ?? false;\n this.hooks = options.hooks ?? new Hooks();\n\n if (this.manifest.inlineCriticalCss) {\n this.inlineCriticalCssProcessor = new InlineCriticalCssProcessor((path: string) => {\n const fileName = path.split('/').pop() ?? path;\n\n return this.assets.getServerAsset(fileName).text();\n });\n }\n }\n\n /**\n * The manifest associated with this server application.\n */\n private readonly manifest = getAngularAppManifest();\n\n /**\n * An instance of ServerAsset that handles server-side asset.\n */\n private readonly assets = new ServerAssets(this.manifest);\n\n /**\n * The router instance used for route matching and handling.\n */\n private router: ServerRouter | undefined;\n\n /**\n * The `inlineCriticalCssProcessor` is responsible for handling critical CSS inlining.\n */\n private inlineCriticalCssProcessor: InlineCriticalCssProcessor | undefined;\n\n /**\n * The bootstrap mechanism for the server application.\n */\n private boostrap: AngularBootstrap | undefined;\n\n /**\n * Decorder used to convert a string to a Uint8Array.\n */\n private readonly textDecoder = new TextEncoder();\n\n /**\n * A cache that stores critical CSS to avoid re-processing for every request, improving performance.\n * This cache uses a Least Recently Used (LRU) eviction policy.\n *\n * @see {@link MAX_INLINE_CSS_CACHE_ENTRIES} for the maximum number of entries this cache can hold.\n */\n private readonly criticalCssLRUCache = new LRUCache<\n string,\n { shaOfContentPreInlinedCss: string; contentWithCriticialCSS: Uint8Array<ArrayBufferLike> }\n >(MAX_INLINE_CSS_CACHE_ENTRIES);\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 * @param request - The HTTP request to handle.\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(request: Request, requestContext?: unknown): Promise<Response | null> {\n const url = new URL(request.url);\n if (WELL_KNOWN_NON_ANGULAR_URLS.has(url.pathname)) {\n return null;\n }\n\n this.router ??= await ServerRouter.from(this.manifest, url);\n const matchedRoute = this.router.match(url);\n\n if (!matchedRoute) {\n // Not a known Angular route.\n return null;\n }\n\n const { redirectTo, status, renderMode } = matchedRoute;\n\n if (redirectTo !== undefined) {\n return createRedirectResponse(\n joinUrlParts(\n request.headers.get('X-Forwarded-Prefix') ?? '',\n buildPathWithParams(redirectTo, url.pathname),\n ),\n status,\n );\n }\n\n if (renderMode === RenderMode.Prerender) {\n const response = await this.handleServe(request, matchedRoute);\n if (response) {\n return response;\n }\n }\n\n return promiseWithAbort(\n this.handleRendering(request, matchedRoute, requestContext),\n request.signal,\n `Request for: ${request.url}`,\n );\n }\n\n /**\n * Handles serving a prerendered static asset if available for the matched route.\n *\n * This method only supports `GET` and `HEAD` requests.\n *\n * @param request - The incoming HTTP request for serving a static page.\n * @param matchedRoute - The metadata of the matched route for rendering.\n * @returns A promise that resolves to a `Response` object if the prerendered page is found, or `null`.\n */\n private async handleServe(\n request: Request,\n matchedRoute: RouteTreeNodeMetadata,\n ): Promise<Response | null> {\n const { headers, renderMode } = matchedRoute;\n if (renderMode !== RenderMode.Prerender) {\n return null;\n }\n\n const { method } = request;\n if (method !== 'GET' && method !== 'HEAD') {\n return null;\n }\n\n const assetPath = this.buildServerAssetPathFromRequest(request);\n const {\n manifest: { locale },\n assets,\n } = this;\n\n if (!assets.hasServerAsset(assetPath)) {\n return null;\n }\n\n const { text, hash, size } = assets.getServerAsset(assetPath);\n const etag = `\"${hash}\"`;\n\n return request.headers.get('if-none-match') === etag\n ? new Response(undefined, { status: 304, statusText: 'Not Modified' })\n : new Response(await text(), {\n headers: {\n 'Content-Length': size.toString(),\n 'ETag': etag,\n 'Content-Type': 'text/html;charset=UTF-8',\n ...(locale !== undefined ? { 'Content-Language': locale } : {}),\n ...headers,\n },\n });\n }\n\n /**\n * Handles the server-side rendering process for the given HTTP request.\n * This method matches the request URL to a route and performs rendering if a matching route is found.\n *\n * @param request - The incoming HTTP request to be processed.\n * @param matchedRoute - The metadata of the matched route for rendering.\n * @param requestContext - Optional additional context for rendering, such as request metadata.\n *\n * @returns A promise that resolves to the rendered response, or null if no matching route is found.\n */\n private async handleRendering(\n request: Request,\n matchedRoute: RouteTreeNodeMetadata,\n requestContext?: unknown,\n ): Promise<Response | null> {\n const { renderMode, headers, status, preload } = matchedRoute;\n\n if (!this.allowStaticRouteRender && renderMode === RenderMode.Prerender) {\n return null;\n }\n\n const url = new URL(request.url);\n const platformProviders: StaticProvider[] = [];\n\n const {\n manifest: { bootstrap, locale },\n assets,\n } = this;\n\n // Initialize the response with status and headers if available.\n const responseInit = {\n status,\n headers: new Headers({\n 'Content-Type': 'text/html;charset=UTF-8',\n ...(locale !== undefined ? { 'Content-Language': locale } : {}),\n ...headers,\n }),\n };\n\n if (renderMode === RenderMode.Server) {\n // Configure platform providers for request and response only for SSR.\n platformProviders.push(\n {\n provide: REQUEST,\n useValue: request,\n },\n {\n provide: REQUEST_CONTEXT,\n useValue: requestContext,\n },\n {\n provide: RESPONSE_INIT,\n useValue: responseInit,\n },\n );\n } else if (renderMode === RenderMode.Client) {\n // Serve the client-side rendered version if the route is configured for CSR.\n let html = await this.assets.getServerAsset('index.csr.html').text();\n html = await this.runTransformsOnHtml(html, url, preload);\n\n return new Response(html, responseInit);\n }\n\n if (locale !== undefined) {\n platformProviders.push({\n provide: LOCALE_ID,\n useValue: locale,\n });\n }\n\n this.boostrap ??= await bootstrap();\n let html = await assets.getIndexServerHtml().text();\n html = await this.runTransformsOnHtml(html, url, preload);\n\n const result = await renderAngular(\n html,\n this.boostrap,\n url,\n platformProviders,\n SERVER_CONTEXT_VALUE[renderMode],\n );\n\n if (result.hasNavigationError) {\n return null;\n }\n\n if (result.redirectTo) {\n return createRedirectResponse(result.redirectTo, responseInit.status);\n }\n\n if (renderMode === RenderMode.Prerender) {\n const renderedHtml = await result.content();\n const finalHtml = await this.inlineCriticalCss(renderedHtml, url);\n\n return new Response(finalHtml, responseInit);\n }\n\n // Use a stream to send the response before finishing rendering and inling critical CSS, improving performance via header flushing.\n const stream = new ReadableStream({\n start: async (controller) => {\n const renderedHtml = await result.content();\n const finalHtml = await this.inlineCriticalCssWithCache(renderedHtml, url);\n controller.enqueue(finalHtml);\n controller.close();\n },\n });\n\n return new Response(stream, responseInit);\n }\n\n /**\n * Inlines critical CSS into the given HTML content.\n *\n * @param html The HTML content to process.\n * @param url The URL associated with the request, for logging purposes.\n * @returns A promise that resolves to the HTML with inlined critical CSS.\n */\n private async inlineCriticalCss(html: string, url: URL): Promise<string> {\n const { inlineCriticalCssProcessor } = this;\n\n if (!inlineCriticalCssProcessor) {\n return html;\n }\n\n try {\n return await inlineCriticalCssProcessor.process(html);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(`An error occurred while inlining critical CSS for: ${url}.`, error);\n\n return html;\n }\n }\n\n /**\n * Inlines critical CSS into the given HTML content.\n * This method uses a cache to avoid reprocessing the same HTML content multiple times.\n *\n * @param html The HTML content to process.\n * @param url The URL associated with the request, for logging purposes.\n * @returns A promise that resolves to the HTML with inlined critical CSS.\n */\n private async inlineCriticalCssWithCache(\n html: string,\n url: URL,\n ): Promise<Uint8Array<ArrayBufferLike>> {\n const { inlineCriticalCssProcessor, criticalCssLRUCache, textDecoder } = this;\n\n if (!inlineCriticalCssProcessor) {\n return textDecoder.encode(html);\n }\n\n const cacheKey = url.toString();\n const cached = criticalCssLRUCache.get(cacheKey);\n const shaOfContentPreInlinedCss = await sha256(html);\n if (cached?.shaOfContentPreInlinedCss === shaOfContentPreInlinedCss) {\n return cached.contentWithCriticialCSS;\n }\n\n const processedHtml = await this.inlineCriticalCss(html, url);\n const finalHtml = textDecoder.encode(processedHtml);\n criticalCssLRUCache.put(cacheKey, {\n shaOfContentPreInlinedCss,\n contentWithCriticialCSS: finalHtml,\n });\n\n return finalHtml;\n }\n\n /**\n * Constructs the asset path on the server based on the provided HTTP request.\n *\n * This method processes the incoming request URL to derive a path corresponding\n * to the requested asset. It ensures the path points to the correct file (e.g.,\n * `index.html`) and removes any base href if it is not part of the asset path.\n *\n * @param request - The incoming HTTP request object.\n * @returns The server-relative asset path derived from the request.\n */\n private buildServerAssetPathFromRequest(request: Request): string {\n let { pathname: assetPath } = new URL(request.url);\n if (!assetPath.endsWith('/index.html')) {\n // Append \"index.html\" to build the default asset path.\n assetPath = joinUrlParts(assetPath, 'index.html');\n }\n\n const { baseHref } = this.manifest;\n // Check if the asset path starts with the base href and the base href is not (`/` or ``).\n if (baseHref.length > 1 && assetPath.startsWith(baseHref)) {\n // Remove the base href from the start of the asset path to align with server-asset expectations.\n assetPath = assetPath.slice(baseHref.length);\n }\n\n return stripLeadingSlash(assetPath);\n }\n\n /**\n * Runs the registered transform hooks on the given HTML content.\n *\n * @param html - The raw HTML content to be transformed.\n * @param url - The URL associated with the HTML content, used for context during transformations.\n * @param preload - An array of URLs representing the JavaScript resources to preload.\n * @returns A promise that resolves to the transformed HTML string.\n */\n private async runTransformsOnHtml(\n html: string,\n url: URL,\n preload: readonly string[] | undefined,\n ): Promise<string> {\n if (this.hooks.has('html:transform:pre')) {\n html = await this.hooks.run('html:transform:pre', { html, url });\n }\n\n if (preload?.length) {\n html = appendPreloadHintsToHtml(html, preload);\n }\n\n return html;\n }\n}\n\nlet angularServerApp: AngularServerApp | undefined;\n\n/**\n * Retrieves or creates an instance of `AngularServerApp`.\n * - If an instance of `AngularServerApp` already exists, it will return the existing one.\n * - If no instance exists, it will create a new one with the provided options.\n *\n * @param options Optional configuration options for the server application.\n *\n * @returns The existing or newly created instance of `AngularServerApp`.\n */\nexport function getOrCreateAngularServerApp(\n options?: Readonly<AngularServerAppOptions>,\n): AngularServerApp {\n return (angularServerApp ??= new AngularServerApp(options));\n}\n\n/**\n * Destroys the existing `AngularServerApp` instance, releasing associated resources and resetting the\n * reference to `undefined`.\n *\n * This function is primarily used to enable the recreation of the `AngularServerApp` instance,\n * typically when server configuration or application state needs to be refreshed.\n */\nexport function destroyAngularServerApp(): void {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n // Need to clean up GENERATED_COMP_IDS map in `@angular/core`.\n // Otherwise an incorrect component ID generation collision detected warning will be displayed in development.\n // See: https://github.com/angular/angular-cli/issues/25924\n ɵresetCompiledComponents();\n }\n\n angularServerApp = undefined;\n}\n\n/**\n * Appends module preload hints to an HTML string for specified JavaScript resources.\n * This function enhances the HTML by injecting `<link rel=\"modulepreload\">` elements\n * for each provided resource, allowing browsers to preload the specified JavaScript\n * modules for better performance.\n *\n * @param html - The original HTML string to which preload hints will be added.\n * @param preload - An array of URLs representing the JavaScript resources to preload.\n * @returns The modified HTML string with the preload hints injected before the closing `</body>` tag.\n * If `</body>` is not found, the links are not added.\n */\nfunction appendPreloadHintsToHtml(html: string, preload: readonly string[]): string {\n const bodyCloseIdx = html.lastIndexOf('</body>');\n if (bodyCloseIdx === -1) {\n return html;\n }\n\n // Note: Module preloads should be placed at the end before the closing body tag to avoid a performance penalty.\n // Placing them earlier can cause the browser to prioritize downloading these modules\n // over other critical page resources like images, CSS, and fonts.\n return [\n html.slice(0, bodyCloseIdx),\n ...preload.map((val) => `<link rel=\"modulepreload\" href=\"${val}\">`),\n html.slice(bodyCloseIdx),\n ].join('\\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\n/**\n * Extracts a potential locale ID from a given URL based on the specified base path.\n *\n * This function parses the URL to locate a potential locale identifier that immediately\n * follows the base path segment in the URL's pathname. If the URL does not contain a valid\n * locale ID, an empty string is returned.\n *\n * @param url - The full URL from which to extract the locale ID.\n * @param basePath - The base path used as the reference point for extracting the locale ID.\n * @returns The extracted locale ID if present, or an empty string if no valid locale ID is found.\n *\n * @example\n * ```js\n * const url = new URL('https://example.com/base/en/page');\n * const basePath = '/base';\n * const localeId = getPotentialLocaleIdFromUrl(url, basePath);\n * console.log(localeId); // Output: 'en'\n * ```\n */\nexport function getPotentialLocaleIdFromUrl(url: URL, basePath: string): string {\n const { pathname } = url;\n\n // Move forward of the base path section.\n let start = basePath.length;\n if (pathname[start] === '/') {\n start++;\n }\n\n // Find the next forward slash.\n let end = pathname.indexOf('/', start);\n if (end === -1) {\n end = pathname.length;\n }\n\n // Extract the potential locale id.\n return pathname.slice(start, end);\n}\n\n/**\n * Parses the `Accept-Language` header and returns a list of locale preferences with their respective quality values.\n *\n * The `Accept-Language` header is typically a comma-separated list of locales, with optional quality values\n * in the form of `q=<value>`. If no quality value is specified, a default quality of `1` is assumed.\n * Special case: if the header is `*`, it returns the default locale with a quality of `1`.\n *\n * @param header - The value of the `Accept-Language` header, typically a comma-separated list of locales\n * with optional quality values (e.g., `en-US;q=0.8,fr-FR;q=0.9`). If the header is `*`,\n * it represents a wildcard for any language, returning the default locale.\n *\n * @returns A `ReadonlyMap` where the key is the locale (e.g., `en-US`, `fr-FR`), and the value is\n * the associated quality value (a number between 0 and 1). If no quality value is provided,\n * a default of `1` is used.\n *\n * @example\n * ```js\n * parseLanguageHeader('en-US;q=0.8,fr-FR;q=0.9')\n * // returns new Map([['en-US', 0.8], ['fr-FR', 0.9]])\n\n * parseLanguageHeader('*')\n * // returns new Map([['*', 1]])\n * ```\n */\nfunction parseLanguageHeader(header: string): ReadonlyMap<string, number> {\n if (header === '*') {\n return new Map([['*', 1]]);\n }\n\n const parsedValues = header\n .split(',')\n .map((item) => {\n const [locale, qualityValue] = item.split(';', 2).map((v) => v.trim());\n\n let quality = qualityValue?.startsWith('q=') ? parseFloat(qualityValue.slice(2)) : undefined;\n if (typeof quality !== 'number' || isNaN(quality) || quality < 0 || quality > 1) {\n quality = 1; // Invalid quality value defaults to 1\n }\n\n return [locale, quality] as const;\n })\n .sort(([_localeA, qualityA], [_localeB, qualityB]) => qualityB - qualityA);\n\n return new Map(parsedValues);\n}\n\n/**\n * Gets the preferred locale based on the highest quality value from the provided `Accept-Language` header\n * and the set of available locales.\n *\n * This function adheres to the HTTP `Accept-Language` header specification as defined in\n * [RFC 7231](https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.5), including:\n * - Case-insensitive matching of language tags.\n * - Quality value handling (e.g., `q=1`, `q=0.8`). If no quality value is provided, it defaults to `q=1`.\n * - Prefix matching (e.g., `en` matching `en-US` or `en-GB`).\n *\n * @param header - The `Accept-Language` header string to parse and evaluate. It may contain multiple\n * locales with optional quality values, for example: `'en-US;q=0.8,fr-FR;q=0.9'`.\n * @param supportedLocales - An array of supported locales (e.g., `['en-US', 'fr-FR']`),\n * representing the locales available in the application.\n * @returns The best matching locale from the supported languages, or `undefined` if no match is found.\n *\n * @example\n * ```js\n * getPreferredLocale('en-US;q=0.8,fr-FR;q=0.9', ['en-US', 'fr-FR', 'de-DE'])\n * // returns 'fr-FR'\n *\n * getPreferredLocale('en;q=0.9,fr-FR;q=0.8', ['en-US', 'fr-FR', 'de-DE'])\n * // returns 'en-US'\n *\n * getPreferredLocale('es-ES;q=0.7', ['en-US', 'fr-FR', 'de-DE'])\n * // returns undefined\n * ```\n */\nexport function getPreferredLocale(\n header: string,\n supportedLocales: ReadonlyArray<string>,\n): string | undefined {\n if (supportedLocales.length < 2) {\n return supportedLocales[0];\n }\n\n const parsedLocales = parseLanguageHeader(header);\n\n // Handle edge cases:\n // - No preferred locales provided.\n // - Only one supported locale.\n // - Wildcard preference.\n if (parsedLocales.size === 0 || (parsedLocales.size === 1 && parsedLocales.has('*'))) {\n return supportedLocales[0];\n }\n\n // Create a map for case-insensitive lookup of supported locales.\n // Keys are normalized (lowercase) locale values, values are original casing.\n const normalizedSupportedLocales = new Map<string, string>();\n for (const locale of supportedLocales) {\n normalizedSupportedLocales.set(normalizeLocale(locale), locale);\n }\n\n // Iterate through parsed locales in descending order of quality.\n let bestMatch: string | undefined;\n const qualityZeroNormalizedLocales = new Set<string>();\n for (const [locale, quality] of parsedLocales) {\n const normalizedLocale = normalizeLocale(locale);\n if (quality === 0) {\n qualityZeroNormalizedLocales.add(normalizedLocale);\n continue; // Skip locales with quality value of 0.\n }\n\n // Exact match found.\n if (normalizedSupportedLocales.has(normalizedLocale)) {\n return normalizedSupportedLocales.get(normalizedLocale);\n }\n\n // If an exact match is not found, try prefix matching (e.g., \"en\" matches \"en-US\").\n // Store the first prefix match encountered, as it has the highest quality value.\n if (bestMatch !== undefined) {\n continue;\n }\n\n const [languagePrefix] = normalizedLocale.split('-', 1);\n for (const supportedLocale of normalizedSupportedLocales.keys()) {\n if (supportedLocale.startsWith(languagePrefix)) {\n bestMatch = normalizedSupportedLocales.get(supportedLocale);\n break; // No need to continue searching for this locale.\n }\n }\n }\n\n if (bestMatch !== undefined) {\n return bestMatch;\n }\n\n // Return the first locale that is not quality zero.\n for (const [normalizedLocale, locale] of normalizedSupportedLocales) {\n if (!qualityZeroNormalizedLocales.has(normalizedLocale)) {\n return locale;\n }\n }\n}\n\n/**\n * Normalizes a locale string by converting it to lowercase.\n *\n * @param locale - The locale string to normalize.\n * @returns The normalized locale string in lowercase.\n *\n * @example\n * ```ts\n * const normalized = normalizeLocale('EN-US');\n * console.log(normalized); // Output: \"en-us\"\n * ```\n */\nfunction normalizeLocale(locale: string): string {\n return locale.toLowerCase();\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 { AngularServerApp, getOrCreateAngularServerApp } from './app';\nimport { Hooks } from './hooks';\nimport { getPotentialLocaleIdFromUrl, getPreferredLocale } from './i18n';\nimport { EntryPointExports, getAngularAppEngineManifest } from './manifest';\nimport { joinUrlParts } from './utils/url';\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 AngularAppEngine {\n /**\n * A flag to enable or disable the rendering of prerendered routes.\n *\n * Typically used during development to avoid prerendering all routes ahead of time,\n * allowing them to be rendered on the fly as requested.\n *\n * @private\n */\n static ɵallowStaticRouteRender = false;\n\n /**\n * Hooks for extending or modifying the behavior of the server application.\n * These hooks are used by the Angular CLI when running the development server and\n * provide extensibility points for the application lifecycle.\n *\n * @private\n */\n static ɵhooks = /* #__PURE__*/ new Hooks();\n\n /**\n * The manifest for the server application.\n */\n private readonly manifest = getAngularAppEngineManifest();\n\n /**\n * A map of supported locales from the server application's manifest.\n */\n private readonly supportedLocales: ReadonlyArray<string> = Object.keys(\n this.manifest.supportedLocales,\n );\n\n /**\n * A cache that holds entry points, keyed by their potential locale string.\n */\n private readonly entryPointsCache = new Map<string, Promise<EntryPointExports>>();\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 * @param request - The HTTP request to handle.\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(request: Request, requestContext?: unknown): Promise<Response | null> {\n const serverApp = await this.getAngularServerAppForRequest(request);\n\n if (serverApp) {\n return serverApp.handle(request, requestContext);\n }\n\n if (this.supportedLocales.length > 1) {\n // Redirect to the preferred language if i18n is enabled.\n return this.redirectBasedOnAcceptLanguage(request);\n }\n\n return null;\n }\n\n /**\n * Handles requests for the base path when i18n is enabled.\n * Redirects the user to a locale-specific path based on the `Accept-Language` header.\n *\n * @param request The incoming request.\n * @returns A `Response` object with a 302 redirect, or `null` if i18n is not enabled\n * or the request is not for the base path.\n */\n private redirectBasedOnAcceptLanguage(request: Request): Response | null {\n const { basePath, supportedLocales } = this.manifest;\n\n // If the request is not for the base path, it's not our responsibility to handle it.\n const { pathname } = new URL(request.url);\n if (pathname !== basePath) {\n return null;\n }\n\n // For requests to the base path (typically '/'), attempt to extract the preferred locale\n // from the 'Accept-Language' header.\n const preferredLocale = getPreferredLocale(\n request.headers.get('Accept-Language') || '*',\n this.supportedLocales,\n );\n\n if (preferredLocale) {\n const subPath = supportedLocales[preferredLocale];\n if (subPath !== undefined) {\n return new Response(null, {\n status: 302, // Use a 302 redirect as language preference may change.\n headers: {\n 'Location': joinUrlParts(pathname, subPath),\n 'Vary': 'Accept-Language',\n },\n });\n }\n }\n\n return null;\n }\n\n /**\n * Retrieves the Angular server application instance for a given request.\n *\n * This method checks if the request URL corresponds to an Angular application entry point.\n * If so, it initializes or retrieves an instance of the Angular server application for that entry point.\n * Requests that resemble file requests (except for `/index.html`) are skipped.\n *\n * @param request - The incoming HTTP request object.\n * @returns A promise that resolves to an `AngularServerApp` instance if a valid entry point is found,\n * or `null` if no entry point matches the request URL.\n */\n private async getAngularServerAppForRequest(request: Request): Promise<AngularServerApp | null> {\n // Skip if the request looks like a file but not `/index.html`.\n const url = new URL(request.url);\n const entryPoint = await this.getEntryPointExportsForUrl(url);\n if (!entryPoint) {\n return null;\n }\n\n // Note: Using `instanceof` is not feasible here because `AngularServerApp` will\n // be located in separate bundles, making `instanceof` checks unreliable.\n const ɵgetOrCreateAngularServerApp =\n entryPoint.ɵgetOrCreateAngularServerApp as typeof getOrCreateAngularServerApp;\n\n const serverApp = ɵgetOrCreateAngularServerApp({\n allowStaticRouteRender: AngularAppEngine.ɵallowStaticRouteRender,\n hooks: AngularAppEngine.ɵhooks,\n });\n\n return serverApp;\n }\n\n /**\n * Retrieves the exports for a specific entry point, caching the result.\n *\n * @param potentialLocale - The locale string used to find the corresponding entry point.\n * @returns A promise that resolves to the entry point exports or `undefined` if not found.\n */\n private getEntryPointExports(potentialLocale: string): Promise<EntryPointExports> | undefined {\n const cachedEntryPoint = this.entryPointsCache.get(potentialLocale);\n if (cachedEntryPoint) {\n return cachedEntryPoint;\n }\n\n const { entryPoints } = this.manifest;\n const entryPoint = entryPoints[potentialLocale];\n if (!entryPoint) {\n return undefined;\n }\n\n const entryPointExports = entryPoint();\n this.entryPointsCache.set(potentialLocale, entryPointExports);\n\n return entryPointExports;\n }\n\n /**\n * Retrieves the entry point for a given URL by determining the locale and mapping it to\n * the appropriate application bundle.\n *\n * This method determines the appropriate entry point and locale for rendering the application by examining the URL.\n * If there is only one entry point available, it is returned regardless of the URL.\n * Otherwise, the method extracts a potential locale identifier from the URL and looks up the corresponding entry point.\n *\n * @param url - The URL of the request.\n * @returns A promise that resolves to the entry point exports or `undefined` if not found.\n */\n private getEntryPointExportsForUrl(url: URL): Promise<EntryPointExports> | undefined {\n const { basePath, supportedLocales } = this.manifest;\n\n if (this.supportedLocales.length === 1) {\n return this.getEntryPointExports(supportedLocales[this.supportedLocales[0]]);\n }\n\n const potentialLocale = getPotentialLocaleIdFromUrl(url, basePath);\n\n return this.getEntryPointExports(potentialLocale) ?? this.getEntryPointExports('');\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\n/**\n * Function for handling HTTP requests in a web environment.\n *\n * @param request - The incoming HTTP request object.\n * @returns A Promise resolving to a `Response` object, `null`, or directly a `Response`,\n * supporting both synchronous and asynchronous handling.\n */\nexport type RequestHandlerFunction = (\n request: Request,\n) => Promise<Response | null> | null | Response;\n\n/**\n * Annotates a request handler function with metadata, marking it as a special\n * handler.\n *\n * @param handler - The request handler function to be annotated.\n * @returns The same handler function passed in, with metadata attached.\n *\n * @example\n * Example usage in a Hono application:\n * ```ts\n * const app = new Hono();\n * export default createRequestHandler(app.fetch);\n * ```\n *\n * @example\n * Example usage in a H3 application:\n * ```ts\n * const app = createApp();\n * const handler = toWebHandler(app);\n * export default createRequestHandler(handler);\n * ```\n */\nexport function createRequestHandler(handler: RequestHandlerFunction): RequestHandlerFunction {\n (handler as RequestHandlerFunction & { __ng_request_handler__?: boolean })[\n '__ng_request_handler__'\n ] = true;\n\n return handler;\n}\n"],"names":["ServerAssets","manifest","constructor","getServerAsset","path","asset","assets","Error","hasServerAsset","getIndexServerHtml","IGNORED_LOGS","Set","Console","ɵConsole","log","message","has","angularAppManifest","setAngularAppManifest","getAngularAppManifest","angularAppEngineManifest","setAngularAppEngineManifest","getAngularAppEngineManifest","stripTrailingSlash","url","length","at","slice","stripLeadingSlash","addLeadingSlash","addTrailingSlash","joinUrlParts","parts","normalizeParts","part","normalizedPart","push","join","stripIndexHtmlFromURL","pathname","endsWith","modifiedURL","URL","buildPathWithParams","toPath","fromPath","includes","fromPathParts","split","toPathParts","resolvedParts","map","index","MATRIX_PARAMS_REGEX","stripMatrixParams","replace","renderAngular","html","bootstrap","platformProviders","serverContext","urlToRender","platformRef","platformServer","provide","INITIAL_CONFIG","useValue","href","document","SERVER_CONTEXT","useFactory","redirectTo","hasNavigationError","applicationRef","isNgModule","moduleRef","bootstrapModule","injector","get","ApplicationRef","whenStable","envInjector","routerIsProvided","ActivatedRoute","router","Router","lastSuccessfulNavigation","finalUrl","requestPrefix","APP_BASE_HREF","optional","REQUEST","headers","search","hash","PlatformLocation","constructDecodedUrl","urlToRenderString","content","Promise","resolve","reject","setTimeout","renderInternal","then","catch","finally","asyncDestroyPlatform","error","value","destroyed","destroy","prefix","urlParts","startsWith","decodeURIComponent","promiseWithAbort","promise","signal","errorMessagePrefix","abortHandler","DOMException","reason","aborted","addEventListener","once","removeEventListener","VALID_REDIRECT_RESPONSE_CODES","isValidRedirectResponseCode","code","createRedirectResponse","location","status","ngDevMode","values","Response","APP_SHELL_ROUTE","ServerRenderingFeatureKind","RenderMode","PrerenderFallback","SERVER_ROUTES_CONFIG","InjectionToken","withRoutes","routes","config","ɵkind","ServerRoutes","ɵproviders","withAppShell","component","routeConfig","loadComponent","AppShell","ROUTES","multi","provideEnvironmentInitializer","inject","appShellRoute","provideServerRendering","features","hasAppShell","hasServerRoutes","providers","provideServerRenderingPlatformServer","makeEnvironmentProviders","RouteTree","root","createEmptyRouteTreeNode","insert","route","metadata","node","segments","getPathSegments","normalizedSegments","segment","normalizedSegment","childNode","children","set","match","traverseBySegments","toObject","Array","from","traverse","fromObject","tree","filter","Boolean","currentIndex","size","undefined","exactMatch","wildcardMatch","Map","MODULE_PRELOAD_MAX","CATCH_ALL_REGEXP","URL_PARAMETER_REGEXP","handleRoute","options","currentRoutePath","compiler","parentInjector","serverConfigRouteTree","entryPointToBrowserMapping","invokeGetPrerenderParams","includePrerenderFallbackRoutes","loadChildren","ɵentryName","appendPreloadToMetadata","renderMode","Prerender","handleSSGRoute","resolveRedirectTo","traverseRoutesConfig","parentRoute","parentPreloads","preload","routeInjector","createEnvironmentInjector","EnvironmentInjector","loadedChildRoutes","loadChildrenHelper","childRoutes","routeConfigs","matcher","matches","matchedMetaData","presentInClientRouter","entryName","existingPreloads","combinedPreloads","add","fallback","meta","getPrerenderParams","isCatchAllRoute","test","catchAllRoutePath","parameters","runInInjectionContext","params","replacer","handlePrerenderParamsReplacement","routeWithResolvedParams","None","Client","Server","parameterName","routePath","pop","buildServerConfigRouteTree","serverRoutes","unshift","errors","getRoutesFromAngularRouterConfig","protocol","host","ɵENABLE_ROOT_COMPONENT_BOOTSTRAP","navigationTransitions","afterPreactivation","next","rawBaseHref","getBaseHrefFromDOM","baseHref","Compiler","serverRoutesConfig","result","routesResults","traverseRoutes","seenRoutes","routeMetadata","rootRouteMetadata","extractRoutesAndCreateRouteTree","extract","routeTree","text","key","Object","entries","fullRoute","Hooks","store","run","name","context","hooks","ctx","hook","on","handler","ServerRouter","sha256","data","encodedData","TextEncoder","encode","hashBuffer","crypto","subtle","digest","hashParts","h","Uint8Array","toString","padStart","MEDIA_SET_HANDLER_PATTERN","CSP_MEDIA_ATTR","LINK_LOAD_SCRIPT_CONTENT","BeastiesBase","Beasties","InlineCriticalCssProcessor","readFile","outputPath","addedCspScriptsDocuments","WeakSet","documentNonces","WeakMap","logger","warn","s","console","info","logLevel","publicPath","compress","pruneSource","reduceInlineStyles","mergeStylesheets","noscriptFallback","inlineFonts","embedLinkedStylesheet","link","getAttribute","media","removeAttribute","setAttribute","remove","returnValue","cspNonce","findCspNonce","beastiesMedia","conditionallyInsertCspLoadingScript","head","forEach","child","tagName","hasAttribute","nonceElement","querySelector","nonce","textContent","script","createElement","insertBefore","LRUCache","capacity","cache","tail","moveToHead","put","cachedNode","newNode","prev","addToHead","removeTail","delete","removeNode","WELL_KNOWN_NON_ANGULAR_URLS","MAX_INLINE_CSS_CACHE_ENTRIES","SERVER_CONTEXT_VALUE","AngularServerApp","allowStaticRouteRender","inlineCriticalCss","inlineCriticalCssProcessor","fileName","boostrap","textDecoder","criticalCssLRUCache","handle","request","requestContext","matchedRoute","response","handleServe","handleRendering","method","assetPath","buildServerAssetPathFromRequest","locale","etag","statusText","responseInit","Headers","REQUEST_CONTEXT","RESPONSE_INIT","runTransformsOnHtml","LOCALE_ID","renderedHtml","finalHtml","stream","ReadableStream","start","controller","inlineCriticalCssWithCache","enqueue","close","process","cacheKey","cached","shaOfContentPreInlinedCss","contentWithCriticialCSS","processedHtml","appendPreloadHintsToHtml","angularServerApp","getOrCreateAngularServerApp","destroyAngularServerApp","ɵresetCompiledComponents","bodyCloseIdx","lastIndexOf","val","getPotentialLocaleIdFromUrl","basePath","end","indexOf","parseLanguageHeader","header","parsedValues","item","qualityValue","v","trim","quality","parseFloat","isNaN","sort","_localeA","qualityA","_localeB","qualityB","getPreferredLocale","supportedLocales","parsedLocales","normalizedSupportedLocales","normalizeLocale","bestMatch","qualityZeroNormalizedLocales","normalizedLocale","languagePrefix","supportedLocale","keys","toLowerCase","AngularAppEngine","ɵallowStaticRouteRender","ɵhooks","entryPointsCache","serverApp","getAngularServerAppForRequest","redirectBasedOnAcceptLanguage","preferredLocale","subPath","entryPoint","getEntryPointExportsForUrl","ɵgetOrCreateAngularServerApp","getEntryPointExports","potentialLocale","cachedEntryPoint","entryPoints","entryPointExports","createRequestHandler"],"mappings":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I;AAER,EAAA,OAAOA,OAAO;AAChB;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@angular/ssr",
3
- "version": "21.0.3",
3
+ "version": "21.0.5",
4
4
  "description": "Angular server side rendering utilities",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -29,12 +29,12 @@
29
29
  },
30
30
  "devDependencies": {
31
31
  "@angular-devkit/schematics": "workspace:*",
32
- "@angular/common": "21.0.3",
33
- "@angular/compiler": "21.0.3",
34
- "@angular/core": "21.0.3",
35
- "@angular/platform-browser": "21.0.3",
36
- "@angular/platform-server": "21.0.3",
37
- "@angular/router": "21.0.3",
32
+ "@angular/common": "21.0.6",
33
+ "@angular/compiler": "21.0.6",
34
+ "@angular/core": "21.0.6",
35
+ "@angular/platform-browser": "21.0.6",
36
+ "@angular/platform-server": "21.0.6",
37
+ "@angular/router": "21.0.6",
38
38
  "@schematics/angular": "workspace:*",
39
39
  "beasties": "0.3.5"
40
40
  },