/
TargetRequest.js
1265 lines (1179 loc) Β· 39.5 KB
/
TargetRequest.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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @flow strict-local
import type {Diagnostic} from '@parcel/diagnostic';
import type {FileSystem} from '@parcel/fs';
import type {
Async,
Engines,
FilePath,
PackageJSON,
PackageTargetDescriptor,
TargetDescriptor,
OutputFormat,
} from '@parcel/types';
import type {StaticRunOpts, RunAPI} from '../RequestTracker';
import type {Entry, ParcelOptions, Target} from '../types';
import type {ConfigAndCachePath} from './ParcelConfigRequest';
import ThrowableDiagnostic, {
generateJSONCodeHighlights,
getJSONSourceLocation,
encodeJSONKeyComponent,
md,
} from '@parcel/diagnostic';
import path from 'path';
import {
loadConfig,
resolveConfig,
hashObject,
validateSchema,
} from '@parcel/utils';
import {createEnvironment} from '../Environment';
import createParcelConfigRequest, {
getCachedParcelConfig,
} from './ParcelConfigRequest';
// $FlowFixMe
import browserslist from 'browserslist';
import jsonMap from 'json-source-map';
import invariant from 'assert';
import nullthrows from 'nullthrows';
import {
COMMON_TARGET_DESCRIPTOR_SCHEMA,
DESCRIPTOR_SCHEMA,
PACKAGE_DESCRIPTOR_SCHEMA,
ENGINES_SCHEMA,
} from '../TargetDescriptor.schema';
import {BROWSER_ENVS} from '../public/Environment';
import {optionsProxy, toInternalSourceLocation} from '../utils';
import {fromProjectPath, toProjectPath, joinProjectPath} from '../projectPath';
type RunOpts = {|
input: Entry,
...StaticRunOpts,
|};
const DEFAULT_DIST_DIRNAME = 'dist';
const JS_RE = /\.[mc]?js$/;
const JS_EXTENSIONS = ['.js', '.mjs', '.cjs'];
const COMMON_TARGETS = {
main: {
match: JS_RE,
extensions: JS_EXTENSIONS,
},
module: {
// module field is always ESM. Don't allow .cjs extension here.
match: /\.m?js$/,
extensions: ['.js', '.mjs'],
},
browser: {
match: JS_RE,
extensions: JS_EXTENSIONS,
},
types: {
match: /\.d\.ts$/,
extensions: ['.d.ts'],
},
};
const DEFAULT_ENGINES = {
node: 'current',
browsers: [
'last 1 Chrome version',
'last 1 Safari version',
'last 1 Firefox version',
'last 1 Edge version',
],
};
export type TargetRequest = {|
id: string,
+type: 'target_request',
run: RunOpts => Async<Array<Target>>,
input: Entry,
|};
const type = 'target_request';
export default function createTargetRequest(input: Entry): TargetRequest {
return {
id: `${type}:${hashObject(input)}`,
type,
run,
input,
};
}
export function skipTarget(
targetName: string,
exclusiveTarget?: FilePath,
descriptorSource?: FilePath | Array<FilePath>,
): boolean {
// We skip targets if they have a descriptor.source and don't match the current exclusiveTarget
// They will be handled by a separate resolvePackageTargets call from their Entry point
// but with exclusiveTarget set.
return exclusiveTarget == null
? descriptorSource != null
: targetName !== exclusiveTarget;
}
async function run({input, api, options}: RunOpts) {
let targetResolver = new TargetResolver(
api,
optionsProxy(options, api.invalidateOnOptionChange),
);
let targets: Array<Target> = await targetResolver.resolve(
fromProjectPath(options.projectRoot, input.packagePath),
input.target,
);
assertTargetsAreNotEntries(targets, input, options);
let configResult = nullthrows(
await api.runRequest<null, ConfigAndCachePath>(createParcelConfigRequest()),
);
let parcelConfig = getCachedParcelConfig(configResult, options);
// Find named pipelines for each target.
let pipelineNames = new Set(parcelConfig.getNamedPipelines());
for (let target of targets) {
if (pipelineNames.has(target.name)) {
target.pipeline = target.name;
}
}
return targets;
}
export class TargetResolver {
fs: FileSystem;
api: RunAPI;
options: ParcelOptions;
constructor(api: RunAPI, options: ParcelOptions) {
this.api = api;
this.fs = options.inputFS;
this.options = options;
}
async resolve(
rootDir: FilePath,
exclusiveTarget?: string,
): Promise<Array<Target>> {
let optionTargets = this.options.targets;
if (exclusiveTarget != null && optionTargets == null) {
optionTargets = [exclusiveTarget];
}
let packageTargets: Map<string, Target | null> =
await this.resolvePackageTargets(rootDir, exclusiveTarget);
let targets: Array<Target>;
if (optionTargets) {
if (Array.isArray(optionTargets)) {
if (optionTargets.length === 0) {
throw new ThrowableDiagnostic({
diagnostic: {
message: `Targets option is an empty array`,
origin: '@parcel/core',
},
});
}
// Only build the intersection of the exclusive target and option targets.
if (exclusiveTarget != null) {
optionTargets = optionTargets.filter(
target => target === exclusiveTarget,
);
}
// If an array of strings is passed, it's a filter on the resolved package
// targets. Load them, and find the matching targets.
targets = optionTargets
.map(target => {
// null means skipped.
if (!packageTargets.has(target)) {
throw new ThrowableDiagnostic({
diagnostic: {
message: md`Could not find target with name "${target}"`,
origin: '@parcel/core',
},
});
}
return packageTargets.get(target);
})
.filter(Boolean);
} else {
// Otherwise, it's an object map of target descriptors (similar to those
// in package.json). Adapt them to native targets.
targets = Object.entries(optionTargets)
.map(([name, _descriptor]) => {
let {distDir, ...descriptor} = parseDescriptor(
name,
_descriptor,
null,
JSON.stringify({targets: optionTargets}, null, '\t'),
);
if (distDir == null) {
let optionTargetsString = JSON.stringify(
optionTargets,
null,
'\t',
);
throw new ThrowableDiagnostic({
diagnostic: {
message: md`Missing distDir for target "${name}"`,
origin: '@parcel/core',
codeFrames: [
{
code: optionTargetsString,
codeHighlights: generateJSONCodeHighlights(
optionTargetsString || '',
[
{
key: `/${name}`,
type: 'value',
},
],
),
},
],
},
});
}
let target: Target = {
name,
distDir: toProjectPath(
this.options.projectRoot,
path.resolve(this.fs.cwd(), distDir),
),
publicUrl:
descriptor.publicUrl ??
this.options.defaultTargetOptions.publicUrl,
env: createEnvironment({
engines: descriptor.engines,
context: descriptor.context,
isLibrary:
descriptor.isLibrary ??
this.options.defaultTargetOptions.isLibrary,
includeNodeModules: descriptor.includeNodeModules,
outputFormat:
descriptor.outputFormat ??
this.options.defaultTargetOptions.outputFormat,
shouldOptimize:
this.options.defaultTargetOptions.shouldOptimize &&
descriptor.optimize !== false,
shouldScopeHoist:
this.options.defaultTargetOptions.shouldScopeHoist &&
descriptor.scopeHoist !== false,
sourceMap: normalizeSourceMap(
this.options,
descriptor.sourceMap,
),
}),
};
if (descriptor.distEntry != null) {
target.distEntry = descriptor.distEntry;
}
if (descriptor.source != null) {
target.source = descriptor.source;
}
return target;
})
.filter(
target => !skipTarget(target.name, exclusiveTarget, target.source),
);
}
let serve = this.options.serveOptions;
if (serve && targets.length > 0) {
// In serve mode, we only support a single browser target. If the user
// provided more than one, or the matching target is not a browser, throw.
if (targets.length > 1) {
throw new ThrowableDiagnostic({
diagnostic: {
message: `More than one target is not supported in serve mode`,
origin: '@parcel/core',
},
});
}
if (!BROWSER_ENVS.has(targets[0].env.context)) {
throw new ThrowableDiagnostic({
diagnostic: {
message: `Only browser targets are supported in serve mode`,
origin: '@parcel/core',
},
});
}
targets[0].distDir = toProjectPath(
this.options.projectRoot,
serve.distDir,
);
}
} else {
// Explicit targets were not provided. Either use a modern target for server
// mode, or simply use the package.json targets.
if (this.options.serveOptions) {
// In serve mode, we only support a single browser target. Since the user
// hasn't specified a target, use one targeting modern browsers for development
targets = [
{
name: 'default',
distDir: toProjectPath(
this.options.projectRoot,
this.options.serveOptions.distDir,
),
publicUrl: this.options.defaultTargetOptions.publicUrl ?? '/',
env: createEnvironment({
context: 'browser',
engines: {
browsers: DEFAULT_ENGINES.browsers,
},
shouldOptimize: this.options.defaultTargetOptions.shouldOptimize,
outputFormat: this.options.defaultTargetOptions.outputFormat,
shouldScopeHoist:
this.options.defaultTargetOptions.shouldScopeHoist,
sourceMap: this.options.defaultTargetOptions.sourceMaps
? {}
: undefined,
}),
},
];
} else {
targets = Array.from(packageTargets.values())
.filter(Boolean)
.filter(descriptor => {
return (
descriptor &&
!skipTarget(descriptor.name, exclusiveTarget, descriptor.source)
);
});
}
}
return targets;
}
async resolvePackageTargets(
rootDir: FilePath,
exclusiveTarget?: string,
): Promise<Map<string, Target | null>> {
let rootFile = path.join(rootDir, 'index');
let conf = await loadConfig(
this.fs,
rootFile,
['package.json'],
this.options.projectRoot,
);
let rootFileProject = toProjectPath(this.options.projectRoot, rootFile);
// Invalidate whenever a package.json file is added.
this.api.invalidateOnFileCreate({
fileName: 'package.json',
aboveFilePath: rootFileProject,
});
let pkg;
let pkgContents;
let pkgFilePath: ?FilePath;
let pkgDir: FilePath;
let pkgMap;
if (conf) {
pkg = (conf.config: PackageJSON);
let pkgFile = conf.files[0];
if (pkgFile == null) {
throw new ThrowableDiagnostic({
diagnostic: {
message: md`Expected package.json file in ${rootDir}`,
origin: '@parcel/core',
},
});
}
let _pkgFilePath = (pkgFilePath = pkgFile.filePath); // For Flow
pkgDir = path.dirname(_pkgFilePath);
pkgContents = await this.fs.readFile(_pkgFilePath, 'utf8');
pkgMap = jsonMap.parse(pkgContents.replace(/\t/g, ' '));
let pp = toProjectPath(this.options.projectRoot, _pkgFilePath);
this.api.invalidateOnFileUpdate(pp);
this.api.invalidateOnFileDelete(pp);
} else {
pkg = {};
pkgDir = this.fs.cwd();
}
let pkgTargets = pkg.targets || {};
let pkgEngines: Engines =
parseEngines(
pkg.engines,
pkgFilePath,
pkgContents,
'/engines',
'Invalid engines in package.json',
) || {};
if (pkgEngines.browsers == null) {
let env =
this.options.env.BROWSERSLIST_ENV ??
this.options.env.NODE_ENV ??
this.options.mode;
if (pkg.browserslist != null) {
let pkgBrowserslist = pkg.browserslist;
let browserslist =
typeof pkgBrowserslist === 'object' && !Array.isArray(pkgBrowserslist)
? pkgBrowserslist[env]
: pkgBrowserslist;
pkgEngines = {
...pkgEngines,
browsers: browserslist,
};
} else {
let browserslistConfig = await resolveConfig(
this.fs,
path.join(rootDir, 'index'),
['browserslist', '.browserslistrc'],
this.options.projectRoot,
);
this.api.invalidateOnFileCreate({
fileName: 'browserslist',
aboveFilePath: rootFileProject,
});
this.api.invalidateOnFileCreate({
fileName: '.browserslistrc',
aboveFilePath: rootFileProject,
});
if (browserslistConfig != null) {
let contents = await this.fs.readFile(browserslistConfig, 'utf8');
let config = browserslist.parseConfig(contents);
let browserslistBrowsers = config[env] || config.defaults;
if (browserslistBrowsers?.length > 0) {
pkgEngines = {
...pkgEngines,
browsers: browserslistBrowsers,
};
}
// Invalidate whenever browserslist config file or relevant environment variables change
let pp = toProjectPath(this.options.projectRoot, browserslistConfig);
this.api.invalidateOnFileUpdate(pp);
this.api.invalidateOnFileDelete(pp);
this.api.invalidateOnEnvChange('BROWSERSLIST_ENV');
this.api.invalidateOnEnvChange('NODE_ENV');
}
}
}
let targets: Map<string, Target | null> = new Map();
let node = pkgEngines.node;
let browsers = pkgEngines.browsers;
// If there is a separate `browser` target, or an `engines.node` field but no browser targets, then
// the `main` and `module` targets refer to node, otherwise browser.
let mainContext =
pkg.browser ?? pkgTargets.browser ?? (node != null && !browsers)
? 'node'
: 'browser';
let moduleContext =
pkg.browser ?? pkgTargets.browser ? 'browser' : mainContext;
let defaultEngines = this.options.defaultTargetOptions.engines;
let context = browsers ?? !node ? 'browser' : 'node';
if (context === 'browser' && pkgEngines.browsers == null) {
pkgEngines = {
...pkgEngines,
browsers: defaultEngines?.browsers ?? DEFAULT_ENGINES.browsers,
};
} else if (context === 'node' && pkgEngines.node == null) {
pkgEngines = {
...pkgEngines,
node: defaultEngines?.node ?? DEFAULT_ENGINES.node,
};
}
for (let targetName in COMMON_TARGETS) {
let _targetDist;
let pointer;
if (
targetName === 'browser' &&
pkg[targetName] != null &&
typeof pkg[targetName] === 'object' &&
pkg.name
) {
// The `browser` field can be a file path or an alias map.
_targetDist = pkg[targetName][pkg.name];
pointer = `/${targetName}/${encodeJSONKeyComponent(pkg.name)}`;
} else {
_targetDist = pkg[targetName];
pointer = `/${targetName}`;
}
// For Flow
let targetDist = _targetDist;
if (typeof targetDist === 'string' || pkgTargets[targetName]) {
let distDir;
let distEntry;
let loc;
invariant(pkgMap != null);
let _descriptor: mixed = pkgTargets[targetName] ?? {};
if (typeof targetDist === 'string') {
distDir = toProjectPath(
this.options.projectRoot,
path.resolve(pkgDir, path.dirname(targetDist)),
);
distEntry = path.basename(targetDist);
loc = {
filePath: nullthrows(pkgFilePath),
...getJSONSourceLocation(pkgMap.pointers[pointer], 'value'),
};
} else {
distDir =
this.options.defaultTargetOptions.distDir ??
toProjectPath(
this.options.projectRoot,
path.join(pkgDir, DEFAULT_DIST_DIRNAME, targetName),
);
}
if (_descriptor == false) {
continue;
}
let descriptor = parseCommonTargetDescriptor(
targetName,
_descriptor,
pkgFilePath,
pkgContents,
);
if (skipTarget(targetName, exclusiveTarget, descriptor.source)) {
targets.set(targetName, null);
continue;
}
if (
distEntry != null &&
!COMMON_TARGETS[targetName].match.test(distEntry)
) {
let contents: string =
typeof pkgContents === 'string'
? pkgContents
: // $FlowFixMe
JSON.stringify(pkgContents, null, '\t');
// $FlowFixMe
let listFormat = new Intl.ListFormat('en-US', {type: 'disjunction'});
let extensions = listFormat.format(
COMMON_TARGETS[targetName].extensions,
);
let ext = path.extname(distEntry);
throw new ThrowableDiagnostic({
diagnostic: {
message: md`Unexpected output file type ${ext} in target "${targetName}"`,
origin: '@parcel/core',
codeFrames: [
{
language: 'json',
filePath: pkgFilePath ?? undefined,
code: contents,
codeHighlights: generateJSONCodeHighlights(contents, [
{
key: pointer,
type: 'value',
message: `File extension must be ${extensions}`,
},
]),
},
],
hints: [
`The "${targetName}" field is meant for libraries. If you meant to output a ${ext} file, either remove the "${targetName}" field or choose a different target name.`,
],
documentationURL:
'https://parceljs.org/features/targets/#library-targets',
},
});
}
if (descriptor.outputFormat === 'global') {
let contents: string =
typeof pkgContents === 'string'
? pkgContents
: // $FlowFixMe
JSON.stringify(pkgContents, null, '\t');
throw new ThrowableDiagnostic({
diagnostic: {
message: md`The "global" output format is not supported in the "${targetName}" target.`,
origin: '@parcel/core',
codeFrames: [
{
language: 'json',
filePath: pkgFilePath ?? undefined,
code: contents,
codeHighlights: generateJSONCodeHighlights(contents, [
{
key: `/targets/${targetName}/outputFormat`,
type: 'value',
},
]),
},
],
hints: [
`The "${targetName}" field is meant for libraries. The outputFormat must be either "commonjs" or "esmodule". Either change or remove the declared outputFormat.`,
],
documentationURL:
'https://parceljs.org/features/targets/#library-targets',
},
});
}
let inferredOutputFormat = this.inferOutputFormat(
distEntry,
descriptor,
targetName,
pkg,
pkgFilePath,
pkgContents,
);
let outputFormat =
descriptor.outputFormat ??
this.options.defaultTargetOptions.outputFormat ??
inferredOutputFormat ??
(targetName === 'module' ? 'esmodule' : 'commonjs');
let isModule = outputFormat === 'esmodule';
if (
targetName === 'main' &&
outputFormat === 'esmodule' &&
inferredOutputFormat !== 'esmodule'
) {
let contents: string =
typeof pkgContents === 'string'
? pkgContents
: // $FlowFixMe
JSON.stringify(pkgContents, null, '\t');
throw new ThrowableDiagnostic({
diagnostic: {
// prettier-ignore
message: md`Output format "esmodule" cannot be used in the "main" target without a .mjs extension or "type": "module" field.`,
origin: '@parcel/core',
codeFrames: [
{
language: 'json',
filePath: pkgFilePath ?? undefined,
code: contents,
codeHighlights: generateJSONCodeHighlights(contents, [
{
key: `/targets/${targetName}/outputFormat`,
type: 'value',
message: 'Declared output format defined here',
},
{
key: '/main',
type: 'value',
message: 'Inferred output format defined here',
},
]),
},
],
hints: [
`Either change the output file extension to .mjs, add "type": "module" to package.json, or remove the declared outputFormat.`,
],
documentationURL:
'https://parceljs.org/features/targets/#library-targets',
},
});
}
if (descriptor.scopeHoist === false) {
let contents: string =
typeof pkgContents === 'string'
? pkgContents
: // $FlowFixMe
JSON.stringify(pkgContents, null, '\t');
throw new ThrowableDiagnostic({
diagnostic: {
message: 'Scope hoisting cannot be disabled for library targets.',
origin: '@parcel/core',
codeFrames: [
{
language: 'json',
filePath: pkgFilePath ?? undefined,
code: contents,
codeHighlights: generateJSONCodeHighlights(contents, [
{
key: `/targets/${targetName}/scopeHoist`,
type: 'value',
},
]),
},
],
hints: [
`The "${targetName}" target is meant for libraries. Either remove the "scopeHoist" option, or use a different target name.`,
],
documentationURL:
'https://parceljs.org/features/targets/#library-targets',
},
});
}
targets.set(targetName, {
name: targetName,
distDir,
distEntry,
publicUrl:
descriptor.publicUrl ?? this.options.defaultTargetOptions.publicUrl,
env: createEnvironment({
engines: descriptor.engines ?? pkgEngines,
context:
descriptor.context ??
(targetName === 'browser'
? 'browser'
: isModule
? moduleContext
: mainContext),
includeNodeModules: descriptor.includeNodeModules ?? false,
outputFormat,
isLibrary: true,
shouldOptimize:
this.options.defaultTargetOptions.shouldOptimize &&
descriptor.optimize === true,
shouldScopeHoist: true,
sourceMap: normalizeSourceMap(this.options, descriptor.sourceMap),
}),
loc: toInternalSourceLocation(this.options.projectRoot, loc),
});
}
}
let customTargets = (Object.keys(pkgTargets): Array<string>).filter(
targetName => !COMMON_TARGETS[targetName],
);
// Custom targets
for (let targetName of customTargets) {
let distPath: mixed = pkg[targetName];
let distDir;
let distEntry;
let loc;
if (distPath == null) {
distDir =
fromProjectPath(
this.options.projectRoot,
this.options.defaultTargetOptions.distDir,
) ?? path.join(pkgDir, DEFAULT_DIST_DIRNAME);
if (customTargets.length >= 2) {
distDir = path.join(distDir, targetName);
}
} else {
if (typeof distPath !== 'string') {
let contents: string =
typeof pkgContents === 'string'
? pkgContents
: // $FlowFixMe
JSON.stringify(pkgContents, null, '\t');
throw new ThrowableDiagnostic({
diagnostic: {
message: md`Invalid distPath for target "${targetName}"`,
origin: '@parcel/core',
codeFrames: [
{
language: 'json',
filePath: pkgFilePath ?? undefined,
code: contents,
codeHighlights: generateJSONCodeHighlights(contents, [
{
key: `/${targetName}`,
type: 'value',
message: 'Expected type string',
},
]),
},
],
},
});
}
distDir = path.resolve(pkgDir, path.dirname(distPath));
distEntry = path.basename(distPath);
invariant(typeof pkgFilePath === 'string');
invariant(pkgMap != null);
loc = {
filePath: pkgFilePath,
...getJSONSourceLocation(pkgMap.pointers[`/${targetName}`], 'value'),
};
}
if (targetName in pkgTargets) {
let descriptor = parsePackageDescriptor(
targetName,
pkgTargets[targetName],
pkgFilePath,
pkgContents,
);
let pkgDir = path.dirname(nullthrows(pkgFilePath));
if (skipTarget(targetName, exclusiveTarget, descriptor.source)) {
targets.set(targetName, null);
continue;
}
let inferredOutputFormat = this.inferOutputFormat(
distEntry,
descriptor,
targetName,
pkg,
pkgFilePath,
pkgContents,
);
if (descriptor.scopeHoist === false && descriptor.isLibrary) {
let contents: string =
typeof pkgContents === 'string'
? pkgContents
: // $FlowFixMe
JSON.stringify(pkgContents, null, '\t');
throw new ThrowableDiagnostic({
diagnostic: {
message: 'Scope hoisting cannot be disabled for library targets.',
origin: '@parcel/core',
codeFrames: [
{
language: 'json',
filePath: pkgFilePath ?? undefined,
code: contents,
codeHighlights: generateJSONCodeHighlights(contents, [
{
key: `/targets/${targetName}/scopeHoist`,
type: 'value',
},
{
key: `/targets/${targetName}/isLibrary`,
type: 'value',
},
]),
},
],
hints: [`Either remove the "scopeHoist" or "isLibrary" option.`],
documentationURL:
'https://parceljs.org/features/targets/#library-targets',
},
});
}
let isLibrary =
descriptor.isLibrary ??
this.options.defaultTargetOptions.isLibrary ??
false;
let shouldScopeHoist = isLibrary
? true
: this.options.defaultTargetOptions.shouldScopeHoist;
targets.set(targetName, {
name: targetName,
distDir: toProjectPath(
this.options.projectRoot,
descriptor.distDir != null
? path.resolve(pkgDir, descriptor.distDir)
: distDir,
),
distEntry,
publicUrl:
descriptor.publicUrl ?? this.options.defaultTargetOptions.publicUrl,
env: createEnvironment({
engines: descriptor.engines ?? pkgEngines,
context: descriptor.context,
includeNodeModules: descriptor.includeNodeModules,
outputFormat:
descriptor.outputFormat ??
this.options.defaultTargetOptions.outputFormat ??
inferredOutputFormat ??
undefined,
isLibrary,
shouldOptimize:
this.options.defaultTargetOptions.shouldOptimize &&
// Libraries are not optimized by default, users must explicitly configure this.
(isLibrary
? descriptor.optimize === true
: descriptor.optimize !== false),
shouldScopeHoist:
shouldScopeHoist && descriptor.scopeHoist !== false,
sourceMap: normalizeSourceMap(this.options, descriptor.sourceMap),
}),
loc: toInternalSourceLocation(this.options.projectRoot, loc),
});
}
}
// If no explicit targets were defined, add a default.
if (targets.size === 0) {
targets.set('default', {
name: 'default',
distDir:
this.options.defaultTargetOptions.distDir ??
toProjectPath(
this.options.projectRoot,
path.join(pkgDir, DEFAULT_DIST_DIRNAME),
),
publicUrl: this.options.defaultTargetOptions.publicUrl,
env: createEnvironment({
engines: pkgEngines,
context,
outputFormat: this.options.defaultTargetOptions.outputFormat,
isLibrary: this.options.defaultTargetOptions.isLibrary,
shouldOptimize: this.options.defaultTargetOptions.shouldOptimize,
shouldScopeHoist:
this.options.defaultTargetOptions.shouldScopeHoist ??
(this.options.mode === 'production' &&
!this.options.defaultTargetOptions.isLibrary),
sourceMap: this.options.defaultTargetOptions.sourceMaps
? {}
: undefined,
}),
});
}
assertNoDuplicateTargets(this.options, targets, pkgFilePath, pkgContents);
return targets;
}
inferOutputFormat(
distEntry: ?FilePath,
descriptor: PackageTargetDescriptor,
targetName: string,
pkg: PackageJSON,
pkgFilePath: ?FilePath,
pkgContents: ?string,
): ?OutputFormat {
// Infer the outputFormat based on package.json properties.
// If the extension is .mjs it's always a module.
// If the extension is .cjs, it's always commonjs.
// If the "type" field is set to "module" and the extension is .js, it's a module.
let ext = distEntry != null ? path.extname(distEntry) : null;
let inferredOutputFormat, inferredOutputFormatField;
switch (ext) {
case '.mjs':
inferredOutputFormat = 'esmodule';
inferredOutputFormatField = `/${targetName}`;
break;
case '.cjs':
inferredOutputFormat = 'commonjs';
inferredOutputFormatField = `/${targetName}`;
break;
case '.js':
if (pkg.type === 'module') {
inferredOutputFormat = 'esmodule';
inferredOutputFormatField = '/type';
}
break;
}
if (
descriptor.outputFormat &&
inferredOutputFormat &&
descriptor.outputFormat !== inferredOutputFormat
) {
let contents: string =
typeof pkgContents === 'string'
? pkgContents
: // $FlowFixMe
JSON.stringify(pkgContents, null, '\t');
let expectedExtensions;
switch (descriptor.outputFormat) {
case 'esmodule':
expectedExtensions = ['.mjs', '.js'];
break;
case 'commonjs':
expectedExtensions = ['.cjs', '.js'];
break;
case 'global':
expectedExtensions = ['.js'];
break;
}