@parcel/types-internal 2.12.1-canary.3182

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js ADDED
@@ -0,0 +1,2096 @@
1
+ // @flow strict-local
2
+
3
+ import type {Readable} from 'stream';
4
+ import type SourceMap from '@parcel/source-map';
5
+ import type {
6
+ Diagnostic,
7
+ Diagnostifiable,
8
+ DiagnosticWithoutOrigin,
9
+ } from '@parcel/diagnostic';
10
+ import type {FeatureFlags} from '@parcel/feature-flags';
11
+ import type {Event, BackendType} from '@parcel/watcher';
12
+
13
+ import type {Cache} from './Cache';
14
+ import type {
15
+ FileSystem,
16
+ FileOptions,
17
+ Stats as FileStats,
18
+ ReaddirOptions,
19
+ Encoding,
20
+ Dirent,
21
+ } from './FileSystem';
22
+ import type {AST as _AST, ConfigResult as _ConfigResult} from './unsafe';
23
+ import type {FilePath} from './FilePath';
24
+ import type {Glob} from './Glob';
25
+ import type {PackageName} from './PackageName';
26
+ import type {
27
+ PackageManager,
28
+ PackageManagerResolveResult,
29
+ Invalidations,
30
+ PackageInstaller,
31
+ ModuleRequest,
32
+ InstallOptions,
33
+ InstallerOptions,
34
+ } from './PackageManager';
35
+ import type {SemverRange} from './SemverRange';
36
+ import type {DependencySpecifier} from './DependencySpecifier';
37
+ import type {
38
+ FileCreateInvalidation,
39
+ GlobInvalidation,
40
+ FileInvalidation,
41
+ FileAboveInvalidation,
42
+ } from './FileCreateInvalidation';
43
+
44
+ export interface TraceMeasurement {
45
+ end(): void;
46
+ }
47
+
48
+ export type {
49
+ FilePath,
50
+ FileSystem,
51
+ FileOptions,
52
+ FileStats,
53
+ ReaddirOptions,
54
+ Encoding,
55
+ Dirent,
56
+ PackageName,
57
+ Glob,
58
+ DependencySpecifier,
59
+ SemverRange,
60
+ FileCreateInvalidation,
61
+ GlobInvalidation,
62
+ FileInvalidation,
63
+ FileAboveInvalidation,
64
+ PackageManager,
65
+ PackageManagerResolveResult,
66
+ Invalidations,
67
+ PackageInstaller,
68
+ ModuleRequest,
69
+ InstallOptions,
70
+ InstallerOptions,
71
+ Cache,
72
+ };
73
+
74
+ /** Plugin-specific AST, <code>any</code> */
75
+ export type AST = _AST;
76
+ export type ConfigResult = _ConfigResult;
77
+ /** Plugin-specific config result, <code>any</code> */
78
+ export type ConfigResultWithFilePath<T> = {|
79
+ contents: T,
80
+ filePath: FilePath,
81
+ |};
82
+ /** <code>process.env</code> */
83
+ export type EnvMap = typeof process.env;
84
+
85
+ export type JSONValue =
86
+ | null
87
+ | void // ? Is this okay?
88
+ | boolean
89
+ | number
90
+ | string
91
+ | Array<JSONValue>
92
+ | JSONObject;
93
+
94
+ /** A JSON object (as in "map") */
95
+ export type JSONObject = {[key: string]: JSONValue, ...};
96
+
97
+ export type Semver = string;
98
+ /** A pipeline as specified in the config mapping to <code>T</code> */
99
+ export type GlobMap<T> = {[Glob]: T, ...};
100
+
101
+ export type RawParcelConfigPipeline = Array<PackageName>;
102
+
103
+ export type HMROptions = {port?: number, host?: string, ...};
104
+
105
+ /** The format of .parcelrc */
106
+ export type RawParcelConfig = {|
107
+ extends?: PackageName | FilePath | Array<PackageName | FilePath>,
108
+ resolvers?: RawParcelConfigPipeline,
109
+ transformers?: {[Glob]: RawParcelConfigPipeline, ...},
110
+ bundler?: PackageName,
111
+ namers?: RawParcelConfigPipeline,
112
+ runtimes?: RawParcelConfigPipeline,
113
+ packagers?: {[Glob]: PackageName, ...},
114
+ optimizers?: {[Glob]: RawParcelConfigPipeline, ...},
115
+ compressors?: {[Glob]: RawParcelConfigPipeline, ...},
116
+ reporters?: RawParcelConfigPipeline,
117
+ validators?: {[Glob]: RawParcelConfigPipeline, ...},
118
+ |};
119
+
120
+ /** A .parcelrc where all package names are resolved */
121
+ export type ResolvedParcelConfigFile = {|
122
+ ...RawParcelConfig,
123
+ +filePath: FilePath,
124
+ +resolveFrom?: FilePath,
125
+ |};
126
+
127
+ /** Corresponds to <code>pkg#engines</code> */
128
+ export type Engines = {
129
+ +browsers?: string | Array<string>,
130
+ +electron?: SemverRange,
131
+ +node?: SemverRange,
132
+ +parcel?: SemverRange,
133
+ ...
134
+ };
135
+
136
+ /** Corresponds to <code>pkg#targets.*.sourceMap</code> */
137
+ export type TargetSourceMapOptions = {|
138
+ +sourceRoot?: string,
139
+ +inline?: boolean,
140
+ +inlineSources?: boolean,
141
+ |};
142
+
143
+ /**
144
+ * A parsed version of PackageTargetDescriptor
145
+ */
146
+ export interface Target {
147
+ /** The output filename of the entry */
148
+ +distEntry: ?FilePath;
149
+ /** The output folder */
150
+ +distDir: FilePath;
151
+ +env: Environment;
152
+ +name: string;
153
+ +publicUrl: string;
154
+ /** The location that created this Target, e.g. `package.json#main`*/
155
+ +loc: ?SourceLocation;
156
+ }
157
+
158
+ /** In which environment the output should run (influces e.g. bundle loaders) */
159
+ export type EnvironmentContext =
160
+ | 'browser'
161
+ | 'web-worker'
162
+ | 'service-worker'
163
+ | 'worklet'
164
+ | 'node'
165
+ | 'electron-main'
166
+ | 'electron-renderer';
167
+
168
+ /** The JS module format for the bundle output */
169
+ export type OutputFormat = 'esmodule' | 'commonjs' | 'global';
170
+
171
+ /**
172
+ * The format of <code>pkg#targets.*</code>
173
+ *
174
+ * See Environment and Target.
175
+ */
176
+ export type PackageTargetDescriptor = {|
177
+ +context?: EnvironmentContext,
178
+ +engines?: Engines,
179
+ +includeNodeModules?:
180
+ | boolean
181
+ | Array<PackageName>
182
+ | {[PackageName]: boolean, ...},
183
+ +outputFormat?: OutputFormat,
184
+ +publicUrl?: string,
185
+ +distDir?: FilePath,
186
+ +sourceMap?: boolean | TargetSourceMapOptions,
187
+ +isLibrary?: boolean,
188
+ +optimize?: boolean,
189
+ +scopeHoist?: boolean,
190
+ +source?: FilePath | Array<FilePath>,
191
+ |};
192
+
193
+ /**
194
+ * The target format when using the JS API.
195
+ *
196
+ * (Same as PackageTargetDescriptor, but <code>distDir</code> is required.)
197
+ */
198
+ export type TargetDescriptor = {|
199
+ ...PackageTargetDescriptor,
200
+ +distDir: FilePath,
201
+ +distEntry?: FilePath,
202
+ |};
203
+
204
+ export type SourceType = 'script' | 'module';
205
+
206
+ /**
207
+ * This is used when creating an Environment (see that).
208
+ */
209
+ export type EnvironmentOptions = {|
210
+ +context?: EnvironmentContext,
211
+ +engines?: Engines,
212
+ +includeNodeModules?:
213
+ | boolean
214
+ | Array<PackageName>
215
+ | {[PackageName]: boolean, ...},
216
+ +outputFormat?: OutputFormat,
217
+ +sourceType?: SourceType,
218
+ +isLibrary?: boolean,
219
+ +shouldOptimize?: boolean,
220
+ +shouldScopeHoist?: boolean,
221
+ +sourceMap?: ?TargetSourceMapOptions,
222
+ +loc?: ?SourceLocation,
223
+ |};
224
+
225
+ /**
226
+ * A resolved browserslist, e.g.:
227
+ * <pre><code>
228
+ * {
229
+ * edge: '76',
230
+ * firefox: '67',
231
+ * chrome: '63',
232
+ * safari: '11.1',
233
+ * opera: '50',
234
+ * }
235
+ * </code></pre>
236
+ */
237
+ export type VersionMap = {
238
+ [string]: string,
239
+ ...
240
+ };
241
+
242
+ export type EnvironmentFeature =
243
+ | 'esmodules'
244
+ | 'dynamic-import'
245
+ | 'worker-module'
246
+ | 'service-worker-module'
247
+ | 'import-meta-url'
248
+ | 'arrow-functions'
249
+ | 'global-this';
250
+
251
+ /**
252
+ * Defines the environment in for the output bundle
253
+ */
254
+ export interface Environment {
255
+ +id: string;
256
+ +context: EnvironmentContext;
257
+ +engines: Engines;
258
+ /** Whether to include all/none packages \
259
+ * (<code>true / false</code>), an array of package names to include, or an object \
260
+ * (of a package is not specified, it's included).
261
+ */
262
+ +includeNodeModules:
263
+ | boolean
264
+ | Array<PackageName>
265
+ | {[PackageName]: boolean, ...};
266
+ +outputFormat: OutputFormat;
267
+ +sourceType: SourceType;
268
+ /** Whether this is a library build (e.g. less loaders) */
269
+ +isLibrary: boolean;
270
+ /** Whether the output should be minified. */
271
+ +shouldOptimize: boolean;
272
+ /** Whether scope hoisting is enabled. */
273
+ +shouldScopeHoist: boolean;
274
+ +sourceMap: ?TargetSourceMapOptions;
275
+ +loc: ?SourceLocation;
276
+
277
+ /** Whether <code>context</code> specifies a browser context. */
278
+ isBrowser(): boolean;
279
+ /** Whether <code>context</code> specifies a node context. */
280
+ isNode(): boolean;
281
+ /** Whether <code>context</code> specifies an electron context. */
282
+ isElectron(): boolean;
283
+ /** Whether <code>context</code> specifies a worker context. */
284
+ isWorker(): boolean;
285
+ /** Whether <code>context</code> specifies a worklet context. */
286
+ isWorklet(): boolean;
287
+ /** Whether <code>context</code> specifies an isolated context (can't access other loaded ancestor bundles). */
288
+ isIsolated(): boolean;
289
+ matchesEngines(minVersions: VersionMap, defaultValue?: boolean): boolean;
290
+ supports(feature: EnvironmentFeature, defaultValue?: boolean): boolean;
291
+ }
292
+
293
+ /**
294
+ * Format of <code>pkg#dependencies</code>, <code>pkg#devDependencies</code>, <code>pkg#peerDependencies</code>
295
+ */
296
+ type PackageDependencies = {|
297
+ [PackageName]: Semver,
298
+ |};
299
+
300
+ /**
301
+ * Format of <code>package.json</code>
302
+ */
303
+ export type PackageJSON = {
304
+ name: PackageName,
305
+ version: Semver,
306
+ type?: 'module',
307
+ main?: FilePath,
308
+ module?: FilePath,
309
+ types?: FilePath,
310
+ browser?: FilePath | {[FilePath]: FilePath | boolean, ...},
311
+ source?: FilePath | Array<FilePath>,
312
+ alias?: {
313
+ [PackageName | FilePath | Glob]:
314
+ | PackageName
315
+ | FilePath
316
+ | {|global: string|},
317
+ ...
318
+ },
319
+ browserslist?: Array<string> | {[string]: Array<string>},
320
+ engines?: Engines,
321
+ targets?: {[string]: PackageTargetDescriptor, ...},
322
+ dependencies?: PackageDependencies,
323
+ devDependencies?: PackageDependencies,
324
+ peerDependencies?: PackageDependencies,
325
+ sideEffects?: boolean | FilePath | Array<FilePath>,
326
+ bin?: string | {|[string]: FilePath|},
327
+ ...
328
+ };
329
+
330
+ export type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'verbose';
331
+ export type BuildMode = 'development' | 'production' | string;
332
+ export type DetailedReportOptions = {|
333
+ assetsPerBundle?: number,
334
+ |};
335
+
336
+ declare type GlobPattern = string;
337
+
338
+ export type InitialParcelOptionsInternal<WorkerFarm> = {|
339
+ +entries?: FilePath | Array<FilePath>,
340
+ +config?: DependencySpecifier,
341
+ +defaultConfig?: DependencySpecifier,
342
+ +env?: EnvMap,
343
+ +targets?: ?(Array<string> | {+[string]: TargetDescriptor, ...}),
344
+
345
+ +shouldDisableCache?: boolean,
346
+ +cacheDir?: FilePath,
347
+ +watchDir?: FilePath,
348
+ +watchBackend?: BackendType,
349
+ +watchIgnore?: Array<FilePath | GlobPattern>,
350
+ +mode?: BuildMode,
351
+ +hmrOptions?: ?HMROptions,
352
+ +shouldContentHash?: boolean,
353
+ +serveOptions?: InitialServerOptions | false,
354
+ +shouldAutoInstall?: boolean,
355
+ +logLevel?: LogLevel,
356
+ +shouldProfile?: boolean,
357
+ +shouldTrace?: boolean,
358
+ +shouldPatchConsole?: boolean,
359
+ +shouldBuildLazily?: boolean,
360
+ +lazyIncludes?: string[],
361
+ +lazyExcludes?: string[],
362
+ +shouldBundleIncrementally?: boolean,
363
+ +unstableFileInvalidations?: Array<Event>,
364
+
365
+ +inputFS?: FileSystem,
366
+ +outputFS?: FileSystem,
367
+ +cache?: Cache,
368
+ +workerFarm?: WorkerFarm,
369
+ +packageManager?: PackageManager,
370
+ +detailedReport?: ?DetailedReportOptions,
371
+
372
+ +defaultTargetOptions?: {|
373
+ +shouldOptimize?: boolean,
374
+ +shouldScopeHoist?: boolean,
375
+ +sourceMaps?: boolean,
376
+ +publicUrl?: string,
377
+ +distDir?: FilePath,
378
+ +engines?: Engines,
379
+ +outputFormat?: OutputFormat,
380
+ +isLibrary?: boolean,
381
+ |},
382
+
383
+ +additionalReporters?: Array<{|
384
+ packageName: DependencySpecifier,
385
+ resolveFrom: FilePath,
386
+ |}>,
387
+
388
+ +featureFlags?: FeatureFlags,
389
+
390
+ // throwErrors
391
+ // global?
392
+ |};
393
+
394
+ export type InitialServerOptions = {|
395
+ +publicUrl?: string,
396
+ +host?: string,
397
+ +port: number,
398
+ +https?: HTTPSOptions | boolean,
399
+ |};
400
+
401
+ export interface PluginOptions {
402
+ +mode: BuildMode;
403
+ +env: EnvMap;
404
+ +hmrOptions: ?HMROptions;
405
+ +serveOptions: ServerOptions | false;
406
+ +shouldBuildLazily: boolean;
407
+ +shouldAutoInstall: boolean;
408
+ +logLevel: LogLevel;
409
+ +projectRoot: FilePath;
410
+ +cacheDir: FilePath;
411
+ +inputFS: FileSystem;
412
+ +outputFS: FileSystem;
413
+ +packageManager: PackageManager;
414
+ +instanceId: string;
415
+ +detailedReport: ?DetailedReportOptions;
416
+ +featureFlags: FeatureFlags;
417
+ }
418
+
419
+ export type ServerOptions = {|
420
+ +distDir: FilePath,
421
+ +host?: string,
422
+ +port: number,
423
+ +https?: HTTPSOptions | boolean,
424
+ +publicUrl?: string,
425
+ |};
426
+
427
+ export type HTTPSOptions = {|
428
+ +cert: FilePath,
429
+ +key: FilePath,
430
+ |};
431
+
432
+ /**
433
+ * Source locations are 1-based, meaning lines and columns start at 1
434
+ */
435
+ export type SourceLocation = {|
436
+ +filePath: string,
437
+ /** inclusive */
438
+ +start: {|
439
+ +line: number,
440
+ +column: number,
441
+ |},
442
+ /** exclusive */
443
+ +end: {|
444
+ +line: number,
445
+ +column: number,
446
+ |},
447
+ |};
448
+
449
+ /**
450
+ * An object that plugins can write arbitrary data to.
451
+ */
452
+ export type Meta = JSONObject;
453
+
454
+ /**
455
+ * An identifier in an asset (likely imported/exported).
456
+ */
457
+ export type Symbol = string;
458
+
459
+ /**
460
+ * A map of export names to the corresponding asset's local variable names.
461
+ */
462
+ export interface AssetSymbols // eslint-disable-next-line no-undef
463
+ extends Iterable<
464
+ [Symbol, {|local: Symbol, loc: ?SourceLocation, meta?: ?Meta|}],
465
+ > {
466
+ /**
467
+ * The exports of the asset are unknown, rather than just empty.
468
+ * This is the default state.
469
+ */
470
+ +isCleared: boolean;
471
+ get(exportSymbol: Symbol): ?{|
472
+ local: Symbol,
473
+ loc: ?SourceLocation,
474
+ meta?: ?Meta,
475
+ |};
476
+ hasExportSymbol(exportSymbol: Symbol): boolean;
477
+ hasLocalSymbol(local: Symbol): boolean;
478
+ exportSymbols(): Iterable<Symbol>;
479
+ }
480
+
481
+ export interface MutableAssetSymbols extends AssetSymbols {
482
+ /**
483
+ * Initializes the map, sets isCleared to false.
484
+ */
485
+ ensure(): void;
486
+ set(
487
+ exportSymbol: Symbol,
488
+ local: Symbol,
489
+ loc: ?SourceLocation,
490
+ meta?: ?Meta,
491
+ ): void;
492
+ delete(exportSymbol: Symbol): void;
493
+ }
494
+
495
+ /**
496
+ * isWeak means: the symbol is not used by the parent asset itself and is merely reexported
497
+ */
498
+ export interface MutableDependencySymbols // eslint-disable-next-line no-undef
499
+ extends Iterable<
500
+ [
501
+ Symbol,
502
+ {|local: Symbol, loc: ?SourceLocation, isWeak: boolean, meta?: ?Meta|},
503
+ ],
504
+ > {
505
+ /**
506
+ * Initializes the map, sets isCleared to false.
507
+ */
508
+ ensure(): void;
509
+ /**
510
+ * The symbols that are imports are unknown, rather than just empty.
511
+ * This is the default state.
512
+ */
513
+ +isCleared: boolean;
514
+ get(exportSymbol: Symbol): ?{|
515
+ local: Symbol,
516
+ loc: ?SourceLocation,
517
+ isWeak: boolean,
518
+ meta?: ?Meta,
519
+ |};
520
+ hasExportSymbol(exportSymbol: Symbol): boolean;
521
+ hasLocalSymbol(local: Symbol): boolean;
522
+ exportSymbols(): Iterable<Symbol>;
523
+ set(
524
+ exportSymbol: Symbol,
525
+ local: Symbol,
526
+ loc: ?SourceLocation,
527
+ isWeak: ?boolean,
528
+ ): void;
529
+ delete(exportSymbol: Symbol): void;
530
+ }
531
+
532
+ export type DependencyPriority = 'sync' | 'parallel' | 'lazy';
533
+ export type SpecifierType = 'commonjs' | 'esm' | 'url' | 'custom';
534
+
535
+ /**
536
+ * Used when creating a Dependency, see that.
537
+ * @section transformer
538
+ */
539
+ export type DependencyOptions = {|
540
+ /** The specifier used to resolve the dependency. */
541
+ +specifier: DependencySpecifier,
542
+ /**
543
+ * How the specifier should be interpreted.
544
+ * - esm: An ES module specifier. It is parsed as a URL, but bare specifiers are treated as node_modules.
545
+ * - commonjs: A CommonJS specifier. It is not parsed as a URL.
546
+ * - url: A URL that works as in a browser. Bare specifiers are treated as relative URLs.
547
+ * - custom: A custom specifier. Must be handled by a custom resolver plugin.
548
+ */
549
+ +specifierType: SpecifierType,
550
+ /**
551
+ * When the dependency should be loaded.
552
+ * - sync: The dependency should be resolvable synchronously. The resolved asset will be placed
553
+ * in the same bundle as the parent, or another bundle that's already on the page.
554
+ * - parallel: The dependency should be placed in a separate bundle that's loaded in parallel
555
+ * with the current bundle.
556
+ * - lazy: The dependency should be placed in a separate bundle that's loaded later.
557
+ * @default 'sync'
558
+ */
559
+ +priority?: DependencyPriority,
560
+ /**
561
+ * Controls the behavior of the bundle the resolved asset is placed into. Use in combination with `priority`
562
+ * to determine when the bundle is loaded.
563
+ * - inline: The resolved asset will be placed into a new inline bundle. Inline bundles are not written
564
+ * to a separate file, but embedded into the parent bundle.
565
+ * - isolated: The resolved asset will be isolated from its parents in a separate bundle.
566
+ * Shared assets will be duplicated.
567
+ */
568
+ +bundleBehavior?: BundleBehavior,
569
+ /**
570
+ * When the dependency is a bundle entry (priority is "parallel" or "lazy"), this controls the naming
571
+ * of that bundle. `needsStableName` indicates that the name should be stable over time, even when the
572
+ * content of the bundle changes. This is useful for entries that a user would manually enter the URL
573
+ * for, as well as for things like service workers or RSS feeds, where the URL must remain consistent
574
+ * over time.
575
+ */
576
+ +needsStableName?: boolean,
577
+ /** Whether the dependency is optional. If the dependency cannot be resolved, this will not fail the build. */
578
+ +isOptional?: boolean,
579
+ /** The location within the source file where the dependency was found. */
580
+ +loc?: SourceLocation,
581
+ /** The environment of the dependency. */
582
+ +env?: EnvironmentOptions,
583
+ /**
584
+ * A list of custom conditions to use when resolving package.json "exports" and "imports".
585
+ * This is combined with the conditions from the environment. However, it overrides the
586
+ * default "import" and "require" conditions inferred from the specifierType. To include those
587
+ * in addition to custom conditions, explicitly add them to this list.
588
+ */
589
+ +packageConditions?: Array<string>,
590
+ /** Plugin-specific metadata for the dependency. */
591
+ +meta?: Meta,
592
+ /** The pipeline defined in .parcelrc that the dependency should be processed with. */
593
+ +pipeline?: string,
594
+ /**
595
+ * The file path where the dependency should be resolved from.
596
+ * By default, this is the path of the source file where the dependency was specified.
597
+ */
598
+ +resolveFrom?: FilePath,
599
+ /** The semver version range expected for the dependency. */
600
+ +range?: SemverRange,
601
+ /** The symbols within the resolved module that the source file depends on. */
602
+ +symbols?: $ReadOnlyMap<
603
+ Symbol,
604
+ {|local: Symbol, loc: ?SourceLocation, isWeak: boolean, meta?: Meta|},
605
+ >,
606
+ |};
607
+
608
+ /**
609
+ * A Dependency denotes a connection between two assets \
610
+ * (likely some effect from the importee is expected - be it a side effect or a value is being imported).
611
+ *
612
+ * @section transformer
613
+ */
614
+ export interface Dependency {
615
+ /** The id of the dependency. */
616
+ +id: string;
617
+ /** The specifier used to resolve the dependency. */
618
+ +specifier: DependencySpecifier;
619
+ /**
620
+ * How the specifier should be interpreted.
621
+ * - esm: An ES module specifier. It is parsed as a URL, but bare specifiers are treated as node_modules.
622
+ * - commonjs: A CommonJS specifier. It is not parsed as a URL.
623
+ * - url: A URL that works as in a browser. Bare specifiers are treated as relative URLs.
624
+ * - custom: A custom specifier. Must be handled by a custom resolver plugin.
625
+ */
626
+ +specifierType: SpecifierType;
627
+ /**
628
+ * When the dependency should be loaded.
629
+ * - sync: The dependency should be resolvable synchronously. The resolved asset will be placed
630
+ * in the same bundle as the parent, or another bundle that's already on the page.
631
+ * - parallel: The dependency should be placed in a separate bundle that's loaded in parallel
632
+ * with the current bundle.
633
+ * - lazy: The dependency should be placed in a separate bundle that's loaded later.
634
+ * @default 'sync'
635
+ */
636
+ +priority: DependencyPriority;
637
+ /**
638
+ * Controls the behavior of the bundle the resolved asset is placed into. Use in combination with `priority`
639
+ * to determine when the bundle is loaded.
640
+ * - inline: The resolved asset will be placed into a new inline bundle. Inline bundles are not written
641
+ * to a separate file, but embedded into the parent bundle.
642
+ * - isolated: The resolved asset will be isolated from its parents in a separate bundle.
643
+ * Shared assets will be duplicated.
644
+ */
645
+ +bundleBehavior: ?BundleBehavior;
646
+ /**
647
+ * When the dependency is a bundle entry (priority is "parallel" or "lazy"), this controls the naming
648
+ * of that bundle. `needsStableName` indicates that the name should be stable over time, even when the
649
+ * content of the bundle changes. This is useful for entries that a user would manually enter the URL
650
+ * for, as well as for things like service workers or RSS feeds, where the URL must remain consistent
651
+ * over time.
652
+ */
653
+ +needsStableName: boolean;
654
+ /** Whether the dependency is optional. If the dependency cannot be resolved, this will not fail the build. */
655
+ +isOptional: boolean;
656
+ /** Whether the dependency is an entry. */
657
+ +isEntry: boolean;
658
+ /** The location within the source file where the dependency was found. */
659
+ +loc: ?SourceLocation;
660
+ /** The environment of the dependency. */
661
+ +env: Environment;
662
+ /**
663
+ * A list of custom conditions to use when resolving package.json "exports" and "imports".
664
+ * This is combined with the conditions from the environment. However, it overrides the
665
+ * default "import" and "require" conditions inferred from the specifierType. To include those
666
+ * in addition to custom conditions, explicitly add them to this list.
667
+ */
668
+ +packageConditions: ?Array<string>;
669
+ /** Plugin-specific metadata for the dependency. */
670
+ +meta: Meta;
671
+ /** If this is an entry, this is the target that is associated with that entry. */
672
+ +target: ?Target;
673
+ /** The id of the asset with this dependency. */
674
+ +sourceAssetId: ?string;
675
+ /** The file path of the asset with this dependency. */
676
+ +sourcePath: ?FilePath;
677
+ /** The type of the asset that referenced this dependency. */
678
+ +sourceAssetType: ?string;
679
+ /**
680
+ * The file path where the dependency should be resolved from.
681
+ * By default, this is the path of the source file where the dependency was specified.
682
+ */
683
+ +resolveFrom: ?FilePath;
684
+ /** The semver version range expected for the dependency. */
685
+ +range: ?SemverRange;
686
+ /** The pipeline defined in .parcelrc that the dependency should be processed with. */
687
+ +pipeline: ?string;
688
+
689
+ // TODO make immutable
690
+ /** The symbols within the resolved module that the source file depends on. */
691
+ +symbols: MutableDependencySymbols;
692
+ }
693
+
694
+ export type File = {|
695
+ +filePath: FilePath,
696
+ +hash?: string,
697
+ |};
698
+
699
+ /**
700
+ * @section transformer
701
+ */
702
+ export type ASTGenerator = {|
703
+ type: string,
704
+ version: Semver,
705
+ |};
706
+
707
+ export type BundleBehavior = 'inline' | 'isolated';
708
+
709
+ export type ParcelTransformOptions = {|
710
+ filePath: FilePath,
711
+ code?: string,
712
+ env?: EnvironmentOptions,
713
+ query?: ?string,
714
+ |};
715
+
716
+ export type ParcelResolveOptions = {|
717
+ specifier: DependencySpecifier,
718
+ specifierType: SpecifierType,
719
+ env?: EnvironmentOptions,
720
+ resolveFrom?: FilePath,
721
+ |};
722
+
723
+ export type ParcelResolveResult = {|
724
+ filePath: FilePath,
725
+ code?: string,
726
+ query?: ?string,
727
+ sideEffects?: boolean,
728
+ |};
729
+
730
+ /**
731
+ * An asset represents a file or part of a file. It may represent any data type, including source code,
732
+ * binary data, etc. Assets may exist in the file system or may be virtual.
733
+ *
734
+ * @section transformer
735
+ */
736
+ export interface BaseAsset {
737
+ /** The id of the asset. */
738
+ +id: string;
739
+ /** The file system where the source is located. */
740
+ +fs: FileSystem;
741
+ /** The file path of the asset. */
742
+ +filePath: FilePath;
743
+ /**
744
+ * The asset's type. This initially corresponds to the source file extension,
745
+ * but it may be changed during transformation.
746
+ */
747
+ +type: string;
748
+ /** The transformer options for the asset from the dependency query string. */
749
+ +query: URLSearchParams;
750
+ /** The environment of the asset. */
751
+ +env: Environment;
752
+ /**
753
+ * Whether this asset is part of the project, and not an external dependency (e.g. in node_modules).
754
+ * This indicates that transformation using the project's configuration should be applied.
755
+ */
756
+ +isSource: boolean;
757
+ /** Plugin-specific metadata for the asset. */
758
+ +meta: Meta;
759
+ /**
760
+ * Controls which bundle the asset is placed into.
761
+ * - inline: The asset will be placed into a new inline bundle. Inline bundles are not written
762
+ * to a separate file, but embedded into the parent bundle.
763
+ * - isolated: The asset will be isolated from its parents in a separate bundle. Shared assets
764
+ * will be duplicated.
765
+ */
766
+ +bundleBehavior: ?BundleBehavior;
767
+ /**
768
+ * If the asset is used as a bundle entry, this controls whether that bundle can be split
769
+ * into multiple, or whether all of the dependencies must be placed in a single bundle.
770
+ */
771
+ +isBundleSplittable: boolean;
772
+ /**
773
+ * Whether this asset can be omitted if none of its exports are being used.
774
+ * This is initially set by the resolver, but can be overridden by transformers.
775
+ */
776
+ +sideEffects: boolean;
777
+ /**
778
+ * When a transformer returns multiple assets, it can give them unique keys to identify them.
779
+ * This can be used to find assets during packaging, or to create dependencies between multiple
780
+ * assets returned by a transformer by using the unique key as the dependency specifier.
781
+ */
782
+ +uniqueKey: ?string;
783
+ /** The type of the AST. */
784
+ +astGenerator: ?ASTGenerator;
785
+ /** The pipeline defined in .parcelrc that the asset should be processed with. */
786
+ +pipeline: ?string;
787
+ /** The symbols that the asset exports. */
788
+ +symbols: AssetSymbols;
789
+ /** Returns the current AST. */
790
+ getAST(): Promise<?AST>;
791
+ /** Returns the asset contents as a string. */
792
+ getCode(): Promise<string>;
793
+ /** Returns the asset contents as a buffer. */
794
+ getBuffer(): Promise<Buffer>;
795
+ /** Returns the asset contents as a stream. */
796
+ getStream(): Readable;
797
+ /** Returns the source map for the asset, if available. */
798
+ getMap(): Promise<?SourceMap>;
799
+ /** Returns a buffer representation of the source map, if available. */
800
+ getMapBuffer(): Promise<?Buffer>;
801
+ /** Returns a list of dependencies for the asset. */
802
+ getDependencies(): $ReadOnlyArray<Dependency>;
803
+ }
804
+
805
+ /**
806
+ * A mutable Asset, available during transformation.
807
+ * @section transformer
808
+ */
809
+ export interface MutableAsset extends BaseAsset {
810
+ /**
811
+ * The asset's type. This initially corresponds to the source file extension,
812
+ * but it may be changed during transformation.
813
+ */
814
+ type: string;
815
+ /**
816
+ * Controls which bundle the asset is placed into.
817
+ * - inline: The asset will be placed into a new inline bundle. Inline bundles are not written
818
+ * to a separate file, but embedded into the parent bundle.
819
+ * - isolated: The asset will be isolated from its parents in a separate bundle. Shared assets
820
+ * will be duplicated.
821
+ */
822
+ bundleBehavior: ?BundleBehavior;
823
+ /**
824
+ * If the asset is used as a bundle entry, this controls whether that bundle can be split
825
+ * into multiple, or whether all of the dependencies must be placed in a single bundle.
826
+ * @default true
827
+ */
828
+ isBundleSplittable: boolean;
829
+ /**
830
+ * Whether this asset can be omitted if none of its exports are being used.
831
+ * This is initially set by the resolver, but can be overridden by transformers.
832
+ */
833
+ sideEffects: boolean;
834
+ /**
835
+ * When a transformer returns multiple assets, it can give them unique keys to identify them.
836
+ * This can be used to find assets during packaging, or to create dependencies between multiple
837
+ * assets returned by a transformer by using the unique key as the dependency specifier.
838
+ */
839
+ uniqueKey: ?string;
840
+ /** The symbols that the asset exports. */
841
+ +symbols: MutableAssetSymbols;
842
+
843
+ /** Adds a dependency to the asset. */
844
+ addDependency(DependencyOptions): string;
845
+ /**
846
+ * Adds a url dependency to the asset.
847
+ * This is a shortcut for addDependency that sets the specifierType to 'url' and priority to 'lazy'.
848
+ */
849
+ addURLDependency(url: string, opts: $Shape<DependencyOptions>): string;
850
+ /** Invalidates the transformation when the given file is modified or deleted. */
851
+ invalidateOnFileChange(FilePath): void;
852
+ /** Invalidates the transformation when matched files are created. */
853
+ invalidateOnFileCreate(FileCreateInvalidation): void;
854
+ /** Invalidates the transformation when the given environment variable changes. */
855
+ invalidateOnEnvChange(string): void;
856
+ /** Invalidates the transformation only when Parcel restarts. */
857
+ invalidateOnStartup(): void;
858
+ /** Invalidates the transformation on every build. */
859
+ invalidateOnBuild(): void;
860
+ /** Sets the asset contents as a string. */
861
+ setCode(string): void;
862
+ /** Sets the asset contents as a buffer. */
863
+ setBuffer(Buffer): void;
864
+ /** Sets the asset contents as a stream. */
865
+ setStream(Readable): void;
866
+ /** Sets the asset's AST. */
867
+ setAST(AST): void;
868
+ /** Returns whether the AST has been modified. */
869
+ isASTDirty(): boolean;
870
+ /** Sets the asset's source map. */
871
+ setMap(?SourceMap): void;
872
+ setEnvironment(opts: EnvironmentOptions): void;
873
+ }
874
+
875
+ /**
876
+ * An immutable Asset, available after transformation.
877
+ * @section transformer
878
+ */
879
+ export interface Asset extends BaseAsset {
880
+ /** Statistics about the asset. */
881
+ +stats: Stats;
882
+ }
883
+
884
+ export type DevDepOptions = {|
885
+ specifier: DependencySpecifier,
886
+ resolveFrom: FilePath,
887
+ range?: ?SemverRange,
888
+ /**
889
+ * When this dev dependency is invalidated, also invalidate these dependencies.
890
+ * This is useful if the parcel plugin or another parent dependency
891
+ * has its own cache for this dev dependency other than Node's require cache.
892
+ */
893
+ additionalInvalidations?: Array<{|
894
+ specifier: DependencySpecifier,
895
+ resolveFrom: FilePath,
896
+ range?: ?SemverRange,
897
+ |}>,
898
+ |};
899
+
900
+ /**
901
+ * @section transformer
902
+ */
903
+ export interface Config {
904
+ /**
905
+ * Whether this config is part of the project, and not an external dependency (e.g. in node_modules).
906
+ * This indicates that transformation using the project's configuration should be applied.
907
+ */
908
+ +isSource: boolean;
909
+ /** The path of the file to start searching for config from. */
910
+ +searchPath: FilePath;
911
+ /** The environment */
912
+ +env: Environment;
913
+
914
+ /** Invalidates the config when the given file is modified or deleted. */
915
+ invalidateOnFileChange(FilePath): void;
916
+ /** Invalidates the config when matched files are created. */
917
+ invalidateOnFileCreate(FileCreateInvalidation): void;
918
+ /** Invalidates the config when the given environment variable changes. */
919
+ invalidateOnEnvChange(string): void;
920
+ /** Invalidates the config only when Parcel restarts. */
921
+ invalidateOnStartup(): void;
922
+ /** Invalidates the config on every build. */
923
+ invalidateOnBuild(): void;
924
+ /**
925
+ * Adds a dev dependency to the config. If the dev dependency or any of its
926
+ * dependencies change, the config will be invalidated.
927
+ */
928
+ addDevDependency(DevDepOptions): void;
929
+ /**
930
+ * Sets the cache key for the config. By default, this is computed as a hash of the
931
+ * files passed to invalidateOnFileChange or loaded by getConfig. If none, then a
932
+ * hash of the result returned from loadConfig is used. This method can be used to
933
+ * override this behavior and explicitly control the cache key. This can be useful
934
+ * in cases where only part of a file is used to avoid unnecessary invalidations,
935
+ * or when the result is not hashable (i.e. contains non-serializable properties like functions).
936
+ */
937
+ setCacheKey(string): void;
938
+
939
+ /**
940
+ * Searches for config files with the given names in all parent directories
941
+ * of the config's searchPath.
942
+ */
943
+ getConfig<T>(
944
+ filePaths: Array<FilePath>,
945
+ options?: {|
946
+ packageKey?: string,
947
+ parse?: boolean,
948
+ exclude?: boolean,
949
+ |},
950
+ ): Promise<?ConfigResultWithFilePath<T>>;
951
+ /**
952
+ * Searches for config files with the given names in all parent directories
953
+ * of the passed searchPath.
954
+ */
955
+ getConfigFrom<T>(
956
+ searchPath: FilePath,
957
+ filePaths: Array<FilePath>,
958
+ options?: {|
959
+ packageKey?: string,
960
+ parse?: boolean,
961
+ exclude?: boolean,
962
+ |},
963
+ ): Promise<?ConfigResultWithFilePath<T>>;
964
+ /** Finds the nearest package.json from the config's searchPath. */
965
+ getPackage(): Promise<?PackageJSON>;
966
+ }
967
+
968
+ export type Stats = {|
969
+ time: number,
970
+ size: number,
971
+ |};
972
+
973
+ /**
974
+ * @section transformer
975
+ */
976
+ export type GenerateOutput = {|
977
+ +content: Blob,
978
+ +map?: ?SourceMap,
979
+ |};
980
+
981
+ export type Blob = string | Buffer | Readable;
982
+
983
+ /**
984
+ * Transformers can return multiple result objects to create new assets.
985
+ * For example, a file may contain multiple parts of different types,
986
+ * which should be processed by their respective transformation pipelines.
987
+ *
988
+ * @section transformer
989
+ */
990
+ export type TransformerResult = {|
991
+ /** The asset's type. */
992
+ +type: string,
993
+ /** The content of the asset. Either content or an AST is required. */
994
+ +content?: ?Blob,
995
+ /** The asset's AST. Either content or an AST is required. */
996
+ +ast?: ?AST,
997
+ /** The source map for the asset. */
998
+ +map?: ?SourceMap,
999
+ /** The dependencies of the asset. */
1000
+ +dependencies?: $ReadOnlyArray<DependencyOptions>,
1001
+ /** The environment of the asset. The options are merged with the input asset's environment. */
1002
+ +env?: EnvironmentOptions | Environment,
1003
+ /**
1004
+ * Controls which bundle the asset is placed into.
1005
+ * - inline: The asset will be placed into a new inline bundle. Inline bundles are not written
1006
+ * to a separate file, but embedded into the parent bundle.
1007
+ * - isolated: The asset will be isolated from its parents in a separate bundle. Shared assets
1008
+ * will be duplicated.
1009
+ */
1010
+ +bundleBehavior?: ?BundleBehavior,
1011
+ /**
1012
+ * If the asset is used as a bundle entry, this controls whether that bundle can be split
1013
+ * into multiple, or whether all of the dependencies must be placed in a single bundle.
1014
+ */
1015
+ +isBundleSplittable?: boolean,
1016
+ /** Plugin-specific metadata for the asset. */
1017
+ +meta?: Meta,
1018
+ /** The pipeline defined in .parcelrc that the asset should be processed with. */
1019
+ +pipeline?: ?string,
1020
+ /**
1021
+ * Whether this asset can be omitted if none of its exports are being used.
1022
+ * This is initially set by the resolver, but can be overridden by transformers.
1023
+ */
1024
+ +sideEffects?: boolean,
1025
+ /** The symbols that the asset exports. */
1026
+ +symbols?: $ReadOnlyMap<Symbol, {|local: Symbol, loc: ?SourceLocation|}>,
1027
+ /**
1028
+ * When a transformer returns multiple assets, it can give them unique keys to identify them.
1029
+ * This can be used to find assets during packaging, or to create dependencies between multiple
1030
+ * assets returned by a transformer by using the unique key as the dependency specifier.
1031
+ */
1032
+ +uniqueKey?: ?string,
1033
+ |};
1034
+
1035
+ export type Async<T> = T | Promise<T>;
1036
+
1037
+ export interface PluginLogger {
1038
+ /** Logs a diagnostic at the verbose log level. */
1039
+ verbose(
1040
+ diagnostic: DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>,
1041
+ ): void;
1042
+
1043
+ /** Logs a diagnostic at the info log level. */
1044
+ info(
1045
+ diagnostic: DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>,
1046
+ ): void;
1047
+
1048
+ /** Synonym for logger.info. */
1049
+ log(
1050
+ diagnostic: DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>,
1051
+ ): void;
1052
+
1053
+ /** Logs a diagnostic at the verbose warning log level. */
1054
+ warn(
1055
+ diagnostic: DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>,
1056
+ ): void;
1057
+
1058
+ /** Logs a diagnostic at the verbose error log level. */
1059
+ error(
1060
+ input:
1061
+ | Diagnostifiable
1062
+ | DiagnosticWithoutOrigin
1063
+ | Array<DiagnosticWithoutOrigin>,
1064
+ ): void;
1065
+ }
1066
+
1067
+ /**
1068
+ * @section transformer
1069
+ */
1070
+ export type ResolveOptions = {|
1071
+ /**
1072
+ * How the specifier should be interpreted.
1073
+ * - esm: An ES module specifier. It is parsed as a URL, but bare specifiers are treated as node_modules.
1074
+ * - commonjs: A CommonJS specifier. It is not parsed as a URL.
1075
+ * - url: A URL that works as in a browser. Bare specifiers are treated as relative URLs.
1076
+ * - custom: A custom specifier. Must be handled by a custom resolver plugin.
1077
+ */
1078
+ +specifierType?: SpecifierType,
1079
+ /** A list of custom conditions to use when resolving package.json "exports" and "imports". */
1080
+ +packageConditions?: Array<string>,
1081
+ |};
1082
+
1083
+ /**
1084
+ * @section transformer
1085
+ */
1086
+ export type ResolveFn = (
1087
+ from: FilePath,
1088
+ to: string,
1089
+ options?: ResolveOptions,
1090
+ ) => Promise<FilePath>;
1091
+
1092
+ /**
1093
+ * @section validator
1094
+ * @experimental
1095
+ */
1096
+ type ResolveConfigFn = (configNames: Array<FilePath>) => Promise<?FilePath>;
1097
+
1098
+ /**
1099
+ * @section validator
1100
+ * @experimental
1101
+ */
1102
+ type ResolveConfigWithPathFn = (
1103
+ configNames: Array<FilePath>,
1104
+ assetFilePath: string,
1105
+ ) => Promise<?FilePath>;
1106
+
1107
+ /**
1108
+ * @section validator
1109
+ * @experimental
1110
+ */
1111
+ export type ValidateResult = {|
1112
+ warnings: Array<Diagnostic>,
1113
+ errors: Array<Diagnostic>,
1114
+ |};
1115
+
1116
+ /**
1117
+ * @section validator
1118
+ * @experimental
1119
+ */
1120
+ export type DedicatedThreadValidator = {|
1121
+ validateAll: ({|
1122
+ assets: Asset[],
1123
+ resolveConfigWithPath: ResolveConfigWithPathFn,
1124
+ options: PluginOptions,
1125
+ logger: PluginLogger,
1126
+ tracer: PluginTracer,
1127
+ |}) => Async<Array<?ValidateResult>>,
1128
+ |};
1129
+
1130
+ /**
1131
+ * @section validator
1132
+ * @experimental
1133
+ */
1134
+ export type MultiThreadValidator = {|
1135
+ validate: ({|
1136
+ asset: Asset,
1137
+ config: ConfigResult | void,
1138
+ options: PluginOptions,
1139
+ logger: PluginLogger,
1140
+ tracer: PluginTracer,
1141
+ |}) => Async<ValidateResult | void>,
1142
+ getConfig?: ({|
1143
+ asset: Asset,
1144
+ resolveConfig: ResolveConfigFn,
1145
+ options: PluginOptions,
1146
+ logger: PluginLogger,
1147
+ tracer: PluginTracer,
1148
+ |}) => Async<ConfigResult | void>,
1149
+ |};
1150
+
1151
+ /**
1152
+ * @section validator
1153
+ */
1154
+ export type Validator = DedicatedThreadValidator | MultiThreadValidator;
1155
+
1156
+ /**
1157
+ * The methods for a transformer plugin.
1158
+ * @section transformer
1159
+ */
1160
+ export type Transformer<ConfigType> = {|
1161
+ loadConfig?: ({|
1162
+ config: Config,
1163
+ options: PluginOptions,
1164
+ logger: PluginLogger,
1165
+ tracer: PluginTracer,
1166
+ |}) => Promise<ConfigType> | ConfigType,
1167
+ /** Whether an AST from a previous transformer can be reused (to prevent double-parsing) */
1168
+ canReuseAST?: ({|
1169
+ ast: AST,
1170
+ options: PluginOptions,
1171
+ logger: PluginLogger,
1172
+ tracer: PluginTracer,
1173
+ |}) => boolean,
1174
+ /** Parse the contents into an ast */
1175
+ parse?: ({|
1176
+ asset: Asset,
1177
+ config: ConfigType,
1178
+ resolve: ResolveFn,
1179
+ options: PluginOptions,
1180
+ logger: PluginLogger,
1181
+ tracer: PluginTracer,
1182
+ |}) => Async<?AST>,
1183
+ /** Transform the asset and/or add new assets */
1184
+ transform({|
1185
+ asset: MutableAsset,
1186
+ config: ConfigType,
1187
+ resolve: ResolveFn,
1188
+ options: PluginOptions,
1189
+ logger: PluginLogger,
1190
+ tracer: PluginTracer,
1191
+ |}): Async<Array<TransformerResult | MutableAsset>>,
1192
+ /**
1193
+ * Do some processing after the transformation
1194
+ * @experimental
1195
+ */
1196
+ postProcess?: ({|
1197
+ assets: Array<MutableAsset>,
1198
+ config: ConfigType,
1199
+ resolve: ResolveFn,
1200
+ options: PluginOptions,
1201
+ logger: PluginLogger,
1202
+ tracer: PluginTracer,
1203
+ |}) => Async<Array<TransformerResult>>,
1204
+ /** Stringify the AST */
1205
+ generate?: ({|
1206
+ asset: Asset,
1207
+ ast: AST,
1208
+ options: PluginOptions,
1209
+ logger: PluginLogger,
1210
+ tracer: PluginTracer,
1211
+ |}) => Async<GenerateOutput>,
1212
+ |};
1213
+
1214
+ /**
1215
+ * Used to control a traversal
1216
+ * @section bundler
1217
+ */
1218
+ export type TraversalActions = {|
1219
+ /** Skip the current node's children and continue the traversal if there are other nodes in the queue. */
1220
+ skipChildren(): void,
1221
+ /** Stop the traversal */
1222
+ stop(): void,
1223
+ |};
1224
+
1225
+ /**
1226
+ * Essentially GraphTraversalCallback, but allows adding specific node enter and exit callbacks.
1227
+ * @section bundler
1228
+ */
1229
+ export type GraphVisitor<TNode, TContext> =
1230
+ | GraphTraversalCallback<TNode, TContext>
1231
+ | {|
1232
+ enter?: GraphTraversalCallback<TNode, TContext>,
1233
+ exit?: GraphTraversalCallback<TNode, TContext>,
1234
+ |};
1235
+
1236
+ /**
1237
+ * A generic callback for graph traversals
1238
+ * @param context The parent node's return value is passed as a parameter to the children's callback. \
1239
+ * This can be used to forward information from the parent to children in a DFS (unlike a global variable).
1240
+ * @section bundler
1241
+ */
1242
+ export type GraphTraversalCallback<TNode, TContext> = (
1243
+ node: TNode,
1244
+ context: ?TContext,
1245
+ actions: TraversalActions,
1246
+ ) => ?TContext;
1247
+
1248
+ /**
1249
+ * @section bundler
1250
+ */
1251
+ export type BundleTraversable =
1252
+ | {|+type: 'asset', value: Asset|}
1253
+ | {|+type: 'dependency', value: Dependency|};
1254
+
1255
+ /**
1256
+ * @section bundler
1257
+ */
1258
+ export type BundleGraphTraversable =
1259
+ | {|+type: 'asset', value: Asset|}
1260
+ | {|+type: 'dependency', value: Dependency|};
1261
+
1262
+ /**
1263
+ * Options for MutableBundleGraph's <code>createBundle</code>.
1264
+ *
1265
+ * If an <code>entryAsset</code> is provided, <code>uniqueKey</code> (for the bundle id),
1266
+ * <code>type</code>, and <code>env</code> will be inferred from the <code>entryAsset</code>.
1267
+ *
1268
+ * If an <code>entryAsset</code> is not provided, <code>uniqueKey</code> (for the bundle id),
1269
+ * <code>type</code>, and <code>env</code> must be provided.
1270
+ *
1271
+ * isSplittable defaults to <code>entryAsset.isSplittable</code> or <code>false</code>
1272
+ * @section bundler
1273
+ */
1274
+ export type CreateBundleOpts =
1275
+ // If an entryAsset is provided, a bundle id, type, and environment will be
1276
+ // inferred from the entryAsset.
1277
+ | {|
1278
+ /** The entry asset of the bundle. If provided, many bundle properties will be inferred from it. */
1279
+ +entryAsset: Asset,
1280
+ /** The target of the bundle. Should come from the dependency that created the bundle. */
1281
+ +target: Target,
1282
+ /**
1283
+ * Indicates that the bundle's file name should be stable over time, even when the content of the bundle
1284
+ * changes. This is useful for entries that a user would manually enter the URL for, as well as for things
1285
+ * like service workers or RSS feeds, where the URL must remain consistent over time.
1286
+ */
1287
+ +needsStableName?: ?boolean,
1288
+ /**
1289
+ * Controls the behavior of the bundle.
1290
+ * to determine when the bundle is loaded.
1291
+ * - inline: Inline bundles are not written to a separate file, but embedded into the parent bundle.
1292
+ * - isolated: The bundle will be isolated from its parents. Shared assets will be duplicated.
1293
+ */
1294
+ +bundleBehavior?: ?BundleBehavior,
1295
+ /** Name of the manual shared bundle config that caused this bundle to be created */
1296
+ +manualSharedBundle?: ?string,
1297
+ |}
1298
+ // If an entryAsset is not provided, a bundle id, type, and environment must
1299
+ // be provided.
1300
+ | {|
1301
+ /** The type of the bundle. */
1302
+ +type: string,
1303
+ /** The environment of the bundle. */
1304
+ +env: Environment,
1305
+ /** A unique value for the bundle to be used in its id. */
1306
+ +uniqueKey: string,
1307
+ /** The target of the bundle. Should come from the dependency that created the bundle. */
1308
+ +target: Target,
1309
+ /**
1310
+ * Indicates that the bundle's file name should be stable over time, even when the content of the bundle
1311
+ * changes. This is useful for entries that a user would manually enter the URL for, as well as for things
1312
+ * like service workers or RSS feeds, where the URL must remain consistent over time.
1313
+ */
1314
+ +needsStableName?: ?boolean,
1315
+ /**
1316
+ * Controls the behavior of the bundle.
1317
+ * to determine when the bundle is loaded.
1318
+ * - inline: Inline bundles are not written to a separate file, but embedded into the parent bundle.
1319
+ * - isolated: The bundle will be isolated from its parents. Shared assets will be duplicated.
1320
+ */
1321
+ +bundleBehavior?: ?BundleBehavior,
1322
+ /**
1323
+ * Whether the bundle can be split. If false, then all dependencies of the bundle will be kept
1324
+ * internal to the bundle, rather than referring to other bundles. This may result in assets
1325
+ * being duplicated between multiple bundles, but can be useful for things like server side rendering.
1326
+ */
1327
+ +isSplittable?: ?boolean,
1328
+ /** The bundle's pipeline, to be used for optimization. Usually based on the pipeline of the entry asset. */
1329
+ +pipeline?: ?string,
1330
+ /** Name of the manual shared bundle config that caused this bundle to be created */
1331
+ +manualSharedBundle?: ?string,
1332
+ |};
1333
+
1334
+ /**
1335
+ * Specifies a symbol in an asset
1336
+ * @section packager
1337
+ */
1338
+ export type SymbolResolution = {|
1339
+ /** The Asset which exports the symbol. */
1340
+ +asset: Asset,
1341
+ /** under which name the symbol is exported */
1342
+ +exportSymbol: Symbol | string,
1343
+ /** The identifier under which the symbol can be referenced. */
1344
+ +symbol: void | null | false | Symbol,
1345
+ /** The location of the specifier that lead to this result. */
1346
+ +loc: ?SourceLocation,
1347
+ |};
1348
+
1349
+ /**
1350
+ * @section packager
1351
+ */
1352
+ export type ExportSymbolResolution = {|
1353
+ ...SymbolResolution,
1354
+ +exportAs: Symbol | string,
1355
+ |};
1356
+
1357
+ /**
1358
+ * A Bundle (a collection of assets)
1359
+ *
1360
+ * @section bundler
1361
+ */
1362
+ export interface Bundle {
1363
+ /** The bundle id. */
1364
+ +id: string;
1365
+ /** The type of the bundle. */
1366
+ +type: string;
1367
+ /** The environment of the bundle. */
1368
+ +env: Environment;
1369
+ /** The bundle's target. */
1370
+ +target: Target;
1371
+ /** Assets that run when the bundle is loaded (e.g. runtimes could be added). VERIFY */
1372
+ /**
1373
+ * Indicates that the bundle's file name should be stable over time, even when the content of the bundle
1374
+ * changes. This is useful for entries that a user would manually enter the URL for, as well as for things
1375
+ * like service workers or RSS feeds, where the URL must remain consistent over time.
1376
+ */
1377
+ +needsStableName: ?boolean;
1378
+ /**
1379
+ * Controls the behavior of the bundle.
1380
+ * to determine when the bundle is loaded.
1381
+ * - inline: Inline bundles are not written to a separate file, but embedded into the parent bundle.
1382
+ * - isolated: The bundle will be isolated from its parents. Shared assets will be duplicated.
1383
+ */
1384
+ +bundleBehavior: ?BundleBehavior;
1385
+ /**
1386
+ * Whether the bundle can be split. If false, then all dependencies of the bundle will be kept
1387
+ * internal to the bundle, rather than referring to other bundles. This may result in assets
1388
+ * being duplicated between multiple bundles, but can be useful for things like server side rendering.
1389
+ */
1390
+ +isSplittable: ?boolean;
1391
+ /**
1392
+ * A placeholder for the bundle's content hash that can be used in the bundle's name or the contents of another
1393
+ * bundle. Hash references are replaced with a content hash of the bundle after packaging and optimizing.
1394
+ */
1395
+ +hashReference: string;
1396
+ /**
1397
+ * Returns the assets that are executed immediately when the bundle is loaded.
1398
+ * Some bundles may not have any entry assets, for example, shared bundles.
1399
+ */
1400
+ getEntryAssets(): Array<Asset>;
1401
+ /**
1402
+ * Returns the main entry of the bundle, which will provide the bundle's exports.
1403
+ * Some bundles do not have a main entry, for example, shared bundles.
1404
+ */
1405
+ getMainEntry(): ?Asset;
1406
+ /** Returns whether the bundle includes the given asset. */
1407
+ hasAsset(Asset): boolean;
1408
+ /** Returns whether the bundle includes the given dependency. */
1409
+ hasDependency(Dependency): boolean;
1410
+ /** Traverses the assets in the bundle. */
1411
+ traverseAssets<TContext>(
1412
+ visit: GraphVisitor<Asset, TContext>,
1413
+ startAsset?: Asset,
1414
+ ): ?TContext;
1415
+ /** Traverses assets and dependencies in the bundle. */
1416
+ traverse<TContext>(
1417
+ visit: GraphVisitor<BundleTraversable, TContext>,
1418
+ ): ?TContext;
1419
+ }
1420
+
1421
+ /**
1422
+ * A Bundle that got named by a Namer
1423
+ * @section bundler
1424
+ */
1425
+ export interface NamedBundle extends Bundle {
1426
+ /** A shortened version of the bundle id that is used to refer to the bundle at runtime. */
1427
+ +publicId: string;
1428
+ /**
1429
+ * The bundle's name. This is a file path relative to the bundle's target directory.
1430
+ * The bundle name may include a hash reference, but not the final content hash.
1431
+ */
1432
+ +name: string;
1433
+ /** A version of the bundle's name with hash references removed for display. */
1434
+ +displayName: string;
1435
+ }
1436
+
1437
+ export interface PackagedBundle extends NamedBundle {
1438
+ /** The absolute file path of the written bundle, including the final content hash if any. */
1439
+ +filePath: FilePath;
1440
+ /** Statistics about the bundle. */
1441
+ +stats: Stats;
1442
+ }
1443
+
1444
+ /**
1445
+ * A collection of sibling bundles (which are stored in the BundleGraph) that should be loaded together (in order).
1446
+ * @section bundler
1447
+ */
1448
+ export interface BundleGroup {
1449
+ /** The target of the bundle group. */
1450
+ +target: Target;
1451
+ /** The id of the entry asset in the bundle group, which is executed immediately when the bundle group is loaded. */
1452
+ +entryAssetId: string;
1453
+ }
1454
+
1455
+ /**
1456
+ * A BundleGraph in the Bundler that can be modified
1457
+ * @section bundler
1458
+ * @experimental
1459
+ */
1460
+ export interface MutableBundleGraph extends BundleGraph<Bundle> {
1461
+ /** Add asset and all child nodes to the bundle. */
1462
+ addAssetGraphToBundle(
1463
+ Asset,
1464
+ Bundle,
1465
+ shouldSkipDependency?: (Dependency) => boolean,
1466
+ ): void;
1467
+ addAssetToBundle(Asset, Bundle): void;
1468
+ /**
1469
+ * Adds an asset as an entry to a bundle. Entry assets are executed immediately
1470
+ * when the bundle is loaded.
1471
+ */
1472
+ addEntryToBundle(
1473
+ Asset,
1474
+ Bundle,
1475
+ shouldSkipDependency?: (Dependency) => boolean,
1476
+ ): void;
1477
+ /** Adds the Bundle to the BundleGroup, loading it along with others in the group */
1478
+ addBundleToBundleGroup(Bundle, BundleGroup): void;
1479
+ createAssetReference(Dependency, Asset, Bundle): void;
1480
+ createBundleReference(Bundle, Bundle): void;
1481
+ createBundle(CreateBundleOpts): Bundle;
1482
+ /** Turns an edge (Dependency -> Asset-s) into (Dependency -> BundleGroup -> Asset-s) */
1483
+ createBundleGroup(Dependency, Target): BundleGroup;
1484
+ /** @returns all Asset-s attached to the Dependency */
1485
+ getDependencyAssets(Dependency): Array<Asset>;
1486
+ /** Get Bundles that load this bundle asynchronously. */
1487
+ getParentBundlesOfBundleGroup(BundleGroup): Array<Bundle>;
1488
+ /** @returns the size in bytes of an asset and all assets in its subgraph */
1489
+ getTotalSize(Asset): number;
1490
+ /**
1491
+ * Recursively removes an asset and its dependencies from a bundle. Stops at
1492
+ * bundle group boundaries.
1493
+ */
1494
+ removeAssetGraphFromBundle(Asset, Bundle): void;
1495
+ /**
1496
+ * Removes a BundleGroup from the graph. If any of the group's Bundle-s no
1497
+ * longer exist in the graph, those are removed as well.
1498
+ */
1499
+ removeBundleGroup(bundleGroup: BundleGroup): void;
1500
+ /** Turns a dependency to a different bundle into a dependency to an asset inside <code>bundle</code>. */
1501
+ internalizeAsyncDependency(bundle: Bundle, dependency: Dependency): void;
1502
+ }
1503
+
1504
+ /**
1505
+ * A Graph that contains Bundle-s, Asset-s, Dependency-s, BundleGroup-s
1506
+ * @section bundler
1507
+ */
1508
+ export interface BundleGraph<TBundle: Bundle> {
1509
+ /** Retrieves an asset by id. */
1510
+ getAssetById(id: string): Asset;
1511
+ /** Returns the public (short) id for an asset. */
1512
+ getAssetPublicId(asset: Asset): string;
1513
+ /** Returns a list of bundles in the bundle graph. By default, inline bundles are excluded. */
1514
+ getBundles(opts?: {|includeInline: boolean|}): Array<TBundle>;
1515
+ /** Traverses the assets and dependencies in the bundle graph, in depth first order. */
1516
+ traverse<TContext>(
1517
+ visit: GraphVisitor<BundleGraphTraversable, TContext>,
1518
+ startAsset: ?Asset,
1519
+ options?: {|skipUnusedDependencies?: boolean|},
1520
+ ): ?TContext;
1521
+ /** Traverses all bundles in the bundle graph, including inline bundles, in depth first order. */
1522
+ traverseBundles<TContext>(
1523
+ visit: GraphVisitor<TBundle, TContext>,
1524
+ startBundle: ?Bundle,
1525
+ ): ?TContext;
1526
+ /** Returns a list of bundle groups that load the given bundle. */
1527
+ getBundleGroupsContainingBundle(bundle: Bundle): Array<BundleGroup>;
1528
+ /** Returns a list of bundles that load together in the given bundle group. */
1529
+ getBundlesInBundleGroup(
1530
+ bundleGroup: BundleGroup,
1531
+ opts?: {|includeInline: boolean|},
1532
+ ): Array<TBundle>;
1533
+ /** Returns a list of bundles that this bundle loads asynchronously. */
1534
+ getChildBundles(bundle: Bundle): Array<TBundle>;
1535
+ /** Returns a list of bundles that load this bundle asynchronously. */
1536
+ getParentBundles(bundle: Bundle): Array<TBundle>;
1537
+ /** Returns whether the bundle was loaded by another bundle of the given type. */
1538
+ hasParentBundleOfType(bundle: Bundle, type: string): boolean;
1539
+ /** Returns a list of bundles that are referenced by this bundle. By default, inline bundles are excluded. */
1540
+ getReferencedBundles(
1541
+ bundle: Bundle,
1542
+ opts?: {|recursive?: boolean, includeInline?: boolean|},
1543
+ ): Array<TBundle>;
1544
+ /** Get the dependencies that the asset requires */
1545
+ getDependencies(asset: Asset): Array<Dependency>;
1546
+ /** Get the dependencies that require the asset */
1547
+ getIncomingDependencies(asset: Asset): Array<Dependency>;
1548
+ /** Get the asset that created the dependency. */
1549
+ getAssetWithDependency(dep: Dependency): ?Asset;
1550
+ /** Returns whether the given bundle group is an entry. */
1551
+ isEntryBundleGroup(bundleGroup: BundleGroup): boolean;
1552
+ /**
1553
+ * Returns undefined if the specified dependency was excluded or wasn't async \
1554
+ * and otherwise the BundleGroup or Asset that the dependency resolves to.
1555
+ */
1556
+ resolveAsyncDependency(
1557
+ dependency: Dependency,
1558
+ bundle: ?Bundle,
1559
+ ): ?(
1560
+ | {|type: 'bundle_group', value: BundleGroup|}
1561
+ | {|type: 'asset', value: Asset|}
1562
+ );
1563
+ /** Returns whether a dependency was excluded because it had no used symbols. */
1564
+ isDependencySkipped(dependency: Dependency): boolean;
1565
+ /**
1566
+ * Returns the asset that the dependency resolved to.
1567
+ * If a bundle is given, assets in that bundle are preferred.
1568
+ * Returns null if the dependency was excluded.
1569
+ */
1570
+ getResolvedAsset(dependency: Dependency, bundle: ?Bundle): ?Asset;
1571
+ /** Returns the bundle that a dependency in a given bundle references, if any. */
1572
+ getReferencedBundle(dependency: Dependency, bundle: Bundle): ?TBundle;
1573
+ /** Returns a list of bundles that contain the given asset. */
1574
+ getBundlesWithAsset(Asset): Array<TBundle>;
1575
+ /** Returns a list of bundles that contain the given dependency. */
1576
+ getBundlesWithDependency(Dependency): Array<TBundle>;
1577
+ /**
1578
+ * Returns whether the given asset is reachable in a sibling, or all possible
1579
+ * ancestries of the given bundle. This indicates that the asset may be excluded
1580
+ * from the given bundle.
1581
+ */
1582
+ isAssetReachableFromBundle(asset: Asset, bundle: Bundle): boolean;
1583
+ /** Returns whether an asset is referenced outside the given bundle. */
1584
+ isAssetReferenced(bundle: Bundle, asset: Asset): boolean;
1585
+ /**
1586
+ * Resolves the export `symbol` of `asset` to the source,
1587
+ * stopping at the first asset after leaving `bundle`.
1588
+ * `symbol === null`: bailout (== caller should do `asset.exports[exportsSymbol]`)
1589
+ * `symbol === undefined`: symbol not found
1590
+ * `symbol === false`: skipped
1591
+ *
1592
+ * <code>asset</code> exports <code>symbol</code>, try to find the asset where the \
1593
+ * corresponding variable lives (resolves re-exports). Stop resolving transitively once \
1594
+ * <code>boundary</code> was left (<code>bundle.hasAsset(asset) === false</code>), then <code>result.symbol</code> is undefined.
1595
+ */
1596
+ getSymbolResolution(
1597
+ asset: Asset,
1598
+ symbol: Symbol,
1599
+ boundary: ?Bundle,
1600
+ ): SymbolResolution;
1601
+ /** Returns a list of symbols that are exported by the asset, including re-exports. */
1602
+ getExportedSymbols(
1603
+ asset: Asset,
1604
+ boundary: ?Bundle,
1605
+ ): Array<ExportSymbolResolution>;
1606
+ /**
1607
+ * Returns a list of symbols from an asset or dependency that are referenced by a dependent asset.
1608
+ *
1609
+ * Returns null if symbol propagation didn't run (so the result is unknown).
1610
+ */
1611
+ getUsedSymbols(Asset | Dependency): ?$ReadOnlySet<Symbol>;
1612
+ /** Returns the common root directory for the entry assets of a target. */
1613
+ getEntryRoot(target: Target): FilePath;
1614
+ }
1615
+
1616
+ /**
1617
+ * @section bundler
1618
+ */
1619
+ export type BundleResult = {|
1620
+ +contents: Blob,
1621
+ +ast?: AST,
1622
+ +map?: ?SourceMap,
1623
+ +type?: string,
1624
+ |};
1625
+
1626
+ /**
1627
+ * @section resolver
1628
+ */
1629
+ export type ResolveResult = {|
1630
+ /** An absolute path to the resolved file. */
1631
+ +filePath?: FilePath,
1632
+ /** An optional named pipeline to use to compile the resolved file. */
1633
+ +pipeline?: ?string,
1634
+ /** Query parameters to be used by transformers when compiling the resolved file. */
1635
+ +query?: URLSearchParams,
1636
+ /** Whether the resolved file should be excluded from the build. */
1637
+ +isExcluded?: boolean,
1638
+ /** Overrides the priority set on the dependency. */
1639
+ +priority?: DependencyPriority,
1640
+ /** Corresponds to BaseAsset's <code>sideEffects</code>. */
1641
+ +sideEffects?: boolean,
1642
+ /** The code of the resolved asset. If provided, this is used rather than reading the file from disk. */
1643
+ +code?: string,
1644
+ /** Whether this dependency can be deferred by Parcel itself (true by default). */
1645
+ +canDefer?: boolean,
1646
+ /** A resolver might return diagnostics to also run subsequent resolvers while still providing a reason why it failed. */
1647
+ +diagnostics?: Diagnostic | Array<Diagnostic>,
1648
+ /** Is spread (shallowly merged) onto the request's dependency.meta */
1649
+ +meta?: JSONObject,
1650
+ /** A list of file paths or patterns that should invalidate the resolution if created. */
1651
+ +invalidateOnFileCreate?: Array<FileCreateInvalidation>,
1652
+ /** A list of files that should invalidate the resolution if modified or deleted. */
1653
+ +invalidateOnFileChange?: Array<FilePath>,
1654
+ /** Invalidates the resolution when the given environment variable changes.*/
1655
+ +invalidateOnEnvChange?: Array<string>,
1656
+ |};
1657
+
1658
+ /**
1659
+ * Turns an asset graph into a BundleGraph.
1660
+ *
1661
+ * bundle and optimize run in series and are functionally identitical.
1662
+ * @section bundler
1663
+ */
1664
+ export type Bundler<ConfigType> = {|
1665
+ loadConfig?: ({|
1666
+ config: Config,
1667
+ options: PluginOptions,
1668
+ logger: PluginLogger,
1669
+ tracer: PluginTracer,
1670
+ |}) => Promise<ConfigType> | ConfigType,
1671
+ bundle({|
1672
+ bundleGraph: MutableBundleGraph,
1673
+ config: ConfigType,
1674
+ options: PluginOptions,
1675
+ logger: PluginLogger,
1676
+ tracer: PluginTracer,
1677
+ |}): Async<void>,
1678
+ optimize({|
1679
+ bundleGraph: MutableBundleGraph,
1680
+ config: ConfigType,
1681
+ options: PluginOptions,
1682
+ logger: PluginLogger,
1683
+ |}): Async<void>,
1684
+ |};
1685
+
1686
+ /**
1687
+ * @section namer
1688
+ */
1689
+ export type Namer<ConfigType> = {|
1690
+ loadConfig?: ({|
1691
+ config: Config,
1692
+ options: PluginOptions,
1693
+ logger: PluginLogger,
1694
+ tracer: PluginTracer,
1695
+ |}) => Promise<ConfigType> | ConfigType,
1696
+ /** Return a filename/-path for <code>bundle</code> or nullish to leave it to the next namer plugin. */
1697
+ name({|
1698
+ bundle: Bundle,
1699
+ bundleGraph: BundleGraph<Bundle>,
1700
+ config: ConfigType,
1701
+ options: PluginOptions,
1702
+ logger: PluginLogger,
1703
+ tracer: PluginTracer,
1704
+ |}): Async<?FilePath>,
1705
+ |};
1706
+
1707
+ type RuntimeAssetPriority = 'sync' | 'parallel';
1708
+
1709
+ /**
1710
+ * A "synthetic" asset that will be inserted into the bundle graph.
1711
+ * @section runtime
1712
+ */
1713
+ export type RuntimeAsset = {|
1714
+ +filePath: FilePath,
1715
+ +code: string,
1716
+ +dependency?: Dependency,
1717
+ +isEntry?: boolean,
1718
+ +env?: EnvironmentOptions,
1719
+ +priority?: RuntimeAssetPriority,
1720
+ |};
1721
+
1722
+ /**
1723
+ * @section runtime
1724
+ */
1725
+ export type Runtime<ConfigType> = {|
1726
+ loadConfig?: ({|
1727
+ config: Config,
1728
+ options: PluginOptions,
1729
+ logger: PluginLogger,
1730
+ tracer: PluginTracer,
1731
+ |}) => Promise<ConfigType> | ConfigType,
1732
+ apply({|
1733
+ bundle: NamedBundle,
1734
+ bundleGraph: BundleGraph<NamedBundle>,
1735
+ config: ConfigType,
1736
+ options: PluginOptions,
1737
+ logger: PluginLogger,
1738
+ tracer: PluginTracer,
1739
+ |}): Async<void | RuntimeAsset | Array<RuntimeAsset>>,
1740
+ |};
1741
+
1742
+ /**
1743
+ * @section packager
1744
+ */
1745
+ export type Packager<ConfigType, BundleConfigType> = {|
1746
+ loadConfig?: ({|
1747
+ config: Config,
1748
+ options: PluginOptions,
1749
+ logger: PluginLogger,
1750
+ tracer: PluginTracer,
1751
+ |}) => Async<ConfigType>,
1752
+ loadBundleConfig?: ({|
1753
+ bundle: NamedBundle,
1754
+ bundleGraph: BundleGraph<NamedBundle>,
1755
+ config: Config,
1756
+ options: PluginOptions,
1757
+ logger: PluginLogger,
1758
+ tracer: PluginTracer,
1759
+ |}) => Async<BundleConfigType>,
1760
+ package({|
1761
+ bundle: NamedBundle,
1762
+ bundleGraph: BundleGraph<NamedBundle>,
1763
+ options: PluginOptions,
1764
+ logger: PluginLogger,
1765
+ tracer: PluginTracer,
1766
+ config: ConfigType,
1767
+ bundleConfig: BundleConfigType,
1768
+ getInlineBundleContents: (
1769
+ Bundle,
1770
+ BundleGraph<NamedBundle>,
1771
+ ) => Async<{|contents: Blob|}>,
1772
+ getSourceMapReference: (map: ?SourceMap) => Async<?string>,
1773
+ |}): Async<BundleResult>,
1774
+ |};
1775
+
1776
+ /**
1777
+ * @section optimizer
1778
+ */
1779
+ export type Optimizer<ConfigType, BundleConfigType> = {|
1780
+ loadConfig?: ({|
1781
+ config: Config,
1782
+ options: PluginOptions,
1783
+ logger: PluginLogger,
1784
+ tracer: PluginTracer,
1785
+ |}) => Async<ConfigType>,
1786
+ loadBundleConfig?: ({|
1787
+ bundle: NamedBundle,
1788
+ bundleGraph: BundleGraph<NamedBundle>,
1789
+ config: Config,
1790
+ options: PluginOptions,
1791
+ logger: PluginLogger,
1792
+ tracer: PluginTracer,
1793
+ |}) => Async<BundleConfigType>,
1794
+ optimize({|
1795
+ bundle: NamedBundle,
1796
+ bundleGraph: BundleGraph<NamedBundle>,
1797
+ contents: Blob,
1798
+ map: ?SourceMap,
1799
+ options: PluginOptions,
1800
+ logger: PluginLogger,
1801
+ tracer: PluginTracer,
1802
+ config: ConfigType,
1803
+ bundleConfig: BundleConfigType,
1804
+ getSourceMapReference: (map: ?SourceMap) => Async<?string>,
1805
+ |}): Async<BundleResult>,
1806
+ |};
1807
+
1808
+ /**
1809
+ * @section compressor
1810
+ */
1811
+ export type Compressor = {|
1812
+ compress({|
1813
+ stream: Readable,
1814
+ options: PluginOptions,
1815
+ logger: PluginLogger,
1816
+ tracer: PluginTracer,
1817
+ |}): Async<?{|
1818
+ stream: Readable,
1819
+ type?: string,
1820
+ |}>,
1821
+ |};
1822
+
1823
+ /**
1824
+ * @section resolver
1825
+ */
1826
+ export type Resolver<ConfigType> = {|
1827
+ loadConfig?: ({|
1828
+ config: Config,
1829
+ options: PluginOptions,
1830
+ logger: PluginLogger,
1831
+ tracer: PluginTracer,
1832
+ |}) => Promise<ConfigType> | ConfigType,
1833
+ resolve({|
1834
+ dependency: Dependency,
1835
+ options: PluginOptions,
1836
+ logger: PluginLogger,
1837
+ tracer: PluginTracer,
1838
+ specifier: FilePath,
1839
+ pipeline: ?string,
1840
+ config: ConfigType,
1841
+ |}): Async<?ResolveResult>,
1842
+ |};
1843
+
1844
+ /**
1845
+ * @section reporter
1846
+ */
1847
+ export type ProgressLogEvent = {|
1848
+ +type: 'log',
1849
+ +level: 'progress',
1850
+ +phase?: string,
1851
+ +message: string,
1852
+ |};
1853
+
1854
+ /**
1855
+ * A log event with a rich diagnostic
1856
+ * @section reporter
1857
+ */
1858
+ export type DiagnosticLogEvent = {|
1859
+ +type: 'log',
1860
+ +level: 'error' | 'warn' | 'info' | 'verbose',
1861
+ +diagnostics: Array<Diagnostic>,
1862
+ |};
1863
+
1864
+ /**
1865
+ * @section reporter
1866
+ */
1867
+ export type TextLogEvent = {|
1868
+ +type: 'log',
1869
+ +level: 'success',
1870
+ +message: string,
1871
+ |};
1872
+
1873
+ /**
1874
+ * @section reporter
1875
+ */
1876
+ export type LogEvent = ProgressLogEvent | DiagnosticLogEvent | TextLogEvent;
1877
+
1878
+ /**
1879
+ * The build just started.
1880
+ * @section reporter
1881
+ */
1882
+ export type BuildStartEvent = {|
1883
+ +type: 'buildStart',
1884
+ |};
1885
+
1886
+ /**
1887
+ * The build just started in watch mode.
1888
+ * @section reporter
1889
+ */
1890
+ export type WatchStartEvent = {|
1891
+ +type: 'watchStart',
1892
+ |};
1893
+
1894
+ /**
1895
+ * The build just ended in watch mode.
1896
+ * @section reporter
1897
+ */
1898
+ export type WatchEndEvent = {|
1899
+ +type: 'watchEnd',
1900
+ |};
1901
+
1902
+ /**
1903
+ * A new Dependency is being resolved.
1904
+ * @section reporter
1905
+ */
1906
+ export type ResolvingProgressEvent = {|
1907
+ +type: 'buildProgress',
1908
+ +phase: 'resolving',
1909
+ +dependency: Dependency,
1910
+ |};
1911
+
1912
+ /**
1913
+ * A new Asset is being transformed.
1914
+ * @section reporter
1915
+ */
1916
+ export type TransformingProgressEvent = {|
1917
+ +type: 'buildProgress',
1918
+ +phase: 'transforming',
1919
+ +filePath: FilePath,
1920
+ |};
1921
+
1922
+ /**
1923
+ * The BundleGraph is generated.
1924
+ * @section reporter
1925
+ */
1926
+ export type BundlingProgressEvent = {|
1927
+ +type: 'buildProgress',
1928
+ +phase: 'bundling',
1929
+ |};
1930
+
1931
+ export type BundledProgressEvent = {|
1932
+ +type: 'buildProgress',
1933
+ +phase: 'bundled',
1934
+ +bundleGraph: BundleGraph<NamedBundle>,
1935
+ +changedAssets: Map<string, Asset>,
1936
+ |};
1937
+
1938
+ /**
1939
+ * A new Bundle is being packaged.
1940
+ * @section reporter
1941
+ */
1942
+ export type PackagingProgressEvent = {|
1943
+ +type: 'buildProgress',
1944
+ +phase: 'packaging',
1945
+ +bundle: NamedBundle,
1946
+ |};
1947
+
1948
+ /**
1949
+ * A new Bundle is being optimized.
1950
+ * @section reporter
1951
+ */
1952
+ export type OptimizingProgressEvent = {|
1953
+ +type: 'buildProgress',
1954
+ +phase: 'optimizing',
1955
+ +bundle: NamedBundle,
1956
+ |};
1957
+
1958
+ /**
1959
+ * @section reporter
1960
+ */
1961
+ export type BuildProgressEvent =
1962
+ | ResolvingProgressEvent
1963
+ | TransformingProgressEvent
1964
+ | BundlingProgressEvent
1965
+ | BundledProgressEvent
1966
+ | PackagingProgressEvent
1967
+ | OptimizingProgressEvent;
1968
+
1969
+ /**
1970
+ * The build was successful.
1971
+ * @section reporter
1972
+ */
1973
+ export type BuildSuccessEvent = {|
1974
+ +type: 'buildSuccess',
1975
+ +bundleGraph: BundleGraph<PackagedBundle>,
1976
+ +buildTime: number,
1977
+ +changedAssets: Map<string, Asset>,
1978
+ +requestBundle: (bundle: NamedBundle) => Promise<BuildSuccessEvent>,
1979
+ +unstable_requestStats: {[requestType: string]: number},
1980
+ |};
1981
+
1982
+ /**
1983
+ * The build failed.
1984
+ * @section reporter
1985
+ */
1986
+ export type BuildFailureEvent = {|
1987
+ +type: 'buildFailure',
1988
+ +diagnostics: Array<Diagnostic>,
1989
+ +unstable_requestStats: {[requestType: string]: number},
1990
+ |};
1991
+
1992
+ /**
1993
+ * @section reporter
1994
+ */
1995
+ export type BuildEvent = BuildFailureEvent | BuildSuccessEvent;
1996
+
1997
+ /**
1998
+ * A new file is being validated.
1999
+ * @section reporter
2000
+ */
2001
+ export type ValidationEvent = {|
2002
+ +type: 'validation',
2003
+ +filePath: FilePath,
2004
+ |};
2005
+
2006
+ /**
2007
+ * A trace event has occured.
2008
+ * Loosely modeled on Chrome's Trace Event format: https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
2009
+ *
2010
+ * @section reporter
2011
+ */
2012
+ export type TraceEvent = {|
2013
+ +type: 'trace',
2014
+ +ts: number,
2015
+ +duration: number,
2016
+ +name: string,
2017
+ +tid: number,
2018
+ +pid: number,
2019
+ +categories: string[],
2020
+ +args?: {[key: string]: mixed},
2021
+ |};
2022
+
2023
+ export type CacheEvent = {|
2024
+ type: 'cache',
2025
+ phase: string,
2026
+ total: number,
2027
+ size: number,
2028
+ |};
2029
+
2030
+ /**
2031
+ * @section reporter
2032
+ */
2033
+ export type ReporterEvent =
2034
+ | LogEvent
2035
+ | BuildStartEvent
2036
+ | BuildProgressEvent
2037
+ | BuildSuccessEvent
2038
+ | BuildFailureEvent
2039
+ | WatchStartEvent
2040
+ | WatchEndEvent
2041
+ | ValidationEvent
2042
+ | TraceEvent
2043
+ | CacheEvent;
2044
+
2045
+ /**
2046
+ * @section reporter
2047
+ */
2048
+ export type Reporter = {|
2049
+ report({|
2050
+ event: ReporterEvent,
2051
+ options: PluginOptions,
2052
+ logger: PluginLogger,
2053
+ tracer: PluginTracer,
2054
+ |}): Async<void>,
2055
+ |};
2056
+
2057
+ export interface ErrorWithCode extends Error {
2058
+ +code?: string;
2059
+ }
2060
+
2061
+ export interface IDisposable {
2062
+ dispose(): mixed;
2063
+ }
2064
+
2065
+ export type AsyncSubscription = {|
2066
+ unsubscribe(): Promise<mixed>,
2067
+ |};
2068
+
2069
+ export interface PluginTracer {
2070
+ /** Returns whether the tracer is enabled. Use this to avoid possibly expensive calculations
2071
+ * of arguments to `createMeasurement` - for example if you need to determine the entry of a bundle to pass it
2072
+ * in as the <code>argumentName</code>, you would only do this if the tracer is enabled.
2073
+ */
2074
+ +enabled: boolean;
2075
+
2076
+ /**
2077
+ * Creates a new trace measurement with the specified name. This name should reflect the current plugin or
2078
+ * function being executed (for example, the name of a Babel transform). The category will default to the name of your plugin,
2079
+ * however it should be set to reflect the type of operation (for example, for a hypothetical operation
2080
+ * to find CSS in an asset within a Compiled plugin you might set this to <code>find_css<code>).
2081
+ *
2082
+ * If this is an operation that executes multiple times on different things - whether that's assets, bundles, or
2083
+ * otherwise - specify the name of the context object in <code>argumentName</code>.
2084
+ *
2085
+ * <code>otherArgs</code> can be used for specifying any other key/value pairs
2086
+ * that should be written to the trace.
2087
+ *
2088
+ * For example: <code>tracer.createMeasurement('compiled', 'find_css', path.relative(options.projecRoot, asset.filePath), { meta: 'data' })</code>
2089
+ */
2090
+ createMeasurement(
2091
+ name: string,
2092
+ category?: string,
2093
+ argumentName?: string,
2094
+ otherArgs?: {[key: string]: mixed},
2095
+ ): TraceMeasurement | null;
2096
+ }