@atlaspack/transformer-js 3.2.3-canary.36 → 3.2.3-canary.360

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,24 @@
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 {type CompiledCssInJsConfigPlugin} from '@atlaspack/rust/index';
21
+ import invariant from 'assert';
15
22
  import browserslist from 'browserslist';
16
23
  import semver from 'semver';
17
24
  import nullthrows from 'nullthrows';
@@ -22,11 +29,12 @@ import ThrowableDiagnostic, {
22
29
  import {validateSchema, remapSourceLocation, globMatch} from '@atlaspack/utils';
23
30
  import pkg from '../package.json';
24
31
  import {getFeatureFlag} from '@atlaspack/feature-flags';
32
+ import path, {join} from 'path';
25
33
 
26
34
  const JSX_EXTENSIONS = {
27
35
  jsx: true,
28
36
  tsx: true,
29
- };
37
+ } as const;
30
38
 
31
39
  const JSX_PRAGMA = {
32
40
  react: {
@@ -49,7 +57,7 @@ const JSX_PRAGMA = {
49
57
  pragmaFrag: undefined,
50
58
  automatic: undefined,
51
59
  },
52
- };
60
+ } as const;
53
61
 
54
62
  const BROWSER_MAPPING = {
55
63
  and_chr: 'chrome',
@@ -63,7 +71,7 @@ const BROWSER_MAPPING = {
63
71
  bb: null,
64
72
  kaios: null,
65
73
  op_mini: null,
66
- };
74
+ } as const;
67
75
 
68
76
  // List of browsers to exclude when the esmodule target is specified.
69
77
  // Based on https://caniuse.com/#feat=es6-module
@@ -108,16 +116,35 @@ const CONFIG_SCHEMA: SchemaEntity = {
108
116
  },
109
117
  ],
110
118
  },
119
+ addReactDisplayName: {
120
+ type: 'boolean',
121
+ },
111
122
  magicComments: {
112
123
  type: 'boolean',
113
124
  },
114
125
  unstable_inlineConstants: {
115
126
  type: 'boolean',
116
127
  },
128
+ jsx: {
129
+ type: 'object',
130
+ },
117
131
  },
118
132
  additionalProperties: false,
119
133
  };
120
134
 
135
+ // Mirrors the CONFIG_SCHEMA
136
+ interface JsTransformerConfig {
137
+ inlineFS?: boolean;
138
+ inlineEnvironment?: boolean | string[];
139
+ addReactDisplayName?: boolean;
140
+ magicComments?: boolean;
141
+ unstable_inlineConstants?: boolean;
142
+ // This is exclusively used in Rust so not worth typing
143
+ jsx: any;
144
+ }
145
+
146
+ const configCache = createBuildCache();
147
+
121
148
  const SCRIPT_ERRORS = {
122
149
  browser: {
123
150
  message: 'Browser scripts cannot have imports or exports.',
@@ -133,132 +160,299 @@ const SCRIPT_ERRORS = {
133
160
  'Service workers cannot have imports or exports without the `type: "module"` option.',
134
161
  hint: "Add {type: 'module'} as a second argument to the navigator.serviceWorker.register() call.",
135
162
  },
136
- };
163
+ } as const;
137
164
 
138
165
  type TSConfig = {
139
166
  compilerOptions?: {
140
167
  // https://www.typescriptlang.org/tsconfig#jsx
141
- jsx?: 'react' | 'react-jsx' | 'react-jsxdev' | 'preserve' | 'react-native',
168
+ jsx?: 'react' | 'react-jsx' | 'react-jsxdev' | 'preserve' | 'react-native';
142
169
  // https://www.typescriptlang.org/tsconfig#jsxFactory
143
- jsxFactory?: string,
170
+ jsxFactory?: string;
144
171
  // https://www.typescriptlang.org/tsconfig#jsxFragmentFactory
145
- jsxFragmentFactory?: string,
172
+ jsxFragmentFactory?: string;
146
173
  // https://www.typescriptlang.org/tsconfig#jsxImportSource
147
- jsxImportSource?: string,
174
+ jsxImportSource?: string;
148
175
  // https://www.typescriptlang.org/tsconfig#experimentalDecorators
149
- experimentalDecorators?: boolean,
176
+ experimentalDecorators?: boolean;
150
177
  // https://www.typescriptlang.org/tsconfig#useDefineForClassFields
151
- useDefineForClassFields?: boolean,
178
+ useDefineForClassFields?: boolean;
152
179
  // https://www.typescriptlang.org/tsconfig#target
153
- target?: string, // 'es3' | 'es5' | 'es6' | 'es2015' | ... |'es2022' | ... | 'esnext'
154
- ...
155
- },
156
- ...
180
+ target?: string; // 'es3' | 'es5' | 'es6' | 'es2015' | ... |'es2022' | ... | 'esnext';
181
+ };
157
182
  };
158
183
 
159
- type MacroAsset = {|
160
- type: string,
161
- content: string,
162
- |};
184
+ type MacroAsset = {
185
+ type: string;
186
+ content: string;
187
+ };
163
188
 
164
189
  // 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
