@parcel/packager-js 2.0.0-beta.3.1 → 2.0.0-nightly.1006

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.
@@ -15,10 +15,10 @@ function _utils() {
15
15
  return data;
16
16
  }
17
17
 
18
- function _sourceMap() {
18
+ function _sourceMap2() {
19
19
  const data = _interopRequireDefault(require("@parcel/source-map"));
20
20
 
21
- _sourceMap = function () {
21
+ _sourceMap2 = function () {
22
22
  return data;
23
23
  };
24
24
 
@@ -65,117 +65,66 @@ function _globals() {
65
65
  return data;
66
66
  }
67
67
 
68
- function _ESMOutputFormat() {
69
- const data = require("./ESMOutputFormat");
68
+ var _ESMOutputFormat = require("./ESMOutputFormat");
70
69
 
71
- _ESMOutputFormat = function () {
72
- return data;
73
- };
74
-
75
- return data;
76
- }
77
-
78
- function _CJSOutputFormat() {
79
- const data = require("./CJSOutputFormat");
80
-
81
- _CJSOutputFormat = function () {
82
- return data;
83
- };
70
+ var _CJSOutputFormat = require("./CJSOutputFormat");
84
71
 
85
- return data;
86
- }
72
+ var _GlobalOutputFormat = require("./GlobalOutputFormat");
87
73
 
88
- function _GlobalOutputFormat() {
89
- const data = require("./GlobalOutputFormat");
74
+ var _helpers = require("./helpers");
90
75
 
91
- _GlobalOutputFormat = function () {
92
- return data;
93
- };
94
-
95
- return data;
96
- }
97
-
98
- function _helpers() {
99
- const data = require("./helpers");
100
-
101
- _helpers = function () {
102
- return data;
103
- };
104
-
105
- return data;
106
- }
76
+ var _utils2 = require("./utils");
107
77
 
108
78
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
109
79
 
110
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
111
-
112
80
  // https://262.ecma-international.org/6.0/#sec-names-and-keywords
113
81
  const IDENTIFIER_RE = /^[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}]*$/u;
114
82
  const ID_START_RE = /^[$_\p{ID_Start}]/u;
115
- const NON_ID_CONTINUE_RE = /[^$_\u200C\u200D\p{ID_Continue}]/gu;
83
+ const NON_ID_CONTINUE_RE = /[^$_\u200C\u200D\p{ID_Continue}]/gu; // General regex used to replace imports with the resolved code, references with resolutions,
84
+ // and count the number of newlines in the file for source maps.
85
+
86
+ const REPLACEMENT_RE = /\n|import\s+"([0-9a-f]{16}:.+?)";|(?:\$[0-9a-f]{16}\$exports)|(?:\$[0-9a-f]{16}\$(?:import|importAsync|require)\$[0-9a-f]+(?:\$[0-9a-f]+)?)/g;
116
87
  const BUILTINS = Object.keys(_globals().default.builtin);
117
88
  const GLOBALS_BY_CONTEXT = {
118
89
  browser: new Set([...BUILTINS, ...Object.keys(_globals().default.browser)]),
119
90
  'web-worker': new Set([...BUILTINS, ...Object.keys(_globals().default.worker)]),
120
91
  'service-worker': new Set([...BUILTINS, ...Object.keys(_globals().default.serviceworker)]),
92
+ worklet: new Set([...BUILTINS]),
121
93
  node: new Set([...BUILTINS, ...Object.keys(_globals().default.node)]),
122
94
  'electron-main': new Set([...BUILTINS, ...Object.keys(_globals().default.node)]),
123
95
  'electron-renderer': new Set([...BUILTINS, ...Object.keys(_globals().default.node), ...Object.keys(_globals().default.browser)])
124
96
  };
125
97
  const OUTPUT_FORMATS = {
126
- esmodule: _ESMOutputFormat().ESMOutputFormat,
127
- commonjs: _CJSOutputFormat().CJSOutputFormat,
128
- global: _GlobalOutputFormat().GlobalOutputFormat
98
+ esmodule: _ESMOutputFormat.ESMOutputFormat,
99
+ commonjs: _CJSOutputFormat.CJSOutputFormat,
100
+ global: _GlobalOutputFormat.GlobalOutputFormat
129
101
  };
130
102
 
131
103
  class ScopeHoistingPackager {
132
- constructor(options, bundleGraph, bundle, parcelRequireName) {
133
- var _this$bundle$getMainE;
134
-
135
- _defineProperty(this, "options", void 0);
136
-
137
- _defineProperty(this, "bundleGraph", void 0);
138
-
139
- _defineProperty(this, "bundle", void 0);
140
-
141
- _defineProperty(this, "parcelRequireName", void 0);
142
-
143
- _defineProperty(this, "outputFormat", void 0);
144
-
145
- _defineProperty(this, "isAsyncBundle", void 0);
146
-
147
- _defineProperty(this, "globalNames", void 0);
148
-
149
- _defineProperty(this, "assetOutputs", void 0);
150
-
151
- _defineProperty(this, "exportedSymbols", new Map());
152
-
153
- _defineProperty(this, "externals", new Map());
154
-
155
- _defineProperty(this, "topLevelNames", new Map());
156
-
157
- _defineProperty(this, "seenAssets", new Set());
158
-
159
- _defineProperty(this, "wrappedAssets", new Set());
160
-
161
- _defineProperty(this, "hoistedRequires", new Map());
162
-
163
- _defineProperty(this, "needsPrelude", false);
164
-
165
- _defineProperty(this, "usedHelpers", new Set());
104
+ exportedSymbols = new Map();
105
+ externals = new Map();
106
+ topLevelNames = new Map();
107
+ seenAssets = new Set();
108
+ wrappedAssets = new Set();
109
+ hoistedRequires = new Map();
110
+ needsPrelude = false;
111
+ usedHelpers = new Set();
166
112
 
113
+ constructor(options, bundleGraph, bundle, parcelRequireName) {
167
114
  this.options = options;
168
115
  this.bundleGraph = bundleGraph;
169
116
  this.bundle = bundle;
170
117
  this.parcelRequireName = parcelRequireName;
171
118
  let OutputFormat = OUTPUT_FORMATS[this.bundle.env.outputFormat];
172
119
  this.outputFormat = new OutputFormat(this);
173
- this.isAsyncBundle = this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') && !this.bundle.env.isIsolated() && !((_this$bundle$getMainE = this.bundle.getMainEntry()) !== null && _this$bundle$getMainE !== void 0 && _this$bundle$getMainE.isIsolated);
120
+ this.isAsyncBundle = this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') && !this.bundle.env.isIsolated() && this.bundle.bundleBehavior !== 'isolated';
174
121
  this.globalNames = GLOBALS_BY_CONTEXT[bundle.env.context];
175
122
  }
176
123
 
177
124
  async package() {
178
- await this.loadAssets();
125
+ var _sourceMap;
126
+
127
+ let wrappedAssets = await this.loadAssets();
179
128
  this.buildExportedSymbols(); // If building a library, the target is actually another bundler rather
180
129
  // than the final output that could be loaded in a browser. So, loader
181
130
  // runtimes are excluded, and instead we add imports into the entry bundle
@@ -188,32 +137,48 @@ class ScopeHoistingPackager {
188
137
  for (let b of bundles) {
189
138
  this.externals.set((0, _utils().relativeBundlePath)(this.bundle, b), new Map());
190
139
  }
191
- } // Add each asset that is directly connected to the bundle. Dependencies will be handled
192
- // by replacing `import` statements in the code.
193
-
140
+ }
194
141
 
195
142
  let res = '';
196
143
  let lineCount = 0;
197
- let sourceMap = this.bundle.env.sourceMap ? new (_sourceMap().default)(this.options.projectRoot) : null;
198
- this.bundle.traverseAssets((asset, _, actions) => {
199
- if (this.seenAssets.has(asset.id)) {
200
- actions.skipChildren();
201
- return;
202
- }
144
+ let sourceMap = null;
203
145
 
146
+ let processAsset = asset => {
204
147
  let [content, map, lines] = this.visitAsset(asset);
205
148
 
206
149
  if (sourceMap && map) {
207
150
  sourceMap.addSourceMap(map, lineCount);
151
+ } else if (this.bundle.env.sourceMap) {
152
+ sourceMap = map;
208
153
  }
209
154
 
210
155
  res += content + '\n';
211
156
  lineCount += lines + 1;
157
+ }; // Hoist wrapped asset to the top of the bundle to ensure that they are registered
158
+ // before they are used.
159
+
160
+
161
+ for (let asset of wrappedAssets) {
162
+ if (!this.seenAssets.has(asset.id)) {
163
+ processAsset(asset);
164
+ }
165
+ } // Add each asset that is directly connected to the bundle. Dependencies will be handled
166
+ // by replacing `import` statements in the code.
167
+
168
+
169
+ this.bundle.traverseAssets((asset, _, actions) => {
170
+ if (this.seenAssets.has(asset.id)) {
171
+ actions.skipChildren();
172
+ return;
173
+ }
174
+
175
+ processAsset(asset);
212
176
  actions.skipChildren();
213
177
  });
214
178
  let [prelude, preludeLines] = this.buildBundlePrelude();
215
179
  res = prelude + res;
216
- sourceMap === null || sourceMap === void 0 ? void 0 : sourceMap.offsetLines(1, preludeLines);
180
+ lineCount += preludeLines;
181
+ (_sourceMap = sourceMap) === null || _sourceMap === void 0 ? void 0 : _sourceMap.offsetLines(1, preludeLines);
217
182
  let entries = this.bundle.getEntryAssets();
218
183
  let mainEntry = this.bundle.getMainEntry();
219
184
 
@@ -230,7 +195,7 @@ class ScopeHoistingPackager {
230
195
 
231
196
 
232
197
  for (let entry of entries) {
233
- if (this.wrappedAssets.has(entry.id)) {
198
+ if (this.wrappedAssets.has(entry.id) && !this.isScriptEntry(entry)) {
234
199
  var _entry$symbols$get;
235
200
 
236
201
  let parcelRequire = `parcelRequire(${JSON.stringify(this.bundleGraph.getAssetPublicId(entry))});\n`;
@@ -241,10 +206,38 @@ class ScopeHoistingPackager {
241
206
  } else {
242
207
  res += `\n${parcelRequire}`;
243
208
  }
209
+
210
+ lineCount += 2;
211
+ }
212
+ }
213
+
214
+ let [postlude, postludeLines] = this.outputFormat.buildBundlePostlude();
215
+ res += postlude;
216
+ lineCount += postludeLines; // The entry asset of a script bundle gets hoisted outside the bundle wrapper so that
217
+ // its top-level variables become globals like a real browser script. We need to replace
218
+ // all dependency references for runtimes with a parcelRequire call.
219
+
220
+ if (this.bundle.env.outputFormat === 'global' && this.bundle.env.sourceType === 'script') {
221
+ res += '\n';
222
+ lineCount++;
223
+ let mainEntry = (0, _nullthrows().default)(this.bundle.getMainEntry());
224
+ let {
225
+ code,
226
+ map: mapBuffer
227
+ } = (0, _nullthrows().default)(this.assetOutputs.get(mainEntry.id));
228
+ let map;
229
+
230
+ if (mapBuffer) {
231
+ map = new (_sourceMap2().default)(this.options.projectRoot, mapBuffer);
232
+ }
233
+
234
+ res += (0, _utils2.replaceScriptDependencies)(this.bundleGraph, this.bundle, code, map, this.parcelRequireName);
235
+
236
+ if (sourceMap && map) {
237
+ sourceMap.addSourceMap(map, lineCount);
244
238
  }
245
239
  }
246
240
 
247
- res += this.outputFormat.buildBundlePostlude();
248
241
  return {
249
242
  contents: res,
250
243
  map: sourceMap
@@ -255,74 +248,61 @@ class ScopeHoistingPackager {
255
248
  let queue = new (_utils().PromiseQueue)({
256
249
  maxConcurrent: 32
257
250
  });
258
- this.bundle.traverse((node, shouldWrap) => {
259
- switch (node.type) {
260
- case 'dependency':
261
- // Mark assets that should be wrapped, based on metadata in the incoming dependency tree
262
- if (node.value.meta.shouldWrap) {
263
- let resolved = this.bundleGraph.getDependencyResolution(node.value, this.bundle);
264
-
265
- if (resolved && resolved.sideEffects) {
266
- this.wrappedAssets.add(resolved.id);
267
- }
268
-
269
- return true;
270
- }
271
-
272
- break;
273
-
274
- case 'asset':
275
- queue.add(async () => {
276
- let [code, map] = await Promise.all([node.value.getCode(), this.bundle.env.sourceMap ? node.value.getMapBuffer() : null]);
277
- return [node.value.id, {
278
- code,
279
- map
280
- }];
281
- });
282
-
283
- if (shouldWrap || node.value.meta.shouldWrap || this.isAsyncBundle || this.bundleGraph.isAssetReferencedByDependant(this.bundle, node.value)) {
284
- this.wrappedAssets.add(node.value.id);
285
- return true;
286
- }
251
+ let wrapped = [];
252
+ this.bundle.traverseAssets((asset, shouldWrap) => {
253
+ queue.add(async () => {
254
+ let [code, map] = await Promise.all([asset.getCode(), this.bundle.env.sourceMap ? asset.getMapBuffer() : null]);
255
+ return [asset.id, {
256
+ code,
257
+ map
258
+ }];
259
+ });
287
260
 
261
+ if (shouldWrap || asset.meta.shouldWrap || this.isAsyncBundle || this.bundle.env.sourceType === 'script' || this.bundleGraph.isAssetReferenced(this.bundle, asset) || this.bundleGraph.getIncomingDependencies(asset).some(dep => dep.meta.shouldWrap && dep.specifierType !== 'url')) {
262
+ this.wrappedAssets.add(asset.id);
263
+ wrapped.push(asset);
264
+ return true;
288
265
  }
289
266
  });
290
267
  this.assetOutputs = new Map(await queue.run());
268
+ return wrapped;
291
269
  }
292
270
 
293
271
  buildExportedSymbols() {
294
- if (this.isAsyncBundle || this.bundle.env.outputFormat !== 'esmodule') {
272
+ if (this.isAsyncBundle || !this.bundle.env.isLibrary || this.bundle.env.outputFormat !== 'esmodule') {
295
273
  return;
296
- }
274
+ } // TODO: handle ESM exports of wrapped entry assets...
275
+
297
276
 
298
277
  let entry = this.bundle.getMainEntry();
299
278
 
300
- if (entry) {
279
+ if (entry && !this.wrappedAssets.has(entry.id)) {
301
280
  for (let {
281
+ asset,
302
282
  exportAs,
303
- symbol
283
+ symbol,
284
+ exportSymbol
304
285
  } of this.bundleGraph.getExportedSymbols(entry)) {
305
286
  if (typeof symbol === 'string') {
306
- var _entry$symbols$get2;
287
+ var _this$exportedSymbols, _entry$symbols$get2;
307
288
 
308
- let symbols = this.exportedSymbols.get(symbol === '*' ? (0, _nullthrows().default)((_entry$symbols$get2 = entry.symbols.get('*')) === null || _entry$symbols$get2 === void 0 ? void 0 : _entry$symbols$get2.local) : symbol);
309
- let local = symbol;
289
+ let symbols = (_this$exportedSymbols = this.exportedSymbols.get(symbol === '*' ? (0, _nullthrows().default)((_entry$symbols$get2 = entry.symbols.get('*')) === null || _entry$symbols$get2 === void 0 ? void 0 : _entry$symbols$get2.local) : symbol)) === null || _this$exportedSymbols === void 0 ? void 0 : _this$exportedSymbols.exportAs;
310
290
 
311
- if (symbols) {
312
- local = symbols[0].local;
313
- } else {
291
+ if (!symbols) {
314
292
  symbols = [];
315
- this.exportedSymbols.set(symbol, symbols);
293
+ this.exportedSymbols.set(symbol, {
294
+ asset,
295
+ exportSymbol,
296
+ local: symbol,
297
+ exportAs: symbols
298
+ });
316
299
  }
317
300
 
318
301
  if (exportAs === '*') {
319
302
  exportAs = 'default';
320
303
  }
321
304
 
322
- symbols.push({
323
- exportAs,
324
- local
325
- });
305
+ symbols.push(exportAs);
326
306
  } else if (symbol === null) {// TODO `meta.exportsIdentifier[exportSymbol]` should be exported
327
307
  // let relativePath = relative(options.projectRoot, asset.filePath);
328
308
  // throw getThrowableDiagnosticForNode(
@@ -359,6 +339,14 @@ class ScopeHoistingPackager {
359
339
  return name + count;
360
340
  }
361
341
 
342
+ getPropertyAccess(obj, property) {
343
+ if (IDENTIFIER_RE.test(property)) {
344
+ return `${obj}.${property}`;
345
+ }
346
+
347
+ return `${obj}[${JSON.stringify(property)}]`;
348
+ }
349
+
362
350
  visitAsset(asset) {
363
351
  (0, _assert().default)(!this.seenAssets.has(asset.id), 'Already visited asset');
364
352
  this.seenAssets.add(asset.id);
@@ -372,19 +360,14 @@ class ScopeHoistingPackager {
372
360
  buildAsset(asset, code, map) {
373
361
  let shouldWrap = this.wrappedAssets.has(asset.id);
374
362
  let deps = this.bundleGraph.getDependencies(asset);
375
- let sourceMap = this.bundle.env.sourceMap ? new (_sourceMap().default)(this.options.projectRoot) : null;
376
-
377
- if (sourceMap && map) {
378
- sourceMap === null || sourceMap === void 0 ? void 0 : sourceMap.addBuffer(map);
379
- } // If this asset is skipped, just add dependencies and not the asset's content.
380
-
363
+ let sourceMap = this.bundle.env.sourceMap && map ? new (_sourceMap2().default)(this.options.projectRoot, map) : null; // If this asset is skipped, just add dependencies and not the asset's content.
381
364
 
382
365
  if (this.shouldSkipAsset(asset)) {
383
366
  let depCode = '';
384
367
  let lineCount = 0;
385
368
 
386
369
  for (let dep of deps) {
387
- let resolved = this.bundleGraph.getDependencyResolution(dep, this.bundle);
370
+ let resolved = this.bundleGraph.getResolvedAsset(dep, this.bundle);
388
371
  let skipped = this.bundleGraph.isDependencySkipped(dep);
389
372
 
390
373
  if (!resolved || skipped) {
@@ -419,92 +402,103 @@ class ScopeHoistingPackager {
419
402
  code = prepend + code;
420
403
  }
421
404
 
422
- code += append; // Build a regular expression for all the replacements we need to do.
423
- // We need to track how many newlines there are for source maps, replace
424
- // all import statements with dependency code, and perform inline replacements
425
- // of all imported symbols with their resolved export symbols. This is all done
426
- // in a single regex so that we only do one pass over the whole code.
427
-
428
- let regex = new RegExp('\n|import\\s+"([0-9a-f]{32}:.+?)";' + (replacements.size > 0 ? '|' + [...replacements.keys()].sort((a, b) => b.length - a.length).map(k => k.replace(/[$]/g, '\\$&')).join('|') : ''), 'g');
405
+ code += append;
429
406
  let lineCount = 0;
430
- let offset = 0;
431
- let columnStartIndex = 0;
432
407
  let depContent = [];
433
- code = code.replace(regex, (m, d, i) => {
434
- var _replacements$get;
435
-
436
- if (m === '\n') {
437
- columnStartIndex = i + offset + 1;
438
- lineCount++;
439
- return '\n';
440
- } // If we matched an import, replace with the source code for the dependency.
441
408
 
409
+ if (depMap.size === 0 && replacements.size === 0) {
410
+ // If there are no dependencies or replacements, use a simple function to count the number of lines.
411
+ lineCount = (0, _utils().countLines)(code) - 1;
412
+ } else {
413
+ // Otherwise, use a regular expression to perform replacements.
414
+ // We need to track how many newlines there are for source maps, replace
415
+ // all import statements with dependency code, and perform inline replacements
416
+ // of all imported symbols with their resolved export symbols. This is all done
417
+ // in a single regex so that we only do one pass over the whole code.
418
+ let offset = 0;
419
+ let columnStartIndex = 0;
420
+ code = code.replace(REPLACEMENT_RE, (m, d, i) => {
421
+ var _replacements$get;
422
+
423
+ if (m === '\n') {
424
+ columnStartIndex = i + offset + 1;
425
+ lineCount++;
426
+ return '\n';
427
+ } // If we matched an import, replace with the source code for the dependency.
428
+
429
+
430
+ if (d != null) {
431
+ let dep = depMap.get(d);
432
+
433
+ if (!dep) {
434
+ return m;
435
+ }
442
436
 
443
- if (d != null) {
444
- let dep = (0, _nullthrows().default)(depMap.get(d));
445
- let resolved = this.bundleGraph.getDependencyResolution(dep, this.bundle);
446
- let skipped = this.bundleGraph.isDependencySkipped(dep);
437
+ let resolved = this.bundleGraph.getResolvedAsset(dep, this.bundle);
438
+ let skipped = this.bundleGraph.isDependencySkipped(dep);
439
+
440
+ if (resolved && !skipped) {
441
+ // Hoist variable declarations for the referenced parcelRequire dependencies
442
+ // after the dependency is declared. This handles the case where the resulting asset
443
+ // is wrapped, but the dependency in this asset is not marked as wrapped. This means
444
+ // that it was imported/required at the top-level, so its side effects should run immediately.
445
+ let [res, lines] = this.getHoistedParcelRequires(asset, dep, resolved);
446
+ let map;
447
+
448
+ if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved.id)) {
449
+ // If this asset is wrapped, we need to hoist the code for the dependency
450
+ // outside our parcelRequire.register wrapper. This is safe because all
451
+ // assets referenced by this asset will also be wrapped. Otherwise, inline the
452
+ // asset content where the import statement was.
453
+ if (shouldWrap) {
454
+ depContent.push(this.visitAsset(resolved));
455
+ } else {
456
+ let [depCode, depMap, depLines] = this.visitAsset(resolved);
457
+ res = depCode + '\n' + res;
458
+ lines += 1 + depLines;
459
+ map = depMap;
460
+ }
461
+ } // Push this asset's source mappings down by the number of lines in the dependency
462
+ // plus the number of hoisted parcelRequires. Then insert the source map for the dependency.
447
463
 
448
- if (resolved && !skipped) {
449
- // Hoist variable declarations for the referenced parcelRequire dependencies
450
- // after the dependency is declared. This handles the case where the resulting asset
451
- // is wrapped, but the dependency in this asset is not marked as wrapped. This means
452
- // that it was imported/required at the top-level, so its side effects should run immediately.
453
- let [res, lines] = this.getHoistedParcelRequires(asset, dep, resolved);
454
- let map;
455
-
456
- if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved.id)) {
457
- // If this asset is wrapped, we need to hoist the code for the dependency
458
- // outside our parcelRequire.register wrapper. This is safe because all
459
- // assets referenced by this asset will also be wrapped. Otherwise, inline the
460
- // asset content where the import statement was.
461
- if (shouldWrap) {
462
- depContent.push(this.visitAsset(resolved));
463
- } else {
464
- let [depCode, depMap, depLines] = this.visitAsset(resolved);
465
- res = depCode + '\n' + res;
466
- lines += 1 + depLines;
467
- map = depMap;
468
- }
469
- } // Push this asset's source mappings down by the number of lines in the dependency
470
- // plus the number of hoisted parcelRequires. Then insert the source map for the dependency.
471
464
 
465
+ if (sourceMap) {
466
+ if (lines > 0) {
467
+ sourceMap.offsetLines(lineCount + 1, lines);
468
+ }
472
469
 
473
- if (sourceMap) {
474
- if (lines > 0) {
475
- sourceMap.offsetLines(lineCount + 1, lines);
470
+ if (map) {
471
+ sourceMap.addSourceMap(map, lineCount);
472
+ }
476
473
  }
477
474
 
478
- if (map) {
479
- sourceMap.addSourceMap(map, lineCount, 0);
480
- }
475
+ lineCount += lines;
476
+ return res;
481
477
  }
482
478
 
483
- lineCount += lines;
484
- return res;
485
- }
486
-
487
- return '';
488
- } // If it wasn't a dependency, then it was an inline replacement (e.g. $id$import$foo -> $id$export$foo).
479
+ return '';
480
+ } // If it wasn't a dependency, then it was an inline replacement (e.g. $id$import$foo -> $id$export$foo).
489
481
 
490
482
 
491
- let replacement = (_replacements$get = replacements.get(m)) !== null && _replacements$get !== void 0 ? _replacements$get : '';
483
+ let replacement = (_replacements$get = replacements.get(m)) !== null && _replacements$get !== void 0 ? _replacements$get : m;
492
484
 
493
- if (sourceMap) {
494
- // Offset the source map columns for this line if the replacement was a different length.
495
- // This assumes that the match and replacement both do not contain any newlines.
496
- let lengthDifference = replacement.length - m.length;
485
+ if (sourceMap) {
486
+ // Offset the source map columns for this line if the replacement was a different length.
487
+ // This assumes that the match and replacement both do not contain any newlines.
488
+ let lengthDifference = replacement.length - m.length;
497
489
 
498
- if (lengthDifference !== 0) {
499
- sourceMap.offsetColumns(lineCount + 1, i + offset - columnStartIndex + m.length, lengthDifference);
500
- offset += lengthDifference;
490
+ if (lengthDifference !== 0) {
491
+ sourceMap.offsetColumns(lineCount + 1, i + offset - columnStartIndex + m.length, lengthDifference);
492
+ offset += lengthDifference;
493
+ }
501
494
  }
502
- }
503
495
 
504
- return replacement;
505
- }); // If the asset is wrapped, we need to insert the dependency code outside the parcelRequire.register
496
+ return replacement;
497
+ });
498
+ } // If the asset is wrapped, we need to insert the dependency code outside the parcelRequire.register
506
499
  // wrapper. Dependencies must be inserted AFTER the asset is registered so that circular dependencies work.
507
500
 
501
+
508
502
  if (shouldWrap) {
509
503
  // Offset by one line for the parcelRequire.register wrapper.
510
504
  sourceMap === null || sourceMap === void 0 ? void 0 : sourceMap.offsetLines(1, 1);
@@ -520,7 +514,7 @@ ${code}
520
514
  code += depCode + '\n';
521
515
 
522
516
  if (sourceMap && map) {
523
- sourceMap.addSourceMap(map, lineCount, 0);
517
+ sourceMap.addSourceMap(map, lineCount);
524
518
  }
525
519
 
526
520
  lineCount += lines + 1;
@@ -541,11 +535,11 @@ ${code}
541
535
  let replacements = new Map();
542
536
 
543
537
  for (let dep of deps) {
544
- depMap.set(`${assetId}:${dep.moduleSpecifier}`, dep);
538
+ depMap.set(`${assetId}:${(0, _utils2.getSpecifier)(dep)}`, dep);
545
539
  let asyncResolution = this.bundleGraph.resolveAsyncDependency(dep, this.bundle);
546
540
  let resolved = (asyncResolution === null || asyncResolution === void 0 ? void 0 : asyncResolution.type) === 'asset' ? // Prefer the underlying asset over a runtime to load it. It will
547
541
  // be wrapped in Promise.resolve() later.
548
- asyncResolution.value : this.bundleGraph.getDependencyResolution(dep, this.bundle);
542
+ asyncResolution.value : this.bundleGraph.getResolvedAsset(dep, this.bundle);
549
543
 
550
544
  if (!resolved && !dep.isOptional && !this.bundleGraph.isDependencySkipped(dep)) {
551
545
  let external = this.addExternal(dep);
@@ -559,28 +553,54 @@ ${code}
559
553
  if (renamed && local !== '*') {
560
554
  replacements.set(local, renamed);
561
555
  continue;
562
- } // Rename the specifier so that multiple local imports of the same imported specifier
563
- // are deduplicated. We have to prefix the imported name with the bundle id so that
564
- // local variables do not shadow it.
556
+ } // For CJS output, always use a property lookup so that exports remain live.
557
+ // For ESM output, use named imports which are always live.
558
+
559
+
560
+ if (this.bundle.env.outputFormat === 'commonjs') {
561
+ renamed = external.get('*');
562
+
563
+ if (!renamed) {
564
+ renamed = this.getTopLevelName(`$${this.bundle.publicId}$${dep.specifier}`);
565
+ external.set('*', renamed);
566
+ }
567
+
568
+ if (local !== '*') {
569
+ let replacement;
565
570
 
571
+ if (imported === '*') {
572
+ replacement = renamed;
573
+ } else if (imported === 'default') {
574
+ replacement = `($parcel$interopDefault(${renamed}))`;
575
+ this.usedHelpers.add('$parcel$interopDefault');
576
+ } else {
577
+ replacement = this.getPropertyAccess(renamed, imported);
578
+ }
566
579
 
567
- if (this.exportedSymbols.has(local)) {
568
- renamed = local;
569
- } else if (imported === 'default' || imported === '*') {
570
- renamed = this.getTopLevelName(`$${this.bundle.publicId}$${dep.moduleSpecifier}`);
580
+ replacements.set(local, replacement);
581
+ }
571
582
  } else {
572
- renamed = this.getTopLevelName(`$${this.bundle.publicId}$${imported}`);
573
- }
583
+ // Rename the specifier so that multiple local imports of the same imported specifier
584
+ // are deduplicated. We have to prefix the imported name with the bundle id so that
585
+ // local variables do not shadow it.
586
+ if (this.exportedSymbols.has(local)) {
587
+ renamed = local;
588
+ } else if (imported === 'default' || imported === '*') {
589
+ renamed = this.getTopLevelName(`$${this.bundle.publicId}$${dep.specifier}`);
590
+ } else {
591
+ renamed = this.getTopLevelName(`$${this.bundle.publicId}$${imported}`);
592
+ }
574
593
 
575
- external.set(imported, renamed);
594
+ external.set(imported, renamed);
576
595
 
577
- if (local !== '*') {
578
- replacements.set(local, renamed);
596
+ if (local !== '*') {
597
+ replacements.set(local, renamed);
598
+ }
579
599
  }
580
600
  }
581
601
  }
582
602
 
583
- if (!resolved || resolved === asset) {
603
+ if (!resolved) {
584
604
  continue;
585
605
  }
586
606
 
@@ -591,7 +611,7 @@ ${code}
591
611
  continue;
592
612
  }
593
613
 
594
- let symbol = this.resolveSymbol(asset, resolved, imported, dep);
614
+ let symbol = this.getSymbolResolution(asset, resolved, imported, dep);
595
615
  replacements.set(local, // If this was an internalized async asset, wrap in a Promise.resolve.
596
616
  (asyncResolution === null || asyncResolution === void 0 ? void 0 : asyncResolution.type) === 'asset' ? `Promise.resolve(${symbol})` : symbol);
597
617
  } // Async dependencies need a namespace object even if all used symbols were statically analyzed.
@@ -599,10 +619,10 @@ ${code}
599
619
  // symbols so that we don't mark all symbols as used.
600
620
 
601
621
 
602
- if (dep.isAsync && dep.meta.promiseSymbol) {
622
+ if (dep.priority === 'lazy' && dep.meta.promiseSymbol) {
603
623
  let promiseSymbol = dep.meta.promiseSymbol;
604
624
  (0, _assert().default)(typeof promiseSymbol === 'string');
605
- let symbol = this.resolveSymbol(asset, resolved, '*', dep);
625
+ let symbol = this.getSymbolResolution(asset, resolved, '*', dep);
606
626
  replacements.set(promiseSymbol, (asyncResolution === null || asyncResolution === void 0 ? void 0 : asyncResolution.type) === 'asset' ? `Promise.resolve(${symbol})` : symbol);
607
627
  }
608
628
  } // If this asset is wrapped, we need to replace the exports namespace with `module.exports`,
@@ -624,36 +644,42 @@ ${code}
624
644
  throw new (_diagnostic().default)({
625
645
  diagnostic: {
626
646
  message: 'External modules are not supported when building for browser',
627
- filePath: (0, _nullthrows().default)(dep.sourcePath),
628
- codeFrame: {
647
+ codeFrames: [{
648
+ filePath: (0, _nullthrows().default)(dep.sourcePath),
629
649
  codeHighlights: dep.loc ? [{
630
650
  start: dep.loc.start,
631
651
  end: dep.loc.end
632
652
  }] : []
633
- }
653
+ }]
634
654
  }
635
655
  });
636
- } // Map of ModuleSpecifier -> Map<ExportedSymbol, Identifier>>
656
+ } // Map of DependencySpecifier -> Map<ExportedSymbol, Identifier>>
637
657
 
638
658
 
639
- let external = this.externals.get(dep.moduleSpecifier);
659
+ let external = this.externals.get(dep.specifier);
640
660
 
641
661
  if (!external) {
642
662
  external = new Map();
643
- this.externals.set(dep.moduleSpecifier, external);
663
+ this.externals.set(dep.specifier, external);
644
664
  }
645
665
 
646
666
  return external;
647
667
  }
648
668
 
649
- resolveSymbol(parentAsset, resolved, imported, dep) {
669
+ getSymbolResolution(parentAsset, resolved, imported, dep) {
650
670
  var _resolvedAsset$symbol;
651
671
 
652
672
  let {
653
673
  asset: resolvedAsset,
654
674
  exportSymbol,
655
675
  symbol
656
- } = this.bundleGraph.resolveSymbol(resolved, imported, this.bundle);
676
+ } = this.bundleGraph.getSymbolResolution(resolved, imported, this.bundle);
677
+
678
+ if (resolvedAsset.type !== 'js') {
679
+ // Graceful fallback for non-js imports
680
+ return '{}';
681
+ }
682
+
657
683
  let isWrapped = !this.bundle.hasAsset(resolvedAsset) || this.wrappedAssets.has(resolvedAsset.id) && resolvedAsset !== parentAsset;
658
684
  let staticExports = resolvedAsset.meta.staticExports !== false;
659
685
  let publicId = this.bundleGraph.getAssetPublicId(resolvedAsset); // If the rsolved asset is wrapped, but imported at the top-level by this asset,
@@ -676,7 +702,7 @@ ${code}
676
702
  // and no __esModule flag, we need to resolve to the namespace instead.
677
703
 
678
704
 
679
- let isDefaultInterop = exportSymbol === 'default' && staticExports && !isWrapped && (dep === null || dep === void 0 ? void 0 : dep.meta.kind) === 'Import' && resolvedAsset.symbols.hasExportSymbol('*') && resolvedAsset.symbols.hasExportSymbol('default') && !resolvedAsset.symbols.hasExportSymbol('__esModule'); // Find the namespace object for the resolved module. If wrapped and this
705
+ let isDefaultInterop = exportSymbol === 'default' && staticExports && !isWrapped && ((dep === null || dep === void 0 ? void 0 : dep.meta.kind) === 'Import' || (dep === null || dep === void 0 ? void 0 : dep.meta.kind) === 'Export') && resolvedAsset.symbols.hasExportSymbol('*') && resolvedAsset.symbols.hasExportSymbol('default') && !resolvedAsset.symbols.hasExportSymbol('__esModule'); // Find the namespace object for the resolved module. If wrapped and this
680
706
  // is an inline require (not top-level), use a parcelRequire call, otherwise
681
707
  // the hoisted variable declared above. Otherwise, if not wrapped, use the
682
708
  // namespace export symbol.
@@ -694,15 +720,13 @@ ${code}
694
720
  // we need to use a member access off the namespace object rather
695
721
  // than a direct reference. If importing default from a CJS module,
696
722
  // use a helper to check the __esModule flag at runtime.
697
- if ((dep === null || dep === void 0 ? void 0 : dep.meta.kind) === 'Import' && exportSymbol === 'default' && resolvedAsset.symbols.hasExportSymbol('*') && this.needsDefaultInterop(resolvedAsset)) {
723
+ let kind = dep === null || dep === void 0 ? void 0 : dep.meta.kind;
724
+
725
+ if ((!dep || kind === 'Import' || kind === 'Export') && exportSymbol === 'default' && resolvedAsset.symbols.hasExportSymbol('*') && this.needsDefaultInterop(resolvedAsset)) {
698
726
  this.usedHelpers.add('$parcel$interopDefault');
699
727
  return `(/*@__PURE__*/$parcel$interopDefault(${obj}))`;
700
728
  } else {
701
- if (IDENTIFIER_RE.test(exportSymbol)) {
702
- return `${obj}.${exportSymbol}`;
703
- }
704
-
705
- return `${obj}[${JSON.stringify(exportSymbol)}]`;
729
+ return this.getPropertyAccess(obj, exportSymbol);
706
730
  }
707
731
  } else if (!symbol) {
708
732
  (0, _assert().default)(false, 'Asset was skipped or not found.');
@@ -743,18 +767,22 @@ ${code}
743
767
  let prependLineCount = 0;
744
768
  let append = '';
745
769
  let shouldWrap = this.wrappedAssets.has(asset.id);
746
- let usedSymbols = this.bundleGraph.getUsedSymbols(asset);
770
+ let usedSymbols = (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(asset));
747
771
  let assetId = asset.meta.id;
748
772
  (0, _assert().default)(typeof assetId === 'string'); // If the asset has a namespace export symbol, it is CommonJS.
749
773
  // If there's no __esModule flag, and default is a used symbol, we need
750
774
  // to insert an interop helper.
751
775
 
752
- let defaultInterop = asset.symbols.hasExportSymbol('*') && usedSymbols.has('default') && !asset.symbols.hasExportSymbol('__esModule'); // If the asset has * in its used symbols, we might need the exports namespace.
776
+ let defaultInterop = asset.symbols.hasExportSymbol('*') && usedSymbols.has('default') && !asset.symbols.hasExportSymbol('__esModule');
777
+ let usedNamespace = // If the asset has * in its used symbols, we might need the exports namespace.
753
778
  // The one case where this isn't true is in ESM library entries, where the only
754
779
  // dependency on * is the entry dependency. In this case, we will use ESM exports
755
780
  // instead of the namespace object.
756
-
757
- let usedNamespace = usedSymbols.has('*') && (this.bundle.env.outputFormat !== 'esmodule' || !this.bundle.env.isLibrary || asset !== this.bundle.getMainEntry() || this.bundleGraph.getIncomingDependencies(asset).some(dep => !dep.isEntry && this.bundleGraph.getUsedSymbols(dep).has('*'))); // If the asset doesn't have static exports, should wrap, the namespace is used,
781
+ usedSymbols.has('*') && (this.bundle.env.outputFormat !== 'esmodule' || !this.bundle.env.isLibrary || asset !== this.bundle.getMainEntry() || this.bundleGraph.getIncomingDependencies(asset).some(dep => !dep.isEntry && (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(dep)).has('*'))) || // If a symbol is imported (used) from a CJS asset but isn't listed in the symbols,
782
+ // we fallback on the namespace object.
783
+ asset.symbols.hasExportSymbol('*') && [...usedSymbols].some(s => !asset.symbols.hasExportSymbol(s)) || // If the exports has this asset's namespace (e.g. ESM output from CJS input),
784
+ // include the namespace object for the default export.
785
+ this.exportedSymbols.has(`$${assetId}$exports`); // If the asset doesn't have static exports, should wrap, the namespace is used,
758
786
  // or we need default interop, then we need to synthesize a namespace object for
759
787
  // this asset.
760
788
 
@@ -793,7 +821,7 @@ ${code}
793
821
  }
794
822
 
795
823
  let unused = incomingDeps.every(d => {
796
- let symbols = this.bundleGraph.getUsedSymbols(d);
824
+ let symbols = (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(d));
797
825
  return !symbols.has(symbol) && !symbols.has('*');
798
826
  });
799
827
  return !unused;
@@ -805,8 +833,10 @@ ${code}
805
833
  // required to simulate ESM live bindings. It's easier to do it this way rather than inserting
806
834
  // additional assignments after each mutation of the original binding.
807
835
  prepend += `\n${usedExports.map(exp => {
808
- let resolved = this.resolveSymbol(asset, asset, exp);
809
- return `$parcel$export($${assetId}$exports, ${JSON.stringify(exp)}, () => ${resolved}${asset.meta.hasCJSExports ? `, (v) => ${resolved} = v` : ''});`;
836
+ let resolved = this.getSymbolResolution(asset, asset, exp);
837
+ let get = this.buildFunctionExpression([], resolved);
838
+ let set = asset.meta.hasCJSExports ? ', ' + this.buildFunctionExpression(['v'], `${resolved} = v`) : '';
839
+ return `$parcel$export($${assetId}$exports, ${JSON.stringify(exp)}, ${get}${set});`;
810
840
  }).join('\n')}\n`;
811
841
  this.usedHelpers.add('$parcel$export');
812
842
  prependLineCount += 1 + usedExports.length;
@@ -814,13 +844,13 @@ ${code}
814
844
 
815
845
 
816
846
  for (let dep of deps) {
817
- let resolved = this.bundleGraph.getDependencyResolution(dep, this.bundle);
847
+ let resolved = this.bundleGraph.getResolvedAsset(dep, this.bundle);
818
848
 
819
849
  if (dep.isOptional || this.bundleGraph.isDependencySkipped(dep)) {
820
850
  continue;
821
851
  }
822
852
 
823
- let isWrapped = resolved && this.wrappedAssets.has(resolved.id);
853
+ let isWrapped = resolved && resolved.meta.shouldWrap;
824
854
 
825
855
  for (let [imported, {
826
856
  local
@@ -828,7 +858,7 @@ ${code}
828
858
  if (imported === '*' && local === '*') {
829
859
  if (!resolved) {
830
860
  // Re-exporting an external module. This should have already been handled in buildReplacements.
831
- let external = (0, _nullthrows().default)((0, _nullthrows().default)(this.externals.get(dep.moduleSpecifier)).get('*'));
861
+ let external = (0, _nullthrows().default)((0, _nullthrows().default)(this.externals.get(dep.specifier)).get('*'));
832
862
  append += `$parcel$exportWildcard($${assetId}$exports, ${external});\n`;
833
863
  this.usedHelpers.add('$parcel$exportWildcard');
834
864
  continue;
@@ -837,14 +867,23 @@ ${code}
837
867
  // $parcel$export calls for each used symbol of the dependency.
838
868
 
839
869
 
840
- if (isWrapped || resolved.meta.staticExports === false || this.bundleGraph.getUsedSymbols(resolved).has('*')) {
841
- let obj = this.resolveSymbol(asset, resolved, '*', dep);
870
+ if (isWrapped || resolved.meta.staticExports === false || (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(resolved)).has('*') || // an empty asset
871
+ !resolved.meta.hasCJSExports && resolved.symbols.hasExportSymbol('*')) {
872
+ let obj = this.getSymbolResolution(asset, resolved, '*', dep);
842
873
  append += `$parcel$exportWildcard($${assetId}$exports, ${obj});\n`;
843
874
  this.usedHelpers.add('$parcel$exportWildcard');
844
875
  } else {
845
- for (let symbol of this.bundleGraph.getUsedSymbols(dep)) {
846
- let resolvedSymbol = this.resolveSymbol(asset, resolved, symbol);
847
- prepend += `$parcel$export($${assetId}$exports, ${JSON.stringify(symbol)}, () => ${resolvedSymbol}${asset.meta.hasCJSExports ? `, (v) => ${resolvedSymbol} = v` : ''});\n`;
876
+ for (let symbol of (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(dep))) {
877
+ if (symbol === 'default' || // `export * as ...` does not include the default export
878
+ symbol === '__esModule') {
879
+ continue;
880
+ }
881
+
882
+ let resolvedSymbol = this.getSymbolResolution(asset, resolved, symbol);
883
+ let get = this.buildFunctionExpression([], resolvedSymbol);
884
+ let set = asset.meta.hasCJSExports ? ', ' + this.buildFunctionExpression(['v'], `${resolvedSymbol} = v`) : '';
885
+ prepend += `$parcel$export($${assetId}$exports, ${JSON.stringify(symbol)}, ${get}${set});\n`;
886
+ this.usedHelpers.add('$parcel$export');
848
887
  prependLineCount++;
849
888
  }
850
889
  }
@@ -883,23 +922,21 @@ ${code}
883
922
  }
884
923
 
885
924
  for (let helper of this.usedHelpers) {
886
- res += _helpers().helpers[helper];
925
+ res += _helpers.helpers[helper];
887
926
 
888
927
  if (enableSourceMaps) {
889
- lines += (0, _utils().countLines)(_helpers().helpers[helper]) - 1;
928
+ lines += (0, _utils().countLines)(_helpers.helpers[helper]) - 1;
890
929
  }
891
930
  }
892
931
 
893
932
  if (this.needsPrelude) {
894
- var _this$bundle$getMainE2;
895
-
896
933
  // Add the prelude if this is potentially the first JS bundle to load in a
897
934
  // particular context (e.g. entry scripts in HTML, workers, etc.).
898
935
  let parentBundles = this.bundleGraph.getParentBundles(this.bundle);
899
- let mightBeFirstJS = parentBundles.length === 0 || parentBundles.some(b => b.type !== 'js') || this.bundleGraph.getBundleGroupsContainingBundle(this.bundle).some(g => this.bundleGraph.isEntryBundleGroup(g)) || this.bundle.env.isIsolated() || !!((_this$bundle$getMainE2 = this.bundle.getMainEntry()) !== null && _this$bundle$getMainE2 !== void 0 && _this$bundle$getMainE2.isIsolated);
936
+ let mightBeFirstJS = parentBundles.length === 0 || parentBundles.some(b => b.type !== 'js') || this.bundleGraph.getBundleGroupsContainingBundle(this.bundle).some(g => this.bundleGraph.isEntryBundleGroup(g)) || this.bundle.env.isIsolated() || this.bundle.bundleBehavior === 'isolated';
900
937
 
901
938
  if (mightBeFirstJS) {
902
- let preludeCode = (0, _helpers().prelude)(this.parcelRequireName);
939
+ let preludeCode = (0, _helpers.prelude)(this.parcelRequireName);
903
940
  res += preludeCode;
904
941
 
905
942
  if (enableSourceMaps) {
@@ -913,12 +950,17 @@ ${code}
913
950
  } // Add importScripts for sibling bundles in workers.
914
951
 
915
952
 
916
- if (this.bundle.env.isWorker()) {
953
+ if (this.bundle.env.isWorker() || this.bundle.env.isWorklet()) {
917
954
  let importScripts = '';
918
955
  let bundles = this.bundleGraph.getReferencedBundles(this.bundle);
919
956
 
920
957
  for (let b of bundles) {
921
- importScripts += `importScripts("${(0, _utils().relativeBundlePath)(this.bundle, b)}");\n`;
958
+ if (this.bundle.env.outputFormat === 'esmodule') {
959
+ // importScripts() is not allowed in native ES module workers.
960
+ importScripts += `import "${(0, _utils().relativeBundlePath)(this.bundle, b)}";\n`;
961
+ } else {
962
+ importScripts += `importScripts("${(0, _utils().relativeBundlePath)(this.bundle, b)}");\n`;
963
+ }
922
964
  }
923
965
 
924
966
  res += importScripts;
@@ -939,7 +981,19 @@ ${code}
939
981
  }
940
982
 
941
983
  shouldSkipAsset(asset) {
942
- return asset.sideEffects === false && this.bundleGraph.getUsedSymbols(asset).size == 0 && !this.bundleGraph.isAssetReferencedByDependant(this.bundle, asset);
984
+ if (this.isScriptEntry(asset)) {
985
+ return true;
986
+ }
987
+
988
+ return asset.sideEffects === false && (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(asset)).size == 0 && !this.bundleGraph.isAssetReferenced(this.bundle, asset);
989
+ }
990
+
991
+ isScriptEntry(asset) {
992
+ return this.bundle.env.outputFormat === 'global' && this.bundle.env.sourceType === 'script' && asset === this.bundle.getMainEntry();
993
+ }
994
+
995
+ buildFunctionExpression(args, expr) {
996
+ return this.bundle.env.supports('arrow-functions', true) ? `(${args.join(', ')}) => ${expr}` : `function (${args.join(', ')}) { return ${expr}; }`;
943
997
  }
944
998
 
945
999
  }