@angular/ssr 21.0.0-next.8 → 21.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/fesm2022/ssr.mjs CHANGED
@@ -1,1604 +1,889 @@
1
1
  import { ɵConsole as _Console, ApplicationRef, InjectionToken, provideEnvironmentInitializer, inject, makeEnvironmentProviders, ɵENABLE_ROOT_COMPONENT_BOOTSTRAP as _ENABLE_ROOT_COMPONENT_BOOTSTRAP, Compiler, createEnvironmentInjector, EnvironmentInjector, runInInjectionContext, ɵresetCompiledComponents as _resetCompiledComponents, REQUEST, REQUEST_CONTEXT, RESPONSE_INIT, LOCALE_ID } from '@angular/core';
2
2
  import { platformServer, INITIAL_CONFIG, ɵSERVER_CONTEXT as _SERVER_CONTEXT, ɵrenderInternal as _renderInternal, provideServerRendering as provideServerRendering$1 } from '@angular/platform-server';
3
3
  import { ActivatedRoute, Router, ROUTES, ɵloadChildren as _loadChildren } from '@angular/router';
4
- import { APP_BASE_HREF, PlatformLocation } from '@angular/common';
4
+ import { PlatformLocation, APP_BASE_HREF } from '@angular/common';
5
5
  import Beasties from '../third_party/beasties/index.js';
6
6
 
7
- /**
8
- * Manages server-side assets.
9
- */
10
7
  class ServerAssets {
11
- manifest;
12
- /**
13
- * Creates an instance of ServerAsset.
14
- *
15
- * @param manifest - The manifest containing the server assets.
16
- */
17
- constructor(manifest) {
18
- this.manifest = manifest;
19
- }
20
- /**
21
- * Retrieves the content of a server-side asset using its path.
22
- *
23
- * @param path - The path to the server asset within the manifest.
24
- * @returns The server asset associated with the provided path, as a `ServerAsset` object.
25
- * @throws Error - Throws an error if the asset does not exist.
26
- */
27
- getServerAsset(path) {
28
- const asset = this.manifest.assets[path];
29
- if (!asset) {
30
- throw new Error(`Server asset '${path}' does not exist.`);
31
- }
32
- return asset;
33
- }
34
- /**
35
- * Checks if a specific server-side asset exists.
36
- *
37
- * @param path - The path to the server asset.
38
- * @returns A boolean indicating whether the asset exists.
39
- */
40
- hasServerAsset(path) {
41
- return !!this.manifest.assets[path];
42
- }
43
- /**
44
- * Retrieves the asset for 'index.server.html'.
45
- *
46
- * @returns The `ServerAsset` object for 'index.server.html'.
47
- * @throws Error - Throws an error if 'index.server.html' does not exist.
48
- */
49
- getIndexServerHtml() {
50
- return this.getServerAsset('index.server.html');
51
- }
8
+ manifest;
9
+ constructor(manifest) {
10
+ this.manifest = manifest;
11
+ }
12
+ getServerAsset(path) {
13
+ const asset = this.manifest.assets[path];
14
+ if (!asset) {
15
+ throw new Error(`Server asset '${path}' does not exist.`);
16
+ }
17
+ return asset;
18
+ }
19
+ hasServerAsset(path) {
20
+ return !!this.manifest.assets[path];
21
+ }
22
+ getIndexServerHtml() {
23
+ return this.getServerAsset('index.server.html');
24
+ }
52
25
  }
53
26
 
54
- /**
55
- * A set of log messages that should be ignored and not printed to the console.
56
- */
57
27
  const IGNORED_LOGS = new Set(['Angular is running in development mode.']);
