You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6367 lines
163 KiB

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