-
Notifications
You must be signed in to change notification settings - Fork 12k
/
index-html-generator.ts
203 lines (171 loc) · 6.08 KB
/
index-html-generator.ts
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
/**
* @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.io/license
*/
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { NormalizedCachedOptions } from '../normalize-cache';
import { NormalizedOptimizationOptions } from '../normalize-optimization';
import { addEventDispatchContract } from './add-event-dispatch-contract';
import { CrossOriginValue, Entrypoint, FileInfo, augmentIndexHtml } from './augment-index-html';
import { InlineCriticalCssProcessor } from './inline-critical-css';
import { InlineFontsProcessor } from './inline-fonts';
import { addNonce } from './nonce';
type IndexHtmlGeneratorPlugin = (
html: string,
options: IndexHtmlGeneratorProcessOptions,
) => Promise<string | IndexHtmlPluginTransformResult> | string;
export type HintMode = 'prefetch' | 'preload' | 'modulepreload' | 'preconnect' | 'dns-prefetch';
export interface IndexHtmlGeneratorProcessOptions {
lang: string | undefined;
baseHref: string | undefined;
outputPath: string;
files: FileInfo[];
hints?: { url: string; mode: HintMode; as?: string }[];
}
export interface IndexHtmlGeneratorOptions {
indexPath: string;
deployUrl?: string;
sri?: boolean;
entrypoints: Entrypoint[];
postTransform?: IndexHtmlTransform;
crossOrigin?: CrossOriginValue;
optimization?: NormalizedOptimizationOptions;
cache?: NormalizedCachedOptions;
imageDomains?: string[];
generateDedicatedSSRContent?: boolean;
}
export type IndexHtmlTransform = (content: string) => Promise<string>;
export interface IndexHtmlPluginTransformResult {
content: string;
warnings: string[];
errors: string[];
}
export interface IndexHtmlProcessResult {
csrContent: string;
ssrContent?: string;
warnings: string[];
errors: string[];
}
export class IndexHtmlGenerator {
private readonly plugins: IndexHtmlGeneratorPlugin[];
private readonly csrPlugins: IndexHtmlGeneratorPlugin[] = [];
private readonly ssrPlugins: IndexHtmlGeneratorPlugin[] = [];
constructor(readonly options: IndexHtmlGeneratorOptions) {
const extraCommonPlugins: IndexHtmlGeneratorPlugin[] = [];
if (options?.optimization?.fonts.inline) {
extraCommonPlugins.push(inlineFontsPlugin(this), addNonce);
}
// Common plugins
this.plugins = [augmentIndexHtmlPlugin(this), ...extraCommonPlugins, postTransformPlugin(this)];
// CSR plugins
if (options?.optimization?.styles?.inlineCritical) {
this.csrPlugins.push(inlineCriticalCssPlugin(this));
}
// SSR plugins
if (options.generateDedicatedSSRContent) {
this.ssrPlugins.push(addEventDispatchContractPlugin(), addNoncePlugin());
}
}
async process(options: IndexHtmlGeneratorProcessOptions): Promise<IndexHtmlProcessResult> {
let content = await this.readIndex(this.options.indexPath);
const warnings: string[] = [];
const errors: string[] = [];
content = await this.runPlugins(content, this.plugins, options, warnings, errors);
const [csrContent, ssrContent] = await Promise.all([
this.runPlugins(content, this.csrPlugins, options, warnings, errors),
this.ssrPlugins.length
? this.runPlugins(content, this.ssrPlugins, options, warnings, errors)
: undefined,
]);
return {
ssrContent,
csrContent,
warnings,
errors,
};
}
private async runPlugins(
content: string,
plugins: IndexHtmlGeneratorPlugin[],
options: IndexHtmlGeneratorProcessOptions,
warnings: string[],
errors: string[],
): Promise<string> {
for (const plugin of plugins) {
const result = await plugin(content, options);
if (typeof result === 'string') {
content = result;
} else {
content = result.content;
if (result.warnings.length) {
warnings.push(...result.warnings);
}
if (result.errors.length) {
errors.push(...result.errors);
}
}
}
return content;
}
async readAsset(path: string): Promise<string> {
try {
return await readFile(path, 'utf-8');
} catch {
throw new Error(`Failed to read asset "${path}".`);
}
}
protected async readIndex(path: string): Promise<string> {
try {
return new TextDecoder('utf-8').decode(await readFile(path));
} catch (cause) {
throw new Error(`Failed to read index HTML file "${path}".`, { cause });
}
}
}
function augmentIndexHtmlPlugin(generator: IndexHtmlGenerator): IndexHtmlGeneratorPlugin {
const { deployUrl, crossOrigin, sri = false, entrypoints, imageDomains } = generator.options;
return async (html, options) => {
const { lang, baseHref, outputPath = '', files, hints } = options;
return augmentIndexHtml({
html,
baseHref,
deployUrl,
crossOrigin,
sri,
lang,
entrypoints,
loadOutputFile: (filePath) => generator.readAsset(join(outputPath, filePath)),
imageDomains,
files,
hints,
});
};
}
function inlineFontsPlugin({ options }: IndexHtmlGenerator): IndexHtmlGeneratorPlugin {
const inlineFontsProcessor = new InlineFontsProcessor({
minify: options.optimization?.styles.minify,
});
return async (html) => inlineFontsProcessor.process(html);
}
function inlineCriticalCssPlugin(generator: IndexHtmlGenerator): IndexHtmlGeneratorPlugin {
const inlineCriticalCssProcessor = new InlineCriticalCssProcessor({
minify: generator.options.optimization?.styles.minify,
deployUrl: generator.options.deployUrl,
readAsset: (filePath) => generator.readAsset(filePath),
});
return async (html, options) =>
inlineCriticalCssProcessor.process(html, { outputPath: options.outputPath });
}
function addNoncePlugin(): IndexHtmlGeneratorPlugin {
return (html) => addNonce(html);
}
function postTransformPlugin({ options }: IndexHtmlGenerator): IndexHtmlGeneratorPlugin {
return async (html) => (options.postTransform ? options.postTransform(html) : html);
}
function addEventDispatchContractPlugin(): IndexHtmlGeneratorPlugin {
return (html) => addEventDispatchContract(html);
}