import fs$l, { promises as promises$2 } from 'node:fs'; import path$o, { posix as posix$1, isAbsolute as isAbsolute$2, join as join$2, relative as relative$2, dirname as dirname$2, basename as basename$2, extname as extname$1 } from 'node:path'; import { URL as URL$3, URLSearchParams, parse as parse$i, pathToFileURL } from 'node:url'; import { performance } from 'node:perf_hooks'; import { createRequire as createRequire$1, builtinModules } from 'node:module'; import require$$0$3 from 'tty'; import esbuild, { transform as transform$2, formatMessages, build as build$3 } from 'esbuild'; import require$$0$4, { win32, posix, isAbsolute as isAbsolute$1, resolve as resolve$3, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join as join$1, sep, normalize } from 'path'; import * as require$$0$2 from 'fs'; import require$$0__default, { existsSync, readFileSync, statSync as statSync$1, promises as promises$1, readdirSync } from 'fs'; import require$$0$5 from 'events'; import require$$5 from 'assert'; import require$$0$6 from 'util'; import require$$3$2 from 'net'; import require$$0$9 from 'url'; import require$$1$1 from 'http'; import require$$0$7 from 'stream'; import require$$2 from 'os'; import require$$2$1 from 'child_process'; import os$3 from 'node:os'; import { createHash as createHash$2 } from 'node:crypto'; import { promisify as promisify$4, format as format$2, inspect } from 'node:util'; import { promises } from 'node:dns'; import resolve$4 from 'resolve'; import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, wildcardHosts, loopbackHosts, VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, ENV_ENTRY, DEFAULT_MAIN_FIELDS, SPECIAL_QUERY_RE, DEP_VERSION_RE, CSS_LANGS_RE, KNOWN_ASSET_TYPES, CLIENT_DIR, JS_TYPES_RE, ESBUILD_MODULES_TARGET, VERSION as VERSION$1, VITE_PACKAGE_DIR, DEFAULT_DEV_PORT, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js'; import require$$5$1 from 'crypto'; import { Buffer as Buffer$1 } from 'node:buffer'; import fsp from 'node:fs/promises'; import require$$0$8, { createRequire as createRequire$2 } from 'module'; import assert$1 from 'node:assert'; import process$1 from 'node:process'; import v8 from 'node:v8'; import require$$1 from 'worker_threads'; import require$$0$a from 'zlib'; import require$$0$b from 'buffer'; import require$$1$2 from 'https'; import require$$4 from 'tls'; import { STATUS_CODES } from 'node:http'; import { createServer as createServer$2 } from 'node:https'; import { VERSION } from 'rollup'; import * as qs from 'querystring'; import readline from 'node:readline'; import { execSync } from 'node:child_process'; import zlib$1, { gzip } from 'node:zlib'; import { fileURLToPath as __cjs_fileURLToPath } from 'node:url'; import { dirname as __cjs_dirname } from 'node:path'; import { createRequire as __cjs_createRequire } from 'node:module'; const __filename = __cjs_fileURLToPath(import.meta.url); const __dirname = __cjs_dirname(__filename); const require = __cjs_createRequire(import.meta.url); const __require = require; 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; } function getAugmentedNamespace(n) { if (n.__esModule) return n; var f = n.default; if (typeof f == "function") { var a = function a () { if (this instanceof a) { var args = [null]; args.push.apply(args, arguments); var Ctor = Function.bind.apply(f, args); return new Ctor(); } 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; } var picocolorsExports = {}; var picocolors = { get exports(){ return picocolorsExports; }, set exports(v){ picocolorsExports = v; }, }; let tty = require$$0$3; let isColorSupported = !("NO_COLOR" in process.env || process.argv.includes("--no-color")) && ("FORCE_COLOR" in process.env || process.argv.includes("--color") || process.platform === "win32" || (tty.isatty(1) && process.env.TERM !== "dumb") || "CI" in process.env); let formatter = (open, close, replace = open) => input => { let string = "" + input; let 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 start = string.substring(0, index) + replace; let end = string.substring(index + close.length); let nextIndex = end.indexOf(close); return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end }; let createColors = (enabled = isColorSupported) => ({ isColorSupported: enabled, reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String, bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String, dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String, italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String, underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String, inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String, hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String, strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String, black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String, red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String, green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String, yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String, blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String, magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String, cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String, white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String, gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String, bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String, bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String, bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String, bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String, bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String, bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String, bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String, bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String, }); picocolors.exports = createColors(); picocolorsExports.createColors = createColors; 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) { if (!importer) { return null; } // 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) => resolved || { id: updatedId }); } }; } // @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$3(ast, { enter, leave }) { const instance = new SyncWalker$1(enter, leave); return instance.visit(ast, null); } var picomatchExports = {}; var picomatch$5 = { get exports(){ return picomatchExports; }, set exports(v){ picomatchExports = v; }, }; var utils$k = {}; const path$n = require$$0$4; const WIN_SLASH = '\\\\/'; const WIN_NO_SLASH = `[^${WIN_SLASH}]`; /** * Posix glob regex */ const DOT_LITERAL = '\\.'; const PLUS_LITERAL = '\\+'; const QMARK_LITERAL = '\\?'; const SLASH_LITERAL = '\\/'; const ONE_CHAR = '(?=.)'; const QMARK = '[^/]'; const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; const NO_DOT = `(?!${DOT_LITERAL})`; const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; const STAR$1 = `${QMARK}*?`; const POSIX_CHARS = { DOT_LITERAL, PLUS_LITERAL, QMARK_LITERAL, SLASH_LITERAL, ONE_CHAR, QMARK, END_ANCHOR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK_NO_DOT, STAR: STAR$1, START_ANCHOR }; /** * Windows glob regex */ const WINDOWS_CHARS = { ...POSIX_CHARS, SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` }; /** * POSIX Bracket Regex */ const POSIX_REGEX_SOURCE$1 = { 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$6 = { MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, // 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 */ SEP: path$n.sep, /** * 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 : POSIX_CHARS; } }; (function (exports) { const path = require$$0$4; const win32 = process.platform === 'win32'; const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = constants$6; 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.removeBackslashes = str => { return str.replace(REGEX_REMOVE_BACKSLASH, match => { return match === '\\' ? '' : match; }); }; exports.supportsLookbehinds = () => { const segs = process.version.slice(1).split('.').map(Number); if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { return true; } return false; }; exports.isWindows = options => { if (options && typeof options.windows === 'boolean') { return options.windows; } return win32 === true || path.sep === '\\'; }; 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; }; } (utils$k)); const utils$j = utils$k; const { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA: CHAR_COMMA$1, /* , */ CHAR_DOT: CHAR_DOT$1, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */ } = constants$6; const isPathSeparator = code => { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; }; const depth = 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$2 = (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) { backslashes = token.backslashes = true; code = advance(); if (code === CHAR_LEFT_CURLY_BRACE$1) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) { braces++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE$1) { braces++; continue; } if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA$1) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE$1) { braces--; if (braces === 0) { braceEscaped = false; isBrace = token.isBrace = true; finished = true; break; } } } if (scanToEnd === true) { continue; } break; } if (code === CHAR_FORWARD_SLASH) { slashes.push(index); tokens.push(token); token = { value: '', depth: 0, isGlob: false }; if (finished === true) continue; if (prev === CHAR_DOT$1 && index === (start + 1)) { start += 2; continue; } lastIndex = index + 1; continue; } if (opts.noext !== true) { const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) { isGlob = token.isGlob = true; isExtglob = token.isExtglob = true; finished = true; if (code === CHAR_EXCLAMATION_MARK && index === start) { negatedExtglob = true; } if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES$1) { isGlob = token.isGlob = true; finished = true; break; } } continue; } break; } } if (code === CHAR_ASTERISK) { if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_QUESTION_MARK) { isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_LEFT_SQUARE_BRACKET$1) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { isBracket = token.isBracket = true; isGlob = token.isGlob = true; finished = true; break; } } if (scanToEnd === true) { continue; } break; } if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { negated = token.negated = true; start++; continue; } if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) { isGlob = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES$1) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES$1) { 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(base.charCodeAt(base.length - 1))) { base = base.slice(0, -1); } } if (opts.unescape === true) { if (glob) glob = utils$j.removeBackslashes(glob); if (base && backslashes === true) { base = utils$j.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(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(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(tokens[tokens.length - 1]); state.maxDepth += tokens[tokens.length - 1].depth; } } state.slashes = slashes; state.parts = parts; } return state; }; var scan_1 = scan$2; const constants$5 = constants$6; const utils$i = utils$k; /** * Constants */ const { MAX_LENGTH: MAX_LENGTH$1, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$5; /** * Helpers */ const expandRange = (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 = (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[input] || input; const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; 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 ? '' : '?:'; const win32 = utils$i.isWindows(options); // create constants based on platform, for windows or posix const PLATFORM_CHARS = constants$5.globChars(win32); const EXTGLOB_CHARS = constants$5.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$i.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.value += tok.value; prev.output = (prev.output || '') + 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, (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$i.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[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$i.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('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('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('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$i.hasRegexChars(prevValue)) { continue; } const escaped = utils$i.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(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 (next === '<' && !utils$i.supportsLookbehinds()) { throw new Error('Node.js v10 or higher is required for regex lookbehinds'); } 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.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('closing', ']')); state.output = utils$i.escapeLast(state.output, '['); decrement('brackets'); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); state.output = utils$i.escapeLast(state.output, '('); decrement('parens'); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); state.output = utils$i.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$1, opts.maxLength) : MAX_LENGTH$1; const len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } input = REPLACEMENTS[input] || input; const win32 = utils$i.isWindows(options); // 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$5.globChars(win32); 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$i.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL}?`; } return source; }; var parse_1$3 = parse$h; const path$m = require$$0$4; const scan$1 = scan_1; const parse$g = parse_1$3; const utils$h = utils$k; const constants$4 = constants$6; 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$4 = (glob, options, returnState = false) => { if (Array.isArray(glob)) { const fns = glob.map(input => picomatch$4(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 = utils$h.isWindows(options); const regex = isState ? picomatch$4.compileRe(glob, options) : picomatch$4.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$4(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { const { isMatch, match, output } = picomatch$4.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$4.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$h.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$4.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$4.matchBase = (input, glob, options, posix = utils$h.isWindows(options)) => { const regex = glob instanceof RegExp ? glob : picomatch$4.makeRe(glob, options); return regex.test(path$m.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$4.isMatch = (str, patterns, options) => picomatch$4(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$4.parse = (pattern, options) => { if (Array.isArray(pattern)) return pattern.map(p => picomatch$4.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$4.scan = (input, options) => scan$1(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$4.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$4.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$4.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$4.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$4.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$4.constants = constants$4; /** * Expose "picomatch" */ var picomatch_1 = picomatch$4; (function (module) { module.exports = picomatch_1; } (picomatch$5)); var picomatch$3 = /*@__PURE__*/getDefaultExportFromCjs(picomatchExports); 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 }; let Scope$1 = 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$1(); walk$3(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$1({ 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$1({ parent: scope, block: true }); } // create new block scope if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) { newScope = new Scope$1({ parent: scope, block: true }); } // catch clause has its own block scope if (node.type === 'CatchClause') { newScope = new Scope$1({ 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$2(arg) { return Array.isArray(arg); } function ensureArray(thing) { if (isArray$2(thing)) return thing; if (thing == null) return []; return [thing]; } const normalizePath$5 = function normalizePath(filename) { return filename.split(win32.sep).join(posix.sep); }; function getMatcherString(id, resolutionBase) { if (resolutionBase === false || isAbsolute$1(id) || id.startsWith('*')) { return normalizePath$5(id); } // resolve('') is valid and will default to process.cwd() const basePath = normalizePath$5(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$5(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$3(pattern, { dot: true }); const result = fn(what); return result; } }; const includeMatchers = ensureArray(include).map(getMatcher); const excludeMatchers = ensureArray(exclude).map(getMatcher); return function result(id) { if (typeof id !== 'string') return false; if (/\0/.test(id)) return false; const pathId = normalizePath$5(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$1 = '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$1 = '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$1} ${builtins$1}`.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$8(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$8(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$8(key)})`; } if (typeof obj === 'bigint') return `${obj}n`; return stringify$8(obj); } const dataToEsm = function dataToEsm(data, options = {}) { 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 namedExportCode = ''; const defaultExportRows = []; 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$8(key)}:${_}${serialize(value, options.compact ? null : t, '')}`); } } return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`; }; var path$l = require$$0$4; var commondir = function (basedir, relfiles) { if (relfiles) { var files = relfiles.map(function (r) { return path$l.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 old$1 = {}; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var pathModule = require$$0$4; var isWindows$6 = process.platform === 'win32'; var fs$k = require$$0__default; // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG$1 = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG$1) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows$6) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows$6) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } old$1.realpathSync = function realpathSync(p, cache) { // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows$6 && !knownHard[base]) { fs$k.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs$k.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows$6) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs$k.statSync(base); linkTarget = fs$k.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows$6) seenLinks[id] = linkTarget; } // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; old$1.realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows$6 && !knownHard[base]) { fs$k.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs$k.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows$6) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs$k.stat(base, function(err) { if (err) return cb(err); fs$k.readlink(base, function(err, target) { if (!isWindows$6) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = pathModule.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } }; var fs_realpath = realpath$2; realpath$2.realpath = realpath$2; realpath$2.sync = realpathSync; realpath$2.realpathSync = realpathSync; realpath$2.monkeypatch = monkeypatch; realpath$2.unmonkeypatch = unmonkeypatch; var fs$j = require$$0__default; var origRealpath = fs$j.realpath; var origRealpathSync = fs$j.realpathSync; var version$4 = process.version; var ok = /^v[0-5]\./.test(version$4); var old = old$1; function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath$2 (p, cache, cb) { if (ok) { return origRealpath(p, cache, cb) } if (typeof cache === 'function') { cb = cache; cache = null; } origRealpath(p, cache, function (er, result) { if (newError(er)) { old.realpath(p, cache, cb); } else { cb(er, result); } }); } function realpathSync (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs$j.realpath = realpath$2; fs$j.realpathSync = realpathSync; } function unmonkeypatch () { fs$j.realpath = origRealpath; fs$j.realpathSync = origRealpathSync; } const isWindows$5 = typeof process === 'object' && process && process.platform === 'win32'; var path$k = isWindows$5 ? { sep: '\\' } : { sep: '/' }; var balancedMatch = balanced$1; function balanced$1(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range$1(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced$1.range = range$1; function range$1(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { if(a===b) { return [ai, bi]; } begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } var balanced = balancedMatch; var braceExpansion = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand$4(escapeBraces(str), true).map(unescapeBraces); } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand$4(str, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m) return [str]; // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand$4(m.post, false) : ['']; if (/\$$/.test(m.pre)) { for (var k = 0; k < post.length; k++) { var expansion = pre+ '{' + m.body + '}' + post[k]; expansions.push(expansion); } } else { var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand$4(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand$4(n[0], false).map(embrace); if (n.length === 1) { return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length); var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = []; for (var j = 0; j < n.length; j++) { N.push.apply(N, expand$4(n[j], false)); } } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } } return expansions; } const minimatch$1 = minimatch_1 = (p, pattern, options = {}) => { assertValidPattern(pattern); // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false } return new Minimatch$1(pattern, options).match(p) }; var minimatch_1 = minimatch$1; const path$j = path$k; minimatch$1.sep = path$j.sep; const GLOBSTAR$2 = Symbol('globstar **'); minimatch$1.GLOBSTAR = GLOBSTAR$2; const expand$3 = braceExpansion; const plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, '?': { open: '(?:', close: ')?' }, '+': { open: '(?:', close: ')+' }, '*': { open: '(?:', close: ')*' }, '@': { open: '(?:', close: ')' } }; // any single thing other than / // don't need to escape / when using new RegExp() const qmark = '[^/]'; // * => any number of characters const star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot, // followed by anything, any number of times. const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // "abc" -> { a:true, b:true, c:true } const charSet = s => s.split('').reduce((set, c) => { set[c] = true; return set }, {}); // characters that need to be escaped in RegExp. const reSpecials = charSet('().*{}+?[]^$\\!'); // characters that indicate we have to add the pattern start const addPatternStartSet = charSet('[.('); // normalizes slashes. const slashSplit = /\/+/; minimatch$1.filter = (pattern, options = {}) => (p, i, list) => minimatch$1(p, pattern, options); const ext = (a, b = {}) => { const t = {}; Object.keys(a).forEach(k => t[k] = a[k]); Object.keys(b).forEach(k => t[k] = b[k]); return t }; minimatch$1.defaults = def => { if (!def || typeof def !== 'object' || !Object.keys(def).length) { return minimatch$1 } const orig = minimatch$1; const m = (p, pattern, options) => orig(p, pattern, ext(def, options)); m.Minimatch = class Minimatch extends orig.Minimatch { constructor (pattern, options) { super(pattern, ext(def, options)); } }; m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch; m.filter = (pattern, options) => orig.filter(pattern, ext(def, options)); m.defaults = options => orig.defaults(ext(def, options)); m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options)); m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options)); m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options)); return m }; // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch$1.braceExpand = (pattern, options) => braceExpand(pattern, options); const braceExpand = (pattern, options = {}) => { assertValidPattern(pattern); // Thanks to Yeting Li for // improving this regexp to avoid a ReDOS vulnerability. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { // shortcut. no need to expand. return [pattern] } return expand$3(pattern) }; const MAX_PATTERN_LENGTH = 1024 * 64; const assertValidPattern = pattern => { if (typeof pattern !== 'string') { throw new TypeError('invalid pattern') } if (pattern.length > MAX_PATTERN_LENGTH) { throw new TypeError('pattern is too long') } }; // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. const SUBPARSE = Symbol('subparse'); minimatch$1.makeRe = (pattern, options) => new Minimatch$1(pattern, options || {}).makeRe(); minimatch$1.match = (list, pattern, options = {}) => { const mm = new Minimatch$1(pattern, options); list = list.filter(f => mm.match(f)); if (mm.options.nonull && !list.length) { list.push(pattern); } return list }; // replace stuff like \* with * const globUnescape = s => s.replace(/\\(.)/g, '$1'); const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); let Minimatch$1 = class Minimatch { constructor (pattern, options) { assertValidPattern(pattern); if (!options) options = {}; this.options = options; this.set = []; this.pattern = pattern; this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; if (this.windowsPathsNoEscape) { this.pattern = this.pattern.replace(/\\/g, '/'); } this.regexp = null; this.negate = false; this.comment = false; this.empty = false; this.partial = !!options.partial; // make the set of regexps etc. this.make(); } debug () {} make () { const pattern = this.pattern; const options = this.options; // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true; return } if (!pattern) { this.empty = true; return } // step 1: figure out negation, etc. this.parseNegate(); // step 2: expand braces let set = this.globSet = this.braceExpand(); if (options.debug) this.debug = (...args) => console.error(...args); this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion // matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters set = this.globParts = set.map(s => s.split(slashSplit)); this.debug(this.pattern, set); // glob --> regexps set = set.map((s, si, set) => s.map(this.parse, this)); this.debug(this.pattern, set); // filter out everything that didn't compile properly. set = set.filter(s => s.indexOf(false) === -1); this.debug(this.pattern, set); this.set = set; } parseNegate () { if (this.options.nonegate) return const pattern = this.pattern; let negate = false; let negateOffset = 0; for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { negate = !negate; negateOffset++; } if (negateOffset) this.pattern = pattern.substr(negateOffset); this.negate = negate; } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. matchOne (file, pattern, partial) { var options = this.options; this.debug('matchOne', { 'this': this, file: file, pattern: pattern }); this.debug('matchOne', file.length, pattern.length); for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length ; (fi < fl) && (pi < pl) ; fi++, pi++) { this.debug('matchOne loop'); var p = pattern[pi]; var f = file[fi]; this.debug(pattern, p, f); // should be impossible. // some invalid regexp stuff in the set. /* istanbul ignore if */ if (p === false) return false if (p === GLOBSTAR$2) { this.debug('GLOBSTAR', [pattern, p, f]); // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi; var pr = pi + 1; if (pr === pl) { this.debug('** at the end'); // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for (; fi < fl; fi++) { if (file[fi] === '.' || file[fi] === '..' || (!options.dot && file[fi].charAt(0) === '.')) return false } return true } // ok, let's see if we can swallow whatever we can. while (fr < fl) { var swallowee = file[fr]; this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { this.debug('globstar found match!', fr, fl, swallowee); // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === '.' || swallowee === '..' || (!options.dot && swallowee.charAt(0) === '.')) { this.debug('dot detected!', file, fr, pattern, pr); break } // ** swallows a segment, and continue. this.debug('globstar swallow a segment, and continue'); fr++; } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then /* istanbul ignore if */ if (partial) { // ran out of file this.debug('\n>>> no match, partial?', file, fr, pattern, pr); if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit; if (typeof p === 'string') { hit = f === p; this.debug('string match', p, f, hit); } else { hit = f.match(p); this.debug('pattern match', p, f, hit); } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else /* istanbul ignore else */ if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ return (fi === fl - 1) && (file[fi] === '') } // should be unreachable. /* istanbul ignore next */ throw new Error('wtf?') } braceExpand () { return braceExpand(this.pattern, this.options) } parse (pattern, isSub) { assertValidPattern(pattern); const options = this.options; // shortcuts if (pattern === '**') { if (!options.noglobstar) return GLOBSTAR$2 else pattern = '*'; } if (pattern === '') return '' let re = ''; let hasMagic = !!options.nocase; let escaping = false; // ? => one single character const patternListStack = []; const negativeLists = []; let stateChar; let inClass = false; let reClassStart = -1; let classStart = -1; let cs; let pl; let sp; // . and .. never match anything that doesn't start with ., // even when options.dot is set. const patternStart = pattern.charAt(0) === '.' ? '' // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)'; const clearStateChar = () => { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case '*': re += star; hasMagic = true; break case '?': re += qmark; hasMagic = true; break default: re += '\\' + stateChar; break } this.debug('clearStateChar %j %j', stateChar, re); stateChar = false; } }; for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) { this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped. if (escaping) { /* istanbul ignore next - completely not allowed, even escaped. */ if (c === '/') { return false } if (reSpecials[c]) { re += '\\'; } re += c; escaping = false; continue } switch (c) { /* istanbul ignore next */ case '/': { // Should already be path-split by now. return false } case '\\': clearStateChar(); escaping = true; continue // the various stateChar values // for the "extglob" stuff. case '?': case '*': case '+': case '@': case '!': this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { this.debug(' in class'); if (c === '!' && i === classStart + 1) c = '^'; re += c; continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. this.debug('call clearStateChar %j', stateChar); clearStateChar(); stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar(); continue case '(': if (inClass) { re += '('; continue } if (!stateChar) { re += '\\('; continue } patternListStack.push({ type: stateChar, start: i - 1, reStart: re.length, open: plTypes[stateChar].open, close: plTypes[stateChar].close }); // negation is (?:(?!js)[^/]*) re += stateChar === '!' ? '(?:(?!(?:' : '(?:'; this.debug('plType %j %j', stateChar, re); stateChar = false; continue case ')': if (inClass || !patternListStack.length) { re += '\\)'; continue } clearStateChar(); hasMagic = true; pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*) // The others are (?:) re += pl.close; if (pl.type === '!') { negativeLists.push(pl); } pl.reEnd = re.length; continue case '|': if (inClass || !patternListStack.length) { re += '\\|'; continue } clearStateChar(); re += '|'; continue // these are mostly the same in regexp and glob case '[': // swallow any state-tracking char before the [ clearStateChar(); if (inClass) { re += '\\' + c; continue } inClass = true; classStart = i; reClassStart = re.length; re += c; continue case ']': // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += '\\' + c; continue } // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that // were passed through as-is // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. cs = pattern.substring(classStart + 1, i); // finish up the class. hasMagic = true; inClass = false; re += c; continue default: // swallow any state char that wasn't consumed clearStateChar(); if (reSpecials[c] && !(c === '^' && inClass)) { re += '\\'; } re += c; break } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is cs = pattern.substr(classStart + 1); sp = this.parse(cs, SUBPARSE); re = re.substr(0, reClassStart) + '\\[' + sp[0]; hasMagic = hasMagic || sp[1]; } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { let tail; tail = re.slice(pl.reStart + pl.open.length); this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { /* istanbul ignore else - should already be done */ if (!$2) { // the | isn't already escaped, so escape it. $2 = '\\'; } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + '|' }); this.debug('tail=%j\n %s', tail, tail, pl, re); const t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type; hasMagic = true; re = re.slice(0, pl.reStart) + t + '\\(' + tail; } // handle trailing things that only matter at the very end. clearStateChar(); if (escaping) { // trailing \\ re += '\\\\'; } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot const addPatternStart = addPatternStartSet[re.charAt(0)]; // Hack to work around lack of negative lookbehind in JS // A pattern like: *.!(x).!(y|z) needs to ensure that a name // like 'a.xyz.yz' doesn't match. So, the first negative // lookahead, has to look ALL the way ahead, to the end of // the pattern. for (let n = negativeLists.length - 1; n > -1; n--) { const nl = negativeLists[n]; const nlBefore = re.slice(0, nl.reStart); const nlFirst = re.slice(nl.reStart, nl.reEnd - 8); let nlAfter = re.slice(nl.reEnd); const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens // mean that we should *not* include the ) in the bit that is considered // "after" the negated section. const openParensBefore = nlBefore.split('(').length - 1; let cleanAfter = nlAfter; for (let i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); } nlAfter = cleanAfter; const dollar = nlAfter === '' && isSub !== SUBPARSE ? '$' : ''; re = nlBefore + nlFirst + nlAfter + dollar + nlLast; } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== '' && hasMagic) { re = '(?=.)' + re; } if (addPatternStart) { re = patternStart + re; } // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [re, hasMagic] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } const flags = options.nocase ? 'i' : ''; try { return Object.assign(new RegExp('^' + re + '$', flags), { _glob: pattern, _src: re, }) } catch (er) /* istanbul ignore next - should be impossible */ { // If it was an invalid regular expression, then it can't match // anything. This trick looks for a character after the end of // the string, which is of course impossible, except in multi-line // mode, but it's not a /m regex. return new RegExp('$.') } } makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. const set = this.set; if (!set.length) { this.regexp = false; return this.regexp } const options = this.options; const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot; const flags = options.nocase ? 'i' : ''; // coalesce globstars and regexpify non-globstar patterns // if it's the only item, then we just do one twoStar // if it's the first, and there are more, prepend (\/|twoStar\/)? to next // if it's the last, append (\/twoStar|) to previous // if it's in the middle, append (\/|\/twoStar\/) to previous // then filter out GLOBSTAR symbols let re = set.map(pattern => { pattern = pattern.map(p => typeof p === 'string' ? regExpEscape(p) : p === GLOBSTAR$2 ? GLOBSTAR$2 : p._src ).reduce((set, p) => { if (!(set[set.length - 1] === GLOBSTAR$2 && p === GLOBSTAR$2)) { set.push(p); } return set }, []); pattern.forEach((p, i) => { if (p !== GLOBSTAR$2 || pattern[i-1] === GLOBSTAR$2) { return } if (i === 0) { if (pattern.length > 1) { pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1]; } else { pattern[i] = twoStar; } } else if (i === pattern.length - 1) { pattern[i-1] += '(?:\\\/|' + twoStar + ')?'; } else { pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1]; pattern[i+1] = GLOBSTAR$2; } }); return pattern.filter(p => p !== GLOBSTAR$2).join('/') }).join('|'); // must match entire pattern // ending in a * or ** will make it less strict. re = '^(?:' + re + ')$'; // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$'; try { this.regexp = new RegExp(re, flags); } catch (ex) /* istanbul ignore next - should be impossible */ { this.regexp = false; } return this.regexp } match (f, partial = this.partial) { this.debug('match', f, this.pattern); // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === '' if (f === '/' && partial) return true const options = this.options; // windows: need to use /, not \ if (path$j.sep !== '/') { f = f.split(path$j.sep).join('/'); } // treat the test path as a set of pathparts. f = f.split(slashSplit); this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. const set = this.set; this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment let filename; for (let i = f.length - 1; i >= 0; i--) { filename = f[i]; if (filename) break } for (let i = 0; i < set.length; i++) { const pattern = set[i]; let file = f; if (options.matchBase && pattern.length === 1) { file = [filename]; } const hit = this.matchOne(file, pattern, partial); if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } static defaults (def) { return minimatch$1.defaults(def).Minimatch } }; minimatch$1.Minimatch = Minimatch$1; var inheritsExports = {}; var inherits = { get exports(){ return inheritsExports; }, set exports(v){ inheritsExports = v; }, }; var inherits_browserExports = {}; var inherits_browser = { get exports(){ return inherits_browserExports; }, set exports(v){ inherits_browserExports = v; }, }; var hasRequiredInherits_browser; function requireInherits_browser () { if (hasRequiredInherits_browser) return inherits_browserExports; hasRequiredInherits_browser = 1; if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module inherits_browser.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } }; } else { // old school shim for old browsers inherits_browser.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } }; } return inherits_browserExports; } (function (module) { try { var util = require('util'); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ module.exports = requireInherits_browser(); } } (inherits)); var common$c = {}; common$c.setopts = setopts; common$c.ownProp = ownProp; common$c.makeAbs = makeAbs; common$c.finish = finish; common$c.mark = mark; common$c.isIgnored = isIgnored; common$c.childrenIgnored = childrenIgnored; function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var fs$i = require$$0__default; var path$i = require$$0$4; var minimatch = minimatch_1; var isAbsolute = require$$0$4.isAbsolute; var Minimatch = minimatch.Minimatch; function alphasort (a, b) { return a.localeCompare(b, 'en') } function setupIgnores (self, options) { self.ignore = options.ignore || []; if (!Array.isArray(self.ignore)) self.ignore = [self.ignore]; if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap); } } // ignore patterns are always in dot:true mode. function ignoreMap (pattern) { var gmatcher = null; if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, ''); gmatcher = new Minimatch(gpattern, { dot: true }); } return { matcher: new Minimatch(pattern, { dot: true }), gmatcher: gmatcher } } function setopts (self, pattern, options) { if (!options) options = {}; // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern; } self.silent = !!options.silent; self.pattern = pattern; self.strict = options.strict !== false; self.realpath = !!options.realpath; self.realpathCache = options.realpathCache || Object.create(null); self.follow = !!options.follow; self.dot = !!options.dot; self.mark = !!options.mark; self.nodir = !!options.nodir; if (self.nodir) self.mark = true; self.sync = !!options.sync; self.nounique = !!options.nounique; self.nonull = !!options.nonull; self.nosort = !!options.nosort; self.nocase = !!options.nocase; self.stat = !!options.stat; self.noprocess = !!options.noprocess; self.absolute = !!options.absolute; self.fs = options.fs || fs$i; self.maxLength = options.maxLength || Infinity; self.cache = options.cache || Object.create(null); self.statCache = options.statCache || Object.create(null); self.symlinks = options.symlinks || Object.create(null); setupIgnores(self, options); self.changedCwd = false; var cwd = process.cwd(); if (!ownProp(options, "cwd")) self.cwd = path$i.resolve(cwd); else { self.cwd = path$i.resolve(options.cwd); self.changedCwd = self.cwd !== cwd; } self.root = options.root || path$i.resolve(self.cwd, "/"); self.root = path$i.resolve(self.root); // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd); self.nomount = !!options.nomount; if (process.platform === "win32") { self.root = self.root.replace(/\\/g, "/"); self.cwd = self.cwd.replace(/\\/g, "/"); self.cwdAbs = self.cwdAbs.replace(/\\/g, "/"); } // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true; options.nocomment = true; // always treat \ in patterns as escapes, not path separators options.allowWindowsEscape = true; self.minimatch = new Minimatch(pattern, options); self.options = self.minimatch.options; } function finish (self) { var nou = self.nounique; var all = nou ? [] : Object.create(null); for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i]; if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i]; if (nou) all.push(literal); else all[literal] = true; } } else { // had matches var m = Object.keys(matches); if (nou) all.push.apply(all, m); else m.forEach(function (m) { all[m] = true; }); } } if (!nou) all = Object.keys(all); if (!self.nosort) all = all.sort(alphasort); // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]); } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)); var c = self.cache[e] || self.cache[makeAbs(self, e)]; if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c); return notDir }); } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored(self, m) }); self.found = all; } function mark (self, p) { var abs = makeAbs(self, p); var c = self.cache[abs]; var m = p; if (c) { var isDir = c === 'DIR' || Array.isArray(c); var slash = p.slice(-1) === '/'; if (isDir && !slash) m += '/'; else if (!isDir && slash) m = m.slice(0, -1); if (m !== p) { var mabs = makeAbs(self, m); self.statCache[mabs] = self.statCache[abs]; self.cache[mabs] = self.cache[abs]; } } return m } // lotta situps... function makeAbs (self, f) { var abs = f; if (f.charAt(0) === '/') { abs = path$i.join(self.root, f); } else if (isAbsolute(f) || f === '') { abs = f; } else if (self.changedCwd) { abs = path$i.resolve(self.cwd, f); } else { abs = path$i.resolve(f); } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/'); return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) }) } function childrenIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path)) }) } var sync$9; var hasRequiredSync; function requireSync () { if (hasRequiredSync) return sync$9; hasRequiredSync = 1; sync$9 = globSync; globSync.GlobSync = GlobSync; var rp = fs_realpath; var minimatch = minimatch_1; requireGlob().Glob; var path = require$$0$4; var assert = require$$5; var isAbsolute = require$$0$4.isAbsolute; var common = common$c; var setopts = common.setopts; var ownProp = common.ownProp; var childrenIgnored = common.childrenIgnored; var isIgnored = common.isIgnored; function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync(pattern, options).found } function GlobSync (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync)) return new GlobSync(pattern, options) setopts(this, pattern, options); if (this.noprocess) return this var n = this.minimatch.set.length; this.matches = new Array(n); for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false); } this._finish(); } GlobSync.prototype._finish = function () { assert.ok(this instanceof GlobSync); if (this.realpath) { var self = this; this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null); for (var p in matchset) { try { p = self._makeAbs(p); var real = rp.realpathSync(p, self.realpathCache); set[real] = true; } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true; else throw er } } }); } common.finish(this); }; GlobSync.prototype._process = function (pattern, index, inGlobStar) { assert.ok(this instanceof GlobSync); // Get the first [n] parts of pattern that are all strings. var n = 0; while (typeof pattern[n] === 'string') { n ++; } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix; switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index); return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null; break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/'); break } var remain = pattern.slice(n); // get the list of entries. var read; if (prefix === null) read = '.'; else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) { return typeof p === 'string' ? p : '[*]' }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix; read = prefix; } else read = prefix; var abs = this._makeAbs(read); //if ignored, skip processing if (childrenIgnored(this, read)) return var isGlobStar = remain[0] === minimatch.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar); else this._processReaddir(prefix, read, abs, remain, index, inGlobStar); }; GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar); // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0]; var negate = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === '.'; var matchedEntries = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.charAt(0) !== '.' || dotOk) { var m; if (negate && !prefix) { m = !e.match(pn); } else { m = e.match(pn); } if (m) matchedEntries.push(e); } } var len = matchedEntries.length; // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e; else e = prefix + e; } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e); } this._emitMatch(index, e); } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift(); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; var newPattern; if (prefix) newPattern = [prefix, e]; else newPattern = [e]; this._process(newPattern.concat(remain), index, inGlobStar); } }; GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored(this, e)) return var abs = this._makeAbs(e); if (this.mark) e = this._mark(e); if (this.absolute) { e = abs; } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs]; if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true; if (this.stat) this._stat(e); }; GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries; var lstat; try { lstat = this.fs.lstatSync(abs); } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink(); this.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE'; else entries = this._readdir(abs, false); return entries }; GlobSync.prototype._readdir = function (abs, inGlobStar) { if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp(this.cache, abs)) { var c = this.cache[abs]; if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, this.fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er); return null } }; GlobSync.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i]; if (abs === '/') e = abs + e; else e = abs + '/' + e; this.cache[e] = true; } } this.cache[abs] = entries; // mark and cache dir-ness return entries }; GlobSync.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f); this.cache[abs] = 'FILE'; if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd); error.path = this.cwd; error.code = er.code; throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false; break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false; if (this.strict) throw er if (!this.silent) console.error('glob error', er); break } }; GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar); // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1); var gspref = prefix ? [ prefix ] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false); var len = entries.length; var isSym = this.symlinks[abs]; // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i]; if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar); this._process(instead, index, true); var below = gspref.concat(entries[i], remain); this._process(below, index, true); } }; GlobSync.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix); if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix); if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix); } else { prefix = path.resolve(this.root, prefix); if (trail) prefix += '/'; } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match this._emitMatch(index, prefix); }; // Returns either 'DIR', 'FILE', or false GlobSync.prototype._stat = function (f) { var abs = this._makeAbs(f); var needDir = f.slice(-1) === '/'; if (f.length > this.maxLength) return false if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs]; if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var stat = this.statCache[abs]; if (!stat) { var lstat; try { lstat = this.fs.lstatSync(abs); } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false; return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = this.fs.statSync(abs); } catch (er) { stat = lstat; } } else { stat = lstat; } } this.statCache[abs] = stat; var c = true; if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE'; this.cache[abs] = this.cache[abs] || c; if (needDir && c === 'FILE') return false return c }; GlobSync.prototype._mark = function (p) { return common.mark(this, p) }; GlobSync.prototype._makeAbs = function (f) { return common.makeAbs(this, f) }; return sync$9; } // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. var wrappy_1 = wrappy$2; function wrappy$2 (fn, cb) { if (fn && cb) return wrappy$2(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k]; }); return wrapper function wrapper() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } var ret = fn.apply(this, args); var cb = args[args.length-1]; if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k]; }); } return ret } } var onceExports = {}; var once$2 = { get exports(){ return onceExports; }, set exports(v){ onceExports = v; }, }; var wrappy$1 = wrappy_1; once$2.exports = wrappy$1(once$1); onceExports.strict = wrappy$1(onceStrict); once$1.proto = once$1(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once$1(this) }, configurable: true }); Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }); }); function once$1 (fn) { var f = function () { if (f.called) return f.value f.called = true; return f.value = fn.apply(this, arguments) }; f.called = false; return f } function onceStrict (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true; return f.value = fn.apply(this, arguments) }; var name = fn.name || 'Function wrapped with `once`'; f.onceError = name + " shouldn't be called more than once"; f.called = false; return f } var wrappy = wrappy_1; var reqs = Object.create(null); var once = onceExports; var inflight_1 = wrappy(inflight); function inflight (key, cb) { if (reqs[key]) { reqs[key].push(cb); return null } else { reqs[key] = [cb]; return makeres(key) } } function makeres (key) { return once(function RES () { var cbs = reqs[key]; var len = cbs.length; var args = slice$1(arguments); // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args); } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len); process.nextTick(function () { RES.apply(null, args); }); } else { delete reqs[key]; } } }) } function slice$1 (args) { var length = args.length; var array = []; for (var i = 0; i < length; i++) array[i] = args[i]; return array } var glob_1; var hasRequiredGlob; function requireGlob () { if (hasRequiredGlob) return glob_1; hasRequiredGlob = 1; // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. glob_1 = glob; var rp = fs_realpath; var minimatch = minimatch_1; var inherits = inheritsExports; var EE = require$$0$5.EventEmitter; var path = require$$0$4; var assert = require$$5; var isAbsolute = require$$0$4.isAbsolute; var globSync = requireSync(); var common = common$c; var setopts = common.setopts; var ownProp = common.ownProp; var inflight = inflight_1; var childrenIgnored = common.childrenIgnored; var isIgnored = common.isIgnored; var once = onceExports; function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {}; if (!options) options = {}; if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync; var GlobSync = glob.GlobSync = globSync.GlobSync; // old api surface glob.glob = glob; function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_); options.noprocess = true; var g = new Glob(pattern, options); var set = g.minimatch.set; if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false }; glob.Glob = Glob; inherits(Glob, EE); function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options; options = null; } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options); this._didRealPath = false; // process each pattern in the minimatch set var n = this.minimatch.set.length; // The matches are stored as {: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n); if (typeof cb === 'function') { cb = once(cb); this.on('error', cb); this.on('end', function (matches) { cb(null, matches); }); } var self = this; this._processing = 0; this._emitQueue = []; this._processQueue = []; this.paused = false; if (this.noprocess) return this if (n === 0) return done() var sync = true; for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done); } sync = false; function done () { --self._processing; if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish(); }); } else { self._finish(); } } } } Glob.prototype._finish = function () { assert(this instanceof Glob); if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this); this.emit('end', this.found); }; Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true; var n = this.matches.length; if (n === 0) return this._finish() var self = this; for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next); function next () { if (--n === 0) self._finish(); } }; Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index]; if (!matchset) return cb() var found = Object.keys(matchset); var self = this; var n = found.length; if (n === 0) return cb() var set = this.matches[index] = Object.create(null); found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p); rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true; else if (er.syscall === 'stat') set[p] = true; else self.emit('error', er); // srsly wtf right here if (--n === 0) { self.matches[index] = set; cb(); } }); }); }; Glob.prototype._mark = function (p) { return common.mark(this, p) }; Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) }; Glob.prototype.abort = function () { this.aborted = true; this.emit('abort'); }; Glob.prototype.pause = function () { if (!this.paused) { this.paused = true; this.emit('pause'); } }; Glob.prototype.resume = function () { if (this.paused) { this.emit('resume'); this.paused = false; if (this._emitQueue.length) { var eq = this._emitQueue.slice(0); this._emitQueue.length = 0; for (var i = 0; i < eq.length; i ++) { var e = eq[i]; this._emitMatch(e[0], e[1]); } } if (this._processQueue.length) { var pq = this._processQueue.slice(0); this._processQueue.length = 0; for (var i = 0; i < pq.length; i ++) { var p = pq[i]; this._processing--; this._process(p[0], p[1], p[2], p[3]); } } } }; Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob); assert(typeof cb === 'function'); if (this.aborted) return this._processing++; if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]); return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0; while (typeof pattern[n] === 'string') { n ++; } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix; switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb); return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null; break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/'); break } var remain = pattern.slice(n); // get the list of entries. var read; if (prefix === null) read = '.'; else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) { return typeof p === 'string' ? p : '[*]' }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix; read = prefix; } else read = prefix; var abs = this._makeAbs(read); //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb); else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb); }; Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this; this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }); }; Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0]; var negate = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === '.'; var matchedEntries = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.charAt(0) !== '.' || dotOk) { var m; if (negate && !prefix) { m = !e.match(pn); } else { m = e.match(pn); } if (m) matchedEntries.push(e); } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length; // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix !== '/') e = prefix + '/' + e; else e = prefix + e; } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e); } this._emitMatch(index, e); } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift(); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix !== '/') e = prefix + '/' + e; else e = prefix + e; } this._process([e].concat(remain), index, inGlobStar, cb); } cb(); }; Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]); return } var abs = isAbsolute(e) ? e : this._makeAbs(e); if (this.mark) e = this._mark(e); if (this.absolute) e = abs; if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs]; if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true; var st = this.statCache[abs]; if (st) this.emit('stat', e, st); this.emit('match', e); }; Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs; var self = this; var lstatcb = inflight(lstatkey, lstatcb_); if (lstatcb) self.fs.lstat(abs, lstatcb); function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink(); self.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE'; cb(); } else self._readdir(abs, false, cb); } }; Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb); if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs]; if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this; self.fs.readdir(abs, readdirCb(this, abs, cb)); }; function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb); else self._readdirEntries(abs, entries, cb); } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i]; if (abs === '/') e = abs + e; else e = abs + '/' + e; this.cache[e] = true; } } this.cache[abs] = entries; return cb(null, entries) }; Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f); this.cache[abs] = 'FILE'; if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd); error.path = this.cwd; error.code = er.code; this.emit('error', error); this.abort(); } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false; break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false; if (this.strict) { this.emit('error', er); // If the error is handled, then we abort // if not, we threw out of here this.abort(); } if (!this.silent) console.error('glob error', er); break } return cb() }; Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this; this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb); }); }; Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1); var gspref = prefix ? [ prefix ] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb); var isSym = this.symlinks[abs]; var len = entries.length; // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i]; if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar); this._process(instead, index, true, cb); var below = gspref.concat(entries[i], remain); this._process(below, index, true, cb); } cb(); }; Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this; this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb); }); }; Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix); if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix); } else { prefix = path.resolve(this.root, prefix); if (trail) prefix += '/'; } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match this._emitMatch(index, prefix); cb(); }; // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f); var needDir = f.slice(-1) === '/'; if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs]; if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var stat = this.statCache[abs]; if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE'; if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this; var statcb = inflight('stat\0' + abs, lstatcb_); if (statcb) self.fs.lstat(abs, statcb); function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return self.fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb); else self._stat2(f, abs, er, stat, cb); }) } else { self._stat2(f, abs, er, lstat, cb); } } }; Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false; return cb() } var needDir = f.slice(-1) === '/'; this.statCache[abs] = stat; if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true; if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE'; this.cache[abs] = this.cache[abs] || c; if (needDir && c === 'FILE') return cb() return cb(null, c, stat) }; return glob_1; } var globExports = requireGlob(); var glob = /*@__PURE__*/getDefaultExportFromCjs(globExports); 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; } // 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; }, }; function decode(mappings) { const state = new Int32Array(5); const decoded = []; let index = 0; do { const semi = indexOf(mappings, index); const line = []; let sorted = true; let lastCol = 0; state[0] = 0; for (let i = index; i < semi; i++) { let seg; i = decodeInteger(mappings, i, state, 0); // genColumn const col = state[0]; if (col < lastCol) sorted = false; lastCol = col; if (hasMoreVlq(mappings, i, semi)) { i = decodeInteger(mappings, i, state, 1); // sourcesIndex i = decodeInteger(mappings, i, state, 2); // sourceLine i = decodeInteger(mappings, i, state, 3); // sourceColumn if (hasMoreVlq(mappings, i, semi)) { i = decodeInteger(mappings, i, state, 4); // namesIndex seg = [col, state[1], state[2], state[3], state[4]]; } else { seg = [col, state[1], state[2], state[3]]; } } else { seg = [col]; } line.push(seg); } if (!sorted) sort(line); decoded.push(line); index = semi + 1; } while (index <= mappings.length); return decoded; } function indexOf(mappings, index) { const idx = mappings.indexOf(';', index); return idx === -1 ? mappings.length : idx; } function decodeInteger(mappings, pos, state, j) { let value = 0; let shift = 0; let integer = 0; do { const c = mappings.charCodeAt(pos++); integer = charToInt[c]; value |= (integer & 31) << shift; shift += 5; } while (integer & 32); const shouldNegate = value & 1; value >>>= 1; if (shouldNegate) { value = -0x80000000 | -value; } state[j] += value; return pos; } function hasMoreVlq(mappings, i, length) { if (i >= length) return false; return mappings.charCodeAt(i) !== comma; } function sort(line) { line.sort(sortComparator$1); } function sortComparator$1(a, b) { return a[0] - b[0]; } function encode$1(decoded) { const state = new Int32Array(5); const bufLength = 1024 * 16; const subLength = bufLength - 36; const buf = new Uint8Array(bufLength); const sub = buf.subarray(0, subLength); let pos = 0; let out = ''; for (let i = 0; i < decoded.length; i++) { const line = decoded[i]; if (i > 0) { if (pos === bufLength) { out += td.decode(buf); pos = 0; } buf[pos++] = semicolon; } if (line.length === 0) continue; state[0] = 0; for (let j = 0; j < line.length; j++) { const segment = line[j]; // We can push up to 5 ints, each int can take at most 7 chars, and we // may push a comma. if (pos > subLength) { out += td.decode(sub); buf.copyWithin(0, subLength, pos); pos -= subLength; } if (j > 0) buf[pos++] = comma; pos = encodeInteger(buf, pos, state, segment, 0); // genColumn if (segment.length === 1) continue; pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn if (segment.length === 4) continue; pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex } } return out + td.decode(buf.subarray(0, pos)); } function encodeInteger(buf, pos, state, segment, j) { const next = segment[j]; let num = next - state[j]; state[j] = next; num = num < 0 ? (-num << 1) | 1 : num << 1; do { let clamped = num & 0b011111; num >>>= 5; if (num > 0) clamped |= 0b100000; buf[pos++] = intToChar[clamped]; } while (num > 0); return pos; } let BitSet$1 = 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))); } }; let Chunk$1 = 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; } 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) { // 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); } 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) { this.split(this.end - trimmed.length); 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$1 () { if (typeof window !== 'undefined' && typeof window.btoa === 'function') { return (str) => window.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$2 = /*#__PURE__*/ getBtoa$1(); let SourceMap$2 = 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); } toString() { return JSON.stringify(this); } toUrl() { return 'data:application/json;charset=utf-8;base64,' + btoa$2(this.toString()); } }; function guessIndent$1(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$3 = Object.prototype.toString; function isObject$3(thing) { return toString$3.call(thing) === '[object Object]'; } function getLocator$1(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 }; }; } let Mappings$1 = 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 segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (nameIndex >= 0) { segment.push(nameIndex); } this.rawSegments.push(segment); } 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; while (originalCharIndex < chunk.end) { if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); } 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 { 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$2 = '\n'; const warned$1 = { insertLeft: false, insertRight: false, storeName: false, }; let MagicString$1 = class MagicString { constructor(string, options = {}) { const chunk = new Chunk$1(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$1() }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: undefined }, }); 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$1(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$1(options.hires); const locate = getLocator$1(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() : null, sources: [options.source ? getRelativePath$1(options.file || '', options.source) : null], sourcesContent: options.includeContent ? [this.original] : [null], names, mappings: mappings.raw, }; } generateMap(options) { return new SourceMap$2(this.generateDecodedMap(options)); } _ensureindentStr() { if (this.indentStr === undefined) { this.indentStr = guessIndent$1(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$1.insertLeft) { console.warn( 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' ); // eslint-disable-line no-console warned$1.insertLeft = true; } return this.appendLeft(index, content); } insertRight(index, content) { if (!warned$1.insertRight) { console.warn( 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' ); // eslint-disable-line no-console warned$1.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'); 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$1.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$1.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$1(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) { 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; } 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$2); 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$2); if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; lineStr = chunk.outro + lineStr; } if (chunk.content.length > 0) { lineIndex = chunk.content.lastIndexOf(n$2); if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; lineStr = chunk.content + lineStr; } if (chunk.intro.length > 0) { lineIndex = chunk.intro.lastIndexOf(n$2); if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; lineStr = chunk.intro + lineStr; } } while ((chunk = chunk.previous)); lineIndex = this.intro.lastIndexOf(n$2); if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; return this.intro + lineStr; } slice(start = 0, end = this.original.length) { 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$1(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) this.overwrite( match.index, match.index + match[0].length, getReplacement(match, this.original) ); }); } else { const match = this.original.match(searchValue); if (match && match.index != null) this.overwrite( match.index, match.index + match[0].length, getReplacement(match, this.original) ); } 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) ) { 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$3 = "24.0.1"; var peerDependencies = { rollup: "^2.68.0||^3.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) { case true: return { strictRequiresFilter: () => true, detectCyclesAndConditional: false }; // eslint-disable-next-line no-undefined case undefined: 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$1(dirPath, 'package.json'))) { entryPoint = JSON.parse(readFileSync(join$1(dirPath, 'package.json'), { encoding: 'utf8' })).main || entryPoint; } } catch (ignored) { // ignored } return entryPoint; } function isDirectory(path) { try { if (statSync$1(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); for (const path of glob.sync(isNegated ? pattern.substr(1) : pattern)) { const resolvedPath = resolve$3(path); const requirePath = normalizePathSlashes(resolvedPath); if (isDirectory(resolvedPath)) { dirNames.add(resolvedPath); const modulePath = resolve$3(join$1(resolvedPath, getPackageEntryPoint(path))); modifyMap(requirePath, modulePath); modifyMap(normalizePathSlashes(modulePath), modulePath); } else { dirNames.add(dirname$1(resolvedPath)); modifyMap(requirePath, resolvedPath); } } } return { commonDir: dirNames.size ? commondir([...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$1 = (id, suffix) => `\0${id}${suffix}`; const unwrapId$1 = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length); const PROXY_SUFFIX = '?commonjs-proxy'; const WRAPPED_SUFFIX = '?commonjs-wrapped'; const EXTERNAL_SUFFIX = '?commonjs-external'; const EXPORTS_SUFFIX = '?commonjs-exports'; const MODULE_SUFFIX = '?commonjs-module'; const ENTRY_SUFFIX = '?commonjs-entry'; 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) { var args = [null]; args.push.apply(args, arguments); var Ctor = Function.bind.apply(f, args); return new Ctor(); } 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); } else if (commonjsMeta.isCommonJS) { return `export { __moduleExports as default } from ${JSON.stringify(id)};`; } else if (!requireReturnsDefault) { return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify( id )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`; } else 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) { 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 code; } return getEsImportProxy(id, defaultIsModuleExports); } function getEsImportProxy(id, defaultIsModuleExports) { 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} = ${requireModule}();\n` + `export { ${exportsName} as __moduleExports };`; if (defaultIsModuleExports === true) { code += `\nexport { ${exportsName} as default };`; } else { code += `export 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$1(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 && customOptions['node-resolve'] && 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$1(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$1(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, { custom: { 'node-resolve': { isRequire: true } } })) || resolveExtensions(source, parentId, extensions); currentlyResolvingForParent.delete(source); if (!resolved) { return { id: wrapId$1(source, EXTERNAL_SUFFIX), allowProxy: false }; } const childId = resolved.id; if (resolved.external) { return { id: wrapId$1(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)); fullyAnalyzedModules[dependencyId] = true; return { source: sources[index].source, id: allowProxy ? isCommonJS === IS_WRAPPED_COMMONJS ? wrapId$1(dependencyId, WRAPPED_SUFFIX) : wrapId$1(dependencyId, 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 isDefineCompiledEsm(node) { const definedProperty = getDefinePropertyCallName(node, 'exports') || getDefinePropertyCallName(node, 'module.exports'); if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) { return isTruthy(definedProperty.value); } 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 hasDefineEsmProperty(node) { return node.properties.some((property) => { if ( property.type === 'Property' && property.key.type === 'Identifier' && property.key.name === '__esModule' && isTruthy(property.value) ) { return true; } return false; }); } 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(exportsName); } magicString .trim() .indent('\t', { exclude: indentExclusionRanges }) .prepend(`(function (${args.join(', ')}) {\n`) .append(`\n} (${passedArgs.join(', ')}));`); } function rewriteExportsAndGetExportsBlock( magicString, moduleName, exportsName, wrapped, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, defineCompiledEsmExpressions, deconflictedExportNames, code, HELPERS_NAME, exportMode, detectWrappedDefault, 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 ); } else { exports.push(`${exportsName} as __moduleExports`); if (wrapped) { getExportsWhenWrapping( exportDeclarations, exportsName, detectWrappedDefault, HELPERS_NAME, defaultIsModuleExports ); } else { getExports( magicString, exports, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports ); } } 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 ) { if (!wrapped) { if (exportMode === 'replace') { for (const { left } of moduleExportsAssignments) { magicString.overwrite(left.start, left.end, exportsName); } } else { // 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) { for (const node of nodes) { magicString.overwrite(node.start, node.left.end, `${exportsName}.${exportName}`); } } // Collect and rewrite exports.__esModule assignments for (const expression of defineCompiledEsmExpressions) { const moduleExportsExpression = expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object; magicString.overwrite( moduleExportsExpression.start, moduleExportsExpression.end, exportsName ); } } } exports.push(`${requireName} as __require`); } function getExportsForReplacedModuleExports( magicString, exports, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName ) { 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(`export default ${exportsName};`); } function getExportsWhenWrapping( exportDeclarations, exportsName, detectWrappedDefault, HELPERS_NAME, defaultIsModuleExports ) { exportDeclarations.push( `export default ${ detectWrappedDefault && defaultIsModuleExports === 'auto' ? `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName})` : defaultIsModuleExports === false ? `${exportsName}.default` : exportsName };` ); } function getExports( magicString, exports, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports ) { 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 of nodes) { let replacement = `${deconflicted} = ${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}`); } } // Collect and rewrite exports.__esModule assignments let isRestorableCompiledEsm = false; for (const expression of defineCompiledEsmExpressions) { isRestorableCompiledEsm = true; const moduleExportsExpression = expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object; magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportsName); } if (!isRestorableCompiledEsm || defaultIsModuleExports === true) { exports.push(`${exportsName} as default`); } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) { exports.push(`${deconflictedDefaultExportName || exportsName} as default`); } else { exportDeclarations.push( `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});` ); } } 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}, exports as ${exportsName} } from ${JSON.stringify( wrapId$1(id, MODULE_SUFFIX) )}` ); } else if (exportMode === 'exports') { imports.push( `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId$1(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 } 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, `${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)$/; 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$1(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 currentTryBlockEnd = null; let shouldWrap = false; let reexports = 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 replacedDynamicRequires = []; const importedVariables = new Set(); const indentExclusionRanges = []; walk$3(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; } if (defaultIsModuleExports === false) { shouldWrap = true; } else if (defaultIsModuleExports === 'auto') { if (node.right.type === 'ObjectExpression') { if (hasDefineEsmProperty(node.right)) { shouldWrap = true; } } else if (isRequireExpression(node.right, scope)) { shouldWrap = true; reexports = true; } } } else if (exportName === KEY_COMPILED_ESM) { if (programDepth > 3) { shouldWrap = true; } else { topLevelDefineCompiledEsmExpressions.push(node); } } else { const exportsAssignments = exportsAssignmentsByName.get(exportName) || { nodes: [], scopes: new Set() }; exportsAssignments.nodes.push(node); 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': { if (isDefineCompiledEsm(node)) { 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); } 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); 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 '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)) return; switch (name) { case 'require': uses.require = true; if (isNodeRequirePropertyAccess(parent)) { return; } if (!ignoreDynamicRequires) { if (isShorthandProperty(parent)) { 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) { uses.global = true; if (!ignoreGlobal) { replacedGlobal.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; } }); 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 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)); const detectWrappedDefault = shouldWrap && (reexports || topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 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(); } const exportMode = isEsModule ? 'none' : shouldWrap ? uses.module ? 'module' : 'exports' : firstTopLevelModuleExportsAssignment ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0 ? 'replace' : 'module' : moduleExportsAssignments.length === 0 ? 'exports' : 'module'; 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, shouldWrap, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, topLevelDefineCompiledEsmExpressions, deconflictedExportNames, code, helpersName, exportMode, detectWrappedDefault, defaultIsModuleExports, usesRequireWrapper, requireName ); if (shouldWrap) { wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges); } if (usesRequireWrapper) { magicString.trim().indent('\t', { exclude: indentExclusionRanges }); magicString.prepend( `var ${isRequiredName}; function ${requireName} () { \tif (${isRequiredName}) return ${exportsName}; \t${isRequiredName} = 1; ` ).append(` \treturn ${exportsName}; }`); if (exportMode === 'replace') { magicString.prepend(`var ${exportsName};\n`); } } magicString .trim() .prepend(leadingComment + importBlock) .append(exportBlock); return { code: magicString.toString(), map: sourceMap ? magicString.generateMap() : null, syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports', meta: { commonjs: commonjsMeta } }; } 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 { 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(normalizePathSlashes(id)) && (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) || (isEsModule && !options.transformMixedEsModules)) ) { commonjsMeta.isCommonJS = false; return { meta: { commonjs: commonjsMeta } }; } const needsRequireWrapper = !isEsModule && (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id)); const checkDynamicRequire = (position) => { if (id.indexOf(dynamicRequireRoot) !== 0) { this.error( { code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT', id, dynamicRequireRoot, message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname$1( id )}" 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$3, 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.' }); } } }, load(id) { if (id === HELPERS_ID) { return getHelpersModule(); } if (isWrappedId(id, MODULE_SUFFIX)) { const module = getName(unwrapId$1(id, MODULE_SUFFIX)); const moduleExports = `${module}Exports`; return { code: `var ${moduleExports} = {}; var ${module} = { get exports(){ return ${moduleExports}; }, set exports(v){ ${moduleExports} = v; }, }; export {${module} as __module, ${moduleExports} as exports}`, meta: { commonjs: { isCommonJS: false } } }; } if (isWrappedId(id, EXPORTS_SUFFIX)) { const name = getName(unwrapId$1(id, EXPORTS_SUFFIX)); return { code: `var ${name} = {}; export {${name} as __exports}`, meta: { commonjs: { isCommonJS: false } } }; } if (isWrappedId(id, EXTERNAL_SUFFIX)) { const actualId = unwrapId$1(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); return getEntryProxy(acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo); } if (isWrappedId(id, ES_IMPORT_SUFFIX)) { const actualId = unwrapId$1(id, ES_IMPORT_SUFFIX); return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId)); } if (id === DYNAMIC_MODULES_ID) { return getDynamicModuleRegistry( isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires ); } if (isWrappedId(id, PROXY_SUFFIX)) { const actualId = unwrapId$1(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.loc); } } }; } // 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; var UrlType; (function (UrlType) { UrlType[UrlType["Empty"] = 1] = "Empty"; UrlType[UrlType["Hash"] = 2] = "Hash"; UrlType[UrlType["Query"] = 3] = "Query"; UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; UrlType[UrlType["Absolute"] = 7] = "Absolute"; })(UrlType || (UrlType = {})); 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: UrlType.Absolute, }; } function parseUrl$2(input) { if (isSchemeRelativeUrl(input)) { const url = parseAbsoluteUrl('http:' + input); url.scheme = ''; url.type = UrlType.SchemeRelative; return url; } if (isAbsolutePath(input)) { const url = parseAbsoluteUrl('http://foo.com' + input); url.scheme = ''; url.host = ''; url.type = UrlType.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('?') ? UrlType.Query : input.startsWith('#') ? UrlType.Hash : UrlType.RelativePath : UrlType.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 <= UrlType.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$2(input); let inputType = url.type; if (base && inputType !== UrlType.Absolute) { const baseUrl = parseUrl$2(base); const baseType = baseUrl.type; switch (inputType) { case UrlType.Empty: url.hash = baseUrl.hash; // fall through case UrlType.Hash: url.query = baseUrl.query; // fall through case UrlType.Query: case UrlType.RelativePath: mergePaths(url, baseUrl); // fall through case UrlType.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 UrlType.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 UrlType.Hash: case UrlType.Query: return queryHash; case UrlType.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 UrlType.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 = 0; const SOURCES_INDEX = 1; const SOURCE_LINE = 2; const SOURCE_COLUMN = 3; const NAMES_INDEX = 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] < line[j - 1][COLUMN]) { return false; } } return true; } function sortSegments(line, owned) { if (!owned) line = line.slice(); return line.sort(sortComparator); } function sortComparator(a, b) { return a[COLUMN] - b[COLUMN]; } 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] - 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] !== needle) break; } return index; } function lowerBound(haystack, needle, index) { for (let i = index - 1; i >= 0; index = i--) { if (haystack[i][COLUMN] !== 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] === 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; /** * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. */ let decodedMappings; /** * 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`. */ let traceSegment; /** * 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. */ let originalPositionFor$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; 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; } } (() => { decodedMappings = (map) => { return (map._decoded || (map._decoded = decode(map._encoded))); }; 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, map._decodedMemo, line, column, GREATEST_LOWER_BOUND); return index === -1 ? null : segments[index]; }; originalPositionFor$1 = (map, { line, column, bias }) => { 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, 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]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null); }; })(); 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; } /** * Gets the index associated with `key` in the backing array, if it is already present. */ let get; /** * Puts `key` into the backing array, if it is not already present. Returns * the index of the `key` in the backing array. */ let put; /** * 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 = []; } } (() => { get = (strarr, key) => strarr._indexes[key]; put = (strarr, key) => { // The key may or may not be present. If it is present, it's a number. const index = get(strarr, key); if (index !== undefined) return index; const { array, _indexes: indexes } = strarr; return (indexes[key] = array.push(key) - 1); }; })(); /** * A low-level API to associate a generated position with an original source position. Line and * column here are 0-based, unlike `addMapping`. */ let addSegment; /** * Adds/removes the content of the source file to the source map. */ let setSourceContent; /** * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects * a sourcemap, or to JSON.stringify. */ let decodedMap; /** * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects * a sourcemap, or to JSON.stringify. */ let encodedMap; /** * 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; } } (() => { addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name) => { const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; const line = getLine(mappings, genLine); if (source == null) { const seg = [genColumn]; const index = getColumnIndex(line, genColumn, seg); return insert(line, index, seg); } const sourcesIndex = put(sources, source); const seg = name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, put(names, name)] : [genColumn, sourcesIndex, sourceLine, sourceColumn]; const index = getColumnIndex(line, genColumn, seg); if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = null; insert(line, index, seg); }; setSourceContent = (map, source, content) => { const { _sources: sources, _sourcesContent: sourcesContent } = map; sourcesContent[put(sources, source)] = content; }; decodedMap = (map) => { const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; return { version: 3, file, names: names.array, sourceRoot: sourceRoot || undefined, sources: sources.array, sourcesContent, mappings, }; }; encodedMap = (map) => { const decoded = decodedMap(map); return Object.assign(Object.assign({}, decoded), { mappings: encode$1(decoded.mappings) }); }; })(); function getLine(mappings, index) { for (let i = mappings.length; i <= index; i++) { mappings[i] = []; } return mappings[index]; } function getColumnIndex(line, column, seg) { let index = line.length; for (let i = index - 1; i >= 0; i--, index--) { const current = line[i]; const col = current[0]; if (col > column) continue; if (col < column) break; const cmp = compare$1(current, seg); if (cmp === 0) return index; if (cmp < 0) break; } return index; } function compare$1(a, b) { let cmp = compareNum(a.length, b.length); if (cmp !== 0) return cmp; // We've already checked genColumn if (a.length === 1) return 0; cmp = compareNum(a[1], b[1]); if (cmp !== 0) return cmp; cmp = compareNum(a[2], b[2]); if (cmp !== 0) return cmp; cmp = compareNum(a[3], b[3]); if (cmp !== 0) return cmp; if (a.length === 4) return 0; return compareNum(a[4], b[4]); } function compareNum(a, b) { return a - b; } function insert(array, index, value) { if (index === -1) return; for (let i = array.length; i > index; i--) { array[i] = array[i - 1]; } array[index] = value; } const SOURCELESS_MAPPING = { source: null, column: null, line: null, name: null, content: null, }; const EMPTY_SOURCES = []; function Source(map, sources, source, content) { return { map, sources, source, content, }; } /** * 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); } /** * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive * segment tracing ends at the `OriginalSource`. */ function OriginalSource(source, content) { return Source(null, EMPTY_SOURCES, source, content); } /** * 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) { 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]; let lastSource = null; let lastSourceLine = null; let lastSourceColumn = null; 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; } // So we traced a segment down into its original source file. Now push a // new segment pointing to this location. const { column, line, name, content, source } = traced; if (line === lastSourceLine && column === lastSourceColumn && source === lastSource) { continue; } lastSourceLine = line; lastSourceColumn = column; lastSource = source; // Sigh, TypeScript can't figure out source/line/column are either all null, or all non-null... addSegment(gen, i, genCol, source, line, column, name); if (content != null) setSourceContent(gen, source, content); } } 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 { column, line, name, source: source.source, content: source.content }; } 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 } = 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, }; // 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 } = 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 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; return OriginalSource(source, sourceContent); }); return MapSource(map, children); } /** * A SourceMap v3 compatible sourcemap, which only includes fields that were * provided to it. */ let SourceMap$1 = class SourceMap { constructor(map, options) { const out = options.decodedMappings ? decodedMap(map) : encodedMap(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.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 = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; const tree = buildSourceMapTree(input, loader); return new SourceMap$1(traceMappings(tree), opts); } var srcExports$1 = {}; var src$2 = { get exports(){ return srcExports$1; }, set exports(v){ srcExports$1 = v; }, }; var browserExports$1 = {}; var browser$2 = { get exports(){ return browserExports$1; }, set exports(v){ browserExports$1 = v; }, }; /** * 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$b; var hasRequiredCommon; function requireCommon () { if (hasRequiredCommon) return common$b; 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$b = setup; return common$b; } /* eslint-env browser */ var hasRequiredBrowser$1; function requireBrowser$1 () { if (hasRequiredBrowser$1) return browserExports$1; 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; } // 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 && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$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, browserExports$1)); return browserExports$1; } var nodeExports$1 = {}; var node$1 = { get exports(){ return nodeExports$1; }, set exports(v){ nodeExports$1 = v; }, }; /** * Module dependencies. */ var hasRequiredNode$1; function requireNode$1 () { if (hasRequiredNode$1) return nodeExports$1; hasRequiredNode$1 = 1; (function (module, exports) { const tty = require$$0$3; const util = require$$0$6; /** * 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.format()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.format(...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, nodeExports$1)); return nodeExports$1; } /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ (function (module) { if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { module.exports = requireBrowser$1(); } else { module.exports = requireNode$1(); } } (src$2)); var _debug = /*@__PURE__*/getDefaultExportFromCjs(srcExports$1); const createFilter = createFilter$1; function slash$1(p) { return p.replace(/\\/g, '/'); } /** * Prepend `/@id/` and replace null byte so the id is URL-safe. * This is prepended to resolved ids that are not valid browser * import specifiers by the importAnalysis plugin. */ function wrapId(id) { return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace('\0', NULL_BYTE_PLACEHOLDER); } /** * Undo {@link wrapId}'s `/@id/` and null byte replacements. */ function unwrapId(id) { return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, '\0') : id; } const flattenId = (id) => id .replace(/[/:]/g, '_') .replace(/\./g, '__') .replace(/(\s*>\s*)/g, '___') .replace(/#/g, '____'); const normalizeId = (id) => id.replace(/(\s*>\s*)/g, ' > '); //TODO: revisit later to see if the edge case that "compiling using node v12 code to be run in node v16 in the server" is what we intend to support. const builtins = new Set([ ...builtinModules, 'assert/strict', 'diagnostics_channel', 'dns/promises', 'fs/promises', 'path/posix', 'path/win32', 'readline/promises', 'stream/consumers', 'stream/promises', 'stream/web', 'timers/promises', 'util/types', 'wasi', ]); function isBuiltin(id) { return builtins.has(id.replace(/^node:/, '')); } function moduleListContains(moduleList, id) { return moduleList?.some((m) => m === id || id.startsWith(m + '/')); } function isOptimizable(id, optimizeDeps) { const { extensions } = optimizeDeps; return (OPTIMIZABLE_ENTRY_RE.test(id) || (extensions?.some((ext) => id.endsWith(ext)) ?? false)); } const bareImportRE = /^[\w@](?!.*:\/\/)/; let isRunningWithYarnPnp; // TODO: use import() const _require$3 = createRequire$1(import.meta.url); try { isRunningWithYarnPnp = Boolean(_require$3('pnpapi')); } catch { } const ssrExtensions = ['.js', '.cjs', '.json', '.node']; function resolveFrom(id, basedir, preserveSymlinks = false, ssr = false) { return resolve$4.sync(id, { basedir, paths: [], extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS$1, // necessary to work with pnpm preserveSymlinks: preserveSymlinks || isRunningWithYarnPnp || false, }); } /** * like `resolveFrom` but supports resolving `>` path in `id`, * for example: `foo > bar > baz` */ function nestedResolveFrom(id, basedir, preserveSymlinks = false, ssr = false) { const pkgs = id.split('>').map((pkg) => pkg.trim()); try { for (const pkg of pkgs) { basedir = resolveFrom(pkg, basedir, preserveSymlinks, ssr); } } catch { } return basedir; } // set in bin/vite.js const filter = process.env.VITE_DEBUG_FILTER; const DEBUG = process.env.DEBUG; function createDebugger(namespace, options = {}) { const log = _debug(namespace); const { onlyWhenFocused } = options; const focus = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace; return (msg, ...args) => { if (filter && !msg.includes(filter)) { return; } if (onlyWhenFocused && !DEBUG?.includes(focus)) { return; } log(msg, ...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$l.existsSync(CLIENT_ENTRY)) { throw new Error('cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' + CLIENT_ENTRY); } return fs$l.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs')); } const isCaseInsensitiveFS = testCaseInsensitiveFS(); const isWindows$4 = os$3.platform() === 'win32'; const VOLUME_RE = /^[A-Z]:/i; function normalizePath$3(id) { return path$o.posix.normalize(isWindows$4 ? slash$1(id) : id); } function fsPathFromId(id) { const fsPath = normalizePath$3(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id); return fsPath.startsWith('/') || fsPath.match(VOLUME_RE) ? fsPath : `/${fsPath}`; } function fsPathFromUrl(url) { return fsPathFromId(cleanUrl(url)); } /** * Check if dir is a parent of file * * Warning: parameters are not validated, only works with normalized absolute paths * * @param dir - normalized absolute path * @param file - normalized absolute path * @returns true if dir is a parent of file */ function isParentDirectory(dir, file) { if (!dir.endsWith('/')) { dir = `${dir}/`; } return (file.startsWith(dir) || (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase()))); } function ensureVolumeInPath(file) { return isWindows$4 ? path$o.resolve(file) : file; } const queryRE = /\?.*$/s; const hashRE = /#.*$/s; const cleanUrl = (url) => url.replace(hashRE, '').replace(queryRE, ''); const externalRE = /^(https?:)?\/\//; 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)(?:$|\?)/; const isJSRequest = (url) => { url = cleanUrl(url); if (knownJsSrcRE.test(url)) { return true; } if (!path$o.extname(url) && !url.endsWith('/')) { return true; } return false; }; const knownTsRE = /\.(?:ts|mts|cts|tsx)$/; const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/; const isTsRequest = (url) => knownTsRE.test(url); const isPossibleTsOutput = (url) => knownTsOutputRE.test(cleanUrl(url)); function getPotentialTsSrcPaths(filePath) { const [name, type, query = ''] = filePath.split(/(\.(?:[cm]?js|jsx))(\?.*)?$/); const paths = [name + type.replace('js', 'ts') + query]; if (!type.endsWith('x')) { paths.push(name + type.replace('js', 'tsx') + query); } return paths; } 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, ''); } function injectQuery(url, queryToInject) { // encode percents for consistent behavior with pathToFileURL // see #2614 for details const resolvedUrl = new URL$3(url.replace(/%/g, '%25'), 'relative:///'); const { search, hash } = resolvedUrl; let pathname = cleanUrl(url); pathname = isWindows$4 ? slash$1(pathname) : pathname; return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash ?? ''}`; } 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 picocolorsExports.green(timeString); } else if (time < 50) { return picocolorsExports.yellow(timeString); } else { return picocolorsExports.red(timeString); } } /** * pretty url for logging. */ function prettifyUrl(url, root) { url = removeTimestampQuery(url); const isAbsoluteFile = url.startsWith(root); if (isAbsoluteFile || url.startsWith(FS_PREFIX)) { let file = path$o.relative(root, isAbsoluteFile ? url : fsPathFromId(url)); const seg = file.split('/'); const npmIndex = seg.indexOf(`node_modules`); const isSourceMap = file.endsWith('.map'); if (npmIndex > 0) { file = seg[npmIndex + 1]; if (file.startsWith('@')) { file = `${file}/${seg[npmIndex + 2]}`; } file = `npm: ${picocolorsExports.dim(file)}${isSourceMap ? ` (source map)` : ``}`; } return picocolorsExports.dim(file); } else { return picocolorsExports.dim(url); } } function isObject$2(value) { return Object.prototype.toString.call(value) === '[object Object]'; } function isDefined(value) { return value != null; } function lookupFile(dir, formats, options) { for (const format of formats) { const fullPath = path$o.join(dir, format); if (fs$l.existsSync(fullPath) && fs$l.statSync(fullPath).isFile()) { const result = options?.pathOnly ? fullPath : fs$l.readFileSync(fullPath, 'utf-8'); if (!options?.predicate || options.predicate(result)) { return result; } } } const parentDir = path$o.dirname(dir); if (parentDir !== dir && (!options?.rootDir || parentDir.startsWith(options?.rootDir))) { return lookupFile(parentDir, formats, options); } } const splitRE = /\r?\n/; const range = 2; function pad$1(source, n = 2) { const lines = source.split(splitRE); return lines.map((l) => ` `.repeat(n) + l).join(`\n`); } 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 = posToNumber(source, start); end = end || start; const lines = source.split(splitRE); let count = 0; const res = []; for (let i = 0; i < lines.length; i++) { count += lines[i].length + 1; 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) { // push underline const pad = Math.max(start - (count - lineLength) + 1, 0); const length = Math.max(1, end > count ? lineLength - pad : end - start); res.push(` | ` + ' '.repeat(pad) + '^'.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; } } return res.join('\n'); } function writeFile(filename, content) { const dir = path$o.dirname(filename); if (!fs$l.existsSync(dir)) { fs$l.mkdirSync(dir, { recursive: true }); } fs$l.writeFileSync(filename, content); } function isFileReadable(filename) { try { fs$l.accessSync(filename, fs$l.constants.R_OK); return true; } catch { return false; } } const splitFirstDirRE = /(.+?)[\\/](.+)/; /** * Delete every file and subdirectory. **The given directory must exist.** * Pass an optional `skip` array to preserve files under the root directory. */ function emptyDir(dir, skip) { const skipInDir = []; let nested = null; if (skip?.length) { for (const file of skip) { if (path$o.dirname(file) !== '.') { const matched = file.match(splitFirstDirRE); if (matched) { nested ?? (nested = 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$l.readdirSync(dir)) { if (skipInDir.includes(file)) { continue; } if (nested?.has(file)) { emptyDir(path$o.resolve(dir, file), nested.get(file)); } else { fs$l.rmSync(path$o.resolve(dir, file), { recursive: true, force: true }); } } } function copyDir(srcDir, destDir) { fs$l.mkdirSync(destDir, { recursive: true }); for (const file of fs$l.readdirSync(srcDir)) { const srcFile = path$o.resolve(srcDir, file); if (srcFile === destDir) { continue; } const destFile = path$o.resolve(destDir, file); const stat = fs$l.statSync(srcFile); if (stat.isDirectory()) { copyDir(srcFile, destFile); } else { fs$l.copyFileSync(srcFile, destFile); } } } const removeDir = isWindows$4 ? promisify$4(gracefulRemoveDir) : function removeDirSync(dir) { // when removing `.vite/deps`, if it doesn't exist, nodejs may also remove // other directories within `.vite/`, including `.vite/deps_temp` (bug). // workaround by checking for directory existence before removing for now. if (fs$l.existsSync(dir)) { fs$l.rmSync(dir, { recursive: true, force: true }); } }; const renameDir = isWindows$4 ? promisify$4(gracefulRename) : fs$l.renameSync; function ensureWatchedFile(watcher, file, root) { if (file && // only need to watch if out of root !file.startsWith(root + '/') && // some rollup plugins use null bytes for private resolved Ids !file.includes('\0') && fs$l.existsSync(file)) { // resolve file to normalized system path watcher.add(path$o.resolve(file)); } } const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g; const imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/; function reduceSrcset(ret) { return ret.reduce((prev, { url, descriptor }, index) => { descriptor ?? (descriptor = ''); return (prev += url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`); }, ''); } function splitSrcSetDescriptor(srcs) { return splitSrcSet(srcs) .map((s) => { const src = s.replace(escapedSpaceCharacters, ' ').trim(); const [url] = imageSetUrlRE.exec(src) || ['']; return { url, descriptor: src?.slice(url.length).trim(), }; }) .filter(({ url }) => !!url); } function processSrcSet(srcs, replacer) { return Promise.all(splitSrcSetDescriptor(srcs).map(async ({ url, descriptor }) => ({ url: await replacer({ url, descriptor }), descriptor, }))).then((ret) => reduceSrcset(ret)); } function processSrcSetSync(srcs, replacer) { return reduceSrcset(splitSrcSetDescriptor(srcs).map(({ url, descriptor }) => ({ url: replacer({ url, descriptor }), descriptor, }))); } function splitSrcSet(srcs) { const parts = []; // There could be a ',' inside of url(data:...), linear-gradient(...) or "data:..." const cleanedSrcs = srcs.replace(/(?:url|image|gradient|cross-fade)\([^)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'/g, blankReplacer); let startIndex = 0; let splitIndex; do { splitIndex = cleanedSrcs.indexOf(',', startIndex); parts.push(srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : undefined)); startIndex = splitIndex + 1; } while (splitIndex !== -1); return parts; } function escapeToLinuxLikePath(path) { if (/^[A-Z]:/.test(path)) { return path.replace(/^([A-Z]):\//, '/windows/$1/'); } if (/^\/[^/]/.test(path)) { return `/linux${path}`; } return path; } function unescapeToLinuxLikePath(path) { if (path.startsWith('/linux/')) { return path.slice('/linux'.length); } if (path.startsWith('/windows/')) { return path.replace(/^\/windows\/([A-Z])\//, '$1:/'); } return path; } // based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221 const nullSourceMap = { names: [], sources: [], mappings: '', version: 3, }; function combineSourcemaps(filename, sourcemapList, excludeContent = true) { if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) { return { ...nullSourceMap }; } // hack for parse broken with normalized absolute paths on windows (C:/path/to/something). // escape them to linux like paths // also avoid mutation here to prevent breaking plugin's using cache to generate sourcemaps like vue (see #7442) 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; }); const escapedFilename = escapeToLinuxLikePath(filename); // We don't declare type here so we can convert/fake/map as RawSourceMap let map; //: SourceMap let mapIndex = 1; const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined; if (useArrayInterface) { map = remapping(sourcemapList, () => null, excludeContent); } else { map = remapping(sourcemapList[0], function loader(sourcefile) { if (sourcefile === escapedFilename && sourcemapList[mapIndex]) { return sourcemapList[mapIndex++]; } else { return null; } }, excludeContent); } if (!map.file) { delete map.file; } // unescape the previous hack map.sources = map.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source); map.file = filename; return map; } function unique(arr) { return Array.from(new Set(arr)); } /** * Returns resolved localhost address when `dns.lookup` result differs from DNS * * `dns.lookup` result is same when defaultResultOrder is `verbatim`. * Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same. * For example, when IPv6 is not supported on that machine/network. */ 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 ? undefined : 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 === undefined || optionsHost === false) { // Use a secure default host = 'localhost'; } else if (optionsHost === true) { // If passed --host in the CLI without arguments host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs) } else { host = optionsHost; } // Set host name to localhost when possible let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host; if (host === 'localhost') { // See #8647 for more details. 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 && loopbackHosts.has(hostname.host)) { let hostnameName = hostname.name; // ipv6 host if (hostnameName.includes(':')) { hostnameName = `[${hostnameName}]`; } local.push(`${protocol}://${hostnameName}:${port}${base}`); } 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); // ipv6 host 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]; } // Taken from https://stackoverflow.com/a/36328890 const multilineCommentsRE$1 = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g; const singlelineCommentsRE$1 = /\/\/.*/g; const requestQuerySplitRE = /\?(?!.*[/|}])/; // @ts-expect-error jest only exists when running Jest const usingDynamicImport = typeof jest === 'undefined'; /** * Dynamically import files. It will make sure it's not being compiled away by TS/Rollup. * * As a temporary workaround for Jest's lack of stable ESM support, we fallback to require * if we're in a Jest environment. * See https://github.com/vitejs/vite/pull/5197#issuecomment-938054077 * * @param file File path to import. */ const dynamicImport = usingDynamicImport ? new Function('file', 'return import(file)') : _require$3; function parseRequest(id) { const [_, search] = id.split(requestQuerySplitRE, 2); if (!search) { return null; } return Object.fromEntries(new URLSearchParams(search)); } const blankReplacer = (match) => ' '.repeat(match.length); function getHash(text) { return createHash$2('sha256').update(text).digest('hex').substring(0, 8); } const requireResolveFromRootWithFallback = (root, id) => { const paths = _require$3.resolve.paths?.(id) || []; // Search in the root directory first, and fallback to the default require paths. paths.unshift(root); // Use `resolve` package to check existence first, so if the package is not found, // it won't be cached by nodejs, since there isn't a way to invalidate them: // https://github.com/nodejs/node/issues/44663 resolve$4.sync(id, { basedir: root, paths }); // Use `require.resolve` again as the `resolve` package doesn't support the `exports` field return _require$3.resolve(id, { paths }); }; // Based on node-graceful-fs // The ISC License // Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors // https://github.com/isaacs/node-graceful-fs/blob/main/LICENSE // On Windows, A/V software can lock the directory, causing this // to fail with an EACCES or EPERM if the directory contains newly // created files. The original tried for up to 60 seconds, we only // wait for 5 seconds, as a longer time would be seen as an error const GRACEFUL_RENAME_TIMEOUT = 5000; function gracefulRename(from, to, cb) { const start = Date.now(); let backoff = 0; fs$l.rename(from, to, function CB(er) { if (er && (er.code === 'EACCES' || er.code === 'EPERM') && Date.now() - start < GRACEFUL_RENAME_TIMEOUT) { setTimeout(function () { fs$l.stat(to, function (stater, st) { if (stater && stater.code === 'ENOENT') fs$l.rename(from, to, CB); else CB(er); }); }, backoff); if (backoff < 100) backoff += 10; return; } if (cb) cb(er); }); } const GRACEFUL_REMOVE_DIR_TIMEOUT = 5000; function gracefulRemoveDir(dir, cb) { const start = Date.now(); let backoff = 0; fs$l.rm(dir, { recursive: true }, function CB(er) { if (er) { if ((er.code === 'ENOTEMPTY' || er.code === 'EACCES' || er.code === 'EPERM') && Date.now() - start < GRACEFUL_REMOVE_DIR_TIMEOUT) { setTimeout(function () { fs$l.rm(dir, { recursive: true }, CB); }, backoff); if (backoff < 100) backoff += 10; return; } if (er.code === 'ENOENT') { er = null; } } if (cb) cb(er); }); } function emptyCssComments(raw) { return raw.replace(multilineCommentsRE$1, (s) => ' '.repeat(s.length)); } function removeComments(raw) { return raw.replace(multilineCommentsRE$1, '').replace(singlelineCommentsRE$1, ''); } 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; } // fields that require special handling 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' && (existing === true || value === true)) { merged[key] = true; 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) { 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 }; } // the order is flipped because the alias is resolved from top-down, // where the later should have higher priority 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], })); } // https://github.com/vitejs/vite/issues/1363 // work around https://github.com/rollup/plugins/issues/759 function normalizeSingleAlias({ find, replacement, customResolver, }) { if (typeof find === 'string' && find.endsWith('/') && replacement.endsWith('/')) { 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; } /** * Transforms transpiled code result where line numbers aren't altered, * so we can skip sourcemap generation during dev */ function transformStableResult(s, id, config) { return { code: s.toString(), map: config.command === 'build' && config.build.sourcemap ? s.generateMap({ hires: true, source: id }) : null, }; } async function asyncFlatten(arr) { do { arr = (await Promise.all(arr)).flat(Infinity); } while (arr.some((v) => v?.then)); return arr; } // strip UTF-8 BOM function stripBomTag(content) { if (content.charCodeAt(0) === 0xfeff) { return content.slice(1); } return content; } const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/; /** * path.isAbsolute also returns true for drive relative paths on windows (e.g. /something) * this function returns false for them but true for absolute paths (e.g. C:/something) */ const isNonDriveRelativeAbsolutePath = (p) => { if (!isWindows$4) return p.startsWith('/'); return windowsDrivePathPrefixRE.test(p); }; /** * Determine if a file is being requested with the correct case, to ensure * consistent behaviour between dev and prod and across operating systems. */ function shouldServeFile(filePath, root) { // can skip case check on Linux if (!isCaseInsensitiveFS) return true; return hasCorrectCase(filePath, root); } /** * Note that we can't use realpath here, because we don't want to follow * symlinks. */ function hasCorrectCase(file, assets) { if (file === assets) return true; const parent = path$o.dirname(file); if (fs$l.readdirSync(parent).includes(path$o.basename(file))) { return hasCorrectCase(parent, assets); } return false; } function joinUrlSegments(a, b) { if (!a || !b) { return a || b || ''; } if (a.endsWith('/')) { a = a.substring(0, a.length - 1); } if (!b.startsWith('/')) { b = '/' + b; } return a + b; } function stripBase(path, base) { if (path === base) { return '/'; } const devBase = base.endsWith('/') ? base : base + '/'; return path.replace(RegExp('^' + devBase), '/'); } 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 (\n${rawValue}\n) `); return fn(); } /* eslint no-console: 0 */ 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); } function createLogger(level = 'info', options = {}) { if (options.customLogger) { return options.customLogger; } const loggedErrors = new WeakSet(); const { prefix = '[vite]', allowClearScreen = true } = options; const thresh = LogLevels[level]; const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI; const clear = canClearScreen ? clearScreen : () => { }; function output(type, msg, options = {}) { if (thresh >= LogLevels[type]) { const method = type === 'info' ? 'log' : type; const format = () => { if (options.timestamp) { const tag = type === 'info' ? picocolorsExports.cyan(picocolorsExports.bold(prefix)) : type === 'warn' ? picocolorsExports.yellow(picocolorsExports.bold(prefix)) : picocolorsExports.red(picocolorsExports.bold(prefix)); return `${picocolorsExports.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`; } else { return msg; } }; if (options.error) { loggedErrors.add(options.error); } if (canClearScreen) { if (type === lastType && msg === lastMsg) { sameCount++; clear(); console[method](format(), picocolorsExports.yellow(`(x${sameCount + 1})`)); } else { sameCount = 0; lastMsg = msg; lastType = type; if (options.clear) { clear(); } console[method](format()); } } else { console[method](format()); } } } const warnedMessages = 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) => picocolorsExports.cyan(url.replace(/:(\d+)\//, (_, port) => `:${picocolorsExports.bold(port)}/`)); for (const url of urls.local) { info(` ${picocolorsExports.green('➜')} ${picocolorsExports.bold('Local')}: ${colorUrl(url)}`); } for (const url of urls.network) { info(` ${picocolorsExports.green('➜')} ${picocolorsExports.bold('Network')}: ${colorUrl(url)}`); } if (urls.network.length === 0 && optionsHost === undefined) { info(picocolorsExports.dim(` ${picocolorsExports.green('➜')} ${picocolorsExports.bold('Network')}: use `) + picocolorsExports.bold('--host') + picocolorsExports.dim(' to expose')); } } const groups = [ { name: 'Assets', color: picocolorsExports.green }, { name: 'CSS', color: picocolorsExports.magenta }, { name: 'JS', color: picocolorsExports.cyan }, ]; function buildReporterPlugin(config) { const compress = promisify$4(gzip); const chunkLimit = config.build.chunkSizeWarningLimit; const tty = process.stdout.isTTY && !process.env.CI; const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info; let hasTransformed = false; let hasRenderedChunk = false; let hasCompressChunk = false; let transformedCount = 0; let chunkCount = 0; let compressedCount = 0; let startTime = Date.now(); async function getCompressedSize(code) { if (config.build.ssr || !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; } const logTransform = throttle((id) => { writeLine(`transforming (${transformedCount}) ${picocolorsExports.dim(path$o.relative(config.root, id))}`); }); return { name: 'vite:reporter', transform(_, id) { transformedCount++; if (shouldLogInfo) { if (!tty) { if (!hasTransformed) { config.logger.info(`transforming...`); } } else { if (id.includes(`?`)) return; logTransform(id); } hasTransformed = true; } return null; }, options() { startTime = Date.now(); }, buildEnd() { if (shouldLogInfo) { if (tty) { process.stdout.clearLine(0); process.stdout.cursorTo(0); } config.logger.info(`${picocolorsExports.green(`✓`)} ${transformedCount} modules transformed.`); } }, renderStart() { chunkCount = 0; compressedCount = 0; }, renderChunk() { chunkCount++; if (shouldLogInfo) { if (!tty) { if (!hasRenderedChunk) { config.logger.info('rendering chunks...'); } } else { writeLine(`rendering chunks (${chunkCount})...`); } hasRenderedChunk = true; } return null; }, generateBundle() { if (shouldLogInfo && tty) clearLine(); }, async writeBundle({ dir: outDir }, output) { 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'); return { name: chunk.fileName, group: isCSS ? 'CSS' : 'Assets', size: chunk.source.length, mapSize: null, compressedSize: isCSS ? await getCompressedSize(chunk.source) : null, }; } }))).filter(isDefined); if (tty) clearLine(); 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$o.relative(config.root, path$o.resolve(config.root, outDir ?? config.build.outDir))); const assetsDir = path$o.join(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 / 1000 > chunkLimit; if (isLarge) hasLargeChunks = true; const sizeColor = isLarge ? picocolorsExports.yellow : picocolorsExports.dim; let log = picocolorsExports.dim(relativeOutDir + '/'); log += !config.build.lib && entry.name.startsWith(assetsDir) ? picocolorsExports.dim(assetsDir) + group.color(entry.name .slice(assetsDir.length) .padEnd(longest + 2 - assetsDir.length)) : group.color(entry.name.padEnd(longest + 2)); log += picocolorsExports.bold(sizeColor(displaySize(entry.size).padStart(sizePad))); if (entry.compressedSize) { log += picocolorsExports.dim(` │ gzip: ${displaySize(entry.compressedSize).padStart(compressPad)}`); } if (entry.mapSize) { log += picocolorsExports.dim(` │ map: ${displaySize(entry.mapSize).padStart(mapPad)}`); } config.logger.info(log); } } } else { hasLargeChunks = Object.values(output).some((chunk) => { return chunk.type === 'chunk' && chunk.code.length / 1000 > chunkLimit; }); } if (hasLargeChunks && config.build.minify && !config.build.lib && !config.build.ssr) { config.logger.warn(picocolorsExports.yellow(`\n(!) Some chunks are larger than ${chunkLimit} kBs after minification. Consider:\n` + `- Using dynamic import() to code-split the application\n` + `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n` + `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`)); } }, closeBundle() { if (shouldLogInfo && !config.build.watch) { config.logger.info(`${picocolorsExports.green(`✓`)} built in ${displayTime(Date.now() - startTime)}`); } }, }; } function writeLine(output) { clearLine(); if (output.length < process.stdout.columns) { process.stdout.write(output); } else { process.stdout.write(output.substring(0, process.stdout.columns - 1)); } } function clearLine() { 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); }; } function displaySize(bytes) { return `${(bytes / 1000).toLocaleString('en', { maximumFractionDigits: 2, minimumFractionDigits: 2, })} kB`; } function displayTime(time) { // display: {X}ms if (time < 1000) { return `${time}ms`; } time = time / 1000; // display: {X}s if (time < 60) { return `${time.toFixed(2)}s`; } const mins = parseInt((time / 60).toString()); const seconds = time % 60; // display: {X}m {Y}s return `${mins}m${seconds < 1 ? '' : ` ${seconds.toFixed(0)}s`}`; } // src/find.ts async function find(filename, options) { let dir = require$$0$4.dirname(require$$0$4.resolve(filename)); const root = (options == null ? void 0 : options.root) ? require$$0$4.resolve(options.root) : null; while (dir) { const tsconfig = await tsconfigInDir(dir, options); if (tsconfig) { return tsconfig; } else { if (root === dir) { break; } const parent = require$$0$4.dirname(dir); if (parent === dir) { break; } else { dir = parent; } } } throw new Error(`no tsconfig file found for ${filename}`); } async function tsconfigInDir(dir, options) { const tsconfig = require$$0$4.join(dir, "tsconfig.json"); if (options == null ? void 0 : options.tsConfigPaths) { return options.tsConfigPaths.has(tsconfig) ? tsconfig : void 0; } try { const stat = await promises$1.stat(tsconfig); if (stat.isFile() || stat.isFIFO()) { return tsconfig; } } catch (e) { if (e.code !== "ENOENT") { throw e; } } } async function findAll(dir, options) { const files = []; for await (const tsconfigFile of findTSConfig(require$$0$4.resolve(dir), options)) { files.push(tsconfigFile); } return files; } async function* findTSConfig(dir, options, visited = /* @__PURE__ */ new Set()) { if (!visited.has(dir)) { visited.add(dir); try { const dirents = await promises$1.readdir(dir, { withFileTypes: true }); for (const dirent of dirents) { if (dirent.isDirectory() && (!(options == null ? void 0 : options.skip) || !options.skip(dirent.name))) { yield* findTSConfig(require$$0$4.resolve(dir, dirent.name), options, visited); } else if (dirent.isFile() && dirent.name === "tsconfig.json") { yield require$$0$4.resolve(dir, dirent.name); } } } catch (e) { if (e.code === "EACCES" || e.code === "ENOENT") { return; } throw e; } } } // src/to-json.ts function toJson(tsconfigJson) { const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson))); if (stripped.trim() === "") { return "{}"; } else { return stripped; } } 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); } function isEscaped(jsonString, quotePosition) { let index = quotePosition - 1; let backslashCount = 0; while (jsonString[index] === "\\") { index -= 1; backslashCount += 1; } return Boolean(backslashCount % 2); } function strip(string, start, end) { return string.slice(start, end).replace(/\S/g, " "); } var singleComment = Symbol("singleComment"); var multiComment = Symbol("multiComment"); function stripJsonComments(jsonString) { let isInsideString = false; 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)); } function stripBom(string) { if (string.charCodeAt(0) === 65279) { return string.slice(1); } return string; } var POSIX_SEP_RE = new RegExp("\\" + require$$0$4.posix.sep, "g"); var NATIVE_SEP_RE = new RegExp("\\" + require$$0$4.sep, "g"); var PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map(); var GLOB_ALL_PATTERN = `**/*`; var DEFAULT_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"]; var DEFAULT_EXTENSIONS_RE_GROUP = `\\.(?:${DEFAULT_EXTENSIONS.map((ext) => ext.substring(1)).join( "|" )})`; new Function("path", "return import(path).then(m => m.default)"); async function resolveTSConfig(filename) { if (require$$0$4.extname(filename) !== ".json") { return; } const tsconfig = require$$0$4.resolve(filename); try { const stat = await promises$1.stat(tsconfig); if (stat.isFile() || stat.isFIFO()) { return tsconfig; } } catch (e) { if (e.code !== "ENOENT") { throw e; } } throw new Error(`no tsconfig file found for ${filename}`); } function posix2native(filename) { return require$$0$4.posix.sep !== require$$0$4.sep && filename.includes(require$$0$4.posix.sep) ? filename.replace(POSIX_SEP_RE, require$$0$4.sep) : filename; } function native2posix(filename) { return require$$0$4.posix.sep !== require$$0$4.sep && filename.includes(require$$0$4.sep) ? filename.replace(NATIVE_SEP_RE, require$$0$4.posix.sep) : filename; } function resolve2posix(dir, filename) { if (require$$0$4.sep === require$$0$4.posix.sep) { return dir ? require$$0$4.resolve(dir, filename) : require$$0$4.resolve(filename); } return native2posix( dir ? require$$0$4.resolve(posix2native(dir), posix2native(filename)) : require$$0$4.resolve(posix2native(filename)) ); } function resolveReferencedTSConfigFiles(result) { const dir = require$$0$4.dirname(result.tsconfigFile); return result.tsconfig.references.map((ref) => { const refPath = ref.path.endsWith(".json") ? ref.path : require$$0$4.join(ref.path, "tsconfig.json"); return resolve2posix(dir, refPath); }); } function resolveSolutionTSConfig(filename, result) { if (result.referenced && DEFAULT_EXTENSIONS.some((ext) => filename.endsWith(ext)) && !isIncluded(filename, result)) { const solutionTSConfig = result.referenced.find( (referenced) => isIncluded(filename, referenced) ); if (solutionTSConfig) { return { ...solutionTSConfig, solution: result }; } } return result; } function isIncluded(filename, result) { const dir = native2posix(require$$0$4.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 isIncluded2 = isGlobMatch( absoluteFilename, dir, result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN]) ); if (isIncluded2) { const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || []); return !isExcluded; } return false; } function isGlobMatch(filename, dir, patterns) { return patterns.some((pattern) => { let lastWildcardIndex = pattern.length; let hasWildcard = false; for (let i = pattern.length - 1; i > -1; i--) { if (pattern[i] === "*" || pattern[i] === "?") { lastWildcardIndex = i; hasWildcard = true; break; } } if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) { return false; } if (pattern.endsWith("*") && !DEFAULT_EXTENSIONS.some((ext) => filename.endsWith(ext))) { return false; } if (pattern === GLOB_ALL_PATTERN) { return filename.startsWith(`${dir}/`); } const resolvedPattern = resolve2posix(dir, pattern); 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) { return filename === resolvedPattern; } if (PATTERN_REGEX_CACHE.has(resolvedPattern)) { return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename); } const regex = pattern2regex(resolvedPattern); PATTERN_REGEX_CACHE.set(resolvedPattern, regex); return regex.test(filename); }); } function pattern2regex(resolvedPattern) { 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 += "(?:[^\\/]*\\/)*"; continue; } regexStr += "[^\\/]*"; continue; } if ("/.+^${}()|[]\\".includes(char)) { regexStr += `\\`; } regexStr += char; } if (resolvedPattern.endsWith("*")) { regexStr += DEFAULT_EXTENSIONS_RE_GROUP; } regexStr += "$"; return new RegExp(regexStr); } // src/parse.ts async function parse$f(filename, options) { const cache = options == null ? void 0 : options.cache; if (cache == null ? void 0 : cache.has(filename)) { return cache.get(filename); } let tsconfigFile; if (options == null ? void 0 : options.resolveWithEmptyIfConfigNotFound) { try { tsconfigFile = await resolveTSConfig(filename) || await find(filename, options); } catch (e) { const notFoundResult = { tsconfigFile: "no_tsconfig_file_found", tsconfig: {} }; cache == null ? void 0 : cache.set(filename, notFoundResult); return notFoundResult; } } else { tsconfigFile = await resolveTSConfig(filename) || await find(filename, options); } let result; if (cache == null ? void 0 : cache.has(tsconfigFile)) { result = cache.get(tsconfigFile); } else { result = await parseFile$1(tsconfigFile, cache); await Promise.all([parseExtends(result, cache), parseReferences(result, cache)]); cache == null ? void 0 : cache.set(tsconfigFile, result); } result = resolveSolutionTSConfig(filename, result); cache == null ? void 0 : cache.set(filename, result); return result; } async function parseFile$1(tsconfigFile, cache) { if (cache == null ? void 0 : cache.has(tsconfigFile)) { return cache.get(tsconfigFile); } try { const tsconfigJson = await promises$1.readFile(tsconfigFile, "utf-8"); const json = toJson(tsconfigJson); const result = { tsconfigFile, tsconfig: normalizeTSConfig(JSON.parse(json), require$$0$4.dirname(tsconfigFile)) }; cache == null ? void 0 : cache.set(tsconfigFile, result); return result; } catch (e) { throw new TSConfckParseError( `parsing ${tsconfigFile} failed: ${e}`, "PARSE_FILE", tsconfigFile, e ); } } function normalizeTSConfig(tsconfig, dir) { var _a; if (((_a = tsconfig.compilerOptions) == null ? void 0 : _a.baseUrl) && !require$$0$4.isAbsolute(tsconfig.compilerOptions.baseUrl)) { tsconfig.compilerOptions.baseUrl = resolve2posix(dir, tsconfig.compilerOptions.baseUrl); } return tsconfig; } async function parseReferences(result, cache) { if (!result.tsconfig.references) { return; } const referencedFiles = resolveReferencedTSConfigFiles(result); const referenced = await Promise.all(referencedFiles.map((file) => parseFile$1(file, cache))); await Promise.all(referenced.map((ref) => parseExtends(ref, cache))); result.referenced = referenced; } async function parseExtends(result, cache) { if (!result.tsconfig.extends) { return; } const extended = [ { tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) } ]; let pos = 0; const extendsPath = []; let currentBranchDepth = 0; while (pos < extended.length) { const extending = extended[pos]; extendsPath.push(extending.tsconfigFile); if (extending.tsconfig.extends) { currentBranchDepth += 1; let resolvedExtends; if (!Array.isArray(extending.tsconfig.extends)) { resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)]; } else { 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 ); } extended.splice( pos + 1, 0, ...await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache))) ); } else { extendsPath.splice(-currentBranchDepth); currentBranchDepth = 0; } pos = pos + 1; } result.extended = extended; for (const ext of result.extended.slice(1)) { extendTSConfig(result, ext); } } function resolveExtends(extended, from) { let error; try { return createRequire$2(from).resolve(extended); } catch (e) { error = e; } if (!require$$0$4.isAbsolute(extended) && !extended.startsWith("./") && !extended.startsWith("../")) { try { const fallbackExtended = require$$0$4.join(extended, "tsconfig.json"); return createRequire$2(from).resolve(fallbackExtended); } catch (e) { error = e; } } throw new TSConfckParseError( `failed to resolve "extends":"${extended}" in ${from}`, "EXTENDS_RESOLVE", from, error ); } var EXTENDABLE_KEYS = [ "compilerOptions", "files", "include", "exclude", "watchOptions", "compileOnSave", "typeAcquisition", "buildOptions" ]; function extendTSConfig(extending, extended) { const extendingConfig = extending.tsconfig; const extendedConfig = extended.tsconfig; const relativePath = native2posix( require$$0$4.relative(require$$0$4.dirname(extending.tsconfigFile), require$$0$4.dirname(extended.tsconfigFile)) ); for (const key of Object.keys(extendedConfig).filter((key2) => EXTENDABLE_KEYS.includes(key2))) { 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; } extendingConfig.compilerOptions[option] = rebaseRelative( option, extendedConfig.compilerOptions[option], relativePath ); } } else if (extendingConfig[key] === void 0) { 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); } } } } var REBASE_KEYS = [ // root "files", "include", "exclude", // compilerOptions "baseUrl", "rootDir", "rootDirs", "typeRoots", "outDir", "outFile", "declarationDir", // watchOptions "excludeDirectories", "excludeFiles" ]; 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); } } function rebasePath(value, prependPath) { if (require$$0$4.isAbsolute(value)) { return value; } else { return require$$0$4.posix.normalize(require$$0$4.posix.join(prependPath, value)); } } var TSConfckParseError = class extends Error { constructor(message, code, tsconfigFile, cause) { super(message); Object.setPrototypeOf(this, TSConfckParseError.prototype); this.name = TSConfckParseError.name; this.code = code; this.cause = cause; this.tsconfigFile = tsconfigFile; } }; const debug$f = createDebugger('vite:esbuild'); const INJECT_HELPERS_IIFE_RE = /^(.*?)((?:const|var)\s+\S+\s*=\s*function\s*\([^)]*\)\s*\{.*?"use strict";)/s; const INJECT_HELPERS_UMD_RE = /^(.*?)(\(function\([^)]*\)\s*\{.+?amd.+?function\([^)]*\)\s*\{.*?"use strict";)/s; let server; async function transformWithEsbuild(code, filename, options, inMap) { let loader = options?.loader; if (!loader) { // if the id ends with a valid ext, use it (e.g. vue blocks) // otherwise, cleanup the query before checking the ext const ext = path$o .extname(/\.\w+$/.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 options provide tsconfigRaw in string, it takes highest precedence if (typeof tsconfigRaw !== 'string') { // these fields would affect the compilation result // https://esbuild.github.io/content-types/#tsconfig-json const meaningfulFields = [ 'alwaysStrict', 'importsNotUsedAsValues', 'jsx', 'jsxFactory', 'jsxFragmentFactory', 'jsxImportSource', 'preserveValueImports', 'target', 'useDefineForClassFields', ]; const compilerOptionsForFile = {}; if (loader === 'ts' || loader === 'tsx') { const loadedTsconfig = await loadTsconfigJsonForFile(filename); const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {}; for (const field of meaningfulFields) { if (field in loadedCompilerOptions) { // @ts-expect-error TypeScript can't tell they are of the same type compilerOptionsForFile[field] = loadedCompilerOptions[field]; } } } tsconfigRaw = { ...tsconfigRaw, compilerOptions: { ...compilerOptionsForFile, ...tsconfigRaw?.compilerOptions, }, }; const { compilerOptions } = tsconfigRaw; if (compilerOptions) { // esbuild derives `useDefineForClassFields` from `target` instead of `tsconfig.compilerOptions.target` // https://github.com/evanw/esbuild/issues/2584 // but we want `useDefineForClassFields` to be derived from `tsconfig.compilerOptions.target` if (compilerOptions.useDefineForClassFields === undefined) { const lowercaseTarget = compilerOptions.target?.toLowerCase() ?? 'es3'; if (lowercaseTarget.startsWith('es')) { const esVersion = lowercaseTarget.slice(2); compilerOptions.useDefineForClassFields = esVersion === 'next' || +esVersion >= 2022; } else { compilerOptions.useDefineForClassFields = false; } } } } const resolvedOptions = { sourcemap: true, // ensure source file name contains full query sourcefile: filename, ...options, loader, tsconfigRaw, }; // esbuild uses tsconfig fields when both the normal options and tsconfig was set // but we want to prioritize the normal options if (options && typeof resolvedOptions.tsconfigRaw === 'object' && resolvedOptions.tsconfigRaw.compilerOptions) { options.jsx && (resolvedOptions.tsconfigRaw.compilerOptions.jsx = undefined); options.jsxFactory && (resolvedOptions.tsconfigRaw.compilerOptions.jsxFactory = undefined); options.jsxFragment && (resolvedOptions.tsconfigRaw.compilerOptions.jsxFragmentFactory = undefined); options.jsxImportSource && (resolvedOptions.tsconfigRaw.compilerOptions.jsxImportSource = undefined); options.target && (resolvedOptions.tsconfigRaw.compilerOptions.target = undefined); } delete resolvedOptions.include; delete resolvedOptions.exclude; delete resolvedOptions.jsxInject; try { const result = await transform$2(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$f(`esbuild error with options used: `, resolvedOptions); // patch error information if (e.errors) { e.frame = ''; e.errors.forEach((m) => { e.frame += `\n` + prettifyMessage(m, code); }); e.loc = e.errors[0].location; } throw e; } } function esbuildPlugin(options) { const filter = createFilter(options.include || /\.(m?ts|[jt]sx)$/, options.exclude || /\.js$/); // Remove optimization options for dev as we only need to transpile them, // and for build as the final optimization is in `buildEsbuildPlugin` const transformOptions = { target: 'esnext', charset: 'utf8', ...options, 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, }; return { name: 'vite:esbuild', configureServer(_server) { server = _server; server.watcher .on('add', reloadOnTsconfigChange) .on('change', reloadOnTsconfigChange) .on('unlink', reloadOnTsconfigChange); }, async configResolved(config) { await initTSConfck(config); }, buildEnd() { // recycle serve to avoid preventing Node self-exit (#6815) server = null; }, async transform(code, id) { if (filter(id) || filter(cleanUrl(id))) { const result = await transformWithEsbuild(code, id, transformOptions); if (result.warnings.length) { result.warnings.forEach((m) => { this.warn(prettifyMessage(m, code)); }); } if (options.jsxInject && /\.(?:j|t)sx\b/.test(id)) { result.code = options.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: undefined, }; const buildEsbuildPlugin = (config) => { return { name: 'vite:esbuild-transpile', async configResolved(config) { await initTSConfck(config); }, async renderChunk(code, chunk, opts) { // @ts-expect-error injected by @vitejs/plugin-legacy 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); if (config.build.lib) { // #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the // names are minified potentially causing collision with other globals. // We use a regex to inject the helpers inside the wrappers. // We don't need to create a MagicString here because both the helpers and // the headers don't modify the sourcemap const injectHelpers = opts.format === 'umd' ? INJECT_HELPERS_UMD_RE : opts.format === 'iife' ? INJECT_HELPERS_IIFE_RE : undefined; if (injectHelpers) { res.code = res.code.replace(injectHelpers, (_, helpers, header) => header + helpers); } } return res; }, }; }; function resolveEsbuildTranspileOptions(config, format) { const target = config.build.target; const minify = config.build.minify === 'esbuild'; if ((!target || target === 'esnext') && !minify) { return null; } // Do not minify whitespace for ES lib output since that would remove // pure annotations and break tree-shaking // https://github.com/vuejs/core/issues/2860#issuecomment-926882793 const isEsLibBuild = config.build.lib && format === 'es'; const esbuildOptions = config.esbuild || {}; const options = { charset: 'utf8', ...esbuildOptions, target: target || undefined, format: rollupToEsbuildFormatMap[format], // the final build should always support dynamic import and import.meta. // if they need to be polyfilled, plugin-legacy should be used. // plugin-legacy detects these two features when checking for modern code. supported: { 'dynamic-import': true, 'import-meta': true, ...esbuildOptions.supported, }, }; // If no minify, disable all minify options if (!minify) { return { ...options, minify: false, minifyIdentifiers: false, minifySyntax: false, minifyWhitespace: false, treeShaking: false, }; } // If user enable fine-grain minify options, minify with their options instead if (options.minifyIdentifiers != null || options.minifySyntax != null || options.minifyWhitespace != null) { if (isEsLibBuild) { // Disable minify whitespace as it breaks tree-shaking 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, }; } } // Else apply default minify options if (isEsLibBuild) { // Minify all except whitespace as it breaks tree-shaking 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 = picocolorsExports.yellow(m.text); if (m.location) { const lines = code.split(/\r?\n/g); const line = Number(m.location.line); const column = Number(m.location.column); const offset = lines .slice(0, line - 1) .map((l) => l.length) .reduce((total, l) => total + l + 1, 0) + column; res += `\n` + generateCodeFrame(code, offset, offset + 1); } return res + `\n`; } const tsconfckParseOptions = { cache: new Map(), tsConfigPaths: undefined, root: undefined, resolveWithEmptyIfConfigNotFound: true, }; async function initTSConfck(config) { const workspaceRoot = searchForWorkspaceRoot(config.root); debug$f(`init tsconfck (root: ${picocolorsExports.cyan(workspaceRoot)})`); tsconfckParseOptions.cache.clear(); tsconfckParseOptions.root = workspaceRoot; tsconfckParseOptions.tsConfigPaths = new Set([ ...(await findAll(workspaceRoot, { skip: (dir) => dir === 'node_modules' || dir === '.git', })), ]); debug$f(`init tsconfck end`); } async function loadTsconfigJsonForFile(filename) { try { const result = await parse$f(filename, tsconfckParseOptions); // tsconfig could be out of root, make sure it is watched on dev if (server && result.tsconfigFile !== 'no_tsconfig_file_found') { ensureWatchedFile(server.watcher, result.tsconfigFile, server.config.root); } return result.tsconfig; } catch (e) { if (e instanceof TSConfckParseError) { // tsconfig could be out of root, make sure it is watched on dev if (server && e.tsconfigFile) { ensureWatchedFile(server.watcher, e.tsconfigFile, server.config.root); } } throw e; } } function reloadOnTsconfigChange(changedFile) { // server could be closed externally after a file change is detected if (!server) return; // any tsconfig.json that's added in the workspace could be closer to a code file than a previously cached one // any json file in the tsconfig cache could have been used to compile ts if (path$o.basename(changedFile) === 'tsconfig.json' || (changedFile.endsWith('.json') && tsconfckParseOptions?.cache?.has(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 }); // clear module graph to remove code compiled with outdated config server.moduleGraph.invalidateAll(); // reset tsconfck so that recompile works with up2date configs initTSConfck(server.config).finally(() => { // server may not be available if vite config is updated at the same time if (server) { // force full reload server.ws.send({ type: 'full-reload', path: '*', }); } }); } } var dist$1 = {}; var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(dist$1, "__esModule", { value: true }); var Worker_1 = dist$1.Worker = void 0; const os_1 = __importDefault(require$$2); const worker_threads_1 = require$$1; class Worker { constructor(fn, options = {}) { this.code = genWorkerCode(fn); this.max = options.max || Math.max(1, os_1.default.cpus().length - 1); 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(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 = []; } async _getAvailableWorker() { // has idle one? if (this.idlePool.length) { return this.idlePool.shift(); } // can spawn more? if (this.pool.length < this.max) { const worker = new worker_threads_1.Worker(this.code, { eval: true }); worker.on('message', (res) => { worker.currentResolve && worker.currentResolve(res); worker.currentResolve = null; this._assignDoneWorker(worker); }); 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(`Wroker stopped with non-0 exit code ${code}`)); worker.currentReject = null; } }); this.pool.push(worker); return worker; } // no one is available, we have to wait let resolve; let reject; const onWorkerAvailablePromise = new Promise((r, rj) => { resolve = r; reject = rj; }); this.queue.push([resolve, reject]); return onWorkerAvailablePromise; } _assignDoneWorker(worker) { // someone's waiting already? if (this.queue.length) { const [resolve] = this.queue.shift(); resolve(worker); return; } // take a rest. this.idlePool.push(worker); } } Worker_1 = dist$1.Worker = Worker; function genWorkerCode(fn) { return ` const doWork = ${fn.toString()} const { parentPort } = require('worker_threads') parentPort.on('message', async (args) => { const res = await doWork(...args) parentPort.postMessage(res) }) `; } 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:\n${e.message}`); message.stack = e.stack + '\n' + message.stack; throw message; } } return terserPath; }; function terserPlugin(config) { const makeWorker = () => new Worker_1(async (terserPath, code, options) => { // test fails when using `import`. maybe related: https://github.com/nodejs/node/issues/43205 // eslint-disable-next-line no-restricted-globals -- this function runs inside cjs const terser = require(terserPath); return terser.minify(code, options); }); let worker; return { name: 'vite:terser', async renderChunk(code, _chunk, outputOptions) { // This plugin is included for any non-false value of config.build.minify, // so that normal chunks can use the preferred minifier, and legacy chunks // can use terser. if (config.build.minify !== 'terser' && // @ts-expect-error injected by @vitejs/plugin-legacy !outputOptions.__vite_force_terser__) { return null; } // Do not minify ES lib output since that would remove pure annotations // and break tree-shaking. if (config.build.lib && outputOptions.format === 'es') { return null; } // Lazy load worker. worker || (worker = makeWorker()); const terserPath = loadTerserPath(config.root); const res = await worker.run(terserPath, code, { safari10: true, ...config.build.terserOptions, sourceMap: !!outputOptions.sourcemap, module: outputOptions.format.startsWith('es'), toplevel: outputOptions.format === 'cjs', }); return { code: res.code, map: res.map, }; }, closeBundle() { worker?.stop(); }, }; } var json = JSON; var isArray$1 = Array.isArray || function (x) { return {}.toString.call(x) === '[object Array]'; }; var objectKeys = Object.keys || function (obj) { var has = Object.prototype.hasOwnProperty || function () { return true; }; var keys = []; for (var key in obj) { if (has.call(obj, key)) { keys.push(key); } } return keys; }; var jsonStableStringify = function (obj, opts) { if (!opts) { opts = {}; } if (typeof opts === 'function') { opts = { cmp: opts }; } var space = opts.space || ''; if (typeof space === 'number') { space = Array(space + 1).join(' '); } var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false; var replacer = opts.replacer || function (key, value) { return value; }; var cmp = opts.cmp && (function (f) { return function (node) { return function (a, b) { var aobj = { key: a, value: node[a] }; var bobj = { key: b, value: node[b] }; return f(aobj, bobj); }; }; }(opts.cmp)); var seen = []; return (function stringify(parent, key, node, level) { var indent = space ? '\n' + new Array(level + 1).join(space) : ''; var colonSeparator = space ? ': ' : ':'; if (node && node.toJSON && typeof node.toJSON === 'function') { node = node.toJSON(); } node = replacer.call(parent, key, node); if (node === undefined) { return; } if (typeof node !== 'object' || node === null) { return json.stringify(node); } if (isArray$1(node)) { var out = []; for (var i = 0; i < node.length; i++) { var item = stringify(node, i, node[i], level + 1) || json.stringify(null); out.push(indent + space + item); } return '[' + out.join(',') + indent + ']'; } if (seen.indexOf(node) !== -1) { if (cycles) { return json.stringify('__cycle__'); } throw new TypeError('Converting circular structure to JSON'); } else { seen.push(node); } var keys = objectKeys(node).sort(cmp && cmp(node)); var out = []; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = stringify(node, key, node[key], level + 1); if (!value) { continue; } var keyValue = json.stringify(key) + colonSeparator + value; out.push(indent + space + keyValue); } seen.splice(seen.indexOf(node), 1); return '{' + out.join(',') + indent + '}'; }({ '': obj }, '', obj, 0)); }; const mimes$1 = { "ez": "application/andrew-inset", "aw": "application/applixware", "atom": "application/atom+xml", "atomcat": "application/atomcat+xml", "atomdeleted": "application/atomdeleted+xml", "atomsvc": "application/atomsvc+xml", "dwd": "application/atsc-dwd+xml", "held": "application/atsc-held+xml", "rsat": "application/atsc-rsat+xml", "bdoc": "application/bdoc", "xcs": "application/calendar+xml", "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", "cu": "application/cu-seeme", "mpd": "application/dash+xml", "davmount": "application/davmount+xml", "dbk": "application/docbook+xml", "dssc": "application/dssc+der", "xdssc": "application/dssc+xml", "es": "application/ecmascript", "ecma": "application/ecmascript", "emma": "application/emma+xml", "emotionml": "application/emotionml+xml", "epub": "application/epub+zip", "exi": "application/exi", "fdt": "application/fdt+xml", "pfr": "application/font-tdpfr", "geojson": "application/geo+json", "gml": "application/gml+xml", "gpx": "application/gpx+xml", "gxf": "application/gxf", "gz": "application/gzip", "hjson": "application/hjson", "stk": "application/hyperstudio", "ink": "application/inkml+xml", "inkml": "application/inkml+xml", "ipfix": "application/ipfix", "its": "application/its+xml", "jar": "application/java-archive", "war": "application/java-archive", "ear": "application/java-archive", "ser": "application/java-serialized-object", "class": "application/java-vm", "js": "application/javascript", "mjs": "application/javascript", "json": "application/json", "map": "application/json", "json5": "application/json5", "jsonml": "application/jsonml+json", "jsonld": "application/ld+json", "lgr": "application/lgr+xml", "lostxml": "application/lost+xml", "hqx": "application/mac-binhex40", "cpt": "application/mac-compactpro", "mads": "application/mads+xml", "webmanifest": "application/manifest+json", "mrc": "application/marc", "mrcx": "application/marcxml+xml", "ma": "application/mathematica", "nb": "application/mathematica", "mb": "application/mathematica", "mathml": "application/mathml+xml", "mbox": "application/mbox", "mscml": "application/mediaservercontrol+xml", "metalink": "application/metalink+xml", "meta4": "application/metalink4+xml", "mets": "application/mets+xml", "maei": "application/mmt-aei+xml", "musd": "application/mmt-usd+xml", "mods": "application/mods+xml", "m21": "application/mp21", "mp21": "application/mp21", "mp4s": "application/mp4", "m4p": "application/mp4", "doc": "application/msword", "dot": "application/msword", "mxf": "application/mxf", "nq": "application/n-quads", "nt": "application/n-triples", "cjs": "application/node", "bin": "application/octet-stream", "dms": "application/octet-stream", "lrf": "application/octet-stream", "mar": "application/octet-stream", "so": "application/octet-stream", "dist": "application/octet-stream", "distz": "application/octet-stream", "pkg": "application/octet-stream", "bpk": "application/octet-stream", "dump": "application/octet-stream", "elc": "application/octet-stream", "deploy": "application/octet-stream", "exe": "application/octet-stream", "dll": "application/octet-stream", "deb": "application/octet-stream", "dmg": "application/octet-stream", "iso": "application/octet-stream", "img": "application/octet-stream", "msi": "application/octet-stream", "msp": "application/octet-stream", "msm": "application/octet-stream", "buffer": "application/octet-stream", "oda": "application/oda", "opf": "application/oebps-package+xml", "ogx": "application/ogg", "omdoc": "application/omdoc+xml", "onetoc": "application/onenote", "onetoc2": "application/onenote", "onetmp": "application/onenote", "onepkg": "application/onenote", "oxps": "application/oxps", "relo": "application/p2p-overlay+xml", "xer": "application/patch-ops-error+xml", "pdf": "application/pdf", "pgp": "application/pgp-encrypted", "asc": "application/pgp-signature", "sig": "application/pgp-signature", "prf": "application/pics-rules", "p10": "application/pkcs10", "p7m": "application/pkcs7-mime", "p7c": "application/pkcs7-mime", "p7s": "application/pkcs7-signature", "p8": "application/pkcs8", "ac": "application/pkix-attr-cert", "cer": "application/pkix-cert", "crl": "application/pkix-crl", "pkipath": "application/pkix-pkipath", "pki": "application/pkixcmp", "pls": "application/pls+xml", "ai": "application/postscript", "eps": "application/postscript", "ps": "application/postscript", "provx": "application/provenance+xml", "cww": "application/prs.cww", "pskcxml": "application/pskc+xml", "raml": "application/raml+yaml", "rdf": "application/rdf+xml", "owl": "application/rdf+xml", "rif": "application/reginfo+xml", "rnc": "application/relax-ng-compact-syntax", "rl": "application/resource-lists+xml", "rld": "application/resource-lists-diff+xml", "rs": "application/rls-services+xml", "rapd": "application/route-apd+xml", "sls": "application/route-s-tsid+xml", "rusd": "application/route-usd+xml", "gbr": "application/rpki-ghostbusters", "mft": "application/rpki-manifest", "roa": "application/rpki-roa", "rsd": "application/rsd+xml", "rss": "application/rss+xml", "rtf": "application/rtf", "sbml": "application/sbml+xml", "scq": "application/scvp-cv-request", "scs": "application/scvp-cv-response", "spq": "application/scvp-vp-request", "spp": "application/scvp-vp-response", "sdp": "application/sdp", "senmlx": "application/senml+xml", "sensmlx": "application/sensml+xml", "setpay": "application/set-payment-initiation", "setreg": "application/set-registration-initiation", "shf": "application/shf+xml", "siv": "application/sieve", "sieve": "application/sieve", "smi": "application/smil+xml", "smil": "application/smil+xml", "rq": "application/sparql-query", "srx": "application/sparql-results+xml", "gram": "application/srgs", "grxml": "application/srgs+xml", "sru": "application/sru+xml", "ssdl": "application/ssdl+xml", "ssml": "application/ssml+xml", "swidtag": "application/swid+xml", "tei": "application/tei+xml", "teicorpus": "application/tei+xml", "tfi": "application/thraud+xml", "tsd": "application/timestamped-data", "toml": "application/toml", "trig": "application/trig", "ttml": "application/ttml+xml", "ubj": "application/ubjson", "rsheet": "application/urc-ressheet+xml", "td": "application/urc-targetdesc+xml", "vxml": "application/voicexml+xml", "wasm": "application/wasm", "wgt": "application/widget", "hlp": "application/winhlp", "wsdl": "application/wsdl+xml", "wspolicy": "application/wspolicy+xml", "xaml": "application/xaml+xml", "xav": "application/xcap-att+xml", "xca": "application/xcap-caps+xml", "xdf": "application/xcap-diff+xml", "xel": "application/xcap-el+xml", "xns": "application/xcap-ns+xml", "xenc": "application/xenc+xml", "xhtml": "application/xhtml+xml", "xht": "application/xhtml+xml", "xlf": "application/xliff+xml", "xml": "application/xml", "xsl": "application/xml", "xsd": "application/xml", "rng": "application/xml", "dtd": "application/xml-dtd", "xop": "application/xop+xml", "xpl": "application/xproc+xml", "xslt": "application/xml", "xspf": "application/xspf+xml", "mxml": "application/xv+xml", "xhvml": "application/xv+xml", "xvml": "application/xv+xml", "xvm": "application/xv+xml", "yang": "application/yang", "yin": "application/yin+xml", "zip": "application/zip", "3gpp": "video/3gpp", "adp": "audio/adpcm", "amr": "audio/amr", "au": "audio/basic", "snd": "audio/basic", "mid": "audio/midi", "midi": "audio/midi", "kar": "audio/midi", "rmi": "audio/midi", "mxmf": "audio/mobile-xmf", "mp3": "audio/mpeg", "m4a": "audio/mp4", "mp4a": "audio/mp4", "mpga": "audio/mpeg", "mp2": "audio/mpeg", "mp2a": "audio/mpeg", "m2a": "audio/mpeg", "m3a": "audio/mpeg", "oga": "audio/ogg", "ogg": "audio/ogg", "spx": "audio/ogg", "opus": "audio/ogg", "s3m": "audio/s3m", "sil": "audio/silk", "wav": "audio/wav", "weba": "audio/webm", "xm": "audio/xm", "ttc": "font/collection", "otf": "font/otf", "ttf": "font/ttf", "woff": "font/woff", "woff2": "font/woff2", "exr": "image/aces", "apng": "image/apng", "avif": "image/avif", "bmp": "image/bmp", "cgm": "image/cgm", "drle": "image/dicom-rle", "emf": "image/emf", "fits": "image/fits", "g3": "image/g3fax", "gif": "image/gif", "heic": "image/heic", "heics": "image/heic-sequence", "heif": "image/heif", "heifs": "image/heif-sequence", "hej2": "image/hej2k", "hsj2": "image/hsj2", "ief": "image/ief", "jls": "image/jls", "jp2": "image/jp2", "jpg2": "image/jp2", "jpeg": "image/jpeg", "jpg": "image/jpeg", "jpe": "image/jpeg", "jph": "image/jph", "jhc": "image/jphc", "jpm": "image/jpm", "jpx": "image/jpx", "jpf": "image/jpx", "jxr": "image/jxr", "jxra": "image/jxra", "jxrs": "image/jxrs", "jxs": "image/jxs", "jxsc": "image/jxsc", "jxsi": "image/jxsi", "jxss": "image/jxss", "ktx": "image/ktx", "ktx2": "image/ktx2", "png": "image/png", "btif": "image/prs.btif", "pti": "image/prs.pti", "sgi": "image/sgi", "svg": "image/svg+xml", "svgz": "image/svg+xml", "t38": "image/t38", "tif": "image/tiff", "tiff": "image/tiff", "tfx": "image/tiff-fx", "webp": "image/webp", "wmf": "image/wmf", "disposition-notification": "message/disposition-notification", "u8msg": "message/global", "u8dsn": "message/global-delivery-status", "u8mdn": "message/global-disposition-notification", "u8hdr": "message/global-headers", "eml": "message/rfc822", "mime": "message/rfc822", "3mf": "model/3mf", "gltf": "model/gltf+json", "glb": "model/gltf-binary", "igs": "model/iges", "iges": "model/iges", "msh": "model/mesh", "mesh": "model/mesh", "silo": "model/mesh", "mtl": "model/mtl", "obj": "model/obj", "stpz": "model/step+zip", "stpxz": "model/step-xml+zip", "stl": "model/stl", "wrl": "model/vrml", "vrml": "model/vrml", "x3db": "model/x3d+fastinfoset", "x3dbz": "model/x3d+binary", "x3dv": "model/x3d-vrml", "x3dvz": "model/x3d+vrml", "x3d": "model/x3d+xml", "x3dz": "model/x3d+xml", "appcache": "text/cache-manifest", "manifest": "text/cache-manifest", "ics": "text/calendar", "ifb": "text/calendar", "coffee": "text/coffeescript", "litcoffee": "text/coffeescript", "css": "text/css", "csv": "text/csv", "html": "text/html", "htm": "text/html", "shtml": "text/html", "jade": "text/jade", "jsx": "text/jsx", "less": "text/less", "markdown": "text/markdown", "md": "text/markdown", "mml": "text/mathml", "mdx": "text/mdx", "n3": "text/n3", "txt": "text/plain", "text": "text/plain", "conf": "text/plain", "def": "text/plain", "list": "text/plain", "log": "text/plain", "in": "text/plain", "ini": "text/plain", "dsc": "text/prs.lines.tag", "rtx": "text/richtext", "sgml": "text/sgml", "sgm": "text/sgml", "shex": "text/shex", "slim": "text/slim", "slm": "text/slim", "spdx": "text/spdx", "stylus": "text/stylus", "styl": "text/stylus", "tsv": "text/tab-separated-values", "t": "text/troff", "tr": "text/troff", "roff": "text/troff", "man": "text/troff", "me": "text/troff", "ms": "text/troff", "ttl": "text/turtle", "uri": "text/uri-list", "uris": "text/uri-list", "urls": "text/uri-list", "vcard": "text/vcard", "vtt": "text/vtt", "yaml": "text/yaml", "yml": "text/yaml", "3gp": "video/3gpp", "3g2": "video/3gpp2", "h261": "video/h261", "h263": "video/h263", "h264": "video/h264", "m4s": "video/iso.segment", "jpgv": "video/jpeg", "jpgm": "image/jpm", "mj2": "video/mj2", "mjp2": "video/mj2", "ts": "video/mp2t", "mp4": "video/mp4", "mp4v": "video/mp4", "mpg4": "video/mp4", "mpeg": "video/mpeg", "mpg": "video/mpeg", "mpe": "video/mpeg", "m1v": "video/mpeg", "m2v": "video/mpeg", "ogv": "video/ogg", "qt": "video/quicktime", "mov": "video/quicktime", "webm": "video/webm" }; function lookup(extn) { let tmp = ('' + extn).trim().toLowerCase(); let idx = tmp.lastIndexOf('.'); return mimes$1[!~idx ? tmp : tmp.substring(++idx)]; } 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; } 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) { // 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); } 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) { this.split(this.end - trimmed.length); 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 window !== 'undefined' && typeof window.btoa === 'function') { return (str) => window.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(); 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; } } 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(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$2 = Object.prototype.toString; function isObject$1(thing) { return toString$2.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 }; }; } 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 segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (nameIndex >= 0) { segment.push(nameIndex); } this.rawSegments.push(segment); } 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; while (originalCharIndex < chunk.end) { if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); } 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 { 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(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(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$1(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'); 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) { 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; } 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) { 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) this.overwrite( match.index, match.index + match[0].length, getReplacement(match, this.original) ); }); } else { const match = this.original.match(searchValue); if (match && match.index != null) this.overwrite( match.index, match.index + match[0].length, getReplacement(match, this.original) ); } 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) ) { 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); } } const assetUrlRE = /__VITE_ASSET__([a-z\d]+)__(?:\$_(.*?)__)?/g; const rawRE = /(?:\?|&)raw(?:&|$)/; const urlRE = /(\?|&)url(?:&|$)/; const jsSourceMapRE = /\.[cm]?js\.map$/; const assetCache = new WeakMap(); const generatedAssets = new WeakMap(); // add own dictionary entry by directly assigning mrmime function registerCustomMime() { // https://github.com/lukeed/mrmime/issues/3 mimes$1['ico'] = 'image/x-icon'; // https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers#flac mimes$1['flac'] = 'audio/flac'; // mrmime and mime-db is not released yet: https://github.com/jshttp/mime-db/commit/c9242a9b7d4bb25d7a0c9244adec74aeef08d8a1 mimes$1['aac'] = 'audio/aac'; // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types mimes$1['eot'] = 'application/vnd.ms-fontobject'; } function renderAssetUrlInJS(ctx, config, chunk, opts, code) { const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format); let match; let s; // Urls added with JS using e.g. // imgElement.src = "__VITE_ASSET__5aa0ddc0__" are using quotes // Urls added in CSS that is imported in JS end up like // var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aa0ddc0__)}\n"; // In both cases, the wrapping should already be fine assetUrlRE.lastIndex = 0; while ((match = assetUrlRE.exec(code))) { s || (s = new MagicString(code)); const [full, referenceId, postfix = ''] = match; const file = ctx.getFileName(referenceId); chunk.viteMetadata.importedAssets.add(cleanUrl(file)); const filename = file + postfix; const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime); const replacementString = typeof replacement === 'string' ? JSON.stringify(replacement).slice(1, -1) : `"+${replacement.runtime}+"`; s.update(match.index, match.index + full.length, replacementString); } // Replace __VITE_PUBLIC_ASSET__5aa0ddc0__ with absolute paths const publicAssetUrlMap = publicAssetUrlCache.get(config); publicAssetUrlRE.lastIndex = 0; while ((match = publicAssetUrlRE.exec(code))) { s || (s = new MagicString(code)); const [full, hash] = match; const publicUrl = publicAssetUrlMap.get(hash).slice(1); const replacement = toOutputFilePathInJS(publicUrl, 'public', chunk.fileName, 'js', config, toRelativeRuntime); const replacementString = typeof replacement === 'string' ? JSON.stringify(replacement).slice(1, -1) : `"+${replacement.runtime}+"`; s.update(match.index, match.index + full.length, replacementString); } return s; } /** * Also supports loading plain strings with import text from './foo.txt?raw' */ function assetPlugin(config) { registerCustomMime(); return { name: 'vite:asset', buildStart() { assetCache.set(config, new Map()); generatedAssets.set(config, new Map()); }, resolveId(id) { if (!config.assetsInclude(cleanUrl(id))) { return; } // imports to absolute urls pointing to files in /public // will fail to resolve in the main resolver. handle them here. const publicFile = checkPublicFile(id, config); if (publicFile) { return id; } }, async load(id) { if (id.startsWith('\0')) { // Rollup convention, this id should be handled by the // plugin that marked it with \0 return; } // raw requests, read from disk if (rawRE.test(id)) { const file = checkPublicFile(id, config) || cleanUrl(id); // raw query, read file and return as string return `export default ${JSON.stringify(await promises$2.readFile(file, 'utf-8'))}`; } if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) { return; } id = id.replace(urlRE, '$1').replace(/[?&]$/, ''); const url = await fileToUrl(id, config, this); return `export default ${JSON.stringify(url)}`; }, renderChunk(code, chunk, opts) { const s = renderAssetUrlInJS(this, config, chunk, opts, code); if (s) { return { code: s.toString(), map: config.build.sourcemap ? s.generateMap({ hires: true }) : null, }; } else { return null; } }, generateBundle(_, bundle) { // do not emit assets for SSR build if (config.command === 'build' && config.build.ssr && !config.build.ssrEmitAssets) { for (const file in bundle) { if (bundle[file].type === 'asset' && !file.endsWith('ssr-manifest.json') && !jsSourceMapRE.test(file)) { delete bundle[file]; } } } }, }; } function checkPublicFile(url, { publicDir }) { // note if the file is in /public, the resolver would have returned it // as-is so it's not going to be a fully resolved path. if (!publicDir || !url.startsWith('/')) { return; } const publicFile = path$o.join(publicDir, cleanUrl(url)); if (!publicFile.startsWith(publicDir)) { // can happen if URL starts with '../' return; } if (fs$l.existsSync(publicFile)) { return publicFile; } else { return; } } async function fileToUrl(id, config, ctx) { if (config.command === 'serve') { return fileToDevUrl(id, config); } else { return fileToBuiltUrl(id, config, ctx); } } function fileToDevUrl(id, config) { let rtn; if (checkPublicFile(id, config)) { // in public dir, keep the url as-is rtn = id; } else if (id.startsWith(config.root)) { // in project root, infer short public path rtn = '/' + path$o.posix.relative(config.root, id); } else { // outside of project root, use absolute fs path // (this is special handled by the serve static middleware rtn = path$o.posix.join(FS_PREFIX, id); } const base = joinUrlSegments(config.server?.origin ?? '', config.base); return joinUrlSegments(base, rtn.replace(/^\//, '')); } function getPublicAssetFilename(hash, config) { return publicAssetUrlCache.get(config)?.get(hash); } const publicAssetUrlCache = new WeakMap(); const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g; function publicFileToBuiltUrl(url, config) { if (config.command !== 'build') { // We don't need relative base or renderBuiltUrl support during dev return joinUrlSegments(config.base, url); } const hash = getHash(url); let cache = publicAssetUrlCache.get(config); if (!cache) { cache = 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; // Check whether the content begins with the characteristic string of Git LFS placeholders return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0; } /** * Register an asset to be emitted as part of the bundle (if necessary) * and returns the resolved public URL */ async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) { if (!skipPublicCheck && checkPublicFile(id, config)) { return publicFileToBuiltUrl(id, config); } const cache = assetCache.get(config); const cached = cache.get(id); if (cached) { return cached; } const file = cleanUrl(id); const content = await promises$2.readFile(file); let url; if (config.build.lib || (!file.endsWith('.svg') && !file.endsWith('.html') && content.length < Number(config.build.assetsInlineLimit) && !isGitLfsPlaceholder(content))) { if (config.build.lib && isGitLfsPlaceholder(content)) { config.logger.warn(picocolorsExports.yellow(`Inlined file ${id} was not downloaded via Git LFS`)); } const mimeType = lookup(file) ?? 'application/octet-stream'; // base64 inlined as a string url = `data:${mimeType};base64,${content.toString('base64')}`; } else { // emit as asset const { search, hash } = parse$i(id); const postfix = (search || '') + (hash || ''); const referenceId = pluginContext.emitFile({ // Ignore directory structure for asset file names name: path$o.basename(file), type: 'asset', source: content, }); const originalName = normalizePath$3(path$o.relative(config.root, file)); generatedAssets.get(config).set(referenceId, { originalName }); url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`; // TODO_BASE } cache.set(id, url); return url; } async function urlToBuiltUrl(url, importer, config, pluginContext) { if (checkPublicFile(url, config)) { return publicFileToBuiltUrl(url, config); } const file = url.startsWith('/') ? path$o.join(config.root, url) : path$o.join(path$o.dirname(importer), url); return fileToBuiltUrl(file, config, pluginContext, // skip public check since we just did it above true); } function manifestPlugin(config) { const manifest = {}; let outputCount; return { name: 'vite:manifest', buildStart() { outputCount = 0; }, generateBundle({ format }, bundle) { function getChunkName(chunk) { if (chunk.facadeModuleId) { let name = normalizePath$3(path$o.relative(config.root, chunk.facadeModuleId)); if (format === 'system' && !chunk.name.includes('-legacy')) { const ext = path$o.extname(name); const endPos = ext.length !== 0 ? -ext.length : undefined; name = name.slice(0, endPos) + `-legacy` + ext; } return name.replace(/\0/g, ''); } else { return `_` + path$o.basename(chunk.fileName); } } function getInternalImports(imports) { const filteredImports = []; for (const file of imports) { if (bundle[file] === undefined) { continue; } filteredImports.push(getChunkName(bundle[file])); } return filteredImports; } function createChunk(chunk) { const manifestChunk = { file: chunk.fileName, }; 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 fileNameToAssetMeta = new Map(); const assets = generatedAssets.get(config); assets.forEach((asset, referenceId) => { const fileName = this.getFileName(referenceId); fileNameToAssetMeta.set(fileName, asset); }); const fileNameToAsset = 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' && typeof chunk.name === 'string') { // Add every unique asset to the manifest, keyed by its original name const assetMeta = fileNameToAssetMeta.get(chunk.fileName); const src = assetMeta?.originalName ?? chunk.name; const asset = createAsset(chunk, src, assetMeta?.isEntry); manifest[src] = asset; fileNameToAsset.set(chunk.fileName, asset); } } // Add deduplicated assets to the manifest assets.forEach(({ originalName }, referenceId) => { if (!manifest[originalName]) { const fileName = this.getFileName(referenceId); const asset = fileNameToAsset.get(fileName); if (asset) { manifest[originalName] = asset; } } }); outputCount++; const output = config.build.rollupOptions?.output; const outputLength = Array.isArray(output) ? output.length : 1; if (outputCount >= outputLength) { this.emitFile({ fileName: typeof config.build.manifest === 'string' ? config.build.manifest : 'manifest.json', type: 'asset', source: jsonStableStringify(manifest, { space: 2 }), }); } }, }; } // This is based on @rollup/plugin-data-uri const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/; const dataUriPrefix = `/@data-uri/`; /** * Build only, since importing from a data URI works natively. */ function dataURIPlugin() { let resolved; return { name: 'vite:data-uri', buildStart() { resolved = {}; }, resolveId(id) { if (!dataUriRE.test(id)) { return null; } const uri = new URL$3(id); if (uri.protocol !== 'data:') { return null; } const match = uri.pathname.match(dataUriRE); if (!match) { return null; } const [, mime, format, data] = match; if (mime !== 'text/javascript') { throw new Error(`data URI with non-JavaScript mime type is not supported.`); } // decode data const base64 = format && /base64/i.test(format.substring(1)); const content = base64 ? Buffer.from(data, 'base64').toString('utf-8') : data; resolved[id] = content; return dataUriPrefix + id; }, load(id) { if (id.startsWith(dataUriPrefix)) { id = id.slice(dataUriPrefix.length); return resolved[id] || null; } }, }; } /* es-module-lexer 1.2.0 */ 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,o=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;o>0&&C.memory.grow(Math.ceil(o/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=[],k=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.ai(),g=C.id(),I=C.ss(),o=C.se();let K;C.ip()&&(K=J(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),D.push({n:K,s:A,e:Q,ss:I,se:o,d:g,a:B});}for(;C.re();){const A=C.es(),Q=C.ee(),B=C.els(),g=C.ele(),I=E.slice(A,Q),o=I[0],K=B<0?void 0:E.slice(B,g),D=K?K[0]:"";k.push({s:A,e:Q,ls:B,le:g,n:'"'===o||"'"===o?J(I):I,ln:'"'===D||"'"===D?J(K):K});}function J(A){try{return (0, eval)(A)}catch(A){}}return [D,k,!!C.f()]}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; const isDebug$6 = !!process.env.DEBUG; const debug$e = createDebugger('vite:sourcemap', { onlyWhenFocused: true, }); // Virtual modules should be prefixed with a null byte to avoid a // false positive "missing source" warning. We also check for certain // prefixes used for special handling in esbuildDepPlugin. const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/; async function injectSourcesContent(map, file, logger) { let sourceRoot; try { // The source root is undefined for virtual modules and permission errors. sourceRoot = await promises$2.realpath(path$o.resolve(path$o.dirname(file), map.sourceRoot || '')); } catch { } const missingSources = []; map.sourcesContent = await Promise.all(map.sources.map((sourcePath) => { if (sourcePath && !virtualSourceRE.test(sourcePath)) { sourcePath = decodeURI(sourcePath); if (sourceRoot) { sourcePath = path$o.resolve(sourceRoot, sourcePath); } return promises$2.readFile(sourcePath, 'utf-8').catch(() => { missingSources.push(sourcePath); return null; }); } return null; })); // Use this command… // DEBUG="vite:sourcemap" vite build // …to log the missing sources. if (missingSources.length) { logger.warnOnce(`Sourcemap for "${file}" points to missing source files`); isDebug$6 && debug$e(`Missing sources:\n ` + missingSources.join(`\n `)); } } 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 (isDebug$6) { code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`; } if (type === 'js') { code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`; } else if (type === 'css') { code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`; } return code; } 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("*",2),~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 code) { return false } pos += set[i + 1]; if (pos >= code) { return true } } return false } // Test whether a given character code starts an identifier. function isIdentifierStart(code, astral) { if (code < 65) { return code === 36 } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) } // Test whether a given character is part of an identifier. function isIdentifierChar(code, astral) { if (code < 48) { return code === 36 } if (code < 58) { return true } if (code < 65) { return false } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) } // ## Token types // The assignment of fine-grained, information-carrying type objects // allows the tokenizer to store the information it has about a // token in a way that is very cheap for the parser to look up. // All token type variables start with an underscore, to make them // easy to recognize. // The `beforeExpr` property is used to disambiguate between regular // expressions and divisions. It is set on all token types that can // be followed by an expression (thus, a slash after them would be a // regular expression). // // The `startsExpr` property is used to check if the token ends a // `yield` expression. It is set on all token types that either can // directly start an expression (like a quotation mark) or can // continue an expression (like the body of a string). // // `isLoop` marks a keyword as starting a loop, which is important // to know when parsing a label, in order to allow or disallow // continue jumps to that label. var TokenType = function TokenType(label, conf) { if ( conf === void 0 ) conf = {}; this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop || null; this.updateContext = null; }; function binop(name, prec) { return new TokenType(name, {beforeExpr: true, binop: prec}) } var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; // Map keyword names to token types. var keywords$2 = {}; // Succinct definitions of keyword token types function kw(name, options) { if ( options === void 0 ) options = {}; options.keyword = name; return keywords$2[name] = new TokenType(name, options) } var types$1 = { num: new TokenType("num", startsExpr), regexp: new TokenType("regexp", startsExpr), string: new TokenType("string", startsExpr), name: new TokenType("name", startsExpr), privateId: new TokenType("privateId", startsExpr), eof: new TokenType("eof"), // Punctuation token types. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), bracketR: new TokenType("]"), braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), braceR: new TokenType("}"), parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), parenR: new TokenType(")"), comma: new TokenType(",", beforeExpr), semi: new TokenType(";", beforeExpr), colon: new TokenType(":", beforeExpr), dot: new TokenType("."), question: new TokenType("?", beforeExpr), questionDot: new TokenType("?."), arrow: new TokenType("=>", beforeExpr), template: new TokenType("template"), invalidTemplate: new TokenType("invalidTemplate"), ellipsis: new TokenType("...", beforeExpr), backQuote: new TokenType("`", startsExpr), dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), // Operators. These carry several kinds of properties to help the // parser use them properly (the presence of these properties is // what categorizes them as operators). // // `binop`, when present, specifies that this operator is a binary // operator, and will refer to its precedence. // // `prefix` and `postfix` mark the operator as a prefix or postfix // unary operator. // // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as // binary operators with a very low precedence, that should result // in AssignmentExpression nodes. eq: new TokenType("=", {beforeExpr: true, isAssign: true}), assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), logicalOR: binop("||", 1), logicalAND: binop("&&", 2), bitwiseOR: binop("|", 3), bitwiseXOR: binop("^", 4), bitwiseAND: binop("&", 5), equality: binop("==/!=/===/!==", 6), relational: binop("/<=/>=", 7), bitShift: binop("<>/>>>", 8), plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), modulo: binop("%", 10), star: binop("*", 10), slash: binop("/", 10), starstar: new TokenType("**", {beforeExpr: true}), coalesce: binop("??", 1), // Keyword token types. _break: kw("break"), _case: kw("case", beforeExpr), _catch: kw("catch"), _continue: kw("continue"), _debugger: kw("debugger"), _default: kw("default", beforeExpr), _do: kw("do", {isLoop: true, beforeExpr: true}), _else: kw("else", beforeExpr), _finally: kw("finally"), _for: kw("for", {isLoop: true}), _function: kw("function", startsExpr), _if: kw("if"), _return: kw("return", beforeExpr), _switch: kw("switch"), _throw: kw("throw", beforeExpr), _try: kw("try"), _var: kw("var"), _const: kw("const"), _while: kw("while", {isLoop: true}), _with: kw("with"), _new: kw("new", {beforeExpr: true, startsExpr: true}), _this: kw("this", startsExpr), _super: kw("super", startsExpr), _class: kw("class", startsExpr), _extends: kw("extends", beforeExpr), _export: kw("export"), _import: kw("import", startsExpr), _null: kw("null", startsExpr), _true: kw("true", startsExpr), _false: kw("false", startsExpr), _in: kw("in", {beforeExpr: true, binop: 7}), _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) }; // Matches a whole line break (where CRLF is considered a single // line break). Used to count lines. var lineBreak = /\r\n?|\n|\u2028|\u2029/; var lineBreakG = new RegExp(lineBreak.source, "g"); function isNewLine(code) { return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 } function nextLineBreak(code, from, end) { if ( end === void 0 ) end = code.length; for (var i = from; i < end; i++) { var next = code.charCodeAt(i); if (isNewLine(next)) { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } } return -1 } var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; var ref = Object.prototype; var hasOwnProperty$1 = ref.hasOwnProperty; var toString$1 = ref.toString; var hasOwn = Object.hasOwn || (function (obj, propName) { return ( hasOwnProperty$1.call(obj, propName) ); }); var isArray = Array.isArray || (function (obj) { return ( toString$1.call(obj) === "[object Array]" ); }); function wordsRegexp(words) { return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") } function codePointToString(code) { // UTF-16 Decoding if (code <= 0xFFFF) { return String.fromCharCode(code) } code -= 0x10000; return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) } var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; // These are used when `options.locations` is on, for the // `startLoc` and `endLoc` properties. var Position = function Position(line, col) { this.line = line; this.column = col; }; Position.prototype.offset = function offset (n) { return new Position(this.line, this.column + n) }; var SourceLocation = function SourceLocation(p, start, end) { this.start = start; this.end = end; if (p.sourceFile !== null) { this.source = p.sourceFile; } }; // The `getLineInfo` function is mostly useful when the // `locations` option is off (for performance reasons) and you // want to find the line/column position for a given character // offset. `input` should be the code string that the offset refers // into. function getLineInfo(input, offset) { for (var line = 1, cur = 0;;) { var nextBreak = nextLineBreak(input, cur, offset); if (nextBreak < 0) { return new Position(line, offset - cur) } ++line; cur = nextBreak; } } // A second argument must be given to configure the parser process. // These options are recognized (only `ecmaVersion` is required): var defaultOptions = { // `ecmaVersion` indicates the ECMAScript version to parse. Must be // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` // (the latest version the library supports). This influences // support for strict mode, the set of reserved words, and support // for new syntax features. ecmaVersion: null, // `sourceType` indicates the mode the code should be parsed in. // Can be either `"script"` or `"module"`. This influences global // strict mode and parsing of `import` and `export` declarations. sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // the position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are only enforced if ecmaVersion >= 5. // Set `allowReserved` to a boolean value to explicitly turn this on // an off. When this option has the value "never", reserved words // and keywords can also not be used as property names. allowReserved: null, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program, and an import.meta expression // in a script isn't considered an error. allowImportExportEverywhere: false, // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. // When enabled, await identifiers are allowed to appear at the top-level scope, // but they are still not allowed in non-async functions. allowAwaitOutsideFunction: null, // When enabled, super identifiers are not constrained to // appearing in methods and do not raise an error when they appear elsewhere. allowSuperOutsideMethod: null, // When enabled, hashbang directive in the beginning of file is // allowed and treated as a line comment. Enabled by default when // `ecmaVersion` >= 2023. allowHashBang: false, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokens returned from `tokenizer().getToken()`. Note // that you are not allowed to call the parser from the // callback—that will corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callback—that will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false }; // Interpret and default an options object var warnedAboutEcmaVersion = false; function getOptions(opts) { var options = {}; for (var opt in defaultOptions) { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; } if (options.ecmaVersion === "latest") { options.ecmaVersion = 1e8; } else if (options.ecmaVersion == null) { if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { warnedAboutEcmaVersion = true; console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); } options.ecmaVersion = 11; } else if (options.ecmaVersion >= 2015) { options.ecmaVersion -= 2009; } if (options.allowReserved == null) { options.allowReserved = options.ecmaVersion < 5; } if (!opts || opts.allowHashBang == null) { options.allowHashBang = options.ecmaVersion >= 14; } if (isArray(options.onToken)) { var tokens = options.onToken; options.onToken = function (token) { return tokens.push(token); }; } if (isArray(options.onComment)) { options.onComment = pushComment(options, options.onComment); } return options } function pushComment(options, array) { return function(block, text, start, end, startLoc, endLoc) { var comment = { type: block ? "Block" : "Line", value: text, start: start, end: end }; if (options.locations) { comment.loc = new SourceLocation(this, startLoc, endLoc); } if (options.ranges) { comment.range = [start, end]; } array.push(comment); } } // Each scope gets a bitset that may contain these flags var SCOPE_TOP = 1, SCOPE_FUNCTION = 2, SCOPE_ASYNC = 4, SCOPE_GENERATOR = 8, SCOPE_ARROW = 16, SCOPE_SIMPLE_CATCH = 32, SCOPE_SUPER = 64, SCOPE_DIRECT_SUPER = 128, SCOPE_CLASS_STATIC_BLOCK = 256, SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; function functionFlags(async, generator) { return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) } // Used in checkLVal* and declareName to determine the type of a binding var BIND_NONE = 0, // Not a binding BIND_VAR = 1, // Var-style binding BIND_LEXICAL = 2, // Let- or const-style binding BIND_FUNCTION = 3, // Function declaration BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding BIND_OUTSIDE = 5; // Special case for function names as bound inside the function var Parser$1 = function Parser(options, input, startPos) { this.options = options = getOptions(options); this.sourceFile = options.sourceFile; this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); var reserved = ""; if (options.allowReserved !== true) { reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; if (options.sourceType === "module") { reserved += " await"; } } this.reservedWords = wordsRegexp(reserved); var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; this.reservedWordsStrict = wordsRegexp(reservedStrict); this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); this.input = String(input); // Used to signal to callers of `readWord1` whether the word // contained any escape sequences. This is needed because words with // escape sequences must not be interpreted as keywords. this.containsEsc = false; // Set up token state // The current position of the tokenizer in the input. if (startPos) { this.pos = startPos; this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } // Properties of the current token: // Its type this.type = types$1.eof; // For tokens that include more information than their type, the value this.value = null; // Its start and end offset this.start = this.end = this.pos; // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = this.curPosition(); // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext(); this.exprAllowed = true; // Figure out if it's a module code. this.inModule = options.sourceType === "module"; this.strict = this.inModule || this.strictDirective(this.pos); // Used to signify the start of a potential arrow function this.potentialArrowAt = -1; this.potentialArrowInForAwait = false; // Positions to delayed-check that yield/await does not exist in default parameters. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; // Labels in scope. this.labels = []; // Thus-far undefined exports. this.undefinedExports = Object.create(null); // If enabled, skip leading hashbang line. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") { this.skipLineComment(2); } // Scope tracking for duplicate variable names (see scope.js) this.scopeStack = []; this.enterScope(SCOPE_TOP); // For RegExp validation this.regexpState = null; // The stack of private names. // Each element has two properties: 'declared' and 'used'. // When it exited from the outermost class definition, all used private names must be declared. this.privateNameStack = []; }; var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; Parser$1.prototype.parse = function parse () { var node = this.options.program || this.startNode(); this.nextToken(); return this.parseTopLevel(node) }; prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }; prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; prototypeAccessors.canAwait.get = function () { for (var i = this.scopeStack.length - 1; i >= 0; i--) { var scope = this.scopeStack[i]; if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false } if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } } return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction }; prototypeAccessors.allowSuper.get = function () { var ref = this.currentThisScope(); var flags = ref.flags; var inClassFieldInit = ref.inClassFieldInit; return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod }; prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; prototypeAccessors.allowNewDotTarget.get = function () { var ref = this.currentThisScope(); var flags = ref.flags; var inClassFieldInit = ref.inClassFieldInit; return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit }; prototypeAccessors.inClassStaticBlock.get = function () { return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 }; Parser$1.extend = function extend () { var plugins = [], len = arguments.length; while ( len-- ) plugins[ len ] = arguments[ len ]; var cls = this; for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } return cls }; Parser$1.parse = function parse (input, options) { return new this(options, input).parse() }; Parser$1.parseExpressionAt = function parseExpressionAt (input, pos, options) { var parser = new this(options, input, pos); parser.nextToken(); return parser.parseExpression() }; Parser$1.tokenizer = function tokenizer (input, options) { return new this(options, input) }; Object.defineProperties( Parser$1.prototype, prototypeAccessors ); var pp$9 = Parser$1.prototype; // ## Parser utilities var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; pp$9.strictDirective = function(start) { if (this.options.ecmaVersion < 5) { return false } for (;;) { // Try to find string literal. skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this.input)[0].length; var match = literal.exec(this.input.slice(start)); if (!match) { return false } if ((match[1] || match[2]) === "use strict") { skipWhiteSpace.lastIndex = start + match[0].length; var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; var next = this.input.charAt(end); return next === ";" || next === "}" || (lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) } start += match[0].length; // Skip semicolon, if any. skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this.input)[0].length; if (this.input[start] === ";") { start++; } } }; // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp$9.eat = function(type) { if (this.type === type) { this.next(); return true } else { return false } }; // Tests whether parsed token is a contextual keyword. pp$9.isContextual = function(name) { return this.type === types$1.name && this.value === name && !this.containsEsc }; // Consumes contextual keyword if possible. pp$9.eatContextual = function(name) { if (!this.isContextual(name)) { return false } this.next(); return true }; // Asserts that following token is given contextual keyword. pp$9.expectContextual = function(name) { if (!this.eatContextual(name)) { this.unexpected(); } }; // Test whether a semicolon can be inserted at the current position. pp$9.canInsertSemicolon = function() { return this.type === types$1.eof || this.type === types$1.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; pp$9.insertSemicolon = function() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } return true } }; // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp$9.semicolon = function() { if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); } }; pp$9.afterTrailingComma = function(tokType, notNext) { if (this.type === tokType) { if (this.options.onTrailingComma) { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } if (!notNext) { this.next(); } return true } }; // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp$9.expect = function(type) { this.eat(type) || this.unexpected(); }; // Raise an unexpected token error. pp$9.unexpected = function(pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); }; var DestructuringErrors = function DestructuringErrors() { this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; }; pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { if (!refDestructuringErrors) { return } if (refDestructuringErrors.trailingComma > -1) { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); } }; pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { if (!refDestructuringErrors) { return false } var shorthandAssign = refDestructuringErrors.shorthandAssign; var doubleProto = refDestructuringErrors.doubleProto; if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } if (shorthandAssign >= 0) { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } if (doubleProto >= 0) { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } }; pp$9.checkYieldAwaitInDefaultParams = function() { if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } if (this.awaitPos) { this.raise(this.awaitPos, "Await expression cannot be a default value"); } }; pp$9.isSimpleAssignTarget = function(expr) { if (expr.type === "ParenthesizedExpression") { return this.isSimpleAssignTarget(expr.expression) } return expr.type === "Identifier" || expr.type === "MemberExpression" }; var pp$8 = Parser$1.prototype; // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp$8.parseTopLevel = function(node) { var exports = Object.create(null); if (!node.body) { node.body = []; } while (this.type !== types$1.eof) { var stmt = this.parseStatement(null, true, exports); node.body.push(stmt); } if (this.inModule) { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) { var name = list[i]; this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); } } this.adaptDirectivePrologue(node.body); this.next(); node.sourceType = this.options.sourceType; return this.finishNode(node, "Program") }; var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; pp$8.isLet = function(context) { if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); // For ambiguous cases, determine if a LexicalDeclaration (or only a // Statement) is allowed here. If context is not empty then only a Statement // is allowed. However, `let [` is an explicit negative lookahead for // ExpressionStatement, so special-case it first. if (nextCh === 91 || nextCh === 92) { return true } // '[', '/' if (context) { return false } if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral if (isIdentifierStart(nextCh, true)) { var pos = next + 1; while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } var ident = this.input.slice(next, pos); if (!keywordRelationalOperator.test(ident)) { return true } } return false }; // check 'async [no LineTerminator here] function' // - 'async /*foo*/ function' is OK. // - 'async /*\n*/ function' is invalid. pp$8.isAsyncFunction = function() { if (this.options.ecmaVersion < 8 || !this.isContextual("async")) { return false } skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, after; return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) }; // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp$8.parseStatement = function(context, topLevel, exports) { var starttype = this.type, node = this.startNode(), kind; if (this.isLet(context)) { starttype = types$1._var; kind = "let"; } // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword) case types$1._debugger: return this.parseDebuggerStatement(node) case types$1._do: return this.parseDoStatement(node) case types$1._for: return this.parseForStatement(node) case types$1._function: // Function as sole body of either an if statement or a labeled statement // works, but not when it is part of a labeled statement that is the sole // body of an if statement. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } return this.parseFunctionStatement(node, false, !context) case types$1._class: if (context) { this.unexpected(); } return this.parseClass(node, true) case types$1._if: return this.parseIfStatement(node) case types$1._return: return this.parseReturnStatement(node) case types$1._switch: return this.parseSwitchStatement(node) case types$1._throw: return this.parseThrowStatement(node) case types$1._try: return this.parseTryStatement(node) case types$1._const: case types$1._var: kind = kind || this.value; if (context && kind !== "var") { this.unexpected(); } return this.parseVarStatement(node, kind) case types$1._while: return this.parseWhileStatement(node) case types$1._with: return this.parseWithStatement(node) case types$1.braceL: return this.parseBlock(true, node) case types$1.semi: return this.parseEmptyStatement(node) case types$1._export: case types$1._import: if (this.options.ecmaVersion > 10 && starttype === types$1._import) { skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); if (nextCh === 40 || nextCh === 46) // '(' or '.' { return this.parseExpressionStatement(node, this.parseExpression()) } } if (!this.options.allowImportExportEverywhere) { if (!topLevel) { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } if (!this.inModule) { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } } return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports) // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. default: if (this.isAsyncFunction()) { if (context) { this.unexpected(); } this.next(); return this.parseFunctionStatement(node, true, !context) } var maybeName = this.value, expr = this.parseExpression(); if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) { return this.parseLabeledStatement(node, maybeName, expr, context) } else { return this.parseExpressionStatement(node, expr) } } }; pp$8.parseBreakContinueStatement = function(node, keyword) { var isBreak = keyword === "break"; this.next(); if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; } else if (this.type !== types$1.name) { this.unexpected(); } else { node.label = this.parseIdent(); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. var i = 0; for (; i < this.labels.length; ++i) { var lab = this.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } if (node.label && isBreak) { break } } } if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") }; pp$8.parseDebuggerStatement = function(node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement") }; pp$8.parseDoStatement = function(node) { this.next(); this.labels.push(loopLabel); node.body = this.parseStatement("do"); this.labels.pop(); this.expect(types$1._while); node.test = this.parseParenExpression(); if (this.options.ecmaVersion >= 6) { this.eat(types$1.semi); } else { this.semicolon(); } return this.finishNode(node, "DoWhileStatement") }; // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp$8.parseForStatement = function(node) { this.next(); var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; this.labels.push(loopLabel); this.enterScope(0); this.expect(types$1.parenL); if (this.type === types$1.semi) { if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, null) } var isLet = this.isLet(); if (this.type === types$1._var || this.type === types$1._const || isLet) { var init$1 = this.startNode(), kind = isLet ? "let" : this.value; this.next(); this.parseVar(init$1, true, kind); this.finishNode(init$1, "VariableDeclaration"); if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { if (this.options.ecmaVersion >= 9) { if (this.type === types$1._in) { if (awaitAt > -1) { this.unexpected(awaitAt); } } else { node.await = awaitAt > -1; } } return this.parseForIn(node, init$1) } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init$1) } var startsWithLet = this.isContextual("let"), isForOf = false; var refDestructuringErrors = new DestructuringErrors; var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { if (this.options.ecmaVersion >= 9) { if (this.type === types$1._in) { if (awaitAt > -1) { this.unexpected(awaitAt); } } else { node.await = awaitAt > -1; } } if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } this.toAssignable(init, false, refDestructuringErrors); this.checkLValPattern(init); return this.parseForIn(node, init) } else { this.checkExpressionErrors(refDestructuringErrors, true); } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init) }; pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { this.next(); return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) }; pp$8.parseIfStatement = function(node) { this.next(); node.test = this.parseParenExpression(); // allow function declarations in branches, but only in non-strict mode node.consequent = this.parseStatement("if"); node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; return this.finishNode(node, "IfStatement") }; pp$8.parseReturnStatement = function(node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) { this.raise(this.start, "'return' outside of function"); } this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; } else { node.argument = this.parseExpression(); this.semicolon(); } return this.finishNode(node, "ReturnStatement") }; pp$8.parseSwitchStatement = function(node) { this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(types$1.braceL); this.labels.push(switchLabel); this.enterScope(0); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. var cur; for (var sawDefault = false; this.type !== types$1.braceR;) { if (this.type === types$1._case || this.type === types$1._default) { var isCase = this.type === types$1._case; if (cur) { this.finishNode(cur, "SwitchCase"); } node.cases.push(cur = this.startNode()); cur.consequent = []; this.next(); if (isCase) { cur.test = this.parseExpression(); } else { if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } sawDefault = true; cur.test = null; } this.expect(types$1.colon); } else { if (!cur) { this.unexpected(); } cur.consequent.push(this.parseStatement(null)); } } this.exitScope(); if (cur) { this.finishNode(cur, "SwitchCase"); } this.next(); // Closing brace this.labels.pop(); return this.finishNode(node, "SwitchStatement") }; pp$8.parseThrowStatement = function(node) { this.next(); if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) { this.raise(this.lastTokEnd, "Illegal newline after throw"); } node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement") }; // Reused empty array added for node fields that are always empty. var empty$1 = []; pp$8.parseTryStatement = function(node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.type === types$1._catch) { var clause = this.startNode(); this.next(); if (this.eat(types$1.parenL)) { clause.param = this.parseBindingAtom(); var simple = clause.param.type === "Identifier"; this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); this.expect(types$1.parenR); } else { if (this.options.ecmaVersion < 10) { this.unexpected(); } clause.param = null; this.enterScope(0); } clause.body = this.parseBlock(false); this.exitScope(); node.handler = this.finishNode(clause, "CatchClause"); } node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) { this.raise(node.start, "Missing catch or finally clause"); } return this.finishNode(node, "TryStatement") }; pp$8.parseVarStatement = function(node, kind) { this.next(); this.parseVar(node, false, kind); this.semicolon(); return this.finishNode(node, "VariableDeclaration") }; pp$8.parseWhileStatement = function(node) { this.next(); node.test = this.parseParenExpression(); this.labels.push(loopLabel); node.body = this.parseStatement("while"); this.labels.pop(); return this.finishNode(node, "WhileStatement") }; pp$8.parseWithStatement = function(node) { if (this.strict) { this.raise(this.start, "'with' in strict mode"); } this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement("with"); return this.finishNode(node, "WithStatement") }; pp$8.parseEmptyStatement = function(node) { this.next(); return this.finishNode(node, "EmptyStatement") }; pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) { var label = list[i$1]; if (label.name === maybeName) { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); } } var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; for (var i = this.labels.length - 1; i >= 0; i--) { var label$1 = this.labels[i]; if (label$1.statementStart === node.start) { // Update information about previous labels on this node label$1.statementStart = this.start; label$1.kind = kind; } else { break } } this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); this.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement") }; pp$8.parseExpressionStatement = function(node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement") }; // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; if ( node === void 0 ) node = this.startNode(); node.body = []; this.expect(types$1.braceL); if (createNewLexicalScope) { this.enterScope(0); } while (this.type !== types$1.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } if (exitStrict) { this.strict = false; } this.next(); if (createNewLexicalScope) { this.exitScope(); } return this.finishNode(node, "BlockStatement") }; // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp$8.parseFor = function(node, init) { node.init = init; this.expect(types$1.semi); node.test = this.type === types$1.semi ? null : this.parseExpression(); this.expect(types$1.semi); node.update = this.type === types$1.parenR ? null : this.parseExpression(); this.expect(types$1.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, "ForStatement") }; // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp$8.parseForIn = function(node, init) { var isForIn = this.type === types$1._in; this.next(); if ( init.type === "VariableDeclaration" && init.declarations[0].init != null && ( !isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier" ) ) { this.raise( init.start, ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") ); } node.left = init; node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); this.expect(types$1.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") }; // Parse a list of variable declarations. pp$8.parseVar = function(node, isFor, kind) { node.declarations = []; node.kind = kind; for (;;) { var decl = this.startNode(); this.parseVarId(decl, kind); if (this.eat(types$1.eq)) { decl.init = this.parseMaybeAssign(isFor); } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { this.unexpected(); } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); } else { decl.init = null; } node.declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(types$1.comma)) { break } } return node }; pp$8.parseVarId = function(decl, kind) { decl.id = this.parseBindingAtom(); this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); }; var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; // Parse a function declaration or literal (depending on the // `statement & FUNC_STATEMENT`). // Remove `allowExpressionBody` for 7.0.0, as it is only called with false pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { this.initFunction(node); if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT)) { this.unexpected(); } node.generator = this.eat(types$1.star); } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } if (statement & FUNC_STATEMENT) { node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent(); if (node.id && !(statement & FUNC_HANGING_STATEMENT)) // If it is a regular function declaration in sloppy mode, then it is // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding // mode depends on properties of the current scope (see // treatFunctionsAsVar). { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } } var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags(node.async, node.generator)); if (!(statement & FUNC_STATEMENT)) { node.id = this.type === types$1.name ? this.parseIdent() : null; } this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") }; pp$8.parseFunctionParams = function(node) { this.expect(types$1.parenL); node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); }; // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp$8.parseClass = function(node, isStatement) { this.next(); // ecma-262 14.6 Class Definitions // A class definition is always strict mode code. var oldStrict = this.strict; this.strict = true; this.parseClassId(node, isStatement); this.parseClassSuper(node); var privateNameMap = this.enterClassBody(); var classBody = this.startNode(); var hadConstructor = false; classBody.body = []; this.expect(types$1.braceL); while (this.type !== types$1.braceR) { var element = this.parseClassElement(node.superClass !== null); if (element) { classBody.body.push(element); if (element.type === "MethodDefinition" && element.kind === "constructor") { if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); } hadConstructor = true; } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); } } } this.strict = oldStrict; this.next(); node.body = this.finishNode(classBody, "ClassBody"); this.exitClassBody(); return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") }; pp$8.parseClassElement = function(constructorAllowsSuper) { if (this.eat(types$1.semi)) { return null } var ecmaVersion = this.options.ecmaVersion; var node = this.startNode(); var keyName = ""; var isGenerator = false; var isAsync = false; var kind = "method"; var isStatic = false; if (this.eatContextual("static")) { // Parse static init block if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { this.parseClassStaticBlock(node); return node } if (this.isClassElementNameStart() || this.type === types$1.star) { isStatic = true; } else { keyName = "static"; } } node.static = isStatic; if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { isAsync = true; } else { keyName = "async"; } } if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { isGenerator = true; } if (!keyName && !isAsync && !isGenerator) { var lastValue = this.value; if (this.eatContextual("get") || this.eatContextual("set")) { if (this.isClassElementNameStart()) { kind = lastValue; } else { keyName = lastValue; } } } // Parse element name if (keyName) { // 'async', 'get', 'set', or 'static' were not a keyword contextually. // The last token is any of those. Make it the element name. node.computed = false; node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); node.key.name = keyName; this.finishNode(node.key, "Identifier"); } else { this.parseClassElementName(node); } // Parse element value if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { var isConstructor = !node.static && checkKeyName(node, "constructor"); var allowsDirectSuper = isConstructor && constructorAllowsSuper; // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } node.kind = isConstructor ? "constructor" : kind; this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); } else { this.parseClassField(node); } return node }; pp$8.isClassElementNameStart = function() { return ( this.type === types$1.name || this.type === types$1.privateId || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword ) }; pp$8.parseClassElementName = function(element) { if (this.type === types$1.privateId) { if (this.value === "constructor") { this.raise(this.start, "Classes can't have an element named '#constructor'"); } element.computed = false; element.key = this.parsePrivateIdent(); } else { this.parsePropertyName(element); } }; pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { // Check key and flags var key = method.key; if (method.kind === "constructor") { if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } } else if (method.static && checkKeyName(method, "prototype")) { this.raise(key.start, "Classes may not have a static property named prototype"); } // Parse value var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); // Check value if (method.kind === "get" && value.params.length !== 0) { this.raiseRecoverable(value.start, "getter should have no params"); } if (method.kind === "set" && value.params.length !== 1) { this.raiseRecoverable(value.start, "setter should have exactly one param"); } if (method.kind === "set" && value.params[0].type === "RestElement") { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } return this.finishNode(method, "MethodDefinition") }; pp$8.parseClassField = function(field) { if (checkKeyName(field, "constructor")) { this.raise(field.key.start, "Classes can't have a field named 'constructor'"); } else if (field.static && checkKeyName(field, "prototype")) { this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); } if (this.eat(types$1.eq)) { // To raise SyntaxError if 'arguments' exists in the initializer. var scope = this.currentThisScope(); var inClassFieldInit = scope.inClassFieldInit; scope.inClassFieldInit = true; field.value = this.parseMaybeAssign(); scope.inClassFieldInit = inClassFieldInit; } else { field.value = null; } this.semicolon(); return this.finishNode(field, "PropertyDefinition") }; pp$8.parseClassStaticBlock = function(node) { node.body = []; var oldLabels = this.labels; this.labels = []; this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); while (this.type !== types$1.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } this.next(); this.exitScope(); this.labels = oldLabels; return this.finishNode(node, "StaticBlock") }; pp$8.parseClassId = function(node, isStatement) { if (this.type === types$1.name) { node.id = this.parseIdent(); if (isStatement) { this.checkLValSimple(node.id, BIND_LEXICAL, false); } } else { if (isStatement === true) { this.unexpected(); } node.id = null; } }; pp$8.parseClassSuper = function(node) { node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null; }; pp$8.enterClassBody = function() { var element = {declared: Object.create(null), used: []}; this.privateNameStack.push(element); return element.declared }; pp$8.exitClassBody = function() { var ref = this.privateNameStack.pop(); var declared = ref.declared; var used = ref.used; var len = this.privateNameStack.length; var parent = len === 0 ? null : this.privateNameStack[len - 1]; for (var i = 0; i < used.length; ++i) { var id = used[i]; if (!hasOwn(declared, id.name)) { if (parent) { parent.used.push(id); } else { this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); } } } }; function isPrivateNameConflicted(privateNameMap, element) { var name = element.key.name; var curr = privateNameMap[name]; var next = "true"; if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { next = (element.static ? "s" : "i") + element.kind; } // `class { get #a(){}; static set #a(_){} }` is also conflict. if ( curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget" ) { privateNameMap[name] = "true"; return false } else if (!curr) { privateNameMap[name] = next; return false } else { return true } } function checkKeyName(node, name) { var computed = node.computed; var key = node.key; return !computed && ( key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name ) } // Parses module export declaration. pp$8.parseExport = function(node, exports) { this.next(); // export * from '...' if (this.eat(types$1.star)) { if (this.options.ecmaVersion >= 11) { if (this.eatContextual("as")) { node.exported = this.parseModuleExportName(); this.checkExport(exports, node.exported, this.lastTokStart); } else { node.exported = null; } } this.expectContextual("from"); if (this.type !== types$1.string) { this.unexpected(); } node.source = this.parseExprAtom(); this.semicolon(); return this.finishNode(node, "ExportAllDeclaration") } if (this.eat(types$1._default)) { // export default ... this.checkExport(exports, "default", this.lastTokStart); var isAsync; if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { var fNode = this.startNode(); this.next(); if (isAsync) { this.next(); } node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); } else if (this.type === types$1._class) { var cNode = this.startNode(); node.declaration = this.parseClass(cNode, "nullableID"); } else { node.declaration = this.parseMaybeAssign(); this.semicolon(); } return this.finishNode(node, "ExportDefaultDeclaration") } // export var|const|let|function|class ... if (this.shouldParseExportStatement()) { node.declaration = this.parseStatement(null); if (node.declaration.type === "VariableDeclaration") { this.checkVariableExport(exports, node.declaration.declarations); } else { this.checkExport(exports, node.declaration.id, node.declaration.id.start); } node.specifiers = []; node.source = null; } else { // export { x, y as z } [from '...'] node.declaration = null; node.specifiers = this.parseExportSpecifiers(exports); if (this.eatContextual("from")) { if (this.type !== types$1.string) { this.unexpected(); } node.source = this.parseExprAtom(); } else { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { // check for keywords used as local names var spec = list[i]; this.checkUnreserved(spec.local); // check if export is defined this.checkLocalExport(spec.local); if (spec.local.type === "Literal") { this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); } } node.source = null; } this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration") }; pp$8.checkExport = function(exports, name, pos) { if (!exports) { return } if (typeof name !== "string") { name = name.type === "Identifier" ? name.name : name.value; } if (hasOwn(exports, name)) { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } exports[name] = true; }; pp$8.checkPatternExport = function(exports, pat) { var type = pat.type; if (type === "Identifier") { this.checkExport(exports, pat, pat.start); } else if (type === "ObjectPattern") { for (var i = 0, list = pat.properties; i < list.length; i += 1) { var prop = list[i]; this.checkPatternExport(exports, prop); } } else if (type === "ArrayPattern") { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { var elt = list$1[i$1]; if (elt) { this.checkPatternExport(exports, elt); } } } else if (type === "Property") { this.checkPatternExport(exports, pat.value); } else if (type === "AssignmentPattern") { this.checkPatternExport(exports, pat.left); } else if (type === "RestElement") { this.checkPatternExport(exports, pat.argument); } else if (type === "ParenthesizedExpression") { this.checkPatternExport(exports, pat.expression); } }; pp$8.checkVariableExport = function(exports, decls) { if (!exports) { return } for (var i = 0, list = decls; i < list.length; i += 1) { var decl = list[i]; this.checkPatternExport(exports, decl.id); } }; pp$8.shouldParseExportStatement = function() { return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction() }; // Parses a comma-separated list of module exports. pp$8.parseExportSpecifiers = function(exports) { var nodes = [], first = true; // export { x, y as z } [from '...'] this.expect(types$1.braceL); while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } var node = this.startNode(); node.local = this.parseModuleExportName(); node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; this.checkExport( exports, node.exported, node.exported.start ); nodes.push(this.finishNode(node, "ExportSpecifier")); } return nodes }; // Parses import declaration. pp$8.parseImport = function(node) { this.next(); // import '...' if (this.type === types$1.string) { node.specifiers = empty$1; node.source = this.parseExprAtom(); } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); } this.semicolon(); return this.finishNode(node, "ImportDeclaration") }; // Parses a comma-separated list of module imports. pp$8.parseImportSpecifiers = function() { var nodes = [], first = true; if (this.type === types$1.name) { // import defaultObj, { x, y as z } from '...' var node = this.startNode(); node.local = this.parseIdent(); this.checkLValSimple(node.local, BIND_LEXICAL); nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); if (!this.eat(types$1.comma)) { return nodes } } if (this.type === types$1.star) { var node$1 = this.startNode(); this.next(); this.expectContextual("as"); node$1.local = this.parseIdent(); this.checkLValSimple(node$1.local, BIND_LEXICAL); nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); return nodes } this.expect(types$1.braceL); while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } var node$2 = this.startNode(); node$2.imported = this.parseModuleExportName(); if (this.eatContextual("as")) { node$2.local = this.parseIdent(); } else { this.checkUnreserved(node$2.imported); node$2.local = node$2.imported; } this.checkLValSimple(node$2.local, BIND_LEXICAL); nodes.push(this.finishNode(node$2, "ImportSpecifier")); } return nodes }; pp$8.parseModuleExportName = function() { if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { var stringLiteral = this.parseLiteral(this.value); if (loneSurrogate.test(stringLiteral.value)) { this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); } return stringLiteral } return this.parseIdent(true) }; // Set `ExpressionStatement#directive` property for directive prologues. pp$8.adaptDirectivePrologue = function(statements) { for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { statements[i].directive = statements[i].expression.raw.slice(1, -1); } }; pp$8.isDirectiveCandidate = function(statement) { return ( this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings. (this.input[statement.start] === "\"" || this.input[statement.start] === "'") ) }; var pp$7 = Parser$1.prototype; // Convert existing expression atom to assignable pattern // if possible. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": if (this.inAsync && node.name === "await") { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } break case "ObjectPattern": case "ArrayPattern": case "AssignmentPattern": case "RestElement": break case "ObjectExpression": node.type = "ObjectPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; this.toAssignable(prop, isBinding); // Early error: // AssignmentRestProperty[Yield, Await] : // `...` DestructuringAssignmentTarget[Yield, Await] // // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. if ( prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") ) { this.raise(prop.argument.start, "Unexpected token"); } } break case "Property": // AssignmentProperty has type === "Property" if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } this.toAssignable(node.value, isBinding); break case "ArrayExpression": node.type = "ArrayPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } this.toAssignableList(node.elements, isBinding); break case "SpreadElement": node.type = "RestElement"; this.toAssignable(node.argument, isBinding); if (node.argument.type === "AssignmentPattern") { this.raise(node.argument.start, "Rest elements cannot have a default value"); } break case "AssignmentExpression": if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } node.type = "AssignmentPattern"; delete node.operator; this.toAssignable(node.left, isBinding); break case "ParenthesizedExpression": this.toAssignable(node.expression, isBinding, refDestructuringErrors); break case "ChainExpression": this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); break case "MemberExpression": if (!isBinding) { break } default: this.raise(node.start, "Assigning to rvalue"); } } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } return node }; // Convert list of expression atoms to binding list. pp$7.toAssignableList = function(exprList, isBinding) { var end = exprList.length; for (var i = 0; i < end; i++) { var elt = exprList[i]; if (elt) { this.toAssignable(elt, isBinding); } } if (end) { var last = exprList[end - 1]; if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") { this.unexpected(last.argument.start); } } return exprList }; // Parses spread element. pp$7.parseSpread = function(refDestructuringErrors) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(false, refDestructuringErrors); return this.finishNode(node, "SpreadElement") }; pp$7.parseRestBinding = function() { var node = this.startNode(); this.next(); // RestElement inside of a function parameter must be an identifier if (this.options.ecmaVersion === 6 && this.type !== types$1.name) { this.unexpected(); } node.argument = this.parseBindingAtom(); return this.finishNode(node, "RestElement") }; // Parses lvalue (assignable) atom. pp$7.parseBindingAtom = function() { if (this.options.ecmaVersion >= 6) { switch (this.type) { case types$1.bracketL: var node = this.startNode(); this.next(); node.elements = this.parseBindingList(types$1.bracketR, true, true); return this.finishNode(node, "ArrayPattern") case types$1.braceL: return this.parseObj(true) } } return this.parseIdent() }; pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) { var elts = [], first = true; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(types$1.comma); } if (allowEmpty && this.type === types$1.comma) { elts.push(null); } else if (allowTrailingComma && this.afterTrailingComma(close)) { break } else if (this.type === types$1.ellipsis) { var rest = this.parseRestBinding(); this.parseBindingListItem(rest); elts.push(rest); if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } this.expect(close); break } else { var elem = this.parseMaybeDefault(this.start, this.startLoc); this.parseBindingListItem(elem); elts.push(elem); } } return elts }; pp$7.parseBindingListItem = function(param) { return param }; // Parses assignment pattern around given atom if possible. pp$7.parseMaybeDefault = function(startPos, startLoc, left) { left = left || this.parseBindingAtom(); if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern") }; // The following three functions all verify that a node is an lvalue — // something that can be bound, or assigned to. In order to do so, they perform // a variety of checks: // // - Check that none of the bound/assigned-to identifiers are reserved words. // - Record name declarations for bindings in the appropriate scope. // - Check duplicate argument names, if checkClashes is set. // // If a complex binding pattern is encountered (e.g., object and array // destructuring), the entire pattern is recursively checked. // // There are three versions of checkLVal*() appropriate for different // circumstances: // // - checkLValSimple() shall be used if the syntactic construct supports // nothing other than identifiers and member expressions. Parenthesized // expressions are also correctly handled. This is generally appropriate for // constructs for which the spec says // // > It is a Syntax Error if AssignmentTargetType of [the production] is not // > simple. // // It is also appropriate for checking if an identifier is valid and not // defined elsewhere, like import declarations or function/class identifiers. // // Examples where this is used include: // a += …; // import a from '…'; // where a is the node to be checked. // // - checkLValPattern() shall be used if the syntactic construct supports // anything checkLValSimple() supports, as well as object and array // destructuring patterns. This is generally appropriate for constructs for // which the spec says // // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor // > an ArrayLiteral and AssignmentTargetType of [the production] is not // > simple. // // Examples where this is used include: // (a = …); // const a = …; // try { … } catch (a) { … } // where a is the node to be checked. // // - checkLValInnerPattern() shall be used if the syntactic construct supports // anything checkLValPattern() supports, as well as default assignment // patterns, rest elements, and other constructs that may appear within an // object or array destructuring pattern. // // As a special case, function parameters also use checkLValInnerPattern(), // as they also support defaults and rest constructs. // // These functions deliberately support both assignment and binding constructs, // as the logic for both is exceedingly similar. If the node is the target of // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it // should be set to the appropriate BIND_* constant, like BIND_VAR or // BIND_LEXICAL. // // If the function is called with a non-BIND_NONE bindingType, then // additionally a checkClashes object may be specified to allow checking for // duplicate argument names. checkClashes is ignored if the provided construct // is an assignment (i.e., bindingType is BIND_NONE). pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE; var isBind = bindingType !== BIND_NONE; switch (expr.type) { case "Identifier": if (this.strict && this.reservedWordsStrictBind.test(expr.name)) { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } if (isBind) { if (bindingType === BIND_LEXICAL && expr.name === "let") { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } if (checkClashes) { if (hasOwn(checkClashes, expr.name)) { this.raiseRecoverable(expr.start, "Argument name clash"); } checkClashes[expr.name] = true; } if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } } break case "ChainExpression": this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); break case "MemberExpression": if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } break case "ParenthesizedExpression": if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } return this.checkLValSimple(expr.expression, bindingType, checkClashes) default: this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); } }; pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE; switch (expr.type) { case "ObjectPattern": for (var i = 0, list = expr.properties; i < list.length; i += 1) { var prop = list[i]; this.checkLValInnerPattern(prop, bindingType, checkClashes); } break case "ArrayPattern": for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { var elem = list$1[i$1]; if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } } break default: this.checkLValSimple(expr, bindingType, checkClashes); } }; pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE; switch (expr.type) { case "Property": // AssignmentProperty has type === "Property" this.checkLValInnerPattern(expr.value, bindingType, checkClashes); break case "AssignmentPattern": this.checkLValPattern(expr.left, bindingType, checkClashes); break case "RestElement": this.checkLValPattern(expr.argument, bindingType, checkClashes); break default: this.checkLValPattern(expr, bindingType, checkClashes); } }; // The algorithm used to determine whether a regexp can appear at a var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; this.generator = !!generator; }; var types$2 = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", false), p_stat: new TokContext("(", false), p_expr: new TokContext("(", true), q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), f_stat: new TokContext("function", false), f_expr: new TokContext("function", true), f_expr_gen: new TokContext("function", true, false, null, true), f_gen: new TokContext("function", false, false, null, true) }; var pp$6 = Parser$1.prototype; pp$6.initialContext = function() { return [types$2.b_stat] }; pp$6.curContext = function() { return this.context[this.context.length - 1] }; pp$6.braceIsBlock = function(prevType) { var parent = this.curContext(); if (parent === types$2.f_expr || parent === types$2.f_stat) { return true } if (prevType === types$1.colon && (parent === types$2.b_stat || parent === types$2.b_expr)) { return !parent.isExpr } // The check for `tt.name && exprAllowed` detects whether we are // after a `yield` or `of` construct. See the `updateContext` for // `tt.name`. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) { return true } if (prevType === types$1.braceL) { return parent === types$2.b_stat } if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) { return false } return !this.exprAllowed }; pp$6.inGeneratorContext = function() { for (var i = this.context.length - 1; i >= 1; i--) { var context = this.context[i]; if (context.token === "function") { return context.generator } } return false }; pp$6.updateContext = function(prevType) { var update, type = this.type; if (type.keyword && prevType === types$1.dot) { this.exprAllowed = false; } else if (update = type.updateContext) { update.call(this, prevType); } else { this.exprAllowed = type.beforeExpr; } }; // Used to handle egde cases when token context could not be inferred correctly during tokenization phase pp$6.overrideContext = function(tokenCtx) { if (this.curContext() !== tokenCtx) { this.context[this.context.length - 1] = tokenCtx; } }; // Token-specific context update code types$1.parenR.updateContext = types$1.braceR.updateContext = function() { if (this.context.length === 1) { this.exprAllowed = true; return } var out = this.context.pop(); if (out === types$2.b_stat && this.curContext().token === "function") { out = this.context.pop(); } this.exprAllowed = !out.isExpr; }; types$1.braceL.updateContext = function(prevType) { this.context.push(this.braceIsBlock(prevType) ? types$2.b_stat : types$2.b_expr); this.exprAllowed = true; }; types$1.dollarBraceL.updateContext = function() { this.context.push(types$2.b_tmpl); this.exprAllowed = true; }; types$1.parenL.updateContext = function(prevType) { var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; this.context.push(statementParens ? types$2.p_stat : types$2.p_expr); this.exprAllowed = true; }; types$1.incDec.updateContext = function() { // tokExprAllowed stays unchanged }; types$1._function.updateContext = types$1._class.updateContext = function(prevType) { if (prevType.beforeExpr && prevType !== types$1._else && !(prevType === types$1.semi && this.curContext() !== types$2.p_stat) && !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types$2.b_stat)) { this.context.push(types$2.f_expr); } else { this.context.push(types$2.f_stat); } this.exprAllowed = false; }; types$1.backQuote.updateContext = function() { if (this.curContext() === types$2.q_tmpl) { this.context.pop(); } else { this.context.push(types$2.q_tmpl); } this.exprAllowed = false; }; types$1.star.updateContext = function(prevType) { if (prevType === types$1._function) { var index = this.context.length - 1; if (this.context[index] === types$2.f_expr) { this.context[index] = types$2.f_expr_gen; } else { this.context[index] = types$2.f_gen; } } this.exprAllowed = true; }; types$1.name.updateContext = function(prevType) { var allowed = false; if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) { allowed = true; } } this.exprAllowed = allowed; }; // A recursive descent parser operates by defining functions for all var pp$5 = Parser$1.prototype; // Check if property name clashes with already added. // Object/class getters and setters are not allowed to clash — // either with each other or with an init property — and in // strict mode, init properties are also not allowed to be repeated. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") { return } if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) { return } var key = prop.key; var name; switch (key.type) { case "Identifier": name = key.name; break case "Literal": name = String(key.value); break default: return } var kind = prop.kind; if (this.options.ecmaVersion >= 6) { if (name === "__proto__" && kind === "init") { if (propHash.proto) { if (refDestructuringErrors) { if (refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; } } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } } propHash.proto = true; } return } name = "$" + name; var other = propHash[name]; if (other) { var redefinition; if (kind === "init") { redefinition = this.strict && other.init || other.get || other.set; } else { redefinition = other.init || other[kind]; } if (redefinition) { this.raiseRecoverable(key.start, "Redefinition of property"); } } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }; // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). pp$5.parseExpression = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); if (this.type === types$1.comma) { var node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } return this.finishNode(node, "SequenceExpression") } return expr }; // Parse an assignment expression. This includes applications of // operators like `+=`. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { if (this.isContextual("yield")) { if (this.inGenerator) { return this.parseYield(forInit) } // The tokenizer will assume an expression is allowed after // `yield`, but this isn't that kind of yield else { this.exprAllowed = false; } } var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; if (refDestructuringErrors) { oldParenAssign = refDestructuringErrors.parenthesizedAssign; oldTrailingComma = refDestructuringErrors.trailingComma; oldDoubleProto = refDestructuringErrors.doubleProto; refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; } else { refDestructuringErrors = new DestructuringErrors; ownDestructuringErrors = true; } var startPos = this.start, startLoc = this.startLoc; if (this.type === types$1.parenL || this.type === types$1.name) { this.potentialArrowAt = this.start; this.potentialArrowInForAwait = forInit === "await"; } var left = this.parseMaybeConditional(forInit, refDestructuringErrors); if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } if (this.type.isAssign) { var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; if (this.type === types$1.eq) { left = this.toAssignable(left, false, refDestructuringErrors); } if (!ownDestructuringErrors) { refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; } if (refDestructuringErrors.shorthandAssign >= left.start) { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly if (this.type === types$1.eq) { this.checkLValPattern(left); } else { this.checkLValSimple(left); } node.left = left; this.next(); node.right = this.parseMaybeAssign(forInit); if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } return this.finishNode(node, "AssignmentExpression") } else { if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } } if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } return left }; // Parse a ternary conditional (`?:`) operator. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprOps(forInit, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } if (this.eat(types$1.question)) { var node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(types$1.colon); node.alternate = this.parseMaybeAssign(forInit); return this.finishNode(node, "ConditionalExpression") } return expr }; // Start the precedence parser. pp$5.parseExprOps = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) }; // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { var prec = this.type.binop; if (prec != null && (!forInit || this.type !== types$1._in)) { if (prec > minPrec) { var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; var coalesce = this.type === types$1.coalesce; if (coalesce) { // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. prec = types$1.logicalAND.binop; } var op = this.value; this.next(); var startPos = this.start, startLoc = this.startLoc; var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) { this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); } return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) } } return left }; pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.operator = op; node.right = right; return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") }; // Parse unary operators, both prefix and postfix. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { var startPos = this.start, startLoc = this.startLoc, expr; if (this.isContextual("await") && this.canAwait) { expr = this.parseAwait(forInit); sawUnary = true; } else if (this.type.prefix) { var node = this.startNode(), update = this.type === types$1.incDec; node.operator = this.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(null, true, update, forInit); this.checkExpressionErrors(refDestructuringErrors, true); if (update) { this.checkLValSimple(node.argument); } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } else { sawUnary = true; } expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } else if (!sawUnary && this.type === types$1.privateId) { if (forInit || this.privateNameStack.length === 0) { this.unexpected(); } expr = this.parsePrivateIdent(); // only could be private fields in 'in', such as #x in obj if (this.type !== types$1._in) { this.unexpected(); } } else { expr = this.parseExprSubscripts(refDestructuringErrors, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } while (this.type.postfix && !this.canInsertSemicolon()) { var node$1 = this.startNodeAt(startPos, startLoc); node$1.operator = this.value; node$1.prefix = false; node$1.argument = expr; this.checkLValSimple(expr); this.next(); expr = this.finishNode(node$1, "UpdateExpression"); } } if (!incDec && this.eat(types$1.starstar)) { if (sawUnary) { this.unexpected(this.lastTokStart); } else { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } } else { return expr } }; function isPrivateFieldAccess(node) { return ( node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) ) } // Parse call, dot, and `[]`-subscript expressions. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprAtom(refDestructuringErrors, forInit); if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") { return expr } var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); if (refDestructuringErrors && result.type === "MemberExpression") { if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } } return result }; pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start; var optionalChained = false; while (true) { var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); if (element.optional) { optionalChained = true; } if (element === base || element.type === "ArrowFunctionExpression") { if (optionalChained) { var chainNode = this.startNodeAt(startPos, startLoc); chainNode.expression = element; element = this.finishNode(chainNode, "ChainExpression"); } return element } base = element; } }; pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { var optionalSupported = this.options.ecmaVersion >= 11; var optional = optionalSupported && this.eat(types$1.questionDot); if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } var computed = this.eat(types$1.bracketL); if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) { var node = this.startNodeAt(startPos, startLoc); node.object = base; if (computed) { node.property = this.parseExpression(); this.expect(types$1.bracketR); } else if (this.type === types$1.privateId && base.type !== "Super") { node.property = this.parsePrivateIdent(); } else { node.property = this.parseIdent(this.options.allowReserved !== "never"); } node.computed = !!computed; if (optionalSupported) { node.optional = optional; } base = this.finishNode(node, "MemberExpression"); } else if (!noCalls && this.eat(types$1.parenL)) { var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); if (this.awaitIdentPos > 0) { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; var node$1 = this.startNodeAt(startPos, startLoc); node$1.callee = base; node$1.arguments = exprList; if (optionalSupported) { node$1.optional = optional; } base = this.finishNode(node$1, "CallExpression"); } else if (this.type === types$1.backQuote) { if (optional || optionalChained) { this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); } var node$2 = this.startNodeAt(startPos, startLoc); node$2.tag = base; node$2.quasi = this.parseTemplate({isTagged: true}); base = this.finishNode(node$2, "TaggedTemplateExpression"); } return base }; // Parse an atomic expression — either a single token that is an // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, // or `{}`. pp$5.parseExprAtom = function(refDestructuringErrors, forInit) { // If a division operator appears in an expression position, the // tokenizer got confused, and we force it to read a regexp instead. if (this.type === types$1.slash) { this.readRegexp(); } var node, canBeArrow = this.potentialArrowAt === this.start; switch (this.type) { case types$1._super: if (!this.allowSuper) { this.raise(this.start, "'super' keyword outside a method"); } node = this.startNode(); this.next(); if (this.type === types$1.parenL && !this.allowDirectSuper) { this.raise(node.start, "super() call outside constructor of a subclass"); } // The `super` keyword can appear at below: // SuperProperty: // super [ Expression ] // super . IdentifierName // SuperCall: // super ( Arguments ) if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) { this.unexpected(); } return this.finishNode(node, "Super") case types$1._this: node = this.startNode(); this.next(); return this.finishNode(node, "ThisExpression") case types$1.name: var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; var id = this.parseIdent(false); if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { this.overrideContext(types$2.f_expr); return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) } if (canBeArrow && !this.canInsertSemicolon()) { if (this.eat(types$1.arrow)) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { id = this.parseIdent(false); if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) { this.unexpected(); } return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) } } return id case types$1.regexp: var value = this.value; node = this.parseLiteral(value.value); node.regex = {pattern: value.pattern, flags: value.flags}; return node case types$1.num: case types$1.string: return this.parseLiteral(this.value) case types$1._null: case types$1._true: case types$1._false: node = this.startNode(); node.value = this.type === types$1._null ? null : this.type === types$1._true; node.raw = this.type.keyword; this.next(); return this.finishNode(node, "Literal") case types$1.parenL: var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); if (refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) { refDestructuringErrors.parenthesizedAssign = start; } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = start; } } return expr case types$1.bracketL: node = this.startNode(); this.next(); node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); return this.finishNode(node, "ArrayExpression") case types$1.braceL: this.overrideContext(types$2.b_expr); return this.parseObj(false, refDestructuringErrors) case types$1._function: node = this.startNode(); this.next(); return this.parseFunction(node, 0) case types$1._class: return this.parseClass(this.startNode(), false) case types$1._new: return this.parseNew() case types$1.backQuote: return this.parseTemplate() case types$1._import: if (this.options.ecmaVersion >= 11) { return this.parseExprImport() } else { return this.unexpected() } default: this.unexpected(); } }; pp$5.parseExprImport = function() { var node = this.startNode(); // Consume `import` as an identifier for `import.meta`. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } var meta = this.parseIdent(true); switch (this.type) { case types$1.parenL: return this.parseDynamicImport(node) case types$1.dot: node.meta = meta; return this.parseImportMeta(node) default: this.unexpected(); } }; pp$5.parseDynamicImport = function(node) { this.next(); // skip `(` // Parse node.source. node.source = this.parseMaybeAssign(); // Verify ending. if (!this.eat(types$1.parenR)) { var errorPos = this.start; if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); } else { this.unexpected(errorPos); } } return this.finishNode(node, "ImportExpression") }; pp$5.parseImportMeta = function(node) { this.next(); // skip `.` var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "meta") { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } if (containsEsc) { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } return this.finishNode(node, "MetaProperty") }; pp$5.parseLiteral = function(value) { var node = this.startNode(); node.value = value; node.raw = this.input.slice(this.start, this.end); if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } this.next(); return this.finishNode(node, "Literal") }; pp$5.parseParenExpression = function() { this.expect(types$1.parenL); var val = this.parseExpression(); this.expect(types$1.parenR); return val }; pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; if (this.options.ecmaVersion >= 6) { this.next(); var innerStartPos = this.start, innerStartLoc = this.startLoc; var exprList = [], first = true, lastIsComma = false; var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; this.yieldPos = 0; this.awaitPos = 0; // Do not save awaitIdentPos to allow checking awaits nested in parameters while (this.type !== types$1.parenR) { first ? first = false : this.expect(types$1.comma); if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { lastIsComma = true; break } else if (this.type === types$1.ellipsis) { spreadStart = this.start; exprList.push(this.parseParenItem(this.parseRestBinding())); if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } break } else { exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); } } var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; this.expect(types$1.parenR); if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return this.parseParenArrowList(startPos, startLoc, exprList, forInit) } if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } if (spreadStart) { this.unexpected(spreadStart); } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); } else { val = exprList[0]; } } else { val = this.parseParenExpression(); } if (this.options.preserveParens) { var par = this.startNodeAt(startPos, startLoc); par.expression = val; return this.finishNode(par, "ParenthesizedExpression") } else { return val } }; pp$5.parseParenItem = function(item) { return item }; pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) }; // New's precedence is slightly tricky. It must allow its argument to // be a `[]` or dot subscript expression, but not a call — at least, // not without wrapping it in parentheses. Thus, it uses the noCalls // argument to parseSubscripts to prevent it from consuming the // argument list. var empty = []; pp$5.parseNew = function() { if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } var node = this.startNode(); var meta = this.parseIdent(true); if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) { node.meta = meta; var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "target") { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } if (containsEsc) { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } if (!this.allowNewDotTarget) { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } return this.finishNode(node, "MetaProperty") } var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import; node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false); if (isImport && node.callee.type === "ImportExpression") { this.raise(startPos, "Cannot use new with import()"); } if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); } else { node.arguments = empty; } return this.finishNode(node, "NewExpression") }; // Parse template expression. pp$5.parseTemplateElement = function(ref) { var isTagged = ref.isTagged; var elem = this.startNode(); if (this.type === types$1.invalidTemplate) { if (!isTagged) { this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); } elem.value = { raw: this.value, cooked: null }; } else { elem.value = { raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), cooked: this.value }; } this.next(); elem.tail = this.type === types$1.backQuote; return this.finishNode(elem, "TemplateElement") }; pp$5.parseTemplate = function(ref) { if ( ref === void 0 ) ref = {}; var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement({isTagged: isTagged}); node.quasis = [curElt]; while (!curElt.tail) { if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); } this.expect(types$1.dollarBraceL); node.expressions.push(this.parseExpression()); this.expect(types$1.braceR); node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); } this.next(); return this.finishNode(node, "TemplateLiteral") }; pp$5.isAsyncProp = function(prop) { return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; // Parse an object literal or binding pattern. pp$5.parseObj = function(isPattern, refDestructuringErrors) { var node = this.startNode(), first = true, propHash = {}; node.properties = []; this.next(); while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } var prop = this.parseProperty(isPattern, refDestructuringErrors); if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } node.properties.push(prop); } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") }; pp$5.parseProperty = function(isPattern, refDestructuringErrors) { var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { if (isPattern) { prop.argument = this.parseIdent(false); if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } return this.finishNode(prop, "RestElement") } // Parse argument. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); // To disallow trailing comma via `this.toAssignable()`. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start; } // Finish return this.finishNode(prop, "SpreadElement") } if (this.options.ecmaVersion >= 6) { prop.method = false; prop.shorthand = false; if (isPattern || refDestructuringErrors) { startPos = this.start; startLoc = this.startLoc; } if (!isPattern) { isGenerator = this.eat(types$1.star); } } var containsEsc = this.containsEsc; this.parsePropertyName(prop); if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { isAsync = true; isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); this.parsePropertyName(prop); } else { isAsync = false; } this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); return this.finishNode(prop, "Property") }; pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { if ((isGenerator || isAsync) && this.type === types$1.colon) { this.unexpected(); } if (this.eat(types$1.colon)) { prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); prop.kind = "init"; } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { if (isPattern) { this.unexpected(); } prop.kind = "init"; prop.method = true; prop.value = this.parseMethod(isGenerator, isAsync); } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { if (isGenerator || isAsync) { this.unexpected(); } prop.kind = prop.key.name; this.parsePropertyName(prop); prop.value = this.parseMethod(false); var paramCount = prop.kind === "get" ? 0 : 1; if (prop.value.params.length !== paramCount) { var start = prop.value.start; if (prop.kind === "get") { this.raiseRecoverable(start, "getter should have no params"); } else { this.raiseRecoverable(start, "setter should have exactly one param"); } } else { if (prop.kind === "set" && prop.value.params[0].type === "RestElement") { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } } } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { if (isGenerator || isAsync) { this.unexpected(); } this.checkUnreserved(prop.key); if (prop.key.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = startPos; } prop.kind = "init"; if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else if (this.type === types$1.eq && refDestructuringErrors) { if (refDestructuringErrors.shorthandAssign < 0) { refDestructuringErrors.shorthandAssign = this.start; } prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else { prop.value = this.copyNode(prop.key); } prop.shorthand = true; } else { this.unexpected(); } }; pp$5.parsePropertyName = function(prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(types$1.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(types$1.bracketR); return prop.key } else { prop.computed = false; } } return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") }; // Initialize empty function node. pp$5.initFunction = function(node) { node.id = null; if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } if (this.options.ecmaVersion >= 8) { node.async = false; } }; // Parse object or class method. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.initFunction(node); if (this.options.ecmaVersion >= 6) { node.generator = isGenerator; } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); this.expect(types$1.parenL); node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); this.parseFunctionBody(node, false, true, false); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "FunctionExpression") }; // Parse arrow function expression with given parameters. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); this.initFunction(node); if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; node.params = this.toAssignableList(params, true); this.parseFunctionBody(node, true, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "ArrowFunctionExpression") }; // Parse function body and check parameters. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { var isExpression = isArrowFunction && this.type !== types$1.braceL; var oldStrict = this.strict, useStrict = false; if (isExpression) { node.body = this.parseMaybeAssign(forInit); node.expression = true; this.checkParams(node, false); } else { var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); if (!oldStrict || nonSimple) { useStrict = this.strictDirective(this.end); // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (useStrict && nonSimple) { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } } // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). var oldLabels = this.labels; this.labels = []; if (useStrict) { this.strict = true; } // Add the params to varDeclaredNames to ensure that an error is thrown // if a let/const declaration in the function clashes with one of the params. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); node.expression = false; this.adaptDirectivePrologue(node.body.body); this.labels = oldLabels; } this.exitScope(); }; pp$5.isSimpleParamList = function(params) { for (var i = 0, list = params; i < list.length; i += 1) { var param = list[i]; if (param.type !== "Identifier") { return false } } return true }; // Checks function params for various disallowed patterns such as using "eval" // or "arguments" and duplicate parameters. pp$5.checkParams = function(node, allowDuplicates) { var nameHash = Object.create(null); for (var i = 0, list = node.params; i < list.length; i += 1) { var param = list[i]; this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); } }; // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { var elts = [], first = true; while (!this.eat(close)) { if (!first) { this.expect(types$1.comma); if (allowTrailingComma && this.afterTrailingComma(close)) { break } } else { first = false; } var elt = (void 0); if (allowEmpty && this.type === types$1.comma) { elt = null; } else if (this.type === types$1.ellipsis) { elt = this.parseSpread(refDestructuringErrors); if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start; } } else { elt = this.parseMaybeAssign(false, refDestructuringErrors); } elts.push(elt); } return elts }; pp$5.checkUnreserved = function(ref) { var start = ref.start; var end = ref.end; var name = ref.name; if (this.inGenerator && name === "yield") { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } if (this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } if (this.currentThisScope().inClassFieldInit && name === "arguments") { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } if (this.inClassStaticBlock && (name === "arguments" || name === "await")) { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } if (this.keywords.test(name)) { this.raise(start, ("Unexpected keyword '" + name + "'")); } if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) { return } var re = this.strict ? this.reservedWordsStrict : this.reservedWords; if (re.test(name)) { if (!this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); } }; // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. pp$5.parseIdent = function(liberal) { var node = this.startNode(); if (this.type === types$1.name) { node.name = this.value; } else if (this.type.keyword) { node.name = this.type.keyword; // To fix https://github.com/acornjs/acorn/issues/575 // `class` and `function` keywords push new context into this.context. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { this.context.pop(); } } else { this.unexpected(); } this.next(!!liberal); this.finishNode(node, "Identifier"); if (!liberal) { this.checkUnreserved(node); if (node.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = node.start; } } return node }; pp$5.parsePrivateIdent = function() { var node = this.startNode(); if (this.type === types$1.privateId) { node.name = this.value; } else { this.unexpected(); } this.next(); this.finishNode(node, "PrivateIdentifier"); // For validating existence if (this.privateNameStack.length === 0) { this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); } else { this.privateNameStack[this.privateNameStack.length - 1].used.push(node); } return node }; // Parses yield expression inside generator. pp$5.parseYield = function(forInit) { if (!this.yieldPos) { this.yieldPos = this.start; } var node = this.startNode(); this.next(); if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(types$1.star); node.argument = this.parseMaybeAssign(forInit); } return this.finishNode(node, "YieldExpression") }; pp$5.parseAwait = function(forInit) { if (!this.awaitPos) { this.awaitPos = this.start; } var node = this.startNode(); this.next(); node.argument = this.parseMaybeUnary(null, true, false, forInit); return this.finishNode(node, "AwaitExpression") }; var pp$4 = Parser$1.prototype; // This function is used to raise exceptions on parse errors. It // takes an offset integer (into the current `input`) to indicate // the location of the error, attaches the position to the end // of the error message, and then raises a `SyntaxError` with that // message. pp$4.raise = function(pos, message) { var loc = getLineInfo(this.input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos; err.loc = loc; err.raisedAt = this.pos; throw err }; pp$4.raiseRecoverable = pp$4.raise; pp$4.curPosition = function() { if (this.options.locations) { return new Position(this.curLine, this.pos - this.lineStart) } }; var pp$3 = Parser$1.prototype; var Scope = function Scope(flags) { this.flags = flags; // A list of var-declared names in the current lexical scope this.var = []; // A list of lexically-declared names in the current lexical scope this.lexical = []; // A list of lexically-declared FunctionDeclaration names in the current lexical scope this.functions = []; // A switch to disallow the identifier reference 'arguments' this.inClassFieldInit = false; }; // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. pp$3.enterScope = function(flags) { this.scopeStack.push(new Scope(flags)); }; pp$3.exitScope = function() { this.scopeStack.pop(); }; // The spec says: // > At the top level of a function, or script, function declarations are // > treated like var declarations rather than like lexical declarations. pp$3.treatFunctionsAsVarInScope = function(scope) { return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) }; pp$3.declareName = function(name, bindingType, pos) { var redeclared = false; if (bindingType === BIND_LEXICAL) { var scope = this.currentScope(); redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; scope.lexical.push(name); if (this.inModule && (scope.flags & SCOPE_TOP)) { delete this.undefinedExports[name]; } } else if (bindingType === BIND_SIMPLE_CATCH) { var scope$1 = this.currentScope(); scope$1.lexical.push(name); } else if (bindingType === BIND_FUNCTION) { var scope$2 = this.currentScope(); if (this.treatFunctionsAsVar) { redeclared = scope$2.lexical.indexOf(name) > -1; } else { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } scope$2.functions.push(name); } else { for (var i = this.scopeStack.length - 1; i >= 0; --i) { var scope$3 = this.scopeStack[i]; if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { redeclared = true; break } scope$3.var.push(name); if (this.inModule && (scope$3.flags & SCOPE_TOP)) { delete this.undefinedExports[name]; } if (scope$3.flags & SCOPE_VAR) { break } } } if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } }; pp$3.checkLocalExport = function(id) { // scope.functions must be empty as Module code is always strict. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) { this.undefinedExports[id.name] = id; } }; pp$3.currentScope = function() { return this.scopeStack[this.scopeStack.length - 1] }; pp$3.currentVarScope = function() { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR) { return scope } } }; // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. pp$3.currentThisScope = function() { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } } }; var Node = function Node(parser, pos, loc) { this.type = ""; this.start = pos; this.end = 0; if (parser.options.locations) { this.loc = new SourceLocation(parser, loc); } if (parser.options.directSourceFile) { this.sourceFile = parser.options.directSourceFile; } if (parser.options.ranges) { this.range = [pos, 0]; } }; // Start an AST node, attaching a start offset. var pp$2 = Parser$1.prototype; pp$2.startNode = function() { return new Node(this, this.start, this.startLoc) }; pp$2.startNodeAt = function(pos, loc) { return new Node(this, pos, loc) }; // Finish an AST node, adding `type` and `end` properties. function finishNodeAt(node, type, pos, loc) { node.type = type; node.end = pos; if (this.options.locations) { node.loc.end = loc; } if (this.options.ranges) { node.range[1] = pos; } return node } pp$2.finishNode = function(node, type) { return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) }; // Finish node at given position pp$2.finishNodeAt = function(node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc) }; pp$2.copyNode = function(node) { var newNode = new Node(this, node.start, this.startLoc); for (var prop in node) { newNode[prop] = node[prop]; } return newNode }; // This file contains Unicode properties extracted from the ECMAScript specification. // The lists are extracted like so: // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) // #table-binary-unicode-properties var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; var ecma11BinaryProperties = ecma10BinaryProperties; var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; var ecma13BinaryProperties = ecma12BinaryProperties; var ecma14BinaryProperties = ecma13BinaryProperties; var unicodeBinaryProperties = { 9: ecma9BinaryProperties, 10: ecma10BinaryProperties, 11: ecma11BinaryProperties, 12: ecma12BinaryProperties, 13: ecma13BinaryProperties, 14: ecma14BinaryProperties }; // #table-unicode-general-category-values var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; // #table-unicode-script-values var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; var ecma14ScriptValues = ecma13ScriptValues + " Kawi Nag_Mundari Nagm"; var unicodeScriptValues = { 9: ecma9ScriptValues, 10: ecma10ScriptValues, 11: ecma11ScriptValues, 12: ecma12ScriptValues, 13: ecma13ScriptValues, 14: ecma14ScriptValues }; var data = {}; function buildUnicodeData(ecmaVersion) { var d = data[ecmaVersion] = { binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), nonBinary: { General_Category: wordsRegexp(unicodeGeneralCategoryValues), Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) } }; d.nonBinary.Script_Extensions = d.nonBinary.Script; d.nonBinary.gc = d.nonBinary.General_Category; d.nonBinary.sc = d.nonBinary.Script; d.nonBinary.scx = d.nonBinary.Script_Extensions; } for (var i$1 = 0, list = [9, 10, 11, 12, 13, 14]; i$1 < list.length; i$1 += 1) { var ecmaVersion = list[i$1]; buildUnicodeData(ecmaVersion); } var pp$1 = Parser$1.prototype; var RegExpValidationState = function RegExpValidationState(parser) { this.parser = parser; this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : ""); this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; this.source = ""; this.flags = ""; this.start = 0; this.switchU = false; this.switchN = false; this.pos = 0; this.lastIntValue = 0; this.lastStringValue = ""; this.lastAssertionIsQuantifiable = false; this.numCapturingParens = 0; this.maxBackReference = 0; this.groupNames = []; this.backReferenceNames = []; }; RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { var unicode = flags.indexOf("u") !== -1; this.start = start | 0; this.source = pattern + ""; this.flags = flags; this.switchU = unicode && this.parser.options.ecmaVersion >= 6; this.switchN = unicode && this.parser.options.ecmaVersion >= 9; }; RegExpValidationState.prototype.raise = function raise (message) { this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); }; // If u flag is given, this returns the code point at the index (it combines a surrogate pair). // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). RegExpValidationState.prototype.at = function at (i, forceU) { if ( forceU === void 0 ) forceU = false; var s = this.source; var l = s.length; if (i >= l) { return -1 } var c = s.charCodeAt(i); if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { return c } var next = s.charCodeAt(i + 1); return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c }; RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { if ( forceU === void 0 ) forceU = false; var s = this.source; var l = s.length; if (i >= l) { return l } var c = s.charCodeAt(i), next; if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { return i + 1 } return i + 2 }; RegExpValidationState.prototype.current = function current (forceU) { if ( forceU === void 0 ) forceU = false; return this.at(this.pos, forceU) }; RegExpValidationState.prototype.lookahead = function lookahead (forceU) { if ( forceU === void 0 ) forceU = false; return this.at(this.nextIndex(this.pos, forceU), forceU) }; RegExpValidationState.prototype.advance = function advance (forceU) { if ( forceU === void 0 ) forceU = false; this.pos = this.nextIndex(this.pos, forceU); }; RegExpValidationState.prototype.eat = function eat (ch, forceU) { if ( forceU === void 0 ) forceU = false; if (this.current(forceU) === ch) { this.advance(forceU); return true } return false }; /** * Validate the flags part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$1.validateRegExpFlags = function(state) { var validFlags = state.validFlags; var flags = state.flags; for (var i = 0; i < flags.length; i++) { var flag = flags.charAt(i); if (validFlags.indexOf(flag) === -1) { this.raise(state.start, "Invalid regular expression flag"); } if (flags.indexOf(flag, i + 1) > -1) { this.raise(state.start, "Duplicate regular expression flag"); } } }; /** * Validate the pattern part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$1.validateRegExpPattern = function(state) { this.regexp_pattern(state); // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of // parsing contains a |GroupName|, reparse with the goal symbol // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* // exception if _P_ did not conform to the grammar, if any elements of _P_ // were not matched by the parse, or if any Early Error conditions exist. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { state.switchN = true; this.regexp_pattern(state); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern pp$1.regexp_pattern = function(state) { state.pos = 0; state.lastIntValue = 0; state.lastStringValue = ""; state.lastAssertionIsQuantifiable = false; state.numCapturingParens = 0; state.maxBackReference = 0; state.groupNames.length = 0; state.backReferenceNames.length = 0; this.regexp_disjunction(state); if (state.pos !== state.source.length) { // Make the same messages as V8. if (state.eat(0x29 /* ) */)) { state.raise("Unmatched ')'"); } if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { state.raise("Lone quantifier brackets"); } } if (state.maxBackReference > state.numCapturingParens) { state.raise("Invalid escape"); } for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { var name = list[i]; if (state.groupNames.indexOf(name) === -1) { state.raise("Invalid named capture referenced"); } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction pp$1.regexp_disjunction = function(state) { this.regexp_alternative(state); while (state.eat(0x7C /* | */)) { this.regexp_alternative(state); } // Make the same message as V8. if (this.regexp_eatQuantifier(state, true)) { state.raise("Nothing to repeat"); } if (state.eat(0x7B /* { */)) { state.raise("Lone quantifier brackets"); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative pp$1.regexp_alternative = function(state) { while (state.pos < state.source.length && this.regexp_eatTerm(state)) { } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term pp$1.regexp_eatTerm = function(state) { if (this.regexp_eatAssertion(state)) { // Handle `QuantifiableAssertion Quantifier` alternative. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion // is a QuantifiableAssertion. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { // Make the same message as V8. if (state.switchU) { state.raise("Invalid quantifier"); } } return true } if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { this.regexp_eatQuantifier(state); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion pp$1.regexp_eatAssertion = function(state) { var start = state.pos; state.lastAssertionIsQuantifiable = false; // ^, $ if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { return true } // \b \B if (state.eat(0x5C /* \ */)) { if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { return true } state.pos = start; } // Lookahead / Lookbehind if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { var lookbehind = false; if (this.options.ecmaVersion >= 9) { lookbehind = state.eat(0x3C /* < */); } if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { this.regexp_disjunction(state); if (!state.eat(0x29 /* ) */)) { state.raise("Unterminated group"); } state.lastAssertionIsQuantifiable = !lookbehind; return true } } state.pos = start; return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier pp$1.regexp_eatQuantifier = function(state, noError) { if ( noError === void 0 ) noError = false; if (this.regexp_eatQuantifierPrefix(state, noError)) { state.eat(0x3F /* ? */); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix pp$1.regexp_eatQuantifierPrefix = function(state, noError) { return ( state.eat(0x2A /* * */) || state.eat(0x2B /* + */) || state.eat(0x3F /* ? */) || this.regexp_eatBracedQuantifier(state, noError) ) }; pp$1.regexp_eatBracedQuantifier = function(state, noError) { var start = state.pos; if (state.eat(0x7B /* { */)) { var min = 0, max = -1; if (this.regexp_eatDecimalDigits(state)) { min = state.lastIntValue; if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { max = state.lastIntValue; } if (state.eat(0x7D /* } */)) { // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term if (max !== -1 && max < min && !noError) { state.raise("numbers out of order in {} quantifier"); } return true } } if (state.switchU && !noError) { state.raise("Incomplete quantifier"); } state.pos = start; } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom pp$1.regexp_eatAtom = function(state) { return ( this.regexp_eatPatternCharacters(state) || state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) ) }; pp$1.regexp_eatReverseSolidusAtomEscape = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if (this.regexp_eatAtomEscape(state)) { return true } state.pos = start; } return false }; pp$1.regexp_eatUncapturingGroup = function(state) { var start = state.pos; if (state.eat(0x28 /* ( */)) { if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { this.regexp_disjunction(state); if (state.eat(0x29 /* ) */)) { return true } state.raise("Unterminated group"); } state.pos = start; } return false }; pp$1.regexp_eatCapturingGroup = function(state) { if (state.eat(0x28 /* ( */)) { if (this.options.ecmaVersion >= 9) { this.regexp_groupSpecifier(state); } else if (state.current() === 0x3F /* ? */) { state.raise("Invalid group"); } this.regexp_disjunction(state); if (state.eat(0x29 /* ) */)) { state.numCapturingParens += 1; return true } state.raise("Unterminated group"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom pp$1.regexp_eatExtendedAtom = function(state) { return ( state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state) ) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier pp$1.regexp_eatInvalidBracedQuantifier = function(state) { if (this.regexp_eatBracedQuantifier(state, true)) { state.raise("Nothing to repeat"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter pp$1.regexp_eatSyntaxCharacter = function(state) { var ch = state.current(); if (isSyntaxCharacter(ch)) { state.lastIntValue = ch; state.advance(); return true } return false }; function isSyntaxCharacter(ch) { return ( ch === 0x24 /* $ */ || ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || ch === 0x2E /* . */ || ch === 0x3F /* ? */ || ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || ch >= 0x7B /* { */ && ch <= 0x7D /* } */ ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter // But eat eager. pp$1.regexp_eatPatternCharacters = function(state) { var start = state.pos; var ch = 0; while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { state.advance(); } return state.pos !== start }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter pp$1.regexp_eatExtendedPatternCharacter = function(state) { var ch = state.current(); if ( ch !== -1 && ch !== 0x24 /* $ */ && !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && ch !== 0x2E /* . */ && ch !== 0x3F /* ? */ && ch !== 0x5B /* [ */ && ch !== 0x5E /* ^ */ && ch !== 0x7C /* | */ ) { state.advance(); return true } return false }; // GroupSpecifier :: // [empty] // `?` GroupName pp$1.regexp_groupSpecifier = function(state) { if (state.eat(0x3F /* ? */)) { if (this.regexp_eatGroupName(state)) { if (state.groupNames.indexOf(state.lastStringValue) !== -1) { state.raise("Duplicate capture group name"); } state.groupNames.push(state.lastStringValue); return } state.raise("Invalid group"); } }; // GroupName :: // `<` RegExpIdentifierName `>` // Note: this updates `state.lastStringValue` property with the eaten name. pp$1.regexp_eatGroupName = function(state) { state.lastStringValue = ""; if (state.eat(0x3C /* < */)) { if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { return true } state.raise("Invalid capture group name"); } return false }; // RegExpIdentifierName :: // RegExpIdentifierStart // RegExpIdentifierName RegExpIdentifierPart // Note: this updates `state.lastStringValue` property with the eaten name. pp$1.regexp_eatRegExpIdentifierName = function(state) { state.lastStringValue = ""; if (this.regexp_eatRegExpIdentifierStart(state)) { state.lastStringValue += codePointToString(state.lastIntValue); while (this.regexp_eatRegExpIdentifierPart(state)) { state.lastStringValue += codePointToString(state.lastIntValue); } return true } return false }; // RegExpIdentifierStart :: // UnicodeIDStart // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] pp$1.regexp_eatRegExpIdentifierStart = function(state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierStart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierStart(ch) { return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ } // RegExpIdentifierPart :: // UnicodeIDContinue // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] // // pp$1.regexp_eatRegExpIdentifierPart = function(state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierPart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierPart(ch) { return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape pp$1.regexp_eatAtomEscape = function(state) { if ( this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || (state.switchN && this.regexp_eatKGroupName(state)) ) { return true } if (state.switchU) { // Make the same message as V8. if (state.current() === 0x63 /* c */) { state.raise("Invalid unicode escape"); } state.raise("Invalid escape"); } return false }; pp$1.regexp_eatBackReference = function(state) { var start = state.pos; if (this.regexp_eatDecimalEscape(state)) { var n = state.lastIntValue; if (state.switchU) { // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape if (n > state.maxBackReference) { state.maxBackReference = n; } return true } if (n <= state.numCapturingParens) { return true } state.pos = start; } return false }; pp$1.regexp_eatKGroupName = function(state) { if (state.eat(0x6B /* k */)) { if (this.regexp_eatGroupName(state)) { state.backReferenceNames.push(state.lastStringValue); return true } state.raise("Invalid named reference"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape pp$1.regexp_eatCharacterEscape = function(state) { return ( this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || this.regexp_eatIdentityEscape(state) ) }; pp$1.regexp_eatCControlLetter = function(state) { var start = state.pos; if (state.eat(0x63 /* c */)) { if (this.regexp_eatControlLetter(state)) { return true } state.pos = start; } return false }; pp$1.regexp_eatZero = function(state) { if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { state.lastIntValue = 0; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape pp$1.regexp_eatControlEscape = function(state) { var ch = state.current(); if (ch === 0x74 /* t */) { state.lastIntValue = 0x09; /* \t */ state.advance(); return true } if (ch === 0x6E /* n */) { state.lastIntValue = 0x0A; /* \n */ state.advance(); return true } if (ch === 0x76 /* v */) { state.lastIntValue = 0x0B; /* \v */ state.advance(); return true } if (ch === 0x66 /* f */) { state.lastIntValue = 0x0C; /* \f */ state.advance(); return true } if (ch === 0x72 /* r */) { state.lastIntValue = 0x0D; /* \r */ state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter pp$1.regexp_eatControlLetter = function(state) { var ch = state.current(); if (isControlLetter(ch)) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; function isControlLetter(ch) { return ( (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { if ( forceU === void 0 ) forceU = false; var start = state.pos; var switchU = forceU || state.switchU; if (state.eat(0x75 /* u */)) { if (this.regexp_eatFixedHexDigits(state, 4)) { var lead = state.lastIntValue; if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { var leadSurrogateEnd = state.pos; if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { var trail = state.lastIntValue; if (trail >= 0xDC00 && trail <= 0xDFFF) { state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; return true } } state.pos = leadSurrogateEnd; state.lastIntValue = lead; } return true } if ( switchU && state.eat(0x7B /* { */) && this.regexp_eatHexDigits(state) && state.eat(0x7D /* } */) && isValidUnicode(state.lastIntValue) ) { return true } if (switchU) { state.raise("Invalid unicode escape"); } state.pos = start; } return false }; function isValidUnicode(ch) { return ch >= 0 && ch <= 0x10FFFF } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape pp$1.regexp_eatIdentityEscape = function(state) { if (state.switchU) { if (this.regexp_eatSyntaxCharacter(state)) { return true } if (state.eat(0x2F /* / */)) { state.lastIntValue = 0x2F; /* / */ return true } return false } var ch = state.current(); if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape pp$1.regexp_eatDecimalEscape = function(state) { state.lastIntValue = 0; var ch = state.current(); if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { do { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); state.advance(); } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape pp$1.regexp_eatCharacterClassEscape = function(state) { var ch = state.current(); if (isCharacterClassEscape(ch)) { state.lastIntValue = -1; state.advance(); return true } if ( state.switchU && this.options.ecmaVersion >= 9 && (ch === 0x50 /* P */ || ch === 0x70 /* p */) ) { state.lastIntValue = -1; state.advance(); if ( state.eat(0x7B /* { */) && this.regexp_eatUnicodePropertyValueExpression(state) && state.eat(0x7D /* } */) ) { return true } state.raise("Invalid property name"); } return false }; function isCharacterClassEscape(ch) { return ( ch === 0x64 /* d */ || ch === 0x44 /* D */ || ch === 0x73 /* s */ || ch === 0x53 /* S */ || ch === 0x77 /* w */ || ch === 0x57 /* W */ ) } // UnicodePropertyValueExpression :: // UnicodePropertyName `=` UnicodePropertyValue // LoneUnicodePropertyNameOrValue pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { var start = state.pos; // UnicodePropertyName `=` UnicodePropertyValue if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { var name = state.lastStringValue; if (this.regexp_eatUnicodePropertyValue(state)) { var value = state.lastStringValue; this.regexp_validateUnicodePropertyNameAndValue(state, name, value); return true } } state.pos = start; // LoneUnicodePropertyNameOrValue if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { var nameOrValue = state.lastStringValue; this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); return true } return false }; pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { if (!hasOwn(state.unicodeProperties.nonBinary, name)) { state.raise("Invalid property name"); } if (!state.unicodeProperties.nonBinary[name].test(value)) { state.raise("Invalid property value"); } }; pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { if (!state.unicodeProperties.binary.test(nameOrValue)) { state.raise("Invalid property name"); } }; // UnicodePropertyName :: // UnicodePropertyNameCharacters pp$1.regexp_eatUnicodePropertyName = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyNameCharacter(ch = state.current())) { state.lastStringValue += codePointToString(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyNameCharacter(ch) { return isControlLetter(ch) || ch === 0x5F /* _ */ } // UnicodePropertyValue :: // UnicodePropertyValueCharacters pp$1.regexp_eatUnicodePropertyValue = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyValueCharacter(ch = state.current())) { state.lastStringValue += codePointToString(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyValueCharacter(ch) { return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) } // LoneUnicodePropertyNameOrValue :: // UnicodePropertyValueCharacters pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { return this.regexp_eatUnicodePropertyValue(state) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass pp$1.regexp_eatCharacterClass = function(state) { if (state.eat(0x5B /* [ */)) { state.eat(0x5E /* ^ */); this.regexp_classRanges(state); if (state.eat(0x5D /* ] */)) { return true } // Unreachable since it threw "unterminated regular expression" error before. state.raise("Unterminated character class"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash pp$1.regexp_classRanges = function(state) { while (this.regexp_eatClassAtom(state)) { var left = state.lastIntValue; if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { var right = state.lastIntValue; if (state.switchU && (left === -1 || right === -1)) { state.raise("Invalid character class"); } if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class"); } } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash pp$1.regexp_eatClassAtom = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if (this.regexp_eatClassEscape(state)) { return true } if (state.switchU) { // Make the same message as V8. var ch$1 = state.current(); if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { state.raise("Invalid class escape"); } state.raise("Invalid escape"); } state.pos = start; } var ch = state.current(); if (ch !== 0x5D /* ] */) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape pp$1.regexp_eatClassEscape = function(state) { var start = state.pos; if (state.eat(0x62 /* b */)) { state.lastIntValue = 0x08; /* */ return true } if (state.switchU && state.eat(0x2D /* - */)) { state.lastIntValue = 0x2D; /* - */ return true } if (!state.switchU && state.eat(0x63 /* c */)) { if (this.regexp_eatClassControlLetter(state)) { return true } state.pos = start; } return ( this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) ) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter pp$1.regexp_eatClassControlLetter = function(state) { var ch = state.current(); if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp$1.regexp_eatHexEscapeSequence = function(state) { var start = state.pos; if (state.eat(0x78 /* x */)) { if (this.regexp_eatFixedHexDigits(state, 2)) { return true } if (state.switchU) { state.raise("Invalid escape"); } state.pos = start; } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits pp$1.regexp_eatDecimalDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isDecimalDigit(ch = state.current())) { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); state.advance(); } return state.pos !== start }; function isDecimalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits pp$1.regexp_eatHexDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isHexDigit(ch = state.current())) { state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return state.pos !== start }; function isHexDigit(ch) { return ( (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) ) } function hexToInt(ch) { if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { return 10 + (ch - 0x41 /* A */) } if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { return 10 + (ch - 0x61 /* a */) } return ch - 0x30 /* 0 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence // Allows only 0-377(octal) i.e. 0-255(decimal). pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { if (this.regexp_eatOctalDigit(state)) { var n1 = state.lastIntValue; if (this.regexp_eatOctalDigit(state)) { var n2 = state.lastIntValue; if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; } else { state.lastIntValue = n1 * 8 + n2; } } else { state.lastIntValue = n1; } return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit pp$1.regexp_eatOctalDigit = function(state) { var ch = state.current(); if (isOctalDigit(ch)) { state.lastIntValue = ch - 0x30; /* 0 */ state.advance(); return true } state.lastIntValue = 0; return false }; function isOctalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp$1.regexp_eatFixedHexDigits = function(state, length) { var start = state.pos; state.lastIntValue = 0; for (var i = 0; i < length; ++i) { var ch = state.current(); if (!isHexDigit(ch)) { state.pos = start; return false } state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return true }; // Object type used to represent tokens. Note that normally, tokens // simply exist as properties on the parser object. This is only // used for the onToken callback and the external tokenizer. var Token = function Token(p) { this.type = p.type; this.value = p.value; this.start = p.start; this.end = p.end; if (p.options.locations) { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } if (p.options.ranges) { this.range = [p.start, p.end]; } }; // ## Tokenizer var pp = Parser$1.prototype; // Move to the next token pp.next = function(ignoreEscapeSequenceInKeyword) { if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } if (this.options.onToken) { this.options.onToken(new Token(this)); } this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); }; pp.getToken = function() { this.next(); return new Token(this) }; // If we're in an ES6 environment, make parsers iterable if (typeof Symbol !== "undefined") { pp[Symbol.iterator] = function() { var this$1$1 = this; return { next: function () { var token = this$1$1.getToken(); return { done: token.type === types$1.eof, value: token } } } }; } // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). // Read a single token, updating the parser object's token-related // properties. pp.nextToken = function() { var curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } this.start = this.pos; if (this.options.locations) { this.startLoc = this.curPosition(); } if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) } if (curContext.override) { return curContext.override(this) } else { this.readToken(this.fullCharCodeAtPos()); } }; pp.readToken = function(code) { // Identifier or keyword. '\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) { return this.readWord() } return this.getTokenFromCode(code) }; pp.fullCharCodeAtPos = function() { var code = this.input.charCodeAt(this.pos); if (code <= 0xd7ff || code >= 0xdc00) { return code } var next = this.input.charCodeAt(this.pos + 1); return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 }; pp.skipBlockComment = function() { var startLoc = this.options.onComment && this.curPosition(); var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } this.pos = end + 2; if (this.options.locations) { for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) { ++this.curLine; pos = this.lineStart = nextBreak; } } if (this.options.onComment) { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition()); } }; pp.skipLineComment = function(startSkip) { var start = this.pos; var startLoc = this.options.onComment && this.curPosition(); var ch = this.input.charCodeAt(this.pos += startSkip); while (this.pos < this.input.length && !isNewLine(ch)) { ch = this.input.charCodeAt(++this.pos); } if (this.options.onComment) { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()); } }; // Called at the start of the parse and after every token. Skips // whitespace and comments, and. pp.skipSpace = function() { loop: while (this.pos < this.input.length) { var ch = this.input.charCodeAt(this.pos); switch (ch) { case 32: case 160: // ' ' ++this.pos; break case 13: if (this.input.charCodeAt(this.pos + 1) === 10) { ++this.pos; } case 10: case 8232: case 8233: ++this.pos; if (this.options.locations) { ++this.curLine; this.lineStart = this.pos; } break case 47: // '/' switch (this.input.charCodeAt(this.pos + 1)) { case 42: // '*' this.skipBlockComment(); break case 47: this.skipLineComment(2); break default: break loop } break default: if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { ++this.pos; } else { break loop } } } }; // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. pp.finishToken = function(type, val) { this.end = this.pos; if (this.options.locations) { this.endLoc = this.curPosition(); } var prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); }; // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // // All in the name of speed. // pp.readToken_dot = function() { var next = this.input.charCodeAt(this.pos + 1); if (next >= 48 && next <= 57) { return this.readNumber(true) } var next2 = this.input.charCodeAt(this.pos + 2); if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' this.pos += 3; return this.finishToken(types$1.ellipsis) } else { ++this.pos; return this.finishToken(types$1.dot) } }; pp.readToken_slash = function() { // '/' var next = this.input.charCodeAt(this.pos + 1); if (this.exprAllowed) { ++this.pos; return this.readRegexp() } if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(types$1.slash, 1) }; pp.readToken_mult_modulo_exp = function(code) { // '%*' var next = this.input.charCodeAt(this.pos + 1); var size = 1; var tokentype = code === 42 ? types$1.star : types$1.modulo; // exponentiation operator ** and **= if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { ++size; tokentype = types$1.starstar; next = this.input.charCodeAt(this.pos + 2); } if (next === 61) { return this.finishOp(types$1.assign, size + 1) } return this.finishOp(tokentype, size) }; pp.readToken_pipe_amp = function(code) { // '|&' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (this.options.ecmaVersion >= 12) { var next2 = this.input.charCodeAt(this.pos + 2); if (next2 === 61) { return this.finishOp(types$1.assign, 3) } } return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2) } if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1) }; pp.readToken_caret = function() { // '^' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(types$1.bitwiseXOR, 1) }; pp.readToken_plus_min = function(code) { // '+-' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { // A `-->` line comment this.skipLineComment(3); this.skipSpace(); return this.nextToken() } return this.finishOp(types$1.incDec, 2) } if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(types$1.plusMin, 1) }; pp.readToken_lt_gt = function(code) { // '<>' var next = this.input.charCodeAt(this.pos + 1); var size = 1; if (next === code) { size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } return this.finishOp(types$1.bitShift, size) } if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { // `/gs; const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const contextRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; function esbuildScanPlugin(config, container, depImports, missing, entries) { const seen = new Map(); const resolve = async (id, importer, options) => { const key = id + (importer && path$o.dirname(importer)); if (seen.has(key)) { return seen.get(key); } const resolved = await container.resolveId(id, importer && normalizePath$3(importer), { ...options, scan: true, }); const res = resolved?.id; seen.set(key, res); return res; }; const include = config.optimizeDeps?.include; const exclude = [ ...(config.optimizeDeps?.exclude || []), '@vite/client', '@vite/env', ]; const externalUnlessEntry = ({ path }) => ({ path, external: !entries.includes(path), }); const doTransformGlobImport = async (contents, id, loader) => { let transpiledContents; // transpile because `transformGlobImport` only expects js if (loader !== 'js') { transpiledContents = (await transform$2(contents, { loader })).code; } else { transpiledContents = contents; } const result = await transformGlobImport(transpiledContents, id, config.root, resolve, config.isProduction); return result?.s.toString() || transpiledContents; }; return { name: 'vite:dep-scan', setup(build) { const scripts = {}; // external urls build.onResolve({ filter: externalRE }, ({ path }) => ({ path, external: true, })); // data urls build.onResolve({ filter: dataUrlRE }, ({ path }) => ({ path, external: true, })); // local scripts (``); }; await traverseHtml(html, filename, (node) => { if (!nodeIsElement(node)) { return; } // script tags if (node.nodeName === 'script') { const { src, sourceCodeLocation, isModule } = getScriptInfo(node); if (src) { processNodeUrl(src, sourceCodeLocation, s, config, htmlPath, originalUrl, moduleGraph); } else if (isModule && node.childNodes.length) { addInlineModule(node, 'js'); } } if (node.nodeName === 'style' && node.childNodes.length) { const children = node.childNodes[0]; styleUrl.push({ start: children.sourceCodeLocation.startOffset, end: children.sourceCodeLocation.endOffset, code: children.value, }); } // elements with [href/src] attrs const assetAttrs = assetAttrsConfig[node.nodeName]; if (assetAttrs) { for (const p of node.attrs) { const attrKey = getAttrKey(p); if (p.value && assetAttrs.includes(attrKey)) { processNodeUrl(p, node.sourceCodeLocation.attrs[attrKey], s, config, htmlPath, originalUrl); } } } }); await Promise.all(styleUrl.map(async ({ start, end, code }, index) => { const url = `${proxyModulePath}?html-proxy&direct&index=${index}.css`; // ensure module in graph after successful load const mod = await moduleGraph.ensureEntryFromUrl(url, false); ensureWatchedFile(watcher, mod.file, config.root); const result = await server.pluginContainer.transform(code, mod.id); s.overwrite(start, end, result?.code || ''); })); html = s.toString(); return { html, tags: [ { tag: 'script', attrs: { type: 'module', src: path$o.posix.join(base, CLIENT_PUBLIC_PATH), }, injectTo: 'head-prepend', }, ], }; }; function indexHtmlMiddleware(server) { // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` return async function viteIndexHtmlMiddleware(req, res, next) { if (res.writableEnded) { return next(); } const url = req.url && cleanUrl(req.url); // htmlFallbackMiddleware appends '.html' to URLs if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') { const filename = getHtmlFilename(url, server); if (fs$l.existsSync(filename)) { try { let html = fs$l.readFileSync(filename, 'utf-8'); html = await server.transformIndexHtml(url, html, req.originalUrl); return send$1(req, res, html, 'html', { headers: server.config.server.headers, }); } catch (e) { return next(e); } } } next(); }; } const logTime = createDebugger('vite:time'); function timeMiddleware(root) { // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` return function viteTimeMiddleware(req, res, next) { const start = performance.now(); const end = res.end; res.end = (...args) => { logTime(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`); return end.call(res, ...args); }; next(); }; } class ModuleNode { /** * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870 */ constructor(url, setIsSelfAccepting = true) { /** * Resolved file system path + query */ this.id = null; this.file = null; this.importers = new Set(); this.importedModules = new Set(); this.acceptedHmrDeps = new Set(); this.acceptedHmrExports = null; this.importedBindings = null; this.transformResult = null; this.ssrTransformResult = null; this.ssrModule = null; this.ssrError = null; this.lastHMRTimestamp = 0; this.lastInvalidationTimestamp = 0; this.url = url; this.type = isDirectCSSRequest(url) ? 'css' : 'js'; if (setIsSelfAccepting) { this.isSelfAccepting = false; } } } class ModuleGraph { constructor(resolveId) { this.resolveId = resolveId; this.urlToModuleMap = new Map(); this.idToModuleMap = new Map(); // a single file may corresponds to multiple modules with different queries this.fileToModulesMap = new Map(); this.safeModulesPath = new Set(); } async getModuleByUrl(rawUrl, ssr) { const [url] = await this.resolveUrl(rawUrl, ssr); return this.urlToModuleMap.get(url); } getModuleById(id) { return this.idToModuleMap.get(removeTimestampQuery(id)); } getModulesByFile(file) { return this.fileToModulesMap.get(file); } onFileChange(file) { const mods = this.getModulesByFile(file); if (mods) { const seen = new Set(); mods.forEach((mod) => { this.invalidateModule(mod, seen); }); } } invalidateModule(mod, seen = new Set(), timestamp = Date.now(), isHmr = false) { if (seen.has(mod)) { return; } seen.add(mod); if (isHmr) { mod.lastHMRTimestamp = timestamp; } else { // Save the timestamp for this invalidation, so we can avoid caching the result of possible already started // processing being done for this module mod.lastInvalidationTimestamp = timestamp; } // Don't invalidate mod.info and mod.meta, as they are part of the processing pipeline // Invalidating the transform result is enough to ensure this module is re-processed next time it is requested mod.transformResult = null; mod.ssrTransformResult = null; mod.ssrModule = null; mod.ssrError = null; mod.importers.forEach((importer) => { if (!importer.acceptedHmrDeps.has(mod)) { this.invalidateModule(importer, seen, timestamp, isHmr); } }); } invalidateAll() { const timestamp = Date.now(); const seen = new Set(); this.idToModuleMap.forEach((mod) => { this.invalidateModule(mod, seen, timestamp); }); } /** * Update the module graph based on a module's updated imports information * If there are dependencies that no longer have any importers, they are * returned as a Set. */ async updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, ssr) { mod.isSelfAccepting = isSelfAccepting; const prevImports = mod.importedModules; const nextImports = (mod.importedModules = new Set()); let noLongerImported; // update import graph for (const imported of importedModules) { const dep = typeof imported === 'string' ? await this.ensureEntryFromUrl(imported, ssr) : imported; dep.importers.add(mod); nextImports.add(dep); } // remove the importer from deps that were imported but no longer are. prevImports.forEach((dep) => { if (!nextImports.has(dep)) { dep.importers.delete(mod); if (!dep.importers.size) { (noLongerImported || (noLongerImported = new Set())).add(dep); } } }); // update accepted hmr deps const deps = (mod.acceptedHmrDeps = new Set()); for (const accepted of acceptedModules) { const dep = typeof accepted === 'string' ? await this.ensureEntryFromUrl(accepted, ssr) : accepted; deps.add(dep); } // update accepted hmr exports mod.acceptedHmrExports = acceptedExports; mod.importedBindings = importedBindings; return noLongerImported; } async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) { const [url, resolvedId, meta] = await this.resolveUrl(rawUrl, ssr); let mod = this.idToModuleMap.get(resolvedId); if (!mod) { mod = new ModuleNode(url, setIsSelfAccepting); if (meta) mod.meta = meta; this.urlToModuleMap.set(url, mod); mod.id = resolvedId; this.idToModuleMap.set(resolvedId, mod); const file = (mod.file = cleanUrl(resolvedId)); let fileMappedModules = this.fileToModulesMap.get(file); if (!fileMappedModules) { fileMappedModules = new Set(); this.fileToModulesMap.set(file, fileMappedModules); } fileMappedModules.add(mod); } // multiple urls can map to the same module and id, make sure we register // the url to the existing module in that case else if (!this.urlToModuleMap.has(url)) { this.urlToModuleMap.set(url, mod); } return mod; } // some deps, like a css file referenced via @import, don't have its own // url because they are inlined into the main css import. But they still // need to be represented in the module graph so that they can trigger // hmr in the importing css file. createFileOnlyEntry(file) { file = normalizePath$3(file); let fileMappedModules = this.fileToModulesMap.get(file); if (!fileMappedModules) { fileMappedModules = new Set(); this.fileToModulesMap.set(file, fileMappedModules); } const url = `${FS_PREFIX}${file}`; for (const m of fileMappedModules) { if (m.url === url || m.id === file) { return m; } } const mod = new ModuleNode(url); mod.file = file; fileMappedModules.add(mod); return mod; } // for incoming urls, it is important to: // 1. remove the HMR timestamp query (?t=xxxx) // 2. resolve its extension so that urls with or without extension all map to // the same module async resolveUrl(url, ssr) { url = removeImportQuery(removeTimestampQuery(url)); const resolved = await this.resolveId(url, !!ssr); const resolvedId = resolved?.id || url; if (url !== resolvedId && !url.includes('\0') && !url.startsWith(`virtual:`)) { const ext = extname$1(cleanUrl(resolvedId)); const { pathname, search, hash } = new URL(url, 'relative://'); if (ext && !pathname.endsWith(ext)) { url = pathname + ext + search + hash; } } return [url, resolvedId, resolved?.meta]; } } var isWslExports = {}; var isWsl$2 = { get exports(){ return isWslExports; }, set exports(v){ isWslExports = v; }, }; const fs$3 = require$$0__default; let isDocker$2; function hasDockerEnv() { try { fs$3.statSync('/.dockerenv'); return true; } catch (_) { return false; } } function hasDockerCGroup() { try { return fs$3.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); } catch (_) { return false; } } var isDocker_1 = () => { if (isDocker$2 === undefined) { isDocker$2 = hasDockerEnv() || hasDockerCGroup(); } return isDocker$2; }; const os = require$$2; const fs$2 = require$$0__default; const isDocker$1 = isDocker_1; const isWsl$1 = () => { if (process.platform !== 'linux') { return false; } if (os.release().toLowerCase().includes('microsoft')) { if (isDocker$1()) { return false; } return true; } try { return fs$2.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? !isDocker$1() : false; } catch (_) { return false; } }; if (process.env.__IS_WSL_TEST__) { isWsl$2.exports = isWsl$1; } else { isWsl$2.exports = isWsl$1(); } var defineLazyProp = (object, propertyName, fn) => { const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true}); Object.defineProperty(object, propertyName, { configurable: true, enumerable: true, get() { const result = fn(); define(result); return result; }, set(value) { define(value); } }); return object; }; const path$3 = require$$0$4; const childProcess = require$$2$1; const {promises: fs$1, constants: fsConstants} = require$$0__default; const isWsl = isWslExports; const isDocker = isDocker_1; const defineLazyProperty = defineLazyProp; // Path to included `xdg-open`. const localXdgOpenPath = path$3.join(__dirname, 'xdg-open'); const {platform, arch} = process; // Podman detection const hasContainerEnv = () => { try { fs$1.statSync('/run/.containerenv'); return true; } catch { return false; } }; let cachedResult; function isInsideContainer() { if (cachedResult === undefined) { cachedResult = hasContainerEnv() || isDocker(); } return cachedResult; } /** Get the mount point for fixed drives in WSL. @inner @returns {string} The mount point. */ const getWslDrivesMountPoint = (() => { // Default value for "root" param // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config const defaultMountPoint = '/mnt/'; let mountPoint; return async function () { if (mountPoint) { // Return memoized mount point value return mountPoint; } const configFilePath = '/etc/wsl.conf'; let isConfigFileExists = false; try { await fs$1.access(configFilePath, fsConstants.F_OK); isConfigFileExists = true; } catch {} if (!isConfigFileExists) { return defaultMountPoint; } const configContent = await fs$1.readFile(configFilePath, {encoding: 'utf8'}); const configMountPoint = /(?.*)/g.exec(configContent); if (!configMountPoint) { return defaultMountPoint; } mountPoint = configMountPoint.groups.mountPoint.trim(); mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`; return mountPoint; }; })(); const pTryEach = async (array, mapper) => { let latestError; for (const item of array) { try { return await mapper(item); // eslint-disable-line no-await-in-loop } catch (error) { latestError = error; } } throw latestError; }; const baseOpen = async options => { options = { wait: false, background: false, newInstance: false, allowNonzeroExitCode: false, ...options }; if (Array.isArray(options.app)) { return pTryEach(options.app, singleApp => baseOpen({ ...options, app: singleApp })); } let {name: app, arguments: appArguments = []} = options.app || {}; appArguments = [...appArguments]; if (Array.isArray(app)) { return pTryEach(app, appName => baseOpen({ ...options, app: { name: appName, arguments: appArguments } })); } let command; const cliArguments = []; const childProcessOptions = {}; if (platform === 'darwin') { command = 'open'; if (options.wait) { cliArguments.push('--wait-apps'); } if (options.background) { cliArguments.push('--background'); } if (options.newInstance) { cliArguments.push('--new'); } if (app) { cliArguments.push('-a', app); } } else if (platform === 'win32' || (isWsl && !isInsideContainer() && !app)) { const mountPoint = await getWslDrivesMountPoint(); command = isWsl ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; cliArguments.push( '-NoProfile', '-NonInteractive', '–ExecutionPolicy', 'Bypass', '-EncodedCommand' ); if (!isWsl) { childProcessOptions.windowsVerbatimArguments = true; } const encodedArguments = ['Start']; if (options.wait) { encodedArguments.push('-Wait'); } if (app) { // Double quote with double quotes to ensure the inner quotes are passed through. // Inner quotes are delimited for PowerShell interpretation with backticks. encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList'); if (options.target) { appArguments.unshift(options.target); } } else if (options.target) { encodedArguments.push(`"${options.target}"`); } if (appArguments.length > 0) { appArguments = appArguments.map(arg => `"\`"${arg}\`""`); encodedArguments.push(appArguments.join(',')); } // Using Base64-encoded command, accepted by PowerShell, to allow special characters. options.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64'); } else { if (app) { command = app; } else { // When bundled by Webpack, there's no actual package file path and no local `xdg-open`. const isBundled = !__dirname || __dirname === '/'; // Check if local `xdg-open` exists and is executable. let exeLocalXdgOpen = false; try { await fs$1.access(localXdgOpenPath, fsConstants.X_OK); exeLocalXdgOpen = true; } catch {} const useSystemXdgOpen = process.versions.electron || platform === 'android' || isBundled || !exeLocalXdgOpen; command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath; } if (appArguments.length > 0) { cliArguments.push(...appArguments); } if (!options.wait) { // `xdg-open` will block the process unless stdio is ignored // and it's detached from the parent even if it's unref'd. childProcessOptions.stdio = 'ignore'; childProcessOptions.detached = true; } } if (options.target) { cliArguments.push(options.target); } if (platform === 'darwin' && appArguments.length > 0) { cliArguments.push('--args', ...appArguments); } const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions); if (options.wait) { return new Promise((resolve, reject) => { subprocess.once('error', reject); subprocess.once('close', exitCode => { if (!options.allowNonzeroExitCode && exitCode > 0) { reject(new Error(`Exited with code ${exitCode}`)); return; } resolve(subprocess); }); }); } subprocess.unref(); return subprocess; }; const open = (target, options) => { if (typeof target !== 'string') { throw new TypeError('Expected a `target`'); } return baseOpen({ ...options, target }); }; const openApp = (name, options) => { if (typeof name !== 'string') { throw new TypeError('Expected a `name`'); } const {arguments: appArguments = []} = options || {}; if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) { throw new TypeError('Expected `appArguments` as Array type'); } return baseOpen({ ...options, app: { name, arguments: appArguments } }); }; function detectArchBinary(binary) { if (typeof binary === 'string' || Array.isArray(binary)) { return binary; } const {[arch]: archBinary} = binary; if (!archBinary) { throw new Error(`${arch} is not supported`); } return archBinary; } function detectPlatformBinary({[platform]: platformBinary}, {wsl}) { if (wsl && isWsl) { return detectArchBinary(wsl); } if (!platformBinary) { throw new Error(`${platform} is not supported`); } return detectArchBinary(platformBinary); } const apps = {}; defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({ darwin: 'google chrome', win32: 'chrome', linux: ['google-chrome', 'google-chrome-stable', 'chromium'] }, { wsl: { ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe', x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'] } })); defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({ darwin: 'firefox', win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe', linux: 'firefox' }, { wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe' })); defineLazyProperty(apps, 'edge', () => detectPlatformBinary({ darwin: 'microsoft edge', win32: 'msedge', linux: ['microsoft-edge', 'microsoft-edge-dev'] }, { wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe' })); open.apps = apps; open.openApp = openApp; var open_1 = open; var crossSpawnExports = {}; var crossSpawn = { get exports(){ return crossSpawnExports; }, set exports(v){ crossSpawnExports = v; }, }; var windows; var hasRequiredWindows; function requireWindows () { if (hasRequiredWindows) return windows; hasRequiredWindows = 1; windows = isexe; isexe.sync = sync; var fs = require$$0__default; function checkPathExt (path, options) { var pathext = options.pathExt !== undefined ? options.pathExt : process.env.PATHEXT; if (!pathext) { return true } pathext = pathext.split(';'); if (pathext.indexOf('') !== -1) { return true } for (var i = 0; i < pathext.length; i++) { var p = pathext[i].toLowerCase(); if (p && path.substr(-p.length).toLowerCase() === p) { return true } } return false } function checkStat (stat, path, options) { if (!stat.isSymbolicLink() && !stat.isFile()) { return false } return checkPathExt(path, options) } function isexe (path, options, cb) { fs.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, path, options)); }); } function sync (path, options) { return checkStat(fs.statSync(path), path, options) } return windows; } var mode; var hasRequiredMode; function requireMode () { if (hasRequiredMode) return mode; hasRequiredMode = 1; mode = isexe; isexe.sync = sync; var fs = require$$0__default; function isexe (path, options, cb) { fs.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, options)); }); } function sync (path, options) { return checkStat(fs.statSync(path), options) } function checkStat (stat, options) { return stat.isFile() && checkMode(stat, options) } function checkMode (stat, options) { var mod = stat.mode; var uid = stat.uid; var gid = stat.gid; var myUid = options.uid !== undefined ? options.uid : process.getuid && process.getuid(); var myGid = options.gid !== undefined ? options.gid : process.getgid && process.getgid(); var u = parseInt('100', 8); var g = parseInt('010', 8); var o = parseInt('001', 8); var ug = u | g; var ret = (mod & o) || (mod & g) && gid === myGid || (mod & u) && uid === myUid || (mod & ug) && myUid === 0; return ret } return mode; } var core; if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) { core = requireWindows(); } else { core = requireMode(); } var isexe_1 = isexe$1; isexe$1.sync = sync; function isexe$1 (path, options, cb) { if (typeof options === 'function') { cb = options; options = {}; } if (!cb) { if (typeof Promise !== 'function') { throw new TypeError('callback not provided') } return new Promise(function (resolve, reject) { isexe$1(path, options || {}, function (er, is) { if (er) { reject(er); } else { resolve(is); } }); }) } core(path, options || {}, function (er, is) { // ignore EACCES because that just means we aren't allowed to run it if (er) { if (er.code === 'EACCES' || options && options.ignoreErrors) { er = null; is = false; } } cb(er, is); }); } function sync (path, options) { // my kingdom for a filtered catch try { return core.sync(path, options || {}) } catch (er) { if (options && options.ignoreErrors || er.code === 'EACCES') { return false } else { throw er } } } const isWindows = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys'; const path$2 = require$$0$4; const COLON = isWindows ? ';' : ':'; const isexe = isexe_1; const getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); const getPathInfo = (cmd, opt) => { const colon = opt.colon || COLON; // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ); const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : ''; const pathExt = isWindows ? pathExtExe.split(colon) : ['']; if (isWindows) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift(''); } return { pathEnv, pathExt, pathExtExe, } }; const which$1 = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt; opt = {}; } if (!opt) opt = {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); const found = []; const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)) const ppRaw = pathEnv[i]; const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; const pCmd = path$2.join(pathPart, cmd); const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; resolve(subStep(p, i, 0)); }); const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)) const ext = pathExt[ii]; isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext); else return resolve(p + ext) } return resolve(subStep(p, i, ii + 1)) }); }); return cb ? step(0).then(res => cb(null, res), cb) : step(0) }; const whichSync = (cmd, opt) => { opt = opt || {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); const found = []; for (let i = 0; i < pathEnv.length; i ++) { const ppRaw = pathEnv[i]; const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; const pCmd = path$2.join(pathPart, cmd); const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; for (let j = 0; j < pathExt.length; j ++) { const cur = p + pathExt[j]; try { const is = isexe.sync(cur, { pathExt: pathExtExe }); if (is) { if (opt.all) found.push(cur); else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError(cmd) }; var which_1 = which$1; which$1.sync = whichSync; var pathKeyExports = {}; var pathKey$1 = { get exports(){ return pathKeyExports; }, set exports(v){ pathKeyExports = v; }, }; const pathKey = (options = {}) => { const environment = options.env || process.env; const platform = options.platform || process.platform; if (platform !== 'win32') { return 'PATH'; } return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; }; pathKey$1.exports = pathKey; // TODO: Remove this for the next major release pathKeyExports.default = pathKey; const path$1 = require$$0$4; const which = which_1; const getPathKey = pathKeyExports; function resolveCommandAttempt(parsed, withoutPathExt) { const env = parsed.options.env || process.env; const cwd = process.cwd(); const hasCustomCwd = parsed.options.cwd != null; // Worker threads do not have process.chdir() const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; // If a custom `cwd` was specified, we need to change the process cwd // because `which` will do stat calls but does not support a custom cwd if (shouldSwitchCwd) { try { process.chdir(parsed.options.cwd); } catch (err) { /* Empty */ } } let resolved; try { resolved = which.sync(parsed.command, { path: env[getPathKey({ env })], pathExt: withoutPathExt ? path$1.delimiter : undefined, }); } catch (e) { /* Empty */ } finally { if (shouldSwitchCwd) { process.chdir(cwd); } } // If we successfully resolved, ensure that an absolute path is returned // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it if (resolved) { resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); } return resolved; } function resolveCommand$1(parsed) { return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); } var resolveCommand_1 = resolveCommand$1; var _escape = {}; // See http://www.robvanderwoude.com/escapechars.php const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; function escapeCommand(arg) { // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); return arg; } function escapeArgument(arg, doubleEscapeMetaChars) { // Convert to string arg = `${arg}`; // Algorithm below is based on https://qntm.org/cmd // Sequence of backslashes followed by a double quote: // double up all the backslashes and escape the double quote arg = arg.replace(/(\\*)"/g, '$1$1\\"'); // Sequence of backslashes followed by the end of the string // (which will become a double quote later): // double up all the backslashes arg = arg.replace(/(\\*)$/, '$1$1'); // All other backslashes occur literally // Quote the whole thing: arg = `"${arg}"`; // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); // Double escape meta chars if necessary if (doubleEscapeMetaChars) { arg = arg.replace(metaCharsRegExp, '^$1'); } return arg; } _escape.command = escapeCommand; _escape.argument = escapeArgument; var shebangRegex$1 = /^#!(.*)/; const shebangRegex = shebangRegex$1; var shebangCommand$1 = (string = '') => { const match = string.match(shebangRegex); if (!match) { return null; } const [path, argument] = match[0].replace(/#! ?/, '').split(' '); const binary = path.split('/').pop(); if (binary === 'env') { return argument; } return argument ? `${binary} ${argument}` : binary; }; const fs = require$$0__default; const shebangCommand = shebangCommand$1; function readShebang$1(command) { // Read the first 150 bytes from the file const size = 150; const buffer = Buffer.alloc(size); let fd; try { fd = fs.openSync(command, 'r'); fs.readSync(fd, buffer, 0, size, 0); fs.closeSync(fd); } catch (e) { /* Empty */ } // Attempt to extract shebang (null is returned if not a shebang) return shebangCommand(buffer.toString()); } var readShebang_1 = readShebang$1; const path = require$$0$4; const resolveCommand = resolveCommand_1; const escape$1 = _escape; const readShebang = readShebang_1; const isWin$1 = process.platform === 'win32'; const isExecutableRegExp = /\.(?:com|exe)$/i; const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; function detectShebang(parsed) { parsed.file = resolveCommand(parsed); const shebang = parsed.file && readShebang(parsed.file); if (shebang) { parsed.args.unshift(parsed.file); parsed.command = shebang; return resolveCommand(parsed); } return parsed.file; } function parseNonShell(parsed) { if (!isWin$1) { return parsed; } // Detect & add support for shebangs const commandFile = detectShebang(parsed); // We don't need a shell if the command filename is an executable const needsShell = !isExecutableRegExp.test(commandFile); // If a shell is required, use cmd.exe and take care of escaping everything correctly // Note that `forceShell` is an hidden option used only in tests if (parsed.options.forceShell || needsShell) { // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, // we need to double escape them const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) // This is necessary otherwise it will always fail with ENOENT in those cases parsed.command = path.normalize(parsed.command); // Escape command & arguments parsed.command = escape$1.command(parsed.command); parsed.args = parsed.args.map((arg) => escape$1.argument(arg, needsDoubleEscapeMetaChars)); const shellCommand = [parsed.command].concat(parsed.args).join(' '); parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; parsed.command = process.env.comspec || 'cmd.exe'; parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped } return parsed; } function parse$1(command, args, options) { // Normalize arguments, similar to nodejs if (args && !Array.isArray(args)) { options = args; args = null; } args = args ? args.slice(0) : []; // Clone array to avoid changing the original options = Object.assign({}, options); // Clone object to avoid changing the original // Build our parsed object const parsed = { command, args, options, file: undefined, original: { command, args, }, }; // Delegate further parsing to shell or non-shell return options.shell ? parsed : parseNonShell(parsed); } var parse_1 = parse$1; const isWin = process.platform === 'win32'; function notFoundError(original, syscall) { return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { code: 'ENOENT', errno: 'ENOENT', syscall: `${syscall} ${original.command}`, path: original.command, spawnargs: original.args, }); } function hookChildProcess(cp, parsed) { if (!isWin) { return; } const originalEmit = cp.emit; cp.emit = function (name, arg1) { // If emitting "exit" event and exit code is 1, we need to check if // the command exists and emit an "error" instead // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 if (name === 'exit') { const err = verifyENOENT(arg1, parsed); if (err) { return originalEmit.call(cp, 'error', err); } } return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params }; } function verifyENOENT(status, parsed) { if (isWin && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawn'); } return null; } function verifyENOENTSync(status, parsed) { if (isWin && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawnSync'); } return null; } var enoent$1 = { hookChildProcess, verifyENOENT, verifyENOENTSync, notFoundError, }; const cp = require$$2$1; const parse = parse_1; const enoent = enoent$1; function spawn(command, args, options) { // Parse the arguments const parsed = parse(command, args, options); // Spawn the child process const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); // Hook into child process "exit" event to emit an error if the command // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 enoent.hookChildProcess(spawned, parsed); return spawned; } function spawnSync(command, args, options) { // Parse the arguments const parsed = parse(command, args, options); // Spawn the child process const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); return result; } crossSpawn.exports = spawn; crossSpawnExports.spawn = spawn; crossSpawnExports.sync = spawnSync; crossSpawnExports._parse = parse; crossSpawnExports._enoent = enoent; /** * The following is modified based on source found in * https://github.com/facebook/create-react-app * * MIT Licensed * Copyright (c) 2015-present, Facebook, Inc. * https://github.com/facebook/create-react-app/blob/master/LICENSE * */ /** * Reads the BROWSER environment variable and decides what to do with it. * Returns true if it opened a browser or ran a node.js script, otherwise false. */ function openBrowser(url, opt, logger) { // The browser executable to open. // See https://github.com/sindresorhus/open#app for documentation. const browser = typeof opt === 'string' ? opt : process.env.BROWSER || ''; if (browser.toLowerCase().endsWith('.js')) { return executeNodeScript(browser, url, logger); } else if (browser.toLowerCase() !== 'none') { const browserArgs = process.env.BROWSER_ARGS ? process.env.BROWSER_ARGS.split(' ') : []; return startBrowserProcess(browser, browserArgs, url); } return false; } function executeNodeScript(scriptPath, url, logger) { const extraArgs = process.argv.slice(2); const child = crossSpawnExports(process.execPath, [scriptPath, ...extraArgs, url], { stdio: 'inherit', }); child.on('close', (code) => { if (code !== 0) { logger.error(picocolorsExports.red(`\nThe script specified as BROWSER environment variable failed.\n\n${picocolorsExports.cyan(scriptPath)} exited with code ${code}.`), { error: null }); } }); return true; } const supportedChromiumBrowsers = [ 'Google Chrome Canary', 'Google Chrome Dev', 'Google Chrome Beta', 'Google Chrome', 'Microsoft Edge', 'Brave Browser', 'Vivaldi', 'Chromium', ]; function startBrowserProcess(browser, browserArgs, url) { // If we're on OS X, the user hasn't specifically // requested a different browser, we can try opening // a Chromium browser with AppleScript. This lets us reuse an // existing tab when possible instead of creating a new one. const preferredOSXBrowser = browser === 'google chrome' ? 'Google Chrome' : browser; const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' && (!preferredOSXBrowser || supportedChromiumBrowsers.includes(preferredOSXBrowser)); if (shouldTryOpenChromeWithAppleScript) { try { const ps = execSync('ps cax').toString(); const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser) ? preferredOSXBrowser : supportedChromiumBrowsers.find((b) => ps.includes(b)); if (openedBrowser) { // Try our best to reuse existing tab with AppleScript execSync(`osascript openChrome.applescript "${encodeURI(url)}" "${openedBrowser}"`, { cwd: join$2(VITE_PACKAGE_DIR, 'bin'), stdio: 'ignore', }); return true; } } catch (err) { // Ignore errors } } // Another special case: on OS X, check if BROWSER has been set to "open". // In this case, instead of passing the string `open` to `open` function (which won't work), // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser): // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768 if (process.platform === 'darwin' && browser === 'open') { browser = undefined; } // Fallback to open // (It will always open new tab) try { const options = browser ? { app: { name: browser, arguments: browserArgs } } : {}; open_1(url, options).catch(() => { }); // Prevent `unhandledRejection` error. return true; } catch (err) { return false; } } async function createServer(inlineConfig = {}) { const config = await resolveConfig(inlineConfig, 'serve'); const { root, server: serverConfig } = config; const httpsOptions = await resolveHttpsConfig(config.server.https); const { middlewareMode } = serverConfig; const resolvedWatchOptions = resolveChokidarOptions(config, { disableGlobbing: true, ...serverConfig.watch, }); const middlewares = connect(); const httpServer = middlewareMode ? null : await resolveHttpServer(serverConfig, middlewares, httpsOptions); const ws = createWebSocketServer(httpServer, config, httpsOptions); if (httpServer) { setClientErrorHandler(httpServer, config.logger); } const watcher = chokidar.watch( // config file dependencies and env file might be outside of root [root, ...config.configFileDependencies, config.envDir], resolvedWatchOptions); const moduleGraph = new ModuleGraph((url, ssr) => container.resolveId(url, undefined, { ssr })); const container = await createPluginContainer(config, moduleGraph, watcher); const closeHttpServer = createServerCloseFn(httpServer); let exitProcess; const server = { config, middlewares, httpServer, watcher, pluginContainer: container, ws, moduleGraph, resolvedUrls: null, ssrTransform(code, inMap, url, originalCode = code) { return ssrTransform(code, inMap, url, originalCode, server.config); }, transformRequest(url, options) { return transformRequest(url, server, options); }, transformIndexHtml: null, async ssrLoadModule(url, opts) { if (isDepsOptimizerEnabled(config, true)) { await initDevSsrDepsOptimizer(config, server); } await updateCjsSsrExternals(server); return ssrLoadModule(url, server, undefined, undefined, opts?.fixStacktrace); }, ssrFixStacktrace(e) { ssrFixStacktrace(e, moduleGraph); }, ssrRewriteStacktrace(stack) { return ssrRewriteStacktrace(stack, moduleGraph); }, async reloadModule(module) { if (serverConfig.hmr !== false && module.file) { updateModules(module.file, [module], Date.now(), server); } }, async listen(port, isRestart) { await startServer(server, port); if (httpServer) { server.resolvedUrls = await resolveServerUrls(httpServer, config.server, config); if (!isRestart && config.server.open) server.openBrowser(); } return server; }, openBrowser() { const options = server.config.server; const url = server.resolvedUrls?.local[0]; if (url) { const path = typeof options.open === 'string' ? new URL(options.open, url).href : url; openBrowser(path, true, server.config.logger); } else { server.config.logger.warn('No URL available to open in browser'); } }, async close() { if (!middlewareMode) { process.off('SIGTERM', exitProcess); if (process.env.CI !== 'true') { process.stdin.off('end', exitProcess); } } await Promise.allSettled([ watcher.close(), ws.close(), container.close(), getDepsOptimizer(server.config)?.close(), getDepsOptimizer(server.config, true)?.close(), closeHttpServer(), ]); server.resolvedUrls = null; }, printUrls() { if (server.resolvedUrls) { printServerUrls(server.resolvedUrls, serverConfig.host, config.logger.info); } else if (middlewareMode) { throw new Error('cannot print server URLs in middleware mode.'); } else { throw new Error('cannot print server URLs before server.listen is called.'); } }, async restart(forceOptimize) { if (!server._restartPromise) { server._forceOptimizeOnRestart = !!forceOptimize; server._restartPromise = restartServer(server).finally(() => { server._restartPromise = null; server._forceOptimizeOnRestart = false; }); } return server._restartPromise; }, _ssrExternals: null, _restartPromise: null, _importGlobMap: new Map(), _forceOptimizeOnRestart: false, _pendingRequests: new Map(), _fsDenyGlob: picomatch$3(config.server.fs.deny, { matchBase: true }), _shortcutsOptions: undefined, }; server.transformIndexHtml = createDevHtmlTransformFn(server); if (!middlewareMode) { exitProcess = async () => { try { await server.close(); } finally { process.exit(); } }; process.once('SIGTERM', exitProcess); if (process.env.CI !== 'true') { process.stdin.on('end', exitProcess); } } const { packageCache } = config; const setPackageData = packageCache.set.bind(packageCache); packageCache.set = (id, pkg) => { if (id.endsWith('.json')) { watcher.add(id); } return setPackageData(id, pkg); }; const onHMRUpdate = async (file, configOnly) => { if (serverConfig.hmr !== false) { try { await handleHMRUpdate(file, server, configOnly); } catch (err) { ws.send({ type: 'error', err: prepareError(err), }); } } }; const onFileAddUnlink = async (file) => { file = normalizePath$3(file); await handleFileAddUnlink(file, server); await onHMRUpdate(file, true); }; watcher.on('change', async (file) => { file = normalizePath$3(file); if (file.endsWith('/package.json')) { return invalidatePackageData(packageCache, file); } // invalidate module graph cache on file change moduleGraph.onFileChange(file); await onHMRUpdate(file, false); }); watcher.on('add', onFileAddUnlink); watcher.on('unlink', onFileAddUnlink); ws.on('vite:invalidate', async ({ path, message }) => { const mod = moduleGraph.urlToModuleMap.get(path); if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) { config.logger.info(picocolorsExports.yellow(`hmr invalidate `) + picocolorsExports.dim(path) + (message ? ` ${message}` : ''), { timestamp: true }); const file = getShortName(mod.file, config.root); updateModules(file, [...mod.importers], mod.lastHMRTimestamp, server, true); } }); if (!middlewareMode && httpServer) { httpServer.once('listening', () => { // update actual port since this may be different from initial value serverConfig.port = httpServer.address().port; }); } // apply server configuration hooks from plugins const postHooks = []; for (const hook of config.getSortedPluginHooks('configureServer')) { postHooks.push(await hook(server)); } // Internal middlewares ------------------------------------------------------ // request timer if (process.env.DEBUG) { middlewares.use(timeMiddleware(root)); } // cors (enabled by default) const { cors } = serverConfig; if (cors !== false) { middlewares.use(libExports$1(typeof cors === 'boolean' ? {} : cors)); } // proxy const { proxy } = serverConfig; if (proxy) { middlewares.use(proxyMiddleware(httpServer, proxy, config)); } // base if (config.base !== '/') { middlewares.use(baseMiddleware(server)); } // open in editor support middlewares.use('/__open-in-editor', launchEditorMiddleware()); // serve static files under /public // this applies before the transform middleware so that these files are served // as-is without transforms. if (config.publicDir) { middlewares.use(servePublicMiddleware(config.publicDir, config.server.headers)); } // main transform middleware middlewares.use(transformMiddleware(server)); // serve static files middlewares.use(serveRawFsMiddleware(server)); middlewares.use(serveStaticMiddleware(root, server)); // html fallback if (config.appType === 'spa' || config.appType === 'mpa') { middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa')); } // run post config hooks // This is applied before the html middleware so that user middleware can // serve custom content instead of index.html. postHooks.forEach((fn) => fn && fn()); if (config.appType === 'spa' || config.appType === 'mpa') { // transform index.html middlewares.use(indexHtmlMiddleware(server)); // handle 404s // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` middlewares.use(function vite404Middleware(_, res) { res.statusCode = 404; res.end(); }); } // error handler middlewares.use(errorMiddleware(server, middlewareMode)); let initingServer; let serverInited = false; const initServer = async () => { if (serverInited) { return; } if (initingServer) { return initingServer; } initingServer = (async function () { await container.buildStart({}); if (isDepsOptimizerEnabled(config, false)) { // non-ssr await initDepsOptimizer(config, server); } initingServer = undefined; serverInited = true; })(); return initingServer; }; if (!middlewareMode && httpServer) { // overwrite listen to init optimizer before server start const listen = httpServer.listen.bind(httpServer); httpServer.listen = (async (port, ...args) => { try { await initServer(); } catch (e) { httpServer.emit('error', e); return; } return listen(port, ...args); }); } else { await initServer(); } // Fire a clean up of stale cache dirs, in case old processes didn't // terminate correctly. Don't await this promise cleanupDepsCacheStaleDirs(config); return server; } async function startServer(server, inlinePort) { const httpServer = server.httpServer; if (!httpServer) { throw new Error('Cannot call server.listen in middleware mode.'); } const options = server.config.server; const port = inlinePort ?? options.port ?? DEFAULT_DEV_PORT; const hostname = await resolveHostname(options.host); await httpServerStart(httpServer, { port, strictPort: options.strictPort, host: hostname.host, logger: server.config.logger, }); } function createServerCloseFn(server) { if (!server) { return () => { }; } let hasListened = false; const openSockets = new Set(); server.on('connection', (socket) => { openSockets.add(socket); socket.on('close', () => { openSockets.delete(socket); }); }); server.once('listening', () => { hasListened = true; }); return () => new Promise((resolve, reject) => { openSockets.forEach((s) => s.destroy()); if (hasListened) { server.close((err) => { if (err) { reject(err); } else { resolve(); } }); } else { resolve(); } }); } function resolvedAllowDir(root, dir) { return normalizePath$3(path$o.resolve(root, dir)); } function resolveServerOptions(root, raw, logger) { const server = { preTransformRequests: true, ...raw, sourcemapIgnoreList: raw?.sourcemapIgnoreList === false ? () => false : raw?.sourcemapIgnoreList || ((sourcePath) => sourcePath.includes('node_modules')), middlewareMode: !!raw?.middlewareMode, }; let allowDirs = server.fs?.allow; const deny = server.fs?.deny || ['.env', '.env.*', '*.{crt,pem}']; if (!allowDirs) { allowDirs = [searchForWorkspaceRoot(root)]; } allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i)); // only push client dir when vite itself is outside-of-root const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR); if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) { allowDirs.push(resolvedClientDir); } server.fs = { strict: server.fs?.strict ?? true, allow: allowDirs, deny, }; if (server.origin?.endsWith('/')) { server.origin = server.origin.slice(0, -1); logger.warn(picocolorsExports.yellow(`${picocolorsExports.bold('(!)')} server.origin should not end with "/". Using "${server.origin}" instead.`)); } return server; } async function restartServer(server) { global.__vite_start_time = performance.now(); const { port: prevPort, host: prevHost } = server.config.server; const shortcutsOptions = server._shortcutsOptions; const oldUrls = server.resolvedUrls; let inlineConfig = server.config.inlineConfig; if (server._forceOptimizeOnRestart) { inlineConfig = mergeConfig(inlineConfig, { optimizeDeps: { force: true, }, }); } let newServer = null; try { newServer = await createServer(inlineConfig); } catch (err) { server.config.logger.error(err.message, { timestamp: true, }); server.config.logger.error('server restart failed', { timestamp: true }); return; } await server.close(); // prevent new server `restart` function from calling newServer._restartPromise = server._restartPromise; Object.assign(server, newServer); const { logger, server: { port, host, middlewareMode }, } = server.config; if (!middlewareMode) { await server.listen(port, true); logger.info('server restarted.', { timestamp: true }); if ((port ?? DEFAULT_DEV_PORT) !== (prevPort ?? DEFAULT_DEV_PORT) || host !== prevHost || diffDnsOrderChange(oldUrls, newServer.resolvedUrls)) { logger.info(''); server.printUrls(); } } else { logger.info('server restarted.', { timestamp: true }); } if (shortcutsOptions) { shortcutsOptions.print = false; bindShortcuts(newServer, shortcutsOptions); } // new server (the current server) can restart now newServer._restartPromise = null; } async function updateCjsSsrExternals(server) { if (!server._ssrExternals) { let knownImports = []; // Important! We use the non-ssr optimized deps to find known imports // Only the explicitly defined deps are optimized during dev SSR, so // we use the generated list from the scanned deps in regular dev. // This is part of the v2 externalization heuristics and it is kept // for backwards compatibility in case user needs to fallback to the // legacy scheme. It may be removed in a future v3 minor. const depsOptimizer = getDepsOptimizer(server.config, false); // non-ssr if (depsOptimizer) { await depsOptimizer.scanProcessing; knownImports = [ ...Object.keys(depsOptimizer.metadata.optimized), ...Object.keys(depsOptimizer.metadata.discovered), ]; } server._ssrExternals = cjsSsrResolveExternals(server.config, knownImports); } } var index = { __proto__: null, createServer: createServer, resolveServerOptions: resolveServerOptions, searchForWorkspaceRoot: searchForWorkspaceRoot }; /* eslint-disable */ /* global Buffer */ const noop = () => { }; const mimes = /text|javascript|\/json|xml/i; const threshold = 1024; const level = -1; let brotli = false; const getChunkSize = (chunk, enc) => (chunk ? Buffer.byteLength(chunk, enc) : 0); function compression() { const brotliOpts = (typeof brotli === 'object' && brotli) || {}; const gzipOpts = {}; // disable Brotli on Node<12.7 where it is unsupported: if (!zlib$1.createBrotliCompress) brotli = false; return (req, res, next = noop) => { const accept = req.headers['accept-encoding'] + ''; const encoding = ((brotli && accept.match(/\bbr\b/)) || (accept.match(/\bgzip\b/)) || [])[0]; // skip if no response body or no supported encoding: if (req.method === 'HEAD' || !encoding) return next(); /** @type {zlib.Gzip | zlib.BrotliCompress} */ let compress; let pendingStatus; /** @type {[string, function][]?} */ let pendingListeners = []; let started = false; let size = 0; function start() { started = true; size = res.getHeader('Content-Length') | 0 || size; const compressible = mimes.test(String(res.getHeader('Content-Type') || 'text/plain')); const cleartext = !res.getHeader('Content-Encoding'); const listeners = pendingListeners || []; if (compressible && cleartext && size >= threshold) { res.setHeader('Content-Encoding', encoding); res.removeHeader('Content-Length'); if (encoding === 'br') { const params = { [zlib$1.constants.BROTLI_PARAM_QUALITY]: level, [zlib$1.constants.BROTLI_PARAM_SIZE_HINT]: size, }; compress = zlib$1.createBrotliCompress({ params: Object.assign(params, brotliOpts), }); } else { compress = zlib$1.createGzip(Object.assign({ level }, gzipOpts)); } // backpressure compress.on('data', (chunk) => write.call(res, chunk) === false && compress.pause()); on.call(res, 'drain', () => compress.resume()); compress.on('end', () => end.call(res)); listeners.forEach((p) => compress.on.apply(compress, p)); } else { pendingListeners = null; listeners.forEach((p) => on.apply(res, p)); } writeHead.call(res, pendingStatus || res.statusCode); } const { end, write, on, writeHead } = res; res.writeHead = function (status, reason, headers) { if (typeof reason !== 'string') [headers, reason] = [reason, headers]; if (headers) for (let i in headers) res.setHeader(i, headers[i]); pendingStatus = status; return this; }; res.write = function (chunk, enc, cb) { size += getChunkSize(chunk, enc); if (!started) start(); if (!compress) return write.apply(this, arguments); return compress.write.apply(compress, arguments); }; res.end = function (chunk, enc, cb) { if (arguments.length > 0 && typeof chunk !== 'function') { size += getChunkSize(chunk, enc); } if (!started) start(); if (!compress) return end.apply(this, arguments); return compress.end.apply(compress, arguments); }; res.on = function (type, listener) { if (!pendingListeners || type !== 'drain') on.call(this, type, listener); else if (compress) compress.on(type, listener); else pendingListeners.push([type, listener]); return this; }; next(); }; } function resolvePreviewOptions(preview, server) { // The preview server inherits every CommonServerOption from the `server` config // except for the port to enable having both the dev and preview servers running // at the same time without extra configuration return { port: preview?.port, strictPort: preview?.strictPort ?? server.strictPort, host: preview?.host ?? server.host, https: preview?.https ?? server.https, open: preview?.open ?? server.open, proxy: preview?.proxy ?? server.proxy, cors: preview?.cors ?? server.cors, headers: preview?.headers ?? server.headers, }; } /** * Starts the Vite server in preview mode, to simulate a production deployment */ async function preview(inlineConfig = {}) { const config = await resolveConfig(inlineConfig, 'serve', 'production', 'production'); const distDir = path$o.resolve(config.root, config.build.outDir); if (!fs$l.existsSync(distDir) && // error if no plugins implement `configurePreviewServer` config.plugins.every((plugin) => !plugin.configurePreviewServer) && // error if called in CLI only. programmatic usage could access `httpServer` // and affect file serving process.argv[1]?.endsWith(path$o.normalize('bin/vite.js')) && process.argv[2] === 'preview') { throw new Error(`The directory "${config.build.outDir}" does not exist. Did you build your project?`); } const app = connect(); const httpServer = await resolveHttpServer(config.preview, app, await resolveHttpsConfig(config.preview?.https)); setClientErrorHandler(httpServer, config.logger); // apply server hooks from plugins const postHooks = []; for (const hook of config.getSortedPluginHooks('configurePreviewServer')) { postHooks.push(await hook({ middlewares: app, httpServer })); } // cors const { cors } = config.preview; if (cors !== false) { app.use(libExports$1(typeof cors === 'boolean' ? {} : cors)); } // proxy const { proxy } = config.preview; if (proxy) { app.use(proxyMiddleware(httpServer, proxy, config)); } app.use(compression()); const previewBase = config.base === './' || config.base === '' ? '/' : config.base; // static assets const headers = config.preview.headers; const assetServer = sirv(distDir, { etag: true, dev: true, single: config.appType === 'spa', setHeaders(res) { if (headers) { for (const name in headers) { res.setHeader(name, headers[name]); } } }, shouldServe(filePath) { return shouldServeFile(filePath, distDir); }, }); app.use(previewBase, assetServer); // apply post server hooks from plugins postHooks.forEach((fn) => fn && fn()); const options = config.preview; const hostname = await resolveHostname(options.host); const port = options.port ?? DEFAULT_PREVIEW_PORT; const protocol = options.https ? 'https' : 'http'; const logger = config.logger; const serverPort = await httpServerStart(httpServer, { port, strictPort: options.strictPort, host: hostname.host, logger, }); const resolvedUrls = await resolveServerUrls(httpServer, config.preview, config); if (options.open) { const path = typeof options.open === 'string' ? options.open : previewBase; openBrowser(path.startsWith('http') ? path : new URL(path, `${protocol}://${hostname.name}:${serverPort}`).href, true, logger); } return { config, httpServer, resolvedUrls, printUrls() { printServerUrls(resolvedUrls, options.host, logger.info); }, }; } var preview$1 = { __proto__: null, preview: preview, resolvePreviewOptions: resolvePreviewOptions }; function resolveSSROptions(ssr, preserveSymlinks, buildSsrCjsExternalHeuristics) { ssr ?? (ssr = {}); const optimizeDeps = ssr.optimizeDeps ?? {}; let format = 'esm'; let target = 'node'; if (buildSsrCjsExternalHeuristics) { if (ssr) { format = 'cjs'; } else { target = 'node'; format = 'cjs'; } } return { format, target, ...ssr, optimizeDeps: { disabled: true, ...optimizeDeps, esbuildOptions: { preserveSymlinks, ...optimizeDeps.esbuildOptions, }, }, }; } const debug = createDebugger('vite:config'); /** * Type helper to make it easier to use vite.config.ts * accepts a direct {@link UserConfig} object, or a function that returns it. * The function receives a {@link ConfigEnv} object that exposes two properties: * `command` (either `'build'` or `'serve'`), and `mode`. */ function defineConfig(config) { return config; } async function resolveConfig(inlineConfig, command, defaultMode = 'development', defaultNodeEnv = 'development') { let config = inlineConfig; let configFileDependencies = []; let mode = inlineConfig.mode || defaultMode; const isNodeEnvSet = !!process.env.NODE_ENV; // some dependencies e.g. @vue/compiler-* relies on NODE_ENV for getting // production-specific behavior, so set it early on if (!isNodeEnvSet) { process.env.NODE_ENV = defaultNodeEnv; } const configEnv = { mode, command, ssrBuild: !!config.build?.ssr, }; let { configFile } = config; if (configFile !== false) { const loadResult = await loadConfigFromFile(configEnv, configFile, config.root, config.logLevel); if (loadResult) { config = mergeConfig(loadResult.config, config); configFile = loadResult.path; configFileDependencies = loadResult.dependencies; } } // user config may provide an alternative mode. But --mode has a higher priority mode = inlineConfig.mode || config.mode || mode; configEnv.mode = mode; const filterPlugin = (p) => { if (!p) { return false; } else if (!p.apply) { return true; } else if (typeof p.apply === 'function') { return p.apply({ ...config, mode }, configEnv); } else { return p.apply === command; } }; // Some plugins that aren't intended to work in the bundling of workers (doing post-processing at build time for example). // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls. // So we need to separate the worker plugin from the plugin that vite needs to run. const rawWorkerUserPlugins = (await asyncFlatten(config.worker?.plugins || [])).filter(filterPlugin); // resolve plugins const rawUserPlugins = (await asyncFlatten(config.plugins || [])).filter(filterPlugin); const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawUserPlugins); // run config hooks const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins]; config = await runConfigHook(config, userPlugins, configEnv); if (process.env.VITE_TEST_WITHOUT_PLUGIN_COMMONJS) { config = mergeConfig(config, { optimizeDeps: { disabled: false }, ssr: { optimizeDeps: { disabled: false } }, }); config.build ?? (config.build = {}); config.build.commonjsOptions = { include: [] }; } // Define logger const logger = createLogger(config.logLevel, { allowClearScreen: config.clearScreen, customLogger: config.customLogger, }); // resolve root const resolvedRoot = normalizePath$3(config.root ? path$o.resolve(config.root) : process.cwd()); const clientAlias = [ { find: /^\/?@vite\/env/, replacement: ENV_ENTRY }, { find: /^\/?@vite\/client/, replacement: CLIENT_ENTRY }, ]; // resolve alias with internal client alias const resolvedAlias = normalizeAlias(mergeAlias(clientAlias, config.resolve?.alias || [])); const resolveOptions = { mainFields: config.resolve?.mainFields ?? DEFAULT_MAIN_FIELDS, browserField: config.resolve?.browserField ?? true, conditions: config.resolve?.conditions ?? [], extensions: config.resolve?.extensions ?? DEFAULT_EXTENSIONS$1, dedupe: config.resolve?.dedupe ?? [], preserveSymlinks: config.resolve?.preserveSymlinks ?? false, alias: resolvedAlias, }; // load .env files const envDir = config.envDir ? normalizePath$3(path$o.resolve(resolvedRoot, config.envDir)) : resolvedRoot; const userEnv = inlineConfig.envFile !== false && loadEnv(mode, envDir, resolveEnvPrefix(config)); // Note it is possible for user to have a custom mode, e.g. `staging` where // development-like behavior is expected. This is indicated by NODE_ENV=development // loaded from `.staging.env` and set by us as VITE_USER_NODE_ENV const userNodeEnv = process.env.VITE_USER_NODE_ENV; if (!isNodeEnvSet && userNodeEnv) { if (userNodeEnv === 'development') { process.env.NODE_ENV = 'development'; } else { // NODE_ENV=production is not supported as it could break HMR in dev for frameworks like Vue logger.warn(`NODE_ENV=${userNodeEnv} is not supported in the .env file. ` + `Only NODE_ENV=development is supported to create a development build of your project. ` + `If you need to set process.env.NODE_ENV, you can set it in the Vite config instead.`); } } const isProduction = process.env.NODE_ENV === 'production'; // resolve public base url const isBuild = command === 'build'; const relativeBaseShortcut = config.base === '' || config.base === './'; // During dev, we ignore relative base and fallback to '/' // For the SSR build, relative base isn't possible by means // of import.meta.url. const resolvedBase = relativeBaseShortcut ? !isBuild || config.build?.ssr ? '/' : './' : resolveBaseUrl(config.base, isBuild, logger) ?? '/'; const resolvedBuildOptions = resolveBuildOptions(config.build, logger, resolvedRoot); // resolve cache directory const pkgPath = lookupFile(resolvedRoot, [`package.json`], { pathOnly: true }); const cacheDir = normalizePath$3(config.cacheDir ? path$o.resolve(resolvedRoot, config.cacheDir) : pkgPath ? path$o.join(path$o.dirname(pkgPath), `node_modules/.vite`) : path$o.join(resolvedRoot, `.vite`)); const assetsFilter = config.assetsInclude && (!Array.isArray(config.assetsInclude) || config.assetsInclude.length) ? createFilter(config.assetsInclude) : () => false; // create an internal resolver to be used in special scenarios, e.g. // optimizer & handling css @imports const createResolver = (options) => { let aliasContainer; let resolverContainer; return async (id, importer, aliasOnly, ssr) => { let container; if (aliasOnly) { container = aliasContainer || (aliasContainer = await createPluginContainer({ ...resolved, plugins: [alias$1({ entries: resolved.resolve.alias })], })); } else { container = resolverContainer || (resolverContainer = await createPluginContainer({ ...resolved, plugins: [ alias$1({ entries: resolved.resolve.alias }), resolvePlugin({ ...resolved.resolve, root: resolvedRoot, isProduction, isBuild: command === 'build', ssrConfig: resolved.ssr, asSrc: true, preferRelative: false, tryIndex: true, ...options, }), ], })); } return (await container.resolveId(id, importer, { ssr, scan: options?.scan, }))?.id; }; }; const { publicDir } = config; const resolvedPublicDir = publicDir !== false && publicDir !== '' ? path$o.resolve(resolvedRoot, typeof publicDir === 'string' ? publicDir : 'public') : ''; const server = resolveServerOptions(resolvedRoot, config.server, logger); const ssr = resolveSSROptions(config.ssr, resolveOptions.preserveSymlinks, config.legacy?.buildSsrCjsExternalHeuristics); const middlewareMode = config?.server?.middlewareMode; const optimizeDeps = config.optimizeDeps || {}; const BASE_URL = resolvedBase; // resolve worker let workerConfig = mergeConfig({}, config); const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(rawWorkerUserPlugins); // run config hooks const workerUserPlugins = [ ...workerPrePlugins, ...workerNormalPlugins, ...workerPostPlugins, ]; workerConfig = await runConfigHook(workerConfig, workerUserPlugins, configEnv); const resolvedWorkerOptions = { format: workerConfig.worker?.format || 'iife', plugins: [], rollupOptions: workerConfig.worker?.rollupOptions || {}, getSortedPlugins: undefined, getSortedPluginHooks: undefined, }; const resolvedConfig = { configFile: configFile ? normalizePath$3(configFile) : undefined, configFileDependencies: configFileDependencies.map((name) => normalizePath$3(path$o.resolve(name))), inlineConfig, root: resolvedRoot, base: resolvedBase.endsWith('/') ? resolvedBase : resolvedBase + '/', rawBase: resolvedBase, resolve: resolveOptions, publicDir: resolvedPublicDir, cacheDir, command, mode, ssr, isWorker: false, mainConfig: null, isProduction, plugins: userPlugins, esbuild: config.esbuild === false ? false : { jsxDev: !isProduction, ...config.esbuild, }, server, build: resolvedBuildOptions, preview: resolvePreviewOptions(config.preview, server), envDir, env: { ...userEnv, BASE_URL, MODE: mode, DEV: !isProduction, PROD: isProduction, }, assetsInclude(file) { return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file); }, logger, packageCache: new Map(), createResolver, optimizeDeps: { disabled: 'build', ...optimizeDeps, esbuildOptions: { preserveSymlinks: resolveOptions.preserveSymlinks, ...optimizeDeps.esbuildOptions, }, }, worker: resolvedWorkerOptions, appType: config.appType ?? (middlewareMode === 'ssr' ? 'custom' : 'spa'), experimental: { importGlobRestoreExtension: false, hmrPartialAccept: false, ...config.experimental, }, getSortedPlugins: undefined, getSortedPluginHooks: undefined, }; const resolved = { ...config, ...resolvedConfig, }; resolved.plugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins); Object.assign(resolved, createPluginHookUtils(resolved.plugins)); const workerResolved = { ...workerConfig, ...resolvedConfig, isWorker: true, mainConfig: resolved, }; resolvedConfig.worker.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins); Object.assign(resolvedConfig.worker, createPluginHookUtils(resolvedConfig.worker.plugins)); // call configResolved hooks await Promise.all([ ...resolved .getSortedPluginHooks('configResolved') .map((hook) => hook(resolved)), ...resolvedConfig.worker .getSortedPluginHooks('configResolved') .map((hook) => hook(workerResolved)), ]); // validate config if (middlewareMode === 'ssr') { logger.warn(picocolorsExports.yellow(`Setting server.middlewareMode to 'ssr' is deprecated, set server.middlewareMode to \`true\`${config.appType === 'custom' ? '' : ` and appType to 'custom'`} instead`)); } if (middlewareMode === 'html') { logger.warn(picocolorsExports.yellow(`Setting server.middlewareMode to 'html' is deprecated, set server.middlewareMode to \`true\` instead`)); } if (config.server?.force && !isBuild && config.optimizeDeps?.force === undefined) { resolved.optimizeDeps.force = true; logger.warn(picocolorsExports.yellow(`server.force is deprecated, use optimizeDeps.force instead`)); } if (process.env.DEBUG) { debug(`using resolved config: %O`, { ...resolved, plugins: resolved.plugins.map((p) => p.name), worker: { ...resolved.worker, plugins: resolved.worker.plugins.map((p) => p.name), }, }); } if (config.build?.terserOptions && config.build.minify !== 'terser') { logger.warn(picocolorsExports.yellow(`build.terserOptions is specified but build.minify is not set to use Terser. ` + `Note Vite now defaults to use esbuild for minification. If you still ` + `prefer Terser, set build.minify to "terser".`)); } // Check if all assetFileNames have the same reference. // If not, display a warn for user. const outputOption = config.build?.rollupOptions?.output ?? []; // Use isArray to narrow its type to array if (Array.isArray(outputOption)) { const assetFileNamesList = outputOption.map((output) => output.assetFileNames); if (assetFileNamesList.length > 1) { const firstAssetFileNames = assetFileNamesList[0]; const hasDifferentReference = assetFileNamesList.some((assetFileNames) => assetFileNames !== firstAssetFileNames); if (hasDifferentReference) { resolved.logger.warn(picocolorsExports.yellow(` assetFileNames isn't equal for every build.rollupOptions.output. A single pattern across all outputs is supported by Vite. `)); } } } return resolved; } /** * Resolve base url. Note that some users use Vite to build for non-web targets like * electron or expects to deploy */ function resolveBaseUrl(base = '/', isBuild, logger) { if (base.startsWith('.')) { logger.warn(picocolorsExports.yellow(picocolorsExports.bold(`(!) invalid "base" option: ${base}. The value can only be an absolute ` + `URL, ./, or an empty string.`))); return '/'; } // external URL flag const isExternal = isExternalUrl(base); // no leading slash warn if (!isExternal && !base.startsWith('/')) { logger.warn(picocolorsExports.yellow(picocolorsExports.bold(`(!) "base" option should start with a slash.`))); } // parse base when command is serve or base is not External URL if (!isBuild || !isExternal) { base = new URL(base, 'http://vitejs.dev').pathname; // ensure leading slash if (!base.startsWith('/')) { base = '/' + base; } } return base; } function sortUserPlugins(plugins) { const prePlugins = []; const postPlugins = []; const normalPlugins = []; if (plugins) { plugins.flat().forEach((p) => { if (p.enforce === 'pre') prePlugins.push(p); else if (p.enforce === 'post') postPlugins.push(p); else normalPlugins.push(p); }); } return [prePlugins, normalPlugins, postPlugins]; } async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel) { const start = performance.now(); const getTime = () => `${(performance.now() - start).toFixed(2)}ms`; let resolvedPath; if (configFile) { // explicit config path is always resolved from cwd resolvedPath = path$o.resolve(configFile); } else { // implicit config file loaded from inline root (if present) // otherwise from cwd for (const filename of DEFAULT_CONFIG_FILES) { const filePath = path$o.resolve(configRoot, filename); if (!fs$l.existsSync(filePath)) continue; resolvedPath = filePath; break; } } if (!resolvedPath) { debug('no config file found.'); return null; } let isESM = false; if (/\.m[jt]s$/.test(resolvedPath)) { isESM = true; } else if (/\.c[jt]s$/.test(resolvedPath)) { isESM = false; } else { // check package.json for type: "module" and set `isESM` to true try { const pkg = lookupFile(configRoot, ['package.json']); isESM = !!pkg && JSON.parse(pkg).type === 'module'; } catch (e) { } } try { const bundled = await bundleConfigFile(resolvedPath, isESM); const userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM); debug(`bundled config file loaded in ${getTime()}`); const config = await (typeof userConfig === 'function' ? userConfig(configEnv) : userConfig); if (!isObject$2(config)) { throw new Error(`config must export or return an object.`); } return { path: normalizePath$3(resolvedPath), config, dependencies: bundled.dependencies, }; } catch (e) { createLogger(logLevel).error(picocolorsExports.red(`failed to load config from ${resolvedPath}`), { error: e }); throw e; } } async function bundleConfigFile(fileName, isESM) { const dirnameVarName = '__vite_injected_original_dirname'; const filenameVarName = '__vite_injected_original_filename'; const importMetaUrlVarName = '__vite_injected_original_import_meta_url'; const result = await build$3({ absWorkingDir: process.cwd(), entryPoints: [fileName], outfile: 'out.js', write: false, target: ['node14.18', 'node16'], platform: 'node', bundle: true, format: isESM ? 'esm' : 'cjs', mainFields: ['main'], sourcemap: 'inline', metafile: true, define: { __dirname: dirnameVarName, __filename: filenameVarName, 'import.meta.url': importMetaUrlVarName, }, plugins: [ { name: 'externalize-deps', setup(build) { const options = { root: path$o.dirname(fileName), isBuild: true, isProduction: true, preferRelative: false, tryIndex: true, mainFields: [], browserField: false, conditions: [], overrideConditions: ['node'], dedupe: [], extensions: DEFAULT_EXTENSIONS$1, preserveSymlinks: false, }; // externalize bare imports build.onResolve({ filter: /^[^.].*/ }, async ({ path: id, importer, kind }) => { if (kind === 'entry-point' || path$o.isAbsolute(id) || isBuiltin(id)) { return; } // partial deno support as `npm:` does not work with esbuild if (id.startsWith('npm:')) { return { external: true }; } const isIdESM = isESM || kind === 'dynamic-import'; let idFsPath = tryNodeResolve(id, importer, { ...options, isRequire: !isIdESM }, false)?.id; if (idFsPath && isIdESM) { idFsPath = pathToFileURL(idFsPath).href; } return { path: idFsPath, external: true, }; }); }, }, { name: 'inject-file-scope-variables', setup(build) { build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => { const contents = await fs$l.promises.readFile(args.path, 'utf8'); const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path$o.dirname(args.path))};` + `const ${filenameVarName} = ${JSON.stringify(args.path)};` + `const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(args.path).href)};`; return { loader: args.path.endsWith('ts') ? 'ts' : 'js', contents: injectValues + contents, }; }); }, }, ], }); const { text } = result.outputFiles[0]; return { code: text, dependencies: result.metafile ? Object.keys(result.metafile.inputs) : [], }; } const _require = createRequire$1(import.meta.url); async function loadConfigFromBundledFile(fileName, bundledCode, isESM) { // for esm, before we can register loaders without requiring users to run node // with --experimental-loader themselves, we have to do a hack here: // write it to disk, load it with native Node ESM, then delete the file. if (isESM) { const fileBase = `${fileName}.timestamp-${Date.now()}`; const fileNameTmp = `${fileBase}.mjs`; const fileUrl = `${pathToFileURL(fileBase)}.mjs`; fs$l.writeFileSync(fileNameTmp, bundledCode); try { return (await dynamicImport(fileUrl)).default; } finally { try { fs$l.unlinkSync(fileNameTmp); } catch { // already removed if this function is called twice simultaneously } } } // for cjs, we can register a custom loader via `_require.extensions` else { const extension = path$o.extname(fileName); const realFileName = fs$l.realpathSync(fileName); const loaderExt = extension in _require.extensions ? extension : '.js'; const defaultLoader = _require.extensions[loaderExt]; _require.extensions[loaderExt] = (module, filename) => { if (filename === realFileName) { module._compile(bundledCode, filename); } else { defaultLoader(module, filename); } }; // clear cache in case of server restart delete _require.cache[_require.resolve(fileName)]; const raw = _require(fileName); _require.extensions[loaderExt] = defaultLoader; return raw.__esModule ? raw.default : raw; } } async function runConfigHook(config, plugins, configEnv) { let conf = config; for (const p of getSortedPluginsByHook('config', plugins)) { const hook = p.config; const handler = hook && 'handler' in hook ? hook.handler : hook; if (handler) { const res = await handler(conf, configEnv); if (res) { conf = mergeConfig(conf, res); } } } return conf; } function getDepOptimizationConfig(config, ssr) { return ssr ? config.ssr.optimizeDeps : config.optimizeDeps; } function isDepsOptimizerEnabled(config, ssr) { const { command } = config; const { disabled } = getDepOptimizationConfig(config, ssr); return !(disabled === true || (command === 'build' && disabled === 'build') || (command === 'serve' && disabled === 'dev')); } export { picocolorsExports as A, bindShortcuts as B, commonjsGlobal as C, index$1 as D, build$1 as E, index as F, preview$1 as G, preprocessCSS as a, build as b, createServer as c, resolvePackageData as d, buildErrorMessage as e, formatPostcssSourceMap as f, defineConfig as g, resolveConfig as h, resolveBaseUrl as i, getDepOptimizationConfig as j, isDepsOptimizerEnabled as k, loadConfigFromFile as l, mergeConfig as m, normalizePath$3 as n, optimizeDeps as o, preview as p, mergeAlias as q, resolvePackageEntry as r, sortUserPlugins as s, transformWithEsbuild as t, createFilter as u, send$1 as v, createLogger as w, searchForWorkspaceRoot as x, loadEnv as y, resolveEnvPrefix as z };