-
Notifications
You must be signed in to change notification settings - Fork 26
/
utils.ts
353 lines (305 loc) · 12.9 KB
/
utils.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
344
345
346
347
348
349
350
351
352
353
import { build, Plugin } from 'vite';
import type { OutputAsset, OutputBundle, OutputChunk } from 'rollup';
import type { BuildCSSInjectionConfiguration, CSSInjectionConfiguration, PluginConfiguration } from './interface';
interface InjectCodeOptions {
styleId?: string | (() => string);
useStrictCSP?: boolean;
//TODO: (BC) Migrate styleId into attributes.
attributes?: { [key: string]: string } | undefined;
}
export type InjectCode = (cssCode: string, options: InjectCodeOptions) => string;
export type InjectCodeFunction = (cssCode: string, options: InjectCodeOptions) => void;
const cssInjectedByJsId = '\0vite/all-css';
const defaultInjectCode: InjectCode = (cssCode, { styleId, useStrictCSP, attributes }) => {
let attributesInjection = '';
for (const attribute in attributes) {
attributesInjection += `elementStyle.setAttribute('${attribute}', '${attributes[attribute]}');`;
}
return `try{if(typeof document != 'undefined'){var elementStyle = document.createElement('style');${
typeof styleId == 'string' && styleId.length > 0 ? `elementStyle.id = '${styleId}';` : ''
}${
useStrictCSP ? `elementStyle.nonce = document.head.querySelector('meta[property=csp-nonce]')?.content;` : ''
}${attributesInjection}elementStyle.appendChild(document.createTextNode(${cssCode}));document.head.appendChild(elementStyle);}}catch(e){console.error('vite-plugin-css-injected-by-js', e);}`;
};
export async function buildCSSInjectionCode({
buildOptions,
cssToInject,
injectCode,
injectCodeFunction,
injectionCodeFormat = 'iife',
styleId,
useStrictCSP,
}: BuildCSSInjectionConfiguration): Promise<OutputChunk | null> {
let { minify, target } = buildOptions;
const generatedStyleId = typeof styleId === 'function' ? styleId() : styleId;
const res = await build({
root: '',
configFile: false,
logLevel: 'error',
plugins: [
injectionCSSCodePlugin({
cssToInject,
styleId: generatedStyleId,
injectCode,
injectCodeFunction,
useStrictCSP,
}),
],
build: {
write: false,
target,
minify,
assetsDir: '',
rollupOptions: {
input: {
['all-css']: cssInjectedByJsId,
},
output: {
format: injectionCodeFormat,
manualChunks: undefined,
},
},
},
});
const _cssChunk = Array.isArray(res) ? res[0] : res;
if (!('output' in _cssChunk)) return null;
return _cssChunk.output[0];
}
export function resolveInjectionCode(
cssCode: string,
injectCode: ((cssCode: string, options: InjectCodeOptions) => string) | undefined,
injectCodeFunction: ((cssCode: string, options: InjectCodeOptions) => void) | undefined,
{ styleId, useStrictCSP, attributes }: InjectCodeOptions
) {
const injectionOptions = { styleId, useStrictCSP, attributes };
if (injectCodeFunction) {
return `(${injectCodeFunction})(${cssCode}, ${JSON.stringify(injectionOptions)})`;
}
const injectFunction = injectCode || defaultInjectCode;
return injectFunction(cssCode, injectionOptions);
}
function injectionCSSCodePlugin({
cssToInject,
injectCode,
injectCodeFunction,
styleId,
useStrictCSP,
}: CSSInjectionConfiguration): Plugin {
return {
name: 'vite:injection-css-code-plugin',
resolveId(id: string) {
if (id == cssInjectedByJsId) {
return id;
}
},
load(id: string) {
if (id == cssInjectedByJsId) {
const cssCode = JSON.stringify(cssToInject.trim());
return resolveInjectionCode(cssCode, injectCode, injectCodeFunction, { styleId, useStrictCSP });
}
},
};
}
export function removeLinkStyleSheets(html: string, cssFileName: string): string {
const removeCSS = new RegExp(`<link rel=".*"[^>]*?href=".*/?${cssFileName}"[^>]*?>`);
return html.replace(removeCSS, '');
}
/* istanbul ignore next -- @preserve */
export function warnLog(msg: string) {
console.warn(`\x1b[33m \n${msg} \x1b[39m`);
}
/* istanbul ignore next -- @preserve */
export function debugLog(msg: string) {
console.debug(`\x1b[34m \n${msg} \x1b[39m`);
}
function isJsOutputChunk(chunk: OutputAsset | OutputChunk): chunk is OutputChunk {
return chunk.type == 'chunk' && chunk.fileName.match(/.[cm]?js(?:\?.+)?$/) != null;
}
function defaultJsAssetsFilter(chunk: OutputChunk): boolean {
return chunk.isEntry && !chunk.fileName.includes('polyfill');
}
// The cache must be global since execution context is different every entry
const cssSourceCache: { [key: string]: string } = {};
export function extractCss(bundle: OutputBundle, cssName: string): string {
const cssAsset = bundle[cssName] as OutputAsset;
if (cssAsset !== undefined && cssAsset.source) {
const cssSource = cssAsset.source;
// We treat these as strings and coerce them implicitly to strings, explicitly handle conversion
cssSourceCache[cssName] =
cssSource instanceof Uint8Array ? new TextDecoder().decode(cssSource) : `${cssSource}`;
}
return cssSourceCache[cssName] ?? '';
}
export function concatCssAndDeleteFromBundle(bundle: OutputBundle, cssAssets: string[]): string {
return cssAssets.reduce(function extractCssAndDeleteFromBundle(previous: string, cssName: string): string {
const cssSource = extractCss(bundle, cssName);
delete bundle[cssName];
return previous + cssSource;
}, '');
}
export function buildJsCssMap(
bundle: OutputBundle,
jsAssetsFilterFunction?: PluginConfiguration['jsAssetsFilterFunction']
): Record<string, string[]> {
const chunksWithCss: Record<string, string[]> = {};
const bundleKeys = getJsTargetBundleKeys(
bundle,
typeof jsAssetsFilterFunction == 'function' ? jsAssetsFilterFunction : () => true
);
if (bundleKeys.length === 0) {
throw new Error(
'Unable to locate the JavaScript asset for adding the CSS injection code. It is recommended to review your configurations.'
);
}
for (const key of bundleKeys) {
const chunk = bundle[key];
if (chunk.type === 'asset' || !chunk.viteMetadata || chunk.viteMetadata.importedCss.size === 0) {
continue;
}
const chunkStyles = chunksWithCss[key] || [];
chunkStyles.push(...chunk.viteMetadata.importedCss.values());
chunksWithCss[key] = chunkStyles;
}
return chunksWithCss;
}
export function getJsTargetBundleKeys(
bundle: OutputBundle,
jsAssetsFilterFunction?: PluginConfiguration['jsAssetsFilterFunction']
): string[] {
if (typeof jsAssetsFilterFunction != 'function') {
const jsAssets = Object.keys(bundle).filter((i) => {
const asset = bundle[i];
return isJsOutputChunk(asset) && defaultJsAssetsFilter(asset);
});
if (jsAssets.length == 0) {
return [];
}
const jsTargetFileName = jsAssets[jsAssets.length - 1];
if (jsAssets.length > 1) {
warnLog(
`[vite-plugin-css-injected-by-js] has identified "${jsTargetFileName}" as one of the multiple output files marked as "entry" to put the CSS injection code.` +
'However, if this is not the intended file to add the CSS injection code, you can use the "jsAssetsFilterFunction" parameter to specify the desired output file (read docs).'
);
if (process.env.VITE_CSS_INJECTED_BY_JS_DEBUG) {
const jsAssetsStr = jsAssets.join(', ');
debugLog(
`[vite-plugin-css-injected-by-js] identified js file targets: ${jsAssetsStr}. Selected "${jsTargetFileName}".\n`
);
}
}
// This should be always the root of the application
return [jsTargetFileName];
}
const chunkFilter = ([_key, chunk]: [string, OutputAsset | OutputChunk]) =>
isJsOutputChunk(chunk) && jsAssetsFilterFunction(chunk);
return Object.entries(bundle)
.filter(chunkFilter)
.map(function extractAssetKeyFromBundleEntry([key]) {
return key;
});
}
export async function relativeCssInjection(
bundle: OutputBundle,
assetsWithCss: Record<string, string[]>,
buildCssCode: (css: string) => Promise<OutputChunk | null>,
topExecutionPriorityFlag: boolean
): Promise<void> {
for (const [jsAssetName, cssAssets] of Object.entries(assetsWithCss)) {
process.env.VITE_CSS_INJECTED_BY_JS_DEBUG &&
debugLog(`[vite-plugin-css-injected-by-js] Relative CSS: ${jsAssetName}: [ ${cssAssets.join(',')} ]`);
const assetCss = concatCssAndDeleteFromBundle(bundle, cssAssets);
const cssInjectionCode = assetCss.length > 0 ? (await buildCssCode(assetCss))?.code : '';
// We have already filtered these chunks to be RenderedChunks
const jsAsset = bundle[jsAssetName] as OutputChunk;
jsAsset.code = buildOutputChunkWithCssInjectionCode(
jsAsset.code,
cssInjectionCode ?? '',
topExecutionPriorityFlag
);
}
}
const globalCSSCodeEntryCache = new Map();
let previousFacadeModuleId = '';
export async function globalCssInjection(
bundle: OutputBundle,
cssAssets: string[],
buildCssCode: (css: string) => Promise<OutputChunk | null>,
jsAssetsFilterFunction: PluginConfiguration['jsAssetsFilterFunction'],
topExecutionPriorityFlag: boolean
) {
const jsTargetBundleKeys = getJsTargetBundleKeys(bundle, jsAssetsFilterFunction);
if (jsTargetBundleKeys.length == 0) {
throw new Error(
'Unable to locate the JavaScript asset for adding the CSS injection code. It is recommended to review your configurations.'
);
}
process.env.VITE_CSS_INJECTED_BY_JS_DEBUG &&
debugLog(`[vite-plugin-css-injected-by-js] Global CSS Assets: [${cssAssets.join(',')}]`);
const allCssCode = concatCssAndDeleteFromBundle(bundle, cssAssets);
let cssInjectionCode: string = '';
if (allCssCode.length > 0) {
const cssCode = (await buildCssCode(allCssCode))?.code;
if (typeof cssCode == 'string') {
cssInjectionCode = cssCode;
}
}
for (const jsTargetKey of jsTargetBundleKeys) {
const jsAsset = bundle[jsTargetKey] as OutputChunk;
/**
* Since it creates the assets once sequential builds for the same entry point
* (for example when multiple formats of same entry point are built),
* we need to reuse the same CSS created the first time.
*/
if (jsAsset.facadeModuleId != null && jsAsset.isEntry && cssInjectionCode != '') {
if (jsAsset.facadeModuleId != previousFacadeModuleId) {
globalCSSCodeEntryCache.clear();
}
previousFacadeModuleId = jsAsset.facadeModuleId;
globalCSSCodeEntryCache.set(jsAsset.facadeModuleId, cssInjectionCode);
}
if (
cssInjectionCode == '' &&
jsAsset.isEntry &&
jsAsset.facadeModuleId != null &&
typeof globalCSSCodeEntryCache.get(jsAsset.facadeModuleId) == 'string'
) {
cssInjectionCode = globalCSSCodeEntryCache.get(jsAsset.facadeModuleId);
}
process.env.VITE_CSS_INJECTED_BY_JS_DEBUG &&
debugLog(`[vite-plugin-css-injected-by-js] Global CSS inject: ${jsAsset.fileName}`);
jsAsset.code = buildOutputChunkWithCssInjectionCode(
jsAsset.code,
cssInjectionCode ?? '',
topExecutionPriorityFlag
);
}
}
export function buildOutputChunkWithCssInjectionCode(
jsAssetCode: string,
cssInjectionCode: string,
topExecutionPriorityFlag: boolean
): string {
const appCode = jsAssetCode.replace(/\/\*\s*empty css\s*\*\//g, '');
jsAssetCode = topExecutionPriorityFlag ? '' : appCode;
jsAssetCode += cssInjectionCode;
jsAssetCode += !topExecutionPriorityFlag ? '' : appCode;
return jsAssetCode;
}
export function clearImportedCssViteMetadataFromBundle(bundle: OutputBundle, unusedCssAssets: string[]): void {
// Required to exclude removed files from manifest.json
for (const key in bundle) {
const chunk = bundle[key] as OutputChunk;
if (chunk.viteMetadata && chunk.viteMetadata.importedCss.size > 0) {
const importedCssFileNames = chunk.viteMetadata.importedCss;
importedCssFileNames.forEach((importedCssFileName) => {
if (!unusedCssAssets.includes(importedCssFileName) && chunk.viteMetadata) {
chunk.viteMetadata.importedCss = new Set();
}
});
}
}
}
export function isCSSRequest(request: string): boolean {
const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
return CSS_LANGS_RE.test(request);
}