2fced0f4e0b76168e9a0772d9055363b58b36cff8e6af234443db301886ea806a60f677e5f2b3030b4277494bb483e2f5a70a5dfff97722a6f0aeedb8be7de 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /*
  2. @license
  3. Rollup.js v3.29.4
  4. Sat, 21 Sep 2024 06:29:06 GMT - commit 2ef77c00ec2635d42697cff2c0567ccc8db34fb4
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. const promises = require('node:fs/promises');
  10. const node_path = require('node:path');
  11. const process$1 = require('node:process');
  12. const node_url = require('node:url');
  13. const rollup = require('./rollup.js');
  14. const getLogFilter_js = require('../getLogFilter.js');
  15. function batchWarnings(command) {
  16. const silent = !!command.silent;
  17. const logFilter = generateLogFilter(command);
  18. let count = 0;
  19. const deferredWarnings = new Map();
  20. let warningOccurred = false;
  21. const add = (warning) => {
  22. count += 1;
  23. warningOccurred = true;
  24. if (silent)
  25. return;
  26. if (warning.code in deferredHandlers) {
  27. rollup.getOrCreate(deferredWarnings, warning.code, rollup.getNewArray).push(warning);
  28. }
  29. else if (warning.code in immediateHandlers) {
  30. immediateHandlers[warning.code](warning);
  31. }
  32. else {
  33. title(warning.message);
  34. defaultBody(warning);
  35. }
  36. };
  37. return {
  38. add,
  39. get count() {
  40. return count;
  41. },
  42. flush() {
  43. if (count === 0 || silent)
  44. return;
  45. const codes = [...deferredWarnings.keys()].sort((a, b) => deferredWarnings.get(b).length - deferredWarnings.get(a).length);
  46. for (const code of codes) {
  47. deferredHandlers[code](deferredWarnings.get(code));
  48. }
  49. deferredWarnings.clear();
  50. count = 0;
  51. },
  52. log(level, log) {
  53. if (!logFilter(log))
  54. return;
  55. switch (level) {
  56. case rollup.LOGLEVEL_WARN: {
  57. return add(log);
  58. }
  59. case rollup.LOGLEVEL_DEBUG: {
  60. if (!silent) {
  61. rollup.stderr(rollup.bold(rollup.blue(log.message)));
  62. defaultBody(log);
  63. }
  64. return;
  65. }
  66. default: {
  67. if (!silent) {
  68. rollup.stderr(rollup.bold(rollup.cyan(log.message)));
  69. defaultBody(log);
  70. }
  71. }
  72. }
  73. },
  74. get warningOccurred() {
  75. return warningOccurred;
  76. }
  77. };
  78. }
  79. const immediateHandlers = {
  80. MISSING_NODE_BUILTINS(warning) {
  81. title(`Missing shims for Node.js built-ins`);
  82. rollup.stderr(`Creating a browser bundle that depends on ${rollup.printQuotedStringList(warning.ids)}. You might need to include https://github.com/FredKSchott/rollup-plugin-polyfill-node`);
  83. },
  84. UNKNOWN_OPTION(warning) {
  85. title(`You have passed an unrecognized option`);
  86. rollup.stderr(warning.message);
  87. }
  88. };
  89. const deferredHandlers = {
  90. CIRCULAR_DEPENDENCY(warnings) {
  91. title(`Circular dependenc${warnings.length > 1 ? 'ies' : 'y'}`);
  92. const displayed = warnings.length > 5 ? warnings.slice(0, 3) : warnings;
  93. for (const warning of displayed) {
  94. rollup.stderr(warning.ids.map(rollup.relativeId).join(' -> '));
  95. }
  96. if (warnings.length > displayed.length) {
  97. rollup.stderr(`...and ${warnings.length - displayed.length} more`);
  98. }
  99. },
  100. EMPTY_BUNDLE(warnings) {
  101. title(`Generated${warnings.length === 1 ? ' an' : ''} empty ${warnings.length > 1 ? 'chunks' : 'chunk'}`);
  102. rollup.stderr(rollup.printQuotedStringList(warnings.map(warning => warning.names[0])));
  103. },
  104. EVAL(warnings) {
  105. title('Use of eval is strongly discouraged');
  106. info(rollup.getRollupUrl(rollup.URL_AVOIDING_EVAL));
  107. showTruncatedWarnings(warnings);
  108. },
  109. MISSING_EXPORT(warnings) {
  110. title('Missing exports');
  111. info(rollup.getRollupUrl(rollup.URL_NAME_IS_NOT_EXPORTED));
  112. for (const warning of warnings) {
  113. rollup.stderr(rollup.bold(rollup.relativeId(warning.id)));
  114. rollup.stderr(`${warning.binding} is not exported by ${rollup.relativeId(warning.exporter)}`);
  115. rollup.stderr(rollup.gray(warning.frame));
  116. }
  117. },
  118. MISSING_GLOBAL_NAME(warnings) {
  119. title(`Missing global variable ${warnings.length > 1 ? 'names' : 'name'}`);
  120. info(rollup.getRollupUrl(rollup.URL_OUTPUT_GLOBALS));
  121. rollup.stderr(`Use "output.globals" to specify browser global variable names corresponding to external modules:`);
  122. for (const warning of warnings) {
  123. rollup.stderr(`${rollup.bold(warning.id)} (guessing "${warning.names[0]}")`);
  124. }
  125. },
  126. MIXED_EXPORTS(warnings) {
  127. title('Mixing named and default exports');
  128. info(rollup.getRollupUrl(rollup.URL_OUTPUT_EXPORTS));
  129. rollup.stderr(rollup.bold('The following entry modules are using named and default exports together:'));
  130. warnings.sort((a, b) => (a.id < b.id ? -1 : 1));
  131. const displayedWarnings = warnings.length > 5 ? warnings.slice(0, 3) : warnings;
  132. for (const warning of displayedWarnings) {
  133. rollup.stderr(rollup.relativeId(warning.id));
  134. }
  135. if (displayedWarnings.length < warnings.length) {
  136. rollup.stderr(`...and ${warnings.length - displayedWarnings.length} other entry modules`);
  137. }
  138. rollup.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.`);
  139. },
  140. NAMESPACE_CONFLICT(warnings) {
  141. title(`Conflicting re-exports`);
  142. for (const warning of warnings) {
  143. rollup.stderr(`"${rollup.bold(rollup.relativeId(warning.reexporter))}" re-exports "${warning.binding}" from both "${rollup.relativeId(warning.ids[0])}" and "${rollup.relativeId(warning.ids[1])}" (will be ignored).`);
  144. }
  145. },
  146. PLUGIN_WARNING(warnings) {
  147. const nestedByPlugin = nest(warnings, 'plugin');
  148. for (const { key: plugin, items } of nestedByPlugin) {
  149. const nestedByMessage = nest(items, 'message');
  150. let lastUrl = '';
  151. for (const { key: message, items } of nestedByMessage) {
  152. title(`Plugin ${plugin}: ${message}`);
  153. for (const warning of items) {
  154. if (warning.url && warning.url !== lastUrl)
  155. info((lastUrl = warning.url));
  156. const id = warning.id || warning.loc?.file;
  157. if (id) {
  158. let loc = rollup.relativeId(id);
  159. if (warning.loc) {
  160. loc += `: (${warning.loc.line}:${warning.loc.column})`;
  161. }
  162. rollup.stderr(rollup.bold(loc));
  163. }
  164. if (warning.frame)
  165. info(warning.frame);
  166. }
  167. }
  168. }
  169. },
  170. SOURCEMAP_BROKEN(warnings) {
  171. title(`Broken sourcemap`);
  172. info(rollup.getRollupUrl(rollup.URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT));
  173. const plugins = [...new Set(warnings.map(({ plugin }) => plugin).filter(Boolean))];
  174. rollup.stderr(`Plugins that transform code (such as ${rollup.printQuotedStringList(plugins)}) should generate accompanying sourcemaps.`);
  175. },
  176. THIS_IS_UNDEFINED(warnings) {
  177. title('"this" has been rewritten to "undefined"');
  178. info(rollup.getRollupUrl(rollup.URL_THIS_IS_UNDEFINED));
  179. showTruncatedWarnings(warnings);
  180. },
  181. UNRESOLVED_IMPORT(warnings) {
  182. title('Unresolved dependencies');
  183. info(rollup.getRollupUrl(rollup.URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY));
  184. const dependencies = new Map();
  185. for (const warning of warnings) {
  186. rollup.getOrCreate(dependencies, rollup.relativeId(warning.exporter), rollup.getNewArray).push(rollup.relativeId(warning.id));
  187. }
  188. for (const [dependency, importers] of dependencies) {
  189. rollup.stderr(`${rollup.bold(dependency)} (imported by ${rollup.printQuotedStringList(importers)})`);
  190. }
  191. },
  192. UNUSED_EXTERNAL_IMPORT(warnings) {
  193. title('Unused external imports');
  194. for (const warning of warnings) {
  195. rollup.stderr(warning.names +
  196. ' imported from external module "' +
  197. warning.exporter +
  198. '" but never used in ' +
  199. rollup.printQuotedStringList(warning.ids.map(rollup.relativeId)) +
  200. '.');
  201. }
  202. }
  203. };
  204. function defaultBody(log) {
  205. if (log.url) {
  206. info(rollup.getRollupUrl(log.url));
  207. }
  208. const id = log.loc?.file || log.id;
  209. if (id) {
  210. const loc = log.loc ? `${rollup.relativeId(id)} (${log.loc.line}:${log.loc.column})` : rollup.relativeId(id);
  211. rollup.stderr(rollup.bold(rollup.relativeId(loc)));
  212. }
  213. if (log.frame)
  214. info(log.frame);
  215. }
  216. function title(string_) {
  217. rollup.stderr(rollup.bold(rollup.yellow(`(!) ${string_}`)));
  218. }
  219. function info(url) {
  220. rollup.stderr(rollup.gray(url));
  221. }
  222. function nest(array, property) {
  223. const nested = [];
  224. const lookup = new Map();
  225. for (const item of array) {
  226. const key = item[property];
  227. rollup.getOrCreate(lookup, key, () => {
  228. const items = {
  229. items: [],
  230. key
  231. };
  232. nested.push(items);
  233. return items;
  234. }).items.push(item);
  235. }
  236. return nested;
  237. }
  238. function showTruncatedWarnings(warnings) {
  239. const nestedByModule = nest(warnings, 'id');
  240. const displayedByModule = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;
  241. for (const { key: id, items } of displayedByModule) {
  242. rollup.stderr(rollup.bold(rollup.relativeId(id)));
  243. rollup.stderr(rollup.gray(items[0].frame));
  244. if (items.length > 1) {
  245. rollup.stderr(`...and ${items.length - 1} other ${items.length > 2 ? 'occurrences' : 'occurrence'}`);
  246. }
  247. }
  248. if (nestedByModule.length > displayedByModule.length) {
  249. rollup.stderr(`\n...and ${nestedByModule.length - displayedByModule.length} other files`);
  250. }
  251. }
  252. function generateLogFilter(command) {
  253. const filters = rollup.ensureArray(command.filterLogs).flatMap(filter => String(filter).split(','));
  254. if (process.env.ROLLUP_FILTER_LOGS) {
  255. filters.push(...process.env.ROLLUP_FILTER_LOGS.split(','));
  256. }
  257. return getLogFilter_js.getLogFilter(filters);
  258. }
  259. const stdinName = '-';
  260. let stdinResult = null;
  261. function stdinPlugin(argument) {
  262. const suffix = typeof argument == 'string' && argument.length > 0 ? '.' + argument : '';
  263. return {
  264. load(id) {
  265. if (id === stdinName || id.startsWith(stdinName + '.')) {
  266. return stdinResult || (stdinResult = readStdin());
  267. }
  268. },
  269. name: 'stdin',
  270. resolveId(id) {
  271. if (id === stdinName) {
  272. return id + suffix;
  273. }
  274. }
  275. };
  276. }
  277. function readStdin() {
  278. return new Promise((resolve, reject) => {
  279. const chunks = [];
  280. process$1.stdin.setEncoding('utf8');
  281. process$1.stdin
  282. .on('data', chunk => chunks.push(chunk))
  283. .on('end', () => {
  284. const result = chunks.join('');
  285. resolve(result);
  286. })
  287. .on('error', error => {
  288. reject(error);
  289. });
  290. });
  291. }
  292. function waitForInputPlugin() {
  293. return {
  294. async buildStart(options) {
  295. const inputSpecifiers = Array.isArray(options.input)
  296. ? options.input
  297. : Object.keys(options.input);
  298. let lastAwaitedSpecifier = null;
  299. checkSpecifiers: while (true) {
  300. for (const specifier of inputSpecifiers) {
  301. if ((await this.resolve(specifier)) === null) {
  302. if (lastAwaitedSpecifier !== specifier) {
  303. rollup.stderr(`waiting for input ${rollup.bold(specifier)}...`);
  304. lastAwaitedSpecifier = specifier;
  305. }
  306. await new Promise(resolve => setTimeout(resolve, 500));
  307. continue checkSpecifiers;
  308. }
  309. }
  310. break;
  311. }
  312. },
  313. name: 'wait-for-input'
  314. };
  315. }
  316. async function addCommandPluginsToInputOptions(inputOptions, command) {
  317. if (command.stdin !== false) {
  318. inputOptions.plugins.push(stdinPlugin(command.stdin));
  319. }
  320. if (command.waitForBundleInput === true) {
  321. inputOptions.plugins.push(waitForInputPlugin());
  322. }
  323. await addPluginsFromCommandOption(command.plugin, inputOptions);
  324. }
  325. async function addPluginsFromCommandOption(commandPlugin, inputOptions) {
  326. if (commandPlugin) {
  327. const plugins = await rollup.normalizePluginOption(commandPlugin);
  328. for (const plugin of plugins) {
  329. if (/[={}]/.test(plugin)) {
  330. // -p plugin=value
  331. // -p "{transform(c,i){...}}"
  332. await loadAndRegisterPlugin(inputOptions, plugin);
  333. }
  334. else {
  335. // split out plugins joined by commas
  336. // -p node-resolve,commonjs,buble
  337. for (const p of plugin.split(',')) {
  338. await loadAndRegisterPlugin(inputOptions, p);
  339. }
  340. }
  341. }
  342. }
  343. }
  344. async function loadAndRegisterPlugin(inputOptions, pluginText) {
  345. let plugin = null;
  346. let pluginArgument = undefined;
  347. if (pluginText[0] === '{') {
  348. // -p "{transform(c,i){...}}"
  349. plugin = new Function('return ' + pluginText);
  350. }
  351. else {
  352. const match = pluginText.match(/^([\w./:@\\^{|}-]+)(=(.*))?$/);
  353. if (match) {
  354. // -p plugin
  355. // -p plugin=arg
  356. pluginText = match[1];
  357. pluginArgument = new Function('return ' + match[3])();
  358. }
  359. else {
  360. throw new Error(`Invalid --plugin argument format: ${JSON.stringify(pluginText)}`);
  361. }
  362. if (!/^\.|^rollup-plugin-|[/@\\]/.test(pluginText)) {
  363. // Try using plugin prefix variations first if applicable.
  364. // Prefix order is significant - left has higher precedence.
  365. for (const prefix of ['@rollup/plugin-', 'rollup-plugin-']) {
  366. try {
  367. plugin = await requireOrImport(prefix + pluginText);
  368. break;
  369. }
  370. catch {
  371. // if this does not work, we try requiring the actual name below
  372. }
  373. }
  374. }
  375. if (!plugin) {
  376. try {
  377. if (pluginText[0] == '.')
  378. pluginText = node_path.resolve(pluginText);
  379. // Windows absolute paths must be specified as file:// protocol URL
  380. // Note that we do not have coverage for Windows-only code paths
  381. else if (/^[A-Za-z]:\\/.test(pluginText)) {
  382. pluginText = node_url.pathToFileURL(node_path.resolve(pluginText)).href;
  383. }
  384. plugin = await requireOrImport(pluginText);
  385. }
  386. catch (error) {
  387. throw new Error(`Cannot load plugin "${pluginText}": ${error.message}.`);
  388. }
  389. }
  390. }
  391. // some plugins do not use `module.exports` for their entry point,
  392. // in which case we try the named default export and the plugin name
  393. if (typeof plugin === 'object') {
  394. plugin = plugin.default || plugin[getCamelizedPluginBaseName(pluginText)];
  395. }
  396. if (!plugin) {
  397. 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.`);
  398. }
  399. inputOptions.plugins.push(typeof plugin === 'function' ? plugin.call(plugin, pluginArgument) : plugin);
  400. }
  401. function getCamelizedPluginBaseName(pluginText) {
  402. return (pluginText.match(/(@rollup\/plugin-|rollup-plugin-)(.+)$/)?.[2] || pluginText)
  403. .split(/[/\\]/)
  404. .slice(-1)[0]
  405. .split('.')[0]
  406. .split('-')
  407. .map((part, index) => (index === 0 || !part ? part : part[0].toUpperCase() + part.slice(1)))
  408. .join('');
  409. }
  410. async function requireOrImport(pluginPath) {
  411. try {
  412. // eslint-disable-next-line unicorn/prefer-module
  413. return require(pluginPath);
  414. }
  415. catch {
  416. return import(pluginPath);
  417. }
  418. }
  419. const loadConfigFile = async (fileName, commandOptions = {}, watchMode = false) => {
  420. const configs = await getConfigList(getDefaultFromCjs(await getConfigFileExport(fileName, commandOptions, watchMode)), commandOptions);
  421. const warnings = batchWarnings(commandOptions);
  422. try {
  423. const normalizedConfigs = [];
  424. for (const config of configs) {
  425. const options = await rollup.mergeOptions(config, watchMode, commandOptions, warnings.log);
  426. await addCommandPluginsToInputOptions(options, commandOptions);
  427. normalizedConfigs.push(options);
  428. }
  429. return { options: normalizedConfigs, warnings };
  430. }
  431. catch (error_) {
  432. warnings.flush();
  433. throw error_;
  434. }
  435. };
  436. async function getConfigFileExport(fileName, commandOptions, watchMode) {
  437. if (commandOptions.configPlugin || commandOptions.bundleConfigAsCjs) {
  438. try {
  439. return await loadTranspiledConfigFile(fileName, commandOptions);
  440. }
  441. catch (error_) {
  442. if (error_.message.includes('not defined in ES module scope')) {
  443. return rollup.error(rollup.logCannotBundleConfigAsEsm(error_));
  444. }
  445. throw error_;
  446. }
  447. }
  448. let cannotLoadEsm = false;
  449. const handleWarning = (warning) => {
  450. if (warning.message.includes('To load an ES module')) {
  451. cannotLoadEsm = true;
  452. }
  453. };
  454. process$1.on('warning', handleWarning);
  455. try {
  456. const fileUrl = node_url.pathToFileURL(fileName);
  457. if (watchMode) {
  458. // We are adding the current date to allow reloads in watch mode
  459. fileUrl.search = `?${Date.now()}`;
  460. }
  461. return (await import(fileUrl.href)).default;
  462. }
  463. catch (error_) {
  464. if (cannotLoadEsm) {
  465. return rollup.error(rollup.logCannotLoadConfigAsCjs(error_));
  466. }
  467. if (error_.message.includes('not defined in ES module scope')) {
  468. return rollup.error(rollup.logCannotLoadConfigAsEsm(error_));
  469. }
  470. throw error_;
  471. }
  472. finally {
  473. process$1.off('warning', handleWarning);
  474. }
  475. }
  476. function getDefaultFromCjs(namespace) {
  477. return namespace.default || namespace;
  478. }
  479. async function loadTranspiledConfigFile(fileName, commandOptions) {
  480. const { bundleConfigAsCjs, configPlugin, silent } = commandOptions;
  481. const warnings = batchWarnings(commandOptions);
  482. const inputOptions = {
  483. external: (id) => (id[0] !== '.' && !node_path.isAbsolute(id)) || id.slice(-5, id.length) === '.json',
  484. input: fileName,
  485. onwarn: warnings.add,
  486. plugins: [],
  487. treeshake: false
  488. };
  489. await addPluginsFromCommandOption(configPlugin, inputOptions);
  490. const bundle = await rollup.rollup(inputOptions);
  491. const { output: [{ code }] } = await bundle.generate({
  492. exports: 'named',
  493. format: bundleConfigAsCjs ? 'cjs' : 'es',
  494. plugins: [
  495. {
  496. name: 'transpile-import-meta',
  497. resolveImportMeta(property, { moduleId }) {
  498. if (property === 'url') {
  499. return `'${node_url.pathToFileURL(moduleId).href}'`;
  500. }
  501. if (property == null) {
  502. return `{url:'${node_url.pathToFileURL(moduleId).href}'}`;
  503. }
  504. }
  505. }
  506. ]
  507. });
  508. if (!silent && warnings.count > 0) {
  509. rollup.stderr(rollup.bold(`loaded ${rollup.relativeId(fileName)} with warnings`));
  510. warnings.flush();
  511. }
  512. return loadConfigFromWrittenFile(node_path.join(node_path.dirname(fileName), `rollup.config-${Date.now()}.${bundleConfigAsCjs ? 'cjs' : 'mjs'}`), code);
  513. }
  514. async function loadConfigFromWrittenFile(bundledFileName, bundledCode) {
  515. await promises.writeFile(bundledFileName, bundledCode);
  516. try {
  517. return (await import(node_url.pathToFileURL(bundledFileName).href)).default;
  518. }
  519. finally {
  520. // Not awaiting here saves some ms while potentially hiding a non-critical error
  521. promises.unlink(bundledFileName);
  522. }
  523. }
  524. async function getConfigList(configFileExport, commandOptions) {
  525. const config = await (typeof configFileExport === 'function'
  526. ? configFileExport(commandOptions)
  527. : configFileExport);
  528. if (Object.keys(config).length === 0) {
  529. return rollup.error(rollup.logMissingConfig());
  530. }
  531. return Array.isArray(config) ? config : [config];
  532. }
  533. exports.addCommandPluginsToInputOptions = addCommandPluginsToInputOptions;
  534. exports.batchWarnings = batchWarnings;
  535. exports.loadConfigFile = loadConfigFile;
  536. exports.stdinName = stdinName;
  537. //# sourceMappingURL=loadConfigFile.js.map