UNPKG

24.5 kBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v2.62.1
4 Sun, 13 Feb 2022 23:06:06 GMT - commit 159f1d7f9506bdd1266d9324efd48b2ec30f5f22
5
6
7 https://github.com/rollup/rollup
8
9 Released under the MIT License.
10*/
11'use strict';
12
13const fs = require('fs');
14const path = require('path');
15const url = require('url');
16const process$1 = require('process');
17const tty = require('tty');
18const rollup = require('./rollup.js');
19const mergeOptions = require('./mergeOptions.js');
20
21function _interopNamespaceDefault(e) {
22 const n = Object.create(null);
23 if (e) {
24 for (const k in e) {
25 n[k] = e[k];
26 }
27 }
28 n.default = e;
29 return n;
30}
31
32const fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
33const path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
34const tty__namespace = /*#__PURE__*/_interopNamespaceDefault(tty);
35
36const env = process.env || {};
37const argv = process.argv || [];
38
39const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
40const isForced = "FORCE_COLOR" in env || argv.includes("--color");
41const isWindows = process.platform === "win32";
42
43const isCompatibleTerminal =
44 tty__namespace && tty__namespace.isatty && tty__namespace.isatty(1) && env.TERM && env.TERM !== "dumb";
45
46const isCI =
47 "CI" in env &&
48 ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
49
50const isColorSupported =
51 !isDisabled && (isForced || isWindows || isCompatibleTerminal || isCI);
52
53const replaceClose = (
54 index,
55 string,
56 close,
57 replace,
58 head = string.substring(0, index) + replace,
59 tail = string.substring(index + close.length),
60 next = tail.indexOf(close)
61) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
62
63const clearBleed = (index, string, open, close, replace) =>
64 index < 0
65 ? open + string + close
66 : open + replaceClose(index, string, close, replace) + close;
67
68const filterEmpty =
69 (open, close, replace = open, at = open.length + 1) =>
70 (string) =>
71 string || !(string === "" || string === undefined)
72 ? clearBleed(
73 ("" + string).indexOf(close, at),
74 string,
75 open,
76 close,
77 replace
78 )
79 : "";
80
81const init = (open, close, replace) =>
82 filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace);
83
84const colors = {
85 reset: init(0, 0),
86 bold: init(1, 22, "\x1b[22m\x1b[1m"),
87 dim: init(2, 22, "\x1b[22m\x1b[2m"),
88 italic: init(3, 23),
89 underline: init(4, 24),
90 inverse: init(7, 27),
91 hidden: init(8, 28),
92 strikethrough: init(9, 29),
93 black: init(30, 39),
94 red: init(31, 39),
95 green: init(32, 39),
96 yellow: init(33, 39),
97 blue: init(34, 39),
98 magenta: init(35, 39),
99 cyan: init(36, 39),
100 white: init(37, 39),
101 gray: init(90, 39),
102 bgBlack: init(40, 49),
103 bgRed: init(41, 49),
104 bgGreen: init(42, 49),
105 bgYellow: init(43, 49),
106 bgBlue: init(44, 49),
107 bgMagenta: init(45, 49),
108 bgCyan: init(46, 49),
109 bgWhite: init(47, 49),
110 blackBright: init(90, 39),
111 redBright: init(91, 39),
112 greenBright: init(92, 39),
113 yellowBright: init(93, 39),
114 blueBright: init(94, 39),
115 magentaBright: init(95, 39),
116 cyanBright: init(96, 39),
117 whiteBright: init(97, 39),
118 bgBlackBright: init(100, 49),
119 bgRedBright: init(101, 49),
120 bgGreenBright: init(102, 49),
121 bgYellowBright: init(103, 49),
122 bgBlueBright: init(104, 49),
123 bgMagentaBright: init(105, 49),
124 bgCyanBright: init(106, 49),
125 bgWhiteBright: init(107, 49),
126};
127
128const none = (any) => any;
129
130const createColors = ({ useColor = isColorSupported } = {}) =>
131 useColor
132 ? colors
133 : Object.keys(colors).reduce(
134 (colors, key) => ({ ...colors, [key]: none }),
135 {}
136 );
137
138createColors();
139
140// @see https://no-color.org
141// @see https://www.npmjs.com/package/chalk
142const { bold, cyan, dim, gray, green, red, underline, yellow } = createColors({
143 useColor: process$1.env.FORCE_COLOR !== '0' && !process$1.env.NO_COLOR
144});
145
146// log to stderr to keep `rollup main.js > bundle.js` from breaking
147const stderr = console.error.bind(console);
148function handleError(err, recover = false) {
149 let description = err.message || err;
150 if (err.name)
151 description = `${err.name}: ${description}`;
152 const message = (err.plugin ? `(plugin ${err.plugin}) ${description}` : description) || err;
153 stderr(bold(red(`[!] ${bold(message.toString())}`)));
154 if (err.url) {
155 stderr(cyan(err.url));
156 }
157 if (err.loc) {
158 stderr(`${rollup.relativeId((err.loc.file || err.id))} (${err.loc.line}:${err.loc.column})`);
159 }
160 else if (err.id) {
161 stderr(rollup.relativeId(err.id));
162 }
163 if (err.frame) {
164 stderr(dim(err.frame));
165 }
166 if (err.stack) {
167 stderr(dim(err.stack));
168 }
169 stderr('');
170 if (!recover)
171 process.exit(1);
172}
173
174function batchWarnings() {
175 let count = 0;
176 let deferredWarnings = new Map();
177 let warningOccurred = false;
178 return {
179 add: (warning) => {
180 count += 1;
181 warningOccurred = true;
182 if (warning.code in deferredHandlers) {
183 rollup.getOrCreate(deferredWarnings, warning.code, () => []).push(warning);
184 }
185 else if (warning.code in immediateHandlers) {
186 immediateHandlers[warning.code](warning);
187 }
188 else {
189 title(warning.message);
190 if (warning.url)
191 info(warning.url);
192 const id = (warning.loc && warning.loc.file) || warning.id;
193 if (id) {
194 const loc = warning.loc
195 ? `${rollup.relativeId(id)} (${warning.loc.line}:${warning.loc.column})`
196 : rollup.relativeId(id);
197 stderr(bold(rollup.relativeId(loc)));
198 }
199 if (warning.frame)
200 info(warning.frame);
201 }
202 },
203 get count() {
204 return count;
205 },
206 flush: () => {
207 if (count === 0)
208 return;
209 const codes = Array.from(deferredWarnings.keys()).sort((a, b) => deferredWarnings.get(b).length - deferredWarnings.get(a).length);
210 for (const code of codes) {
211 deferredHandlers[code](deferredWarnings.get(code));
212 }
213 deferredWarnings = new Map();
214 count = 0;
215 },
216 get warningOccurred() {
217 return warningOccurred;
218 }
219 };
220}
221const immediateHandlers = {
222 MISSING_NODE_BUILTINS: warning => {
223 title(`Missing shims for Node.js built-ins`);
224 stderr(`Creating a browser bundle that depends on ${rollup.printQuotedStringList(warning.modules)}. You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node`);
225 },
226 UNKNOWN_OPTION: warning => {
227 title(`You have passed an unrecognized option`);
228 stderr(warning.message);
229 }
230};
231const deferredHandlers = {
232 CIRCULAR_DEPENDENCY(warnings) {
233 title(`Circular dependenc${warnings.length > 1 ? 'ies' : 'y'}`);
234 const displayed = warnings.length > 5 ? warnings.slice(0, 3) : warnings;
235 for (const warning of displayed) {
236 stderr(warning.cycle.join(' -> '));
237 }
238 if (warnings.length > displayed.length) {
239 stderr(`...and ${warnings.length - displayed.length} more`);
240 }
241 },
242 EMPTY_BUNDLE(warnings) {
243 title(`Generated${warnings.length === 1 ? ' an' : ''} empty ${warnings.length > 1 ? 'chunks' : 'chunk'}`);
244 stderr(warnings.map(warning => warning.chunkName).join(', '));
245 },
246 EVAL(warnings) {
247 title('Use of eval is strongly discouraged');
248 info('https://rollupjs.org/guide/en/#avoiding-eval');
249 showTruncatedWarnings(warnings);
250 },
251 MISSING_EXPORT(warnings) {
252 title('Missing exports');
253 info('https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module');
254 for (const warning of warnings) {
255 stderr(bold(warning.importer));
256 stderr(`${warning.missing} is not exported by ${warning.exporter}`);
257 stderr(gray(warning.frame));
258 }
259 },
260 MISSING_GLOBAL_NAME(warnings) {
261 title(`Missing global variable ${warnings.length > 1 ? 'names' : 'name'}`);
262 stderr(`Use output.globals to specify browser global variable names corresponding to external modules`);
263 for (const warning of warnings) {
264 stderr(`${bold(warning.source)} (guessing '${warning.guess}')`);
265 }
266 },
267 MIXED_EXPORTS: warnings => {
268 title('Mixing named and default exports');
269 info(`https://rollupjs.org/guide/en/#outputexports`);
270 stderr(bold('The following entry modules are using named and default exports together:'));
271 const displayedWarnings = warnings.length > 5 ? warnings.slice(0, 3) : warnings;
272 for (const warning of displayedWarnings) {
273 stderr(rollup.relativeId(warning.id));
274 }
275 if (displayedWarnings.length < warnings.length) {
276 stderr(`...and ${warnings.length - displayedWarnings.length} other entry modules`);
277 }
278 stderr(`\nConsumers of your bundle will have to use chunk['default'] to access their default export, which may not be what you want. Use \`output.exports: 'named'\` to disable this warning`);
279 },
280 NAMESPACE_CONFLICT(warnings) {
281 title(`Conflicting re-exports`);
282 for (const warning of warnings) {
283 stderr(`"${bold(rollup.relativeId(warning.reexporter))}" re-exports "${warning.name}" from both "${rollup.relativeId(warning.sources[0])}" and "${rollup.relativeId(warning.sources[1])}" (will be ignored)`);
284 }
285 },
286 NON_EXISTENT_EXPORT(warnings) {
287 title(`Import of non-existent ${warnings.length > 1 ? 'exports' : 'export'}`);
288 showTruncatedWarnings(warnings);
289 },
290 PLUGIN_WARNING(warnings) {
291 var _a;
292 const nestedByPlugin = nest(warnings, 'plugin');
293 for (const { key: plugin, items } of nestedByPlugin) {
294 const nestedByMessage = nest(items, 'message');
295 let lastUrl = '';
296 for (const { key: message, items } of nestedByMessage) {
297 title(`Plugin ${plugin}: ${message}`);
298 for (const warning of items) {
299 if (warning.url && warning.url !== lastUrl)
300 info((lastUrl = warning.url));
301 const id = warning.id || ((_a = warning.loc) === null || _a === void 0 ? void 0 : _a.file);
302 if (id) {
303 let loc = rollup.relativeId(id);
304 if (warning.loc) {
305 loc += `: (${warning.loc.line}:${warning.loc.column})`;
306 }
307 stderr(bold(loc));
308 }
309 if (warning.frame)
310 info(warning.frame);
311 }
312 }
313 }
314 },
315 SOURCEMAP_BROKEN(warnings) {
316 title(`Broken sourcemap`);
317 info('https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect');
318 const plugins = [
319 ...new Set(warnings.map(warning => warning.plugin).filter(Boolean))
320 ];
321 stderr(`Plugins that transform code (such as ${rollup.printQuotedStringList(plugins)}) should generate accompanying sourcemaps`);
322 },
323 THIS_IS_UNDEFINED(warnings) {
324 title('`this` has been rewritten to `undefined`');
325 info('https://rollupjs.org/guide/en/#error-this-is-undefined');
326 showTruncatedWarnings(warnings);
327 },
328 UNRESOLVED_IMPORT(warnings) {
329 title('Unresolved dependencies');
330 info('https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency');
331 const dependencies = new Map();
332 for (const warning of warnings) {
333 rollup.getOrCreate(dependencies, warning.source, () => []).push(warning.importer);
334 }
335 for (const dependency of dependencies.keys()) {
336 const importers = dependencies.get(dependency);
337 stderr(`${bold(dependency)} (imported by ${importers.join(', ')})`);
338 }
339 },
340 UNUSED_EXTERNAL_IMPORT(warnings) {
341 title('Unused external imports');
342 for (const warning of warnings) {
343 stderr(warning.names +
344 ' imported from external module "' +
345 warning.source +
346 '" but never used in ' +
347 rollup.printQuotedStringList(warning.sources.map(id => rollup.relativeId(id))));
348 }
349 }
350};
351function title(str) {
352 stderr(bold(yellow(`(!) ${str}`)));
353}
354function info(url) {
355 stderr(gray(url));
356}
357function nest(array, prop) {
358 const nested = [];
359 const lookup = new Map();
360 for (const item of array) {
361 const key = item[prop];
362 rollup.getOrCreate(lookup, key, () => {
363 const items = {
364 items: [],
365 key
366 };
367 nested.push(items);
368 return items;
369 }).items.push(item);
370 }
371 return nested;
372}
373function showTruncatedWarnings(warnings) {
374 const nestedByModule = nest(warnings, 'id');
375 const displayedByModule = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;
376 for (const { key: id, items } of displayedByModule) {
377 stderr(bold(rollup.relativeId(id)));
378 stderr(gray(items[0].frame));
379 if (items.length > 1) {
380 stderr(`...and ${items.length - 1} other ${items.length > 2 ? 'occurrences' : 'occurrence'}`);
381 }
382 }
383 if (nestedByModule.length > displayedByModule.length) {
384 stderr(`\n...and ${nestedByModule.length - displayedByModule.length} other files`);
385 }
386}
387
388const stdinName = '-';
389let stdinResult = null;
390function stdinPlugin(arg) {
391 const suffix = typeof arg == 'string' && arg.length ? '.' + arg : '';
392 return {
393 load(id) {
394 if (id === stdinName || id.startsWith(stdinName + '.')) {
395 return stdinResult || (stdinResult = readStdin());
396 }
397 },
398 name: 'stdin',
399 resolveId(id) {
400 if (id === stdinName) {
401 return id + suffix;
402 }
403 }
404 };
405}
406function readStdin() {
407 return new Promise((resolve, reject) => {
408 const chunks = [];
409 process.stdin.setEncoding('utf8');
410 process.stdin
411 .on('data', chunk => chunks.push(chunk))
412 .on('end', () => {
413 const result = chunks.join('');
414 resolve(result);
415 })
416 .on('error', err => {
417 reject(err);
418 });
419 });
420}
421
422function waitForInputPlugin() {
423 return {
424 async buildStart(options) {
425 const inputSpecifiers = Array.isArray(options.input)
426 ? options.input
427 : Object.keys(options.input);
428 let lastAwaitedSpecifier = null;
429 checkSpecifiers: while (true) {
430 for (const specifier of inputSpecifiers) {
431 if ((await this.resolve(specifier)) === null) {
432 if (lastAwaitedSpecifier !== specifier) {
433 stderr(`waiting for input ${bold(specifier)}...`);
434 lastAwaitedSpecifier = specifier;
435 }
436 await new Promise(resolve => setTimeout(resolve, 500));
437 continue checkSpecifiers;
438 }
439 }
440 break;
441 }
442 },
443 name: 'wait-for-input'
444 };
445}
446
447async function addCommandPluginsToInputOptions(inputOptions, command) {
448 if (command.stdin !== false) {
449 inputOptions.plugins.push(stdinPlugin(command.stdin));
450 }
451 if (command.waitForBundleInput === true) {
452 inputOptions.plugins.push(waitForInputPlugin());
453 }
454 await addPluginsFromCommandOption(command.plugin, inputOptions);
455}
456async function addPluginsFromCommandOption(commandPlugin, inputOptions) {
457 if (commandPlugin) {
458 const plugins = Array.isArray(commandPlugin) ? commandPlugin : [commandPlugin];
459 for (const plugin of plugins) {
460 if (/[={}]/.test(plugin)) {
461 // -p plugin=value
462 // -p "{transform(c,i){...}}"
463 await loadAndRegisterPlugin(inputOptions, plugin);
464 }
465 else {
466 // split out plugins joined by commas
467 // -p node-resolve,commonjs,buble
468 for (const p of plugin.split(',')) {
469 await loadAndRegisterPlugin(inputOptions, p);
470 }
471 }
472 }
473 }
474}
475async function loadAndRegisterPlugin(inputOptions, pluginText) {
476 let plugin = null;
477 let pluginArg = undefined;
478 if (pluginText[0] === '{') {
479 // -p "{transform(c,i){...}}"
480 plugin = new Function('return ' + pluginText);
481 }
482 else {
483 const match = pluginText.match(/^([@./\\\w|^{}-]+)(=(.*))?$/);
484 if (match) {
485 // -p plugin
486 // -p plugin=arg
487 pluginText = match[1];
488 pluginArg = new Function('return ' + match[3])();
489 }
490 else {
491 throw new Error(`Invalid --plugin argument format: ${JSON.stringify(pluginText)}`);
492 }
493 if (!/^\.|^rollup-plugin-|[@/\\]/.test(pluginText)) {
494 // Try using plugin prefix variations first if applicable.
495 // Prefix order is significant - left has higher precedence.
496 for (const prefix of ['@rollup/plugin-', 'rollup-plugin-']) {
497 try {
498 plugin = await requireOrImport(prefix + pluginText);
499 break;
500 }
501 catch (_a) {
502 // if this does not work, we try requiring the actual name below
503 }
504 }
505 }
506 if (!plugin) {
507 try {
508 if (pluginText[0] == '.')
509 pluginText = path__namespace.resolve(pluginText);
510 plugin = await requireOrImport(pluginText);
511 }
512 catch (err) {
513 throw new Error(`Cannot load plugin "${pluginText}": ${err.message}.`);
514 }
515 }
516 }
517 // some plugins do not use `module.exports` for their entry point,
518 // in which case we try the named default export and the plugin name
519 if (typeof plugin === 'object') {
520 plugin = plugin.default || plugin[getCamelizedPluginBaseName(pluginText)];
521 }
522 if (!plugin) {
523 throw new Error(`Cannot find entry for plugin "${pluginText}". The plugin needs to export a function either as "default" or "${getCamelizedPluginBaseName(pluginText)}" for Rollup to recognize it.`);
524 }
525 inputOptions.plugins.push(typeof plugin === 'function' ? plugin.call(plugin, pluginArg) : plugin);
526}
527function getCamelizedPluginBaseName(pluginText) {
528 var _a;
529 return (((_a = pluginText.match(/(@rollup\/plugin-|rollup-plugin-)(.+)$/)) === null || _a === void 0 ? void 0 : _a[2]) || pluginText)
530 .split(/[\\/]/)
531 .slice(-1)[0]
532 .split('.')[0]
533 .split('-')
534 .map((part, index) => (index === 0 || !part ? part : part[0].toUpperCase() + part.slice(1)))
535 .join('');
536}
537async function requireOrImport(pluginPath) {
538 try {
539 return require(pluginPath);
540 }
541 catch (_a) {
542 return import(pluginPath);
543 }
544}
545
546function supportsNativeESM() {
547 return Number(/^v(\d+)/.exec(process.version)[1]) >= 13;
548}
549async function loadAndParseConfigFile(fileName, commandOptions = {}) {
550 const configs = await loadConfigFile(fileName, commandOptions);
551 const warnings = batchWarnings();
552 try {
553 const normalizedConfigs = [];
554 for (const config of configs) {
555 const options = mergeOptions.mergeOptions(config, commandOptions, warnings.add);
556 await addCommandPluginsToInputOptions(options, commandOptions);
557 normalizedConfigs.push(options);
558 }
559 return { options: normalizedConfigs, warnings };
560 }
561 catch (err) {
562 warnings.flush();
563 throw err;
564 }
565}
566async function loadConfigFile(fileName, commandOptions) {
567 const extension = path__namespace.extname(fileName);
568 const configFileExport = commandOptions.configPlugin ||
569 !(extension === '.cjs' || (extension === '.mjs' && supportsNativeESM()))
570 ? await getDefaultFromTranspiledConfigFile(fileName, commandOptions)
571 : extension === '.cjs'
572 ? getDefaultFromCjs(require(fileName))
573 : (await import(url.pathToFileURL(fileName).href)).default;
574 return getConfigList(configFileExport, commandOptions);
575}
576function getDefaultFromCjs(namespace) {
577 return namespace.__esModule ? namespace.default : namespace;
578}
579async function getDefaultFromTranspiledConfigFile(fileName, commandOptions) {
580 const warnings = batchWarnings();
581 const inputOptions = {
582 external: (id) => (id[0] !== '.' && !path__namespace.isAbsolute(id)) || id.slice(-5, id.length) === '.json',
583 input: fileName,
584 onwarn: warnings.add,
585 plugins: [],
586 treeshake: false
587 };
588 await addPluginsFromCommandOption(commandOptions.configPlugin, inputOptions);
589 const bundle = await rollup.rollup(inputOptions);
590 if (!commandOptions.silent && warnings.count > 0) {
591 stderr(bold(`loaded ${rollup.relativeId(fileName)} with warnings`));
592 warnings.flush();
593 }
594 const { output: [{ code }] } = await bundle.generate({
595 exports: 'named',
596 format: 'cjs',
597 plugins: [
598 {
599 name: 'transpile-import-meta',
600 resolveImportMeta(property, { moduleId }) {
601 if (property === 'url') {
602 return `'${url.pathToFileURL(moduleId).href}'`;
603 }
604 if (property == null) {
605 return `{url:'${url.pathToFileURL(moduleId).href}'}`;
606 }
607 }
608 }
609 ]
610 });
611 return loadConfigFromBundledFile(fileName, code);
612}
613async function loadConfigFromBundledFile(fileName, bundledCode) {
614 const resolvedFileName = fs__namespace.realpathSync(fileName);
615 const extension = path__namespace.extname(resolvedFileName);
616 const defaultLoader = require.extensions[extension];
617 require.extensions[extension] = (module, requiredFileName) => {
618 if (requiredFileName === resolvedFileName) {
619 module._compile(bundledCode, requiredFileName);
620 }
621 else {
622 defaultLoader(module, requiredFileName);
623 }
624 };
625 delete require.cache[resolvedFileName];
626 try {
627 const config = getDefaultFromCjs(require(fileName));
628 require.extensions[extension] = defaultLoader;
629 return config;
630 }
631 catch (err) {
632 if (err.code === 'ERR_REQUIRE_ESM') {
633 return rollup.error({
634 code: 'TRANSPILED_ESM_CONFIG',
635 message: `While loading the Rollup configuration from "${rollup.relativeId(fileName)}", Node tried to require an ES module from a CommonJS file, which is not supported. A common cause is if there is a package.json file with "type": "module" in the same folder. You can try to fix this by changing the extension of your configuration file to ".cjs" or ".mjs" depending on the content, which will prevent Rollup from trying to preprocess the file but rather hand it to Node directly.`,
636 url: 'https://rollupjs.org/guide/en/#using-untranspiled-config-files'
637 });
638 }
639 throw err;
640 }
641}
642async function getConfigList(configFileExport, commandOptions) {
643 const config = await (typeof configFileExport === 'function'
644 ? configFileExport(commandOptions)
645 : configFileExport);
646 if (Object.keys(config).length === 0) {
647 return rollup.error({
648 code: 'MISSING_CONFIG',
649 message: 'Config file must export an options object, or an array of options objects',
650 url: 'https://rollupjs.org/guide/en/#configuration-files'
651 });
652 }
653 return Array.isArray(config) ? config : [config];
654}
655
656exports.addCommandPluginsToInputOptions = addCommandPluginsToInputOptions;
657exports.batchWarnings = batchWarnings;
658exports.bold = bold;
659exports.cyan = cyan;
660exports.green = green;
661exports.handleError = handleError;
662exports.loadAndParseConfigFile = loadAndParseConfigFile;
663exports.stderr = stderr;
664exports.stdinName = stdinName;
665exports.underline = underline;
666//# sourceMappingURL=loadConfigFile.js.map