watch-cli.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. /*
  2. @license
  3. Rollup.js v3.18.0
  4. Wed, 01 Mar 2023 18:45:12 GMT - commit 25bdc129d21685b69a00ee55397d42ac6eff6449
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  10. const promises = require('node:fs/promises');
  11. const process$2 = require('node:process');
  12. const index = require('./index.js');
  13. const cli = require('../bin/rollup');
  14. const rollup = require('./rollup.js');
  15. const require$$0 = require('assert');
  16. const require$$0$1 = require('events');
  17. const loadConfigFile_js = require('./loadConfigFile.js');
  18. const node_child_process = require('node:child_process');
  19. const watchProxy = require('./watch-proxy.js');
  20. require('fs');
  21. require('util');
  22. require('stream');
  23. require('path');
  24. require('os');
  25. require('./fsevents-importer.js');
  26. require('node:path');
  27. require('tty');
  28. require('node:perf_hooks');
  29. require('node:crypto');
  30. require('node:events');
  31. require('node:url');
  32. function timeZone(date = new Date()) {
  33. const offset = date.getTimezoneOffset();
  34. const absOffset = Math.abs(offset);
  35. const hours = Math.floor(absOffset / 60);
  36. const minutes = absOffset % 60;
  37. const minutesOut = minutes > 0 ? ':' + ('0' + minutes).slice(-2) : '';
  38. return (offset < 0 ? '+' : '-') + hours + minutesOut;
  39. }
  40. function dateTime(options = {}) {
  41. let {
  42. date = new Date(),
  43. local = true,
  44. showTimeZone = false,
  45. showMilliseconds = false
  46. } = options;
  47. if (local) {
  48. // Offset the date so it will return the correct value when getting the ISO string.
  49. date = new Date(date.getTime() - (date.getTimezoneOffset() * 60000));
  50. }
  51. let end = '';
  52. if (showTimeZone) {
  53. end = ' UTC' + (local ? timeZone(date) : '');
  54. }
  55. if (showMilliseconds && date.getUTCMilliseconds() > 0) {
  56. end = ` ${date.getUTCMilliseconds()}ms${end}`;
  57. }
  58. return date
  59. .toISOString()
  60. .replace(/T/, ' ')
  61. .replace(/\..+/, end);
  62. }
  63. var signalExitExports = {};
  64. var signalExit = {
  65. get exports(){ return signalExitExports; },
  66. set exports(v){ signalExitExports = v; },
  67. };
  68. var signalsExports = {};
  69. var signals$1 = {
  70. get exports(){ return signalsExports; },
  71. set exports(v){ signalsExports = v; },
  72. };
  73. var hasRequiredSignals;
  74. function requireSignals () {
  75. if (hasRequiredSignals) return signalsExports;
  76. hasRequiredSignals = 1;
  77. (function (module) {
  78. // This is not the set of all possible signals.
  79. //
  80. // It IS, however, the set of all signals that trigger
  81. // an exit on either Linux or BSD systems. Linux is a
  82. // superset of the signal names supported on BSD, and
  83. // the unknown signals just fail to register, so we can
  84. // catch that easily enough.
  85. //
  86. // Don't bother with SIGKILL. It's uncatchable, which
  87. // means that we can't fire any callbacks anyway.
  88. //
  89. // If a user does happen to register a handler on a non-
  90. // fatal signal like SIGWINCH or something, and then
  91. // exit, it'll end up firing `process.emit('exit')`, so
  92. // the handler will be fired anyway.
  93. //
  94. // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
  95. // artificially, inherently leave the process in a
  96. // state from which it is not safe to try and enter JS
  97. // listeners.
  98. module.exports = [
  99. 'SIGABRT',
  100. 'SIGALRM',
  101. 'SIGHUP',
  102. 'SIGINT',
  103. 'SIGTERM'
  104. ];
  105. if (process.platform !== 'win32') {
  106. module.exports.push(
  107. 'SIGVTALRM',
  108. 'SIGXCPU',
  109. 'SIGXFSZ',
  110. 'SIGUSR2',
  111. 'SIGTRAP',
  112. 'SIGSYS',
  113. 'SIGQUIT',
  114. 'SIGIOT'
  115. // should detect profiler and enable/disable accordingly.
  116. // see #21
  117. // 'SIGPROF'
  118. );
  119. }
  120. if (process.platform === 'linux') {
  121. module.exports.push(
  122. 'SIGIO',
  123. 'SIGPOLL',
  124. 'SIGPWR',
  125. 'SIGSTKFLT',
  126. 'SIGUNUSED'
  127. );
  128. }
  129. } (signals$1));
  130. return signalsExports;
  131. }
  132. // Note: since nyc uses this module to output coverage, any lines
  133. // that are in the direct sync flow of nyc's outputCoverage are
  134. // ignored, since we can never get coverage for them.
  135. // grab a reference to node's real process object right away
  136. var process$1 = rollup.commonjsGlobal.process;
  137. const processOk = function (process) {
  138. return process &&
  139. typeof process === 'object' &&
  140. typeof process.removeListener === 'function' &&
  141. typeof process.emit === 'function' &&
  142. typeof process.reallyExit === 'function' &&
  143. typeof process.listeners === 'function' &&
  144. typeof process.kill === 'function' &&
  145. typeof process.pid === 'number' &&
  146. typeof process.on === 'function'
  147. };
  148. // some kind of non-node environment, just no-op
  149. /* istanbul ignore if */
  150. if (!processOk(process$1)) {
  151. signalExit.exports = function () {
  152. return function () {}
  153. };
  154. } else {
  155. var assert = require$$0;
  156. var signals = requireSignals();
  157. var isWin = /^win/i.test(process$1.platform);
  158. var EE = require$$0$1;
  159. /* istanbul ignore if */
  160. if (typeof EE !== 'function') {
  161. EE = EE.EventEmitter;
  162. }
  163. var emitter;
  164. if (process$1.__signal_exit_emitter__) {
  165. emitter = process$1.__signal_exit_emitter__;
  166. } else {
  167. emitter = process$1.__signal_exit_emitter__ = new EE();
  168. emitter.count = 0;
  169. emitter.emitted = {};
  170. }
  171. // Because this emitter is a global, we have to check to see if a
  172. // previous version of this library failed to enable infinite listeners.
  173. // I know what you're about to say. But literally everything about
  174. // signal-exit is a compromise with evil. Get used to it.
  175. if (!emitter.infinite) {
  176. emitter.setMaxListeners(Infinity);
  177. emitter.infinite = true;
  178. }
  179. signalExit.exports = function (cb, opts) {
  180. /* istanbul ignore if */
  181. if (!processOk(rollup.commonjsGlobal.process)) {
  182. return function () {}
  183. }
  184. assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
  185. if (loaded === false) {
  186. load();
  187. }
  188. var ev = 'exit';
  189. if (opts && opts.alwaysLast) {
  190. ev = 'afterexit';
  191. }
  192. var remove = function () {
  193. emitter.removeListener(ev, cb);
  194. if (emitter.listeners('exit').length === 0 &&
  195. emitter.listeners('afterexit').length === 0) {
  196. unload();
  197. }
  198. };
  199. emitter.on(ev, cb);
  200. return remove
  201. };
  202. var unload = function unload () {
  203. if (!loaded || !processOk(rollup.commonjsGlobal.process)) {
  204. return
  205. }
  206. loaded = false;
  207. signals.forEach(function (sig) {
  208. try {
  209. process$1.removeListener(sig, sigListeners[sig]);
  210. } catch (er) {}
  211. });
  212. process$1.emit = originalProcessEmit;
  213. process$1.reallyExit = originalProcessReallyExit;
  214. emitter.count -= 1;
  215. };
  216. signalExitExports.unload = unload;
  217. var emit = function emit (event, code, signal) {
  218. /* istanbul ignore if */
  219. if (emitter.emitted[event]) {
  220. return
  221. }
  222. emitter.emitted[event] = true;
  223. emitter.emit(event, code, signal);
  224. };
  225. // { <signal>: <listener fn>, ... }
  226. var sigListeners = {};
  227. signals.forEach(function (sig) {
  228. sigListeners[sig] = function listener () {
  229. /* istanbul ignore if */
  230. if (!processOk(rollup.commonjsGlobal.process)) {
  231. return
  232. }
  233. // If there are no other listeners, an exit is coming!
  234. // Simplest way: remove us and then re-send the signal.
  235. // We know that this will kill the process, so we can
  236. // safely emit now.
  237. var listeners = process$1.listeners(sig);
  238. if (listeners.length === emitter.count) {
  239. unload();
  240. emit('exit', null, sig);
  241. /* istanbul ignore next */
  242. emit('afterexit', null, sig);
  243. /* istanbul ignore next */
  244. if (isWin && sig === 'SIGHUP') {
  245. // "SIGHUP" throws an `ENOSYS` error on Windows,
  246. // so use a supported signal instead
  247. sig = 'SIGINT';
  248. }
  249. /* istanbul ignore next */
  250. process$1.kill(process$1.pid, sig);
  251. }
  252. };
  253. });
  254. signalExitExports.signals = function () {
  255. return signals
  256. };
  257. var loaded = false;
  258. var load = function load () {
  259. if (loaded || !processOk(rollup.commonjsGlobal.process)) {
  260. return
  261. }
  262. loaded = true;
  263. // This is the number of onSignalExit's that are in play.
  264. // It's important so that we can count the correct number of
  265. // listeners on signals, and don't wait for the other one to
  266. // handle it instead of us.
  267. emitter.count += 1;
  268. signals = signals.filter(function (sig) {
  269. try {
  270. process$1.on(sig, sigListeners[sig]);
  271. return true
  272. } catch (er) {
  273. return false
  274. }
  275. });
  276. process$1.emit = processEmit;
  277. process$1.reallyExit = processReallyExit;
  278. };
  279. signalExitExports.load = load;
  280. var originalProcessReallyExit = process$1.reallyExit;
  281. var processReallyExit = function processReallyExit (code) {
  282. /* istanbul ignore if */
  283. if (!processOk(rollup.commonjsGlobal.process)) {
  284. return
  285. }
  286. process$1.exitCode = code || /* istanbul ignore next */ 0;
  287. emit('exit', process$1.exitCode, null);
  288. /* istanbul ignore next */
  289. emit('afterexit', process$1.exitCode, null);
  290. /* istanbul ignore next */
  291. originalProcessReallyExit.call(process$1, process$1.exitCode);
  292. };
  293. var originalProcessEmit = process$1.emit;
  294. var processEmit = function processEmit (ev, arg) {
  295. if (ev === 'exit' && processOk(rollup.commonjsGlobal.process)) {
  296. /* istanbul ignore else */
  297. if (arg !== undefined) {
  298. process$1.exitCode = arg;
  299. }
  300. var ret = originalProcessEmit.apply(this, arguments);
  301. /* istanbul ignore next */
  302. emit('exit', process$1.exitCode, null);
  303. /* istanbul ignore next */
  304. emit('afterexit', process$1.exitCode, null);
  305. /* istanbul ignore next */
  306. return ret
  307. } else {
  308. return originalProcessEmit.apply(this, arguments)
  309. }
  310. };
  311. }
  312. const CLEAR_SCREEN = '\u001Bc';
  313. function getResetScreen(configs, allowClearScreen) {
  314. let clearScreen = allowClearScreen;
  315. for (const config of configs) {
  316. if (config.watch && config.watch.clearScreen === false) {
  317. clearScreen = false;
  318. }
  319. }
  320. if (clearScreen) {
  321. return (heading) => rollup.stderr(CLEAR_SCREEN + heading);
  322. }
  323. let firstRun = true;
  324. return (heading) => {
  325. if (firstRun) {
  326. rollup.stderr(heading);
  327. firstRun = false;
  328. }
  329. };
  330. }
  331. function extractWatchHooks(command) {
  332. if (!Array.isArray(command.watch))
  333. return {};
  334. return command.watch
  335. .filter(value => typeof value === 'object')
  336. .reduce((accumulator, keyValueOption) => ({ ...accumulator, ...keyValueOption }), {});
  337. }
  338. function createWatchHooks(command) {
  339. const watchHooks = extractWatchHooks(command);
  340. return function (hook) {
  341. if (watchHooks[hook]) {
  342. const cmd = watchHooks[hook];
  343. if (!command.silent) {
  344. rollup.stderr(rollup.cyan(`watch.${hook} ${rollup.bold(`$ ${cmd}`)}`));
  345. }
  346. try {
  347. // !! important - use stderr for all writes from execSync
  348. const stdio = [process.stdin, process.stderr, process.stderr];
  349. node_child_process.execSync(cmd, { stdio: command.silent ? 'ignore' : stdio });
  350. }
  351. catch (error) {
  352. rollup.stderr(error.message);
  353. }
  354. }
  355. };
  356. }
  357. async function watch(command) {
  358. process$2.env.ROLLUP_WATCH = 'true';
  359. const isTTY = process$2.stderr.isTTY;
  360. const silent = command.silent;
  361. let watcher;
  362. let configWatcher;
  363. let resetScreen;
  364. const configFile = command.config ? await cli.getConfigPath(command.config) : null;
  365. const runWatchHook = createWatchHooks(command);
  366. signalExitExports(close);
  367. process$2.on('uncaughtException', close);
  368. if (!process$2.stdin.isTTY) {
  369. process$2.stdin.on('end', close);
  370. process$2.stdin.resume();
  371. }
  372. async function loadConfigFromFileAndTrack(configFile) {
  373. let configFileData = null;
  374. let configFileRevision = 0;
  375. configWatcher = index.chokidar.watch(configFile).on('change', reloadConfigFile);
  376. await reloadConfigFile();
  377. async function reloadConfigFile() {
  378. try {
  379. const newConfigFileData = await promises.readFile(configFile, 'utf8');
  380. if (newConfigFileData === configFileData) {
  381. return;
  382. }
  383. configFileRevision++;
  384. const currentConfigFileRevision = configFileRevision;
  385. if (configFileData) {
  386. rollup.stderr(`\nReloading updated config...`);
  387. }
  388. configFileData = newConfigFileData;
  389. const { options, warnings } = await loadConfigFile_js.loadConfigFile(configFile, command);
  390. if (currentConfigFileRevision !== configFileRevision) {
  391. return;
  392. }
  393. if (watcher) {
  394. await watcher.close();
  395. }
  396. start(options, warnings);
  397. }
  398. catch (error) {
  399. rollup.handleError(error, true);
  400. }
  401. }
  402. }
  403. if (configFile) {
  404. await loadConfigFromFileAndTrack(configFile);
  405. }
  406. else {
  407. const { options, warnings } = await cli.loadConfigFromCommand(command);
  408. await start(options, warnings);
  409. }
  410. async function start(configs, warnings) {
  411. watcher = watchProxy.watch(configs);
  412. watcher.on('event', event => {
  413. switch (event.code) {
  414. case 'ERROR': {
  415. warnings.flush();
  416. rollup.handleError(event.error, true);
  417. runWatchHook('onError');
  418. break;
  419. }
  420. case 'START': {
  421. if (!silent) {
  422. if (!resetScreen) {
  423. resetScreen = getResetScreen(configs, isTTY);
  424. }
  425. resetScreen(rollup.underline(`rollup v${rollup.version}`));
  426. }
  427. runWatchHook('onStart');
  428. break;
  429. }
  430. case 'BUNDLE_START': {
  431. if (!silent) {
  432. let input = event.input;
  433. if (typeof input !== 'string') {
  434. input = Array.isArray(input)
  435. ? input.join(', ')
  436. : Object.values(input).join(', ');
  437. }
  438. rollup.stderr(rollup.cyan(`bundles ${rollup.bold(input)} → ${rollup.bold(event.output.map(rollup.relativeId).join(', '))}...`));
  439. }
  440. runWatchHook('onBundleStart');
  441. break;
  442. }
  443. case 'BUNDLE_END': {
  444. warnings.flush();
  445. if (!silent)
  446. rollup.stderr(rollup.green(`created ${rollup.bold(event.output.map(rollup.relativeId).join(', '))} in ${rollup.bold(cli.prettyMilliseconds(event.duration))}`));
  447. runWatchHook('onBundleEnd');
  448. if (event.result && event.result.getTimings) {
  449. cli.printTimings(event.result.getTimings());
  450. }
  451. break;
  452. }
  453. case 'END': {
  454. runWatchHook('onEnd');
  455. if (!silent && isTTY) {
  456. rollup.stderr(`\n[${dateTime()}] waiting for changes...`);
  457. }
  458. }
  459. }
  460. if ('result' in event && event.result) {
  461. event.result.close().catch(error => rollup.handleError(error, true));
  462. }
  463. });
  464. }
  465. async function close(code) {
  466. process$2.removeListener('uncaughtException', close);
  467. // removing a non-existent listener is a no-op
  468. process$2.stdin.removeListener('end', close);
  469. if (watcher)
  470. await watcher.close();
  471. if (configWatcher)
  472. configWatcher.close();
  473. if (code) {
  474. // eslint-disable-next-line unicorn/no-process-exit
  475. process$2.exit(code);
  476. }
  477. }
  478. }
  479. exports.watch = watch;
  480. //# sourceMappingURL=watch-cli.js.map