-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathutils.ts
More file actions
273 lines (248 loc) · 8.76 KB
/
Copy pathutils.ts
File metadata and controls
273 lines (248 loc) · 8.76 KB
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
// Copyright 2024 Google LLC. Use of this source code is governed by an
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import * as p from 'path';
import * as supportsColor from 'supports-color';
import {create} from '@bufbuild/protobuf';
import {Deprecation, deprecations, getDeprecationIds} from '../deprecations';
import {deprotofySourceSpan} from '../deprotofy-span';
import {Dispatcher, DispatcherHandlers} from '../dispatcher';
import {Exception} from '../exception';
import {ImporterRegistry} from '../importer-registry';
import {
legacyImporterProtocol,
removeLegacyImporter,
removeLegacyImporterFromSpan,
} from '../legacy/utils';
import {Logger} from '../logger';
import {MessageTransformer} from '../message-transformer';
import * as utils from '../utils';
import * as proto from '../vendor/embedded_sass_pb';
import {SourceSpan} from '../vendor/sass';
import {CompileResult} from '../vendor/sass/compile';
import {Options, StringOptions} from '../vendor/sass/options';
/**
* Allow the legacy API to pass in an option signaling to the modern API that
* it's being run in legacy mode.
*
* This is not intended for API users to pass in, and may be broken without
* warning in the future.
*/
export type OptionsWithLegacy<sync extends 'sync' | 'async'> = Options<sync> & {
legacy?: boolean;
};
/**
* Allow the legacy API to pass in an option signaling to the modern API that
* it's being run in legacy mode.
*
* This is not intended for API users to pass in, and may be broken without
* warning in the future.
*/
export type StringOptionsWithLegacy<sync extends 'sync' | 'async'> =
StringOptions<sync> & {legacy?: boolean};
/**
* Creates a dispatcher that dispatches messages from the given `stdout` stream.
*/
export function createDispatcher<sync extends 'sync' | 'async'>(
compilationId: number,
messageTransformer: MessageTransformer,
handlers: DispatcherHandlers<sync>,
): Dispatcher<sync> {
return new Dispatcher<sync>(
compilationId,
messageTransformer.outboundMessages$,
message => messageTransformer.writeInboundMessage(message),
handlers,
);
}
// Creates a compilation request for the given `options` without adding any
// input-specific options.
function newCompileRequest(
importers: ImporterRegistry<'sync' | 'async'>,
options?: Options<'sync' | 'async'>,
): proto.InboundMessage_CompileRequest {
const request = create(proto.InboundMessage_CompileRequestSchema, {
importers: importers.importers,
globalFunctions: Object.keys(options?.functions ?? {}),
sourceMap: !!options?.sourceMap,
sourceMapIncludeSources: !!options?.sourceMapIncludeSources,
alertColor: options?.alertColor ?? !!supportsColor.stdout,
alertAscii: !!options?.alertAscii,
quietDeps: !!options?.quietDeps,
verbose: !!options?.verbose,
charset: !!(options?.charset ?? true),
silent: options?.logger === Logger.silent,
fatalDeprecation: getDeprecationIds(options?.fatalDeprecations ?? []),
silenceDeprecation: getDeprecationIds(options?.silenceDeprecations ?? []),
futureDeprecation: getDeprecationIds(options?.futureDeprecations ?? []),
});
switch (options?.style ?? 'expanded') {
case 'expanded':
request.style = proto.OutputStyle.EXPANDED;
break;
case 'compressed':
request.style = proto.OutputStyle.COMPRESSED;
break;
default:
throw new Error(`Unknown options.style: "${options?.style}"`);
}
return request;
}
// Creates a request for compiling a file.
export function newCompilePathRequest(
path: string,
importers: ImporterRegistry<'sync' | 'async'>,
options?: Options<'sync' | 'async'>,
): proto.InboundMessage_CompileRequest {
const absPath = p.resolve(path);
const request = newCompileRequest(importers, options);
request.input = {case: 'path', value: absPath};
return request;
}
// Creates a request for compiling a string.
export function newCompileStringRequest(
source: string,
importers: ImporterRegistry<'sync' | 'async'>,
options?: StringOptions<'sync' | 'async'>,
): proto.InboundMessage_CompileRequest {
const input = create(proto.InboundMessage_CompileRequest_StringInputSchema, {
source,
syntax: utils.protofySyntax(options?.syntax ?? 'scss'),
});
const url = options?.url?.toString();
if (url && url !== legacyImporterProtocol) {
input.url = url;
}
if (options && 'importer' in options && options.importer) {
input.importer = importers.register(options.importer);
} else if (url === legacyImporterProtocol) {
input.importer = create(
proto.InboundMessage_CompileRequest_ImporterSchema,
{
importer: {case: 'path', value: p.resolve('.')},
},
);
} else {
// When importer is not set on the host, the compiler will set a
// FileSystemImporter if `url` is set to a file: url or a NoOpImporter.
}
const request = newCompileRequest(importers, options);
request.input = {case: 'string', value: input};
return request;
}
/** Type guard to check that `id` is a valid deprecation ID. */
function validDeprecationId(
id: string | number | symbol | undefined,
): id is keyof typeof deprecations {
return !!id && id in deprecations;
}
/** Handles a log event according to `options`. */
export function handleLogEvent(
options: OptionsWithLegacy<'sync' | 'async'> | undefined,
event: proto.OutboundMessage_LogEvent,
): void {
let span = event.span ? deprotofySourceSpan(event.span) : null;
if (span && options?.legacy) span = removeLegacyImporterFromSpan(span);
let message = event.message;
if (options?.legacy) message = removeLegacyImporter(message);
let formatted = event.formatted;
if (options?.legacy) formatted = removeLegacyImporter(formatted);
const deprecationType = validDeprecationId(event.deprecationType)
? deprecations[event.deprecationType]
: null;
if (event.type === proto.LogEventType.DEBUG) {
if (options?.logger?.debug) {
options.logger.debug(message, {
span: span!,
});
} else {
const url = event.span?.url;
if (url) {
const index = formatted.indexOf(url);
if (index !== -1) {
const replacement = utils.prettyUrl(url);
if (url !== replacement) {
formatted =
formatted.slice(0, index) +
replacement +
formatted.slice(index + url.length);
}
}
}
console.error(formatted);
}
} else {
let stack = event.stackTrace;
if (stack && options?.legacy) stack = removeLegacyImporter(stack);
if (options?.logger?.warn) {
const params: (
| {
deprecation: true;
deprecationType: Deprecation;
}
| {deprecation: false}
) & {
span?: SourceSpan;
stack?: string;
} = deprecationType
? {deprecation: true, deprecationType: deprecationType}
: {deprecation: false};
if (span) params.span = span;
if (stack) {
params.stack = stack;
}
options.logger.warn(message, params);
} else {
console.error(utils.prettyFormatted(formatted, stack));
}
}
}
/**
* Converts a `CompileResponse` into a `CompileResult`.
*
* Throws a `SassException` if the compilation failed.
*/
export function handleCompileResponse(
response: proto.OutboundMessage_CompileResponse,
): CompileResult {
if (response.result.case === 'success') {
const success = response.result.value;
const result: CompileResult = {
css: success.css,
loadedUrls: response.loadedUrls.map(url => new URL(url)),
};
const sourceMap = success.sourceMap;
if (sourceMap) result.sourceMap = JSON.parse(sourceMap);
return result;
} else if (response.result.case === 'failure') {
throw new Exception(response.result.value);
} else {
throw utils.compilerError('Compiler sent empty CompileResponse');
}
}
/**
* A polyfill for the return type of `Promise.withResolvers()` until it's
* universally available in LTS Node.js versions.
*/
interface PromiseWithResolvers<T> {
promise: Promise<T>;
resolve: (value: T | PromiseLike<T>) => void;
// Type definition comes from official types for Node v22.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
reject: (reason?: any) => void;
}
// TODO(nweiz): Replace this with the library function once Node 22 is the
// oldest LTS version (May 2026).
/**
* A polyfill for `Promise.withResolvers()` until it's universally available in
* LTS Node.js versions.
*/
export function promiseWithResolvers<T>(): PromiseWithResolvers<T> {
let resolve: PromiseWithResolvers<T>['resolve'] | undefined;
let reject: PromiseWithResolvers<T>['reject'] | undefined;
const promise = new Promise<T>((resolve_, reject_) => {
resolve = resolve_;
reject = reject_;
});
return {promise, resolve: resolve!, reject: reject!};
}