@atlaspack/transformer-js 3.2.3-canary.31 → 3.2.3-canary.310

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.
@@ -4,8 +4,15 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
+ function _buildCache() {
8
+ const data = require("@atlaspack/build-cache");
9
+ _buildCache = function () {
10
+ return data;
11
+ };
12
+ return data;
13
+ }
7
14
  function _sourceMap() {
8
- const data = _interopRequireDefault(require("@parcel/source-map"));
15
+ const data = _interopRequireDefault(require("@atlaspack/source-map"));
9
16
  _sourceMap = function () {
10
17
  return data;
11
18
  };
@@ -25,6 +32,13 @@ function _rust() {
25
32
  };
26
33
  return data;
27
34
  }
35
+ function _assert() {
36
+ const data = _interopRequireDefault(require("assert"));
37
+ _assert = function () {
38
+ return data;
39
+ };
40
+ return data;
41
+ }
28
42
  function _browserslist() {
29
43
  const data = _interopRequireDefault(require("browserslist"));
30
44
  _browserslist = function () {
@@ -130,6 +144,9 @@ const CONFIG_SCHEMA = {
130
144
  }
131
145
  }]
132
146
  },
147
+ addReactDisplayName: {
148
+ type: 'boolean'
149
+ },
133
150
  magicComments: {
134
151
  type: 'boolean'
135
152
  },
@@ -139,6 +156,7 @@ const CONFIG_SCHEMA = {
139
156
  },
140
157
  additionalProperties: false
141
158
  };
