forked from rollup/rollup
/
FileEmitter.ts
357 lines (326 loc) · 10.7 KB
/
FileEmitter.ts
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
import type Chunk from '../Chunk';
import type Graph from '../Graph';
import type Module from '../Module';
import type {
EmittedChunk,
NormalizedInputOptions,
NormalizedOutputOptions,
WarningHandler
} from '../rollup/types';
import { BuildPhase } from './buildPhase';
import { createHash } from './crypto';
import {
error,
errorAssetNotFinalisedForFileName,
errorAssetReferenceIdNotFoundForSetSource,
errorAssetSourceAlreadySet,
errorChunkNotGeneratedForFileName,
errorFailedValidation,
errorFileNameConflict,
errorFileReferenceIdNotFoundForFilename,
errorInvalidRollupPhaseForChunkEmission,
errorNoAssetSourceSet
} from './error';
import { defaultHashSize } from './hashPlaceholders';
import type { OutputBundleWithPlaceholders } from './outputBundle';
import { FILE_PLACEHOLDER, lowercaseBundleKeys } from './outputBundle';
import { extname } from './path';
import { isPathFragment } from './relativeId';
import { makeUnique, renderNamePattern } from './renderNamePattern';
function getSourceHash(source: string | Uint8Array, size?: number): string {
return createHash()
.update(source)
.digest('hex')
.slice(0, Math.max(0, size || defaultHashSize));
}
function pregenerateAssetFileName(
name: string | undefined,
source: string | Uint8Array,
outputOptions: NormalizedOutputOptions
): { fileName: string; sourceHash: string } {
let sourceHash: string | undefined;
const emittedName = outputOptions.sanitizeFileName(name || 'asset');
const fileName = renderNamePattern(
typeof outputOptions.assetFileNames === 'function'
? outputOptions.assetFileNames({ name, source, type: 'asset' })
: outputOptions.assetFileNames,
'output.assetFileNames',
{
ext: () => extname(emittedName).slice(1),
extname: () => extname(emittedName),
hash: size => (sourceHash = getSourceHash(source, size)),
name: () =>
emittedName.slice(0, Math.max(0, emittedName.length - extname(emittedName).length))
}
);
sourceHash ??= getSourceHash(source);
return { fileName, sourceHash };
}
function reserveFileNameInBundle(
fileName: string,
{ bundle }: FileEmitterOutput,
warn: WarningHandler
) {
if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
warn(errorFileNameConflict(fileName));
} else {
bundle[fileName] = FILE_PLACEHOLDER;
}
}
interface ConsumedChunk {
fileName: string | undefined;
module: null | Module;
name: string;
type: 'chunk';
}
interface ConsumedAsset {
fileName: string | undefined;
name: string | undefined;
source: string | Uint8Array | undefined;
type: 'asset';
}
interface EmittedFile {
[key: string]: unknown;
fileName?: string;
name?: string;
type: 'chunk' | 'asset';
}
type ConsumedFile = ConsumedChunk | ConsumedAsset;
function hasValidType(
emittedFile: unknown
): emittedFile is { [key: string]: unknown; type: 'asset' | 'chunk' } {
return Boolean(
emittedFile &&
((emittedFile as { [key: string]: unknown }).type === 'asset' ||
(emittedFile as { [key: string]: unknown }).type === 'chunk')
);
}
function hasValidName(emittedFile: {
[key: string]: unknown;
type: 'asset' | 'chunk';
}): emittedFile is EmittedFile {
const validatedName = emittedFile.fileName || emittedFile.name;
return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
}
function getValidSource(
source: unknown,
emittedFile: { fileName?: string; name?: string },
fileReferenceId: string | null
): string | Uint8Array {
if (!(typeof source === 'string' || source instanceof Uint8Array)) {
const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
return error(
errorFailedValidation(
`Could not set source for ${
typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'
}, asset source needs to be a string, Uint8Array or Buffer.`
)
);
}
return source;
}
function getAssetFileName(file: ConsumedAsset, referenceId: string): string {
if (typeof file.fileName !== 'string') {
return error(errorAssetNotFinalisedForFileName(file.name || referenceId));
}
return file.fileName;
}
function getChunkFileName(
file: ConsumedChunk,
facadeChunkByModule: ReadonlyMap<Module, Chunk> | null
): string {
if (file.fileName) {
return file.fileName;
}
if (facadeChunkByModule) {
const chunk = facadeChunkByModule.get(file.module!)!;
return chunk.id || chunk.getFileName();
}
return error(errorChunkNotGeneratedForFileName(file.fileName || file.name));
}
interface FileEmitterOutput {
bundle: OutputBundleWithPlaceholders;
fileNamesBySource: Map<string, string>;
outputOptions: NormalizedOutputOptions;
}
export class FileEmitter {
private facadeChunkByModule: ReadonlyMap<Module, Chunk> | null = null;
private readonly filesByReferenceId: Map<string, ConsumedFile>;
private nextIdBase = 1;
private output: FileEmitterOutput | null = null;
constructor(
private readonly graph: Graph,
private readonly options: NormalizedInputOptions,
baseFileEmitter?: FileEmitter
) {
this.filesByReferenceId = baseFileEmitter
? new Map(baseFileEmitter.filesByReferenceId)
: new Map();
}
public emitFile = (emittedFile: unknown): string => {
if (!hasValidType(emittedFile)) {
return error(
errorFailedValidation(
`Emitted files must be of type "asset" or "chunk", received "${
emittedFile && (emittedFile as any).type
}".`
)
);
}
if (!hasValidName(emittedFile)) {
return error(
errorFailedValidation(
`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "${
emittedFile.fileName || emittedFile.name
}".`
)
);
}
if (emittedFile.type === 'chunk') {
return this.emitChunk(emittedFile);
}
return this.emitAsset(emittedFile);
};
public finaliseAssets = (): void => {
for (const [referenceId, emittedFile] of this.filesByReferenceId) {
if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
return error(errorNoAssetSourceSet(emittedFile.name || referenceId));
}
};
public getFileName = (fileReferenceId: string): string => {
const emittedFile = this.filesByReferenceId.get(fileReferenceId);
if (!emittedFile) return error(errorFileReferenceIdNotFoundForFilename(fileReferenceId));
if (emittedFile.type === 'chunk') {
return getChunkFileName(emittedFile, this.facadeChunkByModule);
}
return getAssetFileName(emittedFile, fileReferenceId);
};
public setAssetSource = (referenceId: string, requestedSource: unknown): void => {
const consumedFile = this.filesByReferenceId.get(referenceId);
if (!consumedFile) return error(errorAssetReferenceIdNotFoundForSetSource(referenceId));
if (consumedFile.type !== 'asset') {
return error(
errorFailedValidation(
`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`
)
);
}
if (consumedFile.source !== undefined) {
return error(errorAssetSourceAlreadySet(consumedFile.name || referenceId));
}
const source = getValidSource(requestedSource, consumedFile, referenceId);
if (this.output) {
this.finalizeAsset(consumedFile, source, referenceId, this.output);
} else {
consumedFile.source = source;
}
};
public setChunkInformation = (facadeChunkByModule: ReadonlyMap<Module, Chunk>): void => {
this.facadeChunkByModule = facadeChunkByModule;
};
public setOutputBundle = (
bundle: OutputBundleWithPlaceholders,
outputOptions: NormalizedOutputOptions
): void => {
const fileNamesBySource = new Map();
const output = (this.output = { bundle, fileNamesBySource, outputOptions });
for (const emittedFile of this.filesByReferenceId.values()) {
if (emittedFile.fileName) {
reserveFileNameInBundle(emittedFile.fileName, output, this.options.onwarn);
}
}
for (const [referenceId, consumedFile] of this.filesByReferenceId) {
if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
this.finalizeAsset(consumedFile, consumedFile.source, referenceId, output);
}
}
};
private assignReferenceId(file: ConsumedFile, idBase: string): string {
let referenceId: string | undefined;
do {
referenceId = createHash()
.update(referenceId || idBase)
.digest('hex')
.slice(0, 8);
} while (this.filesByReferenceId.has(referenceId));
this.filesByReferenceId.set(referenceId, file);
return referenceId;
}
private emitAsset(emittedAsset: EmittedFile): string {
const source =
typeof emittedAsset.source !== 'undefined'
? getValidSource(emittedAsset.source, emittedAsset, null)
: undefined;
const consumedAsset: ConsumedAsset = {
fileName: emittedAsset.fileName,
name: emittedAsset.name,
source,
type: 'asset'
};
const referenceId = this.assignReferenceId(
consumedAsset,
emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++)
);
if (this.output) {
if (emittedAsset.fileName) {
reserveFileNameInBundle(emittedAsset.fileName, this.output, this.options.onwarn);
}
if (source !== undefined) {
this.finalizeAsset(consumedAsset, source, referenceId, this.output);
}
}
return referenceId;
}
private emitChunk(emittedChunk: EmittedFile): string {
if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
return error(errorInvalidRollupPhaseForChunkEmission());
}
if (typeof emittedChunk.id !== 'string') {
return error(
errorFailedValidation(
`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`
)
);
}
const consumedChunk: ConsumedChunk = {
fileName: emittedChunk.fileName,
module: null,
name: emittedChunk.name || emittedChunk.id,
type: 'chunk'
};
this.graph.moduleLoader
.emitChunk(emittedChunk as unknown as EmittedChunk)
.then(module => (consumedChunk.module = module))
.catch(() => {
// Avoid unhandled Promise rejection as the error will be thrown later
// once module loading has finished
});
return this.assignReferenceId(consumedChunk, emittedChunk.id);
}
private finalizeAsset(
consumedFile: ConsumedFile,
source: string | Uint8Array,
referenceId: string,
{ bundle, fileNamesBySource, outputOptions }: FileEmitterOutput
): void {
let fileName = consumedFile.fileName;
// Deduplicate assets if an explicit fileName is not provided
if (!fileName) {
const pregenerated = pregenerateAssetFileName(consumedFile.name, source, outputOptions);
fileName = fileNamesBySource.get(pregenerated.sourceHash);
if (!fileName) {
fileName = makeUnique(pregenerated.fileName, bundle);
fileNamesBySource.set(pregenerated.sourceHash, fileName);
}
}
// We must not modify the original assets to avoid interaction between outputs
const assetWithFileName = { ...consumedFile, fileName, source };
this.filesByReferenceId.set(referenceId, assetWithFileName);
bundle[fileName] = {
fileName,
name: consumedFile.name,
source,
type: 'asset'
};
}
}