@angular/ssr 21.2.0-rc.0 → 21.2.0-rc.1

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.
@@ -0,0 +1,137 @@
1
+ const HOST_HEADERS_TO_VALIDATE = new Set(['host', 'x-forwarded-host']);
2
+ const VALID_PORT_REGEX = /^\d+$/;
3
+ const VALID_PROTO_REGEX = /^https?$/i;
4
+ const VALID_HOST_REGEX = /^[a-z0-9.:-]+$/i;
5
+ const INVALID_PREFIX_REGEX = /^[/\\]{2}|(?:^|[/\\])\.\.?(?:[/\\]|$)/;
6
+ function getFirstHeaderValue(value) {
7
+ return value?.toString().split(',', 1)[0]?.trim();
8
+ }
9
+ function validateRequest(request, allowedHosts) {
10
+ validateHeaders(request);
11
+ validateUrl(new URL(request.url), allowedHosts);
12
+ }
13
+ function validateUrl(url, allowedHosts) {
14
+ const {
15
+ hostname
16
+ } = url;
17
+ if (!isHostAllowed(hostname, allowedHosts)) {
18
+ throw new Error(`URL with hostname "${hostname}" is not allowed.`);
19
+ }
20
+ }
21
+ function cloneRequestAndPatchHeaders(request, allowedHosts) {
22
+ let onError;
23
+ const onErrorPromise = new Promise(resolve => {
24
+ onError = resolve;
25
+ });
26
+ const clonedReq = new Request(request.clone(), {
27
+ signal: request.signal
28
+ });
29
+ const headers = clonedReq.headers;
30
+ const originalGet = headers.get;
31
+ headers.get = function (name) {
32
+ const value = originalGet.call(headers, name);
33
+ if (!value) {
34
+ return value;
35
+ }
36
+ validateHeader(name, value, allowedHosts, onError);
37
+ return value;
38
+ };
39
+ const originalValues = headers.values;
40
+ headers.values = function () {
41
+ for (const name of HOST_HEADERS_TO_VALIDATE) {
42
+ validateHeader(name, originalGet.call(headers, name), allowedHosts, onError);
43
+ }
44
+ return originalValues.call(headers);
45
+ };
46
+ const originalEntries = headers.entries;
47
+ headers.entries = function () {
48
+ const iterator = originalEntries.call(headers);
49
+ return {
50
+ next() {
51
+ const result = iterator.next();
52
+ if (!result.done) {
53
+ const [key, value] = result.value;
54
+ validateHeader(key, value, allowedHosts, onError);
55
+ }
56
+ return result;
57
+ },
58
+ [Symbol.iterator]() {
59
+ return this;
60
+ }
61
+ };
62
+ };
63
+ headers[Symbol.iterator] = headers.entries;
64
+ return {
65
+ request: clonedReq,
66
+ onError: onErrorPromise
67
+ };
68
+ }
69
+ function validateHeader(name, value, allowedHosts, onError) {
70
+ if (!value) {
71
+ return;
72
+ }
73
+ if (!HOST_HEADERS_TO_VALIDATE.has(name.toLowerCase())) {
74
+ return;
75
+ }
76
+ try {
77
+ verifyHostAllowed(name, value, allowedHosts);
78
+ } catch (error) {
79
+ onError(error);
80
+ throw error;
81
+ }
82
+ }
83
+ function verifyHostAllowed(headerName, headerValue, allowedHosts) {
84
+ const value = getFirstHeaderValue(headerValue);
85
+ if (!value) {
86
+ return;
87
+ }
88
+ const url = `http://${value}`;
89
+ if (!URL.canParse(url)) {
90
+ throw new Error(`Header "${headerName}" contains an invalid value and cannot be parsed.`);
91
+ }
92
+ const {
93
+ hostname
94
+ } = new URL(url);
95
+ if (!isHostAllowed(hostname, allowedHosts)) {
96
+ throw new Error(`Header "${headerName}" with value "${value}" is not allowed.`);
97
+ }
98
+ }
99
+ function isHostAllowed(hostname, allowedHosts) {
100
+ if (allowedHosts.has(hostname)) {
101
+ return true;
102
+ }
103
+ for (const allowedHost of allowedHosts) {
104
+ if (!allowedHost.startsWith('*.')) {
105
+ continue;
106
+ }
107
+ const domain = allowedHost.slice(1);
108
+ if (hostname.endsWith(domain)) {
109
+ return true;
110
+ }
111
+ }
112
+ return false;
113
+ }
114
+ function validateHeaders(request) {
115
+ const headers = request.headers;
116
+ for (const headerName of HOST_HEADERS_TO_VALIDATE) {
117
+ const headerValue = getFirstHeaderValue(headers.get(headerName));
118
+ if (headerValue && !VALID_HOST_REGEX.test(headerValue)) {
119
+ throw new Error(`Header "${headerName}" contains characters that are not allowed.`);
120
+ }
121
+ }
122
+ const xForwardedPort = getFirstHeaderValue(headers.get('x-forwarded-port'));
123
+ if (xForwardedPort && !VALID_PORT_REGEX.test(xForwardedPort)) {
124
+ throw new Error('Header "x-forwarded-port" must be a numeric value.');
125
+ }
126
+ const xForwardedProto = getFirstHeaderValue(headers.get('x-forwarded-proto'));
127
+ if (xForwardedProto && !VALID_PROTO_REGEX.test(xForwardedProto)) {
128
+ throw new Error('Header "x-forwarded-proto" must be either "http" or "https".');
129
+ }
130
+ const xForwardedPrefix = getFirstHeaderValue(headers.get('x-forwarded-prefix'));
131
+ if (xForwardedPrefix && INVALID_PREFIX_REGEX.test(xForwardedPrefix)) {
132
+ throw new Error('Header "x-forwarded-prefix" must not start with multiple "/" or "\\" or contain ".", ".." path segments.');
133
+ }
134
+ }
135
+
136
+ export { cloneRequestAndPatchHeaders, getFirstHeaderValue, validateRequest, validateUrl };
137
+ //# sourceMappingURL=_validation-chunk.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_validation-chunk.mjs","sources":["../../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/src/utils/validation.ts"],"sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\n/**\n * The set of headers that should be validated for host header injection attacks.\n */\nconst HOST_HEADERS_TO_VALIDATE: ReadonlySet<string> = new Set(['host', 'x-forwarded-host']);\n\n/**\n * Regular expression to validate that the port is a numeric value.\n */\nconst VALID_PORT_REGEX = /^\\d+$/;\n\n/**\n * Regular expression to validate that the protocol is either http or https (case-insensitive).\n */\nconst VALID_PROTO_REGEX = /^https?$/i;\n\n/**\n * Regular expression to validate that the host is a valid hostname.\n */\nconst VALID_HOST_REGEX = /^[a-z0-9.:-]+$/i;\n\n/**\n * Regular expression to validate that the prefix is valid.\n */\nconst INVALID_PREFIX_REGEX = /^[/\\\\]{2}|(?:^|[/\\\\])\\.\\.?(?:[/\\\\]|$)/;\n\n/**\n * Extracts the first value from a multi-value header string.\n *\n * @param value - A string or an array of strings representing the header values.\n * If it's a string, values are expected to be comma-separated.\n * @returns The first trimmed value from the multi-value header, or `undefined` if the input is invalid or empty.\n *\n * @example\n * ```typescript\n * getFirstHeaderValue(\"value1, value2, value3\"); // \"value1\"\n * getFirstHeaderValue([\"value1\", \"value2\"]); // \"value1\"\n * getFirstHeaderValue(undefined); // undefined\n * ```\n */\nexport function getFirstHeaderValue(\n value: string | string[] | undefined | null,\n): string | undefined {\n return value?.toString().split(',', 1)[0]?.trim();\n}\n\n/**\n * Validates a request.\n *\n * @param request - The incoming `Request` object to validate.\n * @param allowedHosts - A set of allowed hostnames.\n * @throws Error if any of the validated headers contain invalid values.\n */\nexport function validateRequest(request: Request, allowedHosts: ReadonlySet<string>): void {\n validateHeaders(request);\n validateUrl(new URL(request.url), allowedHosts);\n}\n\n/**\n * Validates that the hostname of a given URL is allowed.\n *\n * @param url - The URL object to validate.\n * @param allowedHosts - A set of allowed hostnames.\n * @throws Error if the hostname is not in the allowlist.\n */\nexport function validateUrl(url: URL, allowedHosts: ReadonlySet<string>): void {\n const { hostname } = url;\n if (!isHostAllowed(hostname, allowedHosts)) {\n throw new Error(`URL with hostname \"${hostname}\" is not allowed.`);\n }\n}\n\n/**\n * Clones a request and patches the `get` method of the request headers to validate the host headers.\n * @param request - The request to validate.\n * @param allowedHosts - A set of allowed hostnames.\n * @returns An object containing the cloned request and a promise that resolves to an error\n * if any of the validated headers contain invalid values.\n */\nexport function cloneRequestAndPatchHeaders(\n request: Request,\n allowedHosts: ReadonlySet<string>,\n): { request: Request; onError: Promise<Error> } {\n let onError: (value: Error) => void;\n const onErrorPromise = new Promise<Error>((resolve) => {\n onError = resolve;\n });\n\n const clonedReq = new Request(request.clone(), {\n signal: request.signal,\n });\n\n const headers = clonedReq.headers;\n\n const originalGet = headers.get;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n (headers.get as typeof originalGet) = function (name) {\n const value = originalGet.call(headers, name);\n if (!value) {\n return value;\n }\n\n validateHeader(name, value, allowedHosts, onError);\n\n return value;\n };\n\n const originalValues = headers.values;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n (headers.values as typeof originalValues) = function () {\n for (const name of HOST_HEADERS_TO_VALIDATE) {\n validateHeader(name, originalGet.call(headers, name), allowedHosts, onError);\n }\n\n return originalValues.call(headers);\n };\n\n const originalEntries = headers.entries;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n (headers.entries as typeof originalEntries) = function () {\n const iterator = originalEntries.call(headers);\n\n return {\n next() {\n const result = iterator.next();\n if (!result.done) {\n const [key, value] = result.value;\n validateHeader(key, value, allowedHosts, onError);\n }\n\n return result;\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n };\n\n // Ensure for...of loops use the new patched entries\n (headers[Symbol.iterator] as typeof originalEntries) = headers.entries;\n\n return { request: clonedReq, onError: onErrorPromise };\n}\n\n/**\n * Validates a specific header value against the allowed hosts.\n * @param name - The name of the header to validate.\n * @param value - The value of the header to validate.\n * @param allowedHosts - A set of allowed hostnames.\n * @param onError - A callback function to call if the header value is invalid.\n * @throws Error if the header value is invalid.\n */\nfunction validateHeader(\n name: string,\n value: string | null,\n allowedHosts: ReadonlySet<string>,\n onError: (value: Error) => void,\n): void {\n if (!value) {\n return;\n }\n\n if (!HOST_HEADERS_TO_VALIDATE.has(name.toLowerCase())) {\n return;\n }\n\n try {\n verifyHostAllowed(name, value, allowedHosts);\n } catch (error) {\n onError(error as Error);\n\n throw error;\n }\n}\n\n/**\n * Validates a specific host header value against the allowed hosts.\n *\n * @param headerName - The name of the header to validate (e.g., 'host', 'x-forwarded-host').\n * @param headerValue - The value of the header to validate.\n * @param allowedHosts - A set of allowed hostnames.\n * @throws Error if the header value is invalid or the hostname is not in the allowlist.\n */\nfunction verifyHostAllowed(\n headerName: string,\n headerValue: string,\n allowedHosts: ReadonlySet<string>,\n): void {\n const value = getFirstHeaderValue(headerValue);\n if (!value) {\n return;\n }\n\n const url = `http://${value}`;\n if (!URL.canParse(url)) {\n throw new Error(`Header \"${headerName}\" contains an invalid value and cannot be parsed.`);\n }\n\n const { hostname } = new URL(url);\n if (!isHostAllowed(hostname, allowedHosts)) {\n throw new Error(`Header \"${headerName}\" with value \"${value}\" is not allowed.`);\n }\n}\n\n/**\n * Checks if the hostname is allowed.\n * @param hostname - The hostname to check.\n * @param allowedHosts - A set of allowed hostnames.\n * @returns `true` if the hostname is allowed, `false` otherwise.\n */\nfunction isHostAllowed(hostname: string, allowedHosts: ReadonlySet<string>): boolean {\n if (allowedHosts.has(hostname)) {\n return true;\n }\n\n for (const allowedHost of allowedHosts) {\n if (!allowedHost.startsWith('*.')) {\n continue;\n }\n\n const domain = allowedHost.slice(1);\n if (hostname.endsWith(domain)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Validates the headers of an incoming request.\n *\n * @param request - The incoming `Request` object containing the headers to validate.\n * @throws Error if any of the validated headers contain invalid values.\n */\nfunction validateHeaders(request: Request): void {\n const headers = request.headers;\n for (const headerName of HOST_HEADERS_TO_VALIDATE) {\n const headerValue = getFirstHeaderValue(headers.get(headerName));\n if (headerValue && !VALID_HOST_REGEX.test(headerValue)) {\n throw new Error(`Header \"${headerName}\" contains characters that are not allowed.`);\n }\n }\n\n const xForwardedPort = getFirstHeaderValue(headers.get('x-forwarded-port'));\n if (xForwardedPort && !VALID_PORT_REGEX.test(xForwardedPort)) {\n throw new Error('Header \"x-forwarded-port\" must be a numeric value.');\n }\n\n const xForwardedProto = getFirstHeaderValue(headers.get('x-forwarded-proto'));\n if (xForwardedProto && !VALID_PROTO_REGEX.test(xForwardedProto)) {\n throw new Error('Header \"x-forwarded-proto\" must be either \"http\" or \"https\".');\n }\n\n const xForwardedPrefix = getFirstHeaderValue(headers.get('x-forwarded-prefix'));\n if (xForwardedPrefix && INVALID_PREFIX_REGEX.test(xForwardedPrefix)) {\n throw new Error(\n 'Header \"x-forwarded-prefix\" must not start with multiple \"/\" or \"\\\\\" or contain \".\", \"..\" path segments.',\n );\n }\n}\n"],"names":["HOST_HEADERS_TO_VALIDATE","Set","VALID_PORT_REGEX","VALID_PROTO_REGEX","VALID_HOST_REGEX","INVALID_PREFIX_REGEX","getFirstHeaderValue","value","toString","split","trim","validateRequest","request","allowedHosts","validateHeaders","validateUrl","URL","url","hostname","isHostAllowed","Error","cloneRequestAndPatchHeaders","onError","onErrorPromise","Promise","resolve","clonedReq","Request","clone","signal","headers","originalGet","get","name","call","validateHeader","originalValues","values","originalEntries","entries","iterator","next","result","done","key","Symbol","has","toLowerCase","verifyHostAllowed","error","headerName","headerValue","canParse","allowedHost","startsWith","domain","slice","endsWith","test","xForwardedPort","xForwardedProto","xForwardedPrefix"],"mappings":"AAWA,MAAMA,wBAAwB,GAAwB,IAAIC,GAAG,CAAC,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC;AAK3F,MAAMC,gBAAgB,GAAG,OAAO;AAKhC,MAAMC,iBAAiB,GAAG,WAAW;AAKrC,MAAMC,gBAAgB,GAAG,iBAAiB;AAK1C,MAAMC,oBAAoB,GAAG,uCAAuC;AAgB9D,SAAUC,mBAAmBA,CACjCC,KAA2C,EAAA;AAE3C,EAAA,OAAOA,KAAK,EAAEC,QAAQ,EAAE,CAACC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,EAAEC,IAAI,EAAE;AACnD;AASgB,SAAAC,eAAeA,CAACC,OAAgB,EAAEC,YAAiC,EAAA;EACjFC,eAAe,CAACF,OAAO,CAAC;EACxBG,WAAW,CAAC,IAAIC,GAAG,CAACJ,OAAO,CAACK,GAAG,CAAC,EAAEJ,YAAY,CAAC;AACjD;AASgB,SAAAE,WAAWA,CAACE,GAAQ,EAAEJ,YAAiC,EAAA;EACrE,MAAM;AAAEK,IAAAA;AAAU,GAAA,GAAGD,GAAG;AACxB,EAAA,IAAI,CAACE,aAAa,CAACD,QAAQ,EAAEL,YAAY,CAAC,EAAE;AAC1C,IAAA,M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;IAChE,IAAIC,WAAW,IAAI,CAAC/C,gBAAgB,CAACsD,IAAI,CAACP,WAAW,CAAC,EAAE;AACtD,MAAA,MAAM,IAAI/B,KAAK,CAAC,CAAW8B,QAAAA,EAAAA,UAAU,6CAA6C,CAAC;AACrF;AACF;EAEA,MAAMS,cAAc,GAAGrD,mBAAmB,CAACwB,OAAO,CAACE,GAAG,CAAC,kBAAkB,CAAC,CAAC;EAC3E,IAAI2B,cAAc,IAAI,CAACzD,gBAAgB,CAACwD,IAAI,CAACC,cAAc,CAAC,EAAE;AAC5D,IAAA,MAAM,IAAIvC,KAAK,CAAC,oDAAoD,CAAC;AACvE;EAEA,MAAMwC,eAAe,GAAGtD,mBAAmB,CAACwB,OAAO,CAACE,GAAG,CAAC,mBAAmB,CAAC,CAAC;EAC7E,IAAI4B,eAAe,IAAI,CAACzD,iBAAiB,CAACuD,IAAI,CAACE,eAAe,CAAC,EAAE;AAC/D,IAAA,MAAM,IAAIxC,KAAK,CAAC,8DAA8D,CAAC;AACjF;EAEA,MAAMyC,gBAAgB,GAAGvD,mBAAmB,CAACwB,OAAO,CAACE,GAAG,CAAC,oBAAoB,CAAC,CAAC;EAC/E,IAAI6B,gBAAgB,IAAIxD,oBAAoB,CAACqD,IAAI,CAACG,gBAAgB,CAAC,EAAE;AACnE,IAAA,MAAM,IAAIzC,KAAK,CACb,0GAA0G,CAC3G;AACH;AACF;;;;"}
package/fesm2022/node.mjs CHANGED
@@ -2,10 +2,27 @@ import { renderApplication, renderModule, ɵSERVER_CONTEXT as _SERVER_CONTEXT }
2
2
  import * as fs from 'node:fs';
