import * as fs$8 from 'node:fs'; import fs__default, { promises as promises$1, existsSync as existsSync$1, readFileSync as readFileSync$1 } from 'node:fs'; import fsp, { constants as constants$9 } from 'node:fs/promises'; import path$d, { posix as posix$1, isAbsolute as isAbsolute$1, join as join$1, resolve as resolve$4, normalize, dirname as dirname$2, relative as relative$2, basename as basename$2, extname as extname$1 } from 'node:path'; import require$$1$1, { fileURLToPath as fileURLToPath$1, URL as URL$3, pathToFileURL as pathToFileURL$1 } from 'node:url'; import { promisify as promisify$4, format as format$2, inspect, stripVTControlCharacters } from 'node:util'; import { performance } from 'node:perf_hooks'; import require$$0$5, { createRequire as createRequire$1, builtinModules } from 'node:module'; import esbuild, { transform as transform$1, formatMessages, build as build$b } from 'esbuild'; import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, wildcardHosts, loopbackHosts, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, DEFAULT_ASSETS_INLINE_LIMIT, ENV_ENTRY, SPECIAL_QUERY_RE, DEP_VERSION_RE, DEV_PROD_CONDITION, JS_TYPES_RE, KNOWN_ASSET_TYPES, CSS_LANGS_RE, METADATA_FILENAME, ESBUILD_MODULES_TARGET, ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, VITE_PACKAGE_DIR, DEFAULT_DEV_PORT, CLIENT_DIR, VERSION, ROLLUP_HOOKS, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES, DEFAULT_PREVIEW_PORT, DEFAULT_CLIENT_MAIN_FIELDS, DEFAULT_SERVER_MAIN_FIELDS, DEFAULT_CLIENT_CONDITIONS, DEFAULT_SERVER_CONDITIONS } from '../constants.js'; import require$$0$2, { posix, win32, isAbsolute, resolve as resolve$3, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join, sep } from 'path'; import require$$0$3, { existsSync, readFileSync, statSync, readdirSync } from 'fs'; import childProcess$2, { exec, execFile, execSync } from 'node:child_process'; import { createServer as createServer$3, STATUS_CODES, get as get$2 } from 'node:http'; import { createServer as createServer$2, get as get$1 } from 'node:https'; import require$$0$4 from 'tty'; import require$$1 from 'util'; import require$$4$1 from 'net'; import require$$0$7 from 'events'; import require$$0$6 from 'url'; import require$$1$2 from 'http'; import require$$0$8 from 'stream'; import require$$2 from 'os'; import require$$2$1 from 'child_process'; import os$3 from 'node:os'; import crypto$2 from 'node:crypto'; import { promises } from 'node:dns'; import { ModuleRunner, ESModulesEvaluator } from 'vite/module-runner'; import { parseAstAsync, parseAst } from 'rollup/parseAst'; import { createRequire as createRequire$2 } from 'module'; import readline from 'node:readline'; import process$1 from 'node:process'; import { Buffer as Buffer$1 } from 'node:buffer'; import { EventEmitter as EventEmitter$4 } from 'node:events'; import require$$3 from 'crypto'; import assert$1 from 'node:assert'; import v8 from 'node:v8'; import { Worker as Worker$1 } from 'node:worker_threads'; import zlib$1 from 'zlib'; import require$$0$9 from 'buffer'; import require$$1$3 from 'https'; import require$$4$2 from 'tls'; import require$$4$3 from 'assert'; import * as qs from 'node:querystring'; import { gzip } from 'node:zlib'; import { createRequire as __cjs_createRequire } from 'node:module'; const __require = __cjs_createRequire(import.meta.url); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var picocolors = {exports: {}}; let p = process || {}, argv = p.argv || [], env$1 = p.env || {}; let isColorSupported = !(!!env$1.NO_COLOR || argv.includes("--no-color")) && (!!env$1.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env$1.TERM !== "dumb") || !!env$1.CI); let formatter = (open, close, replace = open) => input => { let string = "" + input, index = string.indexOf(close, open.length); return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close }; let replaceClose = (string, close, replace, index) => { let result = "", cursor = 0; do { result += string.substring(cursor, index) + replace; cursor = index + close.length; index = string.indexOf(close, cursor); } while (~index) return result + string.substring(cursor) }; let createColors = (enabled = isColorSupported) => { let f = enabled ? formatter : () => String; return { isColorSupported: enabled, reset: f("\x1b[0m", "\x1b[0m"), bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), italic: f("\x1b[3m", "\x1b[23m"), underline: f("\x1b[4m", "\x1b[24m"), inverse: f("\x1b[7m", "\x1b[27m"), hidden: f("\x1b[8m", "\x1b[28m"), strikethrough: f("\x1b[9m", "\x1b[29m"), black: f("\x1b[30m", "\x1b[39m"), red: f("\x1b[31m", "\x1b[39m"), green: f("\x1b[32m", "\x1b[39m"), yellow: f("\x1b[33m", "\x1b[39m"), blue: f("\x1b[34m", "\x1b[39m"), magenta: f("\x1b[35m", "\x1b[39m"), cyan: f("\x1b[36m", "\x1b[39m"), white: f("\x1b[37m", "\x1b[39m"), gray: f("\x1b[90m", "\x1b[39m"), bgBlack: f("\x1b[40m", "\x1b[49m"), bgRed: f("\x1b[41m", "\x1b[49m"), bgGreen: f("\x1b[42m", "\x1b[49m"), bgYellow: f("\x1b[43m", "\x1b[49m"), bgBlue: f("\x1b[44m", "\x1b[49m"), bgMagenta: f("\x1b[45m", "\x1b[49m"), bgCyan: f("\x1b[46m", "\x1b[49m"), bgWhite: f("\x1b[47m", "\x1b[49m"), blackBright: f("\x1b[90m", "\x1b[39m"), redBright: f("\x1b[91m", "\x1b[39m"), greenBright: f("\x1b[92m", "\x1b[39m"), yellowBright: f("\x1b[93m", "\x1b[39m"), blueBright: f("\x1b[94m", "\x1b[39m"), magentaBright: f("\x1b[95m", "\x1b[39m"), cyanBright: f("\x1b[96m", "\x1b[39m"), whiteBright: f("\x1b[97m", "\x1b[39m"), bgBlackBright: f("\x1b[100m", "\x1b[49m"), bgRedBright: f("\x1b[101m", "\x1b[49m"), bgGreenBright: f("\x1b[102m", "\x1b[49m"), bgYellowBright: f("\x1b[103m", "\x1b[49m"), bgBlueBright: f("\x1b[104m", "\x1b[49m"), bgMagentaBright: f("\x1b[105m", "\x1b[49m"), bgCyanBright: f("\x1b[106m", "\x1b[49m"), bgWhiteBright: f("\x1b[107m", "\x1b[49m"), } }; picocolors.exports = createColors(); picocolors.exports.createColors = createColors; var picocolorsExports = picocolors.exports; var colors$1 = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports); var utils$d = {}; const WIN_SLASH$1 = '\\\\/'; const WIN_NO_SLASH$1 = `[^${WIN_SLASH$1}]`; /** * Posix glob regex */ const DOT_LITERAL$1 = '\\.'; const PLUS_LITERAL$1 = '\\+'; const QMARK_LITERAL$1 = '\\?'; const SLASH_LITERAL$1 = '\\/'; const ONE_CHAR$1 = '(?=.)'; const QMARK$1 = '[^/]'; const END_ANCHOR$1 = `(?:${SLASH_LITERAL$1}|$)`; const START_ANCHOR$1 = `(?:^|${SLASH_LITERAL$1})`; const DOTS_SLASH$1 = `${DOT_LITERAL$1}{1,2}${END_ANCHOR$1}`; const NO_DOT$1 = `(?!${DOT_LITERAL$1})`; const NO_DOTS$1 = `(?!${START_ANCHOR$1}${DOTS_SLASH$1})`; const NO_DOT_SLASH$1 = `(?!${DOT_LITERAL$1}{0,1}${END_ANCHOR$1})`; const NO_DOTS_SLASH$1 = `(?!${DOTS_SLASH$1})`; const QMARK_NO_DOT$1 = `[^.${SLASH_LITERAL$1}]`; const STAR$2 = `${QMARK$1}*?`; const SEP = '/'; const POSIX_CHARS$1 = { DOT_LITERAL: DOT_LITERAL$1, PLUS_LITERAL: PLUS_LITERAL$1, QMARK_LITERAL: QMARK_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, QMARK: QMARK$1, END_ANCHOR: END_ANCHOR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT: NO_DOT$1, NO_DOTS: NO_DOTS$1, NO_DOT_SLASH: NO_DOT_SLASH$1, NO_DOTS_SLASH: NO_DOTS_SLASH$1, QMARK_NO_DOT: QMARK_NO_DOT$1, STAR: STAR$2, START_ANCHOR: START_ANCHOR$1, SEP }; /** * Windows glob regex */ const WINDOWS_CHARS$1 = { ...POSIX_CHARS$1, SLASH_LITERAL: `[${WIN_SLASH$1}]`, QMARK: WIN_NO_SLASH$1, STAR: `${WIN_NO_SLASH$1}*?`, DOTS_SLASH: `${DOT_LITERAL$1}{1,2}(?:[${WIN_SLASH$1}]|$)`, NO_DOT: `(?!${DOT_LITERAL$1})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH$1}])${DOT_LITERAL$1}{1,2}(?:[${WIN_SLASH$1}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL$1}{0,1}(?:[${WIN_SLASH$1}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL$1}{1,2}(?:[${WIN_SLASH$1}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH$1}]`, START_ANCHOR: `(?:^|[${WIN_SLASH$1}])`, END_ANCHOR: `(?:[${WIN_SLASH$1}]|$)`, SEP: '\\' }; /** * POSIX Bracket Regex */ const POSIX_REGEX_SOURCE$3 = { alnum: 'a-zA-Z0-9', alpha: 'a-zA-Z', ascii: '\\x00-\\x7F', blank: ' \\t', cntrl: '\\x00-\\x1F\\x7F', digit: '0-9', graph: '\\x21-\\x7E', lower: 'a-z', print: '\\x20-\\x7E ', punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', space: ' \\t\\r\\n\\v\\f', upper: 'A-Z', word: 'A-Za-z0-9_', xdigit: 'A-Fa-f0-9' }; var constants$8 = { MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$3, // regular expressions REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { '***': '*', '**/**': '**', '**/**/**': '**' }, // Digits CHAR_0: 48, /* 0 */ CHAR_9: 57, /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 65, /* A */ CHAR_LOWERCASE_A: 97, /* a */ CHAR_UPPERCASE_Z: 90, /* Z */ CHAR_LOWERCASE_Z: 122, /* z */ CHAR_LEFT_PARENTHESES: 40, /* ( */ CHAR_RIGHT_PARENTHESES: 41, /* ) */ CHAR_ASTERISK: 42, /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: 38, /* & */ CHAR_AT: 64, /* @ */ CHAR_BACKWARD_SLASH: 92, /* \ */ CHAR_CARRIAGE_RETURN: 13, /* \r */ CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ CHAR_COLON: 58, /* : */ CHAR_COMMA: 44, /* , */ CHAR_DOT: 46, /* . */ CHAR_DOUBLE_QUOTE: 34, /* " */ CHAR_EQUAL: 61, /* = */ CHAR_EXCLAMATION_MARK: 33, /* ! */ CHAR_FORM_FEED: 12, /* \f */ CHAR_FORWARD_SLASH: 47, /* / */ CHAR_GRAVE_ACCENT: 96, /* ` */ CHAR_HASH: 35, /* # */ CHAR_HYPHEN_MINUS: 45, /* - */ CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ CHAR_LEFT_CURLY_BRACE: 123, /* { */ CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ CHAR_LINE_FEED: 10, /* \n */ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ CHAR_PERCENT: 37, /* % */ CHAR_PLUS: 43, /* + */ CHAR_QUESTION_MARK: 63, /* ? */ CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ CHAR_RIGHT_CURLY_BRACE: 125, /* } */ CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ CHAR_SEMICOLON: 59, /* ; */ CHAR_SINGLE_QUOTE: 39, /* ' */ CHAR_SPACE: 32, /* */ CHAR_TAB: 9, /* \t */ CHAR_UNDERSCORE: 95, /* _ */ CHAR_VERTICAL_LINE: 124, /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ /** * Create EXTGLOB_CHARS */ extglobChars(chars) { return { '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, '?': { type: 'qmark', open: '(?:', close: ')?' }, '+': { type: 'plus', open: '(?:', close: ')+' }, '*': { type: 'star', open: '(?:', close: ')*' }, '@': { type: 'at', open: '(?:', close: ')' } }; }, /** * Create GLOB_CHARS */ globChars(win32) { return win32 === true ? WINDOWS_CHARS$1 : POSIX_CHARS$1; } }; /*global navigator*/ (function (exports) { const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = constants$8; exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); exports.isWindows = () => { if (typeof navigator !== 'undefined' && navigator.platform) { const platform = navigator.platform.toLowerCase(); return platform === 'win32' || platform === 'windows'; } if (typeof process !== 'undefined' && process.platform) { return process.platform === 'win32'; } return false; }; exports.removeBackslashes = str => { return str.replace(REGEX_REMOVE_BACKSLASH, match => { return match === '\\' ? '' : match; }); }; exports.escapeLast = (input, char, lastIdx) => { const idx = input.lastIndexOf(char, lastIdx); if (idx === -1) return input; if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); return `${input.slice(0, idx)}\\${input.slice(idx)}`; }; exports.removePrefix = (input, state = {}) => { let output = input; if (output.startsWith('./')) { output = output.slice(2); state.prefix = './'; } return output; }; exports.wrapOutput = (input, state = {}, options = {}) => { const prepend = options.contains ? '' : '^'; const append = options.contains ? '' : '$'; let output = `${prepend}(?:${input})${append}`; if (state.negated === true) { output = `(?:^(?!${output}).*$)`; } return output; }; exports.basename = (path, { windows } = {}) => { const segs = path.split(windows ? /[\\/]/ : '/'); const last = segs[segs.length - 1]; if (last === '') { return segs[segs.length - 2]; } return last; }; } (utils$d)); const utils$c = utils$d; const { CHAR_ASTERISK: CHAR_ASTERISK$1, /* * */ CHAR_AT: CHAR_AT$1, /* @ */ CHAR_BACKWARD_SLASH: CHAR_BACKWARD_SLASH$1, /* \ */ CHAR_COMMA: CHAR_COMMA$2, /* , */ CHAR_DOT: CHAR_DOT$2, /* . */ CHAR_EXCLAMATION_MARK: CHAR_EXCLAMATION_MARK$1, /* ! */ CHAR_FORWARD_SLASH: CHAR_FORWARD_SLASH$1, /* / */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$2, /* { */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$2, /* ( */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$2, /* [ */ CHAR_PLUS: CHAR_PLUS$1, /* + */ CHAR_QUESTION_MARK: CHAR_QUESTION_MARK$1, /* ? */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$2, /* } */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$2, /* ) */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$2 /* ] */ } = constants$8; const isPathSeparator$1 = code => { return code === CHAR_FORWARD_SLASH$1 || code === CHAR_BACKWARD_SLASH$1; }; const depth$1 = token => { if (token.isPrefix !== true) { token.depth = token.isGlobstar ? Infinity : 1; } }; /** * Quickly scans a glob pattern and returns an object with a handful of * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). * * ```js * const pm = require('picomatch'); * console.log(pm.scan('foo/bar/*.js')); * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } * ``` * @param {String} `str` * @param {Object} `options` * @return {Object} Returns an object with tokens and regex source string. * @api public */ const scan$3 = (input, options) => { const opts = options || {}; const length = input.length - 1; const scanToEnd = opts.parts === true || opts.scanToEnd === true; const slashes = []; const tokens = []; const parts = []; let str = input; let index = -1; let start = 0; let lastIndex = 0; let isBrace = false; let isBracket = false; let isGlob = false; let isExtglob = false; let isGlobstar = false; let braceEscaped = false; let backslashes = false; let negated = false; let negatedExtglob = false; let finished = false; let braces = 0; let prev; let code; let token = { value: '', depth: 0, isGlob: false }; const eos = () => index >= length; const peek = () => str.charCodeAt(index + 1); const advance = () => { prev = code; return str.charCodeAt(++index); }; while (index < length) { code = advance(); let next; if (code === CHAR_BACKWARD_SLASH$1) { backslashes = token.backslashes = true; code = advance(); if (code === CHAR_LEFT_CURLY_BRACE$2) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$2) { braces++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH$1) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE$2) { braces++; continue; } if (braceEscaped !== true && code === CHAR_DOT$2 && (code = advance()) === CHAR_DOT$2) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA$2) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE$2) { braces--; if (braces === 0) { braceEscaped = false; isBrace = token.isBrace = true; finished = true; break; } } } if (scanToEnd === true) { continue; } break; } if (code === CHAR_FORWARD_SLASH$1) { slashes.push(index); tokens.push(token); token = { value: '', depth: 0, isGlob: false }; if (finished === true) continue; if (prev === CHAR_DOT$2 && index === (start + 1)) { start += 2; continue; } lastIndex = index + 1; continue; } if (opts.noext !== true) { const isExtglobChar = code === CHAR_PLUS$1 || code === CHAR_AT$1 || code === CHAR_ASTERISK$1 || code === CHAR_QUESTION_MARK$1 || code === CHAR_EXCLAMATION_MARK$1; if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$2) { isGlob = token.isGlob = true; isExtglob = token.isExtglob = true; finished = true; if (code === CHAR_EXCLAMATION_MARK$1 && index === start) { negatedExtglob = true; } if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH$1) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES$2) { isGlob = token.isGlob = true; finished = true; break; } } continue; } break; } } if (code === CHAR_ASTERISK$1) { if (prev === CHAR_ASTERISK$1) isGlobstar = token.isGlobstar = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_QUESTION_MARK$1) { isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_LEFT_SQUARE_BRACKET$2) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH$1) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET$2) { isBracket = token.isBracket = true; isGlob = token.isGlob = true; finished = true; break; } } if (scanToEnd === true) { continue; } break; } if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK$1 && index === start) { negated = token.negated = true; start++; continue; } if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$2) { isGlob = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES$2) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES$2) { finished = true; break; } } continue; } break; } if (isGlob === true) { finished = true; if (scanToEnd === true) { continue; } break; } } if (opts.noext === true) { isExtglob = false; isGlob = false; } let base = str; let prefix = ''; let glob = ''; if (start > 0) { prefix = str.slice(0, start); str = str.slice(start); lastIndex -= start; } if (base && isGlob === true && lastIndex > 0) { base = str.slice(0, lastIndex); glob = str.slice(lastIndex); } else if (isGlob === true) { base = ''; glob = str; } else { base = str; } if (base && base !== '' && base !== '/' && base !== str) { if (isPathSeparator$1(base.charCodeAt(base.length - 1))) { base = base.slice(0, -1); } } if (opts.unescape === true) { if (glob) glob = utils$c.removeBackslashes(glob); if (base && backslashes === true) { base = utils$c.removeBackslashes(base); } } const state = { prefix, input, start, base, glob, isBrace, isBracket, isGlob, isExtglob, isGlobstar, negated, negatedExtglob }; if (opts.tokens === true) { state.maxDepth = 0; if (!isPathSeparator$1(code)) { tokens.push(token); } state.tokens = tokens; } if (opts.parts === true || opts.tokens === true) { let prevIndex; for (let idx = 0; idx < slashes.length; idx++) { const n = prevIndex ? prevIndex + 1 : start; const i = slashes[idx]; const value = input.slice(n, i); if (opts.tokens) { if (idx === 0 && start !== 0) { tokens[idx].isPrefix = true; tokens[idx].value = prefix; } else { tokens[idx].value = value; } depth$1(tokens[idx]); state.maxDepth += tokens[idx].depth; } if (idx !== 0 || value !== '') { parts.push(value); } prevIndex = i; } if (prevIndex && prevIndex + 1 < input.length) { const value = input.slice(prevIndex + 1); parts.push(value); if (opts.tokens) { tokens[tokens.length - 1].value = value; depth$1(tokens[tokens.length - 1]); state.maxDepth += tokens[tokens.length - 1].depth; } } state.slashes = slashes; state.parts = parts; } return state; }; var scan_1$1 = scan$3; const constants$7 = constants$8; const utils$b = utils$d; /** * Constants */ const { MAX_LENGTH: MAX_LENGTH$2, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$2, REGEX_NON_SPECIAL_CHARS: REGEX_NON_SPECIAL_CHARS$1, REGEX_SPECIAL_CHARS_BACKREF: REGEX_SPECIAL_CHARS_BACKREF$1, REPLACEMENTS: REPLACEMENTS$1 } = constants$7; /** * Helpers */ const expandRange$1 = (args, options) => { if (typeof options.expandRange === 'function') { return options.expandRange(...args, options); } args.sort(); const value = `[${args.join('-')}]`; return value; }; /** * Create the message for a syntax error */ const syntaxError$1 = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; /** * Parse the given input string. * @param {String} input * @param {Object} options * @return {Object} */ const parse$h = (input, options) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } input = REPLACEMENTS$1[input] || input; const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$2, opts.maxLength) : MAX_LENGTH$2; let len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } const bos = { type: 'bos', value: '', output: opts.prepend || '' }; const tokens = [bos]; const capture = opts.capture ? '' : '?:'; // create constants based on platform, for windows or posix const PLATFORM_CHARS = constants$7.globChars(opts.windows); const EXTGLOB_CHARS = constants$7.extglobChars(PLATFORM_CHARS); const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS; const globstar = opts => { return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const nodot = opts.dot ? '' : NO_DOT; const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; let star = opts.bash === true ? globstar(opts) : STAR; if (opts.capture) { star = `(${star})`; } // minimatch options support if (typeof opts.noext === 'boolean') { opts.noextglob = opts.noext; } const state = { input, index: -1, start: 0, dot: opts.dot === true, consumed: '', output: '', prefix: '', backtrack: false, negated: false, brackets: 0, braces: 0, parens: 0, quotes: 0, globstar: false, tokens }; input = utils$b.removePrefix(input, state); len = input.length; const extglobs = []; const braces = []; const stack = []; let prev = bos; let value; /** * Tokenizing helpers */ const eos = () => state.index === len - 1; const peek = state.peek = (n = 1) => input[state.index + n]; const advance = state.advance = () => input[++state.index] || ''; const remaining = () => input.slice(state.index + 1); const consume = (value = '', num = 0) => { state.consumed += value; state.index += num; }; const append = token => { state.output += token.output != null ? token.output : token.value; consume(token.value); }; const negate = () => { let count = 1; while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { advance(); state.start++; count++; } if (count % 2 === 0) { return false; } state.negated = true; state.start++; return true; }; const increment = type => { state[type]++; stack.push(type); }; const decrement = type => { state[type]--; stack.pop(); }; /** * Push tokens onto the tokens array. This helper speeds up * tokenizing by 1) helping us avoid backtracking as much as possible, * and 2) helping us avoid creating extra tokens when consecutive * characters are plain text. This improves performance and simplifies * lookbehinds. */ const push = tok => { if (prev.type === 'globstar') { const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { state.output = state.output.slice(0, -prev.output.length); prev.type = 'star'; prev.value = '*'; prev.output = star; state.output += prev.output; } } if (extglobs.length && tok.type !== 'paren') { extglobs[extglobs.length - 1].inner += tok.value; } if (tok.value || tok.output) append(tok); if (prev && prev.type === 'text' && tok.type === 'text') { prev.output = (prev.output || prev.value) + tok.value; prev.value += tok.value; return; } tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value) => { const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; token.prev = prev; token.parens = state.parens; token.output = state.output; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); push({ type, value, output: state.output ? '' : ONE_CHAR }); push({ type: 'paren', extglob: true, value: advance(), output }); extglobs.push(token); }; const extglobClose = token => { let output = token.close + (opts.capture ? ')' : ''); let rest; if (token.type === 'negate') { let extglobStar = star; if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { extglobStar = globstar(opts); } if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { output = token.close = `)$))${extglobStar}`; } if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. // In this case, we need to parse the string and use it in the output of the original pattern. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. // // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. const expression = parse$h(rest, { ...options, fastpaths: false }).output; output = token.close = `)${expression})${extglobStar})`; } if (token.prev.type === 'bos') { state.negatedExtglob = true; } } push({ type: 'paren', extglob: true, value, output }); decrement('parens'); }; /** * Fast paths */ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { let backslashes = false; let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF$1, (m, esc, chars, first, rest, index) => { if (first === '\\') { backslashes = true; return m; } if (first === '?') { if (esc) { return esc + first + (rest ? QMARK.repeat(rest.length) : ''); } if (index === 0) { return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); } return QMARK.repeat(chars.length); } if (first === '.') { return DOT_LITERAL.repeat(chars.length); } if (first === '*') { if (esc) { return esc + first + (rest ? star : ''); } return star; } return esc ? m : `\\${m}`; }); if (backslashes === true) { if (opts.unescape === true) { output = output.replace(/\\/g, ''); } else { output = output.replace(/\\+/g, m => { return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); }); } } if (output === input && opts.contains === true) { state.output = input; return state; } state.output = utils$b.wrapOutput(output, state, options); return state; } /** * Tokenize input until we reach end-of-string */ while (!eos()) { value = advance(); if (value === '\u0000') { continue; } /** * Escaped characters */ if (value === '\\') { const next = peek(); if (next === '/' && opts.bash !== true) { continue; } if (next === '.' || next === ';') { continue; } if (!next) { value += '\\'; push({ type: 'text', value }); continue; } // collapse slashes to reduce potential for exploits const match = /^\\+/.exec(remaining()); let slashes = 0; if (match && match[0].length > 2) { slashes = match[0].length; state.index += slashes; if (slashes % 2 !== 0) { value += '\\'; } } if (opts.unescape === true) { value = advance(); } else { value += advance(); } if (state.brackets === 0) { push({ type: 'text', value }); continue; } } /** * If we're inside a regex character class, continue * until we reach the closing bracket. */ if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { if (opts.posix !== false && value === ':') { const inner = prev.value.slice(1); if (inner.includes('[')) { prev.posix = true; if (inner.includes(':')) { const idx = prev.value.lastIndexOf('['); const pre = prev.value.slice(0, idx); const rest = prev.value.slice(idx + 2); const posix = POSIX_REGEX_SOURCE$2[rest]; if (posix) { prev.value = pre + posix; state.backtrack = true; advance(); if (!bos.output && tokens.indexOf(prev) === 1) { bos.output = ONE_CHAR; } continue; } } } } if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { value = `\\${value}`; } if (value === ']' && (prev.value === '[' || prev.value === '[^')) { value = `\\${value}`; } if (opts.posix === true && value === '!' && prev.value === '[') { value = '^'; } prev.value += value; append({ value }); continue; } /** * If we're inside a quoted string, continue * until we reach the closing double quote. */ if (state.quotes === 1 && value !== '"') { value = utils$b.escapeRegex(value); prev.value += value; append({ value }); continue; } /** * Double quotes */ if (value === '"') { state.quotes = state.quotes === 1 ? 0 : 1; if (opts.keepQuotes === true) { push({ type: 'text', value }); } continue; } /** * Parentheses */ if (value === '(') { increment('parens'); push({ type: 'paren', value }); continue; } if (value === ')') { if (state.parens === 0 && opts.strictBrackets === true) { throw new SyntaxError(syntaxError$1('opening', '(')); } const extglob = extglobs[extglobs.length - 1]; if (extglob && state.parens === extglob.parens + 1) { extglobClose(extglobs.pop()); continue; } push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); decrement('parens'); continue; } /** * Square brackets */ if (value === '[') { if (opts.nobracket === true || !remaining().includes(']')) { if (opts.nobracket !== true && opts.strictBrackets === true) { throw new SyntaxError(syntaxError$1('closing', ']')); } value = `\\${value}`; } else { increment('brackets'); } push({ type: 'bracket', value }); continue; } if (value === ']') { if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { push({ type: 'text', value, output: `\\${value}` }); continue; } if (state.brackets === 0) { if (opts.strictBrackets === true) { throw new SyntaxError(syntaxError$1('opening', '[')); } push({ type: 'text', value, output: `\\${value}` }); continue; } decrement('brackets'); const prevValue = prev.value.slice(1); if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { value = `/${value}`; } prev.value += value; append({ value }); // when literal brackets are explicitly disabled // assume we should match with a regex character class if (opts.literalBrackets === false || utils$b.hasRegexChars(prevValue)) { continue; } const escaped = utils$b.escapeRegex(prev.value); state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled // assume we should escape the brackets to match literal characters if (opts.literalBrackets === true) { state.output += escaped; prev.value = escaped; continue; } // when the user specifies nothing, try to match both prev.value = `(${capture}${escaped}|${prev.value})`; state.output += prev.value; continue; } /** * Braces */ if (value === '{' && opts.nobrace !== true) { increment('braces'); const open = { type: 'brace', value, output: '(', outputIndex: state.output.length, tokensIndex: state.tokens.length }; braces.push(open); push(open); continue; } if (value === '}') { const brace = braces[braces.length - 1]; if (opts.nobrace === true || !brace) { push({ type: 'text', value, output: value }); continue; } let output = ')'; if (brace.dots === true) { const arr = tokens.slice(); const range = []; for (let i = arr.length - 1; i >= 0; i--) { tokens.pop(); if (arr[i].type === 'brace') { break; } if (arr[i].type !== 'dots') { range.unshift(arr[i].value); } } output = expandRange$1(range, opts); state.backtrack = true; } if (brace.comma !== true && brace.dots !== true) { const out = state.output.slice(0, brace.outputIndex); const toks = state.tokens.slice(brace.tokensIndex); brace.value = brace.output = '\\{'; value = output = '\\}'; state.output = out; for (const t of toks) { state.output += (t.output || t.value); } } push({ type: 'brace', value, output }); decrement('braces'); braces.pop(); continue; } /** * Pipes */ if (value === '|') { if (extglobs.length > 0) { extglobs[extglobs.length - 1].conditions++; } push({ type: 'text', value }); continue; } /** * Commas */ if (value === ',') { let output = value; const brace = braces[braces.length - 1]; if (brace && stack[stack.length - 1] === 'braces') { brace.comma = true; output = '|'; } push({ type: 'comma', value, output }); continue; } /** * Slashes */ if (value === '/') { // if the beginning of the glob is "./", advance the start // to the current index, and don't add the "./" characters // to the state. This greatly simplifies lookbehinds when // checking for BOS characters like "!" and "." (not "./") if (prev.type === 'dot' && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ''; state.output = ''; tokens.pop(); prev = bos; // reset "prev" to the first token continue; } push({ type: 'slash', value, output: SLASH_LITERAL }); continue; } /** * Dots */ if (value === '.') { if (state.braces > 0 && prev.type === 'dot') { if (prev.value === '.') prev.output = DOT_LITERAL; const brace = braces[braces.length - 1]; prev.type = 'dots'; prev.output += value; prev.value += value; brace.dots = true; continue; } if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { push({ type: 'text', value, output: DOT_LITERAL }); continue; } push({ type: 'dot', value, output: DOT_LITERAL }); continue; } /** * Question marks */ if (value === '?') { const isGroup = prev && prev.value === '('; if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('qmark', value); continue; } if (prev && prev.type === 'paren') { const next = peek(); let output = value; if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { output = `\\${value}`; } push({ type: 'text', value, output }); continue; } if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { push({ type: 'qmark', value, output: QMARK_NO_DOT }); continue; } push({ type: 'qmark', value, output: QMARK }); continue; } /** * Exclamation */ if (value === '!') { if (opts.noextglob !== true && peek() === '(') { if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { extglobOpen('negate', value); continue; } } if (opts.nonegate !== true && state.index === 0) { negate(); continue; } } /** * Plus */ if (value === '+') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('plus', value); continue; } if ((prev && prev.value === '(') || opts.regex === false) { push({ type: 'plus', value, output: PLUS_LITERAL }); continue; } if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { push({ type: 'plus', value }); continue; } push({ type: 'plus', value: PLUS_LITERAL }); continue; } /** * Plain text */ if (value === '@') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { push({ type: 'at', extglob: true, value, output: '' }); continue; } push({ type: 'text', value }); continue; } /** * Plain text */ if (value !== '*') { if (value === '$' || value === '^') { value = `\\${value}`; } const match = REGEX_NON_SPECIAL_CHARS$1.exec(remaining()); if (match) { value += match[0]; state.index += match[0].length; } push({ type: 'text', value }); continue; } /** * Stars */ if (prev && (prev.type === 'globstar' || prev.star === true)) { prev.type = 'star'; prev.star = true; prev.value += value; prev.output = star; state.backtrack = true; state.globstar = true; consume(value); continue; } let rest = remaining(); if (opts.noextglob !== true && /^\([^?]/.test(rest)) { extglobOpen('star', value); continue; } if (prev.type === 'star') { if (opts.noglobstar === true) { consume(value); continue; } const prior = prev.prev; const before = prior.prev; const isStart = prior.type === 'slash' || prior.type === 'bos'; const afterStar = before && (before.type === 'star' || before.type === 'globstar'); if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { push({ type: 'star', value, output: '' }); continue; } const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { push({ type: 'star', value, output: '' }); continue; } // strip consecutive `/**/` while (rest.slice(0, 3) === '/**') { const after = input[state.index + 4]; if (after && after !== '/') { break; } rest = rest.slice(3); consume('/**', 3); } if (prior.type === 'bos' && eos()) { prev.type = 'globstar'; prev.value += value; prev.output = globstar(opts); state.output = prev.output; state.globstar = true; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); prev.value += value; state.globstar = true; state.output += prior.output + prev.output; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { const end = rest[1] !== void 0 ? '|$' : ''; state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; prev.value += value; state.output += prior.output + prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } if (prior.type === 'bos' && rest[0] === '/') { prev.type = 'globstar'; prev.value += value; prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; state.output = prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } // remove single star from output state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar prev.type = 'globstar'; prev.output = globstar(opts); prev.value += value; // reset output with globstar state.output += prev.output; state.globstar = true; consume(value); continue; } const token = { type: 'star', value, output: star }; if (opts.bash === true) { token.output = '.*?'; if (prev.type === 'bos' || prev.type === 'slash') { token.output = nodot + token.output; } push(token); continue; } if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { token.output = value; push(token); continue; } if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { if (prev.type === 'dot') { state.output += NO_DOT_SLASH; prev.output += NO_DOT_SLASH; } else if (opts.dot === true) { state.output += NO_DOTS_SLASH; prev.output += NO_DOTS_SLASH; } else { state.output += nodot; prev.output += nodot; } if (peek() !== '*') { state.output += ONE_CHAR; prev.output += ONE_CHAR; } } push(token); } while (state.brackets > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ']')); state.output = utils$b.escapeLast(state.output, '['); decrement('brackets'); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ')')); state.output = utils$b.escapeLast(state.output, '('); decrement('parens'); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', '}')); state.output = utils$b.escapeLast(state.output, '{'); decrement('braces'); } if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); } // rebuild the output if we had to backtrack at any point if (state.backtrack === true) { state.output = ''; for (const token of state.tokens) { state.output += token.output != null ? token.output : token.value; if (token.suffix) { state.output += token.suffix; } } } return state; }; /** * Fast paths for creating regular expressions for common glob patterns. * This can significantly speed up processing and has very little downside * impact when none of the fast paths match. */ parse$h.fastpaths = (input, options) => { const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$2, opts.maxLength) : MAX_LENGTH$2; const len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } input = REPLACEMENTS$1[input] || input; // create constants based on platform, for windows or posix const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants$7.globChars(opts.windows); const nodot = opts.dot ? NO_DOTS : NO_DOT; const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; const capture = opts.capture ? '' : '?:'; const state = { negated: false, prefix: '' }; let star = opts.bash === true ? '.*?' : STAR; if (opts.capture) { star = `(${star})`; } const globstar = opts => { if (opts.noglobstar === true) return star; return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const create = str => { switch (str) { case '*': return `${nodot}${ONE_CHAR}${star}`; case '.*': return `${DOT_LITERAL}${ONE_CHAR}${star}`; case '*.*': return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '*/*': return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; case '**': return nodot + globstar(opts); case '**/*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; case '**/*.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '**/.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; default: { const match = /^(.*?)\.(\w+)$/.exec(str); if (!match) return; const source = create(match[1]); if (!source) return; return source + DOT_LITERAL + match[2]; } } }; const output = utils$b.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL}?`; } return source; }; var parse_1$4 = parse$h; const scan$2 = scan_1$1; const parse$g = parse_1$4; const utils$a = utils$d; const constants$6 = constants$8; const isObject$4 = val => val && typeof val === 'object' && !Array.isArray(val); /** * Creates a matcher function from one or more glob patterns. The * returned function takes a string to match as its first argument, * and returns true if the string is a match. The returned matcher * function also takes a boolean as the second argument that, when true, * returns an object with additional information. * * ```js * const picomatch = require('picomatch'); * // picomatch(glob[, options]); * * const isMatch = picomatch('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @name picomatch * @param {String|Array} `globs` One or more glob patterns. * @param {Object=} `options` * @return {Function=} Returns a matcher function. * @api public */ const picomatch$6 = (glob, options, returnState = false) => { if (Array.isArray(glob)) { const fns = glob.map(input => picomatch$6(input, options, returnState)); const arrayMatcher = str => { for (const isMatch of fns) { const state = isMatch(str); if (state) return state; } return false; }; return arrayMatcher; } const isState = isObject$4(glob) && glob.tokens && glob.input; if (glob === '' || (typeof glob !== 'string' && !isState)) { throw new TypeError('Expected pattern to be a non-empty string'); } const opts = options || {}; const posix = opts.windows; const regex = isState ? picomatch$6.compileRe(glob, options) : picomatch$6.makeRe(glob, options, false, true); const state = regex.state; delete regex.state; let isIgnored = () => false; if (opts.ignore) { const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; isIgnored = picomatch$6(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { const { isMatch, match, output } = picomatch$6.test(input, regex, options, { glob, posix }); const result = { glob, state, regex, posix, input, output, match, isMatch }; if (typeof opts.onResult === 'function') { opts.onResult(result); } if (isMatch === false) { result.isMatch = false; return returnObject ? result : false; } if (isIgnored(input)) { if (typeof opts.onIgnore === 'function') { opts.onIgnore(result); } result.isMatch = false; return returnObject ? result : false; } if (typeof opts.onMatch === 'function') { opts.onMatch(result); } return returnObject ? result : true; }; if (returnState) { matcher.state = state; } return matcher; }; /** * Test `input` with the given `regex`. This is used by the main * `picomatch()` function to test the input string. * * ```js * const picomatch = require('picomatch'); * // picomatch.test(input, regex[, options]); * * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } * ``` * @param {String} `input` String to test. * @param {RegExp} `regex` * @return {Object} Returns an object with matching info. * @api public */ picomatch$6.test = (input, regex, options, { glob, posix } = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected input to be a string'); } if (input === '') { return { isMatch: false, output: '' }; } const opts = options || {}; const format = opts.format || (posix ? utils$a.toPosixSlashes : null); let match = input === glob; let output = (match && format) ? format(input) : input; if (match === false) { output = format ? format(input) : input; match = output === glob; } if (match === false || opts.capture === true) { if (opts.matchBase === true || opts.basename === true) { match = picomatch$6.matchBase(input, regex, options, posix); } else { match = regex.exec(output); } } return { isMatch: Boolean(match), match, output }; }; /** * Match the basename of a filepath. * * ```js * const picomatch = require('picomatch'); * // picomatch.matchBase(input, glob[, options]); * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true * ``` * @param {String} `input` String to test. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). * @return {Boolean} * @api public */ picomatch$6.matchBase = (input, glob, options) => { const regex = glob instanceof RegExp ? glob : picomatch$6.makeRe(glob, options); return regex.test(utils$a.basename(input)); }; /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const picomatch = require('picomatch'); * // picomatch.isMatch(string, patterns[, options]); * * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false * ``` * @param {String|Array} str The string to test. * @param {String|Array} patterns One or more glob patterns to use for matching. * @param {Object} [options] See available [options](#options). * @return {Boolean} Returns true if any patterns match `str` * @api public */ picomatch$6.isMatch = (str, patterns, options) => picomatch$6(patterns, options)(str); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const picomatch = require('picomatch'); * const result = picomatch.parse(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as a regex source string. * @api public */ picomatch$6.parse = (pattern, options) => { if (Array.isArray(pattern)) return pattern.map(p => picomatch$6.parse(p, options)); return parse$g(pattern, { ...options, fastpaths: false }); }; /** * Scan a glob pattern to separate the pattern into segments. * * ```js * const picomatch = require('picomatch'); * // picomatch.scan(input[, options]); * * const result = picomatch.scan('!./foo/*.js'); * console.log(result); * { prefix: '!./', * input: '!./foo/*.js', * start: 3, * base: 'foo', * glob: '*.js', * isBrace: false, * isBracket: false, * isGlob: true, * isExtglob: false, * isGlobstar: false, * negated: true } * ``` * @param {String} `input` Glob pattern to scan. * @param {Object} `options` * @return {Object} Returns an object with * @api public */ picomatch$6.scan = (input, options) => scan$2(input, options); /** * Compile a regular expression from the `state` object returned by the * [parse()](#parse) method. * * @param {Object} `state` * @param {Object} `options` * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. * @return {RegExp} * @api public */ picomatch$6.compileRe = (state, options, returnOutput = false, returnState = false) => { if (returnOutput === true) { return state.output; } const opts = options || {}; const prepend = opts.contains ? '' : '^'; const append = opts.contains ? '' : '$'; let source = `${prepend}(?:${state.output})${append}`; if (state && state.negated === true) { source = `^(?!${source}).*$`; } const regex = picomatch$6.toRegex(source, options); if (returnState === true) { regex.state = state; } return regex; }; /** * Create a regular expression from a parsed glob pattern. * * ```js * const picomatch = require('picomatch'); * const state = picomatch.parse('*.js'); * // picomatch.compileRe(state[, options]); * * console.log(picomatch.compileRe(state)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `state` The object returned from the `.parse` method. * @param {Object} `options` * @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. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. * @return {RegExp} Returns a regex created from the given pattern. * @api public */ picomatch$6.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { if (!input || typeof input !== 'string') { throw new TypeError('Expected a non-empty string'); } let parsed = { negated: false, fastpaths: true }; if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { parsed.output = parse$g.fastpaths(input, options); } if (!parsed.output) { parsed = parse$g(input, options); } return picomatch$6.compileRe(parsed, options, returnOutput, returnState); }; /** * Create a regular expression from the given regex source string. * * ```js * const picomatch = require('picomatch'); * // picomatch.toRegex(source[, options]); * * const { output } = picomatch.parse('*.js'); * console.log(picomatch.toRegex(output)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `source` Regular expression source string. * @param {Object} `options` * @return {RegExp} * @api public */ picomatch$6.toRegex = (source, options) => { try { const opts = options || {}; return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); } catch (err) { if (options && options.debug === true) throw err; return /$^/; } }; /** * Picomatch constants. * @return {Object} */ picomatch$6.constants = constants$6; /** * Expose "picomatch" */ var picomatch_1$2 = picomatch$6; const pico = picomatch_1$2; const utils$9 = utils$d; function picomatch$4(glob, options, returnState = false) { // default to os.platform() if (options && (options.windows === null || options.windows === undefined)) { // don't mutate the original options object options = { ...options, windows: utils$9.isWindows() }; } return pico(glob, options, returnState); } Object.assign(picomatch$4, pico); var picomatch_1$1 = picomatch$4; var picomatch$5 = /*@__PURE__*/getDefaultExportFromCjs(picomatch_1$1); const VALID_ID_PREFIX = `/@id/`; const NULL_BYTE_PLACEHOLDER = `__x00__`; let SOURCEMAPPING_URL = "sourceMa"; SOURCEMAPPING_URL += "ppingURL"; const MODULE_RUNNER_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-generated"; const ERR_OUTDATED_OPTIMIZED_DEP = "ERR_OUTDATED_OPTIMIZED_DEP"; const isWindows$3 = typeof process !== "undefined" && process.platform === "win32"; function wrapId$1(id) { return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER); } function unwrapId$1(id) { return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id; } const windowsSlashRE = /\\/g; function slash$1(p) { return p.replace(windowsSlashRE, "/"); } const postfixRE = /[?#].*$/; function cleanUrl(url) { return url.replace(postfixRE, ""); } function splitFileAndPostfix(path) { const file = cleanUrl(path); return { file, postfix: path.slice(file.length) }; } function withTrailingSlash(path) { if (path[path.length - 1] !== "/") { return `${path}/`; } return path; } function promiseWithResolvers() { let resolve; let reject; const promise = new Promise((_resolve, _reject) => { resolve = _resolve; reject = _reject; }); return { promise, resolve, reject }; } // @ts-check /** @typedef { import('estree').BaseNode} BaseNode */ /** @typedef {{ skip: () => void; remove: () => void; replace: (node: BaseNode) => void; }} WalkerContext */ let WalkerBase$1 = class WalkerBase { constructor() { /** @type {boolean} */ this.should_skip = false; /** @type {boolean} */ this.should_remove = false; /** @type {BaseNode | null} */ this.replacement = null; /** @type {WalkerContext} */ this.context = { skip: () => (this.should_skip = true), remove: () => (this.should_remove = true), replace: (node) => (this.replacement = node) }; } /** * * @param {any} parent * @param {string} prop * @param {number} index * @param {BaseNode} node */ replace(parent, prop, index, node) { if (parent) { if (index !== null) { parent[prop][index] = node; } else { parent[prop] = node; } } } /** * * @param {any} parent * @param {string} prop * @param {number} index */ remove(parent, prop, index) { if (parent) { if (index !== null) { parent[prop].splice(index, 1); } else { delete parent[prop]; } } } }; // @ts-check /** @typedef { import('estree').BaseNode} BaseNode */ /** @typedef { import('./walker.js').WalkerContext} WalkerContext */ /** @typedef {( * this: WalkerContext, * node: BaseNode, * parent: BaseNode, * key: string, * index: number * ) => void} SyncHandler */ let SyncWalker$1 = class SyncWalker extends WalkerBase$1 { /** * * @param {SyncHandler} enter * @param {SyncHandler} leave */ constructor(enter, leave) { super(); /** @type {SyncHandler} */ this.enter = enter; /** @type {SyncHandler} */ this.leave = leave; } /** * * @param {BaseNode} node * @param {BaseNode} parent * @param {string} [prop] * @param {number} [index] * @returns {BaseNode} */ visit(node, parent, prop, index) { if (node) { if (this.enter) { const _should_skip = this.should_skip; const _should_remove = this.should_remove; const _replacement = this.replacement; this.should_skip = false; this.should_remove = false; this.replacement = null; this.enter.call(this.context, node, parent, prop, index); if (this.replacement) { node = this.replacement; this.replace(parent, prop, index, node); } if (this.should_remove) { this.remove(parent, prop, index); } const skipped = this.should_skip; const removed = this.should_remove; this.should_skip = _should_skip; this.should_remove = _should_remove; this.replacement = _replacement; if (skipped) return node; if (removed) return null; } for (const key in node) { const value = node[key]; if (typeof value !== "object") { continue; } else if (Array.isArray(value)) { for (let i = 0; i < value.length; i += 1) { if (value[i] !== null && typeof value[i].type === 'string') { if (!this.visit(value[i], node, key, i)) { // removed i--; } } } } else if (value !== null && typeof value.type === "string") { this.visit(value, node, key, null); } } if (this.leave) { const _replacement = this.replacement; const _should_remove = this.should_remove; this.replacement = null; this.should_remove = false; this.leave.call(this.context, node, parent, prop, index); if (this.replacement) { node = this.replacement; this.replace(parent, prop, index, node); } if (this.should_remove) { this.remove(parent, prop, index); } const removed = this.should_remove; this.replacement = _replacement; this.should_remove = _should_remove; if (removed) return null; } } return node; } }; // @ts-check /** @typedef { import('estree').BaseNode} BaseNode */ /** @typedef { import('./sync.js').SyncHandler} SyncHandler */ /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */ /** * * @param {BaseNode} ast * @param {{ * enter?: SyncHandler * leave?: SyncHandler * }} walker * @returns {BaseNode} */ function walk$2(ast, { enter, leave }) { const instance = new SyncWalker$1(enter, leave); return instance.visit(ast, null); } const extractors = { ArrayPattern(names, param) { for (const element of param.elements) { if (element) extractors[element.type](names, element); } }, AssignmentPattern(names, param) { extractors[param.left.type](names, param.left); }, Identifier(names, param) { names.push(param.name); }, MemberExpression() { }, ObjectPattern(names, param) { for (const prop of param.properties) { // @ts-ignore Typescript reports that this is not a valid type if (prop.type === 'RestElement') { extractors.RestElement(names, prop); } else { extractors[prop.value.type](names, prop.value); } } }, RestElement(names, param) { extractors[param.argument.type](names, param.argument); } }; const extractAssignedNames = function extractAssignedNames(param) { const names = []; extractors[param.type](names, param); return names; }; const blockDeclarations = { const: true, let: true }; class Scope { constructor(options = {}) { this.parent = options.parent; this.isBlockScope = !!options.block; this.declarations = Object.create(null); if (options.params) { options.params.forEach((param) => { extractAssignedNames(param).forEach((name) => { this.declarations[name] = true; }); }); } } addDeclaration(node, isBlockDeclaration, isVar) { if (!isBlockDeclaration && this.isBlockScope) { // it's a `var` or function node, and this // is a block scope, so we need to go up this.parent.addDeclaration(node, isBlockDeclaration, isVar); } else if (node.id) { extractAssignedNames(node.id).forEach((name) => { this.declarations[name] = true; }); } } contains(name) { return this.declarations[name] || (this.parent ? this.parent.contains(name) : false); } } const attachScopes = function attachScopes(ast, propertyName = 'scope') { let scope = new Scope(); walk$2(ast, { enter(n, parent) { const node = n; // function foo () {...} // class Foo {...} if (/(?:Function|Class)Declaration/.test(node.type)) { scope.addDeclaration(node, false, false); } // var foo = 1 if (node.type === 'VariableDeclaration') { const { kind } = node; const isBlockDeclaration = blockDeclarations[kind]; node.declarations.forEach((declaration) => { scope.addDeclaration(declaration, isBlockDeclaration, true); }); } let newScope; // create new function scope if (/Function/.test(node.type)) { const func = node; newScope = new Scope({ parent: scope, block: false, params: func.params }); // named function expressions - the name is considered // part of the function's scope if (func.type === 'FunctionExpression' && func.id) { newScope.addDeclaration(func, false, false); } } // create new for scope if (/For(?:In|Of)?Statement/.test(node.type)) { newScope = new Scope({ parent: scope, block: true }); } // create new block scope if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) { newScope = new Scope({ parent: scope, block: true }); } // catch clause has its own block scope if (node.type === 'CatchClause') { newScope = new Scope({ parent: scope, params: node.param ? [node.param] : [], block: true }); } if (newScope) { Object.defineProperty(node, propertyName, { value: newScope, configurable: true }); scope = newScope; } }, leave(n) { const node = n; if (node[propertyName]) scope = scope.parent; } }); return scope; }; // Helper since Typescript can't detect readonly arrays with Array.isArray function isArray(arg) { return Array.isArray(arg); } function ensureArray(thing) { if (isArray(thing)) return thing; if (thing == null) return []; return [thing]; } const normalizePathRegExp = new RegExp(`\\${win32.sep}`, 'g'); const normalizePath$6 = function normalizePath(filename) { return filename.replace(normalizePathRegExp, posix.sep); }; function getMatcherString(id, resolutionBase) { if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) { return normalizePath$6(id); } // resolve('') is valid and will default to process.cwd() const basePath = normalizePath$6(resolve$3(resolutionBase || '')) // escape all possible (posix + win) path characters that might interfere with regex .replace(/[-^$*+?.()|[\]{}]/g, '\\$&'); // Note that we use posix.join because: // 1. the basePath has been normalized to use / // 2. the incoming glob (id) matcher, also uses / // otherwise Node will force backslash (\) on windows return posix.join(basePath, normalizePath$6(id)); } const createFilter$1 = function createFilter(include, exclude, options) { const resolutionBase = options && options.resolve; const getMatcher = (id) => id instanceof RegExp ? id : { test: (what) => { // this refactor is a tad overly verbose but makes for easy debugging const pattern = getMatcherString(id, resolutionBase); const fn = picomatch$5(pattern, { dot: true }); const result = fn(what); return result; } }; const includeMatchers = ensureArray(include).map(getMatcher); const excludeMatchers = ensureArray(exclude).map(getMatcher); if (!includeMatchers.length && !excludeMatchers.length) return (id) => typeof id === 'string' && !id.includes('\0'); return function result(id) { if (typeof id !== 'string') return false; if (id.includes('\0')) return false; const pathId = normalizePath$6(id); for (let i = 0; i < excludeMatchers.length; ++i) { const matcher = excludeMatchers[i]; if (matcher.test(pathId)) return false; } for (let i = 0; i < includeMatchers.length; ++i) { const matcher = includeMatchers[i]; if (matcher.test(pathId)) return true; } return !includeMatchers.length; }; }; 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'; 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'; const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' ')); forbiddenIdentifiers.add(''); const makeLegalIdentifier = function makeLegalIdentifier(str) { let identifier = str .replace(/-(\w)/g, (_, letter) => letter.toUpperCase()) .replace(/[^$_a-zA-Z0-9]/g, '_'); if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) { identifier = `_${identifier}`; } return identifier || '_'; }; function stringify$5(obj) { return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`); } function serializeArray(arr, indent, baseIndent) { let output = '['; const separator = indent ? `\n${baseIndent}${indent}` : ''; for (let i = 0; i < arr.length; i++) { const key = arr[i]; output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`; } return `${output}${indent ? `\n${baseIndent}` : ''}]`; } function serializeObject(obj, indent, baseIndent) { let output = '{'; const separator = indent ? `\n${baseIndent}${indent}` : ''; const entries = Object.entries(obj); for (let i = 0; i < entries.length; i++) { const [key, value] = entries[i]; const stringKey = makeLegalIdentifier(key) === key ? key : stringify$5(key); output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`; } return `${output}${indent ? `\n${baseIndent}` : ''}}`; } function serialize(obj, indent, baseIndent) { if (typeof obj === 'object' && obj !== null) { if (Array.isArray(obj)) return serializeArray(obj, indent, baseIndent); if (obj instanceof Date) return `new Date(${obj.getTime()})`; if (obj instanceof RegExp) return obj.toString(); return serializeObject(obj, indent, baseIndent); } if (typeof obj === 'number') { if (obj === Infinity) return 'Infinity'; if (obj === -Infinity) return '-Infinity'; if (obj === 0) return 1 / obj === Infinity ? '0' : '-0'; if (obj !== obj) return 'NaN'; // eslint-disable-line no-self-compare } if (typeof obj === 'symbol') { const key = Symbol.keyFor(obj); // eslint-disable-next-line no-undefined if (key !== undefined) return `Symbol.for(${stringify$5(key)})`; } if (typeof obj === 'bigint') return `${obj}n`; return stringify$5(obj); } // isWellFormed exists from Node.js 20 const hasStringIsWellFormed = 'isWellFormed' in String.prototype; function isWellFormedString(input) { // @ts-expect-error String::isWellFormed exists from ES2024. tsconfig lib is set to ES6 if (hasStringIsWellFormed) return input.isWellFormed(); // https://github.com/tc39/proposal-is-usv-string/blob/main/README.md#algorithm return !/\p{Surrogate}/u.test(input); } const dataToEsm = function dataToEsm(data, options = {}) { var _a, _b; const t = options.compact ? '' : 'indent' in options ? options.indent : '\t'; const _ = options.compact ? '' : ' '; const n = options.compact ? '' : '\n'; const declarationType = options.preferConst ? 'const' : 'var'; if (options.namedExports === false || typeof data !== 'object' || Array.isArray(data) || data instanceof Date || data instanceof RegExp || data === null) { const code = serialize(data, options.compact ? null : t, ''); const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape return `export default${magic}${code};`; } let maxUnderbarPrefixLength = 0; for (const key of Object.keys(data)) { const underbarPrefixLength = (_b = (_a = /^(_+)/.exec(key)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0; if (underbarPrefixLength > maxUnderbarPrefixLength) { maxUnderbarPrefixLength = underbarPrefixLength; } } const arbitraryNamePrefix = `${'_'.repeat(maxUnderbarPrefixLength + 1)}arbitrary`; let namedExportCode = ''; const defaultExportRows = []; const arbitraryNameExportRows = []; for (const [key, value] of Object.entries(data)) { if (key === makeLegalIdentifier(key)) { if (options.objectShorthand) defaultExportRows.push(key); else defaultExportRows.push(`${key}:${_}${key}`); namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`; } else { defaultExportRows.push(`${stringify$5(key)}:${_}${serialize(value, options.compact ? null : t, '')}`); if (options.includeArbitraryNames && isWellFormedString(key)) { const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`; namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`; arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`); } } } const arbitraryExportCode = arbitraryNameExportRows.length > 0 ? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}` : ''; const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`; return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`; }; var path$c = require$$0$2; var commondir = function (basedir, relfiles) { if (relfiles) { var files = relfiles.map(function (r) { return path$c.resolve(basedir, r); }); } else { var files = basedir; } var res = files.slice(1).reduce(function (ps, file) { if (!file.match(/^([A-Za-z]:)?\/|\\/)) { throw new Error('relative path without a basedir'); } var xs = file.split(/\/+|\\+/); for ( var i = 0; ps[i] === xs[i] && i < Math.min(ps.length, xs.length); i++ ); return ps.slice(0, i); }, files[0].split(/\/+|\\+/)); // Windows correctly handles paths with forward-slashes return res.length > 1 ? res.join('/') : '/' }; var getCommonDir = /*@__PURE__*/getDefaultExportFromCjs(commondir); var dist = {}; var builder = {}; var apiBuilder = {}; var async = {}; var walker = {}; var utils$8 = {}; Object.defineProperty(utils$8, "__esModule", { value: true }); utils$8.normalizePath = utils$8.convertSlashes = utils$8.cleanPath = void 0; const path_1$4 = require$$0$2; function cleanPath(path) { let normalized = (0, path_1$4.normalize)(path); // we have to remove the last path separator // to account for / root path if (normalized.length > 1 && normalized[normalized.length - 1] === path_1$4.sep) normalized = normalized.substring(0, normalized.length - 1); return normalized; } utils$8.cleanPath = cleanPath; const SLASHES_REGEX = /[\\/]/g; function convertSlashes(path, separator) { return path.replace(SLASHES_REGEX, separator); } utils$8.convertSlashes = convertSlashes; function normalizePath$5(path, options) { const { resolvePaths, normalizePath, pathSeparator } = options; const pathNeedsCleaning = (process.platform === "win32" && path.includes("/")) || path.startsWith("."); if (resolvePaths) path = (0, path_1$4.resolve)(path); if (normalizePath || pathNeedsCleaning) path = cleanPath(path); if (path === ".") return ""; const needsSeperator = path[path.length - 1] !== pathSeparator; return convertSlashes(needsSeperator ? path + pathSeparator : path, pathSeparator); } utils$8.normalizePath = normalizePath$5; var joinPath$2 = {}; Object.defineProperty(joinPath$2, "__esModule", { value: true }); joinPath$2.build = joinPath$2.joinDirectoryPath = joinPath$2.joinPathWithBasePath = void 0; const path_1$3 = require$$0$2; const utils_1$1 = utils$8; function joinPathWithBasePath(filename, directoryPath) { return directoryPath + filename; } joinPath$2.joinPathWithBasePath = joinPathWithBasePath; function joinPathWithRelativePath(root, options) { return function (filename, directoryPath) { const sameRoot = directoryPath.startsWith(root); if (sameRoot) return directoryPath.replace(root, "") + filename; else return ((0, utils_1$1.convertSlashes)((0, path_1$3.relative)(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename); }; } function joinPath$1(filename) { return filename; } function joinDirectoryPath(filename, directoryPath, separator) { return directoryPath + filename + separator; } joinPath$2.joinDirectoryPath = joinDirectoryPath; function build$a(root, options) { const { relativePaths, includeBasePath } = options; return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath$1; } joinPath$2.build = build$a; var pushDirectory$2 = {}; Object.defineProperty(pushDirectory$2, "__esModule", { value: true }); pushDirectory$2.build = void 0; function pushDirectoryWithRelativePath(root) { return function (directoryPath, paths) { paths.push(directoryPath.substring(root.length) || "."); }; } function pushDirectoryFilterWithRelativePath(root) { return function (directoryPath, paths, filters) { const relativePath = directoryPath.substring(root.length) || "."; if (filters.every((filter) => filter(relativePath, true))) { paths.push(relativePath); } }; } const pushDirectory$1 = (directoryPath, paths) => { paths.push(directoryPath || "."); }; const pushDirectoryFilter = (directoryPath, paths, filters) => { const path = directoryPath || "."; if (filters.every((filter) => filter(path, true))) { paths.push(path); } }; const empty$2 = () => { }; function build$9(root, options) { const { includeDirs, filters, relativePaths } = options; if (!includeDirs) return empty$2; if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root); return filters && filters.length ? pushDirectoryFilter : pushDirectory$1; } pushDirectory$2.build = build$9; var pushFile$2 = {}; Object.defineProperty(pushFile$2, "__esModule", { value: true }); pushFile$2.build = void 0; const pushFileFilterAndCount = (filename, _paths, counts, filters) => { if (filters.every((filter) => filter(filename, false))) counts.files++; }; const pushFileFilter = (filename, paths, _counts, filters) => { if (filters.every((filter) => filter(filename, false))) paths.push(filename); }; const pushFileCount = (_filename, _paths, counts, _filters) => { counts.files++; }; const pushFile$1 = (filename, paths) => { paths.push(filename); }; const empty$1 = () => { }; function build$8(options) { const { excludeFiles, filters, onlyCounts } = options; if (excludeFiles) return empty$1; if (filters && filters.length) { return onlyCounts ? pushFileFilterAndCount : pushFileFilter; } else if (onlyCounts) { return pushFileCount; } else { return pushFile$1; } } pushFile$2.build = build$8; var getArray$2 = {}; Object.defineProperty(getArray$2, "__esModule", { value: true }); getArray$2.build = void 0; const getArray$1 = (paths) => { return paths; }; const getArrayGroup = () => { return [""].slice(0, 0); }; function build$7(options) { return options.group ? getArrayGroup : getArray$1; } getArray$2.build = build$7; var groupFiles$2 = {}; Object.defineProperty(groupFiles$2, "__esModule", { value: true }); groupFiles$2.build = void 0; const groupFiles$1 = (groups, directory, files) => { groups.push({ directory, files, dir: directory }); }; const empty = () => { }; function build$6(options) { return options.group ? groupFiles$1 : empty; } groupFiles$2.build = build$6; var resolveSymlink$1 = {}; var __importDefault$1 = (resolveSymlink$1 && resolveSymlink$1.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(resolveSymlink$1, "__esModule", { value: true }); resolveSymlink$1.build = void 0; const fs_1$1 = __importDefault$1(require$$0$3); const path_1$2 = require$$0$2; const resolveSymlinksAsync = function (path, state, callback) { const { queue, options: { suppressErrors }, } = state; queue.enqueue(); fs_1$1.default.realpath(path, (error, resolvedPath) => { if (error) return queue.dequeue(suppressErrors ? null : error, state); fs_1$1.default.stat(resolvedPath, (error, stat) => { if (error) return queue.dequeue(suppressErrors ? null : error, state); if (stat.isDirectory() && isRecursive(path, resolvedPath, state)) return queue.dequeue(null, state); callback(stat, resolvedPath); queue.dequeue(null, state); }); }); }; const resolveSymlinks = function (path, state, callback) { const { queue, options: { suppressErrors }, } = state; queue.enqueue(); try { const resolvedPath = fs_1$1.default.realpathSync(path); const stat = fs_1$1.default.statSync(resolvedPath); if (stat.isDirectory() && isRecursive(path, resolvedPath, state)) return; callback(stat, resolvedPath); } catch (e) { if (!suppressErrors) throw e; } }; function build$5(options, isSynchronous) { if (!options.resolveSymlinks || options.excludeSymlinks) return null; return isSynchronous ? resolveSymlinks : resolveSymlinksAsync; } resolveSymlink$1.build = build$5; function isRecursive(path, resolved, state) { if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state); let parent = (0, path_1$2.dirname)(path); let depth = 1; while (parent !== state.root && depth < 2) { const resolvedPath = state.symlinks.get(parent); const isSameRoot = !!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath)); if (isSameRoot) depth++; else parent = (0, path_1$2.dirname)(parent); } state.symlinks.set(path, resolved); return depth > 1; } function isRecursiveUsingRealPaths(resolved, state) { return state.visited.includes(resolved + state.options.pathSeparator); } var invokeCallback$1 = {}; Object.defineProperty(invokeCallback$1, "__esModule", { value: true }); invokeCallback$1.build = void 0; const onlyCountsSync = (state) => { return state.counts; }; const groupsSync = (state) => { return state.groups; }; const defaultSync = (state) => { return state.paths; }; const limitFilesSync = (state) => { return state.paths.slice(0, state.options.maxFiles); }; const onlyCountsAsync = (state, error, callback) => { report(error, callback, state.counts, state.options.suppressErrors); return null; }; const defaultAsync = (state, error, callback) => { report(error, callback, state.paths, state.options.suppressErrors); return null; }; const limitFilesAsync = (state, error, callback) => { report(error, callback, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors); return null; }; const groupsAsync = (state, error, callback) => { report(error, callback, state.groups, state.options.suppressErrors); return null; }; function report(error, callback, output, suppressErrors) { if (error && !suppressErrors) callback(error, output); else callback(null, output); } function build$4(options, isSynchronous) { const { onlyCounts, group, maxFiles } = options; if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync; else if (group) return isSynchronous ? groupsSync : groupsAsync; else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync; else return isSynchronous ? defaultSync : defaultAsync; } invokeCallback$1.build = build$4; var walkDirectory$1 = {}; var __importDefault = (walkDirectory$1 && walkDirectory$1.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(walkDirectory$1, "__esModule", { value: true }); walkDirectory$1.build = void 0; const fs_1 = __importDefault(require$$0$3); const readdirOpts = { withFileTypes: true }; const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback) => { if (currentDepth < 0) return state.queue.dequeue(null, state); state.visited.push(crawlPath); state.counts.directories++; state.queue.enqueue(); // Perf: Node >= 10 introduced withFileTypes that helps us // skip an extra fs.stat call. fs_1.default.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => { callback(entries, directoryPath, currentDepth); state.queue.dequeue(state.options.suppressErrors ? null : error, state); }); }; const walkSync = (state, crawlPath, directoryPath, currentDepth, callback) => { if (currentDepth < 0) return; state.visited.push(crawlPath); state.counts.directories++; let entries = []; try { entries = fs_1.default.readdirSync(crawlPath || ".", readdirOpts); } catch (e) { if (!state.options.suppressErrors) throw e; } callback(entries, directoryPath, currentDepth); }; function build$3(isSynchronous) { return isSynchronous ? walkSync : walkAsync; } walkDirectory$1.build = build$3; var queue = {}; Object.defineProperty(queue, "__esModule", { value: true }); queue.Queue = void 0; /** * This is a custom stateless queue to track concurrent async fs calls. * It increments a counter whenever a call is queued and decrements it * as soon as it completes. When the counter hits 0, it calls onQueueEmpty. */ class Queue { onQueueEmpty; count = 0; constructor(onQueueEmpty) { this.onQueueEmpty = onQueueEmpty; } enqueue() { this.count++; } dequeue(error, output) { if (--this.count <= 0 || error) this.onQueueEmpty(error, output); } } queue.Queue = Queue; var counter = {}; Object.defineProperty(counter, "__esModule", { value: true }); counter.Counter = void 0; class Counter { _files = 0; _directories = 0; set files(num) { this._files = num; } get files() { return this._files; } set directories(num) { this._directories = num; } get directories() { return this._directories; } /** * @deprecated use `directories` instead */ /* c8 ignore next 3 */ get dirs() { return this._directories; } } counter.Counter = Counter; var __createBinding = (walker && walker.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (walker && walker.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (walker && walker.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(walker, "__esModule", { value: true }); walker.Walker = void 0; const path_1$1 = require$$0$2; const utils_1 = utils$8; const joinPath = __importStar(joinPath$2); const pushDirectory = __importStar(pushDirectory$2); const pushFile = __importStar(pushFile$2); const getArray = __importStar(getArray$2); const groupFiles = __importStar(groupFiles$2); const resolveSymlink = __importStar(resolveSymlink$1); const invokeCallback = __importStar(invokeCallback$1); const walkDirectory = __importStar(walkDirectory$1); const queue_1 = queue; const counter_1 = counter; class Walker { root; isSynchronous; state; joinPath; pushDirectory; pushFile; getArray; groupFiles; resolveSymlink; walkDirectory; callbackInvoker; constructor(root, options, callback) { this.isSynchronous = !callback; this.callbackInvoker = invokeCallback.build(options, this.isSynchronous); this.root = (0, utils_1.normalizePath)(root, options); this.state = { root: this.root.slice(0, -1), // Perf: we explicitly tell the compiler to optimize for String arrays paths: [""].slice(0, 0), groups: [], counts: new counter_1.Counter(), options, queue: new queue_1.Queue((error, state) => this.callbackInvoker(state, error, callback)), symlinks: new Map(), visited: [""].slice(0, 0), }; /* * Perf: We conditionally change functions according to options. This gives a slight * performance boost. Since these functions are so small, they are automatically inlined * by the javascript engine so there's no function call overhead (in most cases). */ this.joinPath = joinPath.build(this.root, options); this.pushDirectory = pushDirectory.build(this.root, options); this.pushFile = pushFile.build(options); this.getArray = getArray.build(options); this.groupFiles = groupFiles.build(options); this.resolveSymlink = resolveSymlink.build(options, this.isSynchronous); this.walkDirectory = walkDirectory.build(this.isSynchronous); } start() { this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk); return this.isSynchronous ? this.callbackInvoker(this.state, null) : null; } walk = (entries, directoryPath, depth) => { const { paths, options: { filters, resolveSymlinks, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator, }, } = this.state; if ((signal && signal.aborted) || (maxFiles && paths.length > maxFiles)) return; this.pushDirectory(directoryPath, paths, filters); const files = this.getArray(this.state.paths); for (let i = 0; i < entries.length; ++i) { const entry = entries[i]; if (entry.isFile() || (entry.isSymbolicLink() && !resolveSymlinks && !excludeSymlinks)) { const filename = this.joinPath(entry.name, directoryPath); this.pushFile(filename, files, this.state.counts, filters); } else if (entry.isDirectory()) { let path = joinPath.joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator); if (exclude && exclude(entry.name, path)) continue; this.walkDirectory(this.state, path, path, depth - 1, this.walk); } else if (entry.isSymbolicLink() && this.resolveSymlink) { let path = joinPath.joinPathWithBasePath(entry.name, directoryPath); this.resolveSymlink(path, this.state, (stat, resolvedPath) => { if (stat.isDirectory()) { resolvedPath = (0, utils_1.normalizePath)(resolvedPath, this.state.options); if (exclude && exclude(entry.name, resolvedPath)) return; this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path + pathSeparator, depth - 1, this.walk); } else { resolvedPath = useRealPaths ? resolvedPath : path; const filename = (0, path_1$1.basename)(resolvedPath); const directoryPath = (0, utils_1.normalizePath)((0, path_1$1.dirname)(resolvedPath), this.state.options); resolvedPath = this.joinPath(filename, directoryPath); this.pushFile(resolvedPath, files, this.state.counts, filters); } }); } } this.groupFiles(this.state.groups, directoryPath, files); }; } walker.Walker = Walker; Object.defineProperty(async, "__esModule", { value: true }); async.callback = async.promise = void 0; const walker_1$1 = walker; function promise(root, options) { return new Promise((resolve, reject) => { callback(root, options, (err, output) => { if (err) return reject(err); resolve(output); }); }); } async.promise = promise; function callback(root, options, callback) { let walker = new walker_1$1.Walker(root, options, callback); walker.start(); } async.callback = callback; var sync$2 = {}; Object.defineProperty(sync$2, "__esModule", { value: true }); sync$2.sync = void 0; const walker_1 = walker; function sync$1(root, options) { const walker = new walker_1.Walker(root, options); return walker.start(); } sync$2.sync = sync$1; Object.defineProperty(apiBuilder, "__esModule", { value: true }); apiBuilder.APIBuilder = void 0; const async_1 = async; const sync_1 = sync$2; class APIBuilder { root; options; constructor(root, options) { this.root = root; this.options = options; } withPromise() { return (0, async_1.promise)(this.root, this.options); } withCallback(cb) { (0, async_1.callback)(this.root, this.options, cb); } sync() { return (0, sync_1.sync)(this.root, this.options); } } apiBuilder.APIBuilder = APIBuilder; Object.defineProperty(builder, "__esModule", { value: true }); builder.Builder = void 0; const path_1 = require$$0$2; const api_builder_1 = apiBuilder; var pm = null; /* c8 ignore next 6 */ try { require.resolve("picomatch"); pm = picomatch_1$1; } catch (_e) { // do nothing } class Builder { globCache = {}; options = { maxDepth: Infinity, suppressErrors: true, pathSeparator: path_1.sep, filters: [], }; globFunction; constructor(options) { this.options = { ...this.options, ...options }; this.globFunction = this.options.globFunction; } group() { this.options.group = true; return this; } withPathSeparator(separator) { this.options.pathSeparator = separator; return this; } withBasePath() { this.options.includeBasePath = true; return this; } withRelativePaths() { this.options.relativePaths = true; return this; } withDirs() { this.options.includeDirs = true; return this; } withMaxDepth(depth) { this.options.maxDepth = depth; return this; } withMaxFiles(limit) { this.options.maxFiles = limit; return this; } withFullPaths() { this.options.resolvePaths = true; this.options.includeBasePath = true; return this; } withErrors() { this.options.suppressErrors = false; return this; } withSymlinks({ resolvePaths = true } = {}) { this.options.resolveSymlinks = true; this.options.useRealPaths = resolvePaths; return this.withFullPaths(); } withAbortSignal(signal) { this.options.signal = signal; return this; } normalize() { this.options.normalizePath = true; return this; } filter(predicate) { this.options.filters.push(predicate); return this; } onlyDirs() { this.options.excludeFiles = true; this.options.includeDirs = true; return this; } exclude(predicate) { this.options.exclude = predicate; return this; } onlyCounts() { this.options.onlyCounts = true; return this; } crawl(root) { return new api_builder_1.APIBuilder(root || ".", this.options); } withGlobFunction(fn) { // cast this since we don't have the new type params yet this.globFunction = fn; return this; } /** * @deprecated Pass options using the constructor instead: * ```ts * new fdir(options).crawl("/path/to/root"); * ``` * This method will be removed in v7.0 */ /* c8 ignore next 4 */ crawlWithOptions(root, options) { this.options = { ...this.options, ...options }; return new api_builder_1.APIBuilder(root || ".", this.options); } glob(...patterns) { if (this.globFunction) { return this.globWithOptions(patterns); } return this.globWithOptions(patterns, ...[{ dot: true }]); } globWithOptions(patterns, ...options) { const globFn = (this.globFunction || pm); /* c8 ignore next 5 */ if (!globFn) { throw new Error('Please specify a glob function to use glob matching.'); } var isMatch = this.globCache[patterns.join("\0")]; if (!isMatch) { isMatch = globFn(patterns, ...options); this.globCache[patterns.join("\0")] = isMatch; } this.options.filters.push((path) => isMatch(path)); return this; } } builder.Builder = Builder; var types$1 = {}; Object.defineProperty(types$1, "__esModule", { value: true }); (function (exports) { var __createBinding = (dist && dist.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (dist && dist.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.fdir = void 0; const builder_1 = builder; Object.defineProperty(exports, "fdir", { enumerable: true, get: function () { return builder_1.Builder; } }); __exportStar(types$1, exports); } (dist)); const comma = ','.charCodeAt(0); const semicolon = ';'.charCodeAt(0); const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; const intToChar = new Uint8Array(64); // 64 possible chars. const charToInt = new Uint8Array(128); // z is 122 in ASCII for (let i = 0; i < chars$1.length; i++) { const c = chars$1.charCodeAt(i); intToChar[i] = c; charToInt[c] = i; } function decodeInteger(reader, relative) { let value = 0; let shift = 0; let integer = 0; do { const c = reader.next(); integer = charToInt[c]; value |= (integer & 31) << shift; shift += 5; } while (integer & 32); const shouldNegate = value & 1; value >>>= 1; if (shouldNegate) { value = -0x80000000 | -value; } return relative + value; } function encodeInteger(builder, num, relative) { let delta = num - relative; delta = delta < 0 ? (-delta << 1) | 1 : delta << 1; do { let clamped = delta & 0b011111; delta >>>= 5; if (delta > 0) clamped |= 0b100000; builder.write(intToChar[clamped]); } while (delta > 0); return num; } function hasMoreVlq(reader, max) { if (reader.pos >= max) return false; return reader.peek() !== comma; } const bufLength = 1024 * 16; // Provide a fallback for older environments. const td = typeof TextDecoder !== 'undefined' ? /* #__PURE__ */ new TextDecoder() : typeof Buffer !== 'undefined' ? { decode(buf) { const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); return out.toString(); }, } : { decode(buf) { let out = ''; for (let i = 0; i < buf.length; i++) { out += String.fromCharCode(buf[i]); } return out; }, }; class StringWriter { constructor() { this.pos = 0; this.out = ''; this.buffer = new Uint8Array(bufLength); } write(v) { const { buffer } = this; buffer[this.pos++] = v; if (this.pos === bufLength) { this.out += td.decode(buffer); this.pos = 0; } } flush() { const { buffer, out, pos } = this; return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; } } class StringReader { constructor(buffer) { this.pos = 0; this.buffer = buffer; } next() { return this.buffer.charCodeAt(this.pos++); } peek() { return this.buffer.charCodeAt(this.pos); } indexOf(char) { const { buffer, pos } = this; const idx = buffer.indexOf(char, pos); return idx === -1 ? buffer.length : idx; } } function decode(mappings) { const { length } = mappings; const reader = new StringReader(mappings); const decoded = []; let genColumn = 0; let sourcesIndex = 0; let sourceLine = 0; let sourceColumn = 0; let namesIndex = 0; do { const semi = reader.indexOf(';'); const line = []; let sorted = true; let lastCol = 0; genColumn = 0; while (reader.pos < semi) { let seg; genColumn = decodeInteger(reader, genColumn); if (genColumn < lastCol) sorted = false; lastCol = genColumn; if (hasMoreVlq(reader, semi)) { sourcesIndex = decodeInteger(reader, sourcesIndex); sourceLine = decodeInteger(reader, sourceLine); sourceColumn = decodeInteger(reader, sourceColumn); if (hasMoreVlq(reader, semi)) { namesIndex = decodeInteger(reader, namesIndex); seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; } else { seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; } } else { seg = [genColumn]; } line.push(seg); reader.pos++; } if (!sorted) sort(line); decoded.push(line); reader.pos = semi + 1; } while (reader.pos <= length); return decoded; } function sort(line) { line.sort(sortComparator$1); } function sortComparator$1(a, b) { return a[0] - b[0]; } function encode$1(decoded) { const writer = new StringWriter(); let sourcesIndex = 0; let sourceLine = 0; let sourceColumn = 0; let namesIndex = 0; for (let i = 0; i < decoded.length; i++) { const line = decoded[i]; if (i > 0) writer.write(semicolon); if (line.length === 0) continue; let genColumn = 0; for (let j = 0; j < line.length; j++) { const segment = line[j]; if (j > 0) writer.write(comma); genColumn = encodeInteger(writer, segment[0], genColumn); if (segment.length === 1) continue; sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); sourceLine = encodeInteger(writer, segment[2], sourceLine); sourceColumn = encodeInteger(writer, segment[3], sourceColumn); if (segment.length === 4) continue; namesIndex = encodeInteger(writer, segment[4], namesIndex); } } return writer.flush(); } class BitSet { constructor(arg) { this.bits = arg instanceof BitSet ? arg.bits.slice() : []; } add(n) { this.bits[n >> 5] |= 1 << (n & 31); } has(n) { return !!(this.bits[n >> 5] & (1 << (n & 31))); } } class Chunk { constructor(start, end, content) { this.start = start; this.end = end; this.original = content; this.intro = ''; this.outro = ''; this.content = content; this.storeName = false; this.edited = false; { this.previous = null; this.next = null; } } appendLeft(content) { this.outro += content; } appendRight(content) { this.intro = this.intro + content; } clone() { const chunk = new Chunk(this.start, this.end, this.original); chunk.intro = this.intro; chunk.outro = this.outro; chunk.content = this.content; chunk.storeName = this.storeName; chunk.edited = this.edited; return chunk; } contains(index) { return this.start < index && index < this.end; } eachNext(fn) { let chunk = this; while (chunk) { fn(chunk); chunk = chunk.next; } } eachPrevious(fn) { let chunk = this; while (chunk) { fn(chunk); chunk = chunk.previous; } } edit(content, storeName, contentOnly) { this.content = content; if (!contentOnly) { this.intro = ''; this.outro = ''; } this.storeName = storeName; this.edited = true; return this; } prependLeft(content) { this.outro = content + this.outro; } prependRight(content) { this.intro = content + this.intro; } reset() { this.intro = ''; this.outro = ''; if (this.edited) { this.content = this.original; this.storeName = false; this.edited = false; } } split(index) { const sliceIndex = index - this.start; const originalBefore = this.original.slice(0, sliceIndex); const originalAfter = this.original.slice(sliceIndex); this.original = originalBefore; const newChunk = new Chunk(index, this.end, originalAfter); newChunk.outro = this.outro; this.outro = ''; this.end = index; if (this.edited) { // after split we should save the edit content record into the correct chunk // to make sure sourcemap correct // For example: // ' test'.trim() // split -> ' ' + 'test' // ✔️ edit -> '' + 'test' // ✖️ edit -> 'test' + '' // TODO is this block necessary?... newChunk.edit('', false); this.content = ''; } else { this.content = originalBefore; } newChunk.next = this.next; if (newChunk.next) newChunk.next.previous = newChunk; newChunk.previous = this; this.next = newChunk; return newChunk; } toString() { return this.intro + this.content + this.outro; } trimEnd(rx) { this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; const trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { this.split(this.start + trimmed.length).edit('', undefined, true); if (this.edited) { // save the change, if it has been edited this.edit(trimmed, this.storeName, true); } } return true; } else { this.edit('', undefined, true); this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; } } trimStart(rx) { this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; const trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { const newChunk = this.split(this.end - trimmed.length); if (this.edited) { // save the change, if it has been edited newChunk.edit(trimmed, this.storeName, true); } this.edit('', undefined, true); } return true; } else { this.edit('', undefined, true); this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; } } } function getBtoa() { if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') { return (str) => globalThis.btoa(unescape(encodeURIComponent(str))); } else if (typeof Buffer === 'function') { return (str) => Buffer.from(str, 'utf-8').toString('base64'); } else { return () => { throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); }; } } const btoa$1 = /*#__PURE__*/ getBtoa(); let SourceMap$1 = class SourceMap { constructor(properties) { this.version = 3; this.file = properties.file; this.sources = properties.sources; this.sourcesContent = properties.sourcesContent; this.names = properties.names; this.mappings = encode$1(properties.mappings); if (typeof properties.x_google_ignoreList !== 'undefined') { this.x_google_ignoreList = properties.x_google_ignoreList; } if (typeof properties.debugId !== 'undefined') { this.debugId = properties.debugId; } } toString() { return JSON.stringify(this); } toUrl() { return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString()); } }; function guessIndent(code) { const lines = code.split('\n'); const tabbed = lines.filter((line) => /^\t+/.test(line)); const spaced = lines.filter((line) => /^ {2,}/.test(line)); if (tabbed.length === 0 && spaced.length === 0) { return null; } // More lines tabbed than spaced? Assume tabs, and // default to tabs in the case of a tie (or nothing // to go on) if (tabbed.length >= spaced.length) { return '\t'; } // Otherwise, we need to guess the multiple const min = spaced.reduce((previous, current) => { const numSpaces = /^ +/.exec(current)[0].length; return Math.min(numSpaces, previous); }, Infinity); return new Array(min + 1).join(' '); } function getRelativePath$1(from, to) { const fromParts = from.split(/[/\\]/); const toParts = to.split(/[/\\]/); fromParts.pop(); // get dirname while (fromParts[0] === toParts[0]) { fromParts.shift(); toParts.shift(); } if (fromParts.length) { let i = fromParts.length; while (i--) fromParts[i] = '..'; } return fromParts.concat(toParts).join('/'); } const toString$1 = Object.prototype.toString; function isObject$3(thing) { return toString$1.call(thing) === '[object Object]'; } function getLocator(source) { const originalLines = source.split('\n'); const lineOffsets = []; for (let i = 0, pos = 0; i < originalLines.length; i++) { lineOffsets.push(pos); pos += originalLines[i].length + 1; } return function locate(index) { let i = 0; let j = lineOffsets.length; while (i < j) { const m = (i + j) >> 1; if (index < lineOffsets[m]) { j = m; } else { i = m + 1; } } const line = i - 1; const column = index - lineOffsets[line]; return { line, column }; }; } const wordRegex = /\w/; class Mappings { constructor(hires) { this.hires = hires; this.generatedCodeLine = 0; this.generatedCodeColumn = 0; this.raw = []; this.rawSegments = this.raw[this.generatedCodeLine] = []; this.pending = null; } addEdit(sourceIndex, content, loc, nameIndex) { if (content.length) { const contentLengthMinusOne = content.length - 1; let contentLineEnd = content.indexOf('\n', 0); let previousContentLineEnd = -1; // Loop through each line in the content and add a segment, but stop if the last line is empty, // else code afterwards would fill one line too many while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) { const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (nameIndex >= 0) { segment.push(nameIndex); } this.rawSegments.push(segment); this.generatedCodeLine += 1; this.raw[this.generatedCodeLine] = this.rawSegments = []; this.generatedCodeColumn = 0; previousContentLineEnd = contentLineEnd; contentLineEnd = content.indexOf('\n', contentLineEnd + 1); } const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (nameIndex >= 0) { segment.push(nameIndex); } this.rawSegments.push(segment); this.advance(content.slice(previousContentLineEnd + 1)); } else if (this.pending) { this.rawSegments.push(this.pending); this.advance(content); } this.pending = null; } addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { let originalCharIndex = chunk.start; let first = true; // when iterating each char, check if it's in a word boundary let charInHiresBoundary = false; while (originalCharIndex < chunk.end) { if (original[originalCharIndex] === '\n') { loc.line += 1; loc.column = 0; this.generatedCodeLine += 1; this.raw[this.generatedCodeLine] = this.rawSegments = []; this.generatedCodeColumn = 0; first = true; } else { if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (this.hires === 'boundary') { // in hires "boundary", group segments per word boundary than per char if (wordRegex.test(original[originalCharIndex])) { // for first char in the boundary found, start the boundary by pushing a segment if (!charInHiresBoundary) { this.rawSegments.push(segment); charInHiresBoundary = true; } } else { // for non-word char, end the boundary by pushing a segment this.rawSegments.push(segment); charInHiresBoundary = false; } } else { this.rawSegments.push(segment); } } loc.column += 1; this.generatedCodeColumn += 1; first = false; } originalCharIndex += 1; } this.pending = null; } advance(str) { if (!str) return; const lines = str.split('\n'); if (lines.length > 1) { for (let i = 0; i < lines.length - 1; i++) { this.generatedCodeLine++; this.raw[this.generatedCodeLine] = this.rawSegments = []; } this.generatedCodeColumn = 0; } this.generatedCodeColumn += lines[lines.length - 1].length; } } const n$1 = '\n'; const warned = { insertLeft: false, insertRight: false, storeName: false, }; class MagicString { constructor(string, options = {}) { const chunk = new Chunk(0, string.length, string); Object.defineProperties(this, { original: { writable: true, value: string }, outro: { writable: true, value: '' }, intro: { writable: true, value: '' }, firstChunk: { writable: true, value: chunk }, lastChunk: { writable: true, value: chunk }, lastSearchedChunk: { writable: true, value: chunk }, byStart: { writable: true, value: {} }, byEnd: { writable: true, value: {} }, filename: { writable: true, value: options.filename }, indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, sourcemapLocations: { writable: true, value: new BitSet() }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: undefined }, ignoreList: { writable: true, value: options.ignoreList }, }); this.byStart[0] = chunk; this.byEnd[string.length] = chunk; } addSourcemapLocation(char) { this.sourcemapLocations.add(char); } append(content) { if (typeof content !== 'string') throw new TypeError('outro content must be a string'); this.outro += content; return this; } appendLeft(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byEnd[index]; if (chunk) { chunk.appendLeft(content); } else { this.intro += content; } return this; } appendRight(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byStart[index]; if (chunk) { chunk.appendRight(content); } else { this.outro += content; } return this; } clone() { const cloned = new MagicString(this.original, { filename: this.filename }); let originalChunk = this.firstChunk; let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); while (originalChunk) { cloned.byStart[clonedChunk.start] = clonedChunk; cloned.byEnd[clonedChunk.end] = clonedChunk; const nextOriginalChunk = originalChunk.next; const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); if (nextClonedChunk) { clonedChunk.next = nextClonedChunk; nextClonedChunk.previous = clonedChunk; clonedChunk = nextClonedChunk; } originalChunk = nextOriginalChunk; } cloned.lastChunk = clonedChunk; if (this.indentExclusionRanges) { cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); } cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); cloned.intro = this.intro; cloned.outro = this.outro; return cloned; } generateDecodedMap(options) { options = options || {}; const sourceIndex = 0; const names = Object.keys(this.storedNames); const mappings = new Mappings(options.hires); const locate = getLocator(this.original); if (this.intro) { mappings.advance(this.intro); } this.firstChunk.eachNext((chunk) => { const loc = locate(chunk.start); if (chunk.intro.length) mappings.advance(chunk.intro); if (chunk.edited) { mappings.addEdit( sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1, ); } else { mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); } if (chunk.outro.length) mappings.advance(chunk.outro); }); return { file: options.file ? options.file.split(/[/\\]/).pop() : undefined, sources: [ options.source ? getRelativePath$1(options.file || '', options.source) : options.file || '', ], sourcesContent: options.includeContent ? [this.original] : undefined, names, mappings: mappings.raw, x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined, }; } generateMap(options) { return new SourceMap$1(this.generateDecodedMap(options)); } _ensureindentStr() { if (this.indentStr === undefined) { this.indentStr = guessIndent(this.original); } } _getRawIndentString() { this._ensureindentStr(); return this.indentStr; } getIndentString() { this._ensureindentStr(); return this.indentStr === null ? '\t' : this.indentStr; } indent(indentStr, options) { const pattern = /^[^\r\n]/gm; if (isObject$3(indentStr)) { options = indentStr; indentStr = undefined; } if (indentStr === undefined) { this._ensureindentStr(); indentStr = this.indentStr || '\t'; } if (indentStr === '') return this; // noop options = options || {}; // Process exclusion ranges const isExcluded = {}; if (options.exclude) { const exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; exclusions.forEach((exclusion) => { for (let i = exclusion[0]; i < exclusion[1]; i += 1) { isExcluded[i] = true; } }); } let shouldIndentNextCharacter = options.indentStart !== false; const replacer = (match) => { if (shouldIndentNextCharacter) return `${indentStr}${match}`; shouldIndentNextCharacter = true; return match; }; this.intro = this.intro.replace(pattern, replacer); let charIndex = 0; let chunk = this.firstChunk; while (chunk) { const end = chunk.end; if (chunk.edited) { if (!isExcluded[charIndex]) { chunk.content = chunk.content.replace(pattern, replacer); if (chunk.content.length) { shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; } } } else { charIndex = chunk.start; while (charIndex < end) { if (!isExcluded[charIndex]) { const char = this.original[charIndex]; if (char === '\n') { shouldIndentNextCharacter = true; } else if (char !== '\r' && shouldIndentNextCharacter) { shouldIndentNextCharacter = false; if (charIndex === chunk.start) { chunk.prependRight(indentStr); } else { this._splitChunk(chunk, charIndex); chunk = chunk.next; chunk.prependRight(indentStr); } } } charIndex += 1; } } charIndex = chunk.end; chunk = chunk.next; } this.outro = this.outro.replace(pattern, replacer); return this; } insert() { throw new Error( 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)', ); } insertLeft(index, content) { if (!warned.insertLeft) { console.warn( 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead', ); // eslint-disable-line no-console warned.insertLeft = true; } return this.appendLeft(index, content); } insertRight(index, content) { if (!warned.insertRight) { console.warn( 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead', ); // eslint-disable-line no-console warned.insertRight = true; } return this.prependRight(index, content); } move(start, end, index) { if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); this._split(start); this._split(end); this._split(index); const first = this.byStart[start]; const last = this.byEnd[end]; const oldLeft = first.previous; const oldRight = last.next; const newRight = this.byStart[index]; if (!newRight && last === this.lastChunk) return this; const newLeft = newRight ? newRight.previous : this.lastChunk; if (oldLeft) oldLeft.next = oldRight; if (oldRight) oldRight.previous = oldLeft; if (newLeft) newLeft.next = first; if (newRight) newRight.previous = last; if (!first.previous) this.firstChunk = last.next; if (!last.next) { this.lastChunk = first.previous; this.lastChunk.next = null; } first.previous = newLeft; last.next = newRight || null; if (!newLeft) this.firstChunk = first; if (!newRight) this.lastChunk = last; return this; } overwrite(start, end, content, options) { options = options || {}; return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); } update(start, end, content, options) { if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); if (this.original.length !== 0) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; } if (end > this.original.length) throw new Error('end is out of bounds'); if (start === end) throw new Error( 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead', ); this._split(start); this._split(end); if (options === true) { if (!warned.storeName) { console.warn( 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string', ); // eslint-disable-line no-console warned.storeName = true; } options = { storeName: true }; } const storeName = options !== undefined ? options.storeName : false; const overwrite = options !== undefined ? options.overwrite : false; if (storeName) { const original = this.original.slice(start, end); Object.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true, }); } const first = this.byStart[start]; const last = this.byEnd[end]; if (first) { let chunk = first; while (chunk !== last) { if (chunk.next !== this.byStart[chunk.end]) { throw new Error('Cannot overwrite across a split point'); } chunk = chunk.next; chunk.edit('', false); } first.edit(content, storeName, !overwrite); } else { // must be inserting at the end const newChunk = new Chunk(start, end, '').edit(content, storeName); // TODO last chunk in the array may not be the last chunk, if it's moved... last.next = newChunk; newChunk.previous = last; } return this; } prepend(content) { if (typeof content !== 'string') throw new TypeError('outro content must be a string'); this.intro = content + this.intro; return this; } prependLeft(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byEnd[index]; if (chunk) { chunk.prependLeft(content); } else { this.intro = content + this.intro; } return this; } prependRight(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byStart[index]; if (chunk) { chunk.prependRight(content); } else { this.outro = content + this.outro; } return this; } remove(start, end) { if (this.original.length !== 0) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; } if (start === end) return this; if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); if (start > end) throw new Error('end must be greater than start'); this._split(start); this._split(end); let chunk = this.byStart[start]; while (chunk) { chunk.intro = ''; chunk.outro = ''; chunk.edit(''); chunk = end > chunk.end ? this.byStart[chunk.end] : null; } return this; } reset(start, end) { if (this.original.length !== 0) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; } if (start === end) return this; if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); if (start > end) throw new Error('end must be greater than start'); this._split(start); this._split(end); let chunk = this.byStart[start]; while (chunk) { chunk.reset(); chunk = end > chunk.end ? this.byStart[chunk.end] : null; } return this; } lastChar() { if (this.outro.length) return this.outro[this.outro.length - 1]; let chunk = this.lastChunk; do { if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; if (chunk.content.length) return chunk.content[chunk.content.length - 1]; if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; } while ((chunk = chunk.previous)); if (this.intro.length) return this.intro[this.intro.length - 1]; return ''; } lastLine() { let lineIndex = this.outro.lastIndexOf(n$1); if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); let lineStr = this.outro; let chunk = this.lastChunk; do { if (chunk.outro.length > 0) { lineIndex = chunk.outro.lastIndexOf(n$1); if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; lineStr = chunk.outro + lineStr; } if (chunk.content.length > 0) { lineIndex = chunk.content.lastIndexOf(n$1); if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; lineStr = chunk.content + lineStr; } if (chunk.intro.length > 0) { lineIndex = chunk.intro.lastIndexOf(n$1); if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; lineStr = chunk.intro + lineStr; } } while ((chunk = chunk.previous)); lineIndex = this.intro.lastIndexOf(n$1); if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; return this.intro + lineStr; } slice(start = 0, end = this.original.length) { if (this.original.length !== 0) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; } let result = ''; // find start chunk let chunk = this.firstChunk; while (chunk && (chunk.start > start || chunk.end <= start)) { // found end chunk before start if (chunk.start < end && chunk.end >= end) { return result; } chunk = chunk.next; } if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); const startChunk = chunk; while (chunk) { if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { result += chunk.intro; } const containsEnd = chunk.start < end && chunk.end >= end; if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); const sliceStart = startChunk === chunk ? start - chunk.start : 0; const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; result += chunk.content.slice(sliceStart, sliceEnd); if (chunk.outro && (!containsEnd || chunk.end === end)) { result += chunk.outro; } if (containsEnd) { break; } chunk = chunk.next; } return result; } // TODO deprecate this? not really very useful snip(start, end) { const clone = this.clone(); clone.remove(0, start); clone.remove(end, clone.original.length); return clone; } _split(index) { if (this.byStart[index] || this.byEnd[index]) return; let chunk = this.lastSearchedChunk; const searchForward = index > chunk.end; while (chunk) { if (chunk.contains(index)) return this._splitChunk(chunk, index); chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; } } _splitChunk(chunk, index) { if (chunk.edited && chunk.content.length) { // zero-length edited chunks are a special case (overlapping replacements) const loc = getLocator(this.original)(index); throw new Error( `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`, ); } const newChunk = chunk.split(index); this.byEnd[index] = chunk; this.byStart[index] = newChunk; this.byEnd[newChunk.end] = newChunk; if (chunk === this.lastChunk) this.lastChunk = newChunk; this.lastSearchedChunk = chunk; return true; } toString() { let str = this.intro; let chunk = this.firstChunk; while (chunk) { str += chunk.toString(); chunk = chunk.next; } return str + this.outro; } isEmpty() { let chunk = this.firstChunk; do { if ( (chunk.intro.length && chunk.intro.trim()) || (chunk.content.length && chunk.content.trim()) || (chunk.outro.length && chunk.outro.trim()) ) return false; } while ((chunk = chunk.next)); return true; } length() { let chunk = this.firstChunk; let length = 0; do { length += chunk.intro.length + chunk.content.length + chunk.outro.length; } while ((chunk = chunk.next)); return length; } trimLines() { return this.trim('[\\r\\n]'); } trim(charType) { return this.trimStart(charType).trimEnd(charType); } trimEndAborted(charType) { const rx = new RegExp((charType || '\\s') + '+$'); this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; let chunk = this.lastChunk; do { const end = chunk.end; const aborted = chunk.trimEnd(rx); // if chunk was trimmed, we have a new lastChunk if (chunk.end !== end) { if (this.lastChunk === chunk) { this.lastChunk = chunk.next; } this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) return true; chunk = chunk.previous; } while (chunk); return false; } trimEnd(charType) { this.trimEndAborted(charType); return this; } trimStartAborted(charType) { const rx = new RegExp('^' + (charType || '\\s') + '+'); this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; let chunk = this.firstChunk; do { const end = chunk.end; const aborted = chunk.trimStart(rx); if (chunk.end !== end) { // special case... if (chunk === this.lastChunk) this.lastChunk = chunk.next; this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) return true; chunk = chunk.next; } while (chunk); return false; } trimStart(charType) { this.trimStartAborted(charType); return this; } hasChanged() { return this.original !== this.toString(); } _replaceRegexp(searchValue, replacement) { function getReplacement(match, str) { if (typeof replacement === 'string') { return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter if (i === '$') return '$'; if (i === '&') return match[0]; const num = +i; if (num < match.length) return match[+i]; return `$${i}`; }); } else { return replacement(...match, match.index, str, match.groups); } } function matchAll(re, str) { let match; const matches = []; while ((match = re.exec(str))) { matches.push(match); } return matches; } if (searchValue.global) { const matches = matchAll(searchValue, this.original); matches.forEach((match) => { if (match.index != null) { const replacement = getReplacement(match, this.original); if (replacement !== match[0]) { this.overwrite( match.index, match.index + match[0].length, replacement ); } } }); } else { const match = this.original.match(searchValue); if (match && match.index != null) { const replacement = getReplacement(match, this.original); if (replacement !== match[0]) { this.overwrite( match.index, match.index + match[0].length, replacement ); } } } return this; } _replaceString(string, replacement) { const { original } = this; const index = original.indexOf(string); if (index !== -1) { this.overwrite(index, index + string.length, replacement); } return this; } replace(searchValue, replacement) { if (typeof searchValue === 'string') { return this._replaceString(searchValue, replacement); } return this._replaceRegexp(searchValue, replacement); } _replaceAllString(string, replacement) { const { original } = this; const stringLength = string.length; for ( let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength) ) { const previous = original.slice(index, index + stringLength); if (previous !== replacement) this.overwrite(index, index + stringLength, replacement); } return this; } replaceAll(searchValue, replacement) { if (typeof searchValue === 'string') { return this._replaceAllString(searchValue, replacement); } if (!searchValue.global) { throw new TypeError( 'MagicString.prototype.replaceAll called with a non-global RegExp argument', ); } return this._replaceRegexp(searchValue, replacement); } } function isReference(node, parent) { if (node.type === 'MemberExpression') { return !node.computed && isReference(node.object, node); } if (node.type === 'Identifier') { if (!parent) return true; switch (parent.type) { // disregard `bar` in `foo.bar` case 'MemberExpression': return parent.computed || node === parent.object; // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}` case 'MethodDefinition': return parent.computed; // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}` case 'FieldDefinition': return parent.computed || node === parent.value; // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }` case 'Property': return parent.computed || node === parent.value; // disregard the `bar` in `export { foo as bar }` or // the foo in `import { foo as bar }` case 'ExportSpecifier': case 'ImportSpecifier': return node === parent.local; // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}` case 'LabeledStatement': case 'BreakStatement': case 'ContinueStatement': return false; default: return true; } } return false; } var version$2 = "28.0.1"; var peerDependencies = { rollup: "^2.68.0||^3.0.0||^4.0.0" }; function tryParse(parse, code, id) { try { return parse(code, { allowReturnOutsideFunction: true }); } catch (err) { err.message += ` in ${id}`; throw err; } } const firstpassGlobal = /\b(?:require|module|exports|global)\b/; const firstpassNoGlobal = /\b(?:require|module|exports)\b/; function hasCjsKeywords(code, ignoreGlobal) { const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal; return firstpass.test(code); } /* eslint-disable no-underscore-dangle */ function analyzeTopLevelStatements(parse, code, id) { const ast = tryParse(parse, code, id); let isEsModule = false; let hasDefaultExport = false; let hasNamedExports = false; for (const node of ast.body) { switch (node.type) { case 'ExportDefaultDeclaration': isEsModule = true; hasDefaultExport = true; break; case 'ExportNamedDeclaration': isEsModule = true; if (node.declaration) { hasNamedExports = true; } else { for (const specifier of node.specifiers) { if (specifier.exported.name === 'default') { hasDefaultExport = true; } else { hasNamedExports = true; } } } break; case 'ExportAllDeclaration': isEsModule = true; if (node.exported && node.exported.name === 'default') { hasDefaultExport = true; } else { hasNamedExports = true; } break; case 'ImportDeclaration': isEsModule = true; break; } } return { isEsModule, hasDefaultExport, hasNamedExports, ast }; } /* eslint-disable import/prefer-default-export */ function deconflict(scopes, globals, identifier) { let i = 1; let deconflicted = makeLegalIdentifier(identifier); const hasConflicts = () => scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted); while (hasConflicts()) { deconflicted = makeLegalIdentifier(`${identifier}_${i}`); i += 1; } for (const scope of scopes) { scope.declarations[deconflicted] = true; } return deconflicted; } function getName(id) { const name = makeLegalIdentifier(basename$1(id, extname(id))); if (name !== 'index') { return name; } return makeLegalIdentifier(basename$1(dirname$1(id))); } function normalizePathSlashes(path) { return path.replace(/\\/g, '/'); } const getVirtualPathForDynamicRequirePath = (path, commonDir) => `/${normalizePathSlashes(relative$1(commonDir, path))}`; function capitalize(name) { return name[0].toUpperCase() + name.slice(1); } function getStrictRequiresFilter({ strictRequires }) { switch (strictRequires) { // eslint-disable-next-line no-undefined case undefined: case true: return { strictRequiresFilter: () => true, detectCyclesAndConditional: false }; case 'auto': case 'debug': case null: return { strictRequiresFilter: () => false, detectCyclesAndConditional: true }; case false: return { strictRequiresFilter: () => false, detectCyclesAndConditional: false }; default: if (typeof strictRequires === 'string' || Array.isArray(strictRequires)) { return { strictRequiresFilter: createFilter$1(strictRequires), detectCyclesAndConditional: false }; } throw new Error('Unexpected value for "strictRequires" option.'); } } function getPackageEntryPoint(dirPath) { let entryPoint = 'index.js'; try { if (existsSync(join(dirPath, 'package.json'))) { entryPoint = JSON.parse(readFileSync(join(dirPath, 'package.json'), { encoding: 'utf8' })).main || entryPoint; } } catch (ignored) { // ignored } return entryPoint; } function isDirectory$1(path) { try { if (statSync(path).isDirectory()) return true; } catch (ignored) { // Nothing to do here } return false; } function getDynamicRequireModules(patterns, dynamicRequireRoot) { const dynamicRequireModules = new Map(); const dirNames = new Set(); for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) { const isNegated = pattern.startsWith('!'); const modifyMap = (targetPath, resolvedPath) => isNegated ? dynamicRequireModules.delete(targetPath) : dynamicRequireModules.set(targetPath, resolvedPath); // eslint-disable-next-line new-cap for (const path of new dist.fdir() .withBasePath() .withDirs() .glob(isNegated ? pattern.substr(1) : pattern) .crawl() .sync() .sort((a, b) => a.localeCompare(b, 'en'))) { const resolvedPath = resolve$3(path); const requirePath = normalizePathSlashes(resolvedPath); if (isDirectory$1(resolvedPath)) { dirNames.add(resolvedPath); const modulePath = resolve$3(join(resolvedPath, getPackageEntryPoint(path))); modifyMap(requirePath, modulePath); modifyMap(normalizePathSlashes(modulePath), modulePath); } else { dirNames.add(dirname$1(resolvedPath)); modifyMap(requirePath, resolvedPath); } } } return { commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null, dynamicRequireModules }; } const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`; const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire'; const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire'; function getDynamicModuleRegistry( isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires ) { if (!isDynamicRequireModulesEnabled) { return `export function ${COMMONJS_REQUIRE_EXPORT}(path) { ${FAILED_REQUIRE_ERROR} }`; } const dynamicModuleImports = [...dynamicRequireModules.values()] .map( (id, index) => `import ${ id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }` } from ${JSON.stringify(id)};` ) .join('\n'); const dynamicModuleProps = [...dynamicRequireModules.keys()] .map( (id, index) => `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${ id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}` }` ) .join(',\n'); return `${dynamicModuleImports} var dynamicModules; function getDynamicModules() { return dynamicModules || (dynamicModules = { ${dynamicModuleProps} }); } export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) { function handleRequire(path) { var resolvedPath = commonjsResolve(path, originalModuleDir); if (resolvedPath !== null) { return getDynamicModules()[resolvedPath](); } ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR} } handleRequire.resolve = function (path) { var resolvedPath = commonjsResolve(path, originalModuleDir); if (resolvedPath !== null) { return resolvedPath; } return require.resolve(path); } return handleRequire; } function commonjsResolve (path, originalModuleDir) { var shouldTryNodeModules = isPossibleNodeModulesPath(path); path = normalize(path); var relPath; if (path[0] === '/') { originalModuleDir = ''; } var modules = getDynamicModules(); var checkedExtensions = ['', '.js', '.json']; while (true) { if (!shouldTryNodeModules) { relPath = normalize(originalModuleDir + '/' + path); } else { relPath = normalize(originalModuleDir + '/node_modules/' + path); } if (relPath.endsWith('/..')) { break; // Travelled too far up, avoid infinite loop } for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) { var resolvedPath = relPath + checkedExtensions[extensionIndex]; if (modules[resolvedPath]) { return resolvedPath; } } if (!shouldTryNodeModules) break; var nextDir = normalize(originalModuleDir + '/..'); if (nextDir === originalModuleDir) break; originalModuleDir = nextDir; } return null; } function isPossibleNodeModulesPath (modulePath) { var c0 = modulePath[0]; if (c0 === '/' || c0 === '\\\\') return false; var c1 = modulePath[1], c2 = modulePath[2]; if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) || (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false; if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false; return true; } function normalize (path) { path = path.replace(/\\\\/g, '/'); var parts = path.split('/'); var slashed = parts[0] === ''; for (var i = 1; i < parts.length; i++) { if (parts[i] === '.' || parts[i] === '') { parts.splice(i--, 1); } } for (var i = 1; i < parts.length; i++) { if (parts[i] !== '..') continue; if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') { parts.splice(--i, 2); i--; } } path = parts.join('/'); if (slashed && path[0] !== '/') path = '/' + path; else if (path.length === 0) path = '.'; return path; }`; } const isWrappedId = (id, suffix) => id.endsWith(suffix); const wrapId = (id, suffix) => `\0${id}${suffix}`; const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length); // A proxy module when a module is required from non-wrapped CommonJS. Is different for ESM and CommonJS requires. const PROXY_SUFFIX = '?commonjs-proxy'; // Indicates that a required module is wrapped commonjs and needs special handling. const WRAPPED_SUFFIX = '?commonjs-wrapped'; // Indicates that a required module is external const EXTERNAL_SUFFIX = '?commonjs-external'; // A helper module that contains the exports object of a module const EXPORTS_SUFFIX = '?commonjs-exports'; // A helper module that contains the module object of a module, e.g. when module.exports is reassigned const MODULE_SUFFIX = '?commonjs-module'; // A special proxy for CommonJS entry points const ENTRY_SUFFIX = '?commonjs-entry'; // A proxy when wrapped ESM is required from CommonJS const ES_IMPORT_SUFFIX = '?commonjs-es-import'; const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules'; const HELPERS_ID = '\0commonjsHelpers.js'; const IS_WRAPPED_COMMONJS = 'withRequireFunction'; // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers. // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled. // This could be improved by inspecting Rollup's "generatedCode" option const HELPERS = ` export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; export function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } export function getDefaultExportFromNamespaceIfPresent (n) { return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; } export function getDefaultExportFromNamespaceIfNotNamed (n) { return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; } export function getAugmentedNamespace(n) { if (n.__esModule) return n; var f = n.default; if (typeof f == "function") { var a = function a () { if (this instanceof a) { return Reflect.construct(f, arguments, this.constructor); } return f.apply(this, arguments); }; a.prototype = f.prototype; } else a = {}; Object.defineProperty(a, '__esModule', {value: true}); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function () { return n[k]; } }); }); return a; } `; function getHelpersModule() { return HELPERS; } function getUnknownRequireProxy(id, requireReturnsDefault) { if (requireReturnsDefault === true || id.endsWith('.json')) { return `export { default } from ${JSON.stringify(id)};`; } const name = getName(id); const exported = requireReturnsDefault === 'auto' ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});` : requireReturnsDefault === 'preferred' ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});` : !requireReturnsDefault ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});` : `export default ${name};`; return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`; } async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) { const name = getName(id); const { meta: { commonjs: commonjsMeta } } = await loadModule({ id }); if (!commonjsMeta) { return getUnknownRequireProxy(id, requireReturnsDefault); } if (commonjsMeta.isCommonJS) { return `export { __moduleExports as default } from ${JSON.stringify(id)};`; } if (!requireReturnsDefault) { return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify( id )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`; } if ( requireReturnsDefault !== true && (requireReturnsDefault === 'namespace' || !commonjsMeta.hasDefaultExport || (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports)) ) { return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`; } return `export { default } from ${JSON.stringify(id)};`; } function getEntryProxy(id, defaultIsModuleExports, getModuleInfo, shebang) { const { meta: { commonjs: commonjsMeta }, hasDefaultExport } = getModuleInfo(id); if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) { const stringifiedId = JSON.stringify(id); let code = `export * from ${stringifiedId};`; if (hasDefaultExport) { code += `export { default } from ${stringifiedId};`; } return shebang + code; } const result = getEsImportProxy(id, defaultIsModuleExports, true); return { ...result, code: shebang + result.code }; } function getEsImportProxy(id, defaultIsModuleExports, moduleSideEffects) { const name = getName(id); const exportsName = `${name}Exports`; const requireModule = `require${capitalize(name)}`; let code = `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` + `import { __require as ${requireModule} } from ${JSON.stringify(id)};\n` + `var ${exportsName} = ${moduleSideEffects ? '' : '/*@__PURE__*/ '}${requireModule}();\n` + `export { ${exportsName} as __moduleExports };`; if (defaultIsModuleExports === true) { code += `\nexport { ${exportsName} as default };`; } else if (defaultIsModuleExports === false) { code += `\nexport default ${exportsName}.default;`; } else { code += `\nexport default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`; } return { code, syntheticNamedExports: '__moduleExports' }; } /* eslint-disable no-param-reassign, no-undefined */ function getCandidatesForExtension(resolved, extension) { return [resolved + extension, `${resolved}${sep}index${extension}`]; } function getCandidates(resolved, extensions) { return extensions.reduce( (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)), [resolved] ); } function resolveExtensions(importee, importer, extensions) { // not our problem if (importee[0] !== '.' || !importer) return undefined; const resolved = resolve$3(dirname$1(importer), importee); const candidates = getCandidates(resolved, extensions); for (let i = 0; i < candidates.length; i += 1) { try { const stats = statSync(candidates[i]); if (stats.isFile()) return { id: candidates[i] }; } catch (err) { /* noop */ } } return undefined; } function getResolveId(extensions, isPossibleCjsId) { const currentlyResolving = new Map(); return { /** * This is a Maps of importers to Sets of require sources being resolved at * the moment by resolveRequireSourcesAndUpdateMeta */ currentlyResolving, async resolveId(importee, importer, resolveOptions) { const customOptions = resolveOptions.custom; // All logic below is specific to ES imports. // Also, if we do not skip this logic for requires that are resolved while // transforming a commonjs file, it can easily lead to deadlocks. if (customOptions?.['node-resolve']?.isRequire) { return null; } const currentlyResolvingForParent = currentlyResolving.get(importer); if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) { this.warn({ code: 'THIS_RESOLVE_WITHOUT_OPTIONS', message: 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.', url: 'https://rollupjs.org/guide/en/#resolveid' }); return null; } if (isWrappedId(importee, WRAPPED_SUFFIX)) { return unwrapId(importee, WRAPPED_SUFFIX); } if ( importee.endsWith(ENTRY_SUFFIX) || isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX) || isWrappedId(importee, PROXY_SUFFIX) || isWrappedId(importee, ES_IMPORT_SUFFIX) || isWrappedId(importee, EXTERNAL_SUFFIX) || importee.startsWith(HELPERS_ID) || importee === DYNAMIC_MODULES_ID ) { return importee; } if (importer) { if ( importer === DYNAMIC_MODULES_ID || // Proxies are only importing resolved ids, no need to resolve again isWrappedId(importer, PROXY_SUFFIX) || isWrappedId(importer, ES_IMPORT_SUFFIX) || importer.endsWith(ENTRY_SUFFIX) ) { return importee; } if (isWrappedId(importer, EXTERNAL_SUFFIX)) { // We need to return null for unresolved imports so that the proper warning is shown if ( !(await this.resolve( importee, importer, Object.assign({ skipSelf: true }, resolveOptions) )) ) { return null; } // For other external imports, we need to make sure they are handled as external return { id: importee, external: true }; } } if (importee.startsWith('\0')) { return null; } // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and // if that is the case, we need to add a proxy. const resolved = (await this.resolve( importee, importer, Object.assign({ skipSelf: true }, resolveOptions) )) || resolveExtensions(importee, importer, extensions); // Make sure that even if other plugins resolve again, we ignore our own proxies if ( !resolved || resolved.external || resolved.id.endsWith(ENTRY_SUFFIX) || isWrappedId(resolved.id, ES_IMPORT_SUFFIX) || !isPossibleCjsId(resolved.id) ) { return resolved; } const moduleInfo = await this.load(resolved); const { meta: { commonjs: commonjsMeta } } = moduleInfo; if (commonjsMeta) { const { isCommonJS } = commonjsMeta; if (isCommonJS) { if (resolveOptions.isEntry) { moduleInfo.moduleSideEffects = true; // We must not precede entry proxies with a `\0` as that will mess up relative external resolution return resolved.id + ENTRY_SUFFIX; } if (isCommonJS === IS_WRAPPED_COMMONJS) { return { id: wrapId(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } }; } } } return resolved; } }; } function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) { const knownCjsModuleTypes = Object.create(null); const requiredIds = Object.create(null); const unconditionallyRequiredIds = Object.create(null); const dependencies = Object.create(null); const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set()); const isCyclic = (id) => { const dependenciesToCheck = new Set(getDependencies(id)); for (const dependency of dependenciesToCheck) { if (dependency === id) { return true; } for (const childDependency of getDependencies(dependency)) { dependenciesToCheck.add(childDependency); } } return false; }; // Once a module is listed here, its type (wrapped or not) is fixed and may // not change for the rest of the current build, to not break already // transformed modules. const fullyAnalyzedModules = Object.create(null); const getTypeForFullyAnalyzedModule = (id) => { const knownType = knownCjsModuleTypes[id]; if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) { return knownType; } if (isCyclic(id)) { return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS); } return knownType; }; const setInitialParentType = (id, initialCommonJSType) => { // Fully analyzed modules may never change type if (fullyAnalyzedModules[id]) { return; } knownCjsModuleTypes[id] = initialCommonJSType; if ( detectCyclesAndConditional && knownCjsModuleTypes[id] === true && requiredIds[id] && !unconditionallyRequiredIds[id] ) { knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS; } }; const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => { const childId = resolved.id; requiredIds[childId] = true; if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) { unconditionallyRequiredIds[childId] = true; } getDependencies(parentId).add(childId); if (!isCyclic(childId)) { // This makes sure the current transform handler waits for all direct // dependencies to be loaded and transformed and therefore for all // transitive CommonJS dependencies to be loaded as well so that all // cycles have been found and knownCjsModuleTypes is reliable. await loadModule(resolved); } }; const getTypeForImportedModule = async (resolved, loadModule) => { if (resolved.id in knownCjsModuleTypes) { // This handles cyclic ES dependencies return knownCjsModuleTypes[resolved.id]; } const { meta: { commonjs } } = await loadModule(resolved); return (commonjs && commonjs.isCommonJS) || false; }; return { getWrappedIds: () => Object.keys(knownCjsModuleTypes).filter( (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS ), isRequiredId: (id) => requiredIds[id], async shouldTransformCachedModule({ id: parentId, resolvedSources, meta: { commonjs: parentMeta } }) { // We explicitly track ES modules to handle circular imports if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false; if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false; const parentRequires = parentMeta && parentMeta.requires; if (parentRequires) { setInitialParentType(parentId, parentMeta.initialCommonJSType); await Promise.all( parentRequires.map(({ resolved, isConditional }) => analyzeRequiredModule(parentId, resolved, isConditional, this.load) ) ); if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) { return true; } for (const { resolved: { id } } of parentRequires) { if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) { return true; } } // Now that we decided to go with the cached copy, neither the parent // module nor any of its children may change types anymore fullyAnalyzedModules[parentId] = true; for (const { resolved: { id } } of parentRequires) { fullyAnalyzedModules[id] = true; } } const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id)); return ( await Promise.all( Object.keys(resolvedSources) .map((source) => resolvedSources[source]) .filter(({ id, external }) => !(external || parentRequireSet.has(id))) .map(async (resolved) => { if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) { return ( (await getTypeForImportedModule( ( await this.load({ id: resolved.id }) ).meta.commonjs.resolved, this.load )) !== IS_WRAPPED_COMMONJS ); } return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS; }) ) ).some((shouldTransform) => shouldTransform); }, /* eslint-disable no-param-reassign */ resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => { parentMeta.initialCommonJSType = isParentCommonJS; parentMeta.requires = []; parentMeta.isRequiredCommonJS = Object.create(null); setInitialParentType(parentId, isParentCommonJS); const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set(); currentlyResolving.set(parentId, currentlyResolvingForParent); const requireTargets = await Promise.all( sources.map(async ({ source, isConditional }) => { // Never analyze or proxy internal modules if (source.startsWith('\0')) { return { id: source, allowProxy: false }; } currentlyResolvingForParent.add(source); const resolved = (await rollupContext.resolve(source, parentId, { skipSelf: false, custom: { 'node-resolve': { isRequire: true } } })) || resolveExtensions(source, parentId, extensions); currentlyResolvingForParent.delete(source); if (!resolved) { return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false }; } const childId = resolved.id; if (resolved.external) { return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false }; } parentMeta.requires.push({ resolved, isConditional }); await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load); return { id: childId, allowProxy: true }; }) ); parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId); fullyAnalyzedModules[parentId] = true; return requireTargets.map(({ id: dependencyId, allowProxy }, index) => { // eslint-disable-next-line no-multi-assign const isCommonJS = (parentMeta.isRequiredCommonJS[dependencyId] = getTypeForFullyAnalyzedModule(dependencyId)); const isWrappedCommonJS = isCommonJS === IS_WRAPPED_COMMONJS; fullyAnalyzedModules[dependencyId] = true; return { wrappedModuleSideEffects: isWrappedCommonJS && rollupContext.getModuleInfo(dependencyId).moduleSideEffects, source: sources[index].source, id: allowProxy ? wrapId(dependencyId, isWrappedCommonJS ? WRAPPED_SUFFIX : PROXY_SUFFIX) : dependencyId, isCommonJS }; }); }, isCurrentlyResolving(source, parentId) { const currentlyResolvingForParent = currentlyResolving.get(parentId); return currentlyResolvingForParent && currentlyResolvingForParent.has(source); } }; } function validateVersion(actualVersion, peerDependencyVersion, name) { const versionRegexp = /\^(\d+\.\d+\.\d+)/g; let minMajor = Infinity; let minMinor = Infinity; let minPatch = Infinity; let foundVersion; // eslint-disable-next-line no-cond-assign while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) { const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number); if (foundMajor < minMajor) { minMajor = foundMajor; minMinor = foundMinor; minPatch = foundPatch; } } if (!actualVersion) { throw new Error( `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.` ); } const [major, minor, patch] = actualVersion.split('.').map(Number); if ( major < minMajor || (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch))) ) { throw new Error( `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.` ); } } const operators = { '==': (x) => equals(x.left, x.right, false), '!=': (x) => not(operators['=='](x)), '===': (x) => equals(x.left, x.right, true), '!==': (x) => not(operators['==='](x)), '!': (x) => isFalsy(x.argument), '&&': (x) => isTruthy(x.left) && isTruthy(x.right), '||': (x) => isTruthy(x.left) || isTruthy(x.right) }; function not(value) { return value === null ? value : !value; } function equals(a, b, strict) { if (a.type !== b.type) return null; // eslint-disable-next-line eqeqeq if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value; return null; } function isTruthy(node) { if (!node) return false; if (node.type === 'Literal') return !!node.value; if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression); if (node.operator in operators) return operators[node.operator](node); return null; } function isFalsy(node) { return not(isTruthy(node)); } function getKeypath(node) { const parts = []; while (node.type === 'MemberExpression') { if (node.computed) return null; parts.unshift(node.property.name); // eslint-disable-next-line no-param-reassign node = node.object; } if (node.type !== 'Identifier') return null; const { name } = node; parts.unshift(name); return { name, keypath: parts.join('.') }; } const KEY_COMPILED_ESM = '__esModule'; function getDefineCompiledEsmType(node) { const definedPropertyWithExports = getDefinePropertyCallName(node, 'exports'); const definedProperty = definedPropertyWithExports || getDefinePropertyCallName(node, 'module.exports'); if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) { return isTruthy(definedProperty.value) ? definedPropertyWithExports ? 'exports' : 'module' : false; } return false; } function getDefinePropertyCallName(node, targetName) { const { callee: { object, property } } = node; if (!object || object.type !== 'Identifier' || object.name !== 'Object') return; if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return; if (node.arguments.length !== 3) return; const targetNames = targetName.split('.'); const [target, key, value] = node.arguments; if (targetNames.length === 1) { if (target.type !== 'Identifier' || target.name !== targetNames[0]) { return; } } if (targetNames.length === 2) { if ( target.type !== 'MemberExpression' || target.object.name !== targetNames[0] || target.property.name !== targetNames[1] ) { return; } } if (value.type !== 'ObjectExpression' || !value.properties) return; const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value'); if (!valueProperty || !valueProperty.value) return; // eslint-disable-next-line consistent-return return { key: key.value, value: valueProperty.value }; } function isShorthandProperty(parent) { return parent && parent.type === 'Property' && parent.shorthand; } function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) { const args = []; const passedArgs = []; if (uses.module) { args.push('module'); passedArgs.push(moduleName); } if (uses.exports) { args.push('exports'); passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName); } magicString .trim() .indent('\t', { exclude: indentExclusionRanges }) .prepend(`(function (${args.join(', ')}) {\n`) // For some reason, this line is only indented correctly when using a // require-wrapper if we have this leading space .append(` \n} (${passedArgs.join(', ')}));`); } function rewriteExportsAndGetExportsBlock( magicString, moduleName, exportsName, exportedExportsName, wrapped, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, defineCompiledEsmExpressions, deconflictedExportNames, code, HELPERS_NAME, exportMode, defaultIsModuleExports, usesRequireWrapper, requireName ) { const exports = []; const exportDeclarations = []; if (usesRequireWrapper) { getExportsWhenUsingRequireWrapper( magicString, wrapped, exportMode, exports, moduleExportsAssignments, exportsAssignmentsByName, moduleName, exportsName, requireName, defineCompiledEsmExpressions ); } else if (exportMode === 'replace') { getExportsForReplacedModuleExports( magicString, exports, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName, defaultIsModuleExports, HELPERS_NAME ); } else { if (exportMode === 'module') { exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`); exports.push(`${exportedExportsName} as __moduleExports`); } else { exports.push(`${exportsName} as __moduleExports`); } if (wrapped) { exportDeclarations.push( getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) ); } else { getExports( magicString, exports, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, exportedExportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports, exportMode ); } } if (exports.length) { exportDeclarations.push(`export { ${exports.join(', ')} }`); } return `\n\n${exportDeclarations.join(';\n')};`; } function getExportsWhenUsingRequireWrapper( magicString, wrapped, exportMode, exports, moduleExportsAssignments, exportsAssignmentsByName, moduleName, exportsName, requireName, defineCompiledEsmExpressions ) { exports.push(`${requireName} as __require`); if (wrapped) return; if (exportMode === 'replace') { rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName); } else { rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`); // Collect and rewrite named exports for (const [exportName, { nodes }] of exportsAssignmentsByName) { for (const { node, type } of nodes) { magicString.overwrite( node.start, node.left.end, `${ exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName }.${exportName}` ); } } replaceDefineCompiledEsmExpressionsAndGetIfRestorable( defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName ); } } function getExportsForReplacedModuleExports( magicString, exports, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName, defaultIsModuleExports, HELPERS_NAME ) { for (const { left } of moduleExportsAssignments) { magicString.overwrite(left.start, left.end, exportsName); } magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var '); exports.push(`${exportsName} as __moduleExports`); exportDeclarations.push( getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME) ); } function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) { return `export default ${ defaultIsModuleExports === true ? exportedExportsName : defaultIsModuleExports === false ? `${exportedExportsName}.default` : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})` }`; } function getExports( magicString, exports, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, exportedExportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports, exportMode ) { let deconflictedDefaultExportName; // Collect and rewrite module.exports assignments for (const { left } of moduleExportsAssignments) { magicString.overwrite(left.start, left.end, `${moduleName}.exports`); } // Collect and rewrite named exports for (const [exportName, { nodes }] of exportsAssignmentsByName) { const deconflicted = deconflictedExportNames[exportName]; let needsDeclaration = true; for (const { node, type } of nodes) { let replacement = `${deconflicted} = ${ exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName }.${exportName}`; if (needsDeclaration && topLevelAssignments.has(node)) { replacement = `var ${replacement}`; needsDeclaration = false; } magicString.overwrite(node.start, node.left.end, replacement); } if (needsDeclaration) { magicString.prepend(`var ${deconflicted};\n`); } if (exportName === 'default') { deconflictedDefaultExportName = deconflicted; } else { exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`); } } const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable( defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName ); if ( defaultIsModuleExports === false || (defaultIsModuleExports === 'auto' && isRestorableCompiledEsm && moduleExportsAssignments.length === 0) ) { // If there is no deconflictedDefaultExportName, then we use the namespace as // fallback because there can be no "default" property on the namespace exports.push(`${deconflictedDefaultExportName || exportedExportsName} as default`); } else if ( defaultIsModuleExports === true || (!isRestorableCompiledEsm && moduleExportsAssignments.length === 0) ) { exports.push(`${exportedExportsName} as default`); } else { exportDeclarations.push( getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) ); } } function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) { for (const { left } of moduleExportsAssignments) { magicString.overwrite(left.start, left.end, exportsName); } } function replaceDefineCompiledEsmExpressionsAndGetIfRestorable( defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName ) { let isRestorableCompiledEsm = false; for (const { node, type } of defineCompiledEsmExpressions) { isRestorableCompiledEsm = true; const moduleExportsExpression = node.type === 'CallExpression' ? node.arguments[0] : node.left.object; magicString.overwrite( moduleExportsExpression.start, moduleExportsExpression.end, exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName ); } return isRestorableCompiledEsm; } function isRequireExpression(node, scope) { if (!node) return false; if (node.type !== 'CallExpression') return false; // Weird case of `require()` or `module.require()` without arguments if (node.arguments.length === 0) return false; return isRequire(node.callee, scope); } function isRequire(node, scope) { return ( (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) || (node.type === 'MemberExpression' && isModuleRequire(node, scope)) ); } function isModuleRequire({ object, property }, scope) { return ( object.type === 'Identifier' && object.name === 'module' && property.type === 'Identifier' && property.name === 'require' && !scope.contains('module') ); } function hasDynamicArguments(node) { return ( node.arguments.length > 1 || (node.arguments[0].type !== 'Literal' && (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0)) ); } const reservedMethod = { resolve: true, cache: true, main: true }; function isNodeRequirePropertyAccess(parent) { return parent && parent.property && reservedMethod[parent.property.name]; } function getRequireStringArg(node) { return node.arguments[0].type === 'Literal' ? node.arguments[0].value : node.arguments[0].quasis[0].value.cooked; } function getRequireHandlers() { const requireExpressions = []; function addRequireExpression( sourceId, node, scope, usesReturnValue, isInsideTryBlock, isInsideConditional, toBeRemoved ) { requireExpressions.push({ sourceId, node, scope, usesReturnValue, isInsideTryBlock, isInsideConditional, toBeRemoved }); } async function rewriteRequireExpressionsAndGetImportBlock( magicString, topLevelDeclarations, reassignedNames, helpersName, dynamicRequireName, moduleName, exportsName, id, exportMode, resolveRequireSourcesAndUpdateMeta, needsRequireWrapper, isEsModule, isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, commonjsMeta ) { const imports = []; imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`); if (dynamicRequireName) { imports.push( `import { ${ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"` ); } if (exportMode === 'module') { imports.push( `import { __module as ${moduleName} } from ${JSON.stringify(wrapId(id, MODULE_SUFFIX))}`, `var ${exportsName} = ${moduleName}.exports` ); } else if (exportMode === 'exports') { imports.push( `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}` ); } const requiresBySource = collectSources(requireExpressions); const requireTargets = await resolveRequireSourcesAndUpdateMeta( id, needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule, commonjsMeta, Object.keys(requiresBySource).map((source) => { return { source, isConditional: requiresBySource[source].every((require) => require.isInsideConditional) }; }) ); processRequireExpressions( imports, requireTargets, requiresBySource, getIgnoreTryCatchRequireStatementMode, magicString ); return imports.length ? `${imports.join(';\n')};\n\n` : ''; } return { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock }; } function collectSources(requireExpressions) { const requiresBySource = Object.create(null); for (const requireExpression of requireExpressions) { const { sourceId } = requireExpression; if (!requiresBySource[sourceId]) { requiresBySource[sourceId] = []; } const requires = requiresBySource[sourceId]; requires.push(requireExpression); } return requiresBySource; } function processRequireExpressions( imports, requireTargets, requiresBySource, getIgnoreTryCatchRequireStatementMode, magicString ) { const generateRequireName = getGenerateRequireName(); for (const { source, id: resolvedId, isCommonJS, wrappedModuleSideEffects } of requireTargets) { const requires = requiresBySource[source]; const name = generateRequireName(requires); let usesRequired = false; let needsImport = false; for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) { const { canConvertRequire, shouldRemoveRequire } = isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX) ? getIgnoreTryCatchRequireStatementMode(source) : { canConvertRequire: true, shouldRemoveRequire: false }; if (shouldRemoveRequire) { if (usesReturnValue) { magicString.overwrite(node.start, node.end, 'undefined'); } else { magicString.remove(toBeRemoved.start, toBeRemoved.end); } } else if (canConvertRequire) { needsImport = true; if (isCommonJS === IS_WRAPPED_COMMONJS) { magicString.overwrite( node.start, node.end, `${wrappedModuleSideEffects ? '' : '/*@__PURE__*/ '}${name}()` ); } else if (usesReturnValue) { usesRequired = true; magicString.overwrite(node.start, node.end, name); } else { magicString.remove(toBeRemoved.start, toBeRemoved.end); } } } if (needsImport) { if (isCommonJS === IS_WRAPPED_COMMONJS) { imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)}`); } else { imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)}`); } } } } function getGenerateRequireName() { let uid = 0; return (requires) => { let name; const hasNameConflict = ({ scope }) => scope.contains(name); do { name = `require$$${uid}`; uid += 1; } while (requires.some(hasNameConflict)); return name; }; } /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */ const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/; const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/; // There are three different types of CommonJS modules, described by their // "exportMode": // - exports: Only assignments to (module.)exports properties // - replace: A single assignment to module.exports itself // - module: Anything else // Special cases: // - usesRequireWrapper // - isWrapped async function transformCommonjs( parse, code, id, isEsModule, ignoreGlobal, ignoreRequire, ignoreDynamicRequires, getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, astCache, defaultIsModuleExports, needsRequireWrapper, resolveRequireSourcesAndUpdateMeta, isRequired, checkDynamicRequire, commonjsMeta ) { const ast = astCache || tryParse(parse, code, id); const magicString = new MagicString(code); const uses = { module: false, exports: false, global: false, require: false }; const virtualDynamicRequirePath = isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname$1(id), commonDir); let scope = attachScopes(ast, 'scope'); let lexicalDepth = 0; let programDepth = 0; let classBodyDepth = 0; let currentTryBlockEnd = null; let shouldWrap = false; const globals = new Set(); // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require // or contains nested requires, those should be handled as function calls unless there is an // unconditional require elsewhere. let currentConditionalNodeEnd = null; const conditionalNodes = new Set(); const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers(); // See which names are assigned to. This is necessary to prevent // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`, // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh) const reassignedNames = new Set(); const topLevelDeclarations = []; const skippedNodes = new Set(); const moduleAccessScopes = new Set([scope]); const exportsAccessScopes = new Set([scope]); const moduleExportsAssignments = []; let firstTopLevelModuleExportsAssignment = null; const exportsAssignmentsByName = new Map(); const topLevelAssignments = new Set(); const topLevelDefineCompiledEsmExpressions = []; const replacedGlobal = []; const replacedThis = []; const replacedDynamicRequires = []; const importedVariables = new Set(); const indentExclusionRanges = []; walk$2(ast, { enter(node, parent) { if (skippedNodes.has(node)) { this.skip(); return; } if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) { currentTryBlockEnd = null; } if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) { currentConditionalNodeEnd = null; } if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) { currentConditionalNodeEnd = node.end; } programDepth += 1; if (node.scope) ({ scope } = node); if (functionType.test(node.type)) lexicalDepth += 1; if (sourceMap) { magicString.addSourcemapLocation(node.start); magicString.addSourcemapLocation(node.end); } // eslint-disable-next-line default-case switch (node.type) { case 'AssignmentExpression': if (node.left.type === 'MemberExpression') { const flattened = getKeypath(node.left); if (!flattened || scope.contains(flattened.name)) return; const exportsPatternMatch = exportsPattern.exec(flattened.keypath); if (!exportsPatternMatch || flattened.keypath === 'exports') return; const [, exportName] = exportsPatternMatch; uses[flattened.name] = true; // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` – if (flattened.keypath === 'module.exports') { moduleExportsAssignments.push(node); if (programDepth > 3) { moduleAccessScopes.add(scope); } else if (!firstTopLevelModuleExportsAssignment) { firstTopLevelModuleExportsAssignment = node; } } else if (exportName === KEY_COMPILED_ESM) { if (programDepth > 3) { shouldWrap = true; } else { // The "type" is either "module" or "exports" to discern // assignments to module.exports vs exports if needed topLevelDefineCompiledEsmExpressions.push({ node, type: flattened.name }); } } else { const exportsAssignments = exportsAssignmentsByName.get(exportName) || { nodes: [], scopes: new Set() }; exportsAssignments.nodes.push({ node, type: flattened.name }); exportsAssignments.scopes.add(scope); exportsAccessScopes.add(scope); exportsAssignmentsByName.set(exportName, exportsAssignments); if (programDepth <= 3) { topLevelAssignments.add(node); } } skippedNodes.add(node.left); } else { for (const name of extractAssignedNames(node.left)) { reassignedNames.add(name); } } return; case 'CallExpression': { const defineCompiledEsmType = getDefineCompiledEsmType(node); if (defineCompiledEsmType) { if (programDepth === 3 && parent.type === 'ExpressionStatement') { // skip special handling for [module.]exports until we know we render this skippedNodes.add(node.arguments[0]); topLevelDefineCompiledEsmExpressions.push({ node, type: defineCompiledEsmType }); } else { shouldWrap = true; } return; } // Transform require.resolve if ( isDynamicRequireModulesEnabled && node.callee.object && isRequire(node.callee.object, scope) && node.callee.property.name === 'resolve' ) { checkDynamicRequire(node.start); uses.require = true; const requireNode = node.callee.object; replacedDynamicRequires.push(requireNode); skippedNodes.add(node.callee); return; } if (!isRequireExpression(node, scope)) { const keypath = getKeypath(node.callee); if (keypath && importedVariables.has(keypath.name)) { // Heuristic to deoptimize requires after a required function has been called currentConditionalNodeEnd = Infinity; } return; } skippedNodes.add(node.callee); uses.require = true; if (hasDynamicArguments(node)) { if (isDynamicRequireModulesEnabled) { checkDynamicRequire(node.start); } if (!ignoreDynamicRequires) { replacedDynamicRequires.push(node.callee); } return; } const requireStringArg = getRequireStringArg(node); if (!ignoreRequire(requireStringArg)) { const usesReturnValue = parent.type !== 'ExpressionStatement'; const toBeRemoved = parent.type === 'ExpressionStatement' && (!currentConditionalNodeEnd || // We should completely remove requires directly in a try-catch // so that Rollup can remove up the try-catch (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd)) ? parent : node; addRequireExpression( requireStringArg, node, scope, usesReturnValue, currentTryBlockEnd !== null, currentConditionalNodeEnd !== null, toBeRemoved ); if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') { for (const name of extractAssignedNames(parent.id)) { importedVariables.add(name); } } } return; } case 'ClassBody': classBodyDepth += 1; return; case 'ConditionalExpression': case 'IfStatement': // skip dead branches if (isFalsy(node.test)) { skippedNodes.add(node.consequent); } else if (isTruthy(node.test)) { if (node.alternate) { skippedNodes.add(node.alternate); } } else { conditionalNodes.add(node.consequent); if (node.alternate) { conditionalNodes.add(node.alternate); } } return; case 'ArrowFunctionExpression': case 'FunctionDeclaration': case 'FunctionExpression': // requires in functions should be conditional unless it is an IIFE if ( currentConditionalNodeEnd === null && !(parent.type === 'CallExpression' && parent.callee === node) ) { currentConditionalNodeEnd = node.end; } return; case 'Identifier': { const { name } = node; if ( !isReference(node, parent) || scope.contains(name) || (parent.type === 'PropertyDefinition' && parent.key === node) ) return; switch (name) { case 'require': uses.require = true; if (isNodeRequirePropertyAccess(parent)) { return; } if (!ignoreDynamicRequires) { if (isShorthandProperty(parent)) { // as key and value are the same object, isReference regards // both as references, so we need to skip now skippedNodes.add(parent.value); magicString.prependRight(node.start, 'require: '); } replacedDynamicRequires.push(node); } return; case 'module': case 'exports': shouldWrap = true; uses[name] = true; return; case 'global': uses.global = true; if (!ignoreGlobal) { replacedGlobal.push(node); } return; case 'define': magicString.overwrite(node.start, node.end, 'undefined', { storeName: true }); return; default: globals.add(name); return; } } case 'LogicalExpression': // skip dead branches if (node.operator === '&&') { if (isFalsy(node.left)) { skippedNodes.add(node.right); } else if (!isTruthy(node.left)) { conditionalNodes.add(node.right); } } else if (node.operator === '||') { if (isTruthy(node.left)) { skippedNodes.add(node.right); } else if (!isFalsy(node.left)) { conditionalNodes.add(node.right); } } return; case 'MemberExpression': if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) { uses.require = true; replacedDynamicRequires.push(node); skippedNodes.add(node.object); skippedNodes.add(node.property); } return; case 'ReturnStatement': // if top-level return, we need to wrap it if (lexicalDepth === 0) { shouldWrap = true; } return; case 'ThisExpression': // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal` if (lexicalDepth === 0 && !classBodyDepth) { uses.global = true; if (!ignoreGlobal) { replacedThis.push(node); } } return; case 'TryStatement': if (currentTryBlockEnd === null) { currentTryBlockEnd = node.block.end; } if (currentConditionalNodeEnd === null) { currentConditionalNodeEnd = node.end; } return; case 'UnaryExpression': // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151) if (node.operator === 'typeof') { const flattened = getKeypath(node.argument); if (!flattened) return; if (scope.contains(flattened.name)) return; if ( !isEsModule && (flattened.keypath === 'module.exports' || flattened.keypath === 'module' || flattened.keypath === 'exports') ) { magicString.overwrite(node.start, node.end, `'object'`, { storeName: false }); } } return; case 'VariableDeclaration': if (!scope.parent) { topLevelDeclarations.push(node); } return; case 'TemplateElement': if (node.value.raw.includes('\n')) { indentExclusionRanges.push([node.start, node.end]); } } }, leave(node) { programDepth -= 1; if (node.scope) scope = scope.parent; if (functionType.test(node.type)) lexicalDepth -= 1; if (node.type === 'ClassBody') classBodyDepth -= 1; } }); const nameBase = getName(id); const exportsName = deconflict([...exportsAccessScopes], globals, nameBase); const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`); const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`); const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`); const helpersName = deconflict([scope], globals, 'commonjsHelpers'); const dynamicRequireName = replacedDynamicRequires.length > 0 && deconflict( [scope], globals, isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT ); const deconflictedExportNames = Object.create(null); for (const [exportName, { scopes }] of exportsAssignmentsByName) { deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName); } for (const node of replacedGlobal) { magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, { storeName: true }); } for (const node of replacedThis) { magicString.overwrite(node.start, node.end, exportsName, { storeName: true }); } for (const node of replacedDynamicRequires) { magicString.overwrite( node.start, node.end, isDynamicRequireModulesEnabled ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})` : dynamicRequireName, { contentOnly: true, storeName: true } ); } // We cannot wrap ES/mixed modules shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0)); if ( !( shouldWrap || isRequired || needsRequireWrapper || uses.module || uses.exports || uses.require || topLevelDefineCompiledEsmExpressions.length > 0 ) && (ignoreGlobal || !uses.global) ) { return { meta: { commonjs: { isCommonJS: false } } }; } let leadingComment = ''; if (code.startsWith('/*')) { const commentEnd = code.indexOf('*/', 2) + 2; leadingComment = `${code.slice(0, commentEnd)}\n`; magicString.remove(0, commentEnd).trim(); } let shebang = ''; if (code.startsWith('#!')) { const shebangEndPosition = code.indexOf('\n') + 1; shebang = code.slice(0, shebangEndPosition); magicString.remove(0, shebangEndPosition).trim(); } const exportMode = isEsModule ? 'none' : shouldWrap ? uses.module ? 'module' : 'exports' : firstTopLevelModuleExportsAssignment ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0 ? 'replace' : 'module' : moduleExportsAssignments.length === 0 ? 'exports' : 'module'; const exportedExportsName = exportMode === 'module' ? deconflict([], globals, `${nameBase}Exports`) : exportsName; const importBlock = await rewriteRequireExpressionsAndGetImportBlock( magicString, topLevelDeclarations, reassignedNames, helpersName, dynamicRequireName, moduleName, exportsName, id, exportMode, resolveRequireSourcesAndUpdateMeta, needsRequireWrapper, isEsModule, isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, commonjsMeta ); const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS; const exportBlock = isEsModule ? '' : rewriteExportsAndGetExportsBlock( magicString, moduleName, exportsName, exportedExportsName, shouldWrap, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, topLevelDefineCompiledEsmExpressions, deconflictedExportNames, code, helpersName, exportMode, defaultIsModuleExports, usesRequireWrapper, requireName ); if (shouldWrap) { wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges); } if (usesRequireWrapper) { magicString.trim().indent('\t', { exclude: indentExclusionRanges }); const exported = exportMode === 'module' ? `${moduleName}.exports` : exportsName; magicString.prepend( `var ${isRequiredName}; function ${requireName} () { \tif (${isRequiredName}) return ${exported}; \t${isRequiredName} = 1; ` ).append(` \treturn ${exported}; }`); if (exportMode === 'replace') { magicString.prepend(`var ${exportsName};\n`); } } magicString .trim() .prepend(shebang + leadingComment + importBlock) .append(exportBlock); return { code: magicString.toString(), map: sourceMap ? magicString.generateMap() : null, syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports', meta: { commonjs: { ...commonjsMeta, shebang } } }; } const PLUGIN_NAME = 'commonjs'; function commonjs(options = {}) { const { ignoreGlobal, ignoreDynamicRequires, requireReturnsDefault: requireReturnsDefaultOption, defaultIsModuleExports: defaultIsModuleExportsOption, esmExternals } = options; const extensions = options.extensions || ['.js']; const filter = createFilter$1(options.include, options.exclude); const isPossibleCjsId = (id) => { const extName = extname(id); return extName === '.cjs' || (extensions.includes(extName) && filter(id)); }; const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options); const getRequireReturnsDefault = typeof requireReturnsDefaultOption === 'function' ? requireReturnsDefaultOption : () => requireReturnsDefaultOption; let esmExternalIds; const isEsmExternal = typeof esmExternals === 'function' ? esmExternals : Array.isArray(esmExternals) ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id)) : () => esmExternals; const getDefaultIsModuleExports = typeof defaultIsModuleExportsOption === 'function' ? defaultIsModuleExportsOption : () => typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto'; const dynamicRequireRoot = typeof options.dynamicRequireRoot === 'string' ? resolve$3(options.dynamicRequireRoot) : process.cwd(); const { commonDir, dynamicRequireModules } = getDynamicRequireModules( options.dynamicRequireTargets, dynamicRequireRoot ); const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0; const ignoreRequire = typeof options.ignore === 'function' ? options.ignore : Array.isArray(options.ignore) ? (id) => options.ignore.includes(id) : () => false; const getIgnoreTryCatchRequireStatementMode = (id) => { const mode = typeof options.ignoreTryCatch === 'function' ? options.ignoreTryCatch(id) : Array.isArray(options.ignoreTryCatch) ? options.ignoreTryCatch.includes(id) : typeof options.ignoreTryCatch !== 'undefined' ? options.ignoreTryCatch : true; return { canConvertRequire: mode !== 'remove' && mode !== true, shouldRemoveRequire: mode === 'remove' }; }; const { currentlyResolving, resolveId } = getResolveId(extensions, isPossibleCjsId); const sourceMap = options.sourceMap !== false; // Initialized in buildStart let requireResolver; function transformAndCheckExports(code, id) { const normalizedId = normalizePathSlashes(id); const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements( this.parse, code, id ); const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {}; if (hasDefaultExport) { commonjsMeta.hasDefaultExport = true; } if (hasNamedExports) { commonjsMeta.hasNamedExports = true; } if ( !dynamicRequireModules.has(normalizedId) && (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) || (isEsModule && !options.transformMixedEsModules)) ) { commonjsMeta.isCommonJS = false; return { meta: { commonjs: commonjsMeta } }; } const needsRequireWrapper = !isEsModule && (dynamicRequireModules.has(normalizedId) || strictRequiresFilter(id)); const checkDynamicRequire = (position) => { const normalizedDynamicRequireRoot = normalizePathSlashes(dynamicRequireRoot); if (normalizedId.indexOf(normalizedDynamicRequireRoot) !== 0) { this.error( { code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT', normalizedId, normalizedDynamicRequireRoot, message: `"${normalizedId}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${normalizedDynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname$1( normalizedId )}" or one of its parent directories.` }, position ); } }; return transformCommonjs( this.parse, code, id, isEsModule, ignoreGlobal || isEsModule, ignoreRequire, ignoreDynamicRequires && !isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ast, getDefaultIsModuleExports(id), needsRequireWrapper, requireResolver.resolveRequireSourcesAndUpdateMeta(this), requireResolver.isRequiredId(id), checkDynamicRequire, commonjsMeta ); } return { name: PLUGIN_NAME, version: version$2, options(rawOptions) { // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver // do not prevent our plugin from resolving entry points ot proxies. const plugins = Array.isArray(rawOptions.plugins) ? [...rawOptions.plugins] : rawOptions.plugins ? [rawOptions.plugins] : []; plugins.unshift({ name: 'commonjs--resolver', resolveId }); return { ...rawOptions, plugins }; }, buildStart({ plugins }) { validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup'); const nodeResolve = plugins.find(({ name }) => name === 'node-resolve'); if (nodeResolve) { validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve'); } if (options.namedExports != null) { this.warn( 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.' ); } requireResolver = getRequireResolver( extensions, detectCyclesAndConditional, currentlyResolving ); }, buildEnd() { if (options.strictRequires === 'debug') { const wrappedIds = requireResolver.getWrappedIds(); if (wrappedIds.length) { this.warn({ code: 'WRAPPED_IDS', ids: wrappedIds, message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds .map((id) => `\t${JSON.stringify(relative$1(process.cwd(), id))}`) .join(',\n')}\n]` }); } else { this.warn({ code: 'WRAPPED_IDS', ids: wrappedIds, message: 'The commonjs plugin did not wrap any files.' }); } } }, async load(id) { if (id === HELPERS_ID) { return getHelpersModule(); } if (isWrappedId(id, MODULE_SUFFIX)) { const name = getName(unwrapId(id, MODULE_SUFFIX)); return { code: `var ${name} = {exports: {}}; export {${name} as __module}`, meta: { commonjs: { isCommonJS: false } } }; } if (isWrappedId(id, EXPORTS_SUFFIX)) { const name = getName(unwrapId(id, EXPORTS_SUFFIX)); return { code: `var ${name} = {}; export {${name} as __exports}`, meta: { commonjs: { isCommonJS: false } } }; } if (isWrappedId(id, EXTERNAL_SUFFIX)) { const actualId = unwrapId(id, EXTERNAL_SUFFIX); return getUnknownRequireProxy( actualId, isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true ); } // entry suffix is just appended to not mess up relative external resolution if (id.endsWith(ENTRY_SUFFIX)) { const acutalId = id.slice(0, -ENTRY_SUFFIX.length); const { meta: { commonjs: commonjsMeta } } = this.getModuleInfo(acutalId); const shebang = commonjsMeta?.shebang ?? ''; return getEntryProxy( acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo, shebang ); } if (isWrappedId(id, ES_IMPORT_SUFFIX)) { const actualId = unwrapId(id, ES_IMPORT_SUFFIX); return getEsImportProxy( actualId, getDefaultIsModuleExports(actualId), (await this.load({ id: actualId })).moduleSideEffects ); } if (id === DYNAMIC_MODULES_ID) { return getDynamicModuleRegistry( isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires ); } if (isWrappedId(id, PROXY_SUFFIX)) { const actualId = unwrapId(id, PROXY_SUFFIX); return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load); } return null; }, shouldTransformCachedModule(...args) { return requireResolver.shouldTransformCachedModule.call(this, ...args); }, transform(code, id) { if (!isPossibleCjsId(id)) return null; try { return transformAndCheckExports.call(this, code, id); } catch (err) { return this.error(err, err.pos); } } }; } function perEnvironmentState(initial) { const stateMap = /* @__PURE__ */ new WeakMap(); return function(context) { const { environment } = context; let state = stateMap.get(environment); if (!state) { state = initial(environment); stateMap.set(environment, state); } return state; }; } // Matches the scheme of a URL, eg "http://" const schemeRegex = /^[\w+.-]+:\/\//; /** * Matches the parts of a URL: * 1. Scheme, including ":", guaranteed. * 2. User/password, including "@", optional. * 3. Host, guaranteed. * 4. Port, including ":", optional. * 5. Path, including "/", optional. * 6. Query, including "?", optional. * 7. Hash, including "#", optional. */ const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; /** * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). * * 1. Host, optional. * 2. Path, which may include "/", guaranteed. * 3. Query, including "?", optional. * 4. Hash, including "#", optional. */ const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; function isAbsoluteUrl(input) { return schemeRegex.test(input); } function isSchemeRelativeUrl(input) { return input.startsWith('//'); } function isAbsolutePath(input) { return input.startsWith('/'); } function isFileUrl(input) { return input.startsWith('file:'); } function isRelative(input) { return /^[.?#]/.test(input); } function parseAbsoluteUrl(input) { const match = urlRegex.exec(input); return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); } function parseFileUrl(input) { const match = fileRegex.exec(input); const path = match[2]; return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); } function makeUrl(scheme, user, host, port, path, query, hash) { return { scheme, user, host, port, path, query, hash, type: 7 /* Absolute */, }; } function parseUrl$3(input) { if (isSchemeRelativeUrl(input)) { const url = parseAbsoluteUrl('http:' + input); url.scheme = ''; url.type = 6 /* SchemeRelative */; return url; } if (isAbsolutePath(input)) { const url = parseAbsoluteUrl('http://foo.com' + input); url.scheme = ''; url.host = ''; url.type = 5 /* AbsolutePath */; return url; } if (isFileUrl(input)) return parseFileUrl(input); if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input); const url = parseAbsoluteUrl('http://foo.com/' + input); url.scheme = ''; url.host = ''; url.type = input ? input.startsWith('?') ? 3 /* Query */ : input.startsWith('#') ? 2 /* Hash */ : 4 /* RelativePath */ : 1 /* Empty */; return url; } function stripPathFilename(path) { // If a path ends with a parent directory "..", then it's a relative path with excess parent // paths. It's not a file, so we can't strip it. if (path.endsWith('/..')) return path; const index = path.lastIndexOf('/'); return path.slice(0, index + 1); } function mergePaths(url, base) { normalizePath$4(base, base.type); // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative // path). if (url.path === '/') { url.path = base.path; } else { // Resolution happens relative to the base path's directory, not the file. url.path = stripPathFilename(base.path) + url.path; } } /** * The path can have empty directories "//", unneeded parents "foo/..", or current directory * "foo/.". We need to normalize to a standard representation. */ function normalizePath$4(url, type) { const rel = type <= 4 /* RelativePath */; const pieces = url.path.split('/'); // We need to preserve the first piece always, so that we output a leading slash. The item at // pieces[0] is an empty string. let pointer = 1; // Positive is the number of real directories we've output, used for popping a parent directory. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". let positive = 0; // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a // real directory, we won't need to append, unless the other conditions happen again. let addTrailingSlash = false; for (let i = 1; i < pieces.length; i++) { const piece = pieces[i]; // An empty directory, could be a trailing slash, or just a double "//" in the path. if (!piece) { addTrailingSlash = true; continue; } // If we encounter a real directory, then we don't need to append anymore. addTrailingSlash = false; // A current directory, which we can always drop. if (piece === '.') continue; // A parent directory, we need to see if there are any real directories we can pop. Else, we // have an excess of parents, and we'll need to keep the "..". if (piece === '..') { if (positive) { addTrailingSlash = true; positive--; pointer--; } else if (rel) { // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute // URL, protocol relative URL, or an absolute path, we don't need to keep excess. pieces[pointer++] = piece; } continue; } // We've encountered a real directory. Move it to the next insertion pointer, which accounts for // any popped or dropped directories. pieces[pointer++] = piece; positive++; } let path = ''; for (let i = 1; i < pointer; i++) { path += '/' + pieces[i]; } if (!path || (addTrailingSlash && !path.endsWith('/..'))) { path += '/'; } url.path = path; } /** * Attempts to resolve `input` URL/path relative to `base`. */ function resolve$2(input, base) { if (!input && !base) return ''; const url = parseUrl$3(input); let inputType = url.type; if (base && inputType !== 7 /* Absolute */) { const baseUrl = parseUrl$3(base); const baseType = baseUrl.type; switch (inputType) { case 1 /* Empty */: url.hash = baseUrl.hash; // fall through case 2 /* Hash */: url.query = baseUrl.query; // fall through case 3 /* Query */: case 4 /* RelativePath */: mergePaths(url, baseUrl); // fall through case 5 /* AbsolutePath */: // The host, user, and port are joined, you can't copy one without the others. url.user = baseUrl.user; url.host = baseUrl.host; url.port = baseUrl.port; // fall through case 6 /* SchemeRelative */: // The input doesn't have a schema at least, so we need to copy at least that over. url.scheme = baseUrl.scheme; } if (baseType > inputType) inputType = baseType; } normalizePath$4(url, inputType); const queryHash = url.query + url.hash; switch (inputType) { // This is impossible, because of the empty checks at the start of the function. // case UrlType.Empty: case 2 /* Hash */: case 3 /* Query */: return queryHash; case 4 /* RelativePath */: { // The first char is always a "/", and we need it to be relative. const path = url.path.slice(1); if (!path) return queryHash || '.'; if (isRelative(base || input) && !isRelative(path)) { // If base started with a leading ".", or there is no base and input started with a ".", // then we need to ensure that the relative path starts with a ".". We don't know if // relative starts with a "..", though, so check before prepending. return './' + path + queryHash; } return path + queryHash; } case 5 /* AbsolutePath */: return url.path + queryHash; default: return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; } } function resolve$1(input, base) { // The base is always treated as a directory, if it's not empty. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 if (base && !base.endsWith('/')) base += '/'; return resolve$2(input, base); } /** * Removes everything after the last "/", but leaves the slash. */ function stripFilename(path) { if (!path) return ''; const index = path.lastIndexOf('/'); return path.slice(0, index + 1); } const COLUMN$1 = 0; const SOURCES_INDEX$1 = 1; const SOURCE_LINE$1 = 2; const SOURCE_COLUMN$1 = 3; const NAMES_INDEX$1 = 4; function maybeSort(mappings, owned) { const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); if (unsortedIndex === mappings.length) return mappings; // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If // not, we do not want to modify the consumer's input array. if (!owned) mappings = mappings.slice(); for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { mappings[i] = sortSegments(mappings[i], owned); } return mappings; } function nextUnsortedSegmentLine(mappings, start) { for (let i = start; i < mappings.length; i++) { if (!isSorted(mappings[i])) return i; } return mappings.length; } function isSorted(line) { for (let j = 1; j < line.length; j++) { if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) { return false; } } return true; } function sortSegments(line, owned) { if (!owned) line = line.slice(); return line.sort(sortComparator); } function sortComparator(a, b) { return a[COLUMN$1] - b[COLUMN$1]; } let found = false; /** * A binary search implementation that returns the index if a match is found. * If no match is found, then the left-index (the index associated with the item that comes just * before the desired index) is returned. To maintain proper sort order, a splice would happen at * the next index: * * ```js * const array = [1, 3]; * const needle = 2; * const index = binarySearch(array, needle, (item, needle) => item - needle); * * assert.equal(index, 0); * array.splice(index + 1, 0, needle); * assert.deepEqual(array, [1, 2, 3]); * ``` */ function binarySearch(haystack, needle, low, high) { while (low <= high) { const mid = low + ((high - low) >> 1); const cmp = haystack[mid][COLUMN$1] - needle; if (cmp === 0) { found = true; return mid; } if (cmp < 0) { low = mid + 1; } else { high = mid - 1; } } found = false; return low - 1; } function upperBound(haystack, needle, index) { for (let i = index + 1; i < haystack.length; index = i++) { if (haystack[i][COLUMN$1] !== needle) break; } return index; } function lowerBound(haystack, needle, index) { for (let i = index - 1; i >= 0; index = i--) { if (haystack[i][COLUMN$1] !== needle) break; } return index; } function memoizedState() { return { lastKey: -1, lastNeedle: -1, lastIndex: -1, }; } /** * This overly complicated beast is just to record the last tested line/column and the resulting * index, allowing us to skip a few tests if mappings are monotonically increasing. */ function memoizedBinarySearch(haystack, needle, state, key) { const { lastKey, lastNeedle, lastIndex } = state; let low = 0; let high = haystack.length - 1; if (key === lastKey) { if (needle === lastNeedle) { found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle; return lastIndex; } if (needle >= lastNeedle) { // lastIndex may be -1 if the previous needle was not found. low = lastIndex === -1 ? 0 : lastIndex; } else { high = lastIndex; } } state.lastKey = key; state.lastNeedle = needle; return (state.lastIndex = binarySearch(haystack, needle, low, high)); } const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; const LEAST_UPPER_BOUND = -1; const GREATEST_LOWER_BOUND = 1; class TraceMap { constructor(map, mapUrl) { const isString = typeof map === 'string'; if (!isString && map._decodedMemo) return map; const parsed = (isString ? JSON.parse(map) : map); const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; this.version = version; this.file = file; this.names = names || []; this.sourceRoot = sourceRoot; this.sources = sources; this.sourcesContent = sourcesContent; this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || undefined; const from = resolve$1(sourceRoot || '', stripFilename(mapUrl)); this.resolvedSources = sources.map((s) => resolve$1(s || '', from)); const { mappings } = parsed; if (typeof mappings === 'string') { this._encoded = mappings; this._decoded = undefined; } else { this._encoded = undefined; this._decoded = maybeSort(mappings, isString); } this._decodedMemo = memoizedState(); this._bySources = undefined; this._bySourceMemos = undefined; } } /** * Typescript doesn't allow friend access to private fields, so this just casts the map into a type * with public access modifiers. */ function cast$2(map) { return map; } /** * Returns the encoded (VLQ string) form of the SourceMap's mappings field. */ function encodedMappings(map) { var _a; var _b; return ((_a = (_b = cast$2(map))._encoded) !== null && _a !== void 0 ? _a : (_b._encoded = encode$1(cast$2(map)._decoded))); } /** * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. */ function decodedMappings(map) { var _a; return ((_a = cast$2(map))._decoded || (_a._decoded = decode(cast$2(map)._encoded))); } /** * A low-level API to find the segment associated with a generated line/column (think, from a * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. */ function traceSegment(map, line, column) { const decoded = decodedMappings(map); // It's common for parent source maps to have pointers to lines that have no // mapping (like a "//# sourceMappingURL=") at the end of the child file. if (line >= decoded.length) return null; const segments = decoded[line]; const index = traceSegmentInternal(segments, cast$2(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND); return index === -1 ? null : segments[index]; } /** * A higher-level API to find the source/line/column associated with a generated line/column * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in * `source-map` library. */ function originalPositionFor$1(map, needle) { let { line, column, bias } = needle; line--; if (line < 0) throw new Error(LINE_GTR_ZERO); if (column < 0) throw new Error(COL_GTR_EQ_ZERO); const decoded = decodedMappings(map); // It's common for parent source maps to have pointers to lines that have no // mapping (like a "//# sourceMappingURL=") at the end of the child file. if (line >= decoded.length) return OMapping(null, null, null, null); const segments = decoded[line]; const index = traceSegmentInternal(segments, cast$2(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); if (index === -1) return OMapping(null, null, null, null); const segment = segments[index]; if (segment.length === 1) return OMapping(null, null, null, null); const { names, resolvedSources } = map; return OMapping(resolvedSources[segment[SOURCES_INDEX$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null); } /** * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects * a sourcemap, or to JSON.stringify. */ function decodedMap(map) { return clone(map, decodedMappings(map)); } /** * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects * a sourcemap, or to JSON.stringify. */ function encodedMap(map) { return clone(map, encodedMappings(map)); } function clone(map, mappings) { return { version: map.version, file: map.file, names: map.names, sourceRoot: map.sourceRoot, sources: map.sources, sourcesContent: map.sourcesContent, mappings, ignoreList: map.ignoreList || map.x_google_ignoreList, }; } function OMapping(source, line, column, name) { return { source, line, column, name }; } function traceSegmentInternal(segments, memo, line, column, bias) { let index = memoizedBinarySearch(segments, column, memo, line); if (found) { index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); } else if (bias === LEAST_UPPER_BOUND) index++; if (index === -1 || index === segments.length) return -1; return index; } /** * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the * index of the `key` in the backing array. * * This is designed to allow synchronizing a second array with the contents of the backing array, * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, * and there are never duplicates. */ class SetArray { constructor() { this._indexes = { __proto__: null }; this.array = []; } } /** * Typescript doesn't allow friend access to private fields, so this just casts the set into a type * with public access modifiers. */ function cast$1(set) { return set; } /** * Gets the index associated with `key` in the backing array, if it is already present. */ function get(setarr, key) { return cast$1(setarr)._indexes[key]; } /** * Puts `key` into the backing array, if it is not already present. Returns * the index of the `key` in the backing array. */ function put(setarr, key) { // The key may or may not be present. If it is present, it's a number. const index = get(setarr, key); if (index !== undefined) return index; const { array, _indexes: indexes } = cast$1(setarr); const length = array.push(key); return (indexes[key] = length - 1); } /** * Removes the key, if it exists in the set. */ function remove(setarr, key) { const index = get(setarr, key); if (index === undefined) return; const { array, _indexes: indexes } = cast$1(setarr); for (let i = index + 1; i < array.length; i++) { const k = array[i]; array[i - 1] = k; indexes[k]--; } indexes[key] = undefined; array.pop(); } const COLUMN = 0; const SOURCES_INDEX = 1; const SOURCE_LINE = 2; const SOURCE_COLUMN = 3; const NAMES_INDEX = 4; const NO_NAME = -1; /** * Provides the state to generate a sourcemap. */ class GenMapping { constructor({ file, sourceRoot } = {}) { this._names = new SetArray(); this._sources = new SetArray(); this._sourcesContent = []; this._mappings = []; this.file = file; this.sourceRoot = sourceRoot; this._ignoreList = new SetArray(); } } /** * Typescript doesn't allow friend access to private fields, so this just casts the map into a type * with public access modifiers. */ function cast(map) { return map; } /** * Same as `addSegment`, but will only add the segment if it generates useful information in the * resulting map. This only works correctly if segments are added **in order**, meaning you should * not add a segment with a lower generated line/column than one that came before. */ const maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name); }; /** * Adds/removes the content of the source file to the source map. */ function setSourceContent(map, source, content) { const { _sources: sources, _sourcesContent: sourcesContent } = cast(map); const index = put(sources, source); sourcesContent[index] = content; } function setIgnore(map, source, ignore = true) { const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast(map); const index = put(sources, source); if (index === sourcesContent.length) sourcesContent[index] = null; if (ignore) put(ignoreList, index); else remove(ignoreList, index); } /** * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects * a sourcemap, or to JSON.stringify. */ function toDecodedMap(map) { const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList, } = cast(map); removeEmptyFinalLines(mappings); return { version: 3, file: map.file || undefined, names: names.array, sourceRoot: map.sourceRoot || undefined, sources: sources.array, sourcesContent, mappings, ignoreList: ignoreList.array, }; } /** * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects * a sourcemap, or to JSON.stringify. */ function toEncodedMap(map) { const decoded = toDecodedMap(map); return Object.assign(Object.assign({}, decoded), { mappings: encode$1(decoded.mappings) }); } // This split declaration is only so that terser can elminiate the static initialization block. function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = cast(map); const line = getLine(mappings, genLine); const index = getColumnIndex(line, genColumn); if (!source) { if (skipSourceless(line, index)) return; return insert(line, index, [genColumn]); } const sourcesIndex = put(sources, source); const namesIndex = name ? put(names, name) : NO_NAME; if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = null; if (skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { return; } return insert(line, index, name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn]); } function getLine(mappings, index) { for (let i = mappings.length; i <= index; i++) { mappings[i] = []; } return mappings[index]; } function getColumnIndex(line, genColumn) { let index = line.length; for (let i = index - 1; i >= 0; index = i--) { const current = line[i]; if (genColumn >= current[COLUMN]) break; } return index; } function insert(array, index, value) { for (let i = array.length; i > index; i--) { array[i] = array[i - 1]; } array[index] = value; } function removeEmptyFinalLines(mappings) { const { length } = mappings; let len = length; for (let i = len - 1; i >= 0; len = i, i--) { if (mappings[i].length > 0) break; } if (len < length) mappings.length = len; } function skipSourceless(line, index) { // The start of a line is already sourceless, so adding a sourceless segment to the beginning // doesn't generate any useful information. if (index === 0) return true; const prev = line[index - 1]; // If the previous segment is also sourceless, then adding another sourceless segment doesn't // genrate any new information. Else, this segment will end the source/named segment and point to // a sourceless position, which is useful. return prev.length === 1; } function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { // A source/named segment at the start of a line gives position at that genColumn if (index === 0) return false; const prev = line[index - 1]; // If the previous segment is sourceless, then we're transitioning to a source. if (prev.length === 1) return false; // If the previous segment maps to the exact same source position, then this segment doesn't // provide any new position information. return (sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)); } const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false); const EMPTY_SOURCES = []; function SegmentObject(source, line, column, name, content, ignore) { return { source, line, column, name, content, ignore }; } function Source(map, sources, source, content, ignore) { return { map, sources, source, content, ignore, }; } /** * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes * (which may themselves be SourceMapTrees). */ function MapSource(map, sources) { return Source(map, sources, '', null, false); } /** * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive * segment tracing ends at the `OriginalSource`. */ function OriginalSource(source, content, ignore) { return Source(null, EMPTY_SOURCES, source, content, ignore); } /** * traceMappings is only called on the root level SourceMapTree, and begins the process of * resolving each mapping in terms of the original source files. */ function traceMappings(tree) { // TODO: Eventually support sourceRoot, which has to be removed because the sources are already // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. const gen = new GenMapping({ file: tree.map.file }); const { sources: rootSources, map } = tree; const rootNames = map.names; const rootMappings = decodedMappings(map); for (let i = 0; i < rootMappings.length; i++) { const segments = rootMappings[i]; for (let j = 0; j < segments.length; j++) { const segment = segments[j]; const genCol = segment[0]; let traced = SOURCELESS_MAPPING; // 1-length segments only move the current generated column, there's no source information // to gather from it. if (segment.length !== 1) { const source = rootSources[segment[1]]; traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a // respective segment into an original source. if (traced == null) continue; } const { column, line, name, content, source, ignore } = traced; maybeAddSegment(gen, i, genCol, source, line, column, name); if (source && content != null) setSourceContent(gen, source, content); if (ignore) setIgnore(gen, source, true); } } return gen; } /** * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own * child SourceMapTrees, until we find the original source map. */ function originalPositionFor(source, line, column, name) { if (!source.map) { return SegmentObject(source.source, line, column, name, source.content, source.ignore); } const segment = traceSegment(source.map, line, column); // If we couldn't find a segment, then this doesn't exist in the sourcemap. if (segment == null) return null; // 1-length segments only move the current generated column, there's no source information // to gather from it. if (segment.length === 1) return SOURCELESS_MAPPING; return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); } function asArray(value) { if (Array.isArray(value)) return value; return [value]; } /** * Recursively builds a tree structure out of sourcemap files, with each node * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of * `OriginalSource`s and `SourceMapTree`s. * * Every sourcemap is composed of a collection of source files and mappings * into locations of those source files. When we generate a `SourceMapTree` for * the sourcemap, we attempt to load each source file's own sourcemap. If it * does not have an associated sourcemap, it is considered an original, * unmodified source file. */ function buildSourceMapTree(input, loader) { const maps = asArray(input).map((m) => new TraceMap(m, '')); const map = maps.pop(); for (let i = 0; i < maps.length; i++) { if (maps[i].sources.length > 1) { throw new Error(`Transformation map ${i} must have exactly one source file.\n` + 'Did you specify these with the most recent transformation maps first?'); } } let tree = build$2(map, loader, '', 0); for (let i = maps.length - 1; i >= 0; i--) { tree = MapSource(maps[i], [tree]); } return tree; } function build$2(map, loader, importer, importerDepth) { const { resolvedSources, sourcesContent, ignoreList } = map; const depth = importerDepth + 1; const children = resolvedSources.map((sourceFile, i) => { // The loading context gives the loader more information about why this file is being loaded // (eg, from which importer). It also allows the loader to override the location of the loaded // sourcemap/original source, or to override the content in the sourcesContent field if it's // an unmodified source file. const ctx = { importer, depth, source: sourceFile || '', content: undefined, ignore: undefined, }; // Use the provided loader callback to retrieve the file's sourcemap. // TODO: We should eventually support async loading of sourcemap files. const sourceMap = loader(ctx.source, ctx); const { source, content, ignore } = ctx; // If there is a sourcemap, then we need to recurse into it to load its source files. if (sourceMap) return build$2(new TraceMap(sourceMap, source), loader, source, depth); // Else, it's an unmodified source file. // The contents of this unmodified source file can be overridden via the loader context, // allowing it to be explicitly null or a string. If it remains undefined, we fall back to // the importing sourcemap's `sourcesContent` field. const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false; return OriginalSource(source, sourceContent, ignored); }); return MapSource(map, children); } /** * A SourceMap v3 compatible sourcemap, which only includes fields that were * provided to it. */ class SourceMap { constructor(map, options) { const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map); this.version = out.version; // SourceMap spec says this should be first. this.file = out.file; this.mappings = out.mappings; this.names = out.names; this.ignoreList = out.ignoreList; this.sourceRoot = out.sourceRoot; this.sources = out.sources; if (!options.excludeContent) { this.sourcesContent = out.sourcesContent; } } toString() { return JSON.stringify(this); } } /** * Traces through all the mappings in the root sourcemap, through the sources * (and their sourcemaps), all the way back to the original source location. * * `loader` will be called every time we encounter a source file. If it returns * a sourcemap, we will recurse into that sourcemap to continue the trace. If * it returns a falsey value, that source file is treated as an original, * unmodified source file. * * Pass `excludeContent` to exclude any self-containing source file content * from the output sourcemap. * * Pass `decodedMappings` to receive a SourceMap with decoded (instead of * VLQ encoded) mappings. */ function remapping(input, loader, options) { const opts = { excludeContent: !!options, decodedMappings: false }; const tree = buildSourceMapTree(input, loader); return new SourceMap(traceMappings(tree), opts); } var src$3 = {exports: {}}; var browser$2 = {exports: {}}; /** * Helpers. */ var ms$1; var hasRequiredMs$1; function requireMs$1 () { if (hasRequiredMs$1) return ms$1; hasRequiredMs$1 = 1; var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ ms$1 = function (val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } 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( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } return ms$1; } var common$4; var hasRequiredCommon; function requireCommon () { if (hasRequiredCommon) return common$4; hasRequiredCommon = 1; /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = requireMs$1(); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace * * @param {RegExp} regxep * @return {String} namespace * @api private */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } common$4 = setup; return common$4; } /* eslint-env browser */ var hasRequiredBrowser$1; function requireBrowser$1 () { if (hasRequiredBrowser$1) return browser$2.exports; hasRequiredBrowser$1 = 1; (function (module, exports) { /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } let m; // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = requireCommon()(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; } (browser$2, browser$2.exports)); return browser$2.exports; } var node$1 = {exports: {}}; /** * Module dependencies. */ var hasRequiredNode$1; function requireNode$1 () { if (hasRequiredNode$1) return node$1.exports; hasRequiredNode$1 = 1; (function (module, exports) { const tty = require$$0$4; const util = require$$1; /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = require('supports-color'); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = requireCommon()(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; } (node$1, node$1.exports)); return node$1.exports; } /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { src$3.exports = requireBrowser$1(); } else { src$3.exports = requireNode$1(); } var srcExports$1 = src$3.exports; var debug$i = /*@__PURE__*/getDefaultExportFromCjs(srcExports$1); let pnp; if (process.versions.pnp) { try { pnp = createRequire$1(import.meta.url)("pnpapi"); } catch { } } function invalidatePackageData(packageCache, pkgPath) { const pkgDir = normalizePath$3(path$d.dirname(pkgPath)); packageCache.forEach((pkg, cacheKey) => { if (pkg.dir === pkgDir) { packageCache.delete(cacheKey); } }); } function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) { if (pnp) { const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks); if (packageCache?.has(cacheKey)) return packageCache.get(cacheKey); try { const pkg = pnp.resolveToUnqualified(pkgName, basedir, { considerBuiltins: false }); if (!pkg) return null; const pkgData = loadPackageData(path$d.join(pkg, "package.json")); packageCache?.set(cacheKey, pkgData); return pkgData; } catch { return null; } } const originalBasedir = basedir; while (basedir) { if (packageCache) { const cached = getRpdCache( packageCache, pkgName, basedir, originalBasedir, preserveSymlinks ); if (cached) return cached; } const pkg = path$d.join(basedir, "node_modules", pkgName, "package.json"); try { if (fs__default.existsSync(pkg)) { const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg); const pkgData = loadPackageData(pkgPath); if (packageCache) { setRpdCache( packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks ); } return pkgData; } } catch { } const nextBasedir = path$d.dirname(basedir); if (nextBasedir === basedir) break; basedir = nextBasedir; } return null; } function findNearestPackageData(basedir, packageCache) { const originalBasedir = basedir; while (basedir) { if (packageCache) { const cached = getFnpdCache(packageCache, basedir, originalBasedir); if (cached) return cached; } const pkgPath = path$d.join(basedir, "package.json"); if (tryStatSync(pkgPath)?.isFile()) { try { const pkgData = loadPackageData(pkgPath); if (packageCache) { setFnpdCache(packageCache, pkgData, basedir, originalBasedir); } return pkgData; } catch { } } const nextBasedir = path$d.dirname(basedir); if (nextBasedir === basedir) break; basedir = nextBasedir; } return null; } function findNearestMainPackageData(basedir, packageCache) { const nearestPackage = findNearestPackageData(basedir, packageCache); return nearestPackage && (nearestPackage.data.name ? nearestPackage : findNearestMainPackageData( path$d.dirname(nearestPackage.dir), packageCache )); } function loadPackageData(pkgPath) { const data = JSON.parse(fs__default.readFileSync(pkgPath, "utf-8")); const pkgDir = normalizePath$3(path$d.dirname(pkgPath)); const { sideEffects } = data; let hasSideEffects; if (typeof sideEffects === "boolean") { hasSideEffects = () => sideEffects; } else if (Array.isArray(sideEffects)) { if (sideEffects.length <= 0) { hasSideEffects = () => false; } else { const finalPackageSideEffects = sideEffects.map((sideEffect) => { if (sideEffect.includes("/")) { return sideEffect; } return `**/${sideEffect}`; }); hasSideEffects = createFilter(finalPackageSideEffects, null, { resolve: pkgDir }); } } else { hasSideEffects = () => null; } const resolvedCache = {}; const pkg = { dir: pkgDir, data, hasSideEffects, setResolvedCache(key, entry, options) { resolvedCache[getResolveCacheKey(key, options)] = entry; }, getResolvedCache(key, options) { return resolvedCache[getResolveCacheKey(key, options)]; } }; return pkg; } function getResolveCacheKey(key, options) { return [ key, options.isRequire ? "1" : "0", options.conditions.join("_"), options.extensions.join("_"), options.mainFields.join("_") ].join("|"); } function findNearestNodeModules(basedir) { while (basedir) { const pkgPath = path$d.join(basedir, "node_modules"); if (tryStatSync(pkgPath)?.isDirectory()) { return pkgPath; } const nextBasedir = path$d.dirname(basedir); if (nextBasedir === basedir) break; basedir = nextBasedir; } return null; } function watchPackageDataPlugin(packageCache) { const watchQueue = /* @__PURE__ */ new Set(); const watchedDirs = /* @__PURE__ */ new Set(); const watchFileStub = (id) => { watchQueue.add(id); }; let watchFile = watchFileStub; const setPackageData = packageCache.set.bind(packageCache); packageCache.set = (id, pkg) => { if (!isInNodeModules$1(pkg.dir) && !watchedDirs.has(pkg.dir)) { watchedDirs.add(pkg.dir); watchFile(path$d.join(pkg.dir, "package.json")); } return setPackageData(id, pkg); }; return { name: "vite:watch-package-data", buildStart() { watchFile = this.addWatchFile.bind(this); watchQueue.forEach(watchFile); watchQueue.clear(); }, buildEnd() { watchFile = watchFileStub; }, watchChange(id) { if (id.endsWith("/package.json")) { invalidatePackageData(packageCache, path$d.normalize(id)); } } }; } function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) { const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks); const pkgData = packageCache.get(cacheKey); if (pkgData) { traverseBetweenDirs(originalBasedir, basedir, (dir) => { packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData); }); return pkgData; } } function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) { packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData); traverseBetweenDirs(originalBasedir, basedir, (dir) => { packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData); }); } function getRpdCacheKey(pkgName, basedir, preserveSymlinks) { return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`; } function getFnpdCache(packageCache, basedir, originalBasedir) { const cacheKey = getFnpdCacheKey(basedir); const pkgData = packageCache.get(cacheKey); if (pkgData) { traverseBetweenDirs(originalBasedir, basedir, (dir) => { packageCache.set(getFnpdCacheKey(dir), pkgData); }); return pkgData; } } function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) { packageCache.set(getFnpdCacheKey(basedir), pkgData); traverseBetweenDirs(originalBasedir, basedir, (dir) => { packageCache.set(getFnpdCacheKey(dir), pkgData); }); } function getFnpdCacheKey(basedir) { return `fnpd_${basedir}`; } function traverseBetweenDirs(longerDir, shorterDir, cb) { while (longerDir !== shorterDir) { cb(longerDir); longerDir = path$d.dirname(longerDir); } } const createFilter = createFilter$1; const replaceSlashOrColonRE = /[/:]/g; const replaceDotRE = /\./g; const replaceNestedIdRE = /\s*>\s*/g; const replaceHashRE = /#/g; const flattenId = (id) => { const flatId = limitFlattenIdLength( id.replace(replaceSlashOrColonRE, "_").replace(replaceDotRE, "__").replace(replaceNestedIdRE, "___").replace(replaceHashRE, "____") ); return flatId; }; const FLATTEN_ID_HASH_LENGTH = 8; const FLATTEN_ID_MAX_FILE_LENGTH = 170; const limitFlattenIdLength = (id, limit = FLATTEN_ID_MAX_FILE_LENGTH) => { if (id.length <= limit) { return id; } return id.slice(0, limit - (FLATTEN_ID_HASH_LENGTH + 1)) + "_" + getHash(id); }; const normalizeId = (id) => id.replace(replaceNestedIdRE, " > "); const NODE_BUILTIN_NAMESPACE = "node:"; const NPM_BUILTIN_NAMESPACE = "npm:"; const BUN_BUILTIN_NAMESPACE = "bun:"; const nodeBuiltins = builtinModules.filter((id) => !id.includes(":")); function isBuiltin(id) { if (process.versions.deno && id.startsWith(NPM_BUILTIN_NAMESPACE)) return true; if (process.versions.bun && id.startsWith(BUN_BUILTIN_NAMESPACE)) return true; return isNodeBuiltin(id); } function isNodeBuiltin(id) { if (id.startsWith(NODE_BUILTIN_NAMESPACE)) return true; return nodeBuiltins.includes(id); } function isInNodeModules$1(id) { return id.includes("node_modules"); } function moduleListContains(moduleList, id) { return moduleList?.some( (m) => m === id || id.startsWith(withTrailingSlash(m)) ); } function isOptimizable(id, optimizeDeps) { const { extensions } = optimizeDeps; return OPTIMIZABLE_ENTRY_RE.test(id) || (extensions?.some((ext) => id.endsWith(ext)) ?? false); } const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/; const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//; const _require$1 = createRequire$1(import.meta.url); const _dirname = path$d.dirname(fileURLToPath$1(import.meta.url)); const rollupVersion = resolvePackageData("rollup", _dirname, true)?.data.version ?? ""; const filter = process.env.VITE_DEBUG_FILTER; const DEBUG = process.env.DEBUG; function createDebugger(namespace, options = {}) { const log = debug$i(namespace); const { onlyWhenFocused, depth } = options; if (depth && log.inspectOpts && log.inspectOpts.depth == null) { log.inspectOpts.depth = options.depth; } let enabled = log.enabled; if (enabled && onlyWhenFocused) { const ns = typeof onlyWhenFocused === "string" ? onlyWhenFocused : namespace; enabled = !!DEBUG?.includes(ns); } if (enabled) { return (...args) => { if (!filter || args.some((a) => a?.includes?.(filter))) { log(...args); } }; } } function testCaseInsensitiveFS() { if (!CLIENT_ENTRY.endsWith("client.mjs")) { throw new Error( `cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs` ); } if (!fs__default.existsSync(CLIENT_ENTRY)) { throw new Error( "cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: " + CLIENT_ENTRY ); } return fs__default.existsSync(CLIENT_ENTRY.replace("client.mjs", "cLiEnT.mjs")); } const urlCanParse = ( // eslint-disable-next-line n/no-unsupported-features/node-builtins URL$3.canParse ?? // URL.canParse is supported from Node.js 18.17.0+, 20.0.0+ ((path2, base) => { try { new URL$3(path2, base); return true; } catch { return false; } }) ); const isCaseInsensitiveFS = testCaseInsensitiveFS(); const VOLUME_RE = /^[A-Z]:/i; function normalizePath$3(id) { return path$d.posix.normalize(isWindows$3 ? slash$1(id) : id); } function fsPathFromId(id) { const fsPath = normalizePath$3( id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id ); return fsPath[0] === "/" || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`; } function fsPathFromUrl(url) { return fsPathFromId(cleanUrl(url)); } function isParentDirectory(dir, file) { dir = withTrailingSlash(dir); return file.startsWith(dir) || isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase()); } function isSameFileUri(file1, file2) { return file1 === file2 || isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase(); } const externalRE = /^([a-z]+:)?\/\//; const isExternalUrl = (url) => externalRE.test(url); const dataUrlRE = /^\s*data:/i; const isDataUrl = (url) => dataUrlRE.test(url); const virtualModuleRE = /^virtual-module:.*/; const virtualModulePrefix = "virtual-module:"; const knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba|mdx)(?:$|\?)/; const isJSRequest = (url) => { url = cleanUrl(url); if (knownJsSrcRE.test(url)) { return true; } if (!path$d.extname(url) && url[url.length - 1] !== "/") { return true; } return false; }; const knownTsRE = /\.(?:ts|mts|cts|tsx)(?:$|\?)/; const isTsRequest = (url) => knownTsRE.test(url); const importQueryRE = /(\?|&)import=?(?:&|$)/; const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/; const internalPrefixes = [ FS_PREFIX, VALID_ID_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH ]; const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join("|")})`); const trailingSeparatorRE = /[?&]$/; const isImportRequest = (url) => importQueryRE.test(url); const isInternalRequest = (url) => InternalPrefixRE.test(url); function removeImportQuery(url) { return url.replace(importQueryRE, "$1").replace(trailingSeparatorRE, ""); } function removeDirectQuery(url) { return url.replace(directRequestRE$1, "$1").replace(trailingSeparatorRE, ""); } const urlRE = /(\?|&)url(?:&|$)/; const rawRE = /(\?|&)raw(?:&|$)/; function removeUrlQuery(url) { return url.replace(urlRE, "$1").replace(trailingSeparatorRE, ""); } function injectQuery(url, queryToInject) { const { file, postfix } = splitFileAndPostfix(url); const normalizedFile = isWindows$3 ? slash$1(file) : file; return `${normalizedFile}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : ( /* hash only */ postfix )}`; } const timestampRE = /\bt=\d{13}&?\b/; function removeTimestampQuery(url) { return url.replace(timestampRE, "").replace(trailingSeparatorRE, ""); } async function asyncReplace(input, re, replacer) { let match; let remaining = input; let rewritten = ""; while (match = re.exec(remaining)) { rewritten += remaining.slice(0, match.index); rewritten += await replacer(match); remaining = remaining.slice(match.index + match[0].length); } rewritten += remaining; return rewritten; } function timeFrom(start, subtract = 0) { const time = performance.now() - start - subtract; const timeString = (time.toFixed(2) + `ms`).padEnd(5, " "); if (time < 10) { return colors$1.green(timeString); } else if (time < 50) { return colors$1.yellow(timeString); } else { return colors$1.red(timeString); } } function prettifyUrl(url, root) { url = removeTimestampQuery(url); const isAbsoluteFile = url.startsWith(root); if (isAbsoluteFile || url.startsWith(FS_PREFIX)) { const file = path$d.posix.relative( root, isAbsoluteFile ? url : fsPathFromId(url) ); return colors$1.dim(file); } else { return colors$1.dim(url); } } function isObject$2(value) { return Object.prototype.toString.call(value) === "[object Object]"; } function isDefined(value) { return value != null; } function tryStatSync(file) { try { return fs__default.statSync(file, { throwIfNoEntry: false }); } catch { } } function lookupFile(dir, fileNames) { while (dir) { for (const fileName of fileNames) { const fullPath = path$d.join(dir, fileName); if (tryStatSync(fullPath)?.isFile()) return fullPath; } const parentDir = path$d.dirname(dir); if (parentDir === dir) return; dir = parentDir; } } function isFilePathESM(filePath, packageCache) { if (/\.m[jt]s$/.test(filePath)) { return true; } else if (/\.c[jt]s$/.test(filePath)) { return false; } else { try { const pkg = findNearestPackageData(path$d.dirname(filePath), packageCache); return pkg?.data.type === "module"; } catch { return false; } } } const splitRE = /\r?\n/g; const range = 2; function pad$1(source, n = 2) { const lines = source.split(splitRE); return lines.map((l) => ` `.repeat(n) + l).join(` `); } function posToNumber(source, pos) { if (typeof pos === "number") return pos; const lines = source.split(splitRE); const { line, column } = pos; let start = 0; for (let i = 0; i < line - 1 && i < lines.length; i++) { start += lines[i].length + 1; } return start + column; } function numberToPos(source, offset) { if (typeof offset !== "number") return offset; if (offset > source.length) { throw new Error( `offset is longer than source length! offset ${offset} > length ${source.length}` ); } const lines = source.split(splitRE); let counted = 0; let line = 0; let column = 0; for (; line < lines.length; line++) { const lineLength = lines[line].length + 1; if (counted + lineLength >= offset) { column = offset - counted + 1; break; } counted += lineLength; } return { line: line + 1, column }; } function generateCodeFrame(source, start = 0, end) { start = Math.max(posToNumber(source, start), 0); end = Math.min( end !== void 0 ? posToNumber(source, end) : start, source.length ); const lines = source.split(splitRE); let count = 0; const res = []; for (let i = 0; i < lines.length; i++) { count += lines[i].length; if (count >= start) { for (let j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) continue; const line = j + 1; res.push( `${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}` ); const lineLength = lines[j].length; if (j === i) { const pad2 = Math.max(start - (count - lineLength), 0); const length = Math.max( 1, end > count ? lineLength - pad2 : end - start ); res.push(` | ` + " ".repeat(pad2) + "^".repeat(length)); } else if (j > i) { if (end > count) { const length = Math.max(Math.min(end - count, lineLength), 1); res.push(` | ` + "^".repeat(length)); } count += lineLength + 1; } } break; } count++; } return res.join("\n"); } function isFileReadable(filename) { if (!tryStatSync(filename)) { return false; } try { fs__default.accessSync(filename, fs__default.constants.R_OK); return true; } catch { return false; } } const splitFirstDirRE = /(.+?)[\\/](.+)/; function emptyDir(dir, skip) { const skipInDir = []; let nested = null; if (skip?.length) { for (const file of skip) { if (path$d.dirname(file) !== ".") { const matched = splitFirstDirRE.exec(file); if (matched) { nested ??= /* @__PURE__ */ new Map(); const [, nestedDir, skipPath] = matched; let nestedSkip = nested.get(nestedDir); if (!nestedSkip) { nestedSkip = []; nested.set(nestedDir, nestedSkip); } if (!nestedSkip.includes(skipPath)) { nestedSkip.push(skipPath); } } } else { skipInDir.push(file); } } } for (const file of fs__default.readdirSync(dir)) { if (skipInDir.includes(file)) { continue; } if (nested?.has(file)) { emptyDir(path$d.resolve(dir, file), nested.get(file)); } else { fs__default.rmSync(path$d.resolve(dir, file), { recursive: true, force: true }); } } } function copyDir(srcDir, destDir) { fs__default.mkdirSync(destDir, { recursive: true }); for (const file of fs__default.readdirSync(srcDir)) { const srcFile = path$d.resolve(srcDir, file); if (srcFile === destDir) { continue; } const destFile = path$d.resolve(destDir, file); const stat = fs__default.statSync(srcFile); if (stat.isDirectory()) { copyDir(srcFile, destFile); } else { fs__default.copyFileSync(srcFile, destFile); } } } const ERR_SYMLINK_IN_RECURSIVE_READDIR = "ERR_SYMLINK_IN_RECURSIVE_READDIR"; async function recursiveReaddir(dir) { if (!fs__default.existsSync(dir)) { return []; } let dirents; try { dirents = await fsp.readdir(dir, { withFileTypes: true }); } catch (e) { if (e.code === "EACCES") { return []; } throw e; } if (dirents.some((dirent) => dirent.isSymbolicLink())) { const err = new Error( "Symbolic links are not supported in recursiveReaddir" ); err.code = ERR_SYMLINK_IN_RECURSIVE_READDIR; throw err; } const files = await Promise.all( dirents.map((dirent) => { const res = path$d.resolve(dir, dirent.name); return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath$3(res); }) ); return files.flat(1); } let safeRealpathSync = isWindows$3 ? windowsSafeRealPathSync : fs__default.realpathSync.native; const windowsNetworkMap = /* @__PURE__ */ new Map(); function windowsMappedRealpathSync(path2) { const realPath = fs__default.realpathSync.native(path2); if (realPath.startsWith("\\\\")) { for (const [network, volume] of windowsNetworkMap) { if (realPath.startsWith(network)) return realPath.replace(network, volume); } } return realPath; } const parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/; let firstSafeRealPathSyncRun = false; function windowsSafeRealPathSync(path2) { if (!firstSafeRealPathSyncRun) { optimizeSafeRealPathSync(); firstSafeRealPathSyncRun = true; } return fs__default.realpathSync(path2); } function optimizeSafeRealPathSync() { const nodeVersion = process.versions.node.split(".").map(Number); if (nodeVersion[0] < 18 || nodeVersion[0] === 18 && nodeVersion[1] < 10) { safeRealpathSync = fs__default.realpathSync; return; } try { fs__default.realpathSync.native(path$d.resolve("./")); } catch (error) { if (error.message.includes("EISDIR: illegal operation on a directory")) { safeRealpathSync = fs__default.realpathSync; return; } } exec("net use", (error, stdout) => { if (error) return; const lines = stdout.split("\n"); for (const line of lines) { const m = parseNetUseRE.exec(line); if (m) windowsNetworkMap.set(m[2], m[1]); } if (windowsNetworkMap.size === 0) { safeRealpathSync = fs__default.realpathSync.native; } else { safeRealpathSync = windowsMappedRealpathSync; } }); } function ensureWatchedFile(watcher, file, root) { if (file && // only need to watch if out of root !file.startsWith(withTrailingSlash(root)) && // some rollup plugins use null bytes for private resolved Ids !file.includes("\0") && fs__default.existsSync(file)) { watcher.add(path$d.resolve(file)); } } function joinSrcset(ret) { return ret.map(({ url, descriptor }) => url + (descriptor ? ` ${descriptor}` : "")).join(", "); } const imageCandidateRegex = /(?:^|\s)(?[\w-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?\w[^,]+))?(?:,|$)/g; const escapedSpaceCharacters = /(?: |\\t|\\n|\\f|\\r)+/g; function parseSrcset(string) { const matches = string.trim().replace(escapedSpaceCharacters, " ").replace(/\r?\n/, "").replace(/,\s+/, ", ").replaceAll(/\s+/g, " ").matchAll(imageCandidateRegex); return Array.from(matches, ({ groups }) => ({ url: groups?.url?.trim() ?? "", descriptor: groups?.descriptor?.trim() ?? "" })).filter(({ url }) => !!url); } function processSrcSet(srcs, replacer) { return Promise.all( parseSrcset(srcs).map(async ({ url, descriptor }) => ({ url: await replacer({ url, descriptor }), descriptor })) ).then(joinSrcset); } function processSrcSetSync(srcs, replacer) { return joinSrcset( parseSrcset(srcs).map(({ url, descriptor }) => ({ url: replacer({ url, descriptor }), descriptor })) ); } const windowsDriveRE = /^[A-Z]:/; const replaceWindowsDriveRE = /^([A-Z]):\//; const linuxAbsolutePathRE = /^\/[^/]/; function escapeToLinuxLikePath(path2) { if (windowsDriveRE.test(path2)) { return path2.replace(replaceWindowsDriveRE, "/windows/$1/"); } if (linuxAbsolutePathRE.test(path2)) { return `/linux${path2}`; } return path2; } const revertWindowsDriveRE = /^\/windows\/([A-Z])\//; function unescapeToLinuxLikePath(path2) { if (path2.startsWith("/linux/")) { return path2.slice("/linux".length); } if (path2.startsWith("/windows/")) { return path2.replace(revertWindowsDriveRE, "$1:/"); } return path2; } const nullSourceMap = { names: [], sources: [], mappings: "", version: 3 }; function combineSourcemaps(filename, sourcemapList) { if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) { return { ...nullSourceMap }; } sourcemapList = sourcemapList.map((sourcemap) => { const newSourcemaps = { ...sourcemap }; newSourcemaps.sources = sourcemap.sources.map( (source) => source ? escapeToLinuxLikePath(source) : null ); if (sourcemap.sourceRoot) { newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot); } return newSourcemaps; }); let map; let mapIndex = 1; const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0; if (useArrayInterface) { map = remapping(sourcemapList, () => null); } else { map = remapping(sourcemapList[0], function loader(sourcefile) { const mapForSources = sourcemapList.slice(mapIndex).find((s) => s.sources.includes(sourcefile)); if (mapForSources) { mapIndex++; return mapForSources; } return null; }); } if (!map.file) { delete map.file; } map.sources = map.sources.map( (source) => source ? unescapeToLinuxLikePath(source) : source ); map.file = filename; return map; } function unique(arr) { return Array.from(new Set(arr)); } async function getLocalhostAddressIfDiffersFromDNS() { const [nodeResult, dnsResult] = await Promise.all([ promises.lookup("localhost"), promises.lookup("localhost", { verbatim: true }) ]); const isSame = nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address; return isSame ? void 0 : nodeResult.address; } function diffDnsOrderChange(oldUrls, newUrls) { return !(oldUrls === newUrls || oldUrls && newUrls && arrayEqual(oldUrls.local, newUrls.local) && arrayEqual(oldUrls.network, newUrls.network)); } async function resolveHostname(optionsHost) { let host; if (optionsHost === void 0 || optionsHost === false) { host = "localhost"; } else if (optionsHost === true) { host = void 0; } else { host = optionsHost; } let name = host === void 0 || wildcardHosts.has(host) ? "localhost" : host; if (host === "localhost") { const localhostAddr = await getLocalhostAddressIfDiffersFromDNS(); if (localhostAddr) { name = localhostAddr; } } return { host, name }; } async function resolveServerUrls(server, options, config) { const address = server.address(); const isAddressInfo = (x) => x?.address; if (!isAddressInfo(address)) { return { local: [], network: [] }; } const local = []; const network = []; const hostname = await resolveHostname(options.host); const protocol = options.https ? "https" : "http"; const port = address.port; const base = config.rawBase === "./" || config.rawBase === "" ? "/" : config.rawBase; if (hostname.host !== void 0 && !wildcardHosts.has(hostname.host)) { let hostnameName = hostname.name; if (hostnameName.includes(":")) { hostnameName = `[${hostnameName}]`; } const address2 = `${protocol}://${hostnameName}:${port}${base}`; if (loopbackHosts.has(hostname.host)) { local.push(address2); } else { network.push(address2); } } else { Object.values(os$3.networkInterfaces()).flatMap((nInterface) => nInterface ?? []).filter( (detail) => detail && detail.address && (detail.family === "IPv4" || // @ts-expect-error Node 18.0 - 18.3 returns number detail.family === 4) ).forEach((detail) => { let host = detail.address.replace("127.0.0.1", hostname.name); if (host.includes(":")) { host = `[${host}]`; } const url = `${protocol}://${host}:${port}${base}`; if (detail.address.includes("127.0.0.1")) { local.push(url); } else { network.push(url); } }); } return { local, network }; } function arraify(target) { return Array.isArray(target) ? target : [target]; } const multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g; const singlelineCommentsRE = /\/\/.*/g; const requestQuerySplitRE = /\?(?!.*[/|}])/; const requestQueryMaybeEscapedSplitRE = /\\?\?(?!.*[/|}])/; const blankReplacer = (match) => " ".repeat(match.length); const hash$1 = ( // eslint-disable-next-line n/no-unsupported-features/node-builtins -- crypto.hash is supported in Node 21.7.0+, 20.12.0+ crypto$2.hash ?? ((algorithm, data, outputEncoding) => crypto$2.createHash(algorithm).update(data).digest(outputEncoding)) ); function getHash(text, length = 8) { const h = hash$1("sha256", text, "hex").substring(0, length); if (length <= 64) return h; return h.padEnd(length, "_"); } const requireResolveFromRootWithFallback = (root, id) => { const found = resolvePackageData(id, root) || resolvePackageData(id, _dirname); if (!found) { const error = new Error(`${JSON.stringify(id)} not found.`); error.code = "MODULE_NOT_FOUND"; throw error; } return _require$1.resolve(id, { paths: [root, _dirname] }); }; function emptyCssComments(raw) { return raw.replace(multilineCommentsRE, blankReplacer); } function backwardCompatibleWorkerPlugins(plugins) { if (Array.isArray(plugins)) { return plugins; } if (typeof plugins === "function") { return plugins(); } return []; } function deepClone(value) { if (Array.isArray(value)) { return value.map((v) => deepClone(v)); } if (isObject$2(value)) { const cloned = {}; for (const key in value) { cloned[key] = deepClone(value[key]); } return cloned; } if (typeof value === "function") { return value; } if (value instanceof RegExp) { return structuredClone(value); } if (typeof value === "object" && value != null) { throw new Error("Cannot deep clone non-plain object"); } return value; } function mergeWithDefaultsRecursively(defaults, values) { const merged = defaults; for (const key in values) { const value = values[key]; if (value === void 0) continue; const existing = merged[key]; if (existing === void 0) { merged[key] = value; continue; } if (isObject$2(existing) && isObject$2(value)) { merged[key] = mergeWithDefaultsRecursively(existing, value); continue; } merged[key] = value; } return merged; } function mergeWithDefaults(defaults, values) { const clonedDefaults = deepClone(defaults); return mergeWithDefaultsRecursively(clonedDefaults, values); } function mergeConfigRecursively(defaults, overrides, rootPath) { const merged = { ...defaults }; for (const key in overrides) { const value = overrides[key]; if (value == null) { continue; } const existing = merged[key]; if (existing == null) { merged[key] = value; continue; } if (key === "alias" && (rootPath === "resolve" || rootPath === "")) { merged[key] = mergeAlias(existing, value); continue; } else if (key === "assetsInclude" && rootPath === "") { merged[key] = [].concat(existing, value); continue; } else if (key === "noExternal" && (rootPath === "ssr" || rootPath === "resolve") && (existing === true || value === true)) { merged[key] = true; continue; } else if (key === "plugins" && rootPath === "worker") { merged[key] = () => [ ...backwardCompatibleWorkerPlugins(existing), ...backwardCompatibleWorkerPlugins(value) ]; continue; } else if (key === "server" && rootPath === "server.hmr") { merged[key] = value; continue; } if (Array.isArray(existing) || Array.isArray(value)) { merged[key] = [...arraify(existing), ...arraify(value)]; continue; } if (isObject$2(existing) && isObject$2(value)) { merged[key] = mergeConfigRecursively( existing, value, rootPath ? `${rootPath}.${key}` : key ); continue; } merged[key] = value; } return merged; } function mergeConfig(defaults, overrides, isRoot = true) { if (typeof defaults === "function" || typeof overrides === "function") { throw new Error(`Cannot merge config in form of callback`); } return mergeConfigRecursively(defaults, overrides, isRoot ? "" : "."); } function mergeAlias(a, b) { if (!a) return b; if (!b) return a; if (isObject$2(a) && isObject$2(b)) { return { ...a, ...b }; } return [...normalizeAlias(b), ...normalizeAlias(a)]; } function normalizeAlias(o = []) { return Array.isArray(o) ? o.map(normalizeSingleAlias) : Object.keys(o).map( (find) => normalizeSingleAlias({ find, replacement: o[find] }) ); } function normalizeSingleAlias({ find, replacement, customResolver }) { if (typeof find === "string" && find[find.length - 1] === "/" && replacement[replacement.length - 1] === "/") { find = find.slice(0, find.length - 1); replacement = replacement.slice(0, replacement.length - 1); } const alias = { find, replacement }; if (customResolver) { alias.customResolver = customResolver; } return alias; } function transformStableResult(s, id, config) { return { code: s.toString(), map: config.command === "build" && config.build.sourcemap ? s.generateMap({ hires: "boundary", source: id }) : null }; } async function asyncFlatten(arr) { do { arr = (await Promise.all(arr)).flat(Infinity); } while (arr.some((v) => v?.then)); return arr; } function stripBomTag(content) { if (content.charCodeAt(0) === 65279) { return content.slice(1); } return content; } const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/; const isNonDriveRelativeAbsolutePath = (p) => { if (!isWindows$3) return p[0] === "/"; return windowsDrivePathPrefixRE.test(p); }; function shouldServeFile(filePath, root) { if (!isCaseInsensitiveFS) return true; return hasCorrectCase(filePath, root); } function hasCorrectCase(file, assets) { if (file === assets) return true; const parent = path$d.dirname(file); if (fs__default.readdirSync(parent).includes(path$d.basename(file))) { return hasCorrectCase(parent, assets); } return false; } function joinUrlSegments(a, b) { if (!a || !b) { return a || b || ""; } if (a[a.length - 1] === "/") { a = a.substring(0, a.length - 1); } if (b[0] !== "/") { b = "/" + b; } return a + b; } function removeLeadingSlash(str) { return str[0] === "/" ? str.slice(1) : str; } function stripBase(path2, base) { if (path2 === base) { return "/"; } const devBase = withTrailingSlash(base); return path2.startsWith(devBase) ? path2.slice(devBase.length - 1) : path2; } function arrayEqual(a, b) { if (a === b) return true; if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false; } return true; } function evalValue(rawValue) { const fn = new Function(` var console, exports, global, module, process, require return ( ${rawValue} ) `); return fn(); } function getNpmPackageName(importPath) { const parts = importPath.split("/"); if (parts[0][0] === "@") { if (!parts[1]) return null; return `${parts[0]}/${parts[1]}`; } else { return parts[0]; } } function getPkgName(name) { return name?.[0] === "@" ? name.split("/")[1] : name; } const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g; function escapeRegex(str) { return str.replace(escapeRegexRE, "\\$&"); } function getPackageManagerCommand(type = "install") { const packageManager = process.env.npm_config_user_agent?.split(" ")[0].split("/")[0] || "npm"; switch (type) { case "install": return packageManager === "npm" ? "npm install" : `${packageManager} add`; case "uninstall": return packageManager === "npm" ? "npm uninstall" : `${packageManager} remove`; case "update": return packageManager === "yarn" ? "yarn upgrade" : `${packageManager} update`; default: throw new TypeError(`Unknown command type: ${type}`); } } function isDevServer(server) { return "pluginContainer" in server; } function createSerialPromiseQueue() { let previousTask; return { async run(f) { const thisTask = f(); const depTasks = Promise.all([previousTask, thisTask]); previousTask = depTasks; const [, result] = await depTasks; if (previousTask === depTasks) { previousTask = void 0; } return result; } }; } function sortObjectKeys(obj) { const sorted = {}; for (const key of Object.keys(obj).sort()) { sorted[key] = obj[key]; } return sorted; } function displayTime(time) { if (time < 1e3) { return `${time}ms`; } time = time / 1e3; if (time < 60) { return `${time.toFixed(2)}s`; } const mins = parseInt((time / 60).toString()); const seconds = time % 60; return `${mins}m${seconds < 1 ? "" : ` ${seconds.toFixed(0)}s`}`; } function encodeURIPath(uri) { if (uri.startsWith("data:")) return uri; const filePath = cleanUrl(uri); const postfix = filePath !== uri ? uri.slice(filePath.length) : ""; return encodeURI(filePath) + postfix; } function partialEncodeURIPath(uri) { if (uri.startsWith("data:")) return uri; const filePath = cleanUrl(uri); const postfix = filePath !== uri ? uri.slice(filePath.length) : ""; return filePath.replaceAll("%", "%25") + postfix; } const setupSIGTERMListener = (callback) => { process.once("SIGTERM", callback); if (process.env.CI !== "true") { process.stdin.on("end", callback); } }; const teardownSIGTERMListener = (callback) => { process.off("SIGTERM", callback); if (process.env.CI !== "true") { process.stdin.off("end", callback); } }; const LogLevels = { silent: 0, error: 1, warn: 2, info: 3 }; let lastType; let lastMsg; let sameCount = 0; function clearScreen() { const repeatCount = process.stdout.rows - 2; const blank = repeatCount > 0 ? "\n".repeat(repeatCount) : ""; console.log(blank); readline.cursorTo(process.stdout, 0, 0); readline.clearScreenDown(process.stdout); } let timeFormatter; function getTimeFormatter() { timeFormatter ??= new Intl.DateTimeFormat(void 0, { hour: "numeric", minute: "numeric", second: "numeric" }); return timeFormatter; } function createLogger(level = "info", options = {}) { if (options.customLogger) { return options.customLogger; } const loggedErrors = /* @__PURE__ */ new WeakSet(); const { prefix = "[vite]", allowClearScreen = true, console: console2 = globalThis.console } = options; const thresh = LogLevels[level]; const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI; const clear = canClearScreen ? clearScreen : () => { }; function format(type, msg, options2 = {}) { if (options2.timestamp) { let tag = ""; if (type === "info") { tag = colors$1.cyan(colors$1.bold(prefix)); } else if (type === "warn") { tag = colors$1.yellow(colors$1.bold(prefix)); } else { tag = colors$1.red(colors$1.bold(prefix)); } const environment = options2.environment ? options2.environment + " " : ""; return `${colors$1.dim(getTimeFormatter().format(/* @__PURE__ */ new Date()))} ${tag} ${environment}${msg}`; } else { return msg; } } function output(type, msg, options2 = {}) { if (thresh >= LogLevels[type]) { const method = type === "info" ? "log" : type; if (options2.error) { loggedErrors.add(options2.error); } if (canClearScreen) { if (type === lastType && msg === lastMsg) { sameCount++; clear(); console2[method]( format(type, msg, options2), colors$1.yellow(`(x${sameCount + 1})`) ); } else { sameCount = 0; lastMsg = msg; lastType = type; if (options2.clear) { clear(); } console2[method](format(type, msg, options2)); } } else { console2[method](format(type, msg, options2)); } } } const warnedMessages = /* @__PURE__ */ new Set(); const logger = { hasWarned: false, info(msg, opts) { output("info", msg, opts); }, warn(msg, opts) { logger.hasWarned = true; output("warn", msg, opts); }, warnOnce(msg, opts) { if (warnedMessages.has(msg)) return; logger.hasWarned = true; output("warn", msg, opts); warnedMessages.add(msg); }, error(msg, opts) { logger.hasWarned = true; output("error", msg, opts); }, clearScreen(type) { if (thresh >= LogLevels[type]) { clear(); } }, hasErrorLogged(error) { return loggedErrors.has(error); } }; return logger; } function printServerUrls(urls, optionsHost, info) { const colorUrl = (url) => colors$1.cyan(url.replace(/:(\d+)\//, (_, port) => `:${colors$1.bold(port)}/`)); for (const url of urls.local) { info(` ${colors$1.green("\u279C")} ${colors$1.bold("Local")}: ${colorUrl(url)}`); } for (const url of urls.network) { info(` ${colors$1.green("\u279C")} ${colors$1.bold("Network")}: ${colorUrl(url)}`); } if (urls.network.length === 0 && optionsHost === void 0) { info( colors$1.dim(` ${colors$1.green("\u279C")} ${colors$1.bold("Network")}: use `) + colors$1.bold("--host") + colors$1.dim(" to expose") ); } } const groups = [ { name: "Assets", color: colors$1.green }, { name: "CSS", color: colors$1.magenta }, { name: "JS", color: colors$1.cyan } ]; const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml)$/; function buildReporterPlugin(config) { const compress = promisify$4(gzip); const numberFormatter = new Intl.NumberFormat("en", { maximumFractionDigits: 2, minimumFractionDigits: 2 }); const displaySize = (bytes) => { return `${numberFormatter.format(bytes / 1e3)} kB`; }; const tty = process.stdout.isTTY && !process.env.CI; const shouldLogInfo = LogLevels[config.logLevel || "info"] >= LogLevels.info; const modulesReporter = perEnvironmentState((environment) => { let hasTransformed = false; let transformedCount = 0; const logTransform = throttle((id) => { writeLine( `transforming (${transformedCount}) ${colors$1.dim( path$d.relative(config.root, id) )}` ); }); return { reset() { transformedCount = 0; }, register(id) { transformedCount++; if (shouldLogInfo) { if (!tty) { if (!hasTransformed) { config.logger.info(`transforming...`); } } else { if (id.includes(`?`)) return; logTransform(id); } hasTransformed = true; } }, log() { if (shouldLogInfo) { if (tty) { clearLine$1(); } environment.logger.info( `${colors$1.green(`\u2713`)} ${transformedCount} modules transformed.` ); } } }; }); const chunksReporter = perEnvironmentState((environment) => { let hasRenderedChunk = false; let hasCompressChunk = false; let chunkCount = 0; let compressedCount = 0; async function getCompressedSize(code) { if (environment.config.consumer !== "client" || !environment.config.build.reportCompressedSize) { return null; } if (shouldLogInfo && !hasCompressChunk) { if (!tty) { config.logger.info("computing gzip size..."); } else { writeLine("computing gzip size (0)..."); } hasCompressChunk = true; } const compressed = await compress( typeof code === "string" ? code : Buffer.from(code) ); compressedCount++; if (shouldLogInfo && tty) { writeLine(`computing gzip size (${compressedCount})...`); } return compressed.length; } return { reset() { chunkCount = 0; compressedCount = 0; }, register() { chunkCount++; if (shouldLogInfo) { if (!tty) { if (!hasRenderedChunk) { environment.logger.info("rendering chunks..."); } } else { writeLine(`rendering chunks (${chunkCount})...`); } hasRenderedChunk = true; } }, async log(output, outDir) { const chunkLimit = environment.config.build.chunkSizeWarningLimit; let hasLargeChunks = false; if (shouldLogInfo) { const entries = (await Promise.all( Object.values(output).map( async (chunk) => { if (chunk.type === "chunk") { return { name: chunk.fileName, group: "JS", size: chunk.code.length, compressedSize: await getCompressedSize(chunk.code), mapSize: chunk.map ? chunk.map.toString().length : null }; } else { if (chunk.fileName.endsWith(".map")) return null; const isCSS = chunk.fileName.endsWith(".css"); const isCompressible = isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName); return { name: chunk.fileName, group: isCSS ? "CSS" : "Assets", size: chunk.source.length, mapSize: null, // Rollup doesn't support CSS maps? compressedSize: isCompressible ? await getCompressedSize(chunk.source) : null }; } } ) )).filter(isDefined); if (tty) clearLine$1(); let longest = 0; let biggestSize = 0; let biggestMap = 0; let biggestCompressSize = 0; for (const entry of entries) { if (entry.name.length > longest) longest = entry.name.length; if (entry.size > biggestSize) biggestSize = entry.size; if (entry.mapSize && entry.mapSize > biggestMap) { biggestMap = entry.mapSize; } if (entry.compressedSize && entry.compressedSize > biggestCompressSize) { biggestCompressSize = entry.compressedSize; } } const sizePad = displaySize(biggestSize).length; const mapPad = displaySize(biggestMap).length; const compressPad = displaySize(biggestCompressSize).length; const relativeOutDir = normalizePath$3( path$d.relative( config.root, path$d.resolve( config.root, outDir ?? environment.config.build.outDir ) ) ); const assetsDir = path$d.join(environment.config.build.assetsDir, "/"); for (const group of groups) { const filtered = entries.filter((e) => e.group === group.name); if (!filtered.length) continue; for (const entry of filtered.sort((a, z) => a.size - z.size)) { const isLarge = group.name === "JS" && entry.size / 1e3 > chunkLimit; if (isLarge) hasLargeChunks = true; const sizeColor = isLarge ? colors$1.yellow : colors$1.dim; let log = colors$1.dim(withTrailingSlash(relativeOutDir)); log += !config.build.lib && entry.name.startsWith(withTrailingSlash(assetsDir)) ? colors$1.dim(assetsDir) + group.color( entry.name.slice(assetsDir.length).padEnd(longest + 2 - assetsDir.length) ) : group.color(entry.name.padEnd(longest + 2)); log += colors$1.bold( sizeColor(displaySize(entry.size).padStart(sizePad)) ); if (entry.compressedSize) { log += colors$1.dim( ` \u2502 gzip: ${displaySize(entry.compressedSize).padStart( compressPad )}` ); } if (entry.mapSize) { log += colors$1.dim( ` \u2502 map: ${displaySize(entry.mapSize).padStart(mapPad)}` ); } config.logger.info(log); } } } else { hasLargeChunks = Object.values(output).some((chunk) => { return chunk.type === "chunk" && chunk.code.length / 1e3 > chunkLimit; }); } if (hasLargeChunks && environment.config.build.minify && !config.build.lib && environment.config.consumer === "client") { environment.logger.warn( colors$1.yellow( ` (!) Some chunks are larger than ${chunkLimit} kB after minification. Consider: - Using dynamic import() to code-split the application - Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks - Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.` ) ); } } }; }); return { name: "vite:reporter", sharedDuringBuild: true, perEnvironmentStartEndDuringDev: true, transform(_, id) { modulesReporter(this).register(id); }, buildStart() { modulesReporter(this).reset(); }, buildEnd() { modulesReporter(this).log(); }, renderStart() { chunksReporter(this).reset(); }, renderChunk(_, chunk, options) { if (!options.inlineDynamicImports) { for (const id of chunk.moduleIds) { const module = this.getModuleInfo(id); if (!module) continue; if (module.importers.length && module.dynamicImporters.length) { const detectedIneffectiveDynamicImport = module.dynamicImporters.some( (id2) => !isInNodeModules$1(id2) && chunk.moduleIds.includes(id2) ); if (detectedIneffectiveDynamicImport) { this.warn( ` (!) ${module.id} is dynamically imported by ${module.dynamicImporters.join( ", " )} but also statically imported by ${module.importers.join( ", " )}, dynamic import will not move module into another chunk. ` ); } } } } chunksReporter(this).register(); }, generateBundle() { if (shouldLogInfo && tty) clearLine$1(); }, async writeBundle({ dir }, output) { await chunksReporter(this).log(output, dir); } }; } function writeLine(output) { clearLine$1(); if (output.length < process.stdout.columns) { process.stdout.write(output); } else { process.stdout.write(output.substring(0, process.stdout.columns - 1)); } } function clearLine$1() { process.stdout.clearLine(0); process.stdout.cursorTo(0); } function throttle(fn) { let timerHandle = null; return (...args) => { if (timerHandle) return; fn(...args); timerHandle = setTimeout(() => { timerHandle = null; }, 100); }; } const POSIX_SEP_RE = new RegExp('\\' + path$d.posix.sep, 'g'); const NATIVE_SEP_RE = new RegExp('\\' + path$d.sep, 'g'); /** @type {Map}*/ const PATTERN_REGEX_CACHE = new Map(); const GLOB_ALL_PATTERN = `**/*`; const TS_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts']; const JS_EXTENSIONS = ['.js', '.jsx', '.mjs', '.cjs']; const TSJS_EXTENSIONS = TS_EXTENSIONS.concat(JS_EXTENSIONS); const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.substring(1)).join('|')})`; const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.substring(1)).join( '|' )})`; const IS_POSIX = path$d.posix.sep === path$d.sep; /** * @template T * @returns {{resolve:(result:T)=>void, reject:(error:any)=>void, promise: Promise}} */ function makePromise() { let resolve, reject; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); return { promise, resolve, reject }; } /** * @param {string} filename * @param {import('./cache.js').TSConfckCache} [cache] * @returns {Promise} */ async function resolveTSConfigJson(filename, cache) { if (path$d.extname(filename) !== '.json') { return; // ignore files that are not json } const tsconfig = path$d.resolve(filename); if (cache && (cache.hasParseResult(tsconfig) || cache.hasParseResult(filename))) { return tsconfig; } return promises$1.stat(tsconfig).then((stat) => { if (stat.isFile() || stat.isFIFO()) { return tsconfig; } else { throw new Error(`${filename} exists but is not a regular file.`); } }); } /** * * @param {string} dir an absolute directory path * @returns {boolean} if dir path includes a node_modules segment */ const isInNodeModules = IS_POSIX ? (dir) => dir.includes('/node_modules/') : (dir) => dir.match(/[/\\]node_modules[/\\]/); /** * convert posix separator to native separator * * eg. * windows: C:/foo/bar -> c:\foo\bar * linux: /foo/bar -> /foo/bar * * @param {string} filename with posix separators * @returns {string} filename with native separators */ const posix2native = IS_POSIX ? (filename) => filename : (filename) => filename.replace(POSIX_SEP_RE, path$d.sep); /** * convert native separator to posix separator * * eg. * windows: C:\foo\bar -> c:/foo/bar * linux: /foo/bar -> /foo/bar * * @param {string} filename - filename with native separators * @returns {string} filename with posix separators */ const native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, path$d.posix.sep); /** * converts params to native separator, resolves path and converts native back to posix * * needed on windows to handle posix paths in tsconfig * * @param dir {string|null} directory to resolve from * @param filename {string} filename or pattern to resolve * @returns string */ const resolve2posix = IS_POSIX ? (dir, filename) => (dir ? path$d.resolve(dir, filename) : path$d.resolve(filename)) : (dir, filename) => native2posix( dir ? path$d.resolve(posix2native(dir), posix2native(filename)) : path$d.resolve(posix2native(filename)) ); /** * * @param {import('./public.d.ts').TSConfckParseResult} result * @param {import('./public.d.ts').TSConfckParseOptions} [options] * @returns {string[]} */ function resolveReferencedTSConfigFiles(result, options) { const dir = path$d.dirname(result.tsconfigFile); return result.tsconfig.references.map((ref) => { const refPath = ref.path.endsWith('.json') ? ref.path : path$d.join(ref.path, options?.configName ?? 'tsconfig.json'); return resolve2posix(dir, refPath); }); } /** * @param {string} filename * @param {import('./public.d.ts').TSConfckParseResult} result * @returns {import('./public.d.ts').TSConfckParseResult} */ function resolveSolutionTSConfig(filename, result) { const allowJs = result.tsconfig.compilerOptions?.allowJs; const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS; if ( result.referenced && extensions.some((ext) => filename.endsWith(ext)) && !isIncluded(filename, result) ) { const solutionTSConfig = result.referenced.find((referenced) => isIncluded(filename, referenced) ); if (solutionTSConfig) { return solutionTSConfig; } } return result; } /** * * @param {string} filename * @param {import('./public.d.ts').TSConfckParseResult} result * @returns {boolean} */ function isIncluded(filename, result) { const dir = native2posix(path$d.dirname(result.tsconfigFile)); const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file)); const absoluteFilename = resolve2posix(null, filename); if (files.includes(filename)) { return true; } const allowJs = result.tsconfig.compilerOptions?.allowJs; const isIncluded = isGlobMatch( absoluteFilename, dir, result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN]), allowJs ); if (isIncluded) { const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || [], allowJs); return !isExcluded; } return false; } /** * test filenames agains glob patterns in tsconfig * * @param filename {string} posix style abolute path to filename to test * @param dir {string} posix style absolute path to directory of tsconfig containing patterns * @param patterns {string[]} glob patterns to match against * @param allowJs {boolean} allowJs setting in tsconfig to include js extensions in checks * @returns {boolean} true when at least one pattern matches filename */ function isGlobMatch(filename, dir, patterns, allowJs) { const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS; return patterns.some((pattern) => { // filename must end with part of pattern that comes after last wildcard let lastWildcardIndex = pattern.length; let hasWildcard = false; let hasExtension = false; let hasSlash = false; let lastSlashIndex = -1; for (let i = pattern.length - 1; i > -1; i--) { const c = pattern[i]; if (!hasWildcard) { if (c === '*' || c === '?') { lastWildcardIndex = i; hasWildcard = true; } } if (!hasSlash) { if (c === '.') { hasExtension = true; } else if (c === '/') { lastSlashIndex = i; hasSlash = true; } } if (hasWildcard && hasSlash) { break; } } if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) { // add implicit glob pattern += `${pattern.endsWith('/') ? '' : '/'}${GLOB_ALL_PATTERN}`; lastWildcardIndex = pattern.length - 1; hasWildcard = true; } // if pattern does not end with wildcard, filename must end with pattern after last wildcard if ( lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1)) ) { return false; } // if pattern ends with *, filename must end with a default extension if (pattern.endsWith('*') && !extensions.some((ext) => filename.endsWith(ext))) { return false; } // for **/* , filename must start with the dir if (pattern === GLOB_ALL_PATTERN) { return filename.startsWith(`${dir}/`); } const resolvedPattern = resolve2posix(dir, pattern); // filename must start with part of pattern that comes before first wildcard let firstWildcardIndex = -1; for (let i = 0; i < resolvedPattern.length; i++) { if (resolvedPattern[i] === '*' || resolvedPattern[i] === '?') { firstWildcardIndex = i; hasWildcard = true; break; } } if ( firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1)) ) { return false; } if (!hasWildcard) { // no wildcard in pattern, filename must be equal to resolved pattern return filename === resolvedPattern; } else if ( firstWildcardIndex + GLOB_ALL_PATTERN.length === resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) && resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) === GLOB_ALL_PATTERN ) { // singular glob-all pattern and we already validated prefix and suffix matches return true; } // complex pattern, use regex to check it if (PATTERN_REGEX_CACHE.has(resolvedPattern)) { return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename); } const regex = pattern2regex(resolvedPattern, allowJs); PATTERN_REGEX_CACHE.set(resolvedPattern, regex); return regex.test(filename); }); } /** * @param {string} resolvedPattern * @param {boolean} allowJs * @returns {RegExp} */ function pattern2regex(resolvedPattern, allowJs) { let regexStr = '^'; for (let i = 0; i < resolvedPattern.length; i++) { const char = resolvedPattern[i]; if (char === '?') { regexStr += '[^\\/]'; continue; } if (char === '*') { if (resolvedPattern[i + 1] === '*' && resolvedPattern[i + 2] === '/') { i += 2; regexStr += '(?:[^\\/]*\\/)*'; // zero or more path segments continue; } regexStr += '[^\\/]*'; continue; } if ('/.+^${}()|[]\\'.includes(char)) { regexStr += `\\`; } regexStr += char; } // add known file endings if pattern ends on * if (resolvedPattern.endsWith('*')) { regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP; } regexStr += '$'; return new RegExp(regexStr); } /** * replace tokens like ${configDir} * @param {any} tsconfig * @param {string} configDir * @returns {any} */ function replaceTokens(tsconfig, configDir) { return JSON.parse( JSON.stringify(tsconfig) // replace ${configDir} .replaceAll(/"\${configDir}/g, `"${native2posix(configDir)}`) ); } /** * find the closest tsconfig.json file * * @param {string} filename - path to file to find tsconfig for (absolute or relative to cwd) * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options * @returns {Promise} absolute path to closest tsconfig.json or null if not found */ async function find(filename, options) { let dir = path$d.dirname(path$d.resolve(filename)); if (options?.ignoreNodeModules && isInNodeModules(dir)) { return null; } const cache = options?.cache; const configName = options?.configName ?? 'tsconfig.json'; if (cache?.hasConfigPath(dir, configName)) { return cache.getConfigPath(dir, configName); } const { /** @type {Promise} */ promise, resolve, reject } = makePromise(); if (options?.root && !path$d.isAbsolute(options.root)) { options.root = path$d.resolve(options.root); } findUp(dir, { promise, resolve, reject }, options); return promise; } /** * * @param {string} dir * @param {{promise:Promise,resolve:(result:string|null)=>void,reject:(err:any)=>void}} madePromise * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options */ function findUp(dir, { resolve, reject, promise }, options) { const { cache, root, configName } = options ?? {}; if (cache) { if (cache.hasConfigPath(dir, configName)) { let cached; try { cached = cache.getConfigPath(dir, configName); } catch (e) { reject(e); return; } if (cached?.then) { cached.then(resolve).catch(reject); } else { resolve(cached); } } else { cache.setConfigPath(dir, promise, configName); } } const tsconfig = path$d.join(dir, options?.configName ?? 'tsconfig.json'); fs__default.stat(tsconfig, (err, stats) => { if (stats && (stats.isFile() || stats.isFIFO())) { resolve(tsconfig); } else if (err?.code !== 'ENOENT') { reject(err); } else { let parent; if (root === dir || (parent = path$d.dirname(dir)) === dir) { resolve(null); } else { findUp(parent, { promise, resolve, reject }, options); } } }); } /* this file contains code from strip-bom and strip-json-comments by Sindre Sorhus https://github.com/sindresorhus/strip-json-comments/blob/v4.0.0/index.js https://github.com/sindresorhus/strip-bom/blob/v5.0.0/index.js licensed under MIT, see ../LICENSE */ /** * convert content of tsconfig.json to regular json * * @param {string} tsconfigJson - content of tsconfig.json * @returns {string} content as regular json, comments and dangling commas have been replaced with whitespace */ function toJson(tsconfigJson) { const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson))); if (stripped.trim() === '') { // only whitespace left after stripping, return empty object so that JSON.parse still works return '{}'; } else { return stripped; } } /** * replace dangling commas from pseudo-json string with single space * implementation heavily inspired by strip-json-comments * * @param {string} pseudoJson * @returns {string} */ function stripDanglingComma(pseudoJson) { let insideString = false; let offset = 0; let result = ''; let danglingCommaPos = null; for (let i = 0; i < pseudoJson.length; i++) { const currentCharacter = pseudoJson[i]; if (currentCharacter === '"') { const escaped = isEscaped(pseudoJson, i); if (!escaped) { insideString = !insideString; } } if (insideString) { danglingCommaPos = null; continue; } if (currentCharacter === ',') { danglingCommaPos = i; continue; } if (danglingCommaPos) { if (currentCharacter === '}' || currentCharacter === ']') { result += pseudoJson.slice(offset, danglingCommaPos) + ' '; offset = danglingCommaPos + 1; danglingCommaPos = null; } else if (!currentCharacter.match(/\s/)) { danglingCommaPos = null; } } } return result + pseudoJson.substring(offset); } // start strip-json-comments /** * * @param {string} jsonString * @param {number} quotePosition * @returns {boolean} */ function isEscaped(jsonString, quotePosition) { let index = quotePosition - 1; let backslashCount = 0; while (jsonString[index] === '\\') { index -= 1; backslashCount += 1; } return Boolean(backslashCount % 2); } /** * * @param {string} string * @param {number?} start * @param {number?} end */ function strip(string, start, end) { return string.slice(start, end).replace(/\S/g, ' '); } const singleComment = Symbol('singleComment'); const multiComment = Symbol('multiComment'); /** * @param {string} jsonString * @returns {string} */ function stripJsonComments(jsonString) { let isInsideString = false; /** @type {false | symbol} */ let isInsideComment = false; let offset = 0; let result = ''; for (let index = 0; index < jsonString.length; index++) { const currentCharacter = jsonString[index]; const nextCharacter = jsonString[index + 1]; if (!isInsideComment && currentCharacter === '"') { const escaped = isEscaped(jsonString, index); if (!escaped) { isInsideString = !isInsideString; } } if (isInsideString) { continue; } if (!isInsideComment && currentCharacter + nextCharacter === '//') { result += jsonString.slice(offset, index); offset = index; isInsideComment = singleComment; index++; } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === '\r\n') { index++; isInsideComment = false; result += strip(jsonString, offset, index); offset = index; } else if (isInsideComment === singleComment && currentCharacter === '\n') { isInsideComment = false; result += strip(jsonString, offset, index); offset = index; } else if (!isInsideComment && currentCharacter + nextCharacter === '/*') { result += jsonString.slice(offset, index); offset = index; isInsideComment = multiComment; index++; } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === '*/') { index++; isInsideComment = false; result += strip(jsonString, offset, index + 1); offset = index + 1; } } return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset)); } // end strip-json-comments // start strip-bom /** * @param {string} string * @returns {string} */ function stripBom(string) { // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string // conversion translates it to FEFF (UTF-16 BOM). if (string.charCodeAt(0) === 0xfeff) { return string.slice(1); } return string; } // end strip-bom const not_found_result = { tsconfigFile: null, tsconfig: {} }; /** * parse the closest tsconfig.json file * * @param {string} filename - path to a tsconfig .json or a source file or directory (absolute or relative to cwd) * @param {import('./public.d.ts').TSConfckParseOptions} [options] - options * @returns {Promise} * @throws {TSConfckParseError} */ async function parse$f(filename, options) { /** @type {import('./cache.js').TSConfckCache} */ const cache = options?.cache; if (cache?.hasParseResult(filename)) { return getParsedDeep(filename, cache, options); } const { resolve, reject, /** @type {Promise}*/ promise } = makePromise(); cache?.setParseResult(filename, promise, true); try { let tsconfigFile = (await resolveTSConfigJson(filename, cache)) || (await find(filename, options)); if (!tsconfigFile) { resolve(not_found_result); return promise; } let result; if (filename !== tsconfigFile && cache?.hasParseResult(tsconfigFile)) { result = await getParsedDeep(tsconfigFile, cache, options); } else { result = await parseFile$1(tsconfigFile, cache, filename === tsconfigFile); await Promise.all([parseExtends(result, cache), parseReferences(result, options)]); } result.tsconfig = replaceTokens(result.tsconfig, path$d.dirname(tsconfigFile)); resolve(resolveSolutionTSConfig(filename, result)); } catch (e) { reject(e); } return promise; } /** * ensure extends and references are parsed * * @param {string} filename - cached file * @param {import('./cache.js').TSConfckCache} cache - cache * @param {import('./public.d.ts').TSConfckParseOptions} options - options */ async function getParsedDeep(filename, cache, options) { const result = await cache.getParseResult(filename); if ( (result.tsconfig.extends && !result.extended) || (result.tsconfig.references && !result.referenced) ) { const promise = Promise.all([ parseExtends(result, cache), parseReferences(result, options) ]).then(() => result); cache.setParseResult(filename, promise, true); return promise; } return result; } /** * * @param {string} tsconfigFile - path to tsconfig file * @param {import('./cache.js').TSConfckCache} [cache] - cache * @param {boolean} [skipCache] - skip cache * @returns {Promise} */ async function parseFile$1(tsconfigFile, cache, skipCache) { if ( !skipCache && cache?.hasParseResult(tsconfigFile) && !cache.getParseResult(tsconfigFile)._isRootFile_ ) { return cache.getParseResult(tsconfigFile); } const promise = promises$1 .readFile(tsconfigFile, 'utf-8') .then(toJson) .then((json) => { const parsed = JSON.parse(json); applyDefaults(parsed, tsconfigFile); return { tsconfigFile, tsconfig: normalizeTSConfig(parsed, path$d.dirname(tsconfigFile)) }; }) .catch((e) => { throw new TSConfckParseError( `parsing ${tsconfigFile} failed: ${e}`, 'PARSE_FILE', tsconfigFile, e ); }); if ( !skipCache && (!cache?.hasParseResult(tsconfigFile) || !cache.getParseResult(tsconfigFile)._isRootFile_) ) { cache?.setParseResult(tsconfigFile, promise); } return promise; } /** * normalize to match the output of ts.parseJsonConfigFileContent * * @param {any} tsconfig - typescript tsconfig output * @param {string} dir - directory */ function normalizeTSConfig(tsconfig, dir) { // set baseUrl to absolute path const baseUrl = tsconfig.compilerOptions?.baseUrl; if (baseUrl && !baseUrl.startsWith('${') && !path$d.isAbsolute(baseUrl)) { tsconfig.compilerOptions.baseUrl = resolve2posix(dir, baseUrl); } return tsconfig; } /** * * @param {import('./public.d.ts').TSConfckParseResult} result * @param {import('./public.d.ts').TSConfckParseOptions} [options] * @returns {Promise} */ async function parseReferences(result, options) { if (!result.tsconfig.references) { return; } const referencedFiles = resolveReferencedTSConfigFiles(result, options); const referenced = await Promise.all( referencedFiles.map((file) => parseFile$1(file, options?.cache)) ); await Promise.all(referenced.map((ref) => parseExtends(ref, options?.cache))); referenced.forEach((ref) => { ref.solution = result; }); result.referenced = referenced; } /** * @param {import('./public.d.ts').TSConfckParseResult} result * @param {import('./cache.js').TSConfckCache}[cache] * @returns {Promise} */ async function parseExtends(result, cache) { if (!result.tsconfig.extends) { return; } // use result as first element in extended // but dereference tsconfig so that mergeExtended can modify the original without affecting extended[0] /** @type {import('./public.d.ts').TSConfckParseResult[]} */ const extended = [ { tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) } ]; // flatten extends graph into extended let pos = 0; /** @type {string[]} */ const extendsPath = []; let currentBranchDepth = 0; while (pos < extended.length) { const extending = extended[pos]; extendsPath.push(extending.tsconfigFile); if (extending.tsconfig.extends) { // keep following this branch currentBranchDepth += 1; /** @type {string[]} */ let resolvedExtends; if (!Array.isArray(extending.tsconfig.extends)) { resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)]; } else { // reverse because typescript 5.0 treats ['a','b','c'] as c extends b extends a resolvedExtends = extending.tsconfig.extends .reverse() .map((ex) => resolveExtends(ex, extending.tsconfigFile)); } const circularExtends = resolvedExtends.find((tsconfigFile) => extendsPath.includes(tsconfigFile) ); if (circularExtends) { const circle = extendsPath.concat([circularExtends]).join(' -> '); throw new TSConfckParseError( `Circular dependency in "extends": ${circle}`, 'EXTENDS_CIRCULAR', result.tsconfigFile ); } // add new extends to the list directly after current extended.splice( pos + 1, 0, ...(await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache)))) ); } else { // reached a leaf, backtrack to the last branching point and continue extendsPath.splice(-currentBranchDepth); currentBranchDepth = 0; } pos = pos + 1; } result.extended = extended; // skip first as it is the original config for (const ext of result.extended.slice(1)) { extendTSConfig(result, ext); } } /** * * @param {string} extended * @param {string} from * @returns {string} */ function resolveExtends(extended, from) { if (extended === '..') { // see #149 extended = '../tsconfig.json'; } const req = createRequire$2(from); let error; try { return req.resolve(extended); } catch (e) { error = e; } if (extended[0] !== '.' && !path$d.isAbsolute(extended)) { try { return req.resolve(`${extended}/tsconfig.json`); } catch (e) { error = e; } } throw new TSConfckParseError( `failed to resolve "extends":"${extended}" in ${from}`, 'EXTENDS_RESOLVE', from, error ); } // references, extends and custom keys are not carried over const EXTENDABLE_KEYS = [ 'compilerOptions', 'files', 'include', 'exclude', 'watchOptions', 'compileOnSave', 'typeAcquisition', 'buildOptions' ]; /** * * @param {import('./public.d.ts').TSConfckParseResult} extending * @param {import('./public.d.ts').TSConfckParseResult} extended * @returns void */ function extendTSConfig(extending, extended) { const extendingConfig = extending.tsconfig; const extendedConfig = extended.tsconfig; const relativePath = native2posix( path$d.relative(path$d.dirname(extending.tsconfigFile), path$d.dirname(extended.tsconfigFile)) ); for (const key of Object.keys(extendedConfig).filter((key) => EXTENDABLE_KEYS.includes(key))) { if (key === 'compilerOptions') { if (!extendingConfig.compilerOptions) { extendingConfig.compilerOptions = {}; } for (const option of Object.keys(extendedConfig.compilerOptions)) { if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) { continue; // already set } extendingConfig.compilerOptions[option] = rebaseRelative( option, extendedConfig.compilerOptions[option], relativePath ); } } else if (extendingConfig[key] === undefined) { if (key === 'watchOptions') { extendingConfig.watchOptions = {}; for (const option of Object.keys(extendedConfig.watchOptions)) { extendingConfig.watchOptions[option] = rebaseRelative( option, extendedConfig.watchOptions[option], relativePath ); } } else { extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath); } } } } const REBASE_KEYS = [ // root 'files', 'include', 'exclude', // compilerOptions 'baseUrl', 'rootDir', 'rootDirs', 'typeRoots', 'outDir', 'outFile', 'declarationDir', // watchOptions 'excludeDirectories', 'excludeFiles' ]; /** @typedef {string | string[]} PathValue */ /** * * @param {string} key * @param {PathValue} value * @param {string} prependPath * @returns {PathValue} */ function rebaseRelative(key, value, prependPath) { if (!REBASE_KEYS.includes(key)) { return value; } if (Array.isArray(value)) { return value.map((x) => rebasePath(x, prependPath)); } else { return rebasePath(value, prependPath); } } /** * * @param {string} value * @param {string} prependPath * @returns {string} */ function rebasePath(value, prependPath) { if (path$d.isAbsolute(value) || value.startsWith('${configDir}')) { return value; } else { // relative paths use posix syntax in tsconfig return path$d.posix.normalize(path$d.posix.join(prependPath, value)); } } class TSConfckParseError extends Error { /** * error code * @type {string} */ code; /** * error cause * @type { Error | undefined} */ cause; /** * absolute path of tsconfig file where the error happened * @type {string} */ tsconfigFile; /** * * @param {string} message - error message * @param {string} code - error code * @param {string} tsconfigFile - path to tsconfig file * @param {Error?} cause - cause of this error */ constructor(message, code, tsconfigFile, cause) { super(message); // Set the prototype explicitly. Object.setPrototypeOf(this, TSConfckParseError.prototype); this.name = TSConfckParseError.name; this.code = code; this.cause = cause; this.tsconfigFile = tsconfigFile; } } /** * * @param {any} tsconfig * @param {string} tsconfigFile */ function applyDefaults(tsconfig, tsconfigFile) { if (isJSConfig(tsconfigFile)) { tsconfig.compilerOptions = { ...DEFAULT_JSCONFIG_COMPILER_OPTIONS, ...tsconfig.compilerOptions }; } } const DEFAULT_JSCONFIG_COMPILER_OPTIONS = { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }; /** * @param {string} configFileName */ function isJSConfig(configFileName) { return path$d.basename(configFileName) === 'jsconfig.json'; } /** @template T */ class TSConfckCache { /** * clear cache, use this if you have a long running process and tsconfig files have been added,changed or deleted */ clear() { this.#configPaths.clear(); this.#parsed.clear(); } /** * has cached closest config for files in dir * @param {string} dir * @param {string} [configName=tsconfig.json] * @returns {boolean} */ hasConfigPath(dir, configName = 'tsconfig.json') { return this.#configPaths.has(`${dir}/${configName}`); } /** * get cached closest tsconfig for files in dir * @param {string} dir * @param {string} [configName=tsconfig.json] * @returns {Promise|string|null} * @throws {unknown} if cached value is an error */ getConfigPath(dir, configName = 'tsconfig.json') { const key = `${dir}/${configName}`; const value = this.#configPaths.get(key); if (value == null || value.length || value.then) { return value; } else { throw value; } } /** * has parsed tsconfig for file * @param {string} file * @returns {boolean} */ hasParseResult(file) { return this.#parsed.has(file); } /** * get parsed tsconfig for file * @param {string} file * @returns {Promise|T} * @throws {unknown} if cached value is an error */ getParseResult(file) { const value = this.#parsed.get(file); if (value.then || value.tsconfig) { return value; } else { throw value; // cached error, rethrow } } /** * @internal * @private * @param file * @param {boolean} isRootFile a flag to check if current file which involking the parse() api, used to distinguish the normal cache which only parsed by parseFile() * @param {Promise} result */ setParseResult(file, result, isRootFile = false) { // _isRootFile_ is a temporary property for Promise result, used to prevent deadlock with cache Object.defineProperty(result, '_isRootFile_', { value: isRootFile, writable: false, enumerable: false, configurable: false }); this.#parsed.set(file, result); result .then((parsed) => { if (this.#parsed.get(file) === result) { this.#parsed.set(file, parsed); } }) .catch((e) => { if (this.#parsed.get(file) === result) { this.#parsed.set(file, e); } }); } /** * @internal * @private * @param {string} dir * @param {Promise} configPath * @param {string} [configName=tsconfig.json] */ setConfigPath(dir, configPath, configName = 'tsconfig.json') { const key = `${dir}/${configName}`; this.#configPaths.set(key, configPath); configPath .then((path) => { if (this.#configPaths.get(key) === configPath) { this.#configPaths.set(key, path); } }) .catch((e) => { if (this.#configPaths.get(key) === configPath) { this.#configPaths.set(key, e); } }); } /** * map directories to their closest tsconfig.json * @internal * @private * @type{Map|string|null)>} */ #configPaths = new Map(); /** * map files to their parsed tsconfig result * @internal * @private * @type {Map|T)> } */ #parsed = new Map(); } const debug$h = createDebugger("vite:esbuild"); const IIFE_BEGIN_RE = /(?:const|var)\s+\S+\s*=\s*function\([^()]*\)\s*\{\s*"use strict";/; const validExtensionRE = /\.\w+$/; const jsxExtensionsRE = /\.(?:j|t)sx\b/; const defaultEsbuildSupported = { "dynamic-import": true, "import-meta": true }; async function transformWithEsbuild(code, filename, options, inMap, config, watcher) { let loader = options?.loader; if (!loader) { const ext = path$d.extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename)).slice(1); if (ext === "cjs" || ext === "mjs") { loader = "js"; } else if (ext === "cts" || ext === "mts") { loader = "ts"; } else { loader = ext; } } let tsconfigRaw = options?.tsconfigRaw; if (typeof tsconfigRaw !== "string") { const meaningfulFields = [ "alwaysStrict", "experimentalDecorators", "importsNotUsedAsValues", "jsx", "jsxFactory", "jsxFragmentFactory", "jsxImportSource", "preserveValueImports", "target", "useDefineForClassFields", "verbatimModuleSyntax" ]; const compilerOptionsForFile = {}; if (loader === "ts" || loader === "tsx") { try { const { tsconfig: loadedTsconfig, tsconfigFile } = await loadTsconfigJsonForFile(filename, config); if (watcher && tsconfigFile && config) { ensureWatchedFile(watcher, tsconfigFile, config.root); } const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {}; for (const field of meaningfulFields) { if (field in loadedCompilerOptions) { compilerOptionsForFile[field] = loadedCompilerOptions[field]; } } } catch (e) { if (e instanceof TSConfckParseError) { if (watcher && e.tsconfigFile && config) { ensureWatchedFile(watcher, e.tsconfigFile, config.root); } } throw e; } } const compilerOptions = { ...compilerOptionsForFile, ...tsconfigRaw?.compilerOptions }; if (compilerOptions.useDefineForClassFields === void 0 && compilerOptions.target === void 0) { compilerOptions.useDefineForClassFields = false; } if (options) { if (options.jsx) compilerOptions.jsx = void 0; if (options.jsxFactory) compilerOptions.jsxFactory = void 0; if (options.jsxFragment) compilerOptions.jsxFragmentFactory = void 0; if (options.jsxImportSource) compilerOptions.jsxImportSource = void 0; } tsconfigRaw = { ...tsconfigRaw, compilerOptions }; } const resolvedOptions = { sourcemap: true, // ensure source file name contains full query sourcefile: filename, ...options, loader, tsconfigRaw }; delete resolvedOptions.include; delete resolvedOptions.exclude; delete resolvedOptions.jsxInject; try { const result = await transform$1(code, resolvedOptions); let map; if (inMap && resolvedOptions.sourcemap) { const nextMap = JSON.parse(result.map); nextMap.sourcesContent = []; map = combineSourcemaps(filename, [ nextMap, inMap ]); } else { map = resolvedOptions.sourcemap && resolvedOptions.sourcemap !== "inline" ? JSON.parse(result.map) : { mappings: "" }; } return { ...result, map }; } catch (e) { debug$h?.(`esbuild error with options used: `, resolvedOptions); if (e.errors) { e.frame = ""; e.errors.forEach((m) => { if (m.text === "Experimental decorators are not currently enabled" || m.text === "Parameter decorators only work when experimental decorators are enabled") { m.text += '. Vite 5 now uses esbuild 0.18 and you need to enable them by adding "experimentalDecorators": true in your "tsconfig.json" file.'; } e.frame += ` ` + prettifyMessage(m, code); }); e.loc = e.errors[0].location; } throw e; } } function esbuildPlugin(config) { const options = config.esbuild; const { jsxInject, include, exclude, ...esbuildTransformOptions } = options; const filter = createFilter(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/); const transformOptions = { target: "esnext", charset: "utf8", ...esbuildTransformOptions, minify: false, minifyIdentifiers: false, minifySyntax: false, minifyWhitespace: false, treeShaking: false, // keepNames is not needed when minify is disabled. // Also transforming multiple times with keepNames enabled breaks // tree-shaking. (#9164) keepNames: false, supported: { ...defaultEsbuildSupported, ...esbuildTransformOptions.supported } }; let server; return { name: "vite:esbuild", configureServer(_server) { server = _server; }, async transform(code, id) { if (filter(id) || filter(cleanUrl(id))) { const result = await transformWithEsbuild( code, id, transformOptions, void 0, config, server?.watcher ); if (result.warnings.length) { result.warnings.forEach((m) => { this.warn(prettifyMessage(m, code)); }); } if (jsxInject && jsxExtensionsRE.test(id)) { result.code = jsxInject + ";" + result.code; } return { code: result.code, map: result.map }; } } }; } const rollupToEsbuildFormatMap = { es: "esm", cjs: "cjs", // passing `var Lib = (() => {})()` to esbuild with format = "iife" // will turn it to `(() => { var Lib = (() => {})() })()`, // so we remove the format config to tell esbuild not doing this // // although esbuild doesn't change format, there is still possibility // that `{ treeShaking: true }` removes a top-level no-side-effect variable // like: `var Lib = 1`, which becomes `` after esbuild transforming, // but thankfully rollup does not do this optimization now iife: void 0 }; const buildEsbuildPlugin = (config) => { return { name: "vite:esbuild-transpile", async renderChunk(code, chunk, opts) { if (opts.__vite_skip_esbuild__) { return null; } const options = resolveEsbuildTranspileOptions(config, opts.format); if (!options) { return null; } const res = await transformWithEsbuild( code, chunk.fileName, options, void 0, config ); if (config.build.lib) { const esbuildCode = res.code; const contentIndex = opts.format === "iife" ? Math.max(esbuildCode.search(IIFE_BEGIN_RE), 0) : opts.format === "umd" ? esbuildCode.indexOf(`(function(`) : 0; if (contentIndex > 0) { const esbuildHelpers = esbuildCode.slice(0, contentIndex); res.code = esbuildCode.slice(contentIndex).replace(`"use strict";`, `"use strict";` + esbuildHelpers); } } return res; } }; }; function resolveEsbuildTranspileOptions(config, format) { const target = config.build.target; const minify = config.build.minify === "esbuild"; if ((!target || target === "esnext") && !minify) { return null; } const isEsLibBuild = config.build.lib && format === "es"; const esbuildOptions = config.esbuild || {}; const options = { charset: "utf8", ...esbuildOptions, loader: "js", target: target || void 0, format: rollupToEsbuildFormatMap[format], supported: { ...defaultEsbuildSupported, ...esbuildOptions.supported } }; if (!minify) { return { ...options, minify: false, minifyIdentifiers: false, minifySyntax: false, minifyWhitespace: false, treeShaking: false }; } if (options.minifyIdentifiers != null || options.minifySyntax != null || options.minifyWhitespace != null) { if (isEsLibBuild) { return { ...options, minify: false, minifyIdentifiers: options.minifyIdentifiers ?? true, minifySyntax: options.minifySyntax ?? true, minifyWhitespace: false, treeShaking: true }; } else { return { ...options, minify: false, minifyIdentifiers: options.minifyIdentifiers ?? true, minifySyntax: options.minifySyntax ?? true, minifyWhitespace: options.minifyWhitespace ?? true, treeShaking: true }; } } if (isEsLibBuild) { return { ...options, minify: false, minifyIdentifiers: true, minifySyntax: true, minifyWhitespace: false, treeShaking: true }; } else { return { ...options, minify: true, treeShaking: true }; } } function prettifyMessage(m, code) { let res = colors$1.yellow(m.text); if (m.location) { res += ` ` + generateCodeFrame(code, m.location); } return res + ` `; } let globalTSConfckCache; const tsconfckCacheMap = /* @__PURE__ */ new WeakMap(); function getTSConfckCache(config) { if (!config) { return globalTSConfckCache ??= new TSConfckCache(); } let cache = tsconfckCacheMap.get(config); if (!cache) { cache = new TSConfckCache(); tsconfckCacheMap.set(config, cache); } return cache; } async function loadTsconfigJsonForFile(filename, config) { const { tsconfig, tsconfigFile } = await parse$f(filename, { cache: getTSConfckCache(config), ignoreNodeModules: true }); return { tsconfigFile, tsconfig }; } async function reloadOnTsconfigChange(server, changedFile) { if (changedFile.endsWith(".json")) { const cache = getTSConfckCache(server.config); if (changedFile.endsWith("/tsconfig.json") || cache.hasParseResult(changedFile)) { server.config.logger.info( `changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true } ); for (const environment of Object.values(server.environments)) { environment.moduleGraph.invalidateAll(); } cache.clear(); for (const environment of Object.values(server.environments)) { environment.hot.send({ type: "full-reload", path: "*" }); } } } } // src/realWorker.ts var Worker = class { /** @internal */ _code; /** @internal */ _parentFunctions; /** @internal */ _max; /** @internal */ _pool; /** @internal */ _idlePool; /** @internal */ _queue; constructor(fn, options = {}) { this._code = genWorkerCode(fn, options.parentFunctions ?? {}); this._parentFunctions = options.parentFunctions ?? {}; const defaultMax = Math.max( 1, // os.availableParallelism is available from Node.js 18.14.0 (os$3.availableParallelism?.() ?? os$3.cpus().length) - 1 ); this._max = options.max || defaultMax; this._pool = []; this._idlePool = []; this._queue = []; } async run(...args) { const worker = await this._getAvailableWorker(); return new Promise((resolve, reject) => { worker.currentResolve = resolve; worker.currentReject = reject; worker.postMessage({ type: "run", args }); }); } stop() { this._pool.forEach((w) => w.unref()); this._queue.forEach( ([, reject]) => reject( new Error("Main worker pool stopped before a worker was available.") ) ); this._pool = []; this._idlePool = []; this._queue = []; } /** @internal */ async _getAvailableWorker() { if (this._idlePool.length) { return this._idlePool.shift(); } if (this._pool.length < this._max) { const worker = new Worker$1(this._code, { eval: true }); worker.on("message", async (args) => { if (args.type === "run") { if ("result" in args) { worker.currentResolve && worker.currentResolve(args.result); worker.currentResolve = null; } else { if (args.error instanceof ReferenceError) { args.error.message += ". Maybe you forgot to pass the function to parentFunction?"; } worker.currentReject && worker.currentReject(args.error); worker.currentReject = null; } this._assignDoneWorker(worker); } else if (args.type === "parentFunction") { try { const result = await this._parentFunctions[args.name](...args.args); worker.postMessage({ type: "parentFunction", id: args.id, result }); } catch (e) { worker.postMessage({ type: "parentFunction", id: args.id, error: e }); } } }); worker.on("error", (err) => { worker.currentReject && worker.currentReject(err); worker.currentReject = null; }); worker.on("exit", (code) => { const i = this._pool.indexOf(worker); if (i > -1) this._pool.splice(i, 1); if (code !== 0 && worker.currentReject) { worker.currentReject( new Error(`Worker stopped with non-0 exit code ${code}`) ); worker.currentReject = null; } }); this._pool.push(worker); return worker; } let resolve; let reject; const onWorkerAvailablePromise = new Promise((r, rj) => { resolve = r; reject = rj; }); this._queue.push([resolve, reject]); return onWorkerAvailablePromise; } /** @internal */ _assignDoneWorker(worker) { if (this._queue.length) { const [resolve] = this._queue.shift(); resolve(worker); return; } this._idlePool.push(worker); } }; function genWorkerCode(fn, parentFunctions) { const createParentFunctionCaller = (parentPort) => { let id = 0; const resolvers = /* @__PURE__ */ new Map(); const call = (key) => async (...args) => { id++; let resolve, reject; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); resolvers.set(id, { resolve, reject }); parentPort.postMessage({ type: "parentFunction", id, name: key, args }); return await promise; }; const receive = (id2, args) => { if (resolvers.has(id2)) { const { resolve, reject } = resolvers.get(id2); resolvers.delete(id2); if ("result" in args) { resolve(args.result); } else { reject(args.error); } } }; return { call, receive }; }; return ` const { parentPort } = require('worker_threads') const parentFunctionCaller = (${createParentFunctionCaller.toString()})(parentPort) const doWork = (() => { ${Object.keys(parentFunctions).map( (key) => `const ${key} = parentFunctionCaller.call(${JSON.stringify(key)});` ).join("\n")} return (${fn.toString()})() })() parentPort.on('message', async (args) => { if (args.type === 'run') { try { const res = await doWork(...args.args) parentPort.postMessage({ type: 'run', result: res }) } catch (e) { parentPort.postMessage({ type: 'run', error: e }) } } else if (args.type === 'parentFunction') { parentFunctionCaller.receive(args.id, args) } }) `; } var FakeWorker = class { /** @internal */ _fn; constructor(fn, options = {}) { const argsAndCode = genFakeWorkerArgsAndCode( fn, options.parentFunctions ?? {} ); const require2 = createRequire$1(import.meta.url); this._fn = new Function(...argsAndCode)(require2, options.parentFunctions); } async run(...args) { try { return await this._fn(...args); } catch (err) { if (err instanceof ReferenceError) { err.message += ". Maybe you forgot to pass the function to parentFunction?"; } throw err; } } stop() { } }; function genFakeWorkerArgsAndCode(fn, parentFunctions) { return [ "require", "parentFunctions", ` ${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctions[${JSON.stringify(key)}];`).join("\n")} return (${fn.toString()})() ` ]; } // src/workerWithFallback.ts var WorkerWithFallback = class { /** @internal */ _disableReal; /** @internal */ _realWorker; /** @internal */ _fakeWorker; /** @internal */ _shouldUseFake; constructor(fn, options) { this._disableReal = options.max !== void 0 && options.max <= 0; this._realWorker = new Worker(fn, options); this._fakeWorker = new FakeWorker(fn, options); this._shouldUseFake = options.shouldUseFake; } async run(...args) { const useFake = this._disableReal || this._shouldUseFake(...args); return this[useFake ? "_fakeWorker" : "_realWorker"].run(...args); } stop() { this._realWorker.stop(); this._fakeWorker.stop(); } }; let terserPath; const loadTerserPath = (root) => { if (terserPath) return terserPath; try { terserPath = requireResolveFromRootWithFallback(root, "terser"); } catch (e) { if (e.code === "MODULE_NOT_FOUND") { throw new Error( "terser not found. Since Vite v3, terser has become an optional dependency. You need to install it." ); } else { const message = new Error(`terser failed to load: ${e.message}`); message.stack = e.stack + "\n" + message.stack; throw message; } } return terserPath; }; function terserPlugin(config) { const { maxWorkers, ...terserOptions } = config.build.terserOptions; const makeWorker = () => new Worker( () => async (terserPath2, code, options) => { const terser = require(terserPath2); return terser.minify(code, options); }, { max: maxWorkers } ); let worker; return { name: "vite:terser", applyToEnvironment(environment) { return !!environment.config.build.minify; }, async renderChunk(code, _chunk, outputOptions) { if (config.build.minify !== "terser" && // @ts-expect-error injected by @vitejs/plugin-legacy !outputOptions.__vite_force_terser__) { return null; } if (config.build.lib && outputOptions.format === "es") { return null; } worker ||= makeWorker(); const terserPath2 = loadTerserPath(config.root); const res = await worker.run(terserPath2, code, { safari10: true, ...terserOptions, sourceMap: !!outputOptions.sourcemap, module: outputOptions.format.startsWith("es"), toplevel: outputOptions.format === "cjs" }); return { code: res.code, map: res.map }; }, closeBundle() { worker?.stop(); } }; } async function resolveEnvironmentPlugins(environment) { const environmentPlugins = []; for (const plugin of environment.getTopLevelConfig().plugins) { if (plugin.applyToEnvironment) { const applied = await plugin.applyToEnvironment(environment); if (!applied) { continue; } if (applied !== true) { environmentPlugins.push( ...(await asyncFlatten(arraify(applied))).filter( Boolean ) ); continue; } } environmentPlugins.push(plugin); } return environmentPlugins; } function perEnvironmentPlugin(name, applyToEnvironment) { return { name, applyToEnvironment }; } const mimes = { "3g2": "video/3gpp2", "3gp": "video/3gpp", "3gpp": "video/3gpp", "3mf": "model/3mf", "aac": "audio/aac", "ac": "application/pkix-attr-cert", "adp": "audio/adpcm", "adts": "audio/aac", "ai": "application/postscript", "aml": "application/automationml-aml+xml", "amlx": "application/automationml-amlx+zip", "amr": "audio/amr", "apng": "image/apng", "appcache": "text/cache-manifest", "appinstaller": "application/appinstaller", "appx": "application/appx", "appxbundle": "application/appxbundle", "asc": "application/pgp-keys", "atom": "application/atom+xml", "atomcat": "application/atomcat+xml", "atomdeleted": "application/atomdeleted+xml", "atomsvc": "application/atomsvc+xml", "au": "audio/basic", "avci": "image/avci", "avcs": "image/avcs", "avif": "image/avif", "aw": "application/applixware", "bdoc": "application/bdoc", "bin": "application/octet-stream", "bmp": "image/bmp", "bpk": "application/octet-stream", "btf": "image/prs.btif", "btif": "image/prs.btif", "buffer": "application/octet-stream", "ccxml": "application/ccxml+xml", "cdfx": "application/cdfx+xml", "cdmia": "application/cdmi-capability", "cdmic": "application/cdmi-container", "cdmid": "application/cdmi-domain", "cdmio": "application/cdmi-object", "cdmiq": "application/cdmi-queue", "cer": "application/pkix-cert", "cgm": "image/cgm", "cjs": "application/node", "class": "application/java-vm", "coffee": "text/coffeescript", "conf": "text/plain", "cpl": "application/cpl+xml", "cpt": "application/mac-compactpro", "crl": "application/pkix-crl", "css": "text/css", "csv": "text/csv", "cu": "application/cu-seeme", "cwl": "application/cwl", "cww": "application/prs.cww", "davmount": "application/davmount+xml", "dbk": "application/docbook+xml", "deb": "application/octet-stream", "def": "text/plain", "deploy": "application/octet-stream", "dib": "image/bmp", "disposition-notification": "message/disposition-notification", "dist": "application/octet-stream", "distz": "application/octet-stream", "dll": "application/octet-stream", "dmg": "application/octet-stream", "dms": "application/octet-stream", "doc": "application/msword", "dot": "application/msword", "dpx": "image/dpx", "drle": "image/dicom-rle", "dsc": "text/prs.lines.tag", "dssc": "application/dssc+der", "dtd": "application/xml-dtd", "dump": "application/octet-stream", "dwd": "application/atsc-dwd+xml", "ear": "application/java-archive", "ecma": "application/ecmascript", "elc": "application/octet-stream", "emf": "image/emf", "eml": "message/rfc822", "emma": "application/emma+xml", "emotionml": "application/emotionml+xml", "eps": "application/postscript", "epub": "application/epub+zip", "exe": "application/octet-stream", "exi": "application/exi", "exp": "application/express", "exr": "image/aces", "ez": "application/andrew-inset", "fdf": "application/fdf", "fdt": "application/fdt+xml", "fits": "image/fits", "g3": "image/g3fax", "gbr": "application/rpki-ghostbusters", "geojson": "application/geo+json", "gif": "image/gif", "glb": "model/gltf-binary", "gltf": "model/gltf+json", "gml": "application/gml+xml", "gpx": "application/gpx+xml", "gram": "application/srgs", "grxml": "application/srgs+xml", "gxf": "application/gxf", "gz": "application/gzip", "h261": "video/h261", "h263": "video/h263", "h264": "video/h264", "heic": "image/heic", "heics": "image/heic-sequence", "heif": "image/heif", "heifs": "image/heif-sequence", "hej2": "image/hej2k", "held": "application/atsc-held+xml", "hjson": "application/hjson", "hlp": "application/winhlp", "hqx": "application/mac-binhex40", "hsj2": "image/hsj2", "htm": "text/html", "html": "text/html", "ics": "text/calendar", "ief": "image/ief", "ifb": "text/calendar", "iges": "model/iges", "igs": "model/iges", "img": "application/octet-stream", "in": "text/plain", "ini": "text/plain", "ink": "application/inkml+xml", "inkml": "application/inkml+xml", "ipfix": "application/ipfix", "iso": "application/octet-stream", "its": "application/its+xml", "jade": "text/jade", "jar": "application/java-archive", "jhc": "image/jphc", "jls": "image/jls", "jp2": "image/jp2", "jpe": "image/jpeg", "jpeg": "image/jpeg", "jpf": "image/jpx", "jpg": "image/jpeg", "jpg2": "image/jp2", "jpgm": "image/jpm", "jpgv": "video/jpeg", "jph": "image/jph", "jpm": "image/jpm", "jpx": "image/jpx", "js": "text/javascript", "json": "application/json", "json5": "application/json5", "jsonld": "application/ld+json", "jsonml": "application/jsonml+json", "jsx": "text/jsx", "jt": "model/jt", "jxr": "image/jxr", "jxra": "image/jxra", "jxrs": "image/jxrs", "jxs": "image/jxs", "jxsc": "image/jxsc", "jxsi": "image/jxsi", "jxss": "image/jxss", "kar": "audio/midi", "ktx": "image/ktx", "ktx2": "image/ktx2", "less": "text/less", "lgr": "application/lgr+xml", "list": "text/plain", "litcoffee": "text/coffeescript", "log": "text/plain", "lostxml": "application/lost+xml", "lrf": "application/octet-stream", "m1v": "video/mpeg", "m21": "application/mp21", "m2a": "audio/mpeg", "m2v": "video/mpeg", "m3a": "audio/mpeg", "m4a": "audio/mp4", "m4p": "application/mp4", "m4s": "video/iso.segment", "ma": "application/mathematica", "mads": "application/mads+xml", "maei": "application/mmt-aei+xml", "man": "text/troff", "manifest": "text/cache-manifest", "map": "application/json", "mar": "application/octet-stream", "markdown": "text/markdown", "mathml": "application/mathml+xml", "mb": "application/mathematica", "mbox": "application/mbox", "md": "text/markdown", "mdx": "text/mdx", "me": "text/troff", "mesh": "model/mesh", "meta4": "application/metalink4+xml", "metalink": "application/metalink+xml", "mets": "application/mets+xml", "mft": "application/rpki-manifest", "mid": "audio/midi", "midi": "audio/midi", "mime": "message/rfc822", "mj2": "video/mj2", "mjp2": "video/mj2", "mjs": "text/javascript", "mml": "text/mathml", "mods": "application/mods+xml", "mov": "video/quicktime", "mp2": "audio/mpeg", "mp21": "application/mp21", "mp2a": "audio/mpeg", "mp3": "audio/mpeg", "mp4": "video/mp4", "mp4a": "audio/mp4", "mp4s": "application/mp4", "mp4v": "video/mp4", "mpd": "application/dash+xml", "mpe": "video/mpeg", "mpeg": "video/mpeg", "mpf": "application/media-policy-dataset+xml", "mpg": "video/mpeg", "mpg4": "video/mp4", "mpga": "audio/mpeg", "mpp": "application/dash-patch+xml", "mrc": "application/marc", "mrcx": "application/marcxml+xml", "ms": "text/troff", "mscml": "application/mediaservercontrol+xml", "msh": "model/mesh", "msi": "application/octet-stream", "msix": "application/msix", "msixbundle": "application/msixbundle", "msm": "application/octet-stream", "msp": "application/octet-stream", "mtl": "model/mtl", "musd": "application/mmt-usd+xml", "mxf": "application/mxf", "mxmf": "audio/mobile-xmf", "mxml": "application/xv+xml", "n3": "text/n3", "nb": "application/mathematica", "nq": "application/n-quads", "nt": "application/n-triples", "obj": "model/obj", "oda": "application/oda", "oga": "audio/ogg", "ogg": "audio/ogg", "ogv": "video/ogg", "ogx": "application/ogg", "omdoc": "application/omdoc+xml", "onepkg": "application/onenote", "onetmp": "application/onenote", "onetoc": "application/onenote", "onetoc2": "application/onenote", "opf": "application/oebps-package+xml", "opus": "audio/ogg", "otf": "font/otf", "owl": "application/rdf+xml", "oxps": "application/oxps", "p10": "application/pkcs10", "p7c": "application/pkcs7-mime", "p7m": "application/pkcs7-mime", "p7s": "application/pkcs7-signature", "p8": "application/pkcs8", "pdf": "application/pdf", "pfr": "application/font-tdpfr", "pgp": "application/pgp-encrypted", "pkg": "application/octet-stream", "pki": "application/pkixcmp", "pkipath": "application/pkix-pkipath", "pls": "application/pls+xml", "png": "image/png", "prc": "model/prc", "prf": "application/pics-rules", "provx": "application/provenance+xml", "ps": "application/postscript", "pskcxml": "application/pskc+xml", "pti": "image/prs.pti", "qt": "video/quicktime", "raml": "application/raml+yaml", "rapd": "application/route-apd+xml", "rdf": "application/rdf+xml", "relo": "application/p2p-overlay+xml", "rif": "application/reginfo+xml", "rl": "application/resource-lists+xml", "rld": "application/resource-lists-diff+xml", "rmi": "audio/midi", "rnc": "application/relax-ng-compact-syntax", "rng": "application/xml", "roa": "application/rpki-roa", "roff": "text/troff", "rq": "application/sparql-query", "rs": "application/rls-services+xml", "rsat": "application/atsc-rsat+xml", "rsd": "application/rsd+xml", "rsheet": "application/urc-ressheet+xml", "rss": "application/rss+xml", "rtf": "text/rtf", "rtx": "text/richtext", "rusd": "application/route-usd+xml", "s3m": "audio/s3m", "sbml": "application/sbml+xml", "scq": "application/scvp-cv-request", "scs": "application/scvp-cv-response", "sdp": "application/sdp", "senmlx": "application/senml+xml", "sensmlx": "application/sensml+xml", "ser": "application/java-serialized-object", "setpay": "application/set-payment-initiation", "setreg": "application/set-registration-initiation", "sgi": "image/sgi", "sgm": "text/sgml", "sgml": "text/sgml", "shex": "text/shex", "shf": "application/shf+xml", "shtml": "text/html", "sieve": "application/sieve", "sig": "application/pgp-signature", "sil": "audio/silk", "silo": "model/mesh", "siv": "application/sieve", "slim": "text/slim", "slm": "text/slim", "sls": "application/route-s-tsid+xml", "smi": "application/smil+xml", "smil": "application/smil+xml", "snd": "audio/basic", "so": "application/octet-stream", "spdx": "text/spdx", "spp": "application/scvp-vp-response", "spq": "application/scvp-vp-request", "spx": "audio/ogg", "sql": "application/sql", "sru": "application/sru+xml", "srx": "application/sparql-results+xml", "ssdl": "application/ssdl+xml", "ssml": "application/ssml+xml", "stk": "application/hyperstudio", "stl": "model/stl", "stpx": "model/step+xml", "stpxz": "model/step-xml+zip", "stpz": "model/step+zip", "styl": "text/stylus", "stylus": "text/stylus", "svg": "image/svg+xml", "svgz": "image/svg+xml", "swidtag": "application/swid+xml", "t": "text/troff", "t38": "image/t38", "td": "application/urc-targetdesc+xml", "tei": "application/tei+xml", "teicorpus": "application/tei+xml", "text": "text/plain", "tfi": "application/thraud+xml", "tfx": "image/tiff-fx", "tif": "image/tiff", "tiff": "image/tiff", "toml": "application/toml", "tr": "text/troff", "trig": "application/trig", "ts": "video/mp2t", "tsd": "application/timestamped-data", "tsv": "text/tab-separated-values", "ttc": "font/collection", "ttf": "font/ttf", "ttl": "text/turtle", "ttml": "application/ttml+xml", "txt": "text/plain", "u3d": "model/u3d", "u8dsn": "message/global-delivery-status", "u8hdr": "message/global-headers", "u8mdn": "message/global-disposition-notification", "u8msg": "message/global", "ubj": "application/ubjson", "uri": "text/uri-list", "uris": "text/uri-list", "urls": "text/uri-list", "vcard": "text/vcard", "vrml": "model/vrml", "vtt": "text/vtt", "vxml": "application/voicexml+xml", "war": "application/java-archive", "wasm": "application/wasm", "wav": "audio/wav", "weba": "audio/webm", "webm": "video/webm", "webmanifest": "application/manifest+json", "webp": "image/webp", "wgsl": "text/wgsl", "wgt": "application/widget", "wif": "application/watcherinfo+xml", "wmf": "image/wmf", "woff": "font/woff", "woff2": "font/woff2", "wrl": "model/vrml", "wsdl": "application/wsdl+xml", "wspolicy": "application/wspolicy+xml", "x3d": "model/x3d+xml", "x3db": "model/x3d+fastinfoset", "x3dbz": "model/x3d+binary", "x3dv": "model/x3d-vrml", "x3dvz": "model/x3d+vrml", "x3dz": "model/x3d+xml", "xaml": "application/xaml+xml", "xav": "application/xcap-att+xml", "xca": "application/xcap-caps+xml", "xcs": "application/calendar+xml", "xdf": "application/xcap-diff+xml", "xdssc": "application/dssc+xml", "xel": "application/xcap-el+xml", "xenc": "application/xenc+xml", "xer": "application/patch-ops-error+xml", "xfdf": "application/xfdf", "xht": "application/xhtml+xml", "xhtml": "application/xhtml+xml", "xhvml": "application/xv+xml", "xlf": "application/xliff+xml", "xm": "audio/xm", "xml": "text/xml", "xns": "application/xcap-ns+xml", "xop": "application/xop+xml", "xpl": "application/xproc+xml", "xsd": "application/xml", "xsf": "application/prs.xsf+xml", "xsl": "application/xml", "xslt": "application/xml", "xspf": "application/xspf+xml", "xvm": "application/xv+xml", "xvml": "application/xv+xml", "yaml": "text/yaml", "yang": "application/yang", "yin": "application/yin+xml", "yml": "text/yaml", "zip": "application/zip" }; function lookup(extn) { let tmp = ('' + extn).trim().toLowerCase(); let idx = tmp.lastIndexOf('.'); return mimes[!~idx ? tmp : tmp.substring(++idx)]; } const publicFilesMap = /* @__PURE__ */ new WeakMap(); async function initPublicFiles(config) { let fileNames; try { fileNames = await recursiveReaddir(config.publicDir); } catch (e) { if (e.code === ERR_SYMLINK_IN_RECURSIVE_READDIR) { return; } throw e; } const publicFiles = new Set( fileNames.map((fileName) => fileName.slice(config.publicDir.length)) ); publicFilesMap.set(config, publicFiles); return publicFiles; } function getPublicFiles(config) { return publicFilesMap.get(config); } function checkPublicFile(url, config) { const { publicDir } = config; if (!publicDir || url[0] !== "/") { return; } const fileName = cleanUrl(url); const publicFiles = getPublicFiles(config); if (publicFiles) { return publicFiles.has(fileName) ? normalizePath$3(path$d.join(publicDir, fileName)) : void 0; } const publicFile = normalizePath$3(path$d.join(publicDir, fileName)); if (!publicFile.startsWith(withTrailingSlash(publicDir))) { return; } return fs__default.existsSync(publicFile) ? publicFile : void 0; } const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g; const jsSourceMapRE = /\.[cm]?js\.map$/; const noInlineRE = /[?&]no-inline\b/; const inlineRE$2 = /[?&]inline\b/; const svgExtRE = /\.svg(?:$|\?)/; const assetCache = /* @__PURE__ */ new WeakMap(); const cssEntriesMap = /* @__PURE__ */ new WeakMap(); function registerCustomMime() { mimes["ico"] = "image/x-icon"; mimes["cur"] = "image/x-icon"; mimes["flac"] = "audio/flac"; mimes["eot"] = "application/vnd.ms-fontobject"; } function renderAssetUrlInJS(pluginContext, chunk, opts, code) { const { environment } = pluginContext; const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime( opts.format, environment.config.isWorker ); let match; let s; assetUrlRE.lastIndex = 0; while (match = assetUrlRE.exec(code)) { s ||= new MagicString(code); const [full, referenceId, postfix = ""] = match; const file = pluginContext.getFileName(referenceId); chunk.viteMetadata.importedAssets.add(cleanUrl(file)); const filename = file + postfix; const replacement = toOutputFilePathInJS( environment, filename, "asset", chunk.fileName, "js", toRelativeRuntime ); const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`; s.update(match.index, match.index + full.length, replacementString); } const publicAssetUrlMap = publicAssetUrlCache.get( environment.getTopLevelConfig() ); publicAssetUrlRE.lastIndex = 0; while (match = publicAssetUrlRE.exec(code)) { s ||= new MagicString(code); const [full, hash] = match; const publicUrl = publicAssetUrlMap.get(hash).slice(1); const replacement = toOutputFilePathInJS( environment, publicUrl, "public", chunk.fileName, "js", toRelativeRuntime ); const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`; s.update(match.index, match.index + full.length, replacementString); } return s; } function assetPlugin(config) { registerCustomMime(); return { name: "vite:asset", perEnvironmentStartEndDuringDev: true, buildStart() { assetCache.set(this.environment, /* @__PURE__ */ new Map()); cssEntriesMap.set(this.environment, /* @__PURE__ */ new Set()); }, resolveId(id) { if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) { return; } const publicFile = checkPublicFile(id, config); if (publicFile) { return id; } }, async load(id) { if (id[0] === "\0") { return; } if (rawRE.test(id)) { const file = checkPublicFile(id, config) || cleanUrl(id); this.addWatchFile(file); return `export default ${JSON.stringify( await fsp.readFile(file, "utf-8") )}`; } if (!urlRE.test(id) && !config.assetsInclude(cleanUrl(id))) { return; } id = removeUrlQuery(id); let url = await fileToUrl$1(this, id); if (!url.startsWith("data:") && this.environment.mode === "dev") { const mod = this.environment.moduleGraph.getModuleById(id); if (mod && mod.lastHMRTimestamp > 0) { url = injectQuery(url, `t=${mod.lastHMRTimestamp}`); } } return { code: `export default ${JSON.stringify(encodeURIPath(url))}`, // Force rollup to keep this module from being shared between other entry points if it's an entrypoint. // If the resulting chunk is empty, it will be removed in generateBundle. moduleSideEffects: config.command === "build" && this.getModuleInfo(id)?.isEntry ? "no-treeshake" : false, meta: config.command === "build" ? { "vite:asset": true } : void 0 }; }, renderChunk(code, chunk, opts) { const s = renderAssetUrlInJS(this, chunk, opts, code); if (s) { return { code: s.toString(), map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null }; } else { return null; } }, generateBundle(_, bundle) { for (const file in bundle) { const chunk = bundle[file]; if (chunk.type === "chunk" && chunk.isEntry && chunk.moduleIds.length === 1 && config.assetsInclude(chunk.moduleIds[0]) && this.getModuleInfo(chunk.moduleIds[0])?.meta["vite:asset"]) { delete bundle[file]; } } if (config.command === "build" && !this.environment.config.build.emitAssets) { for (const file in bundle) { if (bundle[file].type === "asset" && !file.endsWith("ssr-manifest.json") && !jsSourceMapRE.test(file)) { delete bundle[file]; } } } } }; } async function fileToUrl$1(pluginContext, id) { const { environment } = pluginContext; if (environment.config.command === "serve") { return fileToDevUrl(environment, id); } else { return fileToBuiltUrl(pluginContext, id); } } async function fileToDevUrl(environment, id, skipBase = false) { const config = environment.getTopLevelConfig(); const publicFile = checkPublicFile(id, config); if (inlineRE$2.test(id)) { const file = publicFile || cleanUrl(id); const content = await fsp.readFile(file); return assetToDataURL(environment, file, content); } if (svgExtRE.test(id)) { const file = publicFile || cleanUrl(id); const content = await fsp.readFile(file); if (shouldInline(environment, file, id, content, void 0, void 0)) { return assetToDataURL(environment, file, content); } } let rtn; if (publicFile) { rtn = id; } else if (id.startsWith(withTrailingSlash(config.root))) { rtn = "/" + path$d.posix.relative(config.root, id); } else { rtn = path$d.posix.join(FS_PREFIX, id); } if (skipBase) { return rtn; } const base = joinUrlSegments(config.server?.origin ?? "", config.decodedBase); return joinUrlSegments(base, removeLeadingSlash(rtn)); } function getPublicAssetFilename(hash, config) { return publicAssetUrlCache.get(config)?.get(hash); } const publicAssetUrlCache = /* @__PURE__ */ new WeakMap(); const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g; function publicFileToBuiltUrl(url, config) { if (config.command !== "build") { return joinUrlSegments(config.decodedBase, url); } const hash = getHash(url); let cache = publicAssetUrlCache.get(config); if (!cache) { cache = /* @__PURE__ */ new Map(); publicAssetUrlCache.set(config, cache); } if (!cache.get(hash)) { cache.set(hash, url); } return `__VITE_PUBLIC_ASSET__${hash}__`; } const GIT_LFS_PREFIX = Buffer$1.from("version https://git-lfs.github.com"); function isGitLfsPlaceholder(content) { if (content.length < GIT_LFS_PREFIX.length) return false; return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0; } async function fileToBuiltUrl(pluginContext, id, skipPublicCheck = false, forceInline) { const environment = pluginContext.environment; const topLevelConfig = environment.getTopLevelConfig(); if (!skipPublicCheck) { const publicFile = checkPublicFile(id, topLevelConfig); if (publicFile) { if (inlineRE$2.test(id)) { id = publicFile; } else { return publicFileToBuiltUrl(id, topLevelConfig); } } } const cache = assetCache.get(environment); const cached = cache.get(id); if (cached) { return cached; } const { file, postfix } = splitFileAndPostfix(id); const content = await fsp.readFile(file); let url; if (shouldInline(environment, file, id, content, pluginContext, forceInline)) { url = assetToDataURL(environment, file, content); } else { const originalFileName = normalizePath$3( path$d.relative(environment.config.root, file) ); const referenceId = pluginContext.emitFile({ type: "asset", // Ignore directory structure for asset file names name: path$d.basename(file), originalFileName, source: content }); url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`; } cache.set(id, url); return url; } async function urlToBuiltUrl(pluginContext, url, importer, forceInline) { const topLevelConfig = pluginContext.environment.getTopLevelConfig(); if (checkPublicFile(url, topLevelConfig)) { return publicFileToBuiltUrl(url, topLevelConfig); } const file = url[0] === "/" ? path$d.join(topLevelConfig.root, url) : path$d.join(path$d.dirname(importer), url); return fileToBuiltUrl( pluginContext, file, // skip public check since we just did it above true, forceInline ); } function shouldInline(environment, file, id, content, buildPluginContext, forceInline) { if (noInlineRE.test(id)) return false; if (inlineRE$2.test(id)) return true; if (buildPluginContext) { if (environment.config.build.lib) return true; if (buildPluginContext.getModuleInfo(id)?.isEntry) return false; } if (forceInline !== void 0) return forceInline; if (file.endsWith(".html")) return false; if (file.endsWith(".svg") && id.includes("#")) return false; let limit; const { assetsInlineLimit } = environment.config.build; if (typeof assetsInlineLimit === "function") { const userShouldInline = assetsInlineLimit(file, content); if (userShouldInline != null) return userShouldInline; limit = DEFAULT_ASSETS_INLINE_LIMIT; } else { limit = Number(assetsInlineLimit); } return content.length < limit && !isGitLfsPlaceholder(content); } function assetToDataURL(environment, file, content) { if (environment.config.build.lib && isGitLfsPlaceholder(content)) { environment.logger.warn( colors$1.yellow(`Inlined file ${file} was not downloaded via Git LFS`) ); } if (file.endsWith(".svg")) { return svgToDataURL(content); } else { const mimeType = lookup(file) ?? "application/octet-stream"; return `data:${mimeType};base64,${content.toString("base64")}`; } } const nestedQuotesRE = /"[^"']*'[^"]*"|'[^'"]*"[^']*'/; function svgToDataURL(content) { const stringContent = content.toString(); if (stringContent.includes("\s+<").replaceAll('"', "'").replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("<", "%3c").replaceAll(">", "%3e").replaceAll(/\s+/g, "%20"); } } const endsWithJSRE = /\.[cm]?js$/; function manifestPlugin() { const getState = perEnvironmentState(() => { return { manifest: {}, outputCount: 0, reset() { this.outputCount = 0; } }; }); return { name: "vite:manifest", perEnvironmentStartEndDuringDev: true, applyToEnvironment(environment) { return !!environment.config.build.manifest; }, buildStart() { getState(this).reset(); }, generateBundle({ format }, bundle) { const state = getState(this); const { manifest } = state; const { root } = this.environment.config; const buildOptions = this.environment.config.build; function getChunkName(chunk) { return getChunkOriginalFileName(chunk, root, format) ?? `_` + path$d.basename(chunk.fileName); } function getInternalImports(imports) { const filteredImports = []; for (const file of imports) { if (bundle[file] === void 0) { continue; } filteredImports.push(getChunkName(bundle[file])); } return filteredImports; } function createChunk(chunk) { const manifestChunk = { file: chunk.fileName, name: chunk.name }; if (chunk.facadeModuleId) { manifestChunk.src = getChunkName(chunk); } if (chunk.isEntry) { manifestChunk.isEntry = true; } if (chunk.isDynamicEntry) { manifestChunk.isDynamicEntry = true; } if (chunk.imports.length) { const internalImports = getInternalImports(chunk.imports); if (internalImports.length > 0) { manifestChunk.imports = internalImports; } } if (chunk.dynamicImports.length) { const internalImports = getInternalImports(chunk.dynamicImports); if (internalImports.length > 0) { manifestChunk.dynamicImports = internalImports; } } if (chunk.viteMetadata?.importedCss.size) { manifestChunk.css = [...chunk.viteMetadata.importedCss]; } if (chunk.viteMetadata?.importedAssets.size) { manifestChunk.assets = [...chunk.viteMetadata.importedAssets]; } return manifestChunk; } function createAsset(asset, src, isEntry) { const manifestChunk = { file: asset.fileName, src }; if (isEntry) manifestChunk.isEntry = true; return manifestChunk; } const entryCssReferenceIds = cssEntriesMap.get(this.environment); const entryCssAssetFileNames = new Set(entryCssReferenceIds); for (const id of entryCssReferenceIds) { try { const fileName = this.getFileName(id); entryCssAssetFileNames.add(fileName); } catch { } } const fileNameToAsset = /* @__PURE__ */ new Map(); for (const file in bundle) { const chunk = bundle[file]; if (chunk.type === "chunk") { manifest[getChunkName(chunk)] = createChunk(chunk); } else if (chunk.type === "asset" && chunk.names.length > 0) { const src = chunk.originalFileNames.length > 0 ? chunk.originalFileNames[0] : "_" + path$d.basename(chunk.fileName); const isEntry = entryCssAssetFileNames.has(chunk.fileName); const asset = createAsset(chunk, src, isEntry); const file2 = manifest[src]?.file; if (!(file2 && endsWithJSRE.test(file2))) { manifest[src] = asset; fileNameToAsset.set(chunk.fileName, asset); } for (const originalFileName of chunk.originalFileNames.slice(1)) { const file3 = manifest[originalFileName]?.file; if (!(file3 && endsWithJSRE.test(file3))) { manifest[originalFileName] = asset; } } } } state.outputCount++; const output = buildOptions.rollupOptions?.output; const outputLength = Array.isArray(output) ? output.length : 1; if (state.outputCount >= outputLength) { this.emitFile({ fileName: typeof buildOptions.manifest === "string" ? buildOptions.manifest : ".vite/manifest.json", type: "asset", source: JSON.stringify(sortObjectKeys(manifest), void 0, 2) }); } } }; } function getChunkOriginalFileName(chunk, root, format) { if (chunk.facadeModuleId) { let name = normalizePath$3(path$d.relative(root, chunk.facadeModuleId)); if (format === "system" && !chunk.name.includes("-legacy")) { const ext = path$d.extname(name); const endPos = ext.length !== 0 ? -ext.length : void 0; name = name.slice(0, endPos) + `-legacy` + ext; } return name.replace(/\0/g, ""); } } const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/; const base64RE = /base64/i; const dataUriPrefix = `\0/@data-uri/`; function dataURIPlugin() { let resolved; return { name: "vite:data-uri", buildStart() { resolved = /* @__PURE__ */ new Map(); }, resolveId(id) { if (!id.trimStart().startsWith("data:")) { return; } const uri = new URL$3(id); if (uri.protocol !== "data:") { return; } const match = dataUriRE.exec(uri.pathname); if (!match) { return; } const [, mime, format, data] = match; if (mime !== "text/javascript") { throw new Error( `data URI with non-JavaScript mime type is not supported. If you're using legacy JavaScript MIME types (such as 'application/javascript'), please use 'text/javascript' instead.` ); } const base64 = format && base64RE.test(format.substring(1)); const content = base64 ? Buffer.from(data, "base64").toString("utf-8") : data; resolved.set(id, content); return dataUriPrefix + id; }, load(id) { if (id.startsWith(dataUriPrefix)) { return resolved.get(id.slice(dataUriPrefix.length)); } } }; } /* es-module-lexer 1.5.4 */ var ImportType;!function(A){A[A.Static=1]="Static",A[A.Dynamic=2]="Dynamic",A[A.ImportMeta=3]="ImportMeta",A[A.StaticSourcePhase=4]="StaticSourcePhase",A[A.DynamicSourcePhase=5]="DynamicSourcePhase";}(ImportType||(ImportType={}));const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$e(E,g="@"){if(!C)return init.then((()=>parse$e(E)));const I=E.length+1,w=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;w>0&&C.memory.grow(Math.ceil(w/65536));const K=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,K,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split("\n").length}:${C.e()-E.lastIndexOf("\n",C.e()-1)}`),{idx:C.e()});const D=[],o=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.it(),g=C.ai(),I=C.id(),w=C.ss(),K=C.se();let o;C.ip()&&(o=k(E.slice(-1===I?A-1:A,-1===I?Q+1:Q))),D.push({n:o,t:B,s:A,e:Q,ss:w,se:K,d:I,a:g});}for(;C.re();){const A=C.es(),Q=C.ee(),B=C.els(),g=C.ele(),I=E.slice(A,Q),w=I[0],K=B<0?void 0:E.slice(B,g),D=K?K[0]:"";o.push({s:A,e:Q,ls:B,le:g,n:'"'===w||"'"===w?k(I):I,ln:'"'===D||"'"===D?k(K):K});}function k(A){try{return (0, eval)(A)}catch(A){}}return [D,o,!!C.f(),!!C.ms()]}function Q(A,Q){const B=A.length;let C=0;for(;C>>8;}}function B(A,Q){const B=A.length;let C=0;for(;CA.charCodeAt(0))))).then(WebAssembly.instantiate).then((({exports:A})=>{C=A;}));var E; var convertSourceMap$1 = {}; (function (exports) { Object.defineProperty(exports, 'commentRegex', { get: function getCommentRegex () { // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg; } }); Object.defineProperty(exports, 'mapFileCommentRegex', { get: function getMapFileCommentRegex () { // Matches sourceMappingURL in either // or /* comment styles. return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg; } }); var decodeBase64; if (typeof Buffer !== 'undefined') { if (typeof Buffer.from === 'function') { decodeBase64 = decodeBase64WithBufferFrom; } else { decodeBase64 = decodeBase64WithNewBuffer; } } else { decodeBase64 = decodeBase64WithAtob; } function decodeBase64WithBufferFrom(base64) { return Buffer.from(base64, 'base64').toString(); } function decodeBase64WithNewBuffer(base64) { if (typeof value === 'number') { throw new TypeError('The value to decode must not be of type number.'); } return new Buffer(base64, 'base64').toString(); } function decodeBase64WithAtob(base64) { return decodeURIComponent(escape(atob(base64))); } function stripComment(sm) { return sm.split(',').pop(); } function readFromFileMap(sm, read) { var r = exports.mapFileCommentRegex.exec(sm); // for some odd reason //# .. captures in 1 and /* .. */ in 2 var filename = r[1] || r[2]; try { var sm = read(filename); if (sm != null && typeof sm.catch === 'function') { return sm.catch(throwError); } else { return sm; } } catch (e) { throwError(e); } function throwError(e) { throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack); } } function Converter (sm, opts) { opts = opts || {}; if (opts.hasComment) { sm = stripComment(sm); } if (opts.encoding === 'base64') { sm = decodeBase64(sm); } else if (opts.encoding === 'uri') { sm = decodeURIComponent(sm); } if (opts.isJSON || opts.encoding) { sm = JSON.parse(sm); } this.sourcemap = sm; } Converter.prototype.toJSON = function (space) { return JSON.stringify(this.sourcemap, null, space); }; if (typeof Buffer !== 'undefined') { if (typeof Buffer.from === 'function') { Converter.prototype.toBase64 = encodeBase64WithBufferFrom; } else { Converter.prototype.toBase64 = encodeBase64WithNewBuffer; } } else { Converter.prototype.toBase64 = encodeBase64WithBtoa; } function encodeBase64WithBufferFrom() { var json = this.toJSON(); return Buffer.from(json, 'utf8').toString('base64'); } function encodeBase64WithNewBuffer() { var json = this.toJSON(); if (typeof json === 'number') { throw new TypeError('The json to encode must not be of type number.'); } return new Buffer(json, 'utf8').toString('base64'); } function encodeBase64WithBtoa() { var json = this.toJSON(); return btoa(unescape(encodeURIComponent(json))); } Converter.prototype.toURI = function () { var json = this.toJSON(); return encodeURIComponent(json); }; Converter.prototype.toComment = function (options) { var encoding, content, data; if (options != null && options.encoding === 'uri') { encoding = ''; content = this.toURI(); } else { encoding = ';base64'; content = this.toBase64(); } data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content; return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; }; // returns copy instead of original Converter.prototype.toObject = function () { return JSON.parse(this.toJSON()); }; Converter.prototype.addProperty = function (key, value) { if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); return this.setProperty(key, value); }; Converter.prototype.setProperty = function (key, value) { this.sourcemap[key] = value; return this; }; Converter.prototype.getProperty = function (key) { return this.sourcemap[key]; }; exports.fromObject = function (obj) { return new Converter(obj); }; exports.fromJSON = function (json) { return new Converter(json, { isJSON: true }); }; exports.fromURI = function (uri) { return new Converter(uri, { encoding: 'uri' }); }; exports.fromBase64 = function (base64) { return new Converter(base64, { encoding: 'base64' }); }; exports.fromComment = function (comment) { var m, encoding; comment = comment .replace(/^\/\*/g, '//') .replace(/\*\/$/g, ''); m = exports.commentRegex.exec(comment); encoding = m && m[4] || 'uri'; return new Converter(comment, { encoding: encoding, hasComment: true }); }; function makeConverter(sm) { return new Converter(sm, { isJSON: true }); } exports.fromMapFileComment = function (comment, read) { if (typeof read === 'string') { throw new Error( 'String directory paths are no longer supported with `fromMapFileComment`\n' + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' ) } var sm = readFromFileMap(comment, read); if (sm != null && typeof sm.then === 'function') { return sm.then(makeConverter); } else { return makeConverter(sm); } }; // Finds last sourcemap comment in file or returns null if none was found exports.fromSource = function (content) { var m = content.match(exports.commentRegex); return m ? exports.fromComment(m.pop()) : null; }; // Finds last sourcemap comment in file or returns null if none was found exports.fromMapFileSource = function (content, read) { if (typeof read === 'string') { throw new Error( 'String directory paths are no longer supported with `fromMapFileSource`\n' + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' ) } var m = content.match(exports.mapFileCommentRegex); return m ? exports.fromMapFileComment(m.pop(), read) : null; }; exports.removeComments = function (src) { return src.replace(exports.commentRegex, ''); }; exports.removeMapFileComments = function (src) { return src.replace(exports.mapFileCommentRegex, ''); }; exports.generateMapFileComment = function (file, options) { var data = 'sourceMappingURL=' + file; return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; }; } (convertSourceMap$1)); var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs(convertSourceMap$1); const debug$g = createDebugger("vite:sourcemap", { onlyWhenFocused: true }); const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/; async function computeSourceRoute(map, file) { let sourceRoot; try { sourceRoot = await fsp.realpath( path$d.resolve(path$d.dirname(file), map.sourceRoot || "") ); } catch { } return sourceRoot; } async function injectSourcesContent(map, file, logger) { let sourceRootPromise; const missingSources = []; const sourcesContent = map.sourcesContent || []; const sourcesContentPromises = []; for (let index = 0; index < map.sources.length; index++) { const sourcePath = map.sources[index]; if (sourcesContent[index] == null && sourcePath && !virtualSourceRE.test(sourcePath)) { sourcesContentPromises.push( (async () => { sourceRootPromise ??= computeSourceRoute(map, file); const sourceRoot = await sourceRootPromise; let resolvedSourcePath = cleanUrl(decodeURI(sourcePath)); if (sourceRoot) { resolvedSourcePath = path$d.resolve(sourceRoot, resolvedSourcePath); } sourcesContent[index] = await fsp.readFile(resolvedSourcePath, "utf-8").catch(() => { missingSources.push(resolvedSourcePath); return null; }); })() ); } } await Promise.all(sourcesContentPromises); map.sourcesContent = sourcesContent; if (missingSources.length) { logger.warnOnce(`Sourcemap for "${file}" points to missing source files`); debug$g?.(`Missing sources: ` + missingSources.join(` `)); } } function genSourceMapUrl(map) { if (typeof map !== "string") { map = JSON.stringify(map); } return `data:application/json;base64,${Buffer.from(map).toString("base64")}`; } function getCodeWithSourcemap(type, code, map) { if (debug$g) { code += ` /*${JSON.stringify(map, null, 2).replace(/\*\//g, "*\\/")}*/ `; } if (type === "js") { code += ` //# sourceMappingURL=${genSourceMapUrl(map)}`; } else if (type === "css") { code += ` /*# sourceMappingURL=${genSourceMapUrl(map)} */`; } return code; } function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logger) { let { x_google_ignoreList } = map; if (x_google_ignoreList === void 0) { x_google_ignoreList = []; } for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) { const sourcePath = map.sources[sourcesIndex]; if (!sourcePath) continue; const ignoreList = sourcemapIgnoreList( path$d.isAbsolute(sourcePath) ? sourcePath : path$d.resolve(path$d.dirname(sourcemapPath), sourcePath), sourcemapPath ); if (logger && typeof ignoreList !== "boolean") { logger.warn("sourcemapIgnoreList function must return a boolean."); } if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) { x_google_ignoreList.push(sourcesIndex); } } if (x_google_ignoreList.length > 0) { if (!map.x_google_ignoreList) map.x_google_ignoreList = x_google_ignoreList; } } async function extractSourcemapFromFile(code, filePath) { const map = (convertSourceMap.fromSource(code) || await convertSourceMap.fromMapFileSource( code, createConvertSourceMapReadMap(filePath) ))?.toObject(); if (map) { return { code: code.replace(convertSourceMap.mapFileCommentRegex, blankReplacer), map }; } } function createConvertSourceMapReadMap(originalFileName) { return (filename) => { return fsp.readFile( path$d.resolve(path$d.dirname(originalFileName), filename), "utf-8" ); }; } var src$2 = {}; // @ts-check const path$b = require$$0$2; const fs$7 = require$$0$3; const os$2 = require$$2; const fsReadFileAsync = fs$7.promises.readFile; /** @type {(name: string, sync: boolean) => string[]} */ function getDefaultSearchPlaces(name, sync) { return [ 'package.json', `.${name}rc.json`, `.${name}rc.js`, `.${name}rc.cjs`, ...(sync ? [] : [`.${name}rc.mjs`]), `.config/${name}rc`, `.config/${name}rc.json`, `.config/${name}rc.js`, `.config/${name}rc.cjs`, ...(sync ? [] : [`.config/${name}rc.mjs`]), `${name}.config.js`, `${name}.config.cjs`, ...(sync ? [] : [`${name}.config.mjs`]), ]; } /** * @type {(p: string) => string} * * see #17 * On *nix, if cwd is not under homedir, * the last path will be '', ('/build' -> '') * but it should be '/' actually. * And on Windows, this will never happen. ('C:\build' -> 'C:') */ function parentDir(p) { return path$b.dirname(p) || path$b.sep; } /** @type {import('./index').LoaderSync} */ const jsonLoader = (_, content) => JSON.parse(content); // Use plain require in webpack context for dynamic import const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require; /** @type {import('./index').LoadersSync} */ const defaultLoadersSync = Object.freeze({ '.js': requireFunc, '.json': requireFunc, '.cjs': requireFunc, noExt: jsonLoader, }); src$2.defaultLoadersSync = defaultLoadersSync; /** @type {import('./index').Loader} */ const dynamicImport = async id => { try { const mod = await import(/* webpackIgnore: true */ id); return mod.default; } catch (e) { try { return requireFunc(id); } catch (/** @type {any} */ requireE) { if ( requireE.code === 'ERR_REQUIRE_ESM' || (requireE instanceof SyntaxError && requireE .toString() .includes('Cannot use import statement outside a module')) ) { throw e; } throw requireE; } } }; /** @type {import('./index').Loaders} */ const defaultLoaders = Object.freeze({ '.js': dynamicImport, '.mjs': dynamicImport, '.cjs': dynamicImport, '.json': jsonLoader, noExt: jsonLoader, }); src$2.defaultLoaders = defaultLoaders; /** * @param {string} name * @param {import('./index').Options | import('./index').OptionsSync} options * @param {boolean} sync * @returns {Required} */ function getOptions(name, options, sync) { /** @type {Required} */ const conf = { stopDir: os$2.homedir(), searchPlaces: getDefaultSearchPlaces(name, sync), ignoreEmptySearchPlaces: true, cache: true, transform: x => x, packageProp: [name], ...options, loaders: { ...(sync ? defaultLoadersSync : defaultLoaders), ...options.loaders, }, }; conf.searchPlaces.forEach(place => { const key = path$b.extname(place) || 'noExt'; const loader = conf.loaders[key]; if (!loader) { throw new Error(`Missing loader for extension "${place}"`); } if (typeof loader !== 'function') { throw new Error( `Loader for extension "${place}" is not a function: Received ${typeof loader}.`, ); } }); return conf; } /** @type {(props: string | string[], obj: Record) => unknown} */ function getPackageProp(props, obj) { if (typeof props === 'string' && props in obj) return obj[props]; return ( (Array.isArray(props) ? props : props.split('.')).reduce( (acc, prop) => (acc === undefined ? acc : acc[prop]), obj, ) || null ); } /** @param {string} filepath */ function validateFilePath(filepath) { if (!filepath) throw new Error('load must pass a non-empty string'); } /** @type {(loader: import('./index').Loader, ext: string) => void} */ function validateLoader(loader, ext) { if (!loader) throw new Error(`No loader specified for extension "${ext}"`); if (typeof loader !== 'function') throw new Error('loader is not a function'); } /** @type {(enableCache: boolean) => (c: Map, filepath: string, res: T) => T} */ const makeEmplace = enableCache => (c, filepath, res) => { if (enableCache) c.set(filepath, res); return res; }; /** @type {import('./index').lilconfig} */ src$2.lilconfig = function lilconfig(name, options) { const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache, } = getOptions(name, options ?? {}, false); const searchCache = new Map(); const loadCache = new Map(); const emplace = makeEmplace(cache); return { async search(searchFrom = process.cwd()) { /** @type {import('./index').LilconfigResult} */ const result = { config: null, filepath: '', }; /** @type {Set} */ const visited = new Set(); let dir = searchFrom; dirLoop: while (true) { if (cache) { const r = searchCache.get(dir); if (r !== undefined) { for (const p of visited) searchCache.set(p, r); return r; } visited.add(dir); } for (const searchPlace of searchPlaces) { const filepath = path$b.join(dir, searchPlace); try { await fs$7.promises.access(filepath); } catch { continue; } const content = String(await fsReadFileAsync(filepath)); const loaderKey = path$b.extname(searchPlace) || 'noExt'; const loader = loaders[loaderKey]; // handle package.json if (searchPlace === 'package.json') { const pkg = await loader(filepath, content); const maybeConfig = getPackageProp(packageProp, pkg); if (maybeConfig != null) { result.config = maybeConfig; result.filepath = filepath; break dirLoop; } continue; } // handle other type of configs const isEmpty = content.trim() === ''; if (isEmpty && ignoreEmptySearchPlaces) continue; if (isEmpty) { result.isEmpty = true; result.config = undefined; } else { validateLoader(loader, loaderKey); result.config = await loader(filepath, content); } result.filepath = filepath; break dirLoop; } if (dir === stopDir || dir === parentDir(dir)) break dirLoop; dir = parentDir(dir); } const transformed = // not found result.filepath === '' && result.config === null ? transform(null) : transform(result); if (cache) { for (const p of visited) searchCache.set(p, transformed); } return transformed; }, async load(filepath) { validateFilePath(filepath); const absPath = path$b.resolve(process.cwd(), filepath); if (cache && loadCache.has(absPath)) { return loadCache.get(absPath); } const {base, ext} = path$b.parse(absPath); const loaderKey = ext || 'noExt'; const loader = loaders[loaderKey]; validateLoader(loader, loaderKey); const content = String(await fsReadFileAsync(absPath)); if (base === 'package.json') { const pkg = await loader(absPath, content); return emplace( loadCache, absPath, transform({ config: getPackageProp(packageProp, pkg), filepath: absPath, }), ); } /** @type {import('./index').LilconfigResult} */ const result = { config: null, filepath: absPath, }; // handle other type of configs const isEmpty = content.trim() === ''; if (isEmpty && ignoreEmptySearchPlaces) return emplace( loadCache, absPath, transform({ config: undefined, filepath: absPath, isEmpty: true, }), ); // cosmiconfig returns undefined for empty files result.config = isEmpty ? undefined : await loader(absPath, content); return emplace( loadCache, absPath, transform(isEmpty ? {...result, isEmpty, config: undefined} : result), ); }, clearLoadCache() { if (cache) loadCache.clear(); }, clearSearchCache() { if (cache) searchCache.clear(); }, clearCaches() { if (cache) { loadCache.clear(); searchCache.clear(); } }, }; }; /** @type {import('./index').lilconfigSync} */ src$2.lilconfigSync = function lilconfigSync(name, options) { const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache, } = getOptions(name, options ?? {}, true); const searchCache = new Map(); const loadCache = new Map(); const emplace = makeEmplace(cache); return { search(searchFrom = process.cwd()) { /** @type {import('./index').LilconfigResult} */ const result = { config: null, filepath: '', }; /** @type {Set} */ const visited = new Set(); let dir = searchFrom; dirLoop: while (true) { if (cache) { const r = searchCache.get(dir); if (r !== undefined) { for (const p of visited) searchCache.set(p, r); return r; } visited.add(dir); } for (const searchPlace of searchPlaces) { const filepath = path$b.join(dir, searchPlace); try { fs$7.accessSync(filepath); } catch { continue; } const loaderKey = path$b.extname(searchPlace) || 'noExt'; const loader = loaders[loaderKey]; const content = String(fs$7.readFileSync(filepath)); // handle package.json if (searchPlace === 'package.json') { const pkg = loader(filepath, content); const maybeConfig = getPackageProp(packageProp, pkg); if (maybeConfig != null) { result.config = maybeConfig; result.filepath = filepath; break dirLoop; } continue; } // handle other type of configs const isEmpty = content.trim() === ''; if (isEmpty && ignoreEmptySearchPlaces) continue; if (isEmpty) { result.isEmpty = true; result.config = undefined; } else { validateLoader(loader, loaderKey); result.config = loader(filepath, content); } result.filepath = filepath; break dirLoop; } if (dir === stopDir || dir === parentDir(dir)) break dirLoop; dir = parentDir(dir); } const transformed = // not found result.filepath === '' && result.config === null ? transform(null) : transform(result); if (cache) { for (const p of visited) searchCache.set(p, transformed); } return transformed; }, load(filepath) { validateFilePath(filepath); const absPath = path$b.resolve(process.cwd(), filepath); if (cache && loadCache.has(absPath)) { return loadCache.get(absPath); } const {base, ext} = path$b.parse(absPath); const loaderKey = ext || 'noExt'; const loader = loaders[loaderKey]; validateLoader(loader, loaderKey); const content = String(fs$7.readFileSync(absPath)); if (base === 'package.json') { const pkg = loader(absPath, content); return transform({ config: getPackageProp(packageProp, pkg), filepath: absPath, }); } const result = { config: null, filepath: absPath, }; // handle other type of configs const isEmpty = content.trim() === ''; if (isEmpty && ignoreEmptySearchPlaces) return emplace( loadCache, absPath, transform({ filepath: absPath, config: undefined, isEmpty: true, }), ); // cosmiconfig returns undefined for empty files result.config = isEmpty ? undefined : loader(absPath, content); return emplace( loadCache, absPath, transform(isEmpty ? {...result, isEmpty, config: undefined} : result), ); }, clearLoadCache() { if (cache) loadCache.clear(); }, clearSearchCache() { if (cache) searchCache.clear(); }, clearCaches() { if (cache) { loadCache.clear(); searchCache.clear(); } }, }; }; // @ts-check const { createRequire } = require$$0$5; const { fileURLToPath, pathToFileURL } = require$$1$1; const TS_EXT_RE = /\.[mc]?ts$/; let tsx; let jiti; let importError = []; /** * @param {string} name * @param {string} rootFile * @returns {Promise} */ async function req$3(name, rootFile = fileURLToPath(import.meta.url)) { let url = createRequire(rootFile).resolve(name); try { return (await import(`${pathToFileURL(url)}?t=${Date.now()}`)).default } catch (err) { if (!TS_EXT_RE.test(url)) { /* c8 ignore start */ throw err } } if (tsx === undefined) { try { tsx = await import('tsx/cjs/api'); } catch (error) { importError.push(error); } } if (tsx) { let loaded = tsx.require(name, rootFile); return loaded && '__esModule' in loaded ? loaded.default : loaded } if (jiti === undefined) { try { jiti = (await import('jiti')).default; } catch (error) { importError.push(error); } } if (jiti) { return jiti(rootFile, { interopDefault: true })(name) } throw new Error( `'tsx' or 'jiti' is required for the TypeScript configuration files. Make sure it is installed\nError: ${importError .map(error => error.message) .join('\n')}` ) } var req_1 = req$3; // @ts-check const req$2 = req_1; /** * Load Options * * @private * @method options * * @param {Object} config PostCSS Config * * @return {Promise} options PostCSS Options */ async function options(config, file) { if (config.parser && typeof config.parser === 'string') { try { config.parser = await req$2(config.parser, file); } catch (err) { throw new Error( `Loading PostCSS Parser failed: ${err.message}\n\n(@${file})` ) } } if (config.syntax && typeof config.syntax === 'string') { try { config.syntax = await req$2(config.syntax, file); } catch (err) { throw new Error( `Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})` ) } } if (config.stringifier && typeof config.stringifier === 'string') { try { config.stringifier = await req$2(config.stringifier, file); } catch (err) { throw new Error( `Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})` ) } } return config } var options_1 = options; // @ts-check const req$1 = req_1; /** * Plugin Loader * * @private * @method load * * @param {String} plugin PostCSS Plugin Name * @param {Object} options PostCSS Plugin Options * * @return {Promise} PostCSS Plugin */ async function load(plugin, options, file) { try { if ( options === null || options === undefined || Object.keys(options).length === 0 ) { return await req$1(plugin, file) } else { return (await req$1(plugin, file))(options) /* c8 ignore next */ } } catch (err) { throw new Error( `Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})` ) } } /** * Load Plugins * * @private * @method plugins * * @param {Object} config PostCSS Config Plugins * * @return {Promise} plugins PostCSS Plugins */ async function plugins(config, file) { let list = []; if (Array.isArray(config.plugins)) { list = config.plugins.filter(Boolean); } else { list = Object.entries(config.plugins) .filter(([, options]) => { return options !== false }) .map(([plugin, options]) => { return load(plugin, options, file) }); list = await Promise.all(list); } if (list.length && list.length > 0) { list.forEach((plugin, i) => { if (plugin.default) { plugin = plugin.default; } if (plugin.postcss === true) { plugin = plugin(); } else if (plugin.postcss) { plugin = plugin.postcss; } if ( !( (typeof plugin === 'object' && Array.isArray(plugin.plugins)) || (typeof plugin === 'object' && plugin.postcssPlugin) || typeof plugin === 'function' ) ) { throw new TypeError( `Invalid PostCSS Plugin found at: plugins[${i}]\n\n(@${file})` ) } }); } return list } var plugins_1 = plugins; // @ts-check const { resolve } = path$d; const config$1 = src$2; const loadOptions = options_1; const loadPlugins = plugins_1; const req = req_1; const interopRequireDefault = obj => obj && obj.__esModule ? obj : { default: obj }; /** * Process the result from cosmiconfig * * @param {Object} ctx Config Context * @param {Object} result Cosmiconfig result * * @return {Promise} PostCSS Config */ async function processResult(ctx, result) { let file = result.filepath || ''; let projectConfig = interopRequireDefault(result.config).default || {}; if (typeof projectConfig === 'function') { projectConfig = projectConfig(ctx); } else { projectConfig = Object.assign({}, projectConfig, ctx); } if (!projectConfig.plugins) { projectConfig.plugins = []; } let res = { file, options: await loadOptions(projectConfig, file), plugins: await loadPlugins(projectConfig, file) }; delete projectConfig.plugins; return res } /** * Builds the Config Context * * @param {Object} ctx Config Context * * @return {Object} Config Context */ function createContext(ctx) { /** * @type {Object} * * @prop {String} cwd=process.cwd() Config search start location * @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined` */ ctx = Object.assign( { cwd: process.cwd(), env: process.env.NODE_ENV }, ctx ); if (!ctx.env) { process.env.NODE_ENV = 'development'; } return ctx } async function loader(filepath) { return req(filepath) } let yaml; async function yamlLoader(_, content) { if (!yaml) { try { yaml = await import('yaml'); } catch (e) { /* c8 ignore start */ throw new Error( `'yaml' is required for the YAML configuration files. Make sure it is installed\nError: ${e.message}` ) } } return yaml.parse(content); } /** @return {import('lilconfig').Options} */ const withLoaders = (options = {}) => { let moduleName = 'postcss'; return { ...options, loaders: { ...options.loaders, '.cjs': loader, '.cts': loader, '.js': loader, '.mjs': loader, '.mts': loader, '.ts': loader, '.yaml': yamlLoader, '.yml': yamlLoader }, searchPlaces: [ ...(options.searchPlaces || []), 'package.json', `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.${moduleName}rc.ts`, `.${moduleName}rc.cts`, `.${moduleName}rc.mts`, `.${moduleName}rc.js`, `.${moduleName}rc.cjs`, `.${moduleName}rc.mjs`, `${moduleName}.config.ts`, `${moduleName}.config.cts`, `${moduleName}.config.mts`, `${moduleName}.config.js`, `${moduleName}.config.cjs`, `${moduleName}.config.mjs` ] } }; /** * Load Config * * @method rc * * @param {Object} ctx Config Context * @param {String} path Config Path * @param {Object} options Config Options * * @return {Promise} config PostCSS Config */ function rc(ctx, path, options) { /** * @type {Object} The full Config Context */ ctx = createContext(ctx); /** * @type {String} `process.cwd()` */ path = path ? resolve(path) : process.cwd(); return config$1 .lilconfig('postcss', withLoaders(options)) .search(path) .then(result => { if (!result) { throw new Error(`No PostCSS Config found in: ${path}`) } return processResult(ctx, result) }) } /** * Autoload Config for PostCSS * * @author Michael Ciniawsky @michael-ciniawsky * @license MIT * * @module postcss-load-config * @version 2.1.0 * * @requires comsiconfig * @requires ./options * @requires ./plugins */ var src$1 = rc; var postcssrc = /*@__PURE__*/getDefaultExportFromCjs(src$1); // src/index.ts var ESCAPED_WIN32_BACKSLASHES = /\\(?![()[\]{}!+@])/g; function convertPosixPathToPattern(path2) { return escapePosixPath(path2); } function convertWin32PathToPattern(path2) { return escapeWin32Path(path2).replace(ESCAPED_WIN32_BACKSLASHES, "/"); } process.platform === "win32" ? convertWin32PathToPattern : convertPosixPathToPattern; var POSIX_UNESCAPED_GLOB_SYMBOLS = /(? path2.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&"); var escapeWin32Path = (path2) => path2.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&"); var escapePath = process.platform === "win32" ? escapeWin32Path : escapePosixPath; function isDynamicPattern(pattern, options) { const scan = picomatch$5.scan(pattern); return scan.isGlob || scan.negated; } // src/index.ts function normalizePattern(pattern, expandDirectories, cwd, properties, isIgnore) { var _a; let result = pattern; if (pattern.endsWith("/")) { result = pattern.slice(0, -1); } if (!result.endsWith("*") && expandDirectories) { result += "/**"; } if (require$$0$2.isAbsolute(result.replace(/\\(?=[()[\]{}!*+?@|])/g, ""))) { result = posix.relative(cwd, result); } else { result = posix.normalize(result); } const parentDirectoryMatch = /^(\/?\.\.)+/.exec(result); if (parentDirectoryMatch == null ? void 0 : parentDirectoryMatch[0]) { const potentialRoot = posix.join(cwd, parentDirectoryMatch[0]); if (properties.root.length > potentialRoot.length) { properties.root = potentialRoot; properties.depthOffset = -(parentDirectoryMatch[0].length + 1) / 3; } } else if (!isIgnore && properties.depthOffset >= 0) { const current = result.split("/"); (_a = properties.commonPath) != null ? _a : properties.commonPath = current; const newCommonPath = []; for (let i = 0; i < Math.min(properties.commonPath.length, current.length); i++) { const part = current[i]; if (part === "**" && !current[i + 1]) { newCommonPath.pop(); break; } if (part !== properties.commonPath[i] || isDynamicPattern(part) || i === current.length - 1) { break; } newCommonPath.push(part); } properties.depthOffset = newCommonPath.length; properties.commonPath = newCommonPath; properties.root = newCommonPath.length > 0 ? `${cwd}/${newCommonPath.join("/")}` : cwd; } return result; } function processPatterns({ patterns, ignore = [], expandDirectories = true }, cwd, properties) { if (typeof patterns === "string") { patterns = [patterns]; } else if (!patterns) { patterns = ["**/*"]; } if (typeof ignore === "string") { ignore = [ignore]; } const matchPatterns = []; const ignorePatterns = []; for (const pattern of ignore) { if (!pattern.startsWith("!") || pattern[1] === "(") { const newPattern = normalizePattern(pattern, expandDirectories, cwd, properties, true); ignorePatterns.push(newPattern); } } for (const pattern of patterns) { if (!pattern.startsWith("!") || pattern[1] === "(") { const newPattern = normalizePattern(pattern, expandDirectories, cwd, properties, false); matchPatterns.push(newPattern); } else if (pattern[1] !== "!" || pattern[2] === "(") { const newPattern = normalizePattern(pattern.slice(1), expandDirectories, cwd, properties, true); ignorePatterns.push(newPattern); } } return { match: matchPatterns, ignore: ignorePatterns }; } function getRelativePath(path2, cwd, root) { return posix.relative(cwd, `${root}/${path2}`); } function processPath(path2, cwd, root, isDirectory, absolute) { const relativePath = absolute ? path2.slice(root.length + 1) || "." : path2; if (root === cwd) { return isDirectory && relativePath !== "." ? relativePath.slice(0, -1) : relativePath; } return getRelativePath(relativePath, cwd, root); } function crawl(options, cwd, sync) { const properties = { root: cwd, commonPath: null, depthOffset: 0 }; const processed = processPatterns(options, cwd, properties); const matcher = picomatch$5(processed.match, { dot: options.dot, nocase: options.caseSensitiveMatch === false, ignore: processed.ignore }); const exclude = picomatch$5(processed.ignore, { dot: options.dot, nocase: options.caseSensitiveMatch === false }); const fdirOptions = { // use relative paths in the matcher filters: [(p, isDirectory) => matcher(processPath(p, cwd, properties.root, isDirectory, options.absolute))], exclude: (_, p) => exclude(processPath(p, cwd, properties.root, true, true)), pathSeparator: "/", relativePaths: true, resolveSymlinks: true }; if (options.deep) { fdirOptions.maxDepth = Math.round(options.deep - properties.depthOffset); } if (options.absolute) { fdirOptions.relativePaths = false; fdirOptions.resolvePaths = true; fdirOptions.includeBasePath = true; } if (options.followSymbolicLinks === false) { fdirOptions.resolveSymlinks = false; fdirOptions.excludeSymlinks = true; } if (options.onlyDirectories) { fdirOptions.excludeFiles = true; fdirOptions.includeDirs = true; } else if (options.onlyFiles === false) { fdirOptions.includeDirs = true; } properties.root = properties.root.replace(/\\/g, ""); const api = new dist.fdir(fdirOptions).crawl(properties.root); if (cwd === properties.root || options.absolute) { return sync ? api.sync() : api.withPromise(); } return sync ? api.sync().map((p) => getRelativePath(p, cwd, properties.root) + (!p || p.endsWith("/") ? "/" : "")) : api.withPromise().then((paths) => paths.map((p) => getRelativePath(p, cwd, properties.root) + (!p || p.endsWith("/") ? "/" : ""))); } async function glob(patternsOrOptions, options) { if (patternsOrOptions && (options == null ? void 0 : options.patterns)) { throw new Error("Cannot pass patterns as both an argument and an option"); } const opts = Array.isArray(patternsOrOptions) || typeof patternsOrOptions === "string" ? { ...options, patterns: patternsOrOptions } : patternsOrOptions; const cwd = opts.cwd ? require$$0$2.resolve(opts.cwd).replace(/\\/g, "/") : process.cwd().replace(/\\/g, "/"); return crawl(opts, cwd, false); } function globSync(patternsOrOptions, options) { if (patternsOrOptions && (options == null ? void 0 : options.patterns)) { throw new Error("Cannot pass patterns as both an argument and an option"); } const opts = Array.isArray(patternsOrOptions) || typeof patternsOrOptions === "string" ? { ...options, patterns: patternsOrOptions } : patternsOrOptions; const cwd = opts.cwd ? require$$0$2.resolve(opts.cwd).replace(/\\/g, "/") : process.cwd().replace(/\\/g, "/"); return crawl(opts, cwd, true); } function matches$1(pattern, importee) { if (pattern instanceof RegExp) { return pattern.test(importee); } if (importee.length < pattern.length) { return false; } if (importee === pattern) { return true; } // eslint-disable-next-line prefer-template return importee.startsWith(pattern + '/'); } function getEntries({ entries, customResolver }) { if (!entries) { return []; } const resolverFunctionFromOptions = resolveCustomResolver(customResolver); if (Array.isArray(entries)) { return entries.map((entry) => { return { find: entry.find, replacement: entry.replacement, resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions }; }); } return Object.entries(entries).map(([key, value]) => { return { find: key, replacement: value, resolverFunction: resolverFunctionFromOptions }; }); } function getHookFunction(hook) { if (typeof hook === 'function') { return hook; } if (hook && 'handler' in hook && typeof hook.handler === 'function') { return hook.handler; } return null; } function resolveCustomResolver(customResolver) { if (typeof customResolver === 'function') { return customResolver; } if (customResolver) { return getHookFunction(customResolver.resolveId); } return null; } function alias$1(options = {}) { const entries = getEntries(options); if (entries.length === 0) { return { name: 'alias', resolveId: () => null }; } return { name: 'alias', async buildStart(inputOptions) { await Promise.all([...(Array.isArray(options.entries) ? options.entries : []), options].map(({ customResolver }) => { var _a; return customResolver && ((_a = getHookFunction(customResolver.buildStart)) === null || _a === void 0 ? void 0 : _a.call(this, inputOptions)); })); }, resolveId(importee, importer, resolveOptions) { // First match is supposed to be the correct one const matchedEntry = entries.find((entry) => matches$1(entry.find, importee)); if (!matchedEntry) { return null; } const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement); if (matchedEntry.resolverFunction) { return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions); } return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => { if (resolved) return resolved; if (!require$$0$2.isAbsolute(updatedId)) { this.warn(`rewrote ${importee} to ${updatedId} but was not an abolute path and was not handled by other plugins. ` + `This will lead to duplicated modules for the same path. ` + `To avoid duplicating modules, you should resolve to an absolute path.`); } return { id: updatedId }; }); } }; } function e(e,n,r){throw new Error(r?`No known conditions for "${n}" specifier in "${e}" package`:`Missing "${n}" specifier in "${e}" package`)}function n(n,i,o,f){let s,u,l=r(n,o),c=function(e){let n=new Set(["default",...e.conditions||[]]);return e.unsafe||n.add(e.require?"require":"import"),e.unsafe||n.add(e.browser?"browser":"node"),n}(f||{}),a=i[l];if(void 0===a){let e,n,r,t;for(t in i)n&&t.length1&&(r=t.indexOf("*",1),~r&&(e=RegExp("^"+t.substring(0,r)+"(.*)"+t.substring(1+r)).exec(l),e&&e[1]&&(u=e[1],n=t))));a=i[n];}return a||e(n,l),s=t(a,c),s||e(n,l,1),u&&function(e,n){let r,t=0,i=e.length,o=/[*]/g,f=/[/]$/;for(;t `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&"); } return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`; } function stringifyQuery(query) { return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&"); } new Set(builtinModules); function clearImports(imports) { return (imports || "").replace(/(\/\/[^\n]*\n|\/\*.*\*\/)/g, "").replace(/\s+/g, " "); } function getImportNames(cleanedImports) { const topLevelImports = cleanedImports.replace(/{([^}]*)}/, ""); const namespacedImport = topLevelImports.match(/\* as \s*(\S*)/)?.[1]; const defaultImport = topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0; return { namespacedImport, defaultImport }; } /** * @typedef ErrnoExceptionFields * @property {number | undefined} [errnode] * @property {string | undefined} [code] * @property {string | undefined} [path] * @property {string | undefined} [syscall] * @property {string | undefined} [url] * * @typedef {Error & ErrnoExceptionFields} ErrnoException */ const own$1 = {}.hasOwnProperty; const classRegExp = /^([A-Z][a-z\d]*)+$/; // Sorted by a rough estimate on most frequently used entries. const kTypes = new Set([ 'string', 'function', 'number', 'object', // Accept 'Function' and 'Object' as alternative to the lower cased version. 'Function', 'Object', 'boolean', 'bigint', 'symbol' ]); /** * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'. * We cannot use Intl.ListFormat because it's not available in * --without-intl builds. * * @param {Array} array * An array of strings. * @param {string} [type] * The list type to be inserted before the last element. * @returns {string} */ function formatList(array, type = 'and') { return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}` } /** @type {Map} */ const messages = new Map(); const nodeInternalPrefix = '__node_internal_'; /** @type {number} */ let userStackTraceLimit; createError( 'ERR_INVALID_ARG_TYPE', /** * @param {string} name * @param {Array | string} expected * @param {unknown} actual */ (name, expected, actual) => { assert$1(typeof name === 'string', "'name' must be a string"); if (!Array.isArray(expected)) { expected = [expected]; } let message = 'The '; if (name.endsWith(' argument')) { // For cases like 'first argument' message += `${name} `; } else { const type = name.includes('.') ? 'property' : 'argument'; message += `"${name}" ${type} `; } message += 'must be '; /** @type {Array} */ const types = []; /** @type {Array} */ const instances = []; /** @type {Array} */ const other = []; for (const value of expected) { assert$1( typeof value === 'string', 'All expected entries have to be of type string' ); if (kTypes.has(value)) { types.push(value.toLowerCase()); } else if (classRegExp.exec(value) === null) { assert$1( value !== 'object', 'The value "object" should be written as "Object"' ); other.push(value); } else { instances.push(value); } } // Special handle `object` in case other instances are allowed to outline // the differences between each other. if (instances.length > 0) { const pos = types.indexOf('object'); if (pos !== -1) { types.slice(pos, 1); instances.push('Object'); } } if (types.length > 0) { message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList( types, 'or' )}`; if (instances.length > 0 || other.length > 0) message += ' or '; } if (instances.length > 0) { message += `an instance of ${formatList(instances, 'or')}`; if (other.length > 0) message += ' or '; } if (other.length > 0) { if (other.length > 1) { message += `one of ${formatList(other, 'or')}`; } else { if (other[0].toLowerCase() !== other[0]) message += 'an '; message += `${other[0]}`; } } message += `. Received ${determineSpecificType(actual)}`; return message }, TypeError ); createError( 'ERR_INVALID_MODULE_SPECIFIER', /** * @param {string} request * @param {string} reason * @param {string} [base] */ (request, reason, base = undefined) => { return `Invalid module "${request}" ${reason}${ base ? ` imported from ${base}` : '' }` }, TypeError ); createError( 'ERR_INVALID_PACKAGE_CONFIG', /** * @param {string} path * @param {string} [base] * @param {string} [message] */ (path, base, message) => { return `Invalid package config ${path}${ base ? ` while importing ${base}` : '' }${message ? `. ${message}` : ''}` }, Error ); createError( 'ERR_INVALID_PACKAGE_TARGET', /** * @param {string} packagePath * @param {string} key * @param {unknown} target * @param {boolean} [isImport=false] * @param {string} [base] */ (packagePath, key, target, isImport = false, base = undefined) => { const relatedError = typeof target === 'string' && !isImport && target.length > 0 && !target.startsWith('./'); if (key === '.') { assert$1(isImport === false); return ( `Invalid "exports" main target ${JSON.stringify(target)} defined ` + `in the package config ${packagePath}package.json${ base ? ` imported from ${base}` : '' }${relatedError ? '; targets must start with "./"' : ''}` ) } return `Invalid "${ isImport ? 'imports' : 'exports' }" target ${JSON.stringify( target )} defined for '${key}' in the package config ${packagePath}package.json${ base ? ` imported from ${base}` : '' }${relatedError ? '; targets must start with "./"' : ''}` }, Error ); createError( 'ERR_MODULE_NOT_FOUND', /** * @param {string} path * @param {string} base * @param {boolean} [exactUrl] */ (path, base, exactUrl = false) => { return `Cannot find ${ exactUrl ? 'module' : 'package' } '${path}' imported from ${base}` }, Error ); createError( 'ERR_NETWORK_IMPORT_DISALLOWED', "import of '%s' by %s is not supported: %s", Error ); createError( 'ERR_PACKAGE_IMPORT_NOT_DEFINED', /** * @param {string} specifier * @param {string} packagePath * @param {string} base */ (specifier, packagePath, base) => { return `Package import specifier "${specifier}" is not defined${ packagePath ? ` in package ${packagePath}package.json` : '' } imported from ${base}` }, TypeError ); createError( 'ERR_PACKAGE_PATH_NOT_EXPORTED', /** * @param {string} packagePath * @param {string} subpath * @param {string} [base] */ (packagePath, subpath, base = undefined) => { if (subpath === '.') return `No "exports" main defined in ${packagePath}package.json${ base ? ` imported from ${base}` : '' }` return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${ base ? ` imported from ${base}` : '' }` }, Error ); createError( 'ERR_UNSUPPORTED_DIR_IMPORT', "Directory import '%s' is not supported " + 'resolving ES modules imported from %s', Error ); createError( 'ERR_UNSUPPORTED_RESOLVE_REQUEST', 'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.', TypeError ); createError( 'ERR_UNKNOWN_FILE_EXTENSION', /** * @param {string} extension * @param {string} path */ (extension, path) => { return `Unknown file extension "${extension}" for ${path}` }, TypeError ); createError( 'ERR_INVALID_ARG_VALUE', /** * @param {string} name * @param {unknown} value * @param {string} [reason='is invalid'] */ (name, value, reason = 'is invalid') => { let inspected = inspect(value); if (inspected.length > 128) { inspected = `${inspected.slice(0, 128)}...`; } const type = name.includes('.') ? 'property' : 'argument'; return `The ${type} '${name}' ${reason}. Received ${inspected}` }, TypeError // Note: extra classes have been shaken out. // , RangeError ); /** * Utility function for registering the error codes. Only used here. Exported * *only* to allow for testing. * @param {string} sym * @param {MessageFunction | string} value * @param {ErrorConstructor} constructor * @returns {new (...parameters: Array) => Error} */ function createError(sym, value, constructor) { // Special case for SystemError that formats the error message differently // The SystemErrors only have SystemError as their base classes. messages.set(sym, value); return makeNodeErrorWithCode(constructor, sym) } /** * @param {ErrorConstructor} Base * @param {string} key * @returns {ErrorConstructor} */ function makeNodeErrorWithCode(Base, key) { // @ts-expect-error It’s a Node error. return NodeError /** * @param {Array} parameters */ function NodeError(...parameters) { const limit = Error.stackTraceLimit; if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0; const error = new Base(); // Reset the limit and setting the name property. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit; const message = getMessage(key, parameters, error); Object.defineProperties(error, { // Note: no need to implement `kIsNodeError` symbol, would be hard, // probably. message: { value: message, enumerable: false, writable: true, configurable: true }, toString: { /** @this {Error} */ value() { return `${this.name} [${key}]: ${this.message}` }, enumerable: false, writable: true, configurable: true } }); captureLargerStackTrace(error); // @ts-expect-error It’s a Node error. error.code = key; return error } } /** * @returns {boolean} */ function isErrorStackTraceLimitWritable() { // Do no touch Error.stackTraceLimit as V8 would attempt to install // it again during deserialization. try { if (v8.startupSnapshot.isBuildingSnapshot()) { return false } } catch {} const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit'); if (desc === undefined) { return Object.isExtensible(Error) } return own$1.call(desc, 'writable') && desc.writable !== undefined ? desc.writable : desc.set !== undefined } /** * This function removes unnecessary frames from Node.js core errors. * @template {(...parameters: unknown[]) => unknown} T * @param {T} wrappedFunction * @returns {T} */ function hideStackFrames(wrappedFunction) { // We rename the functions that will be hidden to cut off the stacktrace // at the outermost one const hidden = nodeInternalPrefix + wrappedFunction.name; Object.defineProperty(wrappedFunction, 'name', {value: hidden}); return wrappedFunction } const captureLargerStackTrace = hideStackFrames( /** * @param {Error} error * @returns {Error} */ // @ts-expect-error: fine function (error) { const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable(); if (stackTraceLimitIsWritable) { userStackTraceLimit = Error.stackTraceLimit; Error.stackTraceLimit = Number.POSITIVE_INFINITY; } Error.captureStackTrace(error); // Reset the limit if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit; return error } ); /** * @param {string} key * @param {Array} parameters * @param {Error} self * @returns {string} */ function getMessage(key, parameters, self) { const message = messages.get(key); assert$1(message !== undefined, 'expected `message` to be found'); if (typeof message === 'function') { assert$1( message.length <= parameters.length, // Default options do not count. `Code: ${key}; The provided arguments length (${parameters.length}) does not ` + `match the required ones (${message.length}).` ); return Reflect.apply(message, self, parameters) } const regex = /%[dfijoOs]/g; let expectedLength = 0; while (regex.exec(message) !== null) expectedLength++; assert$1( expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not ` + `match the required ones (${expectedLength}).` ); if (parameters.length === 0) return message parameters.unshift(message); return Reflect.apply(format$2, null, parameters) } /** * Determine the specific type of a value for type-mismatch errors. * @param {unknown} value * @returns {string} */ function determineSpecificType(value) { if (value === null || value === undefined) { return String(value) } if (typeof value === 'function' && value.name) { return `function ${value.name}` } if (typeof value === 'object') { if (value.constructor && value.constructor.name) { return `an instance of ${value.constructor.name}` } return `${inspect(value, {depth: -1})}` } let inspected = inspect(value, {colors: false}); if (inspected.length > 28) { inspected = `${inspected.slice(0, 25)}...`; } return `type ${typeof value} (${inspected})` } const ESM_STATIC_IMPORT_RE = /(?<=\s|^|;|\})import\s*([\s"']*(?[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu; const TYPE_RE = /^\s*?type\s/; function parseStaticImport(matched) { const cleanedImports = clearImports(matched.imports); const namedImports = {}; const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || []; for (const namedImport of _matches) { const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/); const source = _match?.[1] || namedImport.trim(); const importName = _match?.[2] || source; if (source && !TYPE_RE.test(source)) { namedImports[source] = importName; } } const { namespacedImport, defaultImport } = getImportNames(cleanedImports); return { ...matched, defaultImport, namespacedImport, namedImports }; } const ESM_RE = /([\s;]|^)(import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m; const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g; function hasESMSyntax(code, opts = {}) { if (opts.stripComments) { code = code.replace(COMMENT_RE, ""); } return ESM_RE.test(code); } const debug$f = createDebugger("vite:external"); const isExternalCache = /* @__PURE__ */ new WeakMap(); function shouldExternalize(environment, id, importer) { let isExternal = isExternalCache.get(environment); if (!isExternal) { isExternal = createIsExternal(environment); isExternalCache.set(environment, isExternal); } return isExternal(id, importer); } const isConfiguredAsExternalCache = /* @__PURE__ */ new WeakMap(); function isConfiguredAsExternal(environment, id, importer) { let isExternal = isConfiguredAsExternalCache.get(environment); if (!isExternal) { isExternal = createIsConfiguredAsExternal(environment); isConfiguredAsExternalCache.set(environment, isExternal); } return isExternal(id, importer); } function createIsConfiguredAsExternal(environment) { const { config } = environment; const { root, resolve } = config; const { external, noExternal } = resolve; const noExternalFilter = typeof noExternal !== "boolean" && !(Array.isArray(noExternal) && noExternal.length === 0) && createFilter(void 0, noExternal, { resolve: false }); const targetConditions = resolve.externalConditions || []; const resolveOptions = { ...resolve, root, isProduction: false, isBuild: true, conditions: targetConditions }; const isExternalizable = (id, importer, configuredAsExternal) => { if (!bareImportRE.test(id) || id.includes("\0")) { return false; } try { const resolved = tryNodeResolve( id, // Skip passing importer in build to avoid externalizing non-hoisted dependencies // unresolvable from root (which would be unresolvable from output bundles also) config.command === "build" ? void 0 : importer, resolveOptions, void 0, false ); if (!resolved) { return false; } if (!configuredAsExternal && !isInNodeModules$1(resolved.id)) { return false; } return canExternalizeFile(resolved.id); } catch { debug$f?.( `Failed to node resolve "${id}". Skipping externalizing it by default.` ); return false; } }; return (id, importer) => { if ( // If this id is defined as external, force it as external // Note that individual package entries are allowed in `external` external !== true && external.includes(id) ) { return true; } const pkgName = getNpmPackageName(id); if (!pkgName) { return isExternalizable(id, importer, false); } if ( // A package name in ssr.external externalizes every // externalizable package entry external !== true && external.includes(pkgName) ) { return isExternalizable(id, importer, true); } if (typeof noExternal === "boolean") { return !noExternal; } if (noExternalFilter && !noExternalFilter(pkgName)) { return false; } return isExternalizable(id, importer, external === true); }; } function createIsExternal(environment) { const processedIds = /* @__PURE__ */ new Map(); const isConfiguredAsExternal2 = createIsConfiguredAsExternal(environment); return (id, importer) => { if (processedIds.has(id)) { return processedIds.get(id); } let isExternal = false; if (id[0] !== "." && !path$d.isAbsolute(id)) { isExternal = isBuiltin(id) || isConfiguredAsExternal2(id, importer); } processedIds.set(id, isExternal); return isExternal; }; } function canExternalizeFile(filePath) { const ext = path$d.extname(filePath); return !ext || ext === ".js" || ext === ".mjs" || ext === ".cjs"; } const normalizedClientEntry$1 = normalizePath$3(CLIENT_ENTRY); const normalizedEnvEntry$1 = normalizePath$3(ENV_ENTRY); const ERR_RESOLVE_PACKAGE_ENTRY_FAIL = "ERR_RESOLVE_PACKAGE_ENTRY_FAIL"; const browserExternalId = "__vite-browser-external"; const optionalPeerDepId = "__vite-optional-peer-dep"; const subpathImportsPrefix = "#"; const startsWithWordCharRE = /^\w/; const debug$e = createDebugger("vite:resolve-details", { onlyWhenFocused: true }); function resolvePlugin(resolveOptions) { const { root, isProduction, asSrc, preferRelative = false } = resolveOptions; const rootInRoot = tryStatSync(path$d.join(root, root))?.isDirectory() ?? false; return { name: "vite:resolve", async resolveId(id, importer, resolveOpts) { if (id[0] === "\0" || id.startsWith("virtual:") || // When injected directly in html/client code id.startsWith("/virtual:")) { return; } const depsOptimizer = resolveOptions.optimizeDeps && this.environment.mode === "dev" ? this.environment.depsOptimizer : void 0; if (id.startsWith(browserExternalId)) { return id; } const isRequire = resolveOpts?.custom?.["node-resolve"]?.isRequire ?? false; const currentEnvironmentOptions = this.environment.config; const options = { isRequire, ...currentEnvironmentOptions.resolve, ...resolveOptions, // plugin options + resolve options overrides scan: resolveOpts?.scan ?? resolveOptions.scan }; const resolvedImports = resolveSubpathImports(id, importer, options); if (resolvedImports) { id = resolvedImports; if (resolveOpts.custom?.["vite:import-glob"]?.isSubImportsPattern) { return normalizePath$3(path$d.join(root, id)); } } if (importer) { if (isTsRequest(importer) || resolveOpts.custom?.depScan?.loader?.startsWith("ts")) { options.isFromTsImporter = true; } else { const moduleLang = this.getModuleInfo(importer)?.meta?.vite?.lang; options.isFromTsImporter = moduleLang && isTsRequest(`.${moduleLang}`); } } let res; if (asSrc && depsOptimizer?.isOptimizedDepUrl(id)) { const optimizedPath = id.startsWith(FS_PREFIX) ? fsPathFromId(id) : normalizePath$3(path$d.resolve(root, id.slice(1))); return optimizedPath; } if (asSrc && id.startsWith(FS_PREFIX)) { res = fsPathFromId(id); debug$e?.(`[@fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`); return ensureVersionQuery(res, id, options, depsOptimizer); } if (asSrc && id[0] === "/" && (rootInRoot || !id.startsWith(withTrailingSlash(root)))) { const fsPath = path$d.resolve(root, id.slice(1)); if (res = tryFsResolve(fsPath, options)) { debug$e?.(`[url] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`); return ensureVersionQuery(res, id, options, depsOptimizer); } } if (id[0] === "." || (preferRelative || importer?.endsWith(".html")) && startsWithWordCharRE.test(id)) { const basedir = importer ? path$d.dirname(importer) : process.cwd(); const fsPath = path$d.resolve(basedir, id); const normalizedFsPath = normalizePath$3(fsPath); if (depsOptimizer?.isOptimizedDepFile(normalizedFsPath)) { if (!options.isBuild && !DEP_VERSION_RE.test(normalizedFsPath)) { const browserHash = optimizedDepInfoFromFile( depsOptimizer.metadata, normalizedFsPath )?.browserHash; if (browserHash) { return injectQuery(normalizedFsPath, `v=${browserHash}`); } } return normalizedFsPath; } if (options.mainFields.includes("browser") && (res = tryResolveBrowserMapping(fsPath, importer, options, true))) { return res; } if (res = tryFsResolve(fsPath, options)) { res = ensureVersionQuery(res, id, options, depsOptimizer); debug$e?.(`[relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`); if (!options.idOnly && !options.scan && options.isBuild) { const resPkg = findNearestPackageData( path$d.dirname(res), options.packageCache ); if (resPkg) { return { id: res, moduleSideEffects: resPkg.hasSideEffects(res) }; } } return res; } } if (id.startsWith("file://")) { id = fileURLToPath$1(id); } if (isWindows$3 && id[0] === "/") { const basedir = importer ? path$d.dirname(importer) : process.cwd(); const fsPath = path$d.resolve(basedir, id); if (res = tryFsResolve(fsPath, options)) { debug$e?.(`[drive-relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`); return ensureVersionQuery(res, id, options, depsOptimizer); } } if (isNonDriveRelativeAbsolutePath(id) && (res = tryFsResolve(id, options))) { debug$e?.(`[fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`); return ensureVersionQuery(res, id, options, depsOptimizer); } if (isExternalUrl(id)) { return options.idOnly ? id : { id, external: true }; } if (isDataUrl(id)) { return null; } if (bareImportRE.test(id)) { const external = options.externalize && options.isBuild && currentEnvironmentOptions.consumer === "server" && shouldExternalize(this.environment, id, importer); if (!external && asSrc && depsOptimizer && !options.scan && (res = await tryOptimizedResolve( depsOptimizer, id, importer, options.preserveSymlinks, options.packageCache ))) { return res; } if (options.mainFields.includes("browser") && (res = tryResolveBrowserMapping( id, importer, options, false, external ))) { return res; } if (res = tryNodeResolve(id, importer, options, depsOptimizer, external)) { return res; } if (isBuiltin(id)) { if (currentEnvironmentOptions.consumer === "server") { if (options.noExternal === true && // if both noExternal and external are true, noExternal will take the higher priority and bundle it. // only if the id is explicitly listed in external, we will externalize it and skip this error. (options.external === true || !options.external.includes(id))) { let message = `Cannot bundle Node.js built-in "${id}"`; if (importer) { message += ` imported from "${path$d.relative( process.cwd(), importer )}"`; } message += `. Consider disabling environments.${this.environment.name}.noExternal or remove the built-in dependency.`; this.error(message); } return options.idOnly ? id : { id, external: true, moduleSideEffects: false }; } else { if (!asSrc) { debug$e?.( `externalized node built-in "${id}" to empty module. (imported by: ${colors$1.white(colors$1.dim(importer))})` ); } else if (isProduction) { this.warn( `Module "${id}" has been externalized for browser compatibility, imported by "${importer}". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.` ); } return isProduction ? browserExternalId : `${browserExternalId}:${id}`; } } } debug$e?.(`[fallthrough] ${colors$1.dim(id)}`); }, load(id) { if (id.startsWith(browserExternalId)) { if (isProduction) { return `export default {}`; } else { id = id.slice(browserExternalId.length + 1); return `export default new Proxy({}, { get(_, key) { throw new Error(\`Module "${id}" has been externalized for browser compatibility. Cannot access "${id}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`) } })`; } } if (id.startsWith(optionalPeerDepId)) { if (isProduction) { return `export default {}`; } else { const [, peerDep, parentDep] = id.split(":"); return `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`; } } } }; } function resolveSubpathImports(id, importer, options) { if (!importer || !id.startsWith(subpathImportsPrefix)) return; const basedir = path$d.dirname(importer); const pkgData = findNearestPackageData(basedir, options.packageCache); if (!pkgData) return; let { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id.slice(1)); idWithoutPostfix = "#" + idWithoutPostfix; let importsPath = resolveExportsOrImports( pkgData.data, idWithoutPostfix, options, "imports" ); if (importsPath?.[0] === ".") { importsPath = path$d.relative(basedir, path$d.join(pkgData.dir, importsPath)); if (importsPath[0] !== ".") { importsPath = `./${importsPath}`; } } return importsPath + postfix; } function ensureVersionQuery(resolved, id, options, depsOptimizer) { if (!options.isBuild && !options.scan && depsOptimizer && !(resolved === normalizedClientEntry$1 || resolved === normalizedEnvEntry$1)) { const isNodeModule = isInNodeModules$1(id) || isInNodeModules$1(resolved); if (isNodeModule && !DEP_VERSION_RE.test(resolved)) { const versionHash = depsOptimizer.metadata.browserHash; if (versionHash && isOptimizable(resolved, depsOptimizer.options)) { resolved = injectQuery(resolved, `v=${versionHash}`); } } } return resolved; } function tryFsResolve(fsPath, options, tryIndex = true, skipPackageJson = false) { const hashIndex = fsPath.indexOf("#"); if (hashIndex >= 0 && isInNodeModules$1(fsPath)) { const queryIndex = fsPath.indexOf("?"); if (queryIndex < 0 || queryIndex > hashIndex) { const file2 = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath; const res2 = tryCleanFsResolve(file2, options, tryIndex, skipPackageJson); if (res2) return res2 + fsPath.slice(file2.length); } } const { file, postfix } = splitFileAndPostfix(fsPath); const res = tryCleanFsResolve(file, options, tryIndex, skipPackageJson); if (res) return res + postfix; } const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/; const isPossibleTsOutput = (url) => knownTsOutputRE.test(url); function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = false) { const { tryPrefix, extensions, preserveSymlinks } = options; const fileResult = tryResolveRealFileOrType(file, options.preserveSymlinks); if (fileResult?.path) return fileResult.path; let res; const possibleJsToTs = options.isFromTsImporter && isPossibleTsOutput(file); if (possibleJsToTs || options.extensions.length || tryPrefix) { const dirPath = path$d.dirname(file); if (isDirectory(dirPath)) { if (possibleJsToTs) { const fileExt = path$d.extname(file); const fileName = file.slice(0, -fileExt.length); if (res = tryResolveRealFile( fileName + fileExt.replace("js", "ts"), preserveSymlinks )) return res; if (fileExt === ".js" && (res = tryResolveRealFile(fileName + ".tsx", preserveSymlinks))) return res; } if (res = tryResolveRealFileWithExtensions( file, extensions, preserveSymlinks )) return res; if (tryPrefix) { const prefixed = `${dirPath}/${options.tryPrefix}${path$d.basename(file)}`; if (res = tryResolveRealFile(prefixed, preserveSymlinks)) return res; if (res = tryResolveRealFileWithExtensions( prefixed, extensions, preserveSymlinks )) return res; } } } if (tryIndex && fileResult?.type === "directory") { const dirPath = file; if (!skipPackageJson) { let pkgPath = `${dirPath}/package.json`; try { if (fs__default.existsSync(pkgPath)) { if (!options.preserveSymlinks) { pkgPath = safeRealpathSync(pkgPath); } const pkg = loadPackageData(pkgPath); return resolvePackageEntry(dirPath, pkg, options); } } catch (e) { if (e.code !== ERR_RESOLVE_PACKAGE_ENTRY_FAIL && e.code !== "ENOENT") throw e; } } if (res = tryResolveRealFileWithExtensions( `${dirPath}/index`, extensions, preserveSymlinks )) return res; if (tryPrefix) { if (res = tryResolveRealFileWithExtensions( `${dirPath}/${options.tryPrefix}index`, extensions, preserveSymlinks )) return res; } } } function tryNodeResolve(id, importer, options, depsOptimizer, externalize) { const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options; const deepMatch = deepImportRE.exec(id); const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(id); let basedir; if (dedupe?.includes(pkgId)) { basedir = root; } else if (importer && path$d.isAbsolute(importer) && // css processing appends `*` for importer (importer[importer.length - 1] === "*" || fs__default.existsSync(cleanUrl(importer)))) { basedir = path$d.dirname(importer); } else { basedir = root; } let selfPkg = null; if (!isBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) { const selfPackageData = findNearestPackageData(basedir, packageCache); selfPkg = selfPackageData?.data.exports && selfPackageData?.data.name === pkgId ? selfPackageData : null; } const pkg = selfPkg || resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache); if (!pkg) { if (basedir !== root && // root has no peer dep !isBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) { const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data; if (mainPkg) { const pkgName = getNpmPackageName(id); if (pkgName != null && mainPkg.peerDependencies?.[pkgName] && mainPkg.peerDependenciesMeta?.[pkgName]?.optional) { return { id: `${optionalPeerDepId}:${id}:${mainPkg.name}` }; } } } return; } const resolveId = deepMatch ? resolveDeepImport : resolvePackageEntry; const unresolvedId = deepMatch ? "." + id.slice(pkgId.length) : id; let resolved = resolveId(unresolvedId, pkg, options); if (!resolved) { return; } const processResult = (resolved2) => { if (!externalize) { return resolved2; } if (!canExternalizeFile(resolved2.id)) { return resolved2; } let resolvedId = id; if (deepMatch && !pkg?.data.exports && path$d.extname(id) !== path$d.extname(resolved2.id)) { const index = resolved2.id.indexOf(id); if (index > -1) { resolvedId = resolved2.id.slice(index); debug$e?.( `[processResult] ${colors$1.cyan(id)} -> ${colors$1.dim(resolvedId)}` ); } } return { ...resolved2, id: resolvedId, external: true }; }; if (!options.idOnly && (!options.scan && isBuild || externalize)) { return processResult({ id: resolved, moduleSideEffects: pkg.hasSideEffects(resolved) }); } if (!isInNodeModules$1(resolved) || // linked !depsOptimizer || // resolving before listening to the server options.scan) { return { id: resolved }; } const isJsType = isOptimizable(resolved, depsOptimizer.options); const exclude = depsOptimizer.options.exclude; const skipOptimization = depsOptimizer.options.noDiscovery || !isJsType || importer && isInNodeModules$1(importer) || exclude?.includes(pkgId) || exclude?.includes(id) || SPECIAL_QUERY_RE.test(resolved); if (skipOptimization) { const versionHash = depsOptimizer.metadata.browserHash; if (versionHash && isJsType) { resolved = injectQuery(resolved, `v=${versionHash}`); } } else { const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved); resolved = depsOptimizer.getOptimizedDepId(optimizedInfo); } return { id: resolved }; } async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks, packageCache) { await depsOptimizer.scanProcessing; const metadata = depsOptimizer.metadata; const depInfo = optimizedDepInfoFromId(metadata, id); if (depInfo) { return depsOptimizer.getOptimizedDepId(depInfo); } if (!importer) return; let idPkgDir; const nestedIdMatch = `> ${id}`; for (const optimizedData of metadata.depInfoList) { if (!optimizedData.src) continue; if (!optimizedData.id.endsWith(nestedIdMatch)) continue; if (idPkgDir == null) { const pkgName = getNpmPackageName(id); if (!pkgName) break; idPkgDir = resolvePackageData( pkgName, importer, preserveSymlinks, packageCache )?.dir; if (idPkgDir == null) break; idPkgDir = normalizePath$3(idPkgDir); } if (optimizedData.src.startsWith(withTrailingSlash(idPkgDir))) { return depsOptimizer.getOptimizedDepId(optimizedData); } } } function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, options) { const { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id); const cached = getResolvedCache(".", options); if (cached) { return cached + postfix; } try { let entryPoint; if (data.exports) { entryPoint = resolveExportsOrImports(data, ".", options, "exports"); } if (!entryPoint) { for (const field of options.mainFields) { if (field === "browser") { entryPoint = tryResolveBrowserEntry(dir, data, options); if (entryPoint) { break; } } else if (typeof data[field] === "string") { entryPoint = data[field]; break; } } } entryPoint ||= data.main; const entryPoints = entryPoint ? [entryPoint] : ["index.js", "index.json", "index.node"]; for (let entry of entryPoints) { let skipPackageJson = false; if (options.mainFields[0] === "sass" && !options.extensions.includes(path$d.extname(entry))) { entry = ""; skipPackageJson = true; } else { const { browser: browserField } = data; if (options.mainFields.includes("browser") && isObject$2(browserField)) { entry = mapWithBrowserField(entry, browserField) || entry; } } const entryPointPath = path$d.join(dir, entry); const resolvedEntryPoint = tryFsResolve( entryPointPath, options, true, skipPackageJson ); if (resolvedEntryPoint) { debug$e?.( `[package entry] ${colors$1.cyan(idWithoutPostfix)} -> ${colors$1.dim( resolvedEntryPoint )}${postfix !== "" ? ` (postfix: ${postfix})` : ""}` ); setResolvedCache(".", resolvedEntryPoint, options); return resolvedEntryPoint + postfix; } } } catch (e) { packageEntryFailure(id, e.message); } packageEntryFailure(id); } function packageEntryFailure(id, details) { const err = new Error( `Failed to resolve entry for package "${id}". The package may have incorrect main/module/exports specified in its package.json` + (details ? ": " + details : ".") ); err.code = ERR_RESOLVE_PACKAGE_ENTRY_FAIL; throw err; } function resolveExportsOrImports(pkg, key, options, type) { const conditions = options.conditions.map((condition) => { if (condition === DEV_PROD_CONDITION) { return options.isProduction ? "production" : "development"; } return condition; }); if (options.isRequire) { conditions.push("require"); } else { conditions.push("import"); } const fn = type === "imports" ? f : o; const result = fn(pkg, key, { conditions, unsafe: true }); return result ? result[0] : void 0; } function resolveDeepImport(id, { setResolvedCache, getResolvedCache, dir, data }, options) { const cache = getResolvedCache(id, options); if (cache) { return cache; } let relativeId = id; const { exports: exportsField, browser: browserField } = data; if (exportsField) { if (isObject$2(exportsField) && !Array.isArray(exportsField)) { const { file, postfix } = splitFileAndPostfix(relativeId); const exportsId = resolveExportsOrImports(data, file, options, "exports"); if (exportsId !== void 0) { relativeId = exportsId + postfix; } else { relativeId = void 0; } } else { relativeId = void 0; } if (!relativeId) { throw new Error( `Package subpath '${relativeId}' is not defined by "exports" in ${path$d.join(dir, "package.json")}.` ); } } else if (options.mainFields.includes("browser") && isObject$2(browserField)) { const { file, postfix } = splitFileAndPostfix(relativeId); const mapped = mapWithBrowserField(file, browserField); if (mapped) { relativeId = mapped + postfix; } else if (mapped === false) { setResolvedCache(id, browserExternalId, options); return browserExternalId; } } if (relativeId) { const resolved = tryFsResolve( path$d.join(dir, relativeId), options, !exportsField // try index only if no exports field ); if (resolved) { debug$e?.( `[node/deep-import] ${colors$1.cyan(id)} -> ${colors$1.dim(resolved)}` ); setResolvedCache(id, resolved, options); return resolved; } } } function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize) { let res; const pkg = importer && findNearestPackageData(path$d.dirname(importer), options.packageCache); if (pkg && isObject$2(pkg.data.browser)) { const mapId = isFilePath ? "./" + slash$1(path$d.relative(pkg.dir, id)) : id; const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser); if (browserMappedPath) { if (res = bareImportRE.test(browserMappedPath) ? tryNodeResolve( browserMappedPath, importer, options, void 0, void 0 )?.id : tryFsResolve(path$d.join(pkg.dir, browserMappedPath), options)) { debug$e?.(`[browser mapped] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`); let result = { id: res }; if (options.idOnly) { return result; } if (!options.scan && options.isBuild) { const resPkg = findNearestPackageData( path$d.dirname(res), options.packageCache ); if (resPkg) { result = { id: res, moduleSideEffects: resPkg.hasSideEffects(res) }; } } return externalize ? { ...result, external: true } : result; } } else if (browserMappedPath === false) { return browserExternalId; } } } function tryResolveBrowserEntry(dir, data, options) { const browserEntry = typeof data.browser === "string" ? data.browser : isObject$2(data.browser) && data.browser["."]; if (browserEntry) { if (!options.isRequire && options.mainFields.includes("module") && typeof data.module === "string" && data.module !== browserEntry) { const resolvedBrowserEntry = tryFsResolve( path$d.join(dir, browserEntry), options ); if (resolvedBrowserEntry) { const content = fs__default.readFileSync(resolvedBrowserEntry, "utf-8"); if (hasESMSyntax(content)) { return browserEntry; } else { return data.module; } } } else { return browserEntry; } } } function mapWithBrowserField(relativePathInPkgDir, map) { const normalizedPath = path$d.posix.normalize(relativePathInPkgDir); for (const key in map) { const normalizedKey = path$d.posix.normalize(key); if (normalizedPath === normalizedKey || equalWithoutSuffix(normalizedPath, normalizedKey, ".js") || equalWithoutSuffix(normalizedPath, normalizedKey, "/index.js")) { return map[key]; } } } function equalWithoutSuffix(path2, key, suffix) { return key.endsWith(suffix) && key.slice(0, -suffix.length) === path2; } function tryResolveRealFile(file, preserveSymlinks) { const stat = tryStatSync(file); if (stat?.isFile()) return getRealPath(file, preserveSymlinks); } function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) { for (const ext of extensions) { const res = tryResolveRealFile(filePath + ext, preserveSymlinks); if (res) return res; } } function tryResolveRealFileOrType(file, preserveSymlinks) { const fileStat = tryStatSync(file); if (fileStat?.isFile()) { return { path: getRealPath(file, preserveSymlinks), type: "file" }; } if (fileStat?.isDirectory()) { return { type: "directory" }; } return; } function getRealPath(resolved, preserveSymlinks) { if (!preserveSymlinks) { resolved = safeRealpathSync(resolved); } return normalizePath$3(resolved); } function isDirectory(path2) { const stat = tryStatSync(path2); return stat?.isDirectory() ?? false; } const externalWithConversionNamespace = "vite:dep-pre-bundle:external-conversion"; const convertedExternalPrefix = "vite-dep-pre-bundle-external:"; const cjsExternalFacadeNamespace = "vite:cjs-external-facade"; const nonFacadePrefix = "vite-cjs-external-facade:"; const externalTypes = [ "css", // supported pre-processor types "less", "sass", "scss", "styl", "stylus", "pcss", "postcss", // wasm "wasm", // known SFC types "vue", "svelte", "marko", "astro", "imba", // JSX/TSX may be configured to be compiled differently from how esbuild // handles it by default, so exclude them as well "jsx", "tsx", ...KNOWN_ASSET_TYPES ]; function esbuildDepPlugin(environment, qualified, external) { const { isProduction } = environment.config; const { extensions } = environment.config.optimizeDeps; const allExternalTypes = extensions ? externalTypes.filter((type) => !extensions?.includes("." + type)) : externalTypes; const esmPackageCache = /* @__PURE__ */ new Map(); const cjsPackageCache = /* @__PURE__ */ new Map(); const _resolve = createBackCompatIdResolver(environment.getTopLevelConfig(), { asSrc: false, scan: true, packageCache: esmPackageCache }); const _resolveRequire = createBackCompatIdResolver( environment.getTopLevelConfig(), { asSrc: false, isRequire: true, scan: true, packageCache: cjsPackageCache } ); const resolve = (id, importer, kind, resolveDir) => { let _importer; { _importer = importer in qualified ? qualified[importer] : importer; } const resolver = kind.startsWith("require") ? _resolveRequire : _resolve; return resolver(environment, id, _importer); }; const resolveResult = (id, resolved) => { if (resolved.startsWith(browserExternalId)) { return { path: id, namespace: "browser-external" }; } if (resolved.startsWith(optionalPeerDepId)) { return { path: resolved, namespace: "optional-peer-dep" }; } if (environment.config.consumer === "server" && isBuiltin(resolved)) { return; } if (isExternalUrl(resolved)) { return { path: resolved, external: true }; } return { path: path$d.resolve(resolved) }; }; return { name: "vite:dep-pre-bundle", setup(build) { build.onEnd(() => { esmPackageCache.clear(); cjsPackageCache.clear(); }); build.onResolve( { filter: new RegExp( `\\.(` + allExternalTypes.join("|") + `)(\\?.*)?$` ) }, async ({ path: id, importer, kind }) => { if (id.startsWith(convertedExternalPrefix)) { return { path: id.slice(convertedExternalPrefix.length), external: true }; } const resolved = await resolve(id, importer, kind); if (resolved) { if (JS_TYPES_RE.test(resolved)) { return { path: resolved, external: false }; } if (kind === "require-call") { return { path: resolved, namespace: externalWithConversionNamespace }; } return { path: resolved, external: true }; } } ); build.onLoad( { filter: /./, namespace: externalWithConversionNamespace }, (args) => { const modulePath = `"${convertedExternalPrefix}${args.path}"`; return { contents: isCSSRequest(args.path) && !isModuleCSSRequest(args.path) ? `import ${modulePath};` : `export { default } from ${modulePath};export * from ${modulePath};`, loader: "js" }; } ); function resolveEntry(id) { const flatId = flattenId(id); if (flatId in qualified) { return { path: qualified[flatId] }; } } build.onResolve( { filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind }) => { if (moduleListContains(external, id)) { return { path: id, external: true }; } let entry; if (!importer) { if (entry = resolveEntry(id)) return entry; const aliased = await _resolve(environment, id, void 0, true); if (aliased && (entry = resolveEntry(aliased))) { return entry; } } const resolved = await resolve(id, importer, kind); if (resolved) { return resolveResult(id, resolved); } } ); build.onLoad( { filter: /.*/, namespace: "browser-external" }, ({ path: path2 }) => { if (isProduction) { return { contents: "module.exports = {}" }; } else { return { // Return in CJS to intercept named imports. Use `Object.create` to // create the Proxy in the prototype to workaround esbuild issue. Why? // // In short, esbuild cjs->esm flow: // 1. Create empty object using `Object.create(Object.getPrototypeOf(module.exports))`. // 2. Assign props of `module.exports` to the object. // 3. Return object for ESM use. // // If we do `module.exports = new Proxy({}, {})`, step 1 returns empty object, // step 2 does nothing as there's no props for `module.exports`. The final object // is just an empty object. // // Creating the Proxy in the prototype satisfies step 1 immediately, which means // the returned object is a Proxy that we can intercept. // // Note: Skip keys that are accessed by esbuild and browser devtools. contents: `module.exports = Object.create(new Proxy({}, { get(_, key) { if ( key !== '__esModule' && key !== '__proto__' && key !== 'constructor' && key !== 'splice' ) { console.warn(\`Module "${path2}" has been externalized for browser compatibility. Cannot access "${path2}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`) } } }))` }; } } ); build.onLoad( { filter: /.*/, namespace: "optional-peer-dep" }, ({ path: path2 }) => { if (isProduction) { return { contents: "module.exports = {}" }; } else { const [, peerDep, parentDep] = path2.split(":"); return { contents: `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)` }; } } ); } }; } const matchesEntireLine = (text) => `^${escapeRegex(text)}$`; function esbuildCjsExternalPlugin(externals, platform) { return { name: "cjs-external", setup(build) { const filter = new RegExp(externals.map(matchesEntireLine).join("|")); build.onResolve({ filter: new RegExp(`^${nonFacadePrefix}`) }, (args) => { return { path: args.path.slice(nonFacadePrefix.length), external: true }; }); build.onResolve({ filter }, (args) => { if (args.kind === "require-call" && platform !== "node") { return { path: args.path, namespace: cjsExternalFacadeNamespace }; } return { path: args.path, external: true }; }); build.onLoad( { filter: /.*/, namespace: cjsExternalFacadeNamespace }, (args) => ({ contents: `import * as m from ${JSON.stringify( nonFacadePrefix + args.path )};module.exports = m;` }) ); } }; } const environmentColors = [ colors$1.blue, colors$1.magenta, colors$1.green, colors$1.gray ]; function getDefaultResolvedEnvironmentOptions(config) { return { define: config.define, resolve: config.resolve, consumer: "server", optimizeDeps: config.optimizeDeps, dev: config.dev, build: config.build }; } class PartialEnvironment { name; getTopLevelConfig() { return this._topLevelConfig; } config; /** * @deprecated use environment.config instead **/ get options() { return this._options; } logger; /** * @internal */ _options; /** * @internal */ _topLevelConfig; constructor(name, topLevelConfig, options = topLevelConfig.environments[name]) { if (!/^[\w$]+$/.test(name)) { throw new Error( `Invalid environment name "${name}". Environment names must only contain alphanumeric characters and "$", "_".` ); } this.name = name; this._topLevelConfig = topLevelConfig; this._options = options; this.config = new Proxy( options, { get: (target, prop) => { if (prop === "logger") { return this.logger; } if (prop in target) { return this._options[prop]; } return this._topLevelConfig[prop]; } } ); const environment = colors$1.dim(`(${this.name})`); const colorIndex = [...this.name].reduce((acc, c) => acc + c.charCodeAt(0), 0) % environmentColors.length; const infoColor = environmentColors[colorIndex || 0]; this.logger = { get hasWarned() { return topLevelConfig.logger.hasWarned; }, info(msg, opts) { return topLevelConfig.logger.info(msg, { ...opts, environment: infoColor(environment) }); }, warn(msg, opts) { return topLevelConfig.logger.warn(msg, { ...opts, environment: colors$1.yellow(environment) }); }, warnOnce(msg, opts) { return topLevelConfig.logger.warnOnce(msg, { ...opts, environment: colors$1.yellow(environment) }); }, error(msg, opts) { return topLevelConfig.logger.error(msg, { ...opts, environment: colors$1.red(environment) }); }, clearScreen(type) { return topLevelConfig.logger.clearScreen(type); }, hasErrorLogged(error) { return topLevelConfig.logger.hasErrorLogged(error); } }; } } class BaseEnvironment extends PartialEnvironment { get plugins() { if (!this._plugins) throw new Error( `${this.name} environment.plugins called before initialized` ); return this._plugins; } /** * @internal */ _plugins; /** * @internal */ _initiated = false; constructor(name, config, options = config.environments[name]) { super(name, config, options); } } // Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell // License: MIT. var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace; RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]?|[^\/[\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu; Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y; Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu; StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y; NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y; Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y; WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu; LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y; MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y; SingleLineComment = /\/\/.*/y; HashbangComment = /^#!.*/; JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y; JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu; JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y; JSXText = /[^<>{}]+/y; TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/; TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/; KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/; KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/; Newline = RegExp(LineTerminatorSequence.source); var jsTokens_1 = function*(input, {jsx = false} = {}) { var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack; ({length} = input); lastIndex = 0; lastSignificantToken = ""; stack = [ {tag: "JS"} ]; braces = []; parenNesting = 0; postfixIncDec = false; if (match = HashbangComment.exec(input)) { yield ({ type: "HashbangComment", value: match[0] }); lastIndex = match[0].length; } while (lastIndex < length) { mode = stack[stack.length - 1]; switch (mode.tag) { case "JS": case "JSNonExpressionParen": case "InterpolationInTemplate": case "InterpolationInJSX": if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { RegularExpressionLiteral.lastIndex = lastIndex; if (match = RegularExpressionLiteral.exec(input)) { lastIndex = RegularExpressionLiteral.lastIndex; lastSignificantToken = match[0]; postfixIncDec = true; yield ({ type: "RegularExpressionLiteral", value: match[0], closed: match[1] !== void 0 && match[1] !== "\\" }); continue; } } Punctuator.lastIndex = lastIndex; if (match = Punctuator.exec(input)) { punctuator = match[0]; nextLastIndex = Punctuator.lastIndex; nextLastSignificantToken = punctuator; switch (punctuator) { case "(": if (lastSignificantToken === "?NonExpressionParenKeyword") { stack.push({ tag: "JSNonExpressionParen", nesting: parenNesting }); } parenNesting++; postfixIncDec = false; break; case ")": parenNesting--; postfixIncDec = true; if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) { stack.pop(); nextLastSignificantToken = "?NonExpressionParenEnd"; postfixIncDec = false; } break; case "{": Punctuator.lastIndex = 0; isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken)); braces.push(isExpression); postfixIncDec = false; break; case "}": switch (mode.tag) { case "InterpolationInTemplate": if (braces.length === mode.nesting) { Template.lastIndex = lastIndex; match = Template.exec(input); lastIndex = Template.lastIndex; lastSignificantToken = match[0]; if (match[1] === "${") { lastSignificantToken = "?InterpolationInTemplate"; postfixIncDec = false; yield ({ type: "TemplateMiddle", value: match[0] }); } else { stack.pop(); postfixIncDec = true; yield ({ type: "TemplateTail", value: match[0], closed: match[1] === "`" }); } continue; } break; case "InterpolationInJSX": if (braces.length === mode.nesting) { stack.pop(); lastIndex += 1; lastSignificantToken = "}"; yield ({ type: "JSXPunctuator", value: "}" }); continue; } } postfixIncDec = braces.pop(); nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}"; break; case "]": postfixIncDec = true; break; case "++": case "--": nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec"; break; case "<": if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { stack.push({tag: "JSXTag"}); lastIndex += 1; lastSignificantToken = "<"; yield ({ type: "JSXPunctuator", value: punctuator }); continue; } postfixIncDec = false; break; default: postfixIncDec = false; } lastIndex = nextLastIndex; lastSignificantToken = nextLastSignificantToken; yield ({ type: "Punctuator", value: punctuator }); continue; } Identifier.lastIndex = lastIndex; if (match = Identifier.exec(input)) { lastIndex = Identifier.lastIndex; nextLastSignificantToken = match[0]; switch (match[0]) { case "for": case "if": case "while": case "with": if (lastSignificantToken !== "." && lastSignificantToken !== "?.") { nextLastSignificantToken = "?NonExpressionParenKeyword"; } } lastSignificantToken = nextLastSignificantToken; postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]); yield ({ type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName", value: match[0] }); continue; } StringLiteral.lastIndex = lastIndex; if (match = StringLiteral.exec(input)) { lastIndex = StringLiteral.lastIndex; lastSignificantToken = match[0]; postfixIncDec = true; yield ({ type: "StringLiteral", value: match[0], closed: match[2] !== void 0 }); continue; } NumericLiteral.lastIndex = lastIndex; if (match = NumericLiteral.exec(input)) { lastIndex = NumericLiteral.lastIndex; lastSignificantToken = match[0]; postfixIncDec = true; yield ({ type: "NumericLiteral", value: match[0] }); continue; } Template.lastIndex = lastIndex; if (match = Template.exec(input)) { lastIndex = Template.lastIndex; lastSignificantToken = match[0]; if (match[1] === "${") { lastSignificantToken = "?InterpolationInTemplate"; stack.push({ tag: "InterpolationInTemplate", nesting: braces.length }); postfixIncDec = false; yield ({ type: "TemplateHead", value: match[0] }); } else { postfixIncDec = true; yield ({ type: "NoSubstitutionTemplate", value: match[0], closed: match[1] === "`" }); } continue; } break; case "JSXTag": case "JSXTagEnd": JSXPunctuator.lastIndex = lastIndex; if (match = JSXPunctuator.exec(input)) { lastIndex = JSXPunctuator.lastIndex; nextLastSignificantToken = match[0]; switch (match[0]) { case "<": stack.push({tag: "JSXTag"}); break; case ">": stack.pop(); if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") { nextLastSignificantToken = "?JSX"; postfixIncDec = true; } else { stack.push({tag: "JSXChildren"}); } break; case "{": stack.push({ tag: "InterpolationInJSX", nesting: braces.length }); nextLastSignificantToken = "?InterpolationInJSX"; postfixIncDec = false; break; case "/": if (lastSignificantToken === "<") { stack.pop(); if (stack[stack.length - 1].tag === "JSXChildren") { stack.pop(); } stack.push({tag: "JSXTagEnd"}); } } lastSignificantToken = nextLastSignificantToken; yield ({ type: "JSXPunctuator", value: match[0] }); continue; } JSXIdentifier.lastIndex = lastIndex; if (match = JSXIdentifier.exec(input)) { lastIndex = JSXIdentifier.lastIndex; lastSignificantToken = match[0]; yield ({ type: "JSXIdentifier", value: match[0] }); continue; } JSXString.lastIndex = lastIndex; if (match = JSXString.exec(input)) { lastIndex = JSXString.lastIndex; lastSignificantToken = match[0]; yield ({ type: "JSXString", value: match[0], closed: match[2] !== void 0 }); continue; } break; case "JSXChildren": JSXText.lastIndex = lastIndex; if (match = JSXText.exec(input)) { lastIndex = JSXText.lastIndex; lastSignificantToken = match[0]; yield ({ type: "JSXText", value: match[0] }); continue; } switch (input[lastIndex]) { case "<": stack.push({tag: "JSXTag"}); lastIndex++; lastSignificantToken = "<"; yield ({ type: "JSXPunctuator", value: "<" }); continue; case "{": stack.push({ tag: "InterpolationInJSX", nesting: braces.length }); lastIndex++; lastSignificantToken = "?InterpolationInJSX"; postfixIncDec = false; yield ({ type: "JSXPunctuator", value: "{" }); continue; } } WhiteSpace.lastIndex = lastIndex; if (match = WhiteSpace.exec(input)) { lastIndex = WhiteSpace.lastIndex; yield ({ type: "WhiteSpace", value: match[0] }); continue; } LineTerminatorSequence.lastIndex = lastIndex; if (match = LineTerminatorSequence.exec(input)) { lastIndex = LineTerminatorSequence.lastIndex; postfixIncDec = false; if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) { lastSignificantToken = "?NoLineTerminatorHere"; } yield ({ type: "LineTerminatorSequence", value: match[0] }); continue; } MultiLineComment.lastIndex = lastIndex; if (match = MultiLineComment.exec(input)) { lastIndex = MultiLineComment.lastIndex; if (Newline.test(match[0])) { postfixIncDec = false; if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) { lastSignificantToken = "?NoLineTerminatorHere"; } } yield ({ type: "MultiLineComment", value: match[0], closed: match[1] !== void 0 }); continue; } SingleLineComment.lastIndex = lastIndex; if (match = SingleLineComment.exec(input)) { lastIndex = SingleLineComment.lastIndex; postfixIncDec = false; yield ({ type: "SingleLineComment", value: match[0] }); continue; } firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex)); lastIndex += firstCodePoint.length; lastSignificantToken = firstCodePoint; postfixIncDec = false; yield ({ type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid", value: firstCodePoint }); } return void 0; }; var jsTokens = /*@__PURE__*/getDefaultExportFromCjs(jsTokens_1); function stripLiteralJsTokens(code, options) { const FILL = " "; const FILL_COMMENT = " "; let result = ""; const tokens = []; for (const token of jsTokens(code, { jsx: false })) { tokens.push(token); if (token.type === "SingleLineComment") { result += FILL_COMMENT.repeat(token.value.length); continue; } if (token.type === "MultiLineComment") { result += token.value.replace(/[^\n]/g, FILL_COMMENT); continue; } if (token.type === "StringLiteral") { if (!token.closed) { result += token.value; continue; } const body = token.value.slice(1, -1); { result += token.value[0] + FILL.repeat(body.length) + token.value[token.value.length - 1]; continue; } } if (token.type === "NoSubstitutionTemplate") { const body = token.value.slice(1, -1); { result += `\`${body.replace(/[^\n]/g, FILL)}\``; continue; } } if (token.type === "RegularExpressionLiteral") { const body = token.value; { result += body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${FILL.repeat($1.length)}/${$2}`); continue; } } if (token.type === "TemplateHead") { const body = token.value.slice(1, -2); { result += `\`${body.replace(/[^\n]/g, FILL)}\${`; continue; } } if (token.type === "TemplateTail") { const body = token.value.slice(0, -2); { result += `}${body.replace(/[^\n]/g, FILL)}\``; continue; } } if (token.type === "TemplateMiddle") { const body = token.value.slice(1, -2); { result += `}${body.replace(/[^\n]/g, FILL)}\${`; continue; } } result += token.value; } return { result, tokens }; } function stripLiteral(code, options) { return stripLiteralDetailed(code).result; } function stripLiteralDetailed(code, options) { return stripLiteralJsTokens(code); } function importGlobPlugin(config) { const importGlobMaps = /* @__PURE__ */ new Map(); return { name: "vite:import-glob", buildStart() { importGlobMaps.clear(); }, async transform(code, id) { if (!code.includes("import.meta.glob")) return; const result = await transformGlobImport( code, id, config.root, (im, _, options) => this.resolve(im, id, options).then((i) => i?.id || im), config.experimental.importGlobRestoreExtension, config.logger ); if (result) { const allGlobs = result.matches.map((i) => i.globsResolved); if (!importGlobMaps.has(this.environment)) { importGlobMaps.set(this.environment, /* @__PURE__ */ new Map()); } const globMatchers = allGlobs.map((globs) => { const affirmed = []; const negated = []; for (const glob2 of globs) { (glob2[0] === "!" ? negated : affirmed).push(glob2); } const affirmedMatcher = picomatch$5(affirmed); const negatedMatcher = picomatch$5(negated); return (file) => { return (affirmed.length === 0 || affirmedMatcher(file)) && !(negated.length > 0 && negatedMatcher(file)); }; }); importGlobMaps.get(this.environment).set(id, globMatchers); return transformStableResult(result.s, id, config); } }, hotUpdate({ type, file, modules: oldModules }) { if (type === "update") return; const importGlobMap = importGlobMaps.get(this.environment); if (!importGlobMap) return; const modules = []; for (const [id, globMatchers] of importGlobMap) { if (globMatchers.some((matcher) => matcher(file))) { const mod = this.environment.moduleGraph.getModuleById(id); if (mod) modules.push(mod); } } return modules.length > 0 ? [...oldModules, ...modules] : void 0; } }; } const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g; const objectKeysRE = /\bObject\.keys\(\s*$/; const objectValuesRE = /\bObject\.values\(\s*$/; const knownOptions = { as: ["string"], eager: ["boolean"], import: ["string"], exhaustive: ["boolean"], query: ["object", "string"] }; const forceDefaultAs = ["raw", "url"]; function err$1(e, pos) { const error = new Error(e); error.pos = pos; return error; } function parseGlobOptions(rawOpts, optsStartIndex, logger) { let opts = {}; try { opts = evalValue(rawOpts); } catch { throw err$1( "Vite is unable to parse the glob options as the value is not static", optsStartIndex ); } if (opts == null) { return {}; } for (const key in opts) { if (!(key in knownOptions)) { throw err$1(`Unknown glob option "${key}"`, optsStartIndex); } const allowedTypes = knownOptions[key]; const valueType = typeof opts[key]; if (!allowedTypes.includes(valueType)) { throw err$1( `Expected glob option "${key}" to be of type ${allowedTypes.join( " or " )}, but got ${valueType}`, optsStartIndex ); } } if (typeof opts.query === "object") { for (const key in opts.query) { const value = opts.query[key]; if (!["string", "number", "boolean"].includes(typeof value)) { throw err$1( `Expected glob option "query.${key}" to be of type string, number, or boolean, but got ${typeof value}`, optsStartIndex ); } } opts.query = stringifyQuery(opts.query); } if (opts.as && logger) { const importSuggestion = forceDefaultAs.includes(opts.as) ? `, import: 'default'` : ""; logger.warn( colors$1.yellow( `The glob option "as" has been deprecated in favour of "query". Please update \`as: '${opts.as}'\` to \`query: '?${opts.as}'${importSuggestion}\`.` ) ); } if (opts.as && forceDefaultAs.includes(opts.as)) { if (opts.import && opts.import !== "default" && opts.import !== "*") throw err$1( `Option "import" can only be "default" or "*" when "as" is "${opts.as}", but got "${opts.import}"`, optsStartIndex ); opts.import = opts.import || "default"; } if (opts.as && opts.query) throw err$1( 'Options "as" and "query" cannot be used together', optsStartIndex ); if (opts.as) opts.query = opts.as; if (opts.query && opts.query[0] !== "?") opts.query = `?${opts.query}`; return opts; } async function parseImportGlob(code, importer, root, resolveId, logger) { let cleanCode; try { cleanCode = stripLiteral(code); } catch { return []; } const matches = Array.from(cleanCode.matchAll(importGlobRE)); const tasks = matches.map(async (match, index) => { const start = match.index; const err2 = (msg) => { const e = new Error(`Invalid glob import syntax: ${msg}`); e.pos = start; return e; }; const end = findCorrespondingCloseParenthesisPosition( cleanCode, start + match[0].length ) + 1; if (end <= 0) { throw err2("Close parenthesis not found"); } const statementCode = code.slice(start, end); const rootAst = (await parseAstAsync(statementCode)).body[0]; if (rootAst.type !== "ExpressionStatement") { throw err2(`Expect CallExpression, got ${rootAst.type}`); } const ast = rootAst.expression; if (ast.type !== "CallExpression") { throw err2(`Expect CallExpression, got ${ast.type}`); } if (ast.arguments.length < 1 || ast.arguments.length > 2) throw err2(`Expected 1-2 arguments, but got ${ast.arguments.length}`); const arg1 = ast.arguments[0]; const arg2 = ast.arguments[1]; const globs = []; const validateLiteral = (element) => { if (!element) return; if (element.type === "Literal") { if (typeof element.value !== "string") throw err2( `Expected glob to be a string, but got "${typeof element.value}"` ); globs.push(element.value); } else if (element.type === "TemplateLiteral") { if (element.expressions.length !== 0) { throw err2( `Expected glob to be a string, but got dynamic template literal` ); } globs.push(element.quasis[0].value.raw); } else { throw err2("Could only use literals"); } }; if (arg1.type === "ArrayExpression") { for (const element of arg1.elements) { validateLiteral(element); } } else { validateLiteral(arg1); } let options = {}; if (arg2) { if (arg2.type !== "ObjectExpression") throw err2( `Expected the second argument to be an object literal, but got "${arg2.type}"` ); options = parseGlobOptions( code.slice(start + arg2.start, start + arg2.end), start + arg2.start, logger ); } const globsResolved = await Promise.all( globs.map((glob2) => toAbsoluteGlob(glob2, root, importer, resolveId)) ); const isRelative = globs.every((i) => ".!".includes(i[0])); const sliceCode = cleanCode.slice(0, start); const onlyKeys = objectKeysRE.test(sliceCode); let onlyValues = false; if (!onlyKeys) { onlyValues = objectValuesRE.test(sliceCode); } return { index, globs, globsResolved, isRelative, options, start, end, onlyKeys, onlyValues }; }); return (await Promise.all(tasks)).filter(Boolean); } function findCorrespondingCloseParenthesisPosition(cleanCode, openPos) { const closePos = cleanCode.indexOf(")", openPos); if (closePos < 0) return -1; if (!cleanCode.slice(openPos, closePos).includes("(")) return closePos; let remainingParenthesisCount = 0; const cleanCodeLen = cleanCode.length; for (let pos = openPos; pos < cleanCodeLen; pos++) { switch (cleanCode[pos]) { case "(": { remainingParenthesisCount++; break; } case ")": { remainingParenthesisCount--; if (remainingParenthesisCount <= 0) { return pos; } } } } return -1; } const importPrefix = "__vite_glob_"; const { basename, dirname, relative } = posix$1; async function transformGlobImport(code, id, root, resolveId, restoreQueryExtension = false, logger) { id = slash$1(id); root = slash$1(root); const isVirtual = isVirtualModule(id); const dir = isVirtual ? void 0 : dirname(id); const matches = await parseImportGlob( code, isVirtual ? void 0 : id, root, resolveId, logger ); const matchedFiles = /* @__PURE__ */ new Set(); if (!matches.length) return null; const s = new MagicString(code); const staticImports = (await Promise.all( matches.map( async ({ globsResolved, isRelative, options, index, start, end, onlyKeys, onlyValues }) => { const cwd = getCommonBase(globsResolved) ?? root; const files = (await glob(globsResolved, { absolute: true, cwd, dot: !!options.exhaustive, expandDirectories: false, ignore: options.exhaustive ? [] : ["**/node_modules/**"] })).filter((file) => file !== id).sort(); const objectProps = []; const staticImports2 = []; const resolvePaths = (file) => { if (!dir) { if (isRelative) throw new Error( "In virtual modules, all globs must start with '/'" ); const filePath2 = `/${relative(root, file)}`; return { filePath: filePath2, importPath: filePath2 }; } let importPath = relative(dir, file); if (importPath[0] !== ".") importPath = `./${importPath}`; let filePath; if (isRelative) { filePath = importPath; } else { filePath = relative(root, file); if (filePath[0] !== ".") filePath = `/${filePath}`; } return { filePath, importPath }; }; files.forEach((file, i) => { const paths = resolvePaths(file); const filePath = paths.filePath; let importPath = paths.importPath; let importQuery = options.query ?? ""; if (onlyKeys) { objectProps.push(`${JSON.stringify(filePath)}: 0`); return; } if (importQuery && importQuery !== "?raw") { const fileExtension = basename(file).split(".").slice(-1)[0]; if (fileExtension && restoreQueryExtension) importQuery = `${importQuery}&lang.${fileExtension}`; } importPath = `${importPath}${importQuery}`; const importKey = options.import && options.import !== "*" ? options.import : void 0; if (options.eager) { const variableName = `${importPrefix}${index}_${i}`; const expression = importKey ? `{ ${importKey} as ${variableName} }` : `* as ${variableName}`; staticImports2.push( `import ${expression} from ${JSON.stringify(importPath)}` ); objectProps.push( onlyValues ? `${variableName}` : `${JSON.stringify(filePath)}: ${variableName}` ); } else { let importStatement = `import(${JSON.stringify(importPath)})`; if (importKey) importStatement += `.then(m => m[${JSON.stringify(importKey)}])`; objectProps.push( onlyValues ? `() => ${importStatement}` : `${JSON.stringify(filePath)}: () => ${importStatement}` ); } }); files.forEach((i) => matchedFiles.add(i)); const originalLineBreakCount = code.slice(start, end).match(/\n/g)?.length ?? 0; const lineBreaks = originalLineBreakCount > 0 ? "\n".repeat(originalLineBreakCount) : ""; let replacement = ""; if (onlyKeys) { replacement = `{${objectProps.join(",")}${lineBreaks}}`; } else if (onlyValues) { replacement = `[${objectProps.join(",")}${lineBreaks}]`; } else { replacement = `/* #__PURE__ */ Object.assign({${objectProps.join( "," )}${lineBreaks}})`; } s.overwrite(start, end, replacement); return staticImports2; } ) )).flat(); if (staticImports.length) s.prepend(`${staticImports.join(";")};`); return { s, matches, files: matchedFiles }; } function globSafePath(path) { return escapePath(normalizePath$3(path)); } function lastNthChar(str, n) { return str.charAt(str.length - 1 - n); } function globSafeResolvedPath(resolved, glob2) { let numEqual = 0; const maxEqual = Math.min(resolved.length, glob2.length); while (numEqual < maxEqual && lastNthChar(resolved, numEqual) === lastNthChar(glob2, numEqual)) { numEqual += 1; } const staticPartEnd = resolved.length - numEqual; const staticPart = resolved.slice(0, staticPartEnd); const dynamicPart = resolved.slice(staticPartEnd); return globSafePath(staticPart) + dynamicPart; } async function toAbsoluteGlob(glob2, root, importer, resolveId) { let pre = ""; if (glob2[0] === "!") { pre = "!"; glob2 = glob2.slice(1); } root = globSafePath(root); const dir = importer ? globSafePath(dirname(importer)) : root; if (glob2[0] === "/") return pre + posix$1.join(root, glob2.slice(1)); if (glob2.startsWith("./")) return pre + posix$1.join(dir, glob2.slice(2)); if (glob2.startsWith("../")) return pre + posix$1.join(dir, glob2); if (glob2.startsWith("**")) return pre + glob2; const isSubImportsPattern = glob2[0] === "#" && glob2.includes("*"); const resolved = normalizePath$3( await resolveId(glob2, importer, { custom: { "vite:import-glob": { isSubImportsPattern } } }) || glob2 ); if (isAbsolute$1(resolved)) { return pre + globSafeResolvedPath(resolved, glob2); } throw new Error( `Invalid glob: "${glob2}" (resolved: "${resolved}"). It must start with '/' or './'` ); } function getCommonBase(globsResolved) { const bases = globsResolved.filter((g) => g[0] !== "!").map((glob2) => { let { base } = picomatch$5.scan(glob2); if (posix$1.basename(base).includes(".")) base = posix$1.dirname(base); return base; }); if (!bases.length) return null; let commonAncestor = ""; const dirS = bases[0].split("/"); for (let i = 0; i < dirS.length; i++) { const candidate = dirS.slice(0, i + 1).join("/"); if (bases.every((base) => base.startsWith(candidate))) commonAncestor = candidate; else break; } if (!commonAncestor) commonAncestor = "/"; return commonAncestor; } function isVirtualModule(id) { return id.startsWith("virtual:") || id[0] === "\0" || !id.includes("/"); } class ScanEnvironment extends BaseEnvironment { mode = "scan"; get pluginContainer() { if (!this._pluginContainer) throw new Error( `${this.name} environment.pluginContainer called before initialized` ); return this._pluginContainer; } /** * @internal */ _pluginContainer; async init() { if (this._initiated) { return; } this._initiated = true; this._plugins = await resolveEnvironmentPlugins(this); this._pluginContainer = await createEnvironmentPluginContainer( this, this.plugins ); await this._pluginContainer.buildStart(); } } function devToScanEnvironment(environment) { return { mode: "scan", get name() { return environment.name; }, getTopLevelConfig() { return environment.getTopLevelConfig(); }, /** * @deprecated use environment.config instead **/ get options() { return environment.options; }, get config() { return environment.config; }, get logger() { return environment.logger; }, get pluginContainer() { return environment.pluginContainer; }, get plugins() { return environment.plugins; } }; } const debug$d = createDebugger("vite:deps"); const htmlTypesRE = /\.(html|vue|svelte|astro|imba)$/; const importsRE = /(? { entries = computedEntries; if (!entries.length) { if (!config.optimizeDeps.entries && !config.optimizeDeps.include) { environment.logger.warn( colors$1.yellow( "(!) Could not auto-determine entry point from rollupOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling." ) ); } return; } if (scanContext.cancelled) return; debug$d?.( `Crawling dependencies using entries: ${entries.map((entry) => ` ${colors$1.dim(entry)}`).join("")}` ); return prepareEsbuildScanner( environment, entries, deps, missing, scanContext ); }); const result = esbuildContext.then((context) => { function disposeContext() { return context?.dispose().catch((e) => { environment.logger.error("Failed to dispose esbuild context", { error: e }); }); } if (!context || scanContext?.cancelled) { disposeContext(); return { deps: {}, missing: {} }; } return context.rebuild().then(() => { return { // Ensure a fixed order so hashes are stable and improve logs deps: orderedDependencies(deps), missing }; }).finally(() => { return disposeContext(); }); }).catch(async (e) => { if (e.errors && e.message.includes("The build was canceled")) { return { deps: {}, missing: {} }; } const prependMessage = colors$1.red(` Failed to scan for dependencies from entries: ${entries.join("\n")} `); if (e.errors) { const msgs = await formatMessages(e.errors, { kind: "error", color: true }); e.message = prependMessage + msgs.join("\n"); } else { e.message = prependMessage + e.message; } throw e; }).finally(() => { if (debug$d) { const duration = (performance.now() - start).toFixed(2); const depsStr = Object.keys(orderedDependencies(deps)).sort().map((id) => ` ${colors$1.cyan(id)} -> ${colors$1.dim(deps[id])}`).join("") || colors$1.dim("no dependencies found"); debug$d(`Scan completed in ${duration}ms: ${depsStr}`); } }); return { cancel: async () => { scanContext.cancelled = true; return esbuildContext.then((context) => context?.cancel()); }, result }; } async function computeEntries(environment) { let entries = []; const explicitEntryPatterns = environment.config.optimizeDeps.entries; const buildInput = environment.config.build.rollupOptions?.input; if (explicitEntryPatterns) { entries = await globEntries(explicitEntryPatterns, environment); } else if (buildInput) { const resolvePath = async (p) => { const id = (await environment.pluginContainer.resolveId(p, void 0, { scan: true }))?.id; if (id === void 0) { throw new Error( `failed to resolve rollupOptions.input value: ${JSON.stringify(p)}.` ); } return id; }; if (typeof buildInput === "string") { entries = [await resolvePath(buildInput)]; } else if (Array.isArray(buildInput)) { entries = await Promise.all(buildInput.map(resolvePath)); } else if (isObject$2(buildInput)) { entries = await Promise.all(Object.values(buildInput).map(resolvePath)); } else { throw new Error("invalid rollupOptions.input value."); } } else { entries = await globEntries("**/*.html", environment); } entries = entries.filter( (entry) => isScannable(entry, environment.config.optimizeDeps.extensions) && fs__default.existsSync(entry) ); return entries; } async function prepareEsbuildScanner(environment, entries, deps, missing, scanContext) { if (scanContext?.cancelled) return; const plugin = esbuildScanPlugin(environment, deps, missing, entries); const { plugins = [], ...esbuildOptions } = environment.config.optimizeDeps.esbuildOptions ?? {}; let tsconfigRaw = esbuildOptions.tsconfigRaw; if (!tsconfigRaw && !esbuildOptions.tsconfig) { const { tsconfig } = await loadTsconfigJsonForFile( path$d.join(environment.config.root, "_dummy.js") ); if (tsconfig.compilerOptions?.experimentalDecorators) { tsconfigRaw = { compilerOptions: { experimentalDecorators: true } }; } } return await esbuild.context({ absWorkingDir: process.cwd(), write: false, stdin: { contents: entries.map((e) => `import ${JSON.stringify(e)}`).join("\n"), loader: "js" }, bundle: true, format: "esm", logLevel: "silent", plugins: [...plugins, plugin], ...esbuildOptions, tsconfigRaw }); } function orderedDependencies(deps) { const depsList = Object.entries(deps); depsList.sort((a, b) => a[0].localeCompare(b[0])); return Object.fromEntries(depsList); } function globEntries(pattern, environment) { const resolvedPatterns = arraify(pattern); if (resolvedPatterns.every((str) => !isDynamicPattern(str))) { return resolvedPatterns.map( (p) => normalizePath$3(path$d.resolve(environment.config.root, p)) ); } return glob(pattern, { absolute: true, cwd: environment.config.root, ignore: [ "**/node_modules/**", `**/${environment.config.build.outDir}/**`, // if there aren't explicit entries, also ignore other common folders ...environment.config.optimizeDeps.entries ? [] : [`**/__tests__/**`, `**/coverage/**`] ] }); } const scriptRE = /(=\s]+))?)*\s*>)(.*?)<\/script>/gis; const commentRE$1 = //gs; const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const svelteScriptModuleRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const svelteModuleRE = /\smodule\b/i; function esbuildScanPlugin(environment, depImports, missing, entries) { const seen = /* @__PURE__ */ new Map(); async function resolveId(id, importer, options) { return environment.pluginContainer.resolveId( id, importer && normalizePath$3(importer), { ...options, scan: true } ); } const resolve = async (id, importer, options) => { const key = id + (importer && path$d.dirname(importer)); if (seen.has(key)) { return seen.get(key); } const resolved = await resolveId(id, importer, options); const res = resolved?.id; seen.set(key, res); return res; }; const optimizeDepsOptions = environment.config.optimizeDeps; const include = optimizeDepsOptions.include; const exclude = [ ...optimizeDepsOptions.exclude ?? [], "@vite/client", "@vite/env" ]; const isUnlessEntry = (path2) => !entries.includes(path2); const externalUnlessEntry = ({ path: path2 }) => ({ path: path2, external: isUnlessEntry(path2) }); const doTransformGlobImport = async (contents, id, loader) => { let transpiledContents; if (loader !== "js") { transpiledContents = (await transform$1(contents, { loader })).code; } else { transpiledContents = contents; } const result = await transformGlobImport( transpiledContents, id, environment.config.root, resolve ); return result?.s.toString() || transpiledContents; }; return { name: "vite:dep-scan", setup(build) { const scripts = {}; build.onResolve({ filter: externalRE }, ({ path: path2 }) => ({ path: path2, external: true })); build.onResolve({ filter: dataUrlRE }, ({ path: path2 }) => ({ path: path2, external: true })); build.onResolve({ filter: virtualModuleRE }, ({ path: path2 }) => { return { // strip prefix to get valid filesystem path so esbuild can resolve imports in the file path: path2.replace(virtualModulePrefix, ""), namespace: "script" }; }); build.onLoad({ filter: /.*/, namespace: "script" }, ({ path: path2 }) => { return scripts[path2]; }); build.onResolve({ filter: htmlTypesRE }, async ({ path: path2, importer }) => { const resolved = await resolve(path2, importer); if (!resolved) return; if (isInNodeModules$1(resolved) && isOptimizable(resolved, optimizeDepsOptions)) return; return { path: resolved, namespace: "html" }; }); const htmlTypeOnLoadCallback = async ({ path: p }) => { let raw = await fsp.readFile(p, "utf-8"); raw = raw.replace(commentRE$1, ""); const isHtml = p.endsWith(".html"); let js = ""; let scriptId = 0; const matches = raw.matchAll(scriptRE); for (const [, openTag, content] of matches) { const typeMatch = typeRE.exec(openTag); const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]); const langMatch = langRE.exec(openTag); const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]); if (isHtml && type !== "module") { continue; } if (type && !(type.includes("javascript") || type.includes("ecmascript") || type === "module")) { continue; } let loader = "js"; if (lang === "ts" || lang === "tsx" || lang === "jsx") { loader = lang; } else if (p.endsWith(".astro")) { loader = "ts"; } const srcMatch = srcRE.exec(openTag); if (srcMatch) { const src = srcMatch[1] || srcMatch[2] || srcMatch[3]; js += `import ${JSON.stringify(src)} `; } else if (content.trim()) { const contents = content + (loader.startsWith("ts") ? extractImportPaths(content) : ""); const key = `${p}?id=${scriptId++}`; if (contents.includes("import.meta.glob")) { scripts[key] = { loader: "js", // since it is transpiled contents: await doTransformGlobImport(contents, p, loader), resolveDir: normalizePath$3(path$d.dirname(p)), pluginData: { htmlType: { loader } } }; } else { scripts[key] = { loader, contents, resolveDir: normalizePath$3(path$d.dirname(p)), pluginData: { htmlType: { loader } } }; } const virtualModulePath = JSON.stringify(virtualModulePrefix + key); let addedImport = false; if (p.endsWith(".svelte")) { let isModule = svelteModuleRE.test(openTag); if (!isModule) { const contextMatch = svelteScriptModuleRE.exec(openTag); const context = contextMatch && (contextMatch[1] || contextMatch[2] || contextMatch[3]); isModule = context === "module"; } if (!isModule) { addedImport = true; js += `import ${virtualModulePath} `; } } if (!addedImport) { js += `export * from ${virtualModulePath} `; } } } if (!p.endsWith(".vue") || !js.includes("export default")) { js += "\nexport default {}"; } return { loader: "js", contents: js }; }; build.onLoad( { filter: htmlTypesRE, namespace: "html" }, htmlTypeOnLoadCallback ); build.onLoad( { filter: htmlTypesRE, namespace: "file" }, htmlTypeOnLoadCallback ); build.onResolve( { // avoid matching windows volume filter: /^[\w@][^:]/ }, async ({ path: id, importer, pluginData }) => { if (moduleListContains(exclude, id)) { return externalUnlessEntry({ path: id }); } if (depImports[id]) { return externalUnlessEntry({ path: id }); } const resolved = await resolve(id, importer, { custom: { depScan: { loader: pluginData?.htmlType?.loader } } }); if (resolved) { if (shouldExternalizeDep(resolved, id)) { return externalUnlessEntry({ path: id }); } if (isInNodeModules$1(resolved) || include?.includes(id)) { if (isOptimizable(resolved, optimizeDepsOptions)) { depImports[id] = resolved; } return externalUnlessEntry({ path: id }); } else if (isScannable(resolved, optimizeDepsOptions.extensions)) { const namespace = htmlTypesRE.test(resolved) ? "html" : void 0; return { path: path$d.resolve(resolved), namespace }; } else { return externalUnlessEntry({ path: id }); } } else { missing[id] = normalizePath$3(importer); } } ); const setupExternalize = (filter, doExternalize) => { build.onResolve({ filter }, ({ path: path2 }) => { return { path: path2, external: doExternalize(path2) }; }); }; setupExternalize(CSS_LANGS_RE, isUnlessEntry); setupExternalize(/\.(json|json5|wasm)$/, isUnlessEntry); setupExternalize( new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`), isUnlessEntry ); setupExternalize(SPECIAL_QUERY_RE, () => true); build.onResolve( { filter: /.*/ }, async ({ path: id, importer, pluginData }) => { const resolved = await resolve(id, importer, { custom: { depScan: { loader: pluginData?.htmlType?.loader } } }); if (resolved) { if (shouldExternalizeDep(resolved, id) || !isScannable(resolved, optimizeDepsOptions.extensions)) { return externalUnlessEntry({ path: id }); } const namespace = htmlTypesRE.test(resolved) ? "html" : void 0; return { path: path$d.resolve(cleanUrl(resolved)), namespace }; } else { return externalUnlessEntry({ path: id }); } } ); build.onLoad({ filter: JS_TYPES_RE }, async ({ path: id }) => { let ext = path$d.extname(id).slice(1); if (ext === "mjs") ext = "js"; const esbuildConfig = environment.config.esbuild; let contents = await fsp.readFile(id, "utf-8"); if (ext.endsWith("x") && esbuildConfig && esbuildConfig.jsxInject) { contents = esbuildConfig.jsxInject + ` ` + contents; } const loader = optimizeDepsOptions.esbuildOptions?.loader?.[`.${ext}`] ?? ext; if (contents.includes("import.meta.glob")) { return { loader: "js", // since it is transpiled, contents: await doTransformGlobImport(contents, id, loader) }; } return { loader, contents }; }); build.onLoad({ filter: /.*/, namespace: "file" }, () => { return { loader: "js", contents: "export default {}" }; }); } }; } function extractImportPaths(code) { code = code.replace(multilineCommentsRE, "/* */").replace(singlelineCommentsRE, ""); let js = ""; let m; importsRE.lastIndex = 0; while ((m = importsRE.exec(code)) != null) { js += ` import ${m[1]}`; } return js; } function shouldExternalizeDep(resolvedId, rawId) { if (!path$d.isAbsolute(resolvedId)) { return true; } if (resolvedId === rawId || resolvedId.includes("\0")) { return true; } return false; } function isScannable(id, extensions) { return JS_TYPES_RE.test(id) || htmlTypesRE.test(id) || extensions?.includes(path$d.extname(id)) || false; } function createOptimizeDepsIncludeResolver(environment) { const topLevelConfig = environment.getTopLevelConfig(); const resolve = createBackCompatIdResolver(topLevelConfig, { asSrc: false, scan: true, packageCache: /* @__PURE__ */ new Map() }); return async (id) => { const lastArrowIndex = id.lastIndexOf(">"); if (lastArrowIndex === -1) { return await resolve(environment, id, void 0); } const nestedRoot = id.substring(0, lastArrowIndex).trim(); const nestedPath = id.substring(lastArrowIndex + 1).trim(); const basedir = nestedResolveBasedir( nestedRoot, topLevelConfig.root, topLevelConfig.resolve.preserveSymlinks ); return await resolve( environment, nestedPath, path$d.resolve(basedir, "package.json") ); }; } function expandGlobIds(id, config) { const pkgName = getNpmPackageName(id); if (!pkgName) return []; const pkgData = resolvePackageData( pkgName, config.root, config.resolve.preserveSymlinks, config.packageCache ); if (!pkgData) return []; const pattern = "." + id.slice(pkgName.length); const exports = pkgData.data.exports; if (exports) { if (typeof exports === "string" || Array.isArray(exports)) { return [pkgName]; } const possibleExportPaths = []; for (const key in exports) { if (key[0] === ".") { if (key.includes("*")) { const exportsValue = getFirstExportStringValue(exports[key]); if (!exportsValue) continue; const exportValuePattern = exportsValue.replace(/\*/g, "**/*"); const exportsValueGlobRe = new RegExp( exportsValue.split("*").map(escapeRegex).join("(.*)") ); possibleExportPaths.push( ...globSync(exportValuePattern, { cwd: pkgData.dir, expandDirectories: false, ignore: ["node_modules"] }).map((filePath) => { if (exportsValue.startsWith("./")) { filePath = "./" + filePath; } const matched2 = exportsValueGlobRe.exec(slash$1(filePath)); if (matched2) { let allGlobSame = matched2.length === 2; if (!allGlobSame) { allGlobSame = true; for (let i = 2; i < matched2.length; i++) { if (matched2[i] !== matched2[i - 1]) { allGlobSame = false; break; } } } if (allGlobSame) { return key.replace("*", matched2[1]).slice(2); } } return ""; }).filter(Boolean) ); } else { possibleExportPaths.push(key.slice(2)); } } } const matched = possibleExportPaths.filter(picomatch$5(pattern)).map((match) => path$d.posix.join(pkgName, match)); matched.unshift(pkgName); return matched; } else { const matched = globSync(pattern, { cwd: pkgData.dir, expandDirectories: false, ignore: ["node_modules"] }).map((match) => path$d.posix.join(pkgName, slash$1(match))); matched.unshift(pkgName); return matched; } } function getFirstExportStringValue(obj) { if (typeof obj === "string") { return obj; } else if (Array.isArray(obj)) { return obj[0]; } else { for (const key in obj) { return getFirstExportStringValue(obj[key]); } } } function nestedResolveBasedir(id, basedir, preserveSymlinks = false) { const pkgs = id.split(">").map((pkg) => pkg.trim()); for (const pkg of pkgs) { basedir = resolvePackageData(pkg, basedir, preserveSymlinks)?.dir || basedir; } return basedir; } const debug$c = createDebugger("vite:deps"); const jsExtensionRE = /\.js$/i; const jsMapExtensionRE = /\.js\.map$/i; function isDepOptimizationDisabled(optimizeDeps2) { return optimizeDeps2.disabled === true || optimizeDeps2.disabled === "dev" || !!optimizeDeps2.noDiscovery && !optimizeDeps2.include?.length; } async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) { const log = asCommand ? config.logger.info : debug$c; const environment = new ScanEnvironment("client", config); await environment.init(); const cachedMetadata = await loadCachedDepOptimizationMetadata( environment, force, asCommand ); if (cachedMetadata) { return cachedMetadata; } const deps = await discoverProjectDependencies(environment).result; await addManuallyIncludedOptimizeDeps(environment, deps); const depsString = depsLogString(Object.keys(deps)); log?.(colors$1.green(`Optimizing dependencies: ${depsString}`)); const depsInfo = toDiscoveredDependencies(environment, deps); const result = await runOptimizeDeps(environment, depsInfo).result; await result.commit(); return result.metadata; } async function optimizeExplicitEnvironmentDeps(environment) { const cachedMetadata = await loadCachedDepOptimizationMetadata( environment, environment.config.optimizeDeps.force ?? false, false ); if (cachedMetadata) { return cachedMetadata; } const deps = {}; await addManuallyIncludedOptimizeDeps(environment, deps); const depsInfo = toDiscoveredDependencies(environment, deps); const result = await runOptimizeDeps(environment, depsInfo).result; await result.commit(); return result.metadata; } function initDepsOptimizerMetadata(environment, timestamp) { const { lockfileHash, configHash, hash } = getDepHash(environment); return { hash, lockfileHash, configHash, browserHash: getOptimizedBrowserHash(hash, {}, timestamp), optimized: {}, chunks: {}, discovered: {}, depInfoList: [] }; } function addOptimizedDepInfo(metadata, type, depInfo) { metadata[type][depInfo.id] = depInfo; metadata.depInfoList.push(depInfo); return depInfo; } let firstLoadCachedDepOptimizationMetadata = true; async function loadCachedDepOptimizationMetadata(environment, force = environment.config.optimizeDeps?.force ?? false, asCommand = false) { const log = asCommand ? environment.logger.info : debug$c; if (firstLoadCachedDepOptimizationMetadata) { firstLoadCachedDepOptimizationMetadata = false; setTimeout( () => cleanupDepsCacheStaleDirs(environment.getTopLevelConfig()), 0 ); } const depsCacheDir = getDepsCacheDir(environment); if (!force) { let cachedMetadata; try { const cachedMetadataPath = path$d.join(depsCacheDir, METADATA_FILENAME); cachedMetadata = parseDepsOptimizerMetadata( await fsp.readFile(cachedMetadataPath, "utf-8"), depsCacheDir ); } catch { } if (cachedMetadata) { if (cachedMetadata.lockfileHash !== getLockfileHash(environment)) { environment.logger.info( "Re-optimizing dependencies because lockfile has changed" ); } else if (cachedMetadata.configHash !== getConfigHash(environment)) { environment.logger.info( "Re-optimizing dependencies because vite config has changed" ); } else { log?.("Hash is consistent. Skipping. Use --force to override."); return cachedMetadata; } } } else { environment.logger.info("Forced re-optimization of dependencies"); } debug$c?.(colors$1.green(`removing old cache dir ${depsCacheDir}`)); await fsp.rm(depsCacheDir, { recursive: true, force: true }); } function discoverProjectDependencies(environment) { const { cancel, result } = scanImports(environment); return { cancel, result: result.then(({ deps, missing }) => { const missingIds = Object.keys(missing); if (missingIds.length) { throw new Error( `The following dependencies are imported but could not be resolved: ${missingIds.map( (id) => `${colors$1.cyan(id)} ${colors$1.white( colors$1.dim(`(imported by ${missing[id]})`) )}` ).join(` `)} Are they installed?` ); } return deps; }) }; } function toDiscoveredDependencies(environment, deps, timestamp) { const browserHash = getOptimizedBrowserHash( getDepHash(environment).hash, deps, timestamp ); const discovered = {}; for (const id in deps) { const src = deps[id]; discovered[id] = { id, file: getOptimizedDepPath(environment, id), src, browserHash, exportsData: extractExportsData(environment, src) }; } return discovered; } function depsLogString(qualifiedIds) { return colors$1.yellow(qualifiedIds.join(`, `)); } function runOptimizeDeps(environment, depsInfo) { const optimizerContext = { cancelled: false }; const depsCacheDir = getDepsCacheDir(environment); const processingCacheDir = getProcessingDepsCacheDir(environment); fs__default.mkdirSync(processingCacheDir, { recursive: true }); debug$c?.(colors$1.green(`creating package.json in ${processingCacheDir}`)); fs__default.writeFileSync( path$d.resolve(processingCacheDir, "package.json"), `{ "type": "module" } ` ); const metadata = initDepsOptimizerMetadata(environment); metadata.browserHash = getOptimizedBrowserHash( metadata.hash, depsFromOptimizedDepInfo(depsInfo) ); const qualifiedIds = Object.keys(depsInfo); let cleaned = false; let committed = false; const cleanUp = () => { if (!cleaned && !committed) { cleaned = true; debug$c?.(colors$1.green(`removing cache dir ${processingCacheDir}`)); try { fs__default.rmSync(processingCacheDir, { recursive: true, force: true }); } catch { } } }; const successfulResult = { metadata, cancel: cleanUp, commit: async () => { if (cleaned) { throw new Error( "Can not commit a Deps Optimization run as it was cancelled" ); } committed = true; const dataPath = path$d.join(processingCacheDir, METADATA_FILENAME); debug$c?.( colors$1.green(`creating ${METADATA_FILENAME} in ${processingCacheDir}`) ); fs__default.writeFileSync( dataPath, stringifyDepsOptimizerMetadata(metadata, depsCacheDir) ); const temporaryPath = depsCacheDir + getTempSuffix(); const depsCacheDirPresent = fs__default.existsSync(depsCacheDir); if (isWindows$3) { if (depsCacheDirPresent) { debug$c?.(colors$1.green(`renaming ${depsCacheDir} to ${temporaryPath}`)); await safeRename(depsCacheDir, temporaryPath); } debug$c?.( colors$1.green(`renaming ${processingCacheDir} to ${depsCacheDir}`) ); await safeRename(processingCacheDir, depsCacheDir); } else { if (depsCacheDirPresent) { debug$c?.(colors$1.green(`renaming ${depsCacheDir} to ${temporaryPath}`)); fs__default.renameSync(depsCacheDir, temporaryPath); } debug$c?.( colors$1.green(`renaming ${processingCacheDir} to ${depsCacheDir}`) ); fs__default.renameSync(processingCacheDir, depsCacheDir); } if (depsCacheDirPresent) { debug$c?.(colors$1.green(`removing cache temp dir ${temporaryPath}`)); fsp.rm(temporaryPath, { recursive: true, force: true }); } } }; if (!qualifiedIds.length) { return { cancel: async () => cleanUp(), result: Promise.resolve(successfulResult) }; } const cancelledResult = { metadata, commit: async () => cleanUp(), cancel: cleanUp }; const start = performance.now(); const preparedRun = prepareEsbuildOptimizerRun( environment, depsInfo, processingCacheDir, optimizerContext ); const runResult = preparedRun.then(({ context, idToExports }) => { function disposeContext() { return context?.dispose().catch((e) => { environment.logger.error("Failed to dispose esbuild context", { error: e }); }); } if (!context || optimizerContext.cancelled) { disposeContext(); return cancelledResult; } return context.rebuild().then((result) => { const meta = result.metafile; const processingCacheDirOutputPath = path$d.relative( process.cwd(), processingCacheDir ); for (const id in depsInfo) { const output = esbuildOutputFromId( meta.outputs, id, processingCacheDir ); const { exportsData, ...info } = depsInfo[id]; addOptimizedDepInfo(metadata, "optimized", { ...info, // We only need to hash the output.imports in to check for stability, but adding the hash // and file path gives us a unique hash that may be useful for other things in the future fileHash: getHash( metadata.hash + depsInfo[id].file + JSON.stringify(output.imports) ), browserHash: metadata.browserHash, // After bundling we have more information and can warn the user about legacy packages // that require manual configuration needsInterop: needsInterop( environment, id, idToExports[id], output ) }); } for (const o of Object.keys(meta.outputs)) { if (!jsMapExtensionRE.test(o)) { const id = path$d.relative(processingCacheDirOutputPath, o).replace(jsExtensionRE, ""); const file = getOptimizedDepPath(environment, id); if (!findOptimizedDepInfoInRecord( metadata.optimized, (depInfo) => depInfo.file === file )) { addOptimizedDepInfo(metadata, "chunks", { id, file, needsInterop: false, browserHash: metadata.browserHash }); } } else { const output = meta.outputs[o]; if (output.bytes === 93) { const jsMapPath = path$d.resolve(o); const jsPath = jsMapPath.slice(0, -4); if (fs__default.existsSync(jsPath) && fs__default.existsSync(jsMapPath)) { const map = JSON.parse(fs__default.readFileSync(jsMapPath, "utf-8")); if (map.sources.length === 0) { const js = fs__default.readFileSync(jsPath, "utf-8"); fs__default.writeFileSync( jsPath, js.slice(0, js.lastIndexOf("//# sourceMappingURL=")) ); } } } } } debug$c?.( `Dependencies bundled in ${(performance.now() - start).toFixed(2)}ms` ); return successfulResult; }).catch((e) => { if (e.errors && e.message.includes("The build was canceled")) { return cancelledResult; } throw e; }).finally(() => { return disposeContext(); }); }); runResult.catch(() => { cleanUp(); }); return { async cancel() { optimizerContext.cancelled = true; const { context } = await preparedRun; await context?.cancel(); cleanUp(); }, result: runResult }; } async function prepareEsbuildOptimizerRun(environment, depsInfo, processingCacheDir, optimizerContext) { const flatIdDeps = {}; const idToExports = {}; const { optimizeDeps: optimizeDeps2 } = environment.config; const { plugins: pluginsFromConfig = [], ...esbuildOptions } = optimizeDeps2?.esbuildOptions ?? {}; await Promise.all( Object.keys(depsInfo).map(async (id) => { const src = depsInfo[id].src; const exportsData = await (depsInfo[id].exportsData ?? extractExportsData(environment, src)); if (exportsData.jsxLoader && !esbuildOptions.loader?.[".js"]) { esbuildOptions.loader = { ".js": "jsx", ...esbuildOptions.loader }; } const flatId = flattenId(id); flatIdDeps[flatId] = src; idToExports[id] = exportsData; }) ); if (optimizerContext.cancelled) return { context: void 0, idToExports }; const define = { "process.env.NODE_ENV": JSON.stringify( process.env.NODE_ENV || environment.config.mode ) }; const platform = optimizeDeps2.esbuildOptions?.platform ?? // We generally don't want to use platform 'neutral', as esbuild has custom handling // when the platform is 'node' or 'browser' that can't be emulated by using mainFields // and conditions (environment.config.consumer === "client" || environment.config.ssr.target === "webworker" ? "browser" : "node"); const external = [...optimizeDeps2?.exclude ?? []]; const plugins = [...pluginsFromConfig]; if (external.length) { plugins.push(esbuildCjsExternalPlugin(external, platform)); } plugins.push(esbuildDepPlugin(environment, flatIdDeps, external)); const context = await esbuild.context({ absWorkingDir: process.cwd(), entryPoints: Object.keys(flatIdDeps), bundle: true, platform, define, format: "esm", // See https://github.com/evanw/esbuild/issues/1921#issuecomment-1152991694 banner: platform === "node" ? { js: `import { createRequire } from 'module';const require = createRequire(import.meta.url);` } : void 0, target: ESBUILD_MODULES_TARGET, external, logLevel: "error", splitting: true, sourcemap: true, outdir: processingCacheDir, ignoreAnnotations: true, metafile: true, plugins, charset: "utf8", ...esbuildOptions, supported: { ...defaultEsbuildSupported, ...esbuildOptions.supported } }); return { context, idToExports }; } async function addManuallyIncludedOptimizeDeps(environment, deps) { const { logger } = environment; const { optimizeDeps: optimizeDeps2 } = environment.config; const optimizeDepsInclude = optimizeDeps2?.include ?? []; if (optimizeDepsInclude.length) { const unableToOptimize = (id, msg) => { if (optimizeDepsInclude.includes(id)) { logger.warn( `${msg}: ${colors$1.cyan(id)}, present in ${environment.name} 'optimizeDeps.include'` ); } }; const includes = [...optimizeDepsInclude]; for (let i = 0; i < includes.length; i++) { const id = includes[i]; if (isDynamicPattern(id)) { const globIds = expandGlobIds(id, environment.getTopLevelConfig()); includes.splice(i, 1, ...globIds); i += globIds.length - 1; } } const resolve = createOptimizeDepsIncludeResolver(environment); for (const id of includes) { const normalizedId = normalizeId(id); if (!deps[normalizedId]) { const entry = await resolve(id); if (entry) { if (isOptimizable(entry, optimizeDeps2)) { deps[normalizedId] = entry; } else { unableToOptimize(id, "Cannot optimize dependency"); } } else { unableToOptimize(id, "Failed to resolve dependency"); } } } } } function depsFromOptimizedDepInfo(depsInfo) { const obj = {}; for (const key in depsInfo) { obj[key] = depsInfo[key].src; } return obj; } function getOptimizedDepPath(environment, id) { return normalizePath$3( path$d.resolve(getDepsCacheDir(environment), flattenId(id) + ".js") ); } function getDepsCacheSuffix(environment) { return environment.name === "client" ? "" : `_${environment.name}`; } function getDepsCacheDir(environment) { return getDepsCacheDirPrefix(environment) + getDepsCacheSuffix(environment); } function getProcessingDepsCacheDir(environment) { return getDepsCacheDirPrefix(environment) + getDepsCacheSuffix(environment) + getTempSuffix(); } function getTempSuffix() { return "_temp_" + getHash( `${process.pid}:${Date.now().toString()}:${Math.random().toString(16).slice(2)}` ); } function getDepsCacheDirPrefix(environment) { return normalizePath$3(path$d.resolve(environment.config.cacheDir, "deps")); } function createIsOptimizedDepFile(environment) { const depsCacheDirPrefix = getDepsCacheDirPrefix(environment); return (id) => id.startsWith(depsCacheDirPrefix); } function createIsOptimizedDepUrl(environment) { const { root } = environment.config; const depsCacheDir = getDepsCacheDirPrefix(environment); const depsCacheDirRelative = normalizePath$3(path$d.relative(root, depsCacheDir)); const depsCacheDirPrefix = depsCacheDirRelative.startsWith("../") ? ( // if the cache directory is outside root, the url prefix would be something // like '/@fs/absolute/path/to/node_modules/.vite' `/@fs/${removeLeadingSlash(normalizePath$3(depsCacheDir))}` ) : ( // if the cache directory is inside root, the url prefix would be something // like '/node_modules/.vite' `/${depsCacheDirRelative}` ); return function isOptimizedDepUrl(url) { return url.startsWith(depsCacheDirPrefix); }; } function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) { const { hash, lockfileHash, configHash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => { if (key === "file" || key === "src") { return normalizePath$3(path$d.resolve(depsCacheDir, value)); } return value; }); if (!chunks || Object.values(optimized).some((depInfo) => !depInfo.fileHash)) { return; } const metadata = { hash, lockfileHash, configHash, browserHash, optimized: {}, discovered: {}, chunks: {}, depInfoList: [] }; for (const id of Object.keys(optimized)) { addOptimizedDepInfo(metadata, "optimized", { ...optimized[id], id, browserHash }); } for (const id of Object.keys(chunks)) { addOptimizedDepInfo(metadata, "chunks", { ...chunks[id], id, browserHash, needsInterop: false }); } return metadata; } function stringifyDepsOptimizerMetadata(metadata, depsCacheDir) { const { hash, configHash, lockfileHash, browserHash, optimized, chunks } = metadata; return JSON.stringify( { hash, configHash, lockfileHash, browserHash, optimized: Object.fromEntries( Object.values(optimized).map( ({ id, src, file, fileHash, needsInterop: needsInterop2 }) => [ id, { src, file, fileHash, needsInterop: needsInterop2 } ] ) ), chunks: Object.fromEntries( Object.values(chunks).map(({ id, file }) => [id, { file }]) ) }, (key, value) => { if (key === "file" || key === "src") { return normalizePath$3(path$d.relative(depsCacheDir, value)); } return value; }, 2 ); } function esbuildOutputFromId(outputs, id, cacheDirOutputPath) { const cwd = process.cwd(); const flatId = flattenId(id) + ".js"; const normalizedOutputPath = normalizePath$3( path$d.relative(cwd, path$d.join(cacheDirOutputPath, flatId)) ); const output = outputs[normalizedOutputPath]; if (output) { return output; } for (const [key, value] of Object.entries(outputs)) { if (normalizePath$3(path$d.relative(cwd, key)) === normalizedOutputPath) { return value; } } } async function extractExportsData(environment, filePath) { await init; const { optimizeDeps: optimizeDeps2 } = environment.config; const esbuildOptions = optimizeDeps2?.esbuildOptions ?? {}; if (optimizeDeps2.extensions?.some((ext) => filePath.endsWith(ext))) { const result = await build$b({ ...esbuildOptions, entryPoints: [filePath], write: false, format: "esm" }); const [, exports2, , hasModuleSyntax2] = parse$e(result.outputFiles[0].text); return { hasModuleSyntax: hasModuleSyntax2, exports: exports2.map((e) => e.n) }; } let parseResult; let usedJsxLoader = false; const entryContent = await fsp.readFile(filePath, "utf-8"); try { parseResult = parse$e(entryContent); } catch { const loader = esbuildOptions.loader?.[path$d.extname(filePath)] || "jsx"; debug$c?.( `Unable to parse: ${filePath}. Trying again with a ${loader} transform.` ); const transformed = await transformWithEsbuild( entryContent, filePath, { loader }, void 0, environment.config ); parseResult = parse$e(transformed.code); usedJsxLoader = true; } const [, exports, , hasModuleSyntax] = parseResult; const exportsData = { hasModuleSyntax, exports: exports.map((e) => e.n), jsxLoader: usedJsxLoader }; return exportsData; } function needsInterop(environment, id, exportsData, output) { if (environment.config.optimizeDeps?.needsInterop?.includes(id)) { return true; } const { hasModuleSyntax, exports } = exportsData; if (!hasModuleSyntax) { return true; } if (output) { const generatedExports = output.exports; if (!generatedExports || isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports)) { return true; } } return false; } function isSingleDefaultExport(exports) { return exports.length === 1 && exports[0] === "default"; } const lockfileFormats = [ { path: "node_modules/.package-lock.json", checkPatches: true, manager: "npm" }, { // Yarn non-PnP path: "node_modules/.yarn-state.yml", checkPatches: false, manager: "yarn" }, { // Yarn PnP path: ".yarn/install-state", checkPatches: false, manager: "yarn" }, { // yarn 1 path: "node_modules/.yarn-integrity", checkPatches: true, manager: "yarn" }, { path: "node_modules/.pnpm/lock.yaml", // Included in lockfile checkPatches: false, manager: "pnpm" }, { name: "bun.lockb", path: "bun.lockb", checkPatches: true, manager: "bun" } ].sort((_, { manager }) => { return process.env.npm_config_user_agent?.startsWith(manager) ? 1 : -1; }); const lockfilePaths = lockfileFormats.map((l) => l.path); function getConfigHash(environment) { const { config } = environment; const { optimizeDeps: optimizeDeps2 } = config; const content = JSON.stringify( { mode: process.env.NODE_ENV || config.mode, root: config.root, resolve: config.resolve, assetsInclude: config.assetsInclude, plugins: config.plugins.map((p) => p.name), optimizeDeps: { include: optimizeDeps2?.include ? unique(optimizeDeps2.include).sort() : void 0, exclude: optimizeDeps2?.exclude ? unique(optimizeDeps2.exclude).sort() : void 0, esbuildOptions: { ...optimizeDeps2?.esbuildOptions, plugins: optimizeDeps2?.esbuildOptions?.plugins?.map((p) => p.name) } } }, (_, value) => { if (typeof value === "function" || value instanceof RegExp) { return value.toString(); } return value; } ); return getHash(content); } function getLockfileHash(environment) { const lockfilePath = lookupFile(environment.config.root, lockfilePaths); let content = lockfilePath ? fs__default.readFileSync(lockfilePath, "utf-8") : ""; if (lockfilePath) { const normalizedLockfilePath = lockfilePath.replaceAll("\\", "/"); const lockfileFormat = lockfileFormats.find( (f) => normalizedLockfilePath.endsWith(f.path) ); if (lockfileFormat.checkPatches) { const baseDir = lockfilePath.slice(0, -lockfileFormat.path.length); const fullPath = path$d.join(baseDir, "patches"); const stat = tryStatSync(fullPath); if (stat?.isDirectory()) { content += stat.mtimeMs.toString(); } } } return getHash(content); } function getDepHash(environment) { const lockfileHash = getLockfileHash(environment); const configHash = getConfigHash(environment); const hash = getHash(lockfileHash + configHash); return { hash, lockfileHash, configHash }; } function getOptimizedBrowserHash(hash, deps, timestamp = "") { return getHash(hash + JSON.stringify(deps) + timestamp); } function optimizedDepInfoFromId(metadata, id) { return metadata.optimized[id] || metadata.discovered[id] || metadata.chunks[id]; } function optimizedDepInfoFromFile(metadata, file) { return metadata.depInfoList.find((depInfo) => depInfo.file === file); } function findOptimizedDepInfoInRecord(dependenciesInfo, callbackFn) { for (const o of Object.keys(dependenciesInfo)) { const info = dependenciesInfo[o]; if (callbackFn(info, o)) { return info; } } } async function optimizedDepNeedsInterop(environment, metadata, file) { const depInfo = optimizedDepInfoFromFile(metadata, file); if (depInfo?.src && depInfo.needsInterop === void 0) { depInfo.exportsData ??= extractExportsData(environment, depInfo.src); depInfo.needsInterop = needsInterop( environment, depInfo.id, await depInfo.exportsData ); } return depInfo?.needsInterop; } const MAX_TEMP_DIR_AGE_MS = 24 * 60 * 60 * 1e3; async function cleanupDepsCacheStaleDirs(config) { try { const cacheDir = path$d.resolve(config.cacheDir); if (fs__default.existsSync(cacheDir)) { const dirents = await fsp.readdir(cacheDir, { withFileTypes: true }); for (const dirent of dirents) { if (dirent.isDirectory() && dirent.name.includes("_temp_")) { const tempDirPath = path$d.resolve(config.cacheDir, dirent.name); const stats = await fsp.stat(tempDirPath).catch(() => null); if (stats?.mtime && Date.now() - stats.mtime.getTime() > MAX_TEMP_DIR_AGE_MS) { debug$c?.(`removing stale cache temp dir ${tempDirPath}`); await fsp.rm(tempDirPath, { recursive: true, force: true }); } } } } } catch (err) { config.logger.error(err); } } const GRACEFUL_RENAME_TIMEOUT = 5e3; const safeRename = promisify$4(function gracefulRename(from, to, cb) { const start = Date.now(); let backoff = 0; fs__default.rename(from, to, function CB(er) { if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < GRACEFUL_RENAME_TIMEOUT) { setTimeout(function() { fs__default.stat(to, function(stater, _st) { if (stater && stater.code === "ENOENT") fs__default.rename(from, to, CB); else CB(er); }); }, backoff); if (backoff < 100) backoff += 10; return; } if (cb) cb(er); }); }); var index$1 = { __proto__: null, addManuallyIncludedOptimizeDeps: addManuallyIncludedOptimizeDeps, addOptimizedDepInfo: addOptimizedDepInfo, cleanupDepsCacheStaleDirs: cleanupDepsCacheStaleDirs, createIsOptimizedDepFile: createIsOptimizedDepFile, createIsOptimizedDepUrl: createIsOptimizedDepUrl, depsFromOptimizedDepInfo: depsFromOptimizedDepInfo, depsLogString: depsLogString, discoverProjectDependencies: discoverProjectDependencies, extractExportsData: extractExportsData, getDepsCacheDir: getDepsCacheDir, getOptimizedDepPath: getOptimizedDepPath, initDepsOptimizerMetadata: initDepsOptimizerMetadata, isDepOptimizationDisabled: isDepOptimizationDisabled, loadCachedDepOptimizationMetadata: loadCachedDepOptimizationMetadata, optimizeDeps: optimizeDeps, optimizeExplicitEnvironmentDeps: optimizeExplicitEnvironmentDeps, optimizedDepInfoFromFile: optimizedDepInfoFromFile, optimizedDepInfoFromId: optimizedDepInfoFromId, optimizedDepNeedsInterop: optimizedDepNeedsInterop, runOptimizeDeps: runOptimizeDeps, toDiscoveredDependencies: toDiscoveredDependencies }; const jsonExtRE = /\.json(?:$|\?)(?!commonjs-(?:proxy|external))/; const jsonObjRE = /^\s*\{/; const jsonLangs = `\\.(?:json|json5)(?:$|\\?)`; const jsonLangRE = new RegExp(jsonLangs); const isJSONRequest = (request) => jsonLangRE.test(request); function jsonPlugin(options, isBuild) { return { name: "vite:json", transform(json, id) { if (!jsonExtRE.test(id)) return null; if (SPECIAL_QUERY_RE.test(id)) return null; json = stripBomTag(json); try { if (options.stringify !== false) { if (options.namedExports && jsonObjRE.test(json)) { const parsed = JSON.parse(json); const keys = Object.keys(parsed); let code = ""; let defaultObjectCode = "{\n"; for (const key of keys) { if (key === makeLegalIdentifier(key)) { code += `export const ${key} = ${serializeValue(parsed[key])}; `; defaultObjectCode += ` ${key}, `; } else { defaultObjectCode += ` ${JSON.stringify(key)}: ${serializeValue(parsed[key])}, `; } } defaultObjectCode += "}"; code += `export default ${defaultObjectCode}; `; return { code, map: { mappings: "" } }; } if (options.stringify === true || // use 10kB as a threshold // https://v8.dev/blog/cost-of-javascript-2019#:~:text=A%20good%20rule%20of%20thumb%20is%20to%20apply%20this%20technique%20for%20objects%20of%2010%20kB%20or%20larger options.stringify === "auto" && json.length > 10 * 1e3) { if (isBuild) { json = JSON.stringify(JSON.parse(json)); } return { code: `export default JSON.parse(${JSON.stringify(json)})`, map: { mappings: "" } }; } } return { code: dataToEsm(JSON.parse(json), { preferConst: true, namedExports: options.namedExports }), map: { mappings: "" } }; } catch (e) { const position = extractJsonErrorPosition(e.message, json.length); const msg = position ? `, invalid JSON syntax found at position ${position}` : `.`; this.error(`Failed to parse JSON file` + msg, position); } } }; } function serializeValue(value) { const valueAsString = JSON.stringify(value); if (typeof value === "object" && value != null && valueAsString.length > 10 * 1e3) { return `JSON.parse(${JSON.stringify(valueAsString)})`; } return valueAsString; } function extractJsonErrorPosition(errorMessage, inputLength) { if (errorMessage.startsWith("Unexpected end of JSON input")) { return inputLength - 1; } const errorMessageList = /at position (\d+)/.exec(errorMessage); return errorMessageList ? Math.max(parseInt(errorMessageList[1], 10) - 1, 0) : void 0; } const debug$b = createDebugger("vite:optimize-deps"); function optimizedDepsPlugin() { return { name: "vite:optimized-deps", resolveId(id) { const environment = this.environment; if (environment.depsOptimizer?.isOptimizedDepFile(id)) { return id; } }, // this.load({ id }) isn't implemented in PluginContainer // The logic to register an id to wait until it is processed // is in importAnalysis, see call to delayDepsOptimizerUntil async load(id) { const environment = this.environment; const depsOptimizer = environment.depsOptimizer; if (depsOptimizer?.isOptimizedDepFile(id)) { const metadata = depsOptimizer.metadata; const file = cleanUrl(id); const versionMatch = DEP_VERSION_RE.exec(file); const browserHash = versionMatch ? versionMatch[1].split("=")[1] : void 0; const info = optimizedDepInfoFromFile(metadata, file); if (info) { if (browserHash && info.browserHash !== browserHash) { throwOutdatedRequest(id); } try { await info.processing; } catch { throwProcessingError(id); } const newMetadata = depsOptimizer.metadata; if (metadata !== newMetadata) { const currentInfo = optimizedDepInfoFromFile(newMetadata, file); if (info.browserHash !== currentInfo?.browserHash) { throwOutdatedRequest(id); } } } debug$b?.(`load ${colors$1.cyan(file)}`); try { return await fsp.readFile(file, "utf-8"); } catch { const newMetadata = depsOptimizer.metadata; if (optimizedDepInfoFromFile(newMetadata, file)) { throwOutdatedRequest(id); } throwFileNotFoundInOptimizedDep(id); } } } }; } function throwProcessingError(id) { const err = new Error( `Something unexpected happened while optimizing "${id}". The current page should have reloaded by now` ); err.code = ERR_OPTIMIZE_DEPS_PROCESSING_ERROR; throw err; } function throwOutdatedRequest(id) { const err = new Error( `There is a new version of the pre-bundle for "${id}", a page reload is going to ask for it.` ); err.code = ERR_OUTDATED_OPTIMIZED_DEP; throw err; } function throwFileNotFoundInOptimizedDep(id) { const err = new Error( `The file does not exist at "${id}" which is in the optimize deps directory. The dependency might be incompatible with the dep optimizer. Try adding it to \`optimizeDeps.exclude\`.` ); err.code = ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR; throw err; } var main$1 = {exports: {}}; var name = "dotenv"; var version$1 = "16.4.5"; var description = "Loads environment variables from .env file"; var main = "lib/main.js"; var types = "lib/main.d.ts"; var exports = { ".": { types: "./lib/main.d.ts", require: "./lib/main.js", "default": "./lib/main.js" }, "./config": "./config.js", "./config.js": "./config.js", "./lib/env-options": "./lib/env-options.js", "./lib/env-options.js": "./lib/env-options.js", "./lib/cli-options": "./lib/cli-options.js", "./lib/cli-options.js": "./lib/cli-options.js", "./package.json": "./package.json" }; var scripts = { "dts-check": "tsc --project tests/types/tsconfig.json", lint: "standard", "lint-readme": "standard-markdown", pretest: "npm run lint && npm run dts-check", test: "tap tests/*.js --100 -Rspec", "test:coverage": "tap --coverage-report=lcov", prerelease: "npm test", release: "standard-version" }; var repository = { type: "git", url: "git://github.com/motdotla/dotenv.git" }; var funding = "https://dotenvx.com"; var keywords = [ "dotenv", "env", ".env", "environment", "variables", "config", "settings" ]; var readmeFilename = "README.md"; var license = "BSD-2-Clause"; var devDependencies = { "@definitelytyped/dtslint": "^0.0.133", "@types/node": "^18.11.3", decache: "^4.6.1", sinon: "^14.0.1", standard: "^17.0.0", "standard-markdown": "^7.1.0", "standard-version": "^9.5.0", tap: "^16.3.0", tar: "^6.1.11", typescript: "^4.8.4" }; var engines = { node: ">=12" }; var browser$1 = { fs: false }; var require$$4 = { name: name, version: version$1, description: description, main: main, types: types, exports: exports, scripts: scripts, repository: repository, funding: funding, keywords: keywords, readmeFilename: readmeFilename, license: license, devDependencies: devDependencies, engines: engines, browser: browser$1 }; const fs$6 = require$$0$3; const path$a = require$$0$2; const os$1 = require$$2; const crypto$1 = require$$3; const packageJson = require$$4; const version = packageJson.version; const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; // Parse src into an Object function parse$d (src) { const obj = {}; // Convert buffer to string let lines = src.toString(); // Convert line breaks to same format lines = lines.replace(/\r\n?/mg, '\n'); let match; while ((match = LINE.exec(lines)) != null) { const key = match[1]; // Default undefined or null to empty string let value = (match[2] || ''); // Remove whitespace value = value.trim(); // Check if double quoted const maybeQuote = value[0]; // Remove surrounding quotes value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2'); // Expand newlines if double quoted if (maybeQuote === '"') { value = value.replace(/\\n/g, '\n'); value = value.replace(/\\r/g, '\r'); } // Add to object obj[key] = value; } return obj } function _parseVault (options) { const vaultPath = _vaultPath(options); // Parse .env.vault const result = DotenvModule.configDotenv({ path: vaultPath }); if (!result.parsed) { const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`); err.code = 'MISSING_DATA'; throw err } // handle scenario for comma separated keys - for use with key rotation // example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod" const keys = _dotenvKey(options).split(','); const length = keys.length; let decrypted; for (let i = 0; i < length; i++) { try { // Get full key const key = keys[i].trim(); // Get instructions for decrypt const attrs = _instructions(result, key); // Decrypt decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); break } catch (error) { // last key if (i + 1 >= length) { throw error } // try next key } } // Parse decrypted .env string return DotenvModule.parse(decrypted) } function _log (message) { console.log(`[dotenv@${version}][INFO] ${message}`); } function _warn (message) { console.log(`[dotenv@${version}][WARN] ${message}`); } function _debug (message) { console.log(`[dotenv@${version}][DEBUG] ${message}`); } function _dotenvKey (options) { // prioritize developer directly setting options.DOTENV_KEY if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { return options.DOTENV_KEY } // secondary infra already contains a DOTENV_KEY environment variable if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { return process.env.DOTENV_KEY } // fallback to empty string return '' } function _instructions (result, dotenvKey) { // Parse DOTENV_KEY. Format is a URI let uri; try { uri = new URL(dotenvKey); } catch (error) { if (error.code === 'ERR_INVALID_URL') { 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'); err.code = 'INVALID_DOTENV_KEY'; throw err } throw error } // Get decrypt key const key = uri.password; if (!key) { const err = new Error('INVALID_DOTENV_KEY: Missing key part'); err.code = 'INVALID_DOTENV_KEY'; throw err } // Get environment const environment = uri.searchParams.get('environment'); if (!environment) { const err = new Error('INVALID_DOTENV_KEY: Missing environment part'); err.code = 'INVALID_DOTENV_KEY'; throw err } // Get ciphertext payload const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; const ciphertext = result.parsed[environmentKey]; // DOTENV_VAULT_PRODUCTION if (!ciphertext) { const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`); err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'; throw err } return { ciphertext, key } } function _vaultPath (options) { let possibleVaultPath = null; if (options && options.path && options.path.length > 0) { if (Array.isArray(options.path)) { for (const filepath of options.path) { if (fs$6.existsSync(filepath)) { possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`; } } } else { possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`; } } else { possibleVaultPath = path$a.resolve(process.cwd(), '.env.vault'); } if (fs$6.existsSync(possibleVaultPath)) { return possibleVaultPath } return null } function _resolveHome (envPath) { return envPath[0] === '~' ? path$a.join(os$1.homedir(), envPath.slice(1)) : envPath } function _configVault (options) { _log('Loading env from encrypted .env.vault'); const parsed = DotenvModule._parseVault(options); let processEnv = process.env; if (options && options.processEnv != null) { processEnv = options.processEnv; } DotenvModule.populate(processEnv, parsed, options); return { parsed } } function configDotenv (options) { const dotenvPath = path$a.resolve(process.cwd(), '.env'); let encoding = 'utf8'; const debug = Boolean(options && options.debug); if (options && options.encoding) { encoding = options.encoding; } else { if (debug) { _debug('No encoding is specified. UTF-8 is used by default'); } } let optionPaths = [dotenvPath]; // default, look for .env if (options && options.path) { if (!Array.isArray(options.path)) { optionPaths = [_resolveHome(options.path)]; } else { optionPaths = []; // reset default for (const filepath of options.path) { optionPaths.push(_resolveHome(filepath)); } } } // Build the parsed data in a temporary object (because we need to return it). Once we have the final // parsed data, we will combine it with process.env (or options.processEnv if provided). let lastError; const parsedAll = {}; for (const path of optionPaths) { try { // Specifying an encoding returns a string instead of a buffer const parsed = DotenvModule.parse(fs$6.readFileSync(path, { encoding })); DotenvModule.populate(parsedAll, parsed, options); } catch (e) { if (debug) { _debug(`Failed to load ${path} ${e.message}`); } lastError = e; } } let processEnv = process.env; if (options && options.processEnv != null) { processEnv = options.processEnv; } DotenvModule.populate(processEnv, parsedAll, options); if (lastError) { return { parsed: parsedAll, error: lastError } } else { return { parsed: parsedAll } } } // Populates process.env from .env file function config (options) { // fallback to original dotenv if DOTENV_KEY is not set if (_dotenvKey(options).length === 0) { return DotenvModule.configDotenv(options) } const vaultPath = _vaultPath(options); // dotenvKey exists but .env.vault file does not exist if (!vaultPath) { _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`); return DotenvModule.configDotenv(options) } return DotenvModule._configVault(options) } function decrypt (encrypted, keyStr) { const key = Buffer.from(keyStr.slice(-64), 'hex'); let ciphertext = Buffer.from(encrypted, 'base64'); const nonce = ciphertext.subarray(0, 12); const authTag = ciphertext.subarray(-16); ciphertext = ciphertext.subarray(12, -16); try { const aesgcm = crypto$1.createDecipheriv('aes-256-gcm', key, nonce); aesgcm.setAuthTag(authTag); return `${aesgcm.update(ciphertext)}${aesgcm.final()}` } catch (error) { const isRange = error instanceof RangeError; const invalidKeyLength = error.message === 'Invalid key length'; const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'; if (isRange || invalidKeyLength) { const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)'); err.code = 'INVALID_DOTENV_KEY'; throw err } else if (decryptionFailed) { const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY'); err.code = 'DECRYPTION_FAILED'; throw err } else { throw error } } } // Populate process.env with parsed values function populate (processEnv, parsed, options = {}) { const debug = Boolean(options && options.debug); const override = Boolean(options && options.override); if (typeof parsed !== 'object') { const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate'); err.code = 'OBJECT_REQUIRED'; throw err } // Set process.env for (const key of Object.keys(parsed)) { if (Object.prototype.hasOwnProperty.call(processEnv, key)) { if (override === true) { processEnv[key] = parsed[key]; } if (debug) { if (override === true) { _debug(`"${key}" is already defined and WAS overwritten`); } else { _debug(`"${key}" is already defined and was NOT overwritten`); } } } else { processEnv[key] = parsed[key]; } } } const DotenvModule = { configDotenv, _configVault, _parseVault, config, decrypt, parse: parse$d, populate }; main$1.exports.configDotenv = DotenvModule.configDotenv; main$1.exports._configVault = DotenvModule._configVault; main$1.exports._parseVault = DotenvModule._parseVault; main$1.exports.config = DotenvModule.config; main$1.exports.decrypt = DotenvModule.decrypt; var parse_1$3 = main$1.exports.parse = DotenvModule.parse; main$1.exports.populate = DotenvModule.populate; main$1.exports = DotenvModule; function _resolveEscapeSequences (value) { return value.replace(/\\\$/g, '$') } function expandValue (value, processEnv, runningParsed) { const env = { ...runningParsed, ...processEnv }; // process.env wins const regex = /(? normalizePath$3(path$d.join(envDir, file))); } function loadEnv(mode, envDir, prefixes = "VITE_") { if (mode === "local") { throw new Error( `"local" cannot be used as a mode name because it conflicts with the .local postfix for .env files.` ); } prefixes = arraify(prefixes); const env = {}; const envFiles = getEnvFilesForMode(mode, envDir); const parsed = Object.fromEntries( envFiles.flatMap((filePath) => { if (!tryStatSync(filePath)?.isFile()) return []; return Object.entries(parse_1$3(fs__default.readFileSync(filePath))); }) ); if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === void 0) { process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV; } if (parsed.BROWSER && process.env.BROWSER === void 0) { process.env.BROWSER = parsed.BROWSER; } if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === void 0) { process.env.BROWSER_ARGS = parsed.BROWSER_ARGS; } const processEnv = { ...process.env }; expand_1$1({ parsed, processEnv }); for (const [key, value] of Object.entries(parsed)) { if (prefixes.some((prefix) => key.startsWith(prefix))) { env[key] = value; } } for (const key in process.env) { if (prefixes.some((prefix) => key.startsWith(prefix))) { env[key] = process.env[key]; } } return env; } function resolveEnvPrefix({ envPrefix = "VITE_" }) { envPrefix = arraify(envPrefix); if (envPrefix.includes("")) { throw new Error( `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.` ); } return envPrefix; } const docsURL = "https://main.vite.dev"; const deprecationCode = { removePluginHookSsrArgument: "changes/this-environment-in-hooks", removePluginHookHandleHotUpdate: "changes/hotupdate-hook", removeServerModuleGraph: "changes/per-environment-apis", removeServerHot: "changes/per-environment-apis", removeServerTransformRequest: "changes/per-environment-apis", removeSsrLoadModule: "changes/ssr-using-modulerunner" }; const deprecationMessages = { removePluginHookSsrArgument: "Plugin hook `options.ssr` is replaced with `this.environment.config.consumer === 'server'`.", removePluginHookHandleHotUpdate: "Plugin hook `handleHotUpdate()` is replaced with `hotUpdate()`.", removeServerModuleGraph: "The `server.moduleGraph` is replaced with `this.environment.moduleGraph`.", removeServerHot: "The `server.hot` is replaced with `this.environment.hot`.", removeServerTransformRequest: "The `server.transformRequest` is replaced with `this.environment.transformRequest`.", removeSsrLoadModule: "The `server.ssrLoadModule` is replaced with Environment Runner." }; let _ignoreDeprecationWarnings = false; function warnFutureDeprecation(config, type, extraMessage, stacktrace = true) { if (_ignoreDeprecationWarnings || !config.future || config.future[type] !== "warn") return; let msg = `[vite future] ${deprecationMessages[type]}`; if (extraMessage) { msg += ` ${extraMessage}`; } msg = colors$1.yellow(msg); const docs = `${docsURL}/changes/${deprecationCode[type].toLowerCase()}`; msg += colors$1.gray(` ${stacktrace ? "\u251C" : "\u2514"}\u2500\u2500\u2500 `) + colors$1.underline(docs) + "\n"; if (stacktrace) { const stack = new Error().stack; if (stack) { let stacks = stack.split("\n").slice(3).filter((i) => !i.includes("/node_modules/vite/dist/")); if (stacks.length === 0) { stacks.push("No stack trace found."); } stacks = stacks.map( (i, idx) => ` ${idx === stacks.length - 1 ? "\u2514" : "\u2502"} ${i.trim()}` ); msg += colors$1.dim(stacks.join("\n")) + "\n"; } } config.logger.warnOnce(msg); } function ignoreDeprecationWarnings(fn) { const before = _ignoreDeprecationWarnings; _ignoreDeprecationWarnings = true; const ret = fn(); _ignoreDeprecationWarnings = before; return ret; } function prepareError(err) { return { message: stripVTControlCharacters(err.message), stack: stripVTControlCharacters(cleanStack(err.stack || "")), id: err.id, frame: stripVTControlCharacters(err.frame || ""), plugin: err.plugin, pluginCode: err.pluginCode?.toString(), loc: err.loc }; } function buildErrorMessage(err, args = [], includeStack = true) { if (err.plugin) args.push(` Plugin: ${colors$1.magenta(err.plugin)}`); const loc = err.loc ? `:${err.loc.line}:${err.loc.column}` : ""; if (err.id) args.push(` File: ${colors$1.cyan(err.id)}${loc}`); if (err.frame) args.push(colors$1.yellow(pad$1(err.frame))); if (includeStack && err.stack) args.push(pad$1(cleanStack(err.stack))); return args.join("\n"); } function cleanStack(stack) { return stack.split(/\n/).filter((l) => /^\s*at/.test(l)).join("\n"); } function logError(server, err) { const msg = buildErrorMessage(err, [ colors$1.red(`Internal server error: ${err.message}`) ]); server.config.logger.error(msg, { clear: true, timestamp: true, error: err }); server.environments.client.hot.send({ type: "error", err: prepareError(err) }); } function errorMiddleware(server, allowNext = false) { return function viteErrorMiddleware(err, _req, res, next) { logError(server, err); if (allowNext) { next(); } else { res.statusCode = 500; res.end(` Error