'use strict'; const url = require('node:url'); const path$3$1 = require('node:path'); const vite = require('vite'); const sirv = require('sirv'); const Inspect = require('vite-plugin-inspect'); const svelteKitInspector = require('svelte-kit-inspector'); const skRouterGuard = require('vite-plugin-sk-router-guard'); const birpc = require('birpc'); const require$$0 = require('os'); const require$$0$1 = require('path'); const require$$0$2 = require('util'); const require$$0$3 = require('stream'); const require$$2 = require('events'); const require$$0$4 = require('fs'); const fs$1$1 = require('node:fs'); const fs$9 = require('node:fs/promises'); const require$$0$7 = require('readline'); const node_buffer = require('node:buffer'); const childProcess = require('node:child_process'); const process$2 = require('node:process'); const require$$0$2$1 = require('child_process'); const os$1$1 = require('node:os'); const require$$0$3$1 = require('assert'); const require$$0$5 = require('buffer'); const node_util = require('node:util'); const require$$1 = require('tty'); function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; } const url__default = /*#__PURE__*/_interopDefaultCompat(url); const path$3__default = /*#__PURE__*/_interopDefaultCompat(path$3$1); const sirv__default = /*#__PURE__*/_interopDefaultCompat(sirv); const Inspect__default = /*#__PURE__*/_interopDefaultCompat(Inspect); const svelteKitInspector__default = /*#__PURE__*/_interopDefaultCompat(svelteKitInspector); const skRouterGuard__default = /*#__PURE__*/_interopDefaultCompat(skRouterGuard); const require$$0__default = /*#__PURE__*/_interopDefaultCompat(require$$0); const require$$0__default$1 = /*#__PURE__*/_interopDefaultCompat(require$$0$1); const require$$0__default$2 = /*#__PURE__*/_interopDefaultCompat(require$$0$2); const require$$0__default$3 = /*#__PURE__*/_interopDefaultCompat(require$$0$3); const require$$2__default = /*#__PURE__*/_interopDefaultCompat(require$$2); const require$$0__default$4 = /*#__PURE__*/_interopDefaultCompat(require$$0$4); const fs$1__default = /*#__PURE__*/_interopDefaultCompat(fs$1$1); const fs__default = /*#__PURE__*/_interopDefaultCompat(fs$9); const require$$0$7__default = /*#__PURE__*/_interopDefaultCompat(require$$0$7); const childProcess__default = /*#__PURE__*/_interopDefaultCompat(childProcess); const process$2__default = /*#__PURE__*/_interopDefaultCompat(process$2); const require$$0$2__default = /*#__PURE__*/_interopDefaultCompat(require$$0$2$1); const os$1__default = /*#__PURE__*/_interopDefaultCompat(os$1$1); const require$$0$3__default = /*#__PURE__*/_interopDefaultCompat(require$$0$3$1); const require$$0$5__default = /*#__PURE__*/_interopDefaultCompat(require$$0$5); const require$$1__default = /*#__PURE__*/_interopDefaultCompat(require$$1); function createRPCServer(name, ws, functions) { const event = `${name}:rpc`; const group = birpc.createBirpcGroup( functions, () => birpc.cachedMap( Array.from(ws?.clients || []), (socket) => { return { on: (fn) => { ws.on(event, (data, source) => { if (socket === source) fn(data); }); }, post: (data) => { socket.send(event, data); } }; } ), { timeout: -1 } ); ws.on("connection", () => { group.updateChannels(); }); return group.broadcast; } const DIR_DIST = typeof __dirname !== "undefined" ? __dirname : path$3$1.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href)))); const DIR_CLIENT = path$3$1.resolve(DIR_DIST, "../../dist/client"); var commonjsGlobal$1 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs$1 (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var tasks = {}; var utils$k = {}; var array$1 = {}; Object.defineProperty(array$1, "__esModule", { value: true }); array$1.splitWhen = array$1.flatten = void 0; function flatten(items) { return items.reduce((collection, item) => [].concat(collection, item), []); } array$1.flatten = flatten; function splitWhen(items, predicate) { const result = [[]]; let groupIndex = 0; for (const item of items) { if (predicate(item)) { groupIndex++; result[groupIndex] = []; } else { result[groupIndex].push(item); } } return result; } array$1.splitWhen = splitWhen; var errno$1 = {}; Object.defineProperty(errno$1, "__esModule", { value: true }); errno$1.isEnoentCodeError = void 0; function isEnoentCodeError(error) { return error.code === 'ENOENT'; } errno$1.isEnoentCodeError = isEnoentCodeError; var fs$8 = {}; Object.defineProperty(fs$8, "__esModule", { value: true }); fs$8.createDirentFromStats = void 0; let DirentFromStats$1 = class DirentFromStats { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } }; function createDirentFromStats$1(name, stats) { return new DirentFromStats$1(name, stats); } fs$8.createDirentFromStats = createDirentFromStats$1; var path$c = {}; Object.defineProperty(path$c, "__esModule", { value: true }); path$c.convertPosixPathToPattern = path$c.convertWindowsPathToPattern = path$c.convertPathToPattern = path$c.escapePosixPath = path$c.escapeWindowsPath = path$c.escape = path$c.removeLeadingDotSegment = path$c.makeAbsolute = path$c.unixify = void 0; const os$1 = require$$0__default; const path$b = require$$0__default$1; const IS_WINDOWS_PLATFORM = os$1.platform() === 'win32'; const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ /** * All non-escaped special characters. * Posix: ()*?[\]{|}, !+@ before (, ! at the beginning, \\ before non-special characters. * Windows: (){}, !+@ before (, ! at the beginning. */ const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([(){}]|^!|[!+@](?=\())/g; /** * The device path (\\.\ or \\?\). * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths */ const DOS_DEVICE_PATH_RE = /^\\\\([.?])/; /** * All backslashes except those escaping special characters. * Windows: !()+@{} * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions */ const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@{}])/g; /** * Designed to work only with simple paths: `dir\\file`. */ function unixify(filepath) { return filepath.replace(/\\/g, '/'); } path$c.unixify = unixify; function makeAbsolute(cwd, filepath) { return path$b.resolve(cwd, filepath); } path$c.makeAbsolute = makeAbsolute; function removeLeadingDotSegment(entry) { // We do not use `startsWith` because this is 10x slower than current implementation for some cases. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with if (entry.charAt(0) === '.') { const secondCharactery = entry.charAt(1); if (secondCharactery === '/' || secondCharactery === '\\') { return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); } } return entry; } path$c.removeLeadingDotSegment = removeLeadingDotSegment; path$c.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; function escapeWindowsPath(pattern) { return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); } path$c.escapeWindowsPath = escapeWindowsPath; function escapePosixPath(pattern) { return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); } path$c.escapePosixPath = escapePosixPath; path$c.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; function convertWindowsPathToPattern(filepath) { return escapeWindowsPath(filepath) .replace(DOS_DEVICE_PATH_RE, '//$1') .replace(WINDOWS_BACKSLASHES_RE, '/'); } path$c.convertWindowsPathToPattern = convertWindowsPathToPattern; function convertPosixPathToPattern(filepath) { return escapePosixPath(filepath); } path$c.convertPosixPathToPattern = convertPosixPathToPattern; var pattern$1 = {}; /*! * is-extglob * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ var isExtglob$1 = function isExtglob(str) { if (typeof str !== 'string' || str === '') { return false; } var match; while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { if (match[2]) return true; str = str.slice(match.index + match[0].length); } return false; }; /*! * is-glob * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ var isExtglob = isExtglob$1; var chars = { '{': '}', '(': ')', '[': ']'}; var strictCheck = function(str) { if (str[0] === '!') { return true; } var index = 0; var pipeIndex = -2; var closeSquareIndex = -2; var closeCurlyIndex = -2; var closeParenIndex = -2; var backSlashIndex = -2; while (index < str.length) { if (str[index] === '*') { return true; } if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) { return true; } if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') { if (closeSquareIndex < index) { closeSquareIndex = str.indexOf(']', index); } if (closeSquareIndex > index) { if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { return true; } backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { return true; } } } if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') { closeCurlyIndex = str.indexOf('}', index); if (closeCurlyIndex > index) { backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { return true; } } } if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') { closeParenIndex = str.indexOf(')', index); if (closeParenIndex > index) { backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { return true; } } } if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') { if (pipeIndex < index) { pipeIndex = str.indexOf('|', index); } if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') { closeParenIndex = str.indexOf(')', pipeIndex); if (closeParenIndex > pipeIndex) { backSlashIndex = str.indexOf('\\', pipeIndex); if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { return true; } } } } if (str[index] === '\\') { var open = str[index + 1]; index += 2; var close = chars[open]; if (close) { var n = str.indexOf(close, index); if (n !== -1) { index = n + 1; } } if (str[index] === '!') { return true; } } else { index++; } } return false; }; var relaxedCheck = function(str) { if (str[0] === '!') { return true; } var index = 0; while (index < str.length) { if (/[*?{}()[\]]/.test(str[index])) { return true; } if (str[index] === '\\') { var open = str[index + 1]; index += 2; var close = chars[open]; if (close) { var n = str.indexOf(close, index); if (n !== -1) { index = n + 1; } } if (str[index] === '!') { return true; } } else { index++; } } return false; }; var isGlob$1 = function isGlob(str, options) { if (typeof str !== 'string' || str === '') { return false; } if (isExtglob(str)) { return true; } var check = strictCheck; // optionally relax check if (options && options.strict === false) { check = relaxedCheck; } return check(str); }; var isGlob = isGlob$1; var pathPosixDirname = require$$0__default$1.posix.dirname; var isWin32 = require$$0__default.platform() === 'win32'; var slash = '/'; var backslash = /\\/g; var enclosure = /[\{\[].*[\}\]]$/; var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; /** * @param {string} str * @param {Object} opts * @param {boolean} [opts.flipBackslashes=true] * @returns {string} */ var globParent$1 = function globParent(str, opts) { var options = Object.assign({ flipBackslashes: true }, opts); // flip windows path separators if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { str = str.replace(backslash, slash); } // special case for strings ending in enclosure containing path separator if (enclosure.test(str)) { str += slash; } // preserves full path in case of trailing path separator str += 'a'; // remove path parts that are globby do { str = pathPosixDirname(str); } while (isGlob(str) || globby.test(str)); // remove escape chars and return result return str.replace(escaped, '$1'); }; var utils$j = {}; (function (exports) { exports.isInteger = num => { if (typeof num === 'number') { return Number.isInteger(num); } if (typeof num === 'string' && num.trim() !== '') { return Number.isInteger(Number(num)); } return false; }; /** * Find a node of the given type */ exports.find = (node, type) => node.nodes.find(node => node.type === type); /** * Find a node of the given type */ exports.exceedsLimit = (min, max, step = 1, limit) => { if (limit === false) return false; if (!exports.isInteger(min) || !exports.isInteger(max)) return false; return ((Number(max) - Number(min)) / Number(step)) >= limit; }; /** * Escape the given node with '\\' before node.value */ exports.escapeNode = (block, n = 0, type) => { let node = block.nodes[n]; if (!node) return; if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { if (node.escaped !== true) { node.value = '\\' + node.value; node.escaped = true; } } }; /** * Returns true if the given brace node should be enclosed in literal braces */ exports.encloseBrace = node => { if (node.type !== 'brace') return false; if ((node.commas >> 0 + node.ranges >> 0) === 0) { node.invalid = true; return true; } return false; }; /** * Returns true if a brace node is invalid. */ exports.isInvalidBrace = block => { if (block.type !== 'brace') return false; if (block.invalid === true || block.dollar) return true; if ((block.commas >> 0 + block.ranges >> 0) === 0) { block.invalid = true; return true; } if (block.open !== true || block.close !== true) { block.invalid = true; return true; } return false; }; /** * Returns true if a node is an open or close node */ exports.isOpenOrClose = node => { if (node.type === 'open' || node.type === 'close') { return true; } return node.open === true || node.close === true; }; /** * Reduce an array of text nodes. */ exports.reduce = nodes => nodes.reduce((acc, node) => { if (node.type === 'text') acc.push(node.value); if (node.type === 'range') node.type = 'text'; return acc; }, []); /** * Flatten an array */ exports.flatten = (...args) => { const result = []; const flat = arr => { for (let i = 0; i < arr.length; i++) { let ele = arr[i]; Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); } return result; }; flat(args); return result; }; } (utils$j)); const utils$i = utils$j; var stringify$4 = (ast, options = {}) => { let stringify = (node, parent = {}) => { let invalidBlock = options.escapeInvalid && utils$i.isInvalidBrace(parent); let invalidNode = node.invalid === true && options.escapeInvalid === true; let output = ''; if (node.value) { if ((invalidBlock || invalidNode) && utils$i.isOpenOrClose(node)) { return '\\' + node.value; } return node.value; } if (node.value) { return node.value; } if (node.nodes) { for (let child of node.nodes) { output += stringify(child); } } return output; }; return stringify(ast); }; /*! * is-number * * Copyright (c) 2014-present, Jon Schlinkert. * Released under the MIT License. */ var isNumber$3 = function(num) { if (typeof num === 'number') { return num - num === 0; } if (typeof num === 'string' && num.trim() !== '') { return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); } return false; }; /*! * to-regex-range * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. */ const isNumber$2 = isNumber$3; const toRegexRange$1 = (min, max, options) => { if (isNumber$2(min) === false) { throw new TypeError('toRegexRange: expected the first argument to be a number'); } if (max === void 0 || min === max) { return String(min); } if (isNumber$2(max) === false) { throw new TypeError('toRegexRange: expected the second argument to be a number.'); } let opts = { relaxZeros: true, ...options }; if (typeof opts.strictZeros === 'boolean') { opts.relaxZeros = opts.strictZeros === false; } let relax = String(opts.relaxZeros); let shorthand = String(opts.shorthand); let capture = String(opts.capture); let wrap = String(opts.wrap); let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) { return toRegexRange$1.cache[cacheKey].result; } let a = Math.min(min, max); let b = Math.max(min, max); if (Math.abs(a - b) === 1) { let result = min + '|' + max; if (opts.capture) { return `(${result})`; } if (opts.wrap === false) { return result; } return `(?:${result})`; } let isPadded = hasPadding(min) || hasPadding(max); let state = { min, max, a, b }; let positives = []; let negatives = []; if (isPadded) { state.isPadded = isPadded; state.maxLen = String(state.max).length; } if (a < 0) { let newMin = b < 0 ? Math.abs(b) : 1; negatives = splitToPatterns(newMin, Math.abs(a), state, opts); a = state.a = 0; } if (b >= 0) { positives = splitToPatterns(a, b, state, opts); } state.negatives = negatives; state.positives = positives; state.result = collatePatterns(negatives, positives); if (opts.capture === true) { state.result = `(${state.result})`; } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { state.result = `(?:${state.result})`; } toRegexRange$1.cache[cacheKey] = state; return state.result; }; function collatePatterns(neg, pos, options) { let onlyNegative = filterPatterns(neg, pos, '-', false) || []; let onlyPositive = filterPatterns(pos, neg, '', false) || []; let intersected = filterPatterns(neg, pos, '-?', true) || []; let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); return subpatterns.join('|'); } function splitToRanges(min, max) { let nines = 1; let zeros = 1; let stop = countNines(min, nines); let stops = new Set([max]); while (min <= stop && stop <= max) { stops.add(stop); nines += 1; stop = countNines(min, nines); } stop = countZeros(max + 1, zeros) - 1; while (min < stop && stop <= max) { stops.add(stop); zeros += 1; stop = countZeros(max + 1, zeros) - 1; } stops = [...stops]; stops.sort(compare); return stops; } /** * Convert a range to a regex pattern * @param {Number} `start` * @param {Number} `stop` * @return {String} */ function rangeToPattern(start, stop, options) { if (start === stop) { return { pattern: start, count: [], digits: 0 }; } let zipped = zip(start, stop); let digits = zipped.length; let pattern = ''; let count = 0; for (let i = 0; i < digits; i++) { let [startDigit, stopDigit] = zipped[i]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== '0' || stopDigit !== '9') { pattern += toCharacterClass(startDigit, stopDigit); } else { count++; } } if (count) { pattern += options.shorthand === true ? '\\d' : '[0-9]'; } return { pattern, count: [count], digits }; } function splitToPatterns(min, max, tok, options) { let ranges = splitToRanges(min, max); let tokens = []; let start = min; let prev; for (let i = 0; i < ranges.length; i++) { let max = ranges[i]; let obj = rangeToPattern(String(start), String(max), options); let zeros = ''; if (!tok.isPadded && prev && prev.pattern === obj.pattern) { if (prev.count.length > 1) { prev.count.pop(); } prev.count.push(obj.count[0]); prev.string = prev.pattern + toQuantifier(prev.count); start = max + 1; continue; } if (tok.isPadded) { zeros = padZeros(max, tok, options); } obj.string = zeros + obj.pattern + toQuantifier(obj.count); tokens.push(obj); start = max + 1; prev = obj; } return tokens; } function filterPatterns(arr, comparison, prefix, intersection, options) { let result = []; for (let ele of arr) { let { string } = ele; // only push if _both_ are negative... if (!intersection && !contains(comparison, 'string', string)) { result.push(prefix + string); } // or _both_ are positive if (intersection && contains(comparison, 'string', string)) { result.push(prefix + string); } } return result; } /** * Zip strings */ function zip(a, b) { let arr = []; for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); return arr; } function compare(a, b) { return a > b ? 1 : b > a ? -1 : 0; } function contains(arr, key, val) { return arr.some(ele => ele[key] === val); } function countNines(min, len) { return Number(String(min).slice(0, -len) + '9'.repeat(len)); } function countZeros(integer, zeros) { return integer - (integer % Math.pow(10, zeros)); } function toQuantifier(digits) { let [start = 0, stop = ''] = digits; if (stop || start > 1) { return `{${start + (stop ? ',' + stop : '')}}`; } return ''; } function toCharacterClass(a, b, options) { return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; } function hasPadding(str) { return /^-?(0+)\d/.test(str); } function padZeros(value, tok, options) { if (!tok.isPadded) { return value; } let diff = Math.abs(tok.maxLen - String(value).length); let relax = options.relaxZeros !== false; switch (diff) { case 0: return ''; case 1: return relax ? '0?' : '0'; case 2: return relax ? '0{0,2}' : '00'; default: { return relax ? `0{0,${diff}}` : `0{${diff}}`; } } } /** * Cache */ toRegexRange$1.cache = {}; toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {}); /** * Expose `toRegexRange` */ var toRegexRange_1 = toRegexRange$1; /*! * fill-range * * Copyright (c) 2014-present, Jon Schlinkert. * Licensed under the MIT License. */ const util$2 = require$$0__default$2; const toRegexRange = toRegexRange_1; const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val); const transform = toNumber => { return value => toNumber === true ? Number(value) : String(value); }; const isValidValue = value => { return typeof value === 'number' || (typeof value === 'string' && value !== ''); }; const isNumber$1 = num => Number.isInteger(+num); const zeros = input => { let value = `${input}`; let index = -1; if (value[0] === '-') value = value.slice(1); if (value === '0') return false; while (value[++index] === '0'); return index > 0; }; const stringify$3 = (start, end, options) => { if (typeof start === 'string' || typeof end === 'string') { return true; } return options.stringify === true; }; const pad = (input, maxLength, toNumber) => { if (maxLength > 0) { let dash = input[0] === '-' ? '-' : ''; if (dash) input = input.slice(1); input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); } if (toNumber === false) { return String(input); } return input; }; const toMaxLen = (input, maxLength) => { let negative = input[0] === '-' ? '-' : ''; if (negative) { input = input.slice(1); maxLength--; } while (input.length < maxLength) input = '0' + input; return negative ? ('-' + input) : input; }; const toSequence = (parts, options) => { parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); let prefix = options.capture ? '' : '?:'; let positives = ''; let negatives = ''; let result; if (parts.positives.length) { positives = parts.positives.join('|'); } if (parts.negatives.length) { negatives = `-(${prefix}${parts.negatives.join('|')})`; } if (positives && negatives) { result = `${positives}|${negatives}`; } else { result = positives || negatives; } if (options.wrap) { return `(${prefix}${result})`; } return result; }; const toRange = (a, b, isNumbers, options) => { if (isNumbers) { return toRegexRange(a, b, { wrap: false, ...options }); } let start = String.fromCharCode(a); if (a === b) return start; let stop = String.fromCharCode(b); return `[${start}-${stop}]`; }; const toRegex = (start, end, options) => { if (Array.isArray(start)) { let wrap = options.wrap === true; let prefix = options.capture ? '' : '?:'; return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); } return toRegexRange(start, end, options); }; const rangeError = (...args) => { return new RangeError('Invalid range arguments: ' + util$2.inspect(...args)); }; const invalidRange = (start, end, options) => { if (options.strictRanges === true) throw rangeError([start, end]); return []; }; const invalidStep = (step, options) => { if (options.strictRanges === true) { throw new TypeError(`Expected step "${step}" to be a number`); } return []; }; const fillNumbers = (start, end, step = 1, options = {}) => { let a = Number(start); let b = Number(end); if (!Number.isInteger(a) || !Number.isInteger(b)) { if (options.strictRanges === true) throw rangeError([start, end]); return []; } // fix negative zero if (a === 0) a = 0; if (b === 0) b = 0; let descending = a > b; let startString = String(start); let endString = String(end); let stepString = String(step); step = Math.max(Math.abs(step), 1); let padded = zeros(startString) || zeros(endString) || zeros(stepString); let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; let toNumber = padded === false && stringify$3(start, end, options) === false; let format = options.transform || transform(toNumber); if (options.toRegex && step === 1) { return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); } let parts = { negatives: [], positives: [] }; let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); let range = []; let index = 0; while (descending ? a >= b : a <= b) { if (options.toRegex === true && step > 1) { push(a); } else { range.push(pad(format(a, index), maxLen, toNumber)); } a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return step > 1 ? toSequence(parts, options) : toRegex(range, null, { wrap: false, ...options }); } return range; }; const fillLetters = (start, end, step = 1, options = {}) => { if ((!isNumber$1(start) && start.length > 1) || (!isNumber$1(end) && end.length > 1)) { return invalidRange(start, end, options); } let format = options.transform || (val => String.fromCharCode(val)); let a = `${start}`.charCodeAt(0); let b = `${end}`.charCodeAt(0); let descending = a > b; let min = Math.min(a, b); let max = Math.max(a, b); if (options.toRegex && step === 1) { return toRange(min, max, false, options); } let range = []; let index = 0; while (descending ? a >= b : a <= b) { range.push(format(a, index)); a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return toRegex(range, null, { wrap: false, options }); } return range; }; const fill$2 = (start, end, step, options = {}) => { if (end == null && isValidValue(start)) { return [start]; } if (!isValidValue(start) || !isValidValue(end)) { return invalidRange(start, end, options); } if (typeof step === 'function') { return fill$2(start, end, 1, { transform: step }); } if (isObject$1(step)) { return fill$2(start, end, 0, step); } let opts = { ...options }; if (opts.capture === true) opts.wrap = true; step = step || opts.step || 1; if (!isNumber$1(step)) { if (step != null && !isObject$1(step)) return invalidStep(step, opts); return fill$2(start, end, 1, step); } if (isNumber$1(start) && isNumber$1(end)) { return fillNumbers(start, end, step, opts); } return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); }; var fillRange = fill$2; const fill$1 = fillRange; const utils$h = utils$j; const compile$1 = (ast, options = {}) => { let walk = (node, parent = {}) => { let invalidBlock = utils$h.isInvalidBrace(parent); let invalidNode = node.invalid === true && options.escapeInvalid === true; let invalid = invalidBlock === true || invalidNode === true; let prefix = options.escapeInvalid === true ? '\\' : ''; let output = ''; if (node.isOpen === true) { return prefix + node.value; } if (node.isClose === true) { return prefix + node.value; } if (node.type === 'open') { return invalid ? (prefix + node.value) : '('; } if (node.type === 'close') { return invalid ? (prefix + node.value) : ')'; } if (node.type === 'comma') { return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); } if (node.value) { return node.value; } if (node.nodes && node.ranges > 0) { let args = utils$h.reduce(node.nodes); let range = fill$1(...args, { ...options, wrap: false, toRegex: true }); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; } } if (node.nodes) { for (let child of node.nodes) { output += walk(child, node); } } return output; }; return walk(ast); }; var compile_1 = compile$1; const fill = fillRange; const stringify$2 = stringify$4; const utils$g = utils$j; const append = (queue = '', stash = '', enclose = false) => { let result = []; queue = [].concat(queue); stash = [].concat(stash); if (!stash.length) return queue; if (!queue.length) { return enclose ? utils$g.flatten(stash).map(ele => `{${ele}}`) : stash; } for (let item of queue) { if (Array.isArray(item)) { for (let value of item) { result.push(append(value, stash, enclose)); } } else { for (let ele of stash) { if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele)); } } } return utils$g.flatten(result); }; const expand$1 = (ast, options = {}) => { let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; let walk = (node, parent = {}) => { node.queue = []; let p = parent; let q = parent.queue; while (p.type !== 'brace' && p.type !== 'root' && p.parent) { p = p.parent; q = p.queue; } if (node.invalid || node.dollar) { q.push(append(q.pop(), stringify$2(node, options))); return; } if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { q.push(append(q.pop(), ['{}'])); return; } if (node.nodes && node.ranges > 0) { let args = utils$g.reduce(node.nodes); if (utils$g.exceedsLimit(...args, options.step, rangeLimit)) { throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); } let range = fill(...args, options); if (range.length === 0) { range = stringify$2(node, options); } q.push(append(q.pop(), range)); node.nodes = []; return; } let enclose = utils$g.encloseBrace(node); let queue = node.queue; let block = node; while (block.type !== 'brace' && block.type !== 'root' && block.parent) { block = block.parent; queue = block.queue; } for (let i = 0; i < node.nodes.length; i++) { let child = node.nodes[i]; if (child.type === 'comma' && node.type === 'brace') { if (i === 1) queue.push(''); queue.push(''); continue; } if (child.type === 'close') { q.push(append(q.pop(), queue, enclose)); continue; } if (child.value && child.type !== 'open') { queue.push(append(queue.pop(), child.value)); continue; } if (child.nodes) { walk(child, node); } } return queue; }; return utils$g.flatten(walk(ast)); }; var expand_1 = expand$1; var constants$4 = { MAX_LENGTH: 1024 * 64, // Digits CHAR_0: '0', /* 0 */ CHAR_9: '9', /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 'A', /* A */ CHAR_LOWERCASE_A: 'a', /* a */ CHAR_UPPERCASE_Z: 'Z', /* Z */ CHAR_LOWERCASE_Z: 'z', /* z */ CHAR_LEFT_PARENTHESES: '(', /* ( */ CHAR_RIGHT_PARENTHESES: ')', /* ) */ CHAR_ASTERISK: '*', /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: '&', /* & */ CHAR_AT: '@', /* @ */ CHAR_BACKSLASH: '\\', /* \ */ CHAR_BACKTICK: '`', /* ` */ CHAR_CARRIAGE_RETURN: '\r', /* \r */ CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ CHAR_COLON: ':', /* : */ CHAR_COMMA: ',', /* , */ CHAR_DOLLAR: '$', /* . */ CHAR_DOT: '.', /* . */ CHAR_DOUBLE_QUOTE: '"', /* " */ CHAR_EQUAL: '=', /* = */ CHAR_EXCLAMATION_MARK: '!', /* ! */ CHAR_FORM_FEED: '\f', /* \f */ CHAR_FORWARD_SLASH: '/', /* / */ CHAR_HASH: '#', /* # */ CHAR_HYPHEN_MINUS: '-', /* - */ CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ CHAR_LEFT_CURLY_BRACE: '{', /* { */ CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ CHAR_LINE_FEED: '\n', /* \n */ CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ CHAR_PERCENT: '%', /* % */ CHAR_PLUS: '+', /* + */ CHAR_QUESTION_MARK: '?', /* ? */ CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ CHAR_RIGHT_CURLY_BRACE: '}', /* } */ CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ CHAR_SEMICOLON: ';', /* ; */ CHAR_SINGLE_QUOTE: '\'', /* ' */ CHAR_SPACE: ' ', /* */ CHAR_TAB: '\t', /* \t */ CHAR_UNDERSCORE: '_', /* _ */ CHAR_VERTICAL_LINE: '|', /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ }; const stringify$1 = stringify$4; /** * Constants */ const { MAX_LENGTH: MAX_LENGTH$1, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA: CHAR_COMMA$1, /* , */ CHAR_DOT: CHAR_DOT$1, /* . */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1, /* ] */ CHAR_DOUBLE_QUOTE, /* " */ CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = constants$4; /** * parse */ const parse$5 = (input, options = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } let opts = options || {}; let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; if (input.length > max) { throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); } let ast = { type: 'root', input, nodes: [] }; let stack = [ast]; let block = ast; let prev = ast; let brackets = 0; let length = input.length; let index = 0; let depth = 0; let value; /** * Helpers */ const advance = () => input[index++]; const push = node => { if (node.type === 'text' && prev.type === 'dot') { prev.type = 'text'; } if (prev && prev.type === 'text' && node.type === 'text') { prev.value += node.value; return; } block.nodes.push(node); node.parent = block; node.prev = prev; prev = node; return node; }; push({ type: 'bos' }); while (index < length) { block = stack[stack.length - 1]; value = advance(); /** * Invalid chars */ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { continue; } /** * Escaped chars */ if (value === CHAR_BACKSLASH) { push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); continue; } /** * Right square bracket (literal): ']' */ if (value === CHAR_RIGHT_SQUARE_BRACKET$1) { push({ type: 'text', value: '\\' + value }); continue; } /** * Left square bracket: '[' */ if (value === CHAR_LEFT_SQUARE_BRACKET$1) { brackets++; let next; while (index < length && (next = advance())) { value += next; if (next === CHAR_LEFT_SQUARE_BRACKET$1) { brackets++; continue; } if (next === CHAR_BACKSLASH) { value += advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { brackets--; if (brackets === 0) { break; } } } push({ type: 'text', value }); continue; } /** * Parentheses */ if (value === CHAR_LEFT_PARENTHESES$1) { block = push({ type: 'paren', nodes: [] }); stack.push(block); push({ type: 'text', value }); continue; } if (value === CHAR_RIGHT_PARENTHESES$1) { if (block.type !== 'paren') { push({ type: 'text', value }); continue; } block = stack.pop(); push({ type: 'text', value }); block = stack[stack.length - 1]; continue; } /** * Quotes: '|"|` */ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { let open = value; let next; if (options.keepQuotes !== true) { value = ''; } while (index < length && (next = advance())) { if (next === CHAR_BACKSLASH) { value += next + advance(); continue; } if (next === open) { if (options.keepQuotes === true) value += next; break; } value += next; } push({ type: 'text', value }); continue; } /** * Left curly brace: '{' */ if (value === CHAR_LEFT_CURLY_BRACE$1) { depth++; let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; let brace = { type: 'brace', open: true, close: false, dollar, depth, commas: 0, ranges: 0, nodes: [] }; block = push(brace); stack.push(block); push({ type: 'open', value }); continue; } /** * Right curly brace: '}' */ if (value === CHAR_RIGHT_CURLY_BRACE$1) { if (block.type !== 'brace') { push({ type: 'text', value }); continue; } let type = 'close'; block = stack.pop(); block.close = true; push({ type, value }); depth--; block = stack[stack.length - 1]; continue; } /** * Comma: ',' */ if (value === CHAR_COMMA$1 && depth > 0) { if (block.ranges > 0) { block.ranges = 0; let open = block.nodes.shift(); block.nodes = [open, { type: 'text', value: stringify$1(block) }]; } push({ type: 'comma', value }); block.commas++; continue; } /** * Dot: '.' */ if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) { let siblings = block.nodes; if (depth === 0 || siblings.length === 0) { push({ type: 'text', value }); continue; } if (prev.type === 'dot') { block.range = []; prev.value += value; prev.type = 'range'; if (block.nodes.length !== 3 && block.nodes.length !== 5) { block.invalid = true; block.ranges = 0; prev.type = 'text'; continue; } block.ranges++; block.args = []; continue; } if (prev.type === 'range') { siblings.pop(); let before = siblings[siblings.length - 1]; before.value += prev.value + value; prev = before; block.ranges--; continue; } push({ type: 'dot', value }); continue; } /** * Text */ push({ type: 'text', value }); } // Mark imbalanced braces and brackets as invalid do { block = stack.pop(); if (block.type !== 'root') { block.nodes.forEach(node => { if (!node.nodes) { if (node.type === 'open') node.isOpen = true; if (node.type === 'close') node.isClose = true; if (!node.nodes) node.type = 'text'; node.invalid = true; } }); // get the location of the block on parent.nodes (block's siblings) let parent = stack[stack.length - 1]; let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes parent.nodes.splice(index, 1, ...block.nodes); } } while (stack.length > 0); push({ type: 'eos' }); return ast; }; var parse_1$2 = parse$5; const stringify = stringify$4; const compile = compile_1; const expand = expand_1; const parse$4 = parse_1$2; /** * Expand the given pattern or create a regex-compatible string. * * ```js * const braces = require('braces'); * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] * ``` * @param {String} `str` * @param {Object} `options` * @return {String} * @api public */ const braces$1 = (input, options = {}) => { let output = []; if (Array.isArray(input)) { for (let pattern of input) { let result = braces$1.create(pattern, options); if (Array.isArray(result)) { output.push(...result); } else { output.push(result); } } } else { output = [].concat(braces$1.create(input, options)); } if (options && options.expand === true && options.nodupes === true) { output = [...new Set(output)]; } return output; }; /** * Parse the given `str` with the given `options`. * * ```js * // braces.parse(pattern, [, options]); * const ast = braces.parse('a/{b,c}/d'); * console.log(ast); * ``` * @param {String} pattern Brace pattern to parse * @param {Object} options * @return {Object} Returns an AST * @api public */ braces$1.parse = (input, options = {}) => parse$4(input, options); /** * Creates a braces string from an AST, or an AST node. * * ```js * const braces = require('braces'); * let ast = braces.parse('foo/{a,b}/bar'); * console.log(stringify(ast.nodes[2])); //=> '{a,b}' * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$1.stringify = (input, options = {}) => { if (typeof input === 'string') { return stringify(braces$1.parse(input, options), options); } return stringify(input, options); }; /** * Compiles a brace pattern into a regex-compatible, optimized string. * This method is called by the main [braces](#braces) function by default. * * ```js * const braces = require('braces'); * console.log(braces.compile('a/{b,c}/d')); * //=> ['a/(b|c)/d'] * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$1.compile = (input, options = {}) => { if (typeof input === 'string') { input = braces$1.parse(input, options); } return compile(input, options); }; /** * Expands a brace pattern into an array. This method is called by the * main [braces](#braces) function when `options.expand` is true. Before * using this method it's recommended that you read the [performance notes](#performance)) * and advantages of using [.compile](#compile) instead. * * ```js * const braces = require('braces'); * console.log(braces.expand('a/{b,c}/d')); * //=> ['a/b/d', 'a/c/d']; * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$1.expand = (input, options = {}) => { if (typeof input === 'string') { input = braces$1.parse(input, options); } let result = expand(input, options); // filter out empty strings if specified if (options.noempty === true) { result = result.filter(Boolean); } // filter out duplicates if specified if (options.nodupes === true) { result = [...new Set(result)]; } return result; }; /** * Processes a brace pattern and returns either an expanded array * (if `options.expand` is true), a highly optimized regex-compatible string. * This method is called by the main [braces](#braces) function. * * ```js * const braces = require('braces'); * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$1.create = (input, options = {}) => { if (input === '' || input.length < 3) { return [input]; } return options.expand !== true ? braces$1.compile(input, options) : braces$1.expand(input, options); }; /** * Expose "braces" */ var braces_1 = braces$1; var utils$f = {}; const path$a = require$$0__default$1; 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 = `${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, 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$3 = { 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$a.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__default$1; const win32 = process.platform === 'win32'; const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = constants$3; 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$f)); const utils$e = utils$f; const { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_RIGHT_SQUARE_BRACKET /* ] */ } = constants$3; 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$1 = (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) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { braces++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE) { braces++; continue; } if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE) { 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 && 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) { 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) { 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) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET) { 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) { isGlob = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { 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$e.removeBackslashes(glob); if (base && backslashes === true) { base = utils$e.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$1; const constants$2 = constants$3; const utils$d = utils$f; /** * Constants */ const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$2; /** * Helpers */ const expandRange = (args, options) => { if (typeof options.expandRange === 'function') { return options.expandRange(...args, options); } args.sort(); const value = `[${args.join('-')}]`; try { /* eslint-disable-next-line no-new */ new RegExp(value); } catch (ex) { return args.map(v => utils$d.escapeRegex(v)).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$3 = (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, opts.maxLength) : MAX_LENGTH; 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$d.isWindows(options); // create constants based on platform, for windows or posix const PLATFORM_CHARS = constants$2.globChars(win32); const EXTGLOB_CHARS = constants$2.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$d.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$3(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$d.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$d.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$d.hasRegexChars(prevValue)) { continue; } const escaped = utils$d.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$d.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$d.escapeLast(state.output, '['); decrement('brackets'); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); state.output = utils$d.escapeLast(state.output, '('); decrement('parens'); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); state.output = utils$d.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$3.fastpaths = (input, options) => { const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; 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$d.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$2.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$d.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL}?`; } return source; }; var parse_1$1 = parse$3; const path$9 = require$$0__default$1; const scan = scan_1; const parse$2 = parse_1$1; const utils$c = utils$f; const constants$1 = constants$3; const isObject = 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$2 = (glob, options, returnState = false) => { if (Array.isArray(glob)) { const fns = glob.map(input => picomatch$2(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(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$c.isWindows(options); const regex = isState ? picomatch$2.compileRe(glob, options) : picomatch$2.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$2(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { const { isMatch, match, output } = picomatch$2.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$2.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$c.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$2.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$2.matchBase = (input, glob, options, posix = utils$c.isWindows(options)) => { const regex = glob instanceof RegExp ? glob : picomatch$2.makeRe(glob, options); return regex.test(path$9.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$2.isMatch = (str, patterns, options) => picomatch$2(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$2.parse = (pattern, options) => { if (Array.isArray(pattern)) return pattern.map(p => picomatch$2.parse(p, options)); return parse$2(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$2.scan = (input, options) => scan(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$2.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$2.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$2.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$2.fastpaths(input, options); } if (!parsed.output) { parsed = parse$2(input, options); } return picomatch$2.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$2.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$2.constants = constants$1; /** * Expose "picomatch" */ var picomatch_1 = picomatch$2; var picomatch$1 = picomatch_1; const util$1 = require$$0__default$2; const braces = braces_1; const picomatch = picomatch$1; const utils$b = utils$f; const isEmptyString = val => val === '' || val === './'; /** * Returns an array of strings that match one or more glob patterns. * * ```js * const mm = require('micromatch'); * // mm(list, patterns[, options]); * * console.log(mm(['a.js', 'a.txt'], ['*.js'])); * //=> [ 'a.js' ] * ``` * @param {String|Array} `list` List of strings to match. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) * @return {Array} Returns an array of matches * @summary false * @api public */ const micromatch$1 = (list, patterns, options) => { patterns = [].concat(patterns); list = [].concat(list); let omit = new Set(); let keep = new Set(); let items = new Set(); let negatives = 0; let onResult = state => { items.add(state.output); if (options && options.onResult) { options.onResult(state); } }; for (let i = 0; i < patterns.length; i++) { let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true); let negated = isMatch.state.negated || isMatch.state.negatedExtglob; if (negated) negatives++; for (let item of list) { let matched = isMatch(item, true); let match = negated ? !matched.isMatch : matched.isMatch; if (!match) continue; if (negated) { omit.add(matched.output); } else { omit.delete(matched.output); keep.add(matched.output); } } } let result = negatives === patterns.length ? [...items] : [...keep]; let matches = result.filter(item => !omit.has(item)); if (options && matches.length === 0) { if (options.failglob === true) { throw new Error(`No matches found for "${patterns.join(', ')}"`); } if (options.nonull === true || options.nullglob === true) { return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; } } return matches; }; /** * Backwards compatibility */ micromatch$1.match = micromatch$1; /** * Returns a matcher function from the given glob `pattern` and `options`. * The returned function takes a string to match as its only argument and returns * true if the string is a match. * * ```js * const mm = require('micromatch'); * // mm.matcher(pattern[, options]); * * const isMatch = mm.matcher('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @param {String} `pattern` Glob pattern * @param {Object} `options` * @return {Function} Returns a matcher function. * @api public */ micromatch$1.matcher = (pattern, options) => picomatch(pattern, options); /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const mm = require('micromatch'); * // mm.isMatch(string, patterns[, options]); * * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(mm.isMatch('a.a', 'b.*')); //=> false * ``` * @param {String} `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 */ micromatch$1.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); /** * Backwards compatibility */ micromatch$1.any = micromatch$1.isMatch; /** * Returns a list of strings that _**do not match any**_ of the given `patterns`. * * ```js * const mm = require('micromatch'); * // mm.not(list, patterns[, options]); * * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); * //=> ['b.b', 'c.c'] * ``` * @param {Array} `list` Array of strings to match. * @param {String|Array} `patterns` One or more glob pattern to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Array} Returns an array of strings that **do not match** the given patterns. * @api public */ micromatch$1.not = (list, patterns, options = {}) => { patterns = [].concat(patterns).map(String); let result = new Set(); let items = []; let onResult = state => { if (options.onResult) options.onResult(state); items.push(state.output); }; let matches = new Set(micromatch$1(list, patterns, { ...options, onResult })); for (let item of items) { if (!matches.has(item)) { result.add(item); } } return [...result]; }; /** * Returns true if the given `string` contains the given pattern. Similar * to [.isMatch](#isMatch) but the pattern can match any part of the string. * * ```js * var mm = require('micromatch'); * // mm.contains(string, pattern[, options]); * * console.log(mm.contains('aa/bb/cc', '*b')); * //=> true * console.log(mm.contains('aa/bb/cc', '*d')); * //=> false * ``` * @param {String} `str` The string to match. * @param {String|Array} `patterns` Glob pattern to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any of the patterns matches any part of `str`. * @api public */ micromatch$1.contains = (str, pattern, options) => { if (typeof str !== 'string') { throw new TypeError(`Expected a string: "${util$1.inspect(str)}"`); } if (Array.isArray(pattern)) { return pattern.some(p => micromatch$1.contains(str, p, options)); } if (typeof pattern === 'string') { if (isEmptyString(str) || isEmptyString(pattern)) { return false; } if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { return true; } } return micromatch$1.isMatch(str, pattern, { ...options, contains: true }); }; /** * Filter the keys of the given object with the given `glob` pattern * and `options`. Does not attempt to match nested keys. If you need this feature, * use [glob-object][] instead. * * ```js * const mm = require('micromatch'); * // mm.matchKeys(object, patterns[, options]); * * const obj = { aa: 'a', ab: 'b', ac: 'c' }; * console.log(mm.matchKeys(obj, '*b')); * //=> { ab: 'b' } * ``` * @param {Object} `object` The object with keys to filter. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Object} Returns an object with only keys that match the given patterns. * @api public */ micromatch$1.matchKeys = (obj, patterns, options) => { if (!utils$b.isObject(obj)) { throw new TypeError('Expected the first argument to be an object'); } let keys = micromatch$1(Object.keys(obj), patterns, options); let res = {}; for (let key of keys) res[key] = obj[key]; return res; }; /** * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. * * ```js * const mm = require('micromatch'); * // mm.some(list, patterns[, options]); * * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // true * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` * @api public */ micromatch$1.some = (list, patterns, options) => { let items = [].concat(list); for (let pattern of [].concat(patterns)) { let isMatch = picomatch(String(pattern), options); if (items.some(item => isMatch(item))) { return true; } } return false; }; /** * Returns true if every string in the given `list` matches * any of the given glob `patterns`. * * ```js * const mm = require('micromatch'); * // mm.every(list, patterns[, options]); * * console.log(mm.every('foo.js', ['foo.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // false * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` * @api public */ micromatch$1.every = (list, patterns, options) => { let items = [].concat(list); for (let pattern of [].concat(patterns)) { let isMatch = picomatch(String(pattern), options); if (!items.every(item => isMatch(item))) { return false; } } return true; }; /** * Returns true if **all** of the given `patterns` match * the specified string. * * ```js * const mm = require('micromatch'); * // mm.all(string, patterns[, options]); * * console.log(mm.all('foo.js', ['foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); * // false * * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); * // true * ``` * @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) for changing how matches are performed * @return {Boolean} Returns true if any patterns match `str` * @api public */ micromatch$1.all = (str, patterns, options) => { if (typeof str !== 'string') { throw new TypeError(`Expected a string: "${util$1.inspect(str)}"`); } return [].concat(patterns).every(p => picomatch(p, options)(str)); }; /** * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. * * ```js * const mm = require('micromatch'); * // mm.capture(pattern, string[, options]); * * console.log(mm.capture('test/*.js', 'test/foo.js')); * //=> ['foo'] * console.log(mm.capture('test/*.js', 'foo/bar.css')); * //=> null * ``` * @param {String} `glob` Glob pattern to use for matching. * @param {String} `input` String to match * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. * @api public */ micromatch$1.capture = (glob, input, options) => { let posix = utils$b.isWindows(options); let regex = picomatch.makeRe(String(glob), { ...options, capture: true }); let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input); if (match) { return match.slice(1).map(v => v === void 0 ? '' : v); } }; /** * Create a regular expression from the given glob `pattern`. * * ```js * const mm = require('micromatch'); * // mm.makeRe(pattern[, options]); * * console.log(mm.makeRe('*.js')); * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ * ``` * @param {String} `pattern` A glob pattern to convert to regex. * @param {Object} `options` * @return {RegExp} Returns a regex created from the given pattern. * @api public */ micromatch$1.makeRe = (...args) => picomatch.makeRe(...args); /** * Scan a glob pattern to separate the pattern into segments. Used * by the [split](#split) method. * * ```js * const mm = require('micromatch'); * const state = mm.scan(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with * @api public */ micromatch$1.scan = (...args) => picomatch.scan(...args); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const mm = require('micromatch'); * const state = mm.parse(pattern[, options]); * ``` * @param {String} `glob` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as regex source string. * @api public */ micromatch$1.parse = (patterns, options) => { let res = []; for (let pattern of [].concat(patterns || [])) { for (let str of braces(String(pattern), options)) { res.push(picomatch.parse(str, options)); } } return res; }; /** * Process the given brace `pattern`. * * ```js * const { braces } = require('micromatch'); * console.log(braces('foo/{a,b,c}/bar')); * //=> [ 'foo/(a|b|c)/bar' ] * * console.log(braces('foo/{a,b,c}/bar', { expand: true })); * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] * ``` * @param {String} `pattern` String with brace pattern to process. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. * @return {Array} * @api public */ micromatch$1.braces = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { return [pattern]; } return braces(pattern, options); }; /** * Expand braces */ micromatch$1.braceExpand = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); return micromatch$1.braces(pattern, { ...options, expand: true }); }; /** * Expose micromatch */ var micromatch_1 = micromatch$1; Object.defineProperty(pattern$1, "__esModule", { value: true }); pattern$1.removeDuplicateSlashes = pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0; const path$8 = require$$0__default$1; const globParent = globParent$1; const micromatch = micromatch_1; const GLOBSTAR = '**'; const ESCAPE_SYMBOL = '\\'; const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; /** * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. * The latter is due to the presence of the device path at the beginning of the UNC path. */ const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; function isStaticPattern(pattern, options = {}) { return !isDynamicPattern(pattern, options); } pattern$1.isStaticPattern = isStaticPattern; function isDynamicPattern(pattern, options = {}) { /** * A special case with an empty string is necessary for matching patterns that start with a forward slash. * An empty string cannot be a dynamic pattern. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. */ if (pattern === '') { return false; } /** * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check * filepath directly (without read directory). */ if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { return true; } if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { return true; } if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { return true; } if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { return true; } return false; } pattern$1.isDynamicPattern = isDynamicPattern; function hasBraceExpansion(pattern) { const openingBraceIndex = pattern.indexOf('{'); if (openingBraceIndex === -1) { return false; } const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1); if (closingBraceIndex === -1) { return false; } const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); } function convertToPositivePattern(pattern) { return isNegativePattern(pattern) ? pattern.slice(1) : pattern; } pattern$1.convertToPositivePattern = convertToPositivePattern; function convertToNegativePattern(pattern) { return '!' + pattern; } pattern$1.convertToNegativePattern = convertToNegativePattern; function isNegativePattern(pattern) { return pattern.startsWith('!') && pattern[1] !== '('; } pattern$1.isNegativePattern = isNegativePattern; function isPositivePattern(pattern) { return !isNegativePattern(pattern); } pattern$1.isPositivePattern = isPositivePattern; function getNegativePatterns(patterns) { return patterns.filter(isNegativePattern); } pattern$1.getNegativePatterns = getNegativePatterns; function getPositivePatterns$1(patterns) { return patterns.filter(isPositivePattern); } pattern$1.getPositivePatterns = getPositivePatterns$1; /** * Returns patterns that can be applied inside the current directory. * * @example * // ['./*', '*', 'a/*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ function getPatternsInsideCurrentDirectory(patterns) { return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); } pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; /** * Returns patterns to be expanded relative to (outside) the current directory. * * @example * // ['../*', './../*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ function getPatternsOutsideCurrentDirectory(patterns) { return patterns.filter(isPatternRelatedToParentDirectory); } pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; function isPatternRelatedToParentDirectory(pattern) { return pattern.startsWith('..') || pattern.startsWith('./..'); } pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; function getBaseDirectory(pattern) { return globParent(pattern, { flipBackslashes: false }); } pattern$1.getBaseDirectory = getBaseDirectory; function hasGlobStar(pattern) { return pattern.includes(GLOBSTAR); } pattern$1.hasGlobStar = hasGlobStar; function endsWithSlashGlobStar(pattern) { return pattern.endsWith('/' + GLOBSTAR); } pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar; function isAffectDepthOfReadingPattern(pattern) { const basename = path$8.basename(pattern); return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); } pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; function expandPatternsWithBraceExpansion(patterns) { return patterns.reduce((collection, pattern) => { return collection.concat(expandBraceExpansion(pattern)); }, []); } pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; function expandBraceExpansion(pattern) { const patterns = micromatch.braces(pattern, { expand: true, nodupes: true }); /** * Sort the patterns by length so that the same depth patterns are processed side by side. * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']` */ patterns.sort((a, b) => a.length - b.length); /** * Micromatch can return an empty string in the case of patterns like `{a,}`. */ return patterns.filter((pattern) => pattern !== ''); } pattern$1.expandBraceExpansion = expandBraceExpansion; function getPatternParts(pattern, options) { let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); /** * The scan method returns an empty array in some cases. * See micromatch/picomatch#58 for more details. */ if (parts.length === 0) { parts = [pattern]; } /** * The scan method does not return an empty part for the pattern with a forward slash. * This is another part of micromatch/picomatch#58. */ if (parts[0].startsWith('/')) { parts[0] = parts[0].slice(1); parts.unshift(''); } return parts; } pattern$1.getPatternParts = getPatternParts; function makeRe(pattern, options) { return micromatch.makeRe(pattern, options); } pattern$1.makeRe = makeRe; function convertPatternsToRe(patterns, options) { return patterns.map((pattern) => makeRe(pattern, options)); } pattern$1.convertPatternsToRe = convertPatternsToRe; function matchAny(entry, patternsRe) { return patternsRe.some((patternRe) => patternRe.test(entry)); } pattern$1.matchAny = matchAny; /** * This package only works with forward slashes as a path separator. * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. */ function removeDuplicateSlashes(pattern) { return pattern.replace(DOUBLE_SLASH_RE, '/'); } pattern$1.removeDuplicateSlashes = removeDuplicateSlashes; var stream$5 = {}; /* * merge2 * https://github.com/teambition/merge2 * * Copyright (c) 2014-2020 Teambition * Licensed under the MIT license. */ const Stream = require$$0__default$3; const PassThrough$1 = Stream.PassThrough; const slice = Array.prototype.slice; var merge2_1 = merge2$1; function merge2$1 () { const streamsQueue = []; const args = slice.call(arguments); let merging = false; let options = args[args.length - 1]; if (options && !Array.isArray(options) && options.pipe == null) { args.pop(); } else { options = {}; } const doEnd = options.end !== false; const doPipeError = options.pipeError === true; if (options.objectMode == null) { options.objectMode = true; } if (options.highWaterMark == null) { options.highWaterMark = 64 * 1024; } const mergedStream = PassThrough$1(options); function addStream () { for (let i = 0, len = arguments.length; i < len; i++) { streamsQueue.push(pauseStreams(arguments[i], options)); } mergeStream(); return this } function mergeStream () { if (merging) { return } merging = true; let streams = streamsQueue.shift(); if (!streams) { process.nextTick(endStream); return } if (!Array.isArray(streams)) { streams = [streams]; } let pipesCount = streams.length + 1; function next () { if (--pipesCount > 0) { return } merging = false; mergeStream(); } function pipe (stream) { function onend () { stream.removeListener('merge2UnpipeEnd', onend); stream.removeListener('end', onend); if (doPipeError) { stream.removeListener('error', onerror); } next(); } function onerror (err) { mergedStream.emit('error', err); } // skip ended stream if (stream._readableState.endEmitted) { return next() } stream.on('merge2UnpipeEnd', onend); stream.on('end', onend); if (doPipeError) { stream.on('error', onerror); } stream.pipe(mergedStream, { end: false }); // compatible for old stream stream.resume(); } for (let i = 0; i < streams.length; i++) { pipe(streams[i]); } next(); } function endStream () { merging = false; // emit 'queueDrain' when all streams merged. mergedStream.emit('queueDrain'); if (doEnd) { mergedStream.end(); } } mergedStream.setMaxListeners(0); mergedStream.add = addStream; mergedStream.on('unpipe', function (stream) { stream.emit('merge2UnpipeEnd'); }); if (args.length) { addStream.apply(null, args); } return mergedStream } // check and pause streams for pipe. function pauseStreams (streams, options) { if (!Array.isArray(streams)) { // Backwards-compat with old-style streams if (!streams._readableState && streams.pipe) { streams = streams.pipe(PassThrough$1(options)); } if (!streams._readableState || !streams.pause || !streams.pipe) { throw new Error('Only readable stream can be merged.') } streams.pause(); } else { for (let i = 0, len = streams.length; i < len; i++) { streams[i] = pauseStreams(streams[i], options); } } return streams } Object.defineProperty(stream$5, "__esModule", { value: true }); stream$5.merge = void 0; const merge2 = merge2_1; function merge(streams) { const mergedStream = merge2(streams); streams.forEach((stream) => { stream.once('error', (error) => mergedStream.emit('error', error)); }); mergedStream.once('close', () => propagateCloseEventToSources(streams)); mergedStream.once('end', () => propagateCloseEventToSources(streams)); return mergedStream; } stream$5.merge = merge; function propagateCloseEventToSources(streams) { streams.forEach((stream) => stream.emit('close')); } var string$1 = {}; Object.defineProperty(string$1, "__esModule", { value: true }); string$1.isEmpty = string$1.isString = void 0; function isString(input) { return typeof input === 'string'; } string$1.isString = isString; function isEmpty(input) { return input === ''; } string$1.isEmpty = isEmpty; Object.defineProperty(utils$k, "__esModule", { value: true }); utils$k.string = utils$k.stream = utils$k.pattern = utils$k.path = utils$k.fs = utils$k.errno = utils$k.array = void 0; const array = array$1; utils$k.array = array; const errno = errno$1; utils$k.errno = errno; const fs$7 = fs$8; utils$k.fs = fs$7; const path$7 = path$c; utils$k.path = path$7; const pattern = pattern$1; utils$k.pattern = pattern; const stream$4 = stream$5; utils$k.stream = stream$4; const string = string$1; utils$k.string = string; Object.defineProperty(tasks, "__esModule", { value: true }); tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0; const utils$a = utils$k; function generate(input, settings) { const patterns = processPatterns(input, settings); const ignore = processPatterns(settings.ignore, settings); const positivePatterns = getPositivePatterns(patterns); const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); const staticPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isStaticPattern(pattern, settings)); const dynamicPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isDynamicPattern(pattern, settings)); const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); return staticTasks.concat(dynamicTasks); } tasks.generate = generate; function processPatterns(input, settings) { let patterns = input; /** * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry * and some problems with the micromatch package (see fast-glob issues: #365, #394). * * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown * in matching in the case of a large set of patterns after expansion. */ if (settings.braceExpansion) { patterns = utils$a.pattern.expandPatternsWithBraceExpansion(patterns); } /** * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used * at any nesting level. * * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change * the pattern in the filter before creating a regular expression. There is no need to change the patterns * in the application. Only on the input. */ if (settings.baseNameMatch) { patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`); } /** * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion. */ return patterns.map((pattern) => utils$a.pattern.removeDuplicateSlashes(pattern)); } /** * Returns tasks grouped by basic pattern directories. * * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. * This is necessary because directory traversal starts at the base directory and goes deeper. */ function convertPatternsToTasks(positive, negative, dynamic) { const tasks = []; const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive); const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive); const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); /* * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. */ if ('.' in insideCurrentDirectoryGroup) { tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); } else { tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); } return tasks; } tasks.convertPatternsToTasks = convertPatternsToTasks; function getPositivePatterns(patterns) { return utils$a.pattern.getPositivePatterns(patterns); } tasks.getPositivePatterns = getPositivePatterns; function getNegativePatternsAsPositive(patterns, ignore) { const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore); const positive = negative.map(utils$a.pattern.convertToPositivePattern); return positive; } tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive; function groupPatternsByBaseDirectory(patterns) { const group = {}; return patterns.reduce((collection, pattern) => { const base = utils$a.pattern.getBaseDirectory(pattern); if (base in collection) { collection[base].push(pattern); } else { collection[base] = [pattern]; } return collection; }, group); } tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; function convertPatternGroupsToTasks(positive, negative, dynamic) { return Object.keys(positive).map((base) => { return convertPatternGroupToTask(base, positive[base], negative, dynamic); }); } tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks; function convertPatternGroupToTask(base, positive, negative, dynamic) { return { dynamic, positive, negative, base, patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern)) }; } tasks.convertPatternGroupToTask = convertPatternGroupToTask; var async$7 = {}; var async$6 = {}; var out$3 = {}; var async$5 = {}; var async$4 = {}; var out$2 = {}; var async$3 = {}; var out$1 = {}; var async$2 = {}; Object.defineProperty(async$2, "__esModule", { value: true }); async$2.read = void 0; function read$3(path, settings, callback) { settings.fs.lstat(path, (lstatError, lstat) => { if (lstatError !== null) { callFailureCallback$2(callback, lstatError); return; } if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { callSuccessCallback$2(callback, lstat); return; } settings.fs.stat(path, (statError, stat) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { callFailureCallback$2(callback, statError); return; } callSuccessCallback$2(callback, lstat); return; } if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } callSuccessCallback$2(callback, stat); }); }); } async$2.read = read$3; function callFailureCallback$2(callback, error) { callback(error); } function callSuccessCallback$2(callback, result) { callback(null, result); } var sync$8 = {}; Object.defineProperty(sync$8, "__esModule", { value: true }); sync$8.read = void 0; function read$2(path, settings) { const lstat = settings.fs.lstatSync(path); if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { return lstat; } try { const stat = settings.fs.statSync(path); if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } return stat; } catch (error) { if (!settings.throwErrorOnBrokenSymbolicLink) { return lstat; } throw error; } } sync$8.read = read$2; var settings$3 = {}; var fs$6 = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = require$$0__default$4; exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; } (fs$6)); Object.defineProperty(settings$3, "__esModule", { value: true }); const fs$5 = fs$6; let Settings$2 = class Settings { constructor(_options = {}) { this._options = _options; this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); this.fs = fs$5.createFileSystemAdapter(this._options.fs); this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } }; settings$3.default = Settings$2; Object.defineProperty(out$1, "__esModule", { value: true }); out$1.statSync = out$1.stat = out$1.Settings = void 0; const async$1 = async$2; const sync$7 = sync$8; const settings_1$3 = settings$3; out$1.Settings = settings_1$3.default; function stat(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async$1.read(path, getSettings$2(), optionsOrSettingsOrCallback); return; } async$1.read(path, getSettings$2(optionsOrSettingsOrCallback), callback); } out$1.stat = stat; function statSync(path, optionsOrSettings) { const settings = getSettings$2(optionsOrSettings); return sync$7.read(path, settings); } out$1.statSync = statSync; function getSettings$2(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1$3.default) { return settingsOrOptions; } return new settings_1$3.default(settingsOrOptions); } /*! queue-microtask. MIT License. Feross Aboukhadijeh */ let promise; var queueMicrotask_1 = typeof queueMicrotask === 'function' ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal$1) // reuse resolved promise, and allocate it lazily : cb => (promise || (promise = Promise.resolve())) .then(cb) .catch(err => setTimeout(() => { throw err }, 0)); /*! run-parallel. MIT License. Feross Aboukhadijeh */ var runParallel_1 = runParallel; const queueMicrotask$1 = queueMicrotask_1; function runParallel (tasks, cb) { let results, pending, keys; let isSync = true; if (Array.isArray(tasks)) { results = []; pending = tasks.length; } else { keys = Object.keys(tasks); results = {}; pending = keys.length; } function done (err) { function end () { if (cb) cb(err, results); cb = null; } if (isSync) queueMicrotask$1(end); else end(); } function each (i, err, result) { results[i] = result; if (--pending === 0 || err) { done(err); } } if (!pending) { // empty done(null); } else if (keys) { // object keys.forEach(function (key) { tasks[key](function (err, result) { each(key, err, result); }); }); } else { // array tasks.forEach(function (task, i) { task(function (err, result) { each(i, err, result); }); }); } isSync = false; } var constants = {}; Object.defineProperty(constants, "__esModule", { value: true }); constants.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); } const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); const SUPPORTED_MAJOR_VERSION = 10; const SUPPORTED_MINOR_VERSION = 10; const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; /** * IS `true` for Node.js 10.10 and greater. */ constants.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; var utils$9 = {}; var fs$4 = {}; Object.defineProperty(fs$4, "__esModule", { value: true }); fs$4.createDirentFromStats = void 0; class DirentFromStats { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } } function createDirentFromStats(name, stats) { return new DirentFromStats(name, stats); } fs$4.createDirentFromStats = createDirentFromStats; Object.defineProperty(utils$9, "__esModule", { value: true }); utils$9.fs = void 0; const fs$3 = fs$4; utils$9.fs = fs$3; var common$6 = {}; Object.defineProperty(common$6, "__esModule", { value: true }); common$6.joinPathSegments = void 0; function joinPathSegments$1(a, b, separator) { /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } common$6.joinPathSegments = joinPathSegments$1; Object.defineProperty(async$3, "__esModule", { value: true }); async$3.readdir = async$3.readdirWithFileTypes = async$3.read = void 0; const fsStat$5 = out$1; const rpl = runParallel_1; const constants_1$1 = constants; const utils$8 = utils$9; const common$5 = common$6; function read$1(directory, settings, callback) { if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { readdirWithFileTypes$1(directory, settings, callback); return; } readdir$1(directory, settings, callback); } async$3.read = read$1; function readdirWithFileTypes$1(directory, settings, callback) { settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { if (readdirError !== null) { callFailureCallback$1(callback, readdirError); return; } const entries = dirents.map((dirent) => ({ dirent, name: dirent.name, path: common$5.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) })); if (!settings.followSymbolicLinks) { callSuccessCallback$1(callback, entries); return; } const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); rpl(tasks, (rplError, rplEntries) => { if (rplError !== null) { callFailureCallback$1(callback, rplError); return; } callSuccessCallback$1(callback, rplEntries); }); }); } async$3.readdirWithFileTypes = readdirWithFileTypes$1; function makeRplTaskEntry(entry, settings) { return (done) => { if (!entry.dirent.isSymbolicLink()) { done(null, entry); return; } settings.fs.stat(entry.path, (statError, stats) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { done(statError); return; } done(null, entry); return; } entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats); done(null, entry); }); }; } function readdir$1(directory, settings, callback) { settings.fs.readdir(directory, (readdirError, names) => { if (readdirError !== null) { callFailureCallback$1(callback, readdirError); return; } const tasks = names.map((name) => { const path = common$5.joinPathSegments(directory, name, settings.pathSegmentSeparator); return (done) => { fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => { if (error !== null) { done(error); return; } const entry = { name, path, dirent: utils$8.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } done(null, entry); }); }; }); rpl(tasks, (rplError, entries) => { if (rplError !== null) { callFailureCallback$1(callback, rplError); return; } callSuccessCallback$1(callback, entries); }); }); } async$3.readdir = readdir$1; function callFailureCallback$1(callback, error) { callback(error); } function callSuccessCallback$1(callback, result) { callback(null, result); } var sync$6 = {}; Object.defineProperty(sync$6, "__esModule", { value: true }); sync$6.readdir = sync$6.readdirWithFileTypes = sync$6.read = void 0; const fsStat$4 = out$1; const constants_1 = constants; const utils$7 = utils$9; const common$4 = common$6; function read(directory, settings) { if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { return readdirWithFileTypes(directory, settings); } return readdir(directory, settings); } sync$6.read = read; function readdirWithFileTypes(directory, settings) { const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); return dirents.map((dirent) => { const entry = { dirent, name: dirent.name, path: common$4.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) }; if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { try { const stats = settings.fs.statSync(entry.path); entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats); } catch (error) { if (settings.throwErrorOnBrokenSymbolicLink) { throw error; } } } return entry; }); } sync$6.readdirWithFileTypes = readdirWithFileTypes; function readdir(directory, settings) { const names = settings.fs.readdirSync(directory); return names.map((name) => { const entryPath = common$4.joinPathSegments(directory, name, settings.pathSegmentSeparator); const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings); const entry = { name, path: entryPath, dirent: utils$7.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } return entry; }); } sync$6.readdir = readdir; var settings$2 = {}; var fs$2 = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = require$$0__default$4; exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; } (fs$2)); Object.defineProperty(settings$2, "__esModule", { value: true }); const path$6 = require$$0__default$1; const fsStat$3 = out$1; const fs$1 = fs$2; let Settings$1 = class Settings { constructor(_options = {}) { this._options = _options; this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); this.fs = fs$1.createFileSystemAdapter(this._options.fs); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$6.sep); this.stats = this._getValue(this._options.stats, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); this.fsStatSettings = new fsStat$3.Settings({ followSymbolicLink: this.followSymbolicLinks, fs: this.fs, throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } }; settings$2.default = Settings$1; Object.defineProperty(out$2, "__esModule", { value: true }); out$2.Settings = out$2.scandirSync = out$2.scandir = void 0; const async = async$3; const sync$5 = sync$6; const settings_1$2 = settings$2; out$2.Settings = settings_1$2.default; function scandir(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async.read(path, getSettings$1(), optionsOrSettingsOrCallback); return; } async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback); } out$2.scandir = scandir; function scandirSync(path, optionsOrSettings) { const settings = getSettings$1(optionsOrSettings); return sync$5.read(path, settings); } out$2.scandirSync = scandirSync; function getSettings$1(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1$2.default) { return settingsOrOptions; } return new settings_1$2.default(settingsOrOptions); } var queue = {exports: {}}; function reusify$1 (Constructor) { var head = new Constructor(); var tail = head; function get () { var current = head; if (current.next) { head = current.next; } else { head = new Constructor(); tail = head; } current.next = null; return current } function release (obj) { tail.next = obj; tail = obj; } return { get: get, release: release } } var reusify_1 = reusify$1; /* eslint-disable no-var */ var reusify = reusify_1; function fastqueue (context, worker, concurrency) { if (typeof context === 'function') { concurrency = worker; worker = context; context = null; } if (concurrency < 1) { throw new Error('fastqueue concurrency must be greater than 1') } var cache = reusify(Task); var queueHead = null; var queueTail = null; var _running = 0; var errorHandler = null; var self = { push: push, drain: noop$1, saturated: noop$1, pause: pause, paused: false, concurrency: concurrency, running: running, resume: resume, idle: idle, length: length, getQueue: getQueue, unshift: unshift, empty: noop$1, kill: kill, killAndDrain: killAndDrain, error: error }; return self function running () { return _running } function pause () { self.paused = true; } function length () { var current = queueHead; var counter = 0; while (current) { current = current.next; counter++; } return counter } function getQueue () { var current = queueHead; var tasks = []; while (current) { tasks.push(current.value); current = current.next; } return tasks } function resume () { if (!self.paused) return self.paused = false; for (var i = 0; i < self.concurrency; i++) { _running++; release(); } } function idle () { return _running === 0 && self.length() === 0 } function push (value, done) { var current = cache.get(); current.context = context; current.release = release; current.value = value; current.callback = done || noop$1; current.errorHandler = errorHandler; if (_running === self.concurrency || self.paused) { if (queueTail) { queueTail.next = current; queueTail = current; } else { queueHead = current; queueTail = current; self.saturated(); } } else { _running++; worker.call(context, current.value, current.worked); } } function unshift (value, done) { var current = cache.get(); current.context = context; current.release = release; current.value = value; current.callback = done || noop$1; if (_running === self.concurrency || self.paused) { if (queueHead) { current.next = queueHead; queueHead = current; } else { queueHead = current; queueTail = current; self.saturated(); } } else { _running++; worker.call(context, current.value, current.worked); } } function release (holder) { if (holder) { cache.release(holder); } var next = queueHead; if (next) { if (!self.paused) { if (queueTail === queueHead) { queueTail = null; } queueHead = next.next; next.next = null; worker.call(context, next.value, next.worked); if (queueTail === null) { self.empty(); } } else { _running--; } } else if (--_running === 0) { self.drain(); } } function kill () { queueHead = null; queueTail = null; self.drain = noop$1; } function killAndDrain () { queueHead = null; queueTail = null; self.drain(); self.drain = noop$1; } function error (handler) { errorHandler = handler; } } function noop$1 () {} function Task () { this.value = null; this.callback = noop$1; this.next = null; this.release = noop$1; this.context = null; this.errorHandler = null; var self = this; this.worked = function worked (err, result) { var callback = self.callback; var errorHandler = self.errorHandler; var val = self.value; self.value = null; self.callback = noop$1; if (self.errorHandler) { errorHandler(err, val); } callback.call(self.context, err, result); self.release(self); }; } function queueAsPromised (context, worker, concurrency) { if (typeof context === 'function') { concurrency = worker; worker = context; context = null; } function asyncWrapper (arg, cb) { worker.call(this, arg) .then(function (res) { cb(null, res); }, cb); } var queue = fastqueue(context, asyncWrapper, concurrency); var pushCb = queue.push; var unshiftCb = queue.unshift; queue.push = push; queue.unshift = unshift; queue.drained = drained; return queue function push (value) { var p = new Promise(function (resolve, reject) { pushCb(value, function (err, result) { if (err) { reject(err); return } resolve(result); }); }); // Let's fork the promise chain to // make the error bubble up to the user but // not lead to a unhandledRejection p.catch(noop$1); return p } function unshift (value) { var p = new Promise(function (resolve, reject) { unshiftCb(value, function (err, result) { if (err) { reject(err); return } resolve(result); }); }); // Let's fork the promise chain to // make the error bubble up to the user but // not lead to a unhandledRejection p.catch(noop$1); return p } function drained () { if (queue.idle()) { return new Promise(function (resolve) { resolve(); }) } var previousDrain = queue.drain; var p = new Promise(function (resolve) { queue.drain = function () { previousDrain(); resolve(); }; }); return p } } queue.exports = fastqueue; queue.exports.promise = queueAsPromised; var queueExports = queue.exports; var common$3 = {}; Object.defineProperty(common$3, "__esModule", { value: true }); common$3.joinPathSegments = common$3.replacePathSegmentSeparator = common$3.isAppliedFilter = common$3.isFatalError = void 0; function isFatalError(settings, error) { if (settings.errorFilter === null) { return true; } return !settings.errorFilter(error); } common$3.isFatalError = isFatalError; function isAppliedFilter(filter, value) { return filter === null || filter(value); } common$3.isAppliedFilter = isAppliedFilter; function replacePathSegmentSeparator(filepath, separator) { return filepath.split(/[/\\]/).join(separator); } common$3.replacePathSegmentSeparator = replacePathSegmentSeparator; function joinPathSegments(a, b, separator) { if (a === '') { return b; } /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } common$3.joinPathSegments = joinPathSegments; var reader$1 = {}; Object.defineProperty(reader$1, "__esModule", { value: true }); const common$2 = common$3; let Reader$1 = class Reader { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._root = common$2.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); } }; reader$1.default = Reader$1; Object.defineProperty(async$4, "__esModule", { value: true }); const events_1 = require$$2__default; const fsScandir$2 = out$2; const fastq = queueExports; const common$1 = common$3; const reader_1$4 = reader$1; class AsyncReader extends reader_1$4.default { constructor(_root, _settings) { super(_root, _settings); this._settings = _settings; this._scandir = fsScandir$2.scandir; this._emitter = new events_1.EventEmitter(); this._queue = fastq(this._worker.bind(this), this._settings.concurrency); this._isFatalError = false; this._isDestroyed = false; this._queue.drain = () => { if (!this._isFatalError) { this._emitter.emit('end'); } }; } read() { this._isFatalError = false; this._isDestroyed = false; setImmediate(() => { this._pushToQueue(this._root, this._settings.basePath); }); return this._emitter; } get isDestroyed() { return this._isDestroyed; } destroy() { if (this._isDestroyed) { throw new Error('The reader is already destroyed'); } this._isDestroyed = true; this._queue.killAndDrain(); } onEntry(callback) { this._emitter.on('entry', callback); } onError(callback) { this._emitter.once('error', callback); } onEnd(callback) { this._emitter.once('end', callback); } _pushToQueue(directory, base) { const queueItem = { directory, base }; this._queue.push(queueItem, (error) => { if (error !== null) { this._handleError(error); } }); } _worker(item, done) { this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { if (error !== null) { done(error, undefined); return; } for (const entry of entries) { this._handleEntry(entry, item.base); } done(null, undefined); }); } _handleError(error) { if (this._isDestroyed || !common$1.isFatalError(this._settings, error)) { return; } this._isFatalError = true; this._isDestroyed = true; this._emitter.emit('error', error); } _handleEntry(entry, base) { if (this._isDestroyed || this._isFatalError) { return; } const fullpath = entry.path; if (base !== undefined) { entry.path = common$1.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common$1.isAppliedFilter(this._settings.entryFilter, entry)) { this._emitEntry(entry); } if (entry.dirent.isDirectory() && common$1.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _emitEntry(entry) { this._emitter.emit('entry', entry); } } async$4.default = AsyncReader; Object.defineProperty(async$5, "__esModule", { value: true }); const async_1$4 = async$4; class AsyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1$4.default(this._root, this._settings); this._storage = []; } read(callback) { this._reader.onError((error) => { callFailureCallback(callback, error); }); this._reader.onEntry((entry) => { this._storage.push(entry); }); this._reader.onEnd(() => { callSuccessCallback(callback, this._storage); }); this._reader.read(); } } async$5.default = AsyncProvider; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, entries) { callback(null, entries); } var stream$3 = {}; Object.defineProperty(stream$3, "__esModule", { value: true }); const stream_1$5 = require$$0__default$3; const async_1$3 = async$4; class StreamProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1$3.default(this._root, this._settings); this._stream = new stream_1$5.Readable({ objectMode: true, read: () => { }, destroy: () => { if (!this._reader.isDestroyed) { this._reader.destroy(); } } }); } read() { this._reader.onError((error) => { this._stream.emit('error', error); }); this._reader.onEntry((entry) => { this._stream.push(entry); }); this._reader.onEnd(() => { this._stream.push(null); }); this._reader.read(); return this._stream; } } stream$3.default = StreamProvider; var sync$4 = {}; var sync$3 = {}; Object.defineProperty(sync$3, "__esModule", { value: true }); const fsScandir$1 = out$2; const common = common$3; const reader_1$3 = reader$1; class SyncReader extends reader_1$3.default { constructor() { super(...arguments); this._scandir = fsScandir$1.scandirSync; this._storage = []; this._queue = new Set(); } read() { this._pushToQueue(this._root, this._settings.basePath); this._handleQueue(); return this._storage; } _pushToQueue(directory, base) { this._queue.add({ directory, base }); } _handleQueue() { for (const item of this._queue.values()) { this._handleDirectory(item.directory, item.base); } } _handleDirectory(directory, base) { try { const entries = this._scandir(directory, this._settings.fsScandirSettings); for (const entry of entries) { this._handleEntry(entry, base); } } catch (error) { this._handleError(error); } } _handleError(error) { if (!common.isFatalError(this._settings, error)) { return; } throw error; } _handleEntry(entry, base) { const fullpath = entry.path; if (base !== undefined) { entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common.isAppliedFilter(this._settings.entryFilter, entry)) { this._pushToStorage(entry); } if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _pushToStorage(entry) { this._storage.push(entry); } } sync$3.default = SyncReader; Object.defineProperty(sync$4, "__esModule", { value: true }); const sync_1$3 = sync$3; class SyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new sync_1$3.default(this._root, this._settings); } read() { return this._reader.read(); } } sync$4.default = SyncProvider; var settings$1 = {}; Object.defineProperty(settings$1, "__esModule", { value: true }); const path$5 = require$$0__default$1; const fsScandir = out$2; class Settings { constructor(_options = {}) { this._options = _options; this.basePath = this._getValue(this._options.basePath, undefined); this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); this.deepFilter = this._getValue(this._options.deepFilter, null); this.entryFilter = this._getValue(this._options.entryFilter, null); this.errorFilter = this._getValue(this._options.errorFilter, null); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$5.sep); this.fsScandirSettings = new fsScandir.Settings({ followSymbolicLinks: this._options.followSymbolicLinks, fs: this._options.fs, pathSegmentSeparator: this._options.pathSegmentSeparator, stats: this._options.stats, throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } settings$1.default = Settings; Object.defineProperty(out$3, "__esModule", { value: true }); out$3.Settings = out$3.walkStream = out$3.walkSync = out$3.walk = void 0; const async_1$2 = async$5; const stream_1$4 = stream$3; const sync_1$2 = sync$4; const settings_1$1 = settings$1; out$3.Settings = settings_1$1.default; function walk(directory, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { new async_1$2.default(directory, getSettings()).read(optionsOrSettingsOrCallback); return; } new async_1$2.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); } out$3.walk = walk; function walkSync(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new sync_1$2.default(directory, settings); return provider.read(); } out$3.walkSync = walkSync; function walkStream(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new stream_1$4.default(directory, settings); return provider.read(); } out$3.walkStream = walkStream; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1$1.default) { return settingsOrOptions; } return new settings_1$1.default(settingsOrOptions); } var reader = {}; Object.defineProperty(reader, "__esModule", { value: true }); const path$4 = require$$0__default$1; const fsStat$2 = out$1; const utils$6 = utils$k; class Reader { constructor(_settings) { this._settings = _settings; this._fsStatSettings = new fsStat$2.Settings({ followSymbolicLink: this._settings.followSymbolicLinks, fs: this._settings.fs, throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks }); } _getFullEntryPath(filepath) { return path$4.resolve(this._settings.cwd, filepath); } _makeEntry(stats, pattern) { const entry = { name: pattern, path: pattern, dirent: utils$6.fs.createDirentFromStats(pattern, stats) }; if (this._settings.stats) { entry.stats = stats; } return entry; } _isFatalError(error) { return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; } } reader.default = Reader; var stream$2 = {}; Object.defineProperty(stream$2, "__esModule", { value: true }); const stream_1$3 = require$$0__default$3; const fsStat$1 = out$1; const fsWalk$2 = out$3; const reader_1$2 = reader; class ReaderStream extends reader_1$2.default { constructor() { super(...arguments); this._walkStream = fsWalk$2.walkStream; this._stat = fsStat$1.stat; } dynamic(root, options) { return this._walkStream(root, options); } static(patterns, options) { const filepaths = patterns.map(this._getFullEntryPath, this); const stream = new stream_1$3.PassThrough({ objectMode: true }); stream._write = (index, _enc, done) => { return this._getEntry(filepaths[index], patterns[index], options) .then((entry) => { if (entry !== null && options.entryFilter(entry)) { stream.push(entry); } if (index === filepaths.length - 1) { stream.end(); } done(); }) .catch(done); }; for (let i = 0; i < filepaths.length; i++) { stream.write(i); } return stream; } _getEntry(filepath, pattern, options) { return this._getStat(filepath) .then((stats) => this._makeEntry(stats, pattern)) .catch((error) => { if (options.errorFilter(error)) { return null; } throw error; }); } _getStat(filepath) { return new Promise((resolve, reject) => { this._stat(filepath, this._fsStatSettings, (error, stats) => { return error === null ? resolve(stats) : reject(error); }); }); } } stream$2.default = ReaderStream; Object.defineProperty(async$6, "__esModule", { value: true }); const fsWalk$1 = out$3; const reader_1$1 = reader; const stream_1$2 = stream$2; class ReaderAsync extends reader_1$1.default { constructor() { super(...arguments); this._walkAsync = fsWalk$1.walk; this._readerStream = new stream_1$2.default(this._settings); } dynamic(root, options) { return new Promise((resolve, reject) => { this._walkAsync(root, options, (error, entries) => { if (error === null) { resolve(entries); } else { reject(error); } }); }); } async static(patterns, options) { const entries = []; const stream = this._readerStream.static(patterns, options); // After #235, replace it with an asynchronous iterator. return new Promise((resolve, reject) => { stream.once('error', reject); stream.on('data', (entry) => entries.push(entry)); stream.once('end', () => resolve(entries)); }); } } async$6.default = ReaderAsync; var provider = {}; var deep = {}; var partial = {}; var matcher = {}; Object.defineProperty(matcher, "__esModule", { value: true }); const utils$5 = utils$k; class Matcher { constructor(_patterns, _settings, _micromatchOptions) { this._patterns = _patterns; this._settings = _settings; this._micromatchOptions = _micromatchOptions; this._storage = []; this._fillStorage(); } _fillStorage() { for (const pattern of this._patterns) { const segments = this._getPatternSegments(pattern); const sections = this._splitSegmentsIntoSections(segments); this._storage.push({ complete: sections.length <= 1, pattern, segments, sections }); } } _getPatternSegments(pattern) { const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions); return parts.map((part) => { const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings); if (!dynamic) { return { dynamic: false, pattern: part }; } return { dynamic: true, pattern: part, patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions) }; }); } _splitSegmentsIntoSections(segments) { return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern)); } } matcher.default = Matcher; Object.defineProperty(partial, "__esModule", { value: true }); const matcher_1 = matcher; class PartialMatcher extends matcher_1.default { match(filepath) { const parts = filepath.split('/'); const levels = parts.length; const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); for (const pattern of patterns) { const section = pattern.sections[0]; /** * In this case, the pattern has a globstar and we must read all directories unconditionally, * but only if the level has reached the end of the first group. * * fixtures/{a,b}/** * ^ true/false ^ always true */ if (!pattern.complete && levels > section.length) { return true; } const match = parts.every((part, index) => { const segment = pattern.segments[index]; if (segment.dynamic && segment.patternRe.test(part)) { return true; } if (!segment.dynamic && segment.pattern === part) { return true; } return false; }); if (match) { return true; } } return false; } } partial.default = PartialMatcher; Object.defineProperty(deep, "__esModule", { value: true }); const utils$4 = utils$k; const partial_1 = partial; class DeepFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; this._micromatchOptions = _micromatchOptions; } getFilter(basePath, positive, negative) { const matcher = this._getMatcher(positive); const negativeRe = this._getNegativePatternsRe(negative); return (entry) => this._filter(basePath, entry, matcher, negativeRe); } _getMatcher(patterns) { return new partial_1.default(patterns, this._settings, this._micromatchOptions); } _getNegativePatternsRe(patterns) { const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern); return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); } _filter(basePath, entry, matcher, negativeRe) { if (this._isSkippedByDeep(basePath, entry.path)) { return false; } if (this._isSkippedSymbolicLink(entry)) { return false; } const filepath = utils$4.path.removeLeadingDotSegment(entry.path); if (this._isSkippedByPositivePatterns(filepath, matcher)) { return false; } return this._isSkippedByNegativePatterns(filepath, negativeRe); } _isSkippedByDeep(basePath, entryPath) { /** * Avoid unnecessary depth calculations when it doesn't matter. */ if (this._settings.deep === Infinity) { return false; } return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; } _getEntryLevel(basePath, entryPath) { const entryPathDepth = entryPath.split('/').length; if (basePath === '') { return entryPathDepth; } const basePathDepth = basePath.split('/').length; return entryPathDepth - basePathDepth; } _isSkippedSymbolicLink(entry) { return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); } _isSkippedByPositivePatterns(entryPath, matcher) { return !this._settings.baseNameMatch && !matcher.match(entryPath); } _isSkippedByNegativePatterns(entryPath, patternsRe) { return !utils$4.pattern.matchAny(entryPath, patternsRe); } } deep.default = DeepFilter; var entry$1 = {}; Object.defineProperty(entry$1, "__esModule", { value: true }); const utils$3 = utils$k; class EntryFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; this._micromatchOptions = _micromatchOptions; this.index = new Map(); } getFilter(positive, negative) { const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions); const negativeRe = utils$3.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })); return (entry) => this._filter(entry, positiveRe, negativeRe); } _filter(entry, positiveRe, negativeRe) { const filepath = utils$3.path.removeLeadingDotSegment(entry.path); if (this._settings.unique && this._isDuplicateEntry(filepath)) { return false; } if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { return false; } if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) { return false; } const isDirectory = entry.dirent.isDirectory(); const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(filepath, negativeRe, isDirectory); if (this._settings.unique && isMatched) { this._createIndexRecord(filepath); } return isMatched; } _isDuplicateEntry(filepath) { return this.index.has(filepath); } _createIndexRecord(filepath) { this.index.set(filepath, undefined); } _onlyFileFilter(entry) { return this._settings.onlyFiles && !entry.dirent.isFile(); } _onlyDirectoryFilter(entry) { return this._settings.onlyDirectories && !entry.dirent.isDirectory(); } _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { if (!this._settings.absolute) { return false; } const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath); return utils$3.pattern.matchAny(fullpath, patternsRe); } _isMatchToPatterns(filepath, patternsRe, isDirectory) { // Trying to match files and directories by patterns. const isMatched = utils$3.pattern.matchAny(filepath, patternsRe); // A pattern with a trailling slash can be used for directory matching. // To apply such pattern, we need to add a tralling slash to the path. if (!isMatched && isDirectory) { return utils$3.pattern.matchAny(filepath + '/', patternsRe); } return isMatched; } } entry$1.default = EntryFilter; var error = {}; Object.defineProperty(error, "__esModule", { value: true }); const utils$2 = utils$k; class ErrorFilter { constructor(_settings) { this._settings = _settings; } getFilter() { return (error) => this._isNonFatalError(error); } _isNonFatalError(error) { return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors; } } error.default = ErrorFilter; var entry = {}; Object.defineProperty(entry, "__esModule", { value: true }); const utils$1 = utils$k; class EntryTransformer { constructor(_settings) { this._settings = _settings; } getTransformer() { return (entry) => this._transform(entry); } _transform(entry) { let filepath = entry.path; if (this._settings.absolute) { filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath); filepath = utils$1.path.unixify(filepath); } if (this._settings.markDirectories && entry.dirent.isDirectory()) { filepath += '/'; } if (!this._settings.objectMode) { return filepath; } return Object.assign(Object.assign({}, entry), { path: filepath }); } } entry.default = EntryTransformer; Object.defineProperty(provider, "__esModule", { value: true }); const path$3 = require$$0__default$1; const deep_1 = deep; const entry_1 = entry$1; const error_1 = error; const entry_2 = entry; class Provider { constructor(_settings) { this._settings = _settings; this.errorFilter = new error_1.default(this._settings); this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); this.entryTransformer = new entry_2.default(this._settings); } _getRootDirectory(task) { return path$3.resolve(this._settings.cwd, task.base); } _getReaderOptions(task) { const basePath = task.base === '.' ? '' : task.base; return { basePath, pathSegmentSeparator: '/', concurrency: this._settings.concurrency, deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), entryFilter: this.entryFilter.getFilter(task.positive, task.negative), errorFilter: this.errorFilter.getFilter(), followSymbolicLinks: this._settings.followSymbolicLinks, fs: this._settings.fs, stats: this._settings.stats, throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, transform: this.entryTransformer.getTransformer() }; } _getMicromatchOptions() { return { dot: this._settings.dot, matchBase: this._settings.baseNameMatch, nobrace: !this._settings.braceExpansion, nocase: !this._settings.caseSensitiveMatch, noext: !this._settings.extglob, noglobstar: !this._settings.globstar, posix: true, strictSlashes: false }; } } provider.default = Provider; Object.defineProperty(async$7, "__esModule", { value: true }); const async_1$1 = async$6; const provider_1$2 = provider; class ProviderAsync extends provider_1$2.default { constructor() { super(...arguments); this._reader = new async_1$1.default(this._settings); } async read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const entries = await this.api(root, task, options); return entries.map((entry) => options.transform(entry)); } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } async$7.default = ProviderAsync; var stream$1 = {}; Object.defineProperty(stream$1, "__esModule", { value: true }); const stream_1$1 = require$$0__default$3; const stream_2 = stream$2; const provider_1$1 = provider; class ProviderStream extends provider_1$1.default { constructor() { super(...arguments); this._reader = new stream_2.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const source = this.api(root, task, options); const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } }); source .once('error', (error) => destination.emit('error', error)) .on('data', (entry) => destination.emit('data', options.transform(entry))) .once('end', () => destination.emit('end')); destination .once('close', () => source.destroy()); return destination; } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } stream$1.default = ProviderStream; var sync$2 = {}; var sync$1 = {}; Object.defineProperty(sync$1, "__esModule", { value: true }); const fsStat = out$1; const fsWalk = out$3; const reader_1 = reader; class ReaderSync extends reader_1.default { constructor() { super(...arguments); this._walkSync = fsWalk.walkSync; this._statSync = fsStat.statSync; } dynamic(root, options) { return this._walkSync(root, options); } static(patterns, options) { const entries = []; for (const pattern of patterns) { const filepath = this._getFullEntryPath(pattern); const entry = this._getEntry(filepath, pattern, options); if (entry === null || !options.entryFilter(entry)) { continue; } entries.push(entry); } return entries; } _getEntry(filepath, pattern, options) { try { const stats = this._getStat(filepath); return this._makeEntry(stats, pattern); } catch (error) { if (options.errorFilter(error)) { return null; } throw error; } } _getStat(filepath) { return this._statSync(filepath, this._fsStatSettings); } } sync$1.default = ReaderSync; Object.defineProperty(sync$2, "__esModule", { value: true }); const sync_1$1 = sync$1; const provider_1 = provider; class ProviderSync extends provider_1.default { constructor() { super(...arguments); this._reader = new sync_1$1.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const entries = this.api(root, task, options); return entries.map(options.transform); } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } sync$2.default = ProviderSync; var settings = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; const fs = require$$0__default$4; const os = require$$0__default; /** * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 */ const CPU_COUNT = Math.max(os.cpus().length, 1); exports.DEFAULT_FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, lstatSync: fs.lstatSync, stat: fs.stat, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; class Settings { constructor(_options = {}) { this._options = _options; this.absolute = this._getValue(this._options.absolute, false); this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); this.braceExpansion = this._getValue(this._options.braceExpansion, true); this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); this.cwd = this._getValue(this._options.cwd, process.cwd()); this.deep = this._getValue(this._options.deep, Infinity); this.dot = this._getValue(this._options.dot, false); this.extglob = this._getValue(this._options.extglob, true); this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); this.fs = this._getFileSystemMethods(this._options.fs); this.globstar = this._getValue(this._options.globstar, true); this.ignore = this._getValue(this._options.ignore, []); this.markDirectories = this._getValue(this._options.markDirectories, false); this.objectMode = this._getValue(this._options.objectMode, false); this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); this.onlyFiles = this._getValue(this._options.onlyFiles, true); this.stats = this._getValue(this._options.stats, false); this.suppressErrors = this._getValue(this._options.suppressErrors, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); this.unique = this._getValue(this._options.unique, true); if (this.onlyDirectories) { this.onlyFiles = false; } if (this.stats) { this.objectMode = true; } } _getValue(option, value) { return option === undefined ? value : option; } _getFileSystemMethods(methods = {}) { return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); } } exports.default = Settings; } (settings)); const taskManager = tasks; const async_1 = async$7; const stream_1 = stream$1; const sync_1 = sync$2; const settings_1 = settings; const utils = utils$k; async function FastGlob(source, options) { assertPatternsInput(source); const works = getWorks(source, async_1.default, options); const result = await Promise.all(works); return utils.array.flatten(result); } // https://github.com/typescript-eslint/typescript-eslint/issues/60 // eslint-disable-next-line no-redeclare (function (FastGlob) { FastGlob.glob = FastGlob; FastGlob.globSync = sync; FastGlob.globStream = stream; FastGlob.async = FastGlob; function sync(source, options) { assertPatternsInput(source); const works = getWorks(source, sync_1.default, options); return utils.array.flatten(works); } FastGlob.sync = sync; function stream(source, options) { assertPatternsInput(source); const works = getWorks(source, stream_1.default, options); /** * The stream returned by the provider cannot work with an asynchronous iterator. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. * This affects performance (+25%). I don't see best solution right now. */ return utils.stream.merge(works); } FastGlob.stream = stream; function generateTasks(source, options) { assertPatternsInput(source); const patterns = [].concat(source); const settings = new settings_1.default(options); return taskManager.generate(patterns, settings); } FastGlob.generateTasks = generateTasks; function isDynamicPattern(source, options) { assertPatternsInput(source); const settings = new settings_1.default(options); return utils.pattern.isDynamicPattern(source, settings); } FastGlob.isDynamicPattern = isDynamicPattern; function escapePath(source) { assertPatternsInput(source); return utils.path.escape(source); } FastGlob.escapePath = escapePath; function convertPathToPattern(source) { assertPatternsInput(source); return utils.path.convertPathToPattern(source); } FastGlob.convertPathToPattern = convertPathToPattern; (function (posix) { function escapePath(source) { assertPatternsInput(source); return utils.path.escapePosixPath(source); } posix.escapePath = escapePath; function convertPathToPattern(source) { assertPatternsInput(source); return utils.path.convertPosixPathToPattern(source); } posix.convertPathToPattern = convertPathToPattern; })(FastGlob.posix || (FastGlob.posix = {})); (function (win32) { function escapePath(source) { assertPatternsInput(source); return utils.path.escapeWindowsPath(source); } win32.escapePath = escapePath; function convertPathToPattern(source) { assertPatternsInput(source); return utils.path.convertWindowsPathToPattern(source); } win32.convertPathToPattern = convertPathToPattern; })(FastGlob.win32 || (FastGlob.win32 = {})); })(FastGlob || (FastGlob = {})); function getWorks(source, _Provider, options) { const patterns = [].concat(source); const settings = new settings_1.default(options); const tasks = taskManager.generate(patterns, settings); const provider = new _Provider(settings); return tasks.map(provider.read, provider); } function assertPatternsInput(input) { const source = [].concat(input); const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); if (!isValidSource) { throw new TypeError('Patterns must be a string (non empty) or an array of strings'); } } var out = FastGlob; const fg = /*@__PURE__*/getDefaultExportFromCjs$1(out); function parseRoute(root) { let routeRoot = "src/routes"; if (root) routeRoot = root; const sfcPath = getAllSFCPath(["**/+page**.svelte"], path$3__default.resolve(routeRoot)); const routeInfoRes = []; for (let i = 0; i < sfcPath.length; i++) { if (sfcPath[i] === "+page.svelte") { routeInfoRes.push({ routePath: "/", filePath: `${routeRoot}` }); continue; } if (sfcPath[i].includes("/")) { const pathNode = sfcPath[i].split("/"); const routeInfoItem = { filePath: `${routeRoot}/${sfcPath[i]}`, routePath: "", params: [] }; pathNode.forEach((p) => { const param = p.match(/^\[(.*?)\]$/); if (param) { const paramOptional = param[1].match(/^\[(.*?)\]$/); if (paramOptional) { routeInfoItem.params && routeInfoItem.params.push({ optional: true, reset: false, name: paramOptional[1] }); } else { const paramReset = param[1].match(/^\.\.\.(.*?)$/); const paramMatcher = param[1].match(/^(.*?)=(.*?)$/); if (paramReset) { routeInfoItem.params && routeInfoItem.params.push({ optional: false, reset: true, name: paramReset[1] }); } else if (paramMatcher) { routeInfoItem.params && routeInfoItem.params.push({ optional: false, reset: false, name: paramMatcher[1], matcher: paramMatcher[2] }); } else { routeInfoItem.params && routeInfoItem.params.push({ optional: false, reset: false, name: param[1] }); } } } else { routeInfoItem.routePath = `${routeInfoItem.routePath}/${p.includes("+page") ? "" : p}`; } }); routeInfoRes.push(routeInfoItem); } } return routeInfoRes; } function getAllSFCPath(includeCompile, rootDir) { return fg.sync(includeCompile, { cwd: rootDir }); } const injectGotoContent = " if(__sdt_browser){\n window.__SVELTE_DEVTOOLS_GLOBAL_HOOK__.on('svelte:devtools:goto', (path, opts) => {\n __sdt_goto(path, opts)\n })\n }"; const injectGotoImport = "import { goto as __sdt_goto } from '$app/navigation';\n import { browser as __sdt_browser } from '$app/environment'\n"; function normalizeWindowsPath(input = "") { if (!input || !input.includes("\\")) { return input; } return input.replace(/\\/g, "/"); } const _UNC_REGEX = /^[/\\]{2}/; const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; const normalize = function(path) { if (path.length === 0) { return "."; } path = normalizeWindowsPath(path); const isUNCPath = path.match(_UNC_REGEX); const isPathAbsolute = isAbsolute(path); const trailingSeparator = path[path.length - 1] === "/"; path = normalizeString(path, !isPathAbsolute); if (path.length === 0) { if (isPathAbsolute) { return "/"; } return trailingSeparator ? "./" : "."; } if (trailingSeparator) { path += "/"; } if (_DRIVE_LETTER_RE.test(path)) { path += "/"; } if (isUNCPath) { if (!isPathAbsolute) { return `//./${path}`; } return `//${path}`; } return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; }; const join$1 = function(...arguments_) { if (arguments_.length === 0) { return "."; } let joined; for (const argument of arguments_) { if (argument && argument.length > 0) { if (joined === void 0) { joined = argument; } else { joined += `/${argument}`; } } } if (joined === void 0) { return "."; } return normalize(joined.replace(/\/\/+/g, "/")); }; function cwd() { if (typeof process !== "undefined") { return process.cwd().replace(/\\/g, "/"); } return "/"; } const resolve = function(...arguments_) { arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); let resolvedPath = ""; let resolvedAbsolute = false; for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { const path = index >= 0 ? arguments_[index] : cwd(); if (!path || path.length === 0) { continue; } resolvedPath = `${path}/${resolvedPath}`; resolvedAbsolute = isAbsolute(path); } resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); if (resolvedAbsolute && !isAbsolute(resolvedPath)) { return `/${resolvedPath}`; } return resolvedPath.length > 0 ? resolvedPath : "."; }; function normalizeString(path, allowAboveRoot) { let res = ""; let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; let char = null; for (let index = 0; index <= path.length; ++index) { if (index < path.length) { char = path[index]; } else if (char === "/") { break; } else { char = "/"; } if (char === "/") { if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) { if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { if (res.length > 2) { const lastSlashIndex = res.lastIndexOf("/"); if (lastSlashIndex === -1) { res = ""; lastSegmentLength = 0; } else { res = res.slice(0, lastSlashIndex); lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); } lastSlash = index; dots = 0; continue; } else if (res.length > 0) { res = ""; lastSegmentLength = 0; lastSlash = index; dots = 0; continue; } } if (allowAboveRoot) { res += res.length > 0 ? "/.." : ".."; lastSegmentLength = 2; } } else { if (res.length > 0) { res += `/${path.slice(lastSlash + 1, index)}`; } else { res = path.slice(lastSlash + 1, index); } lastSegmentLength = index - lastSlash - 1; } lastSlash = index; dots = 0; } else if (char === "." && dots !== -1) { ++dots; } else { dots = -1; } } return res; } const isAbsolute = function(p) { return _IS_ABSOLUTE_RE.test(p); }; async function getPackages(root) { const pkgPath = resolve(root, "package.json"); const data = JSON.parse(await fs$1$1.promises.readFile(pkgPath, "utf-8").catch(() => "{}")); const packages = {}; const depTypes = [ "dependencies", "devDependencies", "optionalDependencies", "peerDependencies" ]; for (const type of depTypes) { const dep = data[type]; if (!dep) continue; for (const depName in dep) { packages[depName] = { version: dep[depName], type }; } } return { packages }; } async function getSFCList(root, target = ["**/*.svelte"], ignore = ["**/node_modules/**", "**/dist/**"]) { const files = await fg(target, { cwd: root, onlyFiles: true, ignore }); return files; } const BMP = { validate(buffer) { return buffer.toString("ascii", 0, 2) === "BM"; }, calculate(buffer) { return { height: Math.abs(buffer.readInt32LE(22)), width: buffer.readUInt32LE(18) }; } }; const TYPE_ICON = 1; const SIZE_HEADER$1 = 2 + 2 + 2; const SIZE_IMAGE_ENTRY = 1 + 1 + 1 + 1 + 2 + 2 + 4 + 4; function getSizeFromOffset(buffer, offset) { const value = buffer.readUInt8(offset); return value === 0 ? 256 : value; } function getImageSize$1(buffer, imageIndex) { const offset = SIZE_HEADER$1 + imageIndex * SIZE_IMAGE_ENTRY; return { height: getSizeFromOffset(buffer, offset + 1), width: getSizeFromOffset(buffer, offset) }; } const ICO = { validate(buffer) { if (buffer.readUInt16LE(0) !== 0) { return false; } return buffer.readUInt16LE(2) === TYPE_ICON; }, calculate(buffer) { const nbImages = buffer.readUInt16LE(4); const imageSize = getImageSize$1(buffer, 0); if (nbImages === 1) { return imageSize; } const imgs = [imageSize]; for (let imageIndex = 1; imageIndex < nbImages; imageIndex += 1) { imgs.push(getImageSize$1(buffer, imageIndex)); } const result = { height: imageSize.height, images: imgs, width: imageSize.width }; return result; } }; const TYPE_CURSOR = 2; const CUR = { validate(buffer) { if (buffer.readUInt16LE(0) !== 0) { return false; } return buffer.readUInt16LE(2) === TYPE_CURSOR; }, calculate(buffer) { return ICO.calculate(buffer); } }; const DDS = { validate(buffer) { return buffer.readUInt32LE(0) === 542327876; }, calculate(buffer) { return { height: buffer.readUInt32LE(12), width: buffer.readUInt32LE(16) }; } }; const gifRegexp = /^GIF8[79]a/; const GIF = { validate(buffer) { const signature = buffer.toString("ascii", 0, 6); return gifRegexp.test(signature); }, calculate(buffer) { return { height: buffer.readUInt16LE(8), width: buffer.readUInt16LE(6) }; } }; const SIZE_HEADER = 4 + 4; const FILE_LENGTH_OFFSET = 4; const ENTRY_LENGTH_OFFSET = 4; const ICON_TYPE_SIZE = { ICON: 32, "ICN#": 32, "icm#": 16, icm4: 16, icm8: 16, "ics#": 16, ics4: 16, ics8: 16, is32: 16, s8mk: 16, icp4: 16, icl4: 32, icl8: 32, il32: 32, l8mk: 32, icp5: 32, ic11: 32, ich4: 48, ich8: 48, ih32: 48, h8mk: 48, icp6: 64, ic12: 32, it32: 128, t8mk: 128, ic07: 128, ic08: 256, ic13: 256, ic09: 512, ic14: 512, ic10: 1024 }; function readImageHeader(buffer, imageOffset) { const imageLengthOffset = imageOffset + ENTRY_LENGTH_OFFSET; return [ buffer.toString("ascii", imageOffset, imageLengthOffset), buffer.readUInt32BE(imageLengthOffset) ]; } function getImageSize(type) { const size = ICON_TYPE_SIZE[type]; return { width: size, height: size, type }; } const ICNS = { validate(buffer) { return buffer.toString("ascii", 0, 4) === "icns"; }, calculate(buffer) { const bufferLength = buffer.length; const fileLength = buffer.readUInt32BE(FILE_LENGTH_OFFSET); let imageOffset = SIZE_HEADER; let imageHeader = readImageHeader(buffer, imageOffset); let imageSize = getImageSize(imageHeader[0]); imageOffset += imageHeader[1]; if (imageOffset === fileLength) { return imageSize; } const result = { height: imageSize.height, images: [imageSize], width: imageSize.width }; while (imageOffset < fileLength && imageOffset < bufferLength) { imageHeader = readImageHeader(buffer, imageOffset); imageSize = getImageSize(imageHeader[0]); imageOffset += imageHeader[1]; result.images.push(imageSize); } return result; } }; const J2C = { validate(buffer) { return buffer.toString("hex", 0, 4) === "ff4fff51"; }, calculate(buffer) { return { height: buffer.readUInt32BE(12), width: buffer.readUInt32BE(8) }; } }; const BoxTypes = { ftyp: "66747970", ihdr: "69686472", jp2h: "6a703268", jp__: "6a502020", rreq: "72726571", xml_: "786d6c20" }; const calculateRREQLength = (box) => { const unit = box.readUInt8(0); let offset = 1 + 2 * unit; const numStdFlags = box.readUInt16BE(offset); const flagsLength = numStdFlags * (2 + unit); offset = offset + 2 + flagsLength; const numVendorFeatures = box.readUInt16BE(offset); const featuresLength = numVendorFeatures * (16 + unit); return offset + 2 + featuresLength; }; const parseIHDR = (box) => { return { height: box.readUInt32BE(4), width: box.readUInt32BE(8) }; }; const JP2 = { validate(buffer) { const signature = buffer.toString("hex", 4, 8); const signatureLength = buffer.readUInt32BE(0); if (signature !== BoxTypes.jp__ || signatureLength < 1) { return false; } const ftypeBoxStart = signatureLength + 4; const ftypBoxLength = buffer.readUInt32BE(signatureLength); const ftypBox = buffer.slice(ftypeBoxStart, ftypeBoxStart + ftypBoxLength); return ftypBox.toString("hex", 0, 4) === BoxTypes.ftyp; }, calculate(buffer) { const signatureLength = buffer.readUInt32BE(0); const ftypBoxLength = buffer.readUInt16BE(signatureLength + 2); let offset = signatureLength + 4 + ftypBoxLength; const nextBoxType = buffer.toString("hex", offset, offset + 4); switch (nextBoxType) { case BoxTypes.rreq: const MAGIC = 4; offset = offset + 4 + MAGIC + calculateRREQLength(buffer.slice(offset + 4)); return parseIHDR(buffer.slice(offset + 8, offset + 24)); case BoxTypes.jp2h: return parseIHDR(buffer.slice(offset + 8, offset + 24)); default: throw new TypeError("Unsupported header found: " + buffer.toString("ascii", offset, offset + 4)); } } }; function readUInt(buffer, bits, offset, isBigEndian) { offset = offset || 0; const endian = isBigEndian ? "BE" : "LE"; const methodName = "readUInt" + bits + endian; return buffer[methodName].call(buffer, offset); } const EXIF_MARKER = "45786966"; const APP1_DATA_SIZE_BYTES = 2; const EXIF_HEADER_BYTES = 6; const TIFF_BYTE_ALIGN_BYTES = 2; const BIG_ENDIAN_BYTE_ALIGN = "4d4d"; const LITTLE_ENDIAN_BYTE_ALIGN = "4949"; const IDF_ENTRY_BYTES = 12; const NUM_DIRECTORY_ENTRIES_BYTES = 2; function isEXIF(buffer) { return buffer.toString("hex", 2, 6) === EXIF_MARKER; } function extractSize(buffer, index) { return { height: buffer.readUInt16BE(index), width: buffer.readUInt16BE(index + 2) }; } function extractOrientation(exifBlock, isBigEndian) { const idfOffset = 8; const offset = EXIF_HEADER_BYTES + idfOffset; const idfDirectoryEntries = readUInt(exifBlock, 16, offset, isBigEndian); for (let directoryEntryNumber = 0; directoryEntryNumber < idfDirectoryEntries; directoryEntryNumber++) { const start = offset + NUM_DIRECTORY_ENTRIES_BYTES + directoryEntryNumber * IDF_ENTRY_BYTES; const end = start + IDF_ENTRY_BYTES; if (start > exifBlock.length) { return; } const block = exifBlock.slice(start, end); const tagNumber = readUInt(block, 16, 0, isBigEndian); if (tagNumber === 274) { const dataFormat = readUInt(block, 16, 2, isBigEndian); if (dataFormat !== 3) { return; } const numberOfComponents = readUInt(block, 32, 4, isBigEndian); if (numberOfComponents !== 1) { return; } return readUInt(block, 16, 8, isBigEndian); } } } function validateExifBlock(buffer, index) { const exifBlock = buffer.slice(APP1_DATA_SIZE_BYTES, index); const byteAlign = exifBlock.toString("hex", EXIF_HEADER_BYTES, EXIF_HEADER_BYTES + TIFF_BYTE_ALIGN_BYTES); const isBigEndian = byteAlign === BIG_ENDIAN_BYTE_ALIGN; const isLittleEndian = byteAlign === LITTLE_ENDIAN_BYTE_ALIGN; if (isBigEndian || isLittleEndian) { return extractOrientation(exifBlock, isBigEndian); } } function validateBuffer(buffer, index) { if (index > buffer.length) { throw new TypeError("Corrupt JPG, exceeded buffer limits"); } if (buffer[index] !== 255) { throw new TypeError("Invalid JPG, marker table corrupted"); } } const JPG = { validate(buffer) { const SOIMarker = buffer.toString("hex", 0, 2); return SOIMarker === "ffd8"; }, calculate(buffer) { buffer = buffer.slice(4); let orientation; let next; while (buffer.length) { const i = buffer.readUInt16BE(0); if (isEXIF(buffer)) { orientation = validateExifBlock(buffer, i); } validateBuffer(buffer, i); next = buffer[i + 1]; if (next === 192 || next === 193 || next === 194) { const size = extractSize(buffer, i + 5); if (!orientation) { return size; } return { height: size.height, orientation, width: size.width }; } buffer = buffer.slice(i + 2); } throw new TypeError("Invalid JPG, no size found"); } }; const SIGNATURE = "KTX 11"; const KTX = { validate(buffer) { return SIGNATURE === buffer.toString("ascii", 1, 7); }, calculate(buffer) { return { height: buffer.readUInt32LE(40), width: buffer.readUInt32LE(36) }; } }; const pngSignature = "PNG\r\n\n"; const pngImageHeaderChunkName = "IHDR"; const pngFriedChunkName = "CgBI"; const PNG = { validate(buffer) { if (pngSignature === buffer.toString("ascii", 1, 8)) { let chunkName = buffer.toString("ascii", 12, 16); if (chunkName === pngFriedChunkName) { chunkName = buffer.toString("ascii", 28, 32); } if (chunkName !== pngImageHeaderChunkName) { throw new TypeError("Invalid PNG"); } return true; } return false; }, calculate(buffer) { if (buffer.toString("ascii", 12, 16) === pngFriedChunkName) { return { height: buffer.readUInt32BE(36), width: buffer.readUInt32BE(32) }; } return { height: buffer.readUInt32BE(20), width: buffer.readUInt32BE(16) }; } }; const PNMTypes = { P1: "pbm/ascii", P2: "pgm/ascii", P3: "ppm/ascii", P4: "pbm", P5: "pgm", P6: "ppm", P7: "pam", PF: "pfm" }; const Signatures = Object.keys(PNMTypes); const handlers = { default: (lines) => { let dimensions = []; while (lines.length > 0) { const line = lines.shift(); if (line[0] === "#") { continue; } dimensions = line.split(" "); break; } if (dimensions.length === 2) { return { height: parseInt(dimensions[1], 10), width: parseInt(dimensions[0], 10) }; } else { throw new TypeError("Invalid PNM"); } }, pam: (lines) => { const size = {}; while (lines.length > 0) { const line = lines.shift(); if (line.length > 16 || line.charCodeAt(0) > 128) { continue; } const [key, value] = line.split(" "); if (key && value) { size[key.toLowerCase()] = parseInt(value, 10); } if (size.height && size.width) { break; } } if (size.height && size.width) { return { height: size.height, width: size.width }; } else { throw new TypeError("Invalid PAM"); } } }; const PNM = { validate(buffer) { const signature = buffer.toString("ascii", 0, 2); return Signatures.includes(signature); }, calculate(buffer) { const signature = buffer.toString("ascii", 0, 2); const type = PNMTypes[signature]; const lines = buffer.toString("ascii", 3).split(/[\r\n]+/); const handler = handlers[type] || handlers.default; return handler(lines); } }; const PSD = { validate(buffer) { return buffer.toString("ascii", 0, 4) === "8BPS"; }, calculate(buffer) { return { height: buffer.readUInt32BE(14), width: buffer.readUInt32BE(18) }; } }; const svgReg = /"']|"[^"]*"|'[^']*')*>/; const extractorRegExps = { height: /\sheight=(['"])([^%]+?)\1/, root: svgReg, viewbox: /\sviewBox=(['"])(.+?)\1/, width: /\swidth=(['"])([^%]+?)\1/ }; const INCH_CM = 2.54; const units = { cm: 96 / INCH_CM, em: 16, ex: 8, m: 96 / INCH_CM * 100, mm: 96 / INCH_CM / 10, pc: 96 / 72 / 12, pt: 96 / 72 }; function parseLength(len) { const m = /([0-9.]+)([a-z]*)/.exec(len); if (!m) { return void 0; } return Math.round(parseFloat(m[1]) * (units[m[2]] || 1)); } function parseViewbox(viewbox) { const bounds = viewbox.split(" "); return { height: parseLength(bounds[3]), width: parseLength(bounds[2]) }; } function parseAttributes(root) { const width = root.match(extractorRegExps.width); const height = root.match(extractorRegExps.height); const viewbox = root.match(extractorRegExps.viewbox); return { height: height && parseLength(height[2]), viewbox: viewbox && parseViewbox(viewbox[2]), width: width && parseLength(width[2]) }; } function calculateByDimensions(attrs) { return { height: attrs.height, width: attrs.width }; } function calculateByViewbox(attrs, viewbox) { const ratio = viewbox.width / viewbox.height; if (attrs.width) { return { height: Math.floor(attrs.width / ratio), width: attrs.width }; } if (attrs.height) { return { height: attrs.height, width: Math.floor(attrs.height * ratio) }; } return { height: viewbox.height, width: viewbox.width }; } const SVG = { validate(buffer) { const str = String(buffer); return svgReg.test(str); }, calculate(buffer) { const root = buffer.toString("utf8").match(extractorRegExps.root); if (root) { const attrs = parseAttributes(root[0]); if (attrs.width && attrs.height) { return calculateByDimensions(attrs); } if (attrs.viewbox) { return calculateByViewbox(attrs, attrs.viewbox); } } throw new TypeError("Invalid SVG"); } }; function calculateExtended(buffer) { return { height: 1 + buffer.readUIntLE(7, 3), width: 1 + buffer.readUIntLE(4, 3) }; } function calculateLossless(buffer) { return { height: 1 + ((buffer[4] & 15) << 10 | buffer[3] << 2 | (buffer[2] & 192) >> 6), width: 1 + ((buffer[2] & 63) << 8 | buffer[1]) }; } function calculateLossy(buffer) { return { height: buffer.readInt16LE(8) & 16383, width: buffer.readInt16LE(6) & 16383 }; } const WEBP = { validate(buffer) { const riffHeader = buffer.toString("ascii", 0, 4) === "RIFF"; const webpHeader = buffer.toString("ascii", 8, 12) === "WEBP"; const vp8Header = buffer.toString("ascii", 12, 15) === "VP8"; return riffHeader && webpHeader && vp8Header; }, calculate(buffer) { const chunkHeader = buffer.toString("ascii", 12, 16); buffer = buffer.slice(20, 30); if (chunkHeader === "VP8X") { const extendedHeader = buffer[0]; const validStart = (extendedHeader & 192) === 0; const validEnd = (extendedHeader & 1) === 0; if (validStart && validEnd) { return calculateExtended(buffer); } else { throw new TypeError("Invalid WebP"); } } if (chunkHeader === "VP8 " && buffer[0] !== 47) { return calculateLossy(buffer); } const signature = buffer.toString("hex", 3, 6); if (chunkHeader === "VP8L" && signature !== "9d012a") { return calculateLossless(buffer); } throw new TypeError("Invalid WebP"); } }; const typeHandlers = { bmp: BMP, cur: CUR, dds: DDS, gif: GIF, icns: ICNS, ico: ICO, j2c: J2C, jp2: JP2, jpg: JPG, ktx: KTX, png: PNG, pnm: PNM, psd: PSD, svg: SVG, webp: WEBP }; const getMimeType = (type) => { if (type === "svg") { return "image/svg+xml"; } return `image/${type}`; }; const keys = Object.keys(typeHandlers); const firstBytes = { 56: "psd", 66: "bmp", 68: "dds", 71: "gif", 73: "tiff", 77: "tiff", 82: "webp", 105: "icns", 137: "png", 255: "jpg" }; function detector(buffer) { const byte = buffer[0]; if (byte in firstBytes) { const type = firstBytes[byte]; if (typeHandlers[type].validate(buffer)) { return type; } } const finder = (key) => typeHandlers[key].validate(buffer); return keys.find(finder); } function lookup(buffer, filepath) { const type = detector(buffer); if (type && type in typeHandlers) { const size = typeHandlers[type].calculate(buffer, filepath); if (size !== void 0) { size.type = type; size.mimeType = getMimeType(type); return size; } } throw new TypeError("unsupported file type: " + type + " (file: " + filepath + ")"); } function imageMeta(input) { if (Buffer.isBuffer(input)) { return lookup(input); } throw new Error("Input should be buffer!"); } const _imageMetaCache = /* @__PURE__ */ new Map(); function guessType(path) { if (/\.(a?png|jpe?g|jxl|gif|svg|webp|avif|ico|bmp|tiff?)$/i.test(path)) return "image"; if (/\.(mp4|webm|ogv|mov|avi|flv|wmv|mpg|mpeg|mkv|3gp|3g2|ts|mts|m2ts|vob|ogm|ogx|rm|rmvb|asf|amv|divx|m4v|svi|viv|f4v|f4p|f4a|f4b)$/i.test(path)) return "video"; if (/\.(mp3|wav|ogg|flac|aac|wma|alac|ape|ac3|dts|tta|opus|amr|aiff|au|mid|midi|ra|rm|wv|weba|dss|spx|vox|tak|dsf|dff|dsd|cda)$/i.test(path)) return "audio"; if (/\.(woff2?|eot|ttf|otf|ttc|pfa|pfb|pfm|afm)/i.test(path)) return "font"; if (/\.(json[5c]?|te?xt|[mc]?[jt]sx?|md[cx]?|markdown)/i.test(path)) return "text"; return "other"; } async function getStaticAssets(config) { const dir = resolve(config.root); const baseURL = config.base; const files = await fg([ // image "**/*.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff)", // video "**/*.(mp4|webm|ogv|mov|avi|flv|wmv|mpg|mpeg|mkv|3gp|3g2|m2ts|vob|ogm|ogx|rm|rmvb|asf|amv|divx|m4v|svi|viv|f4v|f4p|f4a|f4b)", // audio "**/*.(mp3|wav|ogg|flac|aac|wma|alac|ape|ac3|dts|tta|opus|amr|aiff|au|mid|midi|ra|rm|wv|weba|dss|spx|vox|tak|dsf|dff|dsd|cda)", // font "**/*.(woff2?|eot|ttf|otf|ttc|pfa|pfb|pfm|afm)", // text "**/*.(json|json5|jsonc|txt|text|tsx|jsx|md|mdx|mdc|markdown)" ], { cwd: dir, onlyFiles: true, ignore: ["**/node_modules/**", "**/dist/**"] }); return await Promise.all(files.map(async (path) => { const filePath = resolve(dir, path); const stat = await fs__default.lstat(filePath); const publicDirname = path$3__default.relative(config.root, config.publicDir); const normalizedPath = publicDirname === path$3__default.basename(path$3__default.dirname(path)) ? path.replace(publicDirname, "") : path; return { path: normalizedPath, filePath, publicPath: join$1(baseURL, normalizedPath), type: guessType(path), size: stat.size, mtime: stat.mtimeMs }; })); } async function getImageMeta(filepath) { if (_imageMetaCache.has(filepath)) return _imageMetaCache.get(filepath); try { const meta = imageMeta(await fs__default.readFile(filepath)); _imageMetaCache.set(filepath, meta); return meta; } catch (e) { _imageMetaCache.set(filepath, void 0); console.error(e); return void 0; } } async function getTextAssetContent(filepath, limit = 300) { try { const content = await fs__default.readFile(filepath, "utf-8"); return content.slice(0, limit); } catch (e) { console.error(e); return void 0; } } const npmRun = (agent) => (args) => { if (args.length > 1) return `${agent} run ${args[0]} -- ${args.slice(1).join(" ")}`; else return `${agent} run ${args[0]}`; }; const yarn = { "agent": "yarn {0}", "run": "yarn run {0}", "install": "yarn install {0}", "frozen": "yarn install --frozen-lockfile", "global": "yarn global add {0}", "add": "yarn add {0}", "upgrade": "yarn upgrade {0}", "upgrade-interactive": "yarn upgrade-interactive {0}", "execute": "npx {0}", "uninstall": "yarn remove {0}", "global_uninstall": "yarn global remove {0}" }; const pnpm = { "agent": "pnpm {0}", "run": "pnpm run {0}", "install": "pnpm i {0}", "frozen": "pnpm i --frozen-lockfile", "global": "pnpm add -g {0}", "add": "pnpm add {0}", "upgrade": "pnpm update {0}", "upgrade-interactive": "pnpm update -i {0}", "execute": "pnpm dlx {0}", "uninstall": "pnpm remove {0}", "global_uninstall": "pnpm remove --global {0}" }; const bun = { "agent": "bun {0}", "run": "bun run {0}", "install": "bun install {0}", "frozen": "bun install --no-save", "global": "bun add -g {0}", "add": "bun add {0}", "upgrade": null, "upgrade-interactive": null, "execute": "bunx {0}", "uninstall": "bun remove {0}", "global_uninstall": "bun remove -g {0}" }; const AGENTS = { "npm": { "agent": "npm {0}", "run": npmRun("npm"), "install": "npm i {0}", "frozen": "npm ci", "global": "npm i -g {0}", "add": "npm i {0}", "upgrade": "npm update {0}", "upgrade-interactive": null, "execute": "npx {0}", "uninstall": "npm uninstall {0}", "global_uninstall": "npm uninstall -g {0}" }, "yarn": yarn, "yarn@berry": { ...yarn, "frozen": "yarn install --immutable", "upgrade": "yarn up {0}", "upgrade-interactive": "yarn up -i {0}", "execute": "yarn dlx {0}", // Yarn 2+ removed 'global', see https://github.com/yarnpkg/berry/issues/821 "global": "npm i -g {0}", "global_uninstall": "npm uninstall -g {0}" }, "pnpm": pnpm, // pnpm v6.x or below "pnpm@6": { ...pnpm, run: npmRun("pnpm") }, "bun": bun }; const LOCKS = { "bun.lockb": "bun", "pnpm-lock.yaml": "pnpm", "yarn.lock": "yarn", "package-lock.json": "npm", "npm-shrinkwrap.json": "npm" }; const INSTALL_PAGE = { "bun": "https://bun.sh", "pnpm": "https://pnpm.io/installation", "pnpm@6": "https://pnpm.io/6.x/installation", "yarn": "https://classic.yarnpkg.com/en/docs/install", "yarn@berry": "https://yarnpkg.com/getting-started/install", "npm": "https://docs.npmjs.com/cli/v8/configuring-npm/install" }; 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; } /* istanbul ignore next */ typeof process !== 'undefined' && process.platform === 'win32' ? '\r\n' : '\n'; /* How it works: `this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value. */ class Node { value; next; constructor(value) { this.value = value; } } class Queue { #head; #tail; #size; constructor() { this.clear(); } enqueue(value) { const node = new Node(value); if (this.#head) { this.#tail.next = node; this.#tail = node; } else { this.#head = node; this.#tail = node; } this.#size++; } dequeue() { const current = this.#head; if (!current) { return; } this.#head = this.#head.next; this.#size--; return current.value; } clear() { this.#head = undefined; this.#tail = undefined; this.#size = 0; } get size() { return this.#size; } * [Symbol.iterator]() { let current = this.#head; while (current) { yield current.value; current = current.next; } } } function pLimit(concurrency) { if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) { throw new TypeError('Expected `concurrency` to be a number from 1 and up'); } const queue = new Queue(); let activeCount = 0; const next = () => { activeCount--; if (queue.size > 0) { queue.dequeue()(); } }; const run = async (fn, resolve, args) => { activeCount++; const result = (async () => fn(...args))(); resolve(result); try { await result; } catch {} next(); }; const enqueue = (fn, resolve, args) => { queue.enqueue(run.bind(undefined, fn, resolve, args)); (async () => { // This function needs to wait until the next microtask before comparing // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously // when the run function is dequeued and called. The comparison in the if-statement // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. await Promise.resolve(); if (activeCount < concurrency && queue.size > 0) { queue.dequeue()(); } })(); }; const generator = (fn, ...args) => new Promise(resolve => { enqueue(fn, resolve, args); }); Object.defineProperties(generator, { activeCount: { get: () => activeCount, }, pendingCount: { get: () => queue.size, }, clearQueue: { value: () => { queue.clear(); }, }, }); return generator; } class EndError extends Error { constructor(value) { super(); this.value = value; } } // The input can also be a promise, so we await it. const testElement = async (element, tester) => tester(await element); // The input can also be a promise, so we `Promise.all()` them both. const finder = async element => { const values = await Promise.all(element); if (values[1] === true) { throw new EndError(values[0]); } return false; }; async function pLocate( iterable, tester, { concurrency = Number.POSITIVE_INFINITY, preserveOrder = true, } = {}, ) { const limit = pLimit(concurrency); // Start all the promises concurrently with optional limit. const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); // Check the promises either serially or concurrently. const checkLimit = pLimit(preserveOrder ? 1 : Number.POSITIVE_INFINITY); try { await Promise.all(items.map(element => checkLimit(finder, element))); } catch (error) { if (error instanceof EndError) { return error.value; } throw error; } } const typeMappings = { directory: 'isDirectory', file: 'isFile', }; function checkType(type) { if (type in typeMappings) { return; } throw new Error(`Invalid type specified: ${type}`); } const matchType = (type, stat) => type === undefined || stat[typeMappings[type]](); const toPath$1 = urlOrPath => urlOrPath instanceof URL ? url.fileURLToPath(urlOrPath) : urlOrPath; async function locatePath( paths, { cwd = process$2__default.cwd(), type = 'file', allowSymlinks = true, concurrency, preserveOrder, } = {}, ) { checkType(type); cwd = toPath$1(cwd); const statFunction = allowSymlinks ? fs$1$1.promises.stat : fs$1$1.promises.lstat; return pLocate(paths, async path_ => { try { const stat = await statFunction(path$3__default.resolve(cwd, path_)); return matchType(type, stat); } catch { return false; } }, {concurrency, preserveOrder}); } const toPath = urlOrPath => urlOrPath instanceof URL ? url.fileURLToPath(urlOrPath) : urlOrPath; const findUpStop = Symbol('findUpStop'); async function findUpMultiple(name, options = {}) { let directory = path$3__default.resolve(toPath(options.cwd) || ''); const {root} = path$3__default.parse(directory); const stopAt = path$3__default.resolve(directory, options.stopAt || root); const limit = options.limit || Number.POSITIVE_INFINITY; const paths = [name].flat(); const runMatcher = async locateOptions => { if (typeof name !== 'function') { return locatePath(paths, locateOptions); } const foundPath = await name(locateOptions.cwd); if (typeof foundPath === 'string') { return locatePath([foundPath], locateOptions); } return foundPath; }; const matches = []; // eslint-disable-next-line no-constant-condition while (true) { // eslint-disable-next-line no-await-in-loop const foundPath = await runMatcher({...options, cwd: directory}); if (foundPath === findUpStop) { break; } if (foundPath) { matches.push(path$3__default.resolve(directory, foundPath)); } if (directory === stopAt || matches.length >= limit) { break; } directory = path$3__default.dirname(directory); } return matches; } async function findUp(name, options = {}) { const matches = await findUpMultiple(name, {...options, limit: 1}); return matches[0]; } process.env.NI_CONFIG_FILE; const home = process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME; path$3__default.join(home || "~/", ".nirc"); 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$4; 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$4; 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$2; isexe$2.sync = sync; function isexe$2 (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$2(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$1 = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys'; const path$2 = require$$0__default$1; const COLON = isWindows$1 ? ';' : ':'; const isexe$1 = isexe_1; const getNotFoundError$1 = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); const getPathInfo$1 = (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$1 && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows$1 ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ); const pathExtExe = isWindows$1 ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : ''; const pathExt = isWindows$1 ? pathExtExe.split(colon) : ['']; if (isWindows$1) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift(''); } return { pathEnv, pathExt, pathExtExe, } }; const which$2 = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt; opt = {}; } if (!opt) opt = {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo$1(cmd, opt); const found = []; const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError$1(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$1(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$1 = (cmd, opt) => { opt = opt || {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo$1(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$1.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$1(cmd) }; var which_1 = which$2; which$2.sync = whichSync$1; var pathKeyExports = {}; var pathKey$2 = { get exports(){ return pathKeyExports; }, set exports(v){ pathKeyExports = v; }, }; const pathKey$1 = (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$2.exports = pathKey$1; // TODO: Remove this for the next major release pathKeyExports.default = pathKey$1; const path$1 = require$$0__default$1; const which$1 = 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$1.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$4; 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__default$1; const resolveCommand = resolveCommand_1; const escape = _escape; const readShebang = readShebang_1; const isWin$2 = 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$2) { 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.command(parsed.command); parsed.args = parsed.args.map((arg) => escape.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$1 = 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$1) { 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$1 && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawn'); } return null; } function verifyENOENTSync(status, parsed) { if (isWin$1 && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawnSync'); } return null; } var enoent$1 = { hookChildProcess, verifyENOENT, verifyENOENTSync, notFoundError, }; const cp = require$$0$2__default; 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; function stripFinalNewline(input) { const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); if (input[input.length - 1] === LF) { input = input.slice(0, -1); } if (input[input.length - 1] === CR) { input = input.slice(0, -1); } return input; } function pathKey(options = {}) { const { env = process.env, platform = process.platform } = options; if (platform !== 'win32') { return 'PATH'; } return Object.keys(env).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; } function npmRunPath(options = {}) { const { cwd = process$2__default.cwd(), path: path_ = process$2__default.env[pathKey()], execPath = process$2__default.execPath, } = options; let previous; const cwdString = cwd instanceof URL ? url__default.fileURLToPath(cwd) : cwd; let cwdPath = path$3__default.resolve(cwdString); const result = []; while (previous !== cwdPath) { result.push(path$3__default.join(cwdPath, 'node_modules/.bin')); previous = cwdPath; cwdPath = path$3__default.resolve(cwdPath, '..'); } // Ensure the running `node` binary is used. result.push(path$3__default.resolve(cwdString, execPath, '..')); return [...result, path_].join(path$3__default.delimiter); } function npmRunPathEnv({env = process$2__default.env, ...options} = {}) { env = {...env}; const path = pathKey({env}); options.path = env[path]; env[path] = npmRunPath(options); return env; } const copyProperty = (to, from, property, ignoreNonConfigurable) => { // `Function#length` should reflect the parameters of `to` not `from` since we keep its body. // `Function#prototype` is non-writable and non-configurable so can never be modified. if (property === 'length' || property === 'prototype') { return; } // `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here. if (property === 'arguments' || property === 'caller') { return; } const toDescriptor = Object.getOwnPropertyDescriptor(to, property); const fromDescriptor = Object.getOwnPropertyDescriptor(from, property); if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) { return; } Object.defineProperty(to, property, fromDescriptor); }; // `Object.defineProperty()` throws if the property exists, is not configurable and either: // - one its descriptors is changed // - it is non-writable and its value is changed const canCopyProperty = function (toDescriptor, fromDescriptor) { return toDescriptor === undefined || toDescriptor.configurable || ( toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value) ); }; const changePrototype = (to, from) => { const fromPrototype = Object.getPrototypeOf(from); if (fromPrototype === Object.getPrototypeOf(to)) { return; } Object.setPrototypeOf(to, fromPrototype); }; const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`; const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString'); const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name'); // We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected. // We use `bind()` instead of a closure for the same reason. // Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times. const changeToString = (to, from, name) => { const withName = name === '' ? '' : `with ${name.trim()}() `; const newToString = wrappedToString.bind(null, withName, from.toString()); // Ensure `to.toString.toString` is non-enumerable and has the same `same` Object.defineProperty(newToString, 'name', toStringName); Object.defineProperty(to, 'toString', {...toStringDescriptor, value: newToString}); }; function mimicFunction(to, from, {ignoreNonConfigurable = false} = {}) { const {name} = to; for (const property of Reflect.ownKeys(from)) { copyProperty(to, from, property, ignoreNonConfigurable); } changePrototype(to, from); changeToString(to, from, name); return to; } const calledFunctions = new WeakMap(); const onetime = (function_, options = {}) => { if (typeof function_ !== 'function') { throw new TypeError('Expected a function'); } let returnValue; let callCount = 0; const functionName = function_.displayName || function_.name || ''; const onetime = function (...arguments_) { calledFunctions.set(onetime, ++callCount); if (callCount === 1) { returnValue = function_.apply(this, arguments_); function_ = null; } else if (options.throw === true) { throw new Error(`Function \`${functionName}\` can only be called once`); } return returnValue; }; mimicFunction(onetime, function_); calledFunctions.set(onetime, callCount); return onetime; }; onetime.callCount = function_ => { if (!calledFunctions.has(function_)) { throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); } return calledFunctions.get(function_); }; const getRealtimeSignals=()=>{ const length=SIGRTMAX-SIGRTMIN+1; return Array.from({length},getRealtimeSignal); }; const getRealtimeSignal=(value,index)=>({ name:`SIGRT${index+1}`, number:SIGRTMIN+index, action:"terminate", description:"Application-specific signal (realtime)", standard:"posix" }); const SIGRTMIN=34; const SIGRTMAX=64; const SIGNALS=[ { name:"SIGHUP", number:1, action:"terminate", description:"Terminal closed", standard:"posix" }, { name:"SIGINT", number:2, action:"terminate", description:"User interruption with CTRL-C", standard:"ansi" }, { name:"SIGQUIT", number:3, action:"core", description:"User interruption with CTRL-\\", standard:"posix" }, { name:"SIGILL", number:4, action:"core", description:"Invalid machine instruction", standard:"ansi" }, { name:"SIGTRAP", number:5, action:"core", description:"Debugger breakpoint", standard:"posix" }, { name:"SIGABRT", number:6, action:"core", description:"Aborted", standard:"ansi" }, { name:"SIGIOT", number:6, action:"core", description:"Aborted", standard:"bsd" }, { name:"SIGBUS", number:7, action:"core", description: "Bus error due to misaligned, non-existing address or paging error", standard:"bsd" }, { name:"SIGEMT", number:7, action:"terminate", description:"Command should be emulated but is not implemented", standard:"other" }, { name:"SIGFPE", number:8, action:"core", description:"Floating point arithmetic error", standard:"ansi" }, { name:"SIGKILL", number:9, action:"terminate", description:"Forced termination", standard:"posix", forced:true }, { name:"SIGUSR1", number:10, action:"terminate", description:"Application-specific signal", standard:"posix" }, { name:"SIGSEGV", number:11, action:"core", description:"Segmentation fault", standard:"ansi" }, { name:"SIGUSR2", number:12, action:"terminate", description:"Application-specific signal", standard:"posix" }, { name:"SIGPIPE", number:13, action:"terminate", description:"Broken pipe or socket", standard:"posix" }, { name:"SIGALRM", number:14, action:"terminate", description:"Timeout or timer", standard:"posix" }, { name:"SIGTERM", number:15, action:"terminate", description:"Termination", standard:"ansi" }, { name:"SIGSTKFLT", number:16, action:"terminate", description:"Stack is empty or overflowed", standard:"other" }, { name:"SIGCHLD", number:17, action:"ignore", description:"Child process terminated, paused or unpaused", standard:"posix" }, { name:"SIGCLD", number:17, action:"ignore", description:"Child process terminated, paused or unpaused", standard:"other" }, { name:"SIGCONT", number:18, action:"unpause", description:"Unpaused", standard:"posix", forced:true }, { name:"SIGSTOP", number:19, action:"pause", description:"Paused", standard:"posix", forced:true }, { name:"SIGTSTP", number:20, action:"pause", description:"Paused using CTRL-Z or \"suspend\"", standard:"posix" }, { name:"SIGTTIN", number:21, action:"pause", description:"Background process cannot read terminal input", standard:"posix" }, { name:"SIGBREAK", number:21, action:"terminate", description:"User interruption with CTRL-BREAK", standard:"other" }, { name:"SIGTTOU", number:22, action:"pause", description:"Background process cannot write to terminal output", standard:"posix" }, { name:"SIGURG", number:23, action:"ignore", description:"Socket received out-of-band data", standard:"bsd" }, { name:"SIGXCPU", number:24, action:"core", description:"Process timed out", standard:"bsd" }, { name:"SIGXFSZ", number:25, action:"core", description:"File too big", standard:"bsd" }, { name:"SIGVTALRM", number:26, action:"terminate", description:"Timeout or timer", standard:"bsd" }, { name:"SIGPROF", number:27, action:"terminate", description:"Timeout or timer", standard:"bsd" }, { name:"SIGWINCH", number:28, action:"ignore", description:"Terminal window size changed", standard:"bsd" }, { name:"SIGIO", number:29, action:"terminate", description:"I/O is available", standard:"other" }, { name:"SIGPOLL", number:29, action:"terminate", description:"Watched event", standard:"other" }, { name:"SIGINFO", number:29, action:"ignore", description:"Request for process information", standard:"other" }, { name:"SIGPWR", number:30, action:"terminate", description:"Device running out of power", standard:"systemv" }, { name:"SIGSYS", number:31, action:"core", description:"Invalid system call", standard:"other" }, { name:"SIGUNUSED", number:31, action:"terminate", description:"Invalid system call", standard:"other" }]; const getSignals=()=>{ const realtimeSignals=getRealtimeSignals(); const signals=[...SIGNALS,...realtimeSignals].map(normalizeSignal); return signals; }; const normalizeSignal=({ name, number:defaultNumber, description, action, forced=false, standard })=>{ const{ signals:{[name]:constantSignal} }=os$1$1.constants; const supported=constantSignal!==undefined; const number=supported?constantSignal:defaultNumber; return {name,number,description,supported,action,forced,standard}; }; const getSignalsByName=()=>{ const signals=getSignals(); return Object.fromEntries(signals.map(getSignalByName)); }; const getSignalByName=({ name, number, description, supported, action, forced, standard })=>[name,{name,number,description,supported,action,forced,standard}]; const signalsByName=getSignalsByName(); const getSignalsByNumber=()=>{ const signals=getSignals(); const length=SIGRTMAX+1; const signalsA=Array.from({length},(value,number)=> getSignalByNumber(number,signals)); return Object.assign({},...signalsA); }; const getSignalByNumber=(number,signals)=>{ const signal=findSignalByNumber(number,signals); if(signal===undefined){ return {}; } const{name,description,supported,action,forced,standard}=signal; return { [number]:{ name, number, description, supported, action, forced, standard } }; }; const findSignalByNumber=(number,signals)=>{ const signal=signals.find(({name})=>os$1$1.constants.signals[name]===number); if(signal!==undefined){ return signal; } return signals.find((signalA)=>signalA.number===number); }; getSignalsByNumber(); const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { if (timedOut) { return `timed out after ${timeout} milliseconds`; } if (isCanceled) { return 'was canceled'; } if (errorCode !== undefined) { return `failed with ${errorCode}`; } if (signal !== undefined) { return `was killed with ${signal} (${signalDescription})`; } if (exitCode !== undefined) { return `failed with exit code ${exitCode}`; } return 'failed'; }; const makeError = ({ stdout, stderr, all, error, signal, exitCode, command, escapedCommand, timedOut, isCanceled, killed, parsed: {options: {timeout}}, }) => { // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. // We normalize them to `undefined` exitCode = exitCode === null ? undefined : exitCode; signal = signal === null ? undefined : signal; const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; const errorCode = error && error.code; const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); const execaMessage = `Command ${prefix}: ${command}`; const isError = Object.prototype.toString.call(error) === '[object Error]'; const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); if (isError) { error.originalMessage = error.message; error.message = message; } else { error = new Error(message); } error.shortMessage = shortMessage; error.command = command; error.escapedCommand = escapedCommand; error.exitCode = exitCode; error.signal = signal; error.signalDescription = signalDescription; error.stdout = stdout; error.stderr = stderr; if (all !== undefined) { error.all = all; } if ('bufferedData' in error) { delete error.bufferedData; } error.failed = true; error.timedOut = Boolean(timedOut); error.isCanceled = isCanceled; error.killed = killed && !timedOut; return error; }; const aliases = ['stdin', 'stdout', 'stderr']; const hasAlias = options => aliases.some(alias => options[alias] !== undefined); const normalizeStdio = options => { if (!options) { return; } const {stdio} = options; if (stdio === undefined) { return aliases.map(alias => options[alias]); } if (hasAlias(options)) { throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); } if (typeof stdio === 'string') { return stdio; } if (!Array.isArray(stdio)) { throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); } const length = Math.max(stdio.length, aliases.length); return Array.from({length}, (value, index) => stdio[index]); }; var signalExitExports = {}; var signalExit = { get exports(){ return signalExitExports; }, set exports(v){ signalExitExports = v; }, }; var signalsExports = {}; var signals$1 = { get exports(){ return signalsExports; }, set exports(v){ signalsExports = v; }, }; var hasRequiredSignals; function requireSignals () { if (hasRequiredSignals) return signalsExports; hasRequiredSignals = 1; (function (module) { // This is not the set of all possible signals. // // It IS, however, the set of all signals that trigger // an exit on either Linux or BSD systems. Linux is a // superset of the signal names supported on BSD, and // the unknown signals just fail to register, so we can // catch that easily enough. // // Don't bother with SIGKILL. It's uncatchable, which // means that we can't fire any callbacks anyway. // // If a user does happen to register a handler on a non- // fatal signal like SIGWINCH or something, and then // exit, it'll end up firing `process.emit('exit')`, so // the handler will be fired anyway. // // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised // artificially, inherently leave the process in a // state from which it is not safe to try and enter JS // listeners. module.exports = [ 'SIGABRT', 'SIGALRM', 'SIGHUP', 'SIGINT', 'SIGTERM' ]; if (process.platform !== 'win32') { module.exports.push( 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT' // should detect profiler and enable/disable accordingly. // see #21 // 'SIGPROF' ); } if (process.platform === 'linux') { module.exports.push( 'SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED' ); } } (signals$1)); return signalsExports; } // Note: since nyc uses this module to output coverage, any lines // that are in the direct sync flow of nyc's outputCoverage are // ignored, since we can never get coverage for them. // grab a reference to node's real process object right away var process$1 = commonjsGlobal.process; const processOk = function (process) { return process && typeof process === 'object' && typeof process.removeListener === 'function' && typeof process.emit === 'function' && typeof process.reallyExit === 'function' && typeof process.listeners === 'function' && typeof process.kill === 'function' && typeof process.pid === 'number' && typeof process.on === 'function' }; // some kind of non-node environment, just no-op /* istanbul ignore if */ if (!processOk(process$1)) { signalExit.exports = function () { return function () {} }; } else { var assert = require$$0$3__default; var signals = requireSignals(); var isWin = /^win/i.test(process$1.platform); var EE = require$$2__default; /* istanbul ignore if */ if (typeof EE !== 'function') { EE = EE.EventEmitter; } var emitter; if (process$1.__signal_exit_emitter__) { emitter = process$1.__signal_exit_emitter__; } else { emitter = process$1.__signal_exit_emitter__ = new EE(); emitter.count = 0; emitter.emitted = {}; } // Because this emitter is a global, we have to check to see if a // previous version of this library failed to enable infinite listeners. // I know what you're about to say. But literally everything about // signal-exit is a compromise with evil. Get used to it. if (!emitter.infinite) { emitter.setMaxListeners(Infinity); emitter.infinite = true; } signalExit.exports = function (cb, opts) { /* istanbul ignore if */ if (!processOk(commonjsGlobal.process)) { return function () {} } assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler'); if (loaded === false) { load(); } var ev = 'exit'; if (opts && opts.alwaysLast) { ev = 'afterexit'; } var remove = function () { emitter.removeListener(ev, cb); if (emitter.listeners('exit').length === 0 && emitter.listeners('afterexit').length === 0) { unload(); } }; emitter.on(ev, cb); return remove }; var unload = function unload () { if (!loaded || !processOk(commonjsGlobal.process)) { return } loaded = false; signals.forEach(function (sig) { try { process$1.removeListener(sig, sigListeners[sig]); } catch (er) {} }); process$1.emit = originalProcessEmit; process$1.reallyExit = originalProcessReallyExit; emitter.count -= 1; }; signalExitExports.unload = unload; var emit = function emit (event, code, signal) { /* istanbul ignore if */ if (emitter.emitted[event]) { return } emitter.emitted[event] = true; emitter.emit(event, code, signal); }; // { : , ... } var sigListeners = {}; signals.forEach(function (sig) { sigListeners[sig] = function listener () { /* istanbul ignore if */ if (!processOk(commonjsGlobal.process)) { return } // If there are no other listeners, an exit is coming! // Simplest way: remove us and then re-send the signal. // We know that this will kill the process, so we can // safely emit now. var listeners = process$1.listeners(sig); if (listeners.length === emitter.count) { unload(); emit('exit', null, sig); /* istanbul ignore next */ emit('afterexit', null, sig); /* istanbul ignore next */ if (isWin && sig === 'SIGHUP') { // "SIGHUP" throws an `ENOSYS` error on Windows, // so use a supported signal instead sig = 'SIGINT'; } /* istanbul ignore next */ process$1.kill(process$1.pid, sig); } }; }); signalExitExports.signals = function () { return signals }; var loaded = false; var load = function load () { if (loaded || !processOk(commonjsGlobal.process)) { return } loaded = true; // This is the number of onSignalExit's that are in play. // It's important so that we can count the correct number of // listeners on signals, and don't wait for the other one to // handle it instead of us. emitter.count += 1; signals = signals.filter(function (sig) { try { process$1.on(sig, sigListeners[sig]); return true } catch (er) { return false } }); process$1.emit = processEmit; process$1.reallyExit = processReallyExit; }; signalExitExports.load = load; var originalProcessReallyExit = process$1.reallyExit; var processReallyExit = function processReallyExit (code) { /* istanbul ignore if */ if (!processOk(commonjsGlobal.process)) { return } process$1.exitCode = code || /* istanbul ignore next */ 0; emit('exit', process$1.exitCode, null); /* istanbul ignore next */ emit('afterexit', process$1.exitCode, null); /* istanbul ignore next */ originalProcessReallyExit.call(process$1, process$1.exitCode); }; var originalProcessEmit = process$1.emit; var processEmit = function processEmit (ev, arg) { if (ev === 'exit' && processOk(commonjsGlobal.process)) { /* istanbul ignore else */ if (arg !== undefined) { process$1.exitCode = arg; } var ret = originalProcessEmit.apply(this, arguments); /* istanbul ignore next */ emit('exit', process$1.exitCode, null); /* istanbul ignore next */ emit('afterexit', process$1.exitCode, null); /* istanbul ignore next */ return ret } else { return originalProcessEmit.apply(this, arguments) } }; } const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; // Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => { const killResult = kill(signal); setKillTimeout(kill, signal, options, killResult); return killResult; }; const setKillTimeout = (kill, signal, options, killResult) => { if (!shouldForceKill(signal, options, killResult)) { return; } const timeout = getForceKillAfterTimeout(options); const t = setTimeout(() => { kill('SIGKILL'); }, timeout); // Guarded because there's no `.unref()` when `execa` is used in the renderer // process in Electron. This cannot be tested since we don't run tests in // Electron. // istanbul ignore else if (t.unref) { t.unref(); } }; const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult; const isSigterm = signal => signal === os$1__default.constants.signals.SIGTERM || (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { if (forceKillAfterTimeout === true) { return DEFAULT_FORCE_KILL_TIMEOUT; } if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); } return forceKillAfterTimeout; }; // `childProcess.cancel()` const spawnedCancel = (spawned, context) => { const killResult = spawned.kill(); if (killResult) { context.isCanceled = true; } }; const timeoutKill = (spawned, signal, reject) => { spawned.kill(signal); reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); }; // `timeout` option handling const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { if (timeout === 0 || timeout === undefined) { return spawnedPromise; } let timeoutId; const timeoutPromise = new Promise((resolve, reject) => { timeoutId = setTimeout(() => { timeoutKill(spawned, killSignal, reject); }, timeout); }); const safeSpawnedPromise = spawnedPromise.finally(() => { clearTimeout(timeoutId); }); return Promise.race([timeoutPromise, safeSpawnedPromise]); }; const validateTimeout = ({timeout}) => { if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); } }; // `cleanup` option handling const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => { if (!cleanup || detached) { return timedPromise; } const removeExitHandler = signalExitExports(() => { spawned.kill(); }); return timedPromise.finally(() => { removeExitHandler(); }); }; function isStream(stream) { return stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function'; } function isWritableStream(stream) { return isStream(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object'; } const isExecaChildProcess = target => target instanceof childProcess.ChildProcess && typeof target.then === 'function'; const pipeToTarget = (spawned, streamName, target) => { if (typeof target === 'string') { spawned[streamName].pipe(fs$1$1.createWriteStream(target)); return spawned; } if (isWritableStream(target)) { spawned[streamName].pipe(target); return spawned; } if (!isExecaChildProcess(target)) { throw new TypeError('The second argument must be a string, a stream or an Execa child process.'); } if (!isWritableStream(target.stdin)) { throw new TypeError('The target child process\'s stdin must be available.'); } spawned[streamName].pipe(target.stdin); return target; }; const addPipeMethods = spawned => { if (spawned.stdout !== null) { spawned.pipeStdout = pipeToTarget.bind(undefined, spawned, 'stdout'); } if (spawned.stderr !== null) { spawned.pipeStderr = pipeToTarget.bind(undefined, spawned, 'stderr'); } if (spawned.all !== undefined) { spawned.pipeAll = pipeToTarget.bind(undefined, spawned, 'all'); } }; var getStreamExports = {}; var getStream$1 = { get exports(){ return getStreamExports; }, set exports(v){ getStreamExports = v; }, }; const {PassThrough: PassThroughStream} = require$$0__default$3; var bufferStream$1 = options => { options = {...options}; const {array} = options; let {encoding} = options; const isBuffer = encoding === 'buffer'; let objectMode = false; if (array) { objectMode = !(encoding || isBuffer); } else { encoding = encoding || 'utf8'; } if (isBuffer) { encoding = null; } const stream = new PassThroughStream({objectMode}); if (encoding) { stream.setEncoding(encoding); } let length = 0; const chunks = []; stream.on('data', chunk => { chunks.push(chunk); if (objectMode) { length = chunks.length; } else { length += chunk.length; } }); stream.getBufferedValue = () => { if (array) { return chunks; } return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); }; stream.getBufferedLength = () => length; return stream; }; const {constants: BufferConstants} = require$$0$5__default; const stream = require$$0__default$3; const {promisify} = require$$0__default$2; const bufferStream = bufferStream$1; const streamPipelinePromisified = promisify(stream.pipeline); class MaxBufferError extends Error { constructor() { super('maxBuffer exceeded'); this.name = 'MaxBufferError'; } } async function getStream(inputStream, options) { if (!inputStream) { throw new Error('Expected a stream'); } options = { maxBuffer: Infinity, ...options }; const {maxBuffer} = options; const stream = bufferStream(options); await new Promise((resolve, reject) => { const rejectPromise = error => { // Don't retrieve an oversized buffer. if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { error.bufferedData = stream.getBufferedValue(); } reject(error); }; (async () => { try { await streamPipelinePromisified(inputStream, stream); resolve(); } catch (error) { rejectPromise(error); } })(); stream.on('data', () => { if (stream.getBufferedLength() > maxBuffer) { rejectPromise(new MaxBufferError()); } }); }); return stream.getBufferedValue(); } getStream$1.exports = getStream; getStreamExports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); getStreamExports.array = (stream, options) => getStream(stream, {...options, array: true}); getStreamExports.MaxBufferError = MaxBufferError; const { PassThrough } = require$$0__default$3; var mergeStream = function (/*streams...*/) { var sources = []; var output = new PassThrough({objectMode: true}); output.setMaxListeners(0); output.add = add; output.isEmpty = isEmpty; output.on('unpipe', remove); Array.prototype.slice.call(arguments).forEach(add); return output function add (source) { if (Array.isArray(source)) { source.forEach(add); return this } sources.push(source); source.once('end', remove.bind(null, source)); source.once('error', output.emit.bind(output, 'error')); source.pipe(output, {end: false}); return this } function isEmpty () { return sources.length == 0; } function remove (source) { sources = sources.filter(function (it) { return it !== source }); if (!sources.length && output.readable) { output.end(); } } }; const validateInputOptions = input => { if (input !== undefined) { throw new TypeError('The `input` and `inputFile` options cannot be both set.'); } }; const getInput = ({input, inputFile}) => { if (typeof inputFile !== 'string') { return input; } validateInputOptions(input); return fs$1$1.createReadStream(inputFile); }; // `input` and `inputFile` option in async mode const handleInput = (spawned, options) => { const input = getInput(options); if (input === undefined) { return; } if (isStream(input)) { input.pipe(spawned.stdin); } else { spawned.stdin.end(input); } }; // `all` interleaves `stdout` and `stderr` const makeAllStream = (spawned, {all}) => { if (!all || (!spawned.stdout && !spawned.stderr)) { return; } const mixed = mergeStream(); if (spawned.stdout) { mixed.add(spawned.stdout); } if (spawned.stderr) { mixed.add(spawned.stderr); } return mixed; }; // On failure, `result.stdout|stderr|all` should contain the currently buffered stream const getBufferedData = async (stream, streamPromise) => { // When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve if (!stream || streamPromise === undefined) { return; } stream.destroy(); try { return await streamPromise; } catch (error) { return error.bufferedData; } }; const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { if (!stream || !buffer) { return; } if (encoding) { return getStreamExports(stream, {encoding, maxBuffer}); } return getStreamExports.buffer(stream, {maxBuffer}); }; // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); try { return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); } catch (error) { return Promise.all([ {error, signal: error.signal, timedOut: error.timedOut}, getBufferedData(stdout, stdoutPromise), getBufferedData(stderr, stderrPromise), getBufferedData(all, allPromise), ]); } }; // eslint-disable-next-line unicorn/prefer-top-level-await const nativePromisePrototype = (async () => {})().constructor.prototype; const descriptors = ['then', 'catch', 'finally'].map(property => [ property, Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property), ]); // The return value is a mixin of `childProcess` and `Promise` const mergePromise = (spawned, promise) => { for (const [property, descriptor] of descriptors) { // Starting the main `promise` is deferred to avoid consuming streams const value = typeof promise === 'function' ? (...args) => Reflect.apply(descriptor.value, promise(), args) : descriptor.value.bind(promise); Reflect.defineProperty(spawned, property, {...descriptor, value}); } }; // Use promises instead of `child_process` events const getSpawnedPromise = spawned => new Promise((resolve, reject) => { spawned.on('exit', (exitCode, signal) => { resolve({exitCode, signal}); }); spawned.on('error', error => { reject(error); }); if (spawned.stdin) { spawned.stdin.on('error', error => { reject(error); }); } }); const normalizeArgs = (file, args = []) => { if (!Array.isArray(args)) { return [file]; } return [file, ...args]; }; const NO_ESCAPE_REGEXP = /^[\w.-]+$/; const DOUBLE_QUOTES_REGEXP = /"/g; const escapeArg = arg => { if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) { return arg; } return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`; }; const joinCommand = (file, args) => normalizeArgs(file, args).join(' '); const getEscapedCommand = (file, args) => normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' '); const SPACES_REGEXP = / +/g; // Handle `execaCommand()` const parseCommand = command => { const tokens = []; for (const token of command.trim().split(SPACES_REGEXP)) { // Allow spaces to be escaped by a backslash if not meant as a delimiter const previousToken = tokens[tokens.length - 1]; if (previousToken && previousToken.endsWith('\\')) { // Merge previous token with current one tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; } else { tokens.push(token); } } return tokens; }; const verboseDefault = node_util.debuglog('execa').enabled; const padField = (field, padding) => String(field).padStart(padding, '0'); const getTimestamp = () => { const date = new Date(); return `${padField(date.getHours(), 2)}:${padField(date.getMinutes(), 2)}:${padField(date.getSeconds(), 2)}.${padField(date.getMilliseconds(), 3)}`; }; const logCommand = (escapedCommand, {verbose}) => { if (!verbose) { return; } process$2__default.stderr.write(`[${getTimestamp()}] ${escapedCommand}\n`); }; const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { const env = extendEnv ? {...process$2__default.env, ...envOption} : envOption; if (preferLocal) { return npmRunPathEnv({env, cwd: localDir, execPath}); } return env; }; const handleArguments = (file, args, options = {}) => { const parsed = crossSpawnExports._parse(file, args, options); file = parsed.command; args = parsed.args; options = parsed.options; options = { maxBuffer: DEFAULT_MAX_BUFFER, buffer: true, stripFinalNewline: true, extendEnv: true, preferLocal: false, localDir: options.cwd || process$2__default.cwd(), execPath: process$2__default.execPath, encoding: 'utf8', reject: true, cleanup: true, all: false, windowsHide: true, verbose: verboseDefault, ...options, }; options.env = getEnv(options); options.stdio = normalizeStdio(options); if (process$2__default.platform === 'win32' && path$3__default.basename(file, '.exe') === 'cmd') { // #116 args.unshift('/q'); } return {file, args, options, parsed}; }; const handleOutput = (options, value, error) => { if (typeof value !== 'string' && !node_buffer.Buffer.isBuffer(value)) { // When `execaSync()` errors, we normalize it to '' to mimic `execa()` return error === undefined ? undefined : ''; } if (options.stripFinalNewline) { return stripFinalNewline(value); } return value; }; function execa(file, args, options) { const parsed = handleArguments(file, args, options); const command = joinCommand(file, args); const escapedCommand = getEscapedCommand(file, args); logCommand(escapedCommand, parsed.options); validateTimeout(parsed.options); let spawned; try { spawned = childProcess__default.spawn(parsed.file, parsed.args, parsed.options); } catch (error) { // Ensure the returned error is always both a promise and a child process const dummySpawned = new childProcess__default.ChildProcess(); const errorPromise = Promise.reject(makeError({ error, stdout: '', stderr: '', all: '', command, escapedCommand, parsed, timedOut: false, isCanceled: false, killed: false, })); mergePromise(dummySpawned, errorPromise); return dummySpawned; } const spawnedPromise = getSpawnedPromise(spawned); const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); const processDone = setExitHandler(spawned, parsed.options, timedPromise); const context = {isCanceled: false}; spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); spawned.cancel = spawnedCancel.bind(null, spawned, context); const handlePromise = async () => { const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); const stdout = handleOutput(parsed.options, stdoutResult); const stderr = handleOutput(parsed.options, stderrResult); const all = handleOutput(parsed.options, allResult); if (error || exitCode !== 0 || signal !== null) { const returnedError = makeError({ error, exitCode, signal, stdout, stderr, all, command, escapedCommand, parsed, timedOut, isCanceled: (parsed.options.signal ? parsed.options.signal.aborted : false), killed: spawned.killed, }); if (!parsed.options.reject) { return returnedError; } throw returnedError; } return { command, escapedCommand, exitCode: 0, stdout, stderr, all, failed: false, timedOut: false, isCanceled: false, killed: false, }; }; const handlePromiseOnce = onetime(handlePromise); handleInput(spawned, parsed.options); spawned.all = makeAllStream(spawned, parsed.options); addPipeMethods(spawned); mergePromise(spawned, handlePromiseOnce); return spawned; } function execaCommand(command, options) { const [file, ...args] = parseCommand(command); return execa(file, args, options); } const ESC$1 = '\u001B['; const OSC = '\u001B]'; const BEL = '\u0007'; const SEP = ';'; const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal'; const ansiEscapes = {}; ansiEscapes.cursorTo = (x, y) => { if (typeof x !== 'number') { throw new TypeError('The `x` argument is required'); } if (typeof y !== 'number') { return ESC$1 + (x + 1) + 'G'; } return ESC$1 + (y + 1) + ';' + (x + 1) + 'H'; }; ansiEscapes.cursorMove = (x, y) => { if (typeof x !== 'number') { throw new TypeError('The `x` argument is required'); } let returnValue = ''; if (x < 0) { returnValue += ESC$1 + (-x) + 'D'; } else if (x > 0) { returnValue += ESC$1 + x + 'C'; } if (y < 0) { returnValue += ESC$1 + (-y) + 'A'; } else if (y > 0) { returnValue += ESC$1 + y + 'B'; } return returnValue; }; ansiEscapes.cursorUp = (count = 1) => ESC$1 + count + 'A'; ansiEscapes.cursorDown = (count = 1) => ESC$1 + count + 'B'; ansiEscapes.cursorForward = (count = 1) => ESC$1 + count + 'C'; ansiEscapes.cursorBackward = (count = 1) => ESC$1 + count + 'D'; ansiEscapes.cursorLeft = ESC$1 + 'G'; ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC$1 + 's'; ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC$1 + 'u'; ansiEscapes.cursorGetPosition = ESC$1 + '6n'; ansiEscapes.cursorNextLine = ESC$1 + 'E'; ansiEscapes.cursorPrevLine = ESC$1 + 'F'; ansiEscapes.cursorHide = ESC$1 + '?25l'; ansiEscapes.cursorShow = ESC$1 + '?25h'; ansiEscapes.eraseLines = count => { let clear = ''; for (let i = 0; i < count; i++) { clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : ''); } if (count) { clear += ansiEscapes.cursorLeft; } return clear; }; ansiEscapes.eraseEndLine = ESC$1 + 'K'; ansiEscapes.eraseStartLine = ESC$1 + '1K'; ansiEscapes.eraseLine = ESC$1 + '2K'; ansiEscapes.eraseDown = ESC$1 + 'J'; ansiEscapes.eraseUp = ESC$1 + '1J'; ansiEscapes.eraseScreen = ESC$1 + '2J'; ansiEscapes.scrollUp = ESC$1 + 'S'; ansiEscapes.scrollDown = ESC$1 + 'T'; ansiEscapes.clearScreen = '\u001Bc'; ansiEscapes.clearTerminal = process.platform === 'win32' ? `${ansiEscapes.eraseScreen}${ESC$1}0f` : // 1. Erases the screen (Only done in case `2` is not supported) // 2. Erases the whole screen including scrollback buffer // 3. Moves cursor to the top-left position // More info: https://www.real-world-systems.com/docs/ANSIcode.html `${ansiEscapes.eraseScreen}${ESC$1}3J${ESC$1}H`; ansiEscapes.beep = BEL; ansiEscapes.link = (text, url) => { return [ OSC, '8', SEP, SEP, url, BEL, text, OSC, '8', SEP, SEP, BEL ].join(''); }; ansiEscapes.image = (buffer, options = {}) => { let returnValue = `${OSC}1337;File=inline=1`; if (options.width) { returnValue += `;width=${options.width}`; } if (options.height) { returnValue += `;height=${options.height}`; } if (options.preserveAspectRatio === false) { returnValue += ';preserveAspectRatio=0'; } return returnValue + ':' + buffer.toString('base64') + BEL; }; ansiEscapes.iTerm = { setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`, annotation: (message, options = {}) => { let returnValue = `${OSC}1337;`; const hasX = typeof options.x !== 'undefined'; const hasY = typeof options.y !== 'undefined'; if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== 'undefined')) { throw new Error('`x`, `y` and `length` must be defined when `x` or `y` is defined'); } message = message.replace(/\|/g, ''); returnValue += options.isHidden ? 'AddHiddenAnnotation=' : 'AddAnnotation='; if (options.length > 0) { returnValue += (hasX ? [message, options.length, options.x, options.y] : [options.length, message]).join('|'); } else { returnValue += message; } return returnValue + BEL; } }; var hasFlag$2 = (flag, argv = process.argv) => { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; const os = require$$0__default; const tty = require$$1__default; const hasFlag$1 = hasFlag$2; const {env} = process; let forceColor; if (hasFlag$1('no-color') || hasFlag$1('no-colors') || hasFlag$1('color=false') || hasFlag$1('color=never')) { forceColor = 0; } else if (hasFlag$1('color') || hasFlag$1('colors') || hasFlag$1('color=true') || hasFlag$1('color=always')) { forceColor = 1; } if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { forceColor = 1; } else if (env.FORCE_COLOR === 'false') { forceColor = 0; } else { forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor$1(haveStream, streamIsTTY) { if (forceColor === 0) { return 0; } if (hasFlag$1('color=16m') || hasFlag$1('color=full') || hasFlag$1('color=truecolor')) { return 3; } if (hasFlag$1('color=256')) { return 2; } if (haveStream && !streamIsTTY && forceColor === undefined) { return 0; } const min = forceColor || 0; if (env.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = os.release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env) { const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } return min; } function getSupportLevel(stream) { const level = supportsColor$1(stream, stream && stream.isTTY); return translateLevel(level); } var supportsColor_1 = { supportsColor: getSupportLevel, stdout: translateLevel(supportsColor$1(true, tty.isatty(1))), stderr: translateLevel(supportsColor$1(true, tty.isatty(2))) }; const supportsColor = supportsColor_1; const hasFlag = hasFlag$2; function parseVersion(versionString) { if (/^\d{3,4}$/.test(versionString)) { // Env var doesn't always use dots. example: 4601 => 46.1.0 const m = /(\d{1,2})(\d{2})/.exec(versionString); return { major: 0, minor: parseInt(m[1], 10), patch: parseInt(m[2], 10) }; } const versions = (versionString || '').split('.').map(n => parseInt(n, 10)); return { major: versions[0], minor: versions[1], patch: versions[2] }; } function supportsHyperlink(stream) { const {env} = process; if ('FORCE_HYPERLINK' in env) { return !(env.FORCE_HYPERLINK.length > 0 && parseInt(env.FORCE_HYPERLINK, 10) === 0); } if (hasFlag('no-hyperlink') || hasFlag('no-hyperlinks') || hasFlag('hyperlink=false') || hasFlag('hyperlink=never')) { return false; } if (hasFlag('hyperlink=true') || hasFlag('hyperlink=always')) { return true; } // If they specify no colors, they probably don't want hyperlinks. if (!supportsColor.supportsColor(stream)) { return false; } if (stream && !stream.isTTY) { return false; } if (process.platform === 'win32') { return false; } if ('NETLIFY' in env) { return true; } if ('CI' in env) { return false; } if ('TEAMCITY_VERSION' in env) { return false; } if ('TERM_PROGRAM' in env) { const version = parseVersion(env.TERM_PROGRAM_VERSION); switch (env.TERM_PROGRAM) { case 'iTerm.app': if (version.major === 3) { return version.minor >= 1; } return version.major > 3; // No default } } if ('VTE_VERSION' in env) { // 0.50.0 was supposed to support hyperlinks, but throws a segfault if (env.VTE_VERSION === '0.50.0') { return false; } const version = parseVersion(env.VTE_VERSION); return version.major > 0 || version.minor >= 50; } return false; } var supportsHyperlinks = { supportsHyperlink, stdout: supportsHyperlink(process.stdout), stderr: supportsHyperlink(process.stderr) }; function terminalLink(text, url, {target = 'stdout', ...options} = {}) { if (!supportsHyperlinks[target]) { // If the fallback has been explicitly disabled, don't modify the text itself. if (options.fallback === false) { return text; } return typeof options.fallback === 'function' ? options.fallback(text, url) : `${text} (\u200B${url}\u200B)`; } return ansiEscapes.link(text, url); } terminalLink.isSupported = supportsHyperlinks.stdout; terminalLink.stderr = (text, url, options = {}) => terminalLink(text, url, {target: 'stderr', ...options}); terminalLink.stderr.isSupported = supportsHyperlinks.stderr; var promptsExports = {}; var prompts$3 = { get exports(){ return promptsExports; }, set exports(v){ promptsExports = v; }, }; var prompts$2 = {}; let FORCE_COLOR$1, NODE_DISABLE_COLORS$1, NO_COLOR$1, TERM$1, isTTY$1=true; if (typeof process !== 'undefined') { ({ FORCE_COLOR: FORCE_COLOR$1, NODE_DISABLE_COLORS: NODE_DISABLE_COLORS$1, NO_COLOR: NO_COLOR$1, TERM: TERM$1 } = process.env || {}); isTTY$1 = process.stdout && process.stdout.isTTY; } const $$1 = { enabled: !NODE_DISABLE_COLORS$1 && NO_COLOR$1 == null && TERM$1 !== 'dumb' && ( FORCE_COLOR$1 != null && FORCE_COLOR$1 !== '0' || isTTY$1 ), // modifiers reset: init$1(0, 0), bold: init$1(1, 22), dim: init$1(2, 22), italic: init$1(3, 23), underline: init$1(4, 24), inverse: init$1(7, 27), hidden: init$1(8, 28), strikethrough: init$1(9, 29), // colors black: init$1(30, 39), red: init$1(31, 39), green: init$1(32, 39), yellow: init$1(33, 39), blue: init$1(34, 39), magenta: init$1(35, 39), cyan: init$1(36, 39), white: init$1(37, 39), gray: init$1(90, 39), grey: init$1(90, 39), // background colors bgBlack: init$1(40, 49), bgRed: init$1(41, 49), bgGreen: init$1(42, 49), bgYellow: init$1(43, 49), bgBlue: init$1(44, 49), bgMagenta: init$1(45, 49), bgCyan: init$1(46, 49), bgWhite: init$1(47, 49) }; function run$2(arr, str) { let i=0, tmp, beg='', end=''; for (; i < arr.length; i++) { tmp = arr[i]; beg += tmp.open; end += tmp.close; if (!!~str.indexOf(tmp.close)) { str = str.replace(tmp.rgx, tmp.close + tmp.open); } } return beg + str + end; } function chain$1(has, keys) { let ctx = { has, keys }; ctx.reset = $$1.reset.bind(ctx); ctx.bold = $$1.bold.bind(ctx); ctx.dim = $$1.dim.bind(ctx); ctx.italic = $$1.italic.bind(ctx); ctx.underline = $$1.underline.bind(ctx); ctx.inverse = $$1.inverse.bind(ctx); ctx.hidden = $$1.hidden.bind(ctx); ctx.strikethrough = $$1.strikethrough.bind(ctx); ctx.black = $$1.black.bind(ctx); ctx.red = $$1.red.bind(ctx); ctx.green = $$1.green.bind(ctx); ctx.yellow = $$1.yellow.bind(ctx); ctx.blue = $$1.blue.bind(ctx); ctx.magenta = $$1.magenta.bind(ctx); ctx.cyan = $$1.cyan.bind(ctx); ctx.white = $$1.white.bind(ctx); ctx.gray = $$1.gray.bind(ctx); ctx.grey = $$1.grey.bind(ctx); ctx.bgBlack = $$1.bgBlack.bind(ctx); ctx.bgRed = $$1.bgRed.bind(ctx); ctx.bgGreen = $$1.bgGreen.bind(ctx); ctx.bgYellow = $$1.bgYellow.bind(ctx); ctx.bgBlue = $$1.bgBlue.bind(ctx); ctx.bgMagenta = $$1.bgMagenta.bind(ctx); ctx.bgCyan = $$1.bgCyan.bind(ctx); ctx.bgWhite = $$1.bgWhite.bind(ctx); return ctx; } function init$1(open, close) { let blk = { open: `\x1b[${open}m`, close: `\x1b[${close}m`, rgx: new RegExp(`\\x1b\\[${close}m`, 'g') }; return function (txt) { if (this !== void 0 && this.has !== void 0) { !!~this.has.indexOf(open) || (this.has.push(open),this.keys.push(blk)); return txt === void 0 ? this : $$1.enabled ? run$2(this.keys, txt+'') : txt+''; } return txt === void 0 ? chain$1([open], [blk]) : $$1.enabled ? run$2([blk], txt+'') : txt+''; }; } var kleur = $$1; var action$1 = (key, isSelect) => { if (key.meta && key.name !== 'escape') return; if (key.ctrl) { if (key.name === 'a') return 'first'; if (key.name === 'c') return 'abort'; if (key.name === 'd') return 'abort'; if (key.name === 'e') return 'last'; if (key.name === 'g') return 'reset'; if (key.name === 'n') return 'down'; if (key.name === 'p') return 'up'; // avoid any non-ascii characters return } if (isSelect) { if (key.name === 'j') return 'down'; if (key.name === 'k') return 'up'; } if (key.name === 'return') return 'submit'; if (key.name === 'enter') return 'submit'; // ctrl + J if (key.name === 'backspace') return 'delete'; if (key.name === 'delete') return 'deleteForward'; if (key.name === 'abort') return 'abort'; if (key.name === 'escape') return 'exit'; // TODO: shift tab for prev if (key.name === 'tab') return 'next'; if (key.name === 'pagedown') return 'nextPage'; if (key.name === 'pageup') return 'prevPage'; // TODO create home() in prompt types (e.g. TextPrompt) if (key.name === 'home') return 'home'; // TODO create end() in prompt types (e.g. TextPrompt) if (key.name === 'end') return 'end'; if (key.name === 'up') return 'up'; if (key.name === 'down') return 'down'; if (key.name === 'right') return 'right'; if (key.name === 'left') return 'left'; return false; }; var strip$2 = str => { const pattern = [ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' ].join('|'); const RGX = new RegExp(pattern, 'g'); return typeof str === 'string' ? str.replace(RGX, '') : str; }; const ESC = '\x1B'; const CSI = `${ESC}[`; const beep$1 = '\u0007'; const cursor$b = { to(x, y) { if (!y) return `${CSI}${x + 1}G`; return `${CSI}${y + 1};${x + 1}H`; }, move(x, y) { let ret = ''; if (x < 0) ret += `${CSI}${-x}D`; else if (x > 0) ret += `${CSI}${x}C`; if (y < 0) ret += `${CSI}${-y}A`; else if (y > 0) ret += `${CSI}${y}B`; return ret; }, up: (count = 1) => `${CSI}${count}A`, down: (count = 1) => `${CSI}${count}B`, forward: (count = 1) => `${CSI}${count}C`, backward: (count = 1) => `${CSI}${count}D`, nextLine: (count = 1) => `${CSI}E`.repeat(count), prevLine: (count = 1) => `${CSI}F`.repeat(count), left: `${CSI}G`, hide: `${CSI}?25l`, show: `${CSI}?25h`, save: `${ESC}7`, restore: `${ESC}8` }; const scroll = { up: (count = 1) => `${CSI}S`.repeat(count), down: (count = 1) => `${CSI}T`.repeat(count) }; const erase$7 = { screen: `${CSI}2J`, up: (count = 1) => `${CSI}1J`.repeat(count), down: (count = 1) => `${CSI}J`.repeat(count), line: `${CSI}2K`, lineEnd: `${CSI}K`, lineStart: `${CSI}1K`, lines(count) { let clear = ''; for (let i = 0; i < count; i++) clear += this.line + (i < count - 1 ? cursor$b.up() : ''); if (count) clear += cursor$b.left; return clear; } }; var src = { cursor: cursor$b, scroll, erase: erase$7, beep: beep$1 }; const strip$1 = strip$2; const { erase: erase$6, cursor: cursor$a } = src; const width = str => [...strip$1(str)].length; /** * @param {string} prompt * @param {number} perLine */ var clear$9 = function(prompt, perLine) { if (!perLine) return erase$6.line + cursor$a.to(0); let rows = 0; const lines = prompt.split(/\r?\n/); for (let line of lines) { rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine); } return erase$6.lines(rows); }; const main = { arrowUp: '↑', arrowDown: '↓', arrowLeft: '←', arrowRight: '→', radioOn: '◉', radioOff: '◯', tick: '✔', cross: '✖', ellipsis: '…', pointerSmall: '›', line: '─', pointer: '❯' }; const win = { arrowUp: main.arrowUp, arrowDown: main.arrowDown, arrowLeft: main.arrowLeft, arrowRight: main.arrowRight, radioOn: '(*)', radioOff: '( )', tick: '√', cross: '×', ellipsis: '...', pointerSmall: '»', line: '─', pointer: '>' }; const figures$8 = process.platform === 'win32' ? win : main; var figures_1 = figures$8; const c = kleur; const figures$7 = figures_1; // rendering user input. const styles = Object.freeze({ password: { scale: 1, render: input => '*'.repeat(input.length) }, emoji: { scale: 2, render: input => '😃'.repeat(input.length) }, invisible: { scale: 0, render: input => '' }, default: { scale: 1, render: input => `${input}` } }); const render = type => styles[type] || styles.default; // icon to signalize a prompt. const symbols = Object.freeze({ aborted: c.red(figures$7.cross), done: c.green(figures$7.tick), exited: c.yellow(figures$7.cross), default: c.cyan('?') }); const symbol = (done, aborted, exited) => aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default; // between the question and the user's input. const delimiter$1 = completing => c.gray(completing ? figures$7.ellipsis : figures$7.pointerSmall); const item = (expandable, expanded) => c.gray(expandable ? (expanded ? figures$7.pointerSmall : '+') : figures$7.line); var style$9 = { styles, render, symbols, symbol, delimiter: delimiter$1, item }; const strip = strip$2; /** * @param {string} msg * @param {number} perLine */ var lines$2 = function (msg, perLine) { let lines = String(strip(msg) || '').split(/\r?\n/); if (!perLine) return lines.length; return lines.map(l => Math.ceil(l.length / perLine)) .reduce((a, b) => a + b); }; /** * @param {string} msg The message to wrap * @param {object} opts * @param {number|string} [opts.margin] Left margin * @param {number} opts.width Maximum characters per line including the margin */ var wrap$3 = (msg, opts = {}) => { const tab = Number.isSafeInteger(parseInt(opts.margin)) ? new Array(parseInt(opts.margin)).fill(' ').join('') : (opts.margin || ''); const width = opts.width; return (msg || '').split(/\r?\n/g) .map(line => line .split(/\s+/g) .reduce((arr, w) => { if (w.length + tab.length >= width || arr[arr.length - 1].length + w.length + 1 < width) arr[arr.length - 1] += ` ${w}`; else arr.push(`${tab}${w}`); return arr; }, [ tab ]) .join('\n')) .join('\n'); }; /** * Determine what entries should be displayed on the screen, based on the * currently selected index and the maximum visible. Used in list-based * prompts like `select` and `multiselect`. * * @param {number} cursor the currently selected entry * @param {number} total the total entries available to display * @param {number} [maxVisible] the number of entries that can be displayed */ var entriesToDisplay$3 = (cursor, total, maxVisible) => { maxVisible = maxVisible || total; let startIndex = Math.min(total- maxVisible, cursor - Math.floor(maxVisible / 2)); if (startIndex < 0) startIndex = 0; let endIndex = Math.min(startIndex + maxVisible, total); return { startIndex, endIndex }; }; var util = { action: action$1, clear: clear$9, style: style$9, strip: strip$2, figures: figures_1, lines: lines$2, wrap: wrap$3, entriesToDisplay: entriesToDisplay$3 }; const readline = require$$0$7__default; const { action } = util; const EventEmitter = require$$2__default; const { beep, cursor: cursor$9 } = src; const color$9 = kleur; /** * Base prompt skeleton * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to */ let Prompt$8 = class Prompt extends EventEmitter { constructor(opts={}) { super(); this.firstRender = true; this.in = opts.stdin || process.stdin; this.out = opts.stdout || process.stdout; this.onRender = (opts.onRender || (() => void 0)).bind(this); const rl = readline.createInterface({ input:this.in, escapeCodeTimeout:50 }); readline.emitKeypressEvents(this.in, rl); if (this.in.isTTY) this.in.setRawMode(true); const isSelect = [ 'SelectPrompt', 'MultiselectPrompt' ].indexOf(this.constructor.name) > -1; const keypress = (str, key) => { let a = action(key, isSelect); if (a === false) { this._ && this._(str, key); } else if (typeof this[a] === 'function') { this[a](key); } else { this.bell(); } }; this.close = () => { this.out.write(cursor$9.show); this.in.removeListener('keypress', keypress); if (this.in.isTTY) this.in.setRawMode(false); rl.close(); this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value); this.closed = true; }; this.in.on('keypress', keypress); } fire() { this.emit('state', { value: this.value, aborted: !!this.aborted, exited: !!this.exited }); } bell() { this.out.write(beep); } render() { this.onRender(color$9); if (this.firstRender) this.firstRender = false; } }; var prompt$1 = Prompt$8; const color$8 = kleur; const Prompt$7 = prompt$1; const { erase: erase$5, cursor: cursor$8 } = src; const { style: style$8, clear: clear$8, lines: lines$1, figures: figures$6 } = util; /** * TextPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {String} [opts.style='default'] Render style * @param {String} [opts.initial] Default value * @param {Function} [opts.validate] Validate function * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to * @param {String} [opts.error] The invalid error label */ class TextPrompt extends Prompt$7 { constructor(opts={}) { super(opts); this.transform = style$8.render(opts.style); this.scale = this.transform.scale; this.msg = opts.message; this.initial = opts.initial || ``; this.validator = opts.validate || (() => true); this.value = ``; this.errorMsg = opts.error || `Please Enter A Valid Value`; this.cursor = Number(!!this.initial); this.cursorOffset = 0; this.clear = clear$8(``, this.out.columns); this.render(); } set value(v) { if (!v && this.initial) { this.placeholder = true; this.rendered = color$8.gray(this.transform.render(this.initial)); } else { this.placeholder = false; this.rendered = this.transform.render(v); } this._value = v; this.fire(); } get value() { return this._value; } reset() { this.value = ``; this.cursor = Number(!!this.initial); this.cursorOffset = 0; this.fire(); this.render(); } exit() { this.abort(); } abort() { this.value = this.value || this.initial; this.done = this.aborted = true; this.error = false; this.red = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } async validate() { let valid = await this.validator(this.value); if (typeof valid === `string`) { this.errorMsg = valid; valid = false; } this.error = !valid; } async submit() { this.value = this.value || this.initial; this.cursorOffset = 0; this.cursor = this.rendered.length; await this.validate(); if (this.error) { this.red = true; this.fire(); this.render(); return; } this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } next() { if (!this.placeholder) return this.bell(); this.value = this.initial; this.cursor = this.rendered.length; this.fire(); this.render(); } moveCursor(n) { if (this.placeholder) return; this.cursor = this.cursor+n; this.cursorOffset += n; } _(c, key) { let s1 = this.value.slice(0, this.cursor); let s2 = this.value.slice(this.cursor); this.value = `${s1}${c}${s2}`; this.red = false; this.cursor = this.placeholder ? 0 : s1.length+1; this.render(); } delete() { if (this.isCursorAtStart()) return this.bell(); let s1 = this.value.slice(0, this.cursor-1); let s2 = this.value.slice(this.cursor); this.value = `${s1}${s2}`; this.red = false; if (this.isCursorAtStart()) { this.cursorOffset = 0; } else { this.cursorOffset++; this.moveCursor(-1); } this.render(); } deleteForward() { if(this.cursor*this.scale >= this.rendered.length || this.placeholder) return this.bell(); let s1 = this.value.slice(0, this.cursor); let s2 = this.value.slice(this.cursor+1); this.value = `${s1}${s2}`; this.red = false; if (this.isCursorAtEnd()) { this.cursorOffset = 0; } else { this.cursorOffset++; } this.render(); } first() { this.cursor = 0; this.render(); } last() { this.cursor = this.value.length; this.render(); } left() { if (this.cursor <= 0 || this.placeholder) return this.bell(); this.moveCursor(-1); this.render(); } right() { if (this.cursor*this.scale >= this.rendered.length || this.placeholder) return this.bell(); this.moveCursor(1); this.render(); } isCursorAtStart() { return this.cursor === 0 || (this.placeholder && this.cursor === 1); } isCursorAtEnd() { return this.cursor === this.rendered.length || (this.placeholder && this.cursor === this.rendered.length + 1) } render() { if (this.closed) return; if (!this.firstRender) { if (this.outputError) this.out.write(cursor$8.down(lines$1(this.outputError, this.out.columns) - 1) + clear$8(this.outputError, this.out.columns)); this.out.write(clear$8(this.outputText, this.out.columns)); } super.render(); this.outputError = ''; this.outputText = [ style$8.symbol(this.done, this.aborted), color$8.bold(this.msg), style$8.delimiter(this.done), this.red ? color$8.red(this.rendered) : this.rendered ].join(` `); if (this.error) { this.outputError += this.errorMsg.split(`\n`) .reduce((a, l, i) => a + `\n${i ? ' ' : figures$6.pointerSmall} ${color$8.red().italic(l)}`, ``); } this.out.write(erase$5.line + cursor$8.to(0) + this.outputText + cursor$8.save + this.outputError + cursor$8.restore + cursor$8.move(this.cursorOffset, 0)); } } var text = TextPrompt; const color$7 = kleur; const Prompt$6 = prompt$1; const { style: style$7, clear: clear$7, figures: figures$5, wrap: wrap$2, entriesToDisplay: entriesToDisplay$2 } = util; const { cursor: cursor$7 } = src; /** * SelectPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Array} opts.choices Array of choice objects * @param {String} [opts.hint] Hint to display * @param {Number} [opts.initial] Index of default value * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to * @param {Number} [opts.optionsPerPage=10] Max options to display at once */ class SelectPrompt extends Prompt$6 { constructor(opts={}) { super(opts); this.msg = opts.message; this.hint = opts.hint || '- Use arrow-keys. Return to submit.'; this.warn = opts.warn || '- This option is disabled'; this.cursor = opts.initial || 0; this.choices = opts.choices.map((ch, idx) => { if (typeof ch === 'string') ch = {title: ch, value: idx}; return { title: ch && (ch.title || ch.value || ch), value: ch && (ch.value === undefined ? idx : ch.value), description: ch && ch.description, selected: ch && ch.selected, disabled: ch && ch.disabled }; }); this.optionsPerPage = opts.optionsPerPage || 10; this.value = (this.choices[this.cursor] || {}).value; this.clear = clear$7('', this.out.columns); this.render(); } moveCursor(n) { this.cursor = n; this.value = this.choices[n].value; this.fire(); } reset() { this.moveCursor(0); this.fire(); this.render(); } exit() { this.abort(); } abort() { this.done = this.aborted = true; this.fire(); this.render(); this.out.write('\n'); this.close(); } submit() { if (!this.selection.disabled) { this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } else this.bell(); } first() { this.moveCursor(0); this.render(); } last() { this.moveCursor(this.choices.length - 1); this.render(); } up() { if (this.cursor === 0) { this.moveCursor(this.choices.length - 1); } else { this.moveCursor(this.cursor - 1); } this.render(); } down() { if (this.cursor === this.choices.length - 1) { this.moveCursor(0); } else { this.moveCursor(this.cursor + 1); } this.render(); } next() { this.moveCursor((this.cursor + 1) % this.choices.length); this.render(); } _(c, key) { if (c === ' ') return this.submit(); } get selection() { return this.choices[this.cursor]; } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor$7.hide); else this.out.write(clear$7(this.outputText, this.out.columns)); super.render(); let { startIndex, endIndex } = entriesToDisplay$2(this.cursor, this.choices.length, this.optionsPerPage); // Print prompt this.outputText = [ style$7.symbol(this.done, this.aborted), color$7.bold(this.msg), style$7.delimiter(false), this.done ? this.selection.title : this.selection.disabled ? color$7.yellow(this.warn) : color$7.gray(this.hint) ].join(' '); // Print choices if (!this.done) { this.outputText += '\n'; for (let i = startIndex; i < endIndex; i++) { let title, prefix, desc = '', v = this.choices[i]; // Determine whether to display "more choices" indicators if (i === startIndex && startIndex > 0) { prefix = figures$5.arrowUp; } else if (i === endIndex - 1 && endIndex < this.choices.length) { prefix = figures$5.arrowDown; } else { prefix = ' '; } if (v.disabled) { title = this.cursor === i ? color$7.gray().underline(v.title) : color$7.strikethrough().gray(v.title); prefix = (this.cursor === i ? color$7.bold().gray(figures$5.pointer) + ' ' : ' ') + prefix; } else { title = this.cursor === i ? color$7.cyan().underline(v.title) : v.title; prefix = (this.cursor === i ? color$7.cyan(figures$5.pointer) + ' ' : ' ') + prefix; if (v.description && this.cursor === i) { desc = ` - ${v.description}`; if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { desc = '\n' + wrap$2(v.description, { margin: 3, width: this.out.columns }); } } } this.outputText += `${prefix} ${title}${color$7.gray(desc)}\n`; } } this.out.write(this.outputText); } } var select = SelectPrompt; const color$6 = kleur; const Prompt$5 = prompt$1; const { style: style$6, clear: clear$6 } = util; const { cursor: cursor$6, erase: erase$4 } = src; /** * TogglePrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Boolean} [opts.initial=false] Default value * @param {String} [opts.active='no'] Active label * @param {String} [opts.inactive='off'] Inactive label * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to */ class TogglePrompt extends Prompt$5 { constructor(opts={}) { super(opts); this.msg = opts.message; this.value = !!opts.initial; this.active = opts.active || 'on'; this.inactive = opts.inactive || 'off'; this.initialValue = this.value; this.render(); } reset() { this.value = this.initialValue; this.fire(); this.render(); } exit() { this.abort(); } abort() { this.done = this.aborted = true; this.fire(); this.render(); this.out.write('\n'); this.close(); } submit() { this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } deactivate() { if (this.value === false) return this.bell(); this.value = false; this.render(); } activate() { if (this.value === true) return this.bell(); this.value = true; this.render(); } delete() { this.deactivate(); } left() { this.deactivate(); } right() { this.activate(); } down() { this.deactivate(); } up() { this.activate(); } next() { this.value = !this.value; this.fire(); this.render(); } _(c, key) { if (c === ' ') { this.value = !this.value; } else if (c === '1') { this.value = true; } else if (c === '0') { this.value = false; } else return this.bell(); this.render(); } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor$6.hide); else this.out.write(clear$6(this.outputText, this.out.columns)); super.render(); this.outputText = [ style$6.symbol(this.done, this.aborted), color$6.bold(this.msg), style$6.delimiter(this.done), this.value ? this.inactive : color$6.cyan().underline(this.inactive), color$6.gray('/'), this.value ? color$6.cyan().underline(this.active) : this.active ].join(' '); this.out.write(erase$4.line + cursor$6.to(0) + this.outputText); } } var toggle = TogglePrompt; let DatePart$9 = class DatePart { constructor({token, date, parts, locales}) { this.token = token; this.date = date || new Date(); this.parts = parts || [this]; this.locales = locales || {}; } up() {} down() {} next() { const currentIdx = this.parts.indexOf(this); return this.parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); } setTo(val) {} prev() { let parts = [].concat(this.parts).reverse(); const currentIdx = parts.indexOf(this); return parts.find((part, idx) => idx > currentIdx && part instanceof DatePart); } toString() { return String(this.date); } }; var datepart = DatePart$9; const DatePart$8 = datepart; let Meridiem$1 = class Meridiem extends DatePart$8 { constructor(opts={}) { super(opts); } up() { this.date.setHours((this.date.getHours() + 12) % 24); } down() { this.up(); } toString() { let meridiem = this.date.getHours() > 12 ? 'pm' : 'am'; return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem; } }; var meridiem = Meridiem$1; const DatePart$7 = datepart; const pos = n => { n = n % 10; return n === 1 ? 'st' : n === 2 ? 'nd' : n === 3 ? 'rd' : 'th'; }; let Day$1 = class Day extends DatePart$7 { constructor(opts={}) { super(opts); } up() { this.date.setDate(this.date.getDate() + 1); } down() { this.date.setDate(this.date.getDate() - 1); } setTo(val) { this.date.setDate(parseInt(val.substr(-2))); } toString() { let date = this.date.getDate(); let day = this.date.getDay(); return this.token === 'DD' ? String(date).padStart(2, '0') : this.token === 'Do' ? date + pos(date) : this.token === 'd' ? day + 1 : this.token === 'ddd' ? this.locales.weekdaysShort[day] : this.token === 'dddd' ? this.locales.weekdays[day] : date; } }; var day = Day$1; const DatePart$6 = datepart; let Hours$1 = class Hours extends DatePart$6 { constructor(opts={}) { super(opts); } up() { this.date.setHours(this.date.getHours() + 1); } down() { this.date.setHours(this.date.getHours() - 1); } setTo(val) { this.date.setHours(parseInt(val.substr(-2))); } toString() { let hours = this.date.getHours(); if (/h/.test(this.token)) hours = (hours % 12) || 12; return this.token.length > 1 ? String(hours).padStart(2, '0') : hours; } }; var hours = Hours$1; const DatePart$5 = datepart; let Milliseconds$1 = class Milliseconds extends DatePart$5 { constructor(opts={}) { super(opts); } up() { this.date.setMilliseconds(this.date.getMilliseconds() + 1); } down() { this.date.setMilliseconds(this.date.getMilliseconds() - 1); } setTo(val) { this.date.setMilliseconds(parseInt(val.substr(-(this.token.length)))); } toString() { return String(this.date.getMilliseconds()).padStart(4, '0') .substr(0, this.token.length); } }; var milliseconds = Milliseconds$1; const DatePart$4 = datepart; let Minutes$1 = class Minutes extends DatePart$4 { constructor(opts={}) { super(opts); } up() { this.date.setMinutes(this.date.getMinutes() + 1); } down() { this.date.setMinutes(this.date.getMinutes() - 1); } setTo(val) { this.date.setMinutes(parseInt(val.substr(-2))); } toString() { let m = this.date.getMinutes(); return this.token.length > 1 ? String(m).padStart(2, '0') : m; } }; var minutes = Minutes$1; const DatePart$3 = datepart; let Month$1 = class Month extends DatePart$3 { constructor(opts={}) { super(opts); } up() { this.date.setMonth(this.date.getMonth() + 1); } down() { this.date.setMonth(this.date.getMonth() - 1); } setTo(val) { val = parseInt(val.substr(-2)) - 1; this.date.setMonth(val < 0 ? 0 : val); } toString() { let month = this.date.getMonth(); let tl = this.token.length; return tl === 2 ? String(month + 1).padStart(2, '0') : tl === 3 ? this.locales.monthsShort[month] : tl === 4 ? this.locales.months[month] : String(month + 1); } }; var month = Month$1; const DatePart$2 = datepart; let Seconds$1 = class Seconds extends DatePart$2 { constructor(opts={}) { super(opts); } up() { this.date.setSeconds(this.date.getSeconds() + 1); } down() { this.date.setSeconds(this.date.getSeconds() - 1); } setTo(val) { this.date.setSeconds(parseInt(val.substr(-2))); } toString() { let s = this.date.getSeconds(); return this.token.length > 1 ? String(s).padStart(2, '0') : s; } }; var seconds = Seconds$1; const DatePart$1 = datepart; let Year$1 = class Year extends DatePart$1 { constructor(opts={}) { super(opts); } up() { this.date.setFullYear(this.date.getFullYear() + 1); } down() { this.date.setFullYear(this.date.getFullYear() - 1); } setTo(val) { this.date.setFullYear(val.substr(-4)); } toString() { let year = String(this.date.getFullYear()).padStart(4, '0'); return this.token.length === 2 ? year.substr(-2) : year; } }; var year = Year$1; var dateparts = { DatePart: datepart, Meridiem: meridiem, Day: day, Hours: hours, Milliseconds: milliseconds, Minutes: minutes, Month: month, Seconds: seconds, Year: year, }; const color$5 = kleur; const Prompt$4 = prompt$1; const { style: style$5, clear: clear$5, figures: figures$4 } = util; const { erase: erase$3, cursor: cursor$5 } = src; const { DatePart, Meridiem, Day, Hours, Milliseconds, Minutes, Month, Seconds, Year } = dateparts; const regex = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g; const regexGroups = { 1: ({token}) => token.replace(/\\(.)/g, '$1'), 2: (opts) => new Day(opts), // Day // TODO 3: (opts) => new Month(opts), // Month 4: (opts) => new Year(opts), // Year 5: (opts) => new Meridiem(opts), // AM/PM // TODO (special) 6: (opts) => new Hours(opts), // Hours 7: (opts) => new Minutes(opts), // Minutes 8: (opts) => new Seconds(opts), // Seconds 9: (opts) => new Milliseconds(opts), // Fractional seconds }; const dfltLocales = { months: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','), monthsShort: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), weekdaysShort: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',') }; /** * DatePrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Number} [opts.initial] Index of default value * @param {String} [opts.mask] The format mask * @param {object} [opts.locales] The date locales * @param {String} [opts.error] The error message shown on invalid value * @param {Function} [opts.validate] Function to validate the submitted value * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to */ class DatePrompt extends Prompt$4 { constructor(opts={}) { super(opts); this.msg = opts.message; this.cursor = 0; this.typed = ''; this.locales = Object.assign(dfltLocales, opts.locales); this._date = opts.initial || new Date(); this.errorMsg = opts.error || 'Please Enter A Valid Value'; this.validator = opts.validate || (() => true); this.mask = opts.mask || 'YYYY-MM-DD HH:mm:ss'; this.clear = clear$5('', this.out.columns); this.render(); } get value() { return this.date } get date() { return this._date; } set date(date) { if (date) this._date.setTime(date.getTime()); } set mask(mask) { let result; this.parts = []; while(result = regex.exec(mask)) { let match = result.shift(); let idx = result.findIndex(gr => gr != null); this.parts.push(idx in regexGroups ? regexGroups[idx]({ token: result[idx] || match, date: this.date, parts: this.parts, locales: this.locales }) : result[idx] || match); } let parts = this.parts.reduce((arr, i) => { if (typeof i === 'string' && typeof arr[arr.length - 1] === 'string') arr[arr.length - 1] += i; else arr.push(i); return arr; }, []); this.parts.splice(0); this.parts.push(...parts); this.reset(); } moveCursor(n) { this.typed = ''; this.cursor = n; this.fire(); } reset() { this.moveCursor(this.parts.findIndex(p => p instanceof DatePart)); this.fire(); this.render(); } exit() { this.abort(); } abort() { this.done = this.aborted = true; this.error = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } async validate() { let valid = await this.validator(this.value); if (typeof valid === 'string') { this.errorMsg = valid; valid = false; } this.error = !valid; } async submit() { await this.validate(); if (this.error) { this.color = 'red'; this.fire(); this.render(); return; } this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } up() { this.typed = ''; this.parts[this.cursor].up(); this.render(); } down() { this.typed = ''; this.parts[this.cursor].down(); this.render(); } left() { let prev = this.parts[this.cursor].prev(); if (prev == null) return this.bell(); this.moveCursor(this.parts.indexOf(prev)); this.render(); } right() { let next = this.parts[this.cursor].next(); if (next == null) return this.bell(); this.moveCursor(this.parts.indexOf(next)); this.render(); } next() { let next = this.parts[this.cursor].next(); this.moveCursor(next ? this.parts.indexOf(next) : this.parts.findIndex((part) => part instanceof DatePart)); this.render(); } _(c) { if (/\d/.test(c)) { this.typed += c; this.parts[this.cursor].setTo(this.typed); this.render(); } } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor$5.hide); else this.out.write(clear$5(this.outputText, this.out.columns)); super.render(); // Print prompt this.outputText = [ style$5.symbol(this.done, this.aborted), color$5.bold(this.msg), style$5.delimiter(false), this.parts.reduce((arr, p, idx) => arr.concat(idx === this.cursor && !this.done ? color$5.cyan().underline(p.toString()) : p), []) .join('') ].join(' '); // Print error if (this.error) { this.outputText += this.errorMsg.split('\n').reduce( (a, l, i) => a + `\n${i ? ` ` : figures$4.pointerSmall} ${color$5.red().italic(l)}`, ``); } this.out.write(erase$3.line + cursor$5.to(0) + this.outputText); } } var date = DatePrompt; const color$4 = kleur; const Prompt$3 = prompt$1; const { cursor: cursor$4, erase: erase$2 } = src; const { style: style$4, figures: figures$3, clear: clear$4, lines } = util; const isNumber = /[0-9]/; const isDef = any => any !== undefined; const round = (number, precision) => { let factor = Math.pow(10, precision); return Math.round(number * factor) / factor; }; /** * NumberPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {String} [opts.style='default'] Render style * @param {Number} [opts.initial] Default value * @param {Number} [opts.max=+Infinity] Max value * @param {Number} [opts.min=-Infinity] Min value * @param {Boolean} [opts.float=false] Parse input as floats * @param {Number} [opts.round=2] Round floats to x decimals * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys * @param {Function} [opts.validate] Validate function * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to * @param {String} [opts.error] The invalid error label */ class NumberPrompt extends Prompt$3 { constructor(opts={}) { super(opts); this.transform = style$4.render(opts.style); this.msg = opts.message; this.initial = isDef(opts.initial) ? opts.initial : ''; this.float = !!opts.float; this.round = opts.round || 2; this.inc = opts.increment || 1; this.min = isDef(opts.min) ? opts.min : -Infinity; this.max = isDef(opts.max) ? opts.max : Infinity; this.errorMsg = opts.error || `Please Enter A Valid Value`; this.validator = opts.validate || (() => true); this.color = `cyan`; this.value = ``; this.typed = ``; this.lastHit = 0; this.render(); } set value(v) { if (!v && v !== 0) { this.placeholder = true; this.rendered = color$4.gray(this.transform.render(`${this.initial}`)); this._value = ``; } else { this.placeholder = false; this.rendered = this.transform.render(`${round(v, this.round)}`); this._value = round(v, this.round); } this.fire(); } get value() { return this._value; } parse(x) { return this.float ? parseFloat(x) : parseInt(x); } valid(c) { return c === `-` || c === `.` && this.float || isNumber.test(c) } reset() { this.typed = ``; this.value = ``; this.fire(); this.render(); } exit() { this.abort(); } abort() { let x = this.value; this.value = x !== `` ? x : this.initial; this.done = this.aborted = true; this.error = false; this.fire(); this.render(); this.out.write(`\n`); this.close(); } async validate() { let valid = await this.validator(this.value); if (typeof valid === `string`) { this.errorMsg = valid; valid = false; } this.error = !valid; } async submit() { await this.validate(); if (this.error) { this.color = `red`; this.fire(); this.render(); return; } let x = this.value; this.value = x !== `` ? x : this.initial; this.done = true; this.aborted = false; this.error = false; this.fire(); this.render(); this.out.write(`\n`); this.close(); } up() { this.typed = ``; if(this.value === '') { this.value = this.min - this.inc; } if (this.value >= this.max) return this.bell(); this.value += this.inc; this.color = `cyan`; this.fire(); this.render(); } down() { this.typed = ``; if(this.value === '') { this.value = this.min + this.inc; } if (this.value <= this.min) return this.bell(); this.value -= this.inc; this.color = `cyan`; this.fire(); this.render(); } delete() { let val = this.value.toString(); if (val.length === 0) return this.bell(); this.value = this.parse((val = val.slice(0, -1))) || ``; if (this.value !== '' && this.value < this.min) { this.value = this.min; } this.color = `cyan`; this.fire(); this.render(); } next() { this.value = this.initial; this.fire(); this.render(); } _(c, key) { if (!this.valid(c)) return this.bell(); const now = Date.now(); if (now - this.lastHit > 1000) this.typed = ``; // 1s elapsed this.typed += c; this.lastHit = now; this.color = `cyan`; if (c === `.`) return this.fire(); this.value = Math.min(this.parse(this.typed), this.max); if (this.value > this.max) this.value = this.max; if (this.value < this.min) this.value = this.min; this.fire(); this.render(); } render() { if (this.closed) return; if (!this.firstRender) { if (this.outputError) this.out.write(cursor$4.down(lines(this.outputError, this.out.columns) - 1) + clear$4(this.outputError, this.out.columns)); this.out.write(clear$4(this.outputText, this.out.columns)); } super.render(); this.outputError = ''; // Print prompt this.outputText = [ style$4.symbol(this.done, this.aborted), color$4.bold(this.msg), style$4.delimiter(this.done), !this.done || (!this.done && !this.placeholder) ? color$4[this.color]().underline(this.rendered) : this.rendered ].join(` `); // Print error if (this.error) { this.outputError += this.errorMsg.split(`\n`) .reduce((a, l, i) => a + `\n${i ? ` ` : figures$3.pointerSmall} ${color$4.red().italic(l)}`, ``); } this.out.write(erase$2.line + cursor$4.to(0) + this.outputText + cursor$4.save + this.outputError + cursor$4.restore); } } var number = NumberPrompt; const color$3 = kleur; const { cursor: cursor$3 } = src; const Prompt$2 = prompt$1; const { clear: clear$3, figures: figures$2, style: style$3, wrap: wrap$1, entriesToDisplay: entriesToDisplay$1 } = util; /** * MultiselectPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Array} opts.choices Array of choice objects * @param {String} [opts.hint] Hint to display * @param {String} [opts.warn] Hint shown for disabled choices * @param {Number} [opts.max] Max choices * @param {Number} [opts.cursor=0] Cursor start position * @param {Number} [opts.optionsPerPage=10] Max options to display at once * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to */ let MultiselectPrompt$1 = class MultiselectPrompt extends Prompt$2 { constructor(opts={}) { super(opts); this.msg = opts.message; this.cursor = opts.cursor || 0; this.scrollIndex = opts.cursor || 0; this.hint = opts.hint || ''; this.warn = opts.warn || '- This option is disabled -'; this.minSelected = opts.min; this.showMinError = false; this.maxChoices = opts.max; this.instructions = opts.instructions; this.optionsPerPage = opts.optionsPerPage || 10; this.value = opts.choices.map((ch, idx) => { if (typeof ch === 'string') ch = {title: ch, value: idx}; return { title: ch && (ch.title || ch.value || ch), description: ch && ch.description, value: ch && (ch.value === undefined ? idx : ch.value), selected: ch && ch.selected, disabled: ch && ch.disabled }; }); this.clear = clear$3('', this.out.columns); if (!opts.overrideRender) { this.render(); } } reset() { this.value.map(v => !v.selected); this.cursor = 0; this.fire(); this.render(); } selected() { return this.value.filter(v => v.selected); } exit() { this.abort(); } abort() { this.done = this.aborted = true; this.fire(); this.render(); this.out.write('\n'); this.close(); } submit() { const selected = this.value .filter(e => e.selected); if (this.minSelected && selected.length < this.minSelected) { this.showMinError = true; this.render(); } else { this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } } first() { this.cursor = 0; this.render(); } last() { this.cursor = this.value.length - 1; this.render(); } next() { this.cursor = (this.cursor + 1) % this.value.length; this.render(); } up() { if (this.cursor === 0) { this.cursor = this.value.length - 1; } else { this.cursor--; } this.render(); } down() { if (this.cursor === this.value.length - 1) { this.cursor = 0; } else { this.cursor++; } this.render(); } left() { this.value[this.cursor].selected = false; this.render(); } right() { if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); this.value[this.cursor].selected = true; this.render(); } handleSpaceToggle() { const v = this.value[this.cursor]; if (v.selected) { v.selected = false; this.render(); } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { return this.bell(); } else { v.selected = true; this.render(); } } toggleAll() { if (this.maxChoices !== undefined || this.value[this.cursor].disabled) { return this.bell(); } const newSelected = !this.value[this.cursor].selected; this.value.filter(v => !v.disabled).forEach(v => v.selected = newSelected); this.render(); } _(c, key) { if (c === ' ') { this.handleSpaceToggle(); } else if (c === 'a') { this.toggleAll(); } else { return this.bell(); } } renderInstructions() { if (this.instructions === undefined || this.instructions) { if (typeof this.instructions === 'string') { return this.instructions; } return '\nInstructions:\n' + ` ${figures$2.arrowUp}/${figures$2.arrowDown}: Highlight option\n` + ` ${figures$2.arrowLeft}/${figures$2.arrowRight}/[space]: Toggle selection\n` + (this.maxChoices === undefined ? ` a: Toggle all\n` : '') + ` enter/return: Complete answer`; } return ''; } renderOption(cursor, v, i, arrowIndicator) { const prefix = (v.selected ? color$3.green(figures$2.radioOn) : figures$2.radioOff) + ' ' + arrowIndicator + ' '; let title, desc; if (v.disabled) { title = cursor === i ? color$3.gray().underline(v.title) : color$3.strikethrough().gray(v.title); } else { title = cursor === i ? color$3.cyan().underline(v.title) : v.title; if (cursor === i && v.description) { desc = ` - ${v.description}`; if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { desc = '\n' + wrap$1(v.description, { margin: prefix.length, width: this.out.columns }); } } } return prefix + title + color$3.gray(desc || ''); } // shared with autocompleteMultiselect paginateOptions(options) { if (options.length === 0) { return color$3.red('No matches for this query.'); } let { startIndex, endIndex } = entriesToDisplay$1(this.cursor, options.length, this.optionsPerPage); let prefix, styledOptions = []; for (let i = startIndex; i < endIndex; i++) { if (i === startIndex && startIndex > 0) { prefix = figures$2.arrowUp; } else if (i === endIndex - 1 && endIndex < options.length) { prefix = figures$2.arrowDown; } else { prefix = ' '; } styledOptions.push(this.renderOption(this.cursor, options[i], i, prefix)); } return '\n' + styledOptions.join('\n'); } // shared with autocomleteMultiselect renderOptions(options) { if (!this.done) { return this.paginateOptions(options); } return ''; } renderDoneOrInstructions() { if (this.done) { return this.value .filter(e => e.selected) .map(v => v.title) .join(', '); } const output = [color$3.gray(this.hint), this.renderInstructions()]; if (this.value[this.cursor].disabled) { output.push(color$3.yellow(this.warn)); } return output.join(' '); } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor$3.hide); super.render(); // print prompt let prompt = [ style$3.symbol(this.done, this.aborted), color$3.bold(this.msg), style$3.delimiter(false), this.renderDoneOrInstructions() ].join(' '); if (this.showMinError) { prompt += color$3.red(`You must select a minimum of ${this.minSelected} choices.`); this.showMinError = false; } prompt += this.renderOptions(this.value); this.out.write(this.clear + prompt); this.clear = clear$3(prompt, this.out.columns); } }; var multiselect = MultiselectPrompt$1; const color$2 = kleur; const Prompt$1 = prompt$1; const { erase: erase$1, cursor: cursor$2 } = src; const { style: style$2, clear: clear$2, figures: figures$1, wrap, entriesToDisplay } = util; const getVal = (arr, i) => arr[i] && (arr[i].value || arr[i].title || arr[i]); const getTitle = (arr, i) => arr[i] && (arr[i].title || arr[i].value || arr[i]); const getIndex = (arr, valOrTitle) => { const index = arr.findIndex(el => el.value === valOrTitle || el.title === valOrTitle); return index > -1 ? index : undefined; }; /** * TextPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Array} opts.choices Array of auto-complete choices objects * @param {Function} [opts.suggest] Filter function. Defaults to sort by title * @param {Number} [opts.limit=10] Max number of results to show * @param {Number} [opts.cursor=0] Cursor start position * @param {String} [opts.style='default'] Render style * @param {String} [opts.fallback] Fallback message - initial to default value * @param {String} [opts.initial] Index of the default value * @param {Boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to * @param {String} [opts.noMatches] The no matches found label */ class AutocompletePrompt extends Prompt$1 { constructor(opts={}) { super(opts); this.msg = opts.message; this.suggest = opts.suggest; this.choices = opts.choices; this.initial = typeof opts.initial === 'number' ? opts.initial : getIndex(opts.choices, opts.initial); this.select = this.initial || opts.cursor || 0; this.i18n = { noMatches: opts.noMatches || 'no matches found' }; this.fallback = opts.fallback || this.initial; this.clearFirst = opts.clearFirst || false; this.suggestions = []; this.input = ''; this.limit = opts.limit || 10; this.cursor = 0; this.transform = style$2.render(opts.style); this.scale = this.transform.scale; this.render = this.render.bind(this); this.complete = this.complete.bind(this); this.clear = clear$2('', this.out.columns); this.complete(this.render); this.render(); } set fallback(fb) { this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb; } get fallback() { let choice; if (typeof this._fb === 'number') choice = this.choices[this._fb]; else if (typeof this._fb === 'string') choice = { title: this._fb }; return choice || this._fb || { title: this.i18n.noMatches }; } moveSelect(i) { this.select = i; if (this.suggestions.length > 0) this.value = getVal(this.suggestions, i); else this.value = this.fallback.value; this.fire(); } async complete(cb) { const p = (this.completing = this.suggest(this.input, this.choices)); const suggestions = await p; if (this.completing !== p) return; this.suggestions = suggestions .map((s, i, arr) => ({ title: getTitle(arr, i), value: getVal(arr, i), description: s.description })); this.completing = false; const l = Math.max(suggestions.length - 1, 0); this.moveSelect(Math.min(l, this.select)); cb && cb(); } reset() { this.input = ''; this.complete(() => { this.moveSelect(this.initial !== void 0 ? this.initial : 0); this.render(); }); this.render(); } exit() { if (this.clearFirst && this.input.length > 0) { this.reset(); } else { this.done = this.exited = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } } abort() { this.done = this.aborted = true; this.exited = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } submit() { this.done = true; this.aborted = this.exited = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } _(c, key) { let s1 = this.input.slice(0, this.cursor); let s2 = this.input.slice(this.cursor); this.input = `${s1}${c}${s2}`; this.cursor = s1.length+1; this.complete(this.render); this.render(); } delete() { if (this.cursor === 0) return this.bell(); let s1 = this.input.slice(0, this.cursor-1); let s2 = this.input.slice(this.cursor); this.input = `${s1}${s2}`; this.complete(this.render); this.cursor = this.cursor-1; this.render(); } deleteForward() { if(this.cursor*this.scale >= this.rendered.length) return this.bell(); let s1 = this.input.slice(0, this.cursor); let s2 = this.input.slice(this.cursor+1); this.input = `${s1}${s2}`; this.complete(this.render); this.render(); } first() { this.moveSelect(0); this.render(); } last() { this.moveSelect(this.suggestions.length - 1); this.render(); } up() { if (this.select === 0) { this.moveSelect(this.suggestions.length - 1); } else { this.moveSelect(this.select - 1); } this.render(); } down() { if (this.select === this.suggestions.length - 1) { this.moveSelect(0); } else { this.moveSelect(this.select + 1); } this.render(); } next() { if (this.select === this.suggestions.length - 1) { this.moveSelect(0); } else this.moveSelect(this.select + 1); this.render(); } nextPage() { this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1)); this.render(); } prevPage() { this.moveSelect(Math.max(this.select - this.limit, 0)); this.render(); } left() { if (this.cursor <= 0) return this.bell(); this.cursor = this.cursor-1; this.render(); } right() { if (this.cursor*this.scale >= this.rendered.length) return this.bell(); this.cursor = this.cursor+1; this.render(); } renderOption(v, hovered, isStart, isEnd) { let desc; let prefix = isStart ? figures$1.arrowUp : isEnd ? figures$1.arrowDown : ' '; let title = hovered ? color$2.cyan().underline(v.title) : v.title; prefix = (hovered ? color$2.cyan(figures$1.pointer) + ' ' : ' ') + prefix; if (v.description) { desc = ` - ${v.description}`; if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) { desc = '\n' + wrap(v.description, { margin: 3, width: this.out.columns }); } } return prefix + ' ' + title + color$2.gray(desc || ''); } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor$2.hide); else this.out.write(clear$2(this.outputText, this.out.columns)); super.render(); let { startIndex, endIndex } = entriesToDisplay(this.select, this.choices.length, this.limit); this.outputText = [ style$2.symbol(this.done, this.aborted, this.exited), color$2.bold(this.msg), style$2.delimiter(this.completing), this.done && this.suggestions[this.select] ? this.suggestions[this.select].title : this.rendered = this.transform.render(this.input) ].join(' '); if (!this.done) { const suggestions = this.suggestions .slice(startIndex, endIndex) .map((item, i) => this.renderOption(item, this.select === i + startIndex, i === 0 && startIndex > 0, i + startIndex === endIndex - 1 && endIndex < this.choices.length)) .join('\n'); this.outputText += `\n` + (suggestions || color$2.gray(this.fallback.title)); } this.out.write(erase$1.line + cursor$2.to(0) + this.outputText); } } var autocomplete = AutocompletePrompt; const color$1 = kleur; const { cursor: cursor$1 } = src; const MultiselectPrompt = multiselect; const { clear: clear$1, style: style$1, figures } = util; /** * MultiselectPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Array} opts.choices Array of choice objects * @param {String} [opts.hint] Hint to display * @param {String} [opts.warn] Hint shown for disabled choices * @param {Number} [opts.max] Max choices * @param {Number} [opts.cursor=0] Cursor start position * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to */ class AutocompleteMultiselectPrompt extends MultiselectPrompt { constructor(opts={}) { opts.overrideRender = true; super(opts); this.inputValue = ''; this.clear = clear$1('', this.out.columns); this.filteredOptions = this.value; this.render(); } last() { this.cursor = this.filteredOptions.length - 1; this.render(); } next() { this.cursor = (this.cursor + 1) % this.filteredOptions.length; this.render(); } up() { if (this.cursor === 0) { this.cursor = this.filteredOptions.length - 1; } else { this.cursor--; } this.render(); } down() { if (this.cursor === this.filteredOptions.length - 1) { this.cursor = 0; } else { this.cursor++; } this.render(); } left() { this.filteredOptions[this.cursor].selected = false; this.render(); } right() { if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell(); this.filteredOptions[this.cursor].selected = true; this.render(); } delete() { if (this.inputValue.length) { this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1); this.updateFilteredOptions(); } } updateFilteredOptions() { const currentHighlight = this.filteredOptions[this.cursor]; this.filteredOptions = this.value .filter(v => { if (this.inputValue) { if (typeof v.title === 'string') { if (v.title.toLowerCase().includes(this.inputValue.toLowerCase())) { return true; } } if (typeof v.value === 'string') { if (v.value.toLowerCase().includes(this.inputValue.toLowerCase())) { return true; } } return false; } return true; }); const newHighlightIndex = this.filteredOptions.findIndex(v => v === currentHighlight); this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex; this.render(); } handleSpaceToggle() { const v = this.filteredOptions[this.cursor]; if (v.selected) { v.selected = false; this.render(); } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) { return this.bell(); } else { v.selected = true; this.render(); } } handleInputChange(c) { this.inputValue = this.inputValue + c; this.updateFilteredOptions(); } _(c, key) { if (c === ' ') { this.handleSpaceToggle(); } else { this.handleInputChange(c); } } renderInstructions() { if (this.instructions === undefined || this.instructions) { if (typeof this.instructions === 'string') { return this.instructions; } return ` Instructions: ${figures.arrowUp}/${figures.arrowDown}: Highlight option ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection [a,b,c]/delete: Filter choices enter/return: Complete answer `; } return ''; } renderCurrentInput() { return ` Filtered results for: ${this.inputValue ? this.inputValue : color$1.gray('Enter something to filter')}\n`; } renderOption(cursor, v, i, arrowIndicator) { const prefix = (v.selected ? color$1.green(figures.radioOn) : figures.radioOff) + ' ' + arrowIndicator + ' '; let title; if (v.disabled) title = cursor === i ? color$1.gray().underline(v.title) : color$1.strikethrough().gray(v.title); else title = cursor === i ? color$1.cyan().underline(v.title) : v.title; return prefix + title; } renderDoneOrInstructions() { if (this.done) { return this.value .filter(e => e.selected) .map(v => v.title) .join(', '); } const output = [color$1.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()]; if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) { output.push(color$1.yellow(this.warn)); } return output.join(' '); } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor$1.hide); super.render(); // print prompt let prompt = [ style$1.symbol(this.done, this.aborted), color$1.bold(this.msg), style$1.delimiter(false), this.renderDoneOrInstructions() ].join(' '); if (this.showMinError) { prompt += color$1.red(`You must select a minimum of ${this.minSelected} choices.`); this.showMinError = false; } prompt += this.renderOptions(this.filteredOptions); this.out.write(this.clear + prompt); this.clear = clear$1(prompt, this.out.columns); } } var autocompleteMultiselect = AutocompleteMultiselectPrompt; const color = kleur; const Prompt = prompt$1; const { style, clear } = util; const { erase, cursor } = src; /** * ConfirmPrompt Base Element * @param {Object} opts Options * @param {String} opts.message Message * @param {Boolean} [opts.initial] Default value (true/false) * @param {Stream} [opts.stdin] The Readable stream to listen to * @param {Stream} [opts.stdout] The Writable stream to write readline data to * @param {String} [opts.yes] The "Yes" label * @param {String} [opts.yesOption] The "Yes" option when choosing between yes/no * @param {String} [opts.no] The "No" label * @param {String} [opts.noOption] The "No" option when choosing between yes/no */ class ConfirmPrompt extends Prompt { constructor(opts={}) { super(opts); this.msg = opts.message; this.value = opts.initial; this.initialValue = !!opts.initial; this.yesMsg = opts.yes || 'yes'; this.yesOption = opts.yesOption || '(Y/n)'; this.noMsg = opts.no || 'no'; this.noOption = opts.noOption || '(y/N)'; this.render(); } reset() { this.value = this.initialValue; this.fire(); this.render(); } exit() { this.abort(); } abort() { this.done = this.aborted = true; this.fire(); this.render(); this.out.write('\n'); this.close(); } submit() { this.value = this.value || false; this.done = true; this.aborted = false; this.fire(); this.render(); this.out.write('\n'); this.close(); } _(c, key) { if (c.toLowerCase() === 'y') { this.value = true; return this.submit(); } if (c.toLowerCase() === 'n') { this.value = false; return this.submit(); } return this.bell(); } render() { if (this.closed) return; if (this.firstRender) this.out.write(cursor.hide); else this.out.write(clear(this.outputText, this.out.columns)); super.render(); this.outputText = [ style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.done ? (this.value ? this.yesMsg : this.noMsg) : color.gray(this.initialValue ? this.yesOption : this.noOption) ].join(' '); this.out.write(erase.line + cursor.to(0) + this.outputText); } } var confirm = ConfirmPrompt; var elements = { TextPrompt: text, SelectPrompt: select, TogglePrompt: toggle, DatePrompt: date, NumberPrompt: number, MultiselectPrompt: multiselect, AutocompletePrompt: autocomplete, AutocompleteMultiselectPrompt: autocompleteMultiselect, ConfirmPrompt: confirm }; (function (exports) { const $ = exports; const el = elements; const noop = v => v; function toPrompt(type, args, opts={}) { return new Promise((res, rej) => { const p = new el[type](args); const onAbort = opts.onAbort || noop; const onSubmit = opts.onSubmit || noop; const onExit = opts.onExit || noop; p.on('state', args.onState || noop); p.on('submit', x => res(onSubmit(x))); p.on('exit', x => res(onExit(x))); p.on('abort', x => rej(onAbort(x))); }); } /** * Text prompt * @param {string} args.message Prompt message to display * @param {string} [args.initial] Default string value * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') * @param {function} [args.onState] On state change callback * @param {function} [args.validate] Function to validate user input * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.text = args => toPrompt('TextPrompt', args); /** * Password prompt with masked input * @param {string} args.message Prompt message to display * @param {string} [args.initial] Default string value * @param {function} [args.onState] On state change callback * @param {function} [args.validate] Function to validate user input * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.password = args => { args.style = 'password'; return $.text(args); }; /** * Prompt where input is invisible, like sudo * @param {string} args.message Prompt message to display * @param {string} [args.initial] Default string value * @param {function} [args.onState] On state change callback * @param {function} [args.validate] Function to validate user input * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.invisible = args => { args.style = 'invisible'; return $.text(args); }; /** * Number prompt * @param {string} args.message Prompt message to display * @param {number} args.initial Default number value * @param {function} [args.onState] On state change callback * @param {number} [args.max] Max value * @param {number} [args.min] Min value * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') * @param {Boolean} [opts.float=false] Parse input as floats * @param {Number} [opts.round=2] Round floats to x decimals * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys * @param {function} [args.validate] Function to validate user input * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.number = args => toPrompt('NumberPrompt', args); /** * Date prompt * @param {string} args.message Prompt message to display * @param {number} args.initial Default number value * @param {function} [args.onState] On state change callback * @param {number} [args.max] Max value * @param {number} [args.min] Min value * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') * @param {Boolean} [opts.float=false] Parse input as floats * @param {Number} [opts.round=2] Round floats to x decimals * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys * @param {function} [args.validate] Function to validate user input * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.date = args => toPrompt('DatePrompt', args); /** * Classic yes/no prompt * @param {string} args.message Prompt message to display * @param {boolean} [args.initial=false] Default value * @param {function} [args.onState] On state change callback * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.confirm = args => toPrompt('ConfirmPrompt', args); /** * List prompt, split intput string by `seperator` * @param {string} args.message Prompt message to display * @param {string} [args.initial] Default string value * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') * @param {string} [args.separator] String separator * @param {function} [args.onState] On state change callback * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input, in form of an `Array` */ $.list = args => { const sep = args.separator || ','; return toPrompt('TextPrompt', args, { onSubmit: str => str.split(sep).map(s => s.trim()) }); }; /** * Toggle/switch prompt * @param {string} args.message Prompt message to display * @param {boolean} [args.initial=false] Default value * @param {string} [args.active="on"] Text for `active` state * @param {string} [args.inactive="off"] Text for `inactive` state * @param {function} [args.onState] On state change callback * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.toggle = args => toPrompt('TogglePrompt', args); /** * Interactive select prompt * @param {string} args.message Prompt message to display * @param {Array} args.choices Array of choices objects `[{ title, value }, ...]` * @param {number} [args.initial] Index of default value * @param {String} [args.hint] Hint to display * @param {function} [args.onState] On state change callback * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.select = args => toPrompt('SelectPrompt', args); /** * Interactive multi-select / autocompleteMultiselect prompt * @param {string} args.message Prompt message to display * @param {Array} args.choices Array of choices objects `[{ title, value, [selected] }, ...]` * @param {number} [args.max] Max select * @param {string} [args.hint] Hint to display user * @param {Number} [args.cursor=0] Cursor start position * @param {function} [args.onState] On state change callback * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.multiselect = args => { args.choices = [].concat(args.choices || []); const toSelected = items => items.filter(item => item.selected).map(item => item.value); return toPrompt('MultiselectPrompt', args, { onAbort: toSelected, onSubmit: toSelected }); }; $.autocompleteMultiselect = args => { args.choices = [].concat(args.choices || []); const toSelected = items => items.filter(item => item.selected).map(item => item.value); return toPrompt('AutocompleteMultiselectPrompt', args, { onAbort: toSelected, onSubmit: toSelected }); }; const byTitle = (input, choices) => Promise.resolve( choices.filter(item => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase()) ); /** * Interactive auto-complete prompt * @param {string} args.message Prompt message to display * @param {Array} args.choices Array of auto-complete choices objects `[{ title, value }, ...]` * @param {Function} [args.suggest] Function to filter results based on user input. Defaults to sort by `title` * @param {number} [args.limit=10] Max number of results to show * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible') * @param {String} [args.initial] Index of the default value * @param {boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input * @param {String} [args.fallback] Fallback message - defaults to initial value * @param {function} [args.onState] On state change callback * @param {Stream} [args.stdin] The Readable stream to listen to * @param {Stream} [args.stdout] The Writable stream to write readline data to * @returns {Promise} Promise with user input */ $.autocomplete = args => { args.suggest = args.suggest || byTitle; args.choices = [].concat(args.choices || []); return toPrompt('AutocompletePrompt', args); }; } (prompts$2)); const prompts$1 = prompts$2; const passOn = ['suggest', 'format', 'onState', 'validate', 'onRender', 'type']; const noop = () => {}; /** * Prompt for a series of questions * @param {Array|Object} questions Single question object or Array of question objects * @param {Function} [onSubmit] Callback function called on prompt submit * @param {Function} [onCancel] Callback function called on cancel/abort * @returns {Object} Object with values from user input */ async function prompt(questions=[], { onSubmit=noop, onCancel=noop }={}) { const answers = {}; const override = prompt._override || {}; questions = [].concat(questions); let answer, question, quit, name, type, lastPrompt; const getFormattedAnswer = async (question, answer, skipValidation = false) => { if (!skipValidation && question.validate && question.validate(answer) !== true) { return; } return question.format ? await question.format(answer, answers) : answer }; for (question of questions) { ({ name, type } = question); // evaluate type first and skip if type is a falsy value if (typeof type === 'function') { type = await type(answer, { ...answers }, question); question['type'] = type; } if (!type) continue; // if property is a function, invoke it unless it's a special function for (let key in question) { if (passOn.includes(key)) continue; let value = question[key]; question[key] = typeof value === 'function' ? await value(answer, { ...answers }, lastPrompt) : value; } lastPrompt = question; if (typeof question.message !== 'string') { throw new Error('prompt message is required'); } // update vars in case they changed ({ name, type } = question); if (prompts$1[type] === void 0) { throw new Error(`prompt type (${type}) is not defined`); } if (override[question.name] !== undefined) { answer = await getFormattedAnswer(question, override[question.name]); if (answer !== undefined) { answers[name] = answer; continue; } } try { // Get the injected answer if there is one or prompt the user answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : await prompts$1[type](question); answers[name] = answer = await getFormattedAnswer(question, answer, true); quit = await onSubmit(question, answer, answers); } catch (err) { quit = !(await onCancel(question, answers)); } if (quit) return answers; } return answers; } function getInjectedAnswer(injected, deafultValue) { const answer = injected.shift(); if (answer instanceof Error) { throw answer; } return (answer === undefined) ? deafultValue : answer; } function inject(answers) { prompt._injected = (prompt._injected || []).concat(answers); } function override(answers) { prompt._override = Object.assign({}, answers); } var lib$1 = Object.assign(prompt, { prompt, prompts: prompts$1, inject, override }); (function (module) { module.exports = lib$1; } (prompts$3)); const prompts = /*@__PURE__*/getDefaultExportFromCjs(promptsExports); const isexe = isexe_1; const { join, delimiter, sep, posix } = require$$0__default$1; const isWindows = process.platform === 'win32'; // used to check for slashed in commands passed in. always checks for the posix // seperator on all platforms, and checks for the current separator when not on // a posix platform. don't use the isWindows check for this since that is mocked // in tests but we still need the code to actually work when called. that is also // why it is ignored from coverage. /* istanbul ignore next */ const rSlash = new RegExp(`[${posix.sep}${sep === posix.sep ? '' : sep}]`.replace(/(\\)/g, '\\$1')); const rRel = new RegExp(`^\\.${rSlash.source}`); const getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); const getPathInfo = (cmd, { path: optPath = process.env.PATH, pathExt: optPathExt = process.env.PATHEXT, delimiter: optDelimiter = delimiter, }) => { // 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(rSlash) ? [''] : [ // windows always checks the cwd first ...(isWindows ? [process.cwd()] : []), ...(optPath || /* istanbul ignore next: very unusual */ '').split(optDelimiter), ]; if (isWindows) { const pathExtExe = optPathExt || ['.EXE', '.CMD', '.BAT', '.COM'].join(optDelimiter); const pathExt = pathExtExe.split(optDelimiter); if (cmd.includes('.') && pathExt[0] !== '') { pathExt.unshift(''); } return { pathEnv, pathExt, pathExtExe } } return { pathEnv, pathExt: [''] } }; const getPathPart = (raw, cmd) => { const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw; const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : ''; return prefix + join(pathPart, cmd) }; const which = async (cmd, opt = {}) => { const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); const found = []; for (const envPart of pathEnv) { const p = getPathPart(envPart, cmd); for (const ext of pathExt) { const withExt = p + ext; const is = await isexe(withExt, { pathExt: pathExtExe, ignoreErrors: true }); if (is) { if (!opt.all) { return withExt } found.push(withExt); } } } if (opt.all && found.length) { return found } if (opt.nothrow) { return null } throw getNotFoundError(cmd) }; const whichSync = (cmd, opt = {}) => { const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); const found = []; for (const pathEnvPart of pathEnv) { const p = getPathPart(pathEnvPart, cmd); for (const ext of pathExt) { const withExt = p + ext; const is = isexe.sync(withExt, { pathExt: pathExtExe, ignoreErrors: true }); if (is) { if (!opt.all) { return withExt } found.push(withExt); } } } if (opt.all && found.length) { return found } if (opt.nothrow) { return null } throw getNotFoundError(cmd) }; var lib = which; which.sync = whichSync; path$3$1.join(os$1__default.tmpdir(), "antfu-ni"); function exclude(arr, v) { return arr.slice().filter((item) => item !== v); } function cmdExists(cmd) { return lib.sync(cmd, { nothrow: true }) !== null; } async function detect({ autoInstall, cwd } = {}) { let agent = null; let version = null; const lockPath = await findUp(Object.keys(LOCKS), { cwd }); let packageJsonPath; if (lockPath) packageJsonPath = path$3__default.resolve(lockPath, "../package.json"); else packageJsonPath = await findUp("package.json", { cwd }); if (packageJsonPath && fs$1__default.existsSync(packageJsonPath)) { try { const pkg = JSON.parse(fs$1__default.readFileSync(packageJsonPath, "utf8")); if (typeof pkg.packageManager === "string") { const [name, ver] = pkg.packageManager.split("@"); version = ver; if (name === "yarn" && parseInt(ver) > 1) agent = "yarn@berry"; else if (name === "pnpm" && parseInt(ver) < 7) agent = "pnpm@6"; else if (name in AGENTS) agent = name; else console.warn("[ni] Unknown packageManager:", pkg.packageManager); } } catch { } } if (!agent && lockPath) agent = LOCKS[path$3__default.basename(lockPath)]; if (agent && !cmdExists(agent.split("@")[0])) { if (!autoInstall) { console.warn(`[ni] Detected ${agent} but it doesn't seem to be installed. `); if (process.env.CI) process.exit(1); const link = terminalLink(agent, INSTALL_PAGE[agent]); const { tryInstall } = await prompts({ name: "tryInstall", type: "confirm", message: `Would you like to globally install ${link}?` }); if (!tryInstall) process.exit(1); } await execaCommand(`npm i -g ${agent}${version ? `@${version}` : ""}`, { stdio: "inherit", cwd }); } return agent; } class UnsupportedCommand extends Error { constructor({ agent, command }) { super(`Command "${command}" is not support by agent "${agent}"`); } } function getCommand(agent, command, args = []) { if (!(agent in AGENTS)) throw new Error(`Unsupported agent "${agent}"`); const c = AGENTS[agent][command]; if (typeof c === "function") return c(args); if (!c) throw new UnsupportedCommand({ agent, command }); return c.replace("{0}", args.join(" ")).trim(); } const parseNi = (agent, args, ctx) => { if (agent === "bun") args = args.map((i) => i === "-D" ? "-d" : i); if (args.includes("-g")) return getCommand(agent, "global", exclude(args, "-g")); if (args.includes("--frozen-if-present")) { args = exclude(args, "--frozen-if-present"); return getCommand(agent, ctx?.hasLock ? "frozen" : "install", args); } if (args.includes("--frozen")) return getCommand(agent, "frozen", exclude(args, "--frozen")); if (args.length === 0 || args.every((i) => i.startsWith("-"))) return getCommand(agent, "install", args); return getCommand(agent, "add", args); }; const parseNun = (agent, args) => { if (args.includes("-g")) return getCommand(agent, "global_uninstall", exclude(args, "-g")); return getCommand(agent, "uninstall", args); }; if (typeof process !== 'undefined') { (process.env || {}); process.stdout && process.stdout.isTTY; } async function execNpmScript(packages, options = {}) { const { isDev = false, cwd = process.cwd(), callback = () => { }, type = "install" } = options; const agent = await detect({}); const fn = type === "install" ? parseNi : parseNun; const command = await fn(agent, [...packages, ...isDev ? ["-D"] : [], type === "install" ? "--ignore-scripts" : ""]); const { execaCommand } = await import('execa'); const _process = execaCommand(command, { encoding: "utf-8", cwd, env: { COLORS: "true", FORCE_COLOR: "true" } }); callback("data", ` > ${command} `); _process.stdout.on("data", (data) => { callback("data", data.toString()); }); _process.stderr.on("data", (data) => { callback("data", data.toString()); }); _process.on("exit", (code) => { callback("data", ` > Successfully ${type === "install" ? "installed" : "removed"}. `); callback("exit", `${code}`); }); } async function getComponentsRelationships(rpc) { const list = await rpc.list(); return list?.modules || []; } const NAME = "vite-plugin-svelte-devtools"; const V_OPTIONS = "virtual:svelte-devtools-options"; const V_PATH = "virtual:svelte-devtools-path"; const V_PATH_APP_LOAD_KIT = `${V_PATH}:app-load-kit.js`; function getSvelteDevtoolsPath() { const pluginPath = vite.normalizePath(path$3__default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href))))); return pluginPath.replace(/\/dist$/, "//src/server"); } function VitePluginSvelteDevTools(options) { const { sveltekit } = options; const svelteDevtoolsPath = getSvelteDevtoolsPath(); const inspect = Inspect__default({ silent: true }); let config; let allowList = []; function configureServer(server) { const base = server.config.base || "/"; const route = parseRoute(options.route); server.middlewares.use(`${base}__devtools__`, sirv__default(DIR_CLIENT, { single: true, dev: true })); const rpc = createRPCServer(NAME, server.ws, { // 获得路由信息,返回给 client getRoutesInfo: () => { return route; }, // get svelte-kit server fs allow list getAllowList: () => { return allowList; }, // 获得组件关系 componentGraph: () => getComponentsRelationships(inspect.api.rpc), inspectClientUrl: () => { return `${config.base || "/"}__inspect/`; }, // 获取项目静态资源 staticAssets: () => getStaticAssets(config), // 根据文件路径获取图片元信息宽、高、尺寸等 getImageMeta, // 根据文件路径获取文本类静态资源的缩略内容 getTextAssetContent, // 获取项目包依赖信息 getPackages: async () => { const res = await getPackages(config.root); return res; }, // 获取SFC列表, 包含项目所有 sfc 文件的相对路径 getSvelteSFCList: async () => { const res = await getSFCList(config.root); return res; }, // 获取组件信息 根据文件名获取组件内容并解析,component docs 用到 // getComponentInfo: async (filename: string) => { // // 组件解析内容,包含组件的名称,各种 option 等。。。 // const res = await getComponentInfo(config.root, filename) // return res // }, // 安装项目依赖 installPackage: (packages, options2 = {}) => { execNpmScript(packages, { ...options2, type: "install", cwd: config.root, callback: (type, data) => { if (type === "data") rpc.onTerminalData({ data }); else if (type === "exit") rpc.onTerminalExit({ data }); } }); }, // 卸载项目依赖 uninstallPackage: (packages, options2 = {}) => { execNpmScript(packages, { ...options2, type: "uninstall", cwd: config.root, callback: (type, data) => { if (type === "data") rpc.onTerminalData({ data }); else if (type === "exit") rpc.onTerminalExit({ data }); } }); }, root: () => { return config.root; } }); } let env = "development"; const plugin = { name: NAME, enforce: "pre", apply: "serve", config(_, { mode }) { env = mode; }, configResolved(resolvedConfig) { config = resolvedConfig; allowList = config.server.fs.allow; }, configureServer(server) { configureServer(server); }, // 生成虚拟模块 id async resolveId(importee) { if (importee.startsWith(V_OPTIONS)) { return importee; } else if (importee.startsWith(`${V_PATH}:`)) { const resolved = importee.replace(`${V_PATH}:`, `${svelteDevtoolsPath}/`); return resolved; } }, // return virtual module code async load(id) { if (id === V_OPTIONS) return `export default ${JSON.stringify({ base: config.base })}`; } }; const pluginInject = { name: `${NAME}:inject`, enforce: "pre", apply: "serve", transform(code, id) { if (env === "development" && id.includes("root.svelte")) { code = code.replaceAll("