/
evaluator.js
333 lines (268 loc) · 7.88 KB
/
evaluator.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
import path from 'path';
import Evaluator from 'stylus/lib/visitor/evaluator';
import normalizePath from 'normalize-path';
import fastGlob from 'fast-glob';
import { urlToRequest } from 'loader-utils';
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 { readFile, isDirectory } from './utils';
const URL_RE = /^(?:url\s*\(\s*)?['"]?(?:[#/]|(?:https?:)?\/\/)/i;
async function resolveFilename(
filename,
currentDirectory,
loaderContext,
webpackFileResolver,
webpackGlobResolver,
resolveGlob
) {
const resolve =
typeof resolveGlob === 'undefined'
? webpackFileResolver
: webpackGlobResolver;
const request = urlToRequest(
filename,
// eslint-disable-next-line no-undefined
filename.charAt(0) === '/' ? loaderContext.rootContext : undefined
);
return resolveRequests(
currentDirectory,
[...new Set([request, filename])],
resolve
);
}
function resolveRequests(context, possibleRequests, resolve) {
if (possibleRequests.length === 0) {
return Promise.reject();
}
return resolve(context, possibleRequests[0])
.then((result) => {
return result;
})
.catch((error) => {
const [, ...tailPossibleRequests] = possibleRequests;
if (tailPossibleRequests.length === 0) {
throw error;
}
return resolveRequests(context, tailPossibleRequests, resolve);
});
}
async function getDependencies(
code,
filepath,
loaderContext,
webpackFileResolver,
webpackGlobResolver,
options,
seen = new Set()
) {
seen.add(filepath);
nodes.filename = filepath;
const parser = new Parser(code, options);
let ast;
try {
ast = parser.parse();
} catch (error) {
loaderContext.emitError(error);
}
const deps = new Map();
class ImportVisitor extends DepsResolver {
// eslint-disable-next-line class-methods-use-this
visitImport(imported) {
let node = imported.path.first;
if (node.name === 'url') {
return;
}
if (!node.val) {
const evaluator = new Evaluator(ast);
node = evaluator.visit.call(evaluator, node).first;
}
const importedPath = (!node.val.isNull && node.val) || node.name;
let nodePath = importedPath;
if (!importedPath || deps.has(importedPath)) {
return;
}
if (fastGlob.isDynamicPattern(importedPath)) {
if (
!isDirectory(
loaderContext.fs,
path.join(path.dirname(filepath), importedPath)
)
) {
deps.set(
importedPath,
Promise.resolve().then(async () => {
const [parsedGlob] = fastGlob.generateTasks(importedPath);
parsedGlob.glob =
parsedGlob.base === '.'
? importedPath
: importedPath.slice(parsedGlob.base.length + 1);
const globRoot = await resolveFilename(
parsedGlob.base,
path.dirname(filepath),
loaderContext,
webpackFileResolver,
webpackGlobResolver,
true
);
return {
isGlob: true,
path: path.posix.join(globRoot, parsedGlob.glob),
};
})
);
return;
}
}
let found;
let oldPath;
const literal = /\.css(?:"|$)/.test(nodePath);
if (!literal && !/\.styl$/i.test(nodePath)) {
oldPath = nodePath;
nodePath += '.styl';
}
found = utils.find(nodePath, this.paths, this.filename);
if (!found && oldPath)
found = utils.lookupIndex(oldPath, this.paths, this.filename);
if (found) {
deps.set(
importedPath,
path.resolve(
loaderContext.rootContext,
path.relative(loaderContext.rootContext, ...found)
)
);
return;
}
deps.set(
importedPath,
resolveFilename(
importedPath,
loaderContext.rootContext,
loaderContext,
webpackFileResolver,
webpackGlobResolver
)
);
}
}
new ImportVisitor(ast, options).visit(ast);
// Recursively process depdendencies, and return a map with all resolved paths.
const resolvedPaths = new Map();
await Promise.all(
Array.from(deps.entries()).map(async (result) => {
const [importedPath] = result;
let [, resolved] = result;
let pathIsGlob;
try {
resolved = await resolved;
} catch (ignoreError) {
/*
* The stylus can still resolve the paths obtained with `use` option
* example `nib`, `bootstrap`, or will generate an error
* */
return;
}
if (resolved.isGlob) {
pathIsGlob = true;
resolved = normalizePath(resolved.path);
}
resolvedPaths.set(importedPath, resolved);
let found = Array.isArray(resolved) ? resolved : [resolved];
if (pathIsGlob) {
found = await fastGlob(resolved);
found = found.filter((file) => /\.styl$/i.test(file));
}
// Recursively process resolved files as well to get nested deps
const nestedDeps = [];
for (const detected of found) {
nestedDeps.push(
(async () => {
if (!seen.has(detected)) {
let source;
try {
source = (
await readFile(loaderContext.fs, detected)
).toString();
} catch (error) {
loaderContext.emitError(error);
}
for (const [importPath, resolvedPath] of await getDependencies(
source,
detected,
loaderContext,
webpackFileResolver,
webpackGlobResolver,
options
)) {
resolvedPaths.set(importPath, resolvedPath);
}
}
})()
);
}
await Promise.all(nestedDeps);
})
);
return resolvedPaths;
}
export default async function createEvaluator(code, options, loaderContext) {
const webpackFileResolver = loaderContext.getResolve({
conditionNames: ['styl', 'stylus', 'style'],
mainFields: ['styl', 'style', 'stylus', 'main', '...'],
mainFiles: ['index', '...'],
extensions: ['.styl', '.css'],
restrictions: [/\.(css|styl)$/i],
});
const webpackGlobResolver = loaderContext.getResolve({
conditionNames: ['styl', 'stylus', 'style'],
mainFields: ['styl', 'style', 'stylus', 'main', '...'],
mainFiles: ['index', '...'],
resolveToContext: true,
});
let optionsImports = '';
if (options.import) {
optionsImports = options.import
.map((entry) => `@import "${entry}";`)
.join('\n');
}
const possibleImports = (
await Promise.all(
[code, optionsImports].map((content) =>
getDependencies(
content,
loaderContext.resourcePath,
loaderContext,
webpackFileResolver,
webpackGlobResolver,
options
)
)
)
).reduce((acc, map) => {
acc.push(...map);
return acc;
}, []);
const resolvedDependencies = new Map(possibleImports);
return class CustomEvaluator extends Evaluator {
visitImport(imported) {
try {
return super.visitImport(imported);
} catch (ignoreError) {
// Then use the webpack resolver
}
this.return += 1;
const node = this.visit(imported.path).first;
const nodePath = node.string;
this.return -= 1;
if (node.name !== 'url' && nodePath && !URL_RE.test(nodePath)) {
const resolved = resolvedDependencies.get(nodePath);
if (resolved) {
node.string = resolved;
}
}
return super.visitImport(imported);
}
};
}