source: imaps-frontend/node_modules/vite/dist/node-cjs/publicUtils.cjs@ 0c6b92a

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

Pred finalna verzija

  • Property mode set to 100644
File size: 156.2 KB
Line 
1'use strict';
2
3var path$3 = require('node:path');
4var node_url = require('node:url');
5var fs$1 = require('node:fs');
6var esbuild = require('esbuild');
7var node_module = require('node:module');
8var require$$0 = require('tty');
9var require$$1 = require('util');
10var require$$0$1 = require('path');
11var require$$0$2 = require('crypto');
12var fs$2 = require('fs');
13var readline = require('node:readline');
14var require$$2 = require('os');
15
16var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
17const { version: version$2 } = JSON.parse(
18 fs$1.readFileSync(new URL("../../package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))).toString()
19);
20const VERSION = version$2;
21const FS_PREFIX = `/@fs/`;
22const VITE_PACKAGE_DIR = path$3.resolve(
23 // import.meta.url is `dist/node/constants.js` after bundle
24 node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))),
25 "../../.."
26);
27const CLIENT_ENTRY = path$3.resolve(VITE_PACKAGE_DIR, "dist/client/client.mjs");
28path$3.resolve(VITE_PACKAGE_DIR, "dist/client/env.mjs");
29path$3.dirname(CLIENT_ENTRY);
30
31const comma = ','.charCodeAt(0);
32const semicolon = ';'.charCodeAt(0);
33const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
34const intToChar = new Uint8Array(64); // 64 possible chars.
35const charToInt = new Uint8Array(128); // z is 122 in ASCII
36for (let i = 0; i < chars.length; i++) {
37 const c = chars.charCodeAt(i);
38 intToChar[i] = c;
39 charToInt[c] = i;
40}
41function encodeInteger(builder, num, relative) {
42 let delta = num - relative;
43 delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
44 do {
45 let clamped = delta & 0b011111;
46 delta >>>= 5;
47 if (delta > 0)
48 clamped |= 0b100000;
49 builder.write(intToChar[clamped]);
50 } while (delta > 0);
51 return num;
52}
53
54const bufLength = 1024 * 16;
55// Provide a fallback for older environments.
56const td = typeof TextDecoder !== 'undefined'
57 ? /* #__PURE__ */ new TextDecoder()
58 : typeof Buffer !== 'undefined'
59 ? {
60 decode(buf) {
61 const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
62 return out.toString();
63 },
64 }
65 : {
66 decode(buf) {
67 let out = '';
68 for (let i = 0; i < buf.length; i++) {
69 out += String.fromCharCode(buf[i]);
70 }
71 return out;
72 },
73 };
74class StringWriter {
75 constructor() {
76 this.pos = 0;
77 this.out = '';
78 this.buffer = new Uint8Array(bufLength);
79 }
80 write(v) {
81 const { buffer } = this;
82 buffer[this.pos++] = v;
83 if (this.pos === bufLength) {
84 this.out += td.decode(buffer);
85 this.pos = 0;
86 }
87 }
88 flush() {
89 const { buffer, out, pos } = this;
90 return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
91 }
92}
93function encode(decoded) {
94 const writer = new StringWriter();
95 let sourcesIndex = 0;
96 let sourceLine = 0;
97 let sourceColumn = 0;
98 let namesIndex = 0;
99 for (let i = 0; i < decoded.length; i++) {
100 const line = decoded[i];
101 if (i > 0)
102 writer.write(semicolon);
103 if (line.length === 0)
104 continue;
105 let genColumn = 0;
106 for (let j = 0; j < line.length; j++) {
107 const segment = line[j];
108 if (j > 0)
109 writer.write(comma);
110 genColumn = encodeInteger(writer, segment[0], genColumn);
111 if (segment.length === 1)
112 continue;
113 sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
114 sourceLine = encodeInteger(writer, segment[2], sourceLine);
115 sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
116 if (segment.length === 4)
117 continue;
118 namesIndex = encodeInteger(writer, segment[4], namesIndex);
119 }
120 }
121 return writer.flush();
122}
123
124function getDefaultExportFromCjs (x) {
125 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
126}
127
128function commonjsRequire(path) {
129 throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
130}
131
132var picocolors = {exports: {}};
133
134let argv = process.argv || [],
135 env = process.env;
136let isColorSupported =
137 !("NO_COLOR" in env || argv.includes("--no-color")) &&
138 ("FORCE_COLOR" in env ||
139 argv.includes("--color") ||
140 process.platform === "win32" ||
141 (commonjsRequire != null && require$$0.isatty(1) && env.TERM !== "dumb") ||
142 "CI" in env);
143
144let formatter =
145 (open, close, replace = open) =>
146 input => {
147 let string = "" + input;
148 let index = string.indexOf(close, open.length);
149 return ~index
150 ? open + replaceClose(string, close, replace, index) + close
151 : open + string + close
152 };
153
154let replaceClose = (string, close, replace, index) => {
155 let result = "";
156 let cursor = 0;
157 do {
158 result += string.substring(cursor, index) + replace;
159 cursor = index + close.length;
160 index = string.indexOf(close, cursor);
161 } while (~index)
162 return result + string.substring(cursor)
163};
164
165let createColors = (enabled = isColorSupported) => {
166 let init = enabled ? formatter : () => String;
167 return {
168 isColorSupported: enabled,
169 reset: init("\x1b[0m", "\x1b[0m"),
170 bold: init("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
171 dim: init("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
172 italic: init("\x1b[3m", "\x1b[23m"),
173 underline: init("\x1b[4m", "\x1b[24m"),
174 inverse: init("\x1b[7m", "\x1b[27m"),
175 hidden: init("\x1b[8m", "\x1b[28m"),
176 strikethrough: init("\x1b[9m", "\x1b[29m"),
177 black: init("\x1b[30m", "\x1b[39m"),
178 red: init("\x1b[31m", "\x1b[39m"),
179 green: init("\x1b[32m", "\x1b[39m"),
180 yellow: init("\x1b[33m", "\x1b[39m"),
181 blue: init("\x1b[34m", "\x1b[39m"),
182 magenta: init("\x1b[35m", "\x1b[39m"),
183 cyan: init("\x1b[36m", "\x1b[39m"),
184 white: init("\x1b[37m", "\x1b[39m"),
185 gray: init("\x1b[90m", "\x1b[39m"),
186 bgBlack: init("\x1b[40m", "\x1b[49m"),
187 bgRed: init("\x1b[41m", "\x1b[49m"),
188 bgGreen: init("\x1b[42m", "\x1b[49m"),
189 bgYellow: init("\x1b[43m", "\x1b[49m"),
190 bgBlue: init("\x1b[44m", "\x1b[49m"),
191 bgMagenta: init("\x1b[45m", "\x1b[49m"),
192 bgCyan: init("\x1b[46m", "\x1b[49m"),
193 bgWhite: init("\x1b[47m", "\x1b[49m"),
194 }
195};
196
197picocolors.exports = createColors();
198picocolors.exports.createColors = createColors;
199
200var picocolorsExports = picocolors.exports;
201var colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
202
203var src = {exports: {}};
204
205var browser$1 = {exports: {}};
206
207/**
208 * Helpers.
209 */
210
211var ms;
212var hasRequiredMs;
213
214function requireMs () {
215 if (hasRequiredMs) return ms;
216 hasRequiredMs = 1;
217 var s = 1000;
218 var m = s * 60;
219 var h = m * 60;
220 var d = h * 24;
221 var w = d * 7;
222 var y = d * 365.25;
223
224 /**
225 * Parse or format the given `val`.
226 *
227 * Options:
228 *
229 * - `long` verbose formatting [false]
230 *
231 * @param {String|Number} val
232 * @param {Object} [options]
233 * @throws {Error} throw an error if val is not a non-empty string or a number
234 * @return {String|Number}
235 * @api public
236 */
237
238 ms = function(val, options) {
239 options = options || {};
240 var type = typeof val;
241 if (type === 'string' && val.length > 0) {
242 return parse(val);
243 } else if (type === 'number' && isFinite(val)) {
244 return options.long ? fmtLong(val) : fmtShort(val);
245 }
246 throw new Error(
247 'val is not a non-empty string or a valid number. val=' +
248 JSON.stringify(val)
249 );
250 };
251
252 /**
253 * Parse the given `str` and return milliseconds.
254 *
255 * @param {String} str
256 * @return {Number}
257 * @api private
258 */
259
260 function parse(str) {
261 str = String(str);
262 if (str.length > 100) {
263 return;
264 }
265 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
266 str
267 );
268 if (!match) {
269 return;
270 }
271 var n = parseFloat(match[1]);
272 var type = (match[2] || 'ms').toLowerCase();
273 switch (type) {
274 case 'years':
275 case 'year':
276 case 'yrs':
277 case 'yr':
278 case 'y':
279 return n * y;
280 case 'weeks':
281 case 'week':
282 case 'w':
283 return n * w;
284 case 'days':
285 case 'day':
286 case 'd':
287 return n * d;
288 case 'hours':
289 case 'hour':
290 case 'hrs':
291 case 'hr':
292 case 'h':
293 return n * h;
294 case 'minutes':
295 case 'minute':
296 case 'mins':
297 case 'min':
298 case 'm':
299 return n * m;
300 case 'seconds':
301 case 'second':
302 case 'secs':
303 case 'sec':
304 case 's':
305 return n * s;
306 case 'milliseconds':
307 case 'millisecond':
308 case 'msecs':
309 case 'msec':
310 case 'ms':
311 return n;
312 default:
313 return undefined;
314 }
315 }
316
317 /**
318 * Short format for `ms`.
319 *
320 * @param {Number} ms
321 * @return {String}
322 * @api private
323 */
324
325 function fmtShort(ms) {
326 var msAbs = Math.abs(ms);
327 if (msAbs >= d) {
328 return Math.round(ms / d) + 'd';
329 }
330 if (msAbs >= h) {
331 return Math.round(ms / h) + 'h';
332 }
333 if (msAbs >= m) {
334 return Math.round(ms / m) + 'm';
335 }
336 if (msAbs >= s) {
337 return Math.round(ms / s) + 's';
338 }
339 return ms + 'ms';
340 }
341
342 /**
343 * Long format for `ms`.
344 *
345 * @param {Number} ms
346 * @return {String}
347 * @api private
348 */
349
350 function fmtLong(ms) {
351 var msAbs = Math.abs(ms);
352 if (msAbs >= d) {
353 return plural(ms, msAbs, d, 'day');
354 }
355 if (msAbs >= h) {
356 return plural(ms, msAbs, h, 'hour');
357 }
358 if (msAbs >= m) {
359 return plural(ms, msAbs, m, 'minute');
360 }
361 if (msAbs >= s) {
362 return plural(ms, msAbs, s, 'second');
363 }
364 return ms + ' ms';
365 }
366
367 /**
368 * Pluralization helper.
369 */
370
371 function plural(ms, msAbs, n, name) {
372 var isPlural = msAbs >= n * 1.5;
373 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
374 }
375 return ms;
376}
377
378var common;
379var hasRequiredCommon;
380
381function requireCommon () {
382 if (hasRequiredCommon) return common;
383 hasRequiredCommon = 1;
384 /**
385 * This is the common logic for both the Node.js and web browser
386 * implementations of `debug()`.
387 */
388
389 function setup(env) {
390 createDebug.debug = createDebug;
391 createDebug.default = createDebug;
392 createDebug.coerce = coerce;
393 createDebug.disable = disable;
394 createDebug.enable = enable;
395 createDebug.enabled = enabled;
396 createDebug.humanize = requireMs();
397 createDebug.destroy = destroy;
398
399 Object.keys(env).forEach(key => {
400 createDebug[key] = env[key];
401 });
402
403 /**
404 * The currently active debug mode names, and names to skip.
405 */
406
407 createDebug.names = [];
408 createDebug.skips = [];
409
410 /**
411 * Map of special "%n" handling functions, for the debug "format" argument.
412 *
413 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
414 */
415 createDebug.formatters = {};
416
417 /**
418 * Selects a color for a debug namespace
419 * @param {String} namespace The namespace string for the debug instance to be colored
420 * @return {Number|String} An ANSI color code for the given namespace
421 * @api private
422 */
423 function selectColor(namespace) {
424 let hash = 0;
425
426 for (let i = 0; i < namespace.length; i++) {
427 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
428 hash |= 0; // Convert to 32bit integer
429 }
430
431 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
432 }
433 createDebug.selectColor = selectColor;
434
435 /**
436 * Create a debugger with the given `namespace`.
437 *
438 * @param {String} namespace
439 * @return {Function}
440 * @api public
441 */
442 function createDebug(namespace) {
443 let prevTime;
444 let enableOverride = null;
445 let namespacesCache;
446 let enabledCache;
447
448 function debug(...args) {
449 // Disabled?
450 if (!debug.enabled) {
451 return;
452 }
453
454 const self = debug;
455
456 // Set `diff` timestamp
457 const curr = Number(new Date());
458 const ms = curr - (prevTime || curr);
459 self.diff = ms;
460 self.prev = prevTime;
461 self.curr = curr;
462 prevTime = curr;
463
464 args[0] = createDebug.coerce(args[0]);
465
466 if (typeof args[0] !== 'string') {
467 // Anything else let's inspect with %O
468 args.unshift('%O');
469 }
470
471 // Apply any `formatters` transformations
472 let index = 0;
473 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
474 // If we encounter an escaped % then don't increase the array index
475 if (match === '%%') {
476 return '%';
477 }
478 index++;
479 const formatter = createDebug.formatters[format];
480 if (typeof formatter === 'function') {
481 const val = args[index];
482 match = formatter.call(self, val);
483
484 // Now we need to remove `args[index]` since it's inlined in the `format`
485 args.splice(index, 1);
486 index--;
487 }
488 return match;
489 });
490
491 // Apply env-specific formatting (colors, etc.)
492 createDebug.formatArgs.call(self, args);
493
494 const logFn = self.log || createDebug.log;
495 logFn.apply(self, args);
496 }
497
498 debug.namespace = namespace;
499 debug.useColors = createDebug.useColors();
500 debug.color = createDebug.selectColor(namespace);
501 debug.extend = extend;
502 debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
503
504 Object.defineProperty(debug, 'enabled', {
505 enumerable: true,
506 configurable: false,
507 get: () => {
508 if (enableOverride !== null) {
509 return enableOverride;
510 }
511 if (namespacesCache !== createDebug.namespaces) {
512 namespacesCache = createDebug.namespaces;
513 enabledCache = createDebug.enabled(namespace);
514 }
515
516 return enabledCache;
517 },
518 set: v => {
519 enableOverride = v;
520 }
521 });
522
523 // Env-specific initialization logic for debug instances
524 if (typeof createDebug.init === 'function') {
525 createDebug.init(debug);
526 }
527
528 return debug;
529 }
530
531 function extend(namespace, delimiter) {
532 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
533 newDebug.log = this.log;
534 return newDebug;
535 }
536
537 /**
538 * Enables a debug mode by namespaces. This can include modes
539 * separated by a colon and wildcards.
540 *
541 * @param {String} namespaces
542 * @api public
543 */
544 function enable(namespaces) {
545 createDebug.save(namespaces);
546 createDebug.namespaces = namespaces;
547
548 createDebug.names = [];
549 createDebug.skips = [];
550
551 let i;
552 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
553 const len = split.length;
554
555 for (i = 0; i < len; i++) {
556 if (!split[i]) {
557 // ignore empty strings
558 continue;
559 }
560
561 namespaces = split[i].replace(/\*/g, '.*?');
562
563 if (namespaces[0] === '-') {
564 createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
565 } else {
566 createDebug.names.push(new RegExp('^' + namespaces + '$'));
567 }
568 }
569 }
570
571 /**
572 * Disable debug output.
573 *
574 * @return {String} namespaces
575 * @api public
576 */
577 function disable() {
578 const namespaces = [
579 ...createDebug.names.map(toNamespace),
580 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
581 ].join(',');
582 createDebug.enable('');
583 return namespaces;
584 }
585
586 /**
587 * Returns true if the given mode name is enabled, false otherwise.
588 *
589 * @param {String} name
590 * @return {Boolean}
591 * @api public
592 */
593 function enabled(name) {
594 if (name[name.length - 1] === '*') {
595 return true;
596 }
597
598 let i;
599 let len;
600
601 for (i = 0, len = createDebug.skips.length; i < len; i++) {
602 if (createDebug.skips[i].test(name)) {
603 return false;
604 }
605 }
606
607 for (i = 0, len = createDebug.names.length; i < len; i++) {
608 if (createDebug.names[i].test(name)) {
609 return true;
610 }
611 }
612
613 return false;
614 }
615
616 /**
617 * Convert regexp to namespace
618 *
619 * @param {RegExp} regxep
620 * @return {String} namespace
621 * @api private
622 */
623 function toNamespace(regexp) {
624 return regexp.toString()
625 .substring(2, regexp.toString().length - 2)
626 .replace(/\.\*\?$/, '*');
627 }
628
629 /**
630 * Coerce `val`.
631 *
632 * @param {Mixed} val
633 * @return {Mixed}
634 * @api private
635 */
636 function coerce(val) {
637 if (val instanceof Error) {
638 return val.stack || val.message;
639 }
640 return val;
641 }
642
643 /**
644 * XXX DO NOT USE. This is a temporary stub function.
645 * XXX It WILL be removed in the next major release.
646 */
647 function destroy() {
648 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
649 }
650
651 createDebug.enable(createDebug.load());
652
653 return createDebug;
654 }
655
656 common = setup;
657 return common;
658}
659
660/* eslint-env browser */
661
662var hasRequiredBrowser;
663
664function requireBrowser () {
665 if (hasRequiredBrowser) return browser$1.exports;
666 hasRequiredBrowser = 1;
667 (function (module, exports) {
668 /**
669 * This is the web browser implementation of `debug()`.
670 */
671
672 exports.formatArgs = formatArgs;
673 exports.save = save;
674 exports.load = load;
675 exports.useColors = useColors;
676 exports.storage = localstorage();
677 exports.destroy = (() => {
678 let warned = false;
679
680 return () => {
681 if (!warned) {
682 warned = true;
683 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
684 }
685 };
686 })();
687
688 /**
689 * Colors.
690 */
691
692 exports.colors = [
693 '#0000CC',
694 '#0000FF',
695 '#0033CC',
696 '#0033FF',
697 '#0066CC',
698 '#0066FF',
699 '#0099CC',
700 '#0099FF',
701 '#00CC00',
702 '#00CC33',
703 '#00CC66',
704 '#00CC99',
705 '#00CCCC',
706 '#00CCFF',
707 '#3300CC',
708 '#3300FF',
709 '#3333CC',
710 '#3333FF',
711 '#3366CC',
712 '#3366FF',
713 '#3399CC',
714 '#3399FF',
715 '#33CC00',
716 '#33CC33',
717 '#33CC66',
718 '#33CC99',
719 '#33CCCC',
720 '#33CCFF',
721 '#6600CC',
722 '#6600FF',
723 '#6633CC',
724 '#6633FF',
725 '#66CC00',
726 '#66CC33',
727 '#9900CC',
728 '#9900FF',
729 '#9933CC',
730 '#9933FF',
731 '#99CC00',
732 '#99CC33',
733 '#CC0000',
734 '#CC0033',
735 '#CC0066',
736 '#CC0099',
737 '#CC00CC',
738 '#CC00FF',
739 '#CC3300',
740 '#CC3333',
741 '#CC3366',
742 '#CC3399',
743 '#CC33CC',
744 '#CC33FF',
745 '#CC6600',
746 '#CC6633',
747 '#CC9900',
748 '#CC9933',
749 '#CCCC00',
750 '#CCCC33',
751 '#FF0000',
752 '#FF0033',
753 '#FF0066',
754 '#FF0099',
755 '#FF00CC',
756 '#FF00FF',
757 '#FF3300',
758 '#FF3333',
759 '#FF3366',
760 '#FF3399',
761 '#FF33CC',
762 '#FF33FF',
763 '#FF6600',
764 '#FF6633',
765 '#FF9900',
766 '#FF9933',
767 '#FFCC00',
768 '#FFCC33'
769 ];
770
771 /**
772 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
773 * and the Firebug extension (any Firefox version) are known
774 * to support "%c" CSS customizations.
775 *
776 * TODO: add a `localStorage` variable to explicitly enable/disable colors
777 */
778
779 // eslint-disable-next-line complexity
780 function useColors() {
781 // NB: In an Electron preload script, document will be defined but not fully
782 // initialized. Since we know we're in Chrome, we'll just detect this case
783 // explicitly
784 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
785 return true;
786 }
787
788 // Internet Explorer and Edge do not support colors.
789 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
790 return false;
791 }
792
793 let m;
794
795 // Is webkit? http://stackoverflow.com/a/16459606/376773
796 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
797 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
798 // Is firebug? http://stackoverflow.com/a/398120/376773
799 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
800 // Is firefox >= v31?
801 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
802 (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
803 // Double check webkit in userAgent just in case we are in a worker
804 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
805 }
806
807 /**
808 * Colorize log arguments if enabled.
809 *
810 * @api public
811 */
812
813 function formatArgs(args) {
814 args[0] = (this.useColors ? '%c' : '') +
815 this.namespace +
816 (this.useColors ? ' %c' : ' ') +
817 args[0] +
818 (this.useColors ? '%c ' : ' ') +
819 '+' + module.exports.humanize(this.diff);
820
821 if (!this.useColors) {
822 return;
823 }
824
825 const c = 'color: ' + this.color;
826 args.splice(1, 0, c, 'color: inherit');
827
828 // The final "%c" is somewhat tricky, because there could be other
829 // arguments passed either before or after the %c, so we need to
830 // figure out the correct index to insert the CSS into
831 let index = 0;
832 let lastC = 0;
833 args[0].replace(/%[a-zA-Z%]/g, match => {
834 if (match === '%%') {
835 return;
836 }
837 index++;
838 if (match === '%c') {
839 // We only are interested in the *last* %c
840 // (the user may have provided their own)
841 lastC = index;
842 }
843 });
844
845 args.splice(lastC, 0, c);
846 }
847
848 /**
849 * Invokes `console.debug()` when available.
850 * No-op when `console.debug` is not a "function".
851 * If `console.debug` is not available, falls back
852 * to `console.log`.
853 *
854 * @api public
855 */
856 exports.log = console.debug || console.log || (() => {});
857
858 /**
859 * Save `namespaces`.
860 *
861 * @param {String} namespaces
862 * @api private
863 */
864 function save(namespaces) {
865 try {
866 if (namespaces) {
867 exports.storage.setItem('debug', namespaces);
868 } else {
869 exports.storage.removeItem('debug');
870 }
871 } catch (error) {
872 // Swallow
873 // XXX (@Qix-) should we be logging these?
874 }
875 }
876
877 /**
878 * Load `namespaces`.
879 *
880 * @return {String} returns the previously persisted debug modes
881 * @api private
882 */
883 function load() {
884 let r;
885 try {
886 r = exports.storage.getItem('debug');
887 } catch (error) {
888 // Swallow
889 // XXX (@Qix-) should we be logging these?
890 }
891
892 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
893 if (!r && typeof process !== 'undefined' && 'env' in process) {
894 r = process.env.DEBUG;
895 }
896
897 return r;
898 }
899
900 /**
901 * Localstorage attempts to return the localstorage.
902 *
903 * This is necessary because safari throws
904 * when a user disables cookies/localstorage
905 * and you attempt to access it.
906 *
907 * @return {LocalStorage}
908 * @api private
909 */
910
911 function localstorage() {
912 try {
913 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
914 // The Browser also has localStorage in the global context.
915 return localStorage;
916 } catch (error) {
917 // Swallow
918 // XXX (@Qix-) should we be logging these?
919 }
920 }
921
922 module.exports = requireCommon()(exports);
923
924 const {formatters} = module.exports;
925
926 /**
927 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
928 */
929
930 formatters.j = function (v) {
931 try {
932 return JSON.stringify(v);
933 } catch (error) {
934 return '[UnexpectedJSONParseError]: ' + error.message;
935 }
936 };
937 } (browser$1, browser$1.exports));
938 return browser$1.exports;
939}
940
941var node = {exports: {}};
942
943/**
944 * Module dependencies.
945 */
946
947var hasRequiredNode;
948
949function requireNode () {
950 if (hasRequiredNode) return node.exports;
951 hasRequiredNode = 1;
952 (function (module, exports) {
953 const tty = require$$0;
954 const util = require$$1;
955
956 /**
957 * This is the Node.js implementation of `debug()`.
958 */
959
960 exports.init = init;
961 exports.log = log;
962 exports.formatArgs = formatArgs;
963 exports.save = save;
964 exports.load = load;
965 exports.useColors = useColors;
966 exports.destroy = util.deprecate(
967 () => {},
968 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
969 );
970
971 /**
972 * Colors.
973 */
974
975 exports.colors = [6, 2, 3, 4, 5, 1];
976
977 try {
978 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
979 // eslint-disable-next-line import/no-extraneous-dependencies
980 const supportsColor = require('supports-color');
981
982 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
983 exports.colors = [
984 20,
985 21,
986 26,
987 27,
988 32,
989 33,
990 38,
991 39,
992 40,
993 41,
994 42,
995 43,
996 44,
997 45,
998 56,
999 57,
1000 62,
1001 63,
1002 68,
1003 69,
1004 74,
1005 75,
1006 76,
1007 77,
1008 78,
1009 79,
1010 80,
1011 81,
1012 92,
1013 93,
1014 98,
1015 99,
1016 112,
1017 113,
1018 128,
1019 129,
1020 134,
1021 135,
1022 148,
1023 149,
1024 160,
1025 161,
1026 162,
1027 163,
1028 164,
1029 165,
1030 166,
1031 167,
1032 168,
1033 169,
1034 170,
1035 171,
1036 172,
1037 173,
1038 178,
1039 179,
1040 184,
1041 185,
1042 196,
1043 197,
1044 198,
1045 199,
1046 200,
1047 201,
1048 202,
1049 203,
1050 204,
1051 205,
1052 206,
1053 207,
1054 208,
1055 209,
1056 214,
1057 215,
1058 220,
1059 221
1060 ];
1061 }
1062 } catch (error) {
1063 // Swallow - we only care if `supports-color` is available; it doesn't have to be.
1064 }
1065
1066 /**
1067 * Build up the default `inspectOpts` object from the environment variables.
1068 *
1069 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
1070 */
1071
1072 exports.inspectOpts = Object.keys(process.env).filter(key => {
1073 return /^debug_/i.test(key);
1074 }).reduce((obj, key) => {
1075 // Camel-case
1076 const prop = key
1077 .substring(6)
1078 .toLowerCase()
1079 .replace(/_([a-z])/g, (_, k) => {
1080 return k.toUpperCase();
1081 });
1082
1083 // Coerce string value into JS value
1084 let val = process.env[key];
1085 if (/^(yes|on|true|enabled)$/i.test(val)) {
1086 val = true;
1087 } else if (/^(no|off|false|disabled)$/i.test(val)) {
1088 val = false;
1089 } else if (val === 'null') {
1090 val = null;
1091 } else {
1092 val = Number(val);
1093 }
1094
1095 obj[prop] = val;
1096 return obj;
1097 }, {});
1098
1099 /**
1100 * Is stdout a TTY? Colored output is enabled when `true`.
1101 */
1102
1103 function useColors() {
1104 return 'colors' in exports.inspectOpts ?
1105 Boolean(exports.inspectOpts.colors) :
1106 tty.isatty(process.stderr.fd);
1107 }
1108
1109 /**
1110 * Adds ANSI color escape codes if enabled.
1111 *
1112 * @api public
1113 */
1114
1115 function formatArgs(args) {
1116 const {namespace: name, useColors} = this;
1117
1118 if (useColors) {
1119 const c = this.color;
1120 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
1121 const prefix = ` ${colorCode};1m${name} \u001B[0m`;
1122
1123 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
1124 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
1125 } else {
1126 args[0] = getDate() + name + ' ' + args[0];
1127 }
1128 }
1129
1130 function getDate() {
1131 if (exports.inspectOpts.hideDate) {
1132 return '';
1133 }
1134 return new Date().toISOString() + ' ';
1135 }
1136
1137 /**
1138 * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.
1139 */
1140
1141 function log(...args) {
1142 return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n');
1143 }
1144
1145 /**
1146 * Save `namespaces`.
1147 *
1148 * @param {String} namespaces
1149 * @api private
1150 */
1151 function save(namespaces) {
1152 if (namespaces) {
1153 process.env.DEBUG = namespaces;
1154 } else {
1155 // If you set a process.env field to null or undefined, it gets cast to the
1156 // string 'null' or 'undefined'. Just delete instead.
1157 delete process.env.DEBUG;
1158 }
1159 }
1160
1161 /**
1162 * Load `namespaces`.
1163 *
1164 * @return {String} returns the previously persisted debug modes
1165 * @api private
1166 */
1167
1168 function load() {
1169 return process.env.DEBUG;
1170 }
1171
1172 /**
1173 * Init logic for `debug` instances.
1174 *
1175 * Create a new `inspectOpts` object in case `useColors` is set
1176 * differently for a particular `debug` instance.
1177 */
1178
1179 function init(debug) {
1180 debug.inspectOpts = {};
1181
1182 const keys = Object.keys(exports.inspectOpts);
1183 for (let i = 0; i < keys.length; i++) {
1184 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
1185 }
1186 }
1187
1188 module.exports = requireCommon()(exports);
1189
1190 const {formatters} = module.exports;
1191
1192 /**
1193 * Map %o to `util.inspect()`, all on a single line.
1194 */
1195
1196 formatters.o = function (v) {
1197 this.inspectOpts.colors = this.useColors;
1198 return util.inspect(v, this.inspectOpts)
1199 .split('\n')
1200 .map(str => str.trim())
1201 .join(' ');
1202 };
1203
1204 /**
1205 * Map %O to `util.inspect()`, allowing multiple lines if needed.
1206 */
1207
1208 formatters.O = function (v) {
1209 this.inspectOpts.colors = this.useColors;
1210 return util.inspect(v, this.inspectOpts);
1211 };
1212 } (node, node.exports));
1213 return node.exports;
1214}
1215
1216/**
1217 * Detect Electron renderer / nwjs process, which is node, but we should
1218 * treat as a browser.
1219 */
1220
1221if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
1222 src.exports = requireBrowser();
1223} else {
1224 src.exports = requireNode();
1225}
1226
1227var srcExports = src.exports;
1228var debug$2 = /*@__PURE__*/getDefaultExportFromCjs(srcExports);
1229
1230var utils$3 = {};
1231
1232const path$2 = require$$0$1;
1233const WIN_SLASH = '\\\\/';
1234const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
1235
1236/**
1237 * Posix glob regex
1238 */
1239
1240const DOT_LITERAL = '\\.';
1241const PLUS_LITERAL = '\\+';
1242const QMARK_LITERAL = '\\?';
1243const SLASH_LITERAL = '\\/';
1244const ONE_CHAR = '(?=.)';
1245const QMARK = '[^/]';
1246const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
1247const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
1248const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
1249const NO_DOT = `(?!${DOT_LITERAL})`;
1250const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
1251const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
1252const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
1253const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
1254const STAR = `${QMARK}*?`;
1255
1256const POSIX_CHARS = {
1257 DOT_LITERAL,
1258 PLUS_LITERAL,
1259 QMARK_LITERAL,
1260 SLASH_LITERAL,
1261 ONE_CHAR,
1262 QMARK,
1263 END_ANCHOR,
1264 DOTS_SLASH,
1265 NO_DOT,
1266 NO_DOTS,
1267 NO_DOT_SLASH,
1268 NO_DOTS_SLASH,
1269 QMARK_NO_DOT,
1270 STAR,
1271 START_ANCHOR
1272};
1273
1274/**
1275 * Windows glob regex
1276 */
1277
1278const WINDOWS_CHARS = {
1279 ...POSIX_CHARS,
1280
1281 SLASH_LITERAL: `[${WIN_SLASH}]`,
1282 QMARK: WIN_NO_SLASH,
1283 STAR: `${WIN_NO_SLASH}*?`,
1284 DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
1285 NO_DOT: `(?!${DOT_LITERAL})`,
1286 NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
1287 NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
1288 NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
1289 QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
1290 START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
1291 END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
1292};
1293
1294/**
1295 * POSIX Bracket Regex
1296 */
1297
1298const POSIX_REGEX_SOURCE$1 = {
1299 alnum: 'a-zA-Z0-9',
1300 alpha: 'a-zA-Z',
1301 ascii: '\\x00-\\x7F',
1302 blank: ' \\t',
1303 cntrl: '\\x00-\\x1F\\x7F',
1304 digit: '0-9',
1305 graph: '\\x21-\\x7E',
1306 lower: 'a-z',
1307 print: '\\x20-\\x7E ',
1308 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
1309 space: ' \\t\\r\\n\\v\\f',
1310 upper: 'A-Z',
1311 word: 'A-Za-z0-9_',
1312 xdigit: 'A-Fa-f0-9'
1313};
1314
1315var constants$2 = {
1316 MAX_LENGTH: 1024 * 64,
1317 POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
1318
1319 // regular expressions
1320 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
1321 REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
1322 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
1323 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
1324 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
1325 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
1326
1327 // Replace globs with equivalent patterns to reduce parsing time.
1328 REPLACEMENTS: {
1329 '***': '*',
1330 '**/**': '**',
1331 '**/**/**': '**'
1332 },
1333
1334 // Digits
1335 CHAR_0: 48, /* 0 */
1336 CHAR_9: 57, /* 9 */
1337
1338 // Alphabet chars.
1339 CHAR_UPPERCASE_A: 65, /* A */
1340 CHAR_LOWERCASE_A: 97, /* a */
1341 CHAR_UPPERCASE_Z: 90, /* Z */
1342 CHAR_LOWERCASE_Z: 122, /* z */
1343
1344 CHAR_LEFT_PARENTHESES: 40, /* ( */
1345 CHAR_RIGHT_PARENTHESES: 41, /* ) */
1346
1347 CHAR_ASTERISK: 42, /* * */
1348
1349 // Non-alphabetic chars.
1350 CHAR_AMPERSAND: 38, /* & */
1351 CHAR_AT: 64, /* @ */
1352 CHAR_BACKWARD_SLASH: 92, /* \ */
1353 CHAR_CARRIAGE_RETURN: 13, /* \r */
1354 CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
1355 CHAR_COLON: 58, /* : */
1356 CHAR_COMMA: 44, /* , */
1357 CHAR_DOT: 46, /* . */
1358 CHAR_DOUBLE_QUOTE: 34, /* " */
1359 CHAR_EQUAL: 61, /* = */
1360 CHAR_EXCLAMATION_MARK: 33, /* ! */
1361 CHAR_FORM_FEED: 12, /* \f */
1362 CHAR_FORWARD_SLASH: 47, /* / */
1363 CHAR_GRAVE_ACCENT: 96, /* ` */
1364 CHAR_HASH: 35, /* # */
1365 CHAR_HYPHEN_MINUS: 45, /* - */
1366 CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
1367 CHAR_LEFT_CURLY_BRACE: 123, /* { */
1368 CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
1369 CHAR_LINE_FEED: 10, /* \n */
1370 CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
1371 CHAR_PERCENT: 37, /* % */
1372 CHAR_PLUS: 43, /* + */
1373 CHAR_QUESTION_MARK: 63, /* ? */
1374 CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
1375 CHAR_RIGHT_CURLY_BRACE: 125, /* } */
1376 CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
1377 CHAR_SEMICOLON: 59, /* ; */
1378 CHAR_SINGLE_QUOTE: 39, /* ' */
1379 CHAR_SPACE: 32, /* */
1380 CHAR_TAB: 9, /* \t */
1381 CHAR_UNDERSCORE: 95, /* _ */
1382 CHAR_VERTICAL_LINE: 124, /* | */
1383 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
1384
1385 SEP: path$2.sep,
1386
1387 /**
1388 * Create EXTGLOB_CHARS
1389 */
1390
1391 extglobChars(chars) {
1392 return {
1393 '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
1394 '?': { type: 'qmark', open: '(?:', close: ')?' },
1395 '+': { type: 'plus', open: '(?:', close: ')+' },
1396 '*': { type: 'star', open: '(?:', close: ')*' },
1397 '@': { type: 'at', open: '(?:', close: ')' }
1398 };
1399 },
1400
1401 /**
1402 * Create GLOB_CHARS
1403 */
1404
1405 globChars(win32) {
1406 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
1407 }
1408};
1409
1410(function (exports) {
1411
1412 const path = require$$0$1;
1413 const win32 = process.platform === 'win32';
1414 const {
1415 REGEX_BACKSLASH,
1416 REGEX_REMOVE_BACKSLASH,
1417 REGEX_SPECIAL_CHARS,
1418 REGEX_SPECIAL_CHARS_GLOBAL
1419 } = constants$2;
1420
1421 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
1422 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
1423 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
1424 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
1425 exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
1426
1427 exports.removeBackslashes = str => {
1428 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
1429 return match === '\\' ? '' : match;
1430 });
1431 };
1432
1433 exports.supportsLookbehinds = () => {
1434 const segs = process.version.slice(1).split('.').map(Number);
1435 if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
1436 return true;
1437 }
1438 return false;
1439 };
1440
1441 exports.isWindows = options => {
1442 if (options && typeof options.windows === 'boolean') {
1443 return options.windows;
1444 }
1445 return win32 === true || path.sep === '\\';
1446 };
1447
1448 exports.escapeLast = (input, char, lastIdx) => {
1449 const idx = input.lastIndexOf(char, lastIdx);
1450 if (idx === -1) return input;
1451 if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
1452 return `${input.slice(0, idx)}\\${input.slice(idx)}`;
1453 };
1454
1455 exports.removePrefix = (input, state = {}) => {
1456 let output = input;
1457 if (output.startsWith('./')) {
1458 output = output.slice(2);
1459 state.prefix = './';
1460 }
1461 return output;
1462 };
1463
1464 exports.wrapOutput = (input, state = {}, options = {}) => {
1465 const prepend = options.contains ? '' : '^';
1466 const append = options.contains ? '' : '$';
1467
1468 let output = `${prepend}(?:${input})${append}`;
1469 if (state.negated === true) {
1470 output = `(?:^(?!${output}).*$)`;
1471 }
1472 return output;
1473 };
1474} (utils$3));
1475
1476const utils$2 = utils$3;
1477const {
1478 CHAR_ASTERISK, /* * */
1479 CHAR_AT, /* @ */
1480 CHAR_BACKWARD_SLASH, /* \ */
1481 CHAR_COMMA, /* , */
1482 CHAR_DOT, /* . */
1483 CHAR_EXCLAMATION_MARK, /* ! */
1484 CHAR_FORWARD_SLASH, /* / */
1485 CHAR_LEFT_CURLY_BRACE, /* { */
1486 CHAR_LEFT_PARENTHESES, /* ( */
1487 CHAR_LEFT_SQUARE_BRACKET, /* [ */
1488 CHAR_PLUS, /* + */
1489 CHAR_QUESTION_MARK, /* ? */
1490 CHAR_RIGHT_CURLY_BRACE, /* } */
1491 CHAR_RIGHT_PARENTHESES, /* ) */
1492 CHAR_RIGHT_SQUARE_BRACKET /* ] */
1493} = constants$2;
1494
1495const isPathSeparator = code => {
1496 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
1497};
1498
1499const depth = token => {
1500 if (token.isPrefix !== true) {
1501 token.depth = token.isGlobstar ? Infinity : 1;
1502 }
1503};
1504
1505/**
1506 * Quickly scans a glob pattern and returns an object with a handful of
1507 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
1508 * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
1509 * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
1510 *
1511 * ```js
1512 * const pm = require('picomatch');
1513 * console.log(pm.scan('foo/bar/*.js'));
1514 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
1515 * ```
1516 * @param {String} `str`
1517 * @param {Object} `options`
1518 * @return {Object} Returns an object with tokens and regex source string.
1519 * @api public
1520 */
1521
1522const scan$1 = (input, options) => {
1523 const opts = options || {};
1524
1525 const length = input.length - 1;
1526 const scanToEnd = opts.parts === true || opts.scanToEnd === true;
1527 const slashes = [];
1528 const tokens = [];
1529 const parts = [];
1530
1531 let str = input;
1532 let index = -1;
1533 let start = 0;
1534 let lastIndex = 0;
1535 let isBrace = false;
1536 let isBracket = false;
1537 let isGlob = false;
1538 let isExtglob = false;
1539 let isGlobstar = false;
1540 let braceEscaped = false;
1541 let backslashes = false;
1542 let negated = false;
1543 let negatedExtglob = false;
1544 let finished = false;
1545 let braces = 0;
1546 let prev;
1547 let code;
1548 let token = { value: '', depth: 0, isGlob: false };
1549
1550 const eos = () => index >= length;
1551 const peek = () => str.charCodeAt(index + 1);
1552 const advance = () => {
1553 prev = code;
1554 return str.charCodeAt(++index);
1555 };
1556
1557 while (index < length) {
1558 code = advance();
1559 let next;
1560
1561 if (code === CHAR_BACKWARD_SLASH) {
1562 backslashes = token.backslashes = true;
1563 code = advance();
1564
1565 if (code === CHAR_LEFT_CURLY_BRACE) {
1566 braceEscaped = true;
1567 }
1568 continue;
1569 }
1570
1571 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
1572 braces++;
1573
1574 while (eos() !== true && (code = advance())) {
1575 if (code === CHAR_BACKWARD_SLASH) {
1576 backslashes = token.backslashes = true;
1577 advance();
1578 continue;
1579 }
1580
1581 if (code === CHAR_LEFT_CURLY_BRACE) {
1582 braces++;
1583 continue;
1584 }
1585
1586 if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
1587 isBrace = token.isBrace = true;
1588 isGlob = token.isGlob = true;
1589 finished = true;
1590
1591 if (scanToEnd === true) {
1592 continue;
1593 }
1594
1595 break;
1596 }
1597
1598 if (braceEscaped !== true && code === CHAR_COMMA) {
1599 isBrace = token.isBrace = true;
1600 isGlob = token.isGlob = true;
1601 finished = true;
1602
1603 if (scanToEnd === true) {
1604 continue;
1605 }
1606
1607 break;
1608 }
1609
1610 if (code === CHAR_RIGHT_CURLY_BRACE) {
1611 braces--;
1612
1613 if (braces === 0) {
1614 braceEscaped = false;
1615 isBrace = token.isBrace = true;
1616 finished = true;
1617 break;
1618 }
1619 }
1620 }
1621
1622 if (scanToEnd === true) {
1623 continue;
1624 }
1625
1626 break;
1627 }
1628
1629 if (code === CHAR_FORWARD_SLASH) {
1630 slashes.push(index);
1631 tokens.push(token);
1632 token = { value: '', depth: 0, isGlob: false };
1633
1634 if (finished === true) continue;
1635 if (prev === CHAR_DOT && index === (start + 1)) {
1636 start += 2;
1637 continue;
1638 }
1639
1640 lastIndex = index + 1;
1641 continue;
1642 }
1643
1644 if (opts.noext !== true) {
1645 const isExtglobChar = code === CHAR_PLUS
1646 || code === CHAR_AT
1647 || code === CHAR_ASTERISK
1648 || code === CHAR_QUESTION_MARK
1649 || code === CHAR_EXCLAMATION_MARK;
1650
1651 if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
1652 isGlob = token.isGlob = true;
1653 isExtglob = token.isExtglob = true;
1654 finished = true;
1655 if (code === CHAR_EXCLAMATION_MARK && index === start) {
1656 negatedExtglob = true;
1657 }
1658
1659 if (scanToEnd === true) {
1660 while (eos() !== true && (code = advance())) {
1661 if (code === CHAR_BACKWARD_SLASH) {
1662 backslashes = token.backslashes = true;
1663 code = advance();
1664 continue;
1665 }
1666
1667 if (code === CHAR_RIGHT_PARENTHESES) {
1668 isGlob = token.isGlob = true;
1669 finished = true;
1670 break;
1671 }
1672 }
1673 continue;
1674 }
1675 break;
1676 }
1677 }
1678
1679 if (code === CHAR_ASTERISK) {
1680 if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
1681 isGlob = token.isGlob = true;
1682 finished = true;
1683
1684 if (scanToEnd === true) {
1685 continue;
1686 }
1687 break;
1688 }
1689
1690 if (code === CHAR_QUESTION_MARK) {
1691 isGlob = token.isGlob = true;
1692 finished = true;
1693
1694 if (scanToEnd === true) {
1695 continue;
1696 }
1697 break;
1698 }
1699
1700 if (code === CHAR_LEFT_SQUARE_BRACKET) {
1701 while (eos() !== true && (next = advance())) {
1702 if (next === CHAR_BACKWARD_SLASH) {
1703 backslashes = token.backslashes = true;
1704 advance();
1705 continue;
1706 }
1707
1708 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
1709 isBracket = token.isBracket = true;
1710 isGlob = token.isGlob = true;
1711 finished = true;
1712 break;
1713 }
1714 }
1715
1716 if (scanToEnd === true) {
1717 continue;
1718 }
1719
1720 break;
1721 }
1722
1723 if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
1724 negated = token.negated = true;
1725 start++;
1726 continue;
1727 }
1728
1729 if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
1730 isGlob = token.isGlob = true;
1731
1732 if (scanToEnd === true) {
1733 while (eos() !== true && (code = advance())) {
1734 if (code === CHAR_LEFT_PARENTHESES) {
1735 backslashes = token.backslashes = true;
1736 code = advance();
1737 continue;
1738 }
1739
1740 if (code === CHAR_RIGHT_PARENTHESES) {
1741 finished = true;
1742 break;
1743 }
1744 }
1745 continue;
1746 }
1747 break;
1748 }
1749
1750 if (isGlob === true) {
1751 finished = true;
1752
1753 if (scanToEnd === true) {
1754 continue;
1755 }
1756
1757 break;
1758 }
1759 }
1760
1761 if (opts.noext === true) {
1762 isExtglob = false;
1763 isGlob = false;
1764 }
1765
1766 let base = str;
1767 let prefix = '';
1768 let glob = '';
1769
1770 if (start > 0) {
1771 prefix = str.slice(0, start);
1772 str = str.slice(start);
1773 lastIndex -= start;
1774 }
1775
1776 if (base && isGlob === true && lastIndex > 0) {
1777 base = str.slice(0, lastIndex);
1778 glob = str.slice(lastIndex);
1779 } else if (isGlob === true) {
1780 base = '';
1781 glob = str;
1782 } else {
1783 base = str;
1784 }
1785
1786 if (base && base !== '' && base !== '/' && base !== str) {
1787 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
1788 base = base.slice(0, -1);
1789 }
1790 }
1791
1792 if (opts.unescape === true) {
1793 if (glob) glob = utils$2.removeBackslashes(glob);
1794
1795 if (base && backslashes === true) {
1796 base = utils$2.removeBackslashes(base);
1797 }
1798 }
1799
1800 const state = {
1801 prefix,
1802 input,
1803 start,
1804 base,
1805 glob,
1806 isBrace,
1807 isBracket,
1808 isGlob,
1809 isExtglob,
1810 isGlobstar,
1811 negated,
1812 negatedExtglob
1813 };
1814
1815 if (opts.tokens === true) {
1816 state.maxDepth = 0;
1817 if (!isPathSeparator(code)) {
1818 tokens.push(token);
1819 }
1820 state.tokens = tokens;
1821 }
1822
1823 if (opts.parts === true || opts.tokens === true) {
1824 let prevIndex;
1825
1826 for (let idx = 0; idx < slashes.length; idx++) {
1827 const n = prevIndex ? prevIndex + 1 : start;
1828 const i = slashes[idx];
1829 const value = input.slice(n, i);
1830 if (opts.tokens) {
1831 if (idx === 0 && start !== 0) {
1832 tokens[idx].isPrefix = true;
1833 tokens[idx].value = prefix;
1834 } else {
1835 tokens[idx].value = value;
1836 }
1837 depth(tokens[idx]);
1838 state.maxDepth += tokens[idx].depth;
1839 }
1840 if (idx !== 0 || value !== '') {
1841 parts.push(value);
1842 }
1843 prevIndex = i;
1844 }
1845
1846 if (prevIndex && prevIndex + 1 < input.length) {
1847 const value = input.slice(prevIndex + 1);
1848 parts.push(value);
1849
1850 if (opts.tokens) {
1851 tokens[tokens.length - 1].value = value;
1852 depth(tokens[tokens.length - 1]);
1853 state.maxDepth += tokens[tokens.length - 1].depth;
1854 }
1855 }
1856
1857 state.slashes = slashes;
1858 state.parts = parts;
1859 }
1860
1861 return state;
1862};
1863
1864var scan_1 = scan$1;
1865
1866const constants$1 = constants$2;
1867const utils$1 = utils$3;
1868
1869/**
1870 * Constants
1871 */
1872
1873const {
1874 MAX_LENGTH,
1875 POSIX_REGEX_SOURCE,
1876 REGEX_NON_SPECIAL_CHARS,
1877 REGEX_SPECIAL_CHARS_BACKREF,
1878 REPLACEMENTS
1879} = constants$1;
1880
1881/**
1882 * Helpers
1883 */
1884
1885const expandRange = (args, options) => {
1886 if (typeof options.expandRange === 'function') {
1887 return options.expandRange(...args, options);
1888 }
1889
1890 args.sort();
1891 const value = `[${args.join('-')}]`;
1892
1893 return value;
1894};
1895
1896/**
1897 * Create the message for a syntax error
1898 */
1899
1900const syntaxError = (type, char) => {
1901 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
1902};
1903
1904/**
1905 * Parse the given input string.
1906 * @param {String} input
1907 * @param {Object} options
1908 * @return {Object}
1909 */
1910
1911const parse$2 = (input, options) => {
1912 if (typeof input !== 'string') {
1913 throw new TypeError('Expected a string');
1914 }
1915
1916 input = REPLACEMENTS[input] || input;
1917
1918 const opts = { ...options };
1919 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
1920
1921 let len = input.length;
1922 if (len > max) {
1923 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
1924 }
1925
1926 const bos = { type: 'bos', value: '', output: opts.prepend || '' };
1927 const tokens = [bos];
1928
1929 const capture = opts.capture ? '' : '?:';
1930 const win32 = utils$1.isWindows(options);
1931
1932 // create constants based on platform, for windows or posix
1933 const PLATFORM_CHARS = constants$1.globChars(win32);
1934 const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
1935
1936 const {
1937 DOT_LITERAL,
1938 PLUS_LITERAL,
1939 SLASH_LITERAL,
1940 ONE_CHAR,
1941 DOTS_SLASH,
1942 NO_DOT,
1943 NO_DOT_SLASH,
1944 NO_DOTS_SLASH,
1945 QMARK,
1946 QMARK_NO_DOT,
1947 STAR,
1948 START_ANCHOR
1949 } = PLATFORM_CHARS;
1950
1951 const globstar = opts => {
1952 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
1953 };
1954
1955 const nodot = opts.dot ? '' : NO_DOT;
1956 const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
1957 let star = opts.bash === true ? globstar(opts) : STAR;
1958
1959 if (opts.capture) {
1960 star = `(${star})`;
1961 }
1962
1963 // minimatch options support
1964 if (typeof opts.noext === 'boolean') {
1965 opts.noextglob = opts.noext;
1966 }
1967
1968 const state = {
1969 input,
1970 index: -1,
1971 start: 0,
1972 dot: opts.dot === true,
1973 consumed: '',
1974 output: '',
1975 prefix: '',
1976 backtrack: false,
1977 negated: false,
1978 brackets: 0,
1979 braces: 0,
1980 parens: 0,
1981 quotes: 0,
1982 globstar: false,
1983 tokens
1984 };
1985
1986 input = utils$1.removePrefix(input, state);
1987 len = input.length;
1988
1989 const extglobs = [];
1990 const braces = [];
1991 const stack = [];
1992 let prev = bos;
1993 let value;
1994
1995 /**
1996 * Tokenizing helpers
1997 */
1998
1999 const eos = () => state.index === len - 1;
2000 const peek = state.peek = (n = 1) => input[state.index + n];
2001 const advance = state.advance = () => input[++state.index] || '';
2002 const remaining = () => input.slice(state.index + 1);
2003 const consume = (value = '', num = 0) => {
2004 state.consumed += value;
2005 state.index += num;
2006 };
2007
2008 const append = token => {
2009 state.output += token.output != null ? token.output : token.value;
2010 consume(token.value);
2011 };
2012
2013 const negate = () => {
2014 let count = 1;
2015
2016 while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
2017 advance();
2018 state.start++;
2019 count++;
2020 }
2021
2022 if (count % 2 === 0) {
2023 return false;
2024 }
2025
2026 state.negated = true;
2027 state.start++;
2028 return true;
2029 };
2030
2031 const increment = type => {
2032 state[type]++;
2033 stack.push(type);
2034 };
2035
2036 const decrement = type => {
2037 state[type]--;
2038 stack.pop();
2039 };
2040
2041 /**
2042 * Push tokens onto the tokens array. This helper speeds up
2043 * tokenizing by 1) helping us avoid backtracking as much as possible,
2044 * and 2) helping us avoid creating extra tokens when consecutive
2045 * characters are plain text. This improves performance and simplifies
2046 * lookbehinds.
2047 */
2048
2049 const push = tok => {
2050 if (prev.type === 'globstar') {
2051 const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
2052 const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
2053
2054 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
2055 state.output = state.output.slice(0, -prev.output.length);
2056 prev.type = 'star';
2057 prev.value = '*';
2058 prev.output = star;
2059 state.output += prev.output;
2060 }
2061 }
2062
2063 if (extglobs.length && tok.type !== 'paren') {
2064 extglobs[extglobs.length - 1].inner += tok.value;
2065 }
2066
2067 if (tok.value || tok.output) append(tok);
2068 if (prev && prev.type === 'text' && tok.type === 'text') {
2069 prev.value += tok.value;
2070 prev.output = (prev.output || '') + tok.value;
2071 return;
2072 }
2073
2074 tok.prev = prev;
2075 tokens.push(tok);
2076 prev = tok;
2077 };
2078
2079 const extglobOpen = (type, value) => {
2080 const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
2081
2082 token.prev = prev;
2083 token.parens = state.parens;
2084 token.output = state.output;
2085 const output = (opts.capture ? '(' : '') + token.open;
2086
2087 increment('parens');
2088 push({ type, value, output: state.output ? '' : ONE_CHAR });
2089 push({ type: 'paren', extglob: true, value: advance(), output });
2090 extglobs.push(token);
2091 };
2092
2093 const extglobClose = token => {
2094 let output = token.close + (opts.capture ? ')' : '');
2095 let rest;
2096
2097 if (token.type === 'negate') {
2098 let extglobStar = star;
2099
2100 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
2101 extglobStar = globstar(opts);
2102 }
2103
2104 if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
2105 output = token.close = `)$))${extglobStar}`;
2106 }
2107
2108 if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
2109 // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
2110 // In this case, we need to parse the string and use it in the output of the original pattern.
2111 // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
2112 //
2113 // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
2114 const expression = parse$2(rest, { ...options, fastpaths: false }).output;
2115
2116 output = token.close = `)${expression})${extglobStar})`;
2117 }
2118
2119 if (token.prev.type === 'bos') {
2120 state.negatedExtglob = true;
2121 }
2122 }
2123
2124 push({ type: 'paren', extglob: true, value, output });
2125 decrement('parens');
2126 };
2127
2128 /**
2129 * Fast paths
2130 */
2131
2132 if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
2133 let backslashes = false;
2134
2135 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
2136 if (first === '\\') {
2137 backslashes = true;
2138 return m;
2139 }
2140
2141 if (first === '?') {
2142 if (esc) {
2143 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
2144 }
2145 if (index === 0) {
2146 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
2147 }
2148 return QMARK.repeat(chars.length);
2149 }
2150
2151 if (first === '.') {
2152 return DOT_LITERAL.repeat(chars.length);
2153 }
2154
2155 if (first === '*') {
2156 if (esc) {
2157 return esc + first + (rest ? star : '');
2158 }
2159 return star;
2160 }
2161 return esc ? m : `\\${m}`;
2162 });
2163
2164 if (backslashes === true) {
2165 if (opts.unescape === true) {
2166 output = output.replace(/\\/g, '');
2167 } else {
2168 output = output.replace(/\\+/g, m => {
2169 return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
2170 });
2171 }
2172 }
2173
2174 if (output === input && opts.contains === true) {
2175 state.output = input;
2176 return state;
2177 }
2178
2179 state.output = utils$1.wrapOutput(output, state, options);
2180 return state;
2181 }
2182
2183 /**
2184 * Tokenize input until we reach end-of-string
2185 */
2186
2187 while (!eos()) {
2188 value = advance();
2189
2190 if (value === '\u0000') {
2191 continue;
2192 }
2193
2194 /**
2195 * Escaped characters
2196 */
2197
2198 if (value === '\\') {
2199 const next = peek();
2200
2201 if (next === '/' && opts.bash !== true) {
2202 continue;
2203 }
2204
2205 if (next === '.' || next === ';') {
2206 continue;
2207 }
2208
2209 if (!next) {
2210 value += '\\';
2211 push({ type: 'text', value });
2212 continue;
2213 }
2214
2215 // collapse slashes to reduce potential for exploits
2216 const match = /^\\+/.exec(remaining());
2217 let slashes = 0;
2218
2219 if (match && match[0].length > 2) {
2220 slashes = match[0].length;
2221 state.index += slashes;
2222 if (slashes % 2 !== 0) {
2223 value += '\\';
2224 }
2225 }
2226
2227 if (opts.unescape === true) {
2228 value = advance();
2229 } else {
2230 value += advance();
2231 }
2232
2233 if (state.brackets === 0) {
2234 push({ type: 'text', value });
2235 continue;
2236 }
2237 }
2238
2239 /**
2240 * If we're inside a regex character class, continue
2241 * until we reach the closing bracket.
2242 */
2243
2244 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
2245 if (opts.posix !== false && value === ':') {
2246 const inner = prev.value.slice(1);
2247 if (inner.includes('[')) {
2248 prev.posix = true;
2249
2250 if (inner.includes(':')) {
2251 const idx = prev.value.lastIndexOf('[');
2252 const pre = prev.value.slice(0, idx);
2253 const rest = prev.value.slice(idx + 2);
2254 const posix = POSIX_REGEX_SOURCE[rest];
2255 if (posix) {
2256 prev.value = pre + posix;
2257 state.backtrack = true;
2258 advance();
2259
2260 if (!bos.output && tokens.indexOf(prev) === 1) {
2261 bos.output = ONE_CHAR;
2262 }
2263 continue;
2264 }
2265 }
2266 }
2267 }
2268
2269 if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
2270 value = `\\${value}`;
2271 }
2272
2273 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
2274 value = `\\${value}`;
2275 }
2276
2277 if (opts.posix === true && value === '!' && prev.value === '[') {
2278 value = '^';
2279 }
2280
2281 prev.value += value;
2282 append({ value });
2283 continue;
2284 }
2285
2286 /**
2287 * If we're inside a quoted string, continue
2288 * until we reach the closing double quote.
2289 */
2290
2291 if (state.quotes === 1 && value !== '"') {
2292 value = utils$1.escapeRegex(value);
2293 prev.value += value;
2294 append({ value });
2295 continue;
2296 }
2297
2298 /**
2299 * Double quotes
2300 */
2301
2302 if (value === '"') {
2303 state.quotes = state.quotes === 1 ? 0 : 1;
2304 if (opts.keepQuotes === true) {
2305 push({ type: 'text', value });
2306 }
2307 continue;
2308 }
2309
2310 /**
2311 * Parentheses
2312 */
2313
2314 if (value === '(') {
2315 increment('parens');
2316 push({ type: 'paren', value });
2317 continue;
2318 }
2319
2320 if (value === ')') {
2321 if (state.parens === 0 && opts.strictBrackets === true) {
2322 throw new SyntaxError(syntaxError('opening', '('));
2323 }
2324
2325 const extglob = extglobs[extglobs.length - 1];
2326 if (extglob && state.parens === extglob.parens + 1) {
2327 extglobClose(extglobs.pop());
2328 continue;
2329 }
2330
2331 push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
2332 decrement('parens');
2333 continue;
2334 }
2335
2336 /**
2337 * Square brackets
2338 */
2339
2340 if (value === '[') {
2341 if (opts.nobracket === true || !remaining().includes(']')) {
2342 if (opts.nobracket !== true && opts.strictBrackets === true) {
2343 throw new SyntaxError(syntaxError('closing', ']'));
2344 }
2345
2346 value = `\\${value}`;
2347 } else {
2348 increment('brackets');
2349 }
2350
2351 push({ type: 'bracket', value });
2352 continue;
2353 }
2354
2355 if (value === ']') {
2356 if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
2357 push({ type: 'text', value, output: `\\${value}` });
2358 continue;
2359 }
2360
2361 if (state.brackets === 0) {
2362 if (opts.strictBrackets === true) {
2363 throw new SyntaxError(syntaxError('opening', '['));
2364 }
2365
2366 push({ type: 'text', value, output: `\\${value}` });
2367 continue;
2368 }
2369
2370 decrement('brackets');
2371
2372 const prevValue = prev.value.slice(1);
2373 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
2374 value = `/${value}`;
2375 }
2376
2377 prev.value += value;
2378 append({ value });
2379
2380 // when literal brackets are explicitly disabled
2381 // assume we should match with a regex character class
2382 if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
2383 continue;
2384 }
2385
2386 const escaped = utils$1.escapeRegex(prev.value);
2387 state.output = state.output.slice(0, -prev.value.length);
2388
2389 // when literal brackets are explicitly enabled
2390 // assume we should escape the brackets to match literal characters
2391 if (opts.literalBrackets === true) {
2392 state.output += escaped;
2393 prev.value = escaped;
2394 continue;
2395 }
2396
2397 // when the user specifies nothing, try to match both
2398 prev.value = `(${capture}${escaped}|${prev.value})`;
2399 state.output += prev.value;
2400 continue;
2401 }
2402
2403 /**
2404 * Braces
2405 */
2406
2407 if (value === '{' && opts.nobrace !== true) {
2408 increment('braces');
2409
2410 const open = {
2411 type: 'brace',
2412 value,
2413 output: '(',
2414 outputIndex: state.output.length,
2415 tokensIndex: state.tokens.length
2416 };
2417
2418 braces.push(open);
2419 push(open);
2420 continue;
2421 }
2422
2423 if (value === '}') {
2424 const brace = braces[braces.length - 1];
2425
2426 if (opts.nobrace === true || !brace) {
2427 push({ type: 'text', value, output: value });
2428 continue;
2429 }
2430
2431 let output = ')';
2432
2433 if (brace.dots === true) {
2434 const arr = tokens.slice();
2435 const range = [];
2436
2437 for (let i = arr.length - 1; i >= 0; i--) {
2438 tokens.pop();
2439 if (arr[i].type === 'brace') {
2440 break;
2441 }
2442 if (arr[i].type !== 'dots') {
2443 range.unshift(arr[i].value);
2444 }
2445 }
2446
2447 output = expandRange(range, opts);
2448 state.backtrack = true;
2449 }
2450
2451 if (brace.comma !== true && brace.dots !== true) {
2452 const out = state.output.slice(0, brace.outputIndex);
2453 const toks = state.tokens.slice(brace.tokensIndex);
2454 brace.value = brace.output = '\\{';
2455 value = output = '\\}';
2456 state.output = out;
2457 for (const t of toks) {
2458 state.output += (t.output || t.value);
2459 }
2460 }
2461
2462 push({ type: 'brace', value, output });
2463 decrement('braces');
2464 braces.pop();
2465 continue;
2466 }
2467
2468 /**
2469 * Pipes
2470 */
2471
2472 if (value === '|') {
2473 if (extglobs.length > 0) {
2474 extglobs[extglobs.length - 1].conditions++;
2475 }
2476 push({ type: 'text', value });
2477 continue;
2478 }
2479
2480 /**
2481 * Commas
2482 */
2483
2484 if (value === ',') {
2485 let output = value;
2486
2487 const brace = braces[braces.length - 1];
2488 if (brace && stack[stack.length - 1] === 'braces') {
2489 brace.comma = true;
2490 output = '|';
2491 }
2492
2493 push({ type: 'comma', value, output });
2494 continue;
2495 }
2496
2497 /**
2498 * Slashes
2499 */
2500
2501 if (value === '/') {
2502 // if the beginning of the glob is "./", advance the start
2503 // to the current index, and don't add the "./" characters
2504 // to the state. This greatly simplifies lookbehinds when
2505 // checking for BOS characters like "!" and "." (not "./")
2506 if (prev.type === 'dot' && state.index === state.start + 1) {
2507 state.start = state.index + 1;
2508 state.consumed = '';
2509 state.output = '';
2510 tokens.pop();
2511 prev = bos; // reset "prev" to the first token
2512 continue;
2513 }
2514
2515 push({ type: 'slash', value, output: SLASH_LITERAL });
2516 continue;
2517 }
2518
2519 /**
2520 * Dots
2521 */
2522
2523 if (value === '.') {
2524 if (state.braces > 0 && prev.type === 'dot') {
2525 if (prev.value === '.') prev.output = DOT_LITERAL;
2526 const brace = braces[braces.length - 1];
2527 prev.type = 'dots';
2528 prev.output += value;
2529 prev.value += value;
2530 brace.dots = true;
2531 continue;
2532 }
2533
2534 if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
2535 push({ type: 'text', value, output: DOT_LITERAL });
2536 continue;
2537 }
2538
2539 push({ type: 'dot', value, output: DOT_LITERAL });
2540 continue;
2541 }
2542
2543 /**
2544 * Question marks
2545 */
2546
2547 if (value === '?') {
2548 const isGroup = prev && prev.value === '(';
2549 if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
2550 extglobOpen('qmark', value);
2551 continue;
2552 }
2553
2554 if (prev && prev.type === 'paren') {
2555 const next = peek();
2556 let output = value;
2557
2558 if (next === '<' && !utils$1.supportsLookbehinds()) {
2559 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
2560 }
2561
2562 if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
2563 output = `\\${value}`;
2564 }
2565
2566 push({ type: 'text', value, output });
2567 continue;
2568 }
2569
2570 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
2571 push({ type: 'qmark', value, output: QMARK_NO_DOT });
2572 continue;
2573 }
2574
2575 push({ type: 'qmark', value, output: QMARK });
2576 continue;
2577 }
2578
2579 /**
2580 * Exclamation
2581 */
2582
2583 if (value === '!') {
2584 if (opts.noextglob !== true && peek() === '(') {
2585 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
2586 extglobOpen('negate', value);
2587 continue;
2588 }
2589 }
2590
2591 if (opts.nonegate !== true && state.index === 0) {
2592 negate();
2593 continue;
2594 }
2595 }
2596
2597 /**
2598 * Plus
2599 */
2600
2601 if (value === '+') {
2602 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
2603 extglobOpen('plus', value);
2604 continue;
2605 }
2606
2607 if ((prev && prev.value === '(') || opts.regex === false) {
2608 push({ type: 'plus', value, output: PLUS_LITERAL });
2609 continue;
2610 }
2611
2612 if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
2613 push({ type: 'plus', value });
2614 continue;
2615 }
2616
2617 push({ type: 'plus', value: PLUS_LITERAL });
2618 continue;
2619 }
2620
2621 /**
2622 * Plain text
2623 */
2624
2625 if (value === '@') {
2626 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
2627 push({ type: 'at', extglob: true, value, output: '' });
2628 continue;
2629 }
2630
2631 push({ type: 'text', value });
2632 continue;
2633 }
2634
2635 /**
2636 * Plain text
2637 */
2638
2639 if (value !== '*') {
2640 if (value === '$' || value === '^') {
2641 value = `\\${value}`;
2642 }
2643
2644 const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
2645 if (match) {
2646 value += match[0];
2647 state.index += match[0].length;
2648 }
2649
2650 push({ type: 'text', value });
2651 continue;
2652 }
2653
2654 /**
2655 * Stars
2656 */
2657
2658 if (prev && (prev.type === 'globstar' || prev.star === true)) {
2659 prev.type = 'star';
2660 prev.star = true;
2661 prev.value += value;
2662 prev.output = star;
2663 state.backtrack = true;
2664 state.globstar = true;
2665 consume(value);
2666 continue;
2667 }
2668
2669 let rest = remaining();
2670 if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
2671 extglobOpen('star', value);
2672 continue;
2673 }
2674
2675 if (prev.type === 'star') {
2676 if (opts.noglobstar === true) {
2677 consume(value);
2678 continue;
2679 }
2680
2681 const prior = prev.prev;
2682 const before = prior.prev;
2683 const isStart = prior.type === 'slash' || prior.type === 'bos';
2684 const afterStar = before && (before.type === 'star' || before.type === 'globstar');
2685
2686 if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
2687 push({ type: 'star', value, output: '' });
2688 continue;
2689 }
2690
2691 const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
2692 const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
2693 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
2694 push({ type: 'star', value, output: '' });
2695 continue;
2696 }
2697
2698 // strip consecutive `/**/`
2699 while (rest.slice(0, 3) === '/**') {
2700 const after = input[state.index + 4];
2701 if (after && after !== '/') {
2702 break;
2703 }
2704 rest = rest.slice(3);
2705 consume('/**', 3);
2706 }
2707
2708 if (prior.type === 'bos' && eos()) {
2709 prev.type = 'globstar';
2710 prev.value += value;
2711 prev.output = globstar(opts);
2712 state.output = prev.output;
2713 state.globstar = true;
2714 consume(value);
2715 continue;
2716 }
2717
2718 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
2719 state.output = state.output.slice(0, -(prior.output + prev.output).length);
2720 prior.output = `(?:${prior.output}`;
2721
2722 prev.type = 'globstar';
2723 prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
2724 prev.value += value;
2725 state.globstar = true;
2726 state.output += prior.output + prev.output;
2727 consume(value);
2728 continue;
2729 }
2730
2731 if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
2732 const end = rest[1] !== void 0 ? '|$' : '';
2733
2734 state.output = state.output.slice(0, -(prior.output + prev.output).length);
2735 prior.output = `(?:${prior.output}`;
2736
2737 prev.type = 'globstar';
2738 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
2739 prev.value += value;
2740
2741 state.output += prior.output + prev.output;
2742 state.globstar = true;
2743
2744 consume(value + advance());
2745
2746 push({ type: 'slash', value: '/', output: '' });
2747 continue;
2748 }
2749
2750 if (prior.type === 'bos' && rest[0] === '/') {
2751 prev.type = 'globstar';
2752 prev.value += value;
2753 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
2754 state.output = prev.output;
2755 state.globstar = true;
2756 consume(value + advance());
2757 push({ type: 'slash', value: '/', output: '' });
2758 continue;
2759 }
2760
2761 // remove single star from output
2762 state.output = state.output.slice(0, -prev.output.length);
2763
2764 // reset previous token to globstar
2765 prev.type = 'globstar';
2766 prev.output = globstar(opts);
2767 prev.value += value;
2768
2769 // reset output with globstar
2770 state.output += prev.output;
2771 state.globstar = true;
2772 consume(value);
2773 continue;
2774 }
2775
2776 const token = { type: 'star', value, output: star };
2777
2778 if (opts.bash === true) {
2779 token.output = '.*?';
2780 if (prev.type === 'bos' || prev.type === 'slash') {
2781 token.output = nodot + token.output;
2782 }
2783 push(token);
2784 continue;
2785 }
2786
2787 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
2788 token.output = value;
2789 push(token);
2790 continue;
2791 }
2792
2793 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
2794 if (prev.type === 'dot') {
2795 state.output += NO_DOT_SLASH;
2796 prev.output += NO_DOT_SLASH;
2797
2798 } else if (opts.dot === true) {
2799 state.output += NO_DOTS_SLASH;
2800 prev.output += NO_DOTS_SLASH;
2801
2802 } else {
2803 state.output += nodot;
2804 prev.output += nodot;
2805 }
2806
2807 if (peek() !== '*') {
2808 state.output += ONE_CHAR;
2809 prev.output += ONE_CHAR;
2810 }
2811 }
2812
2813 push(token);
2814 }
2815
2816 while (state.brackets > 0) {
2817 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
2818 state.output = utils$1.escapeLast(state.output, '[');
2819 decrement('brackets');
2820 }
2821
2822 while (state.parens > 0) {
2823 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
2824 state.output = utils$1.escapeLast(state.output, '(');
2825 decrement('parens');
2826 }
2827
2828 while (state.braces > 0) {
2829 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
2830 state.output = utils$1.escapeLast(state.output, '{');
2831 decrement('braces');
2832 }
2833
2834 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
2835 push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
2836 }
2837
2838 // rebuild the output if we had to backtrack at any point
2839 if (state.backtrack === true) {
2840 state.output = '';
2841
2842 for (const token of state.tokens) {
2843 state.output += token.output != null ? token.output : token.value;
2844
2845 if (token.suffix) {
2846 state.output += token.suffix;
2847 }
2848 }
2849 }
2850
2851 return state;
2852};
2853
2854/**
2855 * Fast paths for creating regular expressions for common glob patterns.
2856 * This can significantly speed up processing and has very little downside
2857 * impact when none of the fast paths match.
2858 */
2859
2860parse$2.fastpaths = (input, options) => {
2861 const opts = { ...options };
2862 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
2863 const len = input.length;
2864 if (len > max) {
2865 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
2866 }
2867
2868 input = REPLACEMENTS[input] || input;
2869 const win32 = utils$1.isWindows(options);
2870
2871 // create constants based on platform, for windows or posix
2872 const {
2873 DOT_LITERAL,
2874 SLASH_LITERAL,
2875 ONE_CHAR,
2876 DOTS_SLASH,
2877 NO_DOT,
2878 NO_DOTS,
2879 NO_DOTS_SLASH,
2880 STAR,
2881 START_ANCHOR
2882 } = constants$1.globChars(win32);
2883
2884 const nodot = opts.dot ? NO_DOTS : NO_DOT;
2885 const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
2886 const capture = opts.capture ? '' : '?:';
2887 const state = { negated: false, prefix: '' };
2888 let star = opts.bash === true ? '.*?' : STAR;
2889
2890 if (opts.capture) {
2891 star = `(${star})`;
2892 }
2893
2894 const globstar = opts => {
2895 if (opts.noglobstar === true) return star;
2896 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
2897 };
2898
2899 const create = str => {
2900 switch (str) {
2901 case '*':
2902 return `${nodot}${ONE_CHAR}${star}`;
2903
2904 case '.*':
2905 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
2906
2907 case '*.*':
2908 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
2909
2910 case '*/*':
2911 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
2912
2913 case '**':
2914 return nodot + globstar(opts);
2915
2916 case '**/*':
2917 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
2918
2919 case '**/*.*':
2920 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
2921
2922 case '**/.*':
2923 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
2924
2925 default: {
2926 const match = /^(.*?)\.(\w+)$/.exec(str);
2927 if (!match) return;
2928
2929 const source = create(match[1]);
2930 if (!source) return;
2931
2932 return source + DOT_LITERAL + match[2];
2933 }
2934 }
2935 };
2936
2937 const output = utils$1.removePrefix(input, state);
2938 let source = create(output);
2939
2940 if (source && opts.strictSlashes !== true) {
2941 source += `${SLASH_LITERAL}?`;
2942 }
2943
2944 return source;
2945};
2946
2947var parse_1$1 = parse$2;
2948
2949const path$1 = require$$0$1;
2950const scan = scan_1;
2951const parse$1 = parse_1$1;
2952const utils = utils$3;
2953const constants = constants$2;
2954const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);
2955
2956/**
2957 * Creates a matcher function from one or more glob patterns. The
2958 * returned function takes a string to match as its first argument,
2959 * and returns true if the string is a match. The returned matcher
2960 * function also takes a boolean as the second argument that, when true,
2961 * returns an object with additional information.
2962 *
2963 * ```js
2964 * const picomatch = require('picomatch');
2965 * // picomatch(glob[, options]);
2966 *
2967 * const isMatch = picomatch('*.!(*a)');
2968 * console.log(isMatch('a.a')); //=> false
2969 * console.log(isMatch('a.b')); //=> true
2970 * ```
2971 * @name picomatch
2972 * @param {String|Array} `globs` One or more glob patterns.
2973 * @param {Object=} `options`
2974 * @return {Function=} Returns a matcher function.
2975 * @api public
2976 */
2977
2978const picomatch$1 = (glob, options, returnState = false) => {
2979 if (Array.isArray(glob)) {
2980 const fns = glob.map(input => picomatch$1(input, options, returnState));
2981 const arrayMatcher = str => {
2982 for (const isMatch of fns) {
2983 const state = isMatch(str);
2984 if (state) return state;
2985 }
2986 return false;
2987 };
2988 return arrayMatcher;
2989 }
2990
2991 const isState = isObject$2(glob) && glob.tokens && glob.input;
2992
2993 if (glob === '' || (typeof glob !== 'string' && !isState)) {
2994 throw new TypeError('Expected pattern to be a non-empty string');
2995 }
2996
2997 const opts = options || {};
2998 const posix = utils.isWindows(options);
2999 const regex = isState
3000 ? picomatch$1.compileRe(glob, options)
3001 : picomatch$1.makeRe(glob, options, false, true);
3002
3003 const state = regex.state;
3004 delete regex.state;
3005
3006 let isIgnored = () => false;
3007 if (opts.ignore) {
3008 const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
3009 isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState);
3010 }
3011
3012 const matcher = (input, returnObject = false) => {
3013 const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix });
3014 const result = { glob, state, regex, posix, input, output, match, isMatch };
3015
3016 if (typeof opts.onResult === 'function') {
3017 opts.onResult(result);
3018 }
3019
3020 if (isMatch === false) {
3021 result.isMatch = false;
3022 return returnObject ? result : false;
3023 }
3024
3025 if (isIgnored(input)) {
3026 if (typeof opts.onIgnore === 'function') {
3027 opts.onIgnore(result);
3028 }
3029 result.isMatch = false;
3030 return returnObject ? result : false;
3031 }
3032
3033 if (typeof opts.onMatch === 'function') {
3034 opts.onMatch(result);
3035 }
3036 return returnObject ? result : true;
3037 };
3038
3039 if (returnState) {
3040 matcher.state = state;
3041 }
3042
3043 return matcher;
3044};
3045
3046/**
3047 * Test `input` with the given `regex`. This is used by the main
3048 * `picomatch()` function to test the input string.
3049 *
3050 * ```js
3051 * const picomatch = require('picomatch');
3052 * // picomatch.test(input, regex[, options]);
3053 *
3054 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
3055 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
3056 * ```
3057 * @param {String} `input` String to test.
3058 * @param {RegExp} `regex`
3059 * @return {Object} Returns an object with matching info.
3060 * @api public
3061 */
3062
3063picomatch$1.test = (input, regex, options, { glob, posix } = {}) => {
3064 if (typeof input !== 'string') {
3065 throw new TypeError('Expected input to be a string');
3066 }
3067
3068 if (input === '') {
3069 return { isMatch: false, output: '' };
3070 }
3071
3072 const opts = options || {};
3073 const format = opts.format || (posix ? utils.toPosixSlashes : null);
3074 let match = input === glob;
3075 let output = (match && format) ? format(input) : input;
3076
3077 if (match === false) {
3078 output = format ? format(input) : input;
3079 match = output === glob;
3080 }
3081
3082 if (match === false || opts.capture === true) {
3083 if (opts.matchBase === true || opts.basename === true) {
3084 match = picomatch$1.matchBase(input, regex, options, posix);
3085 } else {
3086 match = regex.exec(output);
3087 }
3088 }
3089
3090 return { isMatch: Boolean(match), match, output };
3091};
3092
3093/**
3094 * Match the basename of a filepath.
3095 *
3096 * ```js
3097 * const picomatch = require('picomatch');
3098 * // picomatch.matchBase(input, glob[, options]);
3099 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
3100 * ```
3101 * @param {String} `input` String to test.
3102 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
3103 * @return {Boolean}
3104 * @api public
3105 */
3106
3107picomatch$1.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
3108 const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options);
3109 return regex.test(path$1.basename(input));
3110};
3111
3112/**
3113 * Returns true if **any** of the given glob `patterns` match the specified `string`.
3114 *
3115 * ```js
3116 * const picomatch = require('picomatch');
3117 * // picomatch.isMatch(string, patterns[, options]);
3118 *
3119 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
3120 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
3121 * ```
3122 * @param {String|Array} str The string to test.
3123 * @param {String|Array} patterns One or more glob patterns to use for matching.
3124 * @param {Object} [options] See available [options](#options).
3125 * @return {Boolean} Returns true if any patterns match `str`
3126 * @api public
3127 */
3128
3129picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
3130
3131/**
3132 * Parse a glob pattern to create the source string for a regular
3133 * expression.
3134 *
3135 * ```js
3136 * const picomatch = require('picomatch');
3137 * const result = picomatch.parse(pattern[, options]);
3138 * ```
3139 * @param {String} `pattern`
3140 * @param {Object} `options`
3141 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
3142 * @api public
3143 */
3144
3145picomatch$1.parse = (pattern, options) => {
3146 if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options));
3147 return parse$1(pattern, { ...options, fastpaths: false });
3148};
3149
3150/**
3151 * Scan a glob pattern to separate the pattern into segments.
3152 *
3153 * ```js
3154 * const picomatch = require('picomatch');
3155 * // picomatch.scan(input[, options]);
3156 *
3157 * const result = picomatch.scan('!./foo/*.js');
3158 * console.log(result);
3159 * { prefix: '!./',
3160 * input: '!./foo/*.js',
3161 * start: 3,
3162 * base: 'foo',
3163 * glob: '*.js',
3164 * isBrace: false,
3165 * isBracket: false,
3166 * isGlob: true,
3167 * isExtglob: false,
3168 * isGlobstar: false,
3169 * negated: true }
3170 * ```
3171 * @param {String} `input` Glob pattern to scan.
3172 * @param {Object} `options`
3173 * @return {Object} Returns an object with
3174 * @api public
3175 */
3176
3177picomatch$1.scan = (input, options) => scan(input, options);
3178
3179/**
3180 * Compile a regular expression from the `state` object returned by the
3181 * [parse()](#parse) method.
3182 *
3183 * @param {Object} `state`
3184 * @param {Object} `options`
3185 * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
3186 * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
3187 * @return {RegExp}
3188 * @api public
3189 */
3190
3191picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => {
3192 if (returnOutput === true) {
3193 return state.output;
3194 }
3195
3196 const opts = options || {};
3197 const prepend = opts.contains ? '' : '^';
3198 const append = opts.contains ? '' : '$';
3199
3200 let source = `${prepend}(?:${state.output})${append}`;
3201 if (state && state.negated === true) {
3202 source = `^(?!${source}).*$`;
3203 }
3204
3205 const regex = picomatch$1.toRegex(source, options);
3206 if (returnState === true) {
3207 regex.state = state;
3208 }
3209
3210 return regex;
3211};
3212
3213/**
3214 * Create a regular expression from a parsed glob pattern.
3215 *
3216 * ```js
3217 * const picomatch = require('picomatch');
3218 * const state = picomatch.parse('*.js');
3219 * // picomatch.compileRe(state[, options]);
3220 *
3221 * console.log(picomatch.compileRe(state));
3222 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
3223 * ```
3224 * @param {String} `state` The object returned from the `.parse` method.
3225 * @param {Object} `options`
3226 * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
3227 * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
3228 * @return {RegExp} Returns a regex created from the given pattern.
3229 * @api public
3230 */
3231
3232picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
3233 if (!input || typeof input !== 'string') {
3234 throw new TypeError('Expected a non-empty string');
3235 }
3236
3237 let parsed = { negated: false, fastpaths: true };
3238
3239 if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
3240 parsed.output = parse$1.fastpaths(input, options);
3241 }
3242
3243 if (!parsed.output) {
3244 parsed = parse$1(input, options);
3245 }
3246
3247 return picomatch$1.compileRe(parsed, options, returnOutput, returnState);
3248};
3249
3250/**
3251 * Create a regular expression from the given regex source string.
3252 *
3253 * ```js
3254 * const picomatch = require('picomatch');
3255 * // picomatch.toRegex(source[, options]);
3256 *
3257 * const { output } = picomatch.parse('*.js');
3258 * console.log(picomatch.toRegex(output));
3259 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
3260 * ```
3261 * @param {String} `source` Regular expression source string.
3262 * @param {Object} `options`
3263 * @return {RegExp}
3264 * @api public
3265 */
3266
3267picomatch$1.toRegex = (source, options) => {
3268 try {
3269 const opts = options || {};
3270 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
3271 } catch (err) {
3272 if (options && options.debug === true) throw err;
3273 return /$^/;
3274 }
3275};
3276
3277/**
3278 * Picomatch constants.
3279 * @return {Object}
3280 */
3281
3282picomatch$1.constants = constants;
3283
3284/**
3285 * Expose "picomatch"
3286 */
3287
3288var picomatch_1 = picomatch$1;
3289
3290var picomatch = picomatch_1;
3291
3292var pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch);
3293
3294// Helper since Typescript can't detect readonly arrays with Array.isArray
3295function isArray(arg) {
3296 return Array.isArray(arg);
3297}
3298function ensureArray(thing) {
3299 if (isArray(thing))
3300 return thing;
3301 if (thing == null)
3302 return [];
3303 return [thing];
3304}
3305
3306const normalizePath$1 = function normalizePath(filename) {
3307 return filename.split(require$$0$1.win32.sep).join(require$$0$1.posix.sep);
3308};
3309
3310function getMatcherString(id, resolutionBase) {
3311 if (resolutionBase === false || require$$0$1.isAbsolute(id) || id.startsWith('**')) {
3312 return normalizePath$1(id);
3313 }
3314 // resolve('') is valid and will default to process.cwd()
3315 const basePath = normalizePath$1(require$$0$1.resolve(resolutionBase || ''))
3316 // escape all possible (posix + win) path characters that might interfere with regex
3317 .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
3318 // Note that we use posix.join because:
3319 // 1. the basePath has been normalized to use /
3320 // 2. the incoming glob (id) matcher, also uses /
3321 // otherwise Node will force backslash (\) on windows
3322 return require$$0$1.posix.join(basePath, normalizePath$1(id));
3323}
3324const createFilter$1 = function createFilter(include, exclude, options) {
3325 const resolutionBase = options && options.resolve;
3326 const getMatcher = (id) => id instanceof RegExp
3327 ? id
3328 : {
3329 test: (what) => {
3330 // this refactor is a tad overly verbose but makes for easy debugging
3331 const pattern = getMatcherString(id, resolutionBase);
3332 const fn = pm(pattern, { dot: true });
3333 const result = fn(what);
3334 return result;
3335 }
3336 };
3337 const includeMatchers = ensureArray(include).map(getMatcher);
3338 const excludeMatchers = ensureArray(exclude).map(getMatcher);
3339 return function result(id) {
3340 if (typeof id !== 'string')
3341 return false;
3342 if (/\0/.test(id))
3343 return false;
3344 const pathId = normalizePath$1(id);
3345 for (let i = 0; i < excludeMatchers.length; ++i) {
3346 const matcher = excludeMatchers[i];
3347 if (matcher.test(pathId))
3348 return false;
3349 }
3350 for (let i = 0; i < includeMatchers.length; ++i) {
3351 const matcher = includeMatchers[i];
3352 if (matcher.test(pathId))
3353 return true;
3354 }
3355 return !includeMatchers.length;
3356 };
3357};
3358
3359const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
3360const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
3361const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
3362forbiddenIdentifiers.add('');
3363
3364const isWindows = typeof process !== "undefined" && process.platform === "win32";
3365const windowsSlashRE = /\\/g;
3366function slash(p) {
3367 return p.replace(windowsSlashRE, "/");
3368}
3369const postfixRE = /[?#].*$/;
3370function cleanUrl(url) {
3371 return url.replace(postfixRE, "");
3372}
3373function withTrailingSlash(path) {
3374 if (path[path.length - 1] !== "/") {
3375 return `${path}/`;
3376 }
3377 return path;
3378}
3379
3380if (process.versions.pnp) {
3381 try {
3382 node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))("pnpapi");
3383 } catch {
3384 }
3385}
3386
3387const createFilter = createFilter$1;
3388node_module.builtinModules.filter((id) => !id.includes(":"));
3389function isInNodeModules(id) {
3390 return id.includes("node_modules");
3391}
3392const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)));
3393function resolveDependencyVersion(dep, pkgRelativePath = "../../package.json") {
3394 const pkgPath = path$3.resolve(_require.resolve(dep), pkgRelativePath);
3395 return JSON.parse(fs$1.readFileSync(pkgPath, "utf-8")).version;
3396}
3397const rollupVersion = resolveDependencyVersion("rollup");
3398const filter = process.env.VITE_DEBUG_FILTER;
3399const DEBUG = process.env.DEBUG;
3400function createDebugger(namespace, options = {}) {
3401 const log = debug$2(namespace);
3402 const { onlyWhenFocused } = options;
3403 let enabled = log.enabled;
3404 if (enabled && onlyWhenFocused) {
3405 const ns = typeof onlyWhenFocused === "string" ? onlyWhenFocused : namespace;
3406 enabled = !!DEBUG?.includes(ns);
3407 }
3408 if (enabled) {
3409 return (...args) => {
3410 if (!filter || args.some((a) => a?.includes?.(filter))) {
3411 log(...args);
3412 }
3413 };
3414 }
3415}
3416function testCaseInsensitiveFS() {
3417 if (!CLIENT_ENTRY.endsWith("client.mjs")) {
3418 throw new Error(
3419 `cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`
3420 );
3421 }
3422 if (!fs$1.existsSync(CLIENT_ENTRY)) {
3423 throw new Error(
3424 "cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: " + CLIENT_ENTRY
3425 );
3426 }
3427 return fs$1.existsSync(CLIENT_ENTRY.replace("client.mjs", "cLiEnT.mjs"));
3428}
3429const isCaseInsensitiveFS = testCaseInsensitiveFS();
3430const VOLUME_RE = /^[A-Z]:/i;
3431function normalizePath(id) {
3432 return path$3.posix.normalize(isWindows ? slash(id) : id);
3433}
3434function fsPathFromId(id) {
3435 const fsPath = normalizePath(
3436 id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id
3437 );
3438 return fsPath[0] === "/" || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`;
3439}
3440function fsPathFromUrl(url) {
3441 return fsPathFromId(cleanUrl(url));
3442}
3443function isParentDirectory(dir, file) {
3444 dir = withTrailingSlash(dir);
3445 return file.startsWith(dir) || isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase());
3446}
3447function isSameFileUri(file1, file2) {
3448 return file1 === file2 || isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase();
3449}
3450const trailingSeparatorRE = /[?&]$/;
3451const timestampRE = /\bt=\d{13}&?\b/;
3452function removeTimestampQuery(url) {
3453 return url.replace(timestampRE, "").replace(trailingSeparatorRE, "");
3454}
3455function isObject$1(value) {
3456 return Object.prototype.toString.call(value) === "[object Object]";
3457}
3458function tryStatSync(file) {
3459 try {
3460 return fs$1.statSync(file, { throwIfNoEntry: false });
3461 } catch {
3462 }
3463}
3464function isFileReadable(filename) {
3465 if (!tryStatSync(filename)) {
3466 return false;
3467 }
3468 try {
3469 fs$1.accessSync(filename, fs$1.constants.R_OK);
3470 return true;
3471 } catch {
3472 return false;
3473 }
3474}
3475function arraify(target) {
3476 return Array.isArray(target) ? target : [target];
3477}
3478path$3.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))));
3479function backwardCompatibleWorkerPlugins(plugins) {
3480 if (Array.isArray(plugins)) {
3481 return plugins;
3482 }
3483 if (typeof plugins === "function") {
3484 return plugins();
3485 }
3486 return [];
3487}
3488function mergeConfigRecursively(defaults, overrides, rootPath) {
3489 const merged = { ...defaults };
3490 for (const key in overrides) {
3491 const value = overrides[key];
3492 if (value == null) {
3493 continue;
3494 }
3495 const existing = merged[key];
3496 if (existing == null) {
3497 merged[key] = value;
3498 continue;
3499 }
3500 if (key === "alias" && (rootPath === "resolve" || rootPath === "")) {
3501 merged[key] = mergeAlias(existing, value);
3502 continue;
3503 } else if (key === "assetsInclude" && rootPath === "") {
3504 merged[key] = [].concat(existing, value);
3505 continue;
3506 } else if (key === "noExternal" && rootPath === "ssr" && (existing === true || value === true)) {
3507 merged[key] = true;
3508 continue;
3509 } else if (key === "plugins" && rootPath === "worker") {
3510 merged[key] = () => [
3511 ...backwardCompatibleWorkerPlugins(existing),
3512 ...backwardCompatibleWorkerPlugins(value)
3513 ];
3514 continue;
3515 } else if (key === "server" && rootPath === "server.hmr") {
3516 merged[key] = value;
3517 continue;
3518 }
3519 if (Array.isArray(existing) || Array.isArray(value)) {
3520 merged[key] = [...arraify(existing), ...arraify(value)];
3521 continue;
3522 }
3523 if (isObject$1(existing) && isObject$1(value)) {
3524 merged[key] = mergeConfigRecursively(
3525 existing,
3526 value,
3527 rootPath ? `${rootPath}.${key}` : key
3528 );
3529 continue;
3530 }
3531 merged[key] = value;
3532 }
3533 return merged;
3534}
3535function mergeConfig(defaults, overrides, isRoot = true) {
3536 if (typeof defaults === "function" || typeof overrides === "function") {
3537 throw new Error(`Cannot merge config in form of callback`);
3538 }
3539 return mergeConfigRecursively(defaults, overrides, isRoot ? "" : ".");
3540}
3541function mergeAlias(a, b) {
3542 if (!a) return b;
3543 if (!b) return a;
3544 if (isObject$1(a) && isObject$1(b)) {
3545 return { ...a, ...b };
3546 }
3547 return [...normalizeAlias(b), ...normalizeAlias(a)];
3548}
3549function normalizeAlias(o = []) {
3550 return Array.isArray(o) ? o.map(normalizeSingleAlias) : Object.keys(o).map(
3551 (find) => normalizeSingleAlias({
3552 find,
3553 replacement: o[find]
3554 })
3555 );
3556}
3557function normalizeSingleAlias({
3558 find,
3559 replacement,
3560 customResolver
3561}) {
3562 if (typeof find === "string" && find[find.length - 1] === "/" && replacement[replacement.length - 1] === "/") {
3563 find = find.slice(0, find.length - 1);
3564 replacement = replacement.slice(0, replacement.length - 1);
3565 }
3566 const alias = {
3567 find,
3568 replacement
3569 };
3570 if (customResolver) {
3571 alias.customResolver = customResolver;
3572 }
3573 return alias;
3574}
3575
3576const CSS_LANGS_RE = (
3577 // eslint-disable-next-line regexp/no-unused-capturing-group
3578 /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/
3579);
3580const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
3581class SplitVendorChunkCache {
3582 cache;
3583 constructor() {
3584 this.cache = /* @__PURE__ */ new Map();
3585 }
3586 reset() {
3587 this.cache = /* @__PURE__ */ new Map();
3588 }
3589}
3590function splitVendorChunk(options = {}) {
3591 const cache = options.cache ?? new SplitVendorChunkCache();
3592 return (id, { getModuleInfo }) => {
3593 if (isInNodeModules(id) && !isCSSRequest(id) && staticImportedByEntry(id, getModuleInfo, cache.cache)) {
3594 return "vendor";
3595 }
3596 };
3597}
3598function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) {
3599 if (cache.has(id)) {
3600 return cache.get(id);
3601 }
3602 if (importStack.includes(id)) {
3603 cache.set(id, false);
3604 return false;
3605 }
3606 const mod = getModuleInfo(id);
3607 if (!mod) {
3608 cache.set(id, false);
3609 return false;
3610 }
3611 if (mod.isEntry) {
3612 cache.set(id, true);
3613 return true;
3614 }
3615 const someImporterIs = mod.importers.some(
3616 (importer) => staticImportedByEntry(
3617 importer,
3618 getModuleInfo,
3619 cache,
3620 importStack.concat(id)
3621 )
3622 );
3623 cache.set(id, someImporterIs);
3624 return someImporterIs;
3625}
3626function splitVendorChunkPlugin() {
3627 const caches = [];
3628 function createSplitVendorChunk(output, config) {
3629 const cache = new SplitVendorChunkCache();
3630 caches.push(cache);
3631 const build = config.build ?? {};
3632 const format = output?.format;
3633 if (!build.ssr && !build.lib && format !== "umd" && format !== "iife") {
3634 return splitVendorChunk({ cache });
3635 }
3636 }
3637 return {
3638 name: "vite:split-vendor-chunk",
3639 config(config) {
3640 let outputs = config?.build?.rollupOptions?.output;
3641 if (outputs) {
3642 outputs = arraify(outputs);
3643 for (const output of outputs) {
3644 const viteManualChunks = createSplitVendorChunk(output, config);
3645 if (viteManualChunks) {
3646 if (output.manualChunks) {
3647 if (typeof output.manualChunks === "function") {
3648 const userManualChunks = output.manualChunks;
3649 output.manualChunks = (id, api) => {
3650 return userManualChunks(id, api) ?? viteManualChunks(id, api);
3651 };
3652 } else {
3653 console.warn(
3654 "(!) the `splitVendorChunk` plugin doesn't have any effect when using the object form of `build.rollupOptions.output.manualChunks`. Consider using the function form instead."
3655 );
3656 }
3657 } else {
3658 output.manualChunks = viteManualChunks;
3659 }
3660 }
3661 }
3662 } else {
3663 return {
3664 build: {
3665 rollupOptions: {
3666 output: {
3667 manualChunks: createSplitVendorChunk({}, config)
3668 }
3669 }
3670 }
3671 };
3672 }
3673 },
3674 buildStart() {
3675 caches.forEach((cache) => cache.reset());
3676 }
3677 };
3678}
3679
3680var convertSourceMap$1 = {};
3681
3682(function (exports) {
3683
3684 Object.defineProperty(exports, 'commentRegex', {
3685 get: function getCommentRegex () {
3686 // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data.
3687 return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg;
3688 }
3689 });
3690
3691
3692 Object.defineProperty(exports, 'mapFileCommentRegex', {
3693 get: function getMapFileCommentRegex () {
3694 // Matches sourceMappingURL in either // or /* comment styles.
3695 return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg;
3696 }
3697 });
3698
3699 var decodeBase64;
3700 if (typeof Buffer !== 'undefined') {
3701 if (typeof Buffer.from === 'function') {
3702 decodeBase64 = decodeBase64WithBufferFrom;
3703 } else {
3704 decodeBase64 = decodeBase64WithNewBuffer;
3705 }
3706 } else {
3707 decodeBase64 = decodeBase64WithAtob;
3708 }
3709
3710 function decodeBase64WithBufferFrom(base64) {
3711 return Buffer.from(base64, 'base64').toString();
3712 }
3713
3714 function decodeBase64WithNewBuffer(base64) {
3715 if (typeof value === 'number') {
3716 throw new TypeError('The value to decode must not be of type number.');
3717 }
3718 return new Buffer(base64, 'base64').toString();
3719 }
3720
3721 function decodeBase64WithAtob(base64) {
3722 return decodeURIComponent(escape(atob(base64)));
3723 }
3724
3725 function stripComment(sm) {
3726 return sm.split(',').pop();
3727 }
3728
3729 function readFromFileMap(sm, read) {
3730 var r = exports.mapFileCommentRegex.exec(sm);
3731 // for some odd reason //# .. captures in 1 and /* .. */ in 2
3732 var filename = r[1] || r[2];
3733
3734 try {
3735 var sm = read(filename);
3736 if (sm != null && typeof sm.catch === 'function') {
3737 return sm.catch(throwError);
3738 } else {
3739 return sm;
3740 }
3741 } catch (e) {
3742 throwError(e);
3743 }
3744
3745 function throwError(e) {
3746 throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack);
3747 }
3748 }
3749
3750 function Converter (sm, opts) {
3751 opts = opts || {};
3752
3753 if (opts.hasComment) {
3754 sm = stripComment(sm);
3755 }
3756
3757 if (opts.encoding === 'base64') {
3758 sm = decodeBase64(sm);
3759 } else if (opts.encoding === 'uri') {
3760 sm = decodeURIComponent(sm);
3761 }
3762
3763 if (opts.isJSON || opts.encoding) {
3764 sm = JSON.parse(sm);
3765 }
3766
3767 this.sourcemap = sm;
3768 }
3769
3770 Converter.prototype.toJSON = function (space) {
3771 return JSON.stringify(this.sourcemap, null, space);
3772 };
3773
3774 if (typeof Buffer !== 'undefined') {
3775 if (typeof Buffer.from === 'function') {
3776 Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
3777 } else {
3778 Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
3779 }
3780 } else {
3781 Converter.prototype.toBase64 = encodeBase64WithBtoa;
3782 }
3783
3784 function encodeBase64WithBufferFrom() {
3785 var json = this.toJSON();
3786 return Buffer.from(json, 'utf8').toString('base64');
3787 }
3788
3789 function encodeBase64WithNewBuffer() {
3790 var json = this.toJSON();
3791 if (typeof json === 'number') {
3792 throw new TypeError('The json to encode must not be of type number.');
3793 }
3794 return new Buffer(json, 'utf8').toString('base64');
3795 }
3796
3797 function encodeBase64WithBtoa() {
3798 var json = this.toJSON();
3799 return btoa(unescape(encodeURIComponent(json)));
3800 }
3801
3802 Converter.prototype.toURI = function () {
3803 var json = this.toJSON();
3804 return encodeURIComponent(json);
3805 };
3806
3807 Converter.prototype.toComment = function (options) {
3808 var encoding, content, data;
3809 if (options != null && options.encoding === 'uri') {
3810 encoding = '';
3811 content = this.toURI();
3812 } else {
3813 encoding = ';base64';
3814 content = this.toBase64();
3815 }
3816 data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content;
3817 return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
3818 };
3819
3820 // returns copy instead of original
3821 Converter.prototype.toObject = function () {
3822 return JSON.parse(this.toJSON());
3823 };
3824
3825 Converter.prototype.addProperty = function (key, value) {
3826 if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
3827 return this.setProperty(key, value);
3828 };
3829
3830 Converter.prototype.setProperty = function (key, value) {
3831 this.sourcemap[key] = value;
3832 return this;
3833 };
3834
3835 Converter.prototype.getProperty = function (key) {
3836 return this.sourcemap[key];
3837 };
3838
3839 exports.fromObject = function (obj) {
3840 return new Converter(obj);
3841 };
3842
3843 exports.fromJSON = function (json) {
3844 return new Converter(json, { isJSON: true });
3845 };
3846
3847 exports.fromURI = function (uri) {
3848 return new Converter(uri, { encoding: 'uri' });
3849 };
3850
3851 exports.fromBase64 = function (base64) {
3852 return new Converter(base64, { encoding: 'base64' });
3853 };
3854
3855 exports.fromComment = function (comment) {
3856 var m, encoding;
3857 comment = comment
3858 .replace(/^\/\*/g, '//')
3859 .replace(/\*\/$/g, '');
3860 m = exports.commentRegex.exec(comment);
3861 encoding = m && m[4] || 'uri';
3862 return new Converter(comment, { encoding: encoding, hasComment: true });
3863 };
3864
3865 function makeConverter(sm) {
3866 return new Converter(sm, { isJSON: true });
3867 }
3868
3869 exports.fromMapFileComment = function (comment, read) {
3870 if (typeof read === 'string') {
3871 throw new Error(
3872 'String directory paths are no longer supported with `fromMapFileComment`\n' +
3873 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
3874 )
3875 }
3876
3877 var sm = readFromFileMap(comment, read);
3878 if (sm != null && typeof sm.then === 'function') {
3879 return sm.then(makeConverter);
3880 } else {
3881 return makeConverter(sm);
3882 }
3883 };
3884
3885 // Finds last sourcemap comment in file or returns null if none was found
3886 exports.fromSource = function (content) {
3887 var m = content.match(exports.commentRegex);
3888 return m ? exports.fromComment(m.pop()) : null;
3889 };
3890
3891 // Finds last sourcemap comment in file or returns null if none was found
3892 exports.fromMapFileSource = function (content, read) {
3893 if (typeof read === 'string') {
3894 throw new Error(
3895 'String directory paths are no longer supported with `fromMapFileSource`\n' +
3896 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
3897 )
3898 }
3899 var m = content.match(exports.mapFileCommentRegex);
3900 return m ? exports.fromMapFileComment(m.pop(), read) : null;
3901 };
3902
3903 exports.removeComments = function (src) {
3904 return src.replace(exports.commentRegex, '');
3905 };
3906
3907 exports.removeMapFileComments = function (src) {
3908 return src.replace(exports.mapFileCommentRegex, '');
3909 };
3910
3911 exports.generateMapFileComment = function (file, options) {
3912 var data = 'sourceMappingURL=' + file;
3913 return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
3914 };
3915} (convertSourceMap$1));
3916
3917var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs(convertSourceMap$1);
3918
3919/*!
3920 * etag
3921 * Copyright(c) 2014-2016 Douglas Christopher Wilson
3922 * MIT Licensed
3923 */
3924
3925/**
3926 * Module exports.
3927 * @public
3928 */
3929
3930var etag_1 = etag;
3931
3932/**
3933 * Module dependencies.
3934 * @private
3935 */
3936
3937var crypto$1 = require$$0$2;
3938var Stats = fs$2.Stats;
3939
3940/**
3941 * Module variables.
3942 * @private
3943 */
3944
3945var toString$1 = Object.prototype.toString;
3946
3947/**
3948 * Generate an entity tag.
3949 *
3950 * @param {Buffer|string} entity
3951 * @return {string}
3952 * @private
3953 */
3954
3955function entitytag (entity) {
3956 if (entity.length === 0) {
3957 // fast-path empty
3958 return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
3959 }
3960
3961 // compute hash of entity
3962 var hash = crypto$1
3963 .createHash('sha1')
3964 .update(entity, 'utf8')
3965 .digest('base64')
3966 .substring(0, 27);
3967
3968 // compute length of entity
3969 var len = typeof entity === 'string'
3970 ? Buffer.byteLength(entity, 'utf8')
3971 : entity.length;
3972
3973 return '"' + len.toString(16) + '-' + hash + '"'
3974}
3975
3976/**
3977 * Create a simple ETag.
3978 *
3979 * @param {string|Buffer|Stats} entity
3980 * @param {object} [options]
3981 * @param {boolean} [options.weak]
3982 * @return {String}
3983 * @public
3984 */
3985
3986function etag (entity, options) {
3987 if (entity == null) {
3988 throw new TypeError('argument entity is required')
3989 }
3990
3991 // support fs.Stats object
3992 var isStats = isstats(entity);
3993 var weak = options && typeof options.weak === 'boolean'
3994 ? options.weak
3995 : isStats;
3996
3997 // validate argument
3998 if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
3999 throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
4000 }
4001
4002 // generate entity tag
4003 var tag = isStats
4004 ? stattag(entity)
4005 : entitytag(entity);
4006
4007 return weak
4008 ? 'W/' + tag
4009 : tag
4010}
4011
4012/**
4013 * Determine if object is a Stats object.
4014 *
4015 * @param {object} obj
4016 * @return {boolean}
4017 * @api private
4018 */
4019
4020function isstats (obj) {
4021 // genuine fs.Stats
4022 if (typeof Stats === 'function' && obj instanceof Stats) {
4023 return true
4024 }
4025
4026 // quack quack
4027 return obj && typeof obj === 'object' &&
4028 'ctime' in obj && toString$1.call(obj.ctime) === '[object Date]' &&
4029 'mtime' in obj && toString$1.call(obj.mtime) === '[object Date]' &&
4030 'ino' in obj && typeof obj.ino === 'number' &&
4031 'size' in obj && typeof obj.size === 'number'
4032}
4033
4034/**
4035 * Generate a tag for a stat.
4036 *
4037 * @param {object} stat
4038 * @return {string}
4039 * @private
4040 */
4041
4042function stattag (stat) {
4043 var mtime = stat.mtime.getTime().toString(16);
4044 var size = stat.size.toString(16);
4045
4046 return '"' + size + '-' + mtime + '"'
4047}
4048
4049var getEtag = /*@__PURE__*/getDefaultExportFromCjs(etag_1);
4050
4051class BitSet {
4052 constructor(arg) {
4053 this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
4054 }
4055
4056 add(n) {
4057 this.bits[n >> 5] |= 1 << (n & 31);
4058 }
4059
4060 has(n) {
4061 return !!(this.bits[n >> 5] & (1 << (n & 31)));
4062 }
4063}
4064
4065class Chunk {
4066 constructor(start, end, content) {
4067 this.start = start;
4068 this.end = end;
4069 this.original = content;
4070
4071 this.intro = '';
4072 this.outro = '';
4073
4074 this.content = content;
4075 this.storeName = false;
4076 this.edited = false;
4077
4078 {
4079 this.previous = null;
4080 this.next = null;
4081 }
4082 }
4083
4084 appendLeft(content) {
4085 this.outro += content;
4086 }
4087
4088 appendRight(content) {
4089 this.intro = this.intro + content;
4090 }
4091
4092 clone() {
4093 const chunk = new Chunk(this.start, this.end, this.original);
4094
4095 chunk.intro = this.intro;
4096 chunk.outro = this.outro;
4097 chunk.content = this.content;
4098 chunk.storeName = this.storeName;
4099 chunk.edited = this.edited;
4100
4101 return chunk;
4102 }
4103
4104 contains(index) {
4105 return this.start < index && index < this.end;
4106 }
4107
4108 eachNext(fn) {
4109 let chunk = this;
4110 while (chunk) {
4111 fn(chunk);
4112 chunk = chunk.next;
4113 }
4114 }
4115
4116 eachPrevious(fn) {
4117 let chunk = this;
4118 while (chunk) {
4119 fn(chunk);
4120 chunk = chunk.previous;
4121 }
4122 }
4123
4124 edit(content, storeName, contentOnly) {
4125 this.content = content;
4126 if (!contentOnly) {
4127 this.intro = '';
4128 this.outro = '';
4129 }
4130 this.storeName = storeName;
4131
4132 this.edited = true;
4133
4134 return this;
4135 }
4136
4137 prependLeft(content) {
4138 this.outro = content + this.outro;
4139 }
4140
4141 prependRight(content) {
4142 this.intro = content + this.intro;
4143 }
4144
4145 reset() {
4146 this.intro = '';
4147 this.outro = '';
4148 if (this.edited) {
4149 this.content = this.original;
4150 this.storeName = false;
4151 this.edited = false;
4152 }
4153 }
4154
4155 split(index) {
4156 const sliceIndex = index - this.start;
4157
4158 const originalBefore = this.original.slice(0, sliceIndex);
4159 const originalAfter = this.original.slice(sliceIndex);
4160
4161 this.original = originalBefore;
4162
4163 const newChunk = new Chunk(index, this.end, originalAfter);
4164 newChunk.outro = this.outro;
4165 this.outro = '';
4166
4167 this.end = index;
4168
4169 if (this.edited) {
4170 // after split we should save the edit content record into the correct chunk
4171 // to make sure sourcemap correct
4172 // For example:
4173 // ' test'.trim()
4174 // split -> ' ' + 'test'
4175 // ✔️ edit -> '' + 'test'
4176 // ✖️ edit -> 'test' + ''
4177 // TODO is this block necessary?...
4178 newChunk.edit('', false);
4179 this.content = '';
4180 } else {
4181 this.content = originalBefore;
4182 }
4183
4184 newChunk.next = this.next;
4185 if (newChunk.next) newChunk.next.previous = newChunk;
4186 newChunk.previous = this;
4187 this.next = newChunk;
4188
4189 return newChunk;
4190 }
4191
4192 toString() {
4193 return this.intro + this.content + this.outro;
4194 }
4195
4196 trimEnd(rx) {
4197 this.outro = this.outro.replace(rx, '');
4198 if (this.outro.length) return true;
4199
4200 const trimmed = this.content.replace(rx, '');
4201
4202 if (trimmed.length) {
4203 if (trimmed !== this.content) {
4204 this.split(this.start + trimmed.length).edit('', undefined, true);
4205 if (this.edited) {
4206 // save the change, if it has been edited
4207 this.edit(trimmed, this.storeName, true);
4208 }
4209 }
4210 return true;
4211 } else {
4212 this.edit('', undefined, true);
4213
4214 this.intro = this.intro.replace(rx, '');
4215 if (this.intro.length) return true;
4216 }
4217 }
4218
4219 trimStart(rx) {
4220 this.intro = this.intro.replace(rx, '');
4221 if (this.intro.length) return true;
4222
4223 const trimmed = this.content.replace(rx, '');
4224
4225 if (trimmed.length) {
4226 if (trimmed !== this.content) {
4227 const newChunk = this.split(this.end - trimmed.length);
4228 if (this.edited) {
4229 // save the change, if it has been edited
4230 newChunk.edit(trimmed, this.storeName, true);
4231 }
4232 this.edit('', undefined, true);
4233 }
4234 return true;
4235 } else {
4236 this.edit('', undefined, true);
4237
4238 this.outro = this.outro.replace(rx, '');
4239 if (this.outro.length) return true;
4240 }
4241 }
4242}
4243
4244function getBtoa() {
4245 if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
4246 return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
4247 } else if (typeof Buffer === 'function') {
4248 return (str) => Buffer.from(str, 'utf-8').toString('base64');
4249 } else {
4250 return () => {
4251 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
4252 };
4253 }
4254}
4255
4256const btoa$1 = /*#__PURE__*/ getBtoa();
4257
4258class SourceMap {
4259 constructor(properties) {
4260 this.version = 3;
4261 this.file = properties.file;
4262 this.sources = properties.sources;
4263 this.sourcesContent = properties.sourcesContent;
4264 this.names = properties.names;
4265 this.mappings = encode(properties.mappings);
4266 if (typeof properties.x_google_ignoreList !== 'undefined') {
4267 this.x_google_ignoreList = properties.x_google_ignoreList;
4268 }
4269 }
4270
4271 toString() {
4272 return JSON.stringify(this);
4273 }
4274
4275 toUrl() {
4276 return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString());
4277 }
4278}
4279
4280function guessIndent(code) {
4281 const lines = code.split('\n');
4282
4283 const tabbed = lines.filter((line) => /^\t+/.test(line));
4284 const spaced = lines.filter((line) => /^ {2,}/.test(line));
4285
4286 if (tabbed.length === 0 && spaced.length === 0) {
4287 return null;
4288 }
4289
4290 // More lines tabbed than spaced? Assume tabs, and
4291 // default to tabs in the case of a tie (or nothing
4292 // to go on)
4293 if (tabbed.length >= spaced.length) {
4294 return '\t';
4295 }
4296
4297 // Otherwise, we need to guess the multiple
4298 const min = spaced.reduce((previous, current) => {
4299 const numSpaces = /^ +/.exec(current)[0].length;
4300 return Math.min(numSpaces, previous);
4301 }, Infinity);
4302
4303 return new Array(min + 1).join(' ');
4304}
4305
4306function getRelativePath(from, to) {
4307 const fromParts = from.split(/[/\\]/);
4308 const toParts = to.split(/[/\\]/);
4309
4310 fromParts.pop(); // get dirname
4311
4312 while (fromParts[0] === toParts[0]) {
4313 fromParts.shift();
4314 toParts.shift();
4315 }
4316
4317 if (fromParts.length) {
4318 let i = fromParts.length;
4319 while (i--) fromParts[i] = '..';
4320 }
4321
4322 return fromParts.concat(toParts).join('/');
4323}
4324
4325const toString = Object.prototype.toString;
4326
4327function isObject(thing) {
4328 return toString.call(thing) === '[object Object]';
4329}
4330
4331function getLocator(source) {
4332 const originalLines = source.split('\n');
4333 const lineOffsets = [];
4334
4335 for (let i = 0, pos = 0; i < originalLines.length; i++) {
4336 lineOffsets.push(pos);
4337 pos += originalLines[i].length + 1;
4338 }
4339
4340 return function locate(index) {
4341 let i = 0;
4342 let j = lineOffsets.length;
4343 while (i < j) {
4344 const m = (i + j) >> 1;
4345 if (index < lineOffsets[m]) {
4346 j = m;
4347 } else {
4348 i = m + 1;
4349 }
4350 }
4351 const line = i - 1;
4352 const column = index - lineOffsets[line];
4353 return { line, column };
4354 };
4355}
4356
4357const wordRegex = /\w/;
4358
4359class Mappings {
4360 constructor(hires) {
4361 this.hires = hires;
4362 this.generatedCodeLine = 0;
4363 this.generatedCodeColumn = 0;
4364 this.raw = [];
4365 this.rawSegments = this.raw[this.generatedCodeLine] = [];
4366 this.pending = null;
4367 }
4368
4369 addEdit(sourceIndex, content, loc, nameIndex) {
4370 if (content.length) {
4371 const contentLengthMinusOne = content.length - 1;
4372 let contentLineEnd = content.indexOf('\n', 0);
4373 let previousContentLineEnd = -1;
4374 // Loop through each line in the content and add a segment, but stop if the last line is empty,
4375 // else code afterwards would fill one line too many
4376 while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
4377 const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
4378 if (nameIndex >= 0) {
4379 segment.push(nameIndex);
4380 }
4381 this.rawSegments.push(segment);
4382
4383 this.generatedCodeLine += 1;
4384 this.raw[this.generatedCodeLine] = this.rawSegments = [];
4385 this.generatedCodeColumn = 0;
4386
4387 previousContentLineEnd = contentLineEnd;
4388 contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
4389 }
4390
4391 const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
4392 if (nameIndex >= 0) {
4393 segment.push(nameIndex);
4394 }
4395 this.rawSegments.push(segment);
4396
4397 this.advance(content.slice(previousContentLineEnd + 1));
4398 } else if (this.pending) {
4399 this.rawSegments.push(this.pending);
4400 this.advance(content);
4401 }
4402
4403 this.pending = null;
4404 }
4405
4406 addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
4407 let originalCharIndex = chunk.start;
4408 let first = true;
4409 // when iterating each char, check if it's in a word boundary
4410 let charInHiresBoundary = false;
4411
4412 while (originalCharIndex < chunk.end) {
4413 if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
4414 const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
4415
4416 if (this.hires === 'boundary') {
4417 // in hires "boundary", group segments per word boundary than per char
4418 if (wordRegex.test(original[originalCharIndex])) {
4419 // for first char in the boundary found, start the boundary by pushing a segment
4420 if (!charInHiresBoundary) {
4421 this.rawSegments.push(segment);
4422 charInHiresBoundary = true;
4423 }
4424 } else {
4425 // for non-word char, end the boundary by pushing a segment
4426 this.rawSegments.push(segment);
4427 charInHiresBoundary = false;
4428 }
4429 } else {
4430 this.rawSegments.push(segment);
4431 }
4432 }
4433
4434 if (original[originalCharIndex] === '\n') {
4435 loc.line += 1;
4436 loc.column = 0;
4437 this.generatedCodeLine += 1;
4438 this.raw[this.generatedCodeLine] = this.rawSegments = [];
4439 this.generatedCodeColumn = 0;
4440 first = true;
4441 } else {
4442 loc.column += 1;
4443 this.generatedCodeColumn += 1;
4444 first = false;
4445 }
4446
4447 originalCharIndex += 1;
4448 }
4449
4450 this.pending = null;
4451 }
4452
4453 advance(str) {
4454 if (!str) return;
4455
4456 const lines = str.split('\n');
4457
4458 if (lines.length > 1) {
4459 for (let i = 0; i < lines.length - 1; i++) {
4460 this.generatedCodeLine++;
4461 this.raw[this.generatedCodeLine] = this.rawSegments = [];
4462 }
4463 this.generatedCodeColumn = 0;
4464 }
4465
4466 this.generatedCodeColumn += lines[lines.length - 1].length;
4467 }
4468}
4469
4470const n = '\n';
4471
4472const warned = {
4473 insertLeft: false,
4474 insertRight: false,
4475 storeName: false,
4476};
4477
4478class MagicString {
4479 constructor(string, options = {}) {
4480 const chunk = new Chunk(0, string.length, string);
4481
4482 Object.defineProperties(this, {
4483 original: { writable: true, value: string },
4484 outro: { writable: true, value: '' },
4485 intro: { writable: true, value: '' },
4486 firstChunk: { writable: true, value: chunk },
4487 lastChunk: { writable: true, value: chunk },
4488 lastSearchedChunk: { writable: true, value: chunk },
4489 byStart: { writable: true, value: {} },
4490 byEnd: { writable: true, value: {} },
4491 filename: { writable: true, value: options.filename },
4492 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
4493 sourcemapLocations: { writable: true, value: new BitSet() },
4494 storedNames: { writable: true, value: {} },
4495 indentStr: { writable: true, value: undefined },
4496 ignoreList: { writable: true, value: options.ignoreList },
4497 });
4498
4499 this.byStart[0] = chunk;
4500 this.byEnd[string.length] = chunk;
4501 }
4502
4503 addSourcemapLocation(char) {
4504 this.sourcemapLocations.add(char);
4505 }
4506
4507 append(content) {
4508 if (typeof content !== 'string') throw new TypeError('outro content must be a string');
4509
4510 this.outro += content;
4511 return this;
4512 }
4513
4514 appendLeft(index, content) {
4515 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
4516
4517 this._split(index);
4518
4519 const chunk = this.byEnd[index];
4520
4521 if (chunk) {
4522 chunk.appendLeft(content);
4523 } else {
4524 this.intro += content;
4525 }
4526 return this;
4527 }
4528
4529 appendRight(index, content) {
4530 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
4531
4532 this._split(index);
4533
4534 const chunk = this.byStart[index];
4535
4536 if (chunk) {
4537 chunk.appendRight(content);
4538 } else {
4539 this.outro += content;
4540 }
4541 return this;
4542 }
4543
4544 clone() {
4545 const cloned = new MagicString(this.original, { filename: this.filename });
4546
4547 let originalChunk = this.firstChunk;
4548 let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
4549
4550 while (originalChunk) {
4551 cloned.byStart[clonedChunk.start] = clonedChunk;
4552 cloned.byEnd[clonedChunk.end] = clonedChunk;
4553
4554 const nextOriginalChunk = originalChunk.next;
4555 const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
4556
4557 if (nextClonedChunk) {
4558 clonedChunk.next = nextClonedChunk;
4559 nextClonedChunk.previous = clonedChunk;
4560
4561 clonedChunk = nextClonedChunk;
4562 }
4563
4564 originalChunk = nextOriginalChunk;
4565 }
4566
4567 cloned.lastChunk = clonedChunk;
4568
4569 if (this.indentExclusionRanges) {
4570 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
4571 }
4572
4573 cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
4574
4575 cloned.intro = this.intro;
4576 cloned.outro = this.outro;
4577
4578 return cloned;
4579 }
4580
4581 generateDecodedMap(options) {
4582 options = options || {};
4583
4584 const sourceIndex = 0;
4585 const names = Object.keys(this.storedNames);
4586 const mappings = new Mappings(options.hires);
4587
4588 const locate = getLocator(this.original);
4589
4590 if (this.intro) {
4591 mappings.advance(this.intro);
4592 }
4593
4594 this.firstChunk.eachNext((chunk) => {
4595 const loc = locate(chunk.start);
4596
4597 if (chunk.intro.length) mappings.advance(chunk.intro);
4598
4599 if (chunk.edited) {
4600 mappings.addEdit(
4601 sourceIndex,
4602 chunk.content,
4603 loc,
4604 chunk.storeName ? names.indexOf(chunk.original) : -1,
4605 );
4606 } else {
4607 mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
4608 }
4609
4610 if (chunk.outro.length) mappings.advance(chunk.outro);
4611 });
4612
4613 return {
4614 file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
4615 sources: [
4616 options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
4617 ],
4618 sourcesContent: options.includeContent ? [this.original] : undefined,
4619 names,
4620 mappings: mappings.raw,
4621 x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
4622 };
4623 }
4624
4625 generateMap(options) {
4626 return new SourceMap(this.generateDecodedMap(options));
4627 }
4628
4629 _ensureindentStr() {
4630 if (this.indentStr === undefined) {
4631 this.indentStr = guessIndent(this.original);
4632 }
4633 }
4634
4635 _getRawIndentString() {
4636 this._ensureindentStr();
4637 return this.indentStr;
4638 }
4639
4640 getIndentString() {
4641 this._ensureindentStr();
4642 return this.indentStr === null ? '\t' : this.indentStr;
4643 }
4644
4645 indent(indentStr, options) {
4646 const pattern = /^[^\r\n]/gm;
4647
4648 if (isObject(indentStr)) {
4649 options = indentStr;
4650 indentStr = undefined;
4651 }
4652
4653 if (indentStr === undefined) {
4654 this._ensureindentStr();
4655 indentStr = this.indentStr || '\t';
4656 }
4657
4658 if (indentStr === '') return this; // noop
4659
4660 options = options || {};
4661
4662 // Process exclusion ranges
4663 const isExcluded = {};
4664
4665 if (options.exclude) {
4666 const exclusions =
4667 typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
4668 exclusions.forEach((exclusion) => {
4669 for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
4670 isExcluded[i] = true;
4671 }
4672 });
4673 }
4674
4675 let shouldIndentNextCharacter = options.indentStart !== false;
4676 const replacer = (match) => {
4677 if (shouldIndentNextCharacter) return `${indentStr}${match}`;
4678 shouldIndentNextCharacter = true;
4679 return match;
4680 };
4681
4682 this.intro = this.intro.replace(pattern, replacer);
4683
4684 let charIndex = 0;
4685 let chunk = this.firstChunk;
4686
4687 while (chunk) {
4688 const end = chunk.end;
4689
4690 if (chunk.edited) {
4691 if (!isExcluded[charIndex]) {
4692 chunk.content = chunk.content.replace(pattern, replacer);
4693
4694 if (chunk.content.length) {
4695 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
4696 }
4697 }
4698 } else {
4699 charIndex = chunk.start;
4700
4701 while (charIndex < end) {
4702 if (!isExcluded[charIndex]) {
4703 const char = this.original[charIndex];
4704
4705 if (char === '\n') {
4706 shouldIndentNextCharacter = true;
4707 } else if (char !== '\r' && shouldIndentNextCharacter) {
4708 shouldIndentNextCharacter = false;
4709
4710 if (charIndex === chunk.start) {
4711 chunk.prependRight(indentStr);
4712 } else {
4713 this._splitChunk(chunk, charIndex);
4714 chunk = chunk.next;
4715 chunk.prependRight(indentStr);
4716 }
4717 }
4718 }
4719
4720 charIndex += 1;
4721 }
4722 }
4723
4724 charIndex = chunk.end;
4725 chunk = chunk.next;
4726 }
4727
4728 this.outro = this.outro.replace(pattern, replacer);
4729
4730 return this;
4731 }
4732
4733 insert() {
4734 throw new Error(
4735 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
4736 );
4737 }
4738
4739 insertLeft(index, content) {
4740 if (!warned.insertLeft) {
4741 console.warn(
4742 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
4743 ); // eslint-disable-line no-console
4744 warned.insertLeft = true;
4745 }
4746
4747 return this.appendLeft(index, content);
4748 }
4749
4750 insertRight(index, content) {
4751 if (!warned.insertRight) {
4752 console.warn(
4753 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
4754 ); // eslint-disable-line no-console
4755 warned.insertRight = true;
4756 }
4757
4758 return this.prependRight(index, content);
4759 }
4760
4761 move(start, end, index) {
4762 if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
4763
4764 this._split(start);
4765 this._split(end);
4766 this._split(index);
4767
4768 const first = this.byStart[start];
4769 const last = this.byEnd[end];
4770
4771 const oldLeft = first.previous;
4772 const oldRight = last.next;
4773
4774 const newRight = this.byStart[index];
4775 if (!newRight && last === this.lastChunk) return this;
4776 const newLeft = newRight ? newRight.previous : this.lastChunk;
4777
4778 if (oldLeft) oldLeft.next = oldRight;
4779 if (oldRight) oldRight.previous = oldLeft;
4780
4781 if (newLeft) newLeft.next = first;
4782 if (newRight) newRight.previous = last;
4783
4784 if (!first.previous) this.firstChunk = last.next;
4785 if (!last.next) {
4786 this.lastChunk = first.previous;
4787 this.lastChunk.next = null;
4788 }
4789
4790 first.previous = newLeft;
4791 last.next = newRight || null;
4792
4793 if (!newLeft) this.firstChunk = first;
4794 if (!newRight) this.lastChunk = last;
4795 return this;
4796 }
4797
4798 overwrite(start, end, content, options) {
4799 options = options || {};
4800 return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
4801 }
4802
4803 update(start, end, content, options) {
4804 if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
4805
4806 if (this.original.length !== 0) {
4807 while (start < 0) start += this.original.length;
4808 while (end < 0) end += this.original.length;
4809 }
4810
4811 if (end > this.original.length) throw new Error('end is out of bounds');
4812 if (start === end)
4813 throw new Error(
4814 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
4815 );
4816
4817 this._split(start);
4818 this._split(end);
4819
4820 if (options === true) {
4821 if (!warned.storeName) {
4822 console.warn(
4823 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
4824 ); // eslint-disable-line no-console
4825 warned.storeName = true;
4826 }
4827
4828 options = { storeName: true };
4829 }
4830 const storeName = options !== undefined ? options.storeName : false;
4831 const overwrite = options !== undefined ? options.overwrite : false;
4832
4833 if (storeName) {
4834 const original = this.original.slice(start, end);
4835 Object.defineProperty(this.storedNames, original, {
4836 writable: true,
4837 value: true,
4838 enumerable: true,
4839 });
4840 }
4841
4842 const first = this.byStart[start];
4843 const last = this.byEnd[end];
4844
4845 if (first) {
4846 let chunk = first;
4847 while (chunk !== last) {
4848 if (chunk.next !== this.byStart[chunk.end]) {
4849 throw new Error('Cannot overwrite across a split point');
4850 }
4851 chunk = chunk.next;
4852 chunk.edit('', false);
4853 }
4854
4855 first.edit(content, storeName, !overwrite);
4856 } else {
4857 // must be inserting at the end
4858 const newChunk = new Chunk(start, end, '').edit(content, storeName);
4859
4860 // TODO last chunk in the array may not be the last chunk, if it's moved...
4861 last.next = newChunk;
4862 newChunk.previous = last;
4863 }
4864 return this;
4865 }
4866
4867 prepend(content) {
4868 if (typeof content !== 'string') throw new TypeError('outro content must be a string');
4869
4870 this.intro = content + this.intro;
4871 return this;
4872 }
4873
4874 prependLeft(index, content) {
4875 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
4876
4877 this._split(index);
4878
4879 const chunk = this.byEnd[index];
4880
4881 if (chunk) {
4882 chunk.prependLeft(content);
4883 } else {
4884 this.intro = content + this.intro;
4885 }
4886 return this;
4887 }
4888
4889 prependRight(index, content) {
4890 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
4891
4892 this._split(index);
4893
4894 const chunk = this.byStart[index];
4895
4896 if (chunk) {
4897 chunk.prependRight(content);
4898 } else {
4899 this.outro = content + this.outro;
4900 }
4901 return this;
4902 }
4903
4904 remove(start, end) {
4905 if (this.original.length !== 0) {
4906 while (start < 0) start += this.original.length;
4907 while (end < 0) end += this.original.length;
4908 }
4909
4910 if (start === end) return this;
4911
4912 if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
4913 if (start > end) throw new Error('end must be greater than start');
4914
4915 this._split(start);
4916 this._split(end);
4917
4918 let chunk = this.byStart[start];
4919
4920 while (chunk) {
4921 chunk.intro = '';
4922 chunk.outro = '';
4923 chunk.edit('');
4924
4925 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
4926 }
4927 return this;
4928 }
4929
4930 reset(start, end) {
4931 if (this.original.length !== 0) {
4932 while (start < 0) start += this.original.length;
4933 while (end < 0) end += this.original.length;
4934 }
4935
4936 if (start === end) return this;
4937
4938 if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
4939 if (start > end) throw new Error('end must be greater than start');
4940
4941 this._split(start);
4942 this._split(end);
4943
4944 let chunk = this.byStart[start];
4945
4946 while (chunk) {
4947 chunk.reset();
4948
4949 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
4950 }
4951 return this;
4952 }
4953
4954 lastChar() {
4955 if (this.outro.length) return this.outro[this.outro.length - 1];
4956 let chunk = this.lastChunk;
4957 do {
4958 if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
4959 if (chunk.content.length) return chunk.content[chunk.content.length - 1];
4960 if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
4961 } while ((chunk = chunk.previous));
4962 if (this.intro.length) return this.intro[this.intro.length - 1];
4963 return '';
4964 }
4965
4966 lastLine() {
4967 let lineIndex = this.outro.lastIndexOf(n);
4968 if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
4969 let lineStr = this.outro;
4970 let chunk = this.lastChunk;
4971 do {
4972 if (chunk.outro.length > 0) {
4973 lineIndex = chunk.outro.lastIndexOf(n);
4974 if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
4975 lineStr = chunk.outro + lineStr;
4976 }
4977
4978 if (chunk.content.length > 0) {
4979 lineIndex = chunk.content.lastIndexOf(n);
4980 if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
4981 lineStr = chunk.content + lineStr;
4982 }
4983
4984 if (chunk.intro.length > 0) {
4985 lineIndex = chunk.intro.lastIndexOf(n);
4986 if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
4987 lineStr = chunk.intro + lineStr;
4988 }
4989 } while ((chunk = chunk.previous));
4990 lineIndex = this.intro.lastIndexOf(n);
4991 if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
4992 return this.intro + lineStr;
4993 }
4994
4995 slice(start = 0, end = this.original.length) {
4996 if (this.original.length !== 0) {
4997 while (start < 0) start += this.original.length;
4998 while (end < 0) end += this.original.length;
4999 }
5000
5001 let result = '';
5002
5003 // find start chunk
5004 let chunk = this.firstChunk;
5005 while (chunk && (chunk.start > start || chunk.end <= start)) {
5006 // found end chunk before start
5007 if (chunk.start < end && chunk.end >= end) {
5008 return result;
5009 }
5010
5011 chunk = chunk.next;
5012 }
5013
5014 if (chunk && chunk.edited && chunk.start !== start)
5015 throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
5016
5017 const startChunk = chunk;
5018 while (chunk) {
5019 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
5020 result += chunk.intro;
5021 }
5022
5023 const containsEnd = chunk.start < end && chunk.end >= end;
5024 if (containsEnd && chunk.edited && chunk.end !== end)
5025 throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
5026
5027 const sliceStart = startChunk === chunk ? start - chunk.start : 0;
5028 const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
5029
5030 result += chunk.content.slice(sliceStart, sliceEnd);
5031
5032 if (chunk.outro && (!containsEnd || chunk.end === end)) {
5033 result += chunk.outro;
5034 }
5035
5036 if (containsEnd) {
5037 break;
5038 }
5039
5040 chunk = chunk.next;
5041 }
5042
5043 return result;
5044 }
5045
5046 // TODO deprecate this? not really very useful
5047 snip(start, end) {
5048 const clone = this.clone();
5049 clone.remove(0, start);
5050 clone.remove(end, clone.original.length);
5051
5052 return clone;
5053 }
5054
5055 _split(index) {
5056 if (this.byStart[index] || this.byEnd[index]) return;
5057
5058 let chunk = this.lastSearchedChunk;
5059 const searchForward = index > chunk.end;
5060
5061 while (chunk) {
5062 if (chunk.contains(index)) return this._splitChunk(chunk, index);
5063
5064 chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
5065 }
5066 }
5067
5068 _splitChunk(chunk, index) {
5069 if (chunk.edited && chunk.content.length) {
5070 // zero-length edited chunks are a special case (overlapping replacements)
5071 const loc = getLocator(this.original)(index);
5072 throw new Error(
5073 `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
5074 );
5075 }
5076
5077 const newChunk = chunk.split(index);
5078
5079 this.byEnd[index] = chunk;
5080 this.byStart[index] = newChunk;
5081 this.byEnd[newChunk.end] = newChunk;
5082
5083 if (chunk === this.lastChunk) this.lastChunk = newChunk;
5084
5085 this.lastSearchedChunk = chunk;
5086 return true;
5087 }
5088
5089 toString() {
5090 let str = this.intro;
5091
5092 let chunk = this.firstChunk;
5093 while (chunk) {
5094 str += chunk.toString();
5095 chunk = chunk.next;
5096 }
5097
5098 return str + this.outro;
5099 }
5100
5101 isEmpty() {
5102 let chunk = this.firstChunk;
5103 do {
5104 if (
5105 (chunk.intro.length && chunk.intro.trim()) ||
5106 (chunk.content.length && chunk.content.trim()) ||
5107 (chunk.outro.length && chunk.outro.trim())
5108 )
5109 return false;
5110 } while ((chunk = chunk.next));
5111 return true;
5112 }
5113
5114 length() {
5115 let chunk = this.firstChunk;
5116 let length = 0;
5117 do {
5118 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
5119 } while ((chunk = chunk.next));
5120 return length;
5121 }
5122
5123 trimLines() {
5124 return this.trim('[\\r\\n]');
5125 }
5126
5127 trim(charType) {
5128 return this.trimStart(charType).trimEnd(charType);
5129 }
5130
5131 trimEndAborted(charType) {
5132 const rx = new RegExp((charType || '\\s') + '+$');
5133
5134 this.outro = this.outro.replace(rx, '');
5135 if (this.outro.length) return true;
5136
5137 let chunk = this.lastChunk;
5138
5139 do {
5140 const end = chunk.end;
5141 const aborted = chunk.trimEnd(rx);
5142
5143 // if chunk was trimmed, we have a new lastChunk
5144 if (chunk.end !== end) {
5145 if (this.lastChunk === chunk) {
5146 this.lastChunk = chunk.next;
5147 }
5148
5149 this.byEnd[chunk.end] = chunk;
5150 this.byStart[chunk.next.start] = chunk.next;
5151 this.byEnd[chunk.next.end] = chunk.next;
5152 }
5153
5154 if (aborted) return true;
5155 chunk = chunk.previous;
5156 } while (chunk);
5157
5158 return false;
5159 }
5160
5161 trimEnd(charType) {
5162 this.trimEndAborted(charType);
5163 return this;
5164 }
5165 trimStartAborted(charType) {
5166 const rx = new RegExp('^' + (charType || '\\s') + '+');
5167
5168 this.intro = this.intro.replace(rx, '');
5169 if (this.intro.length) return true;
5170
5171 let chunk = this.firstChunk;
5172
5173 do {
5174 const end = chunk.end;
5175 const aborted = chunk.trimStart(rx);
5176
5177 if (chunk.end !== end) {
5178 // special case...
5179 if (chunk === this.lastChunk) this.lastChunk = chunk.next;
5180
5181 this.byEnd[chunk.end] = chunk;
5182 this.byStart[chunk.next.start] = chunk.next;
5183 this.byEnd[chunk.next.end] = chunk.next;
5184 }
5185
5186 if (aborted) return true;
5187 chunk = chunk.next;
5188 } while (chunk);
5189
5190 return false;
5191 }
5192
5193 trimStart(charType) {
5194 this.trimStartAborted(charType);
5195 return this;
5196 }
5197
5198 hasChanged() {
5199 return this.original !== this.toString();
5200 }
5201
5202 _replaceRegexp(searchValue, replacement) {
5203 function getReplacement(match, str) {
5204 if (typeof replacement === 'string') {
5205 return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
5206 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
5207 if (i === '$') return '$';
5208 if (i === '&') return match[0];
5209 const num = +i;
5210 if (num < match.length) return match[+i];
5211 return `$${i}`;
5212 });
5213 } else {
5214 return replacement(...match, match.index, str, match.groups);
5215 }
5216 }
5217 function matchAll(re, str) {
5218 let match;
5219 const matches = [];
5220 while ((match = re.exec(str))) {
5221 matches.push(match);
5222 }
5223 return matches;
5224 }
5225 if (searchValue.global) {
5226 const matches = matchAll(searchValue, this.original);
5227 matches.forEach((match) => {
5228 if (match.index != null) {
5229 const replacement = getReplacement(match, this.original);
5230 if (replacement !== match[0]) {
5231 this.overwrite(
5232 match.index,
5233 match.index + match[0].length,
5234 replacement
5235 );
5236 }
5237 }
5238 });
5239 } else {
5240 const match = this.original.match(searchValue);
5241 if (match && match.index != null) {
5242 const replacement = getReplacement(match, this.original);
5243 if (replacement !== match[0]) {
5244 this.overwrite(
5245 match.index,
5246 match.index + match[0].length,
5247 replacement
5248 );
5249 }
5250 }
5251 }
5252 return this;
5253 }
5254
5255 _replaceString(string, replacement) {
5256 const { original } = this;
5257 const index = original.indexOf(string);
5258
5259 if (index !== -1) {
5260 this.overwrite(index, index + string.length, replacement);
5261 }
5262
5263 return this;
5264 }
5265
5266 replace(searchValue, replacement) {
5267 if (typeof searchValue === 'string') {
5268 return this._replaceString(searchValue, replacement);
5269 }
5270
5271 return this._replaceRegexp(searchValue, replacement);
5272 }
5273
5274 _replaceAllString(string, replacement) {
5275 const { original } = this;
5276 const stringLength = string.length;
5277 for (
5278 let index = original.indexOf(string);
5279 index !== -1;
5280 index = original.indexOf(string, index + stringLength)
5281 ) {
5282 const previous = original.slice(index, index + stringLength);
5283 if (previous !== replacement)
5284 this.overwrite(index, index + stringLength, replacement);
5285 }
5286
5287 return this;
5288 }
5289
5290 replaceAll(searchValue, replacement) {
5291 if (typeof searchValue === 'string') {
5292 return this._replaceAllString(searchValue, replacement);
5293 }
5294
5295 if (!searchValue.global) {
5296 throw new TypeError(
5297 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
5298 );
5299 }
5300
5301 return this._replaceRegexp(searchValue, replacement);
5302 }
5303}
5304
5305const debug$1 = createDebugger("vite:sourcemap", {
5306 onlyWhenFocused: true
5307});
5308function genSourceMapUrl(map) {
5309 if (typeof map !== "string") {
5310 map = JSON.stringify(map);
5311 }
5312 return `data:application/json;base64,${Buffer.from(map).toString("base64")}`;
5313}
5314function getCodeWithSourcemap(type, code, map) {
5315 if (debug$1) {
5316 code += `
5317/*${JSON.stringify(map, null, 2).replace(/\*\//g, "*\\/")}*/
5318`;
5319 }
5320 if (type === "js") {
5321 code += `
5322//# sourceMappingURL=${genSourceMapUrl(map)}`;
5323 } else if (type === "css") {
5324 code += `
5325/*# sourceMappingURL=${genSourceMapUrl(map)} */`;
5326 }
5327 return code;
5328}
5329
5330const debug = createDebugger("vite:send", {
5331 onlyWhenFocused: true
5332});
5333const alias = {
5334 js: "text/javascript",
5335 css: "text/css",
5336 html: "text/html",
5337 json: "application/json"
5338};
5339function send(req, res, content, type, options) {
5340 const {
5341 etag = getEtag(content, { weak: true }),
5342 cacheControl = "no-cache",
5343 headers,
5344 map
5345 } = options;
5346 if (res.writableEnded) {
5347 return;
5348 }
5349 if (req.headers["if-none-match"] === etag) {
5350 res.statusCode = 304;
5351 res.end();
5352 return;
5353 }
5354 res.setHeader("Content-Type", alias[type] || type);
5355 res.setHeader("Cache-Control", cacheControl);
5356 res.setHeader("Etag", etag);
5357 if (headers) {
5358 for (const name in headers) {
5359 res.setHeader(name, headers[name]);
5360 }
5361 }
5362 if (map && "version" in map && map.mappings) {
5363 if (type === "js" || type === "css") {
5364 content = getCodeWithSourcemap(type, content.toString(), map);
5365 }
5366 } else if (type === "js" && (!map || map.mappings !== "")) {
5367 const code = content.toString();
5368 if (convertSourceMap.mapFileCommentRegex.test(code)) {
5369 debug?.(`Skipped injecting fallback sourcemap for ${req.url}`);
5370 } else {
5371 const urlWithoutTimestamp = removeTimestampQuery(req.url);
5372 const ms = new MagicString(code);
5373 content = getCodeWithSourcemap(
5374 type,
5375 code,
5376 ms.generateMap({
5377 source: path$3.basename(urlWithoutTimestamp),
5378 hires: "boundary",
5379 includeContent: true
5380 })
5381 );
5382 }
5383 }
5384 res.statusCode = 200;
5385 res.end(content);
5386 return;
5387}
5388
5389const LogLevels = {
5390 silent: 0,
5391 error: 1,
5392 warn: 2,
5393 info: 3
5394};
5395let lastType;
5396let lastMsg;
5397let sameCount = 0;
5398function clearScreen() {
5399 const repeatCount = process.stdout.rows - 2;
5400 const blank = repeatCount > 0 ? "\n".repeat(repeatCount) : "";
5401 console.log(blank);
5402 readline.cursorTo(process.stdout, 0, 0);
5403 readline.clearScreenDown(process.stdout);
5404}
5405let timeFormatter;
5406function getTimeFormatter() {
5407 timeFormatter ??= new Intl.DateTimeFormat(void 0, {
5408 hour: "numeric",
5409 minute: "numeric",
5410 second: "numeric"
5411 });
5412 return timeFormatter;
5413}
5414function createLogger(level = "info", options = {}) {
5415 if (options.customLogger) {
5416 return options.customLogger;
5417 }
5418 const loggedErrors = /* @__PURE__ */ new WeakSet();
5419 const { prefix = "[vite]", allowClearScreen = true } = options;
5420 const thresh = LogLevels[level];
5421 const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
5422 const clear = canClearScreen ? clearScreen : () => {
5423 };
5424 function format(type, msg, options2 = {}) {
5425 if (options2.timestamp) {
5426 let tag = "";
5427 if (type === "info") {
5428 tag = colors.cyan(colors.bold(prefix));
5429 } else if (type === "warn") {
5430 tag = colors.yellow(colors.bold(prefix));
5431 } else {
5432 tag = colors.red(colors.bold(prefix));
5433 }
5434 return `${colors.dim(getTimeFormatter().format(/* @__PURE__ */ new Date()))} ${tag} ${msg}`;
5435 } else {
5436 return msg;
5437 }
5438 }
5439 function output(type, msg, options2 = {}) {
5440 if (thresh >= LogLevels[type]) {
5441 const method = type === "info" ? "log" : type;
5442 if (options2.error) {
5443 loggedErrors.add(options2.error);
5444 }
5445 if (canClearScreen) {
5446 if (type === lastType && msg === lastMsg) {
5447 sameCount++;
5448 clear();
5449 console[method](
5450 format(type, msg, options2),
5451 colors.yellow(`(x${sameCount + 1})`)
5452 );
5453 } else {
5454 sameCount = 0;
5455 lastMsg = msg;
5456 lastType = type;
5457 if (options2.clear) {
5458 clear();
5459 }
5460 console[method](format(type, msg, options2));
5461 }
5462 } else {
5463 console[method](format(type, msg, options2));
5464 }
5465 }
5466 }
5467 const warnedMessages = /* @__PURE__ */ new Set();
5468 const logger = {
5469 hasWarned: false,
5470 info(msg, opts) {
5471 output("info", msg, opts);
5472 },
5473 warn(msg, opts) {
5474 logger.hasWarned = true;
5475 output("warn", msg, opts);
5476 },
5477 warnOnce(msg, opts) {
5478 if (warnedMessages.has(msg)) return;
5479 logger.hasWarned = true;
5480 output("warn", msg, opts);
5481 warnedMessages.add(msg);
5482 },
5483 error(msg, opts) {
5484 logger.hasWarned = true;
5485 output("error", msg, opts);
5486 },
5487 clearScreen(type) {
5488 if (thresh >= LogLevels[type]) {
5489 clear();
5490 }
5491 },
5492 hasErrorLogged(error) {
5493 return loggedErrors.has(error);
5494 }
5495 };
5496 return logger;
5497}
5498
5499const ROOT_FILES = [
5500 // '.git',
5501 // https://pnpm.io/workspaces/
5502 "pnpm-workspace.yaml",
5503 // https://rushjs.io/pages/advanced/config_files/
5504 // 'rush.json',
5505 // https://nx.dev/latest/react/getting-started/nx-setup
5506 // 'workspace.json',
5507 // 'nx.json',
5508 // https://github.com/lerna/lerna#lernajson
5509 "lerna.json"
5510];
5511function hasWorkspacePackageJSON(root) {
5512 const path = path$3.join(root, "package.json");
5513 if (!isFileReadable(path)) {
5514 return false;
5515 }
5516 try {
5517 const content = JSON.parse(fs$1.readFileSync(path, "utf-8")) || {};
5518 return !!content.workspaces;
5519 } catch {
5520 return false;
5521 }
5522}
5523function hasRootFile(root) {
5524 return ROOT_FILES.some((file) => fs$1.existsSync(path$3.join(root, file)));
5525}
5526function hasPackageJSON(root) {
5527 const path = path$3.join(root, "package.json");
5528 return fs$1.existsSync(path);
5529}
5530function searchForPackageRoot(current, root = current) {
5531 if (hasPackageJSON(current)) return current;
5532 const dir = path$3.dirname(current);
5533 if (!dir || dir === current) return root;
5534 return searchForPackageRoot(dir, root);
5535}
5536function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
5537 if (hasRootFile(current)) return current;
5538 if (hasWorkspacePackageJSON(current)) return current;
5539 const dir = path$3.dirname(current);
5540 if (!dir || dir === current) return root;
5541 return searchForWorkspaceRoot(dir, root);
5542}
5543
5544function isFileServingAllowed(url, server) {
5545 if (!server.config.server.fs.strict) return true;
5546 const file = fsPathFromUrl(url);
5547 if (server._fsDenyGlob(file)) return false;
5548 if (server.moduleGraph.safeModulesPath.has(file)) return true;
5549 if (server.config.server.fs.allow.some(
5550 (uri) => isSameFileUri(uri, file) || isParentDirectory(uri, file)
5551 ))
5552 return true;
5553 return false;
5554}
5555
5556var main$1 = {exports: {}};
5557
5558var name = "dotenv";
5559var version$1 = "16.4.5";
5560var description = "Loads environment variables from .env file";
5561var main = "lib/main.js";
5562var types = "lib/main.d.ts";
5563var exports$1 = {
5564 ".": {
5565 types: "./lib/main.d.ts",
5566 require: "./lib/main.js",
5567 "default": "./lib/main.js"
5568 },
5569 "./config": "./config.js",
5570 "./config.js": "./config.js",
5571 "./lib/env-options": "./lib/env-options.js",
5572 "./lib/env-options.js": "./lib/env-options.js",
5573 "./lib/cli-options": "./lib/cli-options.js",
5574 "./lib/cli-options.js": "./lib/cli-options.js",
5575 "./package.json": "./package.json"
5576};
5577var scripts = {
5578 "dts-check": "tsc --project tests/types/tsconfig.json",
5579 lint: "standard",
5580 "lint-readme": "standard-markdown",
5581 pretest: "npm run lint && npm run dts-check",
5582 test: "tap tests/*.js --100 -Rspec",
5583 "test:coverage": "tap --coverage-report=lcov",
5584 prerelease: "npm test",
5585 release: "standard-version"
5586};
5587var repository = {
5588 type: "git",
5589 url: "git://github.com/motdotla/dotenv.git"
5590};
5591var funding = "https://dotenvx.com";
5592var keywords = [
5593 "dotenv",
5594 "env",
5595 ".env",
5596 "environment",
5597 "variables",
5598 "config",
5599 "settings"
5600];
5601var readmeFilename = "README.md";
5602var license = "BSD-2-Clause";
5603var devDependencies = {
5604 "@definitelytyped/dtslint": "^0.0.133",
5605 "@types/node": "^18.11.3",
5606 decache: "^4.6.1",
5607 sinon: "^14.0.1",
5608 standard: "^17.0.0",
5609 "standard-markdown": "^7.1.0",
5610 "standard-version": "^9.5.0",
5611 tap: "^16.3.0",
5612 tar: "^6.1.11",
5613 typescript: "^4.8.4"
5614};
5615var engines = {
5616 node: ">=12"
5617};
5618var browser = {
5619 fs: false
5620};
5621var require$$4 = {
5622 name: name,
5623 version: version$1,
5624 description: description,
5625 main: main,
5626 types: types,
5627 exports: exports$1,
5628 scripts: scripts,
5629 repository: repository,
5630 funding: funding,
5631 keywords: keywords,
5632 readmeFilename: readmeFilename,
5633 license: license,
5634 devDependencies: devDependencies,
5635 engines: engines,
5636 browser: browser
5637};
5638
5639const fs = fs$2;
5640const path = require$$0$1;
5641const os = require$$2;
5642const crypto = require$$0$2;
5643const packageJson = require$$4;
5644
5645const version = packageJson.version;
5646
5647const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
5648
5649// Parse src into an Object
5650function parse (src) {
5651 const obj = {};
5652
5653 // Convert buffer to string
5654 let lines = src.toString();
5655
5656 // Convert line breaks to same format
5657 lines = lines.replace(/\r\n?/mg, '\n');
5658
5659 let match;
5660 while ((match = LINE.exec(lines)) != null) {
5661 const key = match[1];
5662
5663 // Default undefined or null to empty string
5664 let value = (match[2] || '');
5665
5666 // Remove whitespace
5667 value = value.trim();
5668
5669 // Check if double quoted
5670 const maybeQuote = value[0];
5671
5672 // Remove surrounding quotes
5673 value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2');
5674
5675 // Expand newlines if double quoted
5676 if (maybeQuote === '"') {
5677 value = value.replace(/\\n/g, '\n');
5678 value = value.replace(/\\r/g, '\r');
5679 }
5680
5681 // Add to object
5682 obj[key] = value;
5683 }
5684
5685 return obj
5686}
5687
5688function _parseVault (options) {
5689 const vaultPath = _vaultPath(options);
5690
5691 // Parse .env.vault
5692 const result = DotenvModule.configDotenv({ path: vaultPath });
5693 if (!result.parsed) {
5694 const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
5695 err.code = 'MISSING_DATA';
5696 throw err
5697 }
5698
5699 // handle scenario for comma separated keys - for use with key rotation
5700 // example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod"
5701 const keys = _dotenvKey(options).split(',');
5702 const length = keys.length;
5703
5704 let decrypted;
5705 for (let i = 0; i < length; i++) {
5706 try {
5707 // Get full key
5708 const key = keys[i].trim();
5709
5710 // Get instructions for decrypt
5711 const attrs = _instructions(result, key);
5712
5713 // Decrypt
5714 decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
5715
5716 break
5717 } catch (error) {
5718 // last key
5719 if (i + 1 >= length) {
5720 throw error
5721 }
5722 // try next key
5723 }
5724 }
5725
5726 // Parse decrypted .env string
5727 return DotenvModule.parse(decrypted)
5728}
5729
5730function _log (message) {
5731 console.log(`[dotenv@${version}][INFO] ${message}`);
5732}
5733
5734function _warn (message) {
5735 console.log(`[dotenv@${version}][WARN] ${message}`);
5736}
5737
5738function _debug (message) {
5739 console.log(`[dotenv@${version}][DEBUG] ${message}`);
5740}
5741
5742function _dotenvKey (options) {
5743 // prioritize developer directly setting options.DOTENV_KEY
5744 if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
5745 return options.DOTENV_KEY
5746 }
5747
5748 // secondary infra already contains a DOTENV_KEY environment variable
5749 if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
5750 return process.env.DOTENV_KEY
5751 }
5752
5753 // fallback to empty string
5754 return ''
5755}
5756
5757function _instructions (result, dotenvKey) {
5758 // Parse DOTENV_KEY. Format is a URI
5759 let uri;
5760 try {
5761 uri = new URL(dotenvKey);
5762 } catch (error) {
5763 if (error.code === 'ERR_INVALID_URL') {
5764 const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development');
5765 err.code = 'INVALID_DOTENV_KEY';
5766 throw err
5767 }
5768
5769 throw error
5770 }
5771
5772 // Get decrypt key
5773 const key = uri.password;
5774 if (!key) {
5775 const err = new Error('INVALID_DOTENV_KEY: Missing key part');
5776 err.code = 'INVALID_DOTENV_KEY';
5777 throw err
5778 }
5779
5780 // Get environment
5781 const environment = uri.searchParams.get('environment');
5782 if (!environment) {
5783 const err = new Error('INVALID_DOTENV_KEY: Missing environment part');
5784 err.code = 'INVALID_DOTENV_KEY';
5785 throw err
5786 }
5787
5788 // Get ciphertext payload
5789 const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
5790 const ciphertext = result.parsed[environmentKey]; // DOTENV_VAULT_PRODUCTION
5791 if (!ciphertext) {
5792 const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
5793 err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT';
5794 throw err
5795 }
5796
5797 return { ciphertext, key }
5798}
5799
5800function _vaultPath (options) {
5801 let possibleVaultPath = null;
5802
5803 if (options && options.path && options.path.length > 0) {
5804 if (Array.isArray(options.path)) {
5805 for (const filepath of options.path) {
5806 if (fs.existsSync(filepath)) {
5807 possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`;
5808 }
5809 }
5810 } else {
5811 possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`;
5812 }
5813 } else {
5814 possibleVaultPath = path.resolve(process.cwd(), '.env.vault');
5815 }
5816
5817 if (fs.existsSync(possibleVaultPath)) {
5818 return possibleVaultPath
5819 }
5820
5821 return null
5822}
5823
5824function _resolveHome (envPath) {
5825 return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
5826}
5827
5828function _configVault (options) {
5829 _log('Loading env from encrypted .env.vault');
5830
5831 const parsed = DotenvModule._parseVault(options);
5832
5833 let processEnv = process.env;
5834 if (options && options.processEnv != null) {
5835 processEnv = options.processEnv;
5836 }
5837
5838 DotenvModule.populate(processEnv, parsed, options);
5839
5840 return { parsed }
5841}
5842
5843function configDotenv (options) {
5844 const dotenvPath = path.resolve(process.cwd(), '.env');
5845 let encoding = 'utf8';
5846 const debug = Boolean(options && options.debug);
5847
5848 if (options && options.encoding) {
5849 encoding = options.encoding;
5850 } else {
5851 if (debug) {
5852 _debug('No encoding is specified. UTF-8 is used by default');
5853 }
5854 }
5855
5856 let optionPaths = [dotenvPath]; // default, look for .env
5857 if (options && options.path) {
5858 if (!Array.isArray(options.path)) {
5859 optionPaths = [_resolveHome(options.path)];
5860 } else {
5861 optionPaths = []; // reset default
5862 for (const filepath of options.path) {
5863 optionPaths.push(_resolveHome(filepath));
5864 }
5865 }
5866 }
5867
5868 // Build the parsed data in a temporary object (because we need to return it). Once we have the final
5869 // parsed data, we will combine it with process.env (or options.processEnv if provided).
5870 let lastError;
5871 const parsedAll = {};
5872 for (const path of optionPaths) {
5873 try {
5874 // Specifying an encoding returns a string instead of a buffer
5875 const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }));
5876
5877 DotenvModule.populate(parsedAll, parsed, options);
5878 } catch (e) {
5879 if (debug) {
5880 _debug(`Failed to load ${path} ${e.message}`);
5881 }
5882 lastError = e;
5883 }
5884 }
5885
5886 let processEnv = process.env;
5887 if (options && options.processEnv != null) {
5888 processEnv = options.processEnv;
5889 }
5890
5891 DotenvModule.populate(processEnv, parsedAll, options);
5892
5893 if (lastError) {
5894 return { parsed: parsedAll, error: lastError }
5895 } else {
5896 return { parsed: parsedAll }
5897 }
5898}
5899
5900// Populates process.env from .env file
5901function config (options) {
5902 // fallback to original dotenv if DOTENV_KEY is not set
5903 if (_dotenvKey(options).length === 0) {
5904 return DotenvModule.configDotenv(options)
5905 }
5906
5907 const vaultPath = _vaultPath(options);
5908
5909 // dotenvKey exists but .env.vault file does not exist
5910 if (!vaultPath) {
5911 _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
5912
5913 return DotenvModule.configDotenv(options)
5914 }
5915
5916 return DotenvModule._configVault(options)
5917}
5918
5919function decrypt (encrypted, keyStr) {
5920 const key = Buffer.from(keyStr.slice(-64), 'hex');
5921 let ciphertext = Buffer.from(encrypted, 'base64');
5922
5923 const nonce = ciphertext.subarray(0, 12);
5924 const authTag = ciphertext.subarray(-16);
5925 ciphertext = ciphertext.subarray(12, -16);
5926
5927 try {
5928 const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce);
5929 aesgcm.setAuthTag(authTag);
5930 return `${aesgcm.update(ciphertext)}${aesgcm.final()}`
5931 } catch (error) {
5932 const isRange = error instanceof RangeError;
5933 const invalidKeyLength = error.message === 'Invalid key length';
5934 const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data';
5935
5936 if (isRange || invalidKeyLength) {
5937 const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)');
5938 err.code = 'INVALID_DOTENV_KEY';
5939 throw err
5940 } else if (decryptionFailed) {
5941 const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY');
5942 err.code = 'DECRYPTION_FAILED';
5943 throw err
5944 } else {
5945 throw error
5946 }
5947 }
5948}
5949
5950// Populate process.env with parsed values
5951function populate (processEnv, parsed, options = {}) {
5952 const debug = Boolean(options && options.debug);
5953 const override = Boolean(options && options.override);
5954
5955 if (typeof parsed !== 'object') {
5956 const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate');
5957 err.code = 'OBJECT_REQUIRED';
5958 throw err
5959 }
5960
5961 // Set process.env
5962 for (const key of Object.keys(parsed)) {
5963 if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
5964 if (override === true) {
5965 processEnv[key] = parsed[key];
5966 }
5967
5968 if (debug) {
5969 if (override === true) {
5970 _debug(`"${key}" is already defined and WAS overwritten`);
5971 } else {
5972 _debug(`"${key}" is already defined and was NOT overwritten`);
5973 }
5974 }
5975 } else {
5976 processEnv[key] = parsed[key];
5977 }
5978 }
5979}
5980
5981const DotenvModule = {
5982 configDotenv,
5983 _configVault,
5984 _parseVault,
5985 config,
5986 decrypt,
5987 parse,
5988 populate
5989};
5990
5991main$1.exports.configDotenv = DotenvModule.configDotenv;
5992main$1.exports._configVault = DotenvModule._configVault;
5993main$1.exports._parseVault = DotenvModule._parseVault;
5994main$1.exports.config = DotenvModule.config;
5995main$1.exports.decrypt = DotenvModule.decrypt;
5996var parse_1 = main$1.exports.parse = DotenvModule.parse;
5997main$1.exports.populate = DotenvModule.populate;
5998
5999main$1.exports = DotenvModule;
6000
6001// * /
6002// * (\\)? # is it escaped with a backslash?
6003// * (\$) # literal $
6004// * (?!\() # shouldnt be followed by parenthesis
6005// * (\{?) # first brace wrap opening
6006// * ([\w.]+) # key
6007// * (?::-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))? # optional default nested 3 times
6008// * (\}?) # last brace warp closing
6009// * /xi
6010
6011const DOTENV_SUBSTITUTION_REGEX = /(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;
6012
6013function _resolveEscapeSequences (value) {
6014 return value.replace(/\\\$/g, '$')
6015}
6016
6017function interpolate (value, processEnv, parsed) {
6018 return value.replace(DOTENV_SUBSTITUTION_REGEX, (match, escaped, dollarSign, openBrace, key, defaultValue, closeBrace) => {
6019 if (escaped === '\\') {
6020 return match.slice(1)
6021 } else {
6022 if (processEnv[key]) {
6023 if (processEnv[key] === parsed[key]) {
6024 return processEnv[key]
6025 } else {
6026 // scenario: PASSWORD_EXPAND_NESTED=${PASSWORD_EXPAND}
6027 return interpolate(processEnv[key], processEnv, parsed)
6028 }
6029 }
6030
6031 if (parsed[key]) {
6032 // avoid recursion from EXPAND_SELF=$EXPAND_SELF
6033 if (parsed[key] === value) {
6034 return parsed[key]
6035 } else {
6036 return interpolate(parsed[key], processEnv, parsed)
6037 }
6038 }
6039
6040 if (defaultValue) {
6041 if (defaultValue.startsWith('$')) {
6042 return interpolate(defaultValue, processEnv, parsed)
6043 } else {
6044 return defaultValue
6045 }
6046 }
6047
6048 return ''
6049 }
6050 })
6051}
6052
6053function expand (options) {
6054 let processEnv = process.env;
6055 if (options && options.processEnv != null) {
6056 processEnv = options.processEnv;
6057 }
6058
6059 for (const key in options.parsed) {
6060 let value = options.parsed[key];
6061
6062 const inProcessEnv = Object.prototype.hasOwnProperty.call(processEnv, key);
6063 if (inProcessEnv) {
6064 if (processEnv[key] === options.parsed[key]) {
6065 // assume was set to processEnv from the .env file if the values match and therefore interpolate
6066 value = interpolate(value, processEnv, options.parsed);
6067 } else {
6068 // do not interpolate - assume processEnv had the intended value even if containing a $.
6069 value = processEnv[key];
6070 }
6071 } else {
6072 // not inProcessEnv so assume interpolation for this .env key
6073 value = interpolate(value, processEnv, options.parsed);
6074 }
6075
6076 options.parsed[key] = _resolveEscapeSequences(value);
6077 }
6078
6079 for (const processKey in options.parsed) {
6080 processEnv[processKey] = options.parsed[processKey];
6081 }
6082
6083 return options
6084}
6085
6086var expand_1 = expand;
6087
6088function getEnvFilesForMode(mode, envDir) {
6089 return [
6090 /** default file */
6091 `.env`,
6092 /** local file */
6093 `.env.local`,
6094 /** mode file */
6095 `.env.${mode}`,
6096 /** mode local file */
6097 `.env.${mode}.local`
6098 ].map((file) => normalizePath(path$3.join(envDir, file)));
6099}
6100function loadEnv(mode, envDir, prefixes = "VITE_") {
6101 if (mode === "local") {
6102 throw new Error(
6103 `"local" cannot be used as a mode name because it conflicts with the .local postfix for .env files.`
6104 );
6105 }
6106 prefixes = arraify(prefixes);
6107 const env = {};
6108 const envFiles = getEnvFilesForMode(mode, envDir);
6109 const parsed = Object.fromEntries(
6110 envFiles.flatMap((filePath) => {
6111 if (!tryStatSync(filePath)?.isFile()) return [];
6112 return Object.entries(parse_1(fs$1.readFileSync(filePath)));
6113 })
6114 );
6115 if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === void 0) {
6116 process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV;
6117 }
6118 if (parsed.BROWSER && process.env.BROWSER === void 0) {
6119 process.env.BROWSER = parsed.BROWSER;
6120 }
6121 if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === void 0) {
6122 process.env.BROWSER_ARGS = parsed.BROWSER_ARGS;
6123 }
6124 const processEnv = { ...process.env };
6125 expand_1({ parsed, processEnv });
6126 for (const [key, value] of Object.entries(parsed)) {
6127 if (prefixes.some((prefix) => key.startsWith(prefix))) {
6128 env[key] = value;
6129 }
6130 }
6131 for (const key in process.env) {
6132 if (prefixes.some((prefix) => key.startsWith(prefix))) {
6133 env[key] = process.env[key];
6134 }
6135 }
6136 return env;
6137}
6138function resolveEnvPrefix({
6139 envPrefix = "VITE_"
6140}) {
6141 envPrefix = arraify(envPrefix);
6142 if (envPrefix.includes("")) {
6143 throw new Error(
6144 `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
6145 );
6146 }
6147 return envPrefix;
6148}
6149
6150exports.esbuildVersion = esbuild.version;
6151exports.createFilter = createFilter;
6152exports.createLogger = createLogger;
6153exports.isCSSRequest = isCSSRequest;
6154exports.isFileServingAllowed = isFileServingAllowed;
6155exports.loadEnv = loadEnv;
6156exports.mergeAlias = mergeAlias;
6157exports.mergeConfig = mergeConfig;
6158exports.normalizePath = normalizePath;
6159exports.resolveEnvPrefix = resolveEnvPrefix;
6160exports.rollupVersion = rollupVersion;
6161exports.searchForWorkspaceRoot = searchForWorkspaceRoot;
6162exports.send = send;
6163exports.splitVendorChunk = splitVendorChunk;
6164exports.splitVendorChunkPlugin = splitVendorChunkPlugin;
6165exports.version = VERSION;
Note: See TracBrowser for help on using the repository browser.