@atlaspack/transformer-js 3.2.3-canary.33 → 3.2.3-canary.331

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.
@@ -1,17 +1,23 @@
1
- // @flow
2
1
  import type {
3
2
  JSONObject,
4
3
  EnvMap,
5
4
  SourceLocation,
6
5
  FilePath,
7
6
  FileCreateInvalidation,
8
- ConditionMeta,
7
+ Config,
8
+ PluginOptions,
9
9
  } from '@atlaspack/types';
10
+ import {createBuildCache} from '@atlaspack/build-cache';
10
11
  import type {SchemaEntity} from '@atlaspack/utils';
11
12
  import type {Diagnostic} from '@atlaspack/diagnostic';
12
- import SourceMap from '@parcel/source-map';
13
+ import SourceMap from '@atlaspack/source-map';
13
14
  import {Transformer} from '@atlaspack/plugin';
14
- import {transform, transformAsync} from '@atlaspack/rust';
15
+ import {
16
+ transform,
17
+ transformAsync,
18
+ determineJsxConfiguration,
19
+ } from '@atlaspack/rust';
20
+ import invariant from 'assert';
15
21
  import browserslist from 'browserslist';
16
22
  import semver from 'semver';
17
23
  import nullthrows from 'nullthrows';
@@ -26,7 +32,7 @@ import {getFeatureFlag} from '@atlaspack/feature-flags';
26
32
  const JSX_EXTENSIONS = {
27
33
  jsx: true,
28
34
  tsx: true,
29
- };
35
+ } as const;
30
36
 
31
37
  const JSX_PRAGMA = {
32
38
  react: {
@@ -49,7 +55,7 @@ const JSX_PRAGMA = {
49
55
  pragmaFrag: undefined,
50
56
  automatic: undefined,
51
57
  },
52
- };
58
+ } as const;
53
59
 
54
60
  const BROWSER_MAPPING = {
55
61
  and_chr: 'chrome',
@@ -63,7 +69,7 @@ const BROWSER_MAPPING = {
63
69
  bb: null,
64
70
  kaios: null,
65
71
  op_mini: null,
66
- };
72
+ } as const;
67
73
 
68
74
  // List of browsers to exclude when the esmodule target is specified.
69
75
  // Based on https://caniuse.com/#feat=es6-module
@@ -108,16 +114,35 @@ const CONFIG_SCHEMA: SchemaEntity = {
108
114
  },
109
115
  ],
110
116
  },
117
+ addReactDisplayName: {
118
+ type: 'boolean',
119
+ },
111
120
  magicComments: {
112
121
  type: 'boolean',
113
122
  },
114
123
  unstable_inlineConstants: {
115
124
  type: 'boolean',
116
125
  },
126
+ jsx: {
127
+ type: 'object',
128
+ },
117
129
  },
118
130
  additionalProperties: false,
119
131
  };
120
132
 
133
+ // Mirrors the CONFIG_SCHEMA
134
+ interface JsTransformerConfig {
135
+ inlineFS?: boolean;
136
+ inlineEnvironment?: boolean | string[];
137
+ addReactDisplayName?: boolean;
138
+ magicComments?: boolean;
139
+ unstable_inlineConstants?: boolean;
140
+ // This is exclusively used in Rust so not worth typing
141
+ jsx: any;
142
+ }
143
+
144
+ const configCache = createBuildCache();
145
+
121
146
  const SCRIPT_ERRORS = {
122
147
  browser: {
123
148
  message: 'Browser scripts cannot have imports or exports.',
@@ -133,132 +158,213 @@ const SCRIPT_ERRORS = {
133
158
  'Service workers cannot have imports or exports without the `type: "module"` option.',
134
159
  hint: "Add {type: 'module'} as a second argument to the navigator.serviceWorker.register() call.",
135
160
  },
136
- };
161
+ } as const;
137
162
 
138
163
  type TSConfig = {
139
164
  compilerOptions?: {
140
165
  // https://www.typescriptlang.org/tsconfig#jsx
141
- jsx?: 'react' | 'react-jsx' | 'react-jsxdev' | 'preserve' | 'react-native',
166
+ jsx?: 'react' | 'react-jsx' | 'react-jsxdev' | 'preserve' | 'react-native';
142
167
  // https://www.typescriptlang.org/tsconfig#jsxFactory
143
- jsxFactory?: string,
168
+ jsxFactory?: string;
144
169
  // https://www.typescriptlang.org/tsconfig#jsxFragmentFactory
145
- jsxFragmentFactory?: string,
170
+ jsxFragmentFactory?: string;
146
171
  // https://www.typescriptlang.org/tsconfig#jsxImportSource
147
- jsxImportSource?: string,
172
+ jsxImportSource?: string;
148
173
  // https://www.typescriptlang.org/tsconfig#experimentalDecorators
149
- experimentalDecorators?: boolean,
174
+ experimentalDecorators?: boolean;
150
175
  // https://www.typescriptlang.org/tsconfig#useDefineForClassFields
151
- useDefineForClassFields?: boolean,
176
+ useDefineForClassFields?: boolean;
152
177
  // https://www.typescriptlang.org/tsconfig#target
153
- target?: string, // 'es3' | 'es5' | 'es6' | 'es2015' | ... |'es2022' | ... | 'esnext'
154
- ...
155
- },
156
- ...
178
+ target?: string; // 'es3' | 'es5' | 'es6' | 'es2015' | ... |'es2022' | ... | 'esnext';
179
+ };
157
180
  };
