@atlaspack/packager-js 2.14.5-canary.35 → 2.14.5-canary.350

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.
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.helpers = exports.bundleQueuePrelude = exports.fnExpr = exports.preludeNew = exports.preludeOld = void 0;
4
+ const preludeOld = (parcelRequireName) => `
5
+ var $parcel$modules = {};
6
+ var $parcel$inits = {};
7
+
8
+ var parcelRequire = $parcel$global[${JSON.stringify(parcelRequireName)}];
9
+
10
+ if (parcelRequire == null) {
11
+ parcelRequire = function(id) {
12
+ if (id in $parcel$modules) {
13
+ return $parcel$modules[id].exports;
14
+ }
15
+ if (id in $parcel$inits) {
16
+ var init = $parcel$inits[id];
17
+ delete $parcel$inits[id];
18
+ var module = {id: id, exports: {}};
19
+ $parcel$modules[id] = module;
20
+ init.call(module.exports, module, module.exports);
21
+ return module.exports;
22
+ }
23
+ var err = new Error("Cannot find module '" + id + "'");
24
+ err.code = 'MODULE_NOT_FOUND';
25
+ throw err;
26
+ };
27
+
28
+ parcelRequire.register = function register(id, init) {
29
+ $parcel$inits[id] = init;
30
+ };
31
+
32
+ $parcel$global[${JSON.stringify(parcelRequireName)}] = parcelRequire;
33
+ }
34
+
35
+ var parcelRegister = parcelRequire.register;
36
+ `;
37
+ exports.preludeOld = preludeOld;
38
+ const preludeNew = (parcelRequireName) => `
39
+ var $parcel$modules = {};
40
+ var $parcel$inits = {};
41
+
42
+ var parcelRequire = $parcel$global[${JSON.stringify(parcelRequireName)}];
43
+
44
+ if (parcelRequire == null) {
45
+ parcelRequire = function(id) {
46
+ var mod = $parcel$modules[id];
47
+ if (mod !== undefined) {
48
+ return mod.exports;
49
+ }
50
+ var init = $parcel$inits[id];
51
+ if (init !== undefined) {
52
+ delete $parcel$inits[id];
53
+ var module = {id: id, exports: {}};
54
+ $parcel$modules[id] = module;
55
+ init.call(module.exports, module, module.exports);
56
+ return module.exports;
57
+ }
58
+ var err = new Error("Cannot find module '" + id + "'");
59
+ err.code = 'MODULE_NOT_FOUND';
60
+ throw err;
61
+ };
62
+
63
+ parcelRequire.register = function register(id, init) {
64
+ $parcel$inits[id] = init;
65
+ };
66
+
67
+ $parcel$global[${JSON.stringify(parcelRequireName)}] = parcelRequire;
68
+ }
69
+
70
+ var parcelRegister = parcelRequire.register;
71
+ `;
72
+ exports.preludeNew = preludeNew;
73
+ const fnExpr = (env, params, body) => {
74
+ let block = `{ ${body.join(' ')} }`;
75
+ if (env.supports('arrow-functions')) {
76
+ return `(${params.join(', ')}) => ${block}`;
77
+ }
78
+ return `function (${params.join(', ')}) ${block}`;
79
+ };
80
+ exports.fnExpr = fnExpr;
81
+ const bundleQueuePrelude = (env) => `
82
+ if (!$parcel$global.lb) {
83
+ // Set of loaded bundles
84
+ $parcel$global.lb = new Set();
85
+ // Queue of bundles to execute once they're dep bundles are loaded
86
+ $parcel$global.bq = [];
87
+
88
+ // Register loaded bundle
89
+ $parcel$global.rlb = ${(0, exports.fnExpr)(env, ['bundle'], ['$parcel$global.lb.add(bundle);', '$parcel$global.pq();'])}
90
+
91
+ // Run when ready
92
+ $parcel$global.rwr = ${(0, exports.fnExpr)(env,
93
+ // b = bundle public id
94
+ // r = run function to execute the bundle entry
95
+ // d = list of dependent bundles this bundle requires before executing
96
+ ['b', 'r', 'd'], ['$parcel$global.bq.push({b, r, d});', '$parcel$global.pq();'])}
97
+
98
+ // Process queue
99
+ $parcel$global.pq = ${(0, exports.fnExpr)(env, [], [
100
+ `var runnableEntry = $parcel$global.bq.find(${(0, exports.fnExpr)(env, ['i'], [
101
+ `return i.d.every(${(0, exports.fnExpr)(env, ['dep'], ['return $parcel$global.lb.has(dep);'])});`,
102
+ ])});`,
103
+ 'if (runnableEntry) {',
104
+ `$parcel$global.bq = $parcel$global.bq.filter(${(0, exports.fnExpr)(env, ['i'], ['return i.b !== runnableEntry.b;'])});`,
105
+ 'runnableEntry.r();',
106
+ '$parcel$global.pq();',
107
+ '}',
108
+ ])}
109
+ }
110
+ `;
111
+ exports.bundleQueuePrelude = bundleQueuePrelude;
112
+ const $parcel$export = `
113
+ function $parcel$export(e, n, v, s) {
114
+ Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
115
+ }
116
+ `;
117
+ const $parcel$exportWildcard = `
118
+ function $parcel$exportWildcard(dest, source) {
119
+ Object.keys(source).forEach(function(key) {
120
+ if (key === 'default' || key === '__esModule' || Object.prototype.hasOwnProperty.call(dest, key)) {
121
+ return;
122
+ }
123
+
124
+ Object.defineProperty(dest, key, {
125
+ enumerable: true,
126
+ get: function get() {
127
+ return source[key];
128
+ }
129
+ });
130
+ });
131
+
132
+ return dest;
133
+ }
134
+ `;
135
+ const $parcel$interopDefault = `
136
+ function $parcel$interopDefault(a) {
137
+ return a && a.__esModule ? a.default : a;
138
+ }
139
+ `;
140
+ const $parcel$global = (env) => {
141
+ if (env.supports('global-this')) {
142
+ return `
143
+ var $parcel$global = globalThis;
144
+ `;
145
+ }
146
+ return `
147
+ var $parcel$global =
148
+ typeof globalThis !== 'undefined'
149
+ ? globalThis
150
+ : typeof self !== 'undefined'
151
+ ? self
152
+ : typeof window !== 'undefined'
153
+ ? window
154
+ : typeof global !== 'undefined'
155
+ ? global
156
+ : {};
157
+ `;
158
+ };
159
+ const $parcel$defineInteropFlag = `
160
+ function $parcel$defineInteropFlag(a) {
161
+ Object.defineProperty(a, '__esModule', {value: true, configurable: true});
162
+ }
163
+ `;
164
+ exports.helpers = {
165
+ $parcel$export,
166
+ $parcel$exportWildcard,
167
+ $parcel$interopDefault,
168
+ $parcel$global,
169
+ $parcel$defineInteropFlag,
170
+ };
package/dist/index.js ADDED
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const plugin_1 = require("@atlaspack/plugin");
7
+ const utils_1 = require("@atlaspack/utils");
8
+ const diagnostic_1 = require("@atlaspack/diagnostic");
9
+ const rust_1 = require("@atlaspack/rust");
10
+ const nullthrows_1 = __importDefault(require("nullthrows"));
11
+ const DevPackager_1 = require("./DevPackager");
12
+ const ScopeHoistingPackager_1 = require("./ScopeHoistingPackager");
13
+ const CONFIG_SCHEMA = {
14
+ type: 'object',
15
+ properties: {
16
+ unstable_asyncBundleRuntime: {
17
+ type: 'boolean',
18
+ },
19
+ unstable_manualStaticBindingExports: {
20
+ type: 'array',
21
+ items: {
22
+ type: 'string',
23
+ },
24
+ },
25
+ },
26
+ additionalProperties: false,
27
+ };
28
+ exports.default = new plugin_1.Packager({
29
+ async loadConfig({ config, options }) {
30
+ let packageKey = '@atlaspack/packager-js';
31
+ let conf = await config.getConfigFrom(options.projectRoot + '/index', [], {
32
+ packageKey,
33
+ });
34
+ if (conf?.contents) {
35
+ utils_1.validateSchema.diagnostic(CONFIG_SCHEMA, {
36
+ data: conf?.contents,
37
+ source: () => options.inputFS.readFileSync(conf.filePath, 'utf8'),
38
+ filePath: conf.filePath,
39
+ prependKey: `/${(0, diagnostic_1.encodeJSONKeyComponent)(packageKey)}`,
40
+ }, packageKey, `Invalid config for ${packageKey}`);
41
+ }
42
+ // Generate a name for the global parcelRequire function that is unique to this project.
43
+ // This allows multiple parcel builds to coexist on the same page.
44
+ let packageName = await config.getConfigFrom(options.projectRoot + '/index', [], {
45
+ packageKey: 'name',
46
+ });
47
+ let name = packageName?.contents ?? '';
48
+ return {
49
+ parcelRequireName: 'parcelRequire' + (0, rust_1.hashString)(name).slice(-4),
50
+ unstable_asyncBundleRuntime: Boolean(conf?.contents?.unstable_asyncBundleRuntime),
51
+ unstable_manualStaticBindingExports: conf?.contents?.unstable_manualStaticBindingExports ?? null,
52
+ };
53
+ },
54
+ async package({ bundle, bundleGraph, getInlineBundleContents, getSourceMapReference, config, options, logger, }) {
55
+ // If this is a non-module script, and there is only one asset with no dependencies,
56
+ // then we don't need to package at all and can pass through the original code un-wrapped.
57
+ let contents, map;
58
+ let scopeHoistingStats;
59
+ if (bundle.env.sourceType === 'script') {
60
+ let entries = bundle.getEntryAssets();
61
+ if (entries.length === 1 &&
62
+ bundleGraph.getDependencies(entries[0]).length === 0) {
63
+ contents = await entries[0].getCode();
64
+ map = await entries[0].getMap();
65
+ }
66
+ }
67
+ if (contents == null) {
68
+ if (bundle.env.shouldScopeHoist) {
69
+ let packager = new ScopeHoistingPackager_1.ScopeHoistingPackager(options, bundleGraph, bundle, (0, nullthrows_1.default)(config).parcelRequireName, (0, nullthrows_1.default)(config).unstable_asyncBundleRuntime, (0, nullthrows_1.default)(config).unstable_manualStaticBindingExports, logger);
70
+ let packageResult = await packager.package();
71
+ ({ contents, map } = packageResult);
72
+ scopeHoistingStats = packageResult.scopeHoistingStats;
73
+ }
74
+ else {
75
+ let packager = new DevPackager_1.DevPackager(options, bundleGraph, bundle, (0, nullthrows_1.default)(config).parcelRequireName);
76
+ let packageResult = await packager.package();
77
+ ({ contents, map } = packageResult);
78
+ }
79
+ }
80
+ contents += '\n' + (await getSourceMapSuffix(getSourceMapReference, map));
81
+ // For library builds, we need to replace URL references with their final resolved paths.
82
+ // For non-library builds, this is handled in the JS runtime.
83
+ if (bundle.env.isLibrary) {
84
+ ({ contents, map } = (0, utils_1.replaceURLReferences)({
85
+ bundle,
86
+ bundleGraph,
87
+ contents,
88
+ map,
89
+ getReplacement: (s) => JSON.stringify(s).slice(1, -1),
90
+ }));
91
+ }
92
+ let result = await (0, utils_1.replaceInlineReferences)({
93
+ bundle,
94
+ bundleGraph,
95
+ contents,
96
+ getInlineReplacement: (dependency, inlineType, content) => ({
97
+ from: `"${dependency.id}"`,
98
+ to: inlineType === 'string' ? JSON.stringify(content) : content,
99
+ }),
100
+ getInlineBundleContents,
101
+ map,
102
+ });
103
+ if (utils_1.debugTools['scope-hoisting-stats']) {
104
+ return { ...result, scopeHoistingStats };
105
+ }
106
+ return result;
107
+ },
108
+ });
109
+ async function getSourceMapSuffix(getSourceMapReference, map) {
110
+ let sourcemapReference = await getSourceMapReference(map);
111
+ if (sourcemapReference != null) {
112
+ return '//# sourceMappingURL=' + sourcemapReference + '\n';
113
+ }
114
+ else {
115
+ return '';
116
+ }
117
+ }
package/dist/utils.js ADDED
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.replaceScriptDependencies = replaceScriptDependencies;
7
+ exports.getSpecifier = getSpecifier;
8
+ exports.isValidIdentifier = isValidIdentifier;
9
+ exports.makeValidIdentifier = makeValidIdentifier;
10
+ const nullthrows_1 = __importDefault(require("nullthrows"));
11
+ // This replaces __parcel__require__ references left by the transformer with
12
+ // parcelRequire calls of the resolved asset id. This lets runtimes work within
13
+ // script bundles, which must be outside the bundle wrapper so their variables are global.
14
+ function replaceScriptDependencies(bundleGraph, bundle, code, map, parcelRequireName) {
15
+ let entry = (0, nullthrows_1.default)(bundle.getMainEntry());
16
+ let dependencies = bundleGraph.getDependencies(entry);
17
+ let lineCount = 0;
18
+ let offset = 0;
19
+ let columnStartIndex = 0;
20
+ code = code.replace(/\n|__parcel__require__\(['"](.*?)['"]\)/g, (m, s, i) => {
21
+ if (m === '\n') {
22
+ columnStartIndex = i + offset + 1;
23
+ lineCount++;
24
+ return '\n';
25
+ }
26
+ let dep = (0, nullthrows_1.default)(dependencies.find((d) => getSpecifier(d) === s));
27
+ let resolved = (0, nullthrows_1.default)(bundleGraph.getResolvedAsset(dep, bundle));
28
+ let publicId = bundleGraph.getAssetPublicId(resolved);
29
+ let replacement = `${parcelRequireName}("${publicId}")`;
30
+ if (map) {
31
+ let lengthDifference = replacement.length - m.length;
32
+ if (lengthDifference !== 0) {
33
+ map.offsetColumns(lineCount + 1, i + offset - columnStartIndex + m.length, lengthDifference);
34
+ offset += lengthDifference;
35
+ }
36
+ }
37
+ return replacement;
38
+ });
39
+ return code;
40
+ }
41
+ function getSpecifier(dep) {
42
+ if (typeof dep.meta.placeholder === 'string') {
43
+ return dep.meta.placeholder;
44
+ }
45
+ return dep.specifier;
46
+ }
47
+ // https://262.ecma-international.org/6.0/#sec-names-and-keywords
48
+ const IDENTIFIER_RE = /^[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}]*$/u;
49
+ const ID_START_RE = /^[$_\p{ID_Start}]/u;
50
+ const NON_ID_CONTINUE_RE = /[^$_\u200C\u200D\p{ID_Continue}]/gu;
51
+ function isValidIdentifier(id) {
52
+ return IDENTIFIER_RE.test(id);
53
+ }
54
+ function makeValidIdentifier(name) {
55
+ name = name.replace(NON_ID_CONTINUE_RE, '');
56
+ if (!ID_START_RE.test(name)) {
57
+ name = '_' + name;
58
+ }
59
+ return name;
60
+ }
@@ -12,12 +12,19 @@ function _utils() {
12
12
  return data;
13
13
  }
