-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
PathRequest.js
442 lines (395 loc) Β· 12.5 KB
/
PathRequest.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
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// @flow strict-local
import type {Diagnostic} from '@parcel/diagnostic';
import type {
Async,
FileCreateInvalidation,
FilePath,
Resolver,
} from '@parcel/types';
import type {StaticRunOpts} from '../RequestTracker';
import type {
AssetGroup,
Config,
Dependency,
DevDepRequest,
ParcelOptions,
} from '../types';
import type {ConfigAndCachePath} from './ParcelConfigRequest';
import ThrowableDiagnostic, {
convertSourceLocationToHighlight,
errorToDiagnostic,
md,
} from '@parcel/diagnostic';
import {PluginLogger} from '@parcel/logger';
import nullthrows from 'nullthrows';
import path from 'path';
import {normalizePath} from '@parcel/utils';
import {report} from '../ReporterRunner';
import {getPublicDependency} from '../public/Dependency';
import PluginOptions from '../public/PluginOptions';
import ParcelConfig from '../ParcelConfig';
import createParcelConfigRequest, {
getCachedParcelConfig,
} from './ParcelConfigRequest';
import {invalidateOnFileCreateToInternal} from '../utils';
import {
fromProjectPath,
fromProjectPathRelative,
toProjectPath,
toProjectPathUnsafe,
} from '../projectPath';
import {Priority} from '../types';
import {createBuildCache} from '../buildCache';
import type {LoadedPlugin} from '../ParcelConfig';
import {createConfig} from '../InternalConfig';
import {loadPluginConfig, runConfigRequest} from './ConfigRequest';
import {
createDevDependency,
getDevDepRequests,
invalidateDevDeps,
runDevDepRequest,
} from './DevDepRequest';
import {tracer, PluginTracer} from '@parcel/profiler';
export type PathRequest = {|
id: string,
+type: 'path_request',
run: (RunOpts<?AssetGroup>) => Async<?AssetGroup>,
input: PathRequestInput,
|};
export type PathRequestInput = {|
dependency: Dependency,
name: string,
|};
type RunOpts<TResult> = {|
input: PathRequestInput,
...StaticRunOpts<TResult>,
|};
const type = 'path_request';
const PIPELINE_REGEX = /^([a-z0-9-]+?):(.*)$/i;
export default function createPathRequest(
input: PathRequestInput,
): PathRequest {
return {
id: input.dependency.id + ':' + input.name,
type,
run,
input,
};
}
async function run({input, api, options}) {
let configResult = nullthrows(
await api.runRequest<null, ConfigAndCachePath>(createParcelConfigRequest()),
);
let config = getCachedParcelConfig(configResult, options);
let {devDeps, invalidDevDeps} = await getDevDepRequests(api);
invalidateDevDeps(invalidDevDeps, options, config);
let resolverRunner = new ResolverRunner({
options,
config,
previousDevDeps: devDeps,
});
let result: ResolverResult = await resolverRunner.resolve(input.dependency);
if (result.invalidateOnEnvChange) {
for (let env of result.invalidateOnEnvChange) {
api.invalidateOnEnvChange(env);
}
}
if (result.invalidateOnFileCreate) {
for (let file of result.invalidateOnFileCreate) {
api.invalidateOnFileCreate(
invalidateOnFileCreateToInternal(options.projectRoot, file),
);
}
}
if (result.invalidateOnFileChange) {
for (let filePath of result.invalidateOnFileChange) {
let pp = toProjectPath(options.projectRoot, filePath);
api.invalidateOnFileUpdate(pp);
api.invalidateOnFileDelete(pp);
}
}
for (let config of resolverRunner.configs.values()) {
await runConfigRequest(api, config);
}
for (let devDepRequest of resolverRunner.devDepRequests.values()) {
await runDevDepRequest(api, devDepRequest);
}
if (result.assetGroup) {
api.invalidateOnFileDelete(result.assetGroup.filePath);
return result.assetGroup;
}
if (result.diagnostics && result.diagnostics.length > 0) {
let err = new ThrowableDiagnostic({diagnostic: result.diagnostics});
// $FlowFixMe[prop-missing]
err.code = 'MODULE_NOT_FOUND';
throw err;
}
}
type ResolverRunnerOpts = {|
config: ParcelConfig,
options: ParcelOptions,
previousDevDeps: Map<string, string>,
|};
type ResolverResult = {|
assetGroup: ?AssetGroup,
invalidateOnFileCreate?: Array<FileCreateInvalidation>,
invalidateOnFileChange?: Array<FilePath>,
invalidateOnEnvChange?: Array<string>,
diagnostics?: Array<Diagnostic>,
|};
const configCache = createBuildCache();
export class ResolverRunner {
config: ParcelConfig;
options: ParcelOptions;
pluginOptions: PluginOptions;
previousDevDeps: Map<string, string>;
devDepRequests: Map<string, DevDepRequest>;
configs: Map<string, Config>;
constructor({config, options, previousDevDeps}: ResolverRunnerOpts) {
this.config = config;
this.options = options;
this.pluginOptions = new PluginOptions(this.options);
this.previousDevDeps = previousDevDeps;
this.devDepRequests = new Map();
this.configs = new Map();
}
async getDiagnostic(
dependency: Dependency,
message: string,
): Async<Diagnostic> {
let diagnostic: Diagnostic = {
message,
origin: '@parcel/core',
};
if (dependency.loc && dependency.sourcePath != null) {
let filePath = fromProjectPath(
this.options.projectRoot,
dependency.sourcePath,
);
diagnostic.codeFrames = [
{
filePath,
code: await this.options.inputFS.readFile(filePath, 'utf8'),
codeHighlights: dependency.loc
? [convertSourceLocationToHighlight(dependency.loc)]
: [],
},
];
}
return diagnostic;
}
async loadConfigs(
resolvers: Array<LoadedPlugin<Resolver<mixed>>>,
): Promise<void> {
for (let plugin of resolvers) {
// Only load config for a plugin once per build.
let config = configCache.get(plugin.name);
if (!config && plugin.plugin.loadConfig != null) {
config = createConfig({
plugin: plugin.name,
searchPath: toProjectPathUnsafe('index'),
});
await loadPluginConfig(plugin, config, this.options);
configCache.set(plugin.name, config);
this.configs.set(plugin.name, config);
}
if (config) {
for (let devDep of config.devDeps) {
let devDepRequest = await createDevDependency(
devDep,
this.previousDevDeps,
this.options,
);
this.runDevDepRequest(devDepRequest);
}
this.configs.set(plugin.name, config);
}
}
}
runDevDepRequest(devDepRequest: DevDepRequest) {
let {specifier, resolveFrom} = devDepRequest;
let key = `${specifier}:${fromProjectPathRelative(resolveFrom)}`;
this.devDepRequests.set(key, devDepRequest);
}
async resolve(dependency: Dependency): Promise<ResolverResult> {
let dep = getPublicDependency(dependency, this.options);
report({
type: 'buildProgress',
phase: 'resolving',
dependency: dep,
});
let resolvers = await this.config.getResolvers();
await this.loadConfigs(resolvers);
let pipeline;
let specifier;
let validPipelines = new Set(this.config.getNamedPipelines());
let match = dependency.specifier.match(PIPELINE_REGEX);
if (
match &&
// Don't consider absolute paths. Absolute paths are only supported for entries,
// and include e.g. `C:\` on Windows, conflicting with pipelines.
!path.isAbsolute(dependency.specifier)
) {
[, pipeline, specifier] = match;
if (!validPipelines.has(pipeline)) {
// This may be a url protocol or scheme rather than a pipeline, such as
// `url('http://example.com/foo.png')`. Pass it to resolvers to handle.
specifier = dependency.specifier;
pipeline = null;
}
} else {
specifier = dependency.specifier;
}
// Entrypoints, convert ProjectPath in module specifier to absolute path
if (dep.resolveFrom == null) {
specifier = path.join(this.options.projectRoot, specifier);
}
let diagnostics: Array<Diagnostic> = [];
let invalidateOnFileCreate = [];
let invalidateOnFileChange = [];
let invalidateOnEnvChange = [];
for (let resolver of resolvers) {
let measurement;
try {
measurement = tracer.createMeasurement(
resolver.name,
'resolve',
specifier,
);
let result = await resolver.plugin.resolve({
specifier,
pipeline,
dependency: dep,
options: this.pluginOptions,
logger: new PluginLogger({origin: resolver.name}),
tracer: new PluginTracer({
origin: resolver.name,
category: 'resolver',
}),
config: this.configs.get(resolver.name)?.result,
});
measurement && measurement.end();
if (result) {
if (result.meta) {
dependency.resolverMeta = result.meta;
dependency.meta = {
...dependency.meta,
...result.meta,
};
}
if (result.priority != null) {
dependency.priority = Priority[result.priority];
}
if (result.invalidateOnEnvChange) {
invalidateOnEnvChange.push(...result.invalidateOnEnvChange);
}
if (result.invalidateOnFileCreate) {
invalidateOnFileCreate.push(...result.invalidateOnFileCreate);
}
if (result.invalidateOnFileChange) {
invalidateOnFileChange.push(...result.invalidateOnFileChange);
}
if (result.isExcluded) {
return {
assetGroup: null,
invalidateOnFileCreate,
invalidateOnFileChange,
invalidateOnEnvChange,
};
}
if (result.filePath != null) {
let resultFilePath = result.filePath;
if (!path.isAbsolute(resultFilePath)) {
throw new Error(
md`Resolvers must return an absolute path, ${resolver.name} returned: ${resultFilePath}`,
);
}
return {
assetGroup: {
canDefer: result.canDefer,
filePath: toProjectPath(
this.options.projectRoot,
resultFilePath,
),
query: result.query?.toString(),
sideEffects: result.sideEffects,
code: result.code,
env: dependency.env,
pipeline:
result.pipeline === undefined
? pipeline ?? dependency.pipeline
: result.pipeline,
isURL: dep.specifierType === 'url',
},
invalidateOnFileCreate,
invalidateOnFileChange,
invalidateOnEnvChange,
};
}
if (result.diagnostics) {
let errorDiagnostic = errorToDiagnostic(
new ThrowableDiagnostic({diagnostic: result.diagnostics}),
{
origin: resolver.name,
filePath: specifier,
},
);
diagnostics.push(...errorDiagnostic);
}
}
} catch (e) {
// Add error to error map, we'll append these to the standard error if we can't resolve the asset
let errorDiagnostic = errorToDiagnostic(e, {
origin: resolver.name,
filePath: specifier,
});
if (Array.isArray(errorDiagnostic)) {
diagnostics.push(...errorDiagnostic);
} else {
diagnostics.push(errorDiagnostic);
}
break;
} finally {
measurement && measurement.end();
// Add dev dependency for the resolver. This must be done AFTER running it due to
// the potential for lazy require() that aren't executed until the request runs.
let devDepRequest = await createDevDependency(
{
specifier: resolver.name,
resolveFrom: resolver.resolveFrom,
},
this.previousDevDeps,
this.options,
);
this.runDevDepRequest(devDepRequest);
}
}
if (dep.isOptional) {
return {
assetGroup: null,
invalidateOnFileCreate,
invalidateOnFileChange,
invalidateOnEnvChange,
};
}
let resolveFrom = dependency.resolveFrom ?? dependency.sourcePath;
let dir =
resolveFrom != null
? normalizePath(fromProjectPathRelative(resolveFrom))
: '';
let diagnostic = await this.getDiagnostic(
dependency,
md`Failed to resolve '${dependency.specifier}' ${
dir ? `from '${dir}'` : ''
}`,
);
diagnostics.unshift(diagnostic);
return {
assetGroup: null,
invalidateOnFileCreate,
invalidateOnFileChange,
invalidateOnEnvChange,
diagnostics,
};
}
}