158
181
 
159
- type MacroAsset = {|
160
- type: string,
161
- content: string,
162
- |};
182
+ type MacroAsset = {
183
+ type: string;
184
+ content: string;
185
+ };
163
186
 
164
187
  // NOTE: Make sure this is in sync with the TypeScript definition in the @atlaspack/macros package.
165
- type MacroContext = {|
166
- addAsset(asset: MacroAsset): void,
167
- invalidateOnFileChange(FilePath): void,
168
- invalidateOnFileCreate(FileCreateInvalidation): void,
169
- invalidateOnEnvChange(string): void,
170
- invalidateOnStartup(): void,
171
- invalidateOnBuild(): void,
172
- |};
173
-
174
- export default (new Transformer({
175
- async loadConfig({config, options}) {
176
- let pkg = await config.getPackage();
177
- let isJSX,
178
- pragma,
179
- pragmaFrag,
180
- jsxImportSource,
181
- automaticJSXRuntime,
182
- reactRefresh,
183
- decorators,
184
- useDefineForClassFields;
185
- if (config.isSource) {
186
- let reactLib;
187
- if (pkg?.alias && pkg.alias['react']) {
188
- // e.g.: `{ alias: { "react": "preact/compat" } }`
189
- reactLib = 'react';
190
- } else {
191
- // Find a dependency that we can map to a JSX pragma
192
- reactLib = Object.keys(JSX_PRAGMA).find(
193
- (libName) =>
194
- pkg?.dependencies?.[libName] ||
195
- pkg?.devDependencies?.[libName] ||
196
- pkg?.peerDependencies?.[libName],
197
- );
198
- }
188
+ type MacroContext = {
189
+ addAsset(asset: MacroAsset): void;
190
+ invalidateOnFileChange(arg1: FilePath): void;
191
+ invalidateOnFileCreate(arg1: FileCreateInvalidation): void;
192
+ invalidateOnEnvChange(arg1: string): void;
193
+ invalidateOnStartup(): void;
194
+ invalidateOnBuild(): void;
195
+ };
199
196
 
200
- reactRefresh =
201
- options.hmrOptions &&
202
- options.mode === 'development' &&
203
- Boolean(
204
- pkg?.dependencies?.react ||
205
- pkg?.devDependencies?.react ||
206
- pkg?.peerDependencies?.react,
207
- );
197
+ interface JsxConfig {
198
+ isJSX: boolean | undefined;
199
+ jsxPragma: string | undefined;
200
+ jsxPragmaFrag: string | undefined;
201
+ jsxImportSource: string | undefined;
202
+ automaticJSXRuntime: boolean | undefined;
203
+ reactRefresh: boolean | null | undefined;
204
+ }
205
+
206
+ async function legacyDetemineJsxConfig(
207
+ config: Config,
208
+ options: PluginOptions,
209
+ ): Promise<JsxConfig> {
210
+ let packageJson = await config.getPackage();
211
+ let isJSX,
212
+ jsxPragma,
213
+ jsxPragmaFrag,
214
+ jsxImportSource,
215
+ automaticJSXRuntime,
216
+ reactRefresh;
217
+
218
+ if (config.isSource) {
219
+ let reactLib;
220
+ if (packageJson?.alias && packageJson.alias['react']) {
221
+ // e.g.: `{ alias: { "react": "preact/compat" } }`
222
+ reactLib = 'react';
223
+ } else {
224
+ // Find a dependency that we can map to a JSX pragma
225
+ reactLib = Object.keys(JSX_PRAGMA).find(
226
+ (libName) =>
227
+ packageJson?.dependencies?.[libName] ||
228
+ packageJson?.devDependencies?.[libName] ||
229
+ packageJson?.peerDependencies?.[libName],
230
+ );
231
+ }
232
+
233
+ reactRefresh = Boolean(
234
+ packageJson?.dependencies?.react ||
235
+ packageJson?.devDependencies?.react ||
236
+ packageJson?.peerDependencies?.react,
237
+ );
208
238
 
209
- let tsconfig = await config.getConfigFrom<TSConfig>(
239
+ const compilerOptions: TSConfig['compilerOptions'] = (
240
+ await config.getConfigFrom<TSConfig>(
210
241
  options.projectRoot + '/index',
211
242
  ['tsconfig.json', 'jsconfig.json'],
243
+ {
244
+ readTracking: true,
245
+ },
246
+ )
247
+ )?.contents?.compilerOptions;
248
+
249
+ // Use explicitly defined JSX options in tsconfig.json over inferred values from dependencies.
250
+ jsxPragma =
251
+ compilerOptions?.jsxFactory ||
252
+ // @ts-expect-error TS7053
253
+ (reactLib ? JSX_PRAGMA[reactLib].pragma : undefined);
254
+ jsxPragmaFrag =
255
+ compilerOptions?.jsxFragmentFactory ||
256
+ // @ts-expect-error TS7053
257
+ (reactLib ? JSX_PRAGMA[reactLib].pragmaFrag : undefined);
258
+
259
+ if (
260
+ compilerOptions?.jsx === 'react-jsx' ||
261
+ compilerOptions?.jsx === 'react-jsxdev' ||
262
+ compilerOptions?.jsxImportSource
263
+ ) {
264
+ jsxImportSource = compilerOptions?.jsxImportSource;
265
+ automaticJSXRuntime = true;
266
+ } else if (reactLib) {
267
+ let effectiveReactLib =
268
+ packageJson?.alias && packageJson.alias['react'] === 'preact/compat'
269
+ ? 'preact'
270
+ : reactLib;
271
+ // @ts-expect-error TS7053
272
+ let automaticVersion = JSX_PRAGMA[effectiveReactLib]?.automatic;
273
+ let reactLibVersion =
274
+ packageJson?.dependencies?.[effectiveReactLib] ||
275
+ packageJson?.devDependencies?.[effectiveReactLib] ||
276
+ packageJson?.peerDependencies?.[effectiveReactLib];
277
+ // @ts-expect-error TS2322
278
+ reactLibVersion = reactLibVersion
279
+ ? semver.validRange(reactLibVersion)
280
+ : null;
281
+ let minReactLibVersion =
282
+ reactLibVersion !== null && reactLibVersion !== '*'
283
+ ? // @ts-expect-error TS2345
284
+ semver.minVersion(reactLibVersion)?.toString()
285
+ : null;
286
+
287
+ automaticJSXRuntime =
288
+ automaticVersion &&
289
+ !compilerOptions?.jsxFactory &&
290
+ minReactLibVersion != null &&
291
+ semver.satisfies(minReactLibVersion, automaticVersion, {
292
+ includePrerelease: true,
293
+ });
294
+
295
+ if (automaticJSXRuntime) {
296
+ jsxImportSource = reactLib;
297
+ }
298
+ }
299
+
300
+ isJSX = Boolean(compilerOptions?.jsx || jsxPragma);
301
+ }
302
+
303
+ return {
304
+ isJSX,
305
+ jsxPragma,
306
+ jsxPragmaFrag,
307
+ jsxImportSource,
308
+ automaticJSXRuntime,
309
+ reactRefresh,
310
+ };
311
+ }
312
+
313
+ export default new Transformer({
314
+ async loadConfig({config, options}) {
315
+ let conf = await config.getConfigFrom<JsTransformerConfig>(
316
+ options.projectRoot + '/index',
317
+ [],
318
+ {
319
+ packageKey: '@atlaspack/transformer-js',
320
+ },
321
+ );
322
+
323
+ if (conf && conf.contents) {
324
+ validateSchema.diagnostic(
325
+ CONFIG_SCHEMA,
326
+ {
327
+ data: conf.contents,
328
+ source: () => options.inputFS.readFileSync(conf.filePath, 'utf8'),
329
+ filePath: conf.filePath,
330
+ prependKey: `/${encodeJSONKeyComponent('@atlaspack/transformer-js')}`,
331
+ },
332
+ // FIXME
333
+ '@atlaspack/transformer-js',
334
+ 'Invalid config for @atlaspack/transformer-js',
212
335
  );
213
- let compilerOptions = tsconfig?.contents?.compilerOptions;
336
+ }
214
337
 
215
- // Use explicitly defined JSX options in tsconfig.json over inferred values from dependencies.
216
- pragma =
217
- compilerOptions?.jsxFactory ||
218
- (reactLib ? JSX_PRAGMA[reactLib].pragma : undefined);
219
- pragmaFrag =
220
- compilerOptions?.jsxFragmentFactory ||
221
- (reactLib ? JSX_PRAGMA[reactLib].pragmaFrag : undefined);
338
+ let packageJson = await config.getPackage();
339
+ let decorators, useDefineForClassFields;
222
340
 
223
- if (
224
- compilerOptions?.jsx === 'react-jsx' ||
225
- compilerOptions?.jsx === 'react-jsxdev' ||
226
- compilerOptions?.jsxImportSource
227
- ) {
228
- jsxImportSource = compilerOptions?.jsxImportSource;
229
- automaticJSXRuntime = true;
230
- } else if (reactLib) {
231
- let effectiveReactLib =
232
- pkg?.alias && pkg.alias['react'] === 'preact/compat'
233
- ? 'preact'
234
- : reactLib;
235
- let automaticVersion = JSX_PRAGMA[effectiveReactLib]?.automatic;
236
- let reactLibVersion =
237
- pkg?.dependencies?.[effectiveReactLib] ||
238
- pkg?.devDependencies?.[effectiveReactLib] ||
239
- pkg?.peerDependencies?.[effectiveReactLib];
240
- reactLibVersion = reactLibVersion
241
- ? semver.validRange(reactLibVersion)
242
- : null;
243
- let minReactLibVersion =
244
- reactLibVersion !== null && reactLibVersion !== '*'
245
- ? semver.minVersion(reactLibVersion)?.toString()
246
- : null;
247
-
248
- automaticJSXRuntime =
249
- automaticVersion &&
250
- !compilerOptions?.jsxFactory &&
251
- minReactLibVersion != null &&
252
- semver.satisfies(minReactLibVersion, automaticVersion, {
253
- includePrerelease: true,
254
- });
341
+ let {
342
+ isJSX,
343
+ jsxPragma,
344
+ jsxPragmaFrag,
345
+ jsxImportSource,
346
+ automaticJSXRuntime,
347
+ reactRefresh,
348
+ } = options.featureFlags.newJsxConfig
349
+ ? (determineJsxConfiguration(
350
+ config.searchPath,
351
+ config.isSource,
352
+ conf?.contents?.jsx,
353
+ options.projectRoot,
354
+ ) as JsxConfig)
355
+ : await legacyDetemineJsxConfig(config, options);
255
356
 
256
- if (automaticJSXRuntime) {
257
- jsxImportSource = reactLib;
258
- }
259
- }
357
+ if (config.isSource) {
358
+ const compilerOptions: TSConfig['compilerOptions'] = (
359
+ await config.getConfigFrom<TSConfig>(
360
+ options.projectRoot + '/index',
361
+ ['tsconfig.json', 'jsconfig.json'],
362
+ {
363
+ readTracking: true,
364
+ },
365
+ )
366
+ )?.contents?.compilerOptions;
260
367
 
261
- isJSX = Boolean(compilerOptions?.jsx || pragma);
262
368
  decorators = compilerOptions?.experimentalDecorators;
263
369
  useDefineForClassFields = compilerOptions?.useDefineForClassFields;
264
370
  if (
@@ -278,36 +384,83 @@ export default (new Transformer({
278
384
  // Check if we should ignore fs calls
279
385
  // See https://github.com/defunctzombie/node-browser-resolve#skip
280
386
  let ignoreFS =
281
- pkg &&
282
- pkg.browser &&
283
- typeof pkg.browser === 'object' &&
284
- pkg.browser.fs === false;
285
-
286
- let conf = await config.getConfigFrom(options.projectRoot + '/index', [], {
287
- packageKey: '@atlaspack/transformer-js',
288
- });
387
+ packageJson &&
388
+ packageJson.browser &&
389
+ typeof packageJson.browser === 'object' &&
390
+ packageJson.browser.fs === false;
289
391
 
290
392
  let inlineEnvironment = config.isSource;
291
393
  let inlineFS = !ignoreFS;
292
394
  let inlineConstants = false;
293
395
  let magicComments = false;
396
+ let addReactDisplayName = false;
397
+
398
+ let enableSsrTypeofReplacement =
399
+ options.env.NATIVE_SSR_TYPEOF_REPLACEMENT === 'true';
400
+ let globalAliasingConfig =
401
+ options.env.NATIVE_GLOBAL_ALIASING &&
402
+ JSON.parse(options.env.NATIVE_GLOBAL_ALIASING);
403
+ let enableLazyLoading = options.env.NATIVE_LAZY_LOADING === 'true';
404
+ let enableReactHooksRemoval =
405
+ options.env.NATIVE_REACT_HOOKS_REMOVAL === 'true';
406
+ let enableReactAsyncImportLift =
407
+ options.env.NATIVE_REACT_ASYNC_IMPORT_LIFT === 'true';
408
+ let reactAsyncLiftByDefault =
409
+ options.env.REACT_ASYNC_IMPORT_LIFTING_BY_DEFAULT === 'true';
410
+ let reactAsyncLiftReportLevel =
411
+ options.env.REACT_ASYNC_LIFT_REPORT_LEVEL || 'none';
412
+ let enableStaticPrevaluation = options.env.NATIVE_PREVALUATION === 'true';
413
+ let enableDeadReturnsRemoval =
414
+ options.env.NATIVE_DEAD_RETURNS_REMOVAL === 'true';
415
+ let enableUnusedBindingsRemoval =
416
+ options.env.NATIVE_UNUSED_BINDINGS_REMOVAL === 'true';
417
+ let syncDynamicImportConfig:
418
+ | {
419
+ entrypoint_filepath_suffix: string;
420
+ actual_require_paths: string[];
421
+ }
422
+ | undefined;
294
423
 
295
- if (conf && conf.contents) {
296
- validateSchema.diagnostic(
297
- CONFIG_SCHEMA,
298
- {
299
- data: conf.contents,
300
- // FIXME
301
- source: await options.inputFS.readFile(conf.filePath, 'utf8'),
302
- filePath: conf.filePath,
303
- prependKey: `/${encodeJSONKeyComponent('@atlaspack/transformer-js')}`,
304
- },
305
- // FIXME
306
- '@atlaspack/transformer-js',
307
- 'Invalid config for @atlaspack/transformer-js',
308
- );
424
+ if (config.env.isTesseract() && options.env.SYNC_DYNAMIC_IMPORT_CONFIG) {
425
+ try {
426
+ let config = configCache.get(
427
+ 'SYNC_DYNAMIC_IMPORT_CONFIG',
428
+ ) as typeof syncDynamicImportConfig;
429
+
430
+ if (!config) {
431
+ config = JSON.parse(options.env.SYNC_DYNAMIC_IMPORT_CONFIG);
432
+
433
+ invariant(typeof config?.entrypoint_filepath_suffix === 'string');
434
+ invariant(Array.isArray(config.actual_require_paths));
435
+
436
+ configCache.set('SYNC_DYNAMIC_IMPORT_CONFIG', config);
437
+ }
438
+
439
+ syncDynamicImportConfig = config;
440
+ } catch {
441
+ // eslint-disable-next-line no-console
442
+ console.warn(
443
+ 'Failed to parse SYNC_DYNAMIC_IMPORT_CONFIG to JSON or config shape did not match. Config will not be applied.',
444
+ );
445
+
446
+ const fallback = {
447
+ entrypoint_filepath_suffix: '__NO_MATCH__',
448
+ actual_require_paths: [],
449
+ };
450
+
451
+ // Set cache to fallback so we don't keep trying to parse.
452
+ configCache.set('SYNC_DYNAMIC_IMPORT_CONFIG', fallback);
453
+ syncDynamicImportConfig = fallback;
454
+ }
455
+ }
456
+
457
+ config.invalidateOnEnvChange('SYNC_DYNAMIC_IMPORT_CONFIG');
309
458
 
459
+ if (conf && conf.contents) {
460
+ addReactDisplayName =
461
+ conf.contents?.addReactDisplayName ?? addReactDisplayName;
310
462
  magicComments = conf.contents?.magicComments ?? magicComments;
463
+ // @ts-expect-error TS2322
311
464
  inlineEnvironment = conf.contents?.inlineEnvironment ?? inlineEnvironment;
312
465
  inlineFS = conf.contents?.inlineFS ?? inlineFS;
313
466
  inlineConstants =
@@ -318,15 +471,27 @@ export default (new Transformer({
318
471
  isJSX,
319
472
  automaticJSXRuntime,
320
473
  jsxImportSource,
321
- pragma,
322
- pragmaFrag,
474
+ pragma: jsxPragma,
475
+ pragmaFrag: jsxPragmaFrag,
323
476
  inlineEnvironment,
324
477
  inlineFS,
325
478
  inlineConstants,
479
+ addReactDisplayName,
326
480
  reactRefresh,
327
481
  decorators,
328
482
  useDefineForClassFields,
329
483
  magicComments,
484
+ globalAliasingConfig,
485
+ enableSsrTypeofReplacement,
486
+ enableLazyLoading,
487
+ enableDeadReturnsRemoval,
488
+ enableUnusedBindingsRemoval,
489
+ enableStaticPrevaluation,
490
+ enableReactHooksRemoval,
491
+ syncDynamicImportConfig,
492
+ enableReactAsyncImportLift,
493
+ reactAsyncLiftByDefault,
494
+ reactAsyncLiftReportLevel,
330
495
  };
331
496
  },
332
497
  async transform({asset, config, options, logger}) {
@@ -357,6 +522,7 @@ export default (new Transformer({
357
522
  for (let browser of browsers) {
358
523
  let [name, version] = browser.split(' ');
359
524
  if (BROWSER_MAPPING.hasOwnProperty(name)) {
525
+ // @ts-expect-error TS7053
360
526
  name = BROWSER_MAPPING[name];
361
527
  if (!name) {
362
528
  continue;
@@ -366,12 +532,15 @@ export default (new Transformer({
366
532
  let [major, minor = '0', patch = '0'] = version
367
533
  .split('-')[0]
368
534
  .split('.');
535
+ // @ts-expect-error TS2345
369
536
  if (isNaN(major) || isNaN(minor) || isNaN(patch)) {
370
537
  continue;
371
538
  }
372
539
  let semverVersion = `${major}.${minor}.${patch}`;
373
540
 
541
+ // @ts-expect-error TS2345
374
542
  if (targets[name] == null || semver.gt(targets[name], semverVersion)) {
543
+ // @ts-expect-error TS7053
375
544
  targets[name] = semverVersion;
376
545
  }
377
546
  }
@@ -411,24 +580,47 @@ export default (new Transformer({
411
580
  if (asset.type === 'ts') {
412
581
  isJSX = false;
413
582
  } else if (!isJSX) {
583
+ // @ts-expect-error TS7053
414
584
  isJSX = Boolean(JSX_EXTENSIONS[asset.type]);
415
585
  }
416
586
  }
417
587
 
418
- let macroAssets = [];
588
+ let macroAssets: Array<{
589
+ content: string;
590
+ // @ts-expect-error TS2552
591
+ map: undefined | NodeSourceMap;
592
+ type: string;
593
+ uniqueKey: string;
594
+ }> = [];
419
595
  let {
596
+ // @ts-expect-error TS2339
420
597
  dependencies,
598
+ // @ts-expect-error TS2339
421
599
  code: compiledCode,
600
+ // @ts-expect-error TS2339
422
601
  map,
602
+ // @ts-expect-error TS2339
423
603
  shebang,
604
+ // @ts-expect-error TS2339
424
605
  hoist_result,
606
+ // @ts-expect-error TS2339
425
607
  symbol_result,
608
+ // @ts-expect-error TS2339
609
+ is_empty_or_empty_export,
610
+ // @ts-expect-error TS2339
426
611
  needs_esm_helpers,
612
+ // @ts-expect-error TS2339
427
613
  diagnostics,
614
+ // @ts-expect-error TS2339
428
615
  used_env,
616
+ // @ts-expect-error TS2339
429
617
  has_node_replacements,
618
+ // @ts-expect-error TS2339
430
619
  is_constant_module,
620
+ // @ts-expect-error TS2339
431
621
  conditions,
622
+ // @ts-expect-error TS2339
623
+ magic_comments,
432
624
  } = await (transformAsync || transform)({
433
625
  filename: asset.filePath,
434
626
  code,
@@ -440,7 +632,7 @@ export default (new Transformer({
440
632
  !asset.env.isNode() && asset.env.sourceType !== 'script',
441
633
  node_replacer: asset.env.isNode(),
442
634
  is_browser: asset.env.isBrowser(),
443
- is_worker: asset.env.isWorker(),
635
+ is_worker: asset.env.isWorker() || asset.env.isTesseract(),
444
636
  env,
445
637
  is_type_script: asset.type === 'ts' || asset.type === 'tsx',
446
638
  is_jsx: isJSX,
@@ -449,12 +641,16 @@ export default (new Transformer({
449
641
  automatic_jsx_runtime: Boolean(config?.automaticJSXRuntime),
450
642
  jsx_import_source: config?.jsxImportSource,
451
643
  is_development: options.mode === 'development',
452
- react_refresh:
644
+ react_refresh: Boolean(
453
645
  asset.env.isBrowser() &&
454
- !asset.env.isLibrary &&
455
- !asset.env.isWorker() &&
456
- !asset.env.isWorklet() &&
457
- Boolean(config?.reactRefresh),
646
+ !asset.env.isLibrary &&
647
+ !asset.env.isWorker() &&
648
+ !asset.env.isTesseract() &&
649
+ !asset.env.isWorklet() &&
650
+ config?.reactRefresh &&
651
+ options.hmrOptions &&
652
+ options.mode === 'development',
653
+ ),
458
654
  decorators: Boolean(config?.decorators),
459
655
  use_define_for_class_fields: Boolean(config?.useDefineForClassFields),
460
656
  targets,
@@ -470,9 +666,32 @@ export default (new Transformer({
470
666
  standalone: asset.query.has('standalone'),
471
667
  inline_constants: config.inlineConstants,
472
668
  conditional_bundling: options.featureFlags.conditionalBundlingApi,
473
- magic_comments: Boolean(config?.magicComments),
669
+ hmr_improvements: options.featureFlags.hmrImprovements,
670
+ add_display_name: Boolean(config.addReactDisplayName),
671
+ exports_rebinding_optimisation:
672
+ options.featureFlags.exportsRebindingOptimisation,
673
+ magic_comments:
674
+ Boolean(config?.magicComments) ||
675
+ getFeatureFlag('supportWebpackChunkName'),
676
+ is_source: asset.isSource,
677
+ nested_promise_import_fix: options.featureFlags.nestedPromiseImportFix,
678
+ global_aliasing_config: config.globalAliasingConfig,
679
+ enable_ssr_typeof_replacement: Boolean(config.enableSsrTypeofReplacement),
680
+ enable_lazy_loading: Boolean(config.enableLazyLoading),
681
+ enable_dead_returns_removal: Boolean(config.enableDeadReturnsRemoval),
682
+ enable_unused_bindings_removal: Boolean(
683
+ config.enableUnusedBindingsRemoval,
684
+ ),
685
+ enable_static_prevaluation: Boolean(config.enableStaticPrevaluation),
686
+ enable_react_hooks_removal: Boolean(config.enableReactHooksRemoval),
687
+ enable_react_async_import_lift: Boolean(
688
+ config.enableReactAsyncImportLift,
689
+ ),
690
+ react_async_lift_by_default: Boolean(config.reactAsyncLiftByDefault),
691
+ react_async_lift_report_level: String(config.reactAsyncLiftReportLevel),
692
+ sync_dynamic_import_config: config.syncDynamicImportConfig,
474
693
  callMacro: asset.isSource
475
- ? async (err, src, exportName, args, loc) => {
694
+ ? async (err: any, src: any, exportName: any, args: any, loc: any) => {
476
695
  let mod;
477
696
  try {
478
697
  mod = await options.packageManager.require(src, asset.filePath);
@@ -481,7 +700,6 @@ export default (new Transformer({
481
700
  if (
482
701
  exportName === 'default' &&
483
702
  !mod.__esModule &&
484
- // $FlowFixMe
485
703
  Object.prototype.toString.call(config) !== '[object Module]'
486
704
  ) {
487
705
  mod = {default: mod};
@@ -490,7 +708,7 @@ export default (new Transformer({
490
708
  if (!Object.hasOwnProperty.call(mod, exportName)) {
491
709
  throw new Error(`"${src}" does not export "${exportName}".`);
492
710
  }
493
- } catch (err) {
711
+ } catch (err: any) {
494
712
  throw {
495
713
  kind: 1,
496
714
  message: err.message,
@@ -507,7 +725,8 @@ export default (new Transformer({
507
725
  if (asset.env.sourceMap) {
508
726
  // Generate a source map that maps each line of the asset to the original macro call.
509
727
  map = new SourceMap(options.projectRoot);
510
- let mappings = [];
728
+ // @ts-expect-error TS2304
729
+ let mappings: Array<IndexedMapping<string>> = [];
511
730
  let line = 1;
512
731
  for (let i = 0; i <= a.content.length; i++) {
513
732
  if (i === a.content.length || a.content[i] === '\n') {
@@ -530,7 +749,9 @@ export default (new Transformer({
530
749
  if (originalMap) {
531
750
  map.extends(originalMap);
532
751
  } else {
533
- map.setSourceContent(asset.filePath, code.toString());
752
+ if (!getFeatureFlag('omitSourcesContentInMemory')) {
753
+ map.setSourceContent(asset.filePath, code.toString());
754
+ }
534
755
  }
535
756
  }
536
757
 
@@ -546,13 +767,13 @@ export default (new Transformer({
546
767
  specifierType: 'esm',
547
768
  });
548
769
  },
549
- invalidateOnFileChange(filePath) {
770
+ invalidateOnFileChange(filePath: FilePath) {
550
771
  asset.invalidateOnFileChange(filePath);
551
772
  },
552
- invalidateOnFileCreate(invalidation) {
773
+ invalidateOnFileCreate(invalidation: FileCreateInvalidation) {
553
774
  asset.invalidateOnFileCreate(invalidation);
554
775
  },
555
- invalidateOnEnvChange(env) {
776
+ invalidateOnEnvChange(env: string) {
556
777
  asset.invalidateOnEnvChange(env);
557
778
  },
558
779
  invalidateOnStartup() {
@@ -569,7 +790,7 @@ export default (new Transformer({
569
790
  `"${exportName}" in "${src}" is not a function.`,
570
791
  );
571
792
  }
572
- } catch (err) {
793
+ } catch (err: any) {
573
794
  // Remove atlaspack core from stack and build string so Rust can process errors more easily.
574
795
  let stack = (err.stack || '').split('\n').slice(1);
575
796
  let message = err.message;
@@ -589,18 +810,14 @@ export default (new Transformer({
589
810
  });
590
811
 
591
812
  if (getFeatureFlag('conditionalBundlingApi')) {
592
- asset.meta.conditions = conditions.map((c): ConditionMeta => ({
593
- key: c.key,
594
- ifTruePlaceholder: c.if_true_placeholder,
595
- ifFalsePlaceholder: c.if_false_placeholder,
596
- }));
813
+ asset.meta.conditions = conditions;
597
814
  }
598
815
 
599
816
  if (is_constant_module) {
600
817
  asset.meta.isConstantModule = true;
601
818
  }
602
819
 
603
- let convertLoc = (loc): SourceLocation => {
820
+ let convertLoc = (loc: any): SourceLocation => {
604
821
  let location = {
605
822
  filePath: asset.filePath,
606
823
  start: {
@@ -615,7 +832,11 @@ export default (new Transformer({
615
832
 
616
833
  // If there is an original source map, use it to remap to the original source location.
617
834
  if (originalMap) {
618
- location = remapSourceLocation(location, originalMap);
835
+ location = remapSourceLocation(
836
+ location,
837
+ originalMap,
838
+ options.projectRoot,
839
+ );
619
840
  }
620
841
 
621
842
  return location;
@@ -623,19 +844,22 @@ export default (new Transformer({
623
844
 
624
845
  if (diagnostics) {
625
846
  let errors = diagnostics.filter(
847
+ // @ts-expect-error TS7006
626
848
  (d) =>
627
849
  d.severity === 'Error' ||
628
850
  (d.severity === 'SourceError' && asset.isSource),
629
851
  );
630
852
  let warnings = diagnostics.filter(
853
+ // @ts-expect-error TS7006
631
854
  (d) =>
632
855
  d.severity === 'Warning' ||
633
856
  (d.severity === 'SourceError' && !asset.isSource),
634
857
  );
635
- let convertDiagnostic = (diagnostic) => {
858
+ let convertDiagnostic = (diagnostic: any) => {
636
859
  let message = diagnostic.message;
637
860
  if (message === 'SCRIPT_ERROR') {
638
- let err = SCRIPT_ERRORS[(asset.env.context: string)];
861
+ // @ts-expect-error TS7053
862
+ let err = SCRIPT_ERRORS[asset.env.context as string];
639
863
  message = err?.message || SCRIPT_ERRORS.browser.message;
640
864
  }
641
865
 
@@ -644,11 +868,12 @@ export default (new Transformer({
644
868
  codeFrames: [
645
869
  {
646
870
  filePath: asset.filePath,
647
- codeHighlights: diagnostic.code_highlights?.map((highlight) =>
648
- convertSourceLocationToHighlight(
649
- convertLoc(highlight.loc),
650
- highlight.message ?? undefined,
651
- ),
871
+ codeHighlights: diagnostic.code_highlights?.map(
872
+ (highlight: any) =>
873
+ convertSourceLocationToHighlight(
874
+ convertLoc(highlight.loc),
875
+ highlight.message ?? undefined,
876
+ ),
652
877
  ),
653
878
  },
654
879
  ],
@@ -672,7 +897,8 @@ export default (new Transformer({
672
897
  });
673
898
  }
674
899
 
675
- let err = SCRIPT_ERRORS[(asset.env.context: string)];
900
+ // @ts-expect-error TS7053
901
+ let err = SCRIPT_ERRORS[asset.env.context as string];
676
902
  if (err) {
677
903
  if (!res.hints) {
678
904
  res.hints = [err.hint];
@@ -729,6 +955,7 @@ export default (new Transformer({
729
955
  env: {
730
956
  context: 'web-worker',
731
957
  sourceType: dep.source_type === 'Module' ? 'module' : 'script',
958
+ // @ts-expect-error TS2322
732
959
  outputFormat,
733
960
  loc,
734
961
  },
@@ -776,6 +1003,13 @@ export default (new Transformer({
776
1003
  });
777
1004
  } else if (dep.kind === 'File') {
778
1005
  asset.invalidateOnFileChange(dep.specifier);
1006
+ } else if (dep.kind === 'Id') {
1007
+ // Record parcelRequire calls so that the dev packager can add them as dependencies.
1008
+ // This allows the HMR runtime to collect parents across async boundaries (through runtimes).
1009
+ // TODO: ideally this would result as an actual dep in the graph rather than asset.meta.
1010
+ asset.meta.hmrDeps ??= [];
1011
+ invariant(Array.isArray(asset.meta.hmrDeps));
1012
+ asset.meta.hmrDeps.push(dep.specifier);
779
1013
  } else {
780
1014
  let meta: JSONObject = {kind: dep.kind};
781
1015
  if (dep.attributes) {
@@ -839,6 +1073,13 @@ export default (new Transformer({
839
1073
  outputFormat,
840
1074
  loc: convertLoc(dep.loc),
841
1075
  };
1076
+
1077
+ if (getFeatureFlag('supportWebpackChunkName')) {
1078
+ let chunkName = magic_comments[dep.specifier];
1079
+ if (chunkName) {
1080
+ meta.chunkName = chunkName;
1081
+ }
1082
+ }
842
1083
  }
843
1084
 
844
1085
  // Always bundle helpers, even with includeNodeModules: false, except if this is a library.
@@ -863,6 +1104,7 @@ export default (new Transformer({
863
1104
  idx = dep.specifier.indexOf('/', idx + 1);
864
1105
  }
865
1106
  let module = idx >= 0 ? dep.specifier.slice(0, idx) : dep.specifier;
1107
+ // @ts-expect-error TS7053
866
1108
  range = pkg.dependencies[module];
867
1109
  }
868
1110
 
@@ -874,12 +1116,13 @@ export default (new Transformer({
874
1116
  dep.kind === 'DynamicImport'
875
1117
  ? 'lazy'
876
1118
  : dep.kind === 'ConditionalImport'
877
- ? 'conditional'
878
- : 'sync',
1119
+ ? 'conditional'
1120
+ : 'sync',
879
1121
  isOptional: dep.is_optional,
880
1122
  meta,
881
1123
  resolveFrom: isHelper ? __filename : undefined,
882
1124
  range,
1125
+ // @ts-expect-error TS2322
883
1126
  env,
884
1127
  });
885
1128
  }
@@ -893,8 +1136,12 @@ export default (new Transformer({
893
1136
  local,
894
1137
  loc,
895
1138
  is_esm,
1139
+ is_static_binding_safe,
896
1140
  } of hoist_result.exported_symbols) {
897
- asset.symbols.set(exported, local, convertLoc(loc), {isEsm: is_esm});
1141
+ asset.symbols.set(exported, local, convertLoc(loc), {
1142
+ isEsm: is_esm,
1143
+ isStaticBindingSafe: is_static_binding_safe,
1144
+ });
898
1145
  }
899
1146
 
900
1147
  // deps is a map of dependencies that are keyed by placeholder or specifier
@@ -991,6 +1238,9 @@ export default (new Transformer({
991
1238
  Object.keys(hoist_result.exported_symbols).length === 0) ||
992
1239
  (hoist_result.should_wrap && !asset.symbols.hasExportSymbol('*'))
993
1240
  ) {
1241
+ if (is_empty_or_empty_export) {
1242
+ asset.meta.emptyFileStarReexport = true;
1243
+ }
994
1244
  asset.symbols.set('*', `$${asset.id}$exports`);
995
1245
  }
996
1246
 
@@ -1093,4 +1343,4 @@ export default (new Transformer({
1093
1343
 
1094
1344
  return [asset, ...macroAssets];
1095
1345
  },
1096
- }): Transformer);
1346
+ }) as Transformer<unknown>;