/
UncommittedAsset.js
448 lines (396 loc) Β· 11.7 KB
/
UncommittedAsset.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
// @flow strict-local
import type {
AST,
Blob,
DependencyOptions,
FileCreateInvalidation,
GenerateOutput,
PackageName,
TransformerResult,
} from '@parcel/types';
import type {
Asset,
RequestInvalidation,
Dependency,
ParcelOptions,
InternalFileCreateInvalidation,
} from './types';
import invariant from 'assert';
import {Readable} from 'stream';
import SourceMap from '@parcel/source-map';
import {
blobToStream,
bufferStream,
streamFromPromise,
TapStream,
loadSourceMap,
SOURCEMAP_RE,
} from '@parcel/utils';
import {hashString} from '@parcel/hash';
import {serializeRaw} from './serializer';
import {createDependency, mergeDependencies} from './Dependency';
import {mergeEnvironments} from './Environment';
import {PARCEL_VERSION} from './constants';
import {
createAsset,
createAssetIdFromOptions,
getInvalidationId,
getInvalidationHash,
} from './assetUtils';
import {BundleBehaviorNames} from './types';
import {invalidateOnFileCreateToInternal} from './utils';
import {type ProjectPath, fromProjectPath} from './projectPath';
type UncommittedAssetOptions = {|
value: Asset,
options: ParcelOptions,
content?: ?Blob,
mapBuffer?: ?Buffer,
ast?: ?AST,
isASTDirty?: ?boolean,
idBase?: ?string,
invalidations?: Map<string, RequestInvalidation>,
fileCreateInvalidations?: Array<InternalFileCreateInvalidation>,
|};
export default class UncommittedAsset {
value: Asset;
options: ParcelOptions;
content: ?(Blob | Promise<Buffer>);
mapBuffer: ?Buffer;
sourceContent: ?string;
map: ?SourceMap;
ast: ?AST;
isASTDirty: boolean;
idBase: ?string;
invalidations: Map<string, RequestInvalidation>;
fileCreateInvalidations: Array<InternalFileCreateInvalidation>;
generate: ?() => Promise<GenerateOutput>;
constructor({
value,
options,
content,
mapBuffer,
ast,
isASTDirty,
idBase,
invalidations,
fileCreateInvalidations,
}: UncommittedAssetOptions) {
this.value = value;
this.options = options;
this.content = content;
this.mapBuffer = mapBuffer;
this.ast = ast;
this.isASTDirty = isASTDirty || false;
this.idBase = idBase;
this.invalidations = invalidations || new Map();
this.fileCreateInvalidations = fileCreateInvalidations || [];
}
/*
* Prepares the asset for being serialized to the cache by commiting its
* content and map of the asset to the cache.
*/
async commit(pipelineKey: string): Promise<void> {
// If there is a dirty AST, clear out any old content and map as these
// must be regenerated later and shouldn't be committed.
if (this.ast != null && this.isASTDirty) {
this.content = null;
this.mapBuffer = null;
}
let size = 0;
let contentKey =
this.content == null ? null : this.getCacheKey('content' + pipelineKey);
let mapKey =
this.mapBuffer == null ? null : this.getCacheKey('map' + pipelineKey);
let astKey =
this.ast == null ? null : this.getCacheKey('ast' + pipelineKey);
// Since we can only read from the stream once, compute the content length
// and hash while it's being written to the cache.
await Promise.all([
contentKey != null &&
this.commitContent(contentKey).then(s => (size = s)),
this.mapBuffer != null &&
mapKey != null &&
this.options.cache.setBlob(mapKey, this.mapBuffer),
astKey != null &&
this.options.cache.setBlob(astKey, serializeRaw(this.ast)),
]);
this.value.contentKey = contentKey;
this.value.mapKey = mapKey;
this.value.astKey = astKey;
this.value.outputHash = hashString(
(this.value.hash ?? '') +
pipelineKey +
(await getInvalidationHash(this.getInvalidations(), this.options)),
);
if (this.content != null) {
this.value.stats.size = size;
}
this.value.isLargeBlob = this.content instanceof Readable;
this.value.committed = true;
}
async commitContent(contentKey: string): Promise<number> {
let content = await this.content;
if (content == null) {
return 0;
}
let size = 0;
if (content instanceof Readable) {
await this.options.cache.setStream(
contentKey,
content.pipe(
new TapStream(buf => {
size += buf.length;
}),
),
);
return size;
}
if (typeof content === 'string') {
size = Buffer.byteLength(content);
} else {
size = content.length;
}
await this.options.cache.setBlob(contentKey, content);
return size;
}
async getCode(): Promise<string> {
if (this.ast != null && this.isASTDirty) {
throw new Error(
'Cannot call getCode() on an asset with a dirty AST. For transformers, implement canReuseAST() and check asset.isASTDirty.',
);
}
let content = await this.content;
if (typeof content === 'string' || content instanceof Buffer) {
return content.toString();
} else if (content != null) {
this.content = bufferStream(content);
return (await this.content).toString();
}
invariant(false, 'Internal error: missing content');
}
async getBuffer(): Promise<Buffer> {
let content = await this.content;
if (content == null) {
return Buffer.alloc(0);
} else if (content instanceof Buffer) {
return content;
} else if (typeof content === 'string') {
return Buffer.from(content);
}
this.content = bufferStream(content);
return this.content;
}
getStream(): Readable {
if (this.content instanceof Readable) {
// Remove content if it's a stream, as it should not be reused.
let content = this.content;
this.content = null;
return content;
}
if (this.content instanceof Promise) {
return streamFromPromise(this.content);
}
return blobToStream(this.content ?? Buffer.alloc(0));
}
setCode(code: string) {
this.content = code;
this.clearAST();
}
setBuffer(buffer: Buffer) {
this.content = buffer;
this.clearAST();
}
setStream(stream: Readable) {
this.content = stream;
this.clearAST();
}
async loadExistingSourcemap(): Promise<?SourceMap> {
if (this.map) {
return this.map;
}
let code = await this.getCode();
let map = await loadSourceMap(
fromProjectPath(this.options.projectRoot, this.value.filePath),
code,
{
fs: this.options.inputFS,
projectRoot: this.options.projectRoot,
},
);
if (map) {
this.map = map;
this.mapBuffer = map.toBuffer();
this.setCode(code.replace(SOURCEMAP_RE, ''));
}
return this.map;
}
getMapBuffer(): Promise<?Buffer> {
return Promise.resolve(this.mapBuffer);
}
async getMap(): Promise<?SourceMap> {
if (this.map == null) {
let mapBuffer = this.mapBuffer ?? (await this.getMapBuffer());
if (mapBuffer) {
// Get sourcemap from flatbuffer
this.map = new SourceMap(this.options.projectRoot, mapBuffer);
}
}
return this.map;
}
setMap(map: ?SourceMap): void {
// If we have sourceContent available, it means this asset is source code without
// a previous source map. Ensure that the map set by the transformer has the original
// source content available.
if (map != null && this.sourceContent != null) {
map.setSourceContent(
fromProjectPath(this.options.projectRoot, this.value.filePath),
// $FlowFixMe
this.sourceContent,
);
this.sourceContent = null;
}
this.map = map;
this.mapBuffer = this.map?.toBuffer();
}
getAST(): Promise<?AST> {
return Promise.resolve(this.ast);
}
setAST(ast: AST): void {
this.ast = ast;
this.isASTDirty = true;
this.value.astGenerator = {
type: ast.type,
version: ast.version,
};
}
clearAST() {
this.ast = null;
this.isASTDirty = false;
this.value.astGenerator = null;
}
getCacheKey(key: string): string {
return hashString(
PARCEL_VERSION + key + this.value.id + (this.value.hash || ''),
);
}
addDependency(opts: DependencyOptions): string {
// eslint-disable-next-line no-unused-vars
let {env, symbols, ...rest} = opts;
let dep = createDependency(this.options.projectRoot, {
...rest,
// $FlowFixMe "convert" the $ReadOnlyMaps to the interal mutable one
symbols,
env: mergeEnvironments(this.options.projectRoot, this.value.env, env),
sourceAssetId: this.value.id,
sourcePath: fromProjectPath(
this.options.projectRoot,
this.value.filePath,
),
});
let existing = this.value.dependencies.get(dep.id);
if (existing) {
mergeDependencies(existing, dep);
} else {
this.value.dependencies.set(dep.id, dep);
}
return dep.id;
}
invalidateOnFileChange(filePath: ProjectPath) {
let invalidation: RequestInvalidation = {
type: 'file',
filePath,
};
this.invalidations.set(getInvalidationId(invalidation), invalidation);
}
invalidateOnFileCreate(invalidation: FileCreateInvalidation) {
this.fileCreateInvalidations.push(
invalidateOnFileCreateToInternal(this.options.projectRoot, invalidation),
);
}
invalidateOnEnvChange(key: string) {
let invalidation: RequestInvalidation = {
type: 'env',
key,
};
this.invalidations.set(getInvalidationId(invalidation), invalidation);
}
getInvalidations(): Array<RequestInvalidation> {
return [...this.invalidations.values()];
}
getDependencies(): Array<Dependency> {
return Array.from(this.value.dependencies.values());
}
createChildAsset(
result: TransformerResult,
plugin: PackageName,
configPath: ProjectPath,
configKeyPath?: string,
): UncommittedAsset {
let content = result.content ?? null;
let asset = new UncommittedAsset({
value: createAsset(this.options.projectRoot, {
idBase: this.idBase,
hash: this.value.hash,
filePath: this.value.filePath,
type: result.type,
bundleBehavior:
result.bundleBehavior ??
(this.value.bundleBehavior == null
? null
: BundleBehaviorNames[this.value.bundleBehavior]),
isBundleSplittable:
result.isBundleSplittable ?? this.value.isBundleSplittable,
isSource: this.value.isSource,
env: mergeEnvironments(
this.options.projectRoot,
this.value.env,
result.env,
),
dependencies:
this.value.type === result.type
? new Map(this.value.dependencies)
: new Map(),
meta: {
...this.value.meta,
...result.meta,
},
pipeline:
result.pipeline ??
(this.value.type === result.type ? this.value.pipeline : null),
stats: {
time: 0,
size: this.value.stats.size,
},
// $FlowFixMe
symbols: result.symbols,
sideEffects: result.sideEffects ?? this.value.sideEffects,
uniqueKey: result.uniqueKey,
astGenerator: result.ast
? {type: result.ast.type, version: result.ast.version}
: null,
plugin,
configPath,
configKeyPath,
}),
options: this.options,
content,
ast: result.ast,
isASTDirty: result.ast === this.ast ? this.isASTDirty : true,
mapBuffer: result.map ? result.map.toBuffer() : null,
idBase: this.idBase,
invalidations: this.invalidations,
fileCreateInvalidations: this.fileCreateInvalidations,
});
let dependencies = result.dependencies;
if (dependencies) {
for (let dep of dependencies) {
asset.addDependency(dep);
}
}
return asset;
}
updateId() {
// $FlowFixMe - this is fine
this.value.id = createAssetIdFromOptions(this.value);
}
}