14
14
  function _sourceMap() {
15
- const data = _interopRequireDefault(require("@parcel/source-map"));
15
+ const data = _interopRequireDefault(require("@atlaspack/source-map"));
16
16
  _sourceMap = function () {
17
17
  return data;
18
18
  };
19
19
  return data;
20
20
  }
21
+ function _featureFlags() {
22
+ const data = require("@atlaspack/feature-flags");
23
+ _featureFlags = function () {
24
+ return data;
25
+ };
26
+ return data;
27
+ }
21
28
  function _assert() {
22
29
  const data = _interopRequireDefault(require("assert"));
23
30
  _assert = function () {
@@ -91,6 +98,7 @@ class DevPackager {
91
98
  // If this is the main entry of a script rather than a module, we need to hoist it
92
99
  // outside the bundle wrapper function so that its variables are exposed as globals.
93
100
  if (this.bundle.env.sourceType === 'script' && asset === this.bundle.getMainEntry()) {
101
+ // @ts-expect-error TS2322
94
102
  script = results[i++];
95
103
  return;
96
104
  }
@@ -108,6 +116,19 @@ class DevPackager {
108
116
  deps[specifier] = dep.specifier;
109
117
  }
110
118
  }
119
+ if ((0, _featureFlags().getFeatureFlag)('hmrImprovements')) {
120
+ // Add dependencies for parcelRequire calls added by runtimes
121
+ // so that the HMR runtime can correctly traverse parents.
122
+ let hmrDeps = asset.meta.hmrDeps;
123
+ if (this.options.hmrOptions && Array.isArray(hmrDeps)) {
124
+ for (let id of hmrDeps) {
125
+ (0, _assert().default)(typeof id === 'string');
126
+ deps[id] = id;
127
+ }
128
+ }
129
+ }
130
+
131
+ // @ts-expect-error TS2339
111
132
  let {
112
133
  code,
113
134
  mapBuffer
@@ -152,11 +173,14 @@ class DevPackager {
152
173
  // runtimes with a parcelRequire call.
153
174
  if (this.bundle.env.sourceType === 'script' && script) {
154
175
  let entryMap;
176
+ // @ts-expect-error TS2339
155
177
  let mapBuffer = script.mapBuffer;
156
178
  if (mapBuffer) {
157
179
  entryMap = new (_sourceMap().default)(this.options.projectRoot, mapBuffer);
158
180
  }
159
- contents += (0, _utils2.replaceScriptDependencies)(this.bundleGraph, this.bundle, script.code, entryMap, this.parcelRequireName);
181
+ contents += (0, _utils2.replaceScriptDependencies)(this.bundleGraph, this.bundle,
182
+ // @ts-expect-error TS2339
183
+ script.code, entryMap, this.parcelRequireName);
160
184
  if (this.bundle.env.sourceMap && entryMap) {
161
185
  map.addSourceMap(entryMap, lineOffset);
162
186
  }
@@ -175,7 +199,7 @@ class DevPackager {
175
199
  interpreter = _interpreter;
176
200
  }
177
201
  let importScripts = '';
178
- if (this.bundle.env.isWorker()) {
202
+ if (this.bundle.env.isWorker() || this.bundle.env.isTesseract()) {
179
203
  let bundles = this.bundleGraph.getReferencedBundles(this.bundle);
180
204
  for (let b of bundles) {
181
205
  importScripts += `importScripts("${(0, _utils().relativeBundlePath)(this.bundle, b)}");\n`;
@@ -187,7 +211,7 @@ class DevPackager {
187
211
  );
188
212
  }
189
213
  isEntry() {
190
- return !this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') || this.bundle.env.isIsolated() || this.bundle.bundleBehavior === 'isolated';
214
+ return !this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') || this.bundle.env.isIsolated() || this.bundle.bundleBehavior === 'isolated' || this.bundle.bundleBehavior === 'inlineIsolated';
191
215
  }
192
216
  }
193
217
  exports.DevPackager = DevPackager;
@@ -75,7 +75,7 @@ class ESMOutputFormat {
75
75
  local,
76
76
  exportAs
77
77
  } of this.packager.exportedSymbols.values()) {
78
- if (this.packager.wrappedAssets.has(asset.id)) {
78
+ if (this.packager.wrappedAssets.has(asset)) {
79
79
  let obj = `parcelRequire("${this.packager.bundleGraph.getAssetPublicId(asset)}")`;
80
80
  res += `\nvar ${local} = ${this.packager.getPropertyAccess(obj, exportSymbol)};`;
81
81
  lines++;