- }
190
+ type MacroContext = {
191
+ addAsset(asset: MacroAsset): void;
192
+ invalidateOnFileChange(arg1: FilePath): void;
193
+ invalidateOnFileCreate(arg1: FileCreateInvalidation): void;
194
+ invalidateOnEnvChange(arg1: string): void;
195
+ invalidateOnStartup(): void;
196
+ invalidateOnBuild(): void;
197
+ };
199
198
 
200
- reactRefresh =
201
- options.hmrOptions &&
202
- options.mode === 'development' &&
203
- Boolean(
204
- pkg?.dependencies?.react ||
205
- pkg?.devDependencies?.react ||
206
- pkg?.peerDependencies?.react,
207
- );
199
+ type AtlaskitTokensConfigPartial = {
200
+ shouldUseAutoFallback?: boolean;
201
+ shouldForceAutoFallback?: boolean;
202
+ forceAutoFallbackExemptions?: Array<string>;
203
+ defaultTheme?: 'light' | 'legacy-light';
204
+ tokenDataPath: string;
205
+ };
208
206
 
209
- let tsconfig = await config.getConfigFrom<TSConfig>(
210
- options.projectRoot + '/index',
211
- ['tsconfig.json', 'jsconfig.json'],
207
+ type AtlaskitTokensConfig = Required<AtlaskitTokensConfigPartial>;
208
+
209
+ const TOKENS_CONFIG_SCHEMA = {
210
+ type: 'object',
211
+ properties: {
212
+ shouldUseAutoFallback: {type: 'boolean'},
213
+ shouldForceAutoFallback: {type: 'boolean'},
214
+ forceAutoFallbackExemptions: {
215
+ type: 'array',
216
+ items: {type: 'string'},
217
+ },
218
+ defaultTheme: {type: 'string', enum: ['light', 'legacy-light']},
219
+ tokenDataPath: {type: 'string'},
220
+ },
221
+ additionalProperties: false,
222
+ } as const;
223
+
224
+ interface JsxConfig {
225
+ isJSX: boolean | undefined;
226
+ jsxPragma: string | undefined;
227
+ jsxPragmaFrag: string | undefined;
228
+ jsxImportSource: string | undefined;
229
+ automaticJSXRuntime: boolean | undefined;
230
+ reactRefresh: boolean | null | undefined;
231
+ }
232
+
233
+ async function legacyDetemineJsxConfig(
234
+ config: Config,
235
+ options: PluginOptions,
236
+ ): Promise<JsxConfig> {
237
+ let packageJson = await config.getPackage();
238
+ let isJSX,
239
+ jsxPragma,
240
+ jsxPragmaFrag,
241
+ jsxImportSource,
242
+ automaticJSXRuntime,
243
+ reactRefresh;
244
+
245
+ if (config.isSource) {
246
+ let reactLib;
247
+ if (packageJson?.alias && packageJson.alias['react']) {
248
+ // e.g.: `{ alias: { "react": "preact/compat" } }`
249
+ reactLib = 'react';
250
+ } else {
251
+ // Find a dependency that we can map to a JSX pragma
252
+ reactLib = Object.keys(JSX_PRAGMA).find(
253
+ (libName) =>
254
+ packageJson?.dependencies?.[libName] ||
255
+ packageJson?.devDependencies?.[libName] ||
256
+ packageJson?.peerDependencies?.[libName],
212
257
  );
213
- let compilerOptions = tsconfig?.contents?.compilerOptions;
258
+ }
214
259
 
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);
260
+ reactRefresh = Boolean(
261
+ packageJson?.dependencies?.react ||
262
+ packageJson?.devDependencies?.react ||
263
+ packageJson?.peerDependencies?.react,
264
+ );
222
265
 
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)
266
+ const compilerOptions: TSConfig['compilerOptions'] = (
267
+ await config.getConfigFrom<TSConfig>(
268
+ options.projectRoot + '/index',
269
+ ['tsconfig.json', 'jsconfig.json'],
270
+ {
271
+ readTracking: true,
272
+ },
273
+ )
274
+ )?.contents?.compilerOptions;
275
+
276
+ // Use explicitly defined JSX options in tsconfig.json over inferred values from dependencies.
277
+ jsxPragma =
278
+ compilerOptions?.jsxFactory ||
279
+ // @ts-expect-error TS7053
280
+ (reactLib ? JSX_PRAGMA[reactLib].pragma : undefined);
281
+ jsxPragmaFrag =
282
+ compilerOptions?.jsxFragmentFactory ||
283
+ // @ts-expect-error TS7053
284
+ (reactLib ? JSX_PRAGMA[reactLib].pragmaFrag : undefined);
285
+
286
+ if (
287
+ compilerOptions?.jsx === 'react-jsx' ||
288
+ compilerOptions?.jsx === 'react-jsxdev' ||
289
+ compilerOptions?.jsxImportSource
290
+ ) {
291
+ jsxImportSource = compilerOptions?.jsxImportSource;
292
+ automaticJSXRuntime = true;
293
+ } else if (reactLib) {
294
+ let effectiveReactLib =
295
+ packageJson?.alias && packageJson.alias['react'] === 'preact/compat'
296
+ ? 'preact'
297
+ : reactLib;
298
+ // @ts-expect-error TS7053
299
+ let automaticVersion = JSX_PRAGMA[effectiveReactLib]?.automatic;
300
+ let reactLibVersion =
301
+ packageJson?.dependencies?.[effectiveReactLib] ||
302
+ packageJson?.devDependencies?.[effectiveReactLib] ||
303
+ packageJson?.peerDependencies?.[effectiveReactLib];
304
+ // @ts-expect-error TS2322
305
+ reactLibVersion = reactLibVersion
306
+ ? semver.validRange(reactLibVersion)
307
+ : null;
308
+ let minReactLibVersion =
309
+ reactLibVersion !== null && reactLibVersion !== '*'
310
+ ? // @ts-expect-error TS2345
311
+ semver.minVersion(reactLibVersion)?.toString()
242
312
  : 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
- });
255
313
 
