forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsass-service.ts
266 lines (232 loc) · 7.54 KB
/
sass-service.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
/**
* @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.dev/license
*/
import assert from 'node:assert';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { MessageChannel } from 'node:worker_threads';
import type {
CanonicalizeContext,
CompileResult,
Deprecation,
Exception,
FileImporter,
Importer,
NodePackageImporter,
SourceSpan,
StringOptions,
} from 'sass';
import { maxWorkers } from '../../utils/environment-options';
import { WorkerPool } from '../../utils/worker-pool';
// Polyfill Symbol.dispose if not present
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(Symbol as any).dispose ??= Symbol('Symbol Dispose');
/**
* The maximum number of Workers that will be created to execute render requests.
*/
const MAX_RENDER_WORKERS = maxWorkers;
/**
* All available importer types.
*/
type Importers =
| Importer<'sync'>
| Importer<'async'>
| FileImporter<'sync'>
| FileImporter<'async'>
| NodePackageImporter;
export interface SerializableVersion {
major: number;
minor: number;
patch: number;
}
export interface SerializableDeprecation extends Omit<Deprecation, 'obsoleteIn' | 'deprecatedIn'> {
/** The version this deprecation first became active in. */
deprecatedIn: SerializableVersion | null;
/** The version this deprecation became obsolete in. */
obsoleteIn: SerializableVersion | null;
}
export type SerializableWarningMessage = (
| {
deprecation: true;
deprecationType: SerializableDeprecation;
}
| { deprecation: false }
) & {
message: string;
span?: Omit<SourceSpan, 'url'> & { url?: string };
stack?: string;
};
/**
* A response from the Sass render Worker containing the result of the operation.
*/
interface RenderResponseMessage {
error?: Exception;
result?: Omit<CompileResult, 'loadedUrls'> & { loadedUrls: string[] };
warnings?: SerializableWarningMessage[];
}
/**
* A Sass renderer implementation that provides an interface that can be used by Webpack's
* `sass-loader`. The implementation uses a Worker thread to perform the Sass rendering
* with the `dart-sass` package. The `dart-sass` synchronous render function is used within
* the worker which can be up to two times faster than the asynchronous variant.
*/
export class SassWorkerImplementation {
#workerPool: WorkerPool | undefined;
constructor(
private readonly rebase = false,
readonly maxThreads = MAX_RENDER_WORKERS,
) {}
#ensureWorkerPool(): WorkerPool {
this.#workerPool ??= new WorkerPool({
filename: require.resolve('./worker'),
maxThreads: this.maxThreads,
});
return this.#workerPool;
}
/**
* Provides information about the Sass implementation.
* This mimics enough of the `dart-sass` value to be used with the `sass-loader`.
*/
get info(): string {
return 'dart-sass\tworker';
}
/**
* The synchronous render function is not used by the `sass-loader`.
*/
compileString(): never {
throw new Error('Sass compileString is not supported.');
}
/**
* Asynchronously request a Sass stylesheet to be renderered.
*
* @param source The contents to compile.
* @param options The `dart-sass` options to use when rendering the stylesheet.
*/
async compileStringAsync(
source: string,
options: StringOptions<'async'>,
): Promise<CompileResult> {
// The `functions`, `logger` and `importer` options are JavaScript functions that cannot be transferred.
// If any additional function options are added in the future, they must be excluded as well.
const { functions, importers, url, logger, ...serializableOptions } = options;
// The CLI's configuration does not use or expose the ability to define custom Sass functions
if (functions && Object.keys(functions).length > 0) {
throw new Error('Sass custom functions are not supported.');
}
using importerChannel = importers?.length ? this.#createImporterChannel(importers) : undefined;
const response = (await this.#ensureWorkerPool().run(
{
source,
importerChannel,
hasLogger: !!logger,
rebase: this.rebase,
options: {
...serializableOptions,
// URL is not serializable so to convert to string here and back to URL in the worker.
url: url ? fileURLToPath(url) : undefined,
},
},
{
transferList: importerChannel ? [importerChannel.port] : undefined,
},
)) as RenderResponseMessage;
const { result, error, warnings } = response;
if (warnings && logger?.warn) {
for (const { message, span, ...options } of warnings) {
logger.warn(message, {
...options,
span: span && {
...span,
url: span.url ? pathToFileURL(span.url) : undefined,
},
});
}
}
if (error) {
// Convert stringified url value required for cloning back to a URL object
const url = error.span?.url as string | undefined;
if (url) {
error.span.url = pathToFileURL(url);
}
throw error;
}
assert(result, 'Sass render worker should always return a result or an error');
return {
...result,
// URL is not serializable so in the worker we convert to string and here back to URL.
loadedUrls: result.loadedUrls.map((p) => pathToFileURL(p)),
};
}
/**
* Shutdown the Sass render worker.
* Executing this method will stop any pending render requests.
* @returns A void promise that resolves when closing is complete.
*/
async close(): Promise<void> {
if (this.#workerPool) {
try {
await this.#workerPool.destroy();
} finally {
this.#workerPool = undefined;
}
}
}
#createImporterChannel(importers: Iterable<Importers>) {
const { port1: mainImporterPort, port2: workerImporterPort } = new MessageChannel();
const importerSignal = new Int32Array(new SharedArrayBuffer(4));
mainImporterPort.on(
'message',
({ url, options }: { url: string; options: CanonicalizeContext }) => {
this.processImporters(importers, url, {
...options,
// URL is not serializable so in the worker we convert to string and here back to URL.
containingUrl: options.containingUrl
? pathToFileURL(options.containingUrl as unknown as string)
: null,
})
.then((result) => {
mainImporterPort.postMessage(result);
})
.catch((error) => {
mainImporterPort.postMessage(error);
})
.finally(() => {
Atomics.store(importerSignal, 0, 1);
Atomics.notify(importerSignal, 0);
});
},
);
mainImporterPort.unref();
return {
port: workerImporterPort,
signal: importerSignal,
[Symbol.dispose]() {
mainImporterPort.close();
},
};
}
private async processImporters(
importers: Iterable<Importers>,
url: string,
options: CanonicalizeContext,
): Promise<string | null> {
for (const importer of importers) {
if (!this.isFileImporter(importer)) {
// Importer
throw new Error('Only File Importers are supported.');
}
// File importer (Can be sync or aync).
const result = await importer.findFileUrl(url, options);
if (result) {
return fileURLToPath(result);
}
}
return null;
}
private isFileImporter(value: Importers): value is FileImporter {
return 'findFileUrl' in value;
}
}