-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
StylusTransformer.js
352 lines (311 loc) Β· 9.58 KB
/
StylusTransformer.js
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
// @flow
import {Transformer} from '@parcel/plugin';
import {createDependencyLocation, isGlob, glob, globSync} from '@parcel/utils';
import path from 'path';
import nativeFS from 'fs';
import stylus from 'stylus';
import Parser from 'stylus/lib/parser';
import DepsResolver from 'stylus/lib/visitor/deps-resolver';
import nodes from 'stylus/lib/nodes';
import utils from 'stylus/lib/utils';
import Evaluator from 'stylus/lib/visitor/evaluator';
const URL_RE = /^(?:url\s*\(\s*)?['"]?(?:[#/]|(?:https?:)?\/\/)/i;
export default (new Transformer({
async loadConfig({config}) {
let configFile = await config.getConfig(
['.stylusrc', '.stylusrc.js', '.stylusrc.cjs', '.stylusrc.mjs'],
{
packageKey: 'stylus',
},
);
if (configFile) {
// Resolve relative paths from config file
if (configFile.contents.paths) {
configFile.contents.paths = configFile.contents.paths.map(p =>
path.resolve(path.dirname(configFile.filePath), p),
);
}
return configFile.contents;
}
},
async transform({asset, resolve, config, options}) {
let stylusConfig = config ?? {};
let code = await asset.getCode();
let style = stylus(code, {...stylusConfig});
style.set('filename', asset.filePath);
style.set('include css', true);
// Setup a handler for the URL function so we add dependencies for linked assets.
style.define('url', (node: stylus.nodes.String | stylus.nodes.Literal) => {
let filename = asset.addURLDependency(node.val, {
loc: createDependencyLocation(
{line: node.lineno, column: node.column},
node.val,
),
});
return new stylus.nodes.Literal(`url(${JSON.stringify(filename)})`);
});
let {resolved: stylusPath} = await options.packageManager.resolve(
'stylus',
__filename,
);
let nativeGlob = await options.packageManager.require('glob', stylusPath);
style.set(
'Evaluator',
await createEvaluator(
code,
asset,
resolve,
style.options,
options,
nativeGlob,
),
);
asset.type = 'css';
asset.setCode(style.render());
asset.meta.hasDependencies = false;
return [asset];
},
}): Transformer);
function attemptResolve(importedPath, filepath, asset, resolve, deps) {
if (deps.has(importedPath)) {
return;
}
if (isGlob(importedPath)) {
// Invalidate when new files are created that match the glob pattern.
let absoluteGlob = path.resolve(path.dirname(filepath), importedPath);
asset.invalidateOnFileCreate({glob: absoluteGlob});
deps.set(
importedPath,
glob(absoluteGlob, asset.fs, {
onlyFiles: true,
}).then(entries =>
Promise.all(
entries.map(entry =>
resolve(
filepath,
'./' + path.relative(path.dirname(filepath), entry),
{
packageConditions: ['stylus', 'style'],
},
),
),
),
),
);
} else {
deps.set(
importedPath,
resolve(filepath, importedPath, {
packageConditions: ['stylus', 'style'],
}),
);
}
}
async function getDependencies(
code,
filepath,
asset,
resolve,
options,
parcelOptions,
nativeGlob,
seen = new Set(),
includeImports = true,
) {
seen.add(filepath);
nodes.filename = asset.filePath;
let parser = new Parser(code, options);
let ast = parser.parse();
let deps = new Map();
if (includeImports && options.imports) {
for (let importedPath of options.imports) {
attemptResolve(importedPath, filepath, asset, resolve, deps);
}
}
class ImportVisitor extends DepsResolver {
visitImport(imported) {
let importedPath = imported.path.first.string;
attemptResolve(importedPath, filepath, asset, resolve, deps);
}
}
new ImportVisitor(ast, options).visit(ast);
// Recursively process depdendencies, and return a map with all resolved paths.
let res = new Map();
await Promise.all(
Array.from(deps.entries()).map(async ([importedPath, resolved]) => {
try {
resolved = await resolved;
} catch (err) {
resolved = null;
}
let found;
if (resolved && (!Array.isArray(resolved) || resolved.length > 0)) {
found = Array.isArray(resolved) ? resolved : [resolved];
res.set(importedPath, resolved);
} else {
// If we couldn't resolve, try the normal stylus resolver.
// We just need to do this to keep track of the dependencies - stylus does the real work.
// support optional .styl
let originalPath = importedPath;
if (!/\.styl$/i.test(importedPath)) {
importedPath += '.styl';
}
// Patch the native FS so we use Parcel's FS, and track files that are
// checked so we invalidate the cache when they are created.
let restore = patchNativeFS(asset.fs, nativeGlob);
let paths = [
...new Set(
(options.paths || []).concat(path.dirname(filepath || '.')),
),
];
found = utils.find(importedPath, paths, filepath);
if (!found) {
found = utils.lookupIndex(originalPath, paths, filepath);
}
for (let invalidation of restore()) {
asset.invalidateOnFileCreate(invalidation);
}
if (!found) {
throw new Error('failed to locate file ' + originalPath);
}
}
// Recursively process resolved files as well to get nested deps
for (let resolved of found) {
if (!seen.has(resolved)) {
asset.invalidateOnFileChange(resolved);
let code = await asset.fs.readFile(resolved, 'utf8');
for (let [path, resolvedPath] of await getDependencies(
code,
resolved,
asset,
resolve,
options,
parcelOptions,
nativeGlob,
seen,
false,
)) {
res.set(path, resolvedPath);
}
}
}
}),
);
return res;
}
async function createEvaluator(
code,
asset,
resolve,
options,
parcelOptions,
nativeGlob,
) {
const deps = await getDependencies(
code,
asset.filePath,
asset,
resolve,
options,
parcelOptions,
nativeGlob,
);
// This is a custom stylus evaluator that extends stylus with support for the node
// require resolution algorithm. It also adds all dependencies to the parcel asset
// tree so the file watcher works correctly, etc.
class CustomEvaluator extends Evaluator {
visitImport(imported) {
let node = this.visit(imported.path).first;
let path = node.string;
if (node.name !== 'url' && path && !URL_RE.test(path)) {
let resolved = deps.get(path);
// First try resolving using the node require resolution algorithm.
// This allows stylus files in node_modules to be resolved properly.
// If we find something, update the AST so stylus gets the absolute path to load later.
if (resolved) {
if (!Array.isArray(resolved)) {
node.string = resolved;
} else {
// If the import resolves to multiple files (i.e. glob),
// replace it with a separate import node for each file
return mergeBlocks(
resolved.map(resolvedPath => {
node.string = resolvedPath;
let restore = patchNativeFS(asset.fs, nativeGlob);
let res = super.visitImport(imported.clone());
restore();
return res;
}),
);
}
}
}
// Patch the native FS so stylus uses Parcel's FS to read the file.
let restore = patchNativeFS(asset.fs, nativeGlob);
// Done. Let stylus do its thing.
let res = super.visitImport(imported);
restore();
return res;
}
}
return CustomEvaluator;
}
function patchNativeFS(fs, nativeGlob) {
let invalidations = [];
let readFileSync = nativeFS.readFileSync;
let statSync = nativeFS.statSync;
// $FlowFixMe
nativeFS.readFileSync = (filename, encoding) => {
return fs.readFileSync(filename, encoding);
};
// $FlowFixMe
nativeFS.statSync = p => {
try {
return fs.statSync(p);
} catch (err) {
// Track files that were checked but don't exist so that we watch for their creation.
if (!p.includes(`node_modules${path.sep}stylus`)) {
invalidations.push({filePath: p});
}
throw err;
}
};
// Patch the `glob` module as well so we use the Parcel FS and track invalidations.
let glob = nativeGlob.sync;
nativeGlob.sync = p => {
let res = globSync(p, fs);
if (!p.includes(`node_modules${path.sep}stylus`)) {
// Sometimes stylus passes file paths with no glob parts to the `glob` module.
// We want to avoid treating these as globs for performance.
if (isGlob(p)) {
invalidations.push({glob: p});
} else if (res.length === 0) {
invalidations.push({filePath: p});
}
}
return res;
};
return () => {
// $FlowFixMe
nativeFS.readFileSync = readFileSync;
// $FlowFixMe
nativeFS.statSync = statSync;
nativeGlob.sync = glob;
return invalidations;
};
}
/**
* Puts the content of all given node blocks into the first one, essentially merging them.
*/
function mergeBlocks(blocks) {
let finalBlock;
for (const block of blocks) {
if (finalBlock) {
// $FlowFixMe - finalBlock is definitely defined
block.nodes.forEach(node => finalBlock.push(node));
} else {
finalBlock = block;
}
}
return finalBlock;
}