@angular/ssr 21.0.0-next.9 → 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/node.mjs CHANGED
@@ -6,468 +6,307 @@ import { ɵInlineCriticalCssProcessor as _InlineCriticalCssProcessor, AngularApp
6
6
  import { readFile } from 'node:fs/promises';
7
7
  import { argv } from 'node:process';
8
8
 
9
- /**
10
- * Attaches listeners to the Node.js process to capture and handle unhandled rejections and uncaught exceptions.
11
- * Captured errors are logged to the console. This function logs errors to the console, preventing unhandled errors
12
- * from crashing the server. It is particularly useful for Zoneless apps, ensuring error handling without relying on Zone.js.
13
- *
14
- * @remarks
15
- * This function is a no-op if zone.js is available.
16
- * For Zone-based apps, similar functionality is provided by Zone.js itself. See the Zone.js implementation here:
17
- * https://github.com/angular/angular/blob/4a8d0b79001ec09bcd6f2d6b15117aa6aac1932c/packages/zone.js/lib/node/node.ts#L94%7C
18
- *
19
- * @internal
20
- */
21
9
  function attachNodeGlobalErrorHandlers() {
22
- if (typeof Zone !== 'undefined') {
23
- return;
24
- }
25
- // Ensure that the listeners are registered only once.
26
- // Otherwise, multiple instances may be registered during edit/refresh.
27
- const gThis = globalThis;
28
- if (gThis.ngAttachNodeGlobalErrorHandlersCalled) {
29
- return;
30
- }
31
- gThis.ngAttachNodeGlobalErrorHandlersCalled = true;
32
- process
33
- // eslint-disable-next-line no-console
34
- .on('unhandledRejection', (error) => console.error('unhandledRejection', error))
35
- // eslint-disable-next-line no-console
36
- .on('uncaughtException', (error) => console.error('uncaughtException', error));
10
+ if (typeof Zone !== 'undefined') {
11
+ return;
12
+ }
13
+ const gThis = globalThis;
14
+ if (gThis.ngAttachNodeGlobalErrorHandlersCalled) {
15
+ return;
16
+ }
17
+ gThis.ngAttachNodeGlobalErrorHandlersCalled = true;
18
+ process.on('unhandledRejection', error => console.error('unhandledRejection', error)).on('uncaughtException', error => console.error('uncaughtException', error));
37
19
  }
38
20
 
39
21
  class CommonEngineInlineCriticalCssProcessor {
40
- resourceCache = new Map();
41
- async process(html, outputPath) {
42
- const beasties = new _InlineCriticalCssProcessor(async (path) => {
43
- let resourceContent = this.resourceCache.get(path);
44
- if (resourceContent === undefined) {
45
- resourceContent = await readFile(path, 'utf-8');
46
- this.resourceCache.set(path, resourceContent);
47
- }
48
- return resourceContent;
49
- }, outputPath);
50
- return beasties.process(html);
51
- }
22
+ resourceCache = new Map();
23
+ async process(html, outputPath) {
24
+ const beasties = new _InlineCriticalCssProcessor(async path => {
25
+ let resourceContent = this.resourceCache.get(path);
26
+ if (resourceContent === undefined) {
27
+ resourceContent = await readFile(path, 'utf-8');
28
+ this.resourceCache.set(path, resourceContent);
29
+ }
30
+ return resourceContent;
31
+ }, outputPath);
32
+ return beasties.process(html);
33
+ }
52
34
  }
53
35
 
54
36
  const PERFORMANCE_MARK_PREFIX = '🅰️';
55
37
  function printPerformanceLogs() {
56
- let maxWordLength = 0;
57
- const benchmarks = [];
58
- for (const { name, duration } of performance.getEntriesByType('measure')) {
59
- if (!name.startsWith(PERFORMANCE_MARK_PREFIX)) {
60
- continue;
61
- }
62
- // `🅰️:Retrieve SSG Page` -> `Retrieve SSG Page:`
63
- const step = name.slice(PERFORMANCE_MARK_PREFIX.length + 1) + ':';
64
- if (step.length > maxWordLength) {
65
- maxWordLength = step.length;
66
- }
67
- benchmarks.push([step, `${duration.toFixed(1)}ms`]);
68
- performance.clearMeasures(name);
38
+ let maxWordLength = 0;
39
+ const benchmarks = [];
40
+ for (const {
41
+ name,
42
+ duration
43
+ } of performance.getEntriesByType('measure')) {
44
+ if (!name.startsWith(PERFORMANCE_MARK_PREFIX)) {
45
+ continue;
69
46
  }
70
- /* eslint-disable no-console */
71
- console.log('********** Performance results **********');
72
- for (const [step, value] of benchmarks) {
73
- const spaces = maxWordLength - step.length + 5;
74
- console.log(step + ' '.repeat(spaces) + value);
47
+ const step = name.slice(PERFORMANCE_MARK_PREFIX.length + 1) + ':';
48
+ if (step.length > maxWordLength) {
49
+ maxWordLength = step.length;
75
50
  }
76
- console.log('*****************************************');
77
- /* eslint-enable no-console */
51
+ benchmarks.push([step, `${duration.toFixed(1)}ms`]);
52
+ performance.clearMeasures(name);
53
+ }
54
+ console.log('********** Performance results **********');
55
+ for (const [step, value] of benchmarks) {
56
+ const spaces = maxWordLength - step.length + 5;
57
+ console.log(step + ' '.repeat(spaces) + value);
58
+ }
59
+ console.log('*****************************************');
78
60
  }
79
61
  async function runMethodAndMeasurePerf(label, asyncMethod) {
80
- const labelName = `${PERFORMANCE_MARK_PREFIX}:${label}`;
81
- const startLabel = `start:${labelName}`;
82
- const endLabel = `end:${labelName}`;
83
- try {
84
- performance.mark(startLabel);
85
- return await asyncMethod();
86
- }
87
- finally {
88
- performance.mark(endLabel);
89
- performance.measure(labelName, startLabel, endLabel);
90
- performance.clearMarks(startLabel);
91
- performance.clearMarks(endLabel);
92
- }
62
+ const labelName = `${PERFORMANCE_MARK_PREFIX}:${label}`;
63
+ const startLabel = `start:${labelName}`;
64
+ const endLabel = `end:${labelName}`;
65
+ try {
66
+ performance.mark(startLabel);
67
+ return await asyncMethod();
68
+ } finally {
69
+ performance.mark(endLabel);
70
+ performance.measure(labelName, startLabel, endLabel);
71
+ performance.clearMarks(startLabel);
72
+ performance.clearMarks(endLabel);
73
+ }
93
74
  }
94
75
  function noopRunMethodAndMeasurePerf(label, asyncMethod) {
95
- return asyncMethod();
76
+ return asyncMethod();
96
77
  }
97
78
 
98
79
  const SSG_MARKER_REGEXP = /ng-server-context=["']\w*\|?ssg\|?\w*["']/;
99
- /**
100
- * A common engine to use to server render an application.
101
- */
102
80
  class CommonEngine {
103
- options;
104
- templateCache = new Map();
105
- inlineCriticalCssProcessor = new CommonEngineInlineCriticalCssProcessor();
106
- pageIsSSG = new Map();
107
- constructor(options) {
108
- this.options = options;
109
- attachNodeGlobalErrorHandlers();
81
+ options;
82
+ templateCache = new Map();
83
+ inlineCriticalCssProcessor = new CommonEngineInlineCriticalCssProcessor();
84
+ pageIsSSG = new Map();
85
+ constructor(options) {
86
+ this.options = options;
87
+ attachNodeGlobalErrorHandlers();
88
+ }
89
+ async render(opts) {
90
+ const enablePerformanceProfiler = this.options?.enablePerformanceProfiler;
91
+ const runMethod = enablePerformanceProfiler ? runMethodAndMeasurePerf : noopRunMethodAndMeasurePerf;
92
+ let html = await runMethod('Retrieve SSG Page', () => this.retrieveSSGPage(opts));
93
+ if (html === undefined) {
94
+ html = await runMethod('Render Page', () => this.renderApplication(opts));
95
+ if (opts.inlineCriticalCss !== false) {
96
+ const content = await runMethod('Inline Critical CSS', () => this.inlineCriticalCss(html, opts));
97
+ html = content;
98
+ }
110
99
  }
111
- /**
112
- * Render an HTML document for a specific URL with specified
113
- * render options
114
- */
115
- async render(opts) {
116
- const enablePerformanceProfiler = this.options?.enablePerformanceProfiler;
117
- const runMethod = enablePerformanceProfiler
118
- ? runMethodAndMeasurePerf
119
- : noopRunMethodAndMeasurePerf;
120
- let html = await runMethod('Retrieve SSG Page', () => this.retrieveSSGPage(opts));
121
- if (html === undefined) {
122
- html = await runMethod('Render Page', () => this.renderApplication(opts));
123
- if (opts.inlineCriticalCss !== false) {
124
- const content = await runMethod('Inline Critical CSS', () =>
125
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
126
- this.inlineCriticalCss(html, opts));
127
- html = content;
128
- }
129
- }
130
- if (enablePerformanceProfiler) {
131
- printPerformanceLogs();
132
- }
133
- return html;
100
+ if (enablePerformanceProfiler) {
101
+ printPerformanceLogs();
134
102
  }
135
- inlineCriticalCss(html, opts) {
136
- const outputPath = opts.publicPath ?? (opts.documentFilePath ? dirname(opts.documentFilePath) : '');
137
- return this.inlineCriticalCssProcessor.process(html, outputPath);
103
+ return html;
104
+ }
105
+ inlineCriticalCss(html, opts) {
106
+ const outputPath = opts.publicPath ?? (opts.documentFilePath ? dirname(opts.documentFilePath) : '');
107
+ return this.inlineCriticalCssProcessor.process(html, outputPath);
108
+ }
109
+ async retrieveSSGPage(opts) {
110
+ const {
111
+ publicPath,
112
+ documentFilePath,
113
+ url
114
+ } = opts;
115
+ if (!publicPath || !documentFilePath || url === undefined) {
116
+ return undefined;
138
117
  }
139
- async retrieveSSGPage(opts) {
140
- const { publicPath, documentFilePath, url } = opts;
141
- if (!publicPath || !documentFilePath || url === undefined) {
142
- return undefined;
143
- }
144
- const { pathname } = new URL$1(url, 'resolve://');
145
- // Do not use `resolve` here as otherwise it can lead to path traversal vulnerability.
146
- // See: https://portswigger.net/web-security/file-path-traversal
147
- const pagePath = join(publicPath, pathname, 'index.html');
148
- if (this.pageIsSSG.get(pagePath)) {
149
- // Serve pre-rendered page.
150
- return fs.promises.readFile(pagePath, 'utf-8');
151
- }
152
- if (!pagePath.startsWith(normalize(publicPath))) {
153
- // Potential path traversal detected.
154
- return undefined;
155
- }
156
- if (pagePath === resolve(documentFilePath) || !(await exists(pagePath))) {
157
- // View matches with prerender path or file does not exist.
158
- this.pageIsSSG.set(pagePath, false);
159
- return undefined;
160
- }
161
- // Static file exists.
162
- const content = await fs.promises.readFile(pagePath, 'utf-8');
163
- const isSSG = SSG_MARKER_REGEXP.test(content);
164
- this.pageIsSSG.set(pagePath, isSSG);
165
- return isSSG ? content : undefined;
118
+ const {
119
+ pathname
120
+ } = new URL$1(url, 'resolve://');
121
+ const pagePath = join(publicPath, pathname, 'index.html');
122
+ if (this.pageIsSSG.get(pagePath)) {
123
+ return fs.promises.readFile(pagePath, 'utf-8');
166
124
  }
167
- async renderApplication(opts) {
168
- const moduleOrFactory = this.options?.bootstrap ?? opts.bootstrap;
169
- if (!moduleOrFactory) {
170
- throw new Error('A module or bootstrap option must be provided.');
171
- }
172
- const extraProviders = [
173
- { provide: _SERVER_CONTEXT, useValue: 'ssr' },
174
- ...(opts.providers ?? []),
175
- ...(this.options?.providers ?? []),
176
- ];
177
- let document = opts.document;
178
- if (!document && opts.documentFilePath) {
179
- document = await this.getDocument(opts.documentFilePath);
180
- }
181
- const commonRenderingOptions = {
182
- url: opts.url,
183
- document,
184
- };
185
- return isBootstrapFn(moduleOrFactory)
186
- ? renderApplication(moduleOrFactory, {
187
- platformProviders: extraProviders,
188
- ...commonRenderingOptions,
189
- })
190
- : renderModule(moduleOrFactory, { extraProviders, ...commonRenderingOptions });
125
+ if (!pagePath.startsWith(normalize(publicPath))) {
126
+ return undefined;
191
127
  }
192
- /** Retrieve the document from the cache or the filesystem */
193
- async getDocument(filePath) {
194
- let doc = this.templateCache.get(filePath);
195
- if (!doc) {
196
- doc = await fs.promises.readFile(filePath, 'utf-8');
197
- this.templateCache.set(filePath, doc);
198
- }
199
- return doc;
128
+ if (pagePath === resolve(documentFilePath) || !(await exists(pagePath))) {
129
+ this.pageIsSSG.set(pagePath, false);
130
+ return undefined;
200
131
  }
201
- }
202
- async function exists(path) {
203
- try {
204
- await fs.promises.access(path, fs.constants.F_OK);
205
- return true;
132
+ const content = await fs.promises.readFile(pagePath, 'utf-8');
133
+ const isSSG = SSG_MARKER_REGEXP.test(content);
134
+ this.pageIsSSG.set(pagePath, isSSG);
135
+ return isSSG ? content : undefined;
136
+ }
137
+ async renderApplication(opts) {
138
+ const moduleOrFactory = this.options?.bootstrap ?? opts.bootstrap;
139
+ if (!moduleOrFactory) {
140
+ throw new Error('A module or bootstrap option must be provided.');
206
141
  }
207
- catch {
208
- return false;
142
+ const extraProviders = [{
143
+ provide: _SERVER_CONTEXT,
144
+ useValue: 'ssr'
145
+ }, ...(opts.providers ?? []), ...(this.options?.providers ?? [])];
146
+ let document = opts.document;
147
+ if (!document && opts.documentFilePath) {
148
+ document = await this.getDocument(opts.documentFilePath);
209
149
  }
150
+ const commonRenderingOptions = {
151
+ url: opts.url,
152
+ document
153
+ };
154
+ return isBootstrapFn(moduleOrFactory) ? renderApplication(moduleOrFactory, {
155
+ platformProviders: extraProviders,
156
+ ...commonRenderingOptions
157
+ }) : renderModule(moduleOrFactory, {
158
+ extraProviders,
159
+ ...commonRenderingOptions
160
+ });
161
+ }
162
+ async getDocument(filePath) {
163
+ let doc = this.templateCache.get(filePath);
164
+ if (!doc) {
165
+ doc = await fs.promises.readFile(filePath, 'utf-8');
166
+ this.templateCache.set(filePath, doc);
167
+ }
168
+ return doc;
169
+ }
170
+ }
171
+ async function exists(path) {
172
+ try {
173
+ await fs.promises.access(path, fs.constants.F_OK);
174
+ return true;
175
+ } catch {
176
+ return false;
177
+ }
210
178
  }
211
179
  function isBootstrapFn(value) {
212
- // We can differentiate between a module and a bootstrap function by reading compiler-generated `ɵmod` static property:
213
- return typeof value === 'function' && !('ɵmod' in value);
180
+ return typeof value === 'function' && !('ɵmod' in value);
214
181
  }
215
182
 
216
- /**
217
- * A set containing all the pseudo-headers defined in the HTTP/2 specification.
218
- *
219
- * This set can be used to filter out pseudo-headers from a list of headers,
220
- * as they are not allowed to be set directly using the `Node.js` Undici API or
221
- * the web `Headers` API.
222
- */
223
183
  const HTTP2_PSEUDO_HEADERS = new Set([':method', ':scheme', ':authority', ':path', ':status']);
224
- /**
225
- * Converts a Node.js `IncomingMessage` or `Http2ServerRequest` into a
226
- * Web Standard `Request` object.
227
- *
228
- * This function adapts the Node.js request objects to a format that can
229
- * be used by web platform APIs.
230
- *
231
- * @param nodeRequest - The Node.js request object (`IncomingMessage` or `Http2ServerRequest`) to convert.
232
- * @returns A Web Standard `Request` object.
233
- */
234
184
  function createWebRequestFromNodeRequest(nodeRequest) {
235
- const { headers, method = 'GET' } = nodeRequest;
236
- const withBody = method !== 'GET' && method !== 'HEAD';
237
- const referrer = headers.referer && URL.canParse(headers.referer) ? headers.referer : undefined;
238
- return new Request(createRequestUrl(nodeRequest), {
239
- method,
240
- headers: createRequestHeaders(headers),
241
- body: withBody ? nodeRequest : undefined,
242
- duplex: withBody ? 'half' : undefined,
243
- referrer,
244
- });
185
+ const {
186
+ headers,
187
+ method = 'GET'
188
+ } = nodeRequest;
189
+ const withBody = method !== 'GET' && method !== 'HEAD';
190
+ const referrer = headers.referer && URL.canParse(headers.referer) ? headers.referer : undefined;
191
+ return new Request(createRequestUrl(nodeRequest), {
192
+ method,
193
+ headers: createRequestHeaders(headers),
194
+ body: withBody ? nodeRequest : undefined,
195
+ duplex: withBody ? 'half' : undefined,
196
+ referrer
197
+ });
245
198
  }
246
- /**
247
- * Creates a `Headers` object from Node.js `IncomingHttpHeaders`.
248
- *
249
- * @param nodeHeaders - The Node.js `IncomingHttpHeaders` object to convert.
250
- * @returns A `Headers` object containing the converted headers.
251
- */
252
199
  function createRequestHeaders(nodeHeaders) {
253
- const headers = new Headers();
254
- for (const [name, value] of Object.entries(nodeHeaders)) {
255
- if (HTTP2_PSEUDO_HEADERS.has(name)) {
256
- continue;
257
- }
258
- if (typeof value === 'string') {
259
- headers.append(name, value);
260
- }
261
- else if (Array.isArray(value)) {
262
- for (const item of value) {
263
- headers.append(name, item);
264
- }
265
- }
200
+ const headers = new Headers();
201
+ for (const [name, value] of Object.entries(nodeHeaders)) {
202
+ if (HTTP2_PSEUDO_HEADERS.has(name)) {
203
+ continue;
204
+ }
205
+ if (typeof value === 'string') {
206
+ headers.append(name, value);
207
+ } else if (Array.isArray(value)) {
208
+ for (const item of value) {
209
+ headers.append(name, item);
210
+ }
266
211
  }
267
- return headers;
212
+ }
213
+ return headers;
268
214
  }
269
- /**
270
- * Creates a `URL` object from a Node.js `IncomingMessage`, taking into account the protocol, host, and port.
271
- *
272
- * @param nodeRequest - The Node.js `IncomingMessage` or `Http2ServerRequest` object to extract URL information from.
273
- * @returns A `URL` object representing the request URL.
274
- */
275
215
  function createRequestUrl(nodeRequest) {
276
- const { headers, socket, url = '', originalUrl, } = nodeRequest;
277
- const protocol = getFirstHeaderValue(headers['x-forwarded-proto']) ??
278
- ('encrypted' in socket && socket.encrypted ? 'https' : 'http');
279
- const hostname = getFirstHeaderValue(headers['x-forwarded-host']) ?? headers.host ?? headers[':authority'];
280
- if (Array.isArray(hostname)) {
281
- throw new Error('host value cannot be an array.');
216
+ const {
217
+ headers,
218
+ socket,
219
+ url = '',
220
+ originalUrl
221
+ } = nodeRequest;
222
+ const protocol = getFirstHeaderValue(headers['x-forwarded-proto']) ?? ('encrypted' in socket && socket.encrypted ? 'https' : 'http');
223
+ const hostname = getFirstHeaderValue(headers['x-forwarded-host']) ?? headers.host ?? headers[':authority'];
224
+ if (Array.isArray(hostname)) {
225
+ throw new Error('host value cannot be an array.');
226
+ }
227
+ let hostnameWithPort = hostname;
228
+ if (!hostname?.includes(':')) {
229
+ const port = getFirstHeaderValue(headers['x-forwarded-port']);
230
+ if (port) {
231
+ hostnameWithPort += `:${port}`;
282
232
  }
283
- let hostnameWithPort = hostname;
284
- if (!hostname?.includes(':')) {
285
- const port = getFirstHeaderValue(headers['x-forwarded-port']);
286
- if (port) {
287
- hostnameWithPort += `:${port}`;
288
- }
289
- }
290
- return new URL(`${protocol}://${hostnameWithPort}${originalUrl ?? url}`);
233
+ }
234
+ return new URL(`${protocol}://${hostnameWithPort}${originalUrl ?? url}`);
291
235
  }
292
- /**
293
- * Extracts the first value from a multi-value header string.
294
- *
295
- * @param value - A string or an array of strings representing the header values.
296
- * If it's a string, values are expected to be comma-separated.
297
- * @returns The first trimmed value from the multi-value header, or `undefined` if the input is invalid or empty.
298
- *
299
- * @example
300
- * ```typescript
301
- * getFirstHeaderValue("value1, value2, value3"); // "value1"
302
- * getFirstHeaderValue(["value1", "value2"]); // "value1"
303
- * getFirstHeaderValue(undefined); // undefined
304
- * ```
305
- */
306
236
  function getFirstHeaderValue(value) {
307
- return value?.toString().split(',', 1)[0]?.trim();
237
+ return value?.toString().split(',', 1)[0]?.trim();
308
238
  }
309
239
 
310
- /**
311
- * Angular server application engine.
312
- * Manages Angular server applications (including localized ones), handles rendering requests,
313
- * and optionally transforms index HTML before rendering.
314
- *
315
- * @remarks This class should be instantiated once and used as a singleton across the server-side
316
- * application to ensure consistent handling of rendering requests and resource management.
317
- */
318
240
  class AngularNodeAppEngine {
319
- angularAppEngine = new AngularAppEngine();
320
- constructor() {
321
- attachNodeGlobalErrorHandlers();
322
- }
323
- /**
324
- * Handles an incoming HTTP request by serving prerendered content, performing server-side rendering,
325
- * or delivering a static file for client-side rendered routes based on the `RenderMode` setting.
326
- *
327
- * This method adapts Node.js's `IncomingMessage` or `Http2ServerRequest`
328
- * to a format compatible with the `AngularAppEngine` and delegates the handling logic to it.
329
- *
330
- * @param request - The incoming HTTP request (`IncomingMessage` or `Http2ServerRequest`).
331
- * @param requestContext - Optional context for rendering, such as metadata associated with the request.
332
- * @returns A promise that resolves to the resulting HTTP response object, or `null` if no matching Angular route is found.
333
- *
334
- * @remarks A request to `https://www.example.com/page/index.html` will serve or render the Angular route
335
- * corresponding to `https://www.example.com/page`.
336
- */
337
- async handle(request, requestContext) {
338
- const webRequest = createWebRequestFromNodeRequest(request);
339
- return this.angularAppEngine.handle(webRequest, requestContext);
340
- }
241
+ angularAppEngine = new AngularAppEngine();
242
+ constructor() {
243
+ attachNodeGlobalErrorHandlers();
244
+ }
245
+ async handle(request, requestContext) {
246
+ const webRequest = createWebRequestFromNodeRequest(request);
247
+ return this.angularAppEngine.handle(webRequest, requestContext);
248
+ }
341
249
  }
342
250
 
343
- /**
344
- * Attaches metadata to the handler function to mark it as a special handler for Node.js environments.
345
- *
346
- * @typeParam T - The type of the handler function.
347
- * @param handler - The handler function to be defined and annotated.
348
- * @returns The same handler function passed as an argument, with metadata attached.
349
- *
350
- * @example
351
- * Usage in an Express application:
352
- * ```ts
353
- * const app = express();
354
- * export default createNodeRequestHandler(app);
355
- * ```
356
- *
357
- * @example
358
- * Usage in a Hono application:
359
- * ```ts
360
- * const app = new Hono();
361
- * export default createNodeRequestHandler(async (req, res, next) => {
362
- * try {
363
- * const webRes = await app.fetch(createWebRequestFromNodeRequest(req));
364
- * if (webRes) {
365
- * await writeResponseToNodeResponse(webRes, res);
366
- * } else {
367
- * next();
368
- * }
369
- * } catch (error) {
370
- * next(error);
371
- * }
372
- * });
373
- * ```
374
- *
375
- * @example
376
- * Usage in a Fastify application:
377
- * ```ts
378
- * const app = Fastify();
379
- * export default createNodeRequestHandler(async (req, res) => {
380
- * await app.ready();
381
- * app.server.emit('request', req, res);
382
- * });
383
- * ```
384
- */
385
251
  function createNodeRequestHandler(handler) {
386
- handler['__ng_node_request_handler__'] = true;
387
- return handler;
252
+ handler['__ng_node_request_handler__'] = true;
253
+ return handler;
388
254
  }
389
255
 
390
- /**
391
- * Streams a web-standard `Response` into a Node.js `ServerResponse`
392
- * or `Http2ServerResponse`.
393
- *
394
- * This function adapts the web `Response` object to write its content
395
- * to a Node.js response object, handling both HTTP/1.1 and HTTP/2.
396
- *
397
- * @param source - The web-standard `Response` object to stream from.
398
- * @param destination - The Node.js response object (`ServerResponse` or `Http2ServerResponse`) to stream into.
399
- * @returns A promise that resolves once the streaming operation is complete.
400
- */
401
256
  async function writeResponseToNodeResponse(source, destination) {
402
- const { status, headers, body } = source;
403
- destination.statusCode = status;
404
- let cookieHeaderSet = false;
405
- for (const [name, value] of headers.entries()) {
406
- if (name === 'set-cookie') {
407
- if (cookieHeaderSet) {
408
- continue;
409
- }
410
- // Sets the 'set-cookie' header only once to ensure it is correctly applied.
411
- // Concatenating 'set-cookie' values can lead to incorrect behavior, so we use a single value from `headers.getSetCookie()`.
412
- destination.setHeader(name, headers.getSetCookie());
413
- cookieHeaderSet = true;
414
- }
415
- else {
416
- destination.setHeader(name, value);
417
- }
418
- }
419
- if ('flushHeaders' in destination) {
420
- destination.flushHeaders();
257
+ const {
258
+ status,
259
+ headers,
260
+ body
261
+ } = source;
262
+ destination.statusCode = status;
263
+ let cookieHeaderSet = false;
264
+ for (const [name, value] of headers.entries()) {
265
+ if (name === 'set-cookie') {
266
+ if (cookieHeaderSet) {
267
+ continue;
268
+ }
269
+ destination.setHeader(name, headers.getSetCookie());
270
+ cookieHeaderSet = true;
271
+ } else {
272
+ destination.setHeader(name, value);
421
273
  }
422
- if (!body) {
274
+ }
275
+ if ('flushHeaders' in destination) {
276
+ destination.flushHeaders();
277
+ }
278
+ if (!body) {
279
+ destination.end();
280
+ return;
281
+ }
282
+ try {
283
+ const reader = body.getReader();
284
+ destination.on('close', () => {
285
+ reader.cancel().catch(error => {
286
+ console.error(`An error occurred while writing the response body for: ${destination.req.url}.`, error);
287
+ });
288
+ });
289
+ while (true) {
290
+ const {
291
+ done,
292
+ value
293
+ } = await reader.read();
294
+ if (done) {
423
295
  destination.end();
424
- return;
425
- }
426
- try {
427
- const reader = body.getReader();
428
- destination.on('close', () => {
429
- reader.cancel().catch((error) => {
430
- // eslint-disable-next-line no-console
431
- console.error(`An error occurred while writing the response body for: ${destination.req.url}.`, error);
432
- });
433
- });
434
- // eslint-disable-next-line no-constant-condition
435
- while (true) {
436
- const { done, value } = await reader.read();
437
- if (done) {
438
- destination.end();
439
- break;
440
- }
441
- const canContinue = destination.write(value);
442
- if (canContinue === false) {
443
- // Explicitly check for `false`, as AWS may return `undefined` even though this is not valid.
444
- // See: https://github.com/CodeGenieApp/serverless-express/issues/683
445
- await new Promise((resolve) => destination.once('drain', resolve));
446
- }
447
- }
448
- }
449
- catch {
450
- destination.end('Internal server error.');
296
+ break;
297
+ }
298
+ const canContinue = destination.write(value);
299
+ if (canContinue === false) {
300
+ await new Promise(resolve => destination.once('drain', resolve));
301
+ }
451
302
  }
303
+ } catch {
304
+ destination.end('Internal server error.');
305
+ }
452
306
  }
453
307
 
454
- /**
455
- * Determines whether the provided URL represents the main entry point module.
456
- *
457
- * This function checks if the provided URL corresponds to the main ESM module being executed directly.
458
- * It's useful for conditionally executing code that should only run when a module is the entry point,
459
- * such as starting a server or initializing an application.
460
- *
461
- * It performs two key checks:
462
- * 1. Verifies if the URL starts with 'file:', ensuring it is a local file.
463
- * 2. Compares the URL's resolved file path with the first command-line argument (`process.argv[1]`),
464
- * which points to the file being executed.
465
- *
466
- * @param url The URL of the module to check. This should typically be `import.meta.url`.
467
- * @returns `true` if the provided URL represents the main entry point, otherwise `false`.
468
- */
469
308
  function isMainModule(url) {
470
- return url.startsWith('file:') && argv[1] === fileURLToPath(url);
309
+ return url.startsWith('file:') && argv[1] === fileURLToPath(url);
471
310
  }
472
311
 
473
312
  export { AngularNodeAppEngine, CommonEngine, createNodeRequestHandler, createWebRequestFromNodeRequest, isMainModule, writeResponseToNodeResponse };