58
- /**
59
- * Custom implementation of the Angular Console service that filters out specific log messages.
60
- *
61
- * This class extends the internal Angular `ɵConsole` class to provide customized logging behavior.
62
- * It overrides the `log` method to suppress logs that match certain predefined messages.
63
- */
64
28
  class Console extends _Console {
65
- /**
66
- * Logs a message to the console if it is not in the set of ignored messages.
67
- *
68
- * @param message - The message to log to the console.
69
- *
70
- * This method overrides the `log` method of the `ɵConsole` class. It checks if the
71
- * message is in the `IGNORED_LOGS` set. If it is not, it delegates the logging to
72
- * the parent class's `log` method. Otherwise, the message is suppressed.
73
- */
74
- log(message) {
75
- if (!IGNORED_LOGS.has(message)) {
76
- super.log(message);
77
- }
29
+ log(message) {
30
+ if (!IGNORED_LOGS.has(message)) {
31
+ super.log(message);
78
32
  }
33
+ }
79
34
  }
80
35
 
81
- /**
82
- * The Angular app manifest object.
83
- * This is used internally to store the current Angular app manifest.
84
- */
85
36
  let angularAppManifest;
86
- /**
87
- * Sets the Angular app manifest.
88
- *
89
- * @param manifest - The manifest object to set for the Angular application.
90
- */
91
37
  function setAngularAppManifest(manifest) {
92
- angularAppManifest = manifest;
38
+ angularAppManifest = manifest;
93
39
  }
94
- /**
95
- * Gets the Angular app manifest.
96
- *
97
- * @returns The Angular app manifest.
98
- * @throws Will throw an error if the Angular app manifest is not set.
99
- */
100
40
  function getAngularAppManifest() {
101
- if (!angularAppManifest) {
102
- throw new Error('Angular app manifest is not set. ' +
103
- `Please ensure you are using the '@angular/build:application' builder to build your server application.`);
104
- }
105
- return angularAppManifest;
41
+ if (!angularAppManifest) {
42
+ throw new Error('Angular app manifest is not set. ' + `Please ensure you are using the '@angular/build:application' builder to build your server application.`);
43
+ }
44
+ return angularAppManifest;
106
45
  }
107
- /**
108
- * The Angular app engine manifest object.
109
- * This is used internally to store the current Angular app engine manifest.
110
- */
111
46
  let angularAppEngineManifest;
112
- /**
113
- * Sets the Angular app engine manifest.
114
- *
115
- * @param manifest - The engine manifest object to set.
116
- */
117
47
  function setAngularAppEngineManifest(manifest) {
118
- angularAppEngineManifest = manifest;
48
+ angularAppEngineManifest = manifest;
119
49
  }
120
- /**
121
- * Gets the Angular app engine manifest.
122
- *
123
- * @returns The Angular app engine manifest.
124
- * @throws Will throw an error if the Angular app engine manifest is not set.
125
- */
126
50
  function getAngularAppEngineManifest() {
127
- if (!angularAppEngineManifest) {
128
- throw new Error('Angular app engine manifest is not set. ' +
129
- `Please ensure you are using the '@angular/build:application' builder to build your server application.`);
130
- }
131
- return angularAppEngineManifest;
51
+ if (!angularAppEngineManifest) {
52
+ throw new Error('Angular app engine manifest is not set. ' + `Please ensure you are using the '@angular/build:application' builder to build your server application.`);
53
+ }
54
+ return angularAppEngineManifest;
132
55
  }
133
56
 
134
- /**
135
- * Removes the trailing slash from a URL if it exists.
136
- *
137
- * @param url - The URL string from which to remove the trailing slash.
138
- * @returns The URL string without a trailing slash.
139
- *
140
- * @example
141
- * ```js
142
- * stripTrailingSlash('path/'); // 'path'
143
- * stripTrailingSlash('/path'); // '/path'
144
- * stripTrailingSlash('/'); // '/'
145
- * stripTrailingSlash(''); // ''
146
- * ```
147
- */
148
- /**
149
- * Removes the leading slash from a URL if it exists.
150
- *
151
- * @param url - The URL string from which to remove the leading slash.
152
- * @returns The URL string without a leading slash.
153
- *
154
- * @example
155
- * ```js
156
- * stripLeadingSlash('/path'); // 'path'
157
- * stripLeadingSlash('/path/'); // 'path/'
158
- * stripLeadingSlash('/'); // '/'
159
- * stripLeadingSlash(''); // ''
160
- * ```
161
- */
57
+ function stripTrailingSlash(url) {
58
+ return url.length > 1 && url[url.length - 1] === '/' ? url.slice(0, -1) : url;
59
+ }
162
60
  function stripLeadingSlash(url) {
163
- // Check if the first character of the URL is a slash
164
- return url.length > 1 && url[0] === '/' ? url.slice(1) : url;
61
+ return url.length > 1 && url[0] === '/' ? url.slice(1) : url;
165
62
  }
166
- /**
167
- * Adds a leading slash to a URL if it does not already have one.
168
- *
169
- * @param url - The URL string to which the leading slash will be added.
170
- * @returns The URL string with a leading slash.
171
- *
172
- * @example
173
- * ```js
174
- * addLeadingSlash('path'); // '/path'
175
- * addLeadingSlash('/path'); // '/path'
176
- * ```
177
- */
178
63
  function addLeadingSlash(url) {
179
- // Check if the URL already starts with a slash
180
- return url[0] === '/' ? url : `/${url}`;
64
+ return url[0] === '/' ? url : `/${url}`;
181
65
  }
182
- /**
183
- * Adds a trailing slash to a URL if it does not already have one.
184
- *
185
- * @param url - The URL string to which the trailing slash will be added.
186
- * @returns The URL string with a trailing slash.
187
- *
188
- * @example
189
- * ```js
190
- * addTrailingSlash('path'); // 'path/'
191
- * addTrailingSlash('path/'); // 'path/'
192
- * ```
193
- */
194
66
  function addTrailingSlash(url) {
195
- // Check if the URL already end with a slash
196
- return url[url.length - 1] === '/' ? url : `${url}/`;
67
+ return url[url.length - 1] === '/' ? url : `${url}/`;
197
68
  }
198
- /**
199
- * Joins URL parts into a single URL string.
200
- *
201
- * This function takes multiple URL segments, normalizes them by removing leading
202
- * and trailing slashes where appropriate, and then joins them into a single URL.
203
- *
204
- * @param parts - The parts of the URL to join. Each part can be a string with or without slashes.
205
- * @returns The joined URL string, with normalized slashes.
206
- *
207
- * @example
208
- * ```js
209
- * joinUrlParts('path/', '/to/resource'); // '/path/to/resource'
210
- * joinUrlParts('/path/', 'to/resource'); // '/path/to/resource'
211
- * joinUrlParts('', ''); // '/'
212
- * ```
213
- */
214
69
  function joinUrlParts(...parts) {
215
- const normalizeParts = [];
216
- for (const part of parts) {
217
- if (part === '') {
218
- // Skip any empty parts
219
- continue;
220
- }
221
- let normalizedPart = part;
222
- if (part[0] === '/') {
223
- normalizedPart = normalizedPart.slice(1);
224
- }
225
- if (part[part.length - 1] === '/') {
226
- normalizedPart = normalizedPart.slice(0, -1);
227
- }
228
- if (normalizedPart !== '') {
229
- normalizeParts.push(normalizedPart);
230
- }
70
+ const normalizeParts = [];
71
+ for (const part of parts) {
72
+ if (part === '') {
73
+ continue;
74
+ }
75
+ let normalizedPart = part;
76
+ if (part[0] === '/') {
77
+ normalizedPart = normalizedPart.slice(1);
231
78
  }
232
- return addLeadingSlash(normalizeParts.join('/'));
79
+ if (part[part.length - 1] === '/') {
80
+ normalizedPart = normalizedPart.slice(0, -1);
81
+ }
82
+ if (normalizedPart !== '') {
83
+ normalizeParts.push(normalizedPart);
84
+ }
85
+ }
86
+ return addLeadingSlash(normalizeParts.join('/'));
233
87
  }
234
- /**
235
- * Strips `/index.html` from the end of a URL's path, if present.
236
- *
237
- * This function is used to convert URLs pointing to an `index.html` file into their directory
238
- * equivalents. For example, it transforms a URL like `http://www.example.com/page/index.html`
239
- * into `http://www.example.com/page`.
240
- *
241
- * @param url - The URL object to process.
242
- * @returns A new URL object with `/index.html` removed from the path, if it was present.
243
- *
244
- * @example
245
- * ```typescript
246
- * const originalUrl = new URL('http://www.example.com/page/index.html');
247
- * const cleanedUrl = stripIndexHtmlFromURL(originalUrl);
248
- * console.log(cleanedUrl.href); // Output: 'http://www.example.com/page'
249
- * ```
250
- */
251
88
  function stripIndexHtmlFromURL(url) {
252
- if (url.pathname.endsWith('/index.html')) {
253
- const modifiedURL = new URL(url);
254
- // Remove '/index.html' from the pathname
255
- modifiedURL.pathname = modifiedURL.pathname.slice(0, /** '/index.html'.length */ -11);
256
- return modifiedURL;
257
- }
258
- return url;
89
+ if (url.pathname.endsWith('/index.html')) {
90
+ const modifiedURL = new URL(url);
91
+ modifiedURL.pathname = modifiedURL.pathname.slice(0, -11);
92
+ return modifiedURL;
93
+ }
94
+ return url;
259
95
  }
260
- /**
261
- * Resolves `*` placeholders in a path template by mapping them to corresponding segments
262
- * from a base path. This is useful for constructing paths dynamically based on a given base path.
263
- *
264
- * The function processes the `toPath` string, replacing each `*` placeholder with
265
- * the corresponding segment from the `fromPath`. If the `toPath` contains no placeholders,
266
- * it is returned as-is. Invalid `toPath` formats (not starting with `/`) will throw an error.
267
- *
268
- * @param toPath - A path template string that may contain `*` placeholders. Each `*` is replaced
269
- * by the corresponding segment from the `fromPath`. Static paths (e.g., `/static/path`) are returned
270
- * directly without placeholder replacement.
271
- * @param fromPath - A base path string, split into segments, that provides values for
272
- * replacing `*` placeholders in the `toPath`.
273
- * @returns A resolved path string with `*` placeholders replaced by segments from the `fromPath`,
274
- * or the `toPath` returned unchanged if it contains no placeholders.
275
- *
276
- * @throws If the `toPath` does not start with a `/`, indicating an invalid path format.
277
- *
278
- * @example
279
- * ```typescript
280
- * // Example with placeholders resolved
281
- * const resolvedPath = buildPathWithParams('/*\/details', '/123/abc');
282
- * console.log(resolvedPath); // Outputs: '/123/details'
283
- *
284
- * // Example with a static path
285
- * const staticPath = buildPathWithParams('/static/path', '/base/unused');
286
- * console.log(staticPath); // Outputs: '/static/path'
287
- * ```
288
- */
289
96
  function buildPathWithParams(toPath, fromPath) {
290
- if (toPath[0] !== '/') {
291
- throw new Error(`Invalid toPath: The string must start with a '/'. Received: '${toPath}'`);
292
- }
293
- if (fromPath[0] !== '/') {
294
- throw new Error(`Invalid fromPath: The string must start with a '/'. Received: '${fromPath}'`);
295
- }
296
- if (!toPath.includes('/*')) {
297
- return toPath;
298
- }
299
- const fromPathParts = fromPath.split('/');
300
- const toPathParts = toPath.split('/');
301
- const resolvedParts = toPathParts.map((part, index) => toPathParts[index] === '*' ? fromPathParts[index] : part);
302
- return joinUrlParts(...resolvedParts);
97
+ if (toPath[0] !== '/') {
98
+ throw new Error(`Invalid toPath: The string must start with a '/'. Received: '${toPath}'`);
99
+ }
100
+ if (fromPath[0] !== '/') {
101
+ throw new Error(`Invalid fromPath: The string must start with a '/'. Received: '${fromPath}'`);
102
+ }
103
+ if (!toPath.includes('/*')) {
104
+ return toPath;
105
+ }
106
+ const fromPathParts = fromPath.split('/');
107
+ const toPathParts = toPath.split('/');
108
+ const resolvedParts = toPathParts.map((part, index) => toPathParts[index] === '*' ? fromPathParts[index] : part);
109
+ return joinUrlParts(...resolvedParts);
110
+ }
111
+ const MATRIX_PARAMS_REGEX = /;[^/]+/g;
112
+ function stripMatrixParams(pathname) {
113
+ return pathname.includes(';') ? pathname.replace(MATRIX_PARAMS_REGEX, '') : pathname;
303
114
  }
304
115
 
305
- /**
306
- * Renders an Angular application or module to an HTML string.
307
- *
308
- * This function determines whether the provided `bootstrap` value is an Angular module
309
- * or a bootstrap function and invokes the appropriate rendering method (`renderModule` or `renderApplication`).
310
- *
311
- * @param html - The initial HTML document content.
312
- * @param bootstrap - An Angular module type or a function returning a promise that resolves to an `ApplicationRef`.
313
- * @param url - The application URL, used for route-based rendering in SSR.
314
- * @param platformProviders - An array of platform providers for the rendering process.
315
- * @param serverContext - A string representing the server context, providing additional metadata for SSR.
316
- * @returns A promise resolving to an object containing:
317
- * - `hasNavigationError`: Indicates if a navigation error occurred.
318
- * - `redirectTo`: (Optional) The redirect URL if a navigation redirect occurred.
319
- * - `content`: A function returning a promise that resolves to the rendered HTML string.
320
- */
321
116
  async function renderAngular(html, bootstrap, url, platformProviders, serverContext) {
322
- // A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.
323
- const urlToRender = stripIndexHtmlFromURL(url).toString();
324
- const platformRef = platformServer([
325
- {
326
- provide: INITIAL_CONFIG,
327
- useValue: {
328
- url: urlToRender,
329
- document: html,
330
- },
331
- },
332
- {
333
- provide: _SERVER_CONTEXT,
334
- useValue: serverContext,
335
- },
336
- {
337
- // An Angular Console Provider that does not print a set of predefined logs.
338
- provide: _Console,
339
- // Using `useClass` would necessitate decorating `Console` with `@Injectable`,
340
- // which would require switching from `ts_library` to `ng_module`. This change
341
- // would also necessitate various patches of `@angular/bazel` to support ESM.
342
- useFactory: () => new Console(),
343
- },
344
- ...platformProviders,
345
- ]);
346
- let redirectTo;
347
- let hasNavigationError = true;
348
- try {
349
- let applicationRef;
350
- if (isNgModule(bootstrap)) {
351
- const moduleRef = await platformRef.bootstrapModule(bootstrap);
352
- applicationRef = moduleRef.injector.get(ApplicationRef);
353
- }
354
- else {
355
- applicationRef = await bootstrap({ platformRef });
356
- }
357
- // Block until application is stable.
358
- await applicationRef.whenStable();
359
- // TODO(alanagius): Find a way to avoid rendering here especially for redirects as any output will be discarded.
360
- const envInjector = applicationRef.injector;
361
- const routerIsProvided = !!envInjector.get(ActivatedRoute, null);
362
- const router = envInjector.get(Router);
363
- const lastSuccessfulNavigation = router.lastSuccessfulNavigation();
364
- if (!routerIsProvided) {
365
- hasNavigationError = false;
366
- }
367
- else if (lastSuccessfulNavigation?.finalUrl) {
368
- hasNavigationError = false;
369
- const { finalUrl, initialUrl } = lastSuccessfulNavigation;
370
- const finalUrlStringified = finalUrl.toString();
371
- if (initialUrl.toString() !== finalUrlStringified) {
372
- const baseHref = envInjector.get(APP_BASE_HREF, null, { optional: true }) ??
373
- envInjector.get(PlatformLocation).getBaseHrefFromDOM();
374
- redirectTo = joinUrlParts(baseHref, finalUrlStringified);
375
- }
376
- }
377
- return {
378
- hasNavigationError,
379
- redirectTo,
380
- content: () => new Promise((resolve, reject) => {
381
- // Defer rendering to the next event loop iteration to avoid blocking, as most operations in `renderInternal` are synchronous.
382
- setTimeout(() => {
383
- _renderInternal(platformRef, applicationRef)
384
- .then(resolve)
385
- .catch(reject)
386
- .finally(() => void asyncDestroyPlatform(platformRef));
387
- }, 0);
388
- }),
389
- };
390
- }
391
- catch (error) {
392
- await asyncDestroyPlatform(platformRef);
393
- throw error;
394
- }
395
- finally {
396
- if (hasNavigationError || redirectTo) {
397
- void asyncDestroyPlatform(platformRef);
398
- }
117
+ const urlToRender = stripIndexHtmlFromURL(url);
118
+ const platformRef = platformServer([{
119
+ provide: INITIAL_CONFIG,
120
+ useValue: {
121
+ url: urlToRender.href,
122
+ document: html
123
+ }
124
+ }, {
125
+ provide: _SERVER_CONTEXT,
126
+ useValue: serverContext
127
+ }, {
128
+ provide: _Console,
129
+ useFactory: () => new Console()
130
+ }, ...platformProviders]);
131
+ let redirectTo;
132
+ let hasNavigationError = true;
133
+ try {
134
+ let applicationRef;
135
+ if (isNgModule(bootstrap)) {
136
+ const moduleRef = await platformRef.bootstrapModule(bootstrap);
137
+ applicationRef = moduleRef.injector.get(ApplicationRef);
138
+ } else {
139
+ applicationRef = await bootstrap({
140
+ platformRef
141
+ });
142
+ }
143
+ await applicationRef.whenStable();
144
+ const envInjector = applicationRef.injector;
145
+ const routerIsProvided = !!envInjector.get(ActivatedRoute, null);
146
+ const router = envInjector.get(Router);
147
+ const lastSuccessfulNavigation = router.lastSuccessfulNavigation();
148
+ if (!routerIsProvided) {
149
+ hasNavigationError = false;
150
+ } else if (lastSuccessfulNavigation) {
151
+ hasNavigationError = false;
152
+ const {
153
+ pathname,
154
+ search,
155
+ hash
156
+ } = envInjector.get(PlatformLocation);
157
+ const finalUrl = [stripTrailingSlash(pathname), search, hash].join('');
158
+ if (urlToRender.href !== new URL(finalUrl, urlToRender.origin).href) {
159
+ redirectTo = finalUrl;
160
+ }
399
161
  }
162
+ return {
163
+ hasNavigationError,
164
+ redirectTo,
165
+ content: () => new Promise((resolve, reject) => {
166
+ setTimeout(() => {
167
+ _renderInternal(platformRef, applicationRef).then(resolve).catch(reject).finally(() => void asyncDestroyPlatform(platformRef));
168
+ }, 0);
169
+ })
170
+ };
171
+ } catch (error) {
172
+ await asyncDestroyPlatform(platformRef);
173
+ throw error;
174
+ } finally {
175
+ if (hasNavigationError || redirectTo) {
176
+ void asyncDestroyPlatform(platformRef);
177
+ }
178
+ }
400
179
  }
401
- /**
402
- * Type guard to determine if a given value is an Angular module.
403
- * Angular modules are identified by the presence of the `ɵmod` static property.
404
- * This function helps distinguish between Angular modules and bootstrap functions.
405
- *
406
- * @param value - The value to be checked.
407
- * @returns True if the value is an Angular module (i.e., it has the `ɵmod` property), false otherwise.
408
- */
409
180
  function isNgModule(value) {
410
- return 'ɵmod' in value;
181
+ return 'ɵmod' in value;
411
182
  }
412
- /**
413
- * Gracefully destroys the application in a macrotask, allowing pending promises to resolve
414
- * and surfacing any potential errors to the user.
415
- *
416
- * @param platformRef - The platform reference to be destroyed.
417
- */
418
183
  function asyncDestroyPlatform(platformRef) {
419
- return new Promise((resolve) => {
420
- setTimeout(() => {
421
- if (!platformRef.destroyed) {
422
- platformRef.destroy();
423
- }
424
- resolve();
425
- }, 0);
426
- });
184
+ return new Promise(resolve => {
185
+ setTimeout(() => {
186
+ if (!platformRef.destroyed) {
187
+ platformRef.destroy();
188
+ }
189
+ resolve();
190
+ }, 0);
191
+ });
427
192
  }
428
193
 
429
- /**
430
- * Creates a promise that resolves with the result of the provided `promise` or rejects with an
431
- * `AbortError` if the `AbortSignal` is triggered before the promise resolves.
432
- *
433
- * @param promise - The promise to monitor for completion.
434
- * @param signal - An `AbortSignal` used to monitor for an abort event. If the signal is aborted,
435
- * the returned promise will reject.
436
- * @param errorMessagePrefix - A custom message prefix to include in the error message when the operation is aborted.
437
- * @returns A promise that either resolves with the value of the provided `promise` or rejects with
438
- * an `AbortError` if the `AbortSignal` is triggered.
439
- *
440
- * @throws {AbortError} If the `AbortSignal` is triggered before the `promise` resolves.
441
- */
442
194
  function promiseWithAbort(promise, signal, errorMessagePrefix) {
443
- return new Promise((resolve, reject) => {
444
- const abortHandler = () => {
445
- reject(new DOMException(`${errorMessagePrefix} was aborted.\n${signal.reason}`, 'AbortError'));
446
- };
447
- // Check for abort signal
448
- if (signal.aborted) {
449
- abortHandler();
450
- return;
451
- }
452
- signal.addEventListener('abort', abortHandler, { once: true });
453
- promise
454
- .then(resolve)
455
- .catch(reject)
456
- .finally(() => {
457
- signal.removeEventListener('abort', abortHandler);
458
- });
195
+ return new Promise((resolve, reject) => {
196
+ const abortHandler = () => {
197
+ reject(new DOMException(`${errorMessagePrefix} was aborted.\n${signal.reason}`, 'AbortError'));
198
+ };
199
+ if (signal.aborted) {
200
+ abortHandler();
201
+ return;
202
+ }
203
+ signal.addEventListener('abort', abortHandler, {
204
+ once: true
205
+ });
206
+ promise.then(resolve).catch(reject).finally(() => {
207
+ signal.removeEventListener('abort', abortHandler);
459
208
  });
209
+ });
460
210
  }
461
211
 
462
- /**
463
- * The internal path used for the app shell route.
464
- * @internal
465
- */
466
212
  const APP_SHELL_ROUTE = 'ng-app-shell';
467
- /**
468
- * Identifies a particular kind of `ServerRenderingFeatureKind`.
469
- * @see {@link ServerRenderingFeature}
470
- */
471
213
  var ServerRenderingFeatureKind;
472
214
  (function (ServerRenderingFeatureKind) {
473
- ServerRenderingFeatureKind[ServerRenderingFeatureKind["AppShell"] = 0] = "AppShell";
474
- ServerRenderingFeatureKind[ServerRenderingFeatureKind["ServerRoutes"] = 1] = "ServerRoutes";
215
+ ServerRenderingFeatureKind[ServerRenderingFeatureKind["AppShell"] = 0] = "AppShell";
216
+ ServerRenderingFeatureKind[ServerRenderingFeatureKind["ServerRoutes"] = 1] = "ServerRoutes";
475
217
  })(ServerRenderingFeatureKind || (ServerRenderingFeatureKind = {}));
476
- /**
477
- * Different rendering modes for server routes.
478
- * @see {@link withRoutes}
479
- * @see {@link ServerRoute}
480
- */
481
218
  var RenderMode;
482
219
  (function (RenderMode) {
483
- /** Server-Side Rendering (SSR) mode, where content is rendered on the server for each request. */
484
- RenderMode[RenderMode["Server"] = 0] = "Server";
485
- /** Client-Side Rendering (CSR) mode, where content is rendered on the client side in the browser. */
486
- RenderMode[RenderMode["Client"] = 1] = "Client";
487
- /** Static Site Generation (SSG) mode, where content is pre-rendered at build time and served as static files. */
488
- RenderMode[RenderMode["Prerender"] = 2] = "Prerender";
220
+ RenderMode[RenderMode["Server"] = 0] = "Server";
221
+ RenderMode[RenderMode["Client"] = 1] = "Client";
222
+ RenderMode[RenderMode["Prerender"] = 2] = "Prerender";
489
223
  })(RenderMode || (RenderMode = {}));
490
- /**
491
- * Defines the fallback strategies for Static Site Generation (SSG) routes when a pre-rendered path is not available.
492
- * This is particularly relevant for routes with parameterized URLs where some paths might not be pre-rendered at build time.
493
- * @see {@link ServerRoutePrerenderWithParams}
494
- */
495
224
  var PrerenderFallback;
496
225
  (function (PrerenderFallback) {
497
- /**
498
- * Fallback to Server-Side Rendering (SSR) if the pre-rendered path is not available.
499
- * This strategy dynamically generates the page on the server at request time.
500
- */
501
- PrerenderFallback[PrerenderFallback["Server"] = 0] = "Server";
502
- /**
503
- * Fallback to Client-Side Rendering (CSR) if the pre-rendered path is not available.
504
- * This strategy allows the page to be rendered on the client side.
505
- */
506
- PrerenderFallback[PrerenderFallback["Client"] = 1] = "Client";
507
- /**
508
- * No fallback; if the path is not pre-rendered, the server will not handle the request.
509
- * This means the application will not provide any response for paths that are not pre-rendered.
510
- */
511
- PrerenderFallback[PrerenderFallback["None"] = 2] = "None";
226
+ PrerenderFallback[PrerenderFallback["Server"] = 0] = "Server";
227
+ PrerenderFallback[PrerenderFallback["Client"] = 1] = "Client";
228
+ PrerenderFallback[PrerenderFallback["None"] = 2] = "None";
512
229
  })(PrerenderFallback || (PrerenderFallback = {}));
513
- /**
514
- * Token for providing the server routes configuration.
515
- * @internal
516
- */
517
230
  const SERVER_ROUTES_CONFIG = new InjectionToken('SERVER_ROUTES_CONFIG');
518
- /**
519
- * Configures server-side routing for the application.
520
- *
521
- * This function registers an array of `ServerRoute` definitions, enabling server-side rendering
522
- * for specific URL paths. These routes are used to pre-render content on the server, improving
523
- * initial load performance and SEO.
524
- *
525
- * @param routes - An array of `ServerRoute` objects, each defining a server-rendered route.
526
- * @returns A `ServerRenderingFeature` object configuring server-side routes.
527
- *
528
- * @example
529
- * ```ts
530
- * import { provideServerRendering, withRoutes, ServerRoute, RenderMode } from '@angular/ssr';
531
- *
532
- * const serverRoutes: ServerRoute[] = [
533
- * {
534
- * path: '', // This renders the "/" route on the client (CSR)
535
- * renderMode: RenderMode.Client,
536
- * },
537
- * {
538
- * path: 'about', // This page is static, so we prerender it (SSG)
539
- * renderMode: RenderMode.Prerender,
540
- * },
541
- * {
542
- * path: 'profile', // This page requires user-specific data, so we use SSR
543
- * renderMode: RenderMode.Server,
544
- * },
545
- * {
546
- * path: '**', // All other routes will be rendered on the server (SSR)
547
- * renderMode: RenderMode.Server,
548
- * },
549
- * ];
550
- *
551
- * provideServerRendering(withRoutes(serverRoutes));
552
- * ```
553
- *
554
- * @see {@link provideServerRendering}
555
- * @see {@link ServerRoute}
556
- */
557
231
  function withRoutes(routes) {
558
- const config = { routes };
559
- return {
560
- ɵkind: ServerRenderingFeatureKind.ServerRoutes,
561
- ɵproviders: [
562
- {
563
- provide: SERVER_ROUTES_CONFIG,
564
- useValue: config,
565
- },
566
- ],
567
- };
232
+ const config = {
233
+ routes
234
+ };
235
+ return {
236
+ ɵkind: ServerRenderingFeatureKind.ServerRoutes,
237
+ ɵproviders: [{
238
+ provide: SERVER_ROUTES_CONFIG,
239
+ useValue: config
240
+ }]
241
+ };
568
242
  }
569
- /**
570
- * Configures the shell of the application.
571
- *
572
- * The app shell is a minimal, static HTML page that is served immediately, while the
573
- * full Angular application loads in the background. This improves perceived performance
574
- * by providing instant feedback to the user.
575
- *
576
- * This function configures the app shell route, which serves the provided component for
577
- * requests that do not match any defined server routes.
578
- *
579
- * @param component - The Angular component to render for the app shell. Can be a direct
580
- * component type or a dynamic import function.
581
- * @returns A `ServerRenderingFeature` object configuring the app shell.
582
- *
583
- * @example
584
- * ```ts
585
- * import { provideServerRendering, withAppShell, withRoutes } from '@angular/ssr';
586
- * import { AppShellComponent } from './app-shell.component';
587
- *
588
- * provideServerRendering(
589
- * withRoutes(serverRoutes),
590
- * withAppShell(AppShellComponent)
591
- * );
592
- * ```
593
- *
594
- * @example
595
- * ```ts
596
- * import { provideServerRendering, withAppShell, withRoutes } from '@angular/ssr';
597
- *
598
- * provideServerRendering(
599
- * withRoutes(serverRoutes),
600
- * withAppShell(() =>
601
- * import('./app-shell.component').then((m) => m.AppShellComponent)
602
- * )
603
- * );
604
- * ```
605
- *
606
- * @see {@link provideServerRendering}
607
- * @see {@link https://angular.dev/ecosystem/service-workers/app-shell App shell pattern on Angular.dev}
608
- */
609
243
  function withAppShell(component) {
610
- const routeConfig = {
611
- path: APP_SHELL_ROUTE,
612
- };
613
- if ('ɵcmp' in component) {
614
- routeConfig.component = component;
615
- }
616
- else {
617
- routeConfig.loadComponent = component;
618
- }
619
- return {
620
- ɵkind: ServerRenderingFeatureKind.AppShell,
621
- ɵproviders: [
622
- {
623
- provide: ROUTES,
624
- useValue: routeConfig,
625
- multi: true,
626
- },
627
- provideEnvironmentInitializer(() => {
628
- const config = inject(SERVER_ROUTES_CONFIG);
629
- config.appShellRoute = APP_SHELL_ROUTE;
630
- }),
631
- ],
632
- };
244
+ const routeConfig = {
245
+ path: APP_SHELL_ROUTE
246
+ };
247
+ if ('ɵcmp' in component) {
248
+ routeConfig.component = component;
249
+ } else {
250
+ routeConfig.loadComponent = component;
251
+ }
252
+ return {
253
+ ɵkind: ServerRenderingFeatureKind.AppShell,
254
+ ɵproviders: [{
255
+ provide: ROUTES,
256
+ useValue: routeConfig,
257
+ multi: true
258
+ }, provideEnvironmentInitializer(() => {
259
+ const config = inject(SERVER_ROUTES_CONFIG);
260
+ config.appShellRoute = APP_SHELL_ROUTE;
261
+ })]
262
+ };
633
263
  }
634
- /**
635
- * Configures server-side rendering for an Angular application.
636
- *
637
- * This function sets up the necessary providers for server-side rendering, including
638
- * support for server routes and app shell. It combines features configured using
639
- * `withRoutes` and `withAppShell` to provide a comprehensive server-side rendering setup.
640
- *
641
- * @param features - Optional features to configure additional server rendering behaviors.
642
- * @returns An `EnvironmentProviders` instance with the server-side rendering configuration.
643
- *
644
- * @example
645
- * Basic example of how you can enable server-side rendering in your application
646
- * when using the `bootstrapApplication` function:
647
- *
648
- * ```ts
649
- * import { bootstrapApplication, BootstrapContext } from '@angular/platform-browser';
650
- * import { provideServerRendering, withRoutes, withAppShell } from '@angular/ssr';
651
- * import { AppComponent } from './app/app.component';
652
- * import { SERVER_ROUTES } from './app/app.server.routes';
653
- * import { AppShellComponent } from './app/app-shell.component';
654
- *
655
- * const bootstrap = (context: BootstrapContext) =>
656
- * bootstrapApplication(AppComponent, {
657
- * providers: [
658
- * provideServerRendering(
659
- * withRoutes(SERVER_ROUTES),
660
- * withAppShell(AppShellComponent),
661
- * ),
662
- * ],
663
- * }, context);
664
- *
665
- * export default bootstrap;
666
- * ```
667
- * @see {@link withRoutes} configures server-side routing
668
- * @see {@link withAppShell} configures the application shell
669
- */
670
264
  function provideServerRendering(...features) {
671
- let hasAppShell = false;
672
- let hasServerRoutes = false;
673
- const providers = [provideServerRendering$1()];
674
- for (const { ɵkind, ɵproviders } of features) {
675
- hasAppShell ||= ɵkind === ServerRenderingFeatureKind.AppShell;
676
- hasServerRoutes ||= ɵkind === ServerRenderingFeatureKind.ServerRoutes;
677
- providers.push(...ɵproviders);
678
- }
679
- if (!hasServerRoutes && hasAppShell) {
680
- throw new Error(`Configuration error: found 'withAppShell()' without 'withRoutes()' in the same call to 'provideServerRendering()'.` +
681
- `The 'withAppShell()' function requires 'withRoutes()' to be used.`);
682
- }
683
- return makeEnvironmentProviders(providers);
265
+ let hasAppShell = false;
266
+ let hasServerRoutes = false;
267
+ const providers = [provideServerRendering$1()];
268
+ for (const {
269
+ ɵkind,
270
+ ɵproviders
271
+ } of features) {
272
+ hasAppShell ||= ɵkind === ServerRenderingFeatureKind.AppShell;
273
+ hasServerRoutes ||= ɵkind === ServerRenderingFeatureKind.ServerRoutes;
274
+ providers.push(...ɵproviders);
275
+ }
276
+ if (!hasServerRoutes && hasAppShell) {
277
+ throw new Error(`Configuration error: found 'withAppShell()' without 'withRoutes()' in the same call to 'provideServerRendering()'.` + `The 'withAppShell()' function requires 'withRoutes()' to be used.`);
278
+ }
279
+ return makeEnvironmentProviders(providers);
684
280
  }
685
281
 
686
- /**
687
- * A route tree implementation that supports efficient route matching, including support for wildcard routes.
688
- * This structure is useful for organizing and retrieving routes in a hierarchical manner,
689
- * enabling complex routing scenarios with nested paths.
690
- *
691
- * @typeParam AdditionalMetadata - Type of additional metadata that can be associated with route nodes.
692
- */
693
282
  class RouteTree {
694
- /**
695
- * The root node of the route tree.
696
- * All routes are stored and accessed relative to this root node.
697
- */
698
- root = this.createEmptyRouteTreeNode();
699
- /**
700
- * Inserts a new route into the route tree.
701
- * The route is broken down into segments, and each segment is added to the tree.
702
- * Parameterized segments (e.g., :id) are normalized to wildcards (*) for matching purposes.
703
- *
704
- * @param route - The route path to insert into the tree.
705
- * @param metadata - Metadata associated with the route, excluding the route path itself.
706
- */
707
- insert(route, metadata) {
708
- let node = this.root;
709
- const segments = this.getPathSegments(route);
710
- const normalizedSegments = [];
711
- for (const segment of segments) {
712
- // Replace parameterized segments (e.g., :id) with a wildcard (*) for matching
713
- const normalizedSegment = segment[0] === ':' ? '*' : segment;
714
- let childNode = node.children.get(normalizedSegment);
715
- if (!childNode) {
716
- childNode = this.createEmptyRouteTreeNode();
717
- node.children.set(normalizedSegment, childNode);
718
- }
719
- node = childNode;
720
- normalizedSegments.push(normalizedSegment);
721
- }
722
- // At the leaf node, store the full route and its associated metadata
723
- node.metadata = {
724
- ...metadata,
725
- route: addLeadingSlash(normalizedSegments.join('/')),
726
- };
727
- }
728
- /**
729
- * Matches a given route against the route tree and returns the best matching route's metadata.
730
- * The best match is determined by the lowest insertion index, meaning the earliest defined route
731
- * takes precedence.
732
- *
733
- * @param route - The route path to match against the route tree.
734
- * @returns The metadata of the best matching route or `undefined` if no match is found.
735
- */
736
- match(route) {
737
- const segments = this.getPathSegments(route);
738
- return this.traverseBySegments(segments)?.metadata;
739
- }
740
- /**
741
- * Converts the route tree into a serialized format representation.
742
- * This method converts the route tree into an array of metadata objects that describe the structure of the tree.
743
- * The array represents the routes in a nested manner where each entry includes the route and its associated metadata.
744
- *
745
- * @returns An array of `RouteTreeNodeMetadata` objects representing the route tree structure.
746
- * Each object includes the `route` and associated metadata of a route.
747
- */
748
- toObject() {
749
- return Array.from(this.traverse());
750
- }
751
- /**
752
- * Constructs a `RouteTree` from an object representation.
753
- * This method is used to recreate a `RouteTree` instance from an array of metadata objects.
754
- * The array should be in the format produced by `toObject`, allowing for the reconstruction of the route tree
755
- * with the same routes and metadata.
756
- *
757
- * @param value - An array of `RouteTreeNodeMetadata` objects that represent the serialized format of the route tree.
758
- * Each object should include a `route` and its associated metadata.
759
- * @returns A new `RouteTree` instance constructed from the provided metadata objects.
760
- */
761
- static fromObject(value) {
762
- const tree = new RouteTree();
763
- for (const { route, ...metadata } of value) {
764
- tree.insert(route, metadata);
765
- }
766
- return tree;
767
- }
768
- /**
769
- * A generator function that recursively traverses the route tree and yields the metadata of each node.
770
- * This allows for easy and efficient iteration over all nodes in the tree.
771
- *
772
- * @param node - The current node to start the traversal from. Defaults to the root node of the tree.
773
- */
774
- *traverse(node = this.root) {
775
- if (node.metadata) {
776
- yield node.metadata;
777
- }
778
- for (const childNode of node.children.values()) {
779
- yield* this.traverse(childNode);
780
- }
781
- }
782
- /**
783
- * Extracts the path segments from a given route string.
784
- *
785
- * @param route - The route string from which to extract segments.
786
- * @returns An array of path segments.
787
- */
788
- getPathSegments(route) {
789
- return route.split('/').filter(Boolean);
790
- }
791
- /**
792
- * Recursively traverses the route tree from a given node, attempting to match the remaining route segments.
793
- * If the node is a leaf node (no more segments to match) and contains metadata, the node is yielded.
794
- *
795
- * This function prioritizes exact segment matches first, followed by wildcard matches (`*`),
796
- * and finally deep wildcard matches (`**`) that consume all segments.
797
- *
798
- * @param segments - The array of route path segments to match against the route tree.
799
- * @param node - The current node in the route tree to start traversal from. Defaults to the root node.
800
- * @param currentIndex - The index of the segment in `remainingSegments` currently being matched.
801
- * Defaults to `0` (the first segment).
802
- *
803
- * @returns The node that best matches the remaining segments or `undefined` if no match is found.
804
- */
805
- traverseBySegments(segments, node = this.root, currentIndex = 0) {
806
- if (currentIndex >= segments.length) {
807
- return node.metadata ? node : node.children.get('**');
808
- }
809
- if (!node.children.size) {
810
- return undefined;
811
- }
812
- const segment = segments[currentIndex];
813
- // 1. Attempt exact match with the current segment.
814
- const exactMatch = node.children.get(segment);
815
- if (exactMatch) {
816
- const match = this.traverseBySegments(segments, exactMatch, currentIndex + 1);
817
- if (match) {
818
- return match;
819
- }
820
- }
821
- // 2. Attempt wildcard match ('*').
822
- const wildcardMatch = node.children.get('*');
823
- if (wildcardMatch) {
824
- const match = this.traverseBySegments(segments, wildcardMatch, currentIndex + 1);
825
- if (match) {
826
- return match;
827
- }
828
- }
829
- // 3. Attempt double wildcard match ('**').
830
- return node.children.get('**');
831
- }
832
- /**
833
- * Creates an empty route tree node.
834
- * This helper function is used during the tree construction.
835
- *
836
- * @returns A new, empty route tree node.
837
- */
838
- createEmptyRouteTreeNode() {
839
- return {
840
- children: new Map(),
841
- };
842
- }
283
+ root = this.createEmptyRouteTreeNode();
284
+ insert(route, metadata) {
285
+ let node = this.root;
286
+ const segments = this.getPathSegments(route);
287
+ const normalizedSegments = [];
288
+ for (const segment of segments) {
289
+ const normalizedSegment = segment[0] === ':' ? '*' : segment;
290
+ let childNode = node.children.get(normalizedSegment);
291
+ if (!childNode) {
292
+ childNode = this.createEmptyRouteTreeNode();
293
+ node.children.set(normalizedSegment, childNode);
294
+ }
295
+ node = childNode;
296
+ normalizedSegments.push(normalizedSegment);
297
+ }
298
+ node.metadata = {
299
+ ...metadata,
300
+ route: addLeadingSlash(normalizedSegments.join('/'))
301
+ };
302
+ }
303
+ match(route) {
304
+ const segments = this.getPathSegments(route);
305
+ return this.traverseBySegments(segments)?.metadata;
306
+ }
307
+ toObject() {
308
+ return Array.from(this.traverse());
309
+ }
310
+ static fromObject(value) {
311
+ const tree = new RouteTree();
312
+ for (const {
313
+ route,
314
+ ...metadata
315
+ } of value) {
316
+ tree.insert(route, metadata);
317
+ }
318
+ return tree;
319
+ }
320
+ *traverse(node = this.root) {
321
+ if (node.metadata) {
322
+ yield node.metadata;
323
+ }
324
+ for (const childNode of node.children.values()) {
325
+ yield* this.traverse(childNode);
326
+ }
327
+ }
328
+ getPathSegments(route) {
329
+ return route.split('/').filter(Boolean);
330
+ }
331
+ traverseBySegments(segments, node = this.root, currentIndex = 0) {
332
+ if (currentIndex >= segments.length) {
333
+ return node.metadata ? node : node.children.get('**');
334
+ }
335
+ if (!node.children.size) {
336
+ return undefined;
337
+ }
338
+ const segment = segments[currentIndex];
339
+ const exactMatch = node.children.get(segment);
340
+ if (exactMatch) {
341
+ const match = this.traverseBySegments(segments, exactMatch, currentIndex + 1);
342
+ if (match) {
343
+ return match;
344
+ }
345
+ }
346
+ const wildcardMatch = node.children.get('*');
347
+ if (wildcardMatch) {
348
+ const match = this.traverseBySegments(segments, wildcardMatch, currentIndex + 1);
349
+ if (match) {
350
+ return match;
351
+ }
352
+ }
353
+ return node.children.get('**');
354
+ }
355
+ createEmptyRouteTreeNode() {
356
+ return {
357
+ children: new Map()
358
+ };
359
+ }
843
360
  }
844
361
 
845
- /**
846
- * The maximum number of module preload link elements that should be added for
847
- * initial scripts.
848
- */
849
362
  const MODULE_PRELOAD_MAX = 10;
850
- /**
851
- * Regular expression to match a catch-all route pattern in a URL path,
852
- * specifically one that ends with '/**'.
853
- */
854
363
  const CATCH_ALL_REGEXP = /\/(\*\*)$/;
855
- /**
856
- * Regular expression to match segments preceded by a colon in a string.
857
- */
858
364
  const URL_PARAMETER_REGEXP = /(?<!\\):([^/]+)/g;
859
- /**
860
- * An set of HTTP status codes that are considered valid for redirect responses.
861
- */
862
365
  const VALID_REDIRECT_RESPONSE_CODES = new Set([301, 302, 303, 307, 308]);
863
- /**
864
- * Handles a single route within the route tree and yields metadata or errors.
865
- *
866
- * @param options - Configuration options for handling the route.
867
- * @returns An async iterable iterator yielding `RouteTreeNodeMetadata` or an error object.
868
- */
869
366
  async function* handleRoute(options) {
870
- try {
871
- const { metadata, currentRoutePath, route, compiler, parentInjector, serverConfigRouteTree, entryPointToBrowserMapping, invokeGetPrerenderParams, includePrerenderFallbackRoutes, } = options;
872
- const { redirectTo, loadChildren, loadComponent, children, ɵentryName } = route;
873
- if (ɵentryName && loadComponent) {
874
- appendPreloadToMetadata(ɵentryName, entryPointToBrowserMapping, metadata);
875
- }
876
- if (metadata.renderMode === RenderMode.Prerender) {
877
- yield* handleSSGRoute(serverConfigRouteTree, typeof redirectTo === 'string' ? redirectTo : undefined, metadata, parentInjector, invokeGetPrerenderParams, includePrerenderFallbackRoutes);
878
- }
879
- else if (redirectTo !== undefined) {
880
- if (metadata.status && !VALID_REDIRECT_RESPONSE_CODES.has(metadata.status)) {
881
- yield {
882
- error: `The '${metadata.status}' status code is not a valid redirect response code. ` +
883
- `Please use one of the following redirect response codes: ${[...VALID_REDIRECT_RESPONSE_CODES.values()].join(', ')}.`,
884
- };
885
- }
886
- else if (typeof redirectTo === 'string') {
887
- yield {
888
- ...metadata,
889
- redirectTo: resolveRedirectTo(metadata.route, redirectTo),
890
- };
891
- }
892
- else {
893
- yield metadata;
894
- }
895
- }
896
- else {
897
- yield metadata;
898
- }
899
- // Recursively process child routes
900
- if (children?.length) {
901
- yield* traverseRoutesConfig({
902
- ...options,
903
- routes: children,
904
- parentRoute: currentRoutePath,
905
- parentPreloads: metadata.preload,
906
- });
907
- }
908
- // Load and process lazy-loaded child routes
909
- if (loadChildren) {
910
- if (ɵentryName) {
911
- appendPreloadToMetadata(ɵentryName, entryPointToBrowserMapping, metadata);
912
- }
913
- const routeInjector = route.providers
914
- ? createEnvironmentInjector(route.providers, parentInjector.get(EnvironmentInjector), `Route: ${route.path}`)
915
- : parentInjector;
916
- // TODO(alanagius): replace all the below when FW 21.0.0-next.7 is out.
917
- const loadChildrenHelperResult = _loadChildren(route, compiler, routeInjector);
918
- const loadedChildRoutes = await ('then' in loadChildrenHelperResult
919
- ? loadChildrenHelperResult
920
- : loadChildrenHelperResult.toPromise());
921
- if (loadedChildRoutes) {
922
- const { routes: childRoutes, injector = routeInjector } = loadedChildRoutes;
923
- yield* traverseRoutesConfig({
924
- ...options,
925
- routes: childRoutes,
926
- parentInjector: injector,
927
- parentRoute: currentRoutePath,
928
- parentPreloads: metadata.preload,
929
- });
930
- }
931
- }
932
- }
933
- catch (error) {
367
+ try {
368
+ const {
369
+ metadata,
370
+ currentRoutePath,
371
+ route,
372
+ compiler,
373
+ parentInjector,
374
+ serverConfigRouteTree,
375
+ entryPointToBrowserMapping,
376
+ invokeGetPrerenderParams,
377
+ includePrerenderFallbackRoutes
378
+ } = options;
379
+ const {
380
+ redirectTo,
381
+ loadChildren,
382
+ loadComponent,
383
+ children,
384
+ ɵentryName
385
+ } = route;
386
+ if (ɵentryName && loadComponent) {
387
+ appendPreloadToMetadata(ɵentryName, entryPointToBrowserMapping, metadata);
388
+ }
389
+ if (metadata.renderMode === RenderMode.Prerender) {
390
+ yield* handleSSGRoute(serverConfigRouteTree, typeof redirectTo === 'string' ? redirectTo : undefined, metadata, parentInjector, invokeGetPrerenderParams, includePrerenderFallbackRoutes);
391
+ } else if (redirectTo !== undefined) {
392
+ if (metadata.status && !VALID_REDIRECT_RESPONSE_CODES.has(metadata.status)) {
393
+ yield {
394
+ 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(', ')}.`
395
+ };
396
+ } else if (typeof redirectTo === 'string') {
934
397
  yield {
935
- error: `Error in handleRoute for '${options.currentRoutePath}': ${error.message}`,
398
+ ...metadata,
399
+ redirectTo: resolveRedirectTo(metadata.route, redirectTo)
936
400
  };
401
+ } else {
402
+ yield metadata;
403
+ }
404
+ } else {
405
+ yield metadata;
406
+ }
407
+ if (children?.length) {
408
+ yield* traverseRoutesConfig({
409
+ ...options,
410
+ routes: children,
411
+ parentRoute: currentRoutePath,
412
+ parentPreloads: metadata.preload
413
+ });
414
+ }
415
+ if (loadChildren) {
416
+ if (ɵentryName) {
417
+ appendPreloadToMetadata(ɵentryName, entryPointToBrowserMapping, metadata);
418
+ }
419
+ const routeInjector = route.providers ? createEnvironmentInjector(route.providers, parentInjector.get(EnvironmentInjector), `Route: ${route.path}`) : parentInjector;
420
+ const loadedChildRoutes = await _loadChildren(route, compiler, routeInjector);
421
+ if (loadedChildRoutes) {
422
+ const {
423
+ routes: childRoutes,
424
+ injector = routeInjector
425
+ } = loadedChildRoutes;
426
+ yield* traverseRoutesConfig({
427
+ ...options,
428
+ routes: childRoutes,
429
+ parentInjector: injector,
430
+ parentRoute: currentRoutePath,
431
+ parentPreloads: metadata.preload
432
+ });
433
+ }
937
434
  }
435
+ } catch (error) {
436
+ yield {
437
+ error: `Error in handleRoute for '${options.currentRoutePath}': ${error.message}`
438
+ };
439
+ }
938
440
  }
939
- /**
940
- * Traverses an array of route configurations to generate route tree node metadata.
941
- *
942
- * This function processes each route and its children, handling redirects, SSG (Static Site Generation) settings,
943
- * and lazy-loaded routes. It yields route metadata for each route and its potential variants.
944
- *
945
- * @param options - The configuration options for traversing routes.
946
- * @returns An async iterable iterator yielding either route tree node metadata or an error object with an error message.
947
- */
948
441
  async function* traverseRoutesConfig(options) {
949
- const { routes: routeConfigs, parentPreloads, parentRoute, serverConfigRouteTree } = options;
950
- for (const route of routeConfigs) {
951
- const { matcher, path = matcher ? '**' : '' } = route;
952
- const currentRoutePath = joinUrlParts(parentRoute, path);
953
- if (matcher && serverConfigRouteTree) {
954
- let foundMatch = false;
955
- for (const matchedMetaData of serverConfigRouteTree.traverse()) {
956
- if (!matchedMetaData.route.startsWith(currentRoutePath)) {
957
- continue;
958
- }
959
- foundMatch = true;
960
- matchedMetaData.presentInClientRouter = true;
961
- if (matchedMetaData.renderMode === RenderMode.Prerender) {
962
- yield {
963
- error: `The route '${stripLeadingSlash(currentRoutePath)}' is set for prerendering but has a defined matcher. ` +
964
- `Routes with matchers cannot use prerendering. Please specify a different 'renderMode'.`,
965
- };
966
- continue;
967
- }
968
- yield* handleRoute({
969
- ...options,
970
- currentRoutePath,
971
- route,
972
- metadata: {
973
- ...matchedMetaData,
974
- preload: parentPreloads,
975
- route: matchedMetaData.route,
976
- presentInClientRouter: undefined,
977
- },
978
- });
979
- }
980
- if (!foundMatch) {
981
- yield {
982
- error: `The route '${stripLeadingSlash(currentRoutePath)}' has a defined matcher but does not ` +
983
- 'match any route in the server routing configuration. Please ensure this route is added to the server routing configuration.',
984
- };
985
- }
986
- continue;
987
- }
988
- let matchedMetaData;
989
- if (serverConfigRouteTree) {
990
- matchedMetaData = serverConfigRouteTree.match(currentRoutePath);
991
- if (!matchedMetaData) {
992
- yield {
993
- error: `The '${stripLeadingSlash(currentRoutePath)}' route does not match any route defined in the server routing configuration. ` +
994
- 'Please ensure this route is added to the server routing configuration.',
995
- };
996
- continue;
997
- }
998
- matchedMetaData.presentInClientRouter = true;
442
+ const {
443
+ routes: routeConfigs,
444
+ parentPreloads,
445
+ parentRoute,
446
+ serverConfigRouteTree
447
+ } = options;
448
+ for (const route of routeConfigs) {
449
+ const {
450
+ matcher,
451
+ path = matcher ? '**' : ''
452
+ } = route;
453
+ const currentRoutePath = joinUrlParts(parentRoute, path);
454
+ if (matcher && serverConfigRouteTree) {
455
+ let foundMatch = false;
456
+ for (const matchedMetaData of serverConfigRouteTree.traverse()) {
457
+ if (!matchedMetaData.route.startsWith(currentRoutePath)) {
458
+ continue;
459
+ }
460
+ foundMatch = true;
461
+ matchedMetaData.presentInClientRouter = true;
462
+ if (matchedMetaData.renderMode === RenderMode.Prerender) {
463
+ yield {
464
+ error: `The route '${stripLeadingSlash(currentRoutePath)}' is set for prerendering but has a defined matcher. ` + `Routes with matchers cannot use prerendering. Please specify a different 'renderMode'.`
465
+ };
466
+ continue;
999
467
  }
1000
468
  yield* handleRoute({
1001
- ...options,
1002
- metadata: {
1003
- renderMode: RenderMode.Prerender,
1004
- ...matchedMetaData,
1005
- preload: parentPreloads,
1006
- // Match Angular router behavior
1007
- // ['one', 'two', ''] -> 'one/two/'
1008
- // ['one', 'two', 'three'] -> 'one/two/three'
1009
- route: path === '' ? addTrailingSlash(currentRoutePath) : currentRoutePath,
1010
- presentInClientRouter: undefined,
1011
- },
1012
- currentRoutePath,
1013
- route,
469
+ ...options,
470
+ currentRoutePath,
471
+ route,
472
+ metadata: {
473
+ ...matchedMetaData,
474
+ preload: parentPreloads,
475
+ route: matchedMetaData.route,
476
+ presentInClientRouter: undefined
477
+ }
1014
478
  });
479
+ }
480
+ if (!foundMatch) {
481
+ yield {
482
+ error: `The route '${stripLeadingSlash(currentRoutePath)}' has a defined matcher but does not ` + 'match any route in the server routing configuration. Please ensure this route is added to the server routing configuration.'
483
+ };
484
+ }
485
+ continue;
1015
486
  }
487
+ let matchedMetaData;
488
+ if (serverConfigRouteTree) {
489
+ matchedMetaData = serverConfigRouteTree.match(currentRoutePath);
490
+ if (!matchedMetaData) {
491
+ yield {
492
+ error: `The '${stripLeadingSlash(currentRoutePath)}' route does not match any route defined in the server routing configuration. ` + 'Please ensure this route is added to the server routing configuration.'
493
+ };
494
+ continue;
495
+ }
496
+ matchedMetaData.presentInClientRouter = true;
497
+ }
498
+ yield* handleRoute({
499
+ ...options,
500
+ metadata: {
501
+ renderMode: RenderMode.Prerender,
502
+ ...matchedMetaData,
503
+ preload: parentPreloads,
504
+ route: path === '' ? addTrailingSlash(currentRoutePath) : currentRoutePath,
505
+ presentInClientRouter: undefined
506
+ },
507
+ currentRoutePath,
508
+ route
509
+ });
510
+ }
1016
511
  }
1017
- /**
1018
- * Appends preload information to the metadata object based on the specified entry-point and chunk mappings.
1019
- *
1020
- * This function extracts preload data for a given entry-point from the provided chunk mappings. It adds the
1021
- * corresponding browser bundles to the metadata's preload list, ensuring no duplicates and limiting the total
1022
- * preloads to a predefined maximum.
1023
- */
1024
512
  function appendPreloadToMetadata(entryName, entryPointToBrowserMapping, metadata) {
1025
- const existingPreloads = metadata.preload ?? [];
1026
- if (!entryPointToBrowserMapping || existingPreloads.length >= MODULE_PRELOAD_MAX) {
1027
- return;
1028
- }
1029
- const preload = entryPointToBrowserMapping[entryName];
1030
- if (!preload?.length) {
1031
- return;
1032
- }
1033
- // Merge existing preloads with new ones, ensuring uniqueness and limiting the total to the maximum allowed.
1034
- const combinedPreloads = new Set(existingPreloads);
1035
- for (const href of preload) {
1036
- combinedPreloads.add(href);
1037
- if (combinedPreloads.size === MODULE_PRELOAD_MAX) {
1038
- break;
1039
- }
1040
- }
1041
- metadata.preload = Array.from(combinedPreloads);
513
+ const existingPreloads = metadata.preload ?? [];
514
+ if (!entryPointToBrowserMapping || existingPreloads.length >= MODULE_PRELOAD_MAX) {
515
+ return;
516
+ }
517
+ const preload = entryPointToBrowserMapping[entryName];
518
+ if (!preload?.length) {
519
+ return;
520
+ }
521
+ const combinedPreloads = new Set(existingPreloads);
522
+ for (const href of preload) {
523
+ combinedPreloads.add(href);
524
+ if (combinedPreloads.size === MODULE_PRELOAD_MAX) {
525
+ break;
526
+ }
527
+ }
528
+ metadata.preload = Array.from(combinedPreloads);
1042
529
  }
1043
- /**
1044
- * Handles SSG (Static Site Generation) routes by invoking `getPrerenderParams` and yielding
1045
- * all parameterized paths, returning any errors encountered.
1046
- *
1047
- * @param serverConfigRouteTree - The tree representing the server's routing setup.
1048
- * @param redirectTo - Optional path to redirect to, if specified.
1049
- * @param metadata - The metadata associated with the route tree node.
1050
- * @param parentInjector - The dependency injection container for the parent route.
1051
- * @param invokeGetPrerenderParams - A flag indicating whether to invoke the `getPrerenderParams` function.
1052
- * @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result.
1053
- * @returns An async iterable iterator that yields route tree node metadata for each SSG path or errors.
1054
- */
1055
530
  async function* handleSSGRoute(serverConfigRouteTree, redirectTo, metadata, parentInjector, invokeGetPrerenderParams, includePrerenderFallbackRoutes) {
1056
- if (metadata.renderMode !== RenderMode.Prerender) {
1057
- throw new Error(`'handleSSGRoute' was called for a route which rendering mode is not prerender.`);
1058
- }
1059
- const { route: currentRoutePath, fallback, ...meta } = metadata;
1060
- const getPrerenderParams = 'getPrerenderParams' in meta ? meta.getPrerenderParams : undefined;
1061
- if ('getPrerenderParams' in meta) {
1062
- delete meta['getPrerenderParams'];
1063
- }
1064
- if (redirectTo !== undefined) {
1065
- meta.redirectTo = resolveRedirectTo(currentRoutePath, redirectTo);
531
+ if (metadata.renderMode !== RenderMode.Prerender) {
532
+ throw new Error(`'handleSSGRoute' was called for a route which rendering mode is not prerender.`);
533
+ }
534
+ const {
535
+ route: currentRoutePath,
536
+ fallback,
537
+ ...meta
538
+ } = metadata;
539
+ const getPrerenderParams = 'getPrerenderParams' in meta ? meta.getPrerenderParams : undefined;
540
+ if ('getPrerenderParams' in meta) {
541
+ delete meta['getPrerenderParams'];
542
+ }
543
+ if (redirectTo !== undefined) {
544
+ meta.redirectTo = resolveRedirectTo(currentRoutePath, redirectTo);
545
+ }
546
+ const isCatchAllRoute = CATCH_ALL_REGEXP.test(currentRoutePath);
547
+ if (isCatchAllRoute && !getPrerenderParams || !isCatchAllRoute && !URL_PARAMETER_REGEXP.test(currentRoutePath)) {
548
+ yield {
549
+ ...meta,
550
+ route: currentRoutePath
551
+ };
552
+ return;
553
+ }
554
+ if (invokeGetPrerenderParams) {
555
+ if (!getPrerenderParams) {
556
+ yield {
557
+ error: `The '${stripLeadingSlash(currentRoutePath)}' route uses prerendering and includes parameters, but 'getPrerenderParams' ` + `is missing. Please define 'getPrerenderParams' function for this route in your server routing configuration ` + `or specify a different 'renderMode'.`
558
+ };
559
+ return;
1066
560
  }
1067
- const isCatchAllRoute = CATCH_ALL_REGEXP.test(currentRoutePath);
1068
- if ((isCatchAllRoute && !getPrerenderParams) ||
1069
- (!isCatchAllRoute && !URL_PARAMETER_REGEXP.test(currentRoutePath))) {
1070
- // Route has no parameters
1071
- yield {
1072
- ...meta,
1073
- route: currentRoutePath,
1074
- };
1075
- return;
1076
- }
1077
- if (invokeGetPrerenderParams) {
1078
- if (!getPrerenderParams) {
1079
- yield {
1080
- error: `The '${stripLeadingSlash(currentRoutePath)}' route uses prerendering and includes parameters, but 'getPrerenderParams' ` +
1081
- `is missing. Please define 'getPrerenderParams' function for this route in your server routing configuration ` +
1082
- `or specify a different 'renderMode'.`,
1083
- };
1084
- return;
1085
- }
1086
- if (serverConfigRouteTree) {
1087
- // Automatically resolve dynamic parameters for nested routes.
1088
- const catchAllRoutePath = isCatchAllRoute
1089
- ? currentRoutePath
1090
- : joinUrlParts(currentRoutePath, '**');
1091
- const match = serverConfigRouteTree.match(catchAllRoutePath);
1092
- if (match && match.renderMode === RenderMode.Prerender && !('getPrerenderParams' in match)) {
1093
- serverConfigRouteTree.insert(catchAllRoutePath, {
1094
- ...match,
1095
- presentInClientRouter: true,
1096
- getPrerenderParams,
1097
- });
1098
- }
1099
- }
1100
- const parameters = await runInInjectionContext(parentInjector, () => getPrerenderParams());
1101
- try {
1102
- for (const params of parameters) {
1103
- const replacer = handlePrerenderParamsReplacement(params, currentRoutePath);
1104
- const routeWithResolvedParams = currentRoutePath
1105
- .replace(URL_PARAMETER_REGEXP, replacer)
1106
- .replace(CATCH_ALL_REGEXP, replacer);
1107
- yield {
1108
- ...meta,
1109
- route: routeWithResolvedParams,
1110
- redirectTo: redirectTo === undefined
1111
- ? undefined
1112
- : resolveRedirectTo(routeWithResolvedParams, redirectTo),
1113
- };
1114
- }
1115
- }
1116
- catch (error) {
1117
- yield { error: `${error.message}` };
1118
- return;
1119
- }
561
+ if (serverConfigRouteTree) {
562
+ const catchAllRoutePath = isCatchAllRoute ? currentRoutePath : joinUrlParts(currentRoutePath, '**');
563
+ const match = serverConfigRouteTree.match(catchAllRoutePath);
564
+ if (match && match.renderMode === RenderMode.Prerender && !('getPrerenderParams' in match)) {
565
+ serverConfigRouteTree.insert(catchAllRoutePath, {
566
+ ...match,
567
+ presentInClientRouter: true,
568
+ getPrerenderParams
569
+ });
570
+ }
1120
571
  }
1121
- // Handle fallback render modes
1122
- if (includePrerenderFallbackRoutes &&
1123
- (fallback !== PrerenderFallback.None || !invokeGetPrerenderParams)) {
572
+ const parameters = await runInInjectionContext(parentInjector, () => getPrerenderParams());
573
+ try {
574
+ for (const params of parameters) {
575
+ const replacer = handlePrerenderParamsReplacement(params, currentRoutePath);
576
+ const routeWithResolvedParams = currentRoutePath.replace(URL_PARAMETER_REGEXP, replacer).replace(CATCH_ALL_REGEXP, replacer);
1124
577
  yield {
1125
- ...meta,
1126
- route: currentRoutePath,
1127
- renderMode: fallback === PrerenderFallback.Client ? RenderMode.Client : RenderMode.Server,
578
+ ...meta,
579
+ route: routeWithResolvedParams,
580
+ redirectTo: redirectTo === undefined ? undefined : resolveRedirectTo(routeWithResolvedParams, redirectTo)
1128
581
  };
582
+ }
583
+ } catch (error) {
584
+ yield {
585
+ error: `${error.message}`
586
+ };
587
+ return;
1129
588
  }
589
+ }
590
+ if (includePrerenderFallbackRoutes && (fallback !== PrerenderFallback.None || !invokeGetPrerenderParams)) {
591
+ yield {
592
+ ...meta,
593
+ route: currentRoutePath,
594
+ renderMode: fallback === PrerenderFallback.Client ? RenderMode.Client : RenderMode.Server
595
+ };
596
+ }
1130
597
  }
1131
- /**
1132
- * Creates a replacer function used for substituting parameter placeholders in a route path
1133
- * with their corresponding values provided in the `params` object.
1134
- *
1135
- * @param params - An object mapping parameter names to their string values.
1136
- * @param currentRoutePath - The current route path, used for constructing error messages.
1137
- * @returns A function that replaces a matched parameter placeholder (e.g., ':id') with its corresponding value.
1138
- */
1139
598
  function handlePrerenderParamsReplacement(params, currentRoutePath) {
1140
- return (match) => {
1141
- const parameterName = match.slice(1);
1142
- const value = params[parameterName];
1143
- if (typeof value !== 'string') {
1144
- throw new Error(`The 'getPrerenderParams' function defined for the '${stripLeadingSlash(currentRoutePath)}' route ` +
1145
- `returned a non-string value for parameter '${parameterName}'. ` +
1146
- `Please make sure the 'getPrerenderParams' function returns values for all parameters ` +
1147
- 'specified in this route.');
1148
- }
1149
- return parameterName === '**' ? `/${value}` : value;
1150
- };
599
+ return match => {
600
+ const parameterName = match.slice(1);
601
+ const value = params[parameterName];
602
+ if (typeof value !== 'string') {
603
+ throw new Error(`The 'getPrerenderParams' function defined for the '${stripLeadingSlash(currentRoutePath)}' route ` + `returned a non-string value for parameter '${parameterName}'. ` + `Please make sure the 'getPrerenderParams' function returns values for all parameters ` + 'specified in this route.');
604
+ }
605
+ return parameterName === '**' ? `/${value}` : value;
606
+ };
1151
607
  }
1152
- /**
1153
- * Resolves the `redirectTo` property for a given route.
1154
- *
1155
- * This function processes the `redirectTo` property to ensure that it correctly
1156
- * resolves relative to the current route path. If `redirectTo` is an absolute path,
1157
- * it is returned as is. If it is a relative path, it is resolved based on the current route path.
1158
- *
1159
- * @param routePath - The current route path.
1160
- * @param redirectTo - The target path for redirection.
1161
- * @returns The resolved redirect path as a string.
1162
- */
1163
608
  function resolveRedirectTo(routePath, redirectTo) {
1164
- if (redirectTo[0] === '/') {
1165
- // If the redirectTo path is absolute, return it as is.
1166
- return redirectTo;
1167
- }
1168
- // Resolve relative redirectTo based on the current route path.
1169
- const segments = routePath.replace(URL_PARAMETER_REGEXP, '*').split('/');
1170
- segments.pop(); // Remove the last segment to make it relative.
1171
- return joinUrlParts(...segments, redirectTo);
609
+ if (redirectTo[0] === '/') {
610
+ return redirectTo;
611
+ }
612
+ const segments = routePath.replace(URL_PARAMETER_REGEXP, '*').split('/');
613
+ segments.pop();
614
+ return joinUrlParts(...segments, redirectTo);
1172
615
  }
1173
- /**
1174
- * Builds a server configuration route tree from the given server routes configuration.
1175
- *
1176
- * @param serverRoutesConfig - The server routes to be used for configuration.
1177
-
1178
- * @returns An object containing:
1179
- * - `serverConfigRouteTree`: A populated `RouteTree` instance, which organizes the server routes
1180
- * along with their additional metadata.
1181
- * - `errors`: An array of strings that list any errors encountered during the route tree construction
1182
- * process, such as invalid paths.
1183
- */
1184
- function buildServerConfigRouteTree({ routes, appShellRoute }) {
1185
- const serverRoutes = [...routes];
1186
- if (appShellRoute !== undefined) {
1187
- serverRoutes.unshift({
1188
- path: appShellRoute,
1189
- renderMode: RenderMode.Prerender,
1190
- });
1191
- }
1192
- const serverConfigRouteTree = new RouteTree();
1193
- const errors = [];
1194
- for (const { path, ...metadata } of serverRoutes) {
1195
- if (path[0] === '/') {
1196
- errors.push(`Invalid '${path}' route configuration: the path cannot start with a slash.`);
1197
- continue;
1198
- }
1199
- if ('getPrerenderParams' in metadata && (path.includes('/*/') || path.endsWith('/*'))) {
1200
- errors.push(`Invalid '${path}' route configuration: 'getPrerenderParams' cannot be used with a '*' route.`);
1201
- continue;
1202
- }
1203
- serverConfigRouteTree.insert(path, metadata);
1204
- }
1205
- return { serverConfigRouteTree, errors };
616
+ function buildServerConfigRouteTree({
617
+ routes,
618
+ appShellRoute
619
+ }) {
620
+ const serverRoutes = [...routes];
621
+ if (appShellRoute !== undefined) {
622
+ serverRoutes.unshift({
623
+ path: appShellRoute,
624
+ renderMode: RenderMode.Prerender
625
+ });
626
+ }
627
+ const serverConfigRouteTree = new RouteTree();
628
+ const errors = [];
629
+ for (const {
630
+ path,
631
+ ...metadata
632
+ } of serverRoutes) {
633
+ if (path[0] === '/') {
634
+ errors.push(`Invalid '${path}' route configuration: the path cannot start with a slash.`);
635
+ continue;
636
+ }
637
+ if ('getPrerenderParams' in metadata && (path.includes('/*/') || path.endsWith('/*'))) {
638
+ errors.push(`Invalid '${path}' route configuration: 'getPrerenderParams' cannot be used with a '*' route.`);
639
+ continue;
640
+ }
641
+ serverConfigRouteTree.insert(path, metadata);
642
+ }
643
+ return {
644
+ serverConfigRouteTree,
645
+ errors
646
+ };
1206
647
  }
1207
- /**
1208
- * Retrieves routes from the given Angular application.
1209
- *
1210
- * This function initializes an Angular platform, bootstraps the application or module,
1211
- * and retrieves routes from the Angular router configuration. It handles both module-based
1212
- * and function-based bootstrapping. It yields the resulting routes as `RouteTreeNodeMetadata` objects or errors.
1213
- *
1214
- * @param bootstrap - A function that returns a promise resolving to an `ApplicationRef` or an Angular module to bootstrap.
1215
- * @param document - The initial HTML document used for server-side rendering.
1216
- * This document is necessary to render the application on the server.
1217
- * @param url - The URL for server-side rendering. The URL is used to configure `ServerPlatformLocation`. This configuration is crucial
1218
- * for ensuring that API requests for relative paths succeed, which is essential for accurate route extraction.
1219
- * @param invokeGetPrerenderParams - A boolean flag indicating whether to invoke `getPrerenderParams` for parameterized SSG routes
1220
- * to handle prerendering paths. Defaults to `false`.
1221
- * @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result. Defaults to `true`.
1222
- * @param entryPointToBrowserMapping - Maps the entry-point name to the associated JavaScript browser bundles.
1223
- *
1224
- * @returns A promise that resolves to an object of type `AngularRouterConfigResult` or errors.
1225
- */
1226
648
  async function getRoutesFromAngularRouterConfig(bootstrap, document, url, invokeGetPrerenderParams = false, includePrerenderFallbackRoutes = true, entryPointToBrowserMapping = undefined) {
1227
- const { protocol, host } = url;
1228
- // Create and initialize the Angular platform for server-side rendering.
1229
- const platformRef = platformServer([
1230
- {
1231
- provide: INITIAL_CONFIG,
1232
- useValue: { document, url: `${protocol}//${host}/` },
1233
- },
1234
- {
1235
- // An Angular Console Provider that does not print a set of predefined logs.
1236
- provide: _Console,
1237
- // Using `useClass` would necessitate decorating `Console` with `@Injectable`,
1238
- // which would require switching from `ts_library` to `ng_module`. This change
1239
- // would also necessitate various patches of `@angular/bazel` to support ESM.
1240
- useFactory: () => new Console(),
1241
- },
1242
- {
1243
- provide: _ENABLE_ROOT_COMPONENT_BOOTSTRAP,
1244
- useValue: false,
1245
- },
1246
- ]);
1247
- try {
1248
- let applicationRef;
1249
- if (isNgModule(bootstrap)) {
1250
- const moduleRef = await platformRef.bootstrapModule(bootstrap);
1251
- applicationRef = moduleRef.injector.get(ApplicationRef);
1252
- }
1253
- else {
1254
- applicationRef = await bootstrap({ platformRef });
1255
- }
1256
- const injector = applicationRef.injector;
1257
- const router = injector.get(Router);
1258
- // Workaround to unblock navigation when `withEnabledBlockingInitialNavigation()` is used.
1259
- // This is necessary because route extraction disables component bootstrapping.
1260
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1261
- router.navigationTransitions.afterPreactivation()?.next?.();
1262
- // Wait until the application is stable.
1263
- await applicationRef.whenStable();
1264
- const errors = [];
1265
- const rawBaseHref = injector.get(APP_BASE_HREF, null, { optional: true }) ??
1266
- injector.get(PlatformLocation).getBaseHrefFromDOM();
1267
- const { pathname: baseHref } = new URL(rawBaseHref, 'http://localhost');
1268
- const compiler = injector.get(Compiler);
1269
- const serverRoutesConfig = injector.get(SERVER_ROUTES_CONFIG, null, { optional: true });
1270
- let serverConfigRouteTree;
1271
- if (serverRoutesConfig) {
1272
- const result = buildServerConfigRouteTree(serverRoutesConfig);
1273
- serverConfigRouteTree = result.serverConfigRouteTree;
1274
- errors.push(...result.errors);
1275
- }
1276
- if (errors.length) {
1277
- return {
1278
- baseHref,
1279
- routes: [],
1280
- errors,
1281
- };
1282
- }
1283
- const routesResults = [];
1284
- if (router.config.length) {
1285
- // Retrieve all routes from the Angular router configuration.
1286
- const traverseRoutes = traverseRoutesConfig({
1287
- routes: router.config,
1288
- compiler,
1289
- parentInjector: injector,
1290
- parentRoute: '',
1291
- serverConfigRouteTree,
1292
- invokeGetPrerenderParams,
1293
- includePrerenderFallbackRoutes,
1294
- entryPointToBrowserMapping,
1295
- });
1296
- const seenRoutes = new Set();
1297
- for await (const routeMetadata of traverseRoutes) {
1298
- if ('error' in routeMetadata) {
1299
- errors.push(routeMetadata.error);
1300
- continue;
1301
- }
1302
- // If a result already exists for the exact same route, subsequent matches should be ignored.
1303
- // This aligns with Angular's app router behavior, which prioritizes the first route.
1304
- const routePath = routeMetadata.route;
1305
- if (!seenRoutes.has(routePath)) {
1306
- routesResults.push(routeMetadata);
1307
- seenRoutes.add(routePath);
1308
- }
1309
- }
1310
- // This timeout is necessary to prevent 'adev' from hanging in production builds.
1311
- // The exact cause is unclear, but removing it leads to the issue.
1312
- await new Promise((resolve) => setTimeout(resolve, 0));
1313
- if (serverConfigRouteTree) {
1314
- for (const { route, presentInClientRouter } of serverConfigRouteTree.traverse()) {
1315
- if (presentInClientRouter || route.endsWith('/**')) {
1316
- // Skip if matched or it's the catch-all route.
1317
- continue;
1318
- }
1319
- errors.push(`The '${stripLeadingSlash(route)}' server route does not match any routes defined in the Angular ` +
1320
- `routing configuration (typically provided as a part of the 'provideRouter' call). ` +
1321
- 'Please make sure that the mentioned server route is present in the Angular routing configuration.');
1322
- }
1323
- }
1324
- }
1325
- else {
1326
- const rootRouteMetadata = serverConfigRouteTree?.match('') ?? {
1327
- route: '',
1328
- renderMode: RenderMode.Prerender,
1329
- };
1330
- routesResults.push({
1331
- ...rootRouteMetadata,
1332
- // Matched route might be `/*` or `/**`, which would make Angular serve all routes rather than just `/`.
1333
- // So we limit to just `/` for the empty app router case.
1334
- route: '',
1335
- });
1336
- }
1337
- return {
1338
- baseHref,
1339
- routes: routesResults,
1340
- errors,
1341
- appShellRoute: serverRoutesConfig?.appShellRoute,
1342
- };
1343
- }
1344
- finally {
1345
- platformRef.destroy();
649
+ const {
650
+ protocol,
651
+ host
652
+ } = url;
653
+ const platformRef = platformServer([{
654
+ provide: INITIAL_CONFIG,
655
+ useValue: {
656
+ document,
657
+ url: `${protocol}//${host}/`
658
+ }
659
+ }, {
660
+ provide: _Console,
661
+ useFactory: () => new Console()
662
+ }, {
663
+ provide: _ENABLE_ROOT_COMPONENT_BOOTSTRAP,
664
+ useValue: false
665
+ }]);
666
+ try {
667
+ let applicationRef;
668
+ if (isNgModule(bootstrap)) {
669
+ const moduleRef = await platformRef.bootstrapModule(bootstrap);
670
+ applicationRef = moduleRef.injector.get(ApplicationRef);
671
+ } else {
672
+ applicationRef = await bootstrap({
673
+ platformRef
674
+ });
675
+ }
676
+ const injector = applicationRef.injector;
677
+ const router = injector.get(Router);
678
+ router.navigationTransitions.afterPreactivation()?.next?.();
679
+ await applicationRef.whenStable();
680
+ const errors = [];
681
+ const rawBaseHref = injector.get(APP_BASE_HREF, null, {
682
+ optional: true
683
+ }) ?? injector.get(PlatformLocation).getBaseHrefFromDOM();
684
+ const {
685
+ pathname: baseHref
686
+ } = new URL(rawBaseHref, 'http://localhost');
687
+ const compiler = injector.get(Compiler);
688
+ const serverRoutesConfig = injector.get(SERVER_ROUTES_CONFIG, null, {
689
+ optional: true
690
+ });
691
+ let serverConfigRouteTree;
692
+ if (serverRoutesConfig) {
693
+ const result = buildServerConfigRouteTree(serverRoutesConfig);
694
+ serverConfigRouteTree = result.serverConfigRouteTree;
695
+ errors.push(...result.errors);
696
+ }
697
+ if (errors.length) {
698
+ return {
699
+ baseHref,
700
+ routes: [],
701
+ errors
702
+ };
703
+ }
704
+ const routesResults = [];
705
+ if (router.config.length) {
706
+ const traverseRoutes = traverseRoutesConfig({
707
+ routes: router.config,
708
+ compiler,
709
+ parentInjector: injector,
710
+ parentRoute: '',
711
+ serverConfigRouteTree,
712
+ invokeGetPrerenderParams,
713
+ includePrerenderFallbackRoutes,
714
+ entryPointToBrowserMapping
715
+ });
716
+ const seenRoutes = new Set();
717
+ for await (const routeMetadata of traverseRoutes) {
718
+ if ('error' in routeMetadata) {
719
+ errors.push(routeMetadata.error);
720
+ continue;
721
+ }
722
+ const routePath = routeMetadata.route;
723
+ if (!seenRoutes.has(routePath)) {
724
+ routesResults.push(routeMetadata);
725
+ seenRoutes.add(routePath);
726
+ }
727
+ }
728
+ await new Promise(resolve => setTimeout(resolve, 0));
729
+ if (serverConfigRouteTree) {
730
+ for (const {
731
+ route,
732
+ presentInClientRouter
733
+ } of serverConfigRouteTree.traverse()) {
734
+ if (presentInClientRouter || route.endsWith('/**')) {
735
+ continue;
736
+ }
737
+ errors.push(`The '${stripLeadingSlash(route)}' server route does not match any routes defined in the Angular ` + `routing configuration (typically provided as a part of the 'provideRouter' call). ` + 'Please make sure that the mentioned server route is present in the Angular routing configuration.');
738
+ }
739
+ }
740
+ } else {
741
+ const rootRouteMetadata = serverConfigRouteTree?.match('') ?? {
742
+ route: '',
743
+ renderMode: RenderMode.Prerender
744
+ };
745
+ routesResults.push({
746
+ ...rootRouteMetadata,
747
+ route: ''
748
+ });
1346
749
  }
750
+ return {
751
+ baseHref,
752
+ routes: routesResults,
753
+ errors,
754
+ appShellRoute: serverRoutesConfig?.appShellRoute
755
+ };
756
+ } finally {
757
+ platformRef.destroy();
758
+ }
1347
759
  }
1348
- /**
1349
- * Asynchronously extracts routes from the Angular application configuration
1350
- * and creates a `RouteTree` to manage server-side routing.
1351
- *
1352
- * @param options - An object containing the following options:
1353
- * - `url`: The URL for server-side rendering. The URL is used to configure `ServerPlatformLocation`. This configuration is crucial
1354
- * for ensuring that API requests for relative paths succeed, which is essential for accurate route extraction.
1355
- * See:
1356
- * - https://github.com/angular/angular/blob/d608b857c689d17a7ffa33bbb510301014d24a17/packages/platform-server/src/location.ts#L51
1357
- * - https://github.com/angular/angular/blob/6882cc7d9eed26d3caeedca027452367ba25f2b9/packages/platform-server/src/http.ts#L44
1358
- * - `manifest`: An optional `AngularAppManifest` that contains the application's routing and configuration details.
1359
- * If not provided, the default manifest is retrieved using `getAngularAppManifest()`.
1360
- * - `invokeGetPrerenderParams`: A boolean flag indicating whether to invoke `getPrerenderParams` for parameterized SSG routes
1361
- * to handle prerendering paths. Defaults to `false`.
1362
- * - `includePrerenderFallbackRoutes`: A flag indicating whether to include fallback routes in the result. Defaults to `true`.
1363
- * - `signal`: An optional `AbortSignal` that can be used to abort the operation.
1364
- *
1365
- * @returns A promise that resolves to an object containing:
1366
- * - `routeTree`: A populated `RouteTree` containing all extracted routes from the Angular application.
1367
- * - `appShellRoute`: The specified route for the app-shell, if configured.
1368
- * - `errors`: An array of strings representing any errors encountered during the route extraction process.
1369
- */
1370
760
  function extractRoutesAndCreateRouteTree(options) {
1371
- const { url, manifest = getAngularAppManifest(), invokeGetPrerenderParams = false, includePrerenderFallbackRoutes = true, signal, } = options;
1372
- async function extract() {
1373
- const routeTree = new RouteTree();
1374
- const document = await new ServerAssets(manifest).getIndexServerHtml().text();
1375
- const bootstrap = await manifest.bootstrap();
1376
- const { baseHref, appShellRoute, routes, errors } = await getRoutesFromAngularRouterConfig(bootstrap, document, url, invokeGetPrerenderParams, includePrerenderFallbackRoutes, manifest.entryPointToBrowserMapping);
1377
- for (const { route, ...metadata } of routes) {
1378
- if (metadata.redirectTo !== undefined) {
1379
- metadata.redirectTo = joinUrlParts(baseHref, metadata.redirectTo);
1380
- }
1381
- // Remove undefined fields
1382
- // Helps avoid unnecessary test updates
1383
- for (const [key, value] of Object.entries(metadata)) {
1384
- if (value === undefined) {
1385
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1386
- delete metadata[key];
1387
- }
1388
- }
1389
- const fullRoute = joinUrlParts(baseHref, route);
1390
- routeTree.insert(fullRoute, metadata);
1391
- }
1392
- return {
1393
- appShellRoute,
1394
- routeTree,
1395
- errors,
1396
- };
761
+ const {
762
+ url,
763
+ manifest = getAngularAppManifest(),
764
+ invokeGetPrerenderParams = false,
765
+ includePrerenderFallbackRoutes = true,
766
+ signal
767
+ } = options;
768
+ async function extract() {
769
+ const routeTree = new RouteTree();
770
+ const document = await new ServerAssets(manifest).getIndexServerHtml().text();
771
+ const bootstrap = await manifest.bootstrap();
772
+ const {
773
+ baseHref,
774
+ appShellRoute,
775
+ routes,
776
+ errors
777
+ } = await getRoutesFromAngularRouterConfig(bootstrap, document, url, invokeGetPrerenderParams, includePrerenderFallbackRoutes, manifest.entryPointToBrowserMapping);
778
+ for (const {
779
+ route,
780
+ ...metadata
781
+ } of routes) {
782
+ if (metadata.redirectTo !== undefined) {
783
+ metadata.redirectTo = joinUrlParts(baseHref, metadata.redirectTo);
784
+ }
785
+ for (const [key, value] of Object.entries(metadata)) {
786
+ if (value === undefined) {
787
+ delete metadata[key];
788
+ }
789
+ }
790
+ const fullRoute = joinUrlParts(baseHref, route);
791
+ routeTree.insert(fullRoute, metadata);
1397
792
  }
1398
- return signal ? promiseWithAbort(extract(), signal, 'Routes extraction') : extract();
793
+ return {
794
+ appShellRoute,
795
+ routeTree,
796
+ errors
797
+ };
798
+ }
799
+ return signal ? promiseWithAbort(extract(), signal, 'Routes extraction') : extract();
1399
800
  }
1400
801
 
1401
- /**
1402
- * Manages a collection of hooks and provides methods to register and execute them.
1403
- * Hooks are functions that can be invoked with specific arguments to allow modifications or enhancements.
1404
- */
1405
802
  class Hooks {
1406
- /**
1407
- * A map of hook names to arrays of hook functions.
1408
- * Each hook name can have multiple associated functions, which are executed in sequence.
1409
- */
1410
- store = new Map();
1411
- /**
1412
- * Executes all hooks associated with the specified name, passing the given argument to each hook function.
1413
- * The hooks are invoked sequentially, and the argument may be modified by each hook.
1414
- *
1415
- * @template Hook - The type of the hook name. It should be one of the keys of `HooksMapping`.
1416
- * @param name - The name of the hook whose functions will be executed.
1417
- * @param context - The input value to be passed to each hook function. The value is mutated by each hook function.
1418
- * @returns A promise that resolves once all hook functions have been executed.
1419
- *
1420
- * @example
1421
- * ```typescript
1422
- * const hooks = new Hooks();
1423
- * hooks.on('html:transform:pre', async (ctx) => {
1424
- * ctx.html = ctx.html.replace(/foo/g, 'bar');
1425
- * return ctx.html;
1426
- * });
1427
- * const result = await hooks.run('html:transform:pre', { html: '<div>foo</div>' });
1428
- * console.log(result); // '<div>bar</div>'
1429
- * ```
1430
- * @internal
1431
- */
1432
- async run(name, context) {
1433
- const hooks = this.store.get(name);
1434
- switch (name) {
1435
- case 'html:transform:pre': {
1436
- if (!hooks) {
1437
- return context.html;
1438
- }
1439
- const ctx = { ...context };
1440
- for (const hook of hooks) {
1441
- ctx.html = await hook(ctx);
1442
- }
1443
- return ctx.html;
1444
- }
1445
- default:
1446
- throw new Error(`Running hook "${name}" is not supported.`);
1447
- }
1448
- }
1449
- /**
1450
- * Registers a new hook function under the specified hook name.
1451
- * This function should be a function that takes an argument of type `T` and returns a `string` or `Promise<string>`.
1452
- *
1453
- * @template Hook - The type of the hook name. It should be one of the keys of `HooksMapping`.
1454
- * @param name - The name of the hook under which the function will be registered.
1455
- * @param handler - A function to be executed when the hook is triggered. The handler will be called with an argument
1456
- * that may be modified by the hook functions.
1457
- *
1458
- * @remarks
1459
- * - If there are existing handlers registered under the given hook name, the new handler will be added to the list.
1460
- * - If no handlers are registered under the given hook name, a new list will be created with the handler as its first element.
1461
- *
1462
- * @example
1463
- * ```typescript
1464
- * hooks.on('html:transform:pre', async (ctx) => {
1465
- * return ctx.html.replace(/foo/g, 'bar');
1466
- * });
1467
- * ```
1468
- */
1469
- on(name, handler) {
1470
- const hooks = this.store.get(name);
1471
- if (hooks) {
1472
- hooks.push(handler);
1473
- }
1474
- else {
1475
- this.store.set(name, [handler]);
1476
- }
1477
- }
1478
- /**
1479
- * Checks if there are any hooks registered under the specified name.
1480
- *
1481
- * @param name - The name of the hook to check.
1482
- * @returns `true` if there are hooks registered under the specified name, otherwise `false`.
1483
- */
1484
- has(name) {
1485
- return !!this.store.get(name)?.length;
1486
- }
803
+ store = new Map();
804
+ async run(name, context) {
805
+ const hooks = this.store.get(name);
806
+ switch (name) {
807
+ case 'html:transform:pre':
808
+ {
809
+ if (!hooks) {
810
+ return context.html;
811
+ }
812
+ const ctx = {
813
+ ...context
814
+ };
815
+ for (const hook of hooks) {
816
+ ctx.html = await hook(ctx);
817
+ }
818
+ return ctx.html;
819
+ }
820
+ default:
821
+ throw new Error(`Running hook "${name}" is not supported.`);
822
+ }
823
+ }
824
+ on(name, handler) {
825
+ const hooks = this.store.get(name);
826
+ if (hooks) {
827
+ hooks.push(handler);
828
+ } else {
829
+ this.store.set(name, [handler]);
830
+ }
831
+ }
832
+ has(name) {
833
+ return !!this.store.get(name)?.length;
834
+ }
1487
835
  }
1488
836
 
1489
- /**
1490
- * Manages the application's server routing logic by building and maintaining a route tree.
1491
- *
1492
- * This class is responsible for constructing the route tree from the Angular application
1493
- * configuration and using it to match incoming requests to the appropriate routes.
1494
- */
1495
837
  class ServerRouter {
1496
- routeTree;
1497
- /**
1498
- * Creates an instance of the `ServerRouter`.
1499
- *
1500
- * @param routeTree - An instance of `RouteTree` that holds the routing information.
1501
- * The `RouteTree` is used to match request URLs to the appropriate route metadata.
1502
- */
1503
- constructor(routeTree) {
1504
- this.routeTree = routeTree;
1505
- }
1506
- /**
1507
- * Static property to track the ongoing build promise.
1508
- */
1509
- static #extractionPromise;
1510
- /**
1511
- * Creates or retrieves a `ServerRouter` instance based on the provided manifest and URL.
1512
- *
1513
- * If the manifest contains pre-built routes, a new `ServerRouter` is immediately created.
1514
- * Otherwise, it builds the router by extracting routes from the Angular configuration
1515
- * asynchronously. This method ensures that concurrent builds are prevented by re-using
1516
- * the same promise.
1517
- *
1518
- * @param manifest - An instance of `AngularAppManifest` that contains the route information.
1519
- * @param url - The URL for server-side rendering. The URL is needed to configure `ServerPlatformLocation`.
1520
- * This is necessary to ensure that API requests for relative paths succeed, which is crucial for correct route extraction.
1521
- * [Reference](https://github.com/angular/angular/blob/d608b857c689d17a7ffa33bbb510301014d24a17/packages/platform-server/src/location.ts#L51)
1522
- * @returns A promise resolving to a `ServerRouter` instance.
1523
- */
1524
- static from(manifest, url) {
1525
- if (manifest.routes) {
1526
- const routeTree = RouteTree.fromObject(manifest.routes);
1527
- return Promise.resolve(new ServerRouter(routeTree));
1528
- }
1529
- // Create and store a new promise for the build process.
1530
- // This prevents concurrent builds by re-using the same promise.
1531
- ServerRouter.#extractionPromise ??= extractRoutesAndCreateRouteTree({ url, manifest })
1532
- .then(({ routeTree, errors }) => {
1533
- if (errors.length > 0) {
1534
- throw new Error('Error(s) occurred while extracting routes:\n' +
1535
- errors.map((error) => `- ${error}`).join('\n'));
1536
- }
1537
- return new ServerRouter(routeTree);
1538
- })
1539
- .finally(() => {
1540
- ServerRouter.#extractionPromise = undefined;
1541
- });
1542
- return ServerRouter.#extractionPromise;
1543
- }
1544
- /**
1545
- * Matches a request URL against the route tree to retrieve route metadata.
1546
- *
1547
- * This method strips 'index.html' from the URL if it is present and then attempts
1548
- * to find a match in the route tree. If a match is found, it returns the associated
1549
- * route metadata; otherwise, it returns `undefined`.
1550
- *
1551
- * @param url - The URL to be matched against the route tree.
1552
- * @returns The metadata for the matched route or `undefined` if no match is found.
1553
- */
1554
- match(url) {
1555
- // Strip 'index.html' from URL if present.
1556
- // A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.
1557
- const { pathname } = stripIndexHtmlFromURL(url);
1558
- return this.routeTree.match(decodeURIComponent(pathname));
1559
- }
838
+ routeTree;
839
+ constructor(routeTree) {
840
+ this.routeTree = routeTree;
841
+ }
842
+ static #extractionPromise;
843
+ static from(manifest, url) {
844
+ if (manifest.routes) {
845
+ const routeTree = RouteTree.fromObject(manifest.routes);
846
+ return Promise.resolve(new ServerRouter(routeTree));
847
+ }
848
+ ServerRouter.#extractionPromise ??= extractRoutesAndCreateRouteTree({
849
+ url,
850
+ manifest
851
+ }).then(({
852
+ routeTree,
853
+ errors
854
+ }) => {
855
+ if (errors.length > 0) {
856
+ throw new Error('Error(s) occurred while extracting routes:\n' + errors.map(error => `- ${error}`).join('\n'));
857
+ }
858
+ return new ServerRouter(routeTree);
859
+ }).finally(() => {
860
+ ServerRouter.#extractionPromise = undefined;
861
+ });
862
+ return ServerRouter.#extractionPromise;
863
+ }
864
+ match(url) {
865
+ let {
866
+ pathname
867
+ } = stripIndexHtmlFromURL(url);
868
+ pathname = stripMatrixParams(pathname);
869
+ pathname = decodeURIComponent(pathname);
870
+ return this.routeTree.match(pathname);
871
+ }
1560
872
  }
1561
873
 
1562
- /**
1563
- * Generates a SHA-256 hash of the provided string.
1564
- *
1565
- * @param data - The input string to be hashed.
1566
- * @returns A promise that resolves to the SHA-256 hash of the input,
1567
- * represented as a hexadecimal string.
1568
- */
1569
874
  async function sha256(data) {
1570
- const encodedData = new TextEncoder().encode(data);
1571
- const hashBuffer = await crypto.subtle.digest('SHA-256', encodedData);
1572
- const hashParts = [];
1573
- for (const h of new Uint8Array(hashBuffer)) {
1574
- hashParts.push(h.toString(16).padStart(2, '0'));
1575
- }
1576
- return hashParts.join('');
875
+ const encodedData = new TextEncoder().encode(data);
876
+ const hashBuffer = await crypto.subtle.digest('SHA-256', encodedData);
877
+ const hashParts = [];
878
+ for (const h of new Uint8Array(hashBuffer)) {
879
+ hashParts.push(h.toString(16).padStart(2, '0'));
880
+ }
881
+ return hashParts.join('');
1577
882
  }
1578
883
 
1579
- /**
1580
- * Pattern used to extract the media query set by Beasties in an `onload` handler.
1581
- */
1582
884
  const MEDIA_SET_HANDLER_PATTERN = /^this\.media=["'](.*)["'];?$/;
1583
- /**
1584
- * Name of the attribute used to save the Beasties media query so it can be re-assigned on load.
1585
- */
1586
885
  const CSP_MEDIA_ATTR = 'ngCspMedia';
1587
- /**
1588
- * Script that dynamically updates the `media` attribute of `<link>` tags based on a custom attribute (`CSP_MEDIA_ATTR`).
1589
- *
1590
- * NOTE:
1591
- * We do not use `document.querySelectorAll('link').forEach((s) => s.addEventListener('load', ...)`
1592
- * because load events are not always triggered reliably on Chrome.
1593
- * See: https://github.com/angular/angular-cli/issues/26932 and https://crbug.com/1521256
1594
- *
1595
- * The script:
1596
- * - Ensures the event target is a `<link>` tag with the `CSP_MEDIA_ATTR` attribute.
1597
- * - Updates the `media` attribute with the value of `CSP_MEDIA_ATTR` and then removes the attribute.
1598
- * - Removes the event listener when all relevant `<link>` tags have been processed.
1599
- * - Uses event capturing (the `true` parameter) since load events do not bubble up the DOM.
1600
- */
1601
- const LINK_LOAD_SCRIPT_CONTENT = /* @__PURE__ */ (() => `(() => {
886
+ const LINK_LOAD_SCRIPT_CONTENT = /* @__PURE__ */(() => `(() => {
1602
887
  const CSP_MEDIA_ATTR = '${CSP_MEDIA_ATTR}';
1603
888
  const documentElement = document.documentElement;
1604
889
 
@@ -1623,995 +908,582 @@ const LINK_LOAD_SCRIPT_CONTENT = /* @__PURE__ */ (() => `(() => {
1623
908
 
1624
909
  documentElement.addEventListener('load', listener, true);
1625
910
  })();`)();
1626
- class BeastiesBase extends Beasties {
1627
- }
1628
- /* eslint-enable @typescript-eslint/no-unsafe-declaration-merging */
911
+ class BeastiesBase extends Beasties {}
1629
912
  class InlineCriticalCssProcessor extends BeastiesBase {
1630
- readFile;
1631
- outputPath;
1632
- addedCspScriptsDocuments = new WeakSet();
1633
- documentNonces = new WeakMap();
1634
- constructor(readFile, outputPath) {
1635
- super({
1636
- logger: {
1637
- // eslint-disable-next-line no-console
1638
- warn: (s) => console.warn(s),
1639
- // eslint-disable-next-line no-console
1640
- error: (s) => console.error(s),
1641
- info: () => { },
1642
- },
1643
- logLevel: 'warn',
1644
- path: outputPath,
1645
- publicPath: undefined,
1646
- compress: false,
1647
- pruneSource: false,
1648
- reduceInlineStyles: false,
1649
- mergeStylesheets: false,
1650
- // Note: if `preload` changes to anything other than `media`, the logic in
1651
- // `embedLinkedStylesheet` will have to be updated.
1652
- preload: 'media',
1653
- noscriptFallback: true,
1654
- inlineFonts: true,
1655
- });
1656
- this.readFile = readFile;
1657
- this.outputPath = outputPath;
1658
- }
1659
- /**
1660
- * Override of the Beasties `embedLinkedStylesheet` method
1661
- * that makes it work with Angular's CSP APIs.
1662
- */
1663
- async embedLinkedStylesheet(link, document) {
1664
- if (link.getAttribute('media') === 'print' && link.next?.name === 'noscript') {
1665
- // Workaround for https://github.com/GoogleChromeLabs/critters/issues/64
1666
- // NB: this is only needed for the webpack based builders.
1667
- const media = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);
1668
- if (media) {
1669
- link.removeAttribute('onload');
1670
- link.setAttribute('media', media[1]);
1671
- link?.next?.remove();
1672
- }
1673
- }
1674
- const returnValue = await super.embedLinkedStylesheet(link, document);
1675
- const cspNonce = this.findCspNonce(document);
1676
- if (cspNonce) {
1677
- const beastiesMedia = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);
1678
- if (beastiesMedia) {
1679
- // If there's a Beasties-generated `onload` handler and the file has an Angular CSP nonce,
1680
- // we have to remove the handler, because it's incompatible with CSP. We save the value
1681
- // in a different attribute and we generate a script tag with the nonce that uses
1682
- // `addEventListener` to apply the media query instead.
1683
- link.removeAttribute('onload');
1684
- link.setAttribute(CSP_MEDIA_ATTR, beastiesMedia[1]);
1685
- this.conditionallyInsertCspLoadingScript(document, cspNonce, link);
1686
- }
1687
- // Ideally we would hook in at the time Beasties inserts the `style` tags, but there isn't
1688
- // a way of doing that at the moment so we fall back to doing it any time a `link` tag is
1689
- // inserted. We mitigate it by only iterating the direct children of the `<head>` which
1690
- // should be pretty shallow.
1691
- document.head.children.forEach((child) => {
1692
- if (child.tagName === 'style' && !child.hasAttribute('nonce')) {
1693
- child.setAttribute('nonce', cspNonce);
1694
- }
1695
- });
1696
- }
1697
- return returnValue;
1698
- }
1699
- /**
1700
- * Finds the CSP nonce for a specific document.
1701
- */
1702
- findCspNonce(document) {
1703
- if (this.documentNonces.has(document)) {
1704
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1705
- return this.documentNonces.get(document);
1706
- }
1707
- // HTML attribute are case-insensitive, but the parser used by Beasties is case-sensitive.
1708
- const nonceElement = document.querySelector('[ngCspNonce], [ngcspnonce]');
1709
- const cspNonce = nonceElement?.getAttribute('ngCspNonce') || nonceElement?.getAttribute('ngcspnonce') || null;
1710
- this.documentNonces.set(document, cspNonce);
1711
- return cspNonce;
1712
- }
1713
- /**
1714
- * Inserts the `script` tag that swaps the critical CSS at runtime,
1715
- * if one hasn't been inserted into the document already.
1716
- */
1717
- conditionallyInsertCspLoadingScript(document, nonce, link) {
1718
- if (this.addedCspScriptsDocuments.has(document)) {
1719
- return;
1720
- }
1721
- if (document.head.textContent.includes(LINK_LOAD_SCRIPT_CONTENT)) {
1722
- // Script was already added during the build.
1723
- this.addedCspScriptsDocuments.add(document);
1724
- return;
1725
- }
1726
- const script = document.createElement('script');
1727
- script.setAttribute('nonce', nonce);
1728
- script.textContent = LINK_LOAD_SCRIPT_CONTENT;
1729
- // Prepend the script to the head since it needs to
1730
- // run as early as possible, before the `link` tags.
1731
- document.head.insertBefore(script, link);
1732
- this.addedCspScriptsDocuments.add(document);
913
+ readFile;
914
+ outputPath;
915
+ addedCspScriptsDocuments = new WeakSet();
916
+ documentNonces = new WeakMap();
917
+ constructor(readFile, outputPath) {
918
+ super({
919
+ logger: {
920
+ warn: s => console.warn(s),
921
+ error: s => console.error(s),
922
+ info: () => {}
923
+ },
924
+ logLevel: 'warn',
925
+ path: outputPath,
926
+ publicPath: undefined,
927
+ compress: false,
928
+ pruneSource: false,
929
+ reduceInlineStyles: false,
930
+ mergeStylesheets: false,
931
+ preload: 'media',
932
+ noscriptFallback: true,
933
+ inlineFonts: true
934
+ });
935
+ this.readFile = readFile;
936
+ this.outputPath = outputPath;
937
+ }
938
+ async embedLinkedStylesheet(link, document) {
939
+ if (link.getAttribute('media') === 'print' && link.next?.name === 'noscript') {
940
+ const media = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);
941
+ if (media) {
942
+ link.removeAttribute('onload');
943
+ link.setAttribute('media', media[1]);
944
+ link?.next?.remove();
945
+ }
946
+ }
947
+ const returnValue = await super.embedLinkedStylesheet(link, document);
948
+ const cspNonce = this.findCspNonce(document);
949
+ if (cspNonce) {
950
+ const beastiesMedia = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);
951
+ if (beastiesMedia) {
952
+ link.removeAttribute('onload');
953
+ link.setAttribute(CSP_MEDIA_ATTR, beastiesMedia[1]);
954
+ this.conditionallyInsertCspLoadingScript(document, cspNonce, link);
955
+ }
956
+ document.head.children.forEach(child => {
957
+ if (child.tagName === 'style' && !child.hasAttribute('nonce')) {
958
+ child.setAttribute('nonce', cspNonce);
959
+ }
960
+ });
961
+ }
962
+ return returnValue;
963
+ }
964
+ findCspNonce(document) {
965
+ if (this.documentNonces.has(document)) {
966
+ return this.documentNonces.get(document);
967
+ }
968
+ const nonceElement = document.querySelector('[ngCspNonce], [ngcspnonce]');
969
+ const cspNonce = nonceElement?.getAttribute('ngCspNonce') || nonceElement?.getAttribute('ngcspnonce') || null;
970
+ this.documentNonces.set(document, cspNonce);
971
+ return cspNonce;
972
+ }
973
+ conditionallyInsertCspLoadingScript(document, nonce, link) {
974
+ if (this.addedCspScriptsDocuments.has(document)) {
975
+ return;
976
+ }
977
+ if (document.head.textContent.includes(LINK_LOAD_SCRIPT_CONTENT)) {
978
+ this.addedCspScriptsDocuments.add(document);
979
+ return;
1733
980
  }
981
+ const script = document.createElement('script');
982
+ script.setAttribute('nonce', nonce);
983
+ script.textContent = LINK_LOAD_SCRIPT_CONTENT;
984
+ document.head.insertBefore(script, link);
985
+ this.addedCspScriptsDocuments.add(document);
986
+ }
1734
987
  }
1735
988
 
1736
- /**
1737
- * A Least Recently Used (LRU) cache implementation.
1738
- *
1739
- * This cache stores a fixed number of key-value pairs, and when the cache exceeds its capacity,
1740
- * the least recently accessed items are evicted.
1741
- *
1742
- * @template Key - The type of the cache keys.
1743
- * @template Value - The type of the cache values.
1744
- */
1745
989
  class LRUCache {
1746
- /**
1747
- * The maximum number of items the cache can hold.
1748
- */
1749
- capacity;
1750
- /**
1751
- * Internal storage for the cache, mapping keys to their associated nodes in the linked list.
1752
- */
1753
- cache = new Map();
1754
- /**
1755
- * Head of the doubly linked list, representing the most recently used item.
1756
- */
1757
- head;
1758
- /**
1759
- * Tail of the doubly linked list, representing the least recently used item.
1760
- */
1761
- tail;
1762
- /**
1763
- * Creates a new LRUCache instance.
1764
- * @param capacity The maximum number of items the cache can hold.
1765
- */
1766
- constructor(capacity) {
1767
- this.capacity = capacity;
1768
- }
1769
- /**
1770
- * Gets the value associated with the given key.
1771
- * @param key The key to retrieve the value for.
1772
- * @returns The value associated with the key, or undefined if the key is not found.
1773
- */
1774
- get(key) {
1775
- const node = this.cache.get(key);
1776
- if (node) {
1777
- this.moveToHead(node);
1778
- return node.value;
1779
- }
1780
- return undefined;
1781
- }
1782
- /**
1783
- * Puts a key-value pair into the cache.
1784
- * If the key already exists, the value is updated.
1785
- * If the cache is full, the least recently used item is evicted.
1786
- * @param key The key to insert or update.
1787
- * @param value The value to associate with the key.
1788
- */
1789
- put(key, value) {
1790
- const cachedNode = this.cache.get(key);
1791
- if (cachedNode) {
1792
- // Update existing node
1793
- cachedNode.value = value;
1794
- this.moveToHead(cachedNode);
1795
- return;
1796
- }
1797
- // Create a new node
1798
- const newNode = { key, value, prev: undefined, next: undefined };
1799
- this.cache.set(key, newNode);
1800
- this.addToHead(newNode);
1801
- if (this.cache.size > this.capacity) {
1802
- // Evict the LRU item
1803
- const tail = this.removeTail();
1804
- if (tail) {
1805
- this.cache.delete(tail.key);
1806
- }
1807
- }
1808
- }
1809
- /**
1810
- * Adds a node to the head of the linked list.
1811
- * @param node The node to add.
1812
- */
1813
- addToHead(node) {
1814
- node.next = this.head;
1815
- node.prev = undefined;
1816
- if (this.head) {
1817
- this.head.prev = node;
1818
- }
1819
- this.head = node;
1820
- if (!this.tail) {
1821
- this.tail = node;
1822
- }
1823
- }
1824
- /**
1825
- * Removes a node from the linked list.
1826
- * @param node The node to remove.
1827
- */
1828
- removeNode(node) {
1829
- if (node.prev) {
1830
- node.prev.next = node.next;
1831
- }
1832
- else {
1833
- this.head = node.next;
1834
- }
1835
- if (node.next) {
1836
- node.next.prev = node.prev;
1837
- }
1838
- else {
1839
- this.tail = node.prev;
1840
- }
1841
- }
1842
- /**
1843
- * Moves a node to the head of the linked list.
1844
- * @param node The node to move.
1845
- */
1846
- moveToHead(node) {
1847
- this.removeNode(node);
1848
- this.addToHead(node);
1849
- }
1850
- /**
1851
- * Removes the tail node from the linked list.
1852
- * @returns The removed tail node, or undefined if the list is empty.
1853
- */
1854
- removeTail() {
1855
- const node = this.tail;
1856
- if (node) {
1857
- this.removeNode(node);
1858
- }
1859
- return node;
990
+ capacity;
991
+ cache = new Map();
992
+ head;
993
+ tail;
994
+ constructor(capacity) {
995
+ this.capacity = capacity;
996
+ }
997
+ get(key) {
998
+ const node = this.cache.get(key);
999
+ if (node) {
1000
+ this.moveToHead(node);
1001
+ return node.value;
1002
+ }
1003
+ return undefined;
1004
+ }
1005
+ put(key, value) {
1006
+ const cachedNode = this.cache.get(key);
1007
+ if (cachedNode) {
1008
+ cachedNode.value = value;
1009
+ this.moveToHead(cachedNode);
1010
+ return;
1860
1011
  }
1012
+ const newNode = {
1013
+ key,
1014
+ value,
1015
+ prev: undefined,
1016
+ next: undefined
1017
+ };
1018
+ this.cache.set(key, newNode);
1019
+ this.addToHead(newNode);
1020
+ if (this.cache.size > this.capacity) {
1021
+ const tail = this.removeTail();
1022
+ if (tail) {
1023
+ this.cache.delete(tail.key);
1024
+ }
1025
+ }
1026
+ }
1027
+ addToHead(node) {
1028
+ node.next = this.head;
1029
+ node.prev = undefined;
1030
+ if (this.head) {
1031
+ this.head.prev = node;
1032
+ }
1033
+ this.head = node;
1034
+ if (!this.tail) {
1035
+ this.tail = node;
1036
+ }
1037
+ }
1038
+ removeNode(node) {
1039
+ if (node.prev) {
1040
+ node.prev.next = node.next;
1041
+ } else {
1042
+ this.head = node.next;
1043
+ }
1044
+ if (node.next) {
1045
+ node.next.prev = node.prev;
1046
+ } else {
1047
+ this.tail = node.prev;
1048
+ }
1049
+ }
1050
+ moveToHead(node) {
1051
+ this.removeNode(node);
1052
+ this.addToHead(node);
1053
+ }
1054
+ removeTail() {
1055
+ const node = this.tail;
1056
+ if (node) {
1057
+ this.removeNode(node);
1058
+ }
1059
+ return node;
1060
+ }
1861
1061
  }
1862
1062
 
1863
- /**
1864
- * Maximum number of critical CSS entries the cache can store.
1865
- * This value determines the capacity of the LRU (Least Recently Used) cache, which stores critical CSS for pages.
1866
- */
1867
1063
  const MAX_INLINE_CSS_CACHE_ENTRIES = 50;
1868
- /**
1869
- * A mapping of `RenderMode` enum values to corresponding string representations.
1870
- *
1871
- * This record is used to map each `RenderMode` to a specific string value that represents
1872
- * the server context. The string values are used internally to differentiate
1873
- * between various rendering strategies when processing routes.
1874
- *
1875
- * - `RenderMode.Prerender` maps to `'ssg'` (Static Site Generation).
1876
- * - `RenderMode.Server` maps to `'ssr'` (Server-Side Rendering).
1877
- * - `RenderMode.Client` maps to an empty string `''` (Client-Side Rendering, no server context needed).
1878
- */
1879
1064
  const SERVER_CONTEXT_VALUE = {
1880
- [RenderMode.Prerender]: 'ssg',
1881
- [RenderMode.Server]: 'ssr',
1882
- [RenderMode.Client]: '',
1065
+ [RenderMode.Prerender]: 'ssg',
1066
+ [RenderMode.Server]: 'ssr',
1067
+ [RenderMode.Client]: ''
1883
1068
  };
1884
- /**
1885
- * Represents a locale-specific Angular server application managed by the server application engine.
1886
- *
1887
- * The `AngularServerApp` class handles server-side rendering and asset management for a specific locale.
1888
- */
1889
1069
  class AngularServerApp {
1890
- options;
1891
- /**
1892
- * Whether prerendered routes should be rendered on demand or served directly.
1893
- *
1894
- * @see {@link AngularServerAppOptions.allowStaticRouteRender} for more details.
1895
- */
1896
- allowStaticRouteRender;
1897
- /**
1898
- * Hooks for extending or modifying server behavior.
1899
- *
1900
- * @see {@link AngularServerAppOptions.hooks} for more details.
1901
- */
1902
- hooks;
1903
- /**
1904
- * Constructs an instance of `AngularServerApp`.
1905
- *
1906
- * @param options Optional configuration options for the server application.
1907
- */
1908
- constructor(options = {}) {
1909
- this.options = options;
1910
- this.allowStaticRouteRender = this.options.allowStaticRouteRender ?? false;
1911
- this.hooks = options.hooks ?? new Hooks();
1912
- if (this.manifest.inlineCriticalCss) {
1913
- this.inlineCriticalCssProcessor = new InlineCriticalCssProcessor((path) => {
1914
- const fileName = path.split('/').pop() ?? path;
1915
- return this.assets.getServerAsset(fileName).text();
1916
- });
1917
- }
1918
- }
1919
- /**
1920
- * The manifest associated with this server application.
1921
- */
1922
- manifest = getAngularAppManifest();
1923
- /**
1924
- * An instance of ServerAsset that handles server-side asset.
1925
- */
1926
- assets = new ServerAssets(this.manifest);
1927
- /**
1928
- * The router instance used for route matching and handling.
1929
- */
1930
- router;
1931
- /**
1932
- * The `inlineCriticalCssProcessor` is responsible for handling critical CSS inlining.
1933
- */
1934
- inlineCriticalCssProcessor;
1935
- /**
1936
- * The bootstrap mechanism for the server application.
1937
- */
1938
- boostrap;
1939
- /**
1940
- * Decorder used to convert a string to a Uint8Array.
1941
- */
1942
- textDecoder = new TextEncoder();
1943
- /**
1944
- * A cache that stores critical CSS to avoid re-processing for every request, improving performance.
1945
- * This cache uses a Least Recently Used (LRU) eviction policy.
1946
- *
1947
- * @see {@link MAX_INLINE_CSS_CACHE_ENTRIES} for the maximum number of entries this cache can hold.
1948
- */
1949
- criticalCssLRUCache = new LRUCache(MAX_INLINE_CSS_CACHE_ENTRIES);
1950
- /**
1951
- * Handles an incoming HTTP request by serving prerendered content, performing server-side rendering,
1952
- * or delivering a static file for client-side rendered routes based on the `RenderMode` setting.
1953
- *
1954
- * @param request - The HTTP request to handle.
1955
- * @param requestContext - Optional context for rendering, such as metadata associated with the request.
1956
- * @returns A promise that resolves to the resulting HTTP response object, or `null` if no matching Angular route is found.
1957
- *
1958
- * @remarks A request to `https://www.example.com/page/index.html` will serve or render the Angular route
1959
- * corresponding to `https://www.example.com/page`.
1960
- */
1961
- async handle(request, requestContext) {
1962
- const url = new URL(request.url);
1963
- this.router ??= await ServerRouter.from(this.manifest, url);
1964
- const matchedRoute = this.router.match(url);
1965
- if (!matchedRoute) {
1966
- // Not a known Angular route.
1967
- return null;
1968
- }
1969
- const { redirectTo, status, renderMode } = matchedRoute;
1970
- if (redirectTo !== undefined) {
1971
- return createRedirectResponse(buildPathWithParams(redirectTo, url.pathname), status);
1972
- }
1973
- if (renderMode === RenderMode.Prerender) {
1974
- const response = await this.handleServe(request, matchedRoute);
1975
- if (response) {
1976
- return response;
1977
- }
1978
- }
1979
- return promiseWithAbort(this.handleRendering(request, matchedRoute, requestContext), request.signal, `Request for: ${request.url}`);
1980
- }
1981
- /**
1982
- * Handles serving a prerendered static asset if available for the matched route.
1983
- *
1984
- * This method only supports `GET` and `HEAD` requests.
1985
- *
1986
- * @param request - The incoming HTTP request for serving a static page.
1987
- * @param matchedRoute - The metadata of the matched route for rendering.
1988
- * @returns A promise that resolves to a `Response` object if the prerendered page is found, or `null`.
1989
- */
1990
- async handleServe(request, matchedRoute) {
1991
- const { headers, renderMode } = matchedRoute;
1992
- if (renderMode !== RenderMode.Prerender) {
1993
- return null;
1994
- }
1995
- const { method } = request;
1996
- if (method !== 'GET' && method !== 'HEAD') {
1997
- return null;
1998
- }
1999
- const assetPath = this.buildServerAssetPathFromRequest(request);
2000
- const { manifest: { locale }, assets, } = this;
2001
- if (!assets.hasServerAsset(assetPath)) {
2002
- return null;
2003
- }
2004
- const { text, hash, size } = assets.getServerAsset(assetPath);
2005
- const etag = `"${hash}"`;
2006
- return request.headers.get('if-none-match') === etag
2007
- ? new Response(undefined, { status: 304, statusText: 'Not Modified' })
2008
- : new Response(await text(), {
2009
- headers: {
2010
- 'Content-Length': size.toString(),
2011
- 'ETag': etag,
2012
- 'Content-Type': 'text/html;charset=UTF-8',
2013
- ...(locale !== undefined ? { 'Content-Language': locale } : {}),
2014
- ...headers,
2015
- },
2016
- });
2017
- }
2018
- /**
2019
- * Handles the server-side rendering process for the given HTTP request.
2020
- * This method matches the request URL to a route and performs rendering if a matching route is found.
2021
- *
2022
- * @param request - The incoming HTTP request to be processed.
2023
- * @param matchedRoute - The metadata of the matched route for rendering.
2024
- * @param requestContext - Optional additional context for rendering, such as request metadata.
2025
- *
2026
- * @returns A promise that resolves to the rendered response, or null if no matching route is found.
2027
- */
2028
- async handleRendering(request, matchedRoute, requestContext) {
2029
- const { renderMode, headers, status, preload } = matchedRoute;
2030
- if (!this.allowStaticRouteRender && renderMode === RenderMode.Prerender) {
2031
- return null;
2032
- }
2033
- const url = new URL(request.url);
2034
- const platformProviders = [];
2035
- const { manifest: { bootstrap, locale }, assets, } = this;
2036
- // Initialize the response with status and headers if available.
2037
- const responseInit = {
2038
- status,
2039
- headers: new Headers({
2040
- 'Content-Type': 'text/html;charset=UTF-8',
2041
- ...(locale !== undefined ? { 'Content-Language': locale } : {}),
2042
- ...headers,
2043
- }),
2044
- };
2045
- if (renderMode === RenderMode.Server) {
2046
- // Configure platform providers for request and response only for SSR.
2047
- platformProviders.push({
2048
- provide: REQUEST,
2049
- useValue: request,
2050
- }, {
2051
- provide: REQUEST_CONTEXT,
2052
- useValue: requestContext,
2053
- }, {
2054
- provide: RESPONSE_INIT,
2055
- useValue: responseInit,
2056
- });
2057
- }
2058
- else if (renderMode === RenderMode.Client) {
2059
- // Serve the client-side rendered version if the route is configured for CSR.
2060
- let html = await this.assets.getServerAsset('index.csr.html').text();
2061
- html = await this.runTransformsOnHtml(html, url, preload);
2062
- return new Response(html, responseInit);
2063
- }
2064
- if (locale !== undefined) {
2065
- platformProviders.push({
2066
- provide: LOCALE_ID,
2067
- useValue: locale,
2068
- });
2069
- }
2070
- this.boostrap ??= await bootstrap();
2071
- let html = await assets.getIndexServerHtml().text();
2072
- html = await this.runTransformsOnHtml(html, url, preload);
2073
- const result = await renderAngular(html, this.boostrap, url, platformProviders, SERVER_CONTEXT_VALUE[renderMode]);
2074
- if (result.hasNavigationError) {
2075
- return null;
2076
- }
2077
- if (result.redirectTo) {
2078
- return createRedirectResponse(result.redirectTo, status);
2079
- }
2080
- if (renderMode === RenderMode.Prerender) {
2081
- const renderedHtml = await result.content();
2082
- const finalHtml = await this.inlineCriticalCss(renderedHtml, url);
2083
- return new Response(finalHtml, responseInit);
2084
- }
2085
- // Use a stream to send the response before finishing rendering and inling critical CSS, improving performance via header flushing.
2086
- const stream = new ReadableStream({
2087
- start: async (controller) => {
2088
- const renderedHtml = await result.content();
2089
- const finalHtml = await this.inlineCriticalCssWithCache(renderedHtml, url);
2090
- controller.enqueue(finalHtml);
2091
- controller.close();
2092
- },
2093
- });
2094
- return new Response(stream, responseInit);
2095
- }
2096
- /**
2097
- * Inlines critical CSS into the given HTML content.
2098
- *
2099
- * @param html The HTML content to process.
2100
- * @param url The URL associated with the request, for logging purposes.
2101
- * @returns A promise that resolves to the HTML with inlined critical CSS.
2102
- */
2103
- async inlineCriticalCss(html, url) {
2104
- const { inlineCriticalCssProcessor } = this;
2105
- if (!inlineCriticalCssProcessor) {
2106
- return html;
2107
- }
2108
- try {
2109
- return await inlineCriticalCssProcessor.process(html);
2110
- }
2111
- catch (error) {
2112
- // eslint-disable-next-line no-console
2113
- console.error(`An error occurred while inlining critical CSS for: ${url}.`, error);
2114
- return html;
2115
- }
2116
- }
2117
- /**
2118
- * Inlines critical CSS into the given HTML content.
2119
- * This method uses a cache to avoid reprocessing the same HTML content multiple times.
2120
- *
2121
- * @param html The HTML content to process.
2122
- * @param url The URL associated with the request, for logging purposes.
2123
- * @returns A promise that resolves to the HTML with inlined critical CSS.
2124
- */
2125
- async inlineCriticalCssWithCache(html, url) {
2126
- const { inlineCriticalCssProcessor, criticalCssLRUCache, textDecoder } = this;
2127
- if (!inlineCriticalCssProcessor) {
2128
- return textDecoder.encode(html);
2129
- }
2130
- const cacheKey = url.toString();
2131
- const cached = criticalCssLRUCache.get(cacheKey);
2132
- const shaOfContentPreInlinedCss = await sha256(html);
2133
- if (cached?.shaOfContentPreInlinedCss === shaOfContentPreInlinedCss) {
2134
- return cached.contentWithCriticialCSS;
2135
- }
2136
- const processedHtml = await this.inlineCriticalCss(html, url);
2137
- const finalHtml = textDecoder.encode(processedHtml);
2138
- criticalCssLRUCache.put(cacheKey, {
2139
- shaOfContentPreInlinedCss,
2140
- contentWithCriticialCSS: finalHtml,
2141
- });
2142
- return finalHtml;
2143
- }
2144
- /**
2145
- * Constructs the asset path on the server based on the provided HTTP request.
2146
- *
2147
- * This method processes the incoming request URL to derive a path corresponding
2148
- * to the requested asset. It ensures the path points to the correct file (e.g.,
2149
- * `index.html`) and removes any base href if it is not part of the asset path.
2150
- *
2151
- * @param request - The incoming HTTP request object.
2152
- * @returns The server-relative asset path derived from the request.
2153
- */
2154
- buildServerAssetPathFromRequest(request) {
2155
- let { pathname: assetPath } = new URL(request.url);
2156
- if (!assetPath.endsWith('/index.html')) {
2157
- // Append "index.html" to build the default asset path.
2158
- assetPath = joinUrlParts(assetPath, 'index.html');
2159
- }
2160
- const { baseHref } = this.manifest;
2161
- // Check if the asset path starts with the base href and the base href is not (`/` or ``).
2162
- if (baseHref.length > 1 && assetPath.startsWith(baseHref)) {
2163
- // Remove the base href from the start of the asset path to align with server-asset expectations.
2164
- assetPath = assetPath.slice(baseHref.length);
2165
- }
2166
- return stripLeadingSlash(assetPath);
2167
- }
2168
- /**
2169
- * Runs the registered transform hooks on the given HTML content.
2170
- *
2171
- * @param html - The raw HTML content to be transformed.
2172
- * @param url - The URL associated with the HTML content, used for context during transformations.
2173
- * @param preload - An array of URLs representing the JavaScript resources to preload.
2174
- * @returns A promise that resolves to the transformed HTML string.
2175
- */
2176
- async runTransformsOnHtml(html, url, preload) {
2177
- if (this.hooks.has('html:transform:pre')) {
2178
- html = await this.hooks.run('html:transform:pre', { html, url });
2179
- }
2180
- if (preload?.length) {
2181
- html = appendPreloadHintsToHtml(html, preload);
2182
- }
2183
- return html;
1070
+ options;
1071
+ allowStaticRouteRender;
1072
+ hooks;
1073
+ constructor(options = {}) {
1074
+ this.options = options;
1075
+ this.allowStaticRouteRender = this.options.allowStaticRouteRender ?? false;
1076
+ this.hooks = options.hooks ?? new Hooks();
1077
+ if (this.manifest.inlineCriticalCss) {
1078
+ this.inlineCriticalCssProcessor = new InlineCriticalCssProcessor(path => {
1079
+ const fileName = path.split('/').pop() ?? path;
1080
+ return this.assets.getServerAsset(fileName).text();
1081
+ });
1082
+ }
1083
+ }
1084
+ manifest = getAngularAppManifest();
1085
+ assets = new ServerAssets(this.manifest);
1086
+ router;
1087
+ inlineCriticalCssProcessor;
1088
+ boostrap;
1089
+ textDecoder = new TextEncoder();
1090
+ criticalCssLRUCache = new LRUCache(MAX_INLINE_CSS_CACHE_ENTRIES);
1091
+ async handle(request, requestContext) {
1092
+ const url = new URL(request.url);
1093
+ this.router ??= await ServerRouter.from(this.manifest, url);
1094
+ const matchedRoute = this.router.match(url);
1095
+ if (!matchedRoute) {
1096
+ return null;
1097
+ }
1098
+ const {
1099
+ redirectTo,
1100
+ status,
1101
+ renderMode
1102
+ } = matchedRoute;
1103
+ if (redirectTo !== undefined) {
1104
+ return createRedirectResponse(buildPathWithParams(redirectTo, url.pathname), status);
1105
+ }
1106
+ if (renderMode === RenderMode.Prerender) {
1107
+ const response = await this.handleServe(request, matchedRoute);
1108
+ if (response) {
1109
+ return response;
1110
+ }
1111
+ }
1112
+ return promiseWithAbort(this.handleRendering(request, matchedRoute, requestContext), request.signal, `Request for: ${request.url}`);
1113
+ }
1114
+ async handleServe(request, matchedRoute) {
1115
+ const {
1116
+ headers,
1117
+ renderMode
1118
+ } = matchedRoute;
1119
+ if (renderMode !== RenderMode.Prerender) {
1120
+ return null;
1121
+ }
1122
+ const {
1123
+ method
1124
+ } = request;
1125
+ if (method !== 'GET' && method !== 'HEAD') {
1126
+ return null;
1127
+ }
1128
+ const assetPath = this.buildServerAssetPathFromRequest(request);
1129
+ const {
1130
+ manifest: {
1131
+ locale
1132
+ },
1133
+ assets
1134
+ } = this;
1135
+ if (!assets.hasServerAsset(assetPath)) {
1136
+ return null;
1137
+ }
1138
+ const {
1139
+ text,
1140
+ hash,
1141
+ size
1142
+ } = assets.getServerAsset(assetPath);
1143
+ const etag = `"${hash}"`;
1144
+ return request.headers.get('if-none-match') === etag ? new Response(undefined, {
1145
+ status: 304,
1146
+ statusText: 'Not Modified'
1147
+ }) : new Response(await text(), {
1148
+ headers: {
1149
+ 'Content-Length': size.toString(),
1150
+ 'ETag': etag,
1151
+ 'Content-Type': 'text/html;charset=UTF-8',
1152
+ ...(locale !== undefined ? {
1153
+ 'Content-Language': locale
1154
+ } : {}),
1155
+ ...headers
1156
+ }
1157
+ });
1158
+ }
1159
+ async handleRendering(request, matchedRoute, requestContext) {
1160
+ const {
1161
+ renderMode,
1162
+ headers,
1163
+ status,
1164
+ preload
1165
+ } = matchedRoute;
1166
+ if (!this.allowStaticRouteRender && renderMode === RenderMode.Prerender) {
1167
+ return null;
1168
+ }
1169
+ const url = new URL(request.url);
1170
+ const platformProviders = [];
1171
+ const {
1172
+ manifest: {
1173
+ bootstrap,
1174
+ locale
1175
+ },
1176
+ assets
1177
+ } = this;
1178
+ const responseInit = {
1179
+ status,
1180
+ headers: new Headers({
1181
+ 'Content-Type': 'text/html;charset=UTF-8',
1182
+ ...(locale !== undefined ? {
1183
+ 'Content-Language': locale
1184
+ } : {}),
1185
+ ...headers
1186
+ })
1187
+ };
1188
+ if (renderMode === RenderMode.Server) {
1189
+ platformProviders.push({
1190
+ provide: REQUEST,
1191
+ useValue: request
1192
+ }, {
1193
+ provide: REQUEST_CONTEXT,
1194
+ useValue: requestContext
1195
+ }, {
1196
+ provide: RESPONSE_INIT,
1197
+ useValue: responseInit
1198
+ });
1199
+ } else if (renderMode === RenderMode.Client) {
1200
+ let html = await this.assets.getServerAsset('index.csr.html').text();
1201
+ html = await this.runTransformsOnHtml(html, url, preload);
1202
+ return new Response(html, responseInit);
1203
+ }
1204
+ if (locale !== undefined) {
1205
+ platformProviders.push({
1206
+ provide: LOCALE_ID,
1207
+ useValue: locale
1208
+ });
1209
+ }
1210
+ this.boostrap ??= await bootstrap();
1211
+ let html = await assets.getIndexServerHtml().text();
1212
+ html = await this.runTransformsOnHtml(html, url, preload);
1213
+ const result = await renderAngular(html, this.boostrap, url, platformProviders, SERVER_CONTEXT_VALUE[renderMode]);
1214
+ if (result.hasNavigationError) {
1215
+ return null;
1216
+ }
1217
+ if (result.redirectTo) {
1218
+ return createRedirectResponse(result.redirectTo, status);
1219
+ }
1220
+ if (renderMode === RenderMode.Prerender) {
1221
+ const renderedHtml = await result.content();
1222
+ const finalHtml = await this.inlineCriticalCss(renderedHtml, url);
1223
+ return new Response(finalHtml, responseInit);
1224
+ }
1225
+ const stream = new ReadableStream({
1226
+ start: async controller => {
1227
+ const renderedHtml = await result.content();
1228
+ const finalHtml = await this.inlineCriticalCssWithCache(renderedHtml, url);
1229
+ controller.enqueue(finalHtml);
1230
+ controller.close();
1231
+ }
1232
+ });
1233
+ return new Response(stream, responseInit);
1234
+ }
1235
+ async inlineCriticalCss(html, url) {
1236
+ const {
1237
+ inlineCriticalCssProcessor
1238
+ } = this;
1239
+ if (!inlineCriticalCssProcessor) {
1240
+ return html;
2184
1241
  }
1242
+ try {
1243
+ return await inlineCriticalCssProcessor.process(html);
1244
+ } catch (error) {
1245
+ console.error(`An error occurred while inlining critical CSS for: ${url}.`, error);
1246
+ return html;
1247
+ }
1248
+ }
1249
+ async inlineCriticalCssWithCache(html, url) {
1250
+ const {
1251
+ inlineCriticalCssProcessor,
1252
+ criticalCssLRUCache,
1253
+ textDecoder
1254
+ } = this;
1255
+ if (!inlineCriticalCssProcessor) {
1256
+ return textDecoder.encode(html);
1257
+ }
1258
+ const cacheKey = url.toString();
1259
+ const cached = criticalCssLRUCache.get(cacheKey);
1260
+ const shaOfContentPreInlinedCss = await sha256(html);
1261
+ if (cached?.shaOfContentPreInlinedCss === shaOfContentPreInlinedCss) {
1262
+ return cached.contentWithCriticialCSS;
1263
+ }
1264
+ const processedHtml = await this.inlineCriticalCss(html, url);
1265
+ const finalHtml = textDecoder.encode(processedHtml);
1266
+ criticalCssLRUCache.put(cacheKey, {
1267
+ shaOfContentPreInlinedCss,
1268
+ contentWithCriticialCSS: finalHtml
1269
+ });
1270
+ return finalHtml;
1271
+ }
1272
+ buildServerAssetPathFromRequest(request) {
1273
+ let {
1274
+ pathname: assetPath
1275
+ } = new URL(request.url);
1276
+ if (!assetPath.endsWith('/index.html')) {
1277
+ assetPath = joinUrlParts(assetPath, 'index.html');
1278
+ }
1279
+ const {
1280
+ baseHref
1281
+ } = this.manifest;
1282
+ if (baseHref.length > 1 && assetPath.startsWith(baseHref)) {
1283
+ assetPath = assetPath.slice(baseHref.length);
1284
+ }
1285
+ return stripLeadingSlash(assetPath);
1286
+ }
1287
+ async runTransformsOnHtml(html, url, preload) {
1288
+ if (this.hooks.has('html:transform:pre')) {
1289
+ html = await this.hooks.run('html:transform:pre', {
1290
+ html,
1291
+ url
1292
+ });
1293
+ }
1294
+ if (preload?.length) {
1295
+ html = appendPreloadHintsToHtml(html, preload);
1296
+ }
1297
+ return html;
1298
+ }
2185
1299
  }
2186
1300
  let angularServerApp;
2187
- /**
2188
- * Retrieves or creates an instance of `AngularServerApp`.
2189
- * - If an instance of `AngularServerApp` already exists, it will return the existing one.
2190
- * - If no instance exists, it will create a new one with the provided options.
2191
- *
2192
- * @param options Optional configuration options for the server application.
2193
- *
2194
- * @returns The existing or newly created instance of `AngularServerApp`.
2195
- */
2196
1301
  function getOrCreateAngularServerApp(options) {
2197
- return (angularServerApp ??= new AngularServerApp(options));
1302
+ return angularServerApp ??= new AngularServerApp(options);
2198
1303
  }
2199
- /**
2200
- * Destroys the existing `AngularServerApp` instance, releasing associated resources and resetting the
2201
- * reference to `undefined`.
2202
- *
2203
- * This function is primarily used to enable the recreation of the `AngularServerApp` instance,
2204
- * typically when server configuration or application state needs to be refreshed.
2205
- */
2206
1304
  function destroyAngularServerApp() {
2207
- if (typeof ngDevMode === 'undefined' || ngDevMode) {
2208
- // Need to clean up GENERATED_COMP_IDS map in `@angular/core`.
2209
- // Otherwise an incorrect component ID generation collision detected warning will be displayed in development.
2210
- // See: https://github.com/angular/angular-cli/issues/25924
2211
- _resetCompiledComponents();
2212
- }
2213
- angularServerApp = undefined;
1305
+ if (typeof ngDevMode === 'undefined' || ngDevMode) {
1306
+ _resetCompiledComponents();
1307
+ }
1308
+ angularServerApp = undefined;
2214
1309
  }
2215
- /**
2216
- * Appends module preload hints to an HTML string for specified JavaScript resources.
2217
- * This function enhances the HTML by injecting `<link rel="modulepreload">` elements
2218
- * for each provided resource, allowing browsers to preload the specified JavaScript
2219
- * modules for better performance.
2220
- *
2221
- * @param html - The original HTML string to which preload hints will be added.
2222
- * @param preload - An array of URLs representing the JavaScript resources to preload.
2223
- * @returns The modified HTML string with the preload hints injected before the closing `</body>` tag.
2224
- * If `</body>` is not found, the links are not added.
2225
- */
2226
1310
  function appendPreloadHintsToHtml(html, preload) {
2227
- const bodyCloseIdx = html.lastIndexOf('</body>');
2228
- if (bodyCloseIdx === -1) {
2229
- return html;
2230
- }
2231
- // Note: Module preloads should be placed at the end before the closing body tag to avoid a performance penalty.
2232
- // Placing them earlier can cause the browser to prioritize downloading these modules
2233
- // over other critical page resources like images, CSS, and fonts.
2234
- return [
2235
- html.slice(0, bodyCloseIdx),
2236
- ...preload.map((val) => `<link rel="modulepreload" href="${val}">`),
2237
- html.slice(bodyCloseIdx),
2238
- ].join('\n');
1311
+ const bodyCloseIdx = html.lastIndexOf('</body>');
1312
+ if (bodyCloseIdx === -1) {
1313
+ return html;
1314
+ }
1315
+ return [html.slice(0, bodyCloseIdx), ...preload.map(val => `<link rel="modulepreload" href="${val}">`), html.slice(bodyCloseIdx)].join('\n');
2239
1316
  }
2240
- /**
2241
- * Creates an HTTP redirect response with a specified location and status code.
2242
- *
2243
- * @param location - The URL to which the response should redirect.
2244
- * @param status - The HTTP status code for the redirection. Defaults to 302 (Found).
2245
- * See: https://developer.mozilla.org/en-US/docs/Web/API/Response/redirect_static#status
2246
- * @returns A `Response` object representing the HTTP redirect.
2247
- */
2248
1317
  function createRedirectResponse(location, status = 302) {
2249
- return new Response(null, {
2250
- status,
2251
- headers: {
2252
- 'Location': location,
2253
- },
2254
- });
1318
+ return new Response(null, {
1319
+ status,
1320
+ headers: {
1321
+ 'Location': location
1322
+ }
1323
+ });
2255
1324
  }
2256
1325
 
2257
- /**
2258
- * Extracts a potential locale ID from a given URL based on the specified base path.
2259
- *
2260
- * This function parses the URL to locate a potential locale identifier that immediately
2261
- * follows the base path segment in the URL's pathname. If the URL does not contain a valid
2262
- * locale ID, an empty string is returned.
2263
- *
2264
- * @param url - The full URL from which to extract the locale ID.
2265
- * @param basePath - The base path used as the reference point for extracting the locale ID.
2266
- * @returns The extracted locale ID if present, or an empty string if no valid locale ID is found.
2267
- *
2268
- * @example
2269
- * ```js
2270
- * const url = new URL('https://example.com/base/en/page');
2271
- * const basePath = '/base';
2272
- * const localeId = getPotentialLocaleIdFromUrl(url, basePath);
2273
- * console.log(localeId); // Output: 'en'
2274
- * ```
2275
- */
2276
1326
  function getPotentialLocaleIdFromUrl(url, basePath) {
2277
- const { pathname } = url;
2278
- // Move forward of the base path section.
2279
- let start = basePath.length;
2280
- if (pathname[start] === '/') {
2281
- start++;
2282
- }
2283
- // Find the next forward slash.
2284
- let end = pathname.indexOf('/', start);
2285
- if (end === -1) {
2286
- end = pathname.length;
2287
- }
2288
- // Extract the potential locale id.
2289
- return pathname.slice(start, end);
1327
+ const {
1328
+ pathname
1329
+ } = url;
1330
+ let start = basePath.length;
1331
+ if (pathname[start] === '/') {
1332
+ start++;
1333
+ }
1334
+ let end = pathname.indexOf('/', start);
1335
+ if (end === -1) {
1336
+ end = pathname.length;
1337
+ }
1338
+ return pathname.slice(start, end);
2290
1339
  }
2291
- /**
2292
- * Parses the `Accept-Language` header and returns a list of locale preferences with their respective quality values.
2293
- *
2294
- * The `Accept-Language` header is typically a comma-separated list of locales, with optional quality values
2295
- * in the form of `q=<value>`. If no quality value is specified, a default quality of `1` is assumed.
2296
- * Special case: if the header is `*`, it returns the default locale with a quality of `1`.
2297
- *
2298
- * @param header - The value of the `Accept-Language` header, typically a comma-separated list of locales
2299
- * with optional quality values (e.g., `en-US;q=0.8,fr-FR;q=0.9`). If the header is `*`,
2300
- * it represents a wildcard for any language, returning the default locale.
2301
- *
2302
- * @returns A `ReadonlyMap` where the key is the locale (e.g., `en-US`, `fr-FR`), and the value is
2303
- * the associated quality value (a number between 0 and 1). If no quality value is provided,
2304
- * a default of `1` is used.
2305
- *
2306
- * @example
2307
- * ```js
2308
- * parseLanguageHeader('en-US;q=0.8,fr-FR;q=0.9')
2309
- * // returns new Map([['en-US', 0.8], ['fr-FR', 0.9]])
2310
-
2311
- * parseLanguageHeader('*')
2312
- * // returns new Map([['*', 1]])
2313
- * ```
2314
- */
2315
1340
  function parseLanguageHeader(header) {
2316
- if (header === '*') {
2317
- return new Map([['*', 1]]);
2318
- }
2319
- const parsedValues = header
2320
- .split(',')
2321
- .map((item) => {
2322
- const [locale, qualityValue] = item.split(';', 2).map((v) => v.trim());
2323
- let quality = qualityValue?.startsWith('q=') ? parseFloat(qualityValue.slice(2)) : undefined;
2324
- if (typeof quality !== 'number' || isNaN(quality) || quality < 0 || quality > 1) {
2325
- quality = 1; // Invalid quality value defaults to 1
2326
- }
2327
- return [locale, quality];
2328
- })
2329
- .sort(([_localeA, qualityA], [_localeB, qualityB]) => qualityB - qualityA);
2330
- return new Map(parsedValues);
1341
+ if (header === '*') {
1342
+ return new Map([['*', 1]]);
1343
+ }
1344
+ const parsedValues = header.split(',').map(item => {
1345
+ const [locale, qualityValue] = item.split(';', 2).map(v => v.trim());
1346
+ let quality = qualityValue?.startsWith('q=') ? parseFloat(qualityValue.slice(2)) : undefined;
1347
+ if (typeof quality !== 'number' || isNaN(quality) || quality < 0 || quality > 1) {
1348
+ quality = 1;
1349
+ }
1350
+ return [locale, quality];
1351
+ }).sort(([_localeA, qualityA], [_localeB, qualityB]) => qualityB - qualityA);
1352
+ return new Map(parsedValues);
2331
1353
  }
2332
- /**
2333
- * Gets the preferred locale based on the highest quality value from the provided `Accept-Language` header
2334
- * and the set of available locales.
2335
- *
2336
- * This function adheres to the HTTP `Accept-Language` header specification as defined in
2337
- * [RFC 7231](https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.5), including:
2338
- * - Case-insensitive matching of language tags.
2339
- * - Quality value handling (e.g., `q=1`, `q=0.8`). If no quality value is provided, it defaults to `q=1`.
2340
- * - Prefix matching (e.g., `en` matching `en-US` or `en-GB`).
2341
- *
2342
- * @param header - The `Accept-Language` header string to parse and evaluate. It may contain multiple
2343
- * locales with optional quality values, for example: `'en-US;q=0.8,fr-FR;q=0.9'`.
2344
- * @param supportedLocales - An array of supported locales (e.g., `['en-US', 'fr-FR']`),
2345
- * representing the locales available in the application.
2346
- * @returns The best matching locale from the supported languages, or `undefined` if no match is found.
2347
- *
2348
- * @example
2349
- * ```js
2350
- * getPreferredLocale('en-US;q=0.8,fr-FR;q=0.9', ['en-US', 'fr-FR', 'de-DE'])
2351
- * // returns 'fr-FR'
2352
- *
2353
- * getPreferredLocale('en;q=0.9,fr-FR;q=0.8', ['en-US', 'fr-FR', 'de-DE'])
2354
- * // returns 'en-US'
2355
- *
2356
- * getPreferredLocale('es-ES;q=0.7', ['en-US', 'fr-FR', 'de-DE'])
2357
- * // returns undefined
2358
- * ```
2359
- */
2360
1354
  function getPreferredLocale(header, supportedLocales) {
2361
- if (supportedLocales.length < 2) {
2362
- return supportedLocales[0];
2363
- }
2364
- const parsedLocales = parseLanguageHeader(header);
2365
- // Handle edge cases:
2366
- // - No preferred locales provided.
2367
- // - Only one supported locale.
2368
- // - Wildcard preference.
2369
- if (parsedLocales.size === 0 || (parsedLocales.size === 1 && parsedLocales.has('*'))) {
2370
- return supportedLocales[0];
2371
- }
2372
- // Create a map for case-insensitive lookup of supported locales.
2373
- // Keys are normalized (lowercase) locale values, values are original casing.
2374
- const normalizedSupportedLocales = new Map();
2375
- for (const locale of supportedLocales) {
2376
- normalizedSupportedLocales.set(normalizeLocale(locale), locale);
2377
- }
2378
- // Iterate through parsed locales in descending order of quality.
2379
- let bestMatch;
2380
- const qualityZeroNormalizedLocales = new Set();
2381
- for (const [locale, quality] of parsedLocales) {
2382
- const normalizedLocale = normalizeLocale(locale);
2383
- if (quality === 0) {
2384
- qualityZeroNormalizedLocales.add(normalizedLocale);
2385
- continue; // Skip locales with quality value of 0.
2386
- }
2387
- // Exact match found.
2388
- if (normalizedSupportedLocales.has(normalizedLocale)) {
2389
- return normalizedSupportedLocales.get(normalizedLocale);
2390
- }
2391
- // If an exact match is not found, try prefix matching (e.g., "en" matches "en-US").
2392
- // Store the first prefix match encountered, as it has the highest quality value.
2393
- if (bestMatch !== undefined) {
2394
- continue;
2395
- }
2396
- const [languagePrefix] = normalizedLocale.split('-', 1);
2397
- for (const supportedLocale of normalizedSupportedLocales.keys()) {
2398
- if (supportedLocale.startsWith(languagePrefix)) {
2399
- bestMatch = normalizedSupportedLocales.get(supportedLocale);
2400
- break; // No need to continue searching for this locale.
2401
- }
2402
- }
1355
+ if (supportedLocales.length < 2) {
1356
+ return supportedLocales[0];
1357
+ }
1358
+ const parsedLocales = parseLanguageHeader(header);
1359
+ if (parsedLocales.size === 0 || parsedLocales.size === 1 && parsedLocales.has('*')) {
1360
+ return supportedLocales[0];
1361
+ }
1362
+ const normalizedSupportedLocales = new Map();
1363
+ for (const locale of supportedLocales) {
1364
+ normalizedSupportedLocales.set(normalizeLocale(locale), locale);
1365
+ }
1366
+ let bestMatch;
1367
+ const qualityZeroNormalizedLocales = new Set();
1368
+ for (const [locale, quality] of parsedLocales) {
1369
+ const normalizedLocale = normalizeLocale(locale);
1370
+ if (quality === 0) {
1371
+ qualityZeroNormalizedLocales.add(normalizedLocale);
1372
+ continue;
1373
+ }
1374
+ if (normalizedSupportedLocales.has(normalizedLocale)) {
1375
+ return normalizedSupportedLocales.get(normalizedLocale);
2403
1376
  }
2404
1377
  if (bestMatch !== undefined) {
2405
- return bestMatch;
2406
- }
2407
- // Return the first locale that is not quality zero.
2408
- for (const [normalizedLocale, locale] of normalizedSupportedLocales) {
2409
- if (!qualityZeroNormalizedLocales.has(normalizedLocale)) {
2410
- return locale;
2411
- }
2412
- }
1378
+ continue;
1379
+ }
1380
+ const [languagePrefix] = normalizedLocale.split('-', 1);
1381
+ for (const supportedLocale of normalizedSupportedLocales.keys()) {
1382
+ if (supportedLocale.startsWith(languagePrefix)) {
1383
+ bestMatch = normalizedSupportedLocales.get(supportedLocale);
1384
+ break;
1385
+ }
1386
+ }
1387
+ }
1388
+ if (bestMatch !== undefined) {
1389
+ return bestMatch;
1390
+ }
1391
+ for (const [normalizedLocale, locale] of normalizedSupportedLocales) {
1392
+ if (!qualityZeroNormalizedLocales.has(normalizedLocale)) {
1393
+ return locale;
1394
+ }
1395
+ }
2413
1396
  }
2414
- /**
2415
- * Normalizes a locale string by converting it to lowercase.
2416
- *
2417
- * @param locale - The locale string to normalize.
2418
- * @returns The normalized locale string in lowercase.
2419
- *
2420
- * @example
2421
- * ```ts
2422
- * const normalized = normalizeLocale('EN-US');
2423
- * console.log(normalized); // Output: "en-us"
2424
- * ```
2425
- */
2426
1397
  function normalizeLocale(locale) {
2427
- return locale.toLowerCase();
1398
+ return locale.toLowerCase();
2428
1399
  }
2429
1400
 
2430
- /**
2431
- * Angular server application engine.
2432
- * Manages Angular server applications (including localized ones), handles rendering requests,
2433
- * and optionally transforms index HTML before rendering.
2434
- *
2435
- * @remarks This class should be instantiated once and used as a singleton across the server-side
2436
- * application to ensure consistent handling of rendering requests and resource management.
2437
- */
2438
1401
  class AngularAppEngine {
2439
- /**
2440
- * A flag to enable or disable the rendering of prerendered routes.
2441
- *
2442
- * Typically used during development to avoid prerendering all routes ahead of time,
2443
- * allowing them to be rendered on the fly as requested.
2444
- *
2445
- * @private
2446
- */
2447
- static ɵallowStaticRouteRender = false;
2448
- /**
2449
- * Hooks for extending or modifying the behavior of the server application.
2450
- * These hooks are used by the Angular CLI when running the development server and
2451
- * provide extensibility points for the application lifecycle.
2452
- *
2453
- * @private
2454
- */
2455
- static ɵhooks = /* #__PURE__*/ new Hooks();
2456
- /**
2457
- * The manifest for the server application.
2458
- */
2459
- manifest = getAngularAppEngineManifest();
2460
- /**
2461
- * A map of supported locales from the server application's manifest.
2462
- */
2463
- supportedLocales = Object.keys(this.manifest.supportedLocales);
2464
- /**
2465
- * A cache that holds entry points, keyed by their potential locale string.
2466
- */
2467
- entryPointsCache = new Map();
2468
- /**
2469
- * Handles an incoming HTTP request by serving prerendered content, performing server-side rendering,
2470
- * or delivering a static file for client-side rendered routes based on the `RenderMode` setting.
2471
- *
2472
- * @param request - The HTTP request to handle.
2473
- * @param requestContext - Optional context for rendering, such as metadata associated with the request.
2474
- * @returns A promise that resolves to the resulting HTTP response object, or `null` if no matching Angular route is found.
2475
- *
2476
- * @remarks A request to `https://www.example.com/page/index.html` will serve or render the Angular route
2477
- * corresponding to `https://www.example.com/page`.
2478
- */
2479
- async handle(request, requestContext) {
2480
- const serverApp = await this.getAngularServerAppForRequest(request);
2481
- if (serverApp) {
2482
- return serverApp.handle(request, requestContext);
2483
- }
2484
- if (this.supportedLocales.length > 1) {
2485
- // Redirect to the preferred language if i18n is enabled.
2486
- return this.redirectBasedOnAcceptLanguage(request);
2487
- }
2488
- return null;
2489
- }
2490
- /**
2491
- * Handles requests for the base path when i18n is enabled.
2492
- * Redirects the user to a locale-specific path based on the `Accept-Language` header.
2493
- *
2494
- * @param request The incoming request.
2495
- * @returns A `Response` object with a 302 redirect, or `null` if i18n is not enabled
2496
- * or the request is not for the base path.
2497
- */
2498
- redirectBasedOnAcceptLanguage(request) {
2499
- const { basePath, supportedLocales } = this.manifest;
2500
- // If the request is not for the base path, it's not our responsibility to handle it.
2501
- const { pathname } = new URL(request.url);
2502
- if (pathname !== basePath) {
2503
- return null;
2504
- }
2505
- // For requests to the base path (typically '/'), attempt to extract the preferred locale
2506
- // from the 'Accept-Language' header.
2507
- const preferredLocale = getPreferredLocale(request.headers.get('Accept-Language') || '*', this.supportedLocales);
2508
- if (preferredLocale) {
2509
- const subPath = supportedLocales[preferredLocale];
2510
- if (subPath !== undefined) {
2511
- return new Response(null, {
2512
- status: 302, // Use a 302 redirect as language preference may change.
2513
- headers: {
2514
- 'Location': joinUrlParts(pathname, subPath),
2515
- 'Vary': 'Accept-Language',
2516
- },
2517
- });
2518
- }
2519
- }
2520
- return null;
2521
- }
2522
- /**
2523
- * Retrieves the Angular server application instance for a given request.
2524
- *
2525
- * This method checks if the request URL corresponds to an Angular application entry point.
2526
- * If so, it initializes or retrieves an instance of the Angular server application for that entry point.
2527
- * Requests that resemble file requests (except for `/index.html`) are skipped.
2528
- *
2529
- * @param request - The incoming HTTP request object.
2530
- * @returns A promise that resolves to an `AngularServerApp` instance if a valid entry point is found,
2531
- * or `null` if no entry point matches the request URL.
2532
- */
2533
- async getAngularServerAppForRequest(request) {
2534
- // Skip if the request looks like a file but not `/index.html`.
2535
- const url = new URL(request.url);
2536
- const entryPoint = await this.getEntryPointExportsForUrl(url);
2537
- if (!entryPoint) {
2538
- return null;
2539
- }
2540
- // Note: Using `instanceof` is not feasible here because `AngularServerApp` will
2541
- // be located in separate bundles, making `instanceof` checks unreliable.
2542
- const ɵgetOrCreateAngularServerApp = entryPoint.ɵgetOrCreateAngularServerApp;
2543
- const serverApp = ɵgetOrCreateAngularServerApp({
2544
- allowStaticRouteRender: AngularAppEngine.ɵallowStaticRouteRender,
2545
- hooks: AngularAppEngine.ɵhooks,
1402
+ static ɵallowStaticRouteRender = false;
1403
+ static ɵhooks = /* #__PURE__*/new Hooks();
1404
+ manifest = getAngularAppEngineManifest();
1405
+ supportedLocales = Object.keys(this.manifest.supportedLocales);
1406
+ entryPointsCache = new Map();
1407
+ async handle(request, requestContext) {
1408
+ const serverApp = await this.getAngularServerAppForRequest(request);
1409
+ if (serverApp) {
1410
+ return serverApp.handle(request, requestContext);
1411
+ }
1412
+ if (this.supportedLocales.length > 1) {
1413
+ return this.redirectBasedOnAcceptLanguage(request);
1414
+ }
1415
+ return null;
1416
+ }
1417
+ redirectBasedOnAcceptLanguage(request) {
1418
+ const {
1419
+ basePath,
1420
+ supportedLocales
1421
+ } = this.manifest;
1422
+ const {
1423
+ pathname
1424
+ } = new URL(request.url);
1425
+ if (pathname !== basePath) {
1426
+ return null;
1427
+ }
1428
+ const preferredLocale = getPreferredLocale(request.headers.get('Accept-Language') || '*', this.supportedLocales);
1429
+ if (preferredLocale) {
1430
+ const subPath = supportedLocales[preferredLocale];
1431
+ if (subPath !== undefined) {
1432
+ return new Response(null, {
1433
+ status: 302,
1434
+ headers: {
1435
+ 'Location': joinUrlParts(pathname, subPath),
1436
+ 'Vary': 'Accept-Language'
1437
+ }
2546
1438
  });
2547
- return serverApp;
2548
- }
2549
- /**
2550
- * Retrieves the exports for a specific entry point, caching the result.
2551
- *
2552
- * @param potentialLocale - The locale string used to find the corresponding entry point.
2553
- * @returns A promise that resolves to the entry point exports or `undefined` if not found.
2554
- */
2555
- getEntryPointExports(potentialLocale) {
2556
- const cachedEntryPoint = this.entryPointsCache.get(potentialLocale);
2557
- if (cachedEntryPoint) {
2558
- return cachedEntryPoint;
2559
- }
2560
- const { entryPoints } = this.manifest;
2561
- const entryPoint = entryPoints[potentialLocale];
2562
- if (!entryPoint) {
2563
- return undefined;
2564
- }
2565
- const entryPointExports = entryPoint();
2566
- this.entryPointsCache.set(potentialLocale, entryPointExports);
2567
- return entryPointExports;
2568
- }
2569
- /**
2570
- * Retrieves the entry point for a given URL by determining the locale and mapping it to
2571
- * the appropriate application bundle.
2572
- *
2573
- * This method determines the appropriate entry point and locale for rendering the application by examining the URL.
2574
- * If there is only one entry point available, it is returned regardless of the URL.
2575
- * Otherwise, the method extracts a potential locale identifier from the URL and looks up the corresponding entry point.
2576
- *
2577
- * @param url - The URL of the request.
2578
- * @returns A promise that resolves to the entry point exports or `undefined` if not found.
2579
- */
2580
- getEntryPointExportsForUrl(url) {
2581
- const { basePath } = this.manifest;
2582
- if (this.supportedLocales.length === 1) {
2583
- return this.getEntryPointExports('');
2584
- }
2585
- const potentialLocale = getPotentialLocaleIdFromUrl(url, basePath);
2586
- return this.getEntryPointExports(potentialLocale) ?? this.getEntryPointExports('');
2587
- }
1439
+ }
1440
+ }
1441
+ return null;
1442
+ }
1443
+ async getAngularServerAppForRequest(request) {
1444
+ const url = new URL(request.url);
1445
+ const entryPoint = await this.getEntryPointExportsForUrl(url);
1446
+ if (!entryPoint) {
1447
+ return null;
1448
+ }
1449
+ const ɵgetOrCreateAngularServerApp = entryPoint.ɵgetOrCreateAngularServerApp;
1450
+ const serverApp = ɵgetOrCreateAngularServerApp({
1451
+ allowStaticRouteRender: AngularAppEngine.ɵallowStaticRouteRender,
1452
+ hooks: AngularAppEngine.ɵhooks
1453
+ });
1454
+ return serverApp;
1455
+ }
1456
+ getEntryPointExports(potentialLocale) {
1457
+ const cachedEntryPoint = this.entryPointsCache.get(potentialLocale);
1458
+ if (cachedEntryPoint) {
1459
+ return cachedEntryPoint;
1460
+ }
1461
+ const {
1462
+ entryPoints
1463
+ } = this.manifest;
1464
+ const entryPoint = entryPoints[potentialLocale];
1465
+ if (!entryPoint) {
1466
+ return undefined;
1467
+ }
1468
+ const entryPointExports = entryPoint();
1469
+ this.entryPointsCache.set(potentialLocale, entryPointExports);
1470
+ return entryPointExports;
1471
+ }
1472
+ getEntryPointExportsForUrl(url) {
1473
+ const {
1474
+ basePath
1475
+ } = this.manifest;
1476
+ if (this.supportedLocales.length === 1) {
1477
+ return this.getEntryPointExports('');
1478
+ }
1479
+ const potentialLocale = getPotentialLocaleIdFromUrl(url, basePath);
1480
+ return this.getEntryPointExports(potentialLocale) ?? this.getEntryPointExports('');
1481
+ }
2588
1482
  }
2589
1483
 
2590
- /**
2591
- * Annotates a request handler function with metadata, marking it as a special
2592
- * handler.
2593
- *
2594
- * @param handler - The request handler function to be annotated.
2595
- * @returns The same handler function passed in, with metadata attached.
2596
- *
2597
- * @example
2598
- * Example usage in a Hono application:
2599
- * ```ts
2600
- * const app = new Hono();
2601
- * export default createRequestHandler(app.fetch);
2602
- * ```
2603
- *
2604
- * @example
2605
- * Example usage in a H3 application:
2606
- * ```ts
2607
- * const app = createApp();
2608
- * const handler = toWebHandler(app);
2609
- * export default createRequestHandler(handler);
2610
- * ```
2611
- */
2612
1484
  function createRequestHandler(handler) {
2613
- handler['__ng_request_handler__'] = true;
2614
- return handler;
1485
+ handler['__ng_request_handler__'] = true;
1486
+ return handler;
2615
1487
  }
2616
1488
 
2617
1489
  export { AngularAppEngine, PrerenderFallback, RenderMode, createRequestHandler, provideServerRendering, withAppShell, withRoutes, InlineCriticalCssProcessor as ɵInlineCriticalCssProcessor, destroyAngularServerApp as ɵdestroyAngularServerApp, extractRoutesAndCreateRouteTree as ɵextractRoutesAndCreateRouteTree, getOrCreateAngularServerApp as ɵgetOrCreateAngularServerApp, getRoutesFromAngularRouterConfig as ɵgetRoutesFromAngularRouterConfig, setAngularAppEngineManifest as ɵsetAngularAppEngineManifest, setAngularAppManifest as ɵsetAngularAppManifest };