Repository navigation
Expand file tree
/
Copy pathng.ts
More file actions
319 lines (286 loc) · 11.2 KB
/
Copy pathng.ts
File metadata and controls
319 lines (286 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { APP_BASE_HREF, PlatformLocation } from '@angular/common';
import {
ApplicationRef,
type PlatformRef,
REQUEST,
type StaticProvider,
type Type,
ɵConsole,
} from '@angular/core';
import { BootstrapContext } from '@angular/platform-browser';
import {
INITIAL_CONFIG,
ɵSERVER_CONTEXT as SERVER_CONTEXT,
platformServer,
ɵrenderInternal as renderInternal,
} from '@angular/platform-server';
import { ActivatedRoute, Router } from '@angular/router';
import { Console } from '../console';
import { addTrailingSlash, joinUrlParts, stripIndexHtmlFromURL, stripTrailingSlash } from './url';
import { getFirstHeaderValue } from './validation';
/**
* Represents the bootstrap mechanism for an Angular application.
*
* This type can either be:
* - A reference to an Angular component or module (`Type<unknown>`) that serves as the root of the application.
* - A function that returns a `Promise<ApplicationRef>`, which resolves with the root application reference.
*/
export type AngularBootstrap =
Type<unknown> | ((context: BootstrapContext) => Promise<ApplicationRef>);
/**
* Renders an Angular application or module to an HTML string.
*
* This function supports both Angular modules and bootstrap functions for application initialization.
*
* @param html - The initial HTML document content.
* @param bootstrap - An Angular module type or a function returning a promise that resolves to an `ApplicationRef`.
* @param url - The application URL, used for route-based rendering in SSR.
* @param platformProviders - An array of platform providers for the rendering process.
* @param serverContext - A string representing the server context, providing additional metadata for SSR.
* @param signal - An optional `AbortSignal` to abort the rendering process and destroy the platform.
* @returns A promise resolving to an object containing:
* - `hasNavigationError`: Indicates if a navigation error occurred or if rendering was aborted/destroyed before stability.
* - `redirectTo`: (Optional) The redirect URL if a navigation redirect occurred.
* - `content`: (Optional) A function returning a promise that resolves to the rendered HTML string.
* - `destroy`: (Optional) A function to destroy the underlying Angular platform.
*/
export async function renderAngular(
html: string,
bootstrap: AngularBootstrap,
url: URL,
platformProviders: StaticProvider[],
serverContext: string,
signal?: AbortSignal,
): Promise<
| { hasNavigationError: true }
| {
hasNavigationError: boolean;
redirectTo?: string;
content: () => Promise<string>;
destroy: () => Promise<void>;
}
> {
if (signal?.aborted) {
return { hasNavigationError: true };
}
// A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.
const urlToRender = stripIndexHtmlFromURL(url);
const platformRef = platformServer([
{
provide: INITIAL_CONFIG,
useValue: {
url: urlToRender.href,
document: html,
},
},
{
provide: SERVER_CONTEXT,
useValue: serverContext,
},
{
// An Angular Console Provider that does not print a set of predefined logs.
provide: ɵConsole,
// Using `useClass` would necessitate decorating `Console` with `@Injectable`,
// which would require switching from `ts_library` to `ng_module`. This change
// would also necessitate various patches of `@angular/bazel` to support ESM.
useFactory: () => new Console(),
},
...platformProviders,
]);
let redirectTo: string | undefined;
let hasNavigationError = true;
let renderTimeoutId: ReturnType<typeof setTimeout> | undefined;
let destroyPromise: Promise<void> | undefined;
let contentPromise: Promise<string> | undefined;
let rejectContent: ((reason?: unknown) => void) | undefined;
const createAbortError = (): DOMException =>
new DOMException(
`Request for: ${url} was aborted.${signal?.reason ? `\n${signal.reason}` : ''}`,
'AbortError',
);
const destroy = (): Promise<void> => {
if (!destroyPromise) {
clearTimeout(renderTimeoutId);
rejectContent?.(createAbortError());
rejectContent = undefined;
contentPromise = undefined;
signal?.removeEventListener('abort', abortHandler);
destroyPromise = asyncDestroyPlatform(platformRef);
}
return destroyPromise;
};
const abortHandler = () => void destroy();
const isDestroyedOrAborted = (applicationRef?: ApplicationRef): boolean =>
!!(
destroyPromise ||
platformRef.destroyed ||
applicationRef?.destroyed ||
applicationRef?.injector.destroyed ||
signal?.aborted
);
try {
signal?.addEventListener('abort', abortHandler, { once: true });
let applicationRef: ApplicationRef;
if (isNgModule(bootstrap)) {
const moduleRef = await platformRef.bootstrapModule(bootstrap);
if (isDestroyedOrAborted() || moduleRef.injector.destroyed) {
return { hasNavigationError: true };
}
applicationRef = moduleRef.injector.get(ApplicationRef);
} else {
applicationRef = await bootstrap({ platformRef });
if (isDestroyedOrAborted(applicationRef)) {
return { hasNavigationError: true };
}
}
// Block until application is stable.
await applicationRef.whenStable();
// This code protects against app destruction during bootstrapping which is a
// valid case. We should not assume the `applicationRef` or its injector is not in a destroyed state.
// Calling `envInjector.get` would throw `NG0205: Injector has already been destroyed`.
if (isDestroyedOrAborted(applicationRef)) {
return { hasNavigationError: true };
}
// TODO(alanagius): Find a way to avoid rendering here especially for redirects as any output will be discarded.
const envInjector = applicationRef.injector;
const routerIsProvided = !!envInjector.get(ActivatedRoute, null);
const router = envInjector.get(Router);
const lastSuccessfulNavigation = router.lastSuccessfulNavigation();
if (!routerIsProvided) {
hasNavigationError = false;
} else if (lastSuccessfulNavigation?.finalUrl) {
const requestPrefix =
envInjector.get(APP_BASE_HREF, null, { optional: true }) ??
getFirstHeaderValue(
envInjector.get(REQUEST, null, { optional: true })?.headers.get('X-Forwarded-Prefix'),
);
const { pathname, search, hash } = envInjector.get(PlatformLocation);
const finalUrl = constructSerializedUrl(router, { pathname, search, hash }, requestPrefix);
const urlToRenderString = constructSerializedUrl(router, urlToRender, requestPrefix);
if (urlToRenderString !== finalUrl) {
redirectTo = [pathname, search, hash].join('');
}
hasNavigationError = false;
}
return {
destroy,
hasNavigationError,
redirectTo,
content: () => {
if (isDestroyedOrAborted(applicationRef)) {
void destroy();
return Promise.reject(createAbortError());
}
return (contentPromise ??= new Promise<string>((resolve, reject) => {
rejectContent = reject;
// Defer rendering to the next event loop iteration to avoid blocking, as most operations in `renderInternal` are synchronous.
renderTimeoutId = setTimeout(() => {
if (isDestroyedOrAborted(applicationRef)) {
rejectContent = undefined;
void destroy();
reject(createAbortError());
return;
}
renderInternal(platformRef, applicationRef).then(
(renderedHtml) => {
rejectContent = undefined;
void destroy();
resolve(renderedHtml);
},
(error) => {
rejectContent = undefined;
void destroy();
reject(error);
},
);
}, 0);
}));
},
};
} finally {
if (hasNavigationError || redirectTo) {
void destroy();
}
}
}
/**
* Type guard to determine if a given value is an Angular module.
* Angular modules are identified by the presence of the `ɵmod` static property.
* This function helps distinguish between Angular modules and bootstrap functions.
*
* @param value - The value to be checked.
* @returns True if the value is an Angular module (i.e., it has the `ɵmod` property), false otherwise.
*/
export function isNgModule(value: AngularBootstrap): value is Type<unknown> {
return 'ɵmod' in value;
}
/**
* Gracefully destroys the application in a macrotask, allowing pending promises to resolve
* and surfacing any potential errors to the user.
*
* @param platformRef - The platform reference to be destroyed.
*/
function asyncDestroyPlatform(platformRef: PlatformRef): Promise<void> {
if (platformRef.destroyed) {
return Promise.resolve();
}
return new Promise((resolve) => {
setTimeout(() => {
try {
if (!platformRef.destroyed) {
platformRef.destroy();
}
} catch (error) {
// An error thrown by a destroy hook must not escape this macrotask,
// otherwise it becomes an uncaught exception that can terminate the process.
// eslint-disable-next-line no-console
console.error('An error occurred while destroying the platform.', error);
} finally {
resolve();
}
}, 0);
});
}
/**
* Constructs a normalized and serialized URL string from its components.
*
* This function uses the provided `Router` instance to parse and serialize the URL,
* ensuring that the resulting string is consistent with the router's configuration.
* It also handles the optional `prefix` parameter to ensure proper URL construction.
*
* @param router - The `Router` instance to use for parsing and serializing the URL.
* @param url - An object containing the URL components:
* - `pathname`: The path of the URL.
* - `search`: The query string of the URL (including '?').
* - `hash`: The hash fragment of the URL (including '#').
* @param prefix - An optional prefix (e.g., `APP_BASE_HREF`) to prepend to the pathname
* if it is not already present.
* @returns The normalized and serialized URL string.
*
* @note
* We use the Angular `Router` to construct the URL, so that the URL is consistent with the router's configuration.
* This is important for the URL to be correctly parsed and serialized by the router as it might have different encodings.
*/
function constructSerializedUrl(
router: Router,
url: { pathname: string; search: string; hash: string },
prefix?: string | null,
): string {
const { pathname, hash, search } = url;
const urlParts: string[] = [];
if (prefix && !addTrailingSlash(pathname).startsWith(addTrailingSlash(prefix))) {
urlParts.push(joinUrlParts(prefix, pathname));
} else {
urlParts.push(stripTrailingSlash(pathname));
}
urlParts.push(search, hash);
const urlTree = router.parseUrl(urlParts.join(''));
return router.serializeUrl(urlTree);
}