source: imaps-frontend/node_modules/rollup/dist/shared/watch-cli.js@ d565449

main
Last change on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 18.5 KB
Line 
1/*
2 @license
3 Rollup.js v4.20.0
4 Sat, 03 Aug 2024 04:48:21 GMT - commit df12edfea6e9c1a71bda1a01bed1ab787b7514d5
5
6 https://github.com/rollup/rollup
7
8 Released under the MIT License.
9*/
10'use strict';
11
12Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
13
14const promises = require('node:fs/promises');
15const process$2 = require('node:process');
16const index = require('./index.js');
17const cli = require('../bin/rollup');
18const rollup = require('./rollup.js');
19const parseAst_js = require('./parseAst.js');
20const loadConfigFile_js = require('./loadConfigFile.js');
21const node_child_process = require('node:child_process');
22const rollup_js = require('../rollup.js');
23require('fs');
24require('util');
25require('stream');
26require('path');
27require('os');
28require('./fsevents-importer.js');
29require('events');
30require('node:path');
31require('tty');
32require('../native.js');
33require('node:perf_hooks');
34require('node:url');
35require('../getLogFilter.js');
36
37function timeZone(date = new Date()) {
38 const offset = date.getTimezoneOffset();
39 const absOffset = Math.abs(offset);
40 const hours = Math.floor(absOffset / 60);
41 const minutes = absOffset % 60;
42 const minutesOut = minutes > 0 ? ':' + ('0' + minutes).slice(-2) : '';
43 return (offset < 0 ? '+' : '-') + hours + minutesOut;
44}
45
46function dateTime(options = {}) {
47 let {
48 date = new Date(),
49 local = true,
50 showTimeZone = false,
51 showMilliseconds = false
52 } = options;
53
54 if (local) {
55 // Offset the date so it will return the correct value when getting the ISO string.
56 date = new Date(date.getTime() - (date.getTimezoneOffset() * 60000));
57 }
58
59 let end = '';
60
61 if (showTimeZone) {
62 end = ' UTC' + (local ? timeZone(date) : '');
63 }
64
65 if (showMilliseconds && date.getUTCMilliseconds() > 0) {
66 end = ` ${date.getUTCMilliseconds()}ms${end}`;
67 }
68
69 return date
70 .toISOString()
71 .replace(/T/, ' ')
72 .replace(/\..+/, end);
73}
74
75/**
76 * This is not the set of all possible signals.
77 *
78 * It IS, however, the set of all signals that trigger
79 * an exit on either Linux or BSD systems. Linux is a
80 * superset of the signal names supported on BSD, and
81 * the unknown signals just fail to register, so we can
82 * catch that easily enough.
83 *
84 * Windows signals are a different set, since there are
85 * signals that terminate Windows processes, but don't
86 * terminate (or don't even exist) on Posix systems.
87 *
88 * Don't bother with SIGKILL. It's uncatchable, which
89 * means that we can't fire any callbacks anyway.
90 *
91 * If a user does happen to register a handler on a non-
92 * fatal signal like SIGWINCH or something, and then
93 * exit, it'll end up firing `process.emit('exit')`, so
94 * the handler will be fired anyway.
95 *
96 * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
97 * artificially, inherently leave the process in a
98 * state from which it is not safe to try and enter JS
99 * listeners.
100 */
101const signals = [];
102signals.push('SIGHUP', 'SIGINT', 'SIGTERM');
103if (process.platform !== 'win32') {
104 signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT'
105 // should detect profiler and enable/disable accordingly.
106 // see #21
107 // 'SIGPROF'
108 );
109}
110if (process.platform === 'linux') {
111 signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT');
112}
113
114// Note: since nyc uses this module to output coverage, any lines
115// that are in the direct sync flow of nyc's outputCoverage are
116// ignored, since we can never get coverage for them.
117// grab a reference to node's real process object right away
118const processOk = (process) => !!process &&
119 typeof process === 'object' &&
120 typeof process.removeListener === 'function' &&
121 typeof process.emit === 'function' &&
122 typeof process.reallyExit === 'function' &&
123 typeof process.listeners === 'function' &&
124 typeof process.kill === 'function' &&
125 typeof process.pid === 'number' &&
126 typeof process.on === 'function';
127const kExitEmitter = Symbol.for('signal-exit emitter');
128const global = globalThis;
129const ObjectDefineProperty = Object.defineProperty.bind(Object);
130// teeny special purpose ee
131class Emitter {
132 emitted = {
133 afterExit: false,
134 exit: false,
135 };
136 listeners = {
137 afterExit: [],
138 exit: [],
139 };
140 count = 0;
141 id = Math.random();
142 constructor() {
143 if (global[kExitEmitter]) {
144 return global[kExitEmitter];
145 }
146 ObjectDefineProperty(global, kExitEmitter, {
147 value: this,
148 writable: false,
149 enumerable: false,
150 configurable: false,
151 });
152 }
153 on(ev, fn) {
154 this.listeners[ev].push(fn);
155 }
156 removeListener(ev, fn) {
157 const list = this.listeners[ev];
158 const i = list.indexOf(fn);
159 /* c8 ignore start */
160 if (i === -1) {
161 return;
162 }
163 /* c8 ignore stop */
164 if (i === 0 && list.length === 1) {
165 list.length = 0;
166 }
167 else {
168 list.splice(i, 1);
169 }
170 }
171 emit(ev, code, signal) {
172 if (this.emitted[ev]) {
173 return false;
174 }
175 this.emitted[ev] = true;
176 let ret = false;
177 for (const fn of this.listeners[ev]) {
178 ret = fn(code, signal) === true || ret;
179 }
180 if (ev === 'exit') {
181 ret = this.emit('afterExit', code, signal) || ret;
182 }
183 return ret;
184 }
185}
186class SignalExitBase {
187}
188const signalExitWrap = (handler) => {
189 return {
190 onExit(cb, opts) {
191 return handler.onExit(cb, opts);
192 },
193 load() {
194 return handler.load();
195 },
196 unload() {
197 return handler.unload();
198 },
199 };
200};
201class SignalExitFallback extends SignalExitBase {
202 onExit() {
203 return () => { };
204 }
205 load() { }
206 unload() { }
207}
208class SignalExit extends SignalExitBase {
209 // "SIGHUP" throws an `ENOSYS` error on Windows,
210 // so use a supported signal instead
211 /* c8 ignore start */
212 #hupSig = process$1.platform === 'win32' ? 'SIGINT' : 'SIGHUP';
213 /* c8 ignore stop */
214 #emitter = new Emitter();
215 #process;
216 #originalProcessEmit;
217 #originalProcessReallyExit;
218 #sigListeners = {};
219 #loaded = false;
220 constructor(process) {
221 super();
222 this.#process = process;
223 // { <signal>: <listener fn>, ... }
224 this.#sigListeners = {};
225 for (const sig of signals) {
226 this.#sigListeners[sig] = () => {
227 // If there are no other listeners, an exit is coming!
228 // Simplest way: remove us and then re-send the signal.
229 // We know that this will kill the process, so we can
230 // safely emit now.
231 const listeners = this.#process.listeners(sig);
232 let { count } = this.#emitter;
233 // This is a workaround for the fact that signal-exit v3 and signal
234 // exit v4 are not aware of each other, and each will attempt to let
235 // the other handle it, so neither of them do. To correct this, we
236 // detect if we're the only handler *except* for previous versions
237 // of signal-exit, and increment by the count of listeners it has
238 // created.
239 /* c8 ignore start */
240 const p = process;
241 if (typeof p.__signal_exit_emitter__ === 'object' &&
242 typeof p.__signal_exit_emitter__.count === 'number') {
243 count += p.__signal_exit_emitter__.count;
244 }
245 /* c8 ignore stop */
246 if (listeners.length === count) {
247 this.unload();
248 const ret = this.#emitter.emit('exit', null, sig);
249 /* c8 ignore start */
250 const s = sig === 'SIGHUP' ? this.#hupSig : sig;
251 if (!ret)
252 process.kill(process.pid, s);
253 /* c8 ignore stop */
254 }
255 };
256 }
257 this.#originalProcessReallyExit = process.reallyExit;
258 this.#originalProcessEmit = process.emit;
259 }
260 onExit(cb, opts) {
261 /* c8 ignore start */
262 if (!processOk(this.#process)) {
263 return () => { };
264 }
265 /* c8 ignore stop */
266 if (this.#loaded === false) {
267 this.load();
268 }
269 const ev = opts?.alwaysLast ? 'afterExit' : 'exit';
270 this.#emitter.on(ev, cb);
271 return () => {
272 this.#emitter.removeListener(ev, cb);
273 if (this.#emitter.listeners['exit'].length === 0 &&
274 this.#emitter.listeners['afterExit'].length === 0) {
275 this.unload();
276 }
277 };
278 }
279 load() {
280 if (this.#loaded) {
281 return;
282 }
283 this.#loaded = true;
284 // This is the number of onSignalExit's that are in play.
285 // It's important so that we can count the correct number of
286 // listeners on signals, and don't wait for the other one to
287 // handle it instead of us.
288 this.#emitter.count += 1;
289 for (const sig of signals) {
290 try {
291 const fn = this.#sigListeners[sig];
292 if (fn)
293 this.#process.on(sig, fn);
294 }
295 catch (_) { }
296 }
297 this.#process.emit = (ev, ...a) => {
298 return this.#processEmit(ev, ...a);
299 };
300 this.#process.reallyExit = (code) => {
301 return this.#processReallyExit(code);
302 };
303 }
304 unload() {
305 if (!this.#loaded) {
306 return;
307 }
308 this.#loaded = false;
309 signals.forEach(sig => {
310 const listener = this.#sigListeners[sig];
311 /* c8 ignore start */
312 if (!listener) {
313 throw new Error('Listener not defined for signal: ' + sig);
314 }
315 /* c8 ignore stop */
316 try {
317 this.#process.removeListener(sig, listener);
318 /* c8 ignore start */
319 }
320 catch (_) { }
321 /* c8 ignore stop */
322 });
323 this.#process.emit = this.#originalProcessEmit;
324 this.#process.reallyExit = this.#originalProcessReallyExit;
325 this.#emitter.count -= 1;
326 }
327 #processReallyExit(code) {
328 /* c8 ignore start */
329 if (!processOk(this.#process)) {
330 return 0;
331 }
332 this.#process.exitCode = code || 0;
333 /* c8 ignore stop */
334 this.#emitter.emit('exit', this.#process.exitCode, null);
335 return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
336 }
337 #processEmit(ev, ...args) {
338 const og = this.#originalProcessEmit;
339 if (ev === 'exit' && processOk(this.#process)) {
340 if (typeof args[0] === 'number') {
341 this.#process.exitCode = args[0];
342 /* c8 ignore start */
343 }
344 /* c8 ignore start */
345 const ret = og.call(this.#process, ev, ...args);
346 /* c8 ignore start */
347 this.#emitter.emit('exit', this.#process.exitCode, null);
348 /* c8 ignore stop */
349 return ret;
350 }
351 else {
352 return og.call(this.#process, ev, ...args);
353 }
354 }
355}
356const process$1 = globalThis.process;
357// wrap so that we call the method on the actual handler, without
358// exporting it directly.
359const {
360/**
361 * Called when the process is exiting, whether via signal, explicit
362 * exit, or running out of stuff to do.
363 *
364 * If the global process object is not suitable for instrumentation,
365 * then this will be a no-op.
366 *
367 * Returns a function that may be used to unload signal-exit.
368 */
369onExit,
370/**
371 * Load the listeners. Likely you never need to call this, unless
372 * doing a rather deep integration with signal-exit functionality.
373 * Mostly exposed for the benefit of testing.
374 *
375 * @internal
376 */
377load,
378/**
379 * Unload the listeners. Likely you never need to call this, unless
380 * doing a rather deep integration with signal-exit functionality.
381 * Mostly exposed for the benefit of testing.
382 *
383 * @internal
384 */
385unload, } = signalExitWrap(processOk(process$1) ? new SignalExit(process$1) : new SignalExitFallback());
386
387const CLEAR_SCREEN = '\u001Bc';
388function getResetScreen(configs, allowClearScreen) {
389 let clearScreen = allowClearScreen;
390 for (const config of configs) {
391 if (config.watch && config.watch.clearScreen === false) {
392 clearScreen = false;
393 }
394 }
395 if (clearScreen) {
396 return (heading) => rollup.stderr(CLEAR_SCREEN + heading);
397 }
398 let firstRun = true;
399 return (heading) => {
400 if (firstRun) {
401 rollup.stderr(heading);
402 firstRun = false;
403 }
404 };
405}
406
407function extractWatchHooks(command) {
408 if (!Array.isArray(command.watch))
409 return {};
410 return command.watch
411 .filter(value => typeof value === 'object')
412 .reduce((accumulator, keyValueOption) => ({ ...accumulator, ...keyValueOption }), {});
413}
414function createWatchHooks(command) {
415 const watchHooks = extractWatchHooks(command);
416 return function (hook) {
417 if (watchHooks[hook]) {
418 const cmd = watchHooks[hook];
419 if (!command.silent) {
420 rollup.stderr(rollup.cyan$1(`watch.${hook} ${rollup.bold(`$ ${cmd}`)}`));
421 }
422 try {
423 // !! important - use stderr for all writes from execSync
424 const stdio = [process.stdin, process.stderr, process.stderr];
425 node_child_process.execSync(cmd, { stdio: command.silent ? 'ignore' : stdio });
426 }
427 catch (error) {
428 rollup.stderr(error.message);
429 }
430 }
431 };
432}
433
434async function watch(command) {
435 process$2.env.ROLLUP_WATCH = 'true';
436 const isTTY = process$2.stderr.isTTY;
437 const silent = command.silent;
438 let watcher;
439 let configWatcher;
440 let resetScreen;
441 const configFile = command.config ? await cli.getConfigPath(command.config) : null;
442 const runWatchHook = createWatchHooks(command);
443 onExit(close);
444 process$2.on('uncaughtException', closeWithError);
445 if (!process$2.stdin.isTTY) {
446 process$2.stdin.on('end', close);
447 process$2.stdin.resume();
448 }
449 async function loadConfigFromFileAndTrack(configFile) {
450 let configFileData = null;
451 let configFileRevision = 0;
452 configWatcher = index.chokidar.watch(configFile).on('change', reloadConfigFile);
453 await reloadConfigFile();
454 async function reloadConfigFile() {
455 try {
456 const newConfigFileData = await promises.readFile(configFile, 'utf8');
457 if (newConfigFileData === configFileData) {
458 return;
459 }
460 configFileRevision++;
461 const currentConfigFileRevision = configFileRevision;
462 if (configFileData) {
463 rollup.stderr(`\nReloading updated config...`);
464 }
465 configFileData = newConfigFileData;
466 const { options, warnings } = await loadConfigFile_js.loadConfigFile(configFile, command, true);
467 if (currentConfigFileRevision !== configFileRevision) {
468 return;
469 }
470 if (watcher) {
471 await watcher.close();
472 }
473 start(options, warnings);
474 }
475 catch (error) {
476 rollup.handleError(error, true);
477 }
478 }
479 }
480 if (configFile) {
481 await loadConfigFromFileAndTrack(configFile);
482 }
483 else {
484 const { options, warnings } = await cli.loadConfigFromCommand(command, true);
485 await start(options, warnings);
486 }
487 async function start(configs, warnings) {
488 watcher = rollup_js.watch(configs);
489 watcher.on('event', event => {
490 switch (event.code) {
491 case 'ERROR': {
492 warnings.flush();
493 rollup.handleError(event.error, true);
494 runWatchHook('onError');
495 break;
496 }
497 case 'START': {
498 if (!silent) {
499 if (!resetScreen) {
500 resetScreen = getResetScreen(configs, isTTY);
501 }
502 resetScreen(rollup.underline(`rollup v${rollup.version}`));
503 }
504 runWatchHook('onStart');
505 break;
506 }
507 case 'BUNDLE_START': {
508 if (!silent) {
509 let input = event.input;
510 if (typeof input !== 'string') {
511 input = Array.isArray(input)
512 ? input.join(', ')
513 : Object.values(input).join(', ');
514 }
515 rollup.stderr(rollup.cyan$1(`bundles ${rollup.bold(input)} → ${rollup.bold(event.output.map(parseAst_js.relativeId).join(', '))}...`));
516 }
517 runWatchHook('onBundleStart');
518 break;
519 }
520 case 'BUNDLE_END': {
521 warnings.flush();
522 if (!silent)
523 rollup.stderr(rollup.green(`created ${rollup.bold(event.output.map(parseAst_js.relativeId).join(', '))} in ${rollup.bold(cli.prettyMilliseconds(event.duration))}`));
524 runWatchHook('onBundleEnd');
525 if (event.result && event.result.getTimings) {
526 cli.printTimings(event.result.getTimings());
527 }
528 break;
529 }
530 case 'END': {
531 runWatchHook('onEnd');
532 if (!silent && isTTY) {
533 rollup.stderr(`\n[${dateTime()}] waiting for changes...`);
534 }
535 }
536 }
537 if ('result' in event && event.result) {
538 event.result.close().catch(error => rollup.handleError(error, true));
539 }
540 });
541 }
542 async function close(code) {
543 process$2.removeListener('uncaughtException', closeWithError);
544 // removing a non-existent listener is a no-op
545 process$2.stdin.removeListener('end', close);
546 if (watcher)
547 await watcher.close();
548 if (configWatcher)
549 configWatcher.close();
550 if (code)
551 process$2.exit(code);
552 }
553 // return a promise that never resolves to keep the process running
554 return new Promise(() => { });
555}
556function closeWithError(error) {
557 error.name = `Uncaught ${error.name}`;
558 rollup.handleError(error);
559}
560
561exports.watch = watch;
562//# sourceMappingURL=watch-cli.js.map
Note: See TracBrowser for help on using the repository browser.