loadConfigFile.js 21 KB

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