|
| 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 { Importer, ImporterReturnType, Options, Result, SassException } from 'sass'; |
| 10 | +import { MessageChannel, Worker } from 'worker_threads'; |
| 11 | + |
| 12 | +/** |
| 13 | + * The callback type for the `dart-sass` asynchronous render function. |
| 14 | + */ |
| 15 | +type RenderCallback = (error?: SassException, result?: Result) => void; |
| 16 | + |
| 17 | +/** |
| 18 | + * An object containing the contextual information for a specific render request. |
| 19 | + */ |
| 20 | +interface RenderRequest { |
| 21 | + id: number; |
| 22 | + callback: RenderCallback; |
| 23 | + importers?: Importer[]; |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * A response from the Sass render Worker containing the result of the operation. |
| 28 | + */ |
| 29 | +interface RenderResponseMessage { |
| 30 | + id: number; |
| 31 | + error?: SassException; |
| 32 | + result?: Result; |
| 33 | +} |
| 34 | + |
| 35 | +/** |
| 36 | + * A Sass renderer implementation that provides an interface that can be used by Webpack's |
| 37 | + * `sass-loader`. The implementation uses a Worker thread to perform the Sass rendering |
| 38 | + * with the `dart-sass` package. The `dart-sass` synchronous render function is used within |
| 39 | + * the worker which can be up to two times faster than the asynchronous variant. |
| 40 | + */ |
| 41 | +export class SassWorkerImplementation { |
| 42 | + private worker?: Worker; |
| 43 | + private readonly requests = new Map<number, RenderRequest>(); |
| 44 | + private idCounter = 1; |
| 45 | + |
| 46 | + /** |
| 47 | + * Provides information about the Sass implementation. |
| 48 | + * This mimics enough of the `dart-sass` value to be used with the `sass-loader`. |
| 49 | + */ |
| 50 | + get info(): string { |
| 51 | + return 'dart-sass\tworker'; |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * The synchronous render function is not used by the `sass-loader`. |
| 56 | + */ |
| 57 | + renderSync(): never { |
| 58 | + throw new Error('Sass renderSync is not supported.'); |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * Asynchronously request a Sass stylesheet to be renderered. |
| 63 | + * |
| 64 | + * @param options The `dart-sass` options to use when rendering the stylesheet. |
| 65 | + * @param callback The function to execute when the rendering is complete. |
| 66 | + */ |
| 67 | + render(options: Options, callback: RenderCallback): void { |
| 68 | + // The `functions` and `importer` options are JavaScript functions that cannot be transferred. |
| 69 | + // If any additional function options are added in the future, they must be excluded as well. |
| 70 | + const { functions, importer, ...serializableOptions } = options; |
| 71 | + |
| 72 | + // The CLI's configuration does not use or expose the ability to defined custom Sass functions |
| 73 | + if (functions && Object.keys(functions).length > 0) { |
| 74 | + throw new Error('Sass custom functions are not supported.'); |
| 75 | + } |
| 76 | + |
| 77 | + if (!this.worker) { |
| 78 | + this.worker = this.createWorker(); |
| 79 | + } |
| 80 | + |
| 81 | + const request = this.createRequest(callback, importer); |
| 82 | + this.requests.set(request.id, request); |
| 83 | + |
| 84 | + this.worker.postMessage({ |
| 85 | + id: request.id, |
| 86 | + hasImporter: !!importer, |
| 87 | + options: serializableOptions, |
| 88 | + }); |
| 89 | + } |
| 90 | + |
| 91 | + /** |
| 92 | + * Shutdown the Sass render worker. |
| 93 | + * Executing this method will stop any pending render requests. |
| 94 | + * |
| 95 | + * The worker is unreferenced upon creation and will not block application exit. This method |
| 96 | + * is only needed if early cleanup is needed. |
| 97 | + */ |
| 98 | + close(): void { |
| 99 | + this.worker?.terminate(); |
| 100 | + this.requests.clear(); |
| 101 | + } |
| 102 | + |
| 103 | + private createWorker(): Worker { |
| 104 | + const { port1: mainImporterPort, port2: workerImporterPort } = new MessageChannel(); |
| 105 | + const importerSignal = new Int32Array(new SharedArrayBuffer(4)); |
| 106 | + |
| 107 | + const workerPath = require.resolve('./worker'); |
| 108 | + const worker = new Worker(workerPath, { |
| 109 | + workerData: { workerImporterPort, importerSignal }, |
| 110 | + transferList: [workerImporterPort], |
| 111 | + }); |
| 112 | + |
| 113 | + worker.on('message', (response: RenderResponseMessage) => { |
| 114 | + const request = this.requests.get(response.id); |
| 115 | + if (!request) { |
| 116 | + return; |
| 117 | + } |
| 118 | + |
| 119 | + this.requests.delete(response.id); |
| 120 | + |
| 121 | + if (response.result) { |
| 122 | + // The results are expected to be Node.js `Buffer` objects but will each be transferred as |
| 123 | + // a Uint8Array that does not have the expected `toString` behavior of a `Buffer`. |
| 124 | + const { css, map, stats } = response.result; |
| 125 | + const result: Result = { |
| 126 | + // This `Buffer.from` override will use the memory directly and avoid making a copy |
| 127 | + css: Buffer.from(css.buffer, css.byteOffset, css.byteLength), |
| 128 | + stats, |
| 129 | + }; |
| 130 | + if (map) { |
| 131 | + // This `Buffer.from` override will use the memory directly and avoid making a copy |
| 132 | + result.map = Buffer.from(map.buffer, map.byteOffset, map.byteLength); |
| 133 | + } |
| 134 | + request.callback(undefined, result); |
| 135 | + } else { |
| 136 | + request.callback(response.error); |
| 137 | + } |
| 138 | + }); |
| 139 | + |
| 140 | + mainImporterPort.on( |
| 141 | + 'message', |
| 142 | + ({ id, url, prev }: { id: number; url: string; prev: string }) => { |
| 143 | + const request = this.requests.get(id); |
| 144 | + if (!request?.importers) { |
| 145 | + mainImporterPort.postMessage(null); |
| 146 | + Atomics.store(importerSignal, 0, 1); |
| 147 | + Atomics.notify(importerSignal, 0); |
| 148 | + |
| 149 | + return; |
| 150 | + } |
| 151 | + |
| 152 | + this.processImporters(request.importers, url, prev) |
| 153 | + .then((result) => { |
| 154 | + mainImporterPort.postMessage(result); |
| 155 | + }) |
| 156 | + .catch((error) => { |
| 157 | + mainImporterPort.postMessage(error); |
| 158 | + }) |
| 159 | + .finally(() => { |
| 160 | + Atomics.store(importerSignal, 0, 1); |
| 161 | + Atomics.notify(importerSignal, 0); |
| 162 | + }); |
| 163 | + }, |
| 164 | + ); |
| 165 | + |
| 166 | + worker.unref(); |
| 167 | + mainImporterPort.unref(); |
| 168 | + |
| 169 | + return worker; |
| 170 | + } |
| 171 | + |
| 172 | + private async processImporters( |
| 173 | + importers: Iterable<Importer>, |
| 174 | + url: string, |
| 175 | + prev: string, |
| 176 | + ): Promise<ImporterReturnType> { |
| 177 | + let result = null; |
| 178 | + for (const importer of importers) { |
| 179 | + result = await new Promise<ImporterReturnType>((resolve) => { |
| 180 | + // Importers can be both sync and async |
| 181 | + const innerResult = importer(url, prev, resolve); |
| 182 | + if (innerResult !== undefined) { |
| 183 | + resolve(innerResult); |
| 184 | + } |
| 185 | + }); |
| 186 | + |
| 187 | + if (result) { |
| 188 | + break; |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + return result; |
| 193 | + } |
| 194 | + |
| 195 | + private createRequest( |
| 196 | + callback: RenderCallback, |
| 197 | + importer: Importer | Importer[] | undefined, |
| 198 | + ): RenderRequest { |
| 199 | + return { |
| 200 | + id: this.idCounter++, |
| 201 | + callback, |
| 202 | + importers: !importer || Array.isArray(importer) ? importer : [importer], |
| 203 | + }; |
| 204 | + } |
| 205 | +} |
0 commit comments