256
- if (automaticJSXRuntime) {
257
- jsxImportSource = reactLib;
258
- }
314
+ automaticJSXRuntime =
315
+ automaticVersion &&
316
+ !compilerOptions?.jsxFactory &&
317
+ minReactLibVersion != null &&
318
+ semver.satisfies(minReactLibVersion, automaticVersion, {
319
+ includePrerelease: true,
320
+ });
321
+
322
+ if (automaticJSXRuntime) {
323
+ jsxImportSource = reactLib;
259
324
  }
325
+ }
326
+
327
+ isJSX = Boolean(compilerOptions?.jsx || jsxPragma);
328
+ }
329
+
330
+ return {
331
+ isJSX,
332
+ jsxPragma,
333
+ jsxPragmaFrag,
334
+ jsxImportSource,
335
+ automaticJSXRuntime,
336
+ reactRefresh,
337
+ };
338
+ }
339
+
340
+ export async function loadTokensConfig(config: Config, options: PluginOptions) {
341
+ const conf = await config.getConfigFrom(options.projectRoot + '/index', [], {
342
+ packageKey: '@atlaspack/transformer-tokens',
343
+ });
344
+
345
+ if (conf && conf.contents) {
346
+ validateSchema.diagnostic(
347
+ TOKENS_CONFIG_SCHEMA,
348
+ {
349
+ data: conf.contents,
350
+ source: () => options.inputFS.readFileSync(conf.filePath, 'utf8'),
351
+ filePath: conf.filePath,
352
+ prependKey: `/${encodeJSONKeyComponent('@atlaspack/transformer-tokens')}`,
353
+ },
354
+ '@atlaspack/transformer-tokens',
355
+ 'Invalid config for @atlaspack/transformer-tokens',
356
+ );
357
+
358
+ // @ts-expect-error TS2339
359
+ const tokensConfig: AtlaskitTokensConfigPartial = conf.contents;
360
+
361
+ let resolvedConfig: AtlaskitTokensConfig = {
362
+ shouldUseAutoFallback: tokensConfig.shouldUseAutoFallback ?? true,
363
+ shouldForceAutoFallback: tokensConfig.shouldForceAutoFallback ?? true,
364
+ forceAutoFallbackExemptions:
365
+ tokensConfig.forceAutoFallbackExemptions ?? [],
366
+ defaultTheme: tokensConfig.defaultTheme ?? 'light',
367
+ tokenDataPath: path.join(options.projectRoot, tokensConfig.tokenDataPath),
368
+ };
369
+ return resolvedConfig;
370
+ }
371
+ }
372
+
373
+ export async function loadCompiledCssInJsConfig(
374
+ config: Config,
375
+ options: PluginOptions,
376
+ ): Promise<CompiledCssInJsConfigPlugin> {
377
+ const conf = await config.getConfigFrom<CompiledCssInJsConfigPlugin>(
378
+ join(options.projectRoot, 'index'),
379
+ ['.compiledcssrc', '.compiledcssrc.json'],
380
+ {
381
+ packageKey: '@atlaspack/transformer-compiled-css-in-js',
382
+ },
383
+ );
384
+
385
+ const contents: CompiledCssInJsConfigPlugin = {
386
+ configPath: conf?.filePath,
387
+ importSources: ['@compiled/react', '@atlaskit/css'],
388
+ };
389
+
390
+ Object.assign(contents, conf?.contents);
391
+
392
+ if (!contents.importSources?.includes('@compiled/react')) {
393
+ contents.importSources?.push('@compiled/react');
394
+ }
395
+
396
+ contents.extract = contents.extract && options.mode !== 'development';
397
+
398
+ return contents;
399
+ }
400
+
401
+ export default new Transformer({
402
+ async loadConfig({config, options}) {
403
+ let conf = await config.getConfigFrom<JsTransformerConfig>(
404
+ options.projectRoot + '/index',
405
+ [],
406
+ {
407
+ packageKey: '@atlaspack/transformer-js',
408
+ },
409
+ );
410
+
411
+ if (conf && conf.contents) {
412
+ validateSchema.diagnostic(
413
+ CONFIG_SCHEMA,
414
+ {
415
+ data: conf.contents,
416
+ source: () => options.inputFS.readFileSync(conf.filePath, 'utf8'),
417
+ filePath: conf.filePath,
418
+ prependKey: `/${encodeJSONKeyComponent('@atlaspack/transformer-js')}`,
419
+ },
420
+ // FIXME
421
+ '@atlaspack/transformer-js',
422
+ 'Invalid config for @atlaspack/transformer-js',
423
+ );
424
+ }
425
+
426
+ let packageJson = await config.getPackage();
427
+ let decorators, useDefineForClassFields;
428
+
429
+ let {
430
+ isJSX,
431
+ jsxPragma,
432
+ jsxPragmaFrag,
433
+ jsxImportSource,
434
+ automaticJSXRuntime,
435
+ reactRefresh,
436
+ } = options.featureFlags.newJsxConfig
437
+ ? (determineJsxConfiguration(
438
+ config.searchPath,
439
+ config.isSource,
440
+ conf?.contents?.jsx,
441
+ options.projectRoot,
442
+ ) as JsxConfig)
443
+ : await legacyDetemineJsxConfig(config, options);
444
+
445
+ if (config.isSource) {
446
+ const compilerOptions: TSConfig['compilerOptions'] = (
447
+ await config.getConfigFrom<TSConfig>(
448
+ options.projectRoot + '/index',
449
+ ['tsconfig.json', 'jsconfig.json'],
450
+ {
451
+ readTracking: true,
452
+ },
453
+ )
454
+ )?.contents?.compilerOptions;
260
455
 
261
- isJSX = Boolean(compilerOptions?.jsx || pragma);
262
456
  decorators = compilerOptions?.experimentalDecorators;
263
457
  useDefineForClassFields = compilerOptions?.useDefineForClassFields;
264
458
  if (
@@ -278,36 +472,93 @@ export default (new Transformer({
278
472
  // Check if we should ignore fs calls
279
473
  // See https://github.com/defunctzombie/node-browser-resolve#skip
280
474
  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
- });
475
+ packageJson &&
476
+ packageJson.browser &&
477
+ typeof packageJson.browser === 'object' &&
478
+ packageJson.browser.fs === false;
289
479
 
290
480
  let inlineEnvironment = config.isSource;
291
481
  let inlineFS = !ignoreFS;
292
482
  let inlineConstants = false;
293
483
  let magicComments = false;
484
+ let addReactDisplayName = false;
485
+
486
+ let enableSsrTypeofReplacement =
487
+ options.env.NATIVE_SSR_TYPEOF_REPLACEMENT === 'true';
488
+ let globalAliasingConfig =
489
+ options.env.NATIVE_GLOBAL_ALIASING &&
490
+ JSON.parse(options.env.NATIVE_GLOBAL_ALIASING);
491
+ let enableLazyLoading = options.env.NATIVE_LAZY_LOADING === 'true';
492
+ let enableReactHooksRemoval =
493
+ options.env.NATIVE_REACT_HOOKS_REMOVAL === 'true';
494
+ let enableReactAsyncImportLift =
495
+ options.env.NATIVE_REACT_ASYNC_IMPORT_LIFT === 'true';
496
+ let reactAsyncLiftByDefault =
497
+ options.env.REACT_ASYNC_IMPORT_LIFTING_BY_DEFAULT === 'true';
498
+ let reactAsyncLiftReportLevel =
499
+ options.env.REACT_ASYNC_LIFT_REPORT_LEVEL || 'none';
500
+ let enableStaticPrevaluation = options.env.NATIVE_PREVALUATION === 'true';
501
+ let enableDeadReturnsRemoval =
502
+ options.env.NATIVE_DEAD_RETURNS_REMOVAL === 'true';
503
+ let enableUnusedBindingsRemoval =
504
+ options.env.NATIVE_UNUSED_BINDINGS_REMOVAL === 'true';
505
+ let syncDynamicImportConfig:
506
+ | {
507
+ entrypoint_filepath_suffix: string;
508
+ actual_require_paths: string[];
509
+ }
510
+ | undefined;
294
511
 
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
- );
512
+ if (config.env.isTesseract() && options.env.SYNC_DYNAMIC_IMPORT_CONFIG) {
513
+ try {
514
+ let config = configCache.get(
515
+ 'SYNC_DYNAMIC_IMPORT_CONFIG',
516
+ ) as typeof syncDynamicImportConfig;
517
+
518
+ if (!config) {
519
+ config = JSON.parse(options.env.SYNC_DYNAMIC_IMPORT_CONFIG);
520
+
521
+ invariant(typeof config?.entrypoint_filepath_suffix === 'string');
522
+ invariant(Array.isArray(config.actual_require_paths));
523
+
524
+ configCache.set('SYNC_DYNAMIC_IMPORT_CONFIG', config);
525
+ }
526
+
527
+ syncDynamicImportConfig = config;
528
+ } catch {
529
+ // eslint-disable-next-line no-console
530
+ console.warn(
531
+ 'Failed to parse SYNC_DYNAMIC_IMPORT_CONFIG to JSON or config shape did not match. Config will not be applied.',
532
+ );
533
+
534
+ const fallback = {
535
+ entrypoint_filepath_suffix: '__NO_MATCH__',
536
+ actual_require_paths: [],
537
+ };
538
+
539
+ // Set cache to fallback so we don't keep trying to parse.
540
+ configCache.set('SYNC_DYNAMIC_IMPORT_CONFIG', fallback);
541
+ syncDynamicImportConfig = fallback;
542
+ }
543
+ }
544
+
545
+ config.invalidateOnEnvChange('SYNC_DYNAMIC_IMPORT_CONFIG');
546
+
547
+ const tokensConfig = getFeatureFlag('coreTokensAndCompiledCssInJsTransform')
548
+ ? await loadTokensConfig(config, options)
549
+ : undefined;
309
550
 
551
+ const compiledCssInJsConfig = getFeatureFlag(
552
+ 'coreTokensAndCompiledCssInJsTransform',
553
+ )
554
+ ? await loadCompiledCssInJsConfig(config, options)
555
+ : undefined;
556
+
557
+ if (conf && conf.contents) {
558
+ addReactDisplayName =
559
+ conf.contents?.addReactDisplayName ?? addReactDisplayName;
310
560
  magicComments = conf.contents?.magicComments ?? magicComments;
561
+ // @ts-expect-error TS2322
311
562
  inlineEnvironment = conf.contents?.inlineEnvironment ?? inlineEnvironment;
312
563
  inlineFS = conf.contents?.inlineFS ?? inlineFS;
313
564
  inlineConstants =
@@ -318,15 +569,29 @@ export default (new Transformer({
318
569
  isJSX,
319
570
  automaticJSXRuntime,
320
571
  jsxImportSource,
321
- pragma,
322
- pragmaFrag,
572
+ pragma: jsxPragma,
573
+ pragmaFrag: jsxPragmaFrag,
323
574
  inlineEnvironment,
324
575
  inlineFS,
325
576
  inlineConstants,
577
+ addReactDisplayName,
326
578
  reactRefresh,
327
579
  decorators,
328
580
  useDefineForClassFields,
329
581
  magicComments,
582
+ globalAliasingConfig,
583
+ enableSsrTypeofReplacement,
584
+ enableLazyLoading,
585
+ enableDeadReturnsRemoval,
586
+ enableUnusedBindingsRemoval,
587
+ enableStaticPrevaluation,
588
+ enableReactHooksRemoval,
589
+ syncDynamicImportConfig,
590
+ enableReactAsyncImportLift,
591
+ reactAsyncLiftByDefault,
592
+ reactAsyncLiftReportLevel,
593
+ tokensConfig: tokensConfig,
594
+ compiledCssInJsConfig: compiledCssInJsConfig,
330
595
  };
331
596
  },
332
597
  async transform({asset, config, options, logger}) {
@@ -357,6 +622,7 @@ export default (new Transformer({
357
622
  for (let browser of browsers) {
358
623
  let [name, version] = browser.split(' ');
359
624
  if (BROWSER_MAPPING.hasOwnProperty(name)) {
625
+ // @ts-expect-error TS7053
360
626
  name = BROWSER_MAPPING[name];
361
627
  if (!name) {
362
628
  continue;
@@ -366,12 +632,15 @@ export default (new Transformer({
366
632
  let [major, minor = '0', patch = '0'] = version
367
633
  .split('-')[0]
368
634
  .split('.');
635
+ // @ts-expect-error TS2345
369
636
  if (isNaN(major) || isNaN(minor) || isNaN(patch)) {
370
637
  continue;
371
638
  }
372
639
  let semverVersion = `${major}.${minor}.${patch}`;
373
640
 
641
+ // @ts-expect-error TS2345
374
642
  if (targets[name] == null || semver.gt(targets[name], semverVersion)) {
643
+ // @ts-expect-error TS7053
375
644
  targets[name] = semverVersion;
376
645
  }
377
646
  }
@@ -411,24 +680,49 @@ export default (new Transformer({
411
680
  if (asset.type === 'ts') {
412
681
  isJSX = false;
413
682
  } else if (!isJSX) {
683
+ // @ts-expect-error TS7053
414
684
  isJSX = Boolean(JSX_EXTENSIONS[asset.type]);
415
685
  }
416
686
  }
417
687
 
418
- let macroAssets = [];
688
+ let macroAssets: Array<{
689
+ content: string;
690
+ // @ts-expect-error TS2552
691
+ map: undefined | NodeSourceMap;
692
+ type: string;
693
+ uniqueKey: string;
694
+ }> = [];
419
695
  let {
696
+ // @ts-expect-error TS2339
420
697
  dependencies,
698
+ // @ts-expect-error TS2339
421
699
  code: compiledCode,
700
+ // @ts-expect-error TS2339
422
701
  map,
702
+ // @ts-expect-error TS2339
423
703
  shebang,
704
+ // @ts-expect-error TS2339
424
705
  hoist_result,
706
+ // @ts-expect-error TS2339
425
707
  symbol_result,
708
+ // @ts-expect-error TS2339
709
+ is_empty_or_empty_export,
710
+ // @ts-expect-error TS2339
426
711
  needs_esm_helpers,
712
+ // @ts-expect-error TS2339
427
713
  diagnostics,
714
+ // @ts-expect-error TS2339
428
715
  used_env,
716
+ // @ts-expect-error TS2339
429
717
  has_node_replacements,
718
+ // @ts-expect-error TS2339
430
719
  is_constant_module,
720
+ // @ts-expect-error TS2339
431
721
  conditions,
722
+ // @ts-expect-error TS2339
723
+ magic_comments,
724
+ // @ts-expect-error TS2339
725
+ style_rules,
432
726
  } = await (transformAsync || transform)({
433
727
  filename: asset.filePath,
434
728
  code,
@@ -440,7 +734,7 @@ export default (new Transformer({
440
734
  !asset.env.isNode() && asset.env.sourceType !== 'script',
441
735
  node_replacer: asset.env.isNode(),
442
736
  is_browser: asset.env.isBrowser(),
443
- is_worker: asset.env.isWorker(),
737
+ is_worker: asset.env.isWorker() || asset.env.isTesseract(),
444
738
  env,
445
739
  is_type_script: asset.type === 'ts' || asset.type === 'tsx',
446
740
  is_jsx: isJSX,
@@ -449,12 +743,16 @@ export default (new Transformer({
449
743
  automatic_jsx_runtime: Boolean(config?.automaticJSXRuntime),
450
744
  jsx_import_source: config?.jsxImportSource,
451
745
  is_development: options.mode === 'development',
452
- react_refresh:
746
+ react_refresh: Boolean(
453
747
  asset.env.isBrowser() &&
454
- !asset.env.isLibrary &&
455
- !asset.env.isWorker() &&
456
- !asset.env.isWorklet() &&
457
- Boolean(config?.reactRefresh),
748
+ !asset.env.isLibrary &&
749
+ !asset.env.isWorker() &&
750
+ !asset.env.isTesseract() &&
751
+ !asset.env.isWorklet() &&
752
+ config?.reactRefresh &&
753
+ options.hmrOptions &&
754
+ options.mode === 'development',
755
+ ),
458
756
  decorators: Boolean(config?.decorators),
459
757
  use_define_for_class_fields: Boolean(config?.useDefineForClassFields),
460
758
  targets,
@@ -470,9 +768,37 @@ export default (new Transformer({
470
768
  standalone: asset.query.has('standalone'),
471
769
  inline_constants: config.inlineConstants,
472
770
  conditional_bundling: options.featureFlags.conditionalBundlingApi,
473
- magic_comments: Boolean(config?.magicComments),
771
+ hmr_improvements: options.featureFlags.hmrImprovements,
772
+ add_display_name: Boolean(config.addReactDisplayName),
773
+ exports_rebinding_optimisation:
774
+ options.featureFlags.exportsRebindingOptimisation,
775
+ magic_comments:
776
+ Boolean(config?.magicComments) ||
777
+ getFeatureFlag('supportWebpackChunkName'),
778
+ is_source: asset.isSource,
779
+ nested_promise_import_fix: options.featureFlags.nestedPromiseImportFix,
780
+ global_aliasing_config: config.globalAliasingConfig,
781
+ enable_ssr_typeof_replacement: Boolean(config.enableSsrTypeofReplacement),
782
+ enable_lazy_loading: Boolean(config.enableLazyLoading),
783
+ enable_dead_returns_removal: Boolean(config.enableDeadReturnsRemoval),
784
+ enable_unused_bindings_removal: Boolean(
785
+ config.enableUnusedBindingsRemoval,
786
+ ),
787
+ enable_static_prevaluation: Boolean(config.enableStaticPrevaluation),
788
+ enable_react_hooks_removal: Boolean(config.enableReactHooksRemoval),
789
+ enable_react_async_import_lift: Boolean(
790
+ config.enableReactAsyncImportLift,
791
+ ),
792
+ react_async_lift_by_default: Boolean(config.reactAsyncLiftByDefault),
793
+ react_async_lift_report_level: String(config.reactAsyncLiftReportLevel),
794
+ sync_dynamic_import_config: config.syncDynamicImportConfig,
795
+ enable_tokens_and_compiled_css_in_js_transform: getFeatureFlag(
796
+ 'coreTokensAndCompiledCssInJsTransform',
797
+ ),
798
+ tokens_config: config.tokensConfig,
799
+ compiled_css_in_js_config: config.compiledCssInJsConfig,
474
800
  callMacro: asset.isSource
475
- ? async (err, src, exportName, args, loc) => {
801
+ ? async (err: any, src: any, exportName: any, args: any, loc: any) => {
476
802
  let mod;
477
803
  try {
478
804
  mod = await options.packageManager.require(src, asset.filePath);
@@ -481,7 +807,6 @@ export default (new Transformer({
481
807
  if (
482
808
  exportName === 'default' &&
483
809
  !mod.__esModule &&
484
- // $FlowFixMe
485
810
  Object.prototype.toString.call(config) !== '[object Module]'
486
811
  ) {
487
812
  mod = {default: mod};
@@ -490,7 +815,7 @@ export default (new Transformer({
490
815
  if (!Object.hasOwnProperty.call(mod, exportName)) {
491
816
  throw new Error(`"${src}" does not export "${exportName}".`);
492
817
  }
493
- } catch (err) {
818
+ } catch (err: any) {
494
819
  throw {
495
820
  kind: 1,
496
821
  message: err.message,
@@ -507,7 +832,8 @@ export default (new Transformer({
507
832
  if (asset.env.sourceMap) {
508
833
  // Generate a source map that maps each line of the asset to the original macro call.
509
834
  map = new SourceMap(options.projectRoot);
510
- let mappings = [];
835
+ // @ts-expect-error TS2304
836
+ let mappings: Array<IndexedMapping<string>> = [];
511
837
  let line = 1;
512
838
  for (let i = 0; i <= a.content.length; i++) {
513
839
  if (i === a.content.length || a.content[i] === '\n') {
@@ -530,7 +856,9 @@ export default (new Transformer({
530
856
  if (originalMap) {
531
857
  map.extends(originalMap);
532
858
  } else {
533
- map.setSourceContent(asset.filePath, code.toString());
859
+ if (!getFeatureFlag('omitSourcesContentInMemory')) {
860
+ map.setSourceContent(asset.filePath, code.toString());
861
+ }
534
862
  }
535
863
  }
536
864
 
@@ -546,13 +874,13 @@ export default (new Transformer({
546
874
  specifierType: 'esm',
547
875
  });
548
876
  },
549
- invalidateOnFileChange(filePath) {
877
+ invalidateOnFileChange(filePath: FilePath) {
550
878
  asset.invalidateOnFileChange(filePath);
551
879
  },
552
- invalidateOnFileCreate(invalidation) {
880
+ invalidateOnFileCreate(invalidation: FileCreateInvalidation) {
553
881
  asset.invalidateOnFileCreate(invalidation);
554
882
  },
555
- invalidateOnEnvChange(env) {
883
+ invalidateOnEnvChange(env: string) {
556
884
  asset.invalidateOnEnvChange(env);
557
885
  },
558
886
  invalidateOnStartup() {
@@ -569,7 +897,7 @@ export default (new Transformer({
569
897
  `"${exportName}" in "${src}" is not a function.`,
570
898
  );
571
899
  }
572
- } catch (err) {
900
+ } catch (err: any) {
573
901
  // Remove atlaspack core from stack and build string so Rust can process errors more easily.
574
902
  let stack = (err.stack || '').split('\n').slice(1);
575
903
  let message = err.message;
@@ -589,18 +917,18 @@ export default (new Transformer({
589
917
  });
590
918
 
591
919
  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
- }));
920
+ asset.meta.conditions = conditions;
921
+ }
922
+
923
+ if (style_rules) {
924
+ asset.meta.styleRules = style_rules;
597
925
  }
598
926
 
599
927
  if (is_constant_module) {
600
928
  asset.meta.isConstantModule = true;
601
929
  }
602
930
 
603
- let convertLoc = (loc): SourceLocation => {
931
+ let convertLoc = (loc: any): SourceLocation => {
604
932
  let location = {
605
933
  filePath: asset.filePath,
606
934
  start: {
@@ -615,7 +943,11 @@ export default (new Transformer({
615
943
 
616
944
  // If there is an original source map, use it to remap to the original source location.
617
945
  if (originalMap) {
618
- location = remapSourceLocation(location, originalMap);
946
+ location = remapSourceLocation(
947
+ location,
948
+ originalMap,
949
+ options.projectRoot,
950
+ );
619
951
  }
620
952
 
621
953
  return location;
@@ -623,19 +955,22 @@ export default (new Transformer({
623
955
 
624
956
  if (diagnostics) {
625
957
  let errors = diagnostics.filter(
958
+ // @ts-expect-error TS7006
626
959
  (d) =>
627
960
  d.severity === 'Error' ||
628
961
  (d.severity === 'SourceError' && asset.isSource),
629
962
  );
630
963
  let warnings = diagnostics.filter(
964
+ // @ts-expect-error TS7006
631
965
  (d) =>
632
966
  d.severity === 'Warning' ||
633
967
  (d.severity === 'SourceError' && !asset.isSource),
634
968
  );
635
- let convertDiagnostic = (diagnostic) => {
969
+ let convertDiagnostic = (diagnostic: any) => {
636
970
  let message = diagnostic.message;
637
971
  if (message === 'SCRIPT_ERROR') {
638
- let err = SCRIPT_ERRORS[(asset.env.context: string)];
972
+ // @ts-expect-error TS7053
973
+ let err = SCRIPT_ERRORS[asset.env.context as string];
639
974
  message = err?.message || SCRIPT_ERRORS.browser.message;
640
975
  }
641
976
 
@@ -644,11 +979,12 @@ export default (new Transformer({
644
979
  codeFrames: [
645
980
  {
646
981
  filePath: asset.filePath,
647
- codeHighlights: diagnostic.code_highlights?.map((highlight) =>
648
- convertSourceLocationToHighlight(
649
- convertLoc(highlight.loc),
650
- highlight.message ?? undefined,
651
- ),
982
+ codeHighlights: diagnostic.code_highlights?.map(
983
+ (highlight: any) =>
984
+ convertSourceLocationToHighlight(
985
+ convertLoc(highlight.loc),
986
+ highlight.message ?? undefined,
987
+ ),
652
988
  ),
653
989
  },
654
990
  ],
@@ -672,7 +1008,8 @@ export default (new Transformer({
672
1008
  });
673
1009
  }
674
1010
 
675
- let err = SCRIPT_ERRORS[(asset.env.context: string)];
1011
+ // @ts-expect-error TS7053
1012
+ let err = SCRIPT_ERRORS[asset.env.context as string];
676
1013
  if (err) {
677
1014
  if (!res.hints) {
678
1015
  res.hints = [err.hint];
@@ -729,6 +1066,7 @@ export default (new Transformer({
729
1066
  env: {
730
1067
  context: 'web-worker',
731
1068
  sourceType: dep.source_type === 'Module' ? 'module' : 'script',
1069
+ // @ts-expect-error TS2322
732
1070
  outputFormat,
733
1071
  loc,
734
1072
  },
@@ -776,6 +1114,13 @@ export default (new Transformer({
776
1114
  });
777
1115
  } else if (dep.kind === 'File') {
778
1116
  asset.invalidateOnFileChange(dep.specifier);
1117
+ } else if (dep.kind === 'Id') {
1118
+ // Record parcelRequire calls so that the dev packager can add them as dependencies.
1119
+ // This allows the HMR runtime to collect parents across async boundaries (through runtimes).
1120
+ // TODO: ideally this would result as an actual dep in the graph rather than asset.meta.
1121
+ asset.meta.hmrDeps ??= [];
1122
+ invariant(Array.isArray(asset.meta.hmrDeps));
1123
+ asset.meta.hmrDeps.push(dep.specifier);
779
1124
  } else {
780
1125
  let meta: JSONObject = {kind: dep.kind};
781
1126
  if (dep.attributes) {
@@ -839,6 +1184,13 @@ export default (new Transformer({
839
1184
  outputFormat,
840
1185
  loc: convertLoc(dep.loc),
841
1186
  };
1187
+
1188
+ if (getFeatureFlag('supportWebpackChunkName')) {
1189
+ let chunkName = magic_comments[dep.specifier];
1190
+ if (chunkName) {
1191
+ meta.chunkName = chunkName;
1192
+ }
1193
+ }
842
1194
  }
843
1195
 
844
1196
  // Always bundle helpers, even with includeNodeModules: false, except if this is a library.
@@ -863,6 +1215,7 @@ export default (new Transformer({
863
1215
  idx = dep.specifier.indexOf('/', idx + 1);
864
1216
  }
865
1217
  let module = idx >= 0 ? dep.specifier.slice(0, idx) : dep.specifier;
1218
+ // @ts-expect-error TS7053
866
1219
  range = pkg.dependencies[module];
867
1220
  }
868
1221
 
@@ -874,12 +1227,13 @@ export default (new Transformer({
874
1227
  dep.kind === 'DynamicImport'
875
1228
  ? 'lazy'
876
1229
  : dep.kind === 'ConditionalImport'
877
- ? 'conditional'
878
- : 'sync',
1230
+ ? 'conditional'
1231
+ : 'sync',
879
1232
  isOptional: dep.is_optional,
880
1233
  meta,
881
1234
  resolveFrom: isHelper ? __filename : undefined,
882
1235
  range,
1236
+ // @ts-expect-error TS2322
883
1237
  env,
884
1238
  });
885
1239
  }
@@ -893,8 +1247,12 @@ export default (new Transformer({
893
1247
  local,
894
1248
  loc,
895
1249
  is_esm,
1250
+ is_static_binding_safe,
896
1251
  } of hoist_result.exported_symbols) {
897
- asset.symbols.set(exported, local, convertLoc(loc), {isEsm: is_esm});
1252
+ asset.symbols.set(exported, local, convertLoc(loc), {
1253
+ isEsm: is_esm,
1254
+ isStaticBindingSafe: is_static_binding_safe,
1255
+ });
898
1256
  }
899
1257
 
900
1258
  // deps is a map of dependencies that are keyed by placeholder or specifier
@@ -991,6 +1349,9 @@ export default (new Transformer({
991
1349
  Object.keys(hoist_result.exported_symbols).length === 0) ||
992
1350
  (hoist_result.should_wrap && !asset.symbols.hasExportSymbol('*'))
993
1351
  ) {
1352
+ if (is_empty_or_empty_export) {
1353
+ asset.meta.emptyFileStarReexport = true;
1354
+ }
994
1355
  asset.symbols.set('*', `$${asset.id}$exports`);
995
1356
  }
996
1357
 
@@ -1093,4 +1454,4 @@ export default (new Transformer({
1093
1454
 
1094
1455
  return [asset, ...macroAssets];
1095
1456
  },
1096
- }): Transformer);
1457
+ }) as Transformer<unknown>;