Skip to content

Commit 12b2dc5

Browse files
committed
fix(@angular-devkit/build-angular): isolate zone.js usage when rendering server bundles
When generating an app-shell via the app-shell builder, the server application rendering will now take place within a Node.js Worker. Since the rendering requires the presence of Zone.js, this change allows for the Zone.js patching to be isolated from the remainder of the builder and Angular CLI code. This prevents Zone.js from persisting past the needed render operation. This also allows for a workaround to a Zone.js/Node.js v18 problem where the TypeScript dynamic import workaround involving the Function constructor to ensure a native dynamic import expression will cause a failure when running on Node.js v18.10. (cherry picked from commit 484cda5)
1 parent 4f730aa commit 12b2dc5

File tree

3 files changed

+133
-53
lines changed

3 files changed

+133
-53
lines changed

Diff for: packages/angular_devkit/build_angular/BUILD.bazel

+1
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ ts_library(
106106
"@npm//@angular/compiler-cli",
107107
"@npm//@angular/core",
108108
"@npm//@angular/localize",
109+
"@npm//@angular/platform-server",
109110
"@npm//@angular/service-worker",
110111
"@npm//@babel/core",
111112
"@npm//@babel/generator",

Diff for: packages/angular_devkit/build_angular/src/builders/app-shell/index.ts

+51-53
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
import { JsonObject } from '@angular-devkit/core';
1616
import * as fs from 'fs';
1717
import * as path from 'path';
18+
import Piscina from 'piscina';
1819
import { normalizeOptimization } from '../../utils';
1920
import { assertIsError } from '../../utils/error';
2021
import { InlineCriticalCssProcessor } from '../../utils/index-file/inline-critical-css';
@@ -42,10 +43,9 @@ async function _renderUniversal(
4243
browserBuilderName,
4344
);
4445

45-
// Initialize zone.js
46+
// Locate zone.js to load in the render worker
4647
const root = context.workspaceRoot;
4748
const zonePackage = require.resolve('zone.js', { paths: [root] });
48-
await import(zonePackage);
4949

5050
const projectName = context.target && context.target.project;
5151
if (!projectName) {
@@ -63,65 +63,63 @@ async function _renderUniversal(
6363
})
6464
: undefined;
6565

66-
for (const { path: outputPath, baseHref } of browserResult.outputs) {
67-
const localeDirectory = path.relative(browserResult.baseOutputPath, outputPath);
68-
const browserIndexOutputPath = path.join(outputPath, 'index.html');
69-
const indexHtml = await fs.promises.readFile(browserIndexOutputPath, 'utf8');
70-
const serverBundlePath = await _getServerModuleBundlePath(
71-
options,
72-
context,
73-
serverResult,
74-
localeDirectory,
75-
);
76-
77-
const { AppServerModule, renderModule } = await import(serverBundlePath);
78-
79-
const renderModuleFn: ((module: unknown, options: {}) => Promise<string>) | undefined =
80-
renderModule;
81-
82-
if (!(renderModuleFn && AppServerModule)) {
83-
throw new Error(
84-
`renderModule method and/or AppServerModule were not exported from: ${serverBundlePath}.`,
66+
const renderWorker = new Piscina({
67+
filename: require.resolve('./render-worker'),
68+
maxThreads: 1,
69+
workerData: { zonePackage },
70+
});
71+
72+
try {
73+
for (const { path: outputPath, baseHref } of browserResult.outputs) {
74+
const localeDirectory = path.relative(browserResult.baseOutputPath, outputPath);
75+
const browserIndexOutputPath = path.join(outputPath, 'index.html');
76+
const indexHtml = await fs.promises.readFile(browserIndexOutputPath, 'utf8');
77+
const serverBundlePath = await _getServerModuleBundlePath(
78+
options,
79+
context,
80+
serverResult,
81+
localeDirectory,
8582
);
86-
}
8783

88-
// Load platform server module renderer
89-
const renderOpts = {
90-
document: indexHtml,
91-
url: options.route,
92-
};
93-
94-
let html = await renderModuleFn(AppServerModule, renderOpts);
95-
// Overwrite the client index file.
96-
const outputIndexPath = options.outputIndexPath
97-
? path.join(root, options.outputIndexPath)
98-
: browserIndexOutputPath;
99-
100-
if (inlineCriticalCssProcessor) {
101-
const { content, warnings, errors } = await inlineCriticalCssProcessor.process(html, {
102-
outputPath,
84+
let html: string = await renderWorker.run({
85+
serverBundlePath,
86+
document: indexHtml,
87+
url: options.route,
10388
});
104-
html = content;
10589

106-
if (warnings.length || errors.length) {
107-
spinner.stop();
108-
warnings.forEach((m) => context.logger.warn(m));
109-
errors.forEach((m) => context.logger.error(m));
110-
spinner.start();
90+
// Overwrite the client index file.
91+
const outputIndexPath = options.outputIndexPath
92+
? path.join(root, options.outputIndexPath)
93+
: browserIndexOutputPath;
94+
95+
if (inlineCriticalCssProcessor) {
96+
const { content, warnings, errors } = await inlineCriticalCssProcessor.process(html, {
97+
outputPath,
98+
});
99+
html = content;
100+
101+
if (warnings.length || errors.length) {
102+
spinner.stop();
103+
warnings.forEach((m) => context.logger.warn(m));
104+
errors.forEach((m) => context.logger.error(m));
105+
spinner.start();
106+
}
111107
}
112-
}
113108

114-
await fs.promises.writeFile(outputIndexPath, html);
109+
await fs.promises.writeFile(outputIndexPath, html);
115110

116-
if (browserOptions.serviceWorker) {
117-
await augmentAppWithServiceWorker(
118-
projectRoot,
119-
root,
120-
outputPath,
121-
baseHref ?? '/',
122-
browserOptions.ngswConfigPath,
123-
);
111+
if (browserOptions.serviceWorker) {
112+
await augmentAppWithServiceWorker(
113+
projectRoot,
114+
root,
115+
outputPath,
116+
baseHref ?? '/',
117+
browserOptions.ngswConfigPath,
118+
);
119+
}
124120
}
121+
} finally {
122+
await renderWorker.destroy();
125123
}
126124

127125
return browserResult;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import type { Type } from '@angular/core';
10+
import type * as platformServer from '@angular/platform-server';
11+
import assert from 'assert';
12+
import { workerData } from 'worker_threads';
13+
14+
/**
15+
* The fully resolved path to the zone.js package that will be loaded during worker initialization.
16+
* This is passed as workerData when setting up the worker via the `piscina` package.
17+
*/
18+
const { zonePackage } = workerData as {
19+
zonePackage: string;
20+
};
21+
22+
/**
23+
* A request to render a Server bundle generate by the universal server builder.
24+
*/
25+
interface RenderRequest {
26+
/**
27+
* The path to the server bundle that should be loaded and rendered.
28+
*/
29+
serverBundlePath: string;
30+
/**
31+
* The existing HTML document as a string that will be augmented with the rendered application.
32+
*/
33+
document: string;
34+
/**
35+
* An optional URL path that represents the Angular route that should be rendered.
36+
*/
37+
url: string | undefined;
38+
}
39+
40+
/**
41+
* Renders an application based on a provided server bundle path, initial document, and optional URL route.
42+
* @param param0 A request to render a server bundle.
43+
* @returns A promise that resolves to the render HTML document for the application.
44+
*/
45+
async function render({ serverBundlePath, document, url }: RenderRequest): Promise<string> {
46+
const { AppServerModule, renderModule } = (await import(serverBundlePath)) as {
47+
renderModule: typeof platformServer.renderModule | undefined;
48+
AppServerModule: Type<unknown> | undefined;
49+
};
50+
51+
assert(renderModule, `renderModule was not exported from: ${serverBundlePath}.`);
52+
assert(AppServerModule, `AppServerModule was not exported from: ${serverBundlePath}.`);
53+
54+
// Render platform server module
55+
const html = await renderModule(AppServerModule, {
56+
document,
57+
url,
58+
});
59+
60+
return html;
61+
}
62+
63+
/**
64+
* Initializes the worker when it is first created by loading the Zone.js package
65+
* into the worker instance.
66+
*
67+
* @returns A promise resolving to the render function of the worker.
68+
*/
69+
async function initialize() {
70+
// Setup Zone.js
71+
await import(zonePackage);
72+
73+
// Return the render function for use
74+
return render;
75+
}
76+
77+
/**
78+
* The default export will be the promise returned by the initialize function.
79+
* This is awaited by piscina prior to using the Worker.
80+
*/
81+
export default initialize();

0 commit comments

Comments
 (0)