-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathaugment-index-html.ts
343 lines (295 loc) · 9.42 KB
/
augment-index-html.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
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/**
* @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 { createHash } from 'node:crypto';
import { extname } from 'node:path';
import { loadEsmModule } from '../load-esm';
import { htmlRewritingStream } from './html-rewriting-stream';
export type LoadOutputFileFunctionType = (file: string) => Promise<string>;
export type CrossOriginValue = 'none' | 'anonymous' | 'use-credentials';
export type Entrypoint = [name: string, isModule: boolean];
export interface AugmentIndexHtmlOptions {
/* Input contents */
html: string;
baseHref?: string;
deployUrl?: string;
sri: boolean;
/** crossorigin attribute setting of elements that provide CORS support */
crossOrigin?: CrossOriginValue;
/*
* Files emitted by the build.
*/
files: FileInfo[];
/*
* Function that loads a file used.
* This allows us to use different routines within the IndexHtmlWebpackPlugin and
* when used without this plugin.
*/
loadOutputFile: LoadOutputFileFunctionType;
/** Used to sort the inseration of files in the HTML file */
entrypoints: Entrypoint[];
/** Used to set the document default locale */
lang?: string;
hints?: { url: string; mode: string; as?: string }[];
imageDomains?: string[];
}
export interface FileInfo {
file: string;
name?: string;
extension: string;
}
/*
* Helper function used by the IndexHtmlWebpackPlugin.
* Can also be directly used by builder, e. g. in order to generate an index.html
* after processing several configurations in order to build different sets of
* bundles for differential serving.
*/
// eslint-disable-next-line max-lines-per-function
export async function augmentIndexHtml(
params: AugmentIndexHtmlOptions,
): Promise<{ content: string; warnings: string[]; errors: string[] }> {
const {
loadOutputFile,
files,
entrypoints,
sri,
deployUrl = '',
lang,
baseHref,
html,
imageDomains,
} = params;
const warnings: string[] = [];
const errors: string[] = [];
let { crossOrigin = 'none' } = params;
if (sri && crossOrigin === 'none') {
crossOrigin = 'anonymous';
}
const stylesheets = new Set<string>();
const scripts = new Map</** file name */ string, /** isModule */ boolean>();
// Sort files in the order we want to insert them by entrypoint
for (const [entrypoint, isModule] of entrypoints) {
for (const { extension, file, name } of files) {
if (name !== entrypoint || scripts.has(file) || stylesheets.has(file)) {
continue;
}
switch (extension) {
case '.js':
// Also, non entrypoints need to be loaded as no module as they can contain problematic code.
scripts.set(file, isModule);
break;
case '.mjs':
if (!isModule) {
// It would be very confusing to link an `*.mjs` file in a non-module script context,
// so we disallow it entirely.
throw new Error('`.mjs` files *must* set `isModule` to `true`.');
}
scripts.set(file, true /* isModule */);
break;
case '.css':
stylesheets.add(file);
break;
}
}
}
let scriptTags: string[] = [];
for (const [src, isModule] of scripts) {
const attrs = [`src="${deployUrl}${src}"`];
// This is also need for non entry-points as they may contain problematic code.
if (isModule) {
attrs.push('type="module"');
} else {
attrs.push('defer');
}
if (crossOrigin !== 'none') {
attrs.push(`crossorigin="${crossOrigin}"`);
}
if (sri) {
const content = await loadOutputFile(src);
attrs.push(generateSriAttributes(content));
}
scriptTags.push(`<script ${attrs.join(' ')}></script>`);
}
let linkTags: string[] = [];
for (const src of stylesheets) {
const attrs = [`rel="stylesheet"`, `href="${deployUrl}${src}"`];
if (crossOrigin !== 'none') {
attrs.push(`crossorigin="${crossOrigin}"`);
}
if (sri) {
const content = await loadOutputFile(src);
attrs.push(generateSriAttributes(content));
}
linkTags.push(`<link ${attrs.join(' ')}>`);
}
if (params.hints?.length) {
for (const hint of params.hints) {
const attrs = [`rel="${hint.mode}"`, `href="${deployUrl}${hint.url}"`];
if (hint.mode !== 'modulepreload' && crossOrigin !== 'none') {
// Value is considered anonymous by the browser when not present or empty
attrs.push(crossOrigin === 'anonymous' ? 'crossorigin' : `crossorigin="${crossOrigin}"`);
}
if (hint.mode === 'preload' || hint.mode === 'prefetch') {
switch (extname(hint.url)) {
case '.js':
attrs.push('as="script"');
break;
case '.css':
attrs.push('as="style"');
break;
default:
if (hint.as) {
attrs.push(`as="${hint.as}"`);
}
break;
}
}
if (
sri &&
(hint.mode === 'preload' || hint.mode === 'prefetch' || hint.mode === 'modulepreload')
) {
const content = await loadOutputFile(hint.url);
attrs.push(generateSriAttributes(content));
}
linkTags.push(`<link ${attrs.join(' ')}>`);
}
}
const dir = lang ? await getLanguageDirection(lang, warnings) : undefined;
const { rewriter, transformedContent } = await htmlRewritingStream(html);
const baseTagExists = html.includes('<base');
const foundPreconnects = new Set<string>();
rewriter
.on('startTag', (tag) => {
switch (tag.tagName) {
case 'html':
// Adjust document locale if specified
if (isString(lang)) {
updateAttribute(tag, 'lang', lang);
}
if (dir) {
updateAttribute(tag, 'dir', dir);
}
break;
case 'head':
// Base href should be added before any link, meta tags
if (!baseTagExists && isString(baseHref)) {
rewriter.emitStartTag(tag);
rewriter.emitRaw(`<base href="${baseHref}">`);
return;
}
break;
case 'base':
// Adjust base href if specified
if (isString(baseHref)) {
updateAttribute(tag, 'href', baseHref);
}
break;
case 'link':
if (readAttribute(tag, 'rel') === 'preconnect') {
const href = readAttribute(tag, 'href');
if (href) {
foundPreconnects.add(href);
}
}
}
rewriter.emitStartTag(tag);
})
.on('endTag', (tag) => {
switch (tag.tagName) {
case 'head':
for (const linkTag of linkTags) {
rewriter.emitRaw(linkTag);
}
if (imageDomains) {
for (const imageDomain of imageDomains) {
if (!foundPreconnects.has(imageDomain)) {
rewriter.emitRaw(`<link rel="preconnect" href="${imageDomain}" data-ngimg>`);
}
}
}
linkTags = [];
break;
case 'body':
// Add script tags
for (const scriptTag of scriptTags) {
rewriter.emitRaw(scriptTag);
}
scriptTags = [];
break;
}
rewriter.emitEndTag(tag);
});
const content = await transformedContent();
return {
content:
linkTags.length || scriptTags.length
? // In case no body/head tags are not present (dotnet partial templates)
linkTags.join('') + scriptTags.join('') + content
: content,
warnings,
errors,
};
}
function generateSriAttributes(content: string): string {
const algo = 'sha384';
const hash = createHash(algo).update(content, 'utf8').digest('base64');
return `integrity="${algo}-${hash}"`;
}
function updateAttribute(
tag: { attrs: { name: string; value: string }[] },
name: string,
value: string,
): void {
const index = tag.attrs.findIndex((a) => a.name === name);
const newValue = { name, value };
if (index === -1) {
tag.attrs.push(newValue);
} else {
tag.attrs[index] = newValue;
}
}
function readAttribute(
tag: { attrs: { name: string; value: string }[] },
name: string,
): string | undefined {
const targetAttr = tag.attrs.find((attr) => attr.name === name);
return targetAttr ? targetAttr.value : undefined;
}
function isString(value: unknown): value is string {
return typeof value === 'string';
}
async function getLanguageDirection(
locale: string,
warnings: string[],
): Promise<string | undefined> {
const dir = await getLanguageDirectionFromLocales(locale);
if (!dir) {
warnings.push(
`Locale data for '${locale}' cannot be found. 'dir' attribute will not be set for this locale.`,
);
}
return dir;
}
async function getLanguageDirectionFromLocales(locale: string): Promise<string | undefined> {
try {
const localeData = (
await loadEsmModule<typeof import('@angular/common/locales/en')>(
`@angular/common/locales/${locale}`,
)
).default;
const dir = localeData[localeData.length - 2];
return isString(dir) ? dir : undefined;
} catch {
// In some cases certain locales might map to files which are named only with language id.
// Example: `en-US` -> `en`.
const [languageId] = locale.split('-', 1);
if (languageId !== locale) {
return getLanguageDirectionFromLocales(languageId);
}
}
return undefined;
}