-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
rollup.ts
317 lines (289 loc) · 9.52 KB
/
rollup.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
import { version as rollupVersion } from 'package.json';
import Bundle from '../Bundle';
import Graph from '../Graph';
import { getSortedValidatedPlugins } from '../utils/PluginDriver';
import type { PluginDriver } from '../utils/PluginDriver';
import { ensureArray } from '../utils/ensureArray';
import { errAlreadyClosed, errCannotEmitFromOptionsHook, error } from '../utils/error';
import { promises as fs } from '../utils/fs';
import { catchUnfinishedHookActions } from '../utils/hookActions';
import { normalizeInputOptions } from '../utils/options/normalizeInputOptions';
import { normalizeOutputOptions } from '../utils/options/normalizeOutputOptions';
import type { GenericConfigObject } from '../utils/options/options';
import { basename, dirname, resolve } from '../utils/path';
import { ANONYMOUS_OUTPUT_PLUGIN_PREFIX, ANONYMOUS_PLUGIN_PREFIX } from '../utils/pluginUtils';
import { SOURCEMAPPING_URL } from '../utils/sourceMappingURL';
import { getTimings, initialiseTimers, timeEnd, timeStart } from '../utils/timers';
import type {
NormalizedInputOptions,
NormalizedOutputOptions,
OutputAsset,
OutputChunk,
OutputOptions,
Plugin,
RollupBuild,
RollupOptions,
RollupOutput,
RollupWatcher
} from './types';
export default function rollup(rawInputOptions: GenericConfigObject): Promise<RollupBuild> {
return rollupInternal(rawInputOptions, null);
}
export async function rollupInternal(
rawInputOptions: GenericConfigObject,
watcher: RollupWatcher | null
): Promise<RollupBuild> {
const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(
rawInputOptions,
watcher !== null
);
initialiseTimers(inputOptions);
const graph = new Graph(inputOptions, watcher);
// remove the cache option from the memory after graph creation (cache is not used anymore)
const useCache = rawInputOptions.cache !== false;
delete inputOptions.cache;
delete rawInputOptions.cache;
timeStart('BUILD', 1);
await catchUnfinishedHookActions(graph.pluginDriver, async () => {
try {
await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
await graph.build();
} catch (err: any) {
const watchFiles = Object.keys(graph.watchFiles);
if (watchFiles.length > 0) {
err.watchFiles = watchFiles;
}
await graph.pluginDriver.hookParallel('buildEnd', [err]);
await graph.pluginDriver.hookParallel('closeBundle', []);
throw err;
}
await graph.pluginDriver.hookParallel('buildEnd', []);
});
timeEnd('BUILD', 1);
const result: RollupBuild = {
cache: useCache ? graph.getCache() : undefined,
async close() {
if (result.closed) return;
result.closed = true;
await graph.pluginDriver.hookParallel('closeBundle', []);
},
closed: false,
async generate(rawOutputOptions: OutputOptions) {
if (result.closed) return error(errAlreadyClosed());
return handleGenerateWrite(
false,
inputOptions,
unsetInputOptions,
rawOutputOptions as GenericConfigObject,
graph
);
},
watchFiles: Object.keys(graph.watchFiles),
async write(rawOutputOptions: OutputOptions) {
if (result.closed) return error(errAlreadyClosed());
return handleGenerateWrite(
true,
inputOptions,
unsetInputOptions,
rawOutputOptions as GenericConfigObject,
graph
);
}
};
if (inputOptions.perf) result.getTimings = getTimings;
return result;
}
async function getInputOptions(
rawInputOptions: GenericConfigObject,
watchMode: boolean
): Promise<{ options: NormalizedInputOptions; unsetOptions: Set<string> }> {
if (!rawInputOptions) {
throw new Error('You must supply an options object to rollup');
}
const rawPlugins = getSortedValidatedPlugins(
'options',
ensureArray(rawInputOptions.plugins) as Plugin[]
);
const { options, unsetOptions } = normalizeInputOptions(
await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions))
);
normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
return { options, unsetOptions };
}
function applyOptionHook(watchMode: boolean) {
return async (
inputOptions: Promise<GenericConfigObject>,
plugin: Plugin
): Promise<GenericConfigObject> => {
if (plugin.options) {
const handler = 'handler' in plugin.options ? plugin.options.handler : plugin.options;
return (
((await handler.call(
{ meta: { rollupVersion, watchMode } },
await inputOptions
)) as GenericConfigObject) || inputOptions
);
}
return inputOptions;
};
}
function normalizePlugins(plugins: readonly Plugin[], anonymousPrefix: string): void {
plugins.forEach((plugin, index) => {
if (!plugin.name) {
plugin.name = `${anonymousPrefix}${index + 1}`;
}
});
}
function handleGenerateWrite(
isWrite: boolean,
inputOptions: NormalizedInputOptions,
unsetInputOptions: ReadonlySet<string>,
rawOutputOptions: GenericConfigObject,
graph: Graph
): Promise<RollupOutput> {
const {
options: outputOptions,
outputPluginDriver,
unsetOptions
} = getOutputOptionsAndPluginDriver(
rawOutputOptions,
graph.pluginDriver,
inputOptions,
unsetInputOptions
);
return catchUnfinishedHookActions(outputPluginDriver, async () => {
const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
const generated = await bundle.generate(isWrite);
if (isWrite) {
if (!outputOptions.dir && !outputOptions.file) {
return error({
code: 'MISSING_OPTION',
message: 'You must specify "output.file" or "output.dir" for the build.'
});
}
await Promise.all(
Object.values(generated).map(chunk =>
graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))
)
);
await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
}
return createOutput(generated);
});
}
function getOutputOptionsAndPluginDriver(
rawOutputOptions: GenericConfigObject,
inputPluginDriver: PluginDriver,
inputOptions: NormalizedInputOptions,
unsetInputOptions: ReadonlySet<string>
): {
options: NormalizedOutputOptions;
outputPluginDriver: PluginDriver;
unsetOptions: Set<string>;
} {
if (!rawOutputOptions) {
throw new Error('You must supply an options object');
}
const rawPlugins = ensureArray(rawOutputOptions.plugins) as Plugin[];
normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
return {
...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
outputPluginDriver
};
}
function getOutputOptions(
inputOptions: NormalizedInputOptions,
unsetInputOptions: ReadonlySet<string>,
rawOutputOptions: GenericConfigObject,
outputPluginDriver: PluginDriver
): { options: NormalizedOutputOptions; unsetOptions: Set<string> } {
return normalizeOutputOptions(
outputPluginDriver.hookReduceArg0Sync(
'outputOptions',
[rawOutputOptions.output || rawOutputOptions] as [OutputOptions],
(outputOptions, result) => result || outputOptions,
pluginContext => {
const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
return {
...pluginContext,
emitFile: emitError,
setAssetSource: emitError
};
}
),
inputOptions,
unsetInputOptions
);
}
function createOutput(
outputBundle: Record<string, OutputChunk | OutputAsset | Record<string, never>>
): RollupOutput {
return {
output: (
Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0) as (
| OutputChunk
| OutputAsset
)[]
).sort((outputFileA, outputFileB) => {
const fileTypeA = getSortingFileType(outputFileA);
const fileTypeB = getSortingFileType(outputFileB);
if (fileTypeA === fileTypeB) return 0;
return fileTypeA < fileTypeB ? -1 : 1;
}) as [OutputChunk, ...(OutputChunk | OutputAsset)[]]
};
}
enum SortingFileType {
ENTRY_CHUNK = 0,
SECONDARY_CHUNK = 1,
ASSET = 2
}
function getSortingFileType(file: OutputAsset | OutputChunk): SortingFileType {
if (file.type === 'asset') {
return SortingFileType.ASSET;
}
if (file.isEntry) {
return SortingFileType.ENTRY_CHUNK;
}
return SortingFileType.SECONDARY_CHUNK;
}
async function writeOutputFile(
outputFile: OutputAsset | OutputChunk,
outputOptions: NormalizedOutputOptions
): Promise<unknown> {
const fileName = resolve(outputOptions.dir || dirname(outputOptions.file!), outputFile.fileName);
// 'recursive: true' does not throw if the folder structure, or parts of it, already exist
await fs.mkdir(dirname(fileName), { recursive: true });
let writeSourceMapPromise: Promise<void> | undefined;
let source: string | Uint8Array;
if (outputFile.type === 'asset') {
source = outputFile.source;
} else {
source = outputFile.code;
if (outputOptions.sourcemap && outputFile.map) {
let url: string;
if (outputOptions.sourcemap === 'inline') {
url = outputFile.map.toUrl();
} else {
const { sourcemapBaseUrl } = outputOptions;
const sourcemapFileName = `${basename(outputFile.fileName)}.map`;
url = sourcemapBaseUrl
? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
: sourcemapFileName;
writeSourceMapPromise = fs.writeFile(`${fileName}.map`, outputFile.map.toString());
}
if (outputOptions.sourcemap !== 'hidden') {
source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
}
}
}
return Promise.all([fs.writeFile(fileName, source), writeSourceMapPromise]);
}
/**
* Auxiliary function for defining rollup configuration
* Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
* @param options
*/
export function defineConfig<T extends RollupOptions | RollupOptions[]>(options: T): T {
return options;
}