-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
JSPackager.js
222 lines (196 loc) Β· 6.21 KB
/
JSPackager.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// @flow strict-local
import type {Bundle, BundleGraph, Async} from '@parcel/types';
import invariant from 'assert';
import nullthrows from 'nullthrows';
import {Packager} from '@parcel/plugin';
import fs from 'fs';
import {concat, link, generate} from '@parcel/scope-hoisting';
import SourceMap from '@parcel/source-map';
import {
countLines,
PromiseQueue,
relativeBundlePath,
replaceInlineReferences,
} from '@parcel/utils';
import path from 'path';
const PRELUDE = fs
.readFileSync(path.join(__dirname, 'prelude.js'), 'utf8')
.trim()
.replace(/;$/, '');
export default new Packager({
async package({
bundle,
bundleGraph,
getInlineBundleContents,
getSourceMapReference,
options,
}) {
function replaceReferences({contents, map}) {
return replaceInlineReferences({
bundle,
bundleGraph,
contents,
getInlineReplacement: (dependency, inlineType, content) => ({
from: `"${dependency.id}"`,
to: inlineType === 'string' ? JSON.stringify(content) : content,
}),
getInlineBundleContents,
map,
});
}
// If scope hoisting is enabled, we use a different code path.
if (bundle.env.scopeHoist) {
let ast = await concat(bundle, bundleGraph);
ast = link({bundle, bundleGraph, ast, options});
let {contents, map} = generate(bundleGraph, bundle, ast, options);
return replaceReferences({
contents:
contents +
'\n' +
(await getSourceMapSuffix(getSourceMapReference, map)),
map,
});
}
if (bundle.env.outputFormat === 'esmodule') {
throw new Error(
`esmodule output is not supported without scope hoisting.`,
);
}
// For development, we just concatenate all of the code together
// rather then enabling scope hoisting, which would be too slow.
let queue = new PromiseQueue({maxConcurrent: 32});
bundle.traverse(node => {
if (node.type === 'asset') {
queue.add(async () => {
let [code, mapBuffer] = await Promise.all([
node.value.getCode(),
node.value.getMapBuffer(),
]);
return {code, mapBuffer};
});
}
});
let results = await queue.run();
let assets = '';
let i = 0;
let first = true;
let map = new SourceMap();
let prefix = getPrefix(bundle, bundleGraph);
let lineOffset = countLines(prefix);
let stubsWritten = new Set();
bundle.traverse(node => {
let wrapped = first ? '' : ',';
if (node.type === 'dependency') {
let resolved = bundleGraph.getDependencyResolution(node.value, bundle);
if (
resolved &&
resolved.type !== 'js' &&
!stubsWritten.has(resolved.id)
) {
// if this is a reference to another javascript asset, we should not include
// its output, as its contents should already be loaded.
invariant(!bundle.hasAsset(resolved));
wrapped += JSON.stringify(resolved.id) + ':[function() {},{}]';
} else {
return;
}
}
if (node.type === 'asset') {
let asset = node.value;
invariant(
asset.type === 'js',
'all assets in a js bundle must be js assets',
);
let deps = {};
let dependencies = bundleGraph.getDependencies(asset);
for (let dep of dependencies) {
let resolved = bundleGraph.getDependencyResolution(dep, bundle);
if (resolved) {
deps[dep.moduleSpecifier] = resolved.id;
}
}
let {code, mapBuffer} = results[i];
let output = code || '';
wrapped +=
JSON.stringify(asset.id) +
':[function(require,module,exports) {\n' +
output +
'\n},';
wrapped += JSON.stringify(deps);
wrapped += ']';
if (options.sourceMaps) {
if (mapBuffer) {
map.addBufferMappings(mapBuffer, lineOffset);
} else {
map.addEmptyMap(
path
.relative(options.projectRoot, asset.filePath)
.replace(/\\+/g, '/'),
output,
lineOffset,
);
}
lineOffset += countLines(output) + 1;
}
i++;
}
assets += wrapped;
first = false;
});
let entries = bundle.getEntryAssets();
if (!isEntry(bundle, bundleGraph) && bundle.env.outputFormat === 'global') {
// The last entry is the main entry, but in async bundles we don't want it to execute until we require it
// as there might be dependencies in a sibling bundle that hasn't loaded yet.
entries.pop();
}
return replaceReferences({
contents:
prefix +
'({' +
assets +
'},{},' +
JSON.stringify(entries.map(asset => asset.id)) +
', ' +
'null' +
')' +
'\n\n' +
(await getSourceMapSuffix(getSourceMapReference, map)),
map,
});
},
});
function getPrefix(bundle: Bundle, bundleGraph: BundleGraph): string {
let interpreter: ?string;
if (isEntry(bundle, bundleGraph) && !bundle.target.env.isBrowser()) {
let _interpreter = nullthrows(bundle.getMainEntry()).meta.interpreter;
invariant(_interpreter == null || typeof _interpreter === 'string');
interpreter = _interpreter;
}
let importScripts = '';
if (bundle.env.isWorker()) {
let bundles = bundleGraph.getSiblingBundles(bundle);
for (let b of bundles) {
importScripts += `importScripts("${relativeBundlePath(bundle, b)}");\n`;
}
}
return (
// If the entry asset included a hashbang, repeat it at the top of the bundle
(interpreter != null ? `#!${interpreter}\n` : '') + importScripts + PRELUDE
);
}
function isEntry(bundle: Bundle, bundleGraph: BundleGraph): boolean {
return (
!bundleGraph.hasParentBundleOfType(bundle, 'js') || bundle.env.isIsolated()
);
}
async function getSourceMapSuffix(
getSourceMapReference: (?SourceMap) => Async<?string>,
map: ?SourceMap,
): Promise<string> {
let sourcemapReference = await getSourceMapReference(map);
if (sourcemapReference != null) {
return '//# sourceMappingURL=' + sourcemapReference + '\n';
} else {
return '';
}
}