forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssr-middleware.ts
More file actions
153 lines (127 loc) · 5.23 KB
/
ssr-middleware.ts
File metadata and controls
153 lines (127 loc) · 5.23 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
/**
* @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 type {
AngularAppEngine as SSRAngularAppEngine,
ɵgetOrCreateAngularServerApp as getOrCreateAngularServerApp,
} from '@angular/ssr';
import type { ServerResponse } from 'node:http';
import type { Connect, ViteDevServer } from 'vite';
import {
isSsrNodeRequestHandler,
isSsrRequestHandler,
} from '../../../utils/server-rendering/utils';
export function createAngularSsrInternalMiddleware(
server: ViteDevServer,
indexHtmlTransformer?: (content: string) => Promise<string>,
): Connect.NextHandleFunction {
let cachedAngularServerApp: ReturnType<typeof getOrCreateAngularServerApp> | undefined;
return function angularSsrMiddleware(
req: Connect.IncomingMessage,
res: ServerResponse,
next: Connect.NextFunction,
) {
if (req.url === undefined) {
return next();
}
(async () => {
// Load the compiler because `@angular/ssr/node` depends on `@angular/` packages,
// which must be processed by the runtime linker, even if they are not used.
await import('@angular/compiler');
const { writeResponseToNodeResponse, createWebRequestFromNodeRequest } = (await import(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
'@angular/ssr/node' as any
)) as typeof import('@angular/ssr/node', { with: { 'resolution-mode': 'import' } });
const { ɵgetOrCreateAngularServerApp } = (await server.ssrLoadModule('/main.server.mjs')) as {
ɵgetOrCreateAngularServerApp: typeof getOrCreateAngularServerApp;
};
const angularServerApp = ɵgetOrCreateAngularServerApp({
allowStaticRouteRender: true,
});
// Only Add the transform hook only if it's a different instance.
if (cachedAngularServerApp !== angularServerApp) {
angularServerApp.hooks.on('html:transform:pre', async ({ html, url }) => {
const processedHtml = await server.transformIndexHtml(url.pathname, html);
return indexHtmlTransformer?.(processedHtml) ?? processedHtml;
});
cachedAngularServerApp = angularServerApp;
}
const webReq = new Request(createWebRequestFromNodeRequest(req), {
signal: AbortSignal.timeout(30_000),
});
const webRes = await angularServerApp.handle(webReq);
if (!webRes) {
return next();
}
return writeResponseToNodeResponse(webRes, res);
})().catch(next);
};
}
export async function createAngularSsrExternalMiddleware(
server: ViteDevServer,
indexHtmlTransformer?: (content: string) => Promise<string>,
): Promise<Connect.NextHandleFunction> {
let fallbackWarningShown = false;
let cachedAngularAppEngine: typeof SSRAngularAppEngine | undefined;
let angularSsrInternalMiddleware:
| ReturnType<typeof createAngularSsrInternalMiddleware>
| undefined;
// Load the compiler because `@angular/ssr/node` depends on `@angular/` packages,
// which must be processed by the runtime linker, even if they are not used.
await import('@angular/compiler');
const { createWebRequestFromNodeRequest, writeResponseToNodeResponse } = (await import(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
'@angular/ssr/node' as any
)) as typeof import('@angular/ssr/node', { with: { 'resolution-mode': 'import' } });
return function angularSsrExternalMiddleware(
req: Connect.IncomingMessage,
res: ServerResponse,
next: Connect.NextFunction,
) {
(async () => {
const { reqHandler, AngularAppEngine } = (await server.ssrLoadModule('./server.mjs')) as {
reqHandler?: unknown;
AngularAppEngine: typeof SSRAngularAppEngine;
};
if (!isSsrNodeRequestHandler(reqHandler) && !isSsrRequestHandler(reqHandler)) {
if (!fallbackWarningShown) {
// eslint-disable-next-line no-console
console.warn(
`The 'reqHandler' export in 'server.ts' is either undefined or does not provide a recognized request handler. ` +
'Using the internal SSR middleware instead.',
);
fallbackWarningShown = true;
}
angularSsrInternalMiddleware ??= createAngularSsrInternalMiddleware(
server,
indexHtmlTransformer,
);
angularSsrInternalMiddleware(req, res, next);
return;
}
if (cachedAngularAppEngine !== AngularAppEngine) {
AngularAppEngine.ɵallowStaticRouteRender = true;
AngularAppEngine.ɵhooks.on('html:transform:pre', async ({ html, url }) => {
const processedHtml = await server.transformIndexHtml(url.pathname, html);
return indexHtmlTransformer?.(processedHtml) ?? processedHtml;
});
cachedAngularAppEngine = AngularAppEngine;
}
// Forward the request to the middleware in server.ts
if (isSsrNodeRequestHandler(reqHandler)) {
await reqHandler(req, res, next);
} else {
const webRes = await reqHandler(createWebRequestFromNodeRequest(req));
if (!webRes) {
next();
return;
}
await writeResponseToNodeResponse(webRes, res);
}
})().catch(next);
};
}