159
+ const configCache = (0, _buildCache().createBuildCache)();
142
160
  const SCRIPT_ERRORS = {
143
161
  browser: {
144
162
  message: 'Browser scripts cannot have imports or exports.',
@@ -158,40 +176,49 @@ const SCRIPT_ERRORS = {
158
176
  var _default = exports.default = new (_plugin().Transformer)({
159
177
  async loadConfig({
160
178
  config,
161
- options
179
+ options,
180
+ logger
162
181
  }) {
163
- let pkg = await config.getPackage();
182
+ let packageJson = await config.getPackage();
164
183
  let isJSX, pragma, pragmaFrag, jsxImportSource, automaticJSXRuntime, reactRefresh, decorators, useDefineForClassFields;
165
184
  if (config.isSource) {
166
- var _pkg$dependencies2, _pkg$devDependencies2, _pkg$peerDependencies2, _tsconfig$contents;
185
+ var _packageJson$dependen2, _packageJson$devDepen2, _packageJson$peerDepe2, _await$config$getConf;
167
186
  let reactLib;
168
- if (pkg !== null && pkg !== void 0 && pkg.alias && pkg.alias['react']) {
187
+ if (packageJson !== null && packageJson !== void 0 && packageJson.alias && packageJson.alias['react']) {
169
188
  // e.g.: `{ alias: { "react": "preact/compat" } }`
170
189
  reactLib = 'react';
171
190
  } else {
172
191
  // Find a dependency that we can map to a JSX pragma
173
192
  reactLib = Object.keys(JSX_PRAGMA).find(libName => {
174
- var _pkg$dependencies, _pkg$devDependencies, _pkg$peerDependencies;
175
- return (pkg === null || pkg === void 0 || (_pkg$dependencies = pkg.dependencies) === null || _pkg$dependencies === void 0 ? void 0 : _pkg$dependencies[libName]) || (pkg === null || pkg === void 0 || (_pkg$devDependencies = pkg.devDependencies) === null || _pkg$devDependencies === void 0 ? void 0 : _pkg$devDependencies[libName]) || (pkg === null || pkg === void 0 || (_pkg$peerDependencies = pkg.peerDependencies) === null || _pkg$peerDependencies === void 0 ? void 0 : _pkg$peerDependencies[libName]);
193
+ var _packageJson$dependen, _packageJson$devDepen, _packageJson$peerDepe;
194
+ return (packageJson === null || packageJson === void 0 || (_packageJson$dependen = packageJson.dependencies) === null || _packageJson$dependen === void 0 ? void 0 : _packageJson$dependen[libName]) || (packageJson === null || packageJson === void 0 || (_packageJson$devDepen = packageJson.devDependencies) === null || _packageJson$devDepen === void 0 ? void 0 : _packageJson$devDepen[libName]) || (packageJson === null || packageJson === void 0 || (_packageJson$peerDepe = packageJson.peerDependencies) === null || _packageJson$peerDepe === void 0 ? void 0 : _packageJson$peerDepe[libName]);
176
195
  });
177
196
  }
178
- reactRefresh = options.hmrOptions && options.mode === 'development' && Boolean((pkg === null || pkg === void 0 || (_pkg$dependencies2 = pkg.dependencies) === null || _pkg$dependencies2 === void 0 ? void 0 : _pkg$dependencies2.react) || (pkg === null || pkg === void 0 || (_pkg$devDependencies2 = pkg.devDependencies) === null || _pkg$devDependencies2 === void 0 ? void 0 : _pkg$devDependencies2.react) || (pkg === null || pkg === void 0 || (_pkg$peerDependencies2 = pkg.peerDependencies) === null || _pkg$peerDependencies2 === void 0 ? void 0 : _pkg$peerDependencies2.react));
179
- let tsconfig = await config.getConfigFrom(options.projectRoot + '/index', ['tsconfig.json', 'jsconfig.json']);
180
- let compilerOptions = tsconfig === null || tsconfig === void 0 || (_tsconfig$contents = tsconfig.contents) === null || _tsconfig$contents === void 0 ? void 0 : _tsconfig$contents.compilerOptions;
197
+ reactRefresh = options.hmrOptions && options.mode === 'development' && Boolean((packageJson === null || packageJson === void 0 || (_packageJson$dependen2 = packageJson.dependencies) === null || _packageJson$dependen2 === void 0 ? void 0 : _packageJson$dependen2.react) || (packageJson === null || packageJson === void 0 || (_packageJson$devDepen2 = packageJson.devDependencies) === null || _packageJson$devDepen2 === void 0 ? void 0 : _packageJson$devDepen2.react) || (packageJson === null || packageJson === void 0 || (_packageJson$peerDepe2 = packageJson.peerDependencies) === null || _packageJson$peerDepe2 === void 0 ? void 0 : _packageJson$peerDepe2.react));
198
+ const compilerOptions = (_await$config$getConf = await config.getConfigFrom(options.projectRoot + '/index', ['tsconfig.json', 'jsconfig.json'], {
199
+ readTracking: true
200
+ })) === null || _await$config$getConf === void 0 || (_await$config$getConf = _await$config$getConf.contents) === null || _await$config$getConf === void 0 ? void 0 : _await$config$getConf.compilerOptions;
181
201
 
182
202
  // Use explicitly defined JSX options in tsconfig.json over inferred values from dependencies.
183
- pragma = (compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsxFactory) || (reactLib ? JSX_PRAGMA[reactLib].pragma : undefined);
184
- pragmaFrag = (compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsxFragmentFactory) || (reactLib ? JSX_PRAGMA[reactLib].pragmaFrag : undefined);
203
+ pragma = (compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsxFactory) || (
204
+ // @ts-expect-error TS7053
205
+ reactLib ? JSX_PRAGMA[reactLib].pragma : undefined);
206
+ pragmaFrag = (compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsxFragmentFactory) || (
207
+ // @ts-expect-error TS7053
208
+ reactLib ? JSX_PRAGMA[reactLib].pragmaFrag : undefined);
185
209
  if ((compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsx) === 'react-jsx' || (compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsx) === 'react-jsxdev' || compilerOptions !== null && compilerOptions !== void 0 && compilerOptions.jsxImportSource) {
186
210
  jsxImportSource = compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsxImportSource;
187
211
  automaticJSXRuntime = true;
188
212
  } else if (reactLib) {
189
- var _JSX_PRAGMA$effective, _pkg$dependencies3, _pkg$devDependencies3, _pkg$peerDependencies3, _semver$minVersion;
190
- let effectiveReactLib = pkg !== null && pkg !== void 0 && pkg.alias && pkg.alias['react'] === 'preact/compat' ? 'preact' : reactLib;
213
+ var _JSX_PRAGMA$effective, _packageJson$dependen3, _packageJson$devDepen3, _packageJson$peerDepe3, _semver$minVersion;
214
+ let effectiveReactLib = packageJson !== null && packageJson !== void 0 && packageJson.alias && packageJson.alias['react'] === 'preact/compat' ? 'preact' : reactLib;
215
+ // @ts-expect-error TS7053
191
216
  let automaticVersion = (_JSX_PRAGMA$effective = JSX_PRAGMA[effectiveReactLib]) === null || _JSX_PRAGMA$effective === void 0 ? void 0 : _JSX_PRAGMA$effective.automatic;
192
- let reactLibVersion = (pkg === null || pkg === void 0 || (_pkg$dependencies3 = pkg.dependencies) === null || _pkg$dependencies3 === void 0 ? void 0 : _pkg$dependencies3[effectiveReactLib]) || (pkg === null || pkg === void 0 || (_pkg$devDependencies3 = pkg.devDependencies) === null || _pkg$devDependencies3 === void 0 ? void 0 : _pkg$devDependencies3[effectiveReactLib]) || (pkg === null || pkg === void 0 || (_pkg$peerDependencies3 = pkg.peerDependencies) === null || _pkg$peerDependencies3 === void 0 ? void 0 : _pkg$peerDependencies3[effectiveReactLib]);
217
+ let reactLibVersion = (packageJson === null || packageJson === void 0 || (_packageJson$dependen3 = packageJson.dependencies) === null || _packageJson$dependen3 === void 0 ? void 0 : _packageJson$dependen3[effectiveReactLib]) || (packageJson === null || packageJson === void 0 || (_packageJson$devDepen3 = packageJson.devDependencies) === null || _packageJson$devDepen3 === void 0 ? void 0 : _packageJson$devDepen3[effectiveReactLib]) || (packageJson === null || packageJson === void 0 || (_packageJson$peerDepe3 = packageJson.peerDependencies) === null || _packageJson$peerDepe3 === void 0 ? void 0 : _packageJson$peerDepe3[effectiveReactLib]);
218
+ // @ts-expect-error TS2322
193
219
  reactLibVersion = reactLibVersion ? _semver().default.validRange(reactLibVersion) : null;
194
- let minReactLibVersion = reactLibVersion !== null && reactLibVersion !== '*' ? (_semver$minVersion = _semver().default.minVersion(reactLibVersion)) === null || _semver$minVersion === void 0 ? void 0 : _semver$minVersion.toString() : null;
220
+ let minReactLibVersion = reactLibVersion !== null && reactLibVersion !== '*' ? // @ts-expect-error TS2345
221
+ (_semver$minVersion = _semver().default.minVersion(reactLibVersion)) === null || _semver$minVersion === void 0 ? void 0 : _semver$minVersion.toString() : null;
195
222
  automaticJSXRuntime = automaticVersion && !(compilerOptions !== null && compilerOptions !== void 0 && compilerOptions.jsxFactory) && minReactLibVersion != null && _semver().default.satisfies(minReactLibVersion, automaticVersion, {
196
223
  includePrerelease: true
197
224
  });
@@ -215,7 +242,7 @@ var _default = exports.default = new (_plugin().Transformer)({
215
242
 
216
243
  // Check if we should ignore fs calls
217
244
  // See https://github.com/defunctzombie/node-browser-resolve#skip
218
- let ignoreFS = pkg && pkg.browser && typeof pkg.browser === 'object' && pkg.browser.fs === false;
245
+ let ignoreFS = packageJson && packageJson.browser && typeof packageJson.browser === 'object' && packageJson.browser.fs === false;
219
246
  let conf = await config.getConfigFrom(options.projectRoot + '/index', [], {
220
247
  packageKey: '@atlaspack/transformer-js'
221
248
  });
@@ -223,21 +250,65 @@ var _default = exports.default = new (_plugin().Transformer)({
223
250
  let inlineFS = !ignoreFS;
224
251
  let inlineConstants = false;
225
252
  let magicComments = false;
253
+ let addReactDisplayName = false;
254
+ let enableSsrTypeofReplacement = options.env.NATIVE_SSR_TYPEOF_REPLACEMENT === 'true';
255
+ let globalAliasingConfig = options.env.NATIVE_GLOBAL_ALIASING && JSON.parse(options.env.NATIVE_GLOBAL_ALIASING);
256
+ let enableLazyLoading = options.env.NATIVE_LAZY_LOADING === 'true';
257
+ let enableReactHooksRemoval = options.env.NATIVE_REACT_HOOKS_REMOVAL === 'true';
258
+ let enableReactAsyncImportLift = options.env.NATIVE_REACT_ASYNC_IMPORT_LIFT === 'true';
259
+ let reactAsyncLiftByDefault = options.env.REACT_ASYNC_IMPORT_LIFTING_BY_DEFAULT === 'true';
260
+ let reactAsyncLiftReportLevel = options.env.REACT_ASYNC_LIFT_REPORT_LEVEL || 'none';
261
+ let enableStaticPrevaluation = options.env.NATIVE_PREVALUATION === 'true';
262
+ let enableDeadReturnsRemoval = options.env.NATIVE_DEAD_RETURNS_REMOVAL === 'true';
263
+ let enableUnusedBindingsRemoval = options.env.NATIVE_UNUSED_BINDINGS_REMOVAL === 'true';
264
+ let syncDynamicImportConfig;
265
+ if (config.env.isTesseract() && options.env.SYNC_DYNAMIC_IMPORT_CONFIG) {
266
+ try {
267
+ let config = configCache.get('SYNC_DYNAMIC_IMPORT_CONFIG');
268
+ if (!config) {
269
+ var _config;
270
+ config = JSON.parse(options.env.SYNC_DYNAMIC_IMPORT_CONFIG);
271
+ (0, _assert().default)(typeof ((_config = config) === null || _config === void 0 ? void 0 : _config.entrypoint_filepath_suffix) === 'string');
272
+ (0, _assert().default)(Array.isArray(config.actual_require_paths));
273
+ configCache.set('SYNC_DYNAMIC_IMPORT_CONFIG', config);
274
+ }
275
+ syncDynamicImportConfig = config;
276
+ } catch {
277
+ // eslint-disable-next-line no-console
278
+ console.warn('Failed to parse SYNC_DYNAMIC_IMPORT_CONFIG to JSON or config shape did not match. Config will not be applied.');
279
+ const fallback = {
280
+ entrypoint_filepath_suffix: '__NO_MATCH__',
281
+ actual_require_paths: []
282
+ };
283
+
284
+ // Set cache to fallback so we don't keep trying to parse.
285
+ configCache.set('SYNC_DYNAMIC_IMPORT_CONFIG', fallback);
286
+ syncDynamicImportConfig = fallback;
287
+ }
288
+ }
289
+ config.invalidateOnEnvChange('SYNC_DYNAMIC_IMPORT_CONFIG');
226
290
  if (conf && conf.contents) {
227
- var _conf$contents, _conf$contents2, _conf$contents3, _conf$contents4;
291
+ var _conf$contents, _conf$contents2, _conf$contents3, _conf$contents4, _conf$contents5;
228
292
  _utils().validateSchema.diagnostic(CONFIG_SCHEMA, {
229
293
  data: conf.contents,
230
- // FIXME
231
- source: await options.inputFS.readFile(conf.filePath, 'utf8'),
294
+ source: () => options.inputFS.readFileSync(conf.filePath, 'utf8'),
232
295
  filePath: conf.filePath,
233
296
  prependKey: `/${(0, _diagnostic().encodeJSONKeyComponent)('@atlaspack/transformer-js')}`
234
297
  },
235
298
  // FIXME
236
299
  '@atlaspack/transformer-js', 'Invalid config for @atlaspack/transformer-js');
237
- magicComments = ((_conf$contents = conf.contents) === null || _conf$contents === void 0 ? void 0 : _conf$contents.magicComments) ?? magicComments;
238
- inlineEnvironment = ((_conf$contents2 = conf.contents) === null || _conf$contents2 === void 0 ? void 0 : _conf$contents2.inlineEnvironment) ?? inlineEnvironment;
239
- inlineFS = ((_conf$contents3 = conf.contents) === null || _conf$contents3 === void 0 ? void 0 : _conf$contents3.inlineFS) ?? inlineFS;
240
- inlineConstants = ((_conf$contents4 = conf.contents) === null || _conf$contents4 === void 0 ? void 0 : _conf$contents4.unstable_inlineConstants) ?? inlineConstants;
300
+ addReactDisplayName =
301
+ // @ts-expect-error TS2339
302
+ ((_conf$contents = conf.contents) === null || _conf$contents === void 0 ? void 0 : _conf$contents.addReactDisplayName) ?? addReactDisplayName;
303
+ // @ts-expect-error TS2339
304
+ magicComments = ((_conf$contents2 = conf.contents) === null || _conf$contents2 === void 0 ? void 0 : _conf$contents2.magicComments) ?? magicComments;
305
+ // @ts-expect-error TS2339
306
+ inlineEnvironment = ((_conf$contents3 = conf.contents) === null || _conf$contents3 === void 0 ? void 0 : _conf$contents3.inlineEnvironment) ?? inlineEnvironment;
307
+ // @ts-expect-error TS2339
308
+ inlineFS = ((_conf$contents4 = conf.contents) === null || _conf$contents4 === void 0 ? void 0 : _conf$contents4.inlineFS) ?? inlineFS;
309
+ inlineConstants =
310
+ // @ts-expect-error TS2339
311
+ ((_conf$contents5 = conf.contents) === null || _conf$contents5 === void 0 ? void 0 : _conf$contents5.unstable_inlineConstants) ?? inlineConstants;
241
312
  }
242
313
  return {
243
314
  isJSX,
@@ -248,10 +319,22 @@ var _default = exports.default = new (_plugin().Transformer)({
248
319
  inlineEnvironment,
249
320
  inlineFS,
250
321
  inlineConstants,
322
+ addReactDisplayName,
251
323
  reactRefresh,
252
324
  decorators,
253
325
  useDefineForClassFields,
254
- magicComments
326
+ magicComments,
327
+ globalAliasingConfig,
328
+ enableSsrTypeofReplacement,
329
+ enableLazyLoading,
330
+ enableDeadReturnsRemoval,
331
+ enableUnusedBindingsRemoval,
332
+ enableStaticPrevaluation,
333
+ enableReactHooksRemoval,
334
+ syncDynamicImportConfig,
335
+ enableReactAsyncImportLift,
336
+ reactAsyncLiftByDefault,
337
+ reactAsyncLiftReportLevel
255
338
  };
256
339
  },
257
340
  async transform({
@@ -280,17 +363,22 @@ var _default = exports.default = new (_plugin().Transformer)({
280
363
  for (let browser of browsers) {
281
364
  let [name, version] = browser.split(' ');
282
365
  if (BROWSER_MAPPING.hasOwnProperty(name)) {
366
+ // @ts-expect-error TS7053
283
367
  name = BROWSER_MAPPING[name];
284
368
  if (!name) {
285
369
  continue;
286
370
  }
287
371
  }
288
372
  let [major, minor = '0', patch = '0'] = version.split('-')[0].split('.');
373
+ // @ts-expect-error TS2345
289
374
  if (isNaN(major) || isNaN(minor) || isNaN(patch)) {
290
375
  continue;
291
376
  }
292
377
  let semverVersion = `${major}.${minor}.${patch}`;
378
+
379
+ // @ts-expect-error TS2345
293
380
  if (targets[name] == null || _semver().default.gt(targets[name], semverVersion)) {
381
+ // @ts-expect-error TS7053
294
382
  targets[name] = semverVersion;
295
383
  }
296
384
  }
@@ -305,6 +393,9 @@ var _default = exports.default = new (_plugin().Transformer)({
305
393
  if (options.env.NODE_ENV != null) {
306
394
  env.NODE_ENV = options.env.NODE_ENV;
307
395
  }
396
+ if (process.env.ATLASPACK_BUILD_ENV === 'test') {
397
+ env.ATLASPACK_BUILD_ENV = 'test';
398
+ }
308
399
  } else if (Array.isArray(config === null || config === void 0 ? void 0 : config.inlineEnvironment)) {
309
400
  for (let match of (0, _utils().globMatch)(Object.keys(options.env), config.inlineEnvironment)) {
310
401
  env[match] = String(options.env[match]);
@@ -322,23 +413,40 @@ var _default = exports.default = new (_plugin().Transformer)({
322
413
  if (asset.type === 'ts') {
323
414
  isJSX = false;
324
415
  } else if (!isJSX) {
416
+ // @ts-expect-error TS7053
325
417
  isJSX = Boolean(JSX_EXTENSIONS[asset.type]);
326
418
  }
327
419
  }
328
420
  let macroAssets = [];
329
421
  let {
422
+ // @ts-expect-error TS2339
330
423
  dependencies,
424
+ // @ts-expect-error TS2339
331
425
  code: compiledCode,
426
+ // @ts-expect-error TS2339
332
427
  map,
428
+ // @ts-expect-error TS2339
333
429
  shebang,
430
+ // @ts-expect-error TS2339
334
431
  hoist_result,
432
+ // @ts-expect-error TS2339
335
433
  symbol_result,
434
+ // @ts-expect-error TS2339
435
+ is_empty_or_empty_export,
436
+ // @ts-expect-error TS2339
336
437
  needs_esm_helpers,
438
+ // @ts-expect-error TS2339
337
439
  diagnostics,
440
+ // @ts-expect-error TS2339
338
441
  used_env,
442
+ // @ts-expect-error TS2339
339
443
  has_node_replacements,
444
+ // @ts-expect-error TS2339
340
445
  is_constant_module,
341
- conditions
446
+ // @ts-expect-error TS2339
447
+ conditions,
448
+ // @ts-expect-error TS2339
449
+ magic_comments
342
450
  } = await (_rust().transformAsync || _rust().transform)({
343
451
  filename: asset.filePath,
344
452
  code,
@@ -349,7 +457,7 @@ var _default = exports.default = new (_plugin().Transformer)({
349
457
  insert_node_globals: !asset.env.isNode() && asset.env.sourceType !== 'script',
350
458
  node_replacer: asset.env.isNode(),
351
459
  is_browser: asset.env.isBrowser(),
352
- is_worker: asset.env.isWorker(),
460
+ is_worker: asset.env.isWorker() || asset.env.isTesseract(),
353
461
  env,
354
462
  is_type_script: asset.type === 'ts' || asset.type === 'tsx',
355
463
  is_jsx: isJSX,
@@ -358,7 +466,7 @@ var _default = exports.default = new (_plugin().Transformer)({
358
466
  automatic_jsx_runtime: Boolean(config === null || config === void 0 ? void 0 : config.automaticJSXRuntime),
359
467
  jsx_import_source: config === null || config === void 0 ? void 0 : config.jsxImportSource,
360
468
  is_development: options.mode === 'development',
361
- react_refresh: asset.env.isBrowser() && !asset.env.isLibrary && !asset.env.isWorker() && !asset.env.isWorklet() && Boolean(config === null || config === void 0 ? void 0 : config.reactRefresh),
469
+ react_refresh: asset.env.isBrowser() && !asset.env.isLibrary && !asset.env.isWorker() && !asset.env.isTesseract() && !asset.env.isWorklet() && Boolean(config === null || config === void 0 ? void 0 : config.reactRefresh),
362
470
  decorators: Boolean(config === null || config === void 0 ? void 0 : config.decorators),
363
471
  use_define_for_class_fields: Boolean(config === null || config === void 0 ? void 0 : config.useDefineForClassFields),
364
472
  targets,
@@ -373,16 +481,30 @@ var _default = exports.default = new (_plugin().Transformer)({
373
481
  standalone: asset.query.has('standalone'),
374
482
  inline_constants: config.inlineConstants,
375
483
  conditional_bundling: options.featureFlags.conditionalBundlingApi,
376
- magic_comments: Boolean(config === null || config === void 0 ? void 0 : config.magicComments),
484
+ hmr_improvements: options.featureFlags.hmrImprovements,
485
+ add_display_name: Boolean(config.addReactDisplayName),
486
+ exports_rebinding_optimisation: options.featureFlags.exportsRebindingOptimisation,
487
+ magic_comments: Boolean(config === null || config === void 0 ? void 0 : config.magicComments) || (0, _featureFlags().getFeatureFlag)('supportWebpackChunkName'),
488
+ is_source: asset.isSource,
489
+ nested_promise_import_fix: options.featureFlags.nestedPromiseImportFix,
490
+ global_aliasing_config: config.globalAliasingConfig,
491
+ enable_ssr_typeof_replacement: Boolean(config.enableSsrTypeofReplacement),
492
+ enable_lazy_loading: Boolean(config.enableLazyLoading),
493
+ enable_dead_returns_removal: Boolean(config.enableDeadReturnsRemoval),
494
+ enable_unused_bindings_removal: Boolean(config.enableUnusedBindingsRemoval),
495
+ enable_static_prevaluation: Boolean(config.enableStaticPrevaluation),
496
+ enable_react_hooks_removal: Boolean(config.enableReactHooksRemoval),
497
+ enable_react_async_import_lift: Boolean(config.enableReactAsyncImportLift),
498
+ react_async_lift_by_default: Boolean(config.reactAsyncLiftByDefault),
499
+ react_async_lift_report_level: String(config.reactAsyncLiftReportLevel),
500
+ sync_dynamic_import_config: config.syncDynamicImportConfig,
377
501
  callMacro: asset.isSource ? async (err, src, exportName, args, loc) => {
378
502
  let mod;
379
503
  try {
380
504
  mod = await options.packageManager.require(src, asset.filePath);
381
505
 
382
506
  // Default interop for CommonJS modules.
383
- if (exportName === 'default' && !mod.__esModule &&
384
- // $FlowFixMe
385
- Object.prototype.toString.call(config) !== '[object Module]') {
507
+ if (exportName === 'default' && !mod.__esModule && Object.prototype.toString.call(config) !== '[object Module]') {
386
508
  mod = {
387
509
  default: mod
388
510
  };
@@ -398,7 +520,7 @@ var _default = exports.default = new (_plugin().Transformer)({
398
520
  }
399
521
  try {
400
522
  if (typeof mod[exportName] === 'function') {
401
- return mod[exportName].apply({
523
+ let ctx = {
402
524
  // Allows macros to emit additional assets to add as dependencies (e.g. css).
403
525
  addAsset(a) {
404
526
  let k = String(macroAssets.length);
@@ -406,6 +528,7 @@ var _default = exports.default = new (_plugin().Transformer)({
406
528
  if (asset.env.sourceMap) {
407
529
  // Generate a source map that maps each line of the asset to the original macro call.
408
530
  map = new (_sourceMap().default)(options.projectRoot);
531
+ // @ts-expect-error TS2304
409
532
  let mappings = [];
410
533
  let line = 1;
411
534
  for (let i = 0; i <= a.content.length; i++) {
@@ -428,7 +551,9 @@ var _default = exports.default = new (_plugin().Transformer)({
428
551
  if (originalMap) {
429
552
  map.extends(originalMap);
430
553
  } else {
431
- map.setSourceContent(asset.filePath, code.toString());
554
+ if (!(0, _featureFlags().getFeatureFlag)('omitSourcesContentInMemory')) {
555
+ map.setSourceContent(asset.filePath, code.toString());
556
+ }
432
557
  }
433
558
  }
434
559
  macroAssets.push({
@@ -457,7 +582,8 @@ var _default = exports.default = new (_plugin().Transformer)({
457
582
  invalidateOnBuild() {
458
583
  asset.invalidateOnBuild();
459
584
  }
460
- }, args);
585
+ };
586
+ return mod[exportName].apply(ctx, args);
461
587
  } else {
462
588
  throw new Error(`"${exportName}" in "${src}" is not a function.`);
463
589
  }
@@ -479,11 +605,7 @@ var _default = exports.default = new (_plugin().Transformer)({
479
605
  } : null
480
606
  });
481
607
  if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi')) {
482
- asset.meta.conditions = conditions.map(c => ({
483
- key: c.key,
484
- ifTruePlaceholder: c.if_true_placeholder,
485
- ifFalsePlaceholder: c.if_false_placeholder
486
- }));
608
+ asset.meta.conditions = conditions;
487
609
  }
488
610
  if (is_constant_module) {
489
611
  asset.meta.isConstantModule = true;
@@ -503,17 +625,22 @@ var _default = exports.default = new (_plugin().Transformer)({
503
625
 
504
626
  // If there is an original source map, use it to remap to the original source location.
505
627
  if (originalMap) {
506
- location = (0, _utils().remapSourceLocation)(location, originalMap);
628
+ location = (0, _utils().remapSourceLocation)(location, originalMap, options.projectRoot);
507
629
  }
508
630
  return location;
509
631
  };
510
632
  if (diagnostics) {
511
- let errors = diagnostics.filter(d => d.severity === 'Error' || d.severity === 'SourceError' && asset.isSource);
512
- let warnings = diagnostics.filter(d => d.severity === 'Warning' || d.severity === 'SourceError' && !asset.isSource);
633
+ let errors = diagnostics.filter(
634
+ // @ts-expect-error TS7006
635
+ d => d.severity === 'Error' || d.severity === 'SourceError' && asset.isSource);
636
+ let warnings = diagnostics.filter(
637
+ // @ts-expect-error TS7006
638
+ d => d.severity === 'Warning' || d.severity === 'SourceError' && !asset.isSource);
513
639
  let convertDiagnostic = diagnostic => {
514
640
  var _diagnostic$code_high;
515
641
  let message = diagnostic.message;
516
642
  if (message === 'SCRIPT_ERROR') {
643
+ // @ts-expect-error TS7053
517
644
  let err = SCRIPT_ERRORS[asset.env.context];
518
645
  message = (err === null || err === void 0 ? void 0 : err.message) || SCRIPT_ERRORS.browser.message;
519
646
  }
@@ -536,6 +663,8 @@ var _default = exports.default = new (_plugin().Transformer)({
536
663
  codeHighlights: [(0, _diagnostic().convertSourceLocationToHighlight)(asset.env.loc, 'The environment was originally created here')]
537
664
  });
538
665
  }
666
+
667
+ // @ts-expect-error TS7053
539
668
  let err = SCRIPT_ERRORS[asset.env.context];
540
669
  if (err) {
541
670
  if (!res.hints) {
@@ -580,6 +709,7 @@ var _default = exports.default = new (_plugin().Transformer)({
580
709
  env: {
581
710
  context: 'web-worker',
582
711
  sourceType: dep.source_type === 'Module' ? 'module' : 'script',
712
+ // @ts-expect-error TS2322
583
713
  outputFormat,
584
714
  loc
585
715
  },
@@ -629,6 +759,13 @@ var _default = exports.default = new (_plugin().Transformer)({
629
759
  });
630
760
  } else if (dep.kind === 'File') {
631
761
  asset.invalidateOnFileChange(dep.specifier);
762
+ } else if (dep.kind === 'Id') {
763
+ // Record parcelRequire calls so that the dev packager can add them as dependencies.
764
+ // This allows the HMR runtime to collect parents across async boundaries (through runtimes).
765
+ // TODO: ideally this would result as an actual dep in the graph rather than asset.meta.
766
+ asset.meta.hmrDeps ??= [];
767
+ (0, _assert().default)(Array.isArray(asset.meta.hmrDeps));
768
+ asset.meta.hmrDeps.push(dep.specifier);
632
769
  } else {
633
770
  let meta = {
634
771
  kind: dep.kind
@@ -676,6 +813,12 @@ var _default = exports.default = new (_plugin().Transformer)({
676
813
  outputFormat,
677
814
  loc: convertLoc(dep.loc)
678
815
  };
816
+ if ((0, _featureFlags().getFeatureFlag)('supportWebpackChunkName')) {
817
+ let chunkName = magic_comments[dep.specifier];
818
+ if (chunkName) {
819
+ meta.chunkName = chunkName;
820
+ }
821
+ }
679
822
  }
680
823
 
681
824
  // Always bundle helpers, even with includeNodeModules: false, except if this is a library.
@@ -695,6 +838,7 @@ var _default = exports.default = new (_plugin().Transformer)({
695
838
  idx = dep.specifier.indexOf('/', idx + 1);
696
839
  }
697
840
  let module = idx >= 0 ? dep.specifier.slice(0, idx) : dep.specifier;
841
+ // @ts-expect-error TS7053
698
842
  range = _package.default.dependencies[module];
699
843
  }
700
844
  asset.addDependency({
@@ -706,6 +850,7 @@ var _default = exports.default = new (_plugin().Transformer)({
706
850
  meta,
707
851
  resolveFrom: isHelper ? __filename : undefined,
708
852
  range,
853
+ // @ts-expect-error TS2322
709
854
  env
710
855
  });
711
856
  }
@@ -717,10 +862,12 @@ var _default = exports.default = new (_plugin().Transformer)({
717
862
  exported,
718
863
  local,
719
864
  loc,
720
- is_esm
865
+ is_esm,
866
+ is_static_binding_safe
721
867
  } of hoist_result.exported_symbols) {
722
868
  asset.symbols.set(exported, local, convertLoc(loc), {
723
- isEsm: is_esm
869
+ isEsm: is_esm,
870
+ isStaticBindingSafe: is_static_binding_safe
724
871
  });
725
872
  }
726
873
 
@@ -802,6 +949,9 @@ var _default = exports.default = new (_plugin().Transformer)({
802
949
  // (and the asset has side effects), or the asset is wrapped.
803
950
  // This allows accessing symbols that don't exist without errors in symbol propagation.
804
951
  if (hoist_result.has_cjs_exports || !hoist_result.is_esm && asset.sideEffects && deps.size === 0 && Object.keys(hoist_result.exported_symbols).length === 0 || hoist_result.should_wrap && !asset.symbols.hasExportSymbol('*')) {
952
+ if (is_empty_or_empty_export) {
953
+ asset.meta.emptyFileStarReexport = true;
954
+ }
805
955
  asset.symbols.set('*', `$${asset.id}$exports`);
806
956
  }
807
957
  asset.meta.hasCJSExports = hoist_result.has_cjs_exports;
@@ -0,0 +1,3 @@
1
+ import { Transformer } from '@atlaspack/plugin';
2
+ declare const _default: Transformer<unknown>;
3
+ export default _default;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atlaspack/transformer-js",
3
- "version": "3.2.3-canary.31+e05252108",
3
+ "version": "3.2.3-canary.310+3f6a3b8df",
4
4
  "license": "(MIT OR Apache-2.0)",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -9,10 +9,12 @@
9
9
  "type": "git",
10
10
  "url": "https://github.com/atlassian-labs/atlaspack.git"
11
11
  },
12
- "main": "lib/JSTransformer.js",
13
- "source": "src/JSTransformer.js",
12
+ "main": "./lib/JSTransformer.js",
13
+ "source": "./src/JSTransformer.ts",
14
+ "types": "./lib/types/JSTransformer.d.ts",
14
15
  "scripts": {
15
- "test": "mocha"
16
+ "test": "mocha",
17
+ "build:lib": "gulp build --gulpfile ../../../gulpfile.js --cwd ."
16
18
  },
17
19
  "engines": {
18
20
  "node": ">= 16.0.0"
@@ -22,13 +24,14 @@
22
24
  "src"
23
25
  ],
24
26
  "dependencies": {
25
- "@atlaspack/diagnostic": "2.14.1-canary.99+e05252108",
26
- "@atlaspack/feature-flags": "2.14.1-canary.99+e05252108",
27
- "@atlaspack/plugin": "2.14.5-canary.31+e05252108",
28
- "@atlaspack/rust": "3.2.1-canary.31+e05252108",
29
- "@atlaspack/utils": "2.14.5-canary.31+e05252108",
30
- "@atlaspack/workers": "2.14.5-canary.31+e05252108",
31
- "@parcel/source-map": "^2.1.1",
27
+ "@atlaspack/build-cache": "2.13.3-canary.378+3f6a3b8df",
28
+ "@atlaspack/diagnostic": "2.14.1-canary.378+3f6a3b8df",
29
+ "@atlaspack/feature-flags": "2.14.1-canary.378+3f6a3b8df",
30
+ "@atlaspack/plugin": "2.14.5-canary.310+3f6a3b8df",
31
+ "@atlaspack/rust": "3.2.1-canary.310+3f6a3b8df",
32
+ "@atlaspack/source-map": "3.1.2-canary.4089+3f6a3b8df",
33
+ "@atlaspack/utils": "2.14.5-canary.310+3f6a3b8df",
34
+ "@atlaspack/workers": "2.14.5-canary.310+3f6a3b8df",
32
35
  "@swc/helpers": "^0.5.15",
33
36
  "browserslist": "^4.6.6",
34
37
  "nullthrows": "^1.1.1",
@@ -36,8 +39,8 @@
36
39
  "semver": "^7.5.2"
37
40
  },
38
41
  "peerDependencies": {
39
- "@atlaspack/core": "^2.13.1"
42
+ "@atlaspack/core": "2.29.0"
40
43
  },
41
44
  "type": "commonjs",
42
- "gitHead": "e0525210850ed1606146eb86991049cf567c5dec"
43
- }
45
+ "gitHead": "3f6a3b8df4589fd4d65c072281c7f33bd37341d6"
46
+ }
@@ -1,17 +1,17 @@
1
- // @flow
2
1
  import type {
3
2
  JSONObject,
4
3
  EnvMap,
5
4
  SourceLocation,
6
5
  FilePath,
7
6
  FileCreateInvalidation,
8
- ConditionMeta,
9
7
  } from '@atlaspack/types';
8
+ import {createBuildCache} from '@atlaspack/build-cache';
10
9
  import type {SchemaEntity} from '@atlaspack/utils';
11
10
  import type {Diagnostic} from '@atlaspack/diagnostic';
12
- import SourceMap from '@parcel/source-map';
11
+ import SourceMap from '@atlaspack/source-map';
13
12
  import {Transformer} from '@atlaspack/plugin';
14
13
  import {transform, transformAsync} from '@atlaspack/rust';
14
+ import invariant from 'assert';
15
15
  import browserslist from 'browserslist';
16
16
  import semver from 'semver';
17
17
  import nullthrows from 'nullthrows';
@@ -26,7 +26,7 @@ import {getFeatureFlag} from '@atlaspack/feature-flags';
26
26
  const JSX_EXTENSIONS = {
27
27
  jsx: true,
28
28
  tsx: true,
29
- };
29
+ } as const;
30
30
 
31
31
  const JSX_PRAGMA = {
32
32
  react: {
@@ -49,7 +49,7 @@ const JSX_PRAGMA = {
49
49
  pragmaFrag: undefined,
50
50
  automatic: undefined,
51
51
  },
52
- };
52
+ } as const;
53
53
 
54
54
  const BROWSER_MAPPING = {
55
55
  and_chr: 'chrome',
@@ -63,7 +63,7 @@ const BROWSER_MAPPING = {
63
63
  bb: null,
64
64
  kaios: null,
65
65
  op_mini: null,
66
- };
66
+ } as const;
67
67
 
68
68
  // List of browsers to exclude when the esmodule target is specified.
69
69
  // Based on https://caniuse.com/#feat=es6-module
@@ -108,6 +108,9 @@ const CONFIG_SCHEMA: SchemaEntity = {
108
108
  },
109
109
  ],
110
110
  },
111
+ addReactDisplayName: {
112
+ type: 'boolean',
113
+ },
111
114
  magicComments: {
112
115
  type: 'boolean',
113
116
  },
@@ -118,6 +121,8 @@ const CONFIG_SCHEMA: SchemaEntity = {
118
121
  additionalProperties: false,
119
122
  };
120
123
 
124
+ const configCache = createBuildCache();
125
+
121
126
  const SCRIPT_ERRORS = {
122
127
  browser: {
123
128
  message: 'Browser scripts cannot have imports or exports.',
@@ -133,47 +138,45 @@ const SCRIPT_ERRORS = {
133
138
  'Service workers cannot have imports or exports without the `type: "module"` option.',
134
139
  hint: "Add {type: 'module'} as a second argument to the navigator.serviceWorker.register() call.",
135
140
  },
136
- };
141
+ } as const;
137
142
 
138
143
  type TSConfig = {
139
144
  compilerOptions?: {
140
145
  // https://www.typescriptlang.org/tsconfig#jsx
141
- jsx?: 'react' | 'react-jsx' | 'react-jsxdev' | 'preserve' | 'react-native',
146
+ jsx?: 'react' | 'react-jsx' | 'react-jsxdev' | 'preserve' | 'react-native';
142
147
  // https://www.typescriptlang.org/tsconfig#jsxFactory
143
- jsxFactory?: string,
148
+ jsxFactory?: string;
144
149
  // https://www.typescriptlang.org/tsconfig#jsxFragmentFactory
145
- jsxFragmentFactory?: string,
150
+ jsxFragmentFactory?: string;
146
151
  // https://www.typescriptlang.org/tsconfig#jsxImportSource
147
- jsxImportSource?: string,
152
+ jsxImportSource?: string;
148
153
  // https://www.typescriptlang.org/tsconfig#experimentalDecorators
149
- experimentalDecorators?: boolean,
154
+ experimentalDecorators?: boolean;
150
155
  // https://www.typescriptlang.org/tsconfig#useDefineForClassFields
151
- useDefineForClassFields?: boolean,
156
+ useDefineForClassFields?: boolean;
152
157
  // https://www.typescriptlang.org/tsconfig#target
153
- target?: string, // 'es3' | 'es5' | 'es6' | 'es2015' | ... |'es2022' | ... | 'esnext'
154
- ...
155
- },
156
- ...
158
+ target?: string; // 'es3' | 'es5' | 'es6' | 'es2015' | ... |'es2022' | ... | 'esnext';
159
+ };
157
160
  };
158
161
 
159
- type MacroAsset = {|
160
- type: string,
161
- content: string,
162
- |};
162
+ type MacroAsset = {
163
+ type: string;
164
+ content: string;
165
+ };
163
166
 
164
167
  // 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();
168
+ type MacroContext = {
169
+ addAsset(asset: MacroAsset): void;
170
+ invalidateOnFileChange(arg1: FilePath): void;
171
+ invalidateOnFileCreate(arg1: FileCreateInvalidation): void;
172
+ invalidateOnEnvChange(arg1: string): void;
173
+ invalidateOnStartup(): void;
174
+ invalidateOnBuild(): void;
175
+ };
176
+
177
+ export default new Transformer({
178
+ async loadConfig({config, options, logger}) {
179
+ let packageJson = await config.getPackage();
177
180
  let isJSX,
178
181
  pragma,
179
182
  pragmaFrag,
@@ -184,16 +187,16 @@ export default (new Transformer({
184
187
  useDefineForClassFields;
185
188
  if (config.isSource) {
186
189
  let reactLib;
187
- if (pkg?.alias && pkg.alias['react']) {
190
+ if (packageJson?.alias && packageJson.alias['react']) {
188
191
  // e.g.: `{ alias: { "react": "preact/compat" } }`
189
192
  reactLib = 'react';
190
193
  } else {
191
194
  // Find a dependency that we can map to a JSX pragma
192
195
  reactLib = Object.keys(JSX_PRAGMA).find(
193
196
  (libName) =>
194
- pkg?.dependencies?.[libName] ||
195
- pkg?.devDependencies?.[libName] ||
196
- pkg?.peerDependencies?.[libName],
197
+ packageJson?.dependencies?.[libName] ||
198
+ packageJson?.devDependencies?.[libName] ||
199
+ packageJson?.peerDependencies?.[libName],
197
200
  );
198
201
  }
199
202
 
@@ -201,23 +204,29 @@ export default (new Transformer({
201
204
  options.hmrOptions &&
202
205
  options.mode === 'development' &&
203
206
  Boolean(
204
- pkg?.dependencies?.react ||
205
- pkg?.devDependencies?.react ||
206
- pkg?.peerDependencies?.react,
207
+ packageJson?.dependencies?.react ||
208
+ packageJson?.devDependencies?.react ||
209
+ packageJson?.peerDependencies?.react,
207
210
  );
208
211
 
209
- let tsconfig = await config.getConfigFrom<TSConfig>(
210
- options.projectRoot + '/index',
211
- ['tsconfig.json', 'jsconfig.json'],
212
- );
213
- let compilerOptions = tsconfig?.contents?.compilerOptions;
212
+ const compilerOptions: TSConfig['compilerOptions'] = (
213
+ await config.getConfigFrom<TSConfig>(
214
+ options.projectRoot + '/index',
215
+ ['tsconfig.json', 'jsconfig.json'],
216
+ {
217
+ readTracking: true,
218
+ },
219
+ )
220
+ )?.contents?.compilerOptions;
214
221
 
215
222
  // Use explicitly defined JSX options in tsconfig.json over inferred values from dependencies.
216
223
  pragma =
217
224
  compilerOptions?.jsxFactory ||
225
+ // @ts-expect-error TS7053
218
226
  (reactLib ? JSX_PRAGMA[reactLib].pragma : undefined);
219
227
  pragmaFrag =
220
228
  compilerOptions?.jsxFragmentFactory ||
229
+ // @ts-expect-error TS7053
221
230
  (reactLib ? JSX_PRAGMA[reactLib].pragmaFrag : undefined);
222
231
 
223
232
  if (
@@ -229,20 +238,23 @@ export default (new Transformer({
229
238
  automaticJSXRuntime = true;
230
239
  } else if (reactLib) {
231
240
  let effectiveReactLib =
232
- pkg?.alias && pkg.alias['react'] === 'preact/compat'
241
+ packageJson?.alias && packageJson.alias['react'] === 'preact/compat'
233
242
  ? 'preact'
234
243
  : reactLib;
244
+ // @ts-expect-error TS7053
235
245
  let automaticVersion = JSX_PRAGMA[effectiveReactLib]?.automatic;
236
246
  let reactLibVersion =
237
- pkg?.dependencies?.[effectiveReactLib] ||
238
- pkg?.devDependencies?.[effectiveReactLib] ||
239
- pkg?.peerDependencies?.[effectiveReactLib];
247
+ packageJson?.dependencies?.[effectiveReactLib] ||
248
+ packageJson?.devDependencies?.[effectiveReactLib] ||
249
+ packageJson?.peerDependencies?.[effectiveReactLib];
250
+ // @ts-expect-error TS2322
240
251
  reactLibVersion = reactLibVersion
241
252
  ? semver.validRange(reactLibVersion)
242
253
  : null;
243
254
  let minReactLibVersion =
244
255
  reactLibVersion !== null && reactLibVersion !== '*'
245
- ? semver.minVersion(reactLibVersion)?.toString()
256
+ ? // @ts-expect-error TS2345
257
+ semver.minVersion(reactLibVersion)?.toString()
246
258
  : null;
247
259
 
248
260
  automaticJSXRuntime =
@@ -278,10 +290,10 @@ export default (new Transformer({
278
290
  // Check if we should ignore fs calls
279
291
  // See https://github.com/defunctzombie/node-browser-resolve#skip
280
292
  let ignoreFS =
281
- pkg &&
282
- pkg.browser &&
283
- typeof pkg.browser === 'object' &&
284
- pkg.browser.fs === false;
293
+ packageJson &&
294
+ packageJson.browser &&
295
+ typeof packageJson.browser === 'object' &&
296
+ packageJson.browser.fs === false;
285
297
 
286
298
  let conf = await config.getConfigFrom(options.projectRoot + '/index', [], {
287
299
  packageKey: '@atlaspack/transformer-js',
@@ -291,14 +303,75 @@ export default (new Transformer({
291
303
  let inlineFS = !ignoreFS;
292
304
  let inlineConstants = false;
293
305
  let magicComments = false;
306
+ let addReactDisplayName = false;
307
+
308
+ let enableSsrTypeofReplacement =
309
+ options.env.NATIVE_SSR_TYPEOF_REPLACEMENT === 'true';
310
+ let globalAliasingConfig =
311
+ options.env.NATIVE_GLOBAL_ALIASING &&
312
+ JSON.parse(options.env.NATIVE_GLOBAL_ALIASING);
313
+ let enableLazyLoading = options.env.NATIVE_LAZY_LOADING === 'true';
314
+ let enableReactHooksRemoval =
315
+ options.env.NATIVE_REACT_HOOKS_REMOVAL === 'true';
316
+ let enableReactAsyncImportLift =
317
+ options.env.NATIVE_REACT_ASYNC_IMPORT_LIFT === 'true';
318
+ let reactAsyncLiftByDefault =
319
+ options.env.REACT_ASYNC_IMPORT_LIFTING_BY_DEFAULT === 'true';
320
+ let reactAsyncLiftReportLevel =
321
+ options.env.REACT_ASYNC_LIFT_REPORT_LEVEL || 'none';
322
+ let enableStaticPrevaluation = options.env.NATIVE_PREVALUATION === 'true';
323
+ let enableDeadReturnsRemoval =
324
+ options.env.NATIVE_DEAD_RETURNS_REMOVAL === 'true';
325
+ let enableUnusedBindingsRemoval =
326
+ options.env.NATIVE_UNUSED_BINDINGS_REMOVAL === 'true';
327
+ let syncDynamicImportConfig:
328
+ | {
329
+ entrypoint_filepath_suffix: string;
330
+ actual_require_paths: string[];
331
+ }
332
+ | undefined;
333
+
334
+ if (config.env.isTesseract() && options.env.SYNC_DYNAMIC_IMPORT_CONFIG) {
335
+ try {
336
+ let config = configCache.get(
337
+ 'SYNC_DYNAMIC_IMPORT_CONFIG',
338
+ ) as typeof syncDynamicImportConfig;
339
+
340
+ if (!config) {
341
+ config = JSON.parse(options.env.SYNC_DYNAMIC_IMPORT_CONFIG);
342
+
343
+ invariant(typeof config?.entrypoint_filepath_suffix === 'string');
344
+ invariant(Array.isArray(config.actual_require_paths));
345
+
346
+ configCache.set('SYNC_DYNAMIC_IMPORT_CONFIG', config);
347
+ }
348
+
349
+ syncDynamicImportConfig = config;
350
+ } catch {
351
+ // eslint-disable-next-line no-console
352
+ console.warn(
353
+ 'Failed to parse SYNC_DYNAMIC_IMPORT_CONFIG to JSON or config shape did not match. Config will not be applied.',
354
+ );
355
+
356
+ const fallback = {
357
+ entrypoint_filepath_suffix: '__NO_MATCH__',
358
+ actual_require_paths: [],
359
+ };
360
+
361
+ // Set cache to fallback so we don't keep trying to parse.
362
+ configCache.set('SYNC_DYNAMIC_IMPORT_CONFIG', fallback);
363
+ syncDynamicImportConfig = fallback;
364
+ }
365
+ }
366
+
367
+ config.invalidateOnEnvChange('SYNC_DYNAMIC_IMPORT_CONFIG');
294
368
 
295
369
  if (conf && conf.contents) {
296
370
  validateSchema.diagnostic(
297
371
  CONFIG_SCHEMA,
298
372
  {
299
373
  data: conf.contents,
300
- // FIXME
301
- source: await options.inputFS.readFile(conf.filePath, 'utf8'),
374
+ source: () => options.inputFS.readFileSync(conf.filePath, 'utf8'),
302
375
  filePath: conf.filePath,
303
376
  prependKey: `/${encodeJSONKeyComponent('@atlaspack/transformer-js')}`,
304
377
  },
@@ -307,10 +380,17 @@ export default (new Transformer({
307
380
  'Invalid config for @atlaspack/transformer-js',
308
381
  );
309
382
 
383
+ addReactDisplayName =
384
+ // @ts-expect-error TS2339
385
+ conf.contents?.addReactDisplayName ?? addReactDisplayName;
386
+ // @ts-expect-error TS2339
310
387
  magicComments = conf.contents?.magicComments ?? magicComments;
388
+ // @ts-expect-error TS2339
311
389
  inlineEnvironment = conf.contents?.inlineEnvironment ?? inlineEnvironment;
390
+ // @ts-expect-error TS2339
312
391
  inlineFS = conf.contents?.inlineFS ?? inlineFS;
313
392
  inlineConstants =
393
+ // @ts-expect-error TS2339
314
394
  conf.contents?.unstable_inlineConstants ?? inlineConstants;
315
395
  }
316
396
 
@@ -323,10 +403,22 @@ export default (new Transformer({
323
403
  inlineEnvironment,
324
404
  inlineFS,
325
405
  inlineConstants,
406
+ addReactDisplayName,
326
407
  reactRefresh,
327
408
  decorators,
328
409
  useDefineForClassFields,
329
410
  magicComments,
411
+ globalAliasingConfig,
412
+ enableSsrTypeofReplacement,
413
+ enableLazyLoading,
414
+ enableDeadReturnsRemoval,
415
+ enableUnusedBindingsRemoval,
416
+ enableStaticPrevaluation,
417
+ enableReactHooksRemoval,
418
+ syncDynamicImportConfig,
419
+ enableReactAsyncImportLift,
420
+ reactAsyncLiftByDefault,
421
+ reactAsyncLiftReportLevel,
330
422
  };
331
423
  },
332
424
  async transform({asset, config, options, logger}) {
@@ -357,6 +449,7 @@ export default (new Transformer({
357
449
  for (let browser of browsers) {
358
450
  let [name, version] = browser.split(' ');
359
451
  if (BROWSER_MAPPING.hasOwnProperty(name)) {
452
+ // @ts-expect-error TS7053
360
453
  name = BROWSER_MAPPING[name];
361
454
  if (!name) {
362
455
  continue;
@@ -366,12 +459,15 @@ export default (new Transformer({
366
459
  let [major, minor = '0', patch = '0'] = version
367
460
  .split('-')[0]
368
461
  .split('.');
462
+ // @ts-expect-error TS2345
369
463
  if (isNaN(major) || isNaN(minor) || isNaN(patch)) {
370
464
  continue;
371
465
  }
372
466
  let semverVersion = `${major}.${minor}.${patch}`;
373
467
 
468
+ // @ts-expect-error TS2345
374
469
  if (targets[name] == null || semver.gt(targets[name], semverVersion)) {
470
+ // @ts-expect-error TS7053
375
471
  targets[name] = semverVersion;
376
472
  }
377
473
  }
@@ -411,24 +507,47 @@ export default (new Transformer({
411
507
  if (asset.type === 'ts') {
412
508
  isJSX = false;
413
509
  } else if (!isJSX) {
510
+ // @ts-expect-error TS7053
414
511
  isJSX = Boolean(JSX_EXTENSIONS[asset.type]);
415
512
  }
416
513
  }
417
514
 
418
- let macroAssets = [];
515
+ let macroAssets: Array<{
516
+ content: string;
517
+ // @ts-expect-error TS2552
518
+ map: undefined | NodeSourceMap;
519
+ type: string;
520
+ uniqueKey: string;
521
+ }> = [];
419
522
  let {
523
+ // @ts-expect-error TS2339
420
524
  dependencies,
525
+ // @ts-expect-error TS2339
421
526
  code: compiledCode,
527
+ // @ts-expect-error TS2339
422
528
  map,
529
+ // @ts-expect-error TS2339
423
530
  shebang,
531
+ // @ts-expect-error TS2339
424
532
  hoist_result,
533
+ // @ts-expect-error TS2339
425
534
  symbol_result,
535
+ // @ts-expect-error TS2339
536
+ is_empty_or_empty_export,
537
+ // @ts-expect-error TS2339
426
538
  needs_esm_helpers,
539
+ // @ts-expect-error TS2339
427
540
  diagnostics,
541
+ // @ts-expect-error TS2339
428
542
  used_env,
543
+ // @ts-expect-error TS2339
429
544
  has_node_replacements,
545
+ // @ts-expect-error TS2339
430
546
  is_constant_module,
547
+ // @ts-expect-error TS2339
431
548
  conditions,
549
+ // @ts-expect-error TS2339
550
+ magic_comments,
432
551
  } = await (transformAsync || transform)({
433
552
  filename: asset.filePath,
434
553
  code,
@@ -440,7 +559,7 @@ export default (new Transformer({
440
559
  !asset.env.isNode() && asset.env.sourceType !== 'script',
441
560
  node_replacer: asset.env.isNode(),
442
561
  is_browser: asset.env.isBrowser(),
443
- is_worker: asset.env.isWorker(),
562
+ is_worker: asset.env.isWorker() || asset.env.isTesseract(),
444
563
  env,
445
564
  is_type_script: asset.type === 'ts' || asset.type === 'tsx',
446
565
  is_jsx: isJSX,
@@ -453,6 +572,7 @@ export default (new Transformer({
453
572
  asset.env.isBrowser() &&
454
573
  !asset.env.isLibrary &&
455
574
  !asset.env.isWorker() &&
575
+ !asset.env.isTesseract() &&
456
576
  !asset.env.isWorklet() &&
457
577
  Boolean(config?.reactRefresh),
458
578
  decorators: Boolean(config?.decorators),
@@ -470,9 +590,32 @@ export default (new Transformer({
470
590
  standalone: asset.query.has('standalone'),
471
591
  inline_constants: config.inlineConstants,
472
592
  conditional_bundling: options.featureFlags.conditionalBundlingApi,
473
- magic_comments: Boolean(config?.magicComments),
593
+ hmr_improvements: options.featureFlags.hmrImprovements,
594
+ add_display_name: Boolean(config.addReactDisplayName),
595
+ exports_rebinding_optimisation:
596
+ options.featureFlags.exportsRebindingOptimisation,
597
+ magic_comments:
598
+ Boolean(config?.magicComments) ||
599
+ getFeatureFlag('supportWebpackChunkName'),
600
+ is_source: asset.isSource,
601
+ nested_promise_import_fix: options.featureFlags.nestedPromiseImportFix,
602
+ global_aliasing_config: config.globalAliasingConfig,
603
+ enable_ssr_typeof_replacement: Boolean(config.enableSsrTypeofReplacement),
604
+ enable_lazy_loading: Boolean(config.enableLazyLoading),
605
+ enable_dead_returns_removal: Boolean(config.enableDeadReturnsRemoval),
606
+ enable_unused_bindings_removal: Boolean(
607
+ config.enableUnusedBindingsRemoval,
608
+ ),
609
+ enable_static_prevaluation: Boolean(config.enableStaticPrevaluation),
610
+ enable_react_hooks_removal: Boolean(config.enableReactHooksRemoval),
611
+ enable_react_async_import_lift: Boolean(
612
+ config.enableReactAsyncImportLift,
613
+ ),
614
+ react_async_lift_by_default: Boolean(config.reactAsyncLiftByDefault),
615
+ react_async_lift_report_level: String(config.reactAsyncLiftReportLevel),
616
+ sync_dynamic_import_config: config.syncDynamicImportConfig,
474
617
  callMacro: asset.isSource
475
- ? async (err, src, exportName, args, loc) => {
618
+ ? async (err: any, src: any, exportName: any, args: any, loc: any) => {
476
619
  let mod;
477
620
  try {
478
621
  mod = await options.packageManager.require(src, asset.filePath);
@@ -481,7 +624,6 @@ export default (new Transformer({
481
624
  if (
482
625
  exportName === 'default' &&
483
626
  !mod.__esModule &&
484
- // $FlowFixMe
485
627
  Object.prototype.toString.call(config) !== '[object Module]'
486
628
  ) {
487
629
  mod = {default: mod};
@@ -490,7 +632,7 @@ export default (new Transformer({
490
632
  if (!Object.hasOwnProperty.call(mod, exportName)) {
491
633
  throw new Error(`"${src}" does not export "${exportName}".`);
492
634
  }
493
- } catch (err) {
635
+ } catch (err: any) {
494
636
  throw {
495
637
  kind: 1,
496
638
  message: err.message,
@@ -507,7 +649,8 @@ export default (new Transformer({
507
649
  if (asset.env.sourceMap) {
508
650
  // Generate a source map that maps each line of the asset to the original macro call.
509
651
  map = new SourceMap(options.projectRoot);
510
- let mappings = [];
652
+ // @ts-expect-error TS2304
653
+ let mappings: Array<IndexedMapping<string>> = [];
511
654
  let line = 1;
512
655
  for (let i = 0; i <= a.content.length; i++) {
513
656
  if (i === a.content.length || a.content[i] === '\n') {
@@ -530,7 +673,9 @@ export default (new Transformer({
530
673
  if (originalMap) {
531
674
  map.extends(originalMap);
532
675
  } else {
533
- map.setSourceContent(asset.filePath, code.toString());
676
+ if (!getFeatureFlag('omitSourcesContentInMemory')) {
677
+ map.setSourceContent(asset.filePath, code.toString());
678
+ }
534
679
  }
535
680
  }
536
681
 
@@ -546,13 +691,13 @@ export default (new Transformer({
546
691
  specifierType: 'esm',
547
692
  });
548
693
  },
549
- invalidateOnFileChange(filePath) {
694
+ invalidateOnFileChange(filePath: FilePath) {
550
695
  asset.invalidateOnFileChange(filePath);
551
696
  },
552
- invalidateOnFileCreate(invalidation) {
697
+ invalidateOnFileCreate(invalidation: FileCreateInvalidation) {
553
698
  asset.invalidateOnFileCreate(invalidation);
554
699
  },
555
- invalidateOnEnvChange(env) {
700
+ invalidateOnEnvChange(env: string) {
556
701
  asset.invalidateOnEnvChange(env);
557
702
  },
558
703
  invalidateOnStartup() {
@@ -569,7 +714,7 @@ export default (new Transformer({
569
714
  `"${exportName}" in "${src}" is not a function.`,
570
715
  );
571
716
  }
572
- } catch (err) {
717
+ } catch (err: any) {
573
718
  // Remove atlaspack core from stack and build string so Rust can process errors more easily.
574
719
  let stack = (err.stack || '').split('\n').slice(1);
575
720
  let message = err.message;
@@ -589,18 +734,14 @@ export default (new Transformer({
589
734
  });
590
735
 
591
736
  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
- }));
737
+ asset.meta.conditions = conditions;
597
738
  }
598
739
 
599
740
  if (is_constant_module) {
600
741
  asset.meta.isConstantModule = true;
601
742
  }
602
743
 
603
- let convertLoc = (loc): SourceLocation => {
744
+ let convertLoc = (loc: any): SourceLocation => {
604
745
  let location = {
605
746
  filePath: asset.filePath,
606
747
  start: {
@@ -615,7 +756,11 @@ export default (new Transformer({
615
756
 
616
757
  // If there is an original source map, use it to remap to the original source location.
617
758
  if (originalMap) {
618
- location = remapSourceLocation(location, originalMap);
759
+ location = remapSourceLocation(
760
+ location,
761
+ originalMap,
762
+ options.projectRoot,
763
+ );
619
764
  }
620
765
 
621
766
  return location;
@@ -623,19 +768,22 @@ export default (new Transformer({
623
768
 
624
769
  if (diagnostics) {
625
770
  let errors = diagnostics.filter(
771
+ // @ts-expect-error TS7006
626
772
  (d) =>
627
773
  d.severity === 'Error' ||
628
774
  (d.severity === 'SourceError' && asset.isSource),
629
775
  );
630
776
  let warnings = diagnostics.filter(
777
+ // @ts-expect-error TS7006
631
778
  (d) =>
632
779
  d.severity === 'Warning' ||
633
780
  (d.severity === 'SourceError' && !asset.isSource),
634
781
  );
635
- let convertDiagnostic = (diagnostic) => {
782
+ let convertDiagnostic = (diagnostic: any) => {
636
783
  let message = diagnostic.message;
637
784
  if (message === 'SCRIPT_ERROR') {
638
- let err = SCRIPT_ERRORS[(asset.env.context: string)];
785
+ // @ts-expect-error TS7053
786
+ let err = SCRIPT_ERRORS[asset.env.context as string];
639
787
  message = err?.message || SCRIPT_ERRORS.browser.message;
640
788
  }
641
789
 
@@ -644,11 +792,12 @@ export default (new Transformer({
644
792
  codeFrames: [
645
793
  {
646
794
  filePath: asset.filePath,
647
- codeHighlights: diagnostic.code_highlights?.map((highlight) =>
648
- convertSourceLocationToHighlight(
649
- convertLoc(highlight.loc),
650
- highlight.message ?? undefined,
651
- ),
795
+ codeHighlights: diagnostic.code_highlights?.map(
796
+ (highlight: any) =>
797
+ convertSourceLocationToHighlight(
798
+ convertLoc(highlight.loc),
799
+ highlight.message ?? undefined,
800
+ ),
652
801
  ),
653
802
  },
654
803
  ],
@@ -672,7 +821,8 @@ export default (new Transformer({
672
821
  });
673
822
  }
674
823
 
675
- let err = SCRIPT_ERRORS[(asset.env.context: string)];
824
+ // @ts-expect-error TS7053
825
+ let err = SCRIPT_ERRORS[asset.env.context as string];
676
826
  if (err) {
677
827
  if (!res.hints) {
678
828
  res.hints = [err.hint];
@@ -729,6 +879,7 @@ export default (new Transformer({
729
879
  env: {
730
880
  context: 'web-worker',
731
881
  sourceType: dep.source_type === 'Module' ? 'module' : 'script',
882
+ // @ts-expect-error TS2322
732
883
  outputFormat,
733
884
  loc,
734
885
  },
@@ -776,6 +927,13 @@ export default (new Transformer({
776
927
  });
777
928
  } else if (dep.kind === 'File') {
778
929
  asset.invalidateOnFileChange(dep.specifier);
930
+ } else if (dep.kind === 'Id') {
931
+ // Record parcelRequire calls so that the dev packager can add them as dependencies.
932
+ // This allows the HMR runtime to collect parents across async boundaries (through runtimes).
933
+ // TODO: ideally this would result as an actual dep in the graph rather than asset.meta.
934
+ asset.meta.hmrDeps ??= [];
935
+ invariant(Array.isArray(asset.meta.hmrDeps));
936
+ asset.meta.hmrDeps.push(dep.specifier);
779
937
  } else {
780
938
  let meta: JSONObject = {kind: dep.kind};
781
939
  if (dep.attributes) {
@@ -839,6 +997,13 @@ export default (new Transformer({
839
997
  outputFormat,
840
998
  loc: convertLoc(dep.loc),
841
999
  };
1000
+
1001
+ if (getFeatureFlag('supportWebpackChunkName')) {
1002
+ let chunkName = magic_comments[dep.specifier];
1003
+ if (chunkName) {
1004
+ meta.chunkName = chunkName;
1005
+ }
1006
+ }
842
1007
  }
843
1008
 
844
1009
  // Always bundle helpers, even with includeNodeModules: false, except if this is a library.
@@ -863,6 +1028,7 @@ export default (new Transformer({
863
1028
  idx = dep.specifier.indexOf('/', idx + 1);
864
1029
  }
865
1030
  let module = idx >= 0 ? dep.specifier.slice(0, idx) : dep.specifier;
1031
+ // @ts-expect-error TS7053
866
1032
  range = pkg.dependencies[module];
867
1033
  }
868
1034
 
@@ -874,12 +1040,13 @@ export default (new Transformer({
874
1040
  dep.kind === 'DynamicImport'
875
1041
  ? 'lazy'
876
1042
  : dep.kind === 'ConditionalImport'
877
- ? 'conditional'
878
- : 'sync',
1043
+ ? 'conditional'
1044
+ : 'sync',
879
1045
  isOptional: dep.is_optional,
880
1046
  meta,
881
1047
  resolveFrom: isHelper ? __filename : undefined,
882
1048
  range,
1049
+ // @ts-expect-error TS2322
883
1050
  env,
884
1051
  });
885
1052
  }
@@ -893,8 +1060,12 @@ export default (new Transformer({
893
1060
  local,
894
1061
  loc,
895
1062
  is_esm,
1063
+ is_static_binding_safe,
896
1064
  } of hoist_result.exported_symbols) {
897
- asset.symbols.set(exported, local, convertLoc(loc), {isEsm: is_esm});
1065
+ asset.symbols.set(exported, local, convertLoc(loc), {
1066
+ isEsm: is_esm,
1067
+ isStaticBindingSafe: is_static_binding_safe,
1068
+ });
898
1069
  }
899
1070
 
900
1071
  // deps is a map of dependencies that are keyed by placeholder or specifier
@@ -991,6 +1162,9 @@ export default (new Transformer({
991
1162
  Object.keys(hoist_result.exported_symbols).length === 0) ||
992
1163
  (hoist_result.should_wrap && !asset.symbols.hasExportSymbol('*'))
993
1164
  ) {
1165
+ if (is_empty_or_empty_export) {
1166
+ asset.meta.emptyFileStarReexport = true;
1167
+ }
994
1168
  asset.symbols.set('*', `$${asset.id}$exports`);
995
1169
  }
996
1170
 
@@ -1093,4 +1267,4 @@ export default (new Transformer({
1093
1267
 
1094
1268
  return [asset, ...macroAssets];
1095
1269
  },
1096
- }): Transformer);
1270
+ }) as Transformer<unknown>;