3
3
  import { dirname, join, normalize, resolve } from 'node:path';
4
4
  import { URL as URL$1, fileURLToPath } from 'node:url';
5
+ import { validateUrl, getFirstHeaderValue } from './_validation-chunk.mjs';
5
6
  import { ɵInlineCriticalCssProcessor as _InlineCriticalCssProcessor, AngularAppEngine } from '@angular/ssr';
6
7
  import { readFile } from 'node:fs/promises';
7
8
  import { argv } from 'node:process';
8
9
 
10
+ function getAllowedHostsFromEnv() {
11
+ const allowedHosts = [];
12
+ const envNgAllowedHosts = process.env['NG_ALLOWED_HOSTS'];
13
+ if (!envNgAllowedHosts) {
14
+ return allowedHosts;
15
+ }
16
+ const hosts = envNgAllowedHosts.split(',');
17
+ for (const host of hosts) {
18
+ const trimmed = host.trim();
19
+ if (trimmed.length > 0) {
20
+ allowedHosts.push(trimmed);
21
+ }
22
+ }
23
+ return allowedHosts;
24
+ }
25
+
9
26
  function attachNodeGlobalErrorHandlers() {
10
27
  if (typeof Zone !== 'undefined') {
11
28
  return;
@@ -82,11 +99,35 @@ class CommonEngine {
82
99
  templateCache = new Map();
83
100
  inlineCriticalCssProcessor = new CommonEngineInlineCriticalCssProcessor();
84
101
  pageIsSSG = new Map();
102
+ allowedHosts;
85
103
  constructor(options) {
86
104
  this.options = options;
105
+ this.allowedHosts = new Set([...getAllowedHostsFromEnv(), ...(this.options?.allowedHosts ?? [])]);
87
106
  attachNodeGlobalErrorHandlers();
88
107
  }
89
108
  async render(opts) {
109
+ const {
110
+ url
111
+ } = opts;
112
+ if (url && URL$1.canParse(url)) {
113
+ const urlObj = new URL$1(url);
114
+ try {
115
+ validateUrl(urlObj, this.allowedHosts);
116
+ } catch (error) {
117
+ const isAllowedHostConfigured = this.allowedHosts.size > 0;
118
+ console.error(`ERROR: ${error.message}` + 'Please provide a list of allowed hosts in the "allowedHosts" option in the "CommonEngine" constructor.', isAllowedHostConfigured ? '' : '\nFalling back to client side rendering. This will become a 400 Bad Request in a future major version.');
119
+ if (!isAllowedHostConfigured) {
120
+ let document = opts.document;
121
+ if (!document && opts.documentFilePath) {
122
+ document = opts.document ?? (await this.getDocument(opts.documentFilePath));
123
+ }
124
+ if (document) {
125
+ return document;
126
+ }
127
+ }
128
+ throw error;
129
+ }
130
+ }
90
131
  const enablePerformanceProfiler = this.options?.enablePerformanceProfiler;
91
132
  const runMethod = enablePerformanceProfiler ? runMethodAndMeasurePerf : noopRunMethodAndMeasurePerf;
92
133
  let html = await runMethod('Retrieve SSG Page', () => this.retrieveSSGPage(opts));
@@ -233,17 +274,18 @@ function createRequestUrl(nodeRequest) {
233
274
  }
234
275
  return new URL(`${protocol}://${hostnameWithPort}${originalUrl ?? url}`);
235
276
  }
236
- function getFirstHeaderValue(value) {
237
- return value?.toString().split(',', 1)[0]?.trim();
238
- }
239
277
 
240
278
  class AngularNodeAppEngine {
241
- angularAppEngine = new AngularAppEngine();
242
- constructor() {
279
+ angularAppEngine;
280
+ constructor(options) {
281
+ this.angularAppEngine = new AngularAppEngine({
282
+ ...options,
283
+ allowedHosts: [...getAllowedHostsFromEnv(), ...(options?.allowedHosts ?? [])]
284
+ });
243
285
  attachNodeGlobalErrorHandlers();
244
286
  }
245
287
  async handle(request, requestContext) {
246
- const webRequest = createWebRequestFromNodeRequest(request);
288
+ const webRequest = request instanceof Request ? request : createWebRequestFromNodeRequest(request);
247
289
  return this.angularAppEngine.handle(webRequest, requestContext);
248
290
  }
249
291
  }
@@ -1 +1 @@
1
- {"version":3,"file":"node.mjs","sources":["../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/errors.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/common-engine/inline-css-processor.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/common-engine/peformance-profiler.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/common-engine/common-engine.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/request.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/app-engine.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/handler.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/response.ts","../../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/module.ts"],"sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\n/**\n * Attaches listeners to the Node.js process to capture and handle unhandled rejections and uncaught exceptions.\n * Captured errors are logged to the console. This function logs errors to the console, preventing unhandled errors\n * from crashing the server. It is particularly useful for Zoneless apps, ensuring error handling without relying on Zone.js.\n *\n * @remarks\n * This function is a no-op if zone.js is available.\n * For Zone-based apps, similar functionality is provided by Zone.js itself. See the Zone.js implementation here:\n * https://github.com/angular/angular/blob/4a8d0b79001ec09bcd6f2d6b15117aa6aac1932c/packages/zone.js/lib/node/node.ts#L94%7C\n *\n * @internal\n */\nexport function attachNodeGlobalErrorHandlers(): void {\n if (typeof Zone !== 'undefined') {\n return;\n }\n\n // Ensure that the listeners are registered only once.\n // Otherwise, multiple instances may be registered during edit/refresh.\n const gThis: typeof globalThis & { ngAttachNodeGlobalErrorHandlersCalled?: boolean } = globalThis;\n if (gThis.ngAttachNodeGlobalErrorHandlersCalled) {\n return;\n }\n\n gThis.ngAttachNodeGlobalErrorHandlersCalled = true;\n\n process\n // eslint-disable-next-line no-console\n .on('unhandledRejection', (error) => console.error('unhandledRejection', error))\n // eslint-disable-next-line no-console\n .on('uncaughtException', (error) => console.error('uncaughtException', error));\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { ɵInlineCriticalCssProcessor as InlineCriticalCssProcessor } from '@angular/ssr';\nimport { readFile } from 'node:fs/promises';\n\nexport class CommonEngineInlineCriticalCssProcessor {\n private readonly resourceCache = new Map<string, string>();\n\n async process(html: string, outputPath: string | undefined): Promise<string> {\n const beasties = new InlineCriticalCssProcessor(async (path) => {\n let resourceContent = this.resourceCache.get(path);\n if (resourceContent === undefined) {\n resourceContent = await readFile(path, 'utf-8');\n this.resourceCache.set(path, resourceContent);\n }\n\n return resourceContent;\n }, outputPath);\n\n return beasties.process(html);\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nconst PERFORMANCE_MARK_PREFIX = '🅰️';\n\nexport function printPerformanceLogs(): void {\n let maxWordLength = 0;\n const benchmarks: [step: string, value: string][] = [];\n\n for (const { name, duration } of performance.getEntriesByType('measure')) {\n if (!name.startsWith(PERFORMANCE_MARK_PREFIX)) {\n continue;\n }\n\n // `🅰️:Retrieve SSG Page` -> `Retrieve SSG Page:`\n const step = name.slice(PERFORMANCE_MARK_PREFIX.length + 1) + ':';\n if (step.length > maxWordLength) {\n maxWordLength = step.length;\n }\n\n benchmarks.push([step, `${duration.toFixed(1)}ms`]);\n performance.clearMeasures(name);\n }\n\n /* eslint-disable no-console */\n console.log('********** Performance results **********');\n for (const [step, value] of benchmarks) {\n const spaces = maxWordLength - step.length + 5;\n console.log(step + ' '.repeat(spaces) + value);\n }\n console.log('*****************************************');\n /* eslint-enable no-console */\n}\n\nexport async function runMethodAndMeasurePerf<T>(\n label: string,\n asyncMethod: () => Promise<T>,\n): Promise<T> {\n const labelName = `${PERFORMANCE_MARK_PREFIX}:${label}`;\n const startLabel = `start:${labelName}`;\n const endLabel = `end:${labelName}`;\n\n try {\n performance.mark(startLabel);\n\n return await asyncMethod();\n } finally {\n performance.mark(endLabel);\n performance.measure(labelName, startLabel, endLabel);\n performance.clearMarks(startLabel);\n performance.clearMarks(endLabel);\n }\n}\n\nexport function noopRunMethodAndMeasurePerf<T>(\n label: string,\n asyncMethod: () => Promise<T>,\n): Promise<T> {\n return asyncMethod();\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { ApplicationRef, StaticProvider, Type } from '@angular/core';\nimport { BootstrapContext } from '@angular/platform-browser';\nimport { renderApplication, renderModule, ɵSERVER_CONTEXT } from '@angular/platform-server';\nimport * as fs from 'node:fs';\nimport { dirname, join, normalize, resolve } from 'node:path';\nimport { URL } from 'node:url';\nimport { attachNodeGlobalErrorHandlers } from '../errors';\nimport { CommonEngineInlineCriticalCssProcessor } from './inline-css-processor';\nimport {\n noopRunMethodAndMeasurePerf,\n printPerformanceLogs,\n runMethodAndMeasurePerf,\n} from './peformance-profiler';\n\nconst SSG_MARKER_REGEXP = /ng-server-context=[\"']\\w*\\|?ssg\\|?\\w*[\"']/;\n\nexport interface CommonEngineOptions {\n /** A method that when invoked returns a promise that returns an `ApplicationRef` instance once resolved or an NgModule. */\n bootstrap?: Type<{}> | ((context: BootstrapContext) => Promise<ApplicationRef>);\n\n /** A set of platform level providers for all requests. */\n providers?: StaticProvider[];\n\n /** Enable request performance profiling data collection and printing the results in the server console. */\n enablePerformanceProfiler?: boolean;\n}\n\nexport interface CommonEngineRenderOptions {\n /** A method that when invoked returns a promise that returns an `ApplicationRef` instance once resolved or an NgModule. */\n bootstrap?: Type<{}> | ((context: BootstrapContext) => Promise<ApplicationRef>);\n\n /** A set of platform level providers for the current request. */\n providers?: StaticProvider[];\n url?: string;\n document?: string;\n documentFilePath?: string;\n\n /**\n * Reduce render blocking requests by inlining critical CSS.\n * Defaults to true.\n */\n inlineCriticalCss?: boolean;\n\n /**\n * Base path location of index file.\n * Defaults to the 'documentFilePath' dirname when not provided.\n */\n publicPath?: string;\n}\n\n/**\n * A common engine to use to server render an application.\n */\n\nexport class CommonEngine {\n private readonly templateCache = new Map<string, string>();\n private readonly inlineCriticalCssProcessor = new CommonEngineInlineCriticalCssProcessor();\n private readonly pageIsSSG = new Map<string, boolean>();\n\n constructor(private options?: CommonEngineOptions | undefined) {\n attachNodeGlobalErrorHandlers();\n }\n\n /**\n * Render an HTML document for a specific URL with specified\n * render options\n */\n async render(opts: CommonEngineRenderOptions): Promise<string> {\n const enablePerformanceProfiler = this.options?.enablePerformanceProfiler;\n\n const runMethod = enablePerformanceProfiler\n ? runMethodAndMeasurePerf\n : noopRunMethodAndMeasurePerf;\n\n let html = await runMethod('Retrieve SSG Page', () => this.retrieveSSGPage(opts));\n\n if (html === undefined) {\n html = await runMethod('Render Page', () => this.renderApplication(opts));\n\n if (opts.inlineCriticalCss !== false) {\n const content = await runMethod('Inline Critical CSS', () =>\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.inlineCriticalCss(html!, opts),\n );\n\n html = content;\n }\n }\n\n if (enablePerformanceProfiler) {\n printPerformanceLogs();\n }\n\n return html;\n }\n\n private inlineCriticalCss(html: string, opts: CommonEngineRenderOptions): Promise<string> {\n const outputPath =\n opts.publicPath ?? (opts.documentFilePath ? dirname(opts.documentFilePath) : '');\n\n return this.inlineCriticalCssProcessor.process(html, outputPath);\n }\n\n private async retrieveSSGPage(opts: CommonEngineRenderOptions): Promise<string | undefined> {\n const { publicPath, documentFilePath, url } = opts;\n if (!publicPath || !documentFilePath || url === undefined) {\n return undefined;\n }\n\n const { pathname } = new URL(url, 'resolve://');\n // Do not use `resolve` here as otherwise it can lead to path traversal vulnerability.\n // See: https://portswigger.net/web-security/file-path-traversal\n const pagePath = join(publicPath, pathname, 'index.html');\n\n if (this.pageIsSSG.get(pagePath)) {\n // Serve pre-rendered page.\n return fs.promises.readFile(pagePath, 'utf-8');\n }\n\n if (!pagePath.startsWith(normalize(publicPath))) {\n // Potential path traversal detected.\n return undefined;\n }\n\n if (pagePath === resolve(documentFilePath) || !(await exists(pagePath))) {\n // View matches with prerender path or file does not exist.\n this.pageIsSSG.set(pagePath, false);\n\n return undefined;\n }\n\n // Static file exists.\n const content = await fs.promises.readFile(pagePath, 'utf-8');\n const isSSG = SSG_MARKER_REGEXP.test(content);\n this.pageIsSSG.set(pagePath, isSSG);\n\n return isSSG ? content : undefined;\n }\n\n private async renderApplication(opts: CommonEngineRenderOptions): Promise<string> {\n const moduleOrFactory = this.options?.bootstrap ?? opts.bootstrap;\n if (!moduleOrFactory) {\n throw new Error('A module or bootstrap option must be provided.');\n }\n\n const extraProviders: StaticProvider[] = [\n { provide: ɵSERVER_CONTEXT, useValue: 'ssr' },\n ...(opts.providers ?? []),\n ...(this.options?.providers ?? []),\n ];\n\n let document = opts.document;\n if (!document && opts.documentFilePath) {\n document = await this.getDocument(opts.documentFilePath);\n }\n\n const commonRenderingOptions = {\n url: opts.url,\n document,\n };\n\n return isBootstrapFn(moduleOrFactory)\n ? renderApplication(moduleOrFactory, {\n platformProviders: extraProviders,\n ...commonRenderingOptions,\n })\n : renderModule(moduleOrFactory, { extraProviders, ...commonRenderingOptions });\n }\n\n /** Retrieve the document from the cache or the filesystem */\n private async getDocument(filePath: string): Promise<string> {\n let doc = this.templateCache.get(filePath);\n\n if (!doc) {\n doc = await fs.promises.readFile(filePath, 'utf-8');\n this.templateCache.set(filePath, doc);\n }\n\n return doc;\n }\n}\n\nasync function exists(path: fs.PathLike): Promise<boolean> {\n try {\n await fs.promises.access(path, fs.constants.F_OK);\n\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isBootstrapFn(\n value: unknown,\n): value is (context: BootstrapContext) => Promise<ApplicationRef> {\n // We can differentiate between a module and a bootstrap function by reading compiler-generated `ɵmod` static property:\n return typeof value === 'function' && !('ɵmod' in value);\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type { IncomingHttpHeaders, IncomingMessage } from 'node:http';\nimport type { Http2ServerRequest } from 'node:http2';\n\n/**\n * A set containing all the pseudo-headers defined in the HTTP/2 specification.\n *\n * This set can be used to filter out pseudo-headers from a list of headers,\n * as they are not allowed to be set directly using the `Node.js` Undici API or\n * the web `Headers` API.\n */\nconst HTTP2_PSEUDO_HEADERS = new Set([':method', ':scheme', ':authority', ':path', ':status']);\n\n/**\n * Converts a Node.js `IncomingMessage` or `Http2ServerRequest` into a\n * Web Standard `Request` object.\n *\n * This function adapts the Node.js request objects to a format that can\n * be used by web platform APIs.\n *\n * @param nodeRequest - The Node.js request object (`IncomingMessage` or `Http2ServerRequest`) to convert.\n * @returns A Web Standard `Request` object.\n */\nexport function createWebRequestFromNodeRequest(\n nodeRequest: IncomingMessage | Http2ServerRequest,\n): Request {\n const { headers, method = 'GET' } = nodeRequest;\n const withBody = method !== 'GET' && method !== 'HEAD';\n const referrer = headers.referer && URL.canParse(headers.referer) ? headers.referer : undefined;\n\n return new Request(createRequestUrl(nodeRequest), {\n method,\n headers: createRequestHeaders(headers),\n body: withBody ? nodeRequest : undefined,\n duplex: withBody ? 'half' : undefined,\n referrer,\n });\n}\n\n/**\n * Creates a `Headers` object from Node.js `IncomingHttpHeaders`.\n *\n * @param nodeHeaders - The Node.js `IncomingHttpHeaders` object to convert.\n * @returns A `Headers` object containing the converted headers.\n */\nfunction createRequestHeaders(nodeHeaders: IncomingHttpHeaders): Headers {\n const headers = new Headers();\n\n for (const [name, value] of Object.entries(nodeHeaders)) {\n if (HTTP2_PSEUDO_HEADERS.has(name)) {\n continue;\n }\n\n if (typeof value === 'string') {\n headers.append(name, value);\n } else if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n }\n }\n\n return headers;\n}\n\n/**\n * Creates a `URL` object from a Node.js `IncomingMessage`, taking into account the protocol, host, and port.\n *\n * @param nodeRequest - The Node.js `IncomingMessage` or `Http2ServerRequest` object to extract URL information from.\n * @returns A `URL` object representing the request URL.\n */\nexport function createRequestUrl(nodeRequest: IncomingMessage | Http2ServerRequest): URL {\n const {\n headers,\n socket,\n url = '',\n originalUrl,\n } = nodeRequest as IncomingMessage & { originalUrl?: string };\n const protocol =\n getFirstHeaderValue(headers['x-forwarded-proto']) ??\n ('encrypted' in socket && socket.encrypted ? 'https' : 'http');\n const hostname =\n getFirstHeaderValue(headers['x-forwarded-host']) ?? headers.host ?? headers[':authority'];\n\n if (Array.isArray(hostname)) {\n throw new Error('host value cannot be an array.');\n }\n\n let hostnameWithPort = hostname;\n if (!hostname?.includes(':')) {\n const port = getFirstHeaderValue(headers['x-forwarded-port']);\n if (port) {\n hostnameWithPort += `:${port}`;\n }\n }\n\n return new URL(`${protocol}://${hostnameWithPort}${originalUrl ?? url}`);\n}\n\n/**\n * Extracts the first value from a multi-value header string.\n *\n * @param value - A string or an array of strings representing the header values.\n * If it's a string, values are expected to be comma-separated.\n * @returns The first trimmed value from the multi-value header, or `undefined` if the input is invalid or empty.\n *\n * @example\n * ```typescript\n * getFirstHeaderValue(\"value1, value2, value3\"); // \"value1\"\n * getFirstHeaderValue([\"value1\", \"value2\"]); // \"value1\"\n * getFirstHeaderValue(undefined); // undefined\n * ```\n */\nfunction getFirstHeaderValue(value: string | string[] | undefined): string | undefined {\n return value?.toString().split(',', 1)[0]?.trim();\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { AngularAppEngine } from '@angular/ssr';\nimport type { IncomingMessage } from 'node:http';\nimport type { Http2ServerRequest } from 'node:http2';\nimport { attachNodeGlobalErrorHandlers } from './errors';\nimport { createWebRequestFromNodeRequest } from './request';\n\n/**\n * Angular server application engine.\n * Manages Angular server applications (including localized ones), handles rendering requests,\n * and optionally transforms index HTML before rendering.\n *\n * @remarks This class should be instantiated once and used as a singleton across the server-side\n * application to ensure consistent handling of rendering requests and resource management.\n */\nexport class AngularNodeAppEngine {\n private readonly angularAppEngine = new AngularAppEngine();\n\n constructor() {\n attachNodeGlobalErrorHandlers();\n }\n\n /**\n * Handles an incoming HTTP request by serving prerendered content, performing server-side rendering,\n * or delivering a static file for client-side rendered routes based on the `RenderMode` setting.\n *\n * This method adapts Node.js's `IncomingMessage` or `Http2ServerRequest`\n * to a format compatible with the `AngularAppEngine` and delegates the handling logic to it.\n *\n * @param request - The incoming HTTP request (`IncomingMessage` or `Http2ServerRequest`).\n * @param requestContext - Optional context for rendering, such as metadata associated with the request.\n * @returns A promise that resolves to the resulting HTTP response object, or `null` if no matching Angular route is found.\n *\n * @remarks A request to `https://www.example.com/page/index.html` will serve or render the Angular route\n * corresponding to `https://www.example.com/page`.\n */\n async handle(\n request: IncomingMessage | Http2ServerRequest,\n requestContext?: unknown,\n ): Promise<Response | null> {\n const webRequest = createWebRequestFromNodeRequest(request);\n\n return this.angularAppEngine.handle(webRequest, requestContext);\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\n/**\n * Represents a middleware function for handling HTTP requests in a Node.js environment.\n *\n * @param req - The incoming HTTP request object.\n * @param res - The outgoing HTTP response object.\n * @param next - A callback function that signals the completion of the middleware or forwards the error if provided.\n *\n * @returns A Promise that resolves to void or simply void. The handler can be asynchronous.\n */\nexport type NodeRequestHandlerFunction = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (err?: unknown) => void,\n) => Promise<void> | void;\n\n/**\n * Attaches metadata to the handler function to mark it as a special handler for Node.js environments.\n *\n * @typeParam T - The type of the handler function.\n * @param handler - The handler function to be defined and annotated.\n * @returns The same handler function passed as an argument, with metadata attached.\n *\n * @example\n * Usage in an Express application:\n * ```ts\n * const app = express();\n * export default createNodeRequestHandler(app);\n * ```\n *\n * @example\n * Usage in a Hono application:\n * ```ts\n * const app = new Hono();\n * export default createNodeRequestHandler(async (req, res, next) => {\n * try {\n * const webRes = await app.fetch(createWebRequestFromNodeRequest(req));\n * if (webRes) {\n * await writeResponseToNodeResponse(webRes, res);\n * } else {\n * next();\n * }\n * } catch (error) {\n * next(error);\n * }\n * });\n * ```\n *\n * @example\n * Usage in a Fastify application:\n * ```ts\n * const app = Fastify();\n * export default createNodeRequestHandler(async (req, res) => {\n * await app.ready();\n * app.server.emit('request', req, res);\n * });\n * ```\n */\nexport function createNodeRequestHandler<T extends NodeRequestHandlerFunction>(handler: T): T {\n (handler as T & { __ng_node_request_handler__?: boolean })['__ng_node_request_handler__'] = true;\n\n return handler;\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type { ServerResponse } from 'node:http';\nimport type { Http2ServerResponse } from 'node:http2';\n\n/**\n * Streams a web-standard `Response` into a Node.js `ServerResponse`\n * or `Http2ServerResponse`.\n *\n * This function adapts the web `Response` object to write its content\n * to a Node.js response object, handling both HTTP/1.1 and HTTP/2.\n *\n * @param source - The web-standard `Response` object to stream from.\n * @param destination - The Node.js response object (`ServerResponse` or `Http2ServerResponse`) to stream into.\n * @returns A promise that resolves once the streaming operation is complete.\n */\nexport async function writeResponseToNodeResponse(\n source: Response,\n destination: ServerResponse | Http2ServerResponse,\n): Promise<void> {\n const { status, headers, body } = source;\n destination.statusCode = status;\n\n let cookieHeaderSet = false;\n for (const [name, value] of headers.entries()) {\n if (name === 'set-cookie') {\n if (cookieHeaderSet) {\n continue;\n }\n\n // Sets the 'set-cookie' header only once to ensure it is correctly applied.\n // Concatenating 'set-cookie' values can lead to incorrect behavior, so we use a single value from `headers.getSetCookie()`.\n destination.setHeader(name, headers.getSetCookie());\n cookieHeaderSet = true;\n } else {\n destination.setHeader(name, value);\n }\n }\n\n if ('flushHeaders' in destination) {\n destination.flushHeaders();\n }\n\n if (!body) {\n destination.end();\n\n return;\n }\n\n try {\n const reader = body.getReader();\n\n destination.on('close', () => {\n reader.cancel().catch((error) => {\n // eslint-disable-next-line no-console\n console.error(\n `An error occurred while writing the response body for: ${destination.req.url}.`,\n error,\n );\n });\n });\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n destination.end();\n break;\n }\n\n const canContinue = (destination as ServerResponse).write(value);\n if (canContinue === false) {\n // Explicitly check for `false`, as AWS may return `undefined` even though this is not valid.\n // See: https://github.com/CodeGenieApp/serverless-express/issues/683\n await new Promise<void>((resolve) => destination.once('drain', resolve));\n }\n }\n } catch {\n destination.end('Internal server error.');\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { argv } from 'node:process';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Determines whether the provided URL represents the main entry point module.\n *\n * This function checks if the provided URL corresponds to the main ESM module being executed directly.\n * It's useful for conditionally executing code that should only run when a module is the entry point,\n * such as starting a server or initializing an application.\n *\n * It performs two key checks:\n * 1. Verifies if the URL starts with 'file:', ensuring it is a local file.\n * 2. Compares the URL's resolved file path with the first command-line argument (`process.argv[1]`),\n * which points to the file being executed.\n *\n * @param url The URL of the module to check. This should typically be `import.meta.url`.\n * @returns `true` if the provided URL represents the main entry point, otherwise `false`.\n */\nexport function isMainModule(url: string): boolean {\n return url.startsWith('file:') && argv[1] === fileURLToPath(url);\n}\n"],"names":["attachNodeGlobalErrorHandlers","Zone","gThis","globalThis","ngAttachNodeGlobalErrorHandlersCalled","process","on","error","console","CommonEngineInlineCriticalCssProcessor","resourceCache","Map","html","outputPath","beasties","InlineCriticalCssProcessor","path","resourceContent","get","undefined","readFile","set","PERFORMANCE_MARK_PREFIX","printPerformanceLogs","maxWordLength","benchmarks","name","duration","performance","getEntriesByType","startsWith","step","slice","length","push","toFixed","clearMeasures","log","value","spaces","repeat","runMethodAndMeasurePerf","label","asyncMethod","labelName","startLabel","endLabel","mark","measure","clearMarks","noopRunMethodAndMeasurePerf","SSG_MARKER_REGEXP","CommonEngine","options","templateCache","inlineCriticalCssProcessor","pageIsSSG","constructor","render","opts","enablePerformanceProfiler","runMethod","retrieveSSGPage","renderApplication","inlineCriticalCss","content","publicPath","documentFilePath","dirname","url","pathname","URL","pagePath","join","fs","promises","normalize","resolve","exists","isSSG","test","moduleOrFactory","bootstrap","Error","extraProviders","provide","ɵSERVER_CONTEXT","useValue","providers","document","getDocument","commonRenderingOptions","isBootstrapFn","platformProviders","renderModule","filePath","doc","access","constants","F_OK","HTTP2_PSEUDO_HEADERS","Set","createWebRequestFromNodeRequest","nodeRequest","headers","method","withBody","referrer","referer","canParse","Request","createRequestUrl","createRequestHeaders","body","duplex","nodeHeaders","Headers","Object","entries","has","append","Array","isArray","item","socket","originalUrl","protocol","getFirstHeaderValue","encrypted","hostname","host","hostnameWithPort","includes","port","toString","split","trim","AngularNodeAppEngine","angularAppEngine","AngularAppEngine","handle","request","requestContext","webRequest","createNodeRequestHandler","handler","writeResponseToNodeResponse","source","destination","status","statusCode","cookieHeaderSet","setHeader","getSetCookie","flushHeaders","end","reader","getReader","cancel","catch","req","done","read","canContinue","write","Promise","once","isMainModule","argv","fileURLToPath"],"mappings":";;;;;;;;SAoBgBA,6BAA6BA,GAAA;AAC3C,EAAA,IAAI,OAAOC,IAAI,KAAK,WAAW,EAAE;AAC/B,IAAA;AACF;EAIA,MAAMC,KAAK,GAA4EC,UAAU;EACjG,IAAID,KAAK,CAACE,qCAAqC,EAAE;AAC/C,IAAA;AACF;EAEAF,KAAK,CAACE,qCAAqC,GAAG,IAAI;AAElDC,EAAAA,OAAO,CAEJC,EAAE,CAAC,oBAAoB,EAAGC,KAAK,IAAKC,OAAO,CAACD,KAAK,CAAC,oBAAoB,EAAEA,KAAK,CAAC,CAAA,CAE9ED,EAAE,CAAC,mBAAmB,EAAGC,KAAK,IAAKC,OAAO,CAACD,KAAK,CAAC,mBAAmB,EAAEA,KAAK,CAAC,CAAC;AAClF;;MC5BaE,sCAAsC,CAAA;AAChCC,EAAAA,aAAa,GAAG,IAAIC,GAAG,EAAkB;AAE1D,EAAA,MAAMN,OAAOA,CAACO,IAAY,EAAEC,UAA8B,EAAA;AACxD,IAAA,MAAMC,QAAQ,GAAG,IAAIC,2BAA0B,CAAC,MAAOC,IAAI,IAAI;MAC7D,IAAIC,eAAe,GAAG,IAAI,CAACP,aAAa,CAACQ,GAAG,CA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AAKuE,WAAW,CAACkB,IAAI,CAAC,OAAO,EAAEzF,OAAO,CAAC,CAAC;AAC1E;AACF;AACF,GAAA,CAAE,MAAM;AACNuE,IAAAA,WAAW,CAACO,GAAG,CAAC,wBAAwB,CAAC;AAC3C;AACF;;AC5DM,SAAUY,YAAYA,CAAClG,GAAW,EAAA;AACtC,EAAA,OAAOA,GAAG,CAACvC,UAAU,CAAC,OAAO,CAAC,IAAI0I,IAAI,CAAC,CAAC,CAAC,KAAKC,aAAa,CAACpG,GAAG,CAAC;AAClE;;;;"}
1
+ {"version":3,"file":"node.mjs","sources":["../../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/environment-options.ts","../../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/errors.ts","../../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/common-engine/inline-css-processor.ts","../../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/common-engine/peformance-profiler.ts","../../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/common-engine/common-engine.ts","../../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/request.ts","../../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/app-engine.ts","../../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/handler.ts","../../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/response.ts","../../../../../../k8-fastbuild-ST-fdfa778d11ba/bin/packages/angular/ssr/node/src/module.ts"],"sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\n/**\n * Retrieves the list of allowed hosts from the environment variable `NG_ALLOWED_HOSTS`.\n * @returns An array of allowed hosts.\n */\nexport function getAllowedHostsFromEnv(): ReadonlyArray<string> {\n const allowedHosts: string[] = [];\n const envNgAllowedHosts = process.env['NG_ALLOWED_HOSTS'];\n if (!envNgAllowedHosts) {\n return allowedHosts;\n }\n\n const hosts = envNgAllowedHosts.split(',');\n for (const host of hosts) {\n const trimmed = host.trim();\n if (trimmed.length > 0) {\n allowedHosts.push(trimmed);\n }\n }\n\n return allowedHosts;\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\n/**\n * Attaches listeners to the Node.js process to capture and handle unhandled rejections and uncaught exceptions.\n * Captured errors are logged to the console. This function logs errors to the console, preventing unhandled errors\n * from crashing the server. It is particularly useful for Zoneless apps, ensuring error handling without relying on Zone.js.\n *\n * @remarks\n * This function is a no-op if zone.js is available.\n * For Zone-based apps, similar functionality is provided by Zone.js itself. See the Zone.js implementation here:\n * https://github.com/angular/angular/blob/4a8d0b79001ec09bcd6f2d6b15117aa6aac1932c/packages/zone.js/lib/node/node.ts#L94%7C\n *\n * @internal\n */\nexport function attachNodeGlobalErrorHandlers(): void {\n if (typeof Zone !== 'undefined') {\n return;\n }\n\n // Ensure that the listeners are registered only once.\n // Otherwise, multiple instances may be registered during edit/refresh.\n const gThis: typeof globalThis & { ngAttachNodeGlobalErrorHandlersCalled?: boolean } = globalThis;\n if (gThis.ngAttachNodeGlobalErrorHandlersCalled) {\n return;\n }\n\n gThis.ngAttachNodeGlobalErrorHandlersCalled = true;\n\n process\n // eslint-disable-next-line no-console\n .on('unhandledRejection', (error) => console.error('unhandledRejection', error))\n // eslint-disable-next-line no-console\n .on('uncaughtException', (error) => console.error('uncaughtException', error));\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { ɵInlineCriticalCssProcessor as InlineCriticalCssProcessor } from '@angular/ssr';\nimport { readFile } from 'node:fs/promises';\n\nexport class CommonEngineInlineCriticalCssProcessor {\n private readonly resourceCache = new Map<string, string>();\n\n async process(html: string, outputPath: string | undefined): Promise<string> {\n const beasties = new InlineCriticalCssProcessor(async (path) => {\n let resourceContent = this.resourceCache.get(path);\n if (resourceContent === undefined) {\n resourceContent = await readFile(path, 'utf-8');\n this.resourceCache.set(path, resourceContent);\n }\n\n return resourceContent;\n }, outputPath);\n\n return beasties.process(html);\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nconst PERFORMANCE_MARK_PREFIX = '🅰️';\n\nexport function printPerformanceLogs(): void {\n let maxWordLength = 0;\n const benchmarks: [step: string, value: string][] = [];\n\n for (const { name, duration } of performance.getEntriesByType('measure')) {\n if (!name.startsWith(PERFORMANCE_MARK_PREFIX)) {\n continue;\n }\n\n // `🅰️:Retrieve SSG Page` -> `Retrieve SSG Page:`\n const step = name.slice(PERFORMANCE_MARK_PREFIX.length + 1) + ':';\n if (step.length > maxWordLength) {\n maxWordLength = step.length;\n }\n\n benchmarks.push([step, `${duration.toFixed(1)}ms`]);\n performance.clearMeasures(name);\n }\n\n /* eslint-disable no-console */\n console.log('********** Performance results **********');\n for (const [step, value] of benchmarks) {\n const spaces = maxWordLength - step.length + 5;\n console.log(step + ' '.repeat(spaces) + value);\n }\n console.log('*****************************************');\n /* eslint-enable no-console */\n}\n\nexport async function runMethodAndMeasurePerf<T>(\n label: string,\n asyncMethod: () => Promise<T>,\n): Promise<T> {\n const labelName = `${PERFORMANCE_MARK_PREFIX}:${label}`;\n const startLabel = `start:${labelName}`;\n const endLabel = `end:${labelName}`;\n\n try {\n performance.mark(startLabel);\n\n return await asyncMethod();\n } finally {\n performance.mark(endLabel);\n performance.measure(labelName, startLabel, endLabel);\n performance.clearMarks(startLabel);\n performance.clearMarks(endLabel);\n }\n}\n\nexport function noopRunMethodAndMeasurePerf<T>(\n label: string,\n asyncMethod: () => Promise<T>,\n): Promise<T> {\n return asyncMethod();\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { ApplicationRef, StaticProvider, Type } from '@angular/core';\nimport { BootstrapContext } from '@angular/platform-browser';\nimport { renderApplication, renderModule, ɵSERVER_CONTEXT } from '@angular/platform-server';\nimport * as fs from 'node:fs';\nimport { dirname, join, normalize, resolve } from 'node:path';\nimport { URL } from 'node:url';\nimport { validateUrl } from '../../../src/utils/validation';\nimport { getAllowedHostsFromEnv } from '../environment-options';\nimport { attachNodeGlobalErrorHandlers } from '../errors';\nimport { CommonEngineInlineCriticalCssProcessor } from './inline-css-processor';\nimport {\n noopRunMethodAndMeasurePerf,\n printPerformanceLogs,\n runMethodAndMeasurePerf,\n} from './peformance-profiler';\n\nconst SSG_MARKER_REGEXP = /ng-server-context=[\"']\\w*\\|?ssg\\|?\\w*[\"']/;\n\nexport interface CommonEngineOptions {\n /** A method that when invoked returns a promise that returns an `ApplicationRef` instance once resolved or an NgModule. */\n bootstrap?: Type<{}> | ((context: BootstrapContext) => Promise<ApplicationRef>);\n\n /** A set of platform level providers for all requests. */\n providers?: StaticProvider[];\n\n /** Enable request performance profiling data collection and printing the results in the server console. */\n enablePerformanceProfiler?: boolean;\n\n /** A set of hostnames that are allowed to access the server. */\n allowedHosts?: readonly string[];\n}\n\nexport interface CommonEngineRenderOptions {\n /** A method that when invoked returns a promise that returns an `ApplicationRef` instance once resolved or an NgModule. */\n bootstrap?: Type<{}> | ((context: BootstrapContext) => Promise<ApplicationRef>);\n\n /** A set of platform level providers for the current request. */\n providers?: StaticProvider[];\n url?: string;\n document?: string;\n documentFilePath?: string;\n\n /**\n * Reduce render blocking requests by inlining critical CSS.\n * Defaults to true.\n */\n inlineCriticalCss?: boolean;\n\n /**\n * Base path location of index file.\n * Defaults to the 'documentFilePath' dirname when not provided.\n */\n publicPath?: string;\n}\n\n/**\n * A common engine to use to server render an application.\n */\n\nexport class CommonEngine {\n private readonly templateCache = new Map<string, string>();\n private readonly inlineCriticalCssProcessor = new CommonEngineInlineCriticalCssProcessor();\n private readonly pageIsSSG = new Map<string, boolean>();\n private readonly allowedHosts: ReadonlySet<string>;\n\n constructor(private options?: CommonEngineOptions) {\n this.allowedHosts = new Set([\n ...getAllowedHostsFromEnv(),\n ...(this.options?.allowedHosts ?? []),\n ]);\n\n attachNodeGlobalErrorHandlers();\n }\n\n /**\n * Render an HTML document for a specific URL with specified\n * render options\n */\n async render(opts: CommonEngineRenderOptions): Promise<string> {\n const { url } = opts;\n\n if (url && URL.canParse(url)) {\n const urlObj = new URL(url);\n try {\n validateUrl(urlObj, this.allowedHosts);\n } catch (error) {\n const isAllowedHostConfigured = this.allowedHosts.size > 0;\n // eslint-disable-next-line no-console\n console.error(\n `ERROR: ${(error as Error).message}` +\n 'Please provide a list of allowed hosts in the \"allowedHosts\" option in the \"CommonEngine\" constructor.',\n isAllowedHostConfigured\n ? ''\n : '\\nFalling back to client side rendering. This will become a 400 Bad Request in a future major version.',\n );\n\n if (!isAllowedHostConfigured) {\n // Fallback to CSR to avoid a breaking change.\n // TODO(alanagius): Return a 400 and remove this fallback in the next major version (v22).\n let document = opts.document;\n if (!document && opts.documentFilePath) {\n document = opts.document ?? (await this.getDocument(opts.documentFilePath));\n }\n\n if (document) {\n return document;\n }\n }\n\n throw error;\n }\n }\n\n const enablePerformanceProfiler = this.options?.enablePerformanceProfiler;\n\n const runMethod = enablePerformanceProfiler\n ? runMethodAndMeasurePerf\n : noopRunMethodAndMeasurePerf;\n\n let html = await runMethod('Retrieve SSG Page', () => this.retrieveSSGPage(opts));\n\n if (html === undefined) {\n html = await runMethod('Render Page', () => this.renderApplication(opts));\n\n if (opts.inlineCriticalCss !== false) {\n const content = await runMethod('Inline Critical CSS', () =>\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.inlineCriticalCss(html!, opts),\n );\n\n html = content;\n }\n }\n\n if (enablePerformanceProfiler) {\n printPerformanceLogs();\n }\n\n return html;\n }\n\n private inlineCriticalCss(html: string, opts: CommonEngineRenderOptions): Promise<string> {\n const outputPath =\n opts.publicPath ?? (opts.documentFilePath ? dirname(opts.documentFilePath) : '');\n\n return this.inlineCriticalCssProcessor.process(html, outputPath);\n }\n\n private async retrieveSSGPage(opts: CommonEngineRenderOptions): Promise<string | undefined> {\n const { publicPath, documentFilePath, url } = opts;\n if (!publicPath || !documentFilePath || url === undefined) {\n return undefined;\n }\n\n const { pathname } = new URL(url, 'resolve://');\n // Do not use `resolve` here as otherwise it can lead to path traversal vulnerability.\n // See: https://portswigger.net/web-security/file-path-traversal\n const pagePath = join(publicPath, pathname, 'index.html');\n\n if (this.pageIsSSG.get(pagePath)) {\n // Serve pre-rendered page.\n return fs.promises.readFile(pagePath, 'utf-8');\n }\n\n if (!pagePath.startsWith(normalize(publicPath))) {\n // Potential path traversal detected.\n return undefined;\n }\n\n if (pagePath === resolve(documentFilePath) || !(await exists(pagePath))) {\n // View matches with prerender path or file does not exist.\n this.pageIsSSG.set(pagePath, false);\n\n return undefined;\n }\n\n // Static file exists.\n const content = await fs.promises.readFile(pagePath, 'utf-8');\n const isSSG = SSG_MARKER_REGEXP.test(content);\n this.pageIsSSG.set(pagePath, isSSG);\n\n return isSSG ? content : undefined;\n }\n\n private async renderApplication(opts: CommonEngineRenderOptions): Promise<string> {\n const moduleOrFactory = this.options?.bootstrap ?? opts.bootstrap;\n if (!moduleOrFactory) {\n throw new Error('A module or bootstrap option must be provided.');\n }\n\n const extraProviders: StaticProvider[] = [\n { provide: ɵSERVER_CONTEXT, useValue: 'ssr' },\n ...(opts.providers ?? []),\n ...(this.options?.providers ?? []),\n ];\n\n let document = opts.document;\n if (!document && opts.documentFilePath) {\n document = await this.getDocument(opts.documentFilePath);\n }\n\n const commonRenderingOptions = {\n url: opts.url,\n document,\n };\n\n return isBootstrapFn(moduleOrFactory)\n ? renderApplication(moduleOrFactory, {\n platformProviders: extraProviders,\n ...commonRenderingOptions,\n })\n : renderModule(moduleOrFactory, { extraProviders, ...commonRenderingOptions });\n }\n\n /** Retrieve the document from the cache or the filesystem */\n private async getDocument(filePath: string): Promise<string> {\n let doc = this.templateCache.get(filePath);\n\n if (!doc) {\n doc = await fs.promises.readFile(filePath, 'utf-8');\n this.templateCache.set(filePath, doc);\n }\n\n return doc;\n }\n}\n\nasync function exists(path: fs.PathLike): Promise<boolean> {\n try {\n await fs.promises.access(path, fs.constants.F_OK);\n\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isBootstrapFn(\n value: unknown,\n): value is (context: BootstrapContext) => Promise<ApplicationRef> {\n // We can differentiate between a module and a bootstrap function by reading compiler-generated `ɵmod` static property:\n return typeof value === 'function' && !('ɵmod' in value);\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type { IncomingHttpHeaders, IncomingMessage } from 'node:http';\nimport type { Http2ServerRequest } from 'node:http2';\nimport { getFirstHeaderValue } from '../../src/utils/validation';\n\n/**\n * A set containing all the pseudo-headers defined in the HTTP/2 specification.\n *\n * This set can be used to filter out pseudo-headers from a list of headers,\n * as they are not allowed to be set directly using the `Node.js` Undici API or\n * the web `Headers` API.\n */\nconst HTTP2_PSEUDO_HEADERS = new Set([':method', ':scheme', ':authority', ':path', ':status']);\n\n/**\n * Converts a Node.js `IncomingMessage` or `Http2ServerRequest` into a\n * Web Standard `Request` object.\n *\n * This function adapts the Node.js request objects to a format that can\n * be used by web platform APIs.\n *\n * @param nodeRequest - The Node.js request object (`IncomingMessage` or `Http2ServerRequest`) to convert.\n * @returns A Web Standard `Request` object.\n */\nexport function createWebRequestFromNodeRequest(\n nodeRequest: IncomingMessage | Http2ServerRequest,\n): Request {\n const { headers, method = 'GET' } = nodeRequest;\n const withBody = method !== 'GET' && method !== 'HEAD';\n const referrer = headers.referer && URL.canParse(headers.referer) ? headers.referer : undefined;\n\n return new Request(createRequestUrl(nodeRequest), {\n method,\n headers: createRequestHeaders(headers),\n body: withBody ? nodeRequest : undefined,\n duplex: withBody ? 'half' : undefined,\n referrer,\n });\n}\n\n/**\n * Creates a `Headers` object from Node.js `IncomingHttpHeaders`.\n *\n * @param nodeHeaders - The Node.js `IncomingHttpHeaders` object to convert.\n * @returns A `Headers` object containing the converted headers.\n */\nfunction createRequestHeaders(nodeHeaders: IncomingHttpHeaders): Headers {\n const headers = new Headers();\n\n for (const [name, value] of Object.entries(nodeHeaders)) {\n if (HTTP2_PSEUDO_HEADERS.has(name)) {\n continue;\n }\n\n if (typeof value === 'string') {\n headers.append(name, value);\n } else if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n }\n }\n\n return headers;\n}\n\n/**\n * Creates a `URL` object from a Node.js `IncomingMessage`, taking into account the protocol, host, and port.\n *\n * @param nodeRequest - The Node.js `IncomingMessage` or `Http2ServerRequest` object to extract URL information from.\n * @returns A `URL` object representing the request URL.\n */\nexport function createRequestUrl(nodeRequest: IncomingMessage | Http2ServerRequest): URL {\n const {\n headers,\n socket,\n url = '',\n originalUrl,\n } = nodeRequest as IncomingMessage & { originalUrl?: string };\n const protocol =\n getFirstHeaderValue(headers['x-forwarded-proto']) ??\n ('encrypted' in socket && socket.encrypted ? 'https' : 'http');\n const hostname =\n getFirstHeaderValue(headers['x-forwarded-host']) ?? headers.host ?? headers[':authority'];\n\n if (Array.isArray(hostname)) {\n throw new Error('host value cannot be an array.');\n }\n\n let hostnameWithPort = hostname;\n if (!hostname?.includes(':')) {\n const port = getFirstHeaderValue(headers['x-forwarded-port']);\n if (port) {\n hostnameWithPort += `:${port}`;\n }\n }\n\n return new URL(`${protocol}://${hostnameWithPort}${originalUrl ?? url}`);\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { AngularAppEngine } from '@angular/ssr';\nimport type { IncomingMessage } from 'node:http';\nimport type { Http2ServerRequest } from 'node:http2';\nimport { AngularAppEngineOptions } from '../../src/app-engine';\nimport { getAllowedHostsFromEnv } from './environment-options';\nimport { attachNodeGlobalErrorHandlers } from './errors';\nimport { createWebRequestFromNodeRequest } from './request';\n\n/**\n * Options for the Angular Node.js server application engine.\n */\nexport interface AngularNodeAppEngineOptions extends AngularAppEngineOptions {}\n\n/**\n * Angular server application engine.\n * Manages Angular server applications (including localized ones), handles rendering requests,\n * and optionally transforms index HTML before rendering.\n *\n * @remarks This class should be instantiated once and used as a singleton across the server-side\n * application to ensure consistent handling of rendering requests and resource management.\n */\nexport class AngularNodeAppEngine {\n private readonly angularAppEngine: AngularAppEngine;\n\n /**\n * Creates a new instance of the Angular Node.js server application engine.\n * @param options Options for the Angular Node.js server application engine.\n */\n constructor(options?: AngularNodeAppEngineOptions) {\n this.angularAppEngine = new AngularAppEngine({\n ...options,\n allowedHosts: [...getAllowedHostsFromEnv(), ...(options?.allowedHosts ?? [])],\n });\n\n attachNodeGlobalErrorHandlers();\n }\n\n /**\n * Handles an incoming HTTP request by serving prerendered content, performing server-side rendering,\n * or delivering a static file for client-side rendered routes based on the `RenderMode` setting.\n *\n * This method adapts Node.js's `IncomingMessage`, `Http2ServerRequest` or `Request`\n * to a format compatible with the `AngularAppEngine` and delegates the handling logic to it.\n *\n * @param request - The incoming HTTP request (`IncomingMessage`, `Http2ServerRequest` or `Request`).\n * @param requestContext - Optional context for rendering, such as metadata associated with the request.\n * @returns A promise that resolves to the resulting HTTP response object, or `null` if no matching Angular route is found.\n *\n * @remarks A request to `https://www.example.com/page/index.html` will serve or render the Angular route\n * corresponding to `https://www.example.com/page`.\n *\n * @remarks\n * To prevent potential Server-Side Request Forgery (SSRF), this function verifies the hostname\n * of the `request.url` against a list of authorized hosts.\n * If the hostname is not recognized and `allowedHosts` is not empty, a Client-Side Rendered (CSR) version of the\n * page is returned otherwise a 400 Bad Request is returned.\n *\n * Resolution:\n * Authorize your hostname by configuring `allowedHosts` in `angular.json` in:\n * `projects.[project-name].architect.build.options.security.allowedHosts`.\n * Alternatively, you can define the allowed hostname via the environment variable `process.env['NG_ALLOWED_HOSTS']`\n * or pass it directly through the configuration options of `AngularNodeAppEngine`.\n *\n * For more information see: https://angular.dev/best-practices/security#preventing-server-side-request-forgery-ssrf\n */\n async handle(\n request: IncomingMessage | Http2ServerRequest | Request,\n requestContext?: unknown,\n ): Promise<Response | null> {\n const webRequest =\n request instanceof Request ? request : createWebRequestFromNodeRequest(request);\n\n return this.angularAppEngine.handle(webRequest, requestContext);\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\n/**\n * Represents a middleware function for handling HTTP requests in a Node.js environment.\n *\n * @param req - The incoming HTTP request object.\n * @param res - The outgoing HTTP response object.\n * @param next - A callback function that signals the completion of the middleware or forwards the error if provided.\n *\n * @returns A Promise that resolves to void or simply void. The handler can be asynchronous.\n */\nexport type NodeRequestHandlerFunction = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (err?: unknown) => void,\n) => Promise<void> | void;\n\n/**\n * Attaches metadata to the handler function to mark it as a special handler for Node.js environments.\n *\n * @typeParam T - The type of the handler function.\n * @param handler - The handler function to be defined and annotated.\n * @returns The same handler function passed as an argument, with metadata attached.\n *\n * @example\n * Usage in an Express application:\n * ```ts\n * const app = express();\n * export default createNodeRequestHandler(app);\n * ```\n *\n * @example\n * Usage in a Hono application:\n * ```ts\n * const app = new Hono();\n * export default createNodeRequestHandler(async (req, res, next) => {\n * try {\n * const webRes = await app.fetch(createWebRequestFromNodeRequest(req));\n * if (webRes) {\n * await writeResponseToNodeResponse(webRes, res);\n * } else {\n * next();\n * }\n * } catch (error) {\n * next(error);\n * }\n * });\n * ```\n *\n * @example\n * Usage in a Fastify application:\n * ```ts\n * const app = Fastify();\n * export default createNodeRequestHandler(async (req, res) => {\n * await app.ready();\n * app.server.emit('request', req, res);\n * });\n * ```\n */\nexport function createNodeRequestHandler<T extends NodeRequestHandlerFunction>(handler: T): T {\n (handler as T & { __ng_node_request_handler__?: boolean })['__ng_node_request_handler__'] = true;\n\n return handler;\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type { ServerResponse } from 'node:http';\nimport type { Http2ServerResponse } from 'node:http2';\n\n/**\n * Streams a web-standard `Response` into a Node.js `ServerResponse`\n * or `Http2ServerResponse`.\n *\n * This function adapts the web `Response` object to write its content\n * to a Node.js response object, handling both HTTP/1.1 and HTTP/2.\n *\n * @param source - The web-standard `Response` object to stream from.\n * @param destination - The Node.js response object (`ServerResponse` or `Http2ServerResponse`) to stream into.\n * @returns A promise that resolves once the streaming operation is complete.\n */\nexport async function writeResponseToNodeResponse(\n source: Response,\n destination: ServerResponse | Http2ServerResponse,\n): Promise<void> {\n const { status, headers, body } = source;\n destination.statusCode = status;\n\n let cookieHeaderSet = false;\n for (const [name, value] of headers.entries()) {\n if (name === 'set-cookie') {\n if (cookieHeaderSet) {\n continue;\n }\n\n // Sets the 'set-cookie' header only once to ensure it is correctly applied.\n // Concatenating 'set-cookie' values can lead to incorrect behavior, so we use a single value from `headers.getSetCookie()`.\n destination.setHeader(name, headers.getSetCookie());\n cookieHeaderSet = true;\n } else {\n destination.setHeader(name, value);\n }\n }\n\n if ('flushHeaders' in destination) {\n destination.flushHeaders();\n }\n\n if (!body) {\n destination.end();\n\n return;\n }\n\n try {\n const reader = body.getReader();\n\n destination.on('close', () => {\n reader.cancel().catch((error) => {\n // eslint-disable-next-line no-console\n console.error(\n `An error occurred while writing the response body for: ${destination.req.url}.`,\n error,\n );\n });\n });\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n destination.end();\n break;\n }\n\n const canContinue = (destination as ServerResponse).write(value);\n if (canContinue === false) {\n // Explicitly check for `false`, as AWS may return `undefined` even though this is not valid.\n // See: https://github.com/CodeGenieApp/serverless-express/issues/683\n await new Promise<void>((resolve) => destination.once('drain', resolve));\n }\n }\n } catch {\n destination.end('Internal server error.');\n }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport { argv } from 'node:process';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Determines whether the provided URL represents the main entry point module.\n *\n * This function checks if the provided URL corresponds to the main ESM module being executed directly.\n * It's useful for conditionally executing code that should only run when a module is the entry point,\n * such as starting a server or initializing an application.\n *\n * It performs two key checks:\n * 1. Verifies if the URL starts with 'file:', ensuring it is a local file.\n * 2. Compares the URL's resolved file path with the first command-line argument (`process.argv[1]`),\n * which points to the file being executed.\n *\n * @param url The URL of the module to check. This should typically be `import.meta.url`.\n * @returns `true` if the provided URL represents the main entry point, otherwise `false`.\n */\nexport function isMainModule(url: string): boolean {\n return url.startsWith('file:') && argv[1] === fileURLToPath(url);\n}\n"],"names":["getAllowedHostsFromEnv","allowedHosts","envNgAllowedHosts","process","env","hosts","split","host","trimmed","trim","length","push","attachNodeGlobalErrorHandlers","Zone","gThis","globalThis","ngAttachNodeGlobalErrorHandlersCalled","on","error","console","CommonEngineInlineCriticalCssProcessor","resourceCache","Map","html","outputPath","beasties","InlineCriticalCssProcessor","path","resourceContent","get","undefined","readFile","set","PERFORMANCE_MARK_PREFIX","printPerformanceLogs","maxWordLength","benchmarks","name","duration","performance","getEntriesByType","startsWith","step","slice","toFixed","clearMeasures","log","value","spaces","repeat","runMethodAndMeasurePerf","label","asyncMethod","labelName","startLabel","endLabel","mark","measure","clearMarks","noopRunMethodAndMeasurePerf","SSG_MARKER_REGEXP","CommonEngine","options","templateCache","inlineCriticalCssProcessor","pageIsSSG","constructor","Set","render","opts","url","URL","canParse","urlObj","validateUrl","isAllowedHostConfigured","size","message","document","documentFilePath","getDocument","enablePerformanceProfiler","runMethod","retrieveSSGPage","renderApplication","inlineCriticalCss","content","publicPath","dirname","pathname","pagePath","join","fs","promises","normalize","resolve","exists","isSSG","test","moduleOrFactory","bootstrap","Error","extraProviders","provide","ɵSERVER_CONTEXT","useValue","providers","commonRenderingOptions","isBootstrapFn","platformProviders","renderModule","filePath","doc","access","constants","F_OK","HTTP2_PSEUDO_HEADERS","createWebRequestFromNodeRequest","nodeRequest","headers","method","withBody","referrer","referer","Request","createRequestUrl","createRequestHeaders","body","duplex","nodeHeaders","Headers","Object","entries","has","append","Array","isArray","item","socket","originalUrl","protocol","getFirstHeaderValue","encrypted","hostname","hostnameWithPort","includes","port","AngularNodeAppEngine","angularAppEngine","AngularAppEngine","handle","request","requestContext","webRequest","createNodeRequestHandler","handler","writeResponseToNodeResponse","source","destination","status","statusCode","cookieHeaderSet","setHeader","getSetCookie","flushHeaders","end","reader","getReader","cancel","catch","req","done","read","canContinue","write","Promise","once","isMainModule","argv","fileURLToPath"],"mappings":";;;;;;;;;SAYgBA,sBAAsBA,GAAA;EACpC,MAAMC,YAAY,GAAa,EAAE;AACjC,EAAA,MAAMC,iBAAiB,GAAGC,OAAO,CAACC,GAAG,CAAC,kBAAkB,CAAC;EACzD,IAAI,CAACF,iBAAiB,EAAE;AACtB,IAAA,OAAOD,YAAY;AACrB;AAEA,EAAA,MAAMI,KAAK,GAAGH,iBAAiB,CAACI,KAAK,CAAC,GAAG,CAAC;AAC1C,EAAA,KAAK,MAAMC,IAAI,IAAIF,KAAK,EAAE;AACxB,IAAA,MAAMG,OAAO,GAAGD,IAAI,CAACE,IAAI,EAAE;AAC3B,IAAA,IAAID,OAAO,CAACE,MAAM,GAAG,CAAC,EAAE;AACtBT,MAAAA,YAAY,CAACU,IAAI,CAACH,OAAO,CAAC;AAC5B;AACF;AAEA,EAAA,OAAOP,YAAY;AACrB;;SCRgBW,6BAA6BA,GAAA;AAC3C,EAA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,OAAO,EAAE,MAAK;MAC3BqJ,MAAM,CAACE,MAAM,EAAE,CAACC,KAAK,CAAEvJ,KAAK,IAAI;AAE9BC,QAAAA,OAAO,CAACD,KAAK,CACX,CAAA,uDAAA,EAA0D4I,WAAW,CAACY,GAAG,CAACpG,GAAG,CAAA,CAAA,CAAG,EAChFpD,KAAK,CACN;AACH,OAAC,CAAC;AACJ,KAAC,CAAC;AAGF,IAAA,OAAO,IAAI,EAAE;MACX,MAAM;QAAEyJ,IAAI;AAAE5H,QAAAA;AAAK,OAAE,GAAG,MAAMuH,MAAM,CAACM,IAAI,EAAE;AAC3C,MAAA,IAAID,IAAI,EAAE;QACRb,WAAW,CAACO,GAAG,EAAE;AACjB,QAAA;AACF;AAEA,MAAA,MAAMQ,WAAW,GAAIf,WAA8B,CAACgB,KAAK,CAAC/H,KAAK,CAAC;MAChE,IAAI8H,WAAW,KAAK,KAAK,EAAE;AAGzB,QAAA,MAAM,IAAIE,OAAO,CAAQhF,OAAO,IAAK+D,WAAW,CAACkB,IAAI,CAAC,OAAO,EAAEjF,OAAO,CAAC,CAAC;AAC1E;AACF;AACF,GAAA,CAAE,MAAM;AACN+D,IAAAA,WAAW,CAACO,GAAG,CAAC,wBAAwB,CAAC;AAC3C;AACF;;AC5DM,SAAUY,YAAYA,CAAC3G,GAAW,EAAA;AACtC,EAAA,OAAOA,GAAG,CAAC7B,UAAU,CAAC,OAAO,CAAC,IAAIyI,IAAI,CAAC,CAAC,CAAC,KAAKC,aAAa,CAAC7G,GAAG,CAAC;AAClE;;;;"}
package/fesm2022/ssr.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { validateRequest, cloneRequestAndPatchHeaders } from './_validation-chunk.mjs';
1
2
  import { ɵConsole as _Console, ApplicationRef, REQUEST, InjectionToken, provideEnvironmentInitializer, inject, makeEnvironmentProviders, ɵENABLE_ROOT_COMPONENT_BOOTSTRAP as _ENABLE_ROOT_COMPONENT_BOOTSTRAP, Compiler, createEnvironmentInjector, EnvironmentInjector, runInInjectionContext, ɵresetCompiledComponents as _resetCompiledComponents, REQUEST_CONTEXT, RESPONSE_INIT, LOCALE_ID } from '@angular/core';
2
3
  import { platformServer, INITIAL_CONFIG, ɵSERVER_CONTEXT as _SERVER_CONTEXT, ɵrenderInternal as _renderInternal, provideServerRendering as provideServerRendering$1 } from '@angular/platform-server';
3
4
  import { ActivatedRoute, Router, ROUTES, ɵloadChildren as _loadChildren } from '@angular/router';
@@ -67,23 +68,24 @@ function addTrailingSlash(url) {
67
68
  return url.at(-1) === '/' ? url : `${url}/`;
68
69
  }
69
70
  function joinUrlParts(...parts) {
70
- const normalizeParts = [];
71
+ const normalizedParts = [];
71
72
  for (const part of parts) {
72
73
  if (part === '') {
73
74
  continue;
74
75
  }
75
- let normalizedPart = part;
76
- if (part[0] === '/') {
77
- normalizedPart = normalizedPart.slice(1);
76
+ let start = 0;
77
+ let end = part.length;
78
+ while (start < end && part[start] === '/') {
79
+ start++;
78
80
  }
79
- if (part.at(-1) === '/') {
80
- normalizedPart = normalizedPart.slice(0, -1);
81
+ while (end > start && part[end - 1] === '/') {
82
+ end--;
81
83
  }
82
- if (normalizedPart !== '') {
83
- normalizeParts.push(normalizedPart);
84
+ if (start < end) {
85
+ normalizedParts.push(part.slice(start, end));
84
86
  }
85
87
  }
86
- return addLeadingSlash(normalizeParts.join('/'));
88
+ return addLeadingSlash(normalizedParts.join('/'));
87
89
  }
88
90
  function stripIndexHtmlFromURL(url) {
89
91
  if (url.pathname.endsWith('/index.html')) {
@@ -1352,6 +1354,23 @@ class AngularServerApp {
1352
1354
  }
1353
1355
  return html;
1354
1356
  }
1357
+ async serveClientSidePage() {
1358
+ const {
1359
+ manifest: {
1360
+ locale
1361
+ },
1362
+ assets
1363
+ } = this;
1364
+ const html = await assets.getServerAsset('index.csr.html').text();
1365
+ return new Response(html, {
1366
+ headers: new Headers({
1367
+ 'Content-Type': 'text/html;charset=UTF-8',
1368
+ ...(locale !== undefined ? {
1369
+ 'Content-Language': locale
1370
+ } : {})
1371
+ })
1372
+ });
1373
+ }
1355
1374
  }
1356
1375
  let angularServerApp;
1357
1376
  function getOrCreateAngularServerApp(options) {
@@ -1450,12 +1469,26 @@ class AngularAppEngine {
1450
1469
  static ɵallowStaticRouteRender = false;
1451
1470
  static ɵhooks = new Hooks();
1452
1471
  manifest = getAngularAppEngineManifest();
1472
+ allowedHosts;
1453
1473
  supportedLocales = Object.keys(this.manifest.supportedLocales);
1454
1474
  entryPointsCache = new Map();
1475
+ constructor(options) {
1476
+ this.allowedHosts = new Set([...(options?.allowedHosts ?? []), ...this.manifest.allowedHosts]);
1477
+ }
1455
1478
  async handle(request, requestContext) {
1456
- const serverApp = await this.getAngularServerAppForRequest(request);
1479
+ const allowedHost = this.allowedHosts;
1480
+ try {
1481
+ validateRequest(request, allowedHost);
1482
+ } catch (error) {
1483
+ return this.handleValidationError(error, request);
1484
+ }
1485
+ const {
1486
+ request: securedRequest,
1487
+ onError: onHeaderValidationError
1488
+ } = cloneRequestAndPatchHeaders(request, allowedHost);
1489
+ const serverApp = await this.getAngularServerAppForRequest(securedRequest);
1457
1490
  if (serverApp) {
1458
- return serverApp.handle(request, requestContext);
1491
+ return Promise.race([onHeaderValidationError.then(error => this.handleValidationError(error, securedRequest)), serverApp.handle(securedRequest, requestContext)]);
1459
1492
  }
1460
1493
  if (this.supportedLocales.length > 1) {
1461
1494
  return this.redirectBasedOnAcceptLanguage(request);
@@ -1528,6 +1561,22 @@ class AngularAppEngine {
1528
1561
  const potentialLocale = getPotentialLocaleIdFromUrl(url, basePath);
1529
1562
  return this.getEntryPointExports(potentialLocale) ?? this.getEntryPointExports('');
1530
1563
  }
1564
+ async handleValidationError(error, request) {
1565
+ const isAllowedHostConfigured = this.allowedHosts.size > 0;
1566
+ const errorMessage = error.message;
1567
+ console.error(`ERROR: Bad Request ("${request.url}").\n` + errorMessage + (isAllowedHostConfigured ? '' : '\nFalling back to client side rendering. This will become a 400 Bad Request in a future major version.') + '\n\nFor more information, see https://angular.dev/best-practices/security#preventing-server-side-request-forgery-ssrf');
1568
+ if (isAllowedHostConfigured) {
1569
+ return new Response(errorMessage, {
1570
+ status: 400,
1571
+ statusText: 'Bad Request',
1572
+ headers: {
1573
+ 'Content-Type': 'text/plain'
1574
+ }
1575
+ });
1576
+ }
1577
+ const serverApp = await this.getAngularServerAppForRequest(request);
1578
+ return serverApp?.serveClientSidePage() ?? null;
1579
+ }
1531
1580
  }
1532
1581
 
1533
1582
  function createRequestHandler(handler) {