-
Notifications
You must be signed in to change notification settings - Fork 357
/
Copy pathnode.dart
402 lines (370 loc) · 14.2 KB
/
node.dart
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Copyright 2016 Google Inc. 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 'dart:async';
import 'dart:convert';
import 'dart:js_util';
import 'dart:typed_data';
import 'package:js/js.dart';
import 'package:path/path.dart' as p;
import 'package:tuple/tuple.dart';
import 'ast/sass.dart';
import 'callable.dart';
import 'compile.dart';
import 'exception.dart';
import 'io.dart';
import 'importer/node.dart';
import 'node/error.dart';
import 'node/exports.dart';
import 'node/function.dart';
import 'node/render_context.dart';
import 'node/render_context_options.dart';
import 'node/render_options.dart';
import 'node/render_result.dart';
import 'node/types.dart';
import 'node/value.dart';
import 'node/utils.dart';
import 'parse/scss.dart';
import 'syntax.dart';
import 'value.dart';
import 'visitor/serialize.dart';
/// The entrypoint for the Node.js module.
///
/// This sets up exports that can be called from JS.
void main() {
exports.render = allowInterop(_render);
exports.renderSync = allowInterop(_renderSync);
exports.info =
"dart-sass\t${const String.fromEnvironment('version')}\t(Sass Compiler)\t"
"[Dart]\n"
"dart2js\t${const String.fromEnvironment('dart-version')}\t"
"(Dart Compiler)\t[Dart]";
exports.types = Types(
Boolean: booleanConstructor,
Color: colorConstructor,
List: listConstructor,
Map: mapConstructor,
Null: nullConstructor,
Number: numberConstructor,
String: stringConstructor,
Error: jsErrorConstructor);
exports.NULL = sassNull;
exports.TRUE = sassTrue;
exports.FALSE = sassFalse;
}
/// Converts Sass to CSS.
///
/// This attempts to match the [node-sass `render()` API][render] as closely as
/// possible.
///
/// [render]: https://github.com/sass/node-sass#options
void _render(
RenderOptions options, void callback(JSError error, RenderResult result)) {
if (options.fiber != null) {
options.fiber.call(allowInterop(() {
try {
callback(null, _renderSync(options));
} catch (error) {
callback(error as JSError, null);
}
return null;
})).run();
} else {
_renderAsync(options).then((result) {
callback(null, result);
}, onError: (Object error, StackTrace stackTrace) {
if (error is SassException) {
callback(_wrapException(error), null);
} else {
callback(_newRenderError(error.toString(), status: 3), null);
}
});
}
}
/// Converts Sass to CSS asynchronously.
Future<RenderResult> _renderAsync(RenderOptions options) async {
var start = DateTime.now();
var file = options.file == null ? null : p.absolute(options.file);
CompileResult result;
if (options.data != null) {
result = await compileStringAsync(options.data,
nodeImporter: _parseImporter(options, start),
functions: _parseFunctions(options, asynch: true),
syntax: isTruthy(options.indentedSyntax) ? Syntax.sass : null,
style: _parseOutputStyle(options.outputStyle),
useSpaces: options.indentType != 'tab',
indentWidth: _parseIndentWidth(options.indentWidth),
lineFeed: _parseLineFeed(options.linefeed),
url: options.file == null ? 'stdin' : p.toUri(file).toString(),
sourceMap: _enableSourceMaps(options));
} else if (options.file != null) {
result = await compileAsync(file,
nodeImporter: _parseImporter(options, start),
functions: _parseFunctions(options, asynch: true),
syntax: isTruthy(options.indentedSyntax) ? Syntax.sass : null,
style: _parseOutputStyle(options.outputStyle),
useSpaces: options.indentType != 'tab',
indentWidth: _parseIndentWidth(options.indentWidth),
lineFeed: _parseLineFeed(options.linefeed),
sourceMap: _enableSourceMaps(options));
} else {
throw ArgumentError("Either options.data or options.file must be set.");
}
return _newRenderResult(options, result, start);
}
/// Converts Sass to CSS.
///
/// This attempts to match the [node-sass `renderSync()` API][render] as closely
/// as possible.
///
/// [render]: https://github.com/sass/node-sass#options
RenderResult _renderSync(RenderOptions options) {
try {
var start = DateTime.now();
var file = options.file == null ? null : p.absolute(options.file);
CompileResult result;
if (options.data != null) {
result = compileString(options.data,
nodeImporter: _parseImporter(options, start),
functions: _parseFunctions(options).cast(),
syntax: isTruthy(options.indentedSyntax) ? Syntax.sass : null,
style: _parseOutputStyle(options.outputStyle),
useSpaces: options.indentType != 'tab',
indentWidth: _parseIndentWidth(options.indentWidth),
lineFeed: _parseLineFeed(options.linefeed),
url: options.file == null ? 'stdin' : p.toUri(file).toString(),
sourceMap: _enableSourceMaps(options));
} else if (options.file != null) {
result = compile(file,
nodeImporter: _parseImporter(options, start),
functions: _parseFunctions(options).cast(),
syntax: isTruthy(options.indentedSyntax) ? Syntax.sass : null,
style: _parseOutputStyle(options.outputStyle),
useSpaces: options.indentType != 'tab',
indentWidth: _parseIndentWidth(options.indentWidth),
lineFeed: _parseLineFeed(options.linefeed),
sourceMap: _enableSourceMaps(options));
} else {
throw ArgumentError("Either options.data or options.file must be set.");
}
return _newRenderResult(options, result, start);
} on SassException catch (error) {
jsThrow(_wrapException(error));
} catch (error) {
jsThrow(_newRenderError(error.toString(), status: 3));
}
throw "unreachable";
}
/// Converts an exception to a [JSError].
JSError _wrapException(Object exception) {
if (exception is SassException) {
return _newRenderError(exception.toString().replaceFirst("Error: ", ""),
line: exception.span.start.line + 1,
column: exception.span.start.column + 1,
file: exception.span.sourceUrl == null
? 'stdin'
: p.fromUri(exception.span.sourceUrl),
status: 1);
} else {
return JSError(exception.toString());
}
}
/// Parses `functions` from [RenderOptions] into a list of [Callable]s or
/// [AsyncCallable]s.
///
/// This is typed to always return [AsyncCallable], but in practice it will
/// return a `List<Callable>` if [asynch] is `false`.
List<AsyncCallable> _parseFunctions(RenderOptions options,
{bool asynch = false}) {
if (options.functions == null) return const [];
var result = <AsyncCallable>[];
jsForEach(options.functions, (signature, callback) {
Tuple2<String, ArgumentDeclaration> tuple;
try {
tuple = ScssParser(signature as String).parseSignature();
} on SassFormatException catch (error) {
throw SassFormatException(
'Invalid signature "${signature}": ${error.message}', error.span);
}
if (options.fiber != null) {
result.add(BuiltInCallable.parsed(tuple.item1, tuple.item2, (arguments) {
var fiber = options.fiber.current;
var jsArguments = [
...arguments.map(wrapValue),
allowInterop(([Object result]) {
// Schedule a microtask so we don't try to resume the running fiber
// if [importer] calls `done()` synchronously.
scheduleMicrotask(() => fiber.run(result));
})
];
var result = Function.apply(callback as Function, jsArguments);
return unwrapValue(
isUndefined(result) ? options.fiber.yield() : result);
}));
} else if (!asynch) {
result.add(BuiltInCallable.parsed(
tuple.item1,
tuple.item2,
(arguments) => unwrapValue(Function.apply(
callback as Function, arguments.map(wrapValue).toList()))));
} else {
result.add(AsyncBuiltInCallable.parsed(tuple.item1, tuple.item2,
(arguments) async {
var completer = Completer<Object>();
var jsArguments = [
...arguments.map(wrapValue),
allowInterop(([Object result]) => completer.complete(result))
];
var result = Function.apply(callback as Function, jsArguments);
return unwrapValue(
isUndefined(result) ? await completer.future : result);
}));
}
});
return result;
}
/// Parses [importer] and [includePaths] from [RenderOptions] into a
/// [NodeImporter].
NodeImporter _parseImporter(RenderOptions options, DateTime start) {
List<JSFunction> importers;
if (options.importer == null) {
importers = [];
} else if (options.importer is List<Object>) {
importers = (options.importer as List<Object>).cast();
} else {
importers = [options.importer as JSFunction];
}
var includePaths = List<String>.from(options.includePaths ?? []);
RenderContext context;
if (importers.isNotEmpty) {
context = RenderContext(
options: RenderContextOptions(
file: options.file,
data: options.data,
includePaths:
([p.current, ...includePaths]).join(isWindows ? ';' : ':'),
precision: SassNumber.precision,
style: 1,
indentType: options.indentType == 'tab' ? 1 : 0,
indentWidth: _parseIndentWidth(options.indentWidth) ?? 2,
linefeed: _parseLineFeed(options.linefeed).text,
result: RenderResult(
stats: RenderResultStats(
start: start.millisecondsSinceEpoch,
entry: options.file ?? 'data'))));
context.options.context = context;
}
if (options.fiber != null) {
importers = importers.map((importer) {
return allowInteropCaptureThis(
(Object thisArg, String url, String previous, [Object _]) {
var fiber = options.fiber.current;
var result = call3(importer, thisArg, url, previous,
allowInterop((Object result) {
// Schedule a microtask so we don't try to resume the running fiber if
// [importer] calls `done()` synchronously.
scheduleMicrotask(() => fiber.run(result));
}));
if (isUndefined(result)) return options.fiber.yield();
return result;
}) as JSFunction;
}).toList();
}
return NodeImporter(context, includePaths, importers);
}
/// Parse [style] into an [OutputStyle].
OutputStyle _parseOutputStyle(String style) {
if (style == null || style == 'expanded') return OutputStyle.expanded;
if (style == 'compressed') return OutputStyle.compressed;
throw ArgumentError('Unsupported output style "$style".');
}
/// Parses the indentation width into an [int].
int _parseIndentWidth(Object width) {
if (width == null) return null;
return width is int ? width : int.parse(width.toString());
}
/// Parses the name of a line feed type into a [LineFeed].
LineFeed _parseLineFeed(String str) {
switch (str) {
case 'cr':
return LineFeed.cr;
case 'crlf':
return LineFeed.crlf;
case 'lfcr':
return LineFeed.lfcr;
default:
return LineFeed.lf;
}
}
/// Creates a [RenderResult] that exposes [result] in the Node Sass API format.
RenderResult _newRenderResult(
RenderOptions options, CompileResult result, DateTime start) {
var end = DateTime.now();
var css = result.css;
Uint8List sourceMapBytes;
if (_enableSourceMaps(options)) {
var sourceMapPath = options.sourceMap is String
? options.sourceMap as String
: options.outFile + '.map';
var sourceMapDir = p.dirname(sourceMapPath);
result.sourceMap.sourceRoot = options.sourceMapRoot;
if (options.outFile == null) {
if (options.file == null) {
result.sourceMap.targetUrl = 'stdin.css';
} else {
result.sourceMap.targetUrl =
p.toUri(p.setExtension(options.file, '.css')).toString();
}
} else {
result.sourceMap.targetUrl =
p.toUri(p.relative(options.outFile, from: sourceMapDir)).toString();
}
var sourceMapDirUrl = p.toUri(sourceMapDir).toString();
for (var i = 0; i < result.sourceMap.urls.length; i++) {
var source = result.sourceMap.urls[i];
if (source == "stdin") continue;
// URLs handled by Node importers that directly return file contents are
// preserved in their original (usually relative) form. They may or may
// not be intended as `file:` URLs, but there's nothing we can do about it
// either way so we keep them as-is.
if (p.url.isRelative(source) || p.url.isRootRelative(source)) continue;
result.sourceMap.urls[i] = p.url.relative(source, from: sourceMapDirUrl);
}
var json = result.sourceMap
.toJson(includeSourceContents: isTruthy(options.sourceMapContents));
sourceMapBytes = utf8Encode(jsonEncode(json));
if (!isTruthy(options.omitSourceMapUrl)) {
var url = isTruthy(options.sourceMapEmbed)
? Uri.dataFromBytes(sourceMapBytes, mimeType: "application/json")
: p.toUri(options.outFile == null
? sourceMapPath
: p.relative(sourceMapPath, from: p.dirname(options.outFile)));
css += "\n\n/*# sourceMappingURL=$url */";
}
}
return RenderResult(
css: utf8Encode(css),
map: sourceMapBytes,
stats: RenderResultStats(
entry: options.file ?? 'data',
start: start.millisecondsSinceEpoch,
end: end.millisecondsSinceEpoch,
duration: end.difference(start).inMilliseconds,
includedFiles: result.includedFiles.toList()));
}
/// Returns whether source maps are enabled by [options].
bool _enableSourceMaps(RenderOptions options) =>
options.sourceMap is String ||
(isTruthy(options.sourceMap) && options.outFile != null);
/// Creates a [JSError] with the given fields added to it so it acts like a Node
/// Sass error.
JSError _newRenderError(String message,
{int line, int column, String file, int status}) {
var error = JSError(message);
setProperty(error, 'formatted', 'Error: $message');
if (line != null) setProperty(error, 'line', line);
if (column != null) setProperty(error, 'column', column);
if (file != null) setProperty(error, 'file', file);
if (status != null) setProperty(error, 'status', status);
return error;
}