/
WriteBundleRequest.js
314 lines (283 loc) Β· 8.31 KB
/
WriteBundleRequest.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// @flow strict-local
import type {FileSystem, FileOptions} from '@parcel/fs';
import type {ContentKey} from '@parcel/graph';
import type {Async, FilePath, Compressor} from '@parcel/types';
import type {RunAPI, StaticRunOpts} from '../RequestTracker';
import type {Bundle, PackagedBundleInfo, ParcelOptions} from '../types';
import type BundleGraph from '../BundleGraph';
import type {BundleInfo} from '../PackagerRunner';
import type {ConfigAndCachePath} from './ParcelConfigRequest';
import type {LoadedPlugin} from '../ParcelConfig';
import type {ProjectPath} from '../projectPath';
import {HASH_REF_PREFIX, HASH_REF_REGEX} from '../constants';
import nullthrows from 'nullthrows';
import path from 'path';
import {NamedBundle} from '../public/Bundle';
import {blobToStream, TapStream} from '@parcel/utils';
import {Readable, Transform, pipeline} from 'stream';
import {
fromProjectPath,
fromProjectPathRelative,
toProjectPath,
joinProjectPath,
toProjectPathUnsafe,
} from '../projectPath';
import createParcelConfigRequest, {
getCachedParcelConfig,
} from './ParcelConfigRequest';
import PluginOptions from '../public/PluginOptions';
import {PluginLogger} from '@parcel/logger';
import {
getDevDepRequests,
invalidateDevDeps,
createDevDependency,
runDevDepRequest,
} from './DevDepRequest';
import ParcelConfig from '../ParcelConfig';
import ThrowableDiagnostic, {errorToDiagnostic} from '@parcel/diagnostic';
const BOUNDARY_LENGTH = HASH_REF_PREFIX.length + 32 - 1;
type WriteBundleRequestInput = {|
bundleGraph: BundleGraph,
bundle: Bundle,
info: BundleInfo,
hashRefToNameHash: Map<string, string>,
|};
type RunInput = {|
input: WriteBundleRequestInput,
...StaticRunOpts,
|};
export type WriteBundleRequest = {|
id: ContentKey,
+type: 'write_bundle_request',
run: RunInput => Async<PackagedBundleInfo>,
input: WriteBundleRequestInput,
|};
/**
* Writes a bundle to the dist directory, replacing hash references with the final content hashes.
*/
export default function createWriteBundleRequest(
input: WriteBundleRequestInput,
): WriteBundleRequest {
let nameHash = nullthrows(
input.hashRefToNameHash.get(input.bundle.hashReference),
);
return {
id: `${input.bundle.id}:${input.info.hash}:${nameHash}`,
type: 'write_bundle_request',
run,
input,
};
}
async function run({input, options, api}: RunInput) {
let {bundleGraph, bundle, info, hashRefToNameHash} = input;
let {inputFS, outputFS} = options;
let name = nullthrows(bundle.name);
let thisHashReference = bundle.hashReference;
if (info.type !== bundle.type) {
name = name.slice(0, -path.extname(name).length) + '.' + info.type;
}
if (name.includes(thisHashReference)) {
let thisNameHash = nullthrows(hashRefToNameHash.get(thisHashReference));
name = name.replace(thisHashReference, thisNameHash);
}
let filePath = joinProjectPath(bundle.target.distDir, name);
// Watch the bundle and source map for deletion.
// Also watch the dist dir because invalidateOnFileDelete does not currently
// invalidate when a parent directory is deleted.
// TODO: do we want to also watch for file edits?
api.invalidateOnFileDelete(bundle.target.distDir);
api.invalidateOnFileDelete(filePath);
let cacheKeys = info.cacheKeys;
let mapKey = cacheKeys.map;
let fullPath = fromProjectPath(options.projectRoot, filePath);
if (mapKey && bundle.env.sourceMap && !bundle.env.sourceMap.inline) {
api.invalidateOnFileDelete(
toProjectPath(options.projectRoot, fullPath + '.map'),
);
}
let dir = path.dirname(fullPath);
await outputFS.mkdirp(dir); // ? Got rid of dist exists, is this an expensive operation
// Use the file mode from the entry asset as the file mode for the bundle.
// Don't do this for browser builds, as the executable bit in particular is unnecessary.
let publicBundle = NamedBundle.get(bundle, bundleGraph, options);
let mainEntry = publicBundle.getMainEntry();
let writeOptions =
publicBundle.env.isBrowser() || !mainEntry
? undefined
: {
mode: (await inputFS.stat(mainEntry.filePath)).mode,
};
let contentStream: Readable;
if (info.isLargeBlob) {
contentStream = options.cache.getStream(cacheKeys.content);
} else {
contentStream = blobToStream(
await options.cache.getBlob(cacheKeys.content),
);
}
let size = 0;
contentStream = contentStream.pipe(
new TapStream(buf => {
size += buf.length;
}),
);
let configResult = nullthrows(
await api.runRequest<null, ConfigAndCachePath>(createParcelConfigRequest()),
);
let config = getCachedParcelConfig(configResult, options);
let {devDeps, invalidDevDeps} = await getDevDepRequests(api);
invalidateDevDeps(invalidDevDeps, options, config);
await writeFiles(
contentStream,
info,
hashRefToNameHash,
options,
config,
outputFS,
filePath,
writeOptions,
devDeps,
api,
);
if (
mapKey &&
bundle.env.sourceMap &&
!bundle.env.sourceMap.inline &&
(await options.cache.has(mapKey))
) {
await writeFiles(
blobToStream(await options.cache.getBlob(mapKey)),
info,
hashRefToNameHash,
options,
config,
outputFS,
toProjectPathUnsafe(fromProjectPathRelative(filePath) + '.map'),
writeOptions,
devDeps,
api,
);
}
let res = {
filePath,
stats: {
size,
time: info.time ?? 0,
},
};
api.storeResult(res);
return res;
}
async function writeFiles(
inputStream: stream$Readable,
info: BundleInfo,
hashRefToNameHash: Map<string, string>,
options: ParcelOptions,
config: ParcelConfig,
outputFS: FileSystem,
filePath: ProjectPath,
writeOptions: ?FileOptions,
devDeps: Map<string, string>,
api: RunAPI,
) {
let compressors = await config.getCompressors(
fromProjectPathRelative(filePath),
);
let fullPath = fromProjectPath(options.projectRoot, filePath);
let stream = info.hashReferences.length
? inputStream.pipe(replaceStream(hashRefToNameHash))
: inputStream;
let promises = [];
for (let compressor of compressors) {
promises.push(
runCompressor(
compressor,
cloneStream(stream),
options,
outputFS,
fullPath,
writeOptions,
devDeps,
api,
),
);
}
await Promise.all(promises);
}
async function runCompressor(
compressor: LoadedPlugin<Compressor>,
stream: stream$Readable,
options: ParcelOptions,
outputFS: FileSystem,
filePath: FilePath,
writeOptions: ?FileOptions,
devDeps: Map<string, string>,
api: RunAPI,
) {
try {
let res = await compressor.plugin.compress({
stream,
options: new PluginOptions(options),
logger: new PluginLogger({origin: compressor.name}),
});
await new Promise((resolve, reject) =>
pipeline(
res.stream,
outputFS.createWriteStream(
filePath + (res.type != null ? '.' + res.type : ''),
writeOptions,
),
err => {
if (err) reject(err);
else resolve();
},
),
);
} catch (err) {
throw new ThrowableDiagnostic({
diagnostic: errorToDiagnostic(err, {
origin: compressor.name,
}),
});
} finally {
// Add dev deps for compressor plugins AFTER running them, to account for lazy require().
let devDepRequest = await createDevDependency(
{
specifier: compressor.name,
resolveFrom: compressor.resolveFrom,
},
devDeps,
options,
);
await runDevDepRequest(api, devDepRequest);
}
}
function replaceStream(hashRefToNameHash) {
let boundaryStr = '';
return new Transform({
transform(chunk, encoding, cb) {
let str = boundaryStr + chunk.toString();
let replaced = str.replace(HASH_REF_REGEX, match => {
return hashRefToNameHash.get(match) || match;
});
boundaryStr = replaced.slice(replaced.length - BOUNDARY_LENGTH);
let strUpToBoundary = replaced.slice(
0,
replaced.length - BOUNDARY_LENGTH,
);
cb(null, strUpToBoundary);
},
flush(cb) {
cb(null, boundaryStr);
},
});
}
function cloneStream(readable) {
let res = new Readable();
// $FlowFixMe
res._read = () => {};
readable.on('data', chunk => res.push(chunk));
readable.on('end', () => res.push(null));
readable.on('error', err => res.emit('error', err));
return res;
}