|
| 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 { OutputFile } from 'esbuild'; |
| 10 | +import { createHash } from 'node:crypto'; |
| 11 | +import path from 'node:path'; |
| 12 | +import { BuildOutputFileType, BundleContextResult, BundlerContext } from '../bundler-context'; |
| 13 | +import { LoadResultCache } from '../load-result-cache'; |
| 14 | +import { |
| 15 | + BundleStylesheetOptions, |
| 16 | + createStylesheetBundleOptions, |
| 17 | +} from '../stylesheets/bundle-options'; |
| 18 | + |
| 19 | +class BundlerContextCache extends Map<string, BundlerContext> { |
| 20 | + getOrCreate(key: string, creator: () => BundlerContext): BundlerContext { |
| 21 | + let value = this.get(key); |
| 22 | + |
| 23 | + if (value === undefined) { |
| 24 | + value = creator(); |
| 25 | + this.set(key, value); |
| 26 | + } |
| 27 | + |
| 28 | + return value; |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Bundles component stylesheets. A stylesheet can be either an inline stylesheet that |
| 34 | + * is contained within the Component's metadata definition or an external file referenced |
| 35 | + * from the Component's metadata definition. |
| 36 | + */ |
| 37 | +export class ComponentStylesheetBundler { |
| 38 | + readonly #fileContexts = new BundlerContextCache(); |
| 39 | + readonly #inlineContexts = new BundlerContextCache(); |
| 40 | + |
| 41 | + /** |
| 42 | + * |
| 43 | + * @param options An object containing the stylesheet bundling options. |
| 44 | + * @param cache A load result cache to use when bundling. |
| 45 | + */ |
| 46 | + constructor( |
| 47 | + private readonly options: BundleStylesheetOptions, |
| 48 | + private readonly cache?: LoadResultCache, |
| 49 | + ) {} |
| 50 | + |
| 51 | + async bundleFile(entry: string) { |
| 52 | + const bundlerContext = this.#fileContexts.getOrCreate(entry, () => { |
| 53 | + const buildOptions = createStylesheetBundleOptions(this.options, this.cache); |
| 54 | + buildOptions.entryPoints = [entry]; |
| 55 | + |
| 56 | + return new BundlerContext(this.options.workspaceRoot, true, buildOptions); |
| 57 | + }); |
| 58 | + |
| 59 | + return extractResult(await bundlerContext.bundle(), bundlerContext.watchFiles); |
| 60 | + } |
| 61 | + |
| 62 | + async bundleInline(data: string, filename: string, language: string) { |
| 63 | + // Use a hash of the inline stylesheet content to ensure a consistent identifier. External stylesheets will resolve |
| 64 | + // to the actual stylesheet file path. |
| 65 | + // TODO: Consider xxhash instead for hashing |
| 66 | + const id = createHash('sha256').update(data).digest('hex'); |
| 67 | + |
| 68 | + const bundlerContext = this.#inlineContexts.getOrCreate(id, () => { |
| 69 | + const namespace = 'angular:styles/component'; |
| 70 | + const entry = [language, id, filename].join(';'); |
| 71 | + |
| 72 | + const buildOptions = createStylesheetBundleOptions(this.options, this.cache, { |
| 73 | + [entry]: data, |
| 74 | + }); |
| 75 | + buildOptions.entryPoints = [`${namespace};${entry}`]; |
| 76 | + buildOptions.plugins.push({ |
| 77 | + name: 'angular-component-styles', |
| 78 | + setup(build) { |
| 79 | + build.onResolve({ filter: /^angular:styles\/component;/ }, (args) => { |
| 80 | + if (args.kind !== 'entry-point') { |
| 81 | + return null; |
| 82 | + } |
| 83 | + |
| 84 | + return { |
| 85 | + path: entry, |
| 86 | + namespace, |
| 87 | + }; |
| 88 | + }); |
| 89 | + build.onLoad({ filter: /^css;/, namespace }, async () => { |
| 90 | + return { |
| 91 | + contents: data, |
| 92 | + loader: 'css', |
| 93 | + resolveDir: path.dirname(filename), |
| 94 | + }; |
| 95 | + }); |
| 96 | + }, |
| 97 | + }); |
| 98 | + |
| 99 | + return new BundlerContext(this.options.workspaceRoot, true, buildOptions); |
| 100 | + }); |
| 101 | + |
| 102 | + // Extract the result of the bundling from the output files |
| 103 | + return extractResult(await bundlerContext.bundle(), bundlerContext.watchFiles); |
| 104 | + } |
| 105 | + |
| 106 | + async dispose(): Promise<void> { |
| 107 | + const contexts = [...this.#fileContexts.values(), ...this.#inlineContexts.values()]; |
| 108 | + this.#fileContexts.clear(); |
| 109 | + this.#inlineContexts.clear(); |
| 110 | + |
| 111 | + await Promise.allSettled(contexts.map((context) => context.dispose())); |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +function extractResult(result: BundleContextResult, referencedFiles?: Set<string>) { |
| 116 | + let contents = ''; |
| 117 | + let map; |
| 118 | + let outputPath; |
| 119 | + const resourceFiles: OutputFile[] = []; |
| 120 | + if (!result.errors) { |
| 121 | + for (const outputFile of result.outputFiles) { |
| 122 | + const filename = path.basename(outputFile.path); |
| 123 | + if (outputFile.type === BuildOutputFileType.Media) { |
| 124 | + // The output files could also contain resources (images/fonts/etc.) that were referenced |
| 125 | + resourceFiles.push(outputFile); |
| 126 | + } else if (filename.endsWith('.css')) { |
| 127 | + outputPath = outputFile.path; |
| 128 | + contents = outputFile.text; |
| 129 | + } else if (filename.endsWith('.css.map')) { |
| 130 | + map = outputFile.text; |
| 131 | + } else { |
| 132 | + throw new Error( |
| 133 | + `Unexpected non CSS/Media file "${filename}" outputted during component stylesheet processing.`, |
| 134 | + ); |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + let metafile; |
| 140 | + if (!result.errors) { |
| 141 | + metafile = result.metafile; |
| 142 | + // Remove entryPoint fields from outputs to prevent the internal component styles from being |
| 143 | + // treated as initial files. Also mark the entry as a component resource for stat reporting. |
| 144 | + Object.values(metafile.outputs).forEach((output) => { |
| 145 | + delete output.entryPoint; |
| 146 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 147 | + (output as any)['ng-component'] = true; |
| 148 | + }); |
| 149 | + } |
| 150 | + |
| 151 | + return { |
| 152 | + errors: result.errors, |
| 153 | + warnings: result.warnings, |
| 154 | + contents, |
| 155 | + map, |
| 156 | + path: outputPath, |
| 157 | + resourceFiles, |
| 158 | + metafile, |
| 159 | + referencedFiles, |
| 160 | + }; |
| 161 | +} |
0 commit comments