vlt 0.0.0-0.1727821659739 → 0.0.0-0.1728676223960

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js", "../../../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js", "../../../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js", "../../../../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js", "../../../../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js", "../../../../../node_modules/.pnpm/cross-spawn@7.0.3/node_modules/cross-spawn/lib/util/resolveCommand.js", "../../../../../node_modules/.pnpm/cross-spawn@7.0.3/node_modules/cross-spawn/lib/util/escape.js", "../../../../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js", "../../../../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js", "../../../../../node_modules/.pnpm/cross-spawn@7.0.3/node_modules/cross-spawn/lib/util/readShebang.js", "../../../../../node_modules/.pnpm/cross-spawn@7.0.3/node_modules/cross-spawn/lib/parse.js", "../../../../../node_modules/.pnpm/cross-spawn@7.0.3/node_modules/cross-spawn/lib/enoent.js", "../../../../../node_modules/.pnpm/cross-spawn@7.0.3/node_modules/cross-spawn/index.js", "../../../../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js", "../../../../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js", "../../../../../node_modules/.pnpm/emoji-regex@10.3.0/node_modules/emoji-regex/index.js", "../../../../../src/error-cause/src/index.ts", "../../../../../src/types/src/index.ts", "../../../../../src/package-json/src/index.ts", "../../../../../node_modules/.pnpm/polite-json@5.0.0/node_modules/polite-json/src/index.ts", "../../../../../src/promise-spawn/src/index.ts", "../../../../../node_modules/.pnpm/foreground-child@3.3.0/node_modules/foreground-child/src/index.ts", "../../../../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/src/signals.ts", "../../../../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/src/index.ts", "../../../../../node_modules/.pnpm/foreground-child@3.3.0/node_modules/foreground-child/src/all-signals.ts", "../../../../../node_modules/.pnpm/foreground-child@3.3.0/node_modules/foreground-child/src/proxy-signals.ts", "../../../../../node_modules/.pnpm/foreground-child@3.3.0/node_modules/foreground-child/src/watchdog.ts", "../../../../../src/run/src/index.ts", "../../../../../node_modules/.pnpm/walk-up-path@4.0.0/node_modules/walk-up-path/src/index.ts", "../../../../../src/fast-split/src/index.ts", "../../../../../src/semver/src/version.ts", "../../../../../src/semver/src/comparator.ts", "../../../../../src/semver/src/range.ts", "../../../../../src/semver/src/index.ts", "../../../../../src/spec/src/index.ts", "../../../../../src/dep-id/src/index.ts", "../../../../../src/workspaces/src/index.ts", "../../../../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/src/index.ts", "../../../../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/src/assert-valid-pattern.ts", "../../../../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/src/brace-expressions.ts", "../../../../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/src/unescape.ts", "../../../../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/src/ast.ts", "../../../../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/src/escape.ts", "../../../../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/src/glob.ts", "../../../../../node_modules/.pnpm/lru-cache@11.0.0/node_modules/lru-cache/src/index.ts", "../../../../../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/src/index.ts", "../../../../../node_modules/.pnpm/minipass@7.1.2/node_modules/minipass/src/index.ts", "../../../../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/src/pattern.ts", "../../../../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/src/ignore.ts", "../../../../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/src/processor.ts", "../../../../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/src/walker.ts", "../../../../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/src/has-magic.ts", "../../../../../node_modules/.pnpm/glob@11.0.0/node_modules/glob/src/index.ts", "../../../../../node_modules/.pnpm/graph-run@1.0.4/node_modules/graph-run/src/index.ts", "../../../../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/src/fix-emoji.ts", "../../../../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/src/default-colors.ts", "../../../../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/src/hex-to-rgb.ts", "../../../../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/src/rgb-to-hex.ts", "../../../../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/src/dim-color.ts", "../../../../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/src/html-escape.ts", "../../../../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/src/named.ts", "../../../../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/src/xterm.ts", "../../../../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/src/style.ts", "../../../../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/src/block.ts", "../../../../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/src/terminal.ts", "../../../../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/src/index.ts", "../../../../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/ansi-styles/index.js", "../../../../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/supports-color/index.js", "../../../../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/utilities.js", "../../../../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/index.js", "../../../../../src/vlt/src/exec-command.ts", "../../../../../src/vlt/src/commands/exec.ts"],
4
- "sourcesContent": ["module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction checkPathExt (path, options) {\n var pathext = options.pathExt !== undefined ?\n options.pathExt : process.env.PATHEXT\n\n if (!pathext) {\n return true\n }\n\n pathext = pathext.split(';')\n if (pathext.indexOf('') !== -1) {\n return true\n }\n for (var i = 0; i < pathext.length; i++) {\n var p = pathext[i].toLowerCase()\n if (p && path.substr(-p.length).toLowerCase() === p) {\n return true\n }\n }\n return false\n}\n\nfunction checkStat (stat, path, options) {\n if (!stat.isSymbolicLink() && !stat.isFile()) {\n return false\n }\n return checkPathExt(path, options)\n}\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, path, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), path, options)\n}\n", "module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), options)\n}\n\nfunction checkStat (stat, options) {\n return stat.isFile() && checkMode(stat, options)\n}\n\nfunction checkMode (stat, options) {\n var mod = stat.mode\n var uid = stat.uid\n var gid = stat.gid\n\n var myUid = options.uid !== undefined ?\n options.uid : process.getuid && process.getuid()\n var myGid = options.gid !== undefined ?\n options.gid : process.getgid && process.getgid()\n\n var u = parseInt('100', 8)\n var g = parseInt('010', 8)\n var o = parseInt('001', 8)\n var ug = u | g\n\n var ret = (mod & o) ||\n (mod & g) && gid === myGid ||\n (mod & u) && uid === myUid ||\n (mod & ug) && myUid === 0\n\n return ret\n}\n", "var fs = require('fs')\nvar core\nif (process.platform === 'win32' || global.TESTING_WINDOWS) {\n core = require('./windows.js')\n} else {\n core = require('./mode.js')\n}\n\nmodule.exports = isexe\nisexe.sync = sync\n\nfunction isexe (path, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = {}\n }\n\n if (!cb) {\n if (typeof Promise !== 'function') {\n throw new TypeError('callback not provided')\n }\n\n return new Promise(function (resolve, reject) {\n isexe(path, options || {}, function (er, is) {\n if (er) {\n reject(er)\n } else {\n resolve(is)\n }\n })\n })\n }\n\n core(path, options || {}, function (er, is) {\n // ignore EACCES because that just means we aren't allowed to run it\n if (er) {\n if (er.code === 'EACCES' || options && options.ignoreErrors) {\n er = null\n is = false\n }\n }\n cb(er, is)\n })\n}\n\nfunction sync (path, options) {\n // my kingdom for a filtered catch\n try {\n return core.sync(path, options || {})\n } catch (er) {\n if (options && options.ignoreErrors || er.code === 'EACCES') {\n return false\n } else {\n throw er\n }\n }\n}\n", "const isWindows = process.platform === 'win32' ||\n process.env.OSTYPE === 'cygwin' ||\n process.env.OSTYPE === 'msys'\n\nconst path = require('path')\nconst COLON = isWindows ? ';' : ':'\nconst isexe = require('isexe')\n\nconst getNotFoundError = (cmd) =>\n Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, opt) => {\n const colon = opt.colon || COLON\n\n // If it has a slash, then we don't bother searching the pathenv.\n // just check the file itself, and that's it.\n const pathEnv = cmd.match(/\\//) || isWindows && cmd.match(/\\\\/) ? ['']\n : (\n [\n // windows always checks the cwd first\n ...(isWindows ? [process.cwd()] : []),\n ...(opt.path || process.env.PATH ||\n /* istanbul ignore next: very unusual */ '').split(colon),\n ]\n )\n const pathExtExe = isWindows\n ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'\n : ''\n const pathExt = isWindows ? pathExtExe.split(colon) : ['']\n\n if (isWindows) {\n if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')\n pathExt.unshift('')\n }\n\n return {\n pathEnv,\n pathExt,\n pathExtExe,\n }\n}\n\nconst which = (cmd, opt, cb) => {\n if (typeof opt === 'function') {\n cb = opt\n opt = {}\n }\n if (!opt)\n opt = {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n const step = i => new Promise((resolve, reject) => {\n if (i === pathEnv.length)\n return opt.all && found.length ? resolve(found)\n : reject(getNotFoundError(cmd))\n\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n resolve(subStep(p, i, 0))\n })\n\n const subStep = (p, i, ii) => new Promise((resolve, reject) => {\n if (ii === pathExt.length)\n return resolve(step(i + 1))\n const ext = pathExt[ii]\n isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {\n if (!er && is) {\n if (opt.all)\n found.push(p + ext)\n else\n return resolve(p + ext)\n }\n return resolve(subStep(p, i, ii + 1))\n })\n })\n\n return cb ? step(0).then(res => cb(null, res), cb) : step(0)\n}\n\nconst whichSync = (cmd, opt) => {\n opt = opt || {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n for (let i = 0; i < pathEnv.length; i ++) {\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n for (let j = 0; j < pathExt.length; j ++) {\n const cur = p + pathExt[j]\n try {\n const is = isexe.sync(cur, { pathExt: pathExtExe })\n if (is) {\n if (opt.all)\n found.push(cur)\n else\n return cur\n }\n } catch (ex) {}\n }\n }\n\n if (opt.all && found.length)\n return found\n\n if (opt.nothrow)\n return null\n\n throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n", "'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n", "'use strict';\n\nconst path = require('path');\nconst which = require('which');\nconst getPathKey = require('path-key');\n\nfunction resolveCommandAttempt(parsed, withoutPathExt) {\n const env = parsed.options.env || process.env;\n const cwd = process.cwd();\n const hasCustomCwd = parsed.options.cwd != null;\n // Worker threads do not have process.chdir()\n const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;\n\n // If a custom `cwd` was specified, we need to change the process cwd\n // because `which` will do stat calls but does not support a custom cwd\n if (shouldSwitchCwd) {\n try {\n process.chdir(parsed.options.cwd);\n } catch (err) {\n /* Empty */\n }\n }\n\n let resolved;\n\n try {\n resolved = which.sync(parsed.command, {\n path: env[getPathKey({ env })],\n pathExt: withoutPathExt ? path.delimiter : undefined,\n });\n } catch (e) {\n /* Empty */\n } finally {\n if (shouldSwitchCwd) {\n process.chdir(cwd);\n }\n }\n\n // If we successfully resolved, ensure that an absolute path is returned\n // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it\n if (resolved) {\n resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);\n }\n\n return resolved;\n}\n\nfunction resolveCommand(parsed) {\n return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);\n}\n\nmodule.exports = resolveCommand;\n", "'use strict';\n\n// See http://www.robvanderwoude.com/escapechars.php\nconst metaCharsRegExp = /([()\\][%!^\"`<>&|;, *?])/g;\n\nfunction escapeCommand(arg) {\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n return arg;\n}\n\nfunction escapeArgument(arg, doubleEscapeMetaChars) {\n // Convert to string\n arg = `${arg}`;\n\n // Algorithm below is based on https://qntm.org/cmd\n\n // Sequence of backslashes followed by a double quote:\n // double up all the backslashes and escape the double quote\n arg = arg.replace(/(\\\\*)\"/g, '$1$1\\\\\"');\n\n // Sequence of backslashes followed by the end of the string\n // (which will become a double quote later):\n // double up all the backslashes\n arg = arg.replace(/(\\\\*)$/, '$1$1');\n\n // All other backslashes occur literally\n\n // Quote the whole thing:\n arg = `\"${arg}\"`;\n\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n // Double escape meta chars if necessary\n if (doubleEscapeMetaChars) {\n arg = arg.replace(metaCharsRegExp, '^$1');\n }\n\n return arg;\n}\n\nmodule.exports.command = escapeCommand;\nmodule.exports.argument = escapeArgument;\n", "'use strict';\nmodule.exports = /^#!(.*)/;\n", "'use strict';\nconst shebangRegex = require('shebang-regex');\n\nmodule.exports = (string = '') => {\n\tconst match = string.match(shebangRegex);\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tconst [path, argument] = match[0].replace(/#! ?/, '').split(' ');\n\tconst binary = path.split('/').pop();\n\n\tif (binary === 'env') {\n\t\treturn argument;\n\t}\n\n\treturn argument ? `${binary} ${argument}` : binary;\n};\n", "'use strict';\n\nconst fs = require('fs');\nconst shebangCommand = require('shebang-command');\n\nfunction readShebang(command) {\n // Read the first 150 bytes from the file\n const size = 150;\n const buffer = Buffer.alloc(size);\n\n let fd;\n\n try {\n fd = fs.openSync(command, 'r');\n fs.readSync(fd, buffer, 0, size, 0);\n fs.closeSync(fd);\n } catch (e) { /* Empty */ }\n\n // Attempt to extract shebang (null is returned if not a shebang)\n return shebangCommand(buffer.toString());\n}\n\nmodule.exports = readShebang;\n", "'use strict';\n\nconst path = require('path');\nconst resolveCommand = require('./util/resolveCommand');\nconst escape = require('./util/escape');\nconst readShebang = require('./util/readShebang');\n\nconst isWin = process.platform === 'win32';\nconst isExecutableRegExp = /\\.(?:com|exe)$/i;\nconst isCmdShimRegExp = /node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;\n\nfunction detectShebang(parsed) {\n parsed.file = resolveCommand(parsed);\n\n const shebang = parsed.file && readShebang(parsed.file);\n\n if (shebang) {\n parsed.args.unshift(parsed.file);\n parsed.command = shebang;\n\n return resolveCommand(parsed);\n }\n\n return parsed.file;\n}\n\nfunction parseNonShell(parsed) {\n if (!isWin) {\n return parsed;\n }\n\n // Detect & add support for shebangs\n const commandFile = detectShebang(parsed);\n\n // We don't need a shell if the command filename is an executable\n const needsShell = !isExecutableRegExp.test(commandFile);\n\n // If a shell is required, use cmd.exe and take care of escaping everything correctly\n // Note that `forceShell` is an hidden option used only in tests\n if (parsed.options.forceShell || needsShell) {\n // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`\n // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument\n // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,\n // we need to double escape them\n const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);\n\n // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\\bar)\n // This is necessary otherwise it will always fail with ENOENT in those cases\n parsed.command = path.normalize(parsed.command);\n\n // Escape command & arguments\n parsed.command = escape.command(parsed.command);\n parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));\n\n const shellCommand = [parsed.command].concat(parsed.args).join(' ');\n\n parsed.args = ['/d', '/s', '/c', `\"${shellCommand}\"`];\n parsed.command = process.env.comspec || 'cmd.exe';\n parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped\n }\n\n return parsed;\n}\n\nfunction parse(command, args, options) {\n // Normalize arguments, similar to nodejs\n if (args && !Array.isArray(args)) {\n options = args;\n args = null;\n }\n\n args = args ? args.slice(0) : []; // Clone array to avoid changing the original\n options = Object.assign({}, options); // Clone object to avoid changing the original\n\n // Build our parsed object\n const parsed = {\n command,\n args,\n options,\n file: undefined,\n original: {\n command,\n args,\n },\n };\n\n // Delegate further parsing to shell or non-shell\n return options.shell ? parsed : parseNonShell(parsed);\n}\n\nmodule.exports = parse;\n", "'use strict';\n\nconst isWin = process.platform === 'win32';\n\nfunction notFoundError(original, syscall) {\n return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {\n code: 'ENOENT',\n errno: 'ENOENT',\n syscall: `${syscall} ${original.command}`,\n path: original.command,\n spawnargs: original.args,\n });\n}\n\nfunction hookChildProcess(cp, parsed) {\n if (!isWin) {\n return;\n }\n\n const originalEmit = cp.emit;\n\n cp.emit = function (name, arg1) {\n // If emitting \"exit\" event and exit code is 1, we need to check if\n // the command exists and emit an \"error\" instead\n // See https://github.com/IndigoUnited/node-cross-spawn/issues/16\n if (name === 'exit') {\n const err = verifyENOENT(arg1, parsed, 'spawn');\n\n if (err) {\n return originalEmit.call(cp, 'error', err);\n }\n }\n\n return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params\n };\n}\n\nfunction verifyENOENT(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawn');\n }\n\n return null;\n}\n\nfunction verifyENOENTSync(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawnSync');\n }\n\n return null;\n}\n\nmodule.exports = {\n hookChildProcess,\n verifyENOENT,\n verifyENOENTSync,\n notFoundError,\n};\n", "'use strict';\n\nconst cp = require('child_process');\nconst parse = require('./lib/parse');\nconst enoent = require('./lib/enoent');\n\nfunction spawn(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);\n\n // Hook into child process \"exit\" event to emit an error if the command\n // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n enoent.hookChildProcess(spawned, parsed);\n\n return spawned;\n}\n\nfunction spawnSync(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);\n\n // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);\n\n return result;\n}\n\nmodule.exports = spawn;\nmodule.exports.spawn = spawn;\nmodule.exports.sync = spawnSync;\n\nmodule.exports._parse = parse;\nmodule.exports._enoent = enoent;\n", "'use strict';\nmodule.exports = balanced;\nfunction balanced(a, b, str) {\n if (a instanceof RegExp) a = maybeMatch(a, str);\n if (b instanceof RegExp) b = maybeMatch(b, str);\n\n var r = range(a, b, str);\n\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + a.length, r[1]),\n post: str.slice(r[1] + b.length)\n };\n}\n\nfunction maybeMatch(reg, str) {\n var m = str.match(reg);\n return m ? m[0] : null;\n}\n\nbalanced.range = range;\nfunction range(a, b, str) {\n var begs, beg, left, right, result;\n var ai = str.indexOf(a);\n var bi = str.indexOf(b, ai + 1);\n var i = ai;\n\n if (ai >= 0 && bi > 0) {\n if(a===b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n\n while (i >= 0 && !result) {\n if (i == ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length == 1) {\n result = [ begs.pop(), bi ];\n } else {\n beg = begs.pop();\n if (beg < left) {\n left = beg;\n right = bi;\n }\n\n bi = str.indexOf(b, i + 1);\n }\n\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n\n if (begs.length) {\n result = [ left, right ];\n }\n }\n\n return result;\n}\n", "var balanced = require('balanced-match');\n\nmodule.exports = expandTop;\n\nvar escSlash = '\\0SLASH'+Math.random()+'\\0';\nvar escOpen = '\\0OPEN'+Math.random()+'\\0';\nvar escClose = '\\0CLOSE'+Math.random()+'\\0';\nvar escComma = '\\0COMMA'+Math.random()+'\\0';\nvar escPeriod = '\\0PERIOD'+Math.random()+'\\0';\n\nfunction numeric(str) {\n return parseInt(str, 10) == str\n ? parseInt(str, 10)\n : str.charCodeAt(0);\n}\n\nfunction escapeBraces(str) {\n return str.split('\\\\\\\\').join(escSlash)\n .split('\\\\{').join(escOpen)\n .split('\\\\}').join(escClose)\n .split('\\\\,').join(escComma)\n .split('\\\\.').join(escPeriod);\n}\n\nfunction unescapeBraces(str) {\n return str.split(escSlash).join('\\\\')\n .split(escOpen).join('{')\n .split(escClose).join('}')\n .split(escComma).join(',')\n .split(escPeriod).join('.');\n}\n\n\n// Basically just str.split(\",\"), but handling cases\n// where we have nested braced sections, which should be\n// treated as individual members, like {a,{b,c},d}\nfunction parseCommaParts(str) {\n if (!str)\n return [''];\n\n var parts = [];\n var m = balanced('{', '}', str);\n\n if (!m)\n return str.split(',');\n\n var pre = m.pre;\n var body = m.body;\n var post = m.post;\n var p = pre.split(',');\n\n p[p.length-1] += '{' + body + '}';\n var postParts = parseCommaParts(post);\n if (post.length) {\n p[p.length-1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n\n parts.push.apply(parts, p);\n\n return parts;\n}\n\nfunction expandTop(str) {\n if (!str)\n return [];\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.substr(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.substr(2);\n }\n\n return expand(escapeBraces(str), true).map(unescapeBraces);\n}\n\nfunction embrace(str) {\n return '{' + str + '}';\n}\nfunction isPadded(el) {\n return /^-?0\\d/.test(el);\n}\n\nfunction lte(i, y) {\n return i <= y;\n}\nfunction gte(i, y) {\n return i >= y;\n}\n\nfunction expand(str, isTop) {\n var expansions = [];\n\n var m = balanced('{', '}', str);\n if (!m) return [str];\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n var pre = m.pre;\n var post = m.post.length\n ? expand(m.post, false)\n : [''];\n\n if (/\\$$/.test(m.pre)) { \n for (var k = 0; k < post.length; k++) {\n var expansion = pre+ '{' + m.body + '}' + post[k];\n expansions.push(expansion);\n }\n } else {\n var isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n var isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n var isSequence = isNumericSequence || isAlphaSequence;\n var isOptions = m.body.indexOf(',') >= 0;\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,.*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post;\n return expand(str);\n }\n return [str];\n }\n\n var n;\n if (isSequence) {\n n = m.body.split(/\\.\\./);\n } else {\n n = parseCommaParts(m.body);\n if (n.length === 1) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand(n[0], false).map(embrace);\n if (n.length === 1) {\n return post.map(function(p) {\n return m.pre + n[0] + p;\n });\n }\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n var N;\n\n if (isSequence) {\n var x = numeric(n[0]);\n var y = numeric(n[1]);\n var width = Math.max(n[0].length, n[1].length)\n var incr = n.length == 3\n ? Math.abs(numeric(n[2]))\n : 1;\n var test = lte;\n var reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n var pad = n.some(isPadded);\n\n N = [];\n\n for (var i = x; test(i, y); i += incr) {\n var c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === '\\\\')\n c = '';\n } else {\n c = String(i);\n if (pad) {\n var need = width - c.length;\n if (need > 0) {\n var z = new Array(need + 1).join('0');\n if (i < 0)\n c = '-' + z + c.slice(1);\n else\n c = z + c;\n }\n }\n }\n N.push(c);\n }\n } else {\n N = [];\n\n for (var j = 0; j < n.length; j++) {\n N.push.apply(N, expand(n[j], false));\n }\n }\n\n for (var j = 0; j < N.length; j++) {\n for (var k = 0; k < post.length; k++) {\n var expansion = pre + N[j] + post[k];\n if (!isTop || isSequence || expansion)\n expansions.push(expansion);\n }\n }\n }\n\n return expansions;\n}\n\n", "module.exports = () => {\n\t// https://mths.be/emoji\n\treturn /[#*0-9]\\uFE0F?\\u20E3|[\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u231A\\u231B\\u2328\\u23CF\\u23ED-\\u23EF\\u23F1\\u23F2\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB\\u25FC\\u25FE\\u2600-\\u2604\\u260E\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u2648-\\u2653\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u267F\\u2692\\u2694-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A7\\u26AA\\u26B0\\u26B1\\u26BD\\u26BE\\u26C4\\u26C8\\u26CF\\u26D1\\u26E9\\u26F0-\\u26F5\\u26F7\\u26F8\\u26FA\\u2702\\u2708\\u2709\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u27A1\\u2934\\u2935\\u2B05-\\u2B07\\u2B1B\\u2B1C\\u2B55\\u3030\\u303D\\u3297\\u3299]\\uFE0F?|[\\u261D\\u270C\\u270D](?:\\uFE0F|\\uD83C[\\uDFFB-\\uDFFF])?|[\\u270A\\u270B](?:\\uD83C[\\uDFFB-\\uDFFF])?|[\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u2693\\u26A1\\u26AB\\u26C5\\u26CE\\u26D4\\u26EA\\u26FD\\u2705\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2795-\\u2797\\u27B0\\u27BF\\u2B50]|\\u26D3\\uFE0F?(?:\\u200D\\uD83D\\uDCA5)?|\\u26F9(?:\\uFE0F|\\uD83C[\\uDFFB-\\uDFFF])?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|\\u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\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDC68\\uDC69]\\u200D\\uD83D(?:\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?)|[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?)|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFC-\\uDFFF])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])))?|\\uDFFD(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])))?|\\uDFFE(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])))?|\\uDFFF(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFE])))?))?|\\uDC69(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?[\\uDC68\\uDC69]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?|\\uDC69\\u200D\\uD83D(?:\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?))|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFC-\\uDFFF])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])))?|\\uDFFD(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])))?|\\uDFFE(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])))?|\\uDFFF(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB-\\uDFFE])))?))?|\\uDC6F(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|\\uDD75(?:\\uFE0F|\\uD83C[\\uDFFB-\\uDFFF])?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|\\uDE2E(?:\\u200D\\uD83D\\uDCA8)?|\\uDE35(?:\\u200D\\uD83D\\uDCAB)?|\\uDE36(?:\\u200D\\uD83C\\uDF2B\\uFE0F?)?|\\uDE42(?:\\u200D[\\u2194\\u2195]\\uFE0F?)?|\\uDEB6(?:\\uD83C[\\uDFFB-\\uDFFF])?(?:\\u200D(?:[\\u2640\\u2642]\\uFE0F?(?:\\u200D\\u27A1\\uFE0F?)?|\\u27A1\\uFE0F?))?)|\\uD83E(?:[\\uDD0C\\uDD0F\\uDD18-\\uDD1F\\uDD30-\\uDD34\\uDD36\\uDD77\\uDDB5\\uDDB6\\uDDBB\\uDDD2\\uDDD3\\uDDD5\\uDEC3-\\uDEC5\\uDEF0\\uDEF2-\\uDEF8](?:\\uD83C[\\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\uDFFF(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB-\\uDFFE])?))?)/g;\n};\n", "import type { IncomingMessage } from 'http'\n\n/**\n * Codification of vlt's Error.cause conventions\n *\n * Add new properties to this list as needed.\n *\n * Several of these types are just very basic duck-typing, because referencing\n * internal types directly would create a workspace dependency cycle.\n */\nexport type ErrorCauseObject = {\n /**\n * The `cause` field within a `cause` object should\n * always be an `Error` object that was previously thrown. Note\n * that the `cause` on an Error itself might _also_ be a\n * previously thrown error, if no additional information could be\n * usefully added beyond improving the message.\n */\n cause?: ErrorCause\n\n /** the name of something */\n name?: string\n\n /** byte offset in a Buffer or file */\n offset?: number\n\n /**\n * This should only be a string code that we set. See {@link Codes} for\n * the supported options. Lower-level system codes like `ENOENT` should\n * remain on the errors that generated them.\n */\n code?: Codes\n\n /** target of a file system operation */\n path?: string\n\n /**\n * file path origin of a resolution that failed, for example in the case\n * of `file://` specifiers.\n */\n from?: string\n\n /** path on disk that is being written, linked, or extracted to */\n target?: string\n\n /** Spec object/string relevant to an operation that failed */\n spec?:\n | string\n | {\n type: 'file' | 'git' | 'registry' | 'remote' | 'workspace'\n spec: string\n [k: number | string | symbol]: any\n }\n\n /** exit code of a process, or HTTP response status code */\n status?: number | null\n\n /** null or a signal that a process received */\n signal?: NodeJS.Signals | null\n\n /** the root of a project */\n projectRoot?: string\n\n /** the current working directory of a process */\n cwd?: string\n\n /** a command being run in a child process */\n command?: string\n\n /** the arguments passed to a process */\n args?: string[]\n\n /** standard output from a process */\n stdout?: Buffer | string | null\n\n /** standard error from a process */\n stderr?: Buffer | string | null\n\n /**\n * Array of valid options when something is not a valid option.\n * (For use in `did you mean X?` output.)\n */\n validOptions?: any[]\n\n /**\n * message indicating what bit of work this might be a part of, what feature\n * needs to be implemented, etc. Eg, `{ todo: 'nested workspace support' }`.\n */\n todo?: string\n\n /**\n * A desired value that was not found, or a regular expression or other\n * pattern describing it.\n */\n wanted?: any\n\n /** actual value, which was not wanted */\n found?: any\n\n /** HTTP message, fetch.Response, or `@vltpkg/registry-client.CacheEntry` */\n response?:\n | IncomingMessage\n | Response\n | {\n statusCode: number\n headers: Buffer[] | Record<string, string[] | string>\n text: () => string\n [k: number | string | symbol]: any\n }\n\n /** string or URL object */\n url?: URL | string\n\n /** git repository remote or path */\n repository?: string\n\n /** string or `@vltpkg/semver.Version` object */\n version?:\n | string\n | {\n raw: string\n major: number\n minor: number\n patch: number\n [k: number | string | symbol]: any\n }\n\n /** string or `@vltpkg/semver.Range` object */\n range?:\n | string\n | {\n raw: string\n isAny: boolean\n includePrerelease: boolean\n [k: number | string | symbol]: any\n }\n\n /** a package manifest, either from `package.json` or a registry */\n manifest?: DuckTypeManifest\n\n /** registry top-level package document */\n packument?: {\n name: string\n 'dist-tags': Record<string, string>\n versions: Record<string, DuckTypeManifest>\n time?: Record<string, string>\n }\n\n /** maximum value, which was exceeded */\n max?: any\n\n /** minimum value, which was not met */\n min?: any\n}\n\nexport type DuckTypeManifest = Record<string, any> & {\n name?: string\n version?: string\n deprecated?: string\n engines?: Record<string, string>\n os?: string[] | string\n arch?: string[] | string\n dist?: {\n integrity?: string\n shasum?: string\n tarball?: string\n fileCount?: number\n unpackedSize?: number\n signatures?: {\n keyid: string\n sig: string\n }[]\n }\n}\n\nexport type ErrorCause = Error | ErrorCauseObject\n\n/**\n * Valid properties for the 'code' field in an Error cause.\n * Add new options to this list as needed.\n */\nexport type Codes =\n | 'EEXIST'\n | 'EINTEGRITY'\n | 'EINVAL'\n | 'ELIFECYCLE'\n | 'EMAXREDIRECT'\n | 'ENEEDAUTH'\n | 'ENOENT'\n | 'ENOGIT'\n | 'ERESOLVE'\n | 'EUNKNOWN'\n\nconst create = (\n cls: typeof Error,\n defaultFrom: ((...a: any[]) => any) | (new (...a: any[]) => any),\n message: string,\n cause?: ErrorCause,\n from:\n | ((...a: any[]) => any)\n | (new (...a: any[]) => any) = defaultFrom,\n) => {\n const er = new cls(message, cause ? { cause } : undefined)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n Error.captureStackTrace?.(er, from)\n return er\n}\n\nexport const error = (\n message: string,\n cause?: ErrorCause,\n from?: ((...a: any[]) => any) | (new (...a: any[]) => any),\n) => create(Error, error, message, cause, from)\n\nexport const typeError = (\n message: string,\n cause?: ErrorCause,\n from?: ((...a: any[]) => any) | (new (...a: any[]) => any),\n) => create(TypeError, typeError, message, cause, from)\n\nexport const syntaxError = (\n message: string,\n cause?: ErrorCause,\n from?: ((...a: any[]) => any) | (new (...a: any[]) => any),\n) => create(SyntaxError, syntaxError, message, cause, from)\n", "import { error } from '@vltpkg/error-cause'\n\n/** anything that can be encoded in JSON */\nexport type JSONField =\n | JSONField[]\n | boolean\n | number\n | string\n | { [k: string]: JSONField }\n | null\n\n/** sha512 SRI string */\nexport type Integrity = `sha512-${string}`\n\n/** SHA256 key identifier */\nexport type KeyID = `SHA256:${string}`\n\n/** The Manifest['dist'] field present in registry manifests */\nexport type Dist = {\n integrity?: Integrity\n shasum?: string\n tarball?: string\n fileCount?: number\n unpackedSize?: number\n signatures?: {\n keyid: KeyID\n sig: string\n }[]\n}\n\n/** An object used to mark some peerDeps as optional */\nexport type PeerDependenciesMetaValue = {\n optional?: boolean\n}\n\n// Don't use Record here since TS cant do circular references with that\n// https://github.com/microsoft/TypeScript/issues/41164#issuecomment-1427073368\nexport type ConditionalValueObject = {\n [k: string]: ConditionalValue\n}\nexport type ConditionalValue =\n | ConditionalValue[]\n | ConditionalValueObject\n | string\n | null\n\nexport type ExportsSubpaths = {\n [path in '.' | `./${string}`]?: ConditionalValue\n}\n\nexport type Exports =\n | Exclude<ConditionalValue, null>\n | ExportsSubpaths\n\nexport type Imports = Record<`#${string}`, ConditionalValue>\n\nexport type FundingEntry = string | { url: string }\nexport type Funding = FundingEntry | FundingEntry[]\n\nexport type ManifestRegistry = Manifest & {\n name: string\n version: string\n dist: Dist\n}\n\nexport type ManifestMinified = {\n /** The name of the package. optional because {} is a valid package.json */\n name?: string\n /** The version of the package. optional because {} is a valid package.json */\n version?: string\n /** production dependencies, name:specifier */\n dependencies?: Record<string, string>\n /** development dependencies, name:specifier */\n devDependencies?: Record<string, string>\n /** optional dependencies, name:specifier */\n optionalDependencies?: Record<string, string>\n /** peer dependencies, name:specifier */\n peerDependencies?: Record<string, string>\n /** peer dependencies marked as optional */\n peerDependenciesMeta?: Record<string, PeerDependenciesMetaValue>\n /** dependency ranges that are acceptable, but not forced */\n acceptDependencies?: Record<string, string>\n /** names of dependencies included in the package tarball */\n bundleDependencies?: string[]\n /** a message indicating that this is not to be used */\n deprecated?: string\n /** executable built and linked by this package */\n bin?: Record<string, string> | string\n /** run-script actions for this package */\n scripts?: Record<string, string>\n /** supported run-time platforms this package can run on */\n engines?: Record<string, string>\n /** supported operating systems this package can run on */\n os?: string[] | string\n /** supported CPU architectures this package can run on */\n cpu?: string[] | string\n /** URLs that can be visited to fund this project */\n funding?: Funding\n /**\n * Only present in Manifests served by a registry. Contains information\n * about the artifact served for this package release.\n */\n dist?: Dist\n}\n\nexport type Person =\n | string\n | {\n name: string\n url?: string\n email?: string\n }\n\nexport type Repository =\n | string\n | {\n type: string\n url: string\n }\n\nexport type Bugs =\n | string\n | {\n url?: string\n email?: string\n }\n\nexport type Manifest = ManifestMinified &\n Record<string, JSONField> & {\n /** a short description of the package */\n description?: string\n /** search keywords */\n keywords?: string[]\n /** where to go to file issues */\n bugs?: Bugs\n /** where the development happens */\n repository?: Repository\n /** whether this is ESM or CommonJS by default */\n type?: 'commonjs' | 'module'\n /** the main module, if exports['.'] is not set */\n main?: string\n /** named subpath exports */\n exports?: Exports\n /** named #identifier imports */\n imports?: Imports\n /**\n * the HEAD of the git repo this was published from\n * only present in published packages\n */\n gitHead?: string\n }\n\nexport type PackumentBase = {\n name: string\n 'dist-tags': Record<string, string>\n}\nexport type PackumentMinified = PackumentBase & {\n versions: Record<string, ManifestMinified>\n modified?: string\n}\n\nexport type Packument = PackumentBase &\n Record<string, JSONField> & {\n versions: Record<string, Manifest>\n time?: Record<string, string>\n readme?: string\n }\n\nconst integrityRE = /^sha512-[a-zA-Z0-9/+]{86}==$/\nexport const isIntegrity = (i: unknown): i is Integrity =>\n typeof i === 'string' && integrityRE.test(i)\n\nexport const asIntegrity = (i: unknown): Integrity => {\n if (!isIntegrity(i)) {\n throw error(\n 'invalid integrity',\n {\n found: i,\n wanted: integrityRE,\n },\n asIntegrity,\n )\n }\n return i\n}\n\nexport const assertIntegrity: (\n i: unknown,\n) => asserts i is Integrity = i => {\n asIntegrity(i)\n}\n\nconst keyIDRE = /^SHA256:[a-zA-Z0-9/+]{43}$/\nexport const isKeyID = (k: unknown): k is KeyID =>\n typeof k === 'string' && keyIDRE.test(k)\n\nexport const asKeyID = (k: unknown): KeyID => {\n if (!isKeyID(k)) {\n throw error(\n 'invalid key ID',\n {\n found: k,\n wanted: keyIDRE,\n },\n asKeyID,\n )\n }\n return k\n}\n\nexport const assertKeyID: (k: unknown) => asserts k is KeyID = k => {\n asKeyID(k)\n}\n\nconst maybeRecordStringString = (\n o: unknown,\n): o is Record<string, string> | undefined =>\n o === undefined || isRecordStringString(o)\n\nconst isRecordStringString = (\n o: unknown,\n): o is Record<string, string> =>\n isRecordStringT<string>(o, s => typeof s === 'string')\n\nconst isRecordStringT = <T>(\n o: unknown,\n check: (o: unknown) => boolean,\n): o is Record<string, T> =>\n !!o &&\n typeof o === 'object' &&\n Object.entries(o).every(\n ([k, v]) => typeof k === 'string' && check(v),\n )\n\nconst isRecordStringManifest = (\n o: unknown,\n): o is Record<string, Manifest> =>\n isRecordStringT<Manifest>(o, v => isManifest(v))\n\nconst maybePeerDependenciesMetaSet = (\n o: unknown,\n): o is Record<string, PeerDependenciesMetaValue> | undefined =>\n o === undefined ||\n isRecordStringT<PeerDependenciesMetaValue>(o, v =>\n isPeerDependenciesMetaValue(v),\n )\n\nconst maybeBoolean = (o: unknown): o is boolean =>\n o === undefined || typeof o === 'boolean'\n\nconst isPeerDependenciesMetaValue = (\n o: any,\n): o is PeerDependenciesMetaValue =>\n !!o && typeof o === 'object' && maybeBoolean(o.optional)\n\nconst maybeString = (a: unknown): a is string | undefined =>\n a === undefined || typeof a === 'string'\n\nconst maybeDist = (a: any): a is Manifest['dist'] =>\n a === undefined ||\n (!!a && typeof a === 'object' && maybeString(a.tarball))\n\nexport const isManifest = (m: any): m is Manifest =>\n !!m &&\n typeof m === 'object' &&\n !Array.isArray(m) &&\n maybeString(m.name) &&\n maybeString(m.version) &&\n maybeRecordStringString(m.dependencies) &&\n maybeRecordStringString(m.devDependencies) &&\n maybeRecordStringString(m.optionalDependencies) &&\n maybeRecordStringString(m.peerDependencies) &&\n maybeRecordStringString(m.acceptDependencies) &&\n maybePeerDependenciesMetaSet(m.peerDependenciesMeta) &&\n maybeDist(m.dist)\n\nexport const isManifestRegistry = (\n m: unknown,\n): m is ManifestRegistry =>\n isManifest(m) && !!m.dist && !!m.name && !!m.version\n\nexport const asManifest = (\n m: unknown,\n from?: (...a: any[]) => any,\n): Manifest => {\n if (!isManifest(m)) {\n throw error('invalid manifest', { found: m }, from ?? asManifest)\n }\n return m\n}\n\nexport const asManifestMinified = (\n m: unknown,\n from?: (...a: any[]) => any,\n): ManifestMinified => asManifest(m, from ?? asManifestMinified)\n\nexport const asManifestRegistry = (\n m: unknown,\n from?: (...a: any[]) => any,\n): ManifestRegistry => {\n if (!isManifestRegistry(m)) {\n throw error(\n 'invalid registry manifest',\n { found: m },\n from ?? asManifestRegistry,\n )\n }\n return m\n}\n\nexport const assertManifest: (\n m: unknown,\n) => asserts m is Manifest = m => {\n asManifest(m, assertManifest)\n}\nexport const assertManifestMinified: (\n m: unknown,\n) => asserts m is Manifest = m => {\n asManifestMinified(m, assertManifestMinified)\n}\nexport const assertManifestRegistry: (\n m: unknown,\n) => asserts m is ManifestRegistry = m => {\n asManifestRegistry(m, assertManifestRegistry)\n}\n\nexport const isPackument = (p: any): p is Packument =>\n !!p &&\n typeof p === 'object' &&\n typeof p.name === 'string' &&\n isRecordStringString(p['dist-tags']) &&\n isRecordStringManifest(p.versions) &&\n maybeRecordStringString(p.time) &&\n Object.values(p['dist-tags']).every(\n v => !!p.versions[v] && p.versions[v].name == p.name,\n )\n\nexport const isPackumentMinified = (\n p: unknown,\n): p is PackumentMinified => isPackument(p)\nexport const asPackumentMinified = (p: unknown): PackumentMinified =>\n asPackument(p, asPackumentMinified)\n\nexport const asPackument = (\n p: unknown,\n from?: (...a: unknown[]) => any,\n): Packument => {\n if (!isPackument(p)) {\n throw error(\n 'invalid packument',\n { found: p },\n from ?? asPackument,\n )\n }\n return p\n}\n\nexport const assertPackument: (\n m: unknown,\n) => asserts m is Packument = m => {\n asPackument(m)\n}\nexport const assertPackumentMinified: (\n m: unknown,\n) => asserts m is PackumentMinified = m => {\n asPackumentMinified(m)\n}\n", "import { error, ErrorCauseObject } from '@vltpkg/error-cause'\nimport { asManifest, Manifest } from '@vltpkg/types'\nimport { readFileSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { parse, stringify } from 'polite-json'\n\nexport class PackageJson {\n /**\n * cache of `package.json` loads\n */\n #cache = new Map<string, Manifest>()\n\n /**\n * cache of `package.json` paths by manifest\n */\n #pathCache = new Map<Manifest, string>()\n\n /**\n * cache of load errors\n */\n #errCache = new Map<string, ErrorCauseObject>()\n\n /**\n * Reads and parses contents of a `package.json` file at a directory `dir`.\n * `reload` will optionally skip reading from the cache when set to `true`.\n */\n read(dir: string, { reload }: { reload?: boolean } = {}): Manifest {\n const cachedPackageJson = !reload && this.#cache.get(dir)\n if (cachedPackageJson) {\n return cachedPackageJson\n }\n\n const filename = resolve(dir, 'package.json')\n\n const fail = (err: ErrorCauseObject) =>\n error('Could not read package.json file', err, this.read)\n\n const cachedError = !reload && this.#errCache.get(dir)\n if (cachedError) {\n throw fail(cachedError)\n }\n\n try {\n const res: Manifest = asManifest(\n parse(readFileSync(filename, { encoding: 'utf8' })),\n )\n this.#cache.set(dir, res)\n this.#pathCache.set(res, dir)\n return res\n } catch (err) {\n const ec: ErrorCauseObject = {\n path: filename,\n cause: err as Error,\n }\n this.#errCache.set(dir, ec)\n throw fail(ec)\n }\n }\n\n write(dir: string, manifest: Manifest): void {\n const filename = resolve(dir, 'package.json')\n\n try {\n // This assumes kIndent and kNewline are already present on the manifest because we would\n // only write a package.json after reading it which will set those properties.\n writeFileSync(filename, stringify(manifest))\n this.#cache.set(dir, manifest)\n this.#pathCache.set(manifest, dir)\n } catch (err) {\n // If there was an error writing to this package.json then also delete it from our cache\n // just in case a future read would get stale data.\n this.#cache.delete(dir)\n this.#pathCache.delete(manifest)\n throw error(\n 'Could not write package.json file',\n {\n path: filename,\n cause: err as Error,\n },\n this.write,\n )\n }\n }\n\n save(manifest: Manifest): void {\n const dir = this.#pathCache.get(manifest)\n if (!dir) {\n throw error(\n 'Could not save manifest',\n {\n manifest,\n },\n this.save,\n )\n }\n this.write(dir, manifest)\n }\n}\n", "/**\n * Copyright 2017 Kat Marchán\n * Copyright npm, Inc.\n * Copyright 2023 Isaac Z. Schlueter\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n * ---\n *\n * 'polite-json' is a fork of 'json-parse-even-better-errors',\n * extended and distributed under the terms of the MIT license\n * above.\n *\n * 'json-parse-even-better-errors' is a fork of\n * 'json-parse-better-errors' by Kat Marchán, extended and\n * distributed under the terms of the MIT license above.\n */\n\n// version specific\n/* c8 ignore start */\nconst hexify = (s: string) =>\n Array.from(s)\n .map(\n c => '0x' + c.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')\n )\n .join('')\n/* c8 ignore stop */\n\ntype ParseErrorMeta = {\n message: string\n position: number\n}\nconst parseError = (e: Error, txt: string, context: number): ParseErrorMeta => {\n if (!txt) {\n return {\n message: e.message + ' while parsing empty string',\n position: 0,\n }\n }\n const badToken = e.message.match(/^Unexpected (?:token (.*?))?/i)\n const atPos = e.message.match(/at positions? (\\d+)/)\n\n // version specific\n /* c8 ignore start */\n const errIdx = /^Unexpected end of JSON|Unterminated string in JSON/i.test(\n e.message\n )\n ? txt.length - 1\n : atPos && atPos[1]\n ? +atPos[1]\n : /is not valid JSON$/.test(e.message)\n ? 0\n : null\n\n const msg =\n badToken && badToken[1]\n ? e.message.replace(\n /^Unexpected token ./,\n `Unexpected token ${JSON.stringify(badToken[1])} (${hexify(\n badToken[1]\n )})`\n )\n : e.message\n /* c8 ignore stop */\n\n if (errIdx !== null && errIdx !== undefined) {\n const start = errIdx <= context ? 0 : errIdx - context\n\n const end = errIdx + context >= txt.length ? txt.length : errIdx + context\n\n const slice =\n (start === 0 ? '' : '...') +\n txt.slice(start, end) +\n (end === txt.length ? '' : '...')\n\n const near = txt === slice ? '' : 'near '\n\n return {\n message: msg + ` while parsing ${near}${JSON.stringify(slice)}`,\n position: errIdx,\n }\n } else {\n return {\n message: msg + ` while parsing '${txt.slice(0, context * 2)}'`,\n position: 0,\n }\n }\n}\n\nexport class JSONParseError extends SyntaxError {\n code: 'EJSONPARSE'\n cause: Error\n position: number\n constructor(\n er: Error,\n txt: string,\n context: number = 20,\n caller?: Function | ((...a: any[]) => any)\n ) {\n const { message, position } = parseError(er, txt, context)\n super(message)\n this.cause = er\n this.position = position\n this.code = 'EJSONPARSE'\n Error.captureStackTrace(this, caller || this.constructor)\n }\n get name() {\n return this.constructor.name\n }\n set name(_) {}\n get [Symbol.toStringTag]() {\n return this.constructor.name\n }\n}\n\nexport const kIndent = Symbol.for('indent')\nexport const kNewline = Symbol.for('newline')\n// only respect indentation if we got a line break, otherwise squash it\n// things other than objects and arrays aren't indented, so ignore those\n// Important: in both of these regexps, the $1 capture group is the newline\n// or undefined, and the $2 capture group is the indent, or undefined.\nconst formatRE = /^\\s*[{\\[]((?:\\r?\\n)+)([\\s\\t]*)/\nconst emptyRE = /^(?:\\{\\}|\\[\\])((?:\\r?\\n)+)?$/\n\nexport type Reviver = (this: any, key: string, value: any) => any\nexport type Replacer =\n | ((this: any, key: string, value: any) => any)\n | (string | number)[]\n | null\nexport type Scalar = string | number | null\nexport type JSONResult =\n | {\n [k: string]: JSONResult\n [kIndent]?: string\n [kNewline]?: string\n }\n | (JSONResult[] & { [kIndent]?: string; [kNewline]?: string })\n | Scalar\n\nexport const parse = (\n txt: string | Buffer,\n reviver?: Reviver | null,\n context?: number\n): JSONResult => {\n const parseText = stripBOM(String(txt))\n if (!reviver) reviver = undefined\n context = context || 20\n try {\n // get the indentation so that we can save it back nicely\n // if the file starts with {\" then we have an indent of '', ie, none\n // otherwise, pick the indentation of the next line after the first \\n\n // If the pattern doesn't match, then it means no indentation.\n // JSON.stringify ignores symbols, so this is reasonably safe.\n // if the string is '{}' or '[]', then use the default 2-space indent.\n const [, newline = '\\n', indent = ' '] = parseText.match(emptyRE) ||\n parseText.match(formatRE) || [, '', '']\n\n const result = JSON.parse(parseText, reviver)\n if (result && typeof result === 'object') {\n result[kNewline] = newline\n result[kIndent] = indent\n }\n return result\n } catch (e) {\n if (typeof txt !== 'string' && !Buffer.isBuffer(txt)) {\n const isEmptyArray =\n Array.isArray(txt) && (txt as Array<any>).length === 0\n throw Object.assign(\n new TypeError(\n `Cannot parse ${isEmptyArray ? 'an empty array' : String(txt)}`\n ),\n {\n code: 'EJSONPARSE',\n systemError: e,\n }\n )\n }\n\n throw new JSONParseError(e as Error, parseText, context, parse)\n }\n}\n\nexport const parseNoExceptions = (txt: string | Buffer, reviver?: Reviver) => {\n try {\n return JSON.parse(stripBOM(String(txt)), reviver)\n } catch (e) {}\n}\n\n// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n// because the buffer-to-string conversion in `fs.readFileSync()`\n// translates it to FEFF, the UTF-16 BOM.\nconst stripBOM = (txt: string) => String(txt).replace(/^\\uFEFF/, '')\n\nexport const stringify = (\n obj: any,\n replacer?: Replacer,\n indent?: string | number\n) => {\n const space = indent === undefined ? obj[kIndent] : indent\n // TS is so weird with parameter overloads\n const res =\n /* c8 ignore start */\n typeof replacer === 'function'\n ? JSON.stringify(obj, replacer, space)\n : JSON.stringify(obj, replacer, space)\n /* c8 ignore stop */\n const nl = obj[kNewline] || '\\n'\n return space ? (nl === '\\n' ? res : res.split('\\n').join(nl)) + nl : res\n}\n", "import { error } from '@vltpkg/error-cause'\nimport {\n ChildProcess,\n IOType,\n spawn,\n SpawnOptions,\n StdioOptions,\n} from 'child_process'\n\nconst isPipe = (\n stdio:\n | Exclude<StdioOptions, IOType>[number]\n | StdioOptions = 'pipe',\n fd: number,\n): stdio is IOTypePipe =>\n stdio === 'pipe' || stdio === 'overlapped' || stdio === null ? true\n : Array.isArray(stdio) ? isPipe(stdio[fd], fd)\n : false\n\nexport type IOTypeNoPipe = Exclude<IOType, IOTypePipe>\nexport type IOTypePipe = 'overlapped' | 'pipe' | null | undefined\nexport type PromiseSpawnOptions = SpawnOptions & {\n stdioString?: boolean\n acceptFail?: boolean\n}\nexport type PromiseSpawnOptionsString = PromiseSpawnOptions & {\n stdioString?: true\n}\nexport type PromiseSpawnOptionsBuffer = PromiseSpawnOptions & {\n stdioString: false\n}\nexport type PromiseSpawnOptionsStdin = PromiseSpawnOptions & {\n stdio?:\n | Exclude<IOTypePipe, null>\n | [\n stdin?: IOTypePipe,\n stdout?: Exclude<StdioOptions, IOType>[number],\n stderr?: Exclude<StdioOptions, IOType>[number],\n ]\n}\nexport type PromiseSpawnOptionsNoStdin = PromiseSpawnOptions & {\n stdio:\n | IOTypeNoPipe\n | IOTypeNoPipe[]\n | [\n stdin: IOTypeNoPipe | number,\n stdout?: Exclude<StdioOptions, IOType>[number],\n stderr?: Exclude<StdioOptions, IOType>[number],\n ]\n}\nexport type PromiseSpawnOptionsStdout = PromiseSpawnOptions & {\n stdio?:\n | Exclude<IOTypePipe, null>\n | [\n stdin: Exclude<StdioOptions, IOType>[number] | undefined,\n stdout?: IOTypePipe,\n stderr?: Exclude<StdioOptions, IOType>[number],\n ]\n}\nexport type PromiseSpawnOptionsStdoutString =\n PromiseSpawnOptionsStdout & {\n stdioString?: true\n }\nexport type PromiseSpawnOptionsStdoutBuffer =\n PromiseSpawnOptionsStdout & {\n stdioString: false\n }\nexport type PromiseSpawnOptionsNoStdout = PromiseSpawnOptions & {\n stdio:\n | IOTypeNoPipe\n | IOTypeNoPipe[]\n | [\n stdin: Exclude<StdioOptions, IOType>[number] | undefined,\n stdout?: IOTypeNoPipe,\n stderr?: Exclude<StdioOptions, IOType>[number],\n ]\n}\n/* c8 ignore start - weird windows coverage bug */\nexport type PromiseSpawnOptionsStderr = PromiseSpawnOptions & {\n stdio?:\n | Exclude<IOTypePipe, null>\n | [\n stdin: Exclude<StdioOptions, IOType>[number] | undefined,\n stdout: Exclude<StdioOptions, IOType>[number] | undefined,\n stderr?: IOTypePipe,\n ]\n}\n/* c8 ignore stop */\nexport type PromiseSpawnOptionsStderrString =\n PromiseSpawnOptionsStderr & {\n stdioString?: true\n }\nexport type PromiseSpawnOptionsStderrBuffer =\n PromiseSpawnOptionsStderr & {\n stdioString: false\n }\nexport type PromiseSpawnOptionsNoStderr = PromiseSpawnOptions & {\n stdio:\n | IOTypeNoPipe\n | IOTypeNoPipe[]\n | [\n stdin: Exclude<StdioOptions, IOType>[number] | undefined,\n stdout: Exclude<StdioOptions, IOType>[number] | undefined,\n stderr: IOTypeNoPipe,\n ]\n}\n\nfunction stdioResult<O extends PromiseSpawnOptions>(\n stdout: Buffer[],\n stderr: Buffer[],\n o: O,\n): {\n stdout: SpawnResultByOptions<O>['stdout']\n stderr: SpawnResultByOptions<O>['stderr']\n} {\n return {\n stdout: (!isPipe(o.stdio, 1) ? null\n : o.stdioString !== false ?\n Buffer.concat(stdout).toString().trim()\n : Buffer.concat(stdout)) as SpawnResultByOptions<O>['stdout'],\n stderr: (!isPipe(o.stdio, 2) ? null\n : o.stdioString !== false ?\n Buffer.concat(stderr).toString().trim()\n : Buffer.concat(stderr)) as SpawnResultByOptions<O>['stderr'],\n }\n}\n\nexport type SpawnResult = {\n command: string\n args: string[]\n cwd: string\n status: number | null\n signal: NodeJS.Signals | null\n stdout: Buffer | string | null\n stderr: Buffer | string | null\n}\nexport type SpawnResultString = SpawnResult & {\n stdout: string | null\n stderr: string | null\n}\nexport type SpawnResultBuffer = SpawnResult & {\n stdout: Buffer | null\n stderr: Buffer | null\n}\nexport type SpawnResultStdout = SpawnResult & {\n stdout: Buffer | string\n}\nexport type SpawnResultStdoutString = SpawnResultString & {\n stdout: string\n}\nexport type SpawnResultStdoutBuffer = SpawnResultBuffer & {\n stdout: Buffer\n}\nexport type SpawnResultNoStdout = SpawnResult & {\n stdout: null\n}\nexport type SpawnResultStderr = SpawnResult & {\n stderr: Buffer | string\n}\nexport type SpawnResultStderrString = SpawnResultString & {\n stderr: string\n}\nexport type SpawnResultStderrBuffer = SpawnResultBuffer & {\n stderr: Buffer\n}\nexport type SpawnResultNoStderr = SpawnResult & {\n stderr: null\n}\n\nexport type SpawnResultNoStdio = SpawnResult & {\n stderr: null\n stdout: null\n}\nexport type SpawnResultStdioStrings = SpawnResult & {\n stdout: string\n stderr: string\n}\nexport type SpawnResultStdioBuffers = SpawnResult & {\n stdout: Buffer\n stderr: Buffer\n}\n\nexport type SpawnResultByOptions<T extends PromiseSpawnOptions> =\n SpawnResult & {\n stdout: T extends PromiseSpawnOptionsNoStdout ? null\n : T extends PromiseSpawnOptionsStdoutBuffer ? Buffer\n : T extends PromiseSpawnOptionsStdoutString ? string\n : T extends PromiseSpawnOptionsBuffer ? Buffer | null\n : T extends PromiseSpawnOptionsString ? string | null\n : Buffer | string | null\n stderr: T extends PromiseSpawnOptionsNoStderr ? null\n : T extends PromiseSpawnOptionsStderrBuffer ? Buffer\n : T extends PromiseSpawnOptionsStderrString ? string\n : T extends PromiseSpawnOptionsBuffer ? Buffer | null\n : T extends PromiseSpawnOptionsString ? string | null\n : Buffer | string | null\n }\n\nexport type ChildProcessByOptions<T extends PromiseSpawnOptions> =\n ChildProcess & {\n stdin: T extends PromiseSpawnOptionsNoStdin ? null\n : Exclude<ChildProcess['stdin'], null>\n stdout: T extends PromiseSpawnOptionsNoStdout ? null\n : Exclude<ChildProcess['stdout'], null>\n stderr: T extends PromiseSpawnOptionsNoStderr ? null\n : Exclude<ChildProcess['stderr'], null>\n }\n\n/**\n * Subtype of Promise returned by {@link spawnPromise}.\n *\n * Resolution value is inferred from the provided options.\n */\nexport class SpawnPromise<\n O extends PromiseSpawnOptions,\n T extends object = object,\n> extends Promise<SpawnResultByOptions<O> & T> {\n [Symbol.toStringTag] = 'SpawnPromise'\n\n /** The spawned process this promise references */\n process!: ChildProcessByOptions<O>\n\n /** Expose the child process stdin, if available */\n stdin!: ChildProcessByOptions<O>['stdin']\n\n /**\n * Set static `Symbol.species` back to the base Promise class so that\n * v8 doesn't get confused by the changed constructor signature.\n */\n static get [Symbol.species]() {\n return Promise\n }\n\n constructor(\n command: string,\n args: string[],\n opts: O,\n extra: T = {} as T,\n ) {\n let proc!: ChildProcessByOptions<O>\n super((res, rej) => {\n proc = spawn(command, args, opts) as ChildProcessByOptions<O>\n const stdout: Buffer[] = []\n const stderr: Buffer[] = []\n const reject = (er: Error) =>\n rej(\n error('command failed', {\n command,\n args,\n cwd: opts.cwd ?? process.cwd(),\n ...stdioResult(stdout, stderr, opts),\n ...extra,\n cause: er,\n }),\n )\n proc.on('error', reject)\n if (proc.stdout) {\n proc.stdout\n .on('data', c => stdout.push(c))\n .on('error', er => reject(er))\n }\n if (proc.stderr) {\n proc.stderr\n .on('data', c => stderr.push(c))\n .on('error', er => reject(er))\n }\n proc.on('close', (status, signal) => {\n const result = {\n command,\n args,\n cwd: opts.cwd ?? process.cwd(),\n /* c8 ignore next 2 - because windows */\n status: status ?? null,\n signal: signal ?? null,\n ...stdioResult(stdout, stderr, opts),\n ...extra,\n } as SpawnResultByOptions<O> & T\n if ((status || signal) && !opts.acceptFail)\n rej(error('command failed', result))\n else res(result)\n })\n })\n this.process = proc\n this.stdin = proc.stdin\n }\n}\n\n/**\n * Spawn the specified command, and return a promise that resolves when\n * the process closes or has an error.\n */\nexport function promiseSpawn<\n O extends PromiseSpawnOptions = PromiseSpawnOptionsStderrString &\n PromiseSpawnOptionsStdoutString,\n E extends object = object,\n>(command: string, args: string[], opts = {} as O, extra = {} as E) {\n return new SpawnPromise<O, E>(command, args, opts, extra)\n}\n", "import {\n ChildProcessByStdio,\n SendHandle,\n Serializable,\n spawn as nodeSpawn,\n SpawnOptions,\n ChildProcess,\n} from 'child_process'\nimport crossSpawn from 'cross-spawn'\nimport { onExit } from 'signal-exit'\nimport { proxySignals } from './proxy-signals.js'\nimport { watchdog } from './watchdog.js'\n\n/* c8 ignore start */\nconst spawn = process?.platform === 'win32' ? crossSpawn : nodeSpawn\n/* c8 ignore stop */\n\n/**\n * The signature for the cleanup method.\n *\n * Arguments indicate the exit status of the child process.\n *\n * If a Promise is returned, then the process is not terminated\n * until it resolves, and the resolution value is treated as the\n * exit status (if a number) or signal exit (if a signal string).\n *\n * If `undefined` is returned, then no change is made, and the parent\n * exits in the same way that the child exited.\n *\n * If boolean `false` is returned, then the parent's exit is canceled.\n *\n * If a number is returned, then the parent process exits with the number\n * as its exitCode.\n *\n * If a signal string is returned, then the parent process is killed with\n * the same signal that caused the child to exit.\n */\nexport type Cleanup = (\n code: number | null,\n signal: null | NodeJS.Signals,\n processInfo: {\n watchdogPid?: ChildProcess['pid']\n },\n) =>\n | void\n | undefined\n | number\n | NodeJS.Signals\n | false\n | Promise<void | undefined | number | NodeJS.Signals | false>\n\nexport type FgArgs =\n | [program: string | [cmd: string, ...args: string[]], cleanup?: Cleanup]\n | [\n program: [cmd: string, ...args: string[]],\n opts?: SpawnOptions,\n cleanup?: Cleanup,\n ]\n | [program: string, cleanup?: Cleanup]\n | [program: string, opts?: SpawnOptions, cleanup?: Cleanup]\n | [program: string, args?: string[], cleanup?: Cleanup]\n | [\n program: string,\n args?: string[],\n opts?: SpawnOptions,\n cleanup?: Cleanup,\n ]\n\n/**\n * Normalizes the arguments passed to `foregroundChild`.\n *\n * Exposed for testing.\n *\n * @internal\n */\nexport const normalizeFgArgs = (\n fgArgs: FgArgs,\n): [\n program: string,\n args: string[],\n spawnOpts: SpawnOptions,\n cleanup: Cleanup,\n] => {\n let [program, args = [], spawnOpts = {}, cleanup = () => {}] = fgArgs\n if (typeof args === 'function') {\n cleanup = args\n spawnOpts = {}\n args = []\n } else if (!!args && typeof args === 'object' && !Array.isArray(args)) {\n if (typeof spawnOpts === 'function') cleanup = spawnOpts\n spawnOpts = args\n args = []\n } else if (typeof spawnOpts === 'function') {\n cleanup = spawnOpts\n spawnOpts = {}\n }\n if (Array.isArray(program)) {\n const [pp, ...pa] = program\n program = pp\n args = pa\n }\n return [program, args, { ...spawnOpts }, cleanup]\n}\n\n/**\n * Spawn the specified program as a \"foreground\" process, or at least as\n * close as is possible given node's lack of exec-without-fork.\n *\n * Cleanup method may be used to modify or ignore the result of the child's\n * exit code or signal. If cleanup returns undefined (or a Promise that\n * resolves to undefined), then the parent will exit in the same way that\n * the child did.\n *\n * Return boolean `false` to prevent the parent's exit entirely.\n */\nexport function foregroundChild(\n cmd: string | [cmd: string, ...args: string[]],\n cleanup?: Cleanup,\n): ChildProcessByStdio<null, null, null>\nexport function foregroundChild(\n program: string,\n args?: string[],\n cleanup?: Cleanup,\n): ChildProcessByStdio<null, null, null>\nexport function foregroundChild(\n program: string,\n spawnOpts?: SpawnOptions,\n cleanup?: Cleanup,\n): ChildProcessByStdio<null, null, null>\nexport function foregroundChild(\n program: string,\n args?: string[],\n spawnOpts?: SpawnOptions,\n cleanup?: Cleanup,\n): ChildProcessByStdio<null, null, null>\nexport function foregroundChild(\n ...fgArgs: FgArgs\n): ChildProcessByStdio<null, null, null> {\n const [program, args, spawnOpts, cleanup] = normalizeFgArgs(fgArgs)\n\n spawnOpts.stdio = [0, 1, 2]\n if (process.send) {\n spawnOpts.stdio.push('ipc')\n }\n\n const child = spawn(program, args, spawnOpts) as ChildProcessByStdio<\n null,\n null,\n null\n >\n\n const childHangup = () => {\n try {\n child.kill('SIGHUP')\n\n /* c8 ignore start */\n } catch (_) {\n // SIGHUP is weird on windows\n child.kill('SIGTERM')\n }\n /* c8 ignore stop */\n }\n const removeOnExit = onExit(childHangup)\n\n proxySignals(child)\n const dog = watchdog(child)\n\n let done = false\n child.on('close', async (code, signal) => {\n /* c8 ignore start */\n if (done) return\n /* c8 ignore stop */\n done = true\n const result = cleanup(code, signal, {\n watchdogPid: dog.pid,\n })\n const res = isPromise(result) ? await result : result\n removeOnExit()\n\n if (res === false) return\n else if (typeof res === 'string') {\n signal = res\n code = null\n } else if (typeof res === 'number') {\n code = res\n signal = null\n }\n\n if (signal) {\n // If there is nothing else keeping the event loop alive,\n // then there's a race between a graceful exit and getting\n // the signal to this process. Put this timeout here to\n // make sure we're still alive to get the signal, and thus\n // exit with the intended signal code.\n /* istanbul ignore next */\n setTimeout(() => {}, 2000)\n try {\n process.kill(process.pid, signal)\n /* c8 ignore start */\n } catch (_) {\n process.kill(process.pid, 'SIGTERM')\n }\n /* c8 ignore stop */\n } else {\n process.exit(code || 0)\n }\n })\n\n if (process.send) {\n process.removeAllListeners('message')\n\n child.on('message', (message, sendHandle) => {\n process.send?.(message, sendHandle)\n })\n\n process.on('message', (message, sendHandle) => {\n child.send(\n message as Serializable,\n sendHandle as SendHandle | undefined,\n )\n })\n }\n\n return child\n}\n\nconst isPromise = (o: any): o is Promise<any> =>\n !!o && typeof o === 'object' && typeof o.then === 'function'\n", "/**\n * This is not the set of all possible signals.\n *\n * It IS, however, the set of all signals that trigger\n * an exit on either Linux or BSD systems. Linux is a\n * superset of the signal names supported on BSD, and\n * the unknown signals just fail to register, so we can\n * catch that easily enough.\n *\n * Windows signals are a different set, since there are\n * signals that terminate Windows processes, but don't\n * terminate (or don't even exist) on Posix systems.\n *\n * Don't bother with SIGKILL. It's uncatchable, which\n * means that we can't fire any callbacks anyway.\n *\n * If a user does happen to register a handler on a non-\n * fatal signal like SIGWINCH or something, and then\n * exit, it'll end up firing `process.emit('exit')`, so\n * the handler will be fired anyway.\n *\n * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised\n * artificially, inherently leave the process in a\n * state from which it is not safe to try and enter JS\n * listeners.\n */\nexport const signals: NodeJS.Signals[] = []\nsignals.push('SIGHUP', 'SIGINT', 'SIGTERM')\n\nif (process.platform !== 'win32') {\n signals.push(\n 'SIGALRM',\n 'SIGABRT',\n 'SIGVTALRM',\n 'SIGXCPU',\n 'SIGXFSZ',\n 'SIGUSR2',\n 'SIGTRAP',\n 'SIGSYS',\n 'SIGQUIT',\n 'SIGIOT'\n // should detect profiler and enable/disable accordingly.\n // see #21\n // 'SIGPROF'\n )\n}\n\nif (process.platform === 'linux') {\n signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT')\n}\n", "// Note: since nyc uses this module to output coverage, any lines\n// that are in the direct sync flow of nyc's outputCoverage are\n// ignored, since we can never get coverage for them.\n// grab a reference to node's real process object right away\nimport { signals } from './signals.js'\nexport { signals }\n\n// just a loosened process type so we can do some evil things\ntype ProcessRE = NodeJS.Process & {\n reallyExit: (code?: number | undefined | null) => any\n emit: (ev: string, ...a: any[]) => any\n}\n\nconst processOk = (process: any): process is ProcessRE =>\n !!process &&\n typeof process === 'object' &&\n typeof process.removeListener === 'function' &&\n typeof process.emit === 'function' &&\n typeof process.reallyExit === 'function' &&\n typeof process.listeners === 'function' &&\n typeof process.kill === 'function' &&\n typeof process.pid === 'number' &&\n typeof process.on === 'function'\n\nconst kExitEmitter = Symbol.for('signal-exit emitter')\nconst global: typeof globalThis & { [kExitEmitter]?: Emitter } = globalThis\nconst ObjectDefineProperty = Object.defineProperty.bind(Object)\n\n/**\n * A function that takes an exit code and signal as arguments\n *\n * In the case of signal exits *only*, a return value of true\n * will indicate that the signal is being handled, and we should\n * not synthetically exit with the signal we received. Regardless\n * of the handler return value, the handler is unloaded when an\n * otherwise fatal signal is received, so you get exactly 1 shot\n * at it, unless you add another onExit handler at that point.\n *\n * In the case of numeric code exits, we may already have committed\n * to exiting the process, for example via a fatal exception or\n * unhandled promise rejection, so it is impossible to stop safely.\n */\nexport type Handler = (\n code: number | null | undefined,\n signal: NodeJS.Signals | null\n) => true | void\ntype ExitEvent = 'afterExit' | 'exit'\ntype Emitted = { [k in ExitEvent]: boolean }\ntype Listeners = { [k in ExitEvent]: Handler[] }\n\n// teeny special purpose ee\nclass Emitter {\n emitted: Emitted = {\n afterExit: false,\n exit: false,\n }\n\n listeners: Listeners = {\n afterExit: [],\n exit: [],\n }\n\n count: number = 0\n id: number = Math.random()\n\n constructor() {\n if (global[kExitEmitter]) {\n return global[kExitEmitter]\n }\n ObjectDefineProperty(global, kExitEmitter, {\n value: this,\n writable: false,\n enumerable: false,\n configurable: false,\n })\n }\n\n on(ev: ExitEvent, fn: Handler) {\n this.listeners[ev].push(fn)\n }\n\n removeListener(ev: ExitEvent, fn: Handler) {\n const list = this.listeners[ev]\n const i = list.indexOf(fn)\n /* c8 ignore start */\n if (i === -1) {\n return\n }\n /* c8 ignore stop */\n if (i === 0 && list.length === 1) {\n list.length = 0\n } else {\n list.splice(i, 1)\n }\n }\n\n emit(\n ev: ExitEvent,\n code: number | null | undefined,\n signal: NodeJS.Signals | null\n ): boolean {\n if (this.emitted[ev]) {\n return false\n }\n this.emitted[ev] = true\n let ret: boolean = false\n for (const fn of this.listeners[ev]) {\n ret = fn(code, signal) === true || ret\n }\n if (ev === 'exit') {\n ret = this.emit('afterExit', code, signal) || ret\n }\n return ret\n }\n}\n\nabstract class SignalExitBase {\n abstract onExit(cb: Handler, opts?: { alwaysLast?: boolean }): () => void\n abstract load(): void\n abstract unload(): void\n}\n\nconst signalExitWrap = <T extends SignalExitBase>(handler: T) => {\n return {\n onExit(cb: Handler, opts?: { alwaysLast?: boolean }) {\n return handler.onExit(cb, opts)\n },\n load() {\n return handler.load()\n },\n unload() {\n return handler.unload()\n },\n }\n}\n\nclass SignalExitFallback extends SignalExitBase {\n onExit() {\n return () => {}\n }\n load() {}\n unload() {}\n}\n\nclass SignalExit extends SignalExitBase {\n // \"SIGHUP\" throws an `ENOSYS` error on Windows,\n // so use a supported signal instead\n /* c8 ignore start */\n #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP'\n /* c8 ignore stop */\n #emitter = new Emitter()\n #process: ProcessRE\n #originalProcessEmit: ProcessRE['emit']\n #originalProcessReallyExit: ProcessRE['reallyExit']\n\n #sigListeners: { [k in NodeJS.Signals]?: () => void } = {}\n #loaded: boolean = false\n\n constructor(process: ProcessRE) {\n super()\n this.#process = process\n // { <signal>: <listener fn>, ... }\n this.#sigListeners = {}\n for (const sig of signals) {\n this.#sigListeners[sig] = () => {\n // If there are no other listeners, an exit is coming!\n // Simplest way: remove us and then re-send the signal.\n // We know that this will kill the process, so we can\n // safely emit now.\n const listeners = this.#process.listeners(sig)\n let { count } = this.#emitter\n // This is a workaround for the fact that signal-exit v3 and signal\n // exit v4 are not aware of each other, and each will attempt to let\n // the other handle it, so neither of them do. To correct this, we\n // detect if we're the only handler *except* for previous versions\n // of signal-exit, and increment by the count of listeners it has\n // created.\n /* c8 ignore start */\n const p = process as unknown as {\n __signal_exit_emitter__?: { count: number }\n }\n if (\n typeof p.__signal_exit_emitter__ === 'object' &&\n typeof p.__signal_exit_emitter__.count === 'number'\n ) {\n count += p.__signal_exit_emitter__.count\n }\n /* c8 ignore stop */\n if (listeners.length === count) {\n this.unload()\n const ret = this.#emitter.emit('exit', null, sig)\n /* c8 ignore start */\n const s = sig === 'SIGHUP' ? this.#hupSig : sig\n if (!ret) process.kill(process.pid, s)\n /* c8 ignore stop */\n }\n }\n }\n\n this.#originalProcessReallyExit = process.reallyExit\n this.#originalProcessEmit = process.emit\n }\n\n onExit(cb: Handler, opts?: { alwaysLast?: boolean }) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return () => {}\n }\n /* c8 ignore stop */\n\n if (this.#loaded === false) {\n this.load()\n }\n\n const ev = opts?.alwaysLast ? 'afterExit' : 'exit'\n this.#emitter.on(ev, cb)\n return () => {\n this.#emitter.removeListener(ev, cb)\n if (\n this.#emitter.listeners['exit'].length === 0 &&\n this.#emitter.listeners['afterExit'].length === 0\n ) {\n this.unload()\n }\n }\n }\n\n load() {\n if (this.#loaded) {\n return\n }\n this.#loaded = true\n\n // This is the number of onSignalExit's that are in play.\n // It's important so that we can count the correct number of\n // listeners on signals, and don't wait for the other one to\n // handle it instead of us.\n this.#emitter.count += 1\n\n for (const sig of signals) {\n try {\n const fn = this.#sigListeners[sig]\n if (fn) this.#process.on(sig, fn)\n } catch (_) {}\n }\n\n this.#process.emit = (ev: string, ...a: any[]) => {\n return this.#processEmit(ev, ...a)\n }\n this.#process.reallyExit = (code?: number | null | undefined) => {\n return this.#processReallyExit(code)\n }\n }\n\n unload() {\n if (!this.#loaded) {\n return\n }\n this.#loaded = false\n\n signals.forEach(sig => {\n const listener = this.#sigListeners[sig]\n /* c8 ignore start */\n if (!listener) {\n throw new Error('Listener not defined for signal: ' + sig)\n }\n /* c8 ignore stop */\n try {\n this.#process.removeListener(sig, listener)\n /* c8 ignore start */\n } catch (_) {}\n /* c8 ignore stop */\n })\n this.#process.emit = this.#originalProcessEmit\n this.#process.reallyExit = this.#originalProcessReallyExit\n this.#emitter.count -= 1\n }\n\n #processReallyExit(code?: number | null | undefined) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return 0\n }\n this.#process.exitCode = code || 0\n /* c8 ignore stop */\n\n this.#emitter.emit('exit', this.#process.exitCode, null)\n return this.#originalProcessReallyExit.call(\n this.#process,\n this.#process.exitCode\n )\n }\n\n #processEmit(ev: string, ...args: any[]): any {\n const og = this.#originalProcessEmit\n if (ev === 'exit' && processOk(this.#process)) {\n if (typeof args[0] === 'number') {\n this.#process.exitCode = args[0]\n /* c8 ignore start */\n }\n /* c8 ignore start */\n const ret = og.call(this.#process, ev, ...args)\n /* c8 ignore start */\n this.#emitter.emit('exit', this.#process.exitCode, null)\n /* c8 ignore stop */\n return ret\n } else {\n return og.call(this.#process, ev, ...args)\n }\n }\n}\n\nconst process = globalThis.process\n// wrap so that we call the method on the actual handler, without\n// exporting it directly.\nexport const {\n /**\n * Called when the process is exiting, whether via signal, explicit\n * exit, or running out of stuff to do.\n *\n * If the global process object is not suitable for instrumentation,\n * then this will be a no-op.\n *\n * Returns a function that may be used to unload signal-exit.\n */\n onExit,\n\n /**\n * Load the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\n load,\n\n /**\n * Unload the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\n unload,\n} = signalExitWrap(\n processOk(process) ? new SignalExit(process) : new SignalExitFallback()\n)\n", "import constants from 'node:constants'\nexport const allSignals =\n // this is the full list of signals that Node will let us do anything with\n Object.keys(constants).filter(\n k =>\n k.startsWith('SIG') &&\n // https://github.com/tapjs/signal-exit/issues/21\n k !== 'SIGPROF' &&\n // no sense trying to listen for SIGKILL, it's impossible\n k !== 'SIGKILL',\n ) as NodeJS.Signals[]\n\n// These are some obscure signals that are reported by kill -l\n// on macOS, Linux, or Windows, but which don't have any mapping\n// in Node.js. No sense trying if they're just going to throw\n// every time on every platform.\n//\n// 'SIGEMT',\n// 'SIGLOST',\n// 'SIGPOLL',\n// 'SIGRTMAX',\n// 'SIGRTMAX-1',\n// 'SIGRTMAX-10',\n// 'SIGRTMAX-11',\n// 'SIGRTMAX-12',\n// 'SIGRTMAX-13',\n// 'SIGRTMAX-14',\n// 'SIGRTMAX-15',\n// 'SIGRTMAX-2',\n// 'SIGRTMAX-3',\n// 'SIGRTMAX-4',\n// 'SIGRTMAX-5',\n// 'SIGRTMAX-6',\n// 'SIGRTMAX-7',\n// 'SIGRTMAX-8',\n// 'SIGRTMAX-9',\n// 'SIGRTMIN',\n// 'SIGRTMIN+1',\n// 'SIGRTMIN+10',\n// 'SIGRTMIN+11',\n// 'SIGRTMIN+12',\n// 'SIGRTMIN+13',\n// 'SIGRTMIN+14',\n// 'SIGRTMIN+15',\n// 'SIGRTMIN+16',\n// 'SIGRTMIN+2',\n// 'SIGRTMIN+3',\n// 'SIGRTMIN+4',\n// 'SIGRTMIN+5',\n// 'SIGRTMIN+6',\n// 'SIGRTMIN+7',\n// 'SIGRTMIN+8',\n// 'SIGRTMIN+9',\n// 'SIGSTKFLT',\n// 'SIGUNUSED',\n", "import { type ChildProcess } from 'child_process'\nimport { allSignals } from './all-signals.js'\n\n/**\n * Starts forwarding signals to `child` through `parent`.\n */\nexport const proxySignals = (child: ChildProcess) => {\n const listeners = new Map()\n\n for (const sig of allSignals) {\n const listener = () => {\n // some signals can only be received, not sent\n try {\n child.kill(sig)\n /* c8 ignore start */\n } catch (_) {}\n /* c8 ignore stop */\n }\n try {\n // if it's a signal this system doesn't recognize, skip it\n process.on(sig, listener)\n listeners.set(sig, listener)\n /* c8 ignore start */\n } catch (_) {}\n /* c8 ignore stop */\n }\n\n const unproxy = () => {\n for (const [sig, listener] of listeners) {\n process.removeListener(sig, listener)\n }\n }\n child.on('exit', unproxy)\n return unproxy\n}\n", "// this spawns a child process that listens for SIGHUP when the\n// parent process exits, and after 200ms, sends a SIGKILL to the\n// child, in case it did not terminate.\n\nimport { ChildProcess, spawn } from 'child_process'\n\nconst watchdogCode = String.raw`\nconst pid = parseInt(process.argv[1], 10)\nprocess.title = 'node (foreground-child watchdog pid=' + pid + ')'\nif (!isNaN(pid)) {\n let barked = false\n // keepalive\n const interval = setInterval(() => {}, 60000)\n const bark = () => {\n clearInterval(interval)\n if (barked) return\n barked = true\n process.removeListener('SIGHUP', bark)\n setTimeout(() => {\n try {\n process.kill(pid, 'SIGKILL')\n setTimeout(() => process.exit(), 200)\n } catch (_) {}\n }, 500)\n })\n process.on('SIGHUP', bark)\n}\n`\n\n/**\n * Pass in a ChildProcess, and this will spawn a watchdog process that\n * will make sure it exits if the parent does, thus preventing any\n * dangling detached zombie processes.\n *\n * If the child ends before the parent, then the watchdog will terminate.\n */\nexport const watchdog = (child: ChildProcess) => {\n let dogExited = false\n const dog = spawn(\n process.execPath,\n ['-e', watchdogCode, String(child.pid)],\n {\n stdio: 'ignore',\n },\n )\n dog.on('exit', () => (dogExited = true))\n child.on('exit', () => {\n if (!dogExited) dog.kill('SIGKILL')\n })\n return dog\n}\n", "import { error } from '@vltpkg/error-cause'\nimport { PackageJson } from '@vltpkg/package-json'\nimport {\n promiseSpawn,\n PromiseSpawnOptions,\n type SpawnResultNoStdio,\n type SpawnResultStdioStrings,\n} from '@vltpkg/promise-spawn'\nimport { Manifest } from '@vltpkg/types'\nimport { foregroundChild } from 'foreground-child'\nimport { proxySignals } from 'foreground-child/proxy-signals'\nimport { statSync } from 'node:fs'\nimport { delimiter, resolve } from 'node:path'\nimport { walkUp } from 'walk-up-path'\n\n/** map of which node_modules/.bin folders exist */\nconst dotBins = new Map<string, boolean>()\n\n/** Check if a directory exists, and cache result */\nconst dirExists = (p: string) => {\n const cached = dotBins.get(p)\n if (cached !== undefined) return cached\n try {\n const isDir = statSync(p).isDirectory()\n dotBins.set(p, isDir)\n return isDir\n } catch {\n dotBins.set(p, false)\n return false\n }\n}\n\n/**\n * Add all exsting `node_modules/.bin` folders to the PATH that\n * exist between the cwd and the projectRoot, so dependency bins\n * are found, with closer paths higher priority.\n */\nconst addPaths = (\n projectRoot: string,\n cwd: string,\n env: NodeJS.ProcessEnv,\n): NodeJS.ProcessEnv => {\n const { PATH = '' } = env\n const paths = new Set<string>()\n for (const p of walkUp(cwd)) {\n const dotBin = resolve(p, 'node_modules/.bin')\n if (dirExists(dotBin)) paths.add(dotBin)\n if (p === projectRoot) break\n }\n for (const p of PATH.split(delimiter)) {\n /* c8 ignore next - pretty rare to have an empty entry */\n if (p) paths.add(p)\n }\n env.PATH = [...paths].join(delimiter)\n return env\n}\n\n/** options shared by run() and exec() */\nexport type SharedOptions = PromiseSpawnOptions & {\n /** additional arguments to pass to the command */\n args?: string[]\n /** the root of the project, which we don't walk up past */\n projectRoot: string\n\n /** the directory where the package.json lives and the script runs */\n cwd: string\n /**\n * environment variables to set. `process.env` is always included,\n * to omit fields, set them explicitly to undefined.\n *\n * vlt will add some of its own, as well:\n * - npm_lifecycle_event: the event name\n * - npm_lifecycle_script: the command in package.json#scripts\n * - npm_package_json: path to the package.json file\n * - VLT_* envs for all vlt configuration values that are set\n */\n env?: NodeJS.ProcessEnv\n /**\n * the shell to run the script in. If not set, then the default\n * platform-specific shell will be used.\n */\n 'script-shell'?: boolean | string\n}\n\n/**\n * Options for run() and runFG()\n */\nexport type RunOptions = SharedOptions & {\n /** the name of the thing in package.json#scripts */\n arg0: string\n /**\n * pass in a @vltpkg/package-json.PackageJson instance, and\n * it'll be used for reading the package.json file. Optional,\n * may improve performance somewhat.\n */\n packageJson?: PackageJson\n\n /**\n * Pass in a manifest to avoid having to read it at all\n */\n manifest?: Manifest\n\n /**\n * if the script is not defined in package.json#scripts, just ignore it and\n * treat as success. Otherwise, treat as an error. Default false.\n */\n ignoreMissing?: boolean\n\n /**\n * skip the pre/post commands, just run the one specified.\n * This can be used to run JUST the specified script, without any\n * pre/post commands.\n */\n ignorePrePost?: boolean\n}\n\n/**\n * Options for exec() and execFG()\n */\nexport type ExecOptions = SharedOptions & {\n /** the command to execute */\n arg0: string\n}\n\n/**\n * Options for runExec() and runExecFG()\n */\nexport type RunExecOptions = SharedOptions & {\n /**\n * Either the command to be executed, or the event to be run\n */\n arg0: string\n /**\n * pass in a @vltpkg/package-json.PackageJson instance, and\n * it'll be used for reading the package.json file. Optional,\n * may improve performance somewhat.\n */\n packageJson?: PackageJson\n}\n\n/**\n * Run a package.json#scripts event in the background\n */\nexport const run = async (options: RunOptions): Promise<RunResult> =>\n runImpl(options, exec, '')\n\n/**\n * Run a package.json#scripts event in the foreground\n */\nexport const runFG = async (\n options: RunOptions,\n): Promise<RunFGResult> => runImpl(options, execFG, null)\n\n/** Return type of {@link run} */\nexport type RunResult = SpawnResultStdioStrings & {\n pre?: SpawnResultStdioStrings\n post?: SpawnResultStdioStrings\n}\n\n/** Return type of {@link runFG} */\nexport type RunFGResult = SpawnResultNoStdio & {\n pre?: SpawnResultNoStdio\n post?: SpawnResultNoStdio\n}\n\nexport const isRunResult = (v: unknown): v is RunResult =>\n !!v &&\n typeof v === 'object' &&\n !Array.isArray(v) &&\n 'stdout' in v &&\n 'stderr' in v &&\n 'status' in v &&\n 'signal' in v\n\n/**\n * Return type of {@link run} or {@link runFG}, as determined by their base\n * type\n *\n * @internal\n */\nexport type RunImplResult<\n R extends SpawnResultNoStdio | SpawnResultStdioStrings,\n> = R & { pre?: R; post?: R }\n\n/**\n * Internal implementation of run() and runFG(), since they're mostly identical\n */\nconst runImpl = async <\n R extends SpawnResultNoStdio | SpawnResultStdioStrings,\n>(\n options: RunOptions,\n execImpl: (options: ExecOptions) => Promise<R>,\n empty: R['stdout'],\n): Promise<RunImplResult<R>> => {\n const {\n arg0,\n packageJson = new PackageJson(),\n ignoreMissing = false,\n manifest,\n ...execArgs\n } = options\n const pjPath = resolve(options.cwd, 'package.json')\n const pj = manifest ?? packageJson.read(options.cwd)\n const { scripts } = pj\n const command = scripts?.[arg0]\n if (!command) {\n if (ignoreMissing) {\n return {\n command: '',\n /* c8 ignore next */\n args: execArgs.args ?? [],\n cwd: options.cwd,\n status: 0,\n signal: null,\n stdout: empty,\n stderr: empty,\n // `as` to workaround \"could be instantiated with arbitrary type\".\n // it's private and used in 2 places, we know that it isn't.\n } as R\n }\n throw error('Script not defined in package.json', {\n name: arg0,\n cwd: options.cwd,\n args: options.args,\n path: pjPath,\n manifest: pj,\n })\n }\n\n const precommand = !options.ignorePrePost && scripts[`pre${arg0}`]\n const pre =\n precommand ?\n await execImpl({\n arg0: precommand,\n ...execArgs,\n args: [],\n env: {\n ...execArgs.env,\n npm_package_json: pjPath,\n npm_lifecycle_event: `pre${arg0}`,\n npm_lifecycle_script: precommand,\n },\n })\n : undefined\n if (pre && (pre.status || pre.signal)) {\n return pre as RunImplResult<R>\n }\n const result: RunImplResult<R> = await execImpl({\n arg0: command,\n ...execArgs,\n env: {\n ...execArgs.env,\n npm_package_json: pjPath,\n npm_lifecycle_event: arg0,\n npm_lifecycle_script: command,\n },\n })\n result.pre = pre\n if (result.signal || result.status) {\n return result\n }\n\n const postcommand = !options.ignorePrePost && scripts[`post${arg0}`]\n if (!postcommand) return result\n\n const post = await execImpl({\n arg0: postcommand,\n ...execArgs,\n args: [],\n env: {\n ...execArgs.env,\n npm_package_json: pjPath,\n npm_lifecycle_event: `post${arg0}`,\n npm_lifecycle_script: postcommand,\n },\n })\n\n if (post.status || post.signal) {\n const { status, signal } = post\n return Object.assign(result, { post, status, signal })\n }\n result.post = post\n return result\n}\n\n/**\n * Execute an arbitrary command in the background\n */\nexport const exec = async (\n options: ExecOptions,\n): Promise<SpawnResultStdioStrings> => {\n const {\n arg0,\n args = [],\n cwd,\n env = {},\n projectRoot,\n 'script-shell': shell = true,\n ...spawnOptions\n } = options\n\n const p = promiseSpawn(arg0, args, {\n ...spawnOptions,\n shell,\n stdio: 'pipe',\n stdioString: true,\n cwd,\n env: addPaths(projectRoot, cwd, {\n ...process.env,\n ...env,\n }),\n windowsHide: true,\n })\n proxySignals(p.process)\n return await p\n}\n\n/**\n * Execute an arbitrary command in the foreground\n */\nexport const execFG = async (\n options: ExecOptions,\n): Promise<SpawnResultNoStdio> => {\n const {\n arg0,\n args = [],\n cwd,\n projectRoot,\n env = {},\n 'script-shell': shell = true,\n ...spawnOptions\n } = options\n\n return new Promise<SpawnResultNoStdio>(res => {\n foregroundChild(\n arg0,\n args,\n {\n ...spawnOptions,\n shell,\n cwd,\n env: addPaths(projectRoot, cwd, {\n ...process.env,\n ...env,\n }),\n },\n (status, signal) => {\n res({\n command: arg0,\n args,\n cwd,\n stdout: null,\n stderr: null,\n status,\n signal,\n })\n return false\n },\n )\n })\n}\n\nconst runExecImpl = async <\n R extends SpawnResultNoStdio | SpawnResultStdioStrings,\n>(\n options: RunExecOptions,\n runImpl: (options: RunOptions) => Promise<RunImplResult<R>>,\n execImpl: (options: ExecOptions) => Promise<R>,\n): Promise<R | RunImplResult<R>> => {\n const { arg0, packageJson = new PackageJson(), ...args } = options\n const pj = packageJson.read(options.cwd)\n const { scripts } = pj\n const command = scripts?.[arg0]\n if (command) {\n return runImpl({ ...args, packageJson, arg0 })\n } else {\n return execImpl({ ...args, arg0 })\n }\n}\n\n/**\n * If the arg0 is a defined package.json script, then run(), otherwise exec()\n */\nexport const runExec = async (\n options: RunExecOptions,\n): Promise<RunResult | SpawnResultStdioStrings> =>\n runExecImpl<SpawnResultStdioStrings>(options, run, exec)\n\n/**\n * If the arg0 is a defined package.json script, then runFG(), otherwise\n * execFG()\n */\nexport const runExecFG = async (\n options: RunExecOptions,\n): Promise<RunFGResult | SpawnResultNoStdio> =>\n runExecImpl<SpawnResultNoStdio>(options, runFG, execFG)\n", "import { dirname, resolve } from 'path'\nexport const walkUp = function* (path: string) {\n for (path = resolve(path); path;) {\n yield path\n const pp = dirname(path)\n if (pp === path) {\n break\n } else {\n path = pp\n }\n }\n}\n", "/** utility types to turn a null/undefined/void return into string */\nexport type NullToString<T> = VoidReplace<T>\n\n/** Utility type to replace null/undefined with a given type */\nexport type NullReplace<T, R = string> =\n T extends NonNullable<T> ? T : NonNullable<T> | R\n\n/** Utility type to replace void with a given type */\nexport type VoidReplace<T, R = string> =\n undefined extends T ? NullReplace<Exclude<T, void>, R> | R\n : NullReplace<T, R>\n\n/**\n * Split a string by a string delimiter, optionally limiting the number\n * of parts parsed, and/or transforming the string parts into some other\n * type of value.\n *\n * Pass `-1` as the `limit` parameter to get all parts (useful if an `onPart`\n * method is provided)\n *\n * If an `onPart` method is provided, and returns `undefined`, then the\n * original string part is included in the result set.\n *\n * ```ts\n * import { fastSplit } from '@vltpkg/fast-split'\n *\n * // say we want to split a string on '.' characters\n * const str = getSomeStringSomehow()\n *\n * // basic usage, just like str.split('.'), gives us an array\n * const parts = fastSplit(str, '.')\n *\n * // get just the first two parts, leave the rest intact\n * // Note: unlike str.split('.', 3), the 'rest' here will\n * // include the entire rest of the string.\n * // If you do `str.split('.', 3)`, then the last item in the\n * // returned array is truncated at the next delimiter\n * const [first, second, rest] = fastSplit(str, '.', 3)\n *\n * // If you need to transform it, say if it's an IPv4 address\n * // that you want to turn into numbers, you can do that by\n * // providing the onPart method, which will be slightly faster\n * // than getting an array and subsequently looping over it\n * // pass `-1` as the limit to give us all parts\n * const nums = fastSplit(str, '.', -1, (part, parts, index) => Number(s))\n * ```\n */\nexport function fastSplit<T = string>(\n str: string,\n delim: string,\n limit: number,\n onPart: (part: string, parts: NullToString<T>[], i: number) => T,\n): NullToString<T>[]\nexport function fastSplit(\n str: string,\n delim: string,\n limit?: number,\n): string[]\nexport function fastSplit<T = string>(\n str: string,\n delim: string,\n limit = -1,\n onPart?: (\n part: string,\n parts: NullToString<T>[],\n i: number,\n ) => T | undefined,\n): NullToString<T>[] {\n let i = 0\n let p = 0\n const l = delim.length\n const parts: NullToString<T>[] = []\n while (i !== -1) {\n i = str.indexOf(delim, p)\n const part =\n i === -1 || parts.length === limit - 1 ?\n str.substring(p)\n : str.substring(p, i)\n parts.push((onPart?.(part, parts, i) ?? part) as NullToString<T>)\n if (parts.length === limit) {\n // push the rest into the last part\n return parts\n }\n p = i + l\n }\n return parts\n}\n", "import { syntaxError, typeError } from '@vltpkg/error-cause'\nimport { fastSplit } from '@vltpkg/fast-split'\nimport { type Range } from './range.js'\n\nconst maybeNumber = (s: string): number | string => {\n if (!/^[0-9]+$/.test(s)) return s\n const n = Number(s)\n return n <= Number.MAX_SAFE_INTEGER ? n : s\n}\n\nconst safeNumber = (\n s: string,\n version: string,\n field: string,\n): number => {\n const n = Number(s)\n if (n > Number.MAX_SAFE_INTEGER) {\n throw invalidVersion(\n version,\n `invalid ${field}, must be <= ${Number.MAX_SAFE_INTEGER}`,\n )\n }\n return n\n}\n\nconst re = {\n prefix: /^[ v=]+/,\n main: /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)/,\n prerelease: /-([0-9a-zA-Z_.-]+)(?:$|\\+)/,\n build: /\\+([0-9a-zA-Z_.-]+)$/,\n full: /^[ v=]*(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-([0-9a-zA-Z_.-]+))?(?:\\+([0-9a-zA-Z_.-]+))?$/,\n} as const\n\nconst invalidVersion = (\n version: string,\n message: string,\n): SyntaxError => {\n const er = syntaxError(\n `invalid version: ${message}`,\n { version },\n Version,\n )\n return er\n}\n\n/**\n * Types of incrementing supported by {@link Version#inc}\n */\nexport type IncrementType =\n | 'major'\n | 'minor'\n | 'patch'\n | 'pre'\n | 'premajor'\n | 'preminor'\n | 'prepatch'\n | 'prerelease'\n\n/**\n * A parsed object representation of a SemVer version string\n *\n * This is a bit less forgiving than node-semver, in that prerelease versions\n * MUST start with '-'. Otherwise, the allowed syntax is identical.\n */\nexport class Version {\n /** raw string provided to create this Version */\n raw: string\n\n /** major version number */\n major: number\n /** minor version number */\n minor: number\n /** patch version number */\n patch: number\n /**\n * List of `'.'`-separated strings and numbers indicating that this\n * version is a prerelease.\n *\n * This is undefined if the version does not have a prerelease section.\n */\n prerelease?: (number | string)[]\n /**\n * List of `'.'`-separated strings in the `build` section.\n *\n * This is undefined if the version does not have a build.\n */\n build?: string[]\n\n /** Canonical strict form of this version */\n toString() {\n return `${this.major}.${this.minor}.${this.patch}${\n this.prerelease ? '-' + this.prerelease.join('.') : ''\n }${this.build ? '+' + this.build.join('.') : ''}`\n }\n\n /** Generate a `Version` object from a SemVer string */\n static parse(version: string) {\n version = version.replace(re.prefix, '').trim()\n if (version.length > 256) {\n throw invalidVersion(\n version,\n 'must be less than 256 characters',\n )\n }\n\n const parsed = version.match(re.full)\n if (!parsed) {\n const main = version.match(re.main)\n if (!main) {\n throw invalidVersion(\n version,\n 'no Major.minor.patch tuple present',\n )\n } else {\n throw invalidVersion(\n version,\n 'invalid build or patch section',\n )\n }\n }\n const [_, major_, minor_, patch_, prerelease, build] = parsed as [\n string,\n string,\n string,\n string,\n string | undefined,\n string | undefined,\n ]\n const major = safeNumber(major_, version, 'major')\n const minor = safeNumber(minor_, version, 'minor')\n const patch = safeNumber(patch_, version, 'patch')\n\n return new Version(\n version,\n major,\n minor,\n patch,\n prerelease,\n build,\n )\n }\n\n constructor(\n version: string,\n major: number,\n minor: number,\n patch: number,\n prerelease: string | undefined,\n build: string | undefined,\n ) {\n this.raw = version\n this.major = major\n this.minor = minor\n this.patch = patch\n\n // has prerelease and/or build\n if (prerelease) {\n this.prerelease = fastSplit(prerelease, '.', -1, c => {\n if (!c) {\n throw invalidVersion(\n version,\n 'invalid prerelease, empty identifiers not allowed',\n )\n }\n return maybeNumber(c)\n })\n }\n if (build) {\n this.build = fastSplit(build, '.', -1, c => {\n if (!c) {\n throw invalidVersion(\n version,\n 'invalid build metadata, empty identifiers not allowed',\n )\n }\n })\n }\n }\n\n /**\n * Return 1 if this is > the provided version, -1 if we're less, or 0 if\n * they are equal.\n *\n * No special handling for prerelease versions, this is just a precedence\n * comparison.\n *\n * This can be used to sort a list of versions by precedence:\n *\n * ```ts\n * const versions: Version[] = getVersionsSomehow()\n * const sorted = versions.sort((a, b) => a.compare(b))\n * ```\n */\n compare(v: Version): -1 | 0 | 1 {\n if (this.major > v.major) return 1\n if (this.major < v.major) return -1\n if (this.minor > v.minor) return 1\n if (this.minor < v.minor) return -1\n if (this.patch > v.patch) return 1\n if (this.patch < v.patch) return -1\n // main tuple is equal now\n // if the version has no pr, we're definitely less than or equal to\n if (!v.prerelease?.length)\n return !this.prerelease?.length ? 0 : -1\n // v has a pr. if we don't, we're > it\n if (!this.prerelease?.length) return 1\n // we both have prereleases\n const len = Math.max(this.prerelease.length, v.prerelease.length)\n const me = this.prerelease\n const thee = v.prerelease\n for (let i = 0; i < len; i++) {\n const m = me[i]\n const t = thee[i]\n if (m === t) continue\n // having a field is > not having it\n if (t === undefined) return 1\n if (m === undefined) return -1\n // string parts are higher precedence than\n if (typeof m !== typeof t) {\n return typeof m === 'string' ? 1 : -1\n }\n return m > t ? 1 : -1\n }\n return 0\n }\n\n /**\n * The inverse of compare, for sorting version lists in reverse order\n */\n rcompare(v: Version) {\n return -1 * this.compare(v)\n }\n\n /** true if this version is > the argument */\n greaterThan(v: Version) {\n return this.compare(v) === 1\n }\n\n /** true if this version is >= the argument */\n greaterThanEqual(v: Version) {\n return this.compare(v) > -1\n }\n\n /** true if this version is < the argument */\n lessThan(v: Version) {\n return this.compare(v) === -1\n }\n\n /** true if this version is <= the argument */\n lessThanEqual(v: Version) {\n return this.compare(v) < 1\n }\n\n /** true if these two versions have equal SemVer precedence */\n equals(v: Version) {\n return this.compare(v) === 0\n }\n\n /** just compare the M.m.p parts of the version */\n tupleEquals(v: Version) {\n return (\n this.major === v.major &&\n this.minor === v.minor &&\n this.patch === v.patch\n )\n }\n\n /** true if this version satisfies the range */\n satisfies(r: Range) {\n return r.test(this)\n }\n\n /**\n * Increment the version in place, in the manner specified.\n *\n * See {@link index.inc} for full description.\n */\n inc(part: IncrementType, prereleaseIdentifier?: string) {\n switch (part) {\n case 'premajor':\n this.prerelease = undefined\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', prereleaseIdentifier)\n break\n\n case 'preminor':\n this.prerelease = undefined\n this.patch = 0\n this.minor++\n this.inc('pre', prereleaseIdentifier)\n break\n\n case 'prepatch':\n this.prerelease = undefined\n this.inc('patch')\n this.inc('pre', prereleaseIdentifier)\n break\n\n case 'prerelease':\n if (!this.prerelease?.length)\n this.inc('patch', prereleaseIdentifier)\n this.inc('pre', prereleaseIdentifier)\n break\n\n case 'pre': {\n // this is a bit different than node-semver's logic, but simpler\n // always do zero-based incrementing, and either bump the existing\n // numeric pr value, or add a `.0` after the identifier.\n if (!prereleaseIdentifier) {\n if (!this.prerelease?.length) {\n this.prerelease = [0]\n break\n }\n const last = this.prerelease[this.prerelease.length - 1]\n if (typeof last === 'number') {\n this.prerelease[this.prerelease.length - 1] = last + 1\n } else {\n this.prerelease.push(0)\n }\n break\n }\n if (!this.prerelease?.length) {\n this.prerelease = [prereleaseIdentifier]\n break\n }\n const i = this.prerelease.indexOf(\n maybeNumber(prereleaseIdentifier),\n )\n if (i === -1) {\n this.prerelease = [prereleaseIdentifier]\n break\n }\n const baseValue = this.prerelease[i + 1]\n if (typeof baseValue === 'number') {\n this.prerelease[i + 1] = baseValue + 1\n break\n }\n if (i === this.prerelease.length - 1) {\n this.prerelease.push(0)\n break\n }\n this.prerelease.splice(i + 1, 0, 0)\n break\n }\n\n case 'major':\n if (!this.prerelease?.length || this.minor || this.patch)\n this.major++\n this.prerelease = undefined\n this.patch = 0\n this.minor = 0\n break\n\n case 'minor':\n if (!this.prerelease?.length || this.patch) this.minor++\n this.prerelease = undefined\n this.patch = 0\n break\n\n case 'patch':\n if (!this.prerelease?.length) this.patch++\n this.prerelease = undefined\n break\n\n default:\n throw typeError(\n 'Invalid increment identifier',\n {\n version: this,\n found: part,\n validOptions: [\n 'major',\n 'minor',\n 'patch',\n 'premajor',\n 'preminor',\n 'prepatch',\n 'prerelease',\n 'pre',\n ],\n },\n this.inc,\n )\n }\n\n this.raw = this.toString()\n return this\n }\n}\n", "// TODO: it might be faster to not have Version objects in the\n// comparator tuples, and instead just keep the parsed number arrays?\nimport { syntaxError } from '@vltpkg/error-cause'\nimport { fastSplit } from '@vltpkg/fast-split'\nimport { Version } from './version.js'\n\n/** all comparators are expressed in terms of these operators */\nexport type SimpleOperator = '' | '<' | '<=' | '>' | '>='\n/** operators that are expanded to simpler forms */\nexport type ComplexOperator = '^' | '~' | '~>'\n\nconst isOperator = (\n o?: string,\n): o is ComplexOperator | SimpleOperator =>\n !!o &&\n (o === '>' ||\n o === '<' ||\n o === '>=' ||\n o === '<=' ||\n o === '' ||\n o === '~' ||\n o === '^' ||\n o === '~>')\n\n/** comparator expressed as a [operator,version] tuple */\nexport type OVTuple = [SimpleOperator, Version]\n\nconst preJunk = new Set('=v \\t')\n\nconst invalidComp = (c: string, message: string): SyntaxError =>\n syntaxError(\n `invalid comparator: '${c}' ${message}`,\n { found: c },\n Comparator,\n )\n\nconst assertNumber = (value: string, c: string, field: string) => {\n const n = Number(value)\n if (n !== n) {\n throw invalidComp(\n c,\n `${field} must be numeric or 'x', got: '${value}'`,\n )\n }\n return n\n}\n\nconst assertVersion = (v: string, comp: string) => {\n if (!v) {\n throw invalidComp(comp, 'no value provided for operator')\n }\n}\n\nconst assertMissing = (\n value: string | undefined,\n c: string,\n field: string,\n) => {\n if (value && !isX(value)) {\n throw invalidComp(\n c,\n `cannot omit '${field}' and include subsequent fields`,\n )\n }\n}\n\nconst MAJOR = 0\nconst MINOR = 1\nconst PATCH = 2\n\nconst isX = (c?: string) => !c || c === 'X' || c === 'x' || c === '*'\n\n/**\n * The result of parsing a version value that might be either a full\n * version like `1.2.3` or an X-Range like `1.2.x`\n */\nexport type ParsedXRange =\n | ParsedXMajor\n | ParsedXMinor\n | ParsedXPatch\n | ParsedXVersion\n/**\n * a {@link ParsedXRange} that is just a `*`\n */\nexport type ParsedXMajor = []\n/**\n * a {@link ParsedXRange} that is just a major version\n */\nexport type ParsedXMinor = [number]\n/**\n * a {@link ParsedXRange} that is just a major and minor version\n */\nexport type ParsedXPatch = [number, number]\n/**\n * a {@link ParsedXRange} that is a full version\n */\nexport type ParsedXVersion = [\n M: number,\n m: number,\n p: number,\n pr?: string | undefined,\n b?: string | undefined,\n]\n\nconst isFullVersion = (\n parsed: ParsedXRange,\n): parsed is ParsedXVersion => undefined !== parsed[PATCH]\nconst isXPatch = (parsed: ParsedXRange): parsed is ParsedXPatch =>\n undefined !== parsed[MINOR] && undefined === parsed[PATCH]\nconst isXMinor = (parsed: ParsedXRange): parsed is ParsedXMinor =>\n undefined !== parsed[MAJOR] && undefined === parsed[MINOR]\nconst isXMajor = (parsed: ParsedXRange): parsed is ParsedXMajor =>\n undefined === parsed[MAJOR]\n\n/**\n * Class used to parse the `||` separated portions\n * of a range, and evaluate versions against it.\n *\n * This does most of the heavy lifting of range testing, and provides\n * little affordance for improperly formatted strings. It should be\n * considered an internal class, and usually not accessed directly.\n *\n * @internal\n */\nexport class Comparator {\n /**\n * does this range include prereleases, even when they do not\n * match the tuple in the comparator?\n */\n includePrerelease: boolean\n /** raw string used to create this comparator */\n raw: string\n /** tokens extracted from the raw string input */\n tokens: string[]\n /**\n * Either the `any` comparator, the `none` comparator, or an operator\n * and a {@link ParsedXRange}\n */\n tuples: (Comparator | OVTuple)[] = []\n /** true if this comparator can not match anything */\n isNone = false\n /**\n * true if this comparator is a `'*'` type of range.\n *\n * Note that it still will not match versions with a prerelease value,\n * unless the tuple in the version matches the tuple provided to the\n * comparator, and the comparator version also has a prerelease value,\n * unless `includePrerelease` is set.\n */\n isAny = false\n\n /** the canonical strict simplified parsed form of this constructor */\n toString() {\n return (\n this.isNone ? '<0.0.0-0'\n : this.isAny ? '*'\n : /* c8 ignore next */\n this.tuples.map(c => (isAny(c) ? '*' : c.join(''))).join(' ')\n )\n }\n\n constructor(comp: string, includePrerelease = false) {\n this.includePrerelease = includePrerelease\n comp = comp.trim()\n this.raw = comp\n let hyphen = false\n const rawComps = fastSplit(comp, ' ', -1, (part, parts, i) => {\n if (part === '-') {\n if (hyphen) {\n throw invalidComp(\n comp,\n 'multiple hyphen ranges not allowed',\n )\n }\n if (parts.length !== 1 || i === -1) {\n throw invalidComp(\n comp,\n 'hyphen must be between two versions',\n )\n }\n hyphen = true\n } else if (hyphen && parts.length !== 2) {\n throw invalidComp(comp, 'hyphen range must be alone')\n }\n })\n\n // remove excess spaces, `> 1 2` => `>1 2`\n const comps: string[] = []\n let followingOperator = false\n for (const c of rawComps) {\n if (c === '') continue\n if (!followingOperator) {\n followingOperator = isOperator(c)\n comps.push(c)\n continue\n }\n // we know this is not undefined since followingOperator guards that\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n comps[comps.length - 1]! += c\n followingOperator = false\n }\n\n // TS mistakenly thinks hyphen is always false here\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (hyphen) {\n const [min, _, max] = comps\n /* c8 ignore start - defense in depth for TS, already guaranteed */\n if (!min || !max) {\n throw invalidComp(comp, 'hyphen must be between two versions')\n }\n /* c8 ignore stop */\n this.#parseHyphenRange(min, max)\n } else if (\n !comps.length ||\n (comps.length === 1 && isX(comps[0]))\n ) {\n this.tuples.push(this.#getComparatorAny())\n } else {\n for (const c of comps) {\n this.#parse(c)\n if (this.isNone) break\n }\n }\n this.tokens = comps\n this.isAny = true\n for (const c of this.tuples) {\n if (Array.isArray(c) || !c.isAny) {\n this.isAny = false\n break\n }\n }\n }\n\n // inclusive min\n #xInclusiveMin(raw: string): Comparator | OVTuple {\n const z = this.includePrerelease ? '0' : undefined\n const [M, m = 0, p = 0, pr = z, build] = this.#parseX(raw)\n return M === undefined ?\n this.#getComparatorAny()\n : ['>=', new Version(raw, M, m, p, pr, build)]\n }\n\n // exclusive min.\n // Note, if not a full version, then\n #xExclusiveMin(raw: string): Comparator | OVTuple {\n const parsed = this.#parseX(raw)\n if (isFullVersion(parsed)) {\n return ['>', new Version(raw, ...parsed)]\n }\n const z = this.includePrerelease ? '0' : undefined\n if (isXPatch(parsed)) {\n // >1.2 => >=1.3.0\n return [\n '>=',\n new Version(\n raw,\n parsed[MAJOR],\n parsed[MINOR] + 1,\n 0,\n z,\n undefined,\n ),\n ]\n }\n if (isXMinor(parsed)) {\n // >1 => >=2.0.0\n return [\n '>=',\n new Version(raw, parsed[MAJOR] + 1, 0, 0, z, undefined),\n ]\n }\n this.isNone = true\n this.tuples.length = 0\n return comparatorNone\n }\n\n #xInclusiveMax(raw: string): Comparator | OVTuple {\n const parsed = this.#parseX(raw)\n if (isFullVersion(parsed)) {\n return ['<=', new Version(raw, ...parsed)]\n }\n if (isXPatch(parsed)) {\n return [\n '<',\n new Version(\n raw,\n parsed[MAJOR],\n parsed[MINOR] + 1,\n 0,\n '0',\n undefined,\n ),\n ]\n }\n if (isXMinor(parsed)) {\n return [\n '<',\n new Version(raw, parsed[MAJOR] + 1, 0, 0, '0', undefined),\n ]\n }\n return this.#getComparatorAny()\n }\n\n #xExclusiveMax(raw: string): Comparator | OVTuple {\n const z = this.includePrerelease ? '0' : undefined\n const [M = 0, m = 0, p = 0, pr = z, build] = this.#parseX(raw)\n if (M === 0 && m === 0 && p === 0 && pr === '0') {\n this.isNone = true\n this.tuples.length = 0\n return comparatorNone\n }\n return ['<', new Version(raw, M, m, p, pr, build)]\n }\n\n // pull the relevant values out of an X-range or version\n // return the fields for creating a Version object.\n // only call once operator is stripped off\n #parseX(raw: string): ParsedXRange {\n let [M, m, p] = fastSplit(raw, '.', 3)\n let prune = 0\n while (M && preJunk.has(M.charAt(prune))) prune++\n if (M !== undefined && prune !== 0) M = M.substring(prune)\n // the `|| !M` is so TS knows we've handled undefined\n if (isX(M) || !M) {\n assertMissing(m, raw, 'major')\n assertMissing(p, raw, 'major')\n if (m === '' || p === '') {\n throw invalidComp(raw, `(Did you mean '*'?)`)\n }\n return []\n }\n if (isX(m) || !m) {\n assertMissing(p, raw, 'major')\n if (m === '' || p === '') {\n throw invalidComp(raw, `(Did you mean '${M}'?)`)\n }\n return [assertNumber(M, raw, 'major')]\n }\n if (isX(p) || !p) {\n if (p === '') {\n throw invalidComp(raw, `(Did you mean '${M}.${m}'?)`)\n }\n return [\n assertNumber(M, raw, 'major'),\n assertNumber(m, raw, 'minor'),\n ]\n }\n const hy = p.indexOf('-')\n const pl = p.indexOf('+')\n if (pl === -1 && hy === -1) {\n return [\n assertNumber(M, raw, 'major'),\n assertNumber(m, raw, 'minor'),\n assertNumber(p, raw, 'patch'),\n ]\n }\n if (hy === -1) {\n // build, no prerelease\n const [patch, build] = fastSplit(p, '+', 2)\n if (!patch) {\n throw invalidComp(raw, 'cannot specify build without patch')\n }\n if (!build) {\n throw invalidComp(raw, `encountered '+', but no build value`)\n }\n return [\n assertNumber(M, raw, 'major'),\n assertNumber(m, raw, 'minor'),\n assertNumber(patch, raw, 'patch'),\n undefined,\n build,\n ]\n }\n if (pl === -1) {\n // prerelease, no build\n const [patch, pr] = fastSplit(p, '-', 2)\n if (!patch) {\n throw invalidComp(\n raw,\n 'cannot specify prerelease without patch',\n )\n }\n if (!pr) {\n throw invalidComp(\n raw,\n `encountered '-', but no prerelease value`,\n )\n }\n return [\n assertNumber(M, raw, 'major'),\n assertNumber(m, raw, 'minor'),\n assertNumber(patch, raw, 'patch'),\n pr,\n ]\n }\n // both prerelease and build\n const [patch, trailers = ''] = fastSplit(p, '-', 2)\n if (!patch) {\n throw invalidComp(\n raw,\n 'cannot specify prerelease without patch',\n )\n }\n const [pr, build] = fastSplit(trailers, '+', 2)\n if (!pr) {\n throw invalidComp(\n raw,\n `encountered '-', but no prerelease value`,\n )\n }\n if (!build) {\n throw invalidComp(raw, `encountered '+', but no build value`)\n }\n return [\n assertNumber(M, raw, 'major'),\n assertNumber(m, raw, 'minor'),\n assertNumber(patch, raw, 'patch'),\n pr,\n build,\n ]\n }\n\n #parseHyphenRange(min: string, max: string) {\n const minv = this.#xInclusiveMin(min)\n const maxv = this.#xInclusiveMax(max)\n const minAny = isAny(minv)\n const maxAny = isAny(maxv)\n return (\n minAny && maxAny ? this.tuples.push(this.#getComparatorAny())\n : maxAny ? this.tuples.push(minv)\n : minAny ? this.tuples.push(maxv)\n : this.tuples.push(minv, maxv)\n )\n }\n\n #parse(comp: string) {\n const first = comp.charAt(0)\n const first2 = comp.substring(0, 2)\n const v1 = comp.substring(1)\n const v2 = comp.substring(2)\n switch (first2) {\n case '~>':\n assertVersion(v2, comp)\n return this.#parseTilde(v2)\n case '>=':\n assertVersion(v2, comp)\n return this.tuples.push(this.#xInclusiveMin(v2))\n case '<=':\n assertVersion(v2, comp)\n return this.tuples.push(\n this.#xInclusiveMax(comp.substring(2)),\n )\n }\n switch (first) {\n case '~':\n assertVersion(v1, comp)\n return this.#parseTilde(v1)\n case '^':\n assertVersion(v1, comp)\n return this.#parseCaret(v1)\n case '>':\n assertVersion(v1, comp)\n return this.tuples.push(\n this.#xExclusiveMin(comp.substring(1)),\n )\n case '<':\n assertVersion(v1, comp)\n return this.tuples.push(\n this.#xExclusiveMax(comp.substring(1)),\n )\n }\n return this.#parseEq(comp)\n }\n\n #parseTilde(comp: string) {\n const parsed = this.#parseX(comp)\n if (isXMajor(parsed)) {\n this.tuples.push(this.#getComparatorAny())\n return\n }\n const z = this.includePrerelease ? '0' : undefined\n if (isXMinor(parsed)) {\n const [M] = parsed\n this.tuples.push(\n ['>=', new Version(comp, M, 0, 0, z, undefined)],\n ['<', new Version(comp, M + 1, 0, 0, '0', undefined)],\n )\n return\n }\n if (isXPatch(parsed)) {\n const [M, m] = parsed\n const z = this.includePrerelease ? '0' : undefined\n this.tuples.push(\n ['>=', new Version(comp, M, m, 0, z, undefined)],\n ['<', new Version(comp, M, m + 1, 0, '0', undefined)],\n )\n return\n }\n const [M, m, p, pr = z, build] = parsed\n this.tuples.push(\n ['>=', new Version(comp, M, m, p, pr, build)],\n ['<', new Version(comp, M, m + 1, 0, '0', build)],\n )\n }\n\n #parseCaret(comp: string) {\n const min = this.#xInclusiveMin(comp)\n if (isAny(min)) {\n this.tuples.push(min)\n return\n }\n const minv = min[1]\n if (minv.major !== 0) {\n this.tuples.push(min, [\n '<',\n new Version(comp, minv.major + 1, 0, 0, '0', undefined),\n ])\n } else if (minv.minor !== 0) {\n this.tuples.push(min, [\n '<',\n new Version(\n comp,\n minv.major,\n minv.minor + 1,\n 0,\n '0',\n undefined,\n ),\n ])\n } else if (!minv.prerelease?.length) {\n this.tuples.push(['', minv])\n } else {\n this.tuples.push(min, [\n '<',\n new Version(\n comp,\n minv.major,\n minv.minor,\n minv.patch + 1,\n '0',\n undefined,\n ),\n ])\n }\n }\n\n #parseEq(comp: string) {\n const parsed = this.#parseX(comp)\n const z = this.includePrerelease ? '0' : undefined\n if (isXMajor(parsed)) {\n this.tuples.push(this.#getComparatorAny())\n } else if (isFullVersion(parsed)) {\n this.tuples.push(['', new Version(comp, ...parsed)])\n } else if (isXMinor(parsed)) {\n this.tuples.push(\n ['>=', new Version(comp, parsed[MAJOR], 0, 0, z, undefined)],\n [\n '<',\n new Version(comp, parsed[MAJOR] + 1, 0, 0, '0', undefined),\n ],\n )\n } else if (isXPatch(parsed)) {\n this.tuples.push(\n [\n '>=',\n new Version(\n comp,\n parsed[MAJOR],\n parsed[MINOR],\n 0,\n z,\n undefined,\n ),\n ],\n [\n '<',\n new Version(\n comp,\n parsed[MAJOR],\n parsed[MINOR] + 1,\n 0,\n '0',\n undefined,\n ),\n ],\n )\n }\n }\n\n /** return true if the version is a match for this comparator */\n test(v: Version) {\n if (this.isNone) return false\n const ip = this.includePrerelease\n const hasPR = !!v.prerelease?.length\n let prOK = ip || !hasPR\n for (const c of this.tuples) {\n if (isAny(c)) {\n continue\n }\n const [op, cv] = c\n prOK ||= !!cv.prerelease?.length && v.tupleEquals(cv)\n switch (op) {\n case '':\n if (!v.equals(cv)) return false\n continue\n case '>':\n if (!v.greaterThan(cv)) return false\n continue\n case '>=':\n if (!v.greaterThanEqual(cv)) return false\n continue\n case '<':\n if (!v.lessThan(cv)) return false\n continue\n case '<=':\n if (!v.lessThanEqual(cv)) return false\n continue\n }\n }\n // they all passed, so it can only fail for having a prerelease\n // if we allow prereleases, or saw a matching tuple, that's ok.\n return prOK\n }\n\n #getComparatorAny() {\n return this.includePrerelease ? comparatorAnyPR : comparatorAny\n }\n}\n\nconst isAny = (c: Comparator | OVTuple): c is Comparator =>\n c === comparatorAny || c === comparatorAnyPR\nconst comparatorAny = {\n isAny: true,\n toString: () => '*',\n includePrerelease: false,\n test: (v: Version) => !v.prerelease?.length,\n} as Comparator\nconst comparatorAnyPR = {\n isAny: true,\n toString: () => '*',\n includePrerelease: true,\n test: (_: Version) => true,\n} as Comparator\nconst comparatorNone = {\n isNone: true,\n toString: () => '<0.0.0-0',\n includePrerelease: false,\n test: (_: Version) => false,\n} as unknown as Comparator\n", "import { fastSplit } from '@vltpkg/fast-split'\nimport { Comparator } from './comparator.js'\nimport { Version } from './version.js'\n\n/**\n * A representation of a semver range, used to test versions.\n *\n * Includes a set of comparators representing the `||`-separated\n * sections of the range string\n */\nexport class Range {\n /** raw string used to create this Range */\n raw: string\n\n /** true if the range is `*` */\n isAny: boolean\n\n /** true if the range is a single semver version */\n isSingle: boolean\n\n /** true if the range cannot match anything */\n\n /**\n * set of {@link Comparator} objects representing the `||`-separated sections\n * of the range. If at least one of these matches, then the version is a\n * match.\n */\n set: Comparator[] = []\n\n /** true if all prerelease versions should be included */\n includePrerelease: boolean\n\n /** cached toString */\n #toString?: string\n\n constructor(range: string, includePrerelease = false) {\n this.raw = range\n this.includePrerelease = includePrerelease\n fastSplit(range, '||', -1, part =>\n this.set.push(new Comparator(part, this.includePrerelease)),\n )\n this.isAny = this.set.some(c => c.isAny)\n\n const cmp = this.set[0]\n this.isSingle =\n this.set.length === 1 &&\n !!cmp &&\n Array.isArray(cmp.tuples) &&\n cmp.tuples.length === 1 &&\n Array.isArray(cmp.tuples[0]) &&\n cmp.tuples[0][0] === ''\n\n if (this.isSingle) {\n this.#toString = String(cmp)\n }\n }\n\n /**\n * test a {@link Version} against the range\n */\n test(v: Version) {\n return this.set.some(c => c.test(v))\n }\n\n /** return the simplified canonical form of this range */\n toString() {\n if (this.#toString) return this.#toString\n this.#toString = this.set.map(c => String(c)).join(' || ')\n return this.#toString\n }\n}\n", "import { Range } from './range.js'\nimport { IncrementType, Version } from './version.js'\nimport { syntaxError } from '@vltpkg/error-cause'\n\nexport * from './comparator.js'\nexport * from './range.js'\nexport * from './version.js'\n\n/** Return the parsed version string, or `undefined` if invalid */\nexport const parse = (version: Version | string) => {\n if (version instanceof Version) return version\n try {\n return Version.parse(String(version))\n } catch {\n return undefined\n }\n}\n\n/** Return the parsed version range, or `undefined` if invalid */\nexport const parseRange = (\n range: Range | string,\n includePrerelease = false,\n) => {\n if (typeof range === 'object') {\n if (range.includePrerelease === includePrerelease) return range\n range = range.raw\n }\n try {\n return new Range(range, includePrerelease)\n } catch {\n return undefined\n }\n}\n\n/**\n * return true if the version is valid\n *\n * Note: do not use this if you intend to immediately parse the version if it's\n * valid. Just use {@link parse}, and guard the possible undefined value, or\n * use `Version.parse(..)` to throw on invalid values.\n */\nexport const valid = (version: Version | string) => !!parse(version)\n\n/**\n * return true if the range is valid\n *\n * Note: do not use this if you intend to immediately parse the range if it's\n * valid. Just use {@link parseRange}, and guard the possible undefined value,\n * or use `new Range(..)` to throw on invalid values.\n */\nexport const validRange = (range: Range | string) =>\n !!parseRange(range)\n\n/**\n * Return true if the version satisfies the range.\n */\nexport const satisfies = (\n version: Version | string,\n range: Range | string,\n includePrerelease = false,\n) => {\n if (typeof version === 'string') {\n const parsed = parse(version)\n if (!parsed) return false\n version = parsed\n }\n if (typeof range === 'string') {\n const parsed = parseRange(range, includePrerelease)\n if (!parsed) return false\n range = parsed\n }\n return version.satisfies(range)\n}\n\n/**\n * Increment the specified part of the version, and return the resulting\n * object. If a Version object is provided, it will be modified in-place.\n *\n * Part behaviors:\n *\n * - `'major'` If the version is a `M.0.0-...` version with a prerelease, then\n * simply drop the prerelease. Otherwise, set the minor and patch to 0, and\n * increment the major. So `1.0.0-beta` becomes `1.0.0`, and `1.2.3` becomes\n * `2.0.0`\n *\n * - `'minor'` If the version is a `M.m.0-...` version with a prerelease, then\n * simply drop the prerelease. Otherwise, set the patch to 0, and increment the\n * minor. So `1.2.0-beta` becomes `1.2.0`, and `1.2.3` becomes `1.3.0`.\n *\n * - `'patch'` If the version has a prerelease, then simply drop the\n * prerelease. Otherwise, increment the patch value. So `1.2.3-beta` becomes\n * `1.2.3` and `1.2.3` becomes `1.2.4`.\n *\n * - `'premajor'` Set the patch and minor versions to `0`, increment the major\n * version, and add a prerelease, using the optional identifier.\n *\n * - `'preminor'` Set the patch version to `0`, increment the minor version,\n * and add a prerelease, using the optional identifier.\n *\n * - `'prepatch'` If a prerelease is already present, increment the patch\n * version, otherwise leave it untouched, and add a prerelease, using the\n * optional identifier.\n *\n * - `'prerelease'` If a prerelease version is present, then behave the same as\n * `'prepatch'`. Otherwise, add a prerelease, using the optional identifier.\n *\n * - `'pre'` This is mostly for use by the other prerelease incrementers.\n *\n * - If a prerelease identifier is provided:\n *\n * Update that named portion of the prerelease. For example,\n * `inc('1.2.3-beta.4', 'pre', 'beta')` would result in `1.2.3-beta.5`.\n *\n * If there is no prerelease identifier by that name, then replace the\n * prerelease with `[name]`. So `inc('1.2.3-alpha.4', 'pre', 'beta')`\n * would result in `1.2.3-beta`.\n *\n * If the prerelease identifer is present, but has no numeric value\n * following it, then add `0`. So `inc('1.2.3-beta', 'pre', 'beta')`\n * would result in `1.2.3-beta.0`.\n *\n * - If no prerelease identifier is provided:\n *\n * If there is no current prerelease, then set the prerelease to `0`. So,\n * `inc('1.2.3', 'pre')` becomes `1.2.3-0`.\n *\n * If the last item in the prerelease is numeric, then increment it. So,\n * `inc('1.2.3-beta.3', 'pre')` becomes `1.2.3-beta.4`.\n */\nexport const inc = (\n version: Version | string,\n part: IncrementType,\n prereleaseIdentifier?: string,\n) =>\n (typeof version === 'string' ?\n Version.parse(version)\n : version\n ).inc(part, prereleaseIdentifier)\n\n/**\n * The method used by {@link sort}, exported for passing directly to\n * `Array.sort`.\n *\n * Usage:\n *\n * ```ts\n * import { sortMethod } from '@vltpkg/semver'\n * const versions = ['1.2.3', '5.2.3', '2.3.4']\n * console.log(versions.sort(sortMethod))\n * // ['1.2.3', '2.3.4', '5.2.3']\n * ```\n */\nexport const sortMethod = (\n a: Version | string,\n b: Version | string,\n) => {\n const pa = parse(a)\n const pb = parse(b)\n /* c8 ignore start - nondeterministic */\n if (!pa && !pb) return String(a).localeCompare(String(b), 'en')\n if (!pa) return 1\n if (!pb) return -1\n /* c8 ignore stop */\n return pa.compare(pb)\n}\n\n/**\n * Sort an array of version strings or objects in ascending SemVer precedence\n * order (ie, lowest versions first).\n *\n * Invalid version strings are sorted to the end of the array in ascending\n * alphabetical order.\n *\n * Note: when using this method, the list is cloned prior to sorting, to\n * prevent surprising mutation. To sort the list in place, see\n * {@link sortMethod}.\n */\nexport const sort = <T extends Version | string = Version | string>(\n list: T[],\n): T[] => list.slice().sort(sortMethod)\n\n/**\n * Sort an array of version strings or objects in descending SemVer\n * precedence order (ie, highest versions first).\n *\n * Invalid version strings are sorted to the end of the array in ascending\n * alphabetical order.\n *\n * Note: when using this method, the list is cloned prior to sorting, to\n * prevent surprising mutation. To sort the list in place, see\n * {@link rsortMethod}.\n */\nexport const rsort = <T extends Version | string = Version | string>(\n list: T[],\n): T[] => list.slice().sort(rsortMethod)\n\n/**\n * The method used by {@link rsort}, exported for passing directly to\n * `Array.sort`.\n *\n * Usage:\n *\n * ```ts\n * import { rsortMethod } from '@vltpkg/semver'\n * const versions = ['1.2.3', '5.2.3', '2.3.4']\n * console.log(versions.sort(rsortMethod))\n * // ['5.2.3', '2.3.4', '1.2.3']\n * ```\n */\nexport const rsortMethod = (\n a: Version | string,\n b: Version | string,\n) => {\n const pa = parse(a)\n const pb = parse(b)\n /* c8 ignore start - nondeterministic */\n if (!pa && !pb) return String(a).localeCompare(String(b), 'en')\n if (!pa) return 1\n if (!pb) return -1\n /* c8 ignore stop */\n return pa.rcompare(pb)\n}\n\n/**\n * Method used by {@link filter}, for use in `Array.filter` directly.\n *\n * Usage:\n *\n * ```ts\n * import { filterMethod } from '@vltpkg/semver'\n * const versions = ['1.2.3', '5.2.3', '2.3.4']\n * console.log(versions.filter(filterMethod('>=2.x')))\n * // ['5.2.3', '2.3.4']\n * ```\n */\nexport const filterMethod = (\n range: Range | string,\n includePrerelease = false,\n): ((version: Version | string) => boolean) => {\n const r = parseRange(range, includePrerelease)\n return !r ?\n () => false\n : version => satisfies(version, r, r.includePrerelease)\n}\n\n/**\n * Filter a list of versions to find all that match a given range.\n */\nexport const filter = <T extends Version | string = Version | string>(\n list: T[],\n range: Range | string,\n includePrerelease = false,\n): T[] => list.filter(filterMethod(range, includePrerelease))\n\n/**\n * Find the highest-precedence match for a range within a list of versions\n *\n * Returns `undefined` if no match was found.\n */\nexport const highest = (\n list: (Version | string)[],\n range: Range | string,\n includePrerelease = false,\n): Version | undefined => {\n const r = parseRange(range, includePrerelease)\n if (!r) return undefined\n let max: Version | undefined = undefined\n for (const v of list) {\n const version = parse(v)\n if (!version) continue\n if (!version.satisfies(r)) continue\n if (!max) max = version\n else if (version.greaterThan(max)) max = version\n }\n return max\n}\n\n/**\n * Faster form of {@link highest}, for use when the list is sorted\n * in precedence order (lower-precedence versions first).\n *\n * Note: This stops at the first match, and will produce incorrect results\n * when the list is not properly sorted!\n */\nexport const sortedHighest = (\n list: (Version | string)[],\n range: Range | string,\n includePrerelease = false,\n): Version | undefined => {\n const r = parseRange(range, includePrerelease)\n if (!r) return undefined\n for (let i = list.length - 1; i >= 0; i--) {\n const v = list[i]\n /* c8 ignore next */\n if (!v) continue\n const version = parse(v)\n if (!version) continue\n if (!version.satisfies(r)) continue\n return version\n }\n}\n\n/**\n * Faster form of {@link highest}, for use when the list is sorted\n * in reverse precedence order (higher-precedence versions first).\n *\n * Note: This stops at the first match, and will produce incorrect results\n * when the list is not properly sorted!\n */\nexport const rsortedHighest = (\n list: (Version | string)[],\n range: Range | string,\n includePrerelease = false,\n): Version | undefined => {\n const r = parseRange(range, includePrerelease)\n if (!r) return undefined\n for (const v of list) {\n const version = parse(v)\n if (!version) continue\n if (!version.satisfies(r)) continue\n return version\n }\n}\n\n/**\n * Find the lowest-precedence match for a range within a list of versions\n *\n * Returns `undefined` if no match was found.\n */\nexport const lowest = (\n list: (Version | string)[],\n range: Range | string,\n includePrerelease = false,\n): Version | undefined => {\n const r = parseRange(range, includePrerelease)\n if (!r) return undefined\n let min: Version | undefined = undefined\n for (const v of list) {\n const version = parse(v)\n if (!version) continue\n if (!version.satisfies(r)) continue\n if (!min) min = version\n else if (version.lessThan(min)) min = version\n }\n return min\n}\n\n/**\n * Faster form of {@link lowest}, for use when the list is sorted\n * in precedence order (lower-precedence versions first).\n *\n * Note: This stops at the first match, and will produce incorrect results\n * when the list is not properly sorted!\n */\nexport const sortedLowest = (\n list: (Version | string)[],\n range: Range | string,\n includePrerelease = false,\n): Version | undefined =>\n rsortedHighest(list, range, includePrerelease)\n\n/**\n * Faster form of {@link lowest}, for use when the list is sorted\n * in reverse precedence order (higher-precedence versions first).\n *\n * Note: This stops at the first match, and will produce incorrect results\n * when the list is not properly sorted!\n */\nexport const rsortedLowest = (\n list: (Version | string)[],\n range: Range | string,\n includePrerelease = false,\n): Version | undefined =>\n sortedHighest(list, range, includePrerelease)\n\n/**\n * Same as {@link sortMethod}, but throws if either version is not valid.\n * 1 if versionA is higher precedence than versionB\n * -1 if versionA is lower precedence than versionB\n * 0 if they have equal precedence\n */\nexport const compare = (\n versionA: Version | string,\n versionB: Version | string,\n) => {\n const a = parse(versionA)\n if (!a) {\n throw syntaxError('invalid version', { found: versionA })\n }\n const b = parse(versionB)\n if (!b) {\n throw syntaxError('invalid version', { found: versionB })\n }\n return a.compare(b)\n}\n\n/**\n * Inverse of {@link compare}\n *\n * Same as {@link rsortMethod}, but throws if either version is not valid.\n *\n * -1 if versionA is higher precedence than versionB\n * 1 if versionA is lower precedence than versionB\n * 0 if they have equal precedence\n */\nexport const rcompare = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionB, versionA)\n\n/** true if versionA is > versionB. throws on invalid values */\nexport const gt = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionA, versionB) > 0\n/** true if versionA is >= versionB. throws on invalid values */\nexport const gte = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionA, versionB) >= 0\n/** true if versionA is < versionB. throws on invalid values */\nexport const lt = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionA, versionB) < 0\n/** true if versionA is <= versionB. throws on invalid values */\nexport const lte = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionA, versionB) <= 0\n/** true if versionA is not equal to versionB. throws on invalid values */\nexport const neq = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionA, versionB) !== 0\n/** true if versionA is equal to versionB. throws on invalid values */\nexport const eq = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionA, versionB) === 0\n\n/** extract the major version number, or undefined if invalid */\nexport const major = (version: Version | string) =>\n parse(version)?.major\n/** extract the minor version number, or undefined if invalid */\nexport const minor = (version: Version | string) =>\n parse(version)?.minor\n/** extract the patch version number, or undefined if invalid */\nexport const patch = (version: Version | string) =>\n parse(version)?.patch\n/**\n * extract the list of prerelease identifiers, or undefined if the version\n * is invalid. If no prerelease identifiers are present, returns `[]`.\n */\nexport const prerelease = (version: Version | string) => {\n const p = parse(version)\n if (!p) return undefined\n return p.prerelease ?? []\n}\n/**\n * extract the list of build identifiers, or undefined if the version\n * is invalid. If no build identifiers are present, returns `[]`.\n */\nexport const build = (version: Version | string) => {\n const p = parse(version)\n if (!p) return undefined\n return p.build ?? []\n}\n\n/** return all versions that do not have any prerelease identifiers */\nexport const stable = <T extends Version | string = Version | string>(\n versions: T[],\n): T[] =>\n versions.filter(v => {\n const p = parse(v)\n if (!p) return false\n return !p.prerelease?.length\n })\n", "import {\n error,\n ErrorCauseObject,\n typeError,\n} from '@vltpkg/error-cause'\nimport { parseRange, type Range } from '@vltpkg/semver'\nimport { homedir } from 'node:os'\nimport {\n isAbsolute,\n join,\n resolve,\n win32 as winPath,\n} from 'node:path'\nimport { inspect, InspectOptions } from 'node:util'\nimport {\n GitSelectorParsed,\n Scope,\n SpecLike,\n SpecOptions,\n SpecOptionsFilled,\n} from './types.js'\n\nexport * from './types.js'\n\nexport const kCustomInspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst defaultRegistry = 'https://registry.npmjs.org/'\n\nexport const defaultRegistries = {\n npm: 'https://registry.npmjs.org/',\n}\n\nexport const defaultGitHosts = {\n github: 'git+ssh://git@github.com:$1/$2.git',\n bitbucket: 'git+ssh://git@bitbucket.org:$1/$2.git',\n gitlab: 'git+ssh://git@gitlab.com:$1/$2.git',\n gist: 'git+ssh://git@gist.github.com/$1.git',\n}\n\nexport const defaultGitHostArchives = {\n github: 'https://codeload.github.com/$1/$2/tar.gz/$committish',\n bitbucket: 'https://bitbucket.org/$1/$2/get/$committish.tar.gz',\n gist: 'https://codeload.github.com/gist/$1/tar.gz/$committish',\n gitlab:\n 'https://gitlab.com/$1/$2/repository/archive.tar.gz?ref=$committish',\n}\n\n/**\n * These are just for legacy support of urls that are supported by npm\n * and observed in the wild.\n *\n * Not configurable, because no more will be added. If you wish to define\n * custom git hosts, use it with the `'git-hosts'` and `'git-host-archives'`\n * options.\n */\nexport const gitHostWebsites = {\n github: 'https://github.com/',\n bitbucket: 'https://bitbucket.org/',\n gist: 'https://gist.github.com/',\n gitlab: 'https://gitlab.com/',\n}\n\nconst getOptions = (options: SpecOptions): SpecOptionsFilled => ({\n ...options,\n registry: options.registry ?? defaultRegistry,\n 'scope-registries': options['scope-registries'] ?? {},\n 'git-hosts':\n options['git-hosts'] ?\n {\n ...defaultGitHosts,\n ...options['git-hosts'],\n }\n : defaultGitHosts,\n registries:\n options.registries ?\n {\n ...defaultRegistries,\n ...options.registries,\n }\n : defaultRegistries,\n 'git-host-archives':\n options['git-host-archives'] ?\n {\n ...defaultGitHostArchives,\n ...options['git-host-archives'],\n }\n : defaultGitHostArchives,\n})\n\n/**\n * Various nameless scenarios that are handled in the\n * standard spec parsing and should return an unknown name.\n *\n * Returns `true` if the name can not be inferred, `false` otherwise.\n */\nconst startsWithSpecIdentifier = (\n spec: string,\n options: SpecOptionsFilled,\n): boolean =>\n spec.startsWith('/') ||\n spec.startsWith('./') ||\n spec.startsWith('../') ||\n spec.startsWith('file:') ||\n spec.startsWith('http:') ||\n spec.startsWith('https:') ||\n spec.startsWith('workspace:') ||\n spec.startsWith('git@') ||\n spec.startsWith('git://') ||\n spec.startsWith('git+ssh://') ||\n spec.startsWith('git+http://') ||\n spec.startsWith('git+https://') ||\n spec.startsWith('git+file://') ||\n spec.startsWith('git@github.com') ||\n spec.startsWith('registry:') ||\n // anything that starts with a known git host key, or a\n // custom registered registry protocol e.g: `github:`, `custom:`\n [\n ...Object.keys(options['git-hosts']),\n ...Object.keys(options.registries),\n ].some(key => spec.startsWith(`${key}:`))\n\n/**\n * Returns the location in which the first `@` value is found in a given\n * string, also takes into account that a string starting with @ is\n * using a scoped-name.\n */\nconst findFirstAt = (spec: string, hasScope: boolean) =>\n spec.indexOf('@', hasScope ? 1 : 0)\n\n/**\n * Return `true` if a given spec string is likely to be a git spec.\n */\nconst findGitIdentifier = (spec: string): boolean =>\n spec.indexOf('#') > 2\n\n/**\n * Return `true` if a given spec string is likely to be a file spec.\n */\nconst findFileIdentifier = (spec: string): boolean =>\n spec.includes('/')\n\nexport class Spec implements SpecLike<Spec> {\n /**\n * Create a Spec object from a full spec, name+bareSpec, or Spec object\n *\n * Note: If a Spec object is provided, it is returned as-is, without\n * investigating whether the options match.\n */\n static parse(\n name: string,\n bareSpec: string,\n options?: SpecOptions,\n ): Spec\n static parse(spec: string, options?: SpecOptions): Spec\n static parse(spec: Spec, options?: SpecOptions): Spec\n static parse(\n spec: Spec | string,\n bareOrOptions?: SpecOptions | string,\n options?: SpecOptions,\n ): Spec {\n return typeof spec === 'object' ? spec : (\n new Spec(spec, bareOrOptions, options)\n )\n }\n\n static parseArgs(specOrBareSpec: string, opts?: SpecOptions): Spec {\n const options = getOptions(opts ?? {})\n\n if (startsWithSpecIdentifier(specOrBareSpec, options)) {\n const parsed = Spec.parse('(unknown)', specOrBareSpec, options)\n // try to look into a potential parsed subspec for a name\n if (parsed.subspec) {\n parsed.name = parsed.subspec.name\n parsed.spec = `${parsed.name}@${parsed.bareSpec}`\n }\n return parsed\n } else {\n const hasScope = specOrBareSpec.startsWith('@')\n const at = findFirstAt(specOrBareSpec, hasScope)\n if (at > -1) {\n return Spec.parse(\n specOrBareSpec.substring(0, at),\n specOrBareSpec.substring(at + 1),\n options,\n )\n } else if (\n findGitIdentifier(specOrBareSpec) ||\n (!hasScope && findFileIdentifier(specOrBareSpec))\n ) {\n return Spec.parse('(unknown)', specOrBareSpec, options)\n } else {\n // doesn't have an @, so it's just a name with no version\n return Spec.parse(`${specOrBareSpec}@`, options)\n }\n }\n }\n\n type: 'file' | 'git' | 'registry' | 'remote' | 'workspace'\n spec: string\n options: SpecOptionsFilled\n name: string\n scope?: Scope\n scopeRegistry?: string\n bareSpec: string\n gitRemote?: string\n gitSelector?: string\n gitSelectorParsed?: GitSelectorParsed\n gitCommittish?: string\n namedGitHost?: string\n namedGitHostPath?: string\n workspaceSpec?: string\n workspace?: string\n namedRegistry?: string\n registry?: string\n registrySpec?: string\n conventionalRegistryTarball?: string\n semver?: string\n range?: Range\n distTag?: string\n remoteURL?: string\n file?: string\n subspec?: Spec\n #final?: Spec\n #toString?: string\n\n /**\n * Return the final entry in the chain of subspecs\n * When deciding which thing to actually fetch, spec.final is the thing\n * to look at.\n */\n get final(): Spec {\n if (this.#final) return this.#final\n return (this.#final = this.subspec ? this.subspec.final : this)\n }\n\n /**\n * Normally, the string value of a Spec is just the string passed in to\n * be parsed. However, in the case of a chain of subspecs, like\n * `foo@npm:bar@npm:baz@npm:quux@latest`, this simplifies out the middle\n * parts of the chain, returning just `foo@npm:quux@latest`\n */\n toString() {\n if (this.#toString !== undefined) return this.#toString\n let sub: Spec = this\n // we want the SECOND from the last in the chain\n while (sub.subspec?.subspec) sub = sub.subspec\n if (sub.subspec && sub.subspec.type !== 'registry')\n sub = sub.subspec\n return (this.#toString = this.name + '@' + sub.bareSpec)\n }\n\n constructor(name: string, bareSpec: string, options?: SpecOptions)\n constructor(spec: string, options?: SpecOptions)\n constructor(\n spec: Spec | string,\n bareOrOptions?: SpecOptions | string,\n options?: SpecOptions,\n )\n constructor(\n spec: string,\n bareOrOptions?: SpecOptions | string,\n options: SpecOptions = {},\n ) {\n if (bareOrOptions && typeof bareOrOptions === 'object') {\n options = bareOrOptions\n bareOrOptions = undefined\n }\n this.options = getOptions(options)\n\n if (typeof bareOrOptions === 'string') {\n this.name = spec\n this.#parseScope(spec)\n this.bareSpec = bareOrOptions\n this.spec = `${this.name}@${bareOrOptions}`\n } else {\n this.spec = spec\n const hasScope = spec.startsWith('@')\n let at = findFirstAt(spec, hasScope)\n if (at === -1) {\n // assume that an unadorned spec is just a name at the default\n // registry\n at = spec.length\n spec += '@'\n }\n this.name = spec.substring(0, at)\n if (hasScope) this.#parseScope(this.name)\n this.bareSpec = spec.substring(at + 1)\n }\n\n // legacy affordance: allow project urls like\n // 'https://github.com/user/project#commitish' because npm suports it and\n // this pattern is observed in the wild.\n if (this.bareSpec.startsWith('https://')) {\n for (const [name, origin] of Object.entries(gitHostWebsites)) {\n if (this.bareSpec.startsWith(origin)) {\n const parsed = new URL(this.bareSpec)\n const [user, project] = parsed.pathname\n .replace(/\\.git$/, '')\n .replace(/\\/+/g, ' ')\n .trim()\n .split(' ')\n if (user && project) {\n this.bareSpec = `${name}:${user}/${project}${parsed.hash}`\n this.spec = `${this.name}@${this.bareSpec}`\n break\n }\n }\n }\n }\n\n if (this.bareSpec.startsWith('workspace:')) {\n this.type = 'workspace'\n const ws = this.bareSpec.substring('workspace:'.length).trim()\n const w = ws.lastIndexOf('@')\n if (w === -1) {\n this.workspace = this.name\n } else {\n const wsName = ws.substring(0, w)\n if (\n !wsName ||\n wsName === '*' ||\n wsName === '~' ||\n wsName === '^' ||\n (wsName.startsWith('@') ?\n wsName.split('/').length !== 2 ||\n wsName.substring(1).includes('@')\n : wsName.includes('@'))\n ) {\n throw this.#error(\n 'workspace: name must be a path or valid package name',\n { found: wsName },\n )\n }\n this.workspace = wsName\n }\n // workspace: is the same as workspace:*\n const wss = w === -1 ? ws : ws.substring(w + 1) || '*'\n const range = wss === '*' ? undefined : parseRange(wss)\n if (wss !== '*' && wss !== '~' && wss !== '^' && !range) {\n throw this.#error(\n 'workspace: spec must be one of *, ~, or ^, or a valid semver range',\n {\n found: wss,\n wanted: `'*'|'~'|'^'|SemverRange`,\n },\n )\n }\n this.workspaceSpec = wss\n if (range) {\n this.semver = wss\n this.range = range\n }\n return\n }\n\n if (\n this.bareSpec.startsWith('git://') ||\n this.bareSpec.startsWith('git+ssh://') ||\n this.bareSpec.startsWith('git+http://') ||\n this.bareSpec.startsWith('git+https://') ||\n this.bareSpec.startsWith('git+file://') ||\n // legacy affordance\n this.bareSpec.startsWith('git@github.com')\n ) {\n if (this.bareSpec.startsWith('git@')) {\n this.bareSpec = `git+ssh://${this.bareSpec}`\n this.spec = `${this.name}@${this.bareSpec}`\n }\n this.type = 'git'\n // see if it's one of the known named hosts, and if so, prefer\n // the shorter syntax.\n for (const [name, host] of Object.entries(\n this.options['git-hosts'],\n )) {\n const s = host.indexOf('$')\n if (s > 0 && this.bareSpec.startsWith(host.substring(0, s))) {\n const p = this.bareSpec\n .substring(s)\n .replace(/\\.git(#.*)?$/, '$1')\n this.bareSpec = `${name}:${p}`\n this.spec = `${this.name}@${this.bareSpec}`\n this.#parseHostedGit(name, host)\n this.type = 'git'\n return\n }\n }\n this.#parseGitSelector(this.bareSpec)\n return\n }\n\n // spooky\n const ghosts = Object.entries(this.options['git-hosts'])\n for (const [name, template] of ghosts) {\n if (this.#parseHostedGit(name, template)) {\n this.type = 'git'\n return\n }\n }\n\n if (this.bareSpec.startsWith('registry:')) {\n const reg = this.bareSpec.substring('registry:'.length)\n const h = reg.indexOf('#')\n if (h === -1) {\n throw this.#error('registry: must include name/version')\n }\n this.type = 'registry'\n let url = reg.substring(0, h)\n if (!url.endsWith('/')) url += '/'\n const regSpec = reg.substring(h + 1)\n for (let [name, u] of Object.entries(this.options.registries)) {\n if (!u.endsWith('/')) {\n u += '/'\n this.options.registries[name] = u\n }\n if (u === url) this.namedRegistry = name\n }\n this.#parseRegistrySpec(regSpec, url)\n this.#guessRegistryTarball()\n return\n }\n\n const regs = Object.entries(this.options.registries)\n for (const [host, url] of regs) {\n const h = `${host}:`\n if (this.bareSpec.startsWith(h)) {\n this.type = 'registry'\n this.namedRegistry = host\n this.#parseRegistrySpec(\n this.bareSpec.substring(h.length),\n url,\n ).namedRegistry ??= host\n this.#guessRegistryTarball()\n return\n }\n }\n\n if (\n this.bareSpec.startsWith('https://') ||\n this.bareSpec.startsWith('http://')\n ) {\n this.remoteURL = this.bareSpec\n this.type = 'remote'\n return\n }\n\n // explicit file: url\n if (this.bareSpec.startsWith('file:')) {\n this.type = 'file'\n const [path, uri] = normalizeFile(this.bareSpec, this)\n this.file = path\n this.bareSpec = uri.replace(/\\/+$/, '')\n this.spec = `${this.name}@${this.bareSpec}`\n return\n }\n\n // legacy! once upon a time, `user/project` was a shorthand for pulling\n // packages from github, instead of the more verbose and explicit\n // `github:user/project`.\n if (\n !this.bareSpec.startsWith('./') &&\n !this.bareSpec.startsWith('../') &&\n this.options['git-hosts'].github\n ) {\n const hash = this.bareSpec.indexOf('#')\n const up =\n hash === -1 ? this.bareSpec : this.bareSpec.substring(0, hash)\n if (up.split('/').length === 2) {\n this.bareSpec = `github:${this.bareSpec}`\n this.spec = `${this.name}@${this.bareSpec}`\n this.#parseHostedGit(\n 'github',\n this.options['git-hosts'].github,\n )\n this.type = 'git'\n return\n }\n }\n\n // if it contains a / and isn't picked up in the github shorthand,\n // then convert to file: specifier\n if (\n this.bareSpec.includes('/') ||\n this.bareSpec === '.' ||\n this.bareSpec === '..'\n ) {\n this.type = 'file'\n const [file, uri] = normalizeFile(`file:${this.bareSpec}`, this)\n this.bareSpec = uri\n this.spec = `${this.name}@${this.bareSpec}`\n this.file = file\n return\n }\n\n // at this point, must be either semver range or dist-tag\n this.type = 'registry'\n const range = parseRange(this.bareSpec)\n if (range) {\n this.semver = this.bareSpec.trim()\n this.range = range\n } else {\n this.distTag = this.bareSpec\n }\n this.registrySpec = this.bareSpec\n const { 'scope-registries': scopeRegs, registry } = this.options\n const scopeReg = this.scope && scopeRegs[this.scope]\n this.registry = scopeReg ?? registry\n this.#guessRegistryTarball()\n }\n\n #parseScope(name: string) {\n if (!name.startsWith('@')) return\n const s = name.indexOf('/')\n if (s > 1 && s < name.length - 1) {\n const scope = name.substring(0, s) as Scope\n this.registry = this.scopeRegistry =\n this.options['scope-registries'][scope]\n this.scope = scope\n }\n }\n\n #parseHostedGit(name: string, template: string) {\n if (this.bareSpec.startsWith(`${name}:`)) {\n const h = this.bareSpec.indexOf('#')\n const bare =\n h === -1 ? this.bareSpec : this.bareSpec.substring(0, h)\n const hash = h === -1 ? '' : this.bareSpec.substring(h)\n const hostPath = bare.substring(name.length + 1)\n if (!hostPath) {\n throw error('invalid named git host specifier', {\n spec: this,\n })\n }\n const split = hostPath.split('/')\n let t = template\n for (let i = 0; i < split.length; i++) {\n t = t.split(`$${i + 1}`).join(split[i])\n }\n t += hash\n this.namedGitHost = name\n this.namedGitHostPath = hostPath\n this.#parseGitSelector(t)\n if (this.gitCommittish && !this.gitSelectorParsed?.path) {\n const archiveHost = this.options['git-host-archives'][name]\n if (archiveHost) {\n this.type = 'remote'\n let t = archiveHost\n t = t.split('$committish').join(this.gitCommittish)\n for (let i = 0; i < split.length; i++) {\n t = t.split(`$${i + 1}`).join(split[i])\n }\n this.remoteURL = t\n }\n }\n return true\n }\n return false\n }\n\n [kCustomInspect](\n _depth?: number,\n options?: InspectOptions,\n ): string {\n const str = inspect(\n Object.fromEntries(\n Object.entries(this).filter(([k, v]) => {\n return k !== 'options' && v !== undefined\n }),\n ),\n options,\n )\n return `@vltpkg/spec.Spec ${str}`\n }\n\n #guessRegistryTarball() {\n // only try to guess if it's a single comparator for a single version\n const { name, registry, range } = this.final\n if (!registry || !range?.isSingle) return\n const stripScope = /^@[^/]+\\//\n this.conventionalRegistryTarball = String(\n new URL(\n `/${name}/-/${name.replace(stripScope, '')}-${range}.tgz`,\n registry,\n ),\n )\n }\n\n #parseRegistrySpec(s: string, url: string) {\n // note: this takes priority over the scoped registry, if set\n this.registry = url\n this.subspec = Spec.parse(s, {\n ...this.options,\n registry: url,\n })\n return this.subspec\n }\n\n #error(message: string, extra: ErrorCauseObject = {}) {\n return error(message, { spec: this.spec, ...extra }, this.#error)\n }\n\n #parseGitSelector(s: string) {\n const h = s.indexOf('#')\n if (h === -1) {\n this.gitRemote = s\n return\n }\n this.gitRemote = s.substring(0, h)\n this.gitSelector = s.substring(h + 1)\n const [selectorParsed, committish, range] = Spec.parseGitSelector(\n this.gitSelector,\n this,\n )\n this.range = range\n this.gitCommittish = committish\n this.gitSelectorParsed = selectorParsed\n }\n\n /**\n * Should only ever be called with the bit that comes AFTER the #\n * in the git remote url.\n */\n static parseGitSelector(\n selector: string,\n spec?: Spec,\n ): [parsed: GitSelectorParsed, committish?: string, range?: Range] {\n if (!selector) return [{}]\n const split = selector.split('::')\n const first = split[0]\n let committish: string | undefined = undefined\n let range: Range | undefined = undefined\n const parsed: GitSelectorParsed = {}\n\n /* c8 ignore start - for TS's benefit */\n if (typeof first !== 'string') {\n throw typeError('impossible', {\n found: first,\n wanted: String,\n })\n }\n /* c8 ignore stop */\n if (!first.includes(':')) {\n committish = first\n split.shift()\n }\n for (const kv of split) {\n const c = kv.indexOf(':')\n /* c8 ignore next */\n if (c === -1) continue\n const k = kv.substring(0, c)\n const v = kv.substring(c + 1)\n if (k === 'semver') {\n if (committish) {\n throw error(\n 'Cannot specify a semver range and committish value',\n { spec },\n )\n }\n range = parseRange(v)\n if (!range) {\n throw error(`Invalid git tag semver range: ${v}`, { spec })\n }\n }\n if (k === 'semver' || k === 'path') {\n if (k === 'path') {\n if (isAbsolute(v) || /(^|\\/|\\\\)\\.\\.($|\\\\|\\/)/.test(v)) {\n throw error('Invalid path in git selector', { spec })\n }\n // normalize\n parsed.path = join('/', v).substring(1).replace(/\\\\/g, '/')\n } else {\n parsed[k] = v\n }\n }\n }\n return [parsed, committish, range]\n }\n}\n\n// normalize our kinda-sorta spec compliant `file:` specifiers\n//\n// For historical reasons, we need to support a lot of non-spec-compliant\n// behaviors, but this massages the result into a *slightly* less offensive\n// shape.\n//\n// The result will be either a fully compliant `file://` with an absolute path,\n// or a `file:` with a relative path starting with `~`, `./`, or `../`.\nconst normalizeFile = (\n bareSpec: string,\n spec: Spec,\n): [path: string, uri: string] => {\n const slashes = bareSpec.substring('file:'.length, 'file://'.length)\n const pref = `file:${slashes === '//' ? slashes : ''}`\n const rest = bareSpec.substring(pref.length)\n\n // default to '/' because eol == '/' for parsing purposes\n const [a = '', b = '/', c = '/', d = '/'] = rest.split('', 4)\n\n if (!a) {\n // file:// => file:.\n // file: => file:.\n return ['.', 'file:.']\n }\n\n if (\n (a === '/' && b === '~' && c !== '/') ||\n (a === '~' && b !== '/')\n ) {\n throw error(\n `invalid file: specifier. '~username' not supported`,\n { spec },\n )\n }\n\n if (a === '~') {\n // file://~ => file:~\n // file://~/x => file:~/x\n return [resolve(homedir(), rest.substring(2)), `file:${rest}`]\n }\n\n if (a === '/' && b === '~') {\n // file:///~ => file:~\n // file:/~/x => file:~/x\n return [\n resolve(homedir(), rest.substring(3)),\n `file:${rest.substring(1)}`,\n ]\n }\n\n if (\n a === '/' &&\n b === '.' &&\n (c === '/' || (c === '.' && d === '/'))\n ) {\n // file:/./x => file:./x\n // file:///./x => file:./x\n // file:/../x => file:../x\n // file://../x => file:../x\n return [rest.substring(1), `file:${rest.substring(1)}`]\n }\n\n if (a === '.' && (b === '/' || (b === '.' && c === '/'))) {\n // file://. => file:.\n // file://./x => file:./x\n // file://../x => file:../x\n return [rest, `file:${rest}`]\n }\n\n if (slashes === '//') {\n // must be valid URI, since we ruled out relative and homedir above\n\n // not relative, but note that file://host/share is\n // windows-specific and does not work on darwin, so disallow it.\n try {\n const parsed = new URL(bareSpec)\n if (parsed.host) {\n if (parsed.host !== 'localhost') {\n throw error(\n `invalid file:// specifier. host must be empty or 'localhost'`,\n {\n spec,\n found: parsed.host,\n validOptions: ['', 'localhost'],\n },\n )\n }\n }\n // normalize blank authority\n // file://X:/foo => file:///X:/foo\n // file://localhost/x => file:///x\n // interpret a `file:///D:/x` as `D:/x` though\n return [\n parsed.pathname.replace(/^\\/([a-zA-Z]:\\/)/, '$1'),\n `file://${parsed.pathname}`,\n ]\n } catch (er) {\n // invalid URI for other reasons, eg file://x\\u0000y/z\n throw error('invalid file:// specifier', {\n spec,\n cause: er as Error,\n })\n }\n }\n\n // no //, no authority, be ungovernable\n\n if (winPath.isAbsolute(rest)) {\n // file:/absolute => file:///absolute\n // file:/D:/foo => file:///D:/foo\n return [rest, `file://${rest}`]\n }\n\n // file:x => file:./x\n return [`./${rest}`, `file:./${rest}`]\n}\n", "import { error } from '@vltpkg/error-cause'\nimport { Spec, SpecOptions } from '@vltpkg/spec'\nimport { Manifest } from '@vltpkg/types'\n\nexport const delimiter: Delimiter = '·'\nexport type Delimiter = '·'\n\n/**\n * Dependency IDs are a URI-encoded set of strings, separated\n * by the {@link Delimiter} character (`'·'`).\n *\n * The first entry is always the specifier type. The rest depend on the\n * type. `git`, `registry`, and `workspace` entries have 3 fields, the rest\n * have 2.\n *\n * - `registry`: `'registry·<registry>·name@specifier'`\n * The `<registry>` portion can be a known named registry name, or a\n * url to a registry. If empty, it is the default registry.\n * Examples:\n * - `··some-package@2.0.1`\n * - `·npm·whatever@1.2.3'\n * - `·http%3A%2F%2Fvlt.sh%2F·x@1.2.3`\n * - `git`: `'git·<git remote>·<git selector>`. For example:\n * - `git·github:user/project·branchname`\n * - `git·git%2Bssh%3A%2F%2Fuser%40host%3Aproject.git·semver:1.x`\n * - `workspace`: `'workspace·<path>`. For example:\n * - `workspace·src/mything`\n * - `remote`: `'remote·<url>'`\n * - `file`: `'file·<path>`\n *\n * Lastly, the final portion can contain arbitrary string data, and is\n * used to store peer dep resolutions to maintain the peerDep contract.\n */\nexport type DepID =\n | `${'' | 'git'}${Delimiter}${string}${Delimiter}${string}${Delimiter}${string}`\n | `${'' | 'git'}${Delimiter}${string}${Delimiter}${string}`\n | `${'file' | 'remote' | 'workspace'}${Delimiter}${string}${Delimiter}${string}`\n | `${'file' | 'remote' | 'workspace'}${Delimiter}${string}`\n\n/**\n * A {@link DepID}, split apart and URI-decoded\n */\nexport type DepIDTuple =\n | [\n type: 'git',\n gitRemote: string,\n gitSelector: string,\n extra?: string,\n ]\n | [\n type: 'registry',\n registry: string,\n registrySpec: string,\n extra?: string,\n ]\n | [type: 'file', path: string, extra?: string]\n | [type: 'remote', url: string, extra?: string]\n | [type: 'workspace', workspace: string, extra?: string]\n\nconst depIDRegExp = new RegExp(\n `^((git)?${delimiter}[^${delimiter}]*${delimiter}[^${delimiter}]*(${\n delimiter\n }[^${delimiter}]*)?$` +\n `|` +\n `^(file|remote|workspace)${delimiter}[^${\n delimiter\n }]*)(${delimiter}[^${delimiter}]*)?$`,\n)\n\nexport const isDepID = (str: unknown): str is DepID =>\n typeof str === 'string' && depIDRegExp.test(str)\n\nexport const asDepID = (str: string): DepID => {\n if (!isDepID(str)) {\n throw error('Expected dep id', {\n found: str,\n })\n }\n return str\n}\n\n/**\n * turn a {@link DepIDTuple} into a {@link DepID}\n */\nexport const joinDepIDTuple = (list: DepIDTuple): DepID => {\n const [type, first, second, extra] = list\n const f = encode(first)\n switch (type) {\n case 'registry':\n return `${delimiter}${f}${delimiter}${encode(second)}${extra ? `${delimiter}${encode(extra)}` : ''}`\n case 'git':\n return `${type}${delimiter}${f}${delimiter}${encode(second)}${extra ? `${delimiter}${encode(extra)}` : ''}`\n default:\n return `${type}${delimiter}${f}${second ? `${delimiter}${encode(second)}` : ''}`\n }\n}\n\n// allow @, but otherwise, escape everything urls do\nconst encode = (s: string): string =>\n encodeURIComponent(s).replaceAll('%40', '@')\n\n/**\n * turn a {@link DepID} into a {@link DepIDTuple}\n */\nexport const splitDepID = (id: string): DepIDTuple => {\n const [type, first = '', second, extra] = id.split(delimiter, 4)\n const f = decodeURIComponent(first)\n switch (type) {\n case 'git':\n case '': {\n if (second === undefined) {\n throw error(`invalid ${type} id`, { found: id })\n }\n const t: DepIDTuple = [\n type || 'registry',\n f,\n decodeURIComponent(second),\n ]\n if (extra) t.push(decodeURIComponent(extra))\n return t\n }\n case 'file':\n case 'remote':\n case 'workspace': {\n const t: DepIDTuple = [type, f]\n if (second) t.push(decodeURIComponent(second))\n return t\n }\n default: {\n throw error('invalid DepID type', {\n found: type,\n validOptions: ['git', 'file', 'workspace', 'remote', ''],\n })\n }\n }\n}\n\n/**\n * Turn a {@link DepID} into a {@link Spec} object\n */\nexport const hydrate = (\n id: DepID,\n name?: string,\n options: SpecOptions = {},\n): Spec => hydrateTuple(splitDepID(id), name, options)\n\n/**\n * Turn a {@link DepIDTuple} into a {@link Spec} object\n */\nexport const hydrateTuple = (\n tuple: DepIDTuple,\n name?: string,\n options: SpecOptions = {},\n) => {\n const [type, first, second] = tuple\n switch (type) {\n case 'remote': {\n if (!first)\n throw error('no remoteURL found on remote id', {\n found: tuple,\n })\n return Spec.parse(name ?? '(unknown)', first)\n }\n case 'file': {\n if (!first) {\n throw error('no file path found on remote id', {\n found: tuple,\n })\n }\n return Spec.parse(name ?? '(unknown)', `file:${first}`, options)\n }\n case 'registry': {\n if (typeof first !== 'string') {\n throw error('no registry url or name in registry ID', {\n found: tuple,\n })\n }\n if (!second) {\n throw error('no name/specifier in registry ID', {\n found: tuple,\n })\n }\n if (!first) {\n // just a normal name@version on the default registry\n const s = Spec.parse(second)\n if (name && s.name !== name) {\n return Spec.parse(`${name}@npm:${second}`)\n } else {\n return s\n }\n }\n if (!/^https?:\\/\\//.test(first)) {\n const reg = options.registries?.[first]\n if (first !== 'npm' && !reg) {\n throw error('named registry not found in options', {\n name: first,\n found: tuple,\n })\n }\n return Spec.parse(\n name ?? '(unknown)',\n `${first}:${second}`,\n options,\n )\n }\n const s = Spec.parse(\n name ?? '(unknown)',\n `registry:${first}#${second}`,\n options,\n )\n return name && s.final.name !== name ?\n Spec.parse(s.final.name + '@' + s.bareSpec)\n : s\n }\n case 'git': {\n if (!first) {\n throw error('no git remote in git ID', {\n found: tuple,\n })\n }\n return Spec.parse(\n name ?? '(unknown)',\n first + '#' + second,\n options,\n )\n }\n case 'workspace': {\n if (!first) {\n throw error('no name/path on workspace id', { found: tuple })\n }\n return name && name !== first ?\n Spec.parse(name, `workspace:${first}@*`, options)\n : Spec.parse(first, `workspace:*`, options)\n }\n }\n}\n\n// Strip out the default registry, there's no need to store that\nconst omitDefReg = (s?: string): string =>\n (\n !s ||\n s === 'https://registry.npmjs.org' ||\n s === 'https://registry.npmjs.org/'\n ) ?\n ''\n : s\n\n/**\n * Get the {@link DepIDTuple} for a given {@link Spec} and {@link Manifest}.\n * The Manifest is used to get the name and version, if possible. If not found\n * in the manifest, registry ID types will use the name or bareSpec from the\n * specifier, so at least there's something to use later.\n */\nexport const getTuple = (spec: Spec, mani: Manifest): DepIDTuple => {\n const f = spec.final\n switch (f.type) {\n case 'registry': {\n // try to shorten to a known name if we can.\n const reg = omitDefReg(f.registry)\n if (!f.namedRegistry && reg) {\n for (const [alias, host] of Object.entries(\n spec.options.registries,\n )) {\n if (reg === host) {\n f.namedRegistry = alias\n break\n }\n }\n }\n return [\n f.type,\n f.namedRegistry ?? reg,\n `${mani.name ?? spec.name}@${mani.version ?? spec.bareSpec}`,\n ]\n }\n case 'git': {\n const {\n namedGitHost,\n namedGitHostPath,\n gitRemote,\n gitSelector = '',\n } = f\n if (!gitRemote)\n throw error('no host on git specifier', { spec })\n if (namedGitHost) {\n if (!namedGitHostPath) {\n throw error('named git host without path portion', {\n spec,\n })\n }\n return [\n f.type,\n `${namedGitHost}:${namedGitHostPath}`,\n gitSelector,\n ]\n } else {\n return [f.type, gitRemote, gitSelector]\n }\n }\n case 'remote': {\n const { remoteURL } = f\n if (!remoteURL)\n throw error('no URL on remote specifier', { spec })\n return [f.type, remoteURL]\n }\n case 'file':\n case 'workspace':\n throw error('Path-based dep ids are not supported', { spec })\n }\n}\n\n/**\n * Get the {@link DepID} for a given {@link Spec} and {@link Manifest}. The\n * Manifest is used to get the name and version, if possible. If not found in\n * the manifest, registry ID types will use the name or bareSpec from the\n * specifier, so at least there's something to use later.\n */\nexport const getId = (spec: Spec, mani: Manifest): DepID =>\n joinDepIDTuple(getTuple(spec, mani))\n", "import { DepID, joinDepIDTuple } from '@vltpkg/dep-id'\nimport { error } from '@vltpkg/error-cause'\nimport { PackageJson } from '@vltpkg/package-json'\nimport { Manifest } from '@vltpkg/types'\nimport { readFileSync, statSync } from 'fs'\nimport { GlobOptionsWithFileTypesFalse, globSync } from 'glob'\nimport { DepResults, graphRun, graphRunSync } from 'graph-run'\nimport { basename, resolve, posix } from 'path'\nimport { Path, PathScurry } from 'path-scurry'\nimport { parse } from 'polite-json'\nimport { minimatch } from 'minimatch'\n\nexport type WorkspacesLoadedConfig = {\n workspace?: string[]\n 'workspace-group'?: string[]\n}\n\n/**\n * The object passed to the constructor or {@link Monorepo#load} to limit which\n * {@link Workspace Workspaces} get loaded.\n */\nexport type LoadQuery = {\n /**\n * A glob pattern string, or an array of them. Only workspaces found\n * in paths matched will be loaded.\n */\n paths?: string[] | string\n /**\n * A string, or an array of strings. If set, only workspaces in the\n * specified groups named will be included, if set.\n */\n groups?: string[] | string\n}\n\n/**\n * Canonical form of the {@link WorkspaceConfig}, used\n * internally for consistency.\n */\nexport type WorkspaceConfigObject = Record<string, string[]>\n\n/**\n * Allowed datatype in the `vlt-workspaces.json` file.\n */\nexport type WorkspaceConfig =\n | string[]\n | WorkspaceConfigObject\n | string\n\n/**\n * Turn a {@link WorkspaceConfig} into a\n * {@link WorkspaceConfigObject}, or throw if it's not valid.\n */\nexport const asWSConfig = (\n conf: unknown,\n path?: string,\n): WorkspaceConfigObject => {\n assertWSConfig(conf, path)\n return (\n typeof conf === 'string' ? { packages: [conf] }\n : Array.isArray(conf) ? { packages: conf }\n : conf\n )\n}\n\n/**\n * Throw if the provided value is not a valid {@link WorkspaceConfig}\n */\nexport const assertWSConfig: (\n conf: unknown,\n path?: string,\n) => asserts conf is WorkspaceConfig = (\n conf: unknown,\n path?: string,\n) => {\n if (typeof conf === 'string') return conf\n\n if (Array.isArray(conf)) {\n for (const c of conf) {\n if (typeof c !== 'string') {\n throw error('Invalid workspace definition', {\n path,\n found: c,\n wanted: 'string',\n })\n }\n }\n return\n }\n\n if (conf && typeof conf === 'object') {\n for (const [group, value] of Object.entries(conf)) {\n if (typeof value === 'string') continue\n if (Array.isArray(value)) {\n for (const c of value) {\n if (typeof c !== 'string') {\n throw error('Invalid workspace definition', {\n path,\n name: group,\n found: c,\n wanted: 'string',\n })\n }\n }\n continue\n }\n throw error('Invalid workspace definition', {\n path,\n name: group,\n found: value,\n wanted: 'string | string[]',\n })\n }\n return\n }\n\n throw error('Invalid workspace definition', {\n path,\n found: conf,\n wanted:\n 'string | string[] | { [group: string]: string | string[] }',\n })\n}\n\nexport type MonorepoOptions = {\n /**\n * A {@link PackageJson} object, for sharing manifest caches\n */\n packageJson?: PackageJson\n /**\n * A {@link PathScurry} object, for use in globs\n */\n scurry?: PathScurry\n /** Parsed normalized contents of a `vlt-workspaces.json` file */\n config?: WorkspaceConfigObject\n /**\n * If set, then {@link Monorepo#load} will be called immediately with\n * this argument.\n */\n load?: LoadQuery\n}\n\n/**\n * Class representing a Monorepo containing multiple workspaces.\n *\n * Does not automatically look up the root, but that can be provided by\n * running `Config.load()`, since it stops seeking the route when a\n * `vlt-workspaces.json` file is encountered.\n */\nexport class Monorepo {\n /** The project root where vlt-workspaces.json is found */\n projectRoot: string\n /** Scurry object to cache all filesystem calls (mostly globs) */\n scurry: PathScurry\n\n // maps both name and path to the workspace objects\n #workspaces = new Map<string, Workspace>()\n #groups = new Map<string, Set<Workspace>>()\n #config?: WorkspaceConfigObject\n packageJson: PackageJson\n\n /**\n * Number of {@link Workspace} objects loaded in this Monorepo\n */\n get size(): number {\n return [...this.values()].length\n }\n\n constructor(projectRoot: string, options: MonorepoOptions = {}) {\n this.projectRoot = resolve(projectRoot)\n this.scurry = options.scurry ?? new PathScurry(projectRoot)\n this.packageJson = options.packageJson ?? new PackageJson()\n this.#config = options.config\n if (options.load) this.load(options.load)\n }\n\n /**\n * Load the workspace definitions from vlt-workspaces.json,\n * canonicalizing the result into the effective `{[group:string]:string[]}`\n * form.\n *\n * Eg:\n * - `\"src/*\"` => `{packages:[\"src/*\"]}`\n * - `{\"apps\": \"src/*\"}` => `{apps: [\"src/*\"]}`\n */\n get config(): WorkspaceConfigObject {\n if (this.#config) return this.#config\n const file = resolve(this.projectRoot, 'vlt-workspaces.json')\n let confData: string\n try {\n confData = readFileSync(file, 'utf8')\n } catch (er) {\n throw error('Not in a monorepo, no vlt-workspaces.json found', {\n path: this.projectRoot,\n cause: er as Error,\n })\n }\n let parsed: unknown\n try {\n parsed = parse(confData)\n } catch (er) {\n throw error('Invalid vlt-workspaces.json file', {\n path: this.projectRoot,\n cause: er as Error,\n })\n }\n this.#config = asWSConfig(parsed, file)\n return this.#config\n }\n\n /**\n * Iterating the Monorepo object yields the workspace objects, in as close to\n * topological dependency order as possible.\n */\n *[Symbol.iterator](): Generator<Workspace, void, void> {\n const [ws] = [...this.values()]\n if (!ws) return\n // leverage the fact that graphRun returns results in\n // as close to topological order as possible.\n for (const workspace of this.runSync(() => {}).keys()) {\n yield workspace\n }\n }\n\n /**\n * Iterating the Monorepo object yields the workspace objects, in as close to\n * topological dependency order as possible.\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<\n Workspace,\n void,\n void\n > {\n const [ws] = [...this.values()]\n if (!ws) return\n for (const workspace of (await this.run(() => {})).keys()) {\n yield workspace\n }\n }\n\n /**\n * By default, loads all workspaces reachable in the Monorepo.\n *\n * If provided with one (`string`)or more (`string[]`) group names in\n * the {@link LoadQuery#groups} field, then only Workspaces in the named\n * group(s) will be considered. Note that group names are unique string\n * matches, not globs.\n *\n * If provided with a set of arbitrary path arguments, then only paths\n * patching the provided pattern(s) will be included.\n *\n * These two options intersect, so\n * `load({groups:'foo', paths:'./foo/[xy]*'})` will only load the workspaces\n * in the group `foo` that match the paths glob.\n */\n load(query: LoadQuery = {}): this {\n const paths = new Set(\n typeof query.paths === 'string' ?\n [query.paths]\n : (query.paths ?? []),\n )\n const groups = new Set(\n typeof query.groups === 'string' ?\n [query.groups]\n : (query.groups ?? []),\n )\n\n const groupsExpanded: Record<string, Set<string>> = {}\n for (const [group, pattern] of Object.entries(this.config)) {\n if (groups.size && !groups.has(group)) continue\n groupsExpanded[group] = this.#glob(pattern)\n }\n const filter = paths.size ? this.#glob([...paths]) : paths\n\n // if we specified paths, but none matched, nothing to do\n if (paths.size && !filter.size) return this\n\n for (const [group, matches] of Object.entries(groupsExpanded)) {\n for (const path of matches) {\n if (filter.size && !filter.has(path)) continue\n this.#loadWS(path, group)\n }\n }\n\n return this\n }\n\n // Either load a workspace from disk, or from our internal set,\n // and assign it to the named group\n #loadWS(path: string, group?: string): Workspace {\n const fullpath = resolve(this.projectRoot, path)\n const loaded = this.#workspaces.get(fullpath)\n if (loaded) return loaded\n const fromCache = workspaceCache.get(fullpath)\n const manifest =\n fromCache?.manifest ?? this.packageJson.read(fullpath)\n const ws = fromCache ?? new Workspace(path, manifest, fullpath)\n if (group) ws.groups.push(group)\n this.#workspaces.set(ws.fullpath, ws)\n this.#workspaces.set(ws.path, ws)\n this.#workspaces.set(ws.name, ws)\n for (const name of ws.groups) {\n const group = this.#groups.get(name) ?? new Set()\n group.add(ws)\n this.#groups.set(name, group)\n }\n return ws\n }\n\n // can't be cached, because it's dependent on the matches set\n // but still worthwhile to have it defined in one place\n #globOptions(matches: Set<string>): GlobOptionsWithFileTypesFalse {\n // if the entry or any of its parent dirs are already matched,\n // then we should not explore further down that directory tree.\n // if we hit the projectRoot then stop searching.\n const inMatches = (p?: Path): boolean => {\n return (\n !!p?.relativePosix() &&\n (matches.has(p.relativePosix()) || inMatches(p.parent))\n )\n }\n\n return {\n root: this.projectRoot,\n cwd: this.projectRoot,\n posix: true,\n scurry: this.scurry,\n withFileTypes: false,\n ignore: {\n childrenIgnored: p =>\n basename(p.relativePosix()) === 'node_modules' ||\n inMatches(p),\n // ignore if fails to load package.json\n ignored: p => {\n p.lstatSync()\n const rel = p.relativePosix()\n if (!rel) return true\n const maybeDelete: string[] = []\n for (const m of matches) {\n if (rel.startsWith(m + '/')) return true\n if (m.startsWith(rel + '/')) {\n maybeDelete.push(m)\n }\n }\n if (!p.isDirectory()) return true\n const pj = p.resolve('package.json').lstatSync()\n if (!pj?.isFile()) return true\n try {\n this.packageJson.read(p.fullpath())\n } catch {\n return true\n }\n for (const m of maybeDelete) {\n matches.delete(m)\n }\n matches.add(rel)\n return false\n },\n },\n }\n }\n\n #glob(pattern: string[] | string) {\n const matches = new Set<string>()\n globSync(pattern, this.#globOptions(matches))\n return matches\n }\n\n /**\n * Return the array of workspace dependencies that are found in\n * the loaded set, for use in calculating dependency graph order for\n * build operations.\n *\n * This does *not* get the full set of dependencies, or expand any\n * `workspace:` dependencies that are not loaded.\n *\n * Call with the `forceLoad` param set to `true` to attempt a full\n * load if any deps are not currently loaded.\n */\n getDeps(ws: Workspace, forceLoad = false): Workspace[] {\n // load manifest and find workspace: deps\n // filter by those loaded\n const { manifest } = ws\n const depWorkspaces: Workspace[] = []\n let didForceLoad = false\n for (const depType of [\n 'dependencies',\n 'devDependencies',\n 'optionalDependencies',\n 'peerDependencies',\n ]) {\n const deps = manifest[depType] as Manifest['dependencies']\n if (!deps) continue\n for (const [dep, spec] of Object.entries(deps)) {\n if (spec.startsWith('workspace:')) {\n let depWS = this.#workspaces.get(dep)\n if (!depWS) {\n if (!forceLoad) continue\n if (didForceLoad) continue\n didForceLoad = true\n this.load()\n depWS = this.#workspaces.get(dep)\n if (!depWS) continue\n }\n depWorkspaces.push(depWS)\n }\n }\n }\n return depWorkspaces\n }\n\n /** @todo */\n onCycle(\n _ws: Workspace,\n _cycle: Workspace[],\n _depPath: Workspace[],\n ) {\n // XXX - process logging? Need to say something like:\n // Cyclical workspace dependency warning!\n // When evaluating dependency ${ws.name} via ${\n // path.map(ws => ws.name).join(' -> ')\n // }, a dependency cycle was detected: ${\n // cycle.map(ws => ws.name).join(' -> ')\n // }. Operation will continue, but dependency order not guaranteed.`\n }\n\n /**\n * Return the set of workspaces in the named group.\n * If the group is not one we know about, then undefined is returned.\n */\n group(group: string) {\n return this.#groups.get(group)\n }\n\n /**\n * Get a loaded workspace by path or name.\n *\n * Note that this can only return workspaces that were ingested via a\n * previous call to {@link Monorepo#load}.\n */\n get(nameOrPath: string) {\n return this.#workspaces.get(nameOrPath)\n }\n\n /**\n * get the list of all loaded workspace names used as keys\n */\n *names() {\n for (const [key, ws] of this.#workspaces) {\n if (key === ws.name) yield key\n }\n }\n\n /**\n * get the list of all loaded workspace paths used as keys\n */\n *paths() {\n for (const [key, ws] of this.#workspaces) {\n if (key === ws.path) yield key\n }\n }\n\n /**\n * get the workspace objects in no particular order.\n * this is ever so slightly faster than iterating, because it doesn't\n * explore the graph to yield results in topological dependency order,\n * and should be used instead when order doesn't matter.\n */\n *values() {\n const seen = new Set<string>()\n for (const ws of this.#workspaces.values()) {\n if (seen.has(ws.fullpath)) continue\n seen.add(ws.fullpath)\n yield ws\n }\n }\n\n /**\n * Get all the keys (package names and paths) for loaded workspaces.\n * Union of {@link Monorepo#names} and {@link Monorepo#paths}\n */\n *keys() {\n for (const ws of this.values()) {\n yield ws.path\n if (ws.name !== ws.path) yield ws.name\n }\n }\n\n /**\n * Filter the monorepo object yielding the workspace objects that matches\n * either of the {@link WorkspacesLoadedConfig} options provided, in as close\n * to topological dependency order as possible.\n */\n *filter({\n workspace: namesOrPaths,\n 'workspace-group': groupName,\n }: WorkspacesLoadedConfig) {\n const globPatternChecks = namesOrPaths?.map(glob =>\n minimatch.filter(posix.join(glob)),\n )\n for (const ws of this) {\n // check if any group has any of the provided group names\n if (groupName?.some(i => ws.groups.includes(i))) {\n yield ws\n continue\n }\n // check if any workspace-provided name directly matches any of the\n // configured workspaces by either name or file path\n if (\n namesOrPaths\n ?.map(i => posix.join(i))\n .some(i => ws.keys.includes(i))\n ) {\n yield ws\n continue\n }\n // check if one of the workspace values are matching glob patterns\n if (\n ws.keys.some(key => globPatternChecks?.some(fn => fn(key)))\n ) {\n yield ws\n }\n }\n }\n\n /**\n * Run an operation asynchronously over all loaded workspaces\n *\n * If the `forceLoad` param is true, then it will attempt to do a full load\n * when encountering a `workspace:` dependency that isn't loaded.\n *\n * Note that because the return type appears in the parameters of the\n * operation function, it must be set explicitly either in the operation\n * function signature or by calling `run<MyType>` or it'll fall back to\n * `unknown`, similar to `Array.reduce()`, and for the same reason.\n */\n async run<R>(\n operation: (\n s: Workspace,\n signal: AbortSignal,\n depResults: DepResults<Workspace, R>,\n ) => Promise<R> | R,\n forceLoad = false,\n ) {\n const [ws, ...rest] = [...this.#workspaces.values()]\n if (!ws) {\n throw error('No workspaces loaded', undefined, this.run)\n }\n\n return graphRun<Workspace, R>({\n graph: [ws, ...rest],\n getDeps: ws => this.getDeps(ws, forceLoad),\n visit: async (ws, signal, _, depResults) =>\n await operation(ws, signal, depResults),\n onCycle: (ws, cycle, path) => this.onCycle(ws, cycle, path),\n })\n }\n\n /**\n * Run an operation synchronously over all loaded workspaces\n *\n * If the `forceLoad` param is true, then it will attempt to do a full load\n * when encountering a `workspace:` dependency that isn't loaded.\n *\n * Note that because the return type appears in the parameters of the\n * operation function, it must be set explicitly either in the operation\n * function signature or by calling `runSync<MyType>` or it'll fall back to\n * `unknown`, similar to `Array.reduce()`, and for the same reason.\n */\n runSync<R>(\n operation: (\n s: Workspace,\n signal: AbortSignal,\n depResults: DepResults<Workspace, R>,\n ) => R,\n forceLoad = false,\n ) {\n const [ws, ...rest] = [...this.#workspaces.values()]\n if (!ws) {\n throw error('No workspaces loaded', undefined, this.run)\n }\n\n return graphRunSync<Workspace, R>({\n graph: [ws, ...rest],\n getDeps: ws => this.getDeps(ws, forceLoad),\n visit: (ws, signal, _, depResults) =>\n operation(ws, signal, depResults),\n onCycle: (ws, cycle, path) => this.onCycle(ws, cycle, path),\n })\n }\n\n /**\n * Convenience method to instantiate and load in one call.\n * Returns undefined if the project is not a monorepo workspaces\n * root, otherwise returns the loaded Monorepo.\n */\n static maybeLoad(\n projectRoot: string,\n options: MonorepoOptions = { load: {} },\n ) {\n try {\n if (\n !statSync(\n resolve(projectRoot, 'vlt-workspaces.json'),\n ).isFile()\n ) {\n return\n }\n } catch {\n return\n }\n const { load = {} } = options\n return new Monorepo(projectRoot, { ...options, load })\n }\n\n /**\n * Convenience method to instantiate and load in one call.\n * Throws if called on a directory that is not a workspaces root.\n */\n static load(\n projectRoot: string,\n options: MonorepoOptions = { load: {} },\n ) {\n const { load = {} } = options\n return new Monorepo(projectRoot, { ...options, load })\n }\n}\n\nexport const workspaceCache = new Map<string, Workspace>()\n\n/**\n * Class representing a single Workspace in a {@link Monorepo}\n */\nexport class Workspace {\n id: DepID\n path: string\n fullpath: string\n manifest: Manifest\n groups: string[] = []\n name: string\n #keys?: string[]\n\n constructor(path: string, manifest: Manifest, fullpath: string) {\n this.id = joinDepIDTuple(['workspace', path])\n workspaceCache.set(fullpath, this)\n this.path = path\n this.fullpath = fullpath\n this.manifest = manifest\n this.name = manifest.name ?? path\n }\n\n get keys(): string[] {\n if (this.#keys) {\n return this.#keys\n }\n this.#keys = [this.name, this.path, this.fullpath]\n return this.#keys\n }\n}\n", "import expand from 'brace-expansion'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { AST, ExtglobType } from './ast.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\ntype Platform =\n | 'aix'\n | 'android'\n | 'darwin'\n | 'freebsd'\n | 'haiku'\n | 'linux'\n | 'openbsd'\n | 'sunos'\n | 'win32'\n | 'cygwin'\n | 'netbsd'\n\nexport interface MinimatchOptions {\n nobrace?: boolean\n nocomment?: boolean\n nonegate?: boolean\n debug?: boolean\n noglobstar?: boolean\n noext?: boolean\n nonull?: boolean\n windowsPathsNoEscape?: boolean\n allowWindowsEscape?: boolean\n partial?: boolean\n dot?: boolean\n nocase?: boolean\n nocaseMagicOnly?: boolean\n magicalBraces?: boolean\n matchBase?: boolean\n flipNegate?: boolean\n preserveMultipleSlashes?: boolean\n optimizationLevel?: number\n platform?: Platform\n windowsNoMagicRoot?: boolean\n}\n\nexport const minimatch = (\n p: string,\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n assertValidPattern(pattern)\n\n // shortcut: comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n return false\n }\n\n return new Minimatch(pattern, options).match(p)\n}\n\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?\\*\\[\\(]*)$/\nconst starDotExtTest = (ext: string) => (f: string) =>\n !f.startsWith('.') && f.endsWith(ext)\nconst starDotExtTestDot = (ext: string) => (f: string) => f.endsWith(ext)\nconst starDotExtTestNocase = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => !f.startsWith('.') && f.toLowerCase().endsWith(ext)\n}\nconst starDotExtTestNocaseDot = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => f.toLowerCase().endsWith(ext)\n}\nconst starDotStarRE = /^\\*+\\.\\*+$/\nconst starDotStarTest = (f: string) => !f.startsWith('.') && f.includes('.')\nconst starDotStarTestDot = (f: string) =>\n f !== '.' && f !== '..' && f.includes('.')\nconst dotStarRE = /^\\.\\*+$/\nconst dotStarTest = (f: string) => f !== '.' && f !== '..' && f.startsWith('.')\nconst starRE = /^\\*+$/\nconst starTest = (f: string) => f.length !== 0 && !f.startsWith('.')\nconst starTestDot = (f: string) => f.length !== 0 && f !== '.' && f !== '..'\nconst qmarksRE = /^\\?+([^+@!?\\*\\[\\(]*)?$/\nconst qmarksTestNocase = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestNocaseDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTest = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTestNoExt = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && !f.startsWith('.')\n}\nconst qmarksTestNoExtDot = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && f !== '.' && f !== '..'\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n typeof process === 'object' && process\n ? (typeof process.env === 'object' &&\n process.env &&\n process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n process.platform\n : 'posix'\n) as Platform\ntype Sep = '\\\\' | '/'\nconst path: { [k: string]: { sep: Sep } } = {\n win32: { sep: '\\\\' },\n posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed. Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?'\n\nexport const filter =\n (pattern: string, options: MinimatchOptions = {}) =>\n (p: string) =>\n minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n return minimatch\n }\n\n const orig = minimatch\n\n const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n orig(p, pattern, ext(def, options))\n\n return Object.assign(m, {\n Minimatch: class Minimatch extends orig.Minimatch {\n constructor(pattern: string, options: MinimatchOptions = {}) {\n super(pattern, ext(def, options))\n }\n static defaults(options: MinimatchOptions) {\n return orig.defaults(ext(def, options)).Minimatch\n }\n },\n\n AST: class AST extends orig.AST {\n /* c8 ignore start */\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {}\n ) {\n super(type, parent, ext(def, options))\n }\n /* c8 ignore stop */\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n return orig.AST.fromGlob(pattern, ext(def, options))\n }\n },\n\n unescape: (\n s: string,\n options: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n ) => orig.unescape(s, ext(def, options)),\n\n escape: (\n s: string,\n options: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n ) => orig.escape(s, ext(def, options)),\n\n filter: (pattern: string, options: MinimatchOptions = {}) =>\n orig.filter(pattern, ext(def, options)),\n\n defaults: (options: MinimatchOptions) => orig.defaults(ext(def, options)),\n\n makeRe: (pattern: string, options: MinimatchOptions = {}) =>\n orig.makeRe(pattern, ext(def, options)),\n\n braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n orig.braceExpand(pattern, ext(def, options)),\n\n match: (list: string[], pattern: string, options: MinimatchOptions = {}) =>\n orig.match(list, pattern, ext(def, options)),\n\n sep: orig.sep,\n GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n assertValidPattern(pattern)\n\n // Thanks to Yeting Li <https://github.com/yetingli> for\n // improving this regexp to avoid a ReDOS vulnerability.\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n // shortcut. no need to expand.\n return [pattern]\n }\n\n return expand(pattern)\n}\nminimatch.braceExpand = braceExpand\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion. Otherwise, any series\n// of * is equivalent to a single *. Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\n\nexport const makeRe = (pattern: string, options: MinimatchOptions = {}) =>\n new Minimatch(pattern, options).makeRe()\nminimatch.makeRe = makeRe\n\nexport const match = (\n list: string[],\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n const mm = new Minimatch(pattern, options)\n list = list.filter(f => mm.match(f))\n if (mm.options.nonull && !list.length) {\n list.push(pattern)\n }\n return list\n}\nminimatch.match = match\n\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\nexport type MMRegExp = RegExp & {\n _src?: string\n _glob?: string\n}\n\nexport type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR\nexport type ParseReturn = ParseReturnFiltered | false\n\nexport class Minimatch {\n options: MinimatchOptions\n set: ParseReturnFiltered[][]\n pattern: string\n\n windowsPathsNoEscape: boolean\n nonegate: boolean\n negate: boolean\n comment: boolean\n empty: boolean\n preserveMultipleSlashes: boolean\n partial: boolean\n globSet: string[]\n globParts: string[][]\n nocase: boolean\n\n isWindows: boolean\n platform: Platform\n windowsNoMagicRoot: boolean\n\n regexp: false | null | MMRegExp\n constructor(pattern: string, options: MinimatchOptions = {}) {\n assertValidPattern(pattern)\n\n options = options || {}\n this.options = options\n this.pattern = pattern\n this.platform = options.platform || defaultPlatform\n this.isWindows = this.platform === 'win32'\n this.windowsPathsNoEscape =\n !!options.windowsPathsNoEscape || options.allowWindowsEscape === false\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, '/')\n }\n this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n this.regexp = null\n this.negate = false\n this.nonegate = !!options.nonegate\n this.comment = false\n this.empty = false\n this.partial = !!options.partial\n this.nocase = !!this.options.nocase\n this.windowsNoMagicRoot =\n options.windowsNoMagicRoot !== undefined\n ? options.windowsNoMagicRoot\n : !!(this.isWindows && this.nocase)\n\n this.globSet = []\n this.globParts = []\n this.set = []\n\n // make the set of regexps etc.\n this.make()\n }\n\n hasMagic(): boolean {\n if (this.options.magicalBraces && this.set.length > 1) {\n return true\n }\n for (const pattern of this.set) {\n for (const part of pattern) {\n if (typeof part !== 'string') return true\n }\n }\n return false\n }\n\n debug(..._: any[]) {}\n\n make() {\n const pattern = this.pattern\n const options = this.options\n\n // empty patterns and comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n this.comment = true\n return\n }\n\n if (!pattern) {\n this.empty = true\n return\n }\n\n // step 1: figure out negation, etc.\n this.parseNegate()\n\n // step 2: expand braces\n this.globSet = [...new Set(this.braceExpand())]\n\n if (options.debug) {\n this.debug = (...args: any[]) => console.error(...args)\n }\n\n this.debug(this.pattern, this.globSet)\n\n // step 3: now we have a set, so turn each one into a series of\n // path-portion matching patterns.\n // These will be regexps, except in the case of \"**\", which is\n // set to the GLOBSTAR object for globstar behavior,\n // and will not contain any / characters\n //\n // First, we preprocess to make the glob pattern sets a bit simpler\n // and deduped. There are some perf-killing patterns that can cause\n // problems with a glob walk, but we can simplify them down a bit.\n const rawGlobParts = this.globSet.map(s => this.slashSplit(s))\n this.globParts = this.preprocess(rawGlobParts)\n this.debug(this.pattern, this.globParts)\n\n // glob --> regexps\n let set = this.globParts.map((s, _, __) => {\n if (this.isWindows && this.windowsNoMagicRoot) {\n // check if it's a drive or unc path.\n const isUNC =\n s[0] === '' &&\n s[1] === '' &&\n (s[2] === '?' || !globMagic.test(s[2])) &&\n !globMagic.test(s[3])\n const isDrive = /^[a-z]:/i.test(s[0])\n if (isUNC) {\n return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]\n } else if (isDrive) {\n return [s[0], ...s.slice(1).map(ss => this.parse(ss))]\n }\n }\n return s.map(ss => this.parse(ss))\n })\n\n this.debug(this.pattern, set)\n\n // filter out everything that didn't compile properly.\n this.set = set.filter(\n s => s.indexOf(false) === -1\n ) as ParseReturnFiltered[][]\n\n // do not treat the ? in UNC paths as magic\n if (this.isWindows) {\n for (let i = 0; i < this.set.length; i++) {\n const p = this.set[i]\n if (\n p[0] === '' &&\n p[1] === '' &&\n this.globParts[i][2] === '?' &&\n typeof p[3] === 'string' &&\n /^[a-z]:$/i.test(p[3])\n ) {\n p[2] = '?'\n }\n }\n }\n\n this.debug(this.pattern, this.set)\n }\n\n // various transforms to equivalent pattern sets that are\n // faster to process in a filesystem walk. The goal is to\n // eliminate what we can, and push all ** patterns as far\n // to the right as possible, even if it increases the number\n // of patterns that we have to process.\n preprocess(globParts: string[][]) {\n // if we're not in globstar mode, then turn all ** into *\n if (this.options.noglobstar) {\n for (let i = 0; i < globParts.length; i++) {\n for (let j = 0; j < globParts[i].length; j++) {\n if (globParts[i][j] === '**') {\n globParts[i][j] = '*'\n }\n }\n }\n }\n\n const { optimizationLevel = 1 } = this.options\n\n if (optimizationLevel >= 2) {\n // aggressive optimization for the purpose of fs walking\n globParts = this.firstPhasePreProcess(globParts)\n globParts = this.secondPhasePreProcess(globParts)\n } else if (optimizationLevel >= 1) {\n // just basic optimizations to remove some .. parts\n globParts = this.levelOneOptimize(globParts)\n } else {\n // just collapse multiple ** portions into one\n globParts = this.adjascentGlobstarOptimize(globParts)\n }\n\n return globParts\n }\n\n // just get rid of adjascent ** portions\n adjascentGlobstarOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let i = gs\n while (parts[i + 1] === '**') {\n i++\n }\n if (i !== gs) {\n parts.splice(gs, i - gs)\n }\n }\n return parts\n })\n }\n\n // get rid of adjascent ** and resolve .. portions\n levelOneOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n parts = parts.reduce((set: string[], part) => {\n const prev = set[set.length - 1]\n if (part === '**' && prev === '**') {\n return set\n }\n if (part === '..') {\n if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n set.pop()\n return set\n }\n }\n set.push(part)\n return set\n }, [])\n return parts.length === 0 ? [''] : parts\n })\n }\n\n levelTwoFileOptimize(parts: string | string[]) {\n if (!Array.isArray(parts)) {\n parts = this.slashSplit(parts)\n }\n let didSomething: boolean = false\n do {\n didSomething = false\n // <pre>/<e>/<rest> -> <pre>/<rest>\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i]\n // don't squeeze out UNC patterns\n if (i === 1 && p === '' && parts[0] === '') continue\n if (p === '.' || p === '') {\n didSomething = true\n parts.splice(i, 1)\n i--\n }\n }\n if (\n parts[0] === '.' &&\n parts.length === 2 &&\n (parts[1] === '.' || parts[1] === '')\n ) {\n didSomething = true\n parts.pop()\n }\n }\n\n // <pre>/<p>/../<rest> -> <pre>/<rest>\n let dd: number = 0\n while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n const p = parts[dd - 1]\n if (p && p !== '.' && p !== '..' && p !== '**') {\n didSomething = true\n parts.splice(dd - 1, 2)\n dd -= 2\n }\n }\n } while (didSomething)\n return parts.length === 0 ? [''] : parts\n }\n\n // First phase: single-pattern processing\n // <pre> is 1 or more portions\n // <rest> is 1 or more portions\n // <p> is any portion other than ., .., '', or **\n // <e> is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}\n // <pre>/<e>/<rest> -> <pre>/<rest>\n // <pre>/<p>/../<rest> -> <pre>/<rest>\n // **/**/<rest> -> **/<rest>\n //\n // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow\n // this WOULD be allowed if ** did follow symlinks, or * didn't\n firstPhasePreProcess(globParts: string[][]) {\n let didSomething = false\n do {\n didSomething = false\n // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n // <pre>/**/**/<rest> -> <pre>/**/<rest>\n gss++\n }\n // eg, if gs is 2 and gss is 4, that means we have 3 **\n // parts, and can remove 2 of them.\n if (gss > gs) {\n parts.splice(gs + 1, gss - gs)\n }\n\n let next = parts[gs + 1]\n const p = parts[gs + 2]\n const p2 = parts[gs + 3]\n if (next !== '..') continue\n if (\n !p ||\n p === '.' ||\n p === '..' ||\n !p2 ||\n p2 === '.' ||\n p2 === '..'\n ) {\n continue\n }\n didSomething = true\n // edit parts in place, and push the new one\n parts.splice(gs, 1)\n const other = parts.slice(0)\n other[gs] = '**'\n globParts.push(other)\n gs--\n }\n\n // <pre>/<e>/<rest> -> <pre>/<rest>\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i]\n // don't squeeze out UNC patterns\n if (i === 1 && p === '' && parts[0] === '') continue\n if (p === '.' || p === '') {\n didSomething = true\n parts.splice(i, 1)\n i--\n }\n }\n if (\n parts[0] === '.' &&\n parts.length === 2 &&\n (parts[1] === '.' || parts[1] === '')\n ) {\n didSomething = true\n parts.pop()\n }\n }\n\n // <pre>/<p>/../<rest> -> <pre>/<rest>\n let dd: number = 0\n while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n const p = parts[dd - 1]\n if (p && p !== '.' && p !== '..' && p !== '**') {\n didSomething = true\n const needDot = dd === 1 && parts[dd + 1] === '**'\n const splin = needDot ? ['.'] : []\n parts.splice(dd - 1, 2, ...splin)\n if (parts.length === 0) parts.push('')\n dd -= 2\n }\n }\n }\n } while (didSomething)\n\n return globParts\n }\n\n // second phase: multi-pattern dedupes\n // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>\n // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>\n // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>\n //\n // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>\n // ^-- not valid because ** doens't follow symlinks\n secondPhasePreProcess(globParts: string[][]): string[][] {\n for (let i = 0; i < globParts.length - 1; i++) {\n for (let j = i + 1; j < globParts.length; j++) {\n const matched = this.partsMatch(\n globParts[i],\n globParts[j],\n !this.preserveMultipleSlashes\n )\n if (matched) {\n globParts[i] = []\n globParts[j] = matched\n break\n }\n }\n }\n return globParts.filter(gs => gs.length)\n }\n\n partsMatch(\n a: string[],\n b: string[],\n emptyGSMatch: boolean = false\n ): false | string[] {\n let ai = 0\n let bi = 0\n let result: string[] = []\n let which: string = ''\n while (ai < a.length && bi < b.length) {\n if (a[ai] === b[bi]) {\n result.push(which === 'b' ? b[bi] : a[ai])\n ai++\n bi++\n } else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n result.push(a[ai])\n ai++\n } else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n result.push(b[bi])\n bi++\n } else if (\n a[ai] === '*' &&\n b[bi] &&\n (this.options.dot || !b[bi].startsWith('.')) &&\n b[bi] !== '**'\n ) {\n if (which === 'b') return false\n which = 'a'\n result.push(a[ai])\n ai++\n bi++\n } else if (\n b[bi] === '*' &&\n a[ai] &&\n (this.options.dot || !a[ai].startsWith('.')) &&\n a[ai] !== '**'\n ) {\n if (which === 'a') return false\n which = 'b'\n result.push(b[bi])\n ai++\n bi++\n } else {\n return false\n }\n }\n // if we fall out of the loop, it means they two are identical\n // as long as their lengths match\n return a.length === b.length && result\n }\n\n parseNegate() {\n if (this.nonegate) return\n\n const pattern = this.pattern\n let negate = false\n let negateOffset = 0\n\n for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n negate = !negate\n negateOffset++\n }\n\n if (negateOffset) this.pattern = pattern.slice(negateOffset)\n this.negate = negate\n }\n\n // set partial to true to test if, for example,\n // \"/a/b\" matches the start of \"/*/b/*/d\"\n // Partial means, if you run out of file before you run\n // out of pattern, then that's fine, as long as all\n // the parts match.\n matchOne(file: string[], pattern: ParseReturn[], partial: boolean = false) {\n const options = this.options\n\n // UNC paths like //?/X:/... can match X:/... and vice versa\n // Drive letters in absolute drive or unc paths are always compared\n // case-insensitively.\n if (this.isWindows) {\n const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n const fileUNC =\n !fileDrive &&\n file[0] === '' &&\n file[1] === '' &&\n file[2] === '?' &&\n /^[a-z]:$/i.test(file[3])\n\n const patternDrive =\n typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n const patternUNC =\n !patternDrive &&\n pattern[0] === '' &&\n pattern[1] === '' &&\n pattern[2] === '?' &&\n typeof pattern[3] === 'string' &&\n /^[a-z]:$/i.test(pattern[3])\n\n const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined\n const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined\n if (typeof fdi === 'number' && typeof pdi === 'number') {\n const [fd, pd]: [string, string] = [file[fdi], pattern[pdi] as string]\n if (fd.toLowerCase() === pd.toLowerCase()) {\n pattern[pdi] = fd\n if (pdi > fdi) {\n pattern = pattern.slice(pdi)\n } else if (fdi > pdi) {\n file = file.slice(fdi)\n }\n }\n }\n }\n\n // resolve and reduce . and .. portions in the file as well.\n // dont' need to do the second phase, because it's only one string[]\n const { optimizationLevel = 1 } = this.options\n if (optimizationLevel >= 2) {\n file = this.levelTwoFileOptimize(file)\n }\n\n this.debug('matchOne', this, { file, pattern })\n this.debug('matchOne', file.length, pattern.length)\n\n for (\n var fi = 0, pi = 0, fl = file.length, pl = pattern.length;\n fi < fl && pi < pl;\n fi++, pi++\n ) {\n this.debug('matchOne loop')\n var p = pattern[pi]\n var f = file[fi]\n\n this.debug(pattern, p, f)\n\n // should be impossible.\n // some invalid regexp stuff in the set.\n /* c8 ignore start */\n if (p === false) {\n return false\n }\n /* c8 ignore stop */\n\n if (p === GLOBSTAR) {\n this.debug('GLOBSTAR', [pattern, p, f])\n\n // \"**\"\n // a/**/b/**/c would match the following:\n // a/b/x/y/z/c\n // a/x/y/z/b/c\n // a/b/x/b/x/c\n // a/b/c\n // To do this, take the rest of the pattern after\n // the **, and see if it would match the file remainder.\n // If so, return success.\n // If not, the ** \"swallows\" a segment, and try again.\n // This is recursively awful.\n //\n // a/**/b/**/c matching a/b/x/y/z/c\n // - a matches a\n // - doublestar\n // - matchOne(b/x/y/z/c, b/**/c)\n // - b matches b\n // - doublestar\n // - matchOne(x/y/z/c, c) -> no\n // - matchOne(y/z/c, c) -> no\n // - matchOne(z/c, c) -> no\n // - matchOne(c, c) yes, hit\n var fr = fi\n var pr = pi + 1\n if (pr === pl) {\n this.debug('** at the end')\n // a ** at the end will just swallow the rest.\n // We have found a match.\n // however, it will not swallow /.x, unless\n // options.dot is set.\n // . and .. are *never* matched by **, for explosively\n // exponential reasons.\n for (; fi < fl; fi++) {\n if (\n file[fi] === '.' ||\n file[fi] === '..' ||\n (!options.dot && file[fi].charAt(0) === '.')\n )\n return false\n }\n return true\n }\n\n // ok, let's see if we can swallow whatever we can.\n while (fr < fl) {\n var swallowee = file[fr]\n\n this.debug('\\nglobstar while', file, fr, pattern, pr, swallowee)\n\n // XXX remove this slice. Just pass the start index.\n if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {\n this.debug('globstar found match!', fr, fl, swallowee)\n // found a match.\n return true\n } else {\n // can't swallow \".\" or \"..\" ever.\n // can only swallow \".foo\" when explicitly asked.\n if (\n swallowee === '.' ||\n swallowee === '..' ||\n (!options.dot && swallowee.charAt(0) === '.')\n ) {\n this.debug('dot detected!', file, fr, pattern, pr)\n break\n }\n\n // ** swallows a segment, and continue.\n this.debug('globstar swallow a segment, and continue')\n fr++\n }\n }\n\n // no match was found.\n // However, in partial mode, we can't say this is necessarily over.\n /* c8 ignore start */\n if (partial) {\n // ran out of file\n this.debug('\\n>>> no match, partial?', file, fr, pattern, pr)\n if (fr === fl) {\n return true\n }\n }\n /* c8 ignore stop */\n return false\n }\n\n // something other than **\n // non-magic patterns just have to match exactly\n // patterns with magic have been turned into regexps.\n let hit: boolean\n if (typeof p === 'string') {\n hit = f === p\n this.debug('string match', p, f, hit)\n } else {\n hit = p.test(f)\n this.debug('pattern match', p, f, hit)\n }\n\n if (!hit) return false\n }\n\n // Note: ending in / means that we'll get a final \"\"\n // at the end of the pattern. This can only match a\n // corresponding \"\" at the end of the file.\n // If the file ends in /, then it can only match a\n // a pattern that ends in /, unless the pattern just\n // doesn't have any more for it. But, a/b/ should *not*\n // match \"a/b/*\", even though \"\" matches against the\n // [^/]*? pattern, except in partial mode, where it might\n // simply not be reached yet.\n // However, a/b/ should still satisfy a/*\n\n // now either we fell off the end of the pattern, or we're done.\n if (fi === fl && pi === pl) {\n // ran out of pattern and filename at the same time.\n // an exact hit!\n return true\n } else if (fi === fl) {\n // ran out of file, but still had pattern left.\n // this is ok if we're doing the match as part of\n // a glob fs traversal.\n return partial\n } else if (pi === pl) {\n // ran out of pattern, still have file left.\n // this is only acceptable if we're on the very last\n // empty segment of a file with a trailing slash.\n // a/* should match a/b/\n return fi === fl - 1 && file[fi] === ''\n\n /* c8 ignore start */\n } else {\n // should be unreachable.\n throw new Error('wtf?')\n }\n /* c8 ignore stop */\n }\n\n braceExpand() {\n return braceExpand(this.pattern, this.options)\n }\n\n parse(pattern: string): ParseReturn {\n assertValidPattern(pattern)\n\n const options = this.options\n\n // shortcuts\n if (pattern === '**') return GLOBSTAR\n if (pattern === '') return ''\n\n // far and away, the most common glob pattern parts are\n // *, *.*, and *.<ext> Add a fast check method for those.\n let m: RegExpMatchArray | null\n let fastTest: null | ((f: string) => boolean) = null\n if ((m = pattern.match(starRE))) {\n fastTest = options.dot ? starTestDot : starTest\n } else if ((m = pattern.match(starDotExtRE))) {\n fastTest = (\n options.nocase\n ? options.dot\n ? starDotExtTestNocaseDot\n : starDotExtTestNocase\n : options.dot\n ? starDotExtTestDot\n : starDotExtTest\n )(m[1])\n } else if ((m = pattern.match(qmarksRE))) {\n fastTest = (\n options.nocase\n ? options.dot\n ? qmarksTestNocaseDot\n : qmarksTestNocase\n : options.dot\n ? qmarksTestDot\n : qmarksTest\n )(m)\n } else if ((m = pattern.match(starDotStarRE))) {\n fastTest = options.dot ? starDotStarTestDot : starDotStarTest\n } else if ((m = pattern.match(dotStarRE))) {\n fastTest = dotStarTest\n }\n\n const re = AST.fromGlob(pattern, this.options).toMMPattern()\n if (fastTest && typeof re === 'object') {\n // Avoids overriding in frozen environments\n Reflect.defineProperty(re, 'test', { value: fastTest })\n }\n return re\n }\n\n makeRe() {\n if (this.regexp || this.regexp === false) return this.regexp\n\n // at this point, this.set is a 2d array of partial\n // pattern strings, or \"**\".\n //\n // It's better to use .match(). This function shouldn't\n // be used, really, but it's pretty convenient sometimes,\n // when you just want to work with a regex.\n const set = this.set\n\n if (!set.length) {\n this.regexp = false\n return this.regexp\n }\n const options = this.options\n\n const twoStar = options.noglobstar\n ? star\n : options.dot\n ? twoStarDot\n : twoStarNoDot\n const flags = new Set(options.nocase ? ['i'] : [])\n\n // regexpify non-globstar patterns\n // if ** is only item, then we just do one twoStar\n // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n // if ** is last, append (\\/twoStar|) to previous\n // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n // then filter out GLOBSTAR symbols\n let re = set\n .map(pattern => {\n const pp: (string | typeof GLOBSTAR)[] = pattern.map(p => {\n if (p instanceof RegExp) {\n for (const f of p.flags.split('')) flags.add(f)\n }\n return typeof p === 'string'\n ? regExpEscape(p)\n : p === GLOBSTAR\n ? GLOBSTAR\n : p._src\n }) as (string | typeof GLOBSTAR)[]\n pp.forEach((p, i) => {\n const next = pp[i + 1]\n const prev = pp[i - 1]\n if (p !== GLOBSTAR || prev === GLOBSTAR) {\n return\n }\n if (prev === undefined) {\n if (next !== undefined && next !== GLOBSTAR) {\n pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next\n } else {\n pp[i] = twoStar\n }\n } else if (next === undefined) {\n pp[i - 1] = prev + '(?:\\\\/|' + twoStar + ')?'\n } else if (next !== GLOBSTAR) {\n pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next\n pp[i + 1] = GLOBSTAR\n }\n })\n return pp.filter(p => p !== GLOBSTAR).join('/')\n })\n .join('|')\n\n // need to wrap in parens if we had more than one thing with |,\n // otherwise only the first will be anchored to ^ and the last to $\n const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']\n // must match entire pattern\n // ending in a * or ** will make it less strict.\n re = '^' + open + re + close + '$'\n\n // can match anything, as long as it's not this.\n if (this.negate) re = '^(?!' + re + ').+$'\n\n try {\n this.regexp = new RegExp(re, [...flags].join(''))\n /* c8 ignore start */\n } catch (ex) {\n // should be impossible\n this.regexp = false\n }\n /* c8 ignore stop */\n return this.regexp\n }\n\n slashSplit(p: string) {\n // if p starts with // on windows, we preserve that\n // so that UNC paths aren't broken. Otherwise, any number of\n // / characters are coalesced into one, unless\n // preserveMultipleSlashes is set to true.\n if (this.preserveMultipleSlashes) {\n return p.split('/')\n } else if (this.isWindows && /^\\/\\/[^\\/]+/.test(p)) {\n // add an extra '' for the one we lose\n return ['', ...p.split(/\\/+/)]\n } else {\n return p.split(/\\/+/)\n }\n }\n\n match(f: string, partial = this.partial) {\n this.debug('match', f, this.pattern)\n // short-circuit in the case of busted things.\n // comments, etc.\n if (this.comment) {\n return false\n }\n if (this.empty) {\n return f === ''\n }\n\n if (f === '/' && partial) {\n return true\n }\n\n const options = this.options\n\n // windows: need to use /, not \\\n if (this.isWindows) {\n f = f.split('\\\\').join('/')\n }\n\n // treat the test path as a set of pathparts.\n const ff = this.slashSplit(f)\n this.debug(this.pattern, 'split', ff)\n\n // just ONE of the pattern sets in this.set needs to match\n // in order for it to be valid. If negating, then just one\n // match means that we have failed.\n // Either way, return on the first hit.\n\n const set = this.set\n this.debug(this.pattern, 'set', set)\n\n // Find the basename of the path by looking for the last non-empty segment\n let filename: string = ff[ff.length - 1]\n if (!filename) {\n for (let i = ff.length - 2; !filename && i >= 0; i--) {\n filename = ff[i]\n }\n }\n\n for (let i = 0; i < set.length; i++) {\n const pattern = set[i]\n let file = ff\n if (options.matchBase && pattern.length === 1) {\n file = [filename]\n }\n const hit = this.matchOne(file, pattern, partial)\n if (hit) {\n if (options.flipNegate) {\n return true\n }\n return !this.negate\n }\n }\n\n // didn't get any hits. this is success if it's a negative\n // pattern, failure otherwise.\n if (options.flipNegate) {\n return false\n }\n return this.negate\n }\n\n static defaults(def: MinimatchOptions) {\n return minimatch.defaults(def).Minimatch\n }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js'\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\n/* c8 ignore stop */\nminimatch.AST = AST\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n", "const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: any) => void = (\n pattern: any\n): asserts pattern is string => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern')\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long')\n }\n}\n", "// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { <posix class>: [<translation>, /u flag required, negated]\nconst posixClasses: { [k: string]: [e: string, u: boolean, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n '[:cntrl:]': ['\\\\p{Cc}', true],\n '[:digit:]': ['\\\\p{Nd}', true],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n '[:lower:]': ['\\\\p{Ll}', true],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}', true],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n '[:upper:]': ['\\\\p{Lu}', true],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n '[:xdigit:]': ['A-Fa-f0-9', false],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n// escape all regexp magic characters\nconst regexpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges: string[]): string => ranges.join('')\n\nexport type ParseClassResult = [\n src: string,\n uFlag: boolean,\n consumed: number,\n hasMagic: boolean\n]\n\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (\n glob: string,\n position: number\n): ParseClassResult => {\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let uflag = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = glob.charAt(i)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return ['$.', false, glob.length - pos, true]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n uflag = uflag || u\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (c > rangeStart) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c))\n } else if (c === rangeStart) {\n ranges.push(braceEscape(c))\n }\n rangeStart = ''\n i++\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c<more...>] or c] at this point\n if (glob.startsWith('-]', i + 1)) {\n ranges.push(braceEscape(c + '-'))\n i += 2\n continue\n }\n if (glob.startsWith('-', i + 1)) {\n rangeStart = c\n i += 2\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(c))\n i++\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return ['', false, 0, false]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return ['$.', false, glob.length - pos, true]\n }\n\n // if we got one positive range, and it's a single character, then that's\n // not actually a magic pattern, it's just that one literal character.\n // we should not treat that as \"magic\", we should just return the literal\n // character. [_] is a perfectly valid way to escape glob magic chars.\n if (\n negs.length === 0 &&\n ranges.length === 1 &&\n /^\\\\?.$/.test(ranges[0]) &&\n !negate\n ) {\n const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]\n return [regexpEscape(r), false, endPos - pos, false]\n }\n\n const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'\n const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'\n const comb =\n ranges.length && negs.length\n ? '(' + sranges + '|' + snegs + ')'\n : ranges.length\n ? sranges\n : snegs\n\n return [comb, uflag, endPos - pos, true]\n}\n", "import { MinimatchOptions } from './index.js'\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link windowsPathsNoEscape} option is used, then square-brace\n * escapes are removed, but not backslash escapes. For example, it will turn\n * the string `'[*]'` into `*`, but it will not turn `'\\\\*'` into `'*'`,\n * becuase `\\` is a path separator in `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both brace escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n */\nexport const unescape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n) => {\n return windowsPathsNoEscape\n ? s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2').replace(/\\\\([^\\/])/g, '$1')\n}\n", "// parse a single path portion\n\nimport { parseClass } from './brace-expressions.js'\nimport { MinimatchOptions, MMRegExp } from './index.js'\nimport { unescape } from './unescape.js'\n\n// classes [] are handled by the parseClass method\n// for positive extglobs, we sub-parse the contents, and combine,\n// with the appropriate regexp close.\n// for negative extglobs, we sub-parse the contents, but then\n// have to include the rest of the pattern, then the parent, etc.,\n// as the thing that cannot be because RegExp negative lookaheads\n// are different from globs.\n//\n// So for example:\n// a@(i|w!(x|y)z|j)b => ^a(i|w((!?(x|y)zb).*)z|j)b$\n// 1 2 3 4 5 6 1 2 3 46 5 6\n//\n// Assembling the extglob requires not just the negated patterns themselves,\n// but also anything following the negative patterns up to the boundary\n// of the current pattern, plus anything following in the parent pattern.\n//\n//\n// So, first, we parse the string into an AST of extglobs, without turning\n// anything into regexps yet.\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y']}, 'z'], ['j']]}, 'b']\n//\n// Then, for all the negative extglobs, we append whatever comes after in\n// each parent as their tail\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y'], 'z', 'b'}, 'z'], ['j']]}, 'b']\n//\n// Lastly, we turn each of these pieces into a regexp, and join\n//\n// v----- .* because there's more following,\n// v v otherwise, .+ because it must be\n// v v *something* there.\n// ['^a', {@ ['i', 'w(?:(!?(?:x|y).*zb$).*)z', 'j' ]}, 'b$']\n// copy what follows into here--^^^^^\n// ['^a', '(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)', 'b$']\n// ['^a(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)b$']\n\nexport type ExtglobType = '!' | '?' | '+' | '*' | '@'\nconst types = new Set<ExtglobType>(['!', '?', '+', '*', '@'])\nconst isExtglobType = (c: string): c is ExtglobType =>\n types.has(c as ExtglobType)\n\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))'\nconst startNoDot = '(?!\\\\.)'\n\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.'])\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.'])\nconst reSpecials = new Set('().*{}+?[]^$\\\\!')\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// any single thing other than /\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?'\n\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\n\nexport class AST {\n type: ExtglobType | null\n readonly #root: AST\n\n #hasMagic?: boolean\n #uflag: boolean = false\n #parts: (string | AST)[] = []\n readonly #parent?: AST\n readonly #parentIndex: number\n #negs: AST[]\n #filledNegs: boolean = false\n #options: MinimatchOptions\n #toString?: string\n // set to true if it's an extglob with no children\n // (which really means one child of '')\n #emptyExt: boolean = false\n\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {}\n ) {\n this.type = type\n // extglobs are inherently magical\n if (type) this.#hasMagic = true\n this.#parent = parent\n this.#root = this.#parent ? this.#parent.#root : this\n this.#options = this.#root === this ? options : this.#root.#options\n this.#negs = this.#root === this ? [] : this.#root.#negs\n if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this)\n this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0\n }\n\n get hasMagic(): boolean | undefined {\n /* c8 ignore start */\n if (this.#hasMagic !== undefined) return this.#hasMagic\n /* c8 ignore stop */\n for (const p of this.#parts) {\n if (typeof p === 'string') continue\n if (p.type || p.hasMagic) return (this.#hasMagic = true)\n }\n // note: will be undefined until we generate the regexp src and find out\n return this.#hasMagic\n }\n\n // reconstructs the pattern\n toString(): string {\n if (this.#toString !== undefined) return this.#toString\n if (!this.type) {\n return (this.#toString = this.#parts.map(p => String(p)).join(''))\n } else {\n return (this.#toString =\n this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')')\n }\n }\n\n #fillNegs() {\n /* c8 ignore start */\n if (this !== this.#root) throw new Error('should only call on root')\n if (this.#filledNegs) return this\n /* c8 ignore stop */\n\n // call toString() once to fill this out\n this.toString()\n this.#filledNegs = true\n let n: AST | undefined\n while ((n = this.#negs.pop())) {\n if (n.type !== '!') continue\n // walk up the tree, appending everthing that comes AFTER parentIndex\n let p: AST | undefined = n\n let pp = p.#parent\n while (pp) {\n for (\n let i = p.#parentIndex + 1;\n !pp.type && i < pp.#parts.length;\n i++\n ) {\n for (const part of n.#parts) {\n /* c8 ignore start */\n if (typeof part === 'string') {\n throw new Error('string part in extglob AST??')\n }\n /* c8 ignore stop */\n part.copyIn(pp.#parts[i])\n }\n }\n p = pp\n pp = p.#parent\n }\n }\n return this\n }\n\n push(...parts: (string | AST)[]) {\n for (const p of parts) {\n if (p === '') continue\n /* c8 ignore start */\n if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {\n throw new Error('invalid part: ' + p)\n }\n /* c8 ignore stop */\n this.#parts.push(p)\n }\n }\n\n toJSON() {\n const ret: any[] =\n this.type === null\n ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))\n : [this.type, ...this.#parts.map(p => (p as AST).toJSON())]\n if (this.isStart() && !this.type) ret.unshift([])\n if (\n this.isEnd() &&\n (this === this.#root ||\n (this.#root.#filledNegs && this.#parent?.type === '!'))\n ) {\n ret.push({})\n }\n return ret\n }\n\n isStart(): boolean {\n if (this.#root === this) return true\n // if (this.type) return !!this.#parent?.isStart()\n if (!this.#parent?.isStart()) return false\n if (this.#parentIndex === 0) return true\n // if everything AHEAD of this is a negation, then it's still the \"start\"\n const p = this.#parent\n for (let i = 0; i < this.#parentIndex; i++) {\n const pp = p.#parts[i]\n if (!(pp instanceof AST && pp.type === '!')) {\n return false\n }\n }\n return true\n }\n\n isEnd(): boolean {\n if (this.#root === this) return true\n if (this.#parent?.type === '!') return true\n if (!this.#parent?.isEnd()) return false\n if (!this.type) return this.#parent?.isEnd()\n // if not root, it'll always have a parent\n /* c8 ignore start */\n const pl = this.#parent ? this.#parent.#parts.length : 0\n /* c8 ignore stop */\n return this.#parentIndex === pl - 1\n }\n\n copyIn(part: AST | string) {\n if (typeof part === 'string') this.push(part)\n else this.push(part.clone(this))\n }\n\n clone(parent: AST) {\n const c = new AST(this.type, parent)\n for (const p of this.#parts) {\n c.copyIn(p)\n }\n return c\n }\n\n static #parseAST(\n str: string,\n ast: AST,\n pos: number,\n opt: MinimatchOptions\n ): number {\n let escaping = false\n let inBrace = false\n let braceStart = -1\n let braceNeg = false\n if (ast.type === null) {\n // outside of a extglob, append until we find a start\n let i = pos\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {\n ast.push(acc)\n acc = ''\n const ext = new AST(c, ast)\n i = AST.#parseAST(str, ext, i, opt)\n ast.push(ext)\n continue\n }\n acc += c\n }\n ast.push(acc)\n return i\n }\n\n // some kind of extglob, pos is at the (\n // find the next | or )\n let i = pos + 1\n let part = new AST(null, ast)\n const parts: AST[] = []\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n if (isExtglobType(c) && str.charAt(i) === '(') {\n part.push(acc)\n acc = ''\n const ext = new AST(c, part)\n part.push(ext)\n i = AST.#parseAST(str, ext, i, opt)\n continue\n }\n if (c === '|') {\n part.push(acc)\n acc = ''\n parts.push(part)\n part = new AST(null, ast)\n continue\n }\n if (c === ')') {\n if (acc === '' && ast.#parts.length === 0) {\n ast.#emptyExt = true\n }\n part.push(acc)\n acc = ''\n ast.push(...parts, part)\n return i\n }\n acc += c\n }\n\n // unfinished extglob\n // if we got here, it was a malformed extglob! not an extglob, but\n // maybe something else in there.\n ast.type = null\n ast.#hasMagic = undefined\n ast.#parts = [str.substring(pos - 1)]\n return i\n }\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n const ast = new AST(null, undefined, options)\n AST.#parseAST(pattern, ast, 0, options)\n return ast\n }\n\n // returns the regular expression if there's magic, or the unescaped\n // string if not.\n toMMPattern(): MMRegExp | string {\n // should only be called on root\n /* c8 ignore start */\n if (this !== this.#root) return this.#root.toMMPattern()\n /* c8 ignore stop */\n const glob = this.toString()\n const [re, body, hasMagic, uflag] = this.toRegExpSource()\n // if we're in nocase mode, and not nocaseMagicOnly, then we do\n // still need a regular expression if we have to case-insensitively\n // match capital/lowercase characters.\n const anyMagic =\n hasMagic ||\n this.#hasMagic ||\n (this.#options.nocase &&\n !this.#options.nocaseMagicOnly &&\n glob.toUpperCase() !== glob.toLowerCase())\n if (!anyMagic) {\n return body\n }\n\n const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '')\n return Object.assign(new RegExp(`^${re}$`, flags), {\n _src: re,\n _glob: glob,\n })\n }\n\n get options() {\n return this.#options\n }\n\n // returns the string match, the regexp source, whether there's magic\n // in the regexp (so a regular expression is required) and whether or\n // not the uflag is needed for the regular expression (for posix classes)\n // TODO: instead of injecting the start/end at this point, just return\n // the BODY of the regexp, along with the start/end portions suitable\n // for binding the start/end in either a joined full-path makeRe context\n // (where we bind to (^|/), or a standalone matchPart context (where\n // we bind to ^, and not /). Otherwise slashes get duped!\n //\n // In part-matching mode, the start is:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n // - if dots allowed or not possible: ^\n // - if dots possible and not allowed: ^(?!\\.)\n // end is:\n // - if not isEnd(): nothing\n // - else: $\n //\n // In full-path matching mode, we put the slash at the START of the\n // pattern, so start is:\n // - if first pattern: same as part-matching mode\n // - if not isStart(): nothing\n // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n // - if dots allowed or not possible: /\n // - if dots possible and not allowed: /(?!\\.)\n // end is:\n // - if last pattern, same as part-matching mode\n // - else nothing\n //\n // Always put the (?:$|/) on negated tails, though, because that has to be\n // there to bind the end of the negated pattern portion, and it's easier to\n // just stick it in now rather than try to inject it later in the middle of\n // the pattern.\n //\n // We can just always return the same end, and leave it up to the caller\n // to know whether it's going to be used joined or in parts.\n // And, if the start is adjusted slightly, can do the same there:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n // - if dots allowed or not possible: (?:/|^)\n // - if dots possible and not allowed: (?:/|^)(?!\\.)\n //\n // But it's better to have a simpler binding without a conditional, for\n // performance, so probably better to return both start options.\n //\n // Then the caller just ignores the end if it's not the first pattern,\n // and the start always gets applied.\n //\n // But that's always going to be $ if it's the ending pattern, or nothing,\n // so the caller can just attach $ at the end of the pattern when building.\n //\n // So the todo is:\n // - better detect what kind of start is needed\n // - return both flavors of starting pattern\n // - attach $ at the end of the pattern when creating the actual RegExp\n //\n // Ah, but wait, no, that all only applies to the root when the first pattern\n // is not an extglob. If the first pattern IS an extglob, then we need all\n // that dot prevention biz to live in the extglob portions, because eg\n // +(*|.x*) can match .xy but not .yx.\n //\n // So, return the two flavors if it's #root and the first child is not an\n // AST, otherwise leave it to the child AST to handle it, and there,\n // use the (?:^|/) style of start binding.\n //\n // Even simplified further:\n // - Since the start for a join is eg /(?!\\.) and the start for a part\n // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n // or start or whatever) and prepend ^ or / at the Regexp construction.\n toRegExpSource(\n allowDot?: boolean\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n const dot = allowDot ?? !!this.#options.dot\n if (this.#root === this) this.#fillNegs()\n if (!this.type) {\n const noEmpty = this.isStart() && this.isEnd()\n const src = this.#parts\n .map(p => {\n const [re, _, hasMagic, uflag] =\n typeof p === 'string'\n ? AST.#parseGlob(p, this.#hasMagic, noEmpty)\n : p.toRegExpSource(allowDot)\n this.#hasMagic = this.#hasMagic || hasMagic\n this.#uflag = this.#uflag || uflag\n return re\n })\n .join('')\n\n let start = ''\n if (this.isStart()) {\n if (typeof this.#parts[0] === 'string') {\n // this is the string that will match the start of the pattern,\n // so we need to protect against dots and such.\n\n // '.' and '..' cannot match unless the pattern is that exactly,\n // even if it starts with . or dot:true is set.\n const dotTravAllowed =\n this.#parts.length === 1 && justDots.has(this.#parts[0])\n if (!dotTravAllowed) {\n const aps = addPatternStart\n // check if we have a possibility of matching . or ..,\n // and prevent that.\n const needNoTrav =\n // dots are allowed, and the pattern starts with [ or .\n (dot && aps.has(src.charAt(0))) ||\n // the pattern starts with \\., and then [ or .\n (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n // the pattern starts with \\.\\., and then [ or .\n (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)))\n // no need to prevent dots if it can't match a dot, or if a\n // sub-pattern will be preventing it anyway.\n const needNoDot = !dot && !allowDot && aps.has(src.charAt(0))\n\n start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''\n }\n }\n }\n\n // append the \"end of path portion\" pattern to negation tails\n let end = ''\n if (\n this.isEnd() &&\n this.#root.#filledNegs &&\n this.#parent?.type === '!'\n ) {\n end = '(?:$|\\\\/)'\n }\n const final = start + src + end\n return [\n final,\n unescape(src),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n // We need to calculate the body *twice* if it's a repeat pattern\n // at the start, once in nodot mode, then again in dot mode, so a\n // pattern like *(?) can match 'x.y'\n\n const repeated = this.type === '*' || this.type === '+'\n // some kind of extglob\n const start = this.type === '!' ? '(?:(?!(?:' : '(?:'\n let body = this.#partsToRegExp(dot)\n\n if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n // invalid extglob, has to at least be *something* present, if it's\n // the entire path portion.\n const s = this.toString()\n this.#parts = [s]\n this.type = null\n this.#hasMagic = undefined\n return [s, unescape(this.toString()), false, false]\n }\n\n // XXX abstract out this map method\n let bodyDotAllowed =\n !repeated || allowDot || dot || !startNoDot\n ? ''\n : this.#partsToRegExp(true)\n if (bodyDotAllowed === body) {\n bodyDotAllowed = ''\n }\n if (bodyDotAllowed) {\n body = `(?:${body})(?:${bodyDotAllowed})*?`\n }\n\n // an empty !() is exactly equivalent to a starNoEmpty\n let final = ''\n if (this.type === '!' && this.#emptyExt) {\n final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty\n } else {\n const close =\n this.type === '!'\n ? // !() must match something,but !(x) can match ''\n '))' +\n (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n star +\n ')'\n : this.type === '@'\n ? ')'\n : this.type === '?'\n ? ')?'\n : this.type === '+' && bodyDotAllowed\n ? ')'\n : this.type === '*' && bodyDotAllowed\n ? `)?`\n : `)${this.type}`\n final = start + body + close\n }\n return [\n final,\n unescape(body),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n #partsToRegExp(dot: boolean) {\n return this.#parts\n .map(p => {\n // extglob ASTs should only contain parent ASTs\n /* c8 ignore start */\n if (typeof p === 'string') {\n throw new Error('string type in extglob ast??')\n }\n /* c8 ignore stop */\n // can ignore hasMagic, because extglobs are already always magic\n const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot)\n this.#uflag = this.#uflag || uflag\n return re\n })\n .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n .join('|')\n }\n\n static #parseGlob(\n glob: string,\n hasMagic: boolean | undefined,\n noEmpty: boolean = false\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n let escaping = false\n let re = ''\n let uflag = false\n for (let i = 0; i < glob.length; i++) {\n const c = glob.charAt(i)\n if (escaping) {\n escaping = false\n re += (reSpecials.has(c) ? '\\\\' : '') + c\n continue\n }\n if (c === '\\\\') {\n if (i === glob.length - 1) {\n re += '\\\\\\\\'\n } else {\n escaping = true\n }\n continue\n }\n if (c === '[') {\n const [src, needUflag, consumed, magic] = parseClass(glob, i)\n if (consumed) {\n re += src\n uflag = uflag || needUflag\n i += consumed - 1\n hasMagic = hasMagic || magic\n continue\n }\n }\n if (c === '*') {\n if (noEmpty && glob === '*') re += starNoEmpty\n else re += star\n hasMagic = true\n continue\n }\n if (c === '?') {\n re += qmark\n hasMagic = true\n continue\n }\n re += regExpEscape(c)\n }\n return [re, unescape(glob), !!hasMagic, uflag]\n }\n}\n", "import { MinimatchOptions } from './index.js'\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n */\nexport const escape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n return windowsPathsNoEscape\n ? s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n", "import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n FSOption,\n Path,\n PathScurry,\n PathScurryDarwin,\n PathScurryPosix,\n PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude<Minimatch['globParts'], undefined>\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n /**\n * Set to `true` to always receive absolute paths for\n * matched files. Set to `false` to always return relative paths.\n *\n * When this option is not set, absolute paths are returned for patterns\n * that are absolute, and otherwise paths are returned that are relative\n * to the `cwd` setting.\n *\n * This does _not_ make an extra system call to get\n * the realpath, it only does string path resolution.\n *\n * Conflicts with {@link withFileTypes}\n */\n absolute?: boolean\n\n /**\n * Set to false to enable {@link windowsPathsNoEscape}\n *\n * @deprecated\n */\n allowWindowsEscape?: boolean\n\n /**\n * The current working directory in which to search. Defaults to\n * `process.cwd()`.\n *\n * May be eiher a string path or a `file://` URL object or string.\n */\n cwd?: string | URL\n\n /**\n * Include `.dot` files in normal matches and `globstar`\n * matches. Note that an explicit dot in a portion of the pattern\n * will always match dot files.\n */\n dot?: boolean\n\n /**\n * Prepend all relative path strings with `./` (or `.\\` on Windows).\n *\n * Without this option, returned relative paths are \"bare\", so instead of\n * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n *\n * Relative patterns starting with `'../'` are not prepended with `./`, even\n * if this option is set.\n */\n dotRelative?: boolean\n\n /**\n * Follow symlinked directories when expanding `**`\n * patterns. This can result in a lot of duplicate references in\n * the presence of cyclic links, and make performance quite bad.\n *\n * By default, a `**` in a pattern will follow 1 symbolic link if\n * it is not the first item in the pattern, or none if it is the\n * first item in the pattern, following the same behavior as Bash.\n */\n follow?: boolean\n\n /**\n * string or string[], or an object with `ignore` and `ignoreChildren`\n * methods.\n *\n * If a string or string[] is provided, then this is treated as a glob\n * pattern or array of glob patterns to exclude from matches. To ignore all\n * children within a directory, as well as the entry itself, append `'/**'`\n * to the ignore pattern.\n *\n * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n * any other settings.\n *\n * If an object is provided that has `ignored(path)` and/or\n * `childrenIgnored(path)` methods, then these methods will be called to\n * determine whether any Path is a match or if its children should be\n * traversed, respectively.\n */\n ignore?: string | string[] | IgnoreLike\n\n /**\n * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n * effect if {@link nobrace} is set.\n *\n * Only has effect on the {@link hasMagic} function.\n */\n magicalBraces?: boolean\n\n /**\n * Add a `/` character to directory matches. Note that this requires\n * additional stat calls in some cases.\n */\n mark?: boolean\n\n /**\n * Perform a basename-only match if the pattern does not contain any slash\n * characters. That is, `*.js` would be treated as equivalent to\n * `**\\/*.js`, matching all js files in all directories.\n */\n matchBase?: boolean\n\n /**\n * Limit the directory traversal to a given depth below the cwd.\n * Note that this does NOT prevent traversal to sibling folders,\n * root patterns, and so on. It only limits the maximum folder depth\n * that the walk will descend, relative to the cwd.\n */\n maxDepth?: number\n\n /**\n * Do not expand `{a,b}` and `{1..3}` brace sets.\n */\n nobrace?: boolean\n\n /**\n * Perform a case-insensitive match. This defaults to `true` on macOS and\n * Windows systems, and `false` on all others.\n *\n * **Note** `nocase` should only be explicitly set when it is\n * known that the filesystem's case sensitivity differs from the\n * platform default. If set `true` on case-sensitive file\n * systems, or `false` on case-insensitive file systems, then the\n * walk may return more or less results than expected.\n */\n nocase?: boolean\n\n /**\n * Do not match directories, only files. (Note: to match\n * _only_ directories, put a `/` at the end of the pattern.)\n */\n nodir?: boolean\n\n /**\n * Do not match \"extglob\" patterns such as `+(a|b)`.\n */\n noext?: boolean\n\n /**\n * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n * `*` instead.)\n *\n * Conflicts with {@link matchBase}\n */\n noglobstar?: boolean\n\n /**\n * Defaults to value of `process.platform` if available, or `'linux'` if\n * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n * behavior.\n */\n platform?: NodeJS.Platform\n\n /**\n * Set to true to call `fs.realpath` on all of the\n * results. In the case of an entry that cannot be resolved, the\n * entry is omitted. This incurs a slight performance penalty, of\n * course, because of the added system calls.\n */\n realpath?: boolean\n\n /**\n *\n * A string path resolved against the `cwd` option, which\n * is used as the starting point for absolute patterns that start\n * with `/`, (but not drive letters or UNC paths on Windows).\n *\n * Note that this _doesn't_ necessarily limit the walk to the\n * `root` directory, and doesn't affect the cwd starting point for\n * non-absolute patterns. A pattern containing `..` will still be\n * able to traverse out of the root directory, if it is not an\n * actual root directory on the filesystem, and any non-absolute\n * patterns will be matched in the `cwd`. For example, the\n * pattern `/../*` with `{root:'/some/path'}` will return all\n * files in `/some`, not all files in `/some/path`. The pattern\n * `*` with `{root:'/some/path'}` will return all the entries in\n * the cwd, not the entries in `/some/path`.\n *\n * To start absolute and non-absolute patterns in the same\n * path, you can use `{root:''}`. However, be aware that on\n * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n * _always_ start in the `x:/` or `//host/share` directory,\n * regardless of the `root` setting.\n */\n root?: string\n\n /**\n * A [PathScurry](http://npm.im/path-scurry) object used\n * to traverse the file system. If the `nocase` option is set\n * explicitly, then any provided `scurry` object must match this\n * setting.\n */\n scurry?: PathScurry\n\n /**\n * Call `lstat()` on all entries, whether required or not to determine\n * if it's a valid match. When used with {@link withFileTypes}, this means\n * that matches will include data such as modified time, permissions, and\n * so on. Note that this will incur a performance cost due to the added\n * system calls.\n */\n stat?: boolean\n\n /**\n * An AbortSignal which will cancel the Glob walk when\n * triggered.\n */\n signal?: AbortSignal\n\n /**\n * Use `\\\\` as a path separator _only_, and\n * _never_ as an escape character. If set, all `\\\\` characters are\n * replaced with `/` in the pattern.\n *\n * Note that this makes it **impossible** to match against paths\n * containing literal glob pattern characters, but allows matching\n * with patterns constructed using `path.join()` and\n * `path.resolve()` on Windows platforms, mimicking the (buggy!)\n * behavior of Glob v7 and before on Windows. Please use with\n * caution, and be mindful of [the caveat below about Windows\n * paths](#windows). (For legacy reasons, this is also set if\n * `allowWindowsEscape` is set to the exact value `false`.)\n */\n windowsPathsNoEscape?: boolean\n\n /**\n * Return [PathScurry](http://npm.im/path-scurry)\n * `Path` objects instead of strings. These are similar to a\n * NodeJS `Dirent` object, but with additional methods and\n * properties.\n *\n * Conflicts with {@link absolute}\n */\n withFileTypes?: boolean\n\n /**\n * An fs implementation to override some or all of the defaults. See\n * http://npm.im/path-scurry for details about what can be overridden.\n */\n fs?: FSOption\n\n /**\n * Just passed along to Minimatch. Note that this makes all pattern\n * matching operations slower and *extremely* noisy.\n */\n debug?: boolean\n\n /**\n * Return `/` delimited paths, even on Windows.\n *\n * On posix systems, this has no effect. But, on Windows, it means that\n * paths will be `/` delimited, and absolute paths will be their full\n * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n * `'//?/C:/foo/bar'`\n */\n posix?: boolean\n\n /**\n * Do not match any children of any matches. For example, the pattern\n * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n *\n * This is especially useful for cases like \"find all `node_modules`\n * folders, but not the ones in `node_modules`\".\n *\n * In order to support this, the `Ignore` implementation must support an\n * `add(pattern: string)` method. If using the default `Ignore` class, then\n * this is fine, but if this is set to `false`, and a custom `Ignore` is\n * provided that does not have an `add()` method, then it will throw an\n * error.\n *\n * **Caveat** It *only* ignores matches that would be a descendant of a\n * previous match, and only if that descendant is matched *after* the\n * ancestor is encountered. Since the file system walk happens in\n * indeterminate order, it's possible that a match will already be added\n * before its ancestor, if multiple or braced patterns are used.\n *\n * For example:\n *\n * ```ts\n * const results = await glob([\n * // likely to match first, since it's just a stat\n * 'a/b/c/d/e/f',\n *\n * // this pattern is more complicated! It must to various readdir()\n * // calls and test the results against a regular expression, and that\n * // is certainly going to take a little bit longer.\n * //\n * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n * // late to ignore a/b/c/d/e/f, because it's already been emitted.\n * 'a/[bdf]/?/[a-z]/*',\n * ], { includeChildMatches: false })\n * ```\n *\n * It's best to only set this to `false` if you can be reasonably sure that\n * no components of the pattern will potentially match one another's file\n * system descendants, or if the occasional included child entry will not\n * cause problems.\n *\n * @default true\n */\n includeChildMatches?: boolean\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n withFileTypes: true\n // string options not relevant if returning Path objects.\n absolute?: undefined\n mark?: undefined\n posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n withFileTypes?: undefined\n}\n\nexport type Result<Opts> =\n Opts extends GlobOptionsWithFileTypesTrue ? Path\n : Opts extends GlobOptionsWithFileTypesFalse ? string\n : Opts extends GlobOptionsWithFileTypesUnset ? string\n : string | Path\nexport type Results<Opts> = Result<Opts>[]\n\nexport type FileTypes<Opts> =\n Opts extends GlobOptionsWithFileTypesTrue ? true\n : Opts extends GlobOptionsWithFileTypesFalse ? false\n : Opts extends GlobOptionsWithFileTypesUnset ? false\n : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob<Opts extends GlobOptions> implements GlobOptions {\n absolute?: boolean\n cwd: string\n root?: string\n dot: boolean\n dotRelative: boolean\n follow: boolean\n ignore?: string | string[] | IgnoreLike\n magicalBraces: boolean\n mark?: boolean\n matchBase: boolean\n maxDepth: number\n nobrace: boolean\n nocase: boolean\n nodir: boolean\n noext: boolean\n noglobstar: boolean\n pattern: string[]\n platform: NodeJS.Platform\n realpath: boolean\n scurry: PathScurry\n stat: boolean\n signal?: AbortSignal\n windowsPathsNoEscape: boolean\n withFileTypes: FileTypes<Opts>\n includeChildMatches: boolean\n\n /**\n * The options provided to the constructor.\n */\n opts: Opts\n\n /**\n * An array of parsed immutable {@link Pattern} objects.\n */\n patterns: Pattern[]\n\n /**\n * All options are stored as properties on the `Glob` object.\n *\n * See {@link GlobOptions} for full options descriptions.\n *\n * Note that a previous `Glob` object can be passed as the\n * `GlobOptions` to another `Glob` instantiation to re-use settings\n * and caches with a new pattern.\n *\n * Traversal functions can be called multiple times to run the walk\n * again.\n */\n constructor(pattern: string | string[], opts: Opts) {\n /* c8 ignore start */\n if (!opts) throw new TypeError('glob options required')\n /* c8 ignore stop */\n this.withFileTypes = !!opts.withFileTypes as FileTypes<Opts>\n this.signal = opts.signal\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.dotRelative = !!opts.dotRelative\n this.nodir = !!opts.nodir\n this.mark = !!opts.mark\n if (!opts.cwd) {\n this.cwd = ''\n } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n opts.cwd = fileURLToPath(opts.cwd)\n }\n this.cwd = opts.cwd || ''\n this.root = opts.root\n this.magicalBraces = !!opts.magicalBraces\n this.nobrace = !!opts.nobrace\n this.noext = !!opts.noext\n this.realpath = !!opts.realpath\n this.absolute = opts.absolute\n this.includeChildMatches = opts.includeChildMatches !== false\n\n this.noglobstar = !!opts.noglobstar\n this.matchBase = !!opts.matchBase\n this.maxDepth =\n typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n this.stat = !!opts.stat\n this.ignore = opts.ignore\n\n if (this.withFileTypes && this.absolute !== undefined) {\n throw new Error('cannot set absolute and withFileTypes:true')\n }\n\n if (typeof pattern === 'string') {\n pattern = [pattern]\n }\n\n this.windowsPathsNoEscape =\n !!opts.windowsPathsNoEscape ||\n (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n false\n\n if (this.windowsPathsNoEscape) {\n pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n }\n\n if (this.matchBase) {\n if (opts.noglobstar) {\n throw new TypeError('base matching requires globstar')\n }\n pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n }\n\n this.pattern = pattern\n\n this.platform = opts.platform || defaultPlatform\n this.opts = { ...opts, platform: this.platform }\n if (opts.scurry) {\n this.scurry = opts.scurry\n if (\n opts.nocase !== undefined &&\n opts.nocase !== opts.scurry.nocase\n ) {\n throw new Error('nocase option contradicts provided scurry option')\n }\n } else {\n const Scurry =\n opts.platform === 'win32' ? PathScurryWin32\n : opts.platform === 'darwin' ? PathScurryDarwin\n : opts.platform ? PathScurryPosix\n : PathScurry\n this.scurry = new Scurry(this.cwd, {\n nocase: opts.nocase,\n fs: opts.fs,\n })\n }\n this.nocase = this.scurry.nocase\n\n // If you do nocase:true on a case-sensitive file system, then\n // we need to use regexps instead of strings for non-magic\n // path portions, because statting `aBc` won't return results\n // for the file `AbC` for example.\n const nocaseMagicOnly =\n this.platform === 'darwin' || this.platform === 'win32'\n\n const mmo: MinimatchOptions = {\n // default nocase based on platform\n ...opts,\n dot: this.dot,\n matchBase: this.matchBase,\n nobrace: this.nobrace,\n nocase: this.nocase,\n nocaseMagicOnly,\n nocomment: true,\n noext: this.noext,\n nonegate: true,\n optimizationLevel: 2,\n platform: this.platform,\n windowsPathsNoEscape: this.windowsPathsNoEscape,\n debug: !!this.opts.debug,\n }\n\n const mms = this.pattern.map(p => new Minimatch(p, mmo))\n const [matchSet, globParts] = mms.reduce(\n (set: [MatchSet, GlobParts], m) => {\n set[0].push(...m.set)\n set[1].push(...m.globParts)\n return set\n },\n [[], []],\n )\n this.patterns = matchSet.map((set, i) => {\n const g = globParts[i]\n /* c8 ignore start */\n if (!g) throw new Error('invalid pattern object')\n /* c8 ignore stop */\n return new Pattern(set, g, 0, this.platform)\n })\n }\n\n /**\n * Returns a Promise that resolves to the results array.\n */\n async walk(): Promise<Results<Opts>>\n async walk(): Promise<(string | Path)[]> {\n // Walkers always return array of Path objects, so we just have to\n // coerce them into the right shape. It will have already called\n // realpath() if the option was set to do so, so we know that's cached.\n // start out knowing the cwd, at least\n return [\n ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walk()),\n ]\n }\n\n /**\n * synchronous {@link Glob.walk}\n */\n walkSync(): Results<Opts>\n walkSync(): (string | Path)[] {\n return [\n ...new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walkSync(),\n ]\n }\n\n /**\n * Stream results asynchronously.\n */\n stream(): Minipass<Result<Opts>, Result<Opts>>\n stream(): Minipass<string | Path, string | Path> {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).stream()\n }\n\n /**\n * Stream results synchronously.\n */\n streamSync(): Minipass<Result<Opts>, Result<Opts>>\n streamSync(): Minipass<string | Path, string | Path> {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).streamSync()\n }\n\n /**\n * Default sync iteration function. Returns a Generator that\n * iterates over the results.\n */\n iterateSync(): Generator<Result<Opts>, void, void> {\n return this.streamSync()[Symbol.iterator]()\n }\n [Symbol.iterator]() {\n return this.iterateSync()\n }\n\n /**\n * Default async iteration function. Returns an AsyncGenerator that\n * iterates over the results.\n */\n iterate(): AsyncGenerator<Result<Opts>, void, void> {\n return this.stream()[Symbol.asyncIterator]()\n }\n [Symbol.asyncIterator]() {\n return this.iterate()\n }\n}\n", "/**\n * @module LRUCache\n */\n\n// module-private names and types\ntype Perf = { now: () => number }\nconst perf: Perf =\n typeof performance === 'object' &&\n performance &&\n typeof performance.now === 'function'\n ? performance\n : Date\n\nconst warned = new Set<string>()\n\n// either a function or a class\ntype ForC = ((...a: any[]) => any) | { new (...a: any[]): any }\n\n/* c8 ignore start */\nconst PROCESS = (\n typeof process === 'object' && !!process ? process : {}\n) as { [k: string]: any }\n/* c8 ignore start */\n\nconst emitWarning = (\n msg: string,\n type: string,\n code: string,\n fn: ForC\n) => {\n typeof PROCESS.emitWarning === 'function'\n ? PROCESS.emitWarning(msg, type, code, fn)\n : console.error(`[${code}] ${type}: ${msg}`)\n}\n\nlet AC = globalThis.AbortController\nlet AS = globalThis.AbortSignal\n\n/* c8 ignore start */\nif (typeof AC === 'undefined') {\n //@ts-ignore\n AS = class AbortSignal {\n onabort?: (...a: any[]) => any\n _onabort: ((...a: any[]) => any)[] = []\n reason?: any\n aborted: boolean = false\n addEventListener(_: string, fn: (...a: any[]) => any) {\n this._onabort.push(fn)\n }\n }\n //@ts-ignore\n AC = class AbortController {\n constructor() {\n warnACPolyfill()\n }\n signal = new AS()\n abort(reason: any) {\n if (this.signal.aborted) return\n //@ts-ignore\n this.signal.reason = reason\n //@ts-ignore\n this.signal.aborted = true\n //@ts-ignore\n for (const fn of this.signal._onabort) {\n fn(reason)\n }\n this.signal.onabort?.(reason)\n }\n }\n let printACPolyfillWarning =\n PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'\n const warnACPolyfill = () => {\n if (!printACPolyfillWarning) return\n printACPolyfillWarning = false\n emitWarning(\n 'AbortController is not defined. If using lru-cache in ' +\n 'node 14, load an AbortController polyfill from the ' +\n '`node-abort-controller` package. A minimal polyfill is ' +\n 'provided for use by LRUCache.fetch(), but it should not be ' +\n 'relied upon in other contexts (eg, passing it to other APIs that ' +\n 'use AbortController/AbortSignal might have undesirable effects). ' +\n 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.',\n 'NO_ABORT_CONTROLLER',\n 'ENOTSUP',\n warnACPolyfill\n )\n }\n}\n/* c8 ignore stop */\n\nconst shouldWarn = (code: string) => !warned.has(code)\n\nconst TYPE = Symbol('type')\nexport type PosInt = number & { [TYPE]: 'Positive Integer' }\nexport type Index = number & { [TYPE]: 'LRUCache Index' }\n\nconst isPosInt = (n: any): n is PosInt =>\n n && n === Math.floor(n) && n > 0 && isFinite(n)\n\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array\nexport type NumberArray = UintArray | number[]\n\n/* c8 ignore start */\n// This is a little bit ridiculous, tbh.\n// The maximum array length is 2^32-1 or thereabouts on most JS impls.\n// And well before that point, you're caching the entire world, I mean,\n// that's ~32GB of just integers for the next/prev links, plus whatever\n// else to hold that many keys and values. Just filling the memory with\n// zeroes at init time is brutal when you get that big.\n// But why not be complete?\n// Maybe in the future, these limits will have expanded.\nconst getUintArray = (max: number) =>\n !isPosInt(max)\n ? null\n : max <= Math.pow(2, 8)\n ? Uint8Array\n : max <= Math.pow(2, 16)\n ? Uint16Array\n : max <= Math.pow(2, 32)\n ? Uint32Array\n : max <= Number.MAX_SAFE_INTEGER\n ? ZeroArray\n : null\n/* c8 ignore stop */\n\nclass ZeroArray extends Array<number> {\n constructor(size: number) {\n super(size)\n this.fill(0)\n }\n}\nexport type { ZeroArray }\nexport type { Stack }\n\nexport type StackLike = Stack | Index[]\nclass Stack {\n heap: NumberArray\n length: number\n // private constructor\n static #constructing: boolean = false\n static create(max: number): StackLike {\n const HeapCls = getUintArray(max)\n if (!HeapCls) return []\n Stack.#constructing = true\n const s = new Stack(max, HeapCls)\n Stack.#constructing = false\n return s\n }\n constructor(\n max: number,\n HeapCls: { new (n: number): NumberArray }\n ) {\n /* c8 ignore start */\n if (!Stack.#constructing) {\n throw new TypeError('instantiate Stack using Stack.create(n)')\n }\n /* c8 ignore stop */\n this.heap = new HeapCls(max)\n this.length = 0\n }\n push(n: Index) {\n this.heap[this.length++] = n\n }\n pop(): Index {\n return this.heap[--this.length] as Index\n }\n}\n\n/**\n * Promise representing an in-progress {@link LRUCache#fetch} call\n */\nexport type BackgroundFetch<V> = Promise<V | undefined> & {\n __returned: BackgroundFetch<V> | undefined\n __abortController: AbortController\n __staleWhileFetching: V | undefined\n}\n\nexport type DisposeTask<K, V> = [\n value: V,\n key: K,\n reason: LRUCache.DisposeReason\n]\n\nexport namespace LRUCache {\n /**\n * An integer greater than 0, reflecting the calculated size of items\n */\n export type Size = number\n\n /**\n * Integer greater than 0, representing some number of milliseconds, or the\n * time at which a TTL started counting from.\n */\n export type Milliseconds = number\n\n /**\n * An integer greater than 0, reflecting a number of items\n */\n export type Count = number\n\n /**\n * The reason why an item was removed from the cache, passed\n * to the {@link Disposer} methods.\n *\n * - `evict`: The item was evicted because it is the least recently used,\n * and the cache is full.\n * - `set`: A new value was set, overwriting the old value being disposed.\n * - `delete`: The item was explicitly deleted, either by calling\n * {@link LRUCache#delete}, {@link LRUCache#clear}, or\n * {@link LRUCache#set} with an undefined value.\n * - `expire`: The item was removed due to exceeding its TTL.\n * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n * `undefined` or was aborted, causing the item to be deleted.\n */\n export type DisposeReason =\n | 'evict'\n | 'set'\n | 'delete'\n | 'expire'\n | 'fetch'\n /**\n * A method called upon item removal, passed as the\n * {@link OptionsBase.dispose} and/or\n * {@link OptionsBase.disposeAfter} options.\n */\n export type Disposer<K, V> = (\n value: V,\n key: K,\n reason: DisposeReason\n ) => void\n\n /**\n * A function that returns the effective calculated size\n * of an entry in the cache.\n */\n export type SizeCalculator<K, V> = (value: V, key: K) => Size\n\n /**\n * Options provided to the\n * {@link OptionsBase.fetchMethod} function.\n */\n export interface FetcherOptions<K, V, FC = unknown> {\n signal: AbortSignal\n options: FetcherFetchOptions<K, V, FC>\n /**\n * Object provided in the {@link FetchOptions.context} option to\n * {@link LRUCache#fetch}\n */\n context: FC\n }\n\n /**\n * Occasionally, it may be useful to track the internal behavior of the\n * cache, particularly for logging, debugging, or for behavior within the\n * `fetchMethod`. To do this, you can pass a `status` object to the\n * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n *\n * The `status` option should be a plain JavaScript object. The following\n * fields will be set on it appropriately, depending on the situation.\n */\n export interface Status<V> {\n /**\n * The status of a set() operation.\n *\n * - add: the item was not found in the cache, and was added\n * - update: the item was in the cache, with the same value provided\n * - replace: the item was in the cache, and replaced\n * - miss: the item was not added to the cache for some reason\n */\n set?: 'add' | 'update' | 'replace' | 'miss'\n\n /**\n * the ttl stored for the item, or undefined if ttls are not used.\n */\n ttl?: Milliseconds\n\n /**\n * the start time for the item, or undefined if ttls are not used.\n */\n start?: Milliseconds\n\n /**\n * The timestamp used for TTL calculation\n */\n now?: Milliseconds\n\n /**\n * the remaining ttl for the item, or undefined if ttls are not used.\n */\n remainingTTL?: Milliseconds\n\n /**\n * The calculated size for the item, if sizes are used.\n */\n entrySize?: Size\n\n /**\n * The total calculated size of the cache, if sizes are used.\n */\n totalCalculatedSize?: Size\n\n /**\n * A flag indicating that the item was not stored, due to exceeding the\n * {@link OptionsBase.maxEntrySize}\n */\n maxEntrySizeExceeded?: true\n\n /**\n * The old value, specified in the case of `set:'update'` or\n * `set:'replace'`\n */\n oldValue?: V\n\n /**\n * The results of a {@link LRUCache#has} operation\n *\n * - hit: the item was found in the cache\n * - stale: the item was found in the cache, but is stale\n * - miss: the item was not found in the cache\n */\n has?: 'hit' | 'stale' | 'miss'\n\n /**\n * The status of a {@link LRUCache#fetch} operation.\n * Note that this can change as the underlying fetch() moves through\n * various states.\n *\n * - inflight: there is another fetch() for this key which is in process\n * - get: there is no {@link OptionsBase.fetchMethod}, so\n * {@link LRUCache#get} was called.\n * - miss: the item is not in cache, and will be fetched.\n * - hit: the item is in the cache, and was resolved immediately.\n * - stale: the item is in the cache, but stale.\n * - refresh: the item is in the cache, and not stale, but\n * {@link FetchOptions.forceRefresh} was specified.\n */\n fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'\n\n /**\n * The {@link OptionsBase.fetchMethod} was called\n */\n fetchDispatched?: true\n\n /**\n * The cached value was updated after a successful call to\n * {@link OptionsBase.fetchMethod}\n */\n fetchUpdated?: true\n\n /**\n * The reason for a fetch() rejection. Either the error raised by the\n * {@link OptionsBase.fetchMethod}, or the reason for an\n * AbortSignal.\n */\n fetchError?: Error\n\n /**\n * The fetch received an abort signal\n */\n fetchAborted?: true\n\n /**\n * The abort signal received was ignored, and the fetch was allowed to\n * continue.\n */\n fetchAbortIgnored?: true\n\n /**\n * The fetchMethod promise resolved successfully\n */\n fetchResolved?: true\n\n /**\n * The fetchMethod promise was rejected\n */\n fetchRejected?: true\n\n /**\n * The status of a {@link LRUCache#get} operation.\n *\n * - fetching: The item is currently being fetched. If a previous value\n * is present and allowed, that will be returned.\n * - stale: The item is in the cache, and is stale.\n * - hit: the item is in the cache\n * - miss: the item is not in the cache\n */\n get?: 'stale' | 'hit' | 'miss'\n\n /**\n * A fetch or get operation returned a stale value.\n */\n returnedStale?: true\n }\n\n /**\n * options which override the options set in the LRUCache constructor\n * when calling {@link LRUCache#fetch}.\n *\n * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n * {@link OptionsBase.noDeleteOnFetchRejection},\n * {@link OptionsBase.allowStaleOnFetchRejection},\n * {@link FetchOptions.forceRefresh}, and\n * {@link FetcherOptions.context}\n *\n * Any of these may be modified in the {@link OptionsBase.fetchMethod}\n * function, but the {@link GetOptions} fields will of course have no\n * effect, as the {@link LRUCache#get} call already happened by the time\n * the fetchMethod is called.\n */\n export interface FetcherFetchOptions<K, V, FC = unknown>\n extends Pick<\n OptionsBase<K, V, FC>,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n | 'noDeleteOnFetchRejection'\n | 'allowStaleOnFetchRejection'\n | 'ignoreFetchAbort'\n | 'allowStaleOnFetchAbort'\n > {\n status?: Status<V>\n size?: Size\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#fetch} method.\n */\n export interface FetchOptions<K, V, FC>\n extends FetcherFetchOptions<K, V, FC> {\n /**\n * Set to true to force a re-load of the existing data, even if it\n * is not yet stale.\n */\n forceRefresh?: boolean\n /**\n * Context provided to the {@link OptionsBase.fetchMethod} as\n * the {@link FetcherOptions.context} param.\n *\n * If the FC type is specified as unknown (the default),\n * undefined or void, then this is optional. Otherwise, it will\n * be required.\n */\n context?: FC\n signal?: AbortSignal\n status?: Status<V>\n }\n /**\n * Options provided to {@link LRUCache#fetch} when the FC type is something\n * other than `unknown`, `undefined`, or `void`\n */\n export interface FetchOptionsWithContext<K, V, FC>\n extends FetchOptions<K, V, FC> {\n context: FC\n }\n /**\n * Options provided to {@link LRUCache#fetch} when the FC type is\n * `undefined` or `void`\n */\n export interface FetchOptionsNoContext<K, V>\n extends FetchOptions<K, V, undefined> {\n context?: undefined\n }\n\n export interface MemoOptions<K, V, FC = unknown>\n extends Pick<\n OptionsBase<K, V, FC>,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n | 'noDeleteOnFetchRejection'\n | 'allowStaleOnFetchRejection'\n | 'ignoreFetchAbort'\n | 'allowStaleOnFetchAbort'\n > {\n /**\n * Set to true to force a re-load of the existing data, even if it\n * is not yet stale.\n */\n forceRefresh?: boolean\n /**\n * Context provided to the {@link OptionsBase.memoMethod} as\n * the {@link MemoizerOptions.context} param.\n *\n * If the FC type is specified as unknown (the default),\n * undefined or void, then this is optional. Otherwise, it will\n * be required.\n */\n context?: FC\n status?: Status<V>\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is something\n * other than `unknown`, `undefined`, or `void`\n */\n export interface MemoOptionsWithContext<K, V, FC>\n extends MemoOptions<K, V, FC> {\n context: FC\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is\n * `undefined` or `void`\n */\n export interface MemoOptionsNoContext<K, V>\n extends MemoOptions<K, V, undefined> {\n context?: undefined\n }\n\n /**\n * Options provided to the\n * {@link OptionsBase.memoMethod} function.\n */\n export interface MemoizerOptions<K, V, FC = unknown> {\n options: MemoizerMemoOptions<K, V, FC>\n /**\n * Object provided in the {@link MemoOptions.context} option to\n * {@link LRUCache#memo}\n */\n context: FC\n }\n\n /**\n * options which override the options set in the LRUCache constructor\n * when calling {@link LRUCache#memo}.\n *\n * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n * {@link MemoOptions.forceRefresh}, and\n * {@link MemoerOptions.context}\n *\n * Any of these may be modified in the {@link OptionsBase.memoMethod}\n * function, but the {@link GetOptions} fields will of course have no\n * effect, as the {@link LRUCache#get} call already happened by the time\n * the memoMethod is called.\n */\n export interface MemoizerMemoOptions<K, V, FC = unknown>\n extends Pick<\n OptionsBase<K, V, FC>,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n > {\n status?: Status<V>\n size?: Size\n start?: Milliseconds\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#has} method.\n */\n export interface HasOptions<K, V, FC>\n extends Pick<OptionsBase<K, V, FC>, 'updateAgeOnHas'> {\n status?: Status<V>\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#get} method.\n */\n export interface GetOptions<K, V, FC>\n extends Pick<\n OptionsBase<K, V, FC>,\n 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'\n > {\n status?: Status<V>\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#peek} method.\n */\n export interface PeekOptions<K, V, FC>\n extends Pick<OptionsBase<K, V, FC>, 'allowStale'> {}\n\n /**\n * Options that may be passed to the {@link LRUCache#set} method.\n */\n export interface SetOptions<K, V, FC>\n extends Pick<\n OptionsBase<K, V, FC>,\n 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'\n > {\n /**\n * If size tracking is enabled, then setting an explicit size\n * in the {@link LRUCache#set} call will prevent calling the\n * {@link OptionsBase.sizeCalculation} function.\n */\n size?: Size\n /**\n * If TTL tracking is enabled, then setting an explicit start\n * time in the {@link LRUCache#set} call will override the\n * default time from `performance.now()` or `Date.now()`.\n *\n * Note that it must be a valid value for whichever time-tracking\n * method is in use.\n */\n start?: Milliseconds\n status?: Status<V>\n }\n\n /**\n * The type signature for the {@link OptionsBase.fetchMethod} option.\n */\n export type Fetcher<K, V, FC = unknown> = (\n key: K,\n staleValue: V | undefined,\n options: FetcherOptions<K, V, FC>\n ) => Promise<V | undefined | void> | V | undefined | void\n\n /**\n * the type signature for the {@link OptionsBase.memoMethod} option.\n */\n export type Memoizer<K, V, FC = unknown> = (\n key: K,\n staleValue: V | undefined,\n options: MemoizerOptions<K, V, FC>\n ) => V\n\n /**\n * Options which may be passed to the {@link LRUCache} constructor.\n *\n * Most of these may be overridden in the various options that use\n * them.\n *\n * Despite all being technically optional, the constructor requires that\n * a cache is at minimum limited by one or more of {@link OptionsBase.max},\n * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.\n *\n * If {@link OptionsBase.ttl} is used alone, then it is strongly advised\n * (and in fact required by the type definitions here) that the cache\n * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially\n * unbounded storage.\n *\n * All options are also available on the {@link LRUCache} instance, making\n * it safe to pass an LRUCache instance as the options argumemnt to\n * make another empty cache of the same type.\n *\n * Some options are marked as read-only, because changing them after\n * instantiation is not safe. Changing any of the other options will of\n * course only have an effect on subsequent method calls.\n */\n export interface OptionsBase<K, V, FC> {\n /**\n * The maximum number of items to store in the cache before evicting\n * old entries. This is read-only on the {@link LRUCache} instance,\n * and may not be overridden.\n *\n * If set, then storage space will be pre-allocated at construction\n * time, and the cache will perform significantly faster.\n *\n * Note that significantly fewer items may be stored, if\n * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also\n * set.\n *\n * **It is strongly recommended to set a `max` to prevent unbounded growth\n * of the cache.**\n */\n max?: Count\n\n /**\n * Max time in milliseconds for items to live in cache before they are\n * considered stale. Note that stale items are NOT preemptively removed by\n * default, and MAY live in the cache, contributing to its LRU max, long\n * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n * set.\n *\n * If set to `0` (the default value), then that means \"do not track\n * TTL\", not \"expire immediately\".\n *\n * Also, as this cache is optimized for LRU/MRU operations, some of\n * the staleness/TTL checks will reduce performance, as they will incur\n * overhead by deleting items.\n *\n * This is not primarily a TTL cache, and does not make strong TTL\n * guarantees. There is no pre-emptive pruning of expired items, but you\n * _may_ set a TTL on the cache, and it will treat expired items as missing\n * when they are fetched, and delete them.\n *\n * Optional, but must be a non-negative integer in ms if specified.\n *\n * This may be overridden by passing an options object to `cache.set()`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if ttl tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\n *\n * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n * and `ttlAutopurge` is not set, then a warning will be emitted\n * cautioning about the potential for unbounded memory consumption.\n * (The TypeScript definitions will also discourage this.)\n */\n ttl?: Milliseconds\n\n /**\n * Minimum amount of time in ms in which to check for staleness.\n * Defaults to 1, which means that the current time is checked\n * at most once per millisecond.\n *\n * Set to 0 to check the current time every time staleness is tested.\n * (This reduces performance, and is theoretically unnecessary.)\n *\n * Setting this to a higher value will improve performance somewhat\n * while using ttl tracking, albeit at the expense of keeping stale\n * items around a bit longer than their TTLs would indicate.\n *\n * @default 1\n */\n ttlResolution?: Milliseconds\n\n /**\n * Preemptively remove stale items from the cache.\n *\n * Note that this may *significantly* degrade performance, especially if\n * the cache is storing a large number of items. It is almost always best\n * to just leave the stale items in the cache, and let them fall out as new\n * items are added.\n *\n * Note that this means that {@link OptionsBase.allowStale} is a bit\n * pointless, as stale items will be deleted almost as soon as they\n * expire.\n *\n * Use with caution!\n */\n ttlAutopurge?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever it is retrieved from cache with\n * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n * of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n */\n updateAgeOnGet?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever its presence in the cache is\n * checked with {@link LRUCache#has}, causing it to not expire. (It can\n * still fall out of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\n */\n updateAgeOnHas?: boolean\n\n /**\n * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return\n * stale data, if available.\n *\n * By default, if you set `ttl`, stale items will only be deleted from the\n * cache when you `get(key)`. That is, it's not preemptively pruning items,\n * unless {@link OptionsBase.ttlAutopurge} is set.\n *\n * If you set `allowStale:true`, it'll return the stale value *as well as*\n * deleting it. If you don't set this, then it'll return `undefined` when\n * you try to get a stale entry.\n *\n * Note that when a stale entry is fetched, _even if it is returned due to\n * `allowStale` being set_, it is removed from the cache immediately. You\n * can suppress this behavior by setting\n * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n * the options provided to {@link LRUCache#get}.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n * The `cache.has()` method will always return `false` for stale items.\n *\n * Only relevant if a ttl is set.\n */\n allowStale?: boolean\n\n /**\n * Function that is called on items when they are dropped from the\n * cache, as `dispose(value, key, reason)`.\n *\n * This can be handy if you want to close file descriptors or do\n * other cleanup tasks when items are no longer stored in the cache.\n *\n * **NOTE**: It is called _before_ the item has been fully removed\n * from the cache, so if you want to put it right back in, you need\n * to wait until the next tick. If you try to add it back in during\n * the `dispose()` function call, it will break things in subtle and\n * weird ways.\n *\n * Unlike several other options, this may _not_ be overridden by\n * passing an option to `set()`, for performance reasons.\n *\n * The `reason` will be one of the following strings, corresponding\n * to the reason for the item's deletion:\n *\n * - `evict` Item was evicted to make space for a new addition\n * - `set` Item was overwritten by a new value\n * - `expire` Item expired its TTL\n * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n * fetchMethod returning `undefined.\n * - `delete` Item was removed by explicit `cache.delete(key)`,\n * `cache.clear()`, or `cache.set(key, undefined)`.\n */\n dispose?: Disposer<K, V>\n\n /**\n * The same as {@link OptionsBase.dispose}, but called *after* the entry\n * is completely removed and the cache is once again in a clean state.\n *\n * It is safe to add an item right back into the cache at this point.\n * However, note that it is *very* easy to inadvertently create infinite\n * recursion this way.\n */\n disposeAfter?: Disposer<K, V>\n\n /**\n * Set to true to suppress calling the\n * {@link OptionsBase.dispose} function if the entry key is\n * still accessible within the cache.\n *\n * This may be overridden by passing an options object to\n * {@link LRUCache#set}.\n *\n * Only relevant if `dispose` or `disposeAfter` are set.\n */\n noDisposeOnSet?: boolean\n\n /**\n * Boolean flag to tell the cache to not update the TTL when setting a new\n * value for an existing key (ie, when updating a value rather than\n * inserting a new value). Note that the TTL value is _always_ set (if\n * provided) when adding a new entry into the cache.\n *\n * Has no effect if a {@link OptionsBase.ttl} is not set.\n *\n * May be passed as an option to {@link LRUCache#set}.\n */\n noUpdateTTL?: boolean\n\n /**\n * Set to a positive integer to track the sizes of items added to the\n * cache, and automatically evict items in order to stay below this size.\n * Note that this may result in fewer than `max` items being stored.\n *\n * Attempting to add an item to the cache whose calculated size is greater\n * that this amount will be a no-op. The item will not be cached, and no\n * other items will be evicted.\n *\n * Optional, must be a positive integer if provided.\n *\n * Sets `maxEntrySize` to the same value, unless a different value is\n * provided for `maxEntrySize`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if size tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\n *\n * Note also that size tracking can negatively impact performance,\n * though for most cases, only minimally.\n */\n maxSize?: Size\n\n /**\n * The maximum allowed size for any single item in the cache.\n *\n * If a larger item is passed to {@link LRUCache#set} or returned by a\n * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then\n * it will not be stored in the cache.\n *\n * Attempting to add an item whose calculated size is greater than\n * this amount will not cache the item or evict any old items, but\n * WILL delete an existing value if one is already present.\n *\n * Optional, must be a positive integer if provided. Defaults to\n * the value of `maxSize` if provided.\n */\n maxEntrySize?: Size\n\n /**\n * A function that returns a number indicating the item's size.\n *\n * Requires {@link OptionsBase.maxSize} to be set.\n *\n * If not provided, and {@link OptionsBase.maxSize} or\n * {@link OptionsBase.maxEntrySize} are set, then all\n * {@link LRUCache#set} calls **must** provide an explicit\n * {@link SetOptions.size} or sizeCalculation param.\n */\n sizeCalculation?: SizeCalculator<K, V>\n\n /**\n * Method that provides the implementation for {@link LRUCache#fetch}\n *\n * ```ts\n * fetchMethod(key, staleValue, { signal, options, context })\n * ```\n *\n * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n * to `Promise.resolve(cache.get(key))`.\n *\n * If at any time, `signal.aborted` is set to `true`, or if the\n * `signal.onabort` method is called, or if it emits an `'abort'` event\n * which you can listen to with `addEventListener`, then that means that\n * the fetch should be abandoned. This may be passed along to async\n * functions aware of AbortController/AbortSignal behavior.\n *\n * The `fetchMethod` should **only** return `undefined` or a Promise\n * resolving to `undefined` if the AbortController signaled an `abort`\n * event. In all other cases, it should return or resolve to a value\n * suitable for adding to the cache.\n *\n * The `options` object is a union of the options that may be provided to\n * `set()` and `get()`. If they are modified, then that will result in\n * modifying the settings to `cache.set()` when the value is resolved, and\n * in the case of\n * {@link OptionsBase.noDeleteOnFetchRejection} and\n * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n * `fetchMethod` failures.\n *\n * For example, a DNS cache may update the TTL based on the value returned\n * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n */\n fetchMethod?: Fetcher<K, V, FC>\n\n /**\n * Method that provides the implementation for {@link LRUCache#memo}\n */\n memoMethod?: Memoizer<K, V, FC>\n\n /**\n * Set to true to suppress the deletion of stale data when a\n * {@link OptionsBase.fetchMethod} returns a rejected promise.\n */\n noDeleteOnFetchRejection?: boolean\n\n /**\n * Do not delete stale items when they are retrieved with\n * {@link LRUCache#get}.\n *\n * Note that the `get` return value will still be `undefined`\n * unless {@link OptionsBase.allowStale} is true.\n *\n * When using time-expiring entries with `ttl`, by default stale\n * items will be removed from the cache when the key is accessed\n * with `cache.get()`.\n *\n * Setting this option will cause stale items to remain in the cache, until\n * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n * `noDeleteOnStaleGet` set to `false`.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n *\n * Only relevant if a ttl is used.\n */\n noDeleteOnStaleGet?: boolean\n\n /**\n * Set to true to allow returning stale data when a\n * {@link OptionsBase.fetchMethod} throws an error or returns a rejected\n * promise.\n *\n * This differs from using {@link OptionsBase.allowStale} in that stale\n * data will ONLY be returned in the case that the {@link LRUCache#fetch}\n * fails, not any other times.\n *\n * If a `fetchMethod` fails, and there is no stale value available, the\n * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n * suppressed.\n *\n * Implies `noDeleteOnFetchRejection`.\n *\n * This may be set in calls to `fetch()`, or defaulted on the constructor,\n * or overridden by modifying the options object in the `fetchMethod`.\n */\n allowStaleOnFetchRejection?: boolean\n\n /**\n * Set to true to return a stale value from the cache when the\n * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches\n * an `'abort'` event, whether user-triggered, or due to internal cache\n * behavior.\n *\n * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying\n * {@link OptionsBase.fetchMethod} will still be considered canceled, and\n * any value it returns will be ignored and not cached.\n *\n * Caveat: since fetches are aborted when a new value is explicitly\n * set in the cache, this can lead to fetch returning a stale value,\n * since that was the fallback value _at the moment the `fetch()` was\n * initiated_, even though the new updated value is now present in\n * the cache.\n *\n * For example:\n *\n * ```ts\n * const cache = new LRUCache<string, any>({\n * ttl: 100,\n * fetchMethod: async (url, oldValue, { signal }) => {\n * const res = await fetch(url, { signal })\n * return await res.json()\n * }\n * })\n * cache.set('https://example.com/', { some: 'data' })\n * // 100ms go by...\n * const result = cache.fetch('https://example.com/')\n * cache.set('https://example.com/', { other: 'thing' })\n * console.log(await result) // { some: 'data' }\n * console.log(cache.get('https://example.com/')) // { other: 'thing' }\n * ```\n */\n allowStaleOnFetchAbort?: boolean\n\n /**\n * Set to true to ignore the `abort` event emitted by the `AbortSignal`\n * object passed to {@link OptionsBase.fetchMethod}, and still cache the\n * resulting resolution value, as long as it is not `undefined`.\n *\n * When used on its own, this means aborted {@link LRUCache#fetch} calls\n * are not immediately resolved or rejected when they are aborted, and\n * instead take the full time to await.\n *\n * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted\n * {@link LRUCache#fetch} calls will resolve immediately to their stale\n * cached value or `undefined`, and will continue to process and eventually\n * update the cache when they resolve, as long as the resulting value is\n * not `undefined`, thus supporting a \"return stale on timeout while\n * refreshing\" mechanism by passing `AbortSignal.timeout(n)` as the signal.\n *\n * For example:\n *\n * ```ts\n * const c = new LRUCache({\n * ttl: 100,\n * ignoreFetchAbort: true,\n * allowStaleOnFetchAbort: true,\n * fetchMethod: async (key, oldValue, { signal }) => {\n * // note: do NOT pass the signal to fetch()!\n * // let's say this fetch can take a long time.\n * const res = await fetch(`https://slow-backend-server/${key}`)\n * return await res.json()\n * },\n * })\n *\n * // this will return the stale value after 100ms, while still\n * // updating in the background for next time.\n * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n * ```\n *\n * **Note**: regardless of this setting, an `abort` event _is still\n * emitted on the `AbortSignal` object_, so may result in invalid results\n * when passed to other underlying APIs that use AbortSignals.\n *\n * This may be overridden in the {@link OptionsBase.fetchMethod} or the\n * call to {@link LRUCache#fetch}.\n */\n ignoreFetchAbort?: boolean\n }\n\n export interface OptionsMaxLimit<K, V, FC>\n extends OptionsBase<K, V, FC> {\n max: Count\n }\n export interface OptionsTTLLimit<K, V, FC>\n extends OptionsBase<K, V, FC> {\n ttl: Milliseconds\n ttlAutopurge: boolean\n }\n export interface OptionsSizeLimit<K, V, FC>\n extends OptionsBase<K, V, FC> {\n maxSize: Size\n }\n\n /**\n * The valid safe options for the {@link LRUCache} constructor\n */\n export type Options<K, V, FC> =\n | OptionsMaxLimit<K, V, FC>\n | OptionsSizeLimit<K, V, FC>\n | OptionsTTLLimit<K, V, FC>\n\n /**\n * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},\n * and returned by {@link LRUCache#info}.\n */\n export interface Entry<V> {\n value: V\n ttl?: Milliseconds\n size?: Size\n start?: Milliseconds\n }\n}\n\n/**\n * Default export, the thing you're using this module to get.\n *\n * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache<K extends {}, V extends {}, FC = unknown>\n implements Map<K, V>\n{\n // options that cannot be changed without disaster\n readonly #max: LRUCache.Count\n readonly #maxSize: LRUCache.Size\n readonly #dispose?: LRUCache.Disposer<K, V>\n readonly #disposeAfter?: LRUCache.Disposer<K, V>\n readonly #fetchMethod?: LRUCache.Fetcher<K, V, FC>\n readonly #memoMethod?: LRUCache.Memoizer<K, V, FC>\n\n /**\n * {@link LRUCache.OptionsBase.ttl}\n */\n ttl: LRUCache.Milliseconds\n\n /**\n * {@link LRUCache.OptionsBase.ttlResolution}\n */\n ttlResolution: LRUCache.Milliseconds\n /**\n * {@link LRUCache.OptionsBase.ttlAutopurge}\n */\n ttlAutopurge: boolean\n /**\n * {@link LRUCache.OptionsBase.updateAgeOnGet}\n */\n updateAgeOnGet: boolean\n /**\n * {@link LRUCache.OptionsBase.updateAgeOnHas}\n */\n updateAgeOnHas: boolean\n /**\n * {@link LRUCache.OptionsBase.allowStale}\n */\n allowStale: boolean\n\n /**\n * {@link LRUCache.OptionsBase.noDisposeOnSet}\n */\n noDisposeOnSet: boolean\n /**\n * {@link LRUCache.OptionsBase.noUpdateTTL}\n */\n noUpdateTTL: boolean\n /**\n * {@link LRUCache.OptionsBase.maxEntrySize}\n */\n maxEntrySize: LRUCache.Size\n /**\n * {@link LRUCache.OptionsBase.sizeCalculation}\n */\n sizeCalculation?: LRUCache.SizeCalculator<K, V>\n /**\n * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n */\n noDeleteOnFetchRejection: boolean\n /**\n * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n */\n noDeleteOnStaleGet: boolean\n /**\n * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n */\n allowStaleOnFetchAbort: boolean\n /**\n * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n */\n allowStaleOnFetchRejection: boolean\n /**\n * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n */\n ignoreFetchAbort: boolean\n\n // computed properties\n #size: LRUCache.Count\n #calculatedSize: LRUCache.Size\n #keyMap: Map<K, Index>\n #keyList: (K | undefined)[]\n #valList: (V | BackgroundFetch<V> | undefined)[]\n #next: NumberArray\n #prev: NumberArray\n #head: Index\n #tail: Index\n #free: StackLike\n #disposed?: DisposeTask<K, V>[]\n #sizes?: ZeroArray\n #starts?: ZeroArray\n #ttls?: ZeroArray\n\n #hasDispose: boolean\n #hasFetchMethod: boolean\n #hasDisposeAfter: boolean\n\n /**\n * Do not call this method unless you need to inspect the\n * inner workings of the cache. If anything returned by this\n * object is modified in any way, strange breakage may occur.\n *\n * These fields are private for a reason!\n *\n * @internal\n */\n static unsafeExposeInternals<\n K extends {},\n V extends {},\n FC extends unknown = unknown\n >(c: LRUCache<K, V, FC>) {\n return {\n // properties\n starts: c.#starts,\n ttls: c.#ttls,\n sizes: c.#sizes,\n keyMap: c.#keyMap as Map<K, number>,\n keyList: c.#keyList,\n valList: c.#valList,\n next: c.#next,\n prev: c.#prev,\n get head() {\n return c.#head\n },\n get tail() {\n return c.#tail\n },\n free: c.#free,\n // methods\n isBackgroundFetch: (p: any) => c.#isBackgroundFetch(p),\n backgroundFetch: (\n k: K,\n index: number | undefined,\n options: LRUCache.FetchOptions<K, V, FC>,\n context: any\n ): BackgroundFetch<V> =>\n c.#backgroundFetch(\n k,\n index as Index | undefined,\n options,\n context\n ),\n moveToTail: (index: number): void =>\n c.#moveToTail(index as Index),\n indexes: (options?: { allowStale: boolean }) =>\n c.#indexes(options),\n rindexes: (options?: { allowStale: boolean }) =>\n c.#rindexes(options),\n isStale: (index: number | undefined) =>\n c.#isStale(index as Index),\n }\n }\n\n // Protected read-only members\n\n /**\n * {@link LRUCache.OptionsBase.max} (read-only)\n */\n get max(): LRUCache.Count {\n return this.#max\n }\n /**\n * {@link LRUCache.OptionsBase.maxSize} (read-only)\n */\n get maxSize(): LRUCache.Count {\n return this.#maxSize\n }\n /**\n * The total computed size of items in the cache (read-only)\n */\n get calculatedSize(): LRUCache.Size {\n return this.#calculatedSize\n }\n /**\n * The number of items stored in the cache (read-only)\n */\n get size(): LRUCache.Count {\n return this.#size\n }\n /**\n * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n */\n get fetchMethod(): LRUCache.Fetcher<K, V, FC> | undefined {\n return this.#fetchMethod\n }\n get memoMethod(): LRUCache.Memoizer<K, V, FC> | undefined {\n return this.#memoMethod\n }\n /**\n * {@link LRUCache.OptionsBase.dispose} (read-only)\n */\n get dispose() {\n return this.#dispose\n }\n /**\n * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n */\n get disposeAfter() {\n return this.#disposeAfter\n }\n\n constructor(\n options: LRUCache.Options<K, V, FC> | LRUCache<K, V, FC>\n ) {\n const {\n max = 0,\n ttl,\n ttlResolution = 1,\n ttlAutopurge,\n updateAgeOnGet,\n updateAgeOnHas,\n allowStale,\n dispose,\n disposeAfter,\n noDisposeOnSet,\n noUpdateTTL,\n maxSize = 0,\n maxEntrySize = 0,\n sizeCalculation,\n fetchMethod,\n memoMethod,\n noDeleteOnFetchRejection,\n noDeleteOnStaleGet,\n allowStaleOnFetchRejection,\n allowStaleOnFetchAbort,\n ignoreFetchAbort,\n } = options\n\n if (max !== 0 && !isPosInt(max)) {\n throw new TypeError('max option must be a nonnegative integer')\n }\n\n const UintArray = max ? getUintArray(max) : Array\n if (!UintArray) {\n throw new Error('invalid max value: ' + max)\n }\n\n this.#max = max\n this.#maxSize = maxSize\n this.maxEntrySize = maxEntrySize || this.#maxSize\n this.sizeCalculation = sizeCalculation\n if (this.sizeCalculation) {\n if (!this.#maxSize && !this.maxEntrySize) {\n throw new TypeError(\n 'cannot set sizeCalculation without setting maxSize or maxEntrySize'\n )\n }\n if (typeof this.sizeCalculation !== 'function') {\n throw new TypeError('sizeCalculation set to non-function')\n }\n }\n\n if (\n memoMethod !== undefined &&\n typeof memoMethod !== 'function'\n ) {\n throw new TypeError('memoMethod must be a function if defined')\n }\n this.#memoMethod = memoMethod\n\n if (\n fetchMethod !== undefined &&\n typeof fetchMethod !== 'function'\n ) {\n throw new TypeError(\n 'fetchMethod must be a function if specified'\n )\n }\n this.#fetchMethod = fetchMethod\n this.#hasFetchMethod = !!fetchMethod\n\n this.#keyMap = new Map()\n this.#keyList = new Array(max).fill(undefined)\n this.#valList = new Array(max).fill(undefined)\n this.#next = new UintArray(max)\n this.#prev = new UintArray(max)\n this.#head = 0 as Index\n this.#tail = 0 as Index\n this.#free = Stack.create(max)\n this.#size = 0\n this.#calculatedSize = 0\n\n if (typeof dispose === 'function') {\n this.#dispose = dispose\n }\n if (typeof disposeAfter === 'function') {\n this.#disposeAfter = disposeAfter\n this.#disposed = []\n } else {\n this.#disposeAfter = undefined\n this.#disposed = undefined\n }\n this.#hasDispose = !!this.#dispose\n this.#hasDisposeAfter = !!this.#disposeAfter\n\n this.noDisposeOnSet = !!noDisposeOnSet\n this.noUpdateTTL = !!noUpdateTTL\n this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection\n this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection\n this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort\n this.ignoreFetchAbort = !!ignoreFetchAbort\n\n // NB: maxEntrySize is set to maxSize if it's set\n if (this.maxEntrySize !== 0) {\n if (this.#maxSize !== 0) {\n if (!isPosInt(this.#maxSize)) {\n throw new TypeError(\n 'maxSize must be a positive integer if specified'\n )\n }\n }\n if (!isPosInt(this.maxEntrySize)) {\n throw new TypeError(\n 'maxEntrySize must be a positive integer if specified'\n )\n }\n this.#initializeSizeTracking()\n }\n\n this.allowStale = !!allowStale\n this.noDeleteOnStaleGet = !!noDeleteOnStaleGet\n this.updateAgeOnGet = !!updateAgeOnGet\n this.updateAgeOnHas = !!updateAgeOnHas\n this.ttlResolution =\n isPosInt(ttlResolution) || ttlResolution === 0\n ? ttlResolution\n : 1\n this.ttlAutopurge = !!ttlAutopurge\n this.ttl = ttl || 0\n if (this.ttl) {\n if (!isPosInt(this.ttl)) {\n throw new TypeError(\n 'ttl must be a positive integer if specified'\n )\n }\n this.#initializeTTLTracking()\n }\n\n // do not allow completely unbounded caches\n if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {\n throw new TypeError(\n 'At least one of max, maxSize, or ttl is required'\n )\n }\n if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {\n const code = 'LRU_CACHE_UNBOUNDED'\n if (shouldWarn(code)) {\n warned.add(code)\n const msg =\n 'TTL caching without ttlAutopurge, max, or maxSize can ' +\n 'result in unbounded memory consumption.'\n emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache)\n }\n }\n }\n\n /**\n * Return the number of ms left in the item's TTL. If item is not in cache,\n * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\n */\n getRemainingTTL(key: K) {\n return this.#keyMap.has(key) ? Infinity : 0\n }\n\n #initializeTTLTracking() {\n const ttls = new ZeroArray(this.#max)\n const starts = new ZeroArray(this.#max)\n this.#ttls = ttls\n this.#starts = starts\n\n this.#setItemTTL = (index, ttl, start = perf.now()) => {\n starts[index] = ttl !== 0 ? start : 0\n ttls[index] = ttl\n if (ttl !== 0 && this.ttlAutopurge) {\n const t = setTimeout(() => {\n if (this.#isStale(index)) {\n this.#delete(this.#keyList[index] as K, 'expire')\n }\n }, ttl + 1)\n // unref() not supported on all platforms\n /* c8 ignore start */\n if (t.unref) {\n t.unref()\n }\n /* c8 ignore stop */\n }\n }\n\n this.#updateItemAge = index => {\n starts[index] = ttls[index] !== 0 ? perf.now() : 0\n }\n\n this.#statusTTL = (status, index) => {\n if (ttls[index]) {\n const ttl = ttls[index]\n const start = starts[index]\n /* c8 ignore next */\n if (!ttl || !start) return\n status.ttl = ttl\n status.start = start\n status.now = cachedNow || getNow()\n const age = status.now - start\n status.remainingTTL = ttl - age\n }\n }\n\n // debounce calls to perf.now() to 1s so we're not hitting\n // that costly call repeatedly.\n let cachedNow = 0\n const getNow = () => {\n const n = perf.now()\n if (this.ttlResolution > 0) {\n cachedNow = n\n const t = setTimeout(\n () => (cachedNow = 0),\n this.ttlResolution\n )\n // not available on all platforms\n /* c8 ignore start */\n if (t.unref) {\n t.unref()\n }\n /* c8 ignore stop */\n }\n return n\n }\n\n this.getRemainingTTL = key => {\n const index = this.#keyMap.get(key)\n if (index === undefined) {\n return 0\n }\n const ttl = ttls[index]\n const start = starts[index]\n if (!ttl || !start) {\n return Infinity\n }\n const age = (cachedNow || getNow()) - start\n return ttl - age\n }\n\n this.#isStale = index => {\n const s = starts[index]\n const t = ttls[index]\n return !!t && !!s && (cachedNow || getNow()) - s > t\n }\n }\n\n // conditionally set private methods related to TTL\n #updateItemAge: (index: Index) => void = () => {}\n #statusTTL: (status: LRUCache.Status<V>, index: Index) => void =\n () => {}\n #setItemTTL: (\n index: Index,\n ttl: LRUCache.Milliseconds,\n start?: LRUCache.Milliseconds\n // ignore because we never call this if we're not already in TTL mode\n /* c8 ignore start */\n ) => void = () => {}\n /* c8 ignore stop */\n\n #isStale: (index: Index) => boolean = () => false\n\n #initializeSizeTracking() {\n const sizes = new ZeroArray(this.#max)\n this.#calculatedSize = 0\n this.#sizes = sizes\n this.#removeItemSize = index => {\n this.#calculatedSize -= sizes[index] as number\n sizes[index] = 0\n }\n this.#requireSize = (k, v, size, sizeCalculation) => {\n // provisionally accept background fetches.\n // actual value size will be checked when they return.\n if (this.#isBackgroundFetch(v)) {\n return 0\n }\n if (!isPosInt(size)) {\n if (sizeCalculation) {\n if (typeof sizeCalculation !== 'function') {\n throw new TypeError('sizeCalculation must be a function')\n }\n size = sizeCalculation(v, k)\n if (!isPosInt(size)) {\n throw new TypeError(\n 'sizeCalculation return invalid (expect positive integer)'\n )\n }\n } else {\n throw new TypeError(\n 'invalid size value (must be positive integer). ' +\n 'When maxSize or maxEntrySize is used, sizeCalculation ' +\n 'or size must be set.'\n )\n }\n }\n return size\n }\n this.#addItemSize = (\n index: Index,\n size: LRUCache.Size,\n status?: LRUCache.Status<V>\n ) => {\n sizes[index] = size\n if (this.#maxSize) {\n const maxSize = this.#maxSize - (sizes[index] as number)\n while (this.#calculatedSize > maxSize) {\n this.#evict(true)\n }\n }\n this.#calculatedSize += sizes[index] as number\n if (status) {\n status.entrySize = size\n status.totalCalculatedSize = this.#calculatedSize\n }\n }\n }\n\n #removeItemSize: (index: Index) => void = _i => {}\n #addItemSize: (\n index: Index,\n size: LRUCache.Size,\n status?: LRUCache.Status<V>\n ) => void = (_i, _s, _st) => {}\n #requireSize: (\n k: K,\n v: V | BackgroundFetch<V>,\n size?: LRUCache.Size,\n sizeCalculation?: LRUCache.SizeCalculator<K, V>\n ) => LRUCache.Size = (\n _k: K,\n _v: V | BackgroundFetch<V>,\n size?: LRUCache.Size,\n sizeCalculation?: LRUCache.SizeCalculator<K, V>\n ) => {\n if (size || sizeCalculation) {\n throw new TypeError(\n 'cannot set size without setting maxSize or maxEntrySize on cache'\n )\n }\n return 0\n };\n\n *#indexes({ allowStale = this.allowStale } = {}) {\n if (this.#size) {\n for (let i = this.#tail; true; ) {\n if (!this.#isValidIndex(i)) {\n break\n }\n if (allowStale || !this.#isStale(i)) {\n yield i\n }\n if (i === this.#head) {\n break\n } else {\n i = this.#prev[i] as Index\n }\n }\n }\n }\n\n *#rindexes({ allowStale = this.allowStale } = {}) {\n if (this.#size) {\n for (let i = this.#head; true; ) {\n if (!this.#isValidIndex(i)) {\n break\n }\n if (allowStale || !this.#isStale(i)) {\n yield i\n }\n if (i === this.#tail) {\n break\n } else {\n i = this.#next[i] as Index\n }\n }\n }\n }\n\n #isValidIndex(index: Index) {\n return (\n index !== undefined &&\n this.#keyMap.get(this.#keyList[index] as K) === index\n )\n }\n\n /**\n * Return a generator yielding `[key, value]` pairs,\n * in order from most recently used to least recently used.\n */\n *entries() {\n for (const i of this.#indexes()) {\n if (\n this.#valList[i] !== undefined &&\n this.#keyList[i] !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield [this.#keyList[i], this.#valList[i]] as [K, V]\n }\n }\n }\n\n /**\n * Inverse order version of {@link LRUCache.entries}\n *\n * Return a generator yielding `[key, value]` pairs,\n * in order from least recently used to most recently used.\n */\n *rentries() {\n for (const i of this.#rindexes()) {\n if (\n this.#valList[i] !== undefined &&\n this.#keyList[i] !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield [this.#keyList[i], this.#valList[i]]\n }\n }\n }\n\n /**\n * Return a generator yielding the keys in the cache,\n * in order from most recently used to least recently used.\n */\n *keys() {\n for (const i of this.#indexes()) {\n const k = this.#keyList[i]\n if (\n k !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield k\n }\n }\n }\n\n /**\n * Inverse order version of {@link LRUCache.keys}\n *\n * Return a generator yielding the keys in the cache,\n * in order from least recently used to most recently used.\n */\n *rkeys() {\n for (const i of this.#rindexes()) {\n const k = this.#keyList[i]\n if (\n k !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield k\n }\n }\n }\n\n /**\n * Return a generator yielding the values in the cache,\n * in order from most recently used to least recently used.\n */\n *values() {\n for (const i of this.#indexes()) {\n const v = this.#valList[i]\n if (\n v !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield this.#valList[i] as V\n }\n }\n }\n\n /**\n * Inverse order version of {@link LRUCache.values}\n *\n * Return a generator yielding the values in the cache,\n * in order from least recently used to most recently used.\n */\n *rvalues() {\n for (const i of this.#rindexes()) {\n const v = this.#valList[i]\n if (\n v !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield this.#valList[i]\n }\n }\n }\n\n /**\n * Iterating over the cache itself yields the same results as\n * {@link LRUCache.entries}\n */\n [Symbol.iterator]() {\n return this.entries()\n }\n\n /**\n * A String value that is used in the creation of the default string\n * description of an object. Called by the built-in method\n * `Object.prototype.toString`.\n */\n [Symbol.toStringTag] = 'LRUCache'\n\n /**\n * Find a value for which the supplied fn method returns a truthy value,\n * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.\n */\n find(\n fn: (v: V, k: K, self: LRUCache<K, V, FC>) => boolean,\n getOptions: LRUCache.GetOptions<K, V, FC> = {}\n ) {\n for (const i of this.#indexes()) {\n const v = this.#valList[i]\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) continue\n if (fn(value, this.#keyList[i] as K, this)) {\n return this.get(this.#keyList[i] as K, getOptions)\n }\n }\n }\n\n /**\n * Call the supplied function on each item in the cache, in order from most\n * recently used to least recently used.\n *\n * `fn` is called as `fn(value, key, cache)`.\n *\n * If `thisp` is provided, function will be called in the `this`-context of\n * the provided object, or the cache if no `thisp` object is provided.\n *\n * Does not update age or recenty of use, or iterate over stale values.\n */\n forEach(\n fn: (v: V, k: K, self: LRUCache<K, V, FC>) => any,\n thisp: any = this\n ) {\n for (const i of this.#indexes()) {\n const v = this.#valList[i]\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) continue\n fn.call(thisp, value, this.#keyList[i] as K, this)\n }\n }\n\n /**\n * The same as {@link LRUCache.forEach} but items are iterated over in\n * reverse order. (ie, less recently used items are iterated over first.)\n */\n rforEach(\n fn: (v: V, k: K, self: LRUCache<K, V, FC>) => any,\n thisp: any = this\n ) {\n for (const i of this.#rindexes()) {\n const v = this.#valList[i]\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) continue\n fn.call(thisp, value, this.#keyList[i] as K, this)\n }\n }\n\n /**\n * Delete any stale entries. Returns true if anything was removed,\n * false otherwise.\n */\n purgeStale() {\n let deleted = false\n for (const i of this.#rindexes({ allowStale: true })) {\n if (this.#isStale(i)) {\n this.#delete(this.#keyList[i] as K, 'expire')\n deleted = true\n }\n }\n return deleted\n }\n\n /**\n * Get the extended info about a given entry, to get its value, size, and\n * TTL info simultaneously. Returns `undefined` if the key is not present.\n *\n * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n * serialization, the `start` value is always the current timestamp, and the\n * `ttl` is a calculated remaining time to live (negative if expired).\n *\n * Always returns stale values, if their info is found in the cache, so be\n * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n * if relevant.\n */\n info(key: K): LRUCache.Entry<V> | undefined {\n const i = this.#keyMap.get(key)\n if (i === undefined) return undefined\n const v = this.#valList[i]\n const value: V | undefined = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) return undefined\n const entry: LRUCache.Entry<V> = { value }\n if (this.#ttls && this.#starts) {\n const ttl = this.#ttls[i]\n const start = this.#starts[i]\n if (ttl && start) {\n const remain = ttl - (perf.now() - start)\n entry.ttl = remain\n entry.start = Date.now()\n }\n }\n if (this.#sizes) {\n entry.size = this.#sizes[i]\n }\n return entry\n }\n\n /**\n * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n * passed to {@link LRLUCache#load}.\n *\n * The `start` fields are calculated relative to a portable `Date.now()`\n * timestamp, even if `performance.now()` is available.\n *\n * Stale entries are always included in the `dump`, even if\n * {@link LRUCache.OptionsBase.allowStale} is false.\n *\n * Note: this returns an actual array, not a generator, so it can be more\n * easily passed around.\n */\n dump() {\n const arr: [K, LRUCache.Entry<V>][] = []\n for (const i of this.#indexes({ allowStale: true })) {\n const key = this.#keyList[i]\n const v = this.#valList[i]\n const value: V | undefined = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined || key === undefined) continue\n const entry: LRUCache.Entry<V> = { value }\n if (this.#ttls && this.#starts) {\n entry.ttl = this.#ttls[i]\n // always dump the start relative to a portable timestamp\n // it's ok for this to be a bit slow, it's a rare operation.\n const age = perf.now() - (this.#starts[i] as number)\n entry.start = Math.floor(Date.now() - age)\n }\n if (this.#sizes) {\n entry.size = this.#sizes[i]\n }\n arr.unshift([key, entry])\n }\n return arr\n }\n\n /**\n * Reset the cache and load in the items in entries in the order listed.\n *\n * The shape of the resulting cache may be different if the same options are\n * not used in both caches.\n *\n * The `start` fields are assumed to be calculated relative to a portable\n * `Date.now()` timestamp, even if `performance.now()` is available.\n */\n load(arr: [K, LRUCache.Entry<V>][]) {\n this.clear()\n for (const [key, entry] of arr) {\n if (entry.start) {\n // entry.start is a portable timestamp, but we may be using\n // node's performance.now(), so calculate the offset, so that\n // we get the intended remaining TTL, no matter how long it's\n // been on ice.\n //\n // it's ok for this to be a bit slow, it's a rare operation.\n const age = Date.now() - entry.start\n entry.start = perf.now() - age\n }\n this.set(key, entry.value, entry)\n }\n }\n\n /**\n * Add a value to the cache.\n *\n * Note: if `undefined` is specified as a value, this is an alias for\n * {@link LRUCache#delete}\n *\n * Fields on the {@link LRUCache.SetOptions} options param will override\n * their corresponding values in the constructor options for the scope\n * of this single `set()` operation.\n *\n * If `start` is provided, then that will set the effective start\n * time for the TTL calculation. Note that this must be a previous\n * value of `performance.now()` if supported, or a previous value of\n * `Date.now()` if not.\n *\n * Options object may also include `size`, which will prevent\n * calling the `sizeCalculation` function and just use the specified\n * number if it is a positive integer, and `noDisposeOnSet` which\n * will prevent calling a `dispose` function in the case of\n * overwrites.\n *\n * If the `size` (or return value of `sizeCalculation`) for a given\n * entry is greater than `maxEntrySize`, then the item will not be\n * added to the cache.\n *\n * Will update the recency of the entry.\n *\n * If the value is `undefined`, then this is an alias for\n * `cache.delete(key)`. `undefined` is never stored in the cache.\n */\n set(\n k: K,\n v: V | BackgroundFetch<V> | undefined,\n setOptions: LRUCache.SetOptions<K, V, FC> = {}\n ) {\n if (v === undefined) {\n this.delete(k)\n return this\n }\n const {\n ttl = this.ttl,\n start,\n noDisposeOnSet = this.noDisposeOnSet,\n sizeCalculation = this.sizeCalculation,\n status,\n } = setOptions\n let { noUpdateTTL = this.noUpdateTTL } = setOptions\n\n const size = this.#requireSize(\n k,\n v,\n setOptions.size || 0,\n sizeCalculation\n )\n // if the item doesn't fit, don't do anything\n // NB: maxEntrySize set to maxSize by default\n if (this.maxEntrySize && size > this.maxEntrySize) {\n if (status) {\n status.set = 'miss'\n status.maxEntrySizeExceeded = true\n }\n // have to delete, in case something is there already.\n this.#delete(k, 'set')\n return this\n }\n let index = this.#size === 0 ? undefined : this.#keyMap.get(k)\n if (index === undefined) {\n // addition\n index = (\n this.#size === 0\n ? this.#tail\n : this.#free.length !== 0\n ? this.#free.pop()\n : this.#size === this.#max\n ? this.#evict(false)\n : this.#size\n ) as Index\n this.#keyList[index] = k\n this.#valList[index] = v\n this.#keyMap.set(k, index)\n this.#next[this.#tail] = index\n this.#prev[index] = this.#tail\n this.#tail = index\n this.#size++\n this.#addItemSize(index, size, status)\n if (status) status.set = 'add'\n noUpdateTTL = false\n } else {\n // update\n this.#moveToTail(index)\n const oldVal = this.#valList[index] as V | BackgroundFetch<V>\n if (v !== oldVal) {\n if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {\n oldVal.__abortController.abort(new Error('replaced'))\n const { __staleWhileFetching: s } = oldVal\n if (s !== undefined && !noDisposeOnSet) {\n if (this.#hasDispose) {\n this.#dispose?.(s as V, k, 'set')\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([s as V, k, 'set'])\n }\n }\n } else if (!noDisposeOnSet) {\n if (this.#hasDispose) {\n this.#dispose?.(oldVal as V, k, 'set')\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([oldVal as V, k, 'set'])\n }\n }\n this.#removeItemSize(index)\n this.#addItemSize(index, size, status)\n this.#valList[index] = v\n if (status) {\n status.set = 'replace'\n const oldValue =\n oldVal && this.#isBackgroundFetch(oldVal)\n ? oldVal.__staleWhileFetching\n : oldVal\n if (oldValue !== undefined) status.oldValue = oldValue\n }\n } else if (status) {\n status.set = 'update'\n }\n }\n if (ttl !== 0 && !this.#ttls) {\n this.#initializeTTLTracking()\n }\n if (this.#ttls) {\n if (!noUpdateTTL) {\n this.#setItemTTL(index, ttl, start)\n }\n if (status) this.#statusTTL(status, index)\n }\n if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n return this\n }\n\n /**\n * Evict the least recently used item, returning its value or\n * `undefined` if cache is empty.\n */\n pop(): V | undefined {\n try {\n while (this.#size) {\n const val = this.#valList[this.#head]\n this.#evict(true)\n if (this.#isBackgroundFetch(val)) {\n if (val.__staleWhileFetching) {\n return val.__staleWhileFetching\n }\n } else if (val !== undefined) {\n return val\n }\n }\n } finally {\n if (this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n }\n }\n\n #evict(free: boolean) {\n const head = this.#head\n const k = this.#keyList[head] as K\n const v = this.#valList[head] as V\n if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('evicted'))\n } else if (this.#hasDispose || this.#hasDisposeAfter) {\n if (this.#hasDispose) {\n this.#dispose?.(v, k, 'evict')\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v, k, 'evict'])\n }\n }\n this.#removeItemSize(head)\n // if we aren't about to use the index, then null these out\n if (free) {\n this.#keyList[head] = undefined\n this.#valList[head] = undefined\n this.#free.push(head)\n }\n if (this.#size === 1) {\n this.#head = this.#tail = 0 as Index\n this.#free.length = 0\n } else {\n this.#head = this.#next[head] as Index\n }\n this.#keyMap.delete(k)\n this.#size--\n return head\n }\n\n /**\n * Check if a key is in the cache, without updating the recency of use.\n * Will return false if the item is stale, even though it is technically\n * in the cache.\n *\n * Check if a key is in the cache, without updating the recency of\n * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n * to `true` in either the options or the constructor.\n *\n * Will return `false` if the item is stale, even though it is technically in\n * the cache. The difference can be determined (if it matters) by using a\n * `status` argument, and inspecting the `has` field.\n *\n * Will not update item age unless\n * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n */\n has(k: K, hasOptions: LRUCache.HasOptions<K, V, FC> = {}) {\n const { updateAgeOnHas = this.updateAgeOnHas, status } =\n hasOptions\n const index = this.#keyMap.get(k)\n if (index !== undefined) {\n const v = this.#valList[index]\n if (\n this.#isBackgroundFetch(v) &&\n v.__staleWhileFetching === undefined\n ) {\n return false\n }\n if (!this.#isStale(index)) {\n if (updateAgeOnHas) {\n this.#updateItemAge(index)\n }\n if (status) {\n status.has = 'hit'\n this.#statusTTL(status, index)\n }\n return true\n } else if (status) {\n status.has = 'stale'\n this.#statusTTL(status, index)\n }\n } else if (status) {\n status.has = 'miss'\n }\n return false\n }\n\n /**\n * Like {@link LRUCache#get} but doesn't update recency or delete stale\n * items.\n *\n * Returns `undefined` if the item is stale, unless\n * {@link LRUCache.OptionsBase.allowStale} is set.\n */\n peek(k: K, peekOptions: LRUCache.PeekOptions<K, V, FC> = {}) {\n const { allowStale = this.allowStale } = peekOptions\n const index = this.#keyMap.get(k)\n if (\n index === undefined ||\n (!allowStale && this.#isStale(index))\n ) {\n return\n }\n const v = this.#valList[index]\n // either stale and allowed, or forcing a refresh of non-stale value\n return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n }\n\n #backgroundFetch(\n k: K,\n index: Index | undefined,\n options: LRUCache.FetchOptions<K, V, FC>,\n context: any\n ): BackgroundFetch<V> {\n const v = index === undefined ? undefined : this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n return v\n }\n\n const ac = new AC()\n const { signal } = options\n // when/if our AC signals, then stop listening to theirs.\n signal?.addEventListener('abort', () => ac.abort(signal.reason), {\n signal: ac.signal,\n })\n\n const fetchOpts = {\n signal: ac.signal,\n options,\n context,\n }\n\n const cb = (\n v: V | undefined,\n updateCache = false\n ): V | undefined => {\n const { aborted } = ac.signal\n const ignoreAbort = options.ignoreFetchAbort && v !== undefined\n if (options.status) {\n if (aborted && !updateCache) {\n options.status.fetchAborted = true\n options.status.fetchError = ac.signal.reason\n if (ignoreAbort) options.status.fetchAbortIgnored = true\n } else {\n options.status.fetchResolved = true\n }\n }\n if (aborted && !ignoreAbort && !updateCache) {\n return fetchFail(ac.signal.reason)\n }\n // either we didn't abort, and are still here, or we did, and ignored\n const bf = p as BackgroundFetch<V>\n if (this.#valList[index as Index] === p) {\n if (v === undefined) {\n if (bf.__staleWhileFetching) {\n this.#valList[index as Index] = bf.__staleWhileFetching\n } else {\n this.#delete(k, 'fetch')\n }\n } else {\n if (options.status) options.status.fetchUpdated = true\n this.set(k, v, fetchOpts.options)\n }\n }\n return v\n }\n\n const eb = (er: any) => {\n if (options.status) {\n options.status.fetchRejected = true\n options.status.fetchError = er\n }\n return fetchFail(er)\n }\n\n const fetchFail = (er: any): V | undefined => {\n const { aborted } = ac.signal\n const allowStaleAborted =\n aborted && options.allowStaleOnFetchAbort\n const allowStale =\n allowStaleAborted || options.allowStaleOnFetchRejection\n const noDelete = allowStale || options.noDeleteOnFetchRejection\n const bf = p as BackgroundFetch<V>\n if (this.#valList[index as Index] === p) {\n // if we allow stale on fetch rejections, then we need to ensure that\n // the stale value is not removed from the cache when the fetch fails.\n const del = !noDelete || bf.__staleWhileFetching === undefined\n if (del) {\n this.#delete(k, 'fetch')\n } else if (!allowStaleAborted) {\n // still replace the *promise* with the stale value,\n // since we are done with the promise at this point.\n // leave it untouched if we're still waiting for an\n // aborted background fetch that hasn't yet returned.\n this.#valList[index as Index] = bf.__staleWhileFetching\n }\n }\n if (allowStale) {\n if (options.status && bf.__staleWhileFetching !== undefined) {\n options.status.returnedStale = true\n }\n return bf.__staleWhileFetching\n } else if (bf.__returned === bf) {\n throw er\n }\n }\n\n const pcall = (\n res: (v: V | undefined) => void,\n rej: (e: any) => void\n ) => {\n const fmp = this.#fetchMethod?.(k, v, fetchOpts)\n if (fmp && fmp instanceof Promise) {\n fmp.then(v => res(v === undefined ? undefined : v), rej)\n }\n // ignored, we go until we finish, regardless.\n // defer check until we are actually aborting,\n // so fetchMethod can override.\n ac.signal.addEventListener('abort', () => {\n if (\n !options.ignoreFetchAbort ||\n options.allowStaleOnFetchAbort\n ) {\n res(undefined)\n // when it eventually resolves, update the cache.\n if (options.allowStaleOnFetchAbort) {\n res = v => cb(v, true)\n }\n }\n })\n }\n\n if (options.status) options.status.fetchDispatched = true\n const p = new Promise(pcall).then(cb, eb)\n const bf: BackgroundFetch<V> = Object.assign(p, {\n __abortController: ac,\n __staleWhileFetching: v,\n __returned: undefined,\n })\n\n if (index === undefined) {\n // internal, don't expose status.\n this.set(k, bf, { ...fetchOpts.options, status: undefined })\n index = this.#keyMap.get(k)\n } else {\n this.#valList[index] = bf\n }\n return bf\n }\n\n #isBackgroundFetch(p: any): p is BackgroundFetch<V> {\n if (!this.#hasFetchMethod) return false\n const b = p as BackgroundFetch<V>\n return (\n !!b &&\n b instanceof Promise &&\n b.hasOwnProperty('__staleWhileFetching') &&\n b.__abortController instanceof AC\n )\n }\n\n /**\n * Make an asynchronous cached fetch using the\n * {@link LRUCache.OptionsBase.fetchMethod} function.\n *\n * If the value is in the cache and not stale, then the returned\n * Promise resolves to the value.\n *\n * If not in the cache, or beyond its TTL staleness, then\n * `fetchMethod(key, staleValue, { options, signal, context })` is\n * called, and the value returned will be added to the cache once\n * resolved.\n *\n * If called with `allowStale`, and an asynchronous fetch is\n * currently in progress to reload a stale value, then the former\n * stale value will be returned.\n *\n * If called with `forceRefresh`, then the cached item will be\n * re-fetched, even if it is not stale. However, if `allowStale` is also\n * set, then the old value will still be returned. This is useful\n * in cases where you want to force a reload of a cached value. If\n * a background fetch is already in progress, then `forceRefresh`\n * has no effect.\n *\n * If multiple fetches for the same key are issued, then they will all be\n * coalesced into a single call to fetchMethod.\n *\n * Note that this means that handling options such as\n * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},\n * {@link LRUCache.FetchOptions.signal},\n * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be\n * determined by the FIRST fetch() call for a given key.\n *\n * This is a known (fixable) shortcoming which will be addresed on when\n * someone complains about it, as the fix would involve added complexity and\n * may not be worth the costs for this edge case.\n *\n * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n * effectively an alias for `Promise.resolve(cache.get(key))`.\n *\n * When the fetch method resolves to a value, if the fetch has not\n * been aborted due to deletion, eviction, or being overwritten,\n * then it is added to the cache using the options provided.\n *\n * If the key is evicted or deleted before the `fetchMethod`\n * resolves, then the AbortSignal passed to the `fetchMethod` will\n * receive an `abort` event, and the promise returned by `fetch()`\n * will reject with the reason for the abort.\n *\n * If a `signal` is passed to the `fetch()` call, then aborting the\n * signal will abort the fetch and cause the `fetch()` promise to\n * reject with the reason provided.\n *\n * **Setting `context`**\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the {@link LRUCache} constructor, then all\n * calls to `cache.fetch()` _must_ provide a `context` option. If\n * set to `undefined` or `void`, then calls to fetch _must not_\n * provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that\n * might be relevant in the course of fetching the data. It is only\n * relevant for the course of a single `fetch()` operation, and\n * discarded afterwards.\n *\n * **Note: `fetch()` calls are inflight-unique**\n *\n * If you call `fetch()` multiple times with the same key value,\n * then every call after the first will resolve on the same\n * promise<sup>1</sup>,\n * _even if they have different settings that would otherwise change\n * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n * or `ignoreFetchAbort`.\n *\n * In most cases, this is not a problem (in fact, only fetching\n * something once is what you probably want, if you're caching in\n * the first place). If you are changing the fetch() options\n * dramatically between runs, there's a good chance that you might\n * be trying to fit divergent semantics into a single object, and\n * would be better off with multiple cache instances.\n *\n * **1**: Ie, they're not the \"same Promise\", but they resolve at\n * the same time, because they're both waiting on the same\n * underlying fetchMethod response.\n */\n\n fetch(\n k: K,\n fetchOptions: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : LRUCache.FetchOptionsWithContext<K, V, FC>\n ): Promise<undefined | V>\n\n // this overload not allowed if context is required\n fetch(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n fetchOptions?: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : never\n ): Promise<undefined | V>\n\n async fetch(\n k: K,\n fetchOptions: LRUCache.FetchOptions<K, V, FC> = {}\n ): Promise<undefined | V> {\n const {\n // get options\n allowStale = this.allowStale,\n updateAgeOnGet = this.updateAgeOnGet,\n noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n // set options\n ttl = this.ttl,\n noDisposeOnSet = this.noDisposeOnSet,\n size = 0,\n sizeCalculation = this.sizeCalculation,\n noUpdateTTL = this.noUpdateTTL,\n // fetch exclusive options\n noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,\n allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,\n ignoreFetchAbort = this.ignoreFetchAbort,\n allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,\n context,\n forceRefresh = false,\n status,\n signal,\n } = fetchOptions\n\n if (!this.#hasFetchMethod) {\n if (status) status.fetch = 'get'\n return this.get(k, {\n allowStale,\n updateAgeOnGet,\n noDeleteOnStaleGet,\n status,\n })\n }\n\n const options = {\n allowStale,\n updateAgeOnGet,\n noDeleteOnStaleGet,\n ttl,\n noDisposeOnSet,\n size,\n sizeCalculation,\n noUpdateTTL,\n noDeleteOnFetchRejection,\n allowStaleOnFetchRejection,\n allowStaleOnFetchAbort,\n ignoreFetchAbort,\n status,\n signal,\n }\n\n let index = this.#keyMap.get(k)\n if (index === undefined) {\n if (status) status.fetch = 'miss'\n const p = this.#backgroundFetch(k, index, options, context)\n return (p.__returned = p)\n } else {\n // in cache, maybe already fetching\n const v = this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n const stale =\n allowStale && v.__staleWhileFetching !== undefined\n if (status) {\n status.fetch = 'inflight'\n if (stale) status.returnedStale = true\n }\n return stale ? v.__staleWhileFetching : (v.__returned = v)\n }\n\n // if we force a refresh, that means do NOT serve the cached value,\n // unless we are already in the process of refreshing the cache.\n const isStale = this.#isStale(index)\n if (!forceRefresh && !isStale) {\n if (status) status.fetch = 'hit'\n this.#moveToTail(index)\n if (updateAgeOnGet) {\n this.#updateItemAge(index)\n }\n if (status) this.#statusTTL(status, index)\n return v\n }\n\n // ok, it is stale or a forced refresh, and not already fetching.\n // refresh the cache.\n const p = this.#backgroundFetch(k, index, options, context)\n const hasStale = p.__staleWhileFetching !== undefined\n const staleVal = hasStale && allowStale\n if (status) {\n status.fetch = isStale ? 'stale' : 'refresh'\n if (staleVal && isStale) status.returnedStale = true\n }\n return staleVal ? p.__staleWhileFetching : (p.__returned = p)\n }\n }\n\n /**\n * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n * because `ignoreFetchAbort` was specified (either to the constructor or\n * in the {@link LRUCache.FetchOptions}). Also, the\n * {@link OptionsBase.fetchMethod} may return `undefined` or `void`, making\n * the test even more complicated.\n *\n * Because inferring the cases where `undefined` might be returned are so\n * cumbersome, but testing for `undefined` can also be annoying, this method\n * can be used, which will reject if `this.fetch()` resolves to undefined.\n */\n forceFetch(\n k: K,\n fetchOptions: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : LRUCache.FetchOptionsWithContext<K, V, FC>\n ): Promise<V>\n // this overload not allowed if context is required\n forceFetch(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n fetchOptions?: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : never\n ): Promise<V>\n async forceFetch(\n k: K,\n fetchOptions: LRUCache.FetchOptions<K, V, FC> = {}\n ): Promise<V> {\n const v = await this.fetch(\n k,\n fetchOptions as unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : LRUCache.FetchOptionsWithContext<K, V, FC>\n )\n if (v === undefined) throw new Error('fetch() returned undefined')\n return v\n }\n\n /**\n * If the key is found in the cache, then this is equivalent to\n * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n * _must_ provide a `context` option. If set to `undefined` or `void`, then\n * calls to memo _must not_ provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that might be\n * relevant in the course of fetching the data. It is only relevant for the\n * course of a single `memo()` operation, and discarded afterwards.\n */\n memo(\n k: K,\n memoOptions: unknown extends FC\n ? LRUCache.MemoOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext<K, V>\n : LRUCache.MemoOptionsWithContext<K, V, FC>\n ): V\n // this overload not allowed if context is required\n memo(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n memoOptions?: unknown extends FC\n ? LRUCache.MemoOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext<K, V>\n : never\n ): V\n memo(k: K, memoOptions: LRUCache.MemoOptions<K, V, FC> = {}) {\n const memoMethod = this.#memoMethod\n if (!memoMethod) {\n throw new Error('no memoMethod provided to constructor')\n }\n const { context, forceRefresh, ...options } = memoOptions\n const v = this.get(k, options)\n if (!forceRefresh && v !== undefined) return v\n const vv = memoMethod(k, v, {\n options,\n context,\n } as LRUCache.MemoizerOptions<K, V, FC>)\n this.set(k, vv, options)\n return vv\n }\n\n /**\n * Return a value from the cache. Will update the recency of the cache\n * entry found.\n *\n * If the key is not found, get() will return `undefined`.\n */\n get(k: K, getOptions: LRUCache.GetOptions<K, V, FC> = {}) {\n const {\n allowStale = this.allowStale,\n updateAgeOnGet = this.updateAgeOnGet,\n noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n status,\n } = getOptions\n const index = this.#keyMap.get(k)\n if (index !== undefined) {\n const value = this.#valList[index]\n const fetching = this.#isBackgroundFetch(value)\n if (status) this.#statusTTL(status, index)\n if (this.#isStale(index)) {\n if (status) status.get = 'stale'\n // delete only if not an in-flight background fetch\n if (!fetching) {\n if (!noDeleteOnStaleGet) {\n this.#delete(k, 'expire')\n }\n if (status && allowStale) status.returnedStale = true\n return allowStale ? value : undefined\n } else {\n if (\n status &&\n allowStale &&\n value.__staleWhileFetching !== undefined\n ) {\n status.returnedStale = true\n }\n return allowStale ? value.__staleWhileFetching : undefined\n }\n } else {\n if (status) status.get = 'hit'\n // if we're currently fetching it, we don't actually have it yet\n // it's not stale, which means this isn't a staleWhileRefetching.\n // If it's not stale, and fetching, AND has a __staleWhileFetching\n // value, then that means the user fetched with {forceRefresh:true},\n // so it's safe to return that value.\n if (fetching) {\n return value.__staleWhileFetching\n }\n this.#moveToTail(index)\n if (updateAgeOnGet) {\n this.#updateItemAge(index)\n }\n return value\n }\n } else if (status) {\n status.get = 'miss'\n }\n }\n\n #connect(p: Index, n: Index) {\n this.#prev[n] = p\n this.#next[p] = n\n }\n\n #moveToTail(index: Index): void {\n // if tail already, nothing to do\n // if head, move head to next[index]\n // else\n // move next[prev[index]] to next[index] (head has no prev)\n // move prev[next[index]] to prev[index]\n // prev[index] = tail\n // next[tail] = index\n // tail = index\n if (index !== this.#tail) {\n if (index === this.#head) {\n this.#head = this.#next[index] as Index\n } else {\n this.#connect(\n this.#prev[index] as Index,\n this.#next[index] as Index\n )\n }\n this.#connect(this.#tail, index)\n this.#tail = index\n }\n }\n\n /**\n * Deletes a key out of the cache.\n *\n * Returns true if the key was deleted, false otherwise.\n */\n delete(k: K) {\n return this.#delete(k, 'delete')\n }\n\n #delete(k: K, reason: LRUCache.DisposeReason) {\n let deleted = false\n if (this.#size !== 0) {\n const index = this.#keyMap.get(k)\n if (index !== undefined) {\n deleted = true\n if (this.#size === 1) {\n this.#clear(reason)\n } else {\n this.#removeItemSize(index)\n const v = this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('deleted'))\n } else if (this.#hasDispose || this.#hasDisposeAfter) {\n if (this.#hasDispose) {\n this.#dispose?.(v as V, k, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k, reason])\n }\n }\n this.#keyMap.delete(k)\n this.#keyList[index] = undefined\n this.#valList[index] = undefined\n if (index === this.#tail) {\n this.#tail = this.#prev[index] as Index\n } else if (index === this.#head) {\n this.#head = this.#next[index] as Index\n } else {\n const pi = this.#prev[index] as number\n this.#next[pi] = this.#next[index] as number\n const ni = this.#next[index] as number\n this.#prev[ni] = this.#prev[index] as number\n }\n this.#size--\n this.#free.push(index)\n }\n }\n }\n if (this.#hasDisposeAfter && this.#disposed?.length) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n return deleted\n }\n\n /**\n * Clear the cache entirely, throwing away all values.\n */\n clear() {\n return this.#clear('delete')\n }\n #clear(reason: LRUCache.DisposeReason) {\n for (const index of this.#rindexes({ allowStale: true })) {\n const v = this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('deleted'))\n } else {\n const k = this.#keyList[index]\n if (this.#hasDispose) {\n this.#dispose?.(v as V, k as K, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k as K, reason])\n }\n }\n }\n\n this.#keyMap.clear()\n this.#valList.fill(undefined)\n this.#keyList.fill(undefined)\n if (this.#ttls && this.#starts) {\n this.#ttls.fill(0)\n this.#starts.fill(0)\n }\n if (this.#sizes) {\n this.#sizes.fill(0)\n }\n this.#head = 0 as Index\n this.#tail = 0 as Index\n this.#free.length = 0\n this.#calculatedSize = 0\n this.#size = 0\n if (this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n }\n}\n", "import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n lstatSync,\n readdir as readdirCB,\n readdirSync,\n readlinkSync,\n realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods. Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n * readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n * - lstat\n * - readdir (Dirent variant only)\n * - readlink\n * - realpath\n */\nexport interface FSOption {\n lstatSync?: (path: string) => Stats\n readdir?: (\n path: string,\n options: { withFileTypes: true },\n cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n ) => void\n readdirSync?: (\n path: string,\n options: { withFileTypes: true },\n ) => Dirent[]\n readlinkSync?: (path: string) => string\n realpathSync?: (path: string) => string\n promises?: {\n lstat?: (path: string) => Promise<Stats>\n readdir?: (\n path: string,\n options: { withFileTypes: true },\n ) => Promise<Dirent[]>\n readlink?: (path: string) => Promise<string>\n realpath?: (path: string) => Promise<string>\n [k: string]: any\n }\n [k: string]: any\n}\n\ninterface FSValue {\n lstatSync: (path: string) => Stats\n readdir: (\n path: string,\n options: { withFileTypes: true },\n cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n ) => void\n readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n readlinkSync: (path: string) => string\n realpathSync: (path: string) => string\n promises: {\n lstat: (path: string) => Promise<Stats>\n readdir: (\n path: string,\n options: { withFileTypes: true },\n ) => Promise<Dirent[]>\n readlink: (path: string) => Promise<string>\n realpath: (path: string) => Promise<string>\n [k: string]: any\n }\n [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n lstatSync,\n readdir: readdirCB,\n readdirSync,\n readlinkSync,\n realpathSync,\n promises: {\n lstat,\n readdir,\n readlink,\n realpath,\n },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n defaultFS\n : {\n ...defaultFS,\n ...fsOption,\n promises: {\n ...defaultFS.promises,\n ...(fsOption.promises || {}),\n },\n }\n\n// turn something like //?/c:/ into c:\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncToDrive = (rootPath: string): string =>\n rootPath.replace(/\\//g, '\\\\').replace(uncDriveRegexp, '$1\\\\')\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n | 'Unknown'\n | 'FIFO'\n | 'CharacterDevice'\n | 'Directory'\n | 'BlockDevice'\n | 'File'\n | 'SymbolicLink'\n | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n s.isFile() ? IFREG\n : s.isDirectory() ? IFDIR\n : s.isSymbolicLink() ? IFLNK\n : s.isCharacterDevice() ? IFCHR\n : s.isBlockDevice() ? IFBLK\n : s.isSocket() ? IFSOCK\n : s.isFIFO() ? IFIFO\n : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new Map<string, string>()\nconst normalize = (s: string) => {\n const c = normalizeCache.get(s)\n if (c) return c\n const n = s.normalize('NFKD')\n normalizeCache.set(s, n)\n return n\n}\n\nconst normalizeNocaseCache = new Map<string, string>()\nconst normalizeNocase = (s: string) => {\n const c = normalizeNocaseCache.get(s)\n if (c) return c\n const n = normalize(s.toLowerCase())\n normalizeNocaseCache.set(s, n)\n return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n fullpath?: string\n relative?: string\n relativePosix?: string\n parent?: PathBase\n /**\n * See {@link FSOption}\n */\n fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache<string, string> {\n constructor() {\n super({ max: 256 })\n }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent. At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache. This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache<PathBase, Children> {\n constructor(maxSize: number = 16 * 1024) {\n super({\n maxSize,\n // parent + children\n sizeCalculation: a => a.length + 1,\n })\n }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n /**\n * the basename of this path\n *\n * **Important**: *always* test the path name against any test string\n * usingthe {@link isNamed} method, and not by directly comparing this\n * string. Otherwise, unicode path strings that the system sees as identical\n * will not be properly treated as the same path, leading to incorrect\n * behavior and possible security issues.\n */\n name: string\n /**\n * the Path entry corresponding to the path root.\n *\n * @internal\n */\n root: PathBase\n /**\n * All roots found within the current PathScurry family\n *\n * @internal\n */\n roots: { [k: string]: PathBase }\n /**\n * a reference to the parent path, or undefined in the case of root entries\n *\n * @internal\n */\n parent?: PathBase\n /**\n * boolean indicating whether paths are compared case-insensitively\n * @internal\n */\n nocase: boolean\n\n /**\n * boolean indicating that this path is the current working directory\n * of the PathScurry collection that contains it.\n */\n isCWD: boolean = false\n\n /**\n * the string or regexp used to split paths. On posix, it is `'/'`, and on\n * windows it is a RegExp matching either `'/'` or `'\\\\'`\n */\n abstract splitSep: string | RegExp\n /**\n * The path separator string to use when joining paths\n */\n abstract sep: string\n\n // potential default fs override\n #fs: FSValue\n\n // Stats fields\n #dev?: number\n get dev() {\n return this.#dev\n }\n #mode?: number\n get mode() {\n return this.#mode\n }\n #nlink?: number\n get nlink() {\n return this.#nlink\n }\n #uid?: number\n get uid() {\n return this.#uid\n }\n #gid?: number\n get gid() {\n return this.#gid\n }\n #rdev?: number\n get rdev() {\n return this.#rdev\n }\n #blksize?: number\n get blksize() {\n return this.#blksize\n }\n #ino?: number\n get ino() {\n return this.#ino\n }\n #size?: number\n get size() {\n return this.#size\n }\n #blocks?: number\n get blocks() {\n return this.#blocks\n }\n #atimeMs?: number\n get atimeMs() {\n return this.#atimeMs\n }\n #mtimeMs?: number\n get mtimeMs() {\n return this.#mtimeMs\n }\n #ctimeMs?: number\n get ctimeMs() {\n return this.#ctimeMs\n }\n #birthtimeMs?: number\n get birthtimeMs() {\n return this.#birthtimeMs\n }\n #atime?: Date\n get atime() {\n return this.#atime\n }\n #mtime?: Date\n get mtime() {\n return this.#mtime\n }\n #ctime?: Date\n get ctime() {\n return this.#ctime\n }\n #birthtime?: Date\n get birthtime() {\n return this.#birthtime\n }\n\n #matchName: string\n #depth?: number\n #fullpath?: string\n #fullpathPosix?: string\n #relative?: string\n #relativePosix?: string\n #type: number\n #children: ChildrenCache\n #linkTarget?: PathBase\n #realpath?: PathBase\n\n /**\n * This property is for compatibility with the Dirent class as of\n * Node v20, where Dirent['parentPath'] refers to the path of the\n * directory that was passed to readdir. For root entries, it's the path\n * to the entry itself.\n */\n get parentPath(): string {\n return (this.parent || this).fullpath()\n }\n\n /**\n * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n * this property refers to the *parent* path, not the path object itself.\n *\n * @deprecated\n */\n get path(): string {\n return this.parentPath\n }\n\n /**\n * Do not create new Path objects directly. They should always be accessed\n * via the PathScurry class or other methods on the Path class.\n *\n * @internal\n */\n constructor(\n name: string,\n type: number = UNKNOWN,\n root: PathBase | undefined,\n roots: { [k: string]: PathBase },\n nocase: boolean,\n children: ChildrenCache,\n opts: PathOpts,\n ) {\n this.name = name\n this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n this.#type = type & TYPEMASK\n this.nocase = nocase\n this.roots = roots\n this.root = root || this\n this.#children = children\n this.#fullpath = opts.fullpath\n this.#relative = opts.relative\n this.#relativePosix = opts.relativePosix\n this.parent = opts.parent\n if (this.parent) {\n this.#fs = this.parent.#fs\n } else {\n this.#fs = fsFromOption(opts.fs)\n }\n }\n\n /**\n * Returns the depth of the Path object from its root.\n *\n * For example, a path at `/foo/bar` would have a depth of 2.\n */\n depth(): number {\n if (this.#depth !== undefined) return this.#depth\n if (!this.parent) return (this.#depth = 0)\n return (this.#depth = this.parent.depth() + 1)\n }\n\n /**\n * @internal\n */\n abstract getRootString(path: string): string\n /**\n * @internal\n */\n abstract getRoot(rootPath: string): PathBase\n /**\n * @internal\n */\n abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n /**\n * @internal\n */\n childrenCache() {\n return this.#children\n }\n\n /**\n * Get the Path object referenced by the string path, resolved from this Path\n */\n resolve(path?: string): PathBase {\n if (!path) {\n return this\n }\n const rootPath = this.getRootString(path)\n const dir = path.substring(rootPath.length)\n const dirParts = dir.split(this.splitSep)\n const result: PathBase =\n rootPath ?\n this.getRoot(rootPath).#resolveParts(dirParts)\n : this.#resolveParts(dirParts)\n return result\n }\n\n #resolveParts(dirParts: string[]) {\n let p: PathBase = this\n for (const part of dirParts) {\n p = p.child(part)\n }\n return p\n }\n\n /**\n * Returns the cached children Path objects, if still available. If they\n * have fallen out of the cache, then returns an empty array, and resets the\n * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n * lookup.\n *\n * @internal\n */\n children(): Children {\n const cached = this.#children.get(this)\n if (cached) {\n return cached\n }\n const children: Children = Object.assign([], { provisional: 0 })\n this.#children.set(this, children)\n this.#type &= ~READDIR_CALLED\n return children\n }\n\n /**\n * Resolves a path portion and returns or creates the child Path.\n *\n * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n * `'..'`.\n *\n * This should not be called directly. If `pathPart` contains any path\n * separators, it will lead to unsafe undefined behavior.\n *\n * Use `Path.resolve()` instead.\n *\n * @internal\n */\n child(pathPart: string, opts?: PathOpts): PathBase {\n if (pathPart === '' || pathPart === '.') {\n return this\n }\n if (pathPart === '..') {\n return this.parent || this\n }\n\n // find the child\n const children = this.children()\n const name =\n this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n for (const p of children) {\n if (p.#matchName === name) {\n return p\n }\n }\n\n // didn't find it, create provisional child, since it might not\n // actually exist. If we know the parent isn't a dir, then\n // in fact it CAN'T exist.\n const s = this.parent ? this.sep : ''\n const fullpath =\n this.#fullpath ? this.#fullpath + s + pathPart : undefined\n const pchild = this.newChild(pathPart, UNKNOWN, {\n ...opts,\n parent: this,\n fullpath,\n })\n\n if (!this.canReaddir()) {\n pchild.#type |= ENOENT\n }\n\n // don't have to update provisional, because if we have real children,\n // then provisional is set to children.length, otherwise a lower number\n children.push(pchild)\n return pchild\n }\n\n /**\n * The relative path from the cwd. If it does not share an ancestor with\n * the cwd, then this ends up being equivalent to the fullpath()\n */\n relative(): string {\n if (this.isCWD) return ''\n if (this.#relative !== undefined) {\n return this.#relative\n }\n const name = this.name\n const p = this.parent\n if (!p) {\n return (this.#relative = this.name)\n }\n const pv = p.relative()\n return pv + (!pv || !p.parent ? '' : this.sep) + name\n }\n\n /**\n * The relative path from the cwd, using / as the path separator.\n * If it does not share an ancestor with\n * the cwd, then this ends up being equivalent to the fullpathPosix()\n * On posix systems, this is identical to relative().\n */\n relativePosix(): string {\n if (this.sep === '/') return this.relative()\n if (this.isCWD) return ''\n if (this.#relativePosix !== undefined) return this.#relativePosix\n const name = this.name\n const p = this.parent\n if (!p) {\n return (this.#relativePosix = this.fullpathPosix())\n }\n const pv = p.relativePosix()\n return pv + (!pv || !p.parent ? '' : '/') + name\n }\n\n /**\n * The fully resolved path string for this Path entry\n */\n fullpath(): string {\n if (this.#fullpath !== undefined) {\n return this.#fullpath\n }\n const name = this.name\n const p = this.parent\n if (!p) {\n return (this.#fullpath = this.name)\n }\n const pv = p.fullpath()\n const fp = pv + (!p.parent ? '' : this.sep) + name\n return (this.#fullpath = fp)\n }\n\n /**\n * On platforms other than windows, this is identical to fullpath.\n *\n * On windows, this is overridden to return the forward-slash form of the\n * full UNC path.\n */\n fullpathPosix(): string {\n if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n if (!this.parent) {\n const p = this.fullpath().replace(/\\\\/g, '/')\n if (/^[a-z]:\\//i.test(p)) {\n return (this.#fullpathPosix = `//?/${p}`)\n } else {\n return (this.#fullpathPosix = p)\n }\n }\n const p = this.parent\n const pfpp = p.fullpathPosix()\n const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n return (this.#fullpathPosix = fpp)\n }\n\n /**\n * Is the Path of an unknown type?\n *\n * Note that we might know *something* about it if there has been a previous\n * filesystem operation, for example that it does not exist, or is not a\n * link, or whether it has child entries.\n */\n isUnknown(): boolean {\n return (this.#type & IFMT) === UNKNOWN\n }\n\n isType(type: Type): boolean {\n return this[`is${type}`]()\n }\n\n getType(): Type {\n return (\n this.isUnknown() ? 'Unknown'\n : this.isDirectory() ? 'Directory'\n : this.isFile() ? 'File'\n : this.isSymbolicLink() ? 'SymbolicLink'\n : this.isFIFO() ? 'FIFO'\n : this.isCharacterDevice() ? 'CharacterDevice'\n : this.isBlockDevice() ? 'BlockDevice'\n : /* c8 ignore start */ this.isSocket() ? 'Socket'\n : 'Unknown'\n )\n /* c8 ignore stop */\n }\n\n /**\n * Is the Path a regular file?\n */\n isFile(): boolean {\n return (this.#type & IFMT) === IFREG\n }\n\n /**\n * Is the Path a directory?\n */\n isDirectory(): boolean {\n return (this.#type & IFMT) === IFDIR\n }\n\n /**\n * Is the path a character device?\n */\n isCharacterDevice(): boolean {\n return (this.#type & IFMT) === IFCHR\n }\n\n /**\n * Is the path a block device?\n */\n isBlockDevice(): boolean {\n return (this.#type & IFMT) === IFBLK\n }\n\n /**\n * Is the path a FIFO pipe?\n */\n isFIFO(): boolean {\n return (this.#type & IFMT) === IFIFO\n }\n\n /**\n * Is the path a socket?\n */\n isSocket(): boolean {\n return (this.#type & IFMT) === IFSOCK\n }\n\n /**\n * Is the path a symbolic link?\n */\n isSymbolicLink(): boolean {\n return (this.#type & IFLNK) === IFLNK\n }\n\n /**\n * Return the entry if it has been subject of a successful lstat, or\n * undefined otherwise.\n *\n * Does not read the filesystem, so an undefined result *could* simply\n * mean that we haven't called lstat on it.\n */\n lstatCached(): PathBase | undefined {\n return this.#type & LSTAT_CALLED ? this : undefined\n }\n\n /**\n * Return the cached link target if the entry has been the subject of a\n * successful readlink, or undefined otherwise.\n *\n * Does not read the filesystem, so an undefined result *could* just mean we\n * don't have any cached data. Only use it if you are very sure that a\n * readlink() has been called at some point.\n */\n readlinkCached(): PathBase | undefined {\n return this.#linkTarget\n }\n\n /**\n * Returns the cached realpath target if the entry has been the subject\n * of a successful realpath, or undefined otherwise.\n *\n * Does not read the filesystem, so an undefined result *could* just mean we\n * don't have any cached data. Only use it if you are very sure that a\n * realpath() has been called at some point.\n */\n realpathCached(): PathBase | undefined {\n return this.#realpath\n }\n\n /**\n * Returns the cached child Path entries array if the entry has been the\n * subject of a successful readdir(), or [] otherwise.\n *\n * Does not read the filesystem, so an empty array *could* just mean we\n * don't have any cached data. Only use it if you are very sure that a\n * readdir() has been called recently enough to still be valid.\n */\n readdirCached(): PathBase[] {\n const children = this.children()\n return children.slice(0, children.provisional)\n }\n\n /**\n * Return true if it's worth trying to readlink. Ie, we don't (yet) have\n * any indication that readlink will definitely fail.\n *\n * Returns false if the path is known to not be a symlink, if a previous\n * readlink failed, or if the entry does not exist.\n */\n canReadlink(): boolean {\n if (this.#linkTarget) return true\n if (!this.parent) return false\n // cases where it cannot possibly succeed\n const ifmt = this.#type & IFMT\n return !(\n (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n this.#type & ENOREADLINK ||\n this.#type & ENOENT\n )\n }\n\n /**\n * Return true if readdir has previously been successfully called on this\n * path, indicating that cachedReaddir() is likely valid.\n */\n calledReaddir(): boolean {\n return !!(this.#type & READDIR_CALLED)\n }\n\n /**\n * Returns true if the path is known to not exist. That is, a previous lstat\n * or readdir failed to verify its existence when that would have been\n * expected, or a parent entry was marked either enoent or enotdir.\n */\n isENOENT(): boolean {\n return !!(this.#type & ENOENT)\n }\n\n /**\n * Return true if the path is a match for the given path name. This handles\n * case sensitivity and unicode normalization.\n *\n * Note: even on case-sensitive systems, it is **not** safe to test the\n * equality of the `.name` property to determine whether a given pathname\n * matches, due to unicode normalization mismatches.\n *\n * Always use this method instead of testing the `path.name` property\n * directly.\n */\n isNamed(n: string): boolean {\n return !this.nocase ?\n this.#matchName === normalize(n)\n : this.#matchName === normalizeNocase(n)\n }\n\n /**\n * Return the Path object corresponding to the target of a symbolic link.\n *\n * If the Path is not a symbolic link, or if the readlink call fails for any\n * reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n */\n async readlink(): Promise<PathBase | undefined> {\n const target = this.#linkTarget\n if (target) {\n return target\n }\n if (!this.canReadlink()) {\n return undefined\n }\n /* c8 ignore start */\n // already covered by the canReadlink test, here for ts grumples\n if (!this.parent) {\n return undefined\n }\n /* c8 ignore stop */\n try {\n const read = await this.#fs.promises.readlink(this.fullpath())\n const linkTarget = (await this.parent.realpath())?.resolve(read)\n if (linkTarget) {\n return (this.#linkTarget = linkTarget)\n }\n } catch (er) {\n this.#readlinkFail((er as NodeJS.ErrnoException).code)\n return undefined\n }\n }\n\n /**\n * Synchronous {@link PathBase.readlink}\n */\n readlinkSync(): PathBase | undefined {\n const target = this.#linkTarget\n if (target) {\n return target\n }\n if (!this.canReadlink()) {\n return undefined\n }\n /* c8 ignore start */\n // already covered by the canReadlink test, here for ts grumples\n if (!this.parent) {\n return undefined\n }\n /* c8 ignore stop */\n try {\n const read = this.#fs.readlinkSync(this.fullpath())\n const linkTarget = this.parent.realpathSync()?.resolve(read)\n if (linkTarget) {\n return (this.#linkTarget = linkTarget)\n }\n } catch (er) {\n this.#readlinkFail((er as NodeJS.ErrnoException).code)\n return undefined\n }\n }\n\n #readdirSuccess(children: Children) {\n // succeeded, mark readdir called bit\n this.#type |= READDIR_CALLED\n // mark all remaining provisional children as ENOENT\n for (let p = children.provisional; p < children.length; p++) {\n const c = children[p]\n if (c) c.#markENOENT()\n }\n }\n\n #markENOENT() {\n // mark as UNKNOWN and ENOENT\n if (this.#type & ENOENT) return\n this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n this.#markChildrenENOENT()\n }\n\n #markChildrenENOENT() {\n // all children are provisional and do not exist\n const children = this.children()\n children.provisional = 0\n for (const p of children) {\n p.#markENOENT()\n }\n }\n\n #markENOREALPATH() {\n this.#type |= ENOREALPATH\n this.#markENOTDIR()\n }\n\n // save the information when we know the entry is not a dir\n #markENOTDIR() {\n // entry is not a directory, so any children can't exist.\n // this *should* be impossible, since any children created\n // after it's been marked ENOTDIR should be marked ENOENT,\n // so it won't even get to this point.\n /* c8 ignore start */\n if (this.#type & ENOTDIR) return\n /* c8 ignore stop */\n let t = this.#type\n // this could happen if we stat a dir, then delete it,\n // then try to read it or one of its children.\n if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n this.#type = t | ENOTDIR\n this.#markChildrenENOENT()\n }\n\n #readdirFail(code: string = '') {\n // markENOTDIR and markENOENT also set provisional=0\n if (code === 'ENOTDIR' || code === 'EPERM') {\n this.#markENOTDIR()\n } else if (code === 'ENOENT') {\n this.#markENOENT()\n } else {\n this.children().provisional = 0\n }\n }\n\n #lstatFail(code: string = '') {\n // Windows just raises ENOENT in this case, disable for win CI\n /* c8 ignore start */\n if (code === 'ENOTDIR') {\n // already know it has a parent by this point\n const p = this.parent as PathBase\n p.#markENOTDIR()\n } else if (code === 'ENOENT') {\n /* c8 ignore stop */\n this.#markENOENT()\n }\n }\n\n #readlinkFail(code: string = '') {\n let ter = this.#type\n ter |= ENOREADLINK\n if (code === 'ENOENT') ter |= ENOENT\n // windows gets a weird error when you try to readlink a file\n if (code === 'EINVAL' || code === 'UNKNOWN') {\n // exists, but not a symlink, we don't know WHAT it is, so remove\n // all IFMT bits.\n ter &= IFMT_UNKNOWN\n }\n this.#type = ter\n // windows just gets ENOENT in this case. We do cover the case,\n // just disabled because it's impossible on Windows CI\n /* c8 ignore start */\n if (code === 'ENOTDIR' && this.parent) {\n this.parent.#markENOTDIR()\n }\n /* c8 ignore stop */\n }\n\n #readdirAddChild(e: Dirent, c: Children) {\n return (\n this.#readdirMaybePromoteChild(e, c) ||\n this.#readdirAddNewChild(e, c)\n )\n }\n\n #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n // alloc new entry at head, so it's never provisional\n const type = entToType(e)\n const child = this.newChild(e.name, type, { parent: this })\n const ifmt = child.#type & IFMT\n if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n child.#type |= ENOTDIR\n }\n c.unshift(child)\n c.provisional++\n return child\n }\n\n #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n for (let p = c.provisional; p < c.length; p++) {\n const pchild = c[p]\n const name =\n this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n if (name !== pchild!.#matchName) {\n continue\n }\n\n return this.#readdirPromoteChild(e, pchild!, p, c)\n }\n }\n\n #readdirPromoteChild(\n e: Dirent,\n p: PathBase,\n index: number,\n c: Children,\n ): PathBase {\n const v = p.name\n // retain any other flags, but set ifmt from dirent\n p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n // case sensitivity fixing when we learn the true name.\n if (v !== e.name) p.name = e.name\n\n // just advance provisional index (potentially off the list),\n // otherwise we have to splice/pop it out and re-insert at head\n if (index !== c.provisional) {\n if (index === c.length - 1) c.pop()\n else c.splice(index, 1)\n c.unshift(p)\n }\n c.provisional++\n return p\n }\n\n /**\n * Call lstat() on this Path, and update all known information that can be\n * determined.\n *\n * Note that unlike `fs.lstat()`, the returned value does not contain some\n * information, such as `mode`, `dev`, `nlink`, and `ino`. If that\n * information is required, you will need to call `fs.lstat` yourself.\n *\n * If the Path refers to a nonexistent file, or if the lstat call fails for\n * any reason, `undefined` is returned. Otherwise the updated Path object is\n * returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n */\n async lstat(): Promise<PathBase | undefined> {\n if ((this.#type & ENOENT) === 0) {\n try {\n this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n return this\n } catch (er) {\n this.#lstatFail((er as NodeJS.ErrnoException).code)\n }\n }\n }\n\n /**\n * synchronous {@link PathBase.lstat}\n */\n lstatSync(): PathBase | undefined {\n if ((this.#type & ENOENT) === 0) {\n try {\n this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n return this\n } catch (er) {\n this.#lstatFail((er as NodeJS.ErrnoException).code)\n }\n }\n }\n\n #applyStat(st: Stats) {\n const {\n atime,\n atimeMs,\n birthtime,\n birthtimeMs,\n blksize,\n blocks,\n ctime,\n ctimeMs,\n dev,\n gid,\n ino,\n mode,\n mtime,\n mtimeMs,\n nlink,\n rdev,\n size,\n uid,\n } = st\n this.#atime = atime\n this.#atimeMs = atimeMs\n this.#birthtime = birthtime\n this.#birthtimeMs = birthtimeMs\n this.#blksize = blksize\n this.#blocks = blocks\n this.#ctime = ctime\n this.#ctimeMs = ctimeMs\n this.#dev = dev\n this.#gid = gid\n this.#ino = ino\n this.#mode = mode\n this.#mtime = mtime\n this.#mtimeMs = mtimeMs\n this.#nlink = nlink\n this.#rdev = rdev\n this.#size = size\n this.#uid = uid\n const ifmt = entToType(st)\n // retain any other flags, but set the ifmt\n this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n this.#type |= ENOTDIR\n }\n }\n\n #onReaddirCB: ((\n er: NodeJS.ErrnoException | null,\n entries: Path[],\n ) => any)[] = []\n #readdirCBInFlight: boolean = false\n #callOnReaddirCB(children: Path[]) {\n this.#readdirCBInFlight = false\n const cbs = this.#onReaddirCB.slice()\n this.#onReaddirCB.length = 0\n cbs.forEach(cb => cb(null, children))\n }\n\n /**\n * Standard node-style callback interface to get list of directory entries.\n *\n * If the Path cannot or does not contain any children, then an empty array\n * is returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n *\n * @param cb The callback called with (er, entries). Note that the `er`\n * param is somewhat extraneous, as all readdir() errors are handled and\n * simply result in an empty set of entries being returned.\n * @param allowZalgo Boolean indicating that immediately known results should\n * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n * zalgo at your peril, the dark pony lord is devious and unforgiving.\n */\n readdirCB(\n cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n allowZalgo: boolean = false,\n ): void {\n if (!this.canReaddir()) {\n if (allowZalgo) cb(null, [])\n else queueMicrotask(() => cb(null, []))\n return\n }\n\n const children = this.children()\n if (this.calledReaddir()) {\n const c = children.slice(0, children.provisional)\n if (allowZalgo) cb(null, c)\n else queueMicrotask(() => cb(null, c))\n return\n }\n\n // don't have to worry about zalgo at this point.\n this.#onReaddirCB.push(cb)\n if (this.#readdirCBInFlight) {\n return\n }\n this.#readdirCBInFlight = true\n\n // else read the directory, fill up children\n // de-provisionalize any provisional children.\n const fullpath = this.fullpath()\n this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n if (er) {\n this.#readdirFail((er as NodeJS.ErrnoException).code)\n children.provisional = 0\n } else {\n // if we didn't get an error, we always get entries.\n //@ts-ignore\n for (const e of entries) {\n this.#readdirAddChild(e, children)\n }\n this.#readdirSuccess(children)\n }\n this.#callOnReaddirCB(children.slice(0, children.provisional))\n return\n })\n }\n\n #asyncReaddirInFlight?: Promise<void>\n\n /**\n * Return an array of known child entries.\n *\n * If the Path cannot or does not contain any children, then an empty array\n * is returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n */\n async readdir(): Promise<PathBase[]> {\n if (!this.canReaddir()) {\n return []\n }\n\n const children = this.children()\n if (this.calledReaddir()) {\n return children.slice(0, children.provisional)\n }\n\n // else read the directory, fill up children\n // de-provisionalize any provisional children.\n const fullpath = this.fullpath()\n if (this.#asyncReaddirInFlight) {\n await this.#asyncReaddirInFlight\n } else {\n /* c8 ignore start */\n let resolve: () => void = () => {}\n /* c8 ignore stop */\n this.#asyncReaddirInFlight = new Promise<void>(\n res => (resolve = res),\n )\n try {\n for (const e of await this.#fs.promises.readdir(fullpath, {\n withFileTypes: true,\n })) {\n this.#readdirAddChild(e, children)\n }\n this.#readdirSuccess(children)\n } catch (er) {\n this.#readdirFail((er as NodeJS.ErrnoException).code)\n children.provisional = 0\n }\n this.#asyncReaddirInFlight = undefined\n resolve()\n }\n return children.slice(0, children.provisional)\n }\n\n /**\n * synchronous {@link PathBase.readdir}\n */\n readdirSync(): PathBase[] {\n if (!this.canReaddir()) {\n return []\n }\n\n const children = this.children()\n if (this.calledReaddir()) {\n return children.slice(0, children.provisional)\n }\n\n // else read the directory, fill up children\n // de-provisionalize any provisional children.\n const fullpath = this.fullpath()\n try {\n for (const e of this.#fs.readdirSync(fullpath, {\n withFileTypes: true,\n })) {\n this.#readdirAddChild(e, children)\n }\n this.#readdirSuccess(children)\n } catch (er) {\n this.#readdirFail((er as NodeJS.ErrnoException).code)\n children.provisional = 0\n }\n return children.slice(0, children.provisional)\n }\n\n canReaddir() {\n if (this.#type & ENOCHILD) return false\n const ifmt = IFMT & this.#type\n // we always set ENOTDIR when setting IFMT, so should be impossible\n /* c8 ignore start */\n if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n return false\n }\n /* c8 ignore stop */\n return true\n }\n\n shouldWalk(\n dirs: Set<PathBase | undefined>,\n walkFilter?: (e: PathBase) => boolean,\n ): boolean {\n return (\n (this.#type & IFDIR) === IFDIR &&\n !(this.#type & ENOCHILD) &&\n !dirs.has(this) &&\n (!walkFilter || walkFilter(this))\n )\n }\n\n /**\n * Return the Path object corresponding to path as resolved\n * by realpath(3).\n *\n * If the realpath call fails for any reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n * On success, returns a Path object.\n */\n async realpath(): Promise<PathBase | undefined> {\n if (this.#realpath) return this.#realpath\n if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n try {\n const rp = await this.#fs.promises.realpath(this.fullpath())\n return (this.#realpath = this.resolve(rp))\n } catch (_) {\n this.#markENOREALPATH()\n }\n }\n\n /**\n * Synchronous {@link realpath}\n */\n realpathSync(): PathBase | undefined {\n if (this.#realpath) return this.#realpath\n if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n try {\n const rp = this.#fs.realpathSync(this.fullpath())\n return (this.#realpath = this.resolve(rp))\n } catch (_) {\n this.#markENOREALPATH()\n }\n }\n\n /**\n * Internal method to mark this Path object as the scurry cwd,\n * called by {@link PathScurry#chdir}\n *\n * @internal\n */\n [setAsCwd](oldCwd: PathBase): void {\n if (oldCwd === this) return\n oldCwd.isCWD = false\n this.isCWD = true\n\n const changed = new Set<PathBase>([])\n let rp = []\n let p: PathBase = this\n while (p && p.parent) {\n changed.add(p)\n p.#relative = rp.join(this.sep)\n p.#relativePosix = rp.join('/')\n p = p.parent\n rp.push('..')\n }\n // now un-memoize parents of old cwd\n p = oldCwd\n while (p && p.parent && !changed.has(p)) {\n p.#relative = undefined\n p.#relativePosix = undefined\n p = p.parent\n }\n }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n /**\n * Separator for generating path strings.\n */\n sep: '\\\\' = '\\\\'\n /**\n * Separator for parsing path strings.\n */\n splitSep: RegExp = eitherSep\n\n /**\n * Do not create new Path objects directly. They should always be accessed\n * via the PathScurry class or other methods on the Path class.\n *\n * @internal\n */\n constructor(\n name: string,\n type: number = UNKNOWN,\n root: PathBase | undefined,\n roots: { [k: string]: PathBase },\n nocase: boolean,\n children: ChildrenCache,\n opts: PathOpts,\n ) {\n super(name, type, root, roots, nocase, children, opts)\n }\n\n /**\n * @internal\n */\n newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n return new PathWin32(\n name,\n type,\n this.root,\n this.roots,\n this.nocase,\n this.childrenCache(),\n opts,\n )\n }\n\n /**\n * @internal\n */\n getRootString(path: string): string {\n return win32.parse(path).root\n }\n\n /**\n * @internal\n */\n getRoot(rootPath: string): PathBase {\n rootPath = uncToDrive(rootPath.toUpperCase())\n if (rootPath === this.root.name) {\n return this.root\n }\n // ok, not that one, check if it matches another we know about\n for (const [compare, root] of Object.entries(this.roots)) {\n if (this.sameRoot(rootPath, compare)) {\n return (this.roots[rootPath] = root)\n }\n }\n // otherwise, have to create a new one.\n return (this.roots[rootPath] = new PathScurryWin32(\n rootPath,\n this,\n ).root)\n }\n\n /**\n * @internal\n */\n sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n // windows can (rarely) have case-sensitive filesystem, but\n // UNC and drive letters are always case-insensitive, and canonically\n // represented uppercase.\n rootPath = rootPath\n .toUpperCase()\n .replace(/\\//g, '\\\\')\n .replace(uncDriveRegexp, '$1\\\\')\n return rootPath === compare\n }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n /**\n * separator for parsing path strings\n */\n splitSep: '/' = '/'\n /**\n * separator for generating path strings\n */\n sep: '/' = '/'\n\n /**\n * Do not create new Path objects directly. They should always be accessed\n * via the PathScurry class or other methods on the Path class.\n *\n * @internal\n */\n constructor(\n name: string,\n type: number = UNKNOWN,\n root: PathBase | undefined,\n roots: { [k: string]: PathBase },\n nocase: boolean,\n children: ChildrenCache,\n opts: PathOpts,\n ) {\n super(name, type, root, roots, nocase, children, opts)\n }\n\n /**\n * @internal\n */\n getRootString(path: string): string {\n return path.startsWith('/') ? '/' : ''\n }\n\n /**\n * @internal\n */\n getRoot(_rootPath: string): PathBase {\n return this.root\n }\n\n /**\n * @internal\n */\n newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n return new PathPosix(\n name,\n type,\n this.root,\n this.roots,\n this.nocase,\n this.childrenCache(),\n opts,\n )\n }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n /**\n * perform case-insensitive path matching. Default based on platform\n * subclass.\n */\n nocase?: boolean\n /**\n * Number of Path entries to keep in the cache of Path child references.\n *\n * Setting this higher than 65536 will dramatically increase the data\n * consumption and construction time overhead of each PathScurry.\n *\n * Setting this value to 256 or lower will significantly reduce the data\n * consumption and construction time overhead, but may also reduce resolve()\n * and readdir() performance on large filesystems.\n *\n * Default `16384`.\n */\n childrenCacheSize?: number\n /**\n * An object that overrides the built-in functions from the fs and\n * fs/promises modules.\n *\n * See {@link FSOption}\n */\n fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n /**\n * The root Path entry for the current working directory of this Scurry\n */\n root: PathBase\n /**\n * The string path for the root of this Scurry's current working directory\n */\n rootPath: string\n /**\n * A collection of all roots encountered, referenced by rootPath\n */\n roots: { [k: string]: PathBase }\n /**\n * The Path entry corresponding to this PathScurry's current working directory.\n */\n cwd: PathBase\n #resolveCache: ResolveCache\n #resolvePosixCache: ResolveCache\n #children: ChildrenCache\n /**\n * Perform path comparisons case-insensitively.\n *\n * Defaults true on Darwin and Windows systems, false elsewhere.\n */\n nocase: boolean\n\n /**\n * The path separator used for parsing paths\n *\n * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n */\n abstract sep: string | RegExp\n\n #fs: FSValue\n\n /**\n * This class should not be instantiated directly.\n *\n * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n *\n * @internal\n */\n constructor(\n cwd: URL | string = process.cwd(),\n pathImpl: typeof win32 | typeof posix,\n sep: string | RegExp,\n {\n nocase,\n childrenCacheSize = 16 * 1024,\n fs = defaultFS,\n }: PathScurryOpts = {},\n ) {\n this.#fs = fsFromOption(fs)\n if (cwd instanceof URL || cwd.startsWith('file://')) {\n cwd = fileURLToPath(cwd)\n }\n // resolve and split root, and then add to the store.\n // this is the only time we call path.resolve()\n const cwdPath = pathImpl.resolve(cwd)\n this.roots = Object.create(null)\n this.rootPath = this.parseRootPath(cwdPath)\n this.#resolveCache = new ResolveCache()\n this.#resolvePosixCache = new ResolveCache()\n this.#children = new ChildrenCache(childrenCacheSize)\n\n const split = cwdPath.substring(this.rootPath.length).split(sep)\n // resolve('/') leaves '', splits to [''], we don't want that.\n if (split.length === 1 && !split[0]) {\n split.pop()\n }\n /* c8 ignore start */\n if (nocase === undefined) {\n throw new TypeError(\n 'must provide nocase setting to PathScurryBase ctor',\n )\n }\n /* c8 ignore stop */\n this.nocase = nocase\n this.root = this.newRoot(this.#fs)\n this.roots[this.rootPath] = this.root\n let prev: PathBase = this.root\n let len = split.length - 1\n const joinSep = pathImpl.sep\n let abs = this.rootPath\n let sawFirst = false\n for (const part of split) {\n const l = len--\n prev = prev.child(part, {\n relative: new Array(l).fill('..').join(joinSep),\n relativePosix: new Array(l).fill('..').join('/'),\n fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n })\n sawFirst = true\n }\n this.cwd = prev\n }\n\n /**\n * Get the depth of a provided path, string, or the cwd\n */\n depth(path: Path | string = this.cwd): number {\n if (typeof path === 'string') {\n path = this.cwd.resolve(path)\n }\n return path.depth()\n }\n\n /**\n * Parse the root portion of a path string\n *\n * @internal\n */\n abstract parseRootPath(dir: string): string\n /**\n * create a new Path to use as root during construction.\n *\n * @internal\n */\n abstract newRoot(fs: FSValue): PathBase\n /**\n * Determine whether a given path string is absolute\n */\n abstract isAbsolute(p: string): boolean\n\n /**\n * Return the cache of child entries. Exposed so subclasses can create\n * child Path objects in a platform-specific way.\n *\n * @internal\n */\n childrenCache() {\n return this.#children\n }\n\n /**\n * Resolve one or more path strings to a resolved string\n *\n * Same interface as require('path').resolve.\n *\n * Much faster than path.resolve() when called multiple times for the same\n * path, because the resolved Path objects are cached. Much slower\n * otherwise.\n */\n resolve(...paths: string[]): string {\n // first figure out the minimum number of paths we have to test\n // we always start at cwd, but any absolutes will bump the start\n let r = ''\n for (let i = paths.length - 1; i >= 0; i--) {\n const p = paths[i]\n if (!p || p === '.') continue\n r = r ? `${p}/${r}` : p\n if (this.isAbsolute(p)) {\n break\n }\n }\n const cached = this.#resolveCache.get(r)\n if (cached !== undefined) {\n return cached\n }\n const result = this.cwd.resolve(r).fullpath()\n this.#resolveCache.set(r, result)\n return result\n }\n\n /**\n * Resolve one or more path strings to a resolved string, returning\n * the posix path. Identical to .resolve() on posix systems, but on\n * windows will return a forward-slash separated UNC path.\n *\n * Same interface as require('path').resolve.\n *\n * Much faster than path.resolve() when called multiple times for the same\n * path, because the resolved Path objects are cached. Much slower\n * otherwise.\n */\n resolvePosix(...paths: string[]): string {\n // first figure out the minimum number of paths we have to test\n // we always start at cwd, but any absolutes will bump the start\n let r = ''\n for (let i = paths.length - 1; i >= 0; i--) {\n const p = paths[i]\n if (!p || p === '.') continue\n r = r ? `${p}/${r}` : p\n if (this.isAbsolute(p)) {\n break\n }\n }\n const cached = this.#resolvePosixCache.get(r)\n if (cached !== undefined) {\n return cached\n }\n const result = this.cwd.resolve(r).fullpathPosix()\n this.#resolvePosixCache.set(r, result)\n return result\n }\n\n /**\n * find the relative path from the cwd to the supplied path string or entry\n */\n relative(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.relative()\n }\n\n /**\n * find the relative path from the cwd to the supplied path string or\n * entry, using / as the path delimiter, even on Windows.\n */\n relativePosix(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.relativePosix()\n }\n\n /**\n * Return the basename for the provided string or Path object\n */\n basename(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.name\n }\n\n /**\n * Return the dirname for the provided string or Path object\n */\n dirname(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return (entry.parent || entry).fullpath()\n }\n\n /**\n * Return an array of known child entries.\n *\n * First argument may be either a string, or a Path object.\n *\n * If the Path cannot or does not contain any children, then an empty array\n * is returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n *\n * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n * `{ withFileTypes: false }` to return strings.\n */\n\n readdir(): Promise<PathBase[]>\n readdir(opts: { withFileTypes: true }): Promise<PathBase[]>\n readdir(opts: { withFileTypes: false }): Promise<string[]>\n readdir(opts: { withFileTypes: boolean }): Promise<PathBase[] | string[]>\n readdir(entry: PathBase | string): Promise<PathBase[]>\n readdir(\n entry: PathBase | string,\n opts: { withFileTypes: true },\n ): Promise<PathBase[]>\n readdir(\n entry: PathBase | string,\n opts: { withFileTypes: false },\n ): Promise<string[]>\n readdir(\n entry: PathBase | string,\n opts: { withFileTypes: boolean },\n ): Promise<PathBase[] | string[]>\n async readdir(\n entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n opts: { withFileTypes: boolean } = {\n withFileTypes: true,\n },\n ): Promise<PathBase[] | string[]> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const { withFileTypes } = opts\n if (!entry.canReaddir()) {\n return []\n } else {\n const p = await entry.readdir()\n return withFileTypes ? p : p.map(e => e.name)\n }\n }\n\n /**\n * synchronous {@link PathScurryBase.readdir}\n */\n readdirSync(): PathBase[]\n readdirSync(opts: { withFileTypes: true }): PathBase[]\n readdirSync(opts: { withFileTypes: false }): string[]\n readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n readdirSync(entry: PathBase | string): PathBase[]\n readdirSync(\n entry: PathBase | string,\n opts: { withFileTypes: true },\n ): PathBase[]\n readdirSync(\n entry: PathBase | string,\n opts: { withFileTypes: false },\n ): string[]\n readdirSync(\n entry: PathBase | string,\n opts: { withFileTypes: boolean },\n ): PathBase[] | string[]\n readdirSync(\n entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n opts: { withFileTypes: boolean } = {\n withFileTypes: true,\n },\n ): PathBase[] | string[] {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const { withFileTypes = true } = opts\n if (!entry.canReaddir()) {\n return []\n } else if (withFileTypes) {\n return entry.readdirSync()\n } else {\n return entry.readdirSync().map(e => e.name)\n }\n }\n\n /**\n * Call lstat() on the string or Path object, and update all known\n * information that can be determined.\n *\n * Note that unlike `fs.lstat()`, the returned value does not contain some\n * information, such as `mode`, `dev`, `nlink`, and `ino`. If that\n * information is required, you will need to call `fs.lstat` yourself.\n *\n * If the Path refers to a nonexistent file, or if the lstat call fails for\n * any reason, `undefined` is returned. Otherwise the updated Path object is\n * returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n */\n async lstat(\n entry: string | PathBase = this.cwd,\n ): Promise<PathBase | undefined> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.lstat()\n }\n\n /**\n * synchronous {@link PathScurryBase.lstat}\n */\n lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.lstatSync()\n }\n\n /**\n * Return the Path object or string path corresponding to the target of a\n * symbolic link.\n *\n * If the path is not a symbolic link, or if the readlink call fails for any\n * reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n *\n * `{withFileTypes}` option defaults to `false`.\n *\n * On success, returns a Path object if `withFileTypes` option is true,\n * otherwise a string.\n */\n readlink(): Promise<string | undefined>\n readlink(opt: { withFileTypes: false }): Promise<string | undefined>\n readlink(opt: { withFileTypes: true }): Promise<PathBase | undefined>\n readlink(opt: {\n withFileTypes: boolean\n }): Promise<PathBase | string | undefined>\n readlink(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): Promise<string | undefined>\n readlink(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): Promise<PathBase | undefined>\n readlink(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): Promise<string | PathBase | undefined>\n async readlink(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): Promise<string | PathBase | undefined> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = await entry.readlink()\n return withFileTypes ? e : e?.fullpath()\n }\n\n /**\n * synchronous {@link PathScurryBase.readlink}\n */\n readlinkSync(): string | undefined\n readlinkSync(opt: { withFileTypes: false }): string | undefined\n readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n readlinkSync(opt: {\n withFileTypes: boolean\n }): PathBase | string | undefined\n readlinkSync(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): string | undefined\n readlinkSync(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): PathBase | undefined\n readlinkSync(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): string | PathBase | undefined\n readlinkSync(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): string | PathBase | undefined {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = entry.readlinkSync()\n return withFileTypes ? e : e?.fullpath()\n }\n\n /**\n * Return the Path object or string path corresponding to path as resolved\n * by realpath(3).\n *\n * If the realpath call fails for any reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n *\n * `{withFileTypes}` option defaults to `false`.\n *\n * On success, returns a Path object if `withFileTypes` option is true,\n * otherwise a string.\n */\n realpath(): Promise<string | undefined>\n realpath(opt: { withFileTypes: false }): Promise<string | undefined>\n realpath(opt: { withFileTypes: true }): Promise<PathBase | undefined>\n realpath(opt: {\n withFileTypes: boolean\n }): Promise<PathBase | string | undefined>\n realpath(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): Promise<string | undefined>\n realpath(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): Promise<PathBase | undefined>\n realpath(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): Promise<string | PathBase | undefined>\n async realpath(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): Promise<string | PathBase | undefined> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = await entry.realpath()\n return withFileTypes ? e : e?.fullpath()\n }\n\n realpathSync(): string | undefined\n realpathSync(opt: { withFileTypes: false }): string | undefined\n realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n realpathSync(opt: {\n withFileTypes: boolean\n }): PathBase | string | undefined\n realpathSync(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): string | undefined\n realpathSync(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): PathBase | undefined\n realpathSync(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): string | PathBase | undefined\n realpathSync(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): string | PathBase | undefined {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = entry.realpathSync()\n return withFileTypes ? e : e?.fullpath()\n }\n\n /**\n * Asynchronously walk the directory tree, returning an array of\n * all path strings or Path objects found.\n *\n * Note that this will be extremely memory-hungry on large filesystems.\n * In such cases, it may be better to use the stream or async iterator\n * walk implementation.\n */\n walk(): Promise<PathBase[]>\n walk(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Promise<PathBase[]>\n walk(opts: WalkOptionsWithFileTypesFalse): Promise<string[]>\n walk(opts: WalkOptions): Promise<string[] | PathBase[]>\n walk(entry: string | PathBase): Promise<PathBase[]>\n walk(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Promise<PathBase[]>\n walk(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Promise<string[]>\n walk(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Promise<PathBase[] | string[]>\n async walk(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Promise<PathBase[] | string[]> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results: (string | PathBase)[] = []\n if (!filter || filter(entry)) {\n results.push(withFileTypes ? entry : entry.fullpath())\n }\n const dirs = new Set<PathBase>()\n const walk = (\n dir: PathBase,\n cb: (er?: NodeJS.ErrnoException) => void,\n ) => {\n dirs.add(dir)\n dir.readdirCB((er, entries) => {\n /* c8 ignore start */\n if (er) {\n return cb(er)\n }\n /* c8 ignore stop */\n let len = entries.length\n if (!len) return cb()\n const next = () => {\n if (--len === 0) {\n cb()\n }\n }\n for (const e of entries) {\n if (!filter || filter(e)) {\n results.push(withFileTypes ? e : e.fullpath())\n }\n if (follow && e.isSymbolicLink()) {\n e.realpath()\n .then(r => (r?.isUnknown() ? r.lstat() : r))\n .then(r =>\n r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n )\n } else {\n if (e.shouldWalk(dirs, walkFilter)) {\n walk(e, next)\n } else {\n next()\n }\n }\n }\n }, true) // zalgooooooo\n }\n\n const start = entry\n return new Promise<PathBase[] | string[]>((res, rej) => {\n walk(start, er => {\n /* c8 ignore start */\n if (er) return rej(er)\n /* c8 ignore stop */\n res(results as PathBase[] | string[])\n })\n })\n }\n\n /**\n * Synchronously walk the directory tree, returning an array of\n * all path strings or Path objects found.\n *\n * Note that this will be extremely memory-hungry on large filesystems.\n * In such cases, it may be better to use the stream or async iterator\n * walk implementation.\n */\n walkSync(): PathBase[]\n walkSync(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): PathBase[]\n walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n walkSync(opts: WalkOptions): string[] | PathBase[]\n walkSync(entry: string | PathBase): PathBase[]\n walkSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n ): PathBase[]\n walkSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): string[]\n walkSync(\n entry: string | PathBase,\n opts: WalkOptions,\n ): PathBase[] | string[]\n walkSync(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): PathBase[] | string[] {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results: (string | PathBase)[] = []\n if (!filter || filter(entry)) {\n results.push(withFileTypes ? entry : entry.fullpath())\n }\n const dirs = new Set<PathBase>([entry])\n for (const dir of dirs) {\n const entries = dir.readdirSync()\n for (const e of entries) {\n if (!filter || filter(e)) {\n results.push(withFileTypes ? e : e.fullpath())\n }\n let r: PathBase | undefined = e\n if (e.isSymbolicLink()) {\n if (!(follow && (r = e.realpathSync()))) continue\n if (r.isUnknown()) r.lstatSync()\n }\n if (r.shouldWalk(dirs, walkFilter)) {\n dirs.add(r)\n }\n }\n }\n return results as string[] | PathBase[]\n }\n\n /**\n * Support for `for await`\n *\n * Alias for {@link PathScurryBase.iterate}\n *\n * Note: As of Node 19, this is very slow, compared to other methods of\n * walking. Consider using {@link PathScurryBase.stream} if memory overhead\n * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n */\n [Symbol.asyncIterator]() {\n return this.iterate()\n }\n\n /**\n * Async generator form of {@link PathScurryBase.walk}\n *\n * Note: As of Node 19, this is very slow, compared to other methods of\n * walking, especially if most/all of the directory tree has been previously\n * walked. Consider using {@link PathScurryBase.stream} if memory overhead\n * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n */\n iterate(): AsyncGenerator<PathBase, void, void>\n iterate(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): AsyncGenerator<PathBase, void, void>\n iterate(\n opts: WalkOptionsWithFileTypesFalse,\n ): AsyncGenerator<string, void, void>\n iterate(opts: WalkOptions): AsyncGenerator<string | PathBase, void, void>\n iterate(entry: string | PathBase): AsyncGenerator<PathBase, void, void>\n iterate(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): AsyncGenerator<PathBase, void, void>\n iterate(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): AsyncGenerator<string, void, void>\n iterate(\n entry: string | PathBase,\n opts: WalkOptions,\n ): AsyncGenerator<PathBase | string, void, void>\n iterate(\n entry: string | PathBase | WalkOptions = this.cwd,\n options: WalkOptions = {},\n ): AsyncGenerator<PathBase | string, void, void> {\n // iterating async over the stream is significantly more performant,\n // especially in the warm-cache scenario, because it buffers up directory\n // entries in the background instead of waiting for a yield for each one.\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n options = entry\n entry = this.cwd\n }\n return this.stream(entry, options)[Symbol.asyncIterator]()\n }\n\n /**\n * Iterating over a PathScurry performs a synchronous walk.\n *\n * Alias for {@link PathScurryBase.iterateSync}\n */\n [Symbol.iterator]() {\n return this.iterateSync()\n }\n\n iterateSync(): Generator<PathBase, void, void>\n iterateSync(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Generator<PathBase, void, void>\n iterateSync(\n opts: WalkOptionsWithFileTypesFalse,\n ): Generator<string, void, void>\n iterateSync(opts: WalkOptions): Generator<string | PathBase, void, void>\n iterateSync(entry: string | PathBase): Generator<PathBase, void, void>\n iterateSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Generator<PathBase, void, void>\n iterateSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Generator<string, void, void>\n iterateSync(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Generator<PathBase | string, void, void>\n *iterateSync(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Generator<PathBase | string, void, void> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n if (!filter || filter(entry)) {\n yield withFileTypes ? entry : entry.fullpath()\n }\n const dirs = new Set<PathBase>([entry])\n for (const dir of dirs) {\n const entries = dir.readdirSync()\n for (const e of entries) {\n if (!filter || filter(e)) {\n yield withFileTypes ? e : e.fullpath()\n }\n let r: PathBase | undefined = e\n if (e.isSymbolicLink()) {\n if (!(follow && (r = e.realpathSync()))) continue\n if (r.isUnknown()) r.lstatSync()\n }\n if (r.shouldWalk(dirs, walkFilter)) {\n dirs.add(r)\n }\n }\n }\n }\n\n /**\n * Stream form of {@link PathScurryBase.walk}\n *\n * Returns a Minipass stream that emits {@link PathBase} objects by default,\n * or strings if `{ withFileTypes: false }` is set in the options.\n */\n stream(): Minipass<PathBase>\n stream(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Minipass<PathBase>\n stream(opts: WalkOptionsWithFileTypesFalse): Minipass<string>\n stream(opts: WalkOptions): Minipass<string | PathBase>\n stream(entry: string | PathBase): Minipass<PathBase>\n stream(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n ): Minipass<PathBase>\n stream(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Minipass<string>\n stream(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Minipass<string> | Minipass<PathBase>\n stream(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Minipass<string> | Minipass<PathBase> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results = new Minipass<string | PathBase>({ objectMode: true })\n if (!filter || filter(entry)) {\n results.write(withFileTypes ? entry : entry.fullpath())\n }\n const dirs = new Set<PathBase>()\n const queue: PathBase[] = [entry]\n let processing = 0\n const process = () => {\n let paused = false\n while (!paused) {\n const dir = queue.shift()\n if (!dir) {\n if (processing === 0) results.end()\n return\n }\n\n processing++\n dirs.add(dir)\n\n const onReaddir = (\n er: null | NodeJS.ErrnoException,\n entries: PathBase[],\n didRealpaths: boolean = false,\n ) => {\n /* c8 ignore start */\n if (er) return results.emit('error', er)\n /* c8 ignore stop */\n if (follow && !didRealpaths) {\n const promises: Promise<PathBase | undefined>[] = []\n for (const e of entries) {\n if (e.isSymbolicLink()) {\n promises.push(\n e\n .realpath()\n .then((r: PathBase | undefined) =>\n r?.isUnknown() ? r.lstat() : r,\n ),\n )\n }\n }\n if (promises.length) {\n Promise.all(promises).then(() =>\n onReaddir(null, entries, true),\n )\n return\n }\n }\n\n for (const e of entries) {\n if (e && (!filter || filter(e))) {\n if (!results.write(withFileTypes ? e : e.fullpath())) {\n paused = true\n }\n }\n }\n\n processing--\n for (const e of entries) {\n const r = e.realpathCached() || e\n if (r.shouldWalk(dirs, walkFilter)) {\n queue.push(r)\n }\n }\n if (paused && !results.flowing) {\n results.once('drain', process)\n } else if (!sync) {\n process()\n }\n }\n\n // zalgo containment\n let sync = true\n dir.readdirCB(onReaddir, true)\n sync = false\n }\n }\n process()\n return results as Minipass<string> | Minipass<PathBase>\n }\n\n /**\n * Synchronous form of {@link PathScurryBase.stream}\n *\n * Returns a Minipass stream that emits {@link PathBase} objects by default,\n * or strings if `{ withFileTypes: false }` is set in the options.\n *\n * Will complete the walk in a single tick if the stream is consumed fully.\n * Otherwise, will pause as needed for stream backpressure.\n */\n streamSync(): Minipass<PathBase>\n streamSync(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Minipass<PathBase>\n streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass<string>\n streamSync(opts: WalkOptions): Minipass<string | PathBase>\n streamSync(entry: string | PathBase): Minipass<PathBase>\n streamSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n ): Minipass<PathBase>\n streamSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Minipass<string>\n streamSync(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Minipass<string> | Minipass<PathBase>\n streamSync(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Minipass<string> | Minipass<PathBase> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results = new Minipass<string | PathBase>({ objectMode: true })\n const dirs = new Set<PathBase>()\n if (!filter || filter(entry)) {\n results.write(withFileTypes ? entry : entry.fullpath())\n }\n const queue: PathBase[] = [entry]\n let processing = 0\n const process = () => {\n let paused = false\n while (!paused) {\n const dir = queue.shift()\n if (!dir) {\n if (processing === 0) results.end()\n return\n }\n processing++\n dirs.add(dir)\n\n const entries = dir.readdirSync()\n for (const e of entries) {\n if (!filter || filter(e)) {\n if (!results.write(withFileTypes ? e : e.fullpath())) {\n paused = true\n }\n }\n }\n processing--\n for (const e of entries) {\n let r: PathBase | undefined = e\n if (e.isSymbolicLink()) {\n if (!(follow && (r = e.realpathSync()))) continue\n if (r.isUnknown()) r.lstatSync()\n }\n if (r.shouldWalk(dirs, walkFilter)) {\n queue.push(r)\n }\n }\n }\n if (paused && !results.flowing) results.once('drain', process)\n }\n process()\n return results as Minipass<string> | Minipass<PathBase>\n }\n\n chdir(path: string | Path = this.cwd) {\n const oldCwd = this.cwd\n this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n this.cwd[setAsCwd](oldCwd)\n }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n /**\n * Return results as {@link PathBase} objects rather than strings.\n * When set to false, results are fully resolved paths, as returned by\n * {@link PathBase.fullpath}.\n * @default true\n */\n withFileTypes?: boolean\n\n /**\n * Attempt to read directory entries from symbolic links. Otherwise, only\n * actual directories are traversed. Regardless of this setting, a given\n * target path will only ever be walked once, meaning that a symbolic link\n * to a previously traversed directory will never be followed.\n *\n * Setting this imposes a slight performance penalty, because `readlink`\n * must be called on all symbolic links encountered, in order to avoid\n * infinite cycles.\n * @default false\n */\n follow?: boolean\n\n /**\n * Only return entries where the provided function returns true.\n *\n * This will not prevent directories from being traversed, even if they do\n * not pass the filter, though it will prevent directories themselves from\n * being included in the result set. See {@link walkFilter}\n *\n * Asynchronous functions are not supported here.\n *\n * By default, if no filter is provided, all entries and traversed\n * directories are included.\n */\n filter?: (entry: PathBase) => boolean\n\n /**\n * Only traverse directories (and in the case of {@link follow} being set to\n * true, symbolic links to directories) if the provided function returns\n * true.\n *\n * This will not prevent directories from being included in the result set,\n * even if they do not pass the supplied filter function. See {@link filter}\n * to do that.\n *\n * Asynchronous functions are not supported here.\n */\n walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings. Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n /**\n * separator for generating path strings\n */\n sep: '\\\\' = '\\\\'\n\n constructor(\n cwd: URL | string = process.cwd(),\n opts: PathScurryOpts = {},\n ) {\n const { nocase = true } = opts\n super(cwd, win32, '\\\\', { ...opts, nocase })\n this.nocase = nocase\n for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n p.nocase = this.nocase\n }\n }\n\n /**\n * @internal\n */\n parseRootPath(dir: string): string {\n // if the path starts with a single separator, it's not a UNC, and we'll\n // just get separator as the root, and driveFromUNC will return \\\n // In that case, mount \\ on the root from the cwd.\n return win32.parse(dir).root.toUpperCase()\n }\n\n /**\n * @internal\n */\n newRoot(fs: FSValue) {\n return new PathWin32(\n this.rootPath,\n IFDIR,\n undefined,\n this.roots,\n this.nocase,\n this.childrenCache(),\n { fs },\n )\n }\n\n /**\n * Return true if the provided path string is an absolute path\n */\n isAbsolute(p: string): boolean {\n return (\n p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n )\n }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n /**\n * separator for generating path strings\n */\n sep: '/' = '/'\n constructor(\n cwd: URL | string = process.cwd(),\n opts: PathScurryOpts = {},\n ) {\n const { nocase = false } = opts\n super(cwd, posix, '/', { ...opts, nocase })\n this.nocase = nocase\n }\n\n /**\n * @internal\n */\n parseRootPath(_dir: string): string {\n return '/'\n }\n\n /**\n * @internal\n */\n newRoot(fs: FSValue) {\n return new PathPosix(\n this.rootPath,\n IFDIR,\n undefined,\n this.roots,\n this.nocase,\n this.childrenCache(),\n { fs },\n )\n }\n\n /**\n * Return true if the provided path string is an absolute path\n */\n isAbsolute(p: string): boolean {\n return p.startsWith('/')\n }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n constructor(\n cwd: URL | string = process.cwd(),\n opts: PathScurryOpts = {},\n ) {\n const { nocase = true } = opts\n super(cwd, { ...opts, nocase })\n }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType<typeof Path>\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n | typeof PathScurryWin32\n | typeof PathScurryDarwin\n | typeof PathScurryPosix =\n process.platform === 'win32' ? PathScurryWin32\n : process.platform === 'darwin' ? PathScurryDarwin\n : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType<typeof PathScurry>\n", "const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe<T extends unknown> {\n src: Minipass<T>\n dest: Minipass<any, T>\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass<any, T>\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors<T> extends Pipe<T> {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrors = er => dest.emit('error', er)\n src.on('error', this.proxyErrors)\n }\n}\n\nexport namespace Minipass {\n /**\n * Encoding used to create a stream that outputs strings rather than\n * Buffer objects.\n */\n export type Encoding = BufferEncoding | 'buffer' | null\n\n /**\n * Any stream that Minipass can pipe into\n */\n export type Writable =\n | Minipass<any, any, any>\n | NodeJS.WriteStream\n | (NodeJS.WriteStream & { fd: number })\n | (EventEmitter & {\n end(): any\n write(chunk: any, ...args: any[]): any\n })\n\n /**\n * Any stream that can be read from\n */\n export type Readable =\n | Minipass<any, any, any>\n | NodeJS.ReadStream\n | (NodeJS.ReadStream & { fd: number })\n | (EventEmitter & {\n pause(): any\n resume(): any\n pipe(...destArgs: any[]): any\n })\n\n /**\n * Utility type that can be iterated sync or async\n */\n export type DualIterable<T> = Iterable<T> & AsyncIterable<T>\n\n type EventArguments = Record<string | symbol, unknown[]>\n\n /**\n * The listing of events that a Minipass class can emit.\n * Extend this when extending the Minipass class, and pass as\n * the third template argument. The key is the name of the event,\n * and the value is the argument list.\n *\n * Any undeclared events will still be allowed, but the handler will get\n * arguments as `unknown[]`.\n */\n export interface Events<RType extends any = Buffer>\n extends EventArguments {\n readable: []\n data: [chunk: RType]\n error: [er: unknown]\n abort: [reason: unknown]\n drain: []\n resume: []\n end: []\n finish: []\n prefinish: []\n close: []\n [DESTROYED]: [er?: unknown]\n [ERROR]: [er: unknown]\n }\n\n /**\n * String or buffer-like data that can be joined and sliced\n */\n export type ContiguousData =\n | Buffer\n | ArrayBufferLike\n | ArrayBufferView\n | string\n export type BufferOrString = Buffer | string\n\n /**\n * Options passed to the Minipass constructor.\n */\n export type SharedOptions = {\n /**\n * Defer all data emission and other events until the end of the\n * current tick, similar to Node core streams\n */\n async?: boolean\n /**\n * A signal which will abort the stream\n */\n signal?: AbortSignal\n /**\n * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n * emit Buffer objects rather than strings.\n *\n * Conflicts with `objectMode`\n */\n encoding?: BufferEncoding | null | 'buffer'\n /**\n * Output data exactly as it was written, supporting non-buffer/string\n * data (such as arbitrary objects, falsey values, etc.)\n *\n * Conflicts with `encoding`\n */\n objectMode?: boolean\n }\n\n /**\n * Options for a string encoded output\n */\n export type EncodingOptions = SharedOptions & {\n encoding: BufferEncoding\n objectMode?: false\n }\n\n /**\n * Options for contiguous data buffer output\n */\n export type BufferOptions = SharedOptions & {\n encoding?: null | 'buffer'\n objectMode?: false\n }\n\n /**\n * Options for objectMode arbitrary output\n */\n export type ObjectModeOptions = SharedOptions & {\n objectMode: true\n encoding?: null\n }\n\n /**\n * Utility type to determine allowed options based on read type\n */\n export type Options<T> =\n | ObjectModeOptions\n | (T extends string\n ? EncodingOptions\n : T extends Buffer\n ? BufferOptions\n : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n RType extends unknown = Buffer,\n WType extends unknown = RType extends Minipass.BufferOrString\n ? Minipass.ContiguousData\n : RType,\n Events extends Minipass.Events<RType> = Minipass.Events<RType>\n >\n extends EventEmitter\n implements Minipass.DualIterable<RType>\n{\n [FLOWING]: boolean = false;\n [PAUSED]: boolean = false;\n [PIPES]: Pipe<RType>[] = [];\n [BUFFER]: RType[] = [];\n [OBJECTMODE]: boolean;\n [ENCODING]: BufferEncoding | null;\n [ASYNC]: boolean;\n [DECODER]: SD | null;\n [EOF]: boolean = false;\n [EMITTED_END]: boolean = false;\n [EMITTING_END]: boolean = false;\n [CLOSED]: boolean = false;\n [EMITTED_ERROR]: unknown = null;\n [BUFFERLENGTH]: number = 0;\n [DESTROYED]: boolean = false;\n [SIGNAL]?: AbortSignal;\n [ABORTED]: boolean = false;\n [DATALISTENERS]: number = 0;\n [DISCARDED]: boolean = false\n\n /**\n * true if the stream can be written\n */\n writable: boolean = true\n /**\n * true if the stream can be read\n */\n readable: boolean = true\n\n /**\n * If `RType` is Buffer, then options do not need to be provided.\n * Otherwise, an options object must be provided to specify either\n * {@link Minipass.SharedOptions.objectMode} or\n * {@link Minipass.SharedOptions.encoding}, as appropriate.\n */\n constructor(\n ...args:\n | [Minipass.ObjectModeOptions]\n | (RType extends Buffer\n ? [] | [Minipass.Options<RType>]\n : [Minipass.Options<RType>])\n ) {\n const options: Minipass.Options<RType> = (args[0] ||\n {}) as Minipass.Options<RType>\n super()\n if (options.objectMode && typeof options.encoding === 'string') {\n throw new TypeError(\n 'Encoding and objectMode may not be used together'\n )\n }\n if (isObjectModeOptions(options)) {\n this[OBJECTMODE] = true\n this[ENCODING] = null\n } else if (isEncodingOptions(options)) {\n this[ENCODING] = options.encoding\n this[OBJECTMODE] = false\n } else {\n this[OBJECTMODE] = false\n this[ENCODING] = null\n }\n this[ASYNC] = !!options.async\n this[DECODER] = this[ENCODING]\n ? (new StringDecoder(this[ENCODING]) as SD)\n : null\n\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposeBuffer === true) {\n Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n }\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposePipes === true) {\n Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n }\n\n const { signal } = options\n if (signal) {\n this[SIGNAL] = signal\n if (signal.aborted) {\n this[ABORT]()\n } else {\n signal.addEventListener('abort', () => this[ABORT]())\n }\n }\n }\n\n /**\n * The amount of data stored in the buffer waiting to be read.\n *\n * For Buffer strings, this will be the total byte length.\n * For string encoding streams, this will be the string character length,\n * according to JavaScript's `string.length` logic.\n * For objectMode streams, this is a count of the items waiting to be\n * emitted.\n */\n get bufferLength() {\n return this[BUFFERLENGTH]\n }\n\n /**\n * The `BufferEncoding` currently in use, or `null`\n */\n get encoding() {\n return this[ENCODING]\n }\n\n /**\n * @deprecated - This is a read only property\n */\n set encoding(_enc) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * @deprecated - Encoding may only be set at instantiation time\n */\n setEncoding(_enc: Minipass.Encoding) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * True if this is an objectMode stream\n */\n get objectMode() {\n return this[OBJECTMODE]\n }\n\n /**\n * @deprecated - This is a read-only property\n */\n set objectMode(_om) {\n throw new Error('objectMode must be set at instantiation time')\n }\n\n /**\n * true if this is an async stream\n */\n get ['async'](): boolean {\n return this[ASYNC]\n }\n /**\n * Set to true to make this stream async.\n *\n * Once set, it cannot be unset, as this would potentially cause incorrect\n * behavior. Ie, a sync stream can be made async, but an async stream\n * cannot be safely made sync.\n */\n set ['async'](a: boolean) {\n this[ASYNC] = this[ASYNC] || !!a\n }\n\n // drop everything and get out of the flow completely\n [ABORT]() {\n this[ABORTED] = true\n this.emit('abort', this[SIGNAL]?.reason)\n this.destroy(this[SIGNAL]?.reason)\n }\n\n /**\n * True if the stream has been aborted.\n */\n get aborted() {\n return this[ABORTED]\n }\n /**\n * No-op setter. Stream aborted status is set via the AbortSignal provided\n * in the constructor options.\n */\n set aborted(_) {}\n\n /**\n * Write data into the stream\n *\n * If the chunk written is a string, and encoding is not specified, then\n * `utf8` will be assumed. If the stream encoding matches the encoding of\n * a written string, and the state of the string decoder allows it, then\n * the string will be passed through to either the output or the internal\n * buffer without any processing. Otherwise, it will be turned into a\n * Buffer object for processing into the desired encoding.\n *\n * If provided, `cb` function is called immediately before return for\n * sync streams, or on next tick for async streams, because for this\n * base class, a chunk is considered \"processed\" once it is accepted\n * and either emitted or buffered. That is, the callback does not indicate\n * that the chunk has been eventually emitted, though of course child\n * classes can override this function to do whatever processing is required\n * and call `super.write(...)` only once processing is completed.\n */\n write(chunk: WType, cb?: () => void): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding,\n cb?: () => void\n ): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): boolean {\n if (this[ABORTED]) return false\n if (this[EOF]) throw new Error('write after end')\n\n if (this[DESTROYED]) {\n this.emit(\n 'error',\n Object.assign(\n new Error('Cannot call write after a stream was destroyed'),\n { code: 'ERR_STREAM_DESTROYED' }\n )\n )\n return true\n }\n\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n\n if (!encoding) encoding = 'utf8'\n\n const fn = this[ASYNC] ? defer : nodefer\n\n // convert array buffers and typed array views into buffers\n // at some point in the future, we may want to do the opposite!\n // leave strings and buffers as-is\n // anything is only allowed if in object mode, so throw\n if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n if (isArrayBufferView(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n )\n } else if (isArrayBufferLike(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(chunk)\n } else if (typeof chunk !== 'string') {\n throw new Error(\n 'Non-contiguous data written to non-objectMode stream'\n )\n }\n }\n\n // handle object mode up front, since it's simpler\n // this yields better performance, fewer checks later.\n if (this[OBJECTMODE]) {\n // maybe impossible?\n /* c8 ignore start */\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n /* c8 ignore stop */\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n // at this point the chunk is a buffer or string\n // don't buffer it up or send it to the decoder\n if (!(chunk as Minipass.BufferOrString).length) {\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n if (cb) fn(cb)\n return this[FLOWING]\n }\n\n // fast-path writing strings of same encoding to a stream with\n // an empty buffer, skipping the buffer/decoder dance\n if (\n typeof chunk === 'string' &&\n // unless it is a string already ready for us to use\n !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n ) {\n //@ts-ignore - sinful unsafe type change\n chunk = Buffer.from(chunk, encoding)\n }\n\n if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n //@ts-ignore - sinful unsafe type change\n chunk = this[DECODER].write(chunk)\n }\n\n // Note: flushing CAN potentially switch us into not-flowing mode\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n /**\n * Low-level explicit read method.\n *\n * In objectMode, the argument is ignored, and one item is returned if\n * available.\n *\n * `n` is the number of bytes (or in the case of encoding streams,\n * characters) to consume. If `n` is not provided, then the entire buffer\n * is returned, or `null` is returned if no data is available.\n *\n * If `n` is greater that the amount of data in the internal buffer,\n * then `null` is returned.\n */\n read(n?: number | null): RType | null {\n if (this[DESTROYED]) return null\n this[DISCARDED] = false\n\n if (\n this[BUFFERLENGTH] === 0 ||\n n === 0 ||\n (n && n > this[BUFFERLENGTH])\n ) {\n this[MAYBE_EMIT_END]()\n return null\n }\n\n if (this[OBJECTMODE]) n = null\n\n if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n // not object mode, so if we have an encoding, then RType is string\n // otherwise, must be Buffer\n this[BUFFER] = [\n (this[ENCODING]\n ? this[BUFFER].join('')\n : Buffer.concat(\n this[BUFFER] as Buffer[],\n this[BUFFERLENGTH]\n )) as RType,\n ]\n }\n\n const ret = this[READ](n || null, this[BUFFER][0] as RType)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [READ](n: number | null, chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n else {\n const c = chunk as Minipass.BufferOrString\n if (n === c.length || n === null) this[BUFFERSHIFT]()\n else if (typeof c === 'string') {\n this[BUFFER][0] = c.slice(n) as RType\n chunk = c.slice(0, n) as RType\n this[BUFFERLENGTH] -= n\n } else {\n this[BUFFER][0] = c.subarray(n) as RType\n chunk = c.subarray(0, n) as RType\n this[BUFFERLENGTH] -= n\n }\n }\n\n this.emit('data', chunk)\n\n if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n return chunk\n }\n\n /**\n * End the stream, optionally providing a final write.\n *\n * See {@link Minipass#write} for argument descriptions\n */\n end(cb?: () => void): this\n end(chunk: WType, cb?: () => void): this\n end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n end(\n chunk?: WType | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): this {\n if (typeof chunk === 'function') {\n cb = chunk as () => void\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n if (chunk !== undefined) this.write(chunk, encoding)\n if (cb) this.once('end', cb)\n this[EOF] = true\n this.writable = false\n\n // if we haven't written anything, then go ahead and emit,\n // even if we're not reading.\n // we'll re-emit if a new 'end' listener is added anyway.\n // This makes MP more suitable to write-only use cases.\n if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n return this\n }\n\n // don't let the internal resume be overwritten\n [RESUME]() {\n if (this[DESTROYED]) return\n\n if (!this[DATALISTENERS] && !this[PIPES].length) {\n this[DISCARDED] = true\n }\n this[PAUSED] = false\n this[FLOWING] = true\n this.emit('resume')\n if (this[BUFFER].length) this[FLUSH]()\n else if (this[EOF]) this[MAYBE_EMIT_END]()\n else this.emit('drain')\n }\n\n /**\n * Resume the stream if it is currently in a paused state\n *\n * If called when there are no pipe destinations or `data` event listeners,\n * this will place the stream in a \"discarded\" state, where all data will\n * be thrown away. The discarded state is removed if a pipe destination or\n * data handler is added, if pause() is called, or if any synchronous or\n * asynchronous iteration is started.\n */\n resume() {\n return this[RESUME]()\n }\n\n /**\n * Pause the stream\n */\n pause() {\n this[FLOWING] = false\n this[PAUSED] = true\n this[DISCARDED] = false\n }\n\n /**\n * true if the stream has been forcibly destroyed\n */\n get destroyed() {\n return this[DESTROYED]\n }\n\n /**\n * true if the stream is currently in a flowing state, meaning that\n * any writes will be immediately emitted.\n */\n get flowing() {\n return this[FLOWING]\n }\n\n /**\n * true if the stream is currently in a paused state\n */\n get paused() {\n return this[PAUSED]\n }\n\n [BUFFERPUSH](chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n this[BUFFER].push(chunk)\n }\n\n [BUFFERSHIFT](): RType {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n else\n this[BUFFERLENGTH] -= (\n this[BUFFER][0] as Minipass.BufferOrString\n ).length\n return this[BUFFER].shift() as RType\n }\n\n [FLUSH](noDrain: boolean = false) {\n do {} while (\n this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n this[BUFFER].length\n )\n\n if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n }\n\n [FLUSHCHUNK](chunk: RType) {\n this.emit('data', chunk)\n return this[FLOWING]\n }\n\n /**\n * Pipe all data emitted by this stream into the destination provided.\n *\n * Triggers the flow of data.\n */\n pipe<W extends Minipass.Writable>(dest: W, opts?: PipeOptions): W {\n if (this[DESTROYED]) return dest\n this[DISCARDED] = false\n\n const ended = this[EMITTED_END]\n opts = opts || {}\n if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n else opts.end = opts.end !== false\n opts.proxyErrors = !!opts.proxyErrors\n\n // piping an ended stream ends immediately\n if (ended) {\n if (opts.end) dest.end()\n } else {\n // \"as\" here just ignores the WType, which pipes don't care about,\n // since they're only consuming from us, and writing to the dest\n this[PIPES].push(\n !opts.proxyErrors\n ? new Pipe<RType>(this as Minipass<RType>, dest, opts)\n : new PipeProxyErrors<RType>(this as Minipass<RType>, dest, opts)\n )\n if (this[ASYNC]) defer(() => this[RESUME]())\n else this[RESUME]()\n }\n\n return dest\n }\n\n /**\n * Fully unhook a piped destination stream.\n *\n * If the destination stream was the only consumer of this stream (ie,\n * there are no other piped destinations or `'data'` event listeners)\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n unpipe<W extends Minipass.Writable>(dest: W) {\n const p = this[PIPES].find(p => p.dest === dest)\n if (p) {\n if (this[PIPES].length === 1) {\n if (this[FLOWING] && this[DATALISTENERS] === 0) {\n this[FLOWING] = false\n }\n this[PIPES] = []\n } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n p.unpipe()\n }\n }\n\n /**\n * Alias for {@link Minipass#on}\n */\n addListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n return this.on(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.on`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * - Adding a 'data' event handler will trigger the flow of data\n *\n * - Adding a 'readable' event handler when there is data waiting to be read\n * will cause 'readable' to be emitted immediately.\n *\n * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n * already passed will cause the event to be emitted immediately and all\n * handlers removed.\n *\n * - Adding an 'error' event handler after an error has been emitted will\n * cause the event to be re-emitted immediately with the error previously\n * raised.\n */\n on<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n const ret = super.on(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n if (ev === 'data') {\n this[DISCARDED] = false\n this[DATALISTENERS]++\n if (!this[PIPES].length && !this[FLOWING]) {\n this[RESUME]()\n }\n } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n super.emit('readable')\n } else if (isEndish(ev) && this[EMITTED_END]) {\n super.emit(ev)\n this.removeAllListeners(ev)\n } else if (ev === 'error' && this[EMITTED_ERROR]) {\n const h = handler as (...a: Events['error']) => any\n if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n else h.call(this, this[EMITTED_ERROR])\n }\n return ret\n }\n\n /**\n * Alias for {@link Minipass#off}\n */\n removeListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n return this.off(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.off`\n *\n * If a 'data' event handler is removed, and it was the last consumer\n * (ie, there are no pipe destinations or other 'data' event listeners),\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n off<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n const ret = super.off(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n // if we previously had listeners, and now we don't, and we don't\n // have any pipes, then stop the flow, unless it's been explicitly\n // put in a discarded flowing state via stream.resume().\n if (ev === 'data') {\n this[DATALISTENERS] = this.listeners('data').length\n if (\n this[DATALISTENERS] === 0 &&\n !this[DISCARDED] &&\n !this[PIPES].length\n ) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * Mostly identical to `EventEmitter.removeAllListeners`\n *\n * If all 'data' event handlers are removed, and they were the last consumer\n * (ie, there are no pipe destinations), then the flow of data will stop\n * until there is another consumer or {@link Minipass#resume} is explicitly\n * called.\n */\n removeAllListeners<Event extends keyof Events>(ev?: Event) {\n const ret = super.removeAllListeners(ev as string | symbol | undefined)\n if (ev === 'data' || ev === undefined) {\n this[DATALISTENERS] = 0\n if (!this[DISCARDED] && !this[PIPES].length) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * true if the 'end' event has been emitted\n */\n get emittedEnd() {\n return this[EMITTED_END]\n }\n\n [MAYBE_EMIT_END]() {\n if (\n !this[EMITTING_END] &&\n !this[EMITTED_END] &&\n !this[DESTROYED] &&\n this[BUFFER].length === 0 &&\n this[EOF]\n ) {\n this[EMITTING_END] = true\n this.emit('end')\n this.emit('prefinish')\n this.emit('finish')\n if (this[CLOSED]) this.emit('close')\n this[EMITTING_END] = false\n }\n }\n\n /**\n * Mostly identical to `EventEmitter.emit`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * If the stream has been destroyed, and the event is something other\n * than 'close' or 'error', then `false` is returned and no handlers\n * are called.\n *\n * If the event is 'end', and has already been emitted, then the event\n * is ignored. If the stream is in a paused or non-flowing state, then\n * the event will be deferred until data flow resumes. If the stream is\n * async, then handlers will be called on the next tick rather than\n * immediately.\n *\n * If the event is 'close', and 'end' has not yet been emitted, then\n * the event will be deferred until after 'end' is emitted.\n *\n * If the event is 'error', and an AbortSignal was provided for the stream,\n * and there are no listeners, then the event is ignored, matching the\n * behavior of node core streams in the presense of an AbortSignal.\n *\n * If the event is 'finish' or 'prefinish', then all listeners will be\n * removed after emitting the event, to prevent double-firing.\n */\n emit<Event extends keyof Events>(\n ev: Event,\n ...args: Events[Event]\n ): boolean {\n const data = args[0]\n // error and close are only events allowed after calling destroy()\n if (\n ev !== 'error' &&\n ev !== 'close' &&\n ev !== DESTROYED &&\n this[DESTROYED]\n ) {\n return false\n } else if (ev === 'data') {\n return !this[OBJECTMODE] && !data\n ? false\n : this[ASYNC]\n ? (defer(() => this[EMITDATA](data as RType)), true)\n : this[EMITDATA](data as RType)\n } else if (ev === 'end') {\n return this[EMITEND]()\n } else if (ev === 'close') {\n this[CLOSED] = true\n // don't emit close before 'end' and 'finish'\n if (!this[EMITTED_END] && !this[DESTROYED]) return false\n const ret = super.emit('close')\n this.removeAllListeners('close')\n return ret\n } else if (ev === 'error') {\n this[EMITTED_ERROR] = data\n super.emit(ERROR, data)\n const ret =\n !this[SIGNAL] || this.listeners('error').length\n ? super.emit('error', data)\n : false\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'resume') {\n const ret = super.emit('resume')\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'finish' || ev === 'prefinish') {\n const ret = super.emit(ev)\n this.removeAllListeners(ev)\n return ret\n }\n\n // Some other unknown event\n const ret = super.emit(ev as string, ...args)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITDATA](data: RType) {\n for (const p of this[PIPES]) {\n if (p.dest.write(data as RType) === false) this.pause()\n }\n const ret = this[DISCARDED] ? false : super.emit('data', data)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITEND]() {\n if (this[EMITTED_END]) return false\n\n this[EMITTED_END] = true\n this.readable = false\n return this[ASYNC]\n ? (defer(() => this[EMITEND2]()), true)\n : this[EMITEND2]()\n }\n\n [EMITEND2]() {\n if (this[DECODER]) {\n const data = this[DECODER].end()\n if (data) {\n for (const p of this[PIPES]) {\n p.dest.write(data as RType)\n }\n if (!this[DISCARDED]) super.emit('data', data)\n }\n }\n\n for (const p of this[PIPES]) {\n p.end()\n }\n const ret = super.emit('end')\n this.removeAllListeners('end')\n return ret\n }\n\n /**\n * Return a Promise that resolves to an array of all emitted data once\n * the stream ends.\n */\n async collect(): Promise<RType[] & { dataLength: number }> {\n const buf: RType[] & { dataLength: number } = Object.assign([], {\n dataLength: 0,\n })\n if (!this[OBJECTMODE]) buf.dataLength = 0\n // set the promise first, in case an error is raised\n // by triggering the flow here.\n const p = this.promise()\n this.on('data', c => {\n buf.push(c)\n if (!this[OBJECTMODE])\n buf.dataLength += (c as Minipass.BufferOrString).length\n })\n await p\n return buf\n }\n\n /**\n * Return a Promise that resolves to the concatenation of all emitted data\n * once the stream ends.\n *\n * Not allowed on objectMode streams.\n */\n async concat(): Promise<RType> {\n if (this[OBJECTMODE]) {\n throw new Error('cannot concat in objectMode')\n }\n const buf = await this.collect()\n return (\n this[ENCODING]\n ? buf.join('')\n : Buffer.concat(buf as Buffer[], buf.dataLength)\n ) as RType\n }\n\n /**\n * Return a void Promise that resolves once the stream ends.\n */\n async promise(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n this.on('error', er => reject(er))\n this.on('end', () => resolve())\n })\n }\n\n /**\n * Asynchronous `for await of` iteration.\n *\n * This will continue emitting all chunks until the stream terminates.\n */\n [Symbol.asyncIterator](): AsyncGenerator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = async (): Promise<IteratorReturnResult<void>> => {\n this.pause()\n stopped = true\n return { value: undefined, done: true }\n }\n const next = (): Promise<IteratorResult<RType, void>> => {\n if (stopped) return stop()\n const res = this.read()\n if (res !== null) return Promise.resolve({ done: false, value: res })\n\n if (this[EOF]) return stop()\n\n let resolve!: (res: IteratorResult<RType>) => void\n let reject!: (er: unknown) => void\n const onerr = (er: unknown) => {\n this.off('data', ondata)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n stop()\n reject(er)\n }\n const ondata = (value: RType) => {\n this.off('error', onerr)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n this.pause()\n resolve({ value, done: !!this[EOF] })\n }\n const onend = () => {\n this.off('error', onerr)\n this.off('data', ondata)\n this.off(DESTROYED, ondestroy)\n stop()\n resolve({ done: true, value: undefined })\n }\n const ondestroy = () => onerr(new Error('stream destroyed'))\n return new Promise<IteratorResult<RType>>((res, rej) => {\n reject = rej\n resolve = res\n this.once(DESTROYED, ondestroy)\n this.once('error', onerr)\n this.once('end', onend)\n this.once('data', ondata)\n })\n }\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.asyncIterator]() {\n return this\n },\n }\n }\n\n /**\n * Synchronous `for of` iteration.\n *\n * The iteration will terminate when the internal buffer runs out, even\n * if the stream has not yet terminated.\n */\n [Symbol.iterator](): Generator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = (): IteratorReturnResult<void> => {\n this.pause()\n this.off(ERROR, stop)\n this.off(DESTROYED, stop)\n this.off('end', stop)\n stopped = true\n return { done: true, value: undefined }\n }\n\n const next = (): IteratorResult<RType, void> => {\n if (stopped) return stop()\n const value = this.read()\n return value === null ? stop() : { done: false, value }\n }\n\n this.once('end', stop)\n this.once(ERROR, stop)\n this.once(DESTROYED, stop)\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n /**\n * Destroy a stream, preventing it from being used for any further purpose.\n *\n * If the stream has a `close()` method, then it will be called on\n * destruction.\n *\n * After destruction, any attempt to write data, read data, or emit most\n * events will be ignored.\n *\n * If an error argument is provided, then it will be emitted in an\n * 'error' event.\n */\n destroy(er?: unknown) {\n if (this[DESTROYED]) {\n if (er) this.emit('error', er)\n else this.emit(DESTROYED)\n return this\n }\n\n this[DESTROYED] = true\n this[DISCARDED] = true\n\n // throw away all buffered data, it's never coming out\n this[BUFFER].length = 0\n this[BUFFERLENGTH] = 0\n\n const wc = this as Minipass<RType, WType, Events> & {\n close?: () => void\n }\n if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n if (er) this.emit('error', er)\n // if no error to emit, still reject pending promises\n else this.emit(DESTROYED)\n\n return this\n }\n\n /**\n * Alias for {@link isStream}\n *\n * Former export location, maintained for backwards compatibility.\n *\n * @deprecated\n */\n static get isStream() {\n return isStream\n }\n}\n", "// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n p0: '',\n p1: '',\n p2: string,\n p3: string,\n ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n readonly #patternList: PatternList\n readonly #globList: GlobList\n readonly #index: number\n readonly length: number\n readonly #platform: NodeJS.Platform\n #rest?: Pattern | null\n #globString?: string\n #isDrive?: boolean\n #isUNC?: boolean\n #isAbsolute?: boolean\n #followGlobstar: boolean = true\n\n constructor(\n patternList: MMPattern[],\n globList: string[],\n index: number,\n platform: NodeJS.Platform,\n ) {\n if (!isPatternList(patternList)) {\n throw new TypeError('empty pattern list')\n }\n if (!isGlobList(globList)) {\n throw new TypeError('empty glob list')\n }\n if (globList.length !== patternList.length) {\n throw new TypeError('mismatched pattern list and glob list lengths')\n }\n this.length = patternList.length\n if (index < 0 || index >= this.length) {\n throw new TypeError('index out of range')\n }\n this.#patternList = patternList\n this.#globList = globList\n this.#index = index\n this.#platform = platform\n\n // normalize root entries of absolute patterns on initial creation.\n if (this.#index === 0) {\n // c: => ['c:/']\n // C:/ => ['C:/']\n // C:/x => ['C:/', 'x']\n // //host/share => ['//host/share/']\n // //host/share/ => ['//host/share/']\n // //host/share/x => ['//host/share/', 'x']\n // /etc => ['/', 'etc']\n // / => ['/']\n if (this.isUNC()) {\n // '' / '' / 'host' / 'share'\n const [p0, p1, p2, p3, ...prest] = this.#patternList\n const [g0, g1, g2, g3, ...grest] = this.#globList\n if (prest[0] === '') {\n // ends in /\n prest.shift()\n grest.shift()\n }\n const p = [p0, p1, p2, p3, ''].join('/')\n const g = [g0, g1, g2, g3, ''].join('/')\n this.#patternList = [p, ...prest]\n this.#globList = [g, ...grest]\n this.length = this.#patternList.length\n } else if (this.isDrive() || this.isAbsolute()) {\n const [p1, ...prest] = this.#patternList\n const [g1, ...grest] = this.#globList\n if (prest[0] === '') {\n // ends in /\n prest.shift()\n grest.shift()\n }\n const p = (p1 as string) + '/'\n const g = g1 + '/'\n this.#patternList = [p, ...prest]\n this.#globList = [g, ...grest]\n this.length = this.#patternList.length\n }\n }\n }\n\n /**\n * The first entry in the parsed list of patterns\n */\n pattern(): MMPattern {\n return this.#patternList[this.#index] as MMPattern\n }\n\n /**\n * true of if pattern() returns a string\n */\n isString(): boolean {\n return typeof this.#patternList[this.#index] === 'string'\n }\n /**\n * true of if pattern() returns GLOBSTAR\n */\n isGlobstar(): boolean {\n return this.#patternList[this.#index] === GLOBSTAR\n }\n /**\n * true if pattern() returns a regexp\n */\n isRegExp(): boolean {\n return this.#patternList[this.#index] instanceof RegExp\n }\n\n /**\n * The /-joined set of glob parts that make up this pattern\n */\n globString(): string {\n return (this.#globString =\n this.#globString ||\n (this.#index === 0 ?\n this.isAbsolute() ?\n this.#globList[0] + this.#globList.slice(1).join('/')\n : this.#globList.join('/')\n : this.#globList.slice(this.#index).join('/')))\n }\n\n /**\n * true if there are more pattern parts after this one\n */\n hasMore(): boolean {\n return this.length > this.#index + 1\n }\n\n /**\n * The rest of the pattern after this part, or null if this is the end\n */\n rest(): Pattern | null {\n if (this.#rest !== undefined) return this.#rest\n if (!this.hasMore()) return (this.#rest = null)\n this.#rest = new Pattern(\n this.#patternList,\n this.#globList,\n this.#index + 1,\n this.#platform,\n )\n this.#rest.#isAbsolute = this.#isAbsolute\n this.#rest.#isUNC = this.#isUNC\n this.#rest.#isDrive = this.#isDrive\n return this.#rest\n }\n\n /**\n * true if the pattern represents a //unc/path/ on windows\n */\n isUNC(): boolean {\n const pl = this.#patternList\n return this.#isUNC !== undefined ?\n this.#isUNC\n : (this.#isUNC =\n this.#platform === 'win32' &&\n this.#index === 0 &&\n pl[0] === '' &&\n pl[1] === '' &&\n typeof pl[2] === 'string' &&\n !!pl[2] &&\n typeof pl[3] === 'string' &&\n !!pl[3])\n }\n\n // pattern like C:/...\n // split = ['C:', ...]\n // XXX: would be nice to handle patterns like `c:*` to test the cwd\n // in c: for *, but I don't know of a way to even figure out what that\n // cwd is without actually chdir'ing into it?\n /**\n * True if the pattern starts with a drive letter on Windows\n */\n isDrive(): boolean {\n const pl = this.#patternList\n return this.#isDrive !== undefined ?\n this.#isDrive\n : (this.#isDrive =\n this.#platform === 'win32' &&\n this.#index === 0 &&\n this.length > 1 &&\n typeof pl[0] === 'string' &&\n /^[a-z]:$/i.test(pl[0]))\n }\n\n // pattern = '/' or '/...' or '/x/...'\n // split = ['', ''] or ['', ...] or ['', 'x', ...]\n // Drive and UNC both considered absolute on windows\n /**\n * True if the pattern is rooted on an absolute path\n */\n isAbsolute(): boolean {\n const pl = this.#patternList\n return this.#isAbsolute !== undefined ?\n this.#isAbsolute\n : (this.#isAbsolute =\n (pl[0] === '' && pl.length > 1) ||\n this.isDrive() ||\n this.isUNC())\n }\n\n /**\n * consume the root of the pattern, and return it\n */\n root(): string {\n const p = this.#patternList[0]\n return (\n typeof p === 'string' && this.isAbsolute() && this.#index === 0\n ) ?\n p\n : ''\n }\n\n /**\n * Check to see if the current globstar pattern is allowed to follow\n * a symbolic link.\n */\n checkFollowGlobstar(): boolean {\n return !(\n this.#index === 0 ||\n !this.isGlobstar() ||\n !this.#followGlobstar\n )\n }\n\n /**\n * Mark that the current globstar pattern is following a symbolic link\n */\n markFollowGlobstar(): boolean {\n if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n return false\n this.#followGlobstar = false\n return true\n }\n}\n", "// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n ignored?: (p: Path) => boolean\n childrenIgnored?: (p: Path) => boolean\n add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n relative: Minimatch[]\n relativeChildren: Minimatch[]\n absolute: Minimatch[]\n absoluteChildren: Minimatch[]\n platform: NodeJS.Platform\n mmopts: MinimatchOptions\n\n constructor(\n ignored: string[],\n {\n nobrace,\n nocase,\n noext,\n noglobstar,\n platform = defaultPlatform,\n }: GlobWalkerOpts,\n ) {\n this.relative = []\n this.absolute = []\n this.relativeChildren = []\n this.absoluteChildren = []\n this.platform = platform\n this.mmopts = {\n dot: true,\n nobrace,\n nocase,\n noext,\n noglobstar,\n optimizationLevel: 2,\n platform,\n nocomment: true,\n nonegate: true,\n }\n for (const ign of ignored) this.add(ign)\n }\n\n add(ign: string) {\n // this is a little weird, but it gives us a clean set of optimized\n // minimatch matchers, without getting tripped up if one of them\n // ends in /** inside a brace section, and it's only inefficient at\n // the start of the walk, not along it.\n // It'd be nice if the Pattern class just had a .test() method, but\n // handling globstars is a bit of a pita, and that code already lives\n // in minimatch anyway.\n // Another way would be if maybe Minimatch could take its set/globParts\n // as an option, and then we could at least just use Pattern to test\n // for absolute-ness.\n // Yet another way, Minimatch could take an array of glob strings, and\n // a cwd option, and do the right thing.\n const mm = new Minimatch(ign, this.mmopts)\n for (let i = 0; i < mm.set.length; i++) {\n const parsed = mm.set[i]\n const globParts = mm.globParts[i]\n /* c8 ignore start */\n if (!parsed || !globParts) {\n throw new Error('invalid pattern object')\n }\n // strip off leading ./ portions\n // https://github.com/isaacs/node-glob/issues/570\n while (parsed[0] === '.' && globParts[0] === '.') {\n parsed.shift()\n globParts.shift()\n }\n /* c8 ignore stop */\n const p = new Pattern(parsed, globParts, 0, this.platform)\n const m = new Minimatch(p.globString(), this.mmopts)\n const children = globParts[globParts.length - 1] === '**'\n const absolute = p.isAbsolute()\n if (absolute) this.absolute.push(m)\n else this.relative.push(m)\n if (children) {\n if (absolute) this.absoluteChildren.push(m)\n else this.relativeChildren.push(m)\n }\n }\n }\n\n ignored(p: Path): boolean {\n const fullpath = p.fullpath()\n const fullpaths = `${fullpath}/`\n const relative = p.relative() || '.'\n const relatives = `${relative}/`\n for (const m of this.relative) {\n if (m.match(relative) || m.match(relatives)) return true\n }\n for (const m of this.absolute) {\n if (m.match(fullpath) || m.match(fullpaths)) return true\n }\n return false\n }\n\n childrenIgnored(p: Path): boolean {\n const fullpath = p.fullpath() + '/'\n const relative = (p.relative() || '.') + '/'\n for (const m of this.relativeChildren) {\n if (m.match(relative)) return true\n }\n for (const m of this.absoluteChildren) {\n if (m.match(fullpath)) return true\n }\n return false\n }\n}\n", "// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n store: Map<string, Set<string>>\n constructor(store: Map<string, Set<string>> = new Map()) {\n this.store = store\n }\n copy() {\n return new HasWalkedCache(new Map(this.store))\n }\n hasWalked(target: Path, pattern: Pattern) {\n return this.store.get(target.fullpath())?.has(pattern.globString())\n }\n storeWalked(target: Path, pattern: Pattern) {\n const fullpath = target.fullpath()\n const cached = this.store.get(fullpath)\n if (cached) cached.add(pattern.globString())\n else this.store.set(fullpath, new Set([pattern.globString()]))\n }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n store: Map<Path, number> = new Map()\n add(target: Path, absolute: boolean, ifDir: boolean) {\n const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n const current = this.store.get(target)\n this.store.set(target, current === undefined ? n : n & current)\n }\n // match, absolute, ifdir\n entries(): [Path, boolean, boolean][] {\n return [...this.store.entries()].map(([path, n]) => [\n path,\n !!(n & 2),\n !!(n & 1),\n ])\n }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n store: Map<Path, Pattern[]> = new Map()\n add(target: Path, pattern: Pattern) {\n if (!target.canReaddir()) {\n return\n }\n const subs = this.store.get(target)\n if (subs) {\n if (!subs.find(p => p.globString() === pattern.globString())) {\n subs.push(pattern)\n }\n } else this.store.set(target, [pattern])\n }\n get(target: Path): Pattern[] {\n const subs = this.store.get(target)\n /* c8 ignore start */\n if (!subs) {\n throw new Error('attempting to walk unknown path')\n }\n /* c8 ignore stop */\n return subs\n }\n entries(): [Path, Pattern[]][] {\n return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n }\n keys(): Path[] {\n return [...this.store.keys()].filter(t => t.canReaddir())\n }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n hasWalkedCache: HasWalkedCache\n matches = new MatchRecord()\n subwalks = new SubWalks()\n patterns?: Pattern[]\n follow: boolean\n dot: boolean\n opts: GlobWalkerOpts\n\n constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n this.opts = opts\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.hasWalkedCache =\n hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n }\n\n processPatterns(target: Path, patterns: Pattern[]) {\n this.patterns = patterns\n const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n // map of paths to the magic-starting subwalks they need to walk\n // first item in patterns is the filter\n\n for (let [t, pattern] of processingSet) {\n this.hasWalkedCache.storeWalked(t, pattern)\n\n const root = pattern.root()\n const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n // start absolute patterns at root\n if (root) {\n t = t.resolve(\n root === '/' && this.opts.root !== undefined ?\n this.opts.root\n : root,\n )\n const rest = pattern.rest()\n if (!rest) {\n this.matches.add(t, true, false)\n continue\n } else {\n pattern = rest\n }\n }\n\n if (t.isENOENT()) continue\n\n let p: MMPattern\n let rest: Pattern | null\n let changed = false\n while (\n typeof (p = pattern.pattern()) === 'string' &&\n (rest = pattern.rest())\n ) {\n const c = t.resolve(p)\n t = c\n pattern = rest\n changed = true\n }\n p = pattern.pattern()\n rest = pattern.rest()\n if (changed) {\n if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n this.hasWalkedCache.storeWalked(t, pattern)\n }\n\n // now we have either a final string for a known entry,\n // more strings for an unknown entry,\n // or a pattern starting with magic, mounted on t.\n if (typeof p === 'string') {\n // must not be final entry, otherwise we would have\n // concatenated it earlier.\n const ifDir = p === '..' || p === '' || p === '.'\n this.matches.add(t.resolve(p), absolute, ifDir)\n continue\n } else if (p === GLOBSTAR) {\n // if no rest, match and subwalk pattern\n // if rest, process rest and subwalk pattern\n // if it's a symlink, but we didn't get here by way of a\n // globstar match (meaning it's the first time THIS globstar\n // has traversed a symlink), then we follow it. Otherwise, stop.\n if (\n !t.isSymbolicLink() ||\n this.follow ||\n pattern.checkFollowGlobstar()\n ) {\n this.subwalks.add(t, pattern)\n }\n const rp = rest?.pattern()\n const rrest = rest?.rest()\n if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n // only HAS to be a dir if it ends in **/ or **/.\n // but ending in ** will match files as well.\n this.matches.add(t, absolute, rp === '' || rp === '.')\n } else {\n if (rp === '..') {\n // this would mean you're matching **/.. at the fs root,\n // and no thanks, I'm not gonna test that specific case.\n /* c8 ignore start */\n const tp = t.parent || t\n /* c8 ignore stop */\n if (!rrest) this.matches.add(tp, absolute, true)\n else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n this.subwalks.add(tp, rrest)\n }\n }\n }\n } else if (p instanceof RegExp) {\n this.subwalks.add(t, pattern)\n }\n }\n\n return this\n }\n\n subwalkTargets(): Path[] {\n return this.subwalks.keys()\n }\n\n child() {\n return new Processor(this.opts, this.hasWalkedCache)\n }\n\n // return a new Processor containing the subwalks for each\n // child entry, and a set of matches, and\n // a hasWalkedCache that's a copy of this one\n // then we're going to call\n filterEntries(parent: Path, entries: Path[]): Processor {\n const patterns = this.subwalks.get(parent)\n // put matches and entry walks into the results processor\n const results = this.child()\n for (const e of entries) {\n for (const pattern of patterns) {\n const absolute = pattern.isAbsolute()\n const p = pattern.pattern()\n const rest = pattern.rest()\n if (p === GLOBSTAR) {\n results.testGlobstar(e, pattern, rest, absolute)\n } else if (p instanceof RegExp) {\n results.testRegExp(e, p, rest, absolute)\n } else {\n results.testString(e, p, rest, absolute)\n }\n }\n }\n return results\n }\n\n testGlobstar(\n e: Path,\n pattern: Pattern,\n rest: Pattern | null,\n absolute: boolean,\n ) {\n if (this.dot || !e.name.startsWith('.')) {\n if (!pattern.hasMore()) {\n this.matches.add(e, absolute, false)\n }\n if (e.canReaddir()) {\n // if we're in follow mode or it's not a symlink, just keep\n // testing the same pattern. If there's more after the globstar,\n // then this symlink consumes the globstar. If not, then we can\n // follow at most ONE symlink along the way, so we mark it, which\n // also checks to ensure that it wasn't already marked.\n if (this.follow || !e.isSymbolicLink()) {\n this.subwalks.add(e, pattern)\n } else if (e.isSymbolicLink()) {\n if (rest && pattern.checkFollowGlobstar()) {\n this.subwalks.add(e, rest)\n } else if (pattern.markFollowGlobstar()) {\n this.subwalks.add(e, pattern)\n }\n }\n }\n }\n // if the NEXT thing matches this entry, then also add\n // the rest.\n if (rest) {\n const rp = rest.pattern()\n if (\n typeof rp === 'string' &&\n // dots and empty were handled already\n rp !== '..' &&\n rp !== '' &&\n rp !== '.'\n ) {\n this.testString(e, rp, rest.rest(), absolute)\n } else if (rp === '..') {\n /* c8 ignore start */\n const ep = e.parent || e\n /* c8 ignore stop */\n this.subwalks.add(ep, rest)\n } else if (rp instanceof RegExp) {\n this.testRegExp(e, rp, rest.rest(), absolute)\n }\n }\n }\n\n testRegExp(\n e: Path,\n p: MMRegExp,\n rest: Pattern | null,\n absolute: boolean,\n ) {\n if (!p.test(e.name)) return\n if (!rest) {\n this.matches.add(e, absolute, false)\n } else {\n this.subwalks.add(e, rest)\n }\n }\n\n testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n // should never happen?\n if (!e.isNamed(p)) return\n if (!rest) {\n this.matches.add(e, absolute, false)\n } else {\n this.subwalks.add(e, rest)\n }\n }\n}\n", "/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed? that'd speed\n// things up a lot. Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n absolute?: boolean\n allowWindowsEscape?: boolean\n cwd?: string | URL\n dot?: boolean\n dotRelative?: boolean\n follow?: boolean\n ignore?: string | string[] | IgnoreLike\n mark?: boolean\n matchBase?: boolean\n // Note: maxDepth here means \"maximum actual Path.depth()\",\n // not \"maximum depth beyond cwd\"\n maxDepth?: number\n nobrace?: boolean\n nocase?: boolean\n nodir?: boolean\n noext?: boolean\n noglobstar?: boolean\n platform?: NodeJS.Platform\n posix?: boolean\n realpath?: boolean\n root?: string\n stat?: boolean\n signal?: AbortSignal\n windowsPathsNoEscape?: boolean\n withFileTypes?: boolean\n includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n withFileTypes?: undefined\n}\n\nexport type Result<O extends GlobWalkerOpts> =\n O extends GWOFileTypesTrue ? Path\n : O extends GWOFileTypesFalse ? string\n : O extends GWOFileTypesUnset ? string\n : Path | string\n\nexport type Matches<O extends GlobWalkerOpts> =\n O extends GWOFileTypesTrue ? Set<Path>\n : O extends GWOFileTypesFalse ? Set<string>\n : O extends GWOFileTypesUnset ? Set<string>\n : Set<Path | string>\n\nexport type MatchStream<O extends GlobWalkerOpts> = Minipass<\n Result<O>,\n Result<O>\n>\n\nconst makeIgnore = (\n ignore: string | string[] | IgnoreLike,\n opts: GlobWalkerOpts,\n): IgnoreLike =>\n typeof ignore === 'string' ? new Ignore([ignore], opts)\n : Array.isArray(ignore) ? new Ignore(ignore, opts)\n : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil<O extends GlobWalkerOpts = GlobWalkerOpts> {\n path: Path\n patterns: Pattern[]\n opts: O\n seen: Set<Path> = new Set<Path>()\n paused: boolean = false\n aborted: boolean = false\n #onResume: (() => any)[] = []\n #ignore?: IgnoreLike\n #sep: '\\\\' | '/'\n signal?: AbortSignal\n maxDepth: number\n includeChildMatches: boolean\n\n constructor(patterns: Pattern[], path: Path, opts: O)\n constructor(patterns: Pattern[], path: Path, opts: O) {\n this.patterns = patterns\n this.path = path\n this.opts = opts\n this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n this.includeChildMatches = opts.includeChildMatches !== false\n if (opts.ignore || !this.includeChildMatches) {\n this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n if (\n !this.includeChildMatches &&\n typeof this.#ignore.add !== 'function'\n ) {\n const m = 'cannot ignore child matches, ignore lacks add() method.'\n throw new Error(m)\n }\n }\n // ignore, always set with maxDepth, but it's optional on the\n // GlobOptions type\n /* c8 ignore start */\n this.maxDepth = opts.maxDepth || Infinity\n /* c8 ignore stop */\n if (opts.signal) {\n this.signal = opts.signal\n this.signal.addEventListener('abort', () => {\n this.#onResume.length = 0\n })\n }\n }\n\n #ignored(path: Path): boolean {\n return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n }\n #childrenIgnored(path: Path): boolean {\n return !!this.#ignore?.childrenIgnored?.(path)\n }\n\n // backpressure mechanism\n pause() {\n this.paused = true\n }\n resume() {\n /* c8 ignore start */\n if (this.signal?.aborted) return\n /* c8 ignore stop */\n this.paused = false\n let fn: (() => any) | undefined = undefined\n while (!this.paused && (fn = this.#onResume.shift())) {\n fn()\n }\n }\n onResume(fn: () => any) {\n if (this.signal?.aborted) return\n /* c8 ignore start */\n if (!this.paused) {\n fn()\n } else {\n /* c8 ignore stop */\n this.#onResume.push(fn)\n }\n }\n\n // do the requisite realpath/stat checking, and return the path\n // to add or undefined to filter it out.\n async matchCheck(e: Path, ifDir: boolean): Promise<Path | undefined> {\n if (ifDir && this.opts.nodir) return undefined\n let rpc: Path | undefined\n if (this.opts.realpath) {\n rpc = e.realpathCached() || (await e.realpath())\n if (!rpc) return undefined\n e = rpc\n }\n const needStat = e.isUnknown() || this.opts.stat\n const s = needStat ? await e.lstat() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = await s.realpath()\n /* c8 ignore start */\n if (target && (target.isUnknown() || this.opts.stat)) {\n await target.lstat()\n }\n /* c8 ignore stop */\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n return (\n e &&\n (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n (!ifDir || e.canReaddir()) &&\n (!this.opts.nodir || !e.isDirectory()) &&\n (!this.opts.nodir ||\n !this.opts.follow ||\n !e.isSymbolicLink() ||\n !e.realpathCached()?.isDirectory()) &&\n !this.#ignored(e)\n ) ?\n e\n : undefined\n }\n\n matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n if (ifDir && this.opts.nodir) return undefined\n let rpc: Path | undefined\n if (this.opts.realpath) {\n rpc = e.realpathCached() || e.realpathSync()\n if (!rpc) return undefined\n e = rpc\n }\n const needStat = e.isUnknown() || this.opts.stat\n const s = needStat ? e.lstatSync() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = s.realpathSync()\n if (target && (target?.isUnknown() || this.opts.stat)) {\n target.lstatSync()\n }\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n abstract matchEmit(p: Result<O>): void\n abstract matchEmit(p: string | Path): void\n\n matchFinish(e: Path, absolute: boolean) {\n if (this.#ignored(e)) return\n // we know we have an ignore if this is false, but TS doesn't\n if (!this.includeChildMatches && this.#ignore?.add) {\n const ign = `${e.relativePosix()}/**`\n this.#ignore.add(ign)\n }\n const abs =\n this.opts.absolute === undefined ? absolute : this.opts.absolute\n this.seen.add(e)\n const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n // ok, we have what we need!\n if (this.opts.withFileTypes) {\n this.matchEmit(e)\n } else if (abs) {\n const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n this.matchEmit(abs + mark)\n } else {\n const rel = this.opts.posix ? e.relativePosix() : e.relative()\n const pre =\n this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n '.' + this.#sep\n : ''\n this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n }\n }\n\n async match(e: Path, absolute: boolean, ifDir: boolean): Promise<void> {\n const p = await this.matchCheck(e, ifDir)\n if (p) this.matchFinish(p, absolute)\n }\n\n matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n const p = this.matchCheckSync(e, ifDir)\n if (p) this.matchFinish(p, absolute)\n }\n\n walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n /* c8 ignore start */\n if (this.signal?.aborted) cb()\n /* c8 ignore stop */\n this.walkCB2(target, patterns, new Processor(this.opts), cb)\n }\n\n walkCB2(\n target: Path,\n patterns: Pattern[],\n processor: Processor,\n cb: () => any,\n ) {\n if (this.#childrenIgnored(target)) return cb()\n if (this.signal?.aborted) cb()\n if (this.paused) {\n this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n return\n }\n processor.processPatterns(target, patterns)\n\n // done processing. all of the above is sync, can be abstracted out.\n // subwalks is a map of paths to the entry filters they need\n // matches is a map of paths to [absolute, ifDir] tuples.\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n tasks++\n this.match(m, absolute, ifDir).then(() => next())\n }\n\n for (const t of processor.subwalkTargets()) {\n if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n continue\n }\n tasks++\n const childrenCached = t.readdirCached()\n if (t.calledReaddir())\n this.walkCB3(t, childrenCached, processor, next)\n else {\n t.readdirCB(\n (_, entries) => this.walkCB3(t, entries, processor, next),\n true,\n )\n }\n }\n\n next()\n }\n\n walkCB3(\n target: Path,\n entries: Path[],\n processor: Processor,\n cb: () => any,\n ) {\n processor = processor.filterEntries(target, entries)\n\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n tasks++\n this.match(m, absolute, ifDir).then(() => next())\n }\n for (const [target, patterns] of processor.subwalks.entries()) {\n tasks++\n this.walkCB2(target, patterns, processor.child(), next)\n }\n\n next()\n }\n\n walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n /* c8 ignore start */\n if (this.signal?.aborted) cb()\n /* c8 ignore stop */\n this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n }\n\n walkCB2Sync(\n target: Path,\n patterns: Pattern[],\n processor: Processor,\n cb: () => any,\n ) {\n if (this.#childrenIgnored(target)) return cb()\n if (this.signal?.aborted) cb()\n if (this.paused) {\n this.onResume(() =>\n this.walkCB2Sync(target, patterns, processor, cb),\n )\n return\n }\n processor.processPatterns(target, patterns)\n\n // done processing. all of the above is sync, can be abstracted out.\n // subwalks is a map of paths to the entry filters they need\n // matches is a map of paths to [absolute, ifDir] tuples.\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n this.matchSync(m, absolute, ifDir)\n }\n\n for (const t of processor.subwalkTargets()) {\n if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n continue\n }\n tasks++\n const children = t.readdirSync()\n this.walkCB3Sync(t, children, processor, next)\n }\n\n next()\n }\n\n walkCB3Sync(\n target: Path,\n entries: Path[],\n processor: Processor,\n cb: () => any,\n ) {\n processor = processor.filterEntries(target, entries)\n\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n this.matchSync(m, absolute, ifDir)\n }\n for (const [target, patterns] of processor.subwalks.entries()) {\n tasks++\n this.walkCB2Sync(target, patterns, processor.child(), next)\n }\n\n next()\n }\n}\n\nexport class GlobWalker<\n O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil<O> {\n matches = new Set<Result<O>>()\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n }\n\n matchEmit(e: Result<O>): void {\n this.matches.add(e)\n }\n\n async walk(): Promise<Set<Result<O>>> {\n if (this.signal?.aborted) throw this.signal.reason\n if (this.path.isUnknown()) {\n await this.path.lstat()\n }\n await new Promise((res, rej) => {\n this.walkCB(this.path, this.patterns, () => {\n if (this.signal?.aborted) {\n rej(this.signal.reason)\n } else {\n res(this.matches)\n }\n })\n })\n return this.matches\n }\n\n walkSync(): Set<Result<O>> {\n if (this.signal?.aborted) throw this.signal.reason\n if (this.path.isUnknown()) {\n this.path.lstatSync()\n }\n // nothing for the callback to do, because this never pauses\n this.walkCBSync(this.path, this.patterns, () => {\n if (this.signal?.aborted) throw this.signal.reason\n })\n return this.matches\n }\n}\n\nexport class GlobStream<\n O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil<O> {\n results: Minipass<Result<O>, Result<O>>\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n this.results = new Minipass<Result<O>, Result<O>>({\n signal: this.signal,\n objectMode: true,\n })\n this.results.on('drain', () => this.resume())\n this.results.on('resume', () => this.resume())\n }\n\n matchEmit(e: Result<O>): void {\n this.results.write(e)\n if (!this.results.flowing) this.pause()\n }\n\n stream(): MatchStream<O> {\n const target = this.path\n if (target.isUnknown()) {\n target.lstat().then(() => {\n this.walkCB(target, this.patterns, () => this.results.end())\n })\n } else {\n this.walkCB(target, this.patterns, () => this.results.end())\n }\n return this.results\n }\n\n streamSync(): MatchStream<O> {\n if (this.path.isUnknown()) {\n this.path.lstatSync()\n }\n this.walkCBSync(this.path, this.patterns, () => this.results.end())\n return this.results\n }\n}\n", "import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n pattern: string | string[],\n options: GlobOptions = {},\n): boolean => {\n if (!Array.isArray(pattern)) {\n pattern = [pattern]\n }\n for (const p of pattern) {\n if (new Minimatch(p, options).hasMagic()) return true\n }\n return false\n}\n", "import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n FSOption,\n Path,\n WalkOptions,\n WalkOptionsWithFileTypesTrue,\n WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass<Path, Path>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass<string, string>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesUnset,\n): Minipass<string, string>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass<Path, Path> | Minipass<string, string>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass<string, string>\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass<Path, Path>\nexport function globStream(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass<string, string>\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass<Path, Path> | Minipass<string, string>\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise<string[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Promise<Path[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Promise<string[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions,\n): Promise<Path[] | string[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator<string, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Generator<Path, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Generator<string, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions,\n): Generator<Path, void, void> | Generator<string, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator<string, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator<Path, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator<string, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions,\n): AsyncGenerator<Path, void, void> | AsyncGenerator<string, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n stream: globStreamSync,\n iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n glob: glob_,\n globSync,\n sync,\n globStream,\n stream,\n globStreamSync,\n streamSync,\n globIterate,\n iterate,\n globIterateSync,\n iterateSync,\n Glob,\n hasMagic,\n escape,\n unescape,\n})\nglob.glob = glob\n", "import { setMaxListeners } from 'node:events'\n\n/**\n * Options that define the graph and how to traverse it\n */\nexport interface RunnerOptions<Node, Result = void> {\n /** Array of one or more entry nodes. */\n graph: [node: Node, ...rest: Node[]]\n\n /** get the dependencies of a given node */\n getDeps: (node: Node) => Node[] | Promise<Node[]>\n\n /** action to take on each node */\n visit: (\n node: Node,\n signal: AbortSignal,\n path: Node[],\n depResults: DepResults<Node, Result>,\n ) => Result | Promise<Result>\n\n /**\n * Called when a cycle is encountered.\n * Throw in this method to enforce a DAG graph.\n * If left undefined, then cycles are silently ignored and skipped.\n *\n * `node` parameter is the dependency that is being skipped.\n *\n * `cycle` is the route from the dependent back to itself via\n * the parent.\n *\n * `path` is the path to the dependent who wanted this dep to be\n * loaded.\n */\n onCycle?: (\n node: Node,\n cycle: Node[],\n path: Node[],\n ) => void | Promise<void>\n\n /**\n * Set to `false` to continue operations even if errors occur.\n * If set to false, then an AggregateError will be raised on failure\n * containing all failures (even if only one). If true, then a normal\n * Error will be raised on failure.\n *\n * @default true\n */\n failFast?: boolean\n\n /** a signal that will trigger the graph traversal to end prematurely */\n signal?: AbortSignal\n}\n\nexport type DepResults<Node, Result> = Map<Node, Result | undefined>\n\n/**\n * Options that can define a synchronous graph traversal.\n *\n * Note that if the visit() method is async, then the *promises themselves*\n * will be used as the `Result` type, which is likely not what you want!\n */\nexport interface RunnerOptionsSync<Node, Result = void>\n extends RunnerOptions<Node, Result> {\n /** Get a set of dependency nodes synchronously */\n getDeps: (node: Node) => Node[]\n\n /** Visit a node synchronously */\n visit: (\n node: Node,\n signal: AbortSignal,\n path: Node[],\n depResults: DepResults<Node, Result>,\n ) => Result\n\n /** Handle cycles synchronously */\n onCycle?: (node: Node, cycle: Node[], path: Node[]) => void\n}\n\n/** A map of nodes to their PromiseSettledResult value */\nexport type SettledMap<Node, Result = void> = Map<\n Node,\n PromiseSettledResult<Result>\n>\n\n/** Any function or class. Used for Error.captureStackTrace */\nexport type Callable =\n | Function\n | ((...a: unknown[]) => unknown)\n | {\n new (...a: unknown[]): unknown\n }\n\n/** Base class of Runner and RunnerSync */\nexport abstract class RunnerBase<\n /** The type of thing to be found in this graph */\n Node,\n /** Type returned by the visit() method */\n Result = void,\n Sync extends boolean = false,\n O extends Sync extends true ? RunnerOptionsSync<Node, Result>\n : RunnerOptions<Node, Result> = Sync extends true ?\n RunnerOptionsSync<Node, Result>\n : RunnerOptions<Node, Result>,\n> {\n /** The map of traversal results */\n readonly results: Map<Node, Result> = new Map()\n\n /** The map of PromiseSettledResult objects */\n readonly settled: SettledMap<Node, Result> = new Map()\n\n /** Set of dependents (direct & transitive) on each node */\n readonly dependents: Map<Node, Set<Node>> = new Map()\n\n /** Set of direct dependents on each node */\n readonly directDependents: Map<Node, Set<Node>> = new Map()\n\n /** Options provided to constructor */\n readonly options: O\n\n /**\n * AbortController used internally to abort the process.\n *\n * This is internal only, and triggering it at the wrong time may cause\n * undefined and unsupported behavior. Do not use!\n *\n * Instead, if you want to be able to abort the walk at any time, provide\n * your own AbortSignal in the opions.\n *\n * @internal\n */\n readonly abortController: AbortController\n\n /** True if we are in failFast mode */\n readonly failFast: boolean\n\n /** Rejections and Errors encountered in the traversal */\n readonly errors: unknown[] = []\n\n /**\n * Function defining the callsite where the traversal was initiated,\n * used for Error.captureStackTrace.\n */\n readonly from: Callable\n\n constructor(options: O, from?: Callable) {\n const ac = new AbortController()\n this.from = from ?? this.constructor\n this.abortController = ac\n setMaxListeners(Infinity, ac.signal)\n this.options = options\n if (!options.graph.length) {\n const er = new Error('no nodes provided to graph traversal', {\n cause: {\n found: options.graph,\n wanted: '[first: Node, ...rest: Node[]]',\n },\n })\n Error.captureStackTrace(er, from)\n throw er\n }\n this.failFast = options.failFast !== false\n const { signal } = options\n if (signal !== undefined) {\n signal.addEventListener('abort', reason => ac.abort(reason), {\n once: true,\n signal: ac.signal,\n })\n }\n }\n\n /** Initiate the graph traversal, resolving/returning when complete */\n abstract run(): Sync extends true ? void : Promise<void>\n\n /** Get the dependencies of a given node */\n abstract getDeps(\n n: Node,\n ): Sync extends true ? Node[] : Promise<Node[]>\n\n /** Visit a node. Calls `options.visit()` */\n abstract visit(\n n: Node,\n path: Node[],\n depResults: DepResults<Node, Result>,\n ): Sync extends true ? Result : Promise<Result>\n\n /**\n * Calls the `options.onCycle()` method when a cycle is detected.\n */\n abstract onCycle(\n n: Node,\n cycle: Node[],\n path: Node[],\n ): Sync extends true ? void : void | Promise<void>\n\n /**\n * For a Node `n` that depends directly or transitively on Node `d`, find the\n * shortest known dependency path from `n` to `d`. This is done by walking\n * backwards breadth-first up the dependency relations from `d` until `n` is\n * found.\n *\n * If no known path can be found, then `undefined` is returned. Otherwise,\n * a path array is returned that starts with `n` and ends with `d`.\n *\n * Note that self-referential links are never considered, since they're\n * by definition cyclical.\n */\n route(n: Node, d: Node): undefined | [n: Node, ...path: Node[]] {\n const dependents = this.dependents.get(d)\n if (!dependents?.has(n)) return undefined\n const directDependents = this.directDependents.get(d)\n /* c8 ignore next */\n if (!directDependents) return undefined\n if (directDependents.has(n)) {\n return [n, d]\n }\n const queue: [n: Node, ...r: Node[]][] = [\n ...directDependents,\n ].map(dd => [dd, d])\n let step: undefined | [n: Node, ...r: Node[]] = undefined\n while (undefined !== (step = queue.shift())) {\n /* c8 ignore next */\n if (!dependents.has(step[0])) continue\n if (step[0] === n) {\n return step\n }\n const ddd = this.directDependents.get(step[0])\n if (ddd) {\n for (const d of ddd) {\n queue.push([d, ...step])\n }\n }\n }\n }\n\n /**\n * If the dependency from `n -> d` at the specified path would\n * cause a cycle, then call the onCycle method and return true.\n * Oherwise, assign the appropriate entries in the dependency\n * tracking sets, and return false.\n *\n * @internal\n */\n cycleCheck(n: Node, path: Node[], d: Node) {\n /* c8 ignore next */\n const dependents = this.dependents.get(n) ?? new Set()\n this.dependents.set(n, dependents)\n const isCycle = dependents.has(d)\n if (isCycle) {\n const cycle = this.route(d, n)\n /* c8 ignore start - impossible */\n if (!cycle) {\n throw new Error('cycle detected, but cycle route not found')\n }\n /* c8 ignore stop */\n cycle.unshift(n)\n this.onCycle(d, cycle, path)\n return true\n }\n\n const depDD = this.directDependents.get(d) ?? new Set()\n this.directDependents.set(d, depDD)\n depDD.add(n)\n\n const depDependents = this.dependents.get(d) ?? new Set()\n this.dependents.set(d, depDependents)\n for (const n of dependents) {\n depDependents.add(n)\n }\n depDependents.add(n)\n return false\n }\n\n /**\n * Method that handles errors raised by visits.\n *\n * @internal\n */\n handleError(er: unknown, n: Node, path: Node[]) {\n this.errors.push(er)\n this.settled.set(n, {\n status: 'rejected',\n reason: er,\n })\n if (this.failFast) {\n this.abortController.abort(er)\n const e = new Error('failed graph traversal', {\n cause: {\n node: n,\n path,\n cause: er as Error,\n },\n })\n Error.captureStackTrace(e, this.from)\n throw e\n }\n }\n\n /**\n * Method that handles successful visit results\n *\n * @internal\n */\n handleValue(value: Result, n: Node) {\n this.results.set(n, value)\n this.settled.set(n, {\n status: 'fulfilled',\n value,\n })\n }\n}\n\n/** Asynchronous graph runner */\nexport class Runner<Node, Result> extends RunnerBase<\n Node,\n Result,\n false,\n RunnerOptions<Node, Result>\n> {\n /** Map of nodes currently awaiting completion */\n readonly running = new Map<Node, Promise<void>>()\n\n async getDeps(n: Node) {\n /* c8 ignore next */\n if (this.abortController.signal.aborted) return []\n const deps = await this.options.getDeps(n);\n for (const d of deps) {\n const dependents = this.dependents.get(d) ?? new Set()\n this.dependents.set(d, dependents)\n dependents.add(n)\n const depDD = this.directDependents.get(d) ?? new Set()\n this.directDependents.set(d, depDD)\n depDD.add(n)\n }\n return deps\n }\n\n async visit(\n n: Node,\n path: Node[],\n depResults: DepResults<Node, Result>,\n ) {\n const { signal } = this.abortController\n return this.options.visit(n, signal, path, depResults)\n }\n\n async onCycle(n: Node, cycle: Node[], path: Node[]) {\n /* c8 ignore next */\n if (this.abortController.signal.aborted) return\n await this.options.onCycle?.(n, cycle, path)\n }\n\n async #walk(n: Node, path: Node[]) {\n const r = this.running.get(n)\n /* c8 ignore next */\n if (r) return r\n /* c8 ignore start */\n if (this.settled.get(n)) return\n /* c8 ignore stop */\n const p = this.#step(n, path).then(\n () => {\n this.running.delete(n)\n },\n /* c8 ignore start - handled deeper in the chain */\n er => {\n this.running.delete(n)\n throw er\n },\n /* c8 ignore stop */\n )\n this.running.set(n, p)\n return p\n }\n\n async #step(n: Node, path: Node[]) {\n const dependents = this.dependents.get(n) ?? new Set()\n this.dependents.set(n, dependents)\n\n const deps = await this.getDeps(n)\n const awaiting: Promise<void>[] = []\n const depPath = [...path, n]\n\n for (const d of deps) {\n /* c8 ignore next */\n if (this.abortController.signal.aborted) return\n // self-link, skip\n if (d === n) continue\n if (this.cycleCheck(n, depPath, d)) continue\n /* c8 ignore next */\n if (this.settled.get(d)) continue\n awaiting.push(this.running.get(d) ?? this.#walk(d, depPath))\n }\n\n /* c8 ignore next */\n if (this.abortController.signal.aborted) return\n await Promise.all(awaiting)\n if (this.abortController.signal.aborted) return\n const depRes = new Map<Node, Result | undefined>(\n deps.map(d => [d, this.results.get(d)]),\n )\n try {\n this.handleValue(await this.visit(n, path, depRes), n)\n } catch (er) {\n this.handleError(er, n, path)\n }\n }\n\n async run(): Promise<void> {\n const promises: Promise<void>[] = []\n for (const n of this.options.graph) {\n promises.push(this.#walk(n, []))\n }\n await Promise.all(promises)\n }\n}\n\n/** Synchronous graph runner */\nexport class RunnerSync<Node, Result> extends RunnerBase<\n Node,\n Result,\n true,\n RunnerOptionsSync<Node, Result>\n> {\n getDeps(n: Node) {\n if (this.abortController.signal.aborted) return []\n return this.options.getDeps(n)\n }\n\n visit(n: Node, path: Node[], depResults: DepResults<Node, Result>) {\n const { signal } = this.abortController\n return this.options.visit(n, signal, path, depResults)\n }\n\n onCycle(n: Node, cycle: Node[], path: Node[]) {\n /* c8 ignore next */\n if (this.abortController.signal.aborted) return\n this.options.onCycle?.(n, cycle, path)\n }\n\n #walk(n: Node, path: Node[]) {\n /* c8 ignore start */\n if (this.settled.get(n)) return\n /* c8 ignore stop */\n this.#step(n, path)\n }\n\n #step(n: Node, path: Node[]) {\n const dependents = this.dependents.get(n) ?? new Set()\n this.dependents.set(n, dependents)\n\n const deps = this.getDeps(n)\n const depPath = [...path, n]\n for (const d of deps) {\n if (this.abortController.signal.aborted) return\n /* c8 ignore next */\n if (d === n) continue\n if (this.cycleCheck(n, depPath, d)) continue\n if (!this.settled.get(d)) this.#walk(d, depPath)\n }\n\n if (this.abortController.signal.aborted) return\n const depRes = new Map<Node, Result | undefined>(\n deps.map(d => [d, this.results.get(d)]),\n )\n try {\n this.handleValue(this.visit(n, path, depRes), n)\n } catch (er) {\n this.handleError(er, n, path)\n }\n }\n\n run(): Map<Node, Result> {\n for (const n of this.options.graph) {\n this.#walk(n, [])\n }\n return this.results\n }\n}\n\n/**\n * Asynchronous graph traversal method\n *\n * If `failFast:false` is set in the options, then an AggregateError\n * will be raised if there were any failures. Otherwise, a normal Error\n * is raised on failure.\n */\nexport const graphRun = async <Node, Result>(\n options: RunnerOptions<Node, Result>,\n): Promise<Map<Node, Result>> => {\n const runner = new Runner(options, graphRun)\n await runner.run()\n if (runner.errors.length) {\n const e = new AggregateError(\n runner.errors,\n 'failed graph traversal',\n )\n Error.captureStackTrace(e, graphRun)\n throw e\n }\n return runner.results\n}\n\n/**\n * Synchronous graph traversal method\n *\n * If `failFast:false` is set in the options, then an AggregateError\n * will be thrown if there were any failures. Otherwise, a normal Error\n * is thrown on failure.\n */\nexport const graphRunSync = <Node, Result>(\n options: RunnerOptionsSync<Node, Result>,\n): Map<Node, Result> => {\n const runner = new RunnerSync(options, graphRunSync)\n runner.run()\n if (runner.errors.length) {\n const e = new AggregateError(\n runner.errors,\n 'failed graph traversal',\n )\n Error.captureStackTrace(e, graphRunSync)\n throw e\n }\n return runner.results\n}\n\n/**\n * Asynchronous graph traversal, capturing all error/result\n * statuses.\n */\nexport const allSettled = async <Node, Result>(\n options: RunnerOptions<Node, Result>,\n): Promise<SettledMap<Node, Result>> => {\n const runner = new Runner(\n { ...options, failFast: false },\n allSettled,\n )\n await runner.run()\n return runner.settled\n}\n\n/**\n * Synchronous graph traversal, capturing all error/result\n * statuses.\n */\nexport const allSettledSync = <Node, Result>(\n options: RunnerOptionsSync<Node, Result>,\n): SettledMap<Node, Result> => {\n const runner = new RunnerSync(\n { ...options, failFast: false },\n allSettledSync,\n )\n runner.run()\n return runner.settled\n}\n\n/**\n * Asynchronous graph traversal, returning the first successful visit.\n * If all visits fail, then an AggregateError is raised with all errors\n * encountered.\n */\nexport const any = async <Node, Result>(\n options: RunnerOptions<Node, Result>,\n): Promise<Result> => {\n const ac = new AbortController()\n let result!: Result\n let found: boolean = false\n const runner = new Runner<Node, Result>(\n {\n ...options,\n failFast: false,\n signal: ac.signal,\n visit: async (node, signal, path, depResults) => {\n try {\n result = await options.visit(node, signal, path, depResults)\n found = true\n ac.abort('found')\n } finally {\n return result\n }\n },\n },\n any,\n )\n await runner.run()\n if (!found) {\n const e = new AggregateError(\n runner.errors,\n 'failed graph traversal',\n )\n Error.captureStackTrace(e, any)\n throw e\n }\n return result\n}\n\n/**\n * Synchronous graph traversal, returning the first successful visit.\n * If all visits fail, then an AggregateError is thrown with all errors\n * encountered.\n */\nexport const anySync = <Node, Result>(\n options: RunnerOptionsSync<Node, Result>,\n): Result => {\n const ac = new AbortController()\n let result!: Result\n let found: boolean = false\n const runner = new RunnerSync<Node, Result>(\n {\n ...options,\n failFast: false,\n signal: ac.signal,\n visit: (node, signal, path, depResults) => {\n try {\n result = options.visit(node, signal, path, depResults)\n found = true\n ac.abort('found')\n } finally {\n return result\n }\n },\n },\n anySync,\n )\n runner.run()\n if (!found) {\n const e = new AggregateError(\n runner.errors,\n 'failed graph traversal',\n )\n Error.captureStackTrace(e, anySync)\n throw e\n }\n return result\n}\n\n/**\n * Asynchronous graph traversal, resolving or rejecting when the first visit\n * resolves or rejects.\n */\nexport const race = async <Node, Result>(\n options: RunnerOptions<Node, Result>,\n): Promise<Result> => {\n const ac = new AbortController()\n let result!: Result\n const runner = new Runner<Node, Result>(\n {\n ...options,\n failFast: true,\n signal: ac.signal,\n visit: async (node, signal, path, depResults) => {\n try {\n result = await options.visit(node, signal, path, depResults)\n ac.abort('found')\n } finally {\n return result\n }\n },\n },\n race,\n )\n await runner.run()\n return result\n}\n\n/**\n * Synchronous graph traversal, returning or throwing when the first visit\n * is completed.\n */\nexport const raceSync = <Node, Result>(\n options: RunnerOptionsSync<Node, Result>,\n): Result => {\n const ac = new AbortController()\n let result!: Result\n const runner = new RunnerSync<Node, Result>(\n {\n ...options,\n failFast: true,\n signal: ac.signal,\n visit: (node, signal, path, depResults) => {\n try {\n result = options.visit(node, signal, path, depResults)\n ac.abort('found')\n } finally {\n return result\n }\n },\n },\n race,\n )\n runner.run()\n return result\n}\n", "// Handling emoji is hard.\n// because many/most emoji are 2-character width, give or take,\n// but have bizarre line-height and spacing in most fonts, replace emojis\n// in the html string with an absolute-position wrapper and 2 spaces for\n// them to float above.\n// *Some* emojis are 1 character wide, so this ends up being a bit wrong\n// sometimes, but better too much space than have things be cut off or\n// overlapping, which looks broken.\n// Due to limitations of the emoji-regex, some complex emojis will render\n// as their constituent parts rather than the conjoined glyph.\n\nimport emojiRegex from 'emoji-regex'\nconst EMOJI_RE = emojiRegex()\nconst replaceWide = (c: string) => replaceNarrow(c) + ' '\nconst replaceNarrow = (c: string) =>\n `<span style=\"position:absolute;line-height:1;margin-top:0.3ex\">${c}</span> `\nexport const fixEmoji = (s: string): string => {\n return s\n .replace(/[\\u2500-\\u25FF]/g, replaceNarrow)\n .replace(EMOJI_RE, replaceWide)\n}\n", "let COLOR = '#eeeeee'\nlet BACKGROUND = '#222222'\n\nexport const defaultColor = (s?: string) => {\n if (s) COLOR = s\n return COLOR\n}\n\nexport const defaultBackground = (s?: string) => {\n if (s) BACKGROUND = s\n return BACKGROUND\n}\n", "export const hexToRgb = (c: string): [number, number, number] => {\n c = c.replace(/^#/, '')\n if (c.length === 3) {\n const r = c.charAt(0)\n const g = c.charAt(1)\n const b = c.charAt(2)\n return hexToRgb(`${r}${r}${g}${g}${b}${b}`)\n }\n if (c.length !== 6) {\n throw new Error('invalid hex string: ' + c)\n }\n const r = parseInt(c.substring(0, 2), 16)\n const g = parseInt(c.substring(2, 4), 16)\n const b = parseInt(c.substring(4, 6), 16)\n if (r !== r || g !== g || b !== b) {\n throw new Error('invalid hex string: ' + c)\n }\n return [r, g, b]\n}\n", "export const rgbToHex = ([r, g, b]: [number, number, number]): string => {\n if (r !== r || g !== g || b !== b) {\n throw new Error('invalid RGB: ' + [r, g, b].join(','))\n }\n return `#${\n Math.max(0, Math.min(r, 255)).toString(16).padStart(2, '0') +\n Math.max(0, Math.min(g, 255)).toString(16).padStart(2, '0') +\n Math.max(0, Math.min(b, 255)).toString(16).padStart(2, '0')\n }`\n}\n", "import { hexToRgb } from './hex-to-rgb.js'\nimport { rgbToHex } from './rgb-to-hex.js'\n\nconst DIMLEVEL = 0.75\nexport const dimColor = (c: string): string =>\n rgbToHex(\n hexToRgb(c).map(c => Math.floor(c * DIMLEVEL)) as [\n number,\n number,\n number,\n ],\n )\n", "export const htmlEscape = (s: string): string =>\n s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n", "export type Names =\n | 'black'\n | 'red'\n | 'green'\n | 'yellow'\n | 'blue'\n | 'magenta'\n | 'cyan'\n | 'white'\n\nexport type NameCodes = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7\n\nexport const nameCodes: { [name in Names]: NameCodes } = {\n black: 0b000,\n red: 0b001,\n green: 0b010,\n yellow: 0b011,\n blue: 0b100,\n magenta: 0b101,\n cyan: 0b110,\n white: 0b111,\n}\n\nexport const codeNames: ReadonlyArray<Names> = [\n 'black',\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'white',\n] as const\n\nexport const namedColors: Omit<string[], number> & {\n 0: string\n 1: string\n 2: string\n 3: string\n 4: string\n 5: string\n 6: string\n 7: string\n} = [\n '#000000',\n '#ff0000',\n '#00a000',\n '#e0e000',\n '#0040e0',\n '#e000e0',\n '#00b0b0',\n '#e0e0e0',\n]\n\nexport const namedBrightColors: Omit<string[], number> & {\n 0: string\n 1: string\n 2: string\n 3: string\n 4: string\n 5: string\n 6: string\n 7: string\n} = [\n '#404040',\n '#ff3030',\n '#00ff00',\n '#ffff00',\n '#0080ff',\n '#ff33ff',\n '#00ffff',\n '#ffffff',\n]\n", "import { NameCodes, namedBrightColors, namedColors } from './named.js'\n\nconst hex = (n: number) => n.toString(16).padStart(2, '0')\n\nconst colors = [\n ...(function* () {\n for (let red = 0; red < 6; red++) {\n for (let green = 0; green < 6; green++) {\n for (let blue = 0; blue < 6; blue++) {\n const r = red ? red * 40 + 55 : 0\n const g = green ? green * 40 + 55 : 0\n const b = blue ? blue * 40 + 55 : 0\n yield `#${hex(r)}${hex(g)}${hex(b)}`\n }\n }\n }\n })(),\n]\n\nconst grays = [\n ...(function* () {\n for (let gray = 0; gray < 24; gray++) {\n const g = gray * 10 + 8\n yield `#${hex(g).repeat(3)}`\n }\n })(),\n]\n\nexport const xtermCode = (n: number) => {\n if (n < 8) return namedColors[n as NameCodes]\n if (n < 16) return namedBrightColors[(n - 8) as NameCodes]\n if (n < Math.pow(6, 3)) return colors[n - 16] as string\n if (n < 256) return grays[n - 232] as string\n}\n", "// this object is deposited into the style buffer in the Terminal\n// every time a character is written to the character buffer.\n// Handles all parsing of \\x1b[...m ANSI codes and conversion to CSS.\nimport { defaultBackground, defaultColor } from './default-colors.js'\nimport { dimColor } from './dim-color.js'\nimport { hexToRgb } from './hex-to-rgb.js'\nimport { htmlEscape } from './html-escape.js'\nimport {\n NameCodes,\n nameCodes,\n namedBrightColors,\n namedColors,\n Names,\n} from './named.js'\nimport { rgbToHex } from './rgb-to-hex.js'\nimport { xtermCode } from './xterm.js'\n\nconst ALL_END = '0'\nconst BG_END = '49'\nconst BG_START = '48'\nconst BOLD_END = '22'\nconst BOLD_START = '1'\nconst DIM_START = '2'\n// DIM_END is the same as BOLD_END because it's really \"font-weight:normal\"\n// In practice, dim modifies color, not font-weight, since modern screens\n// have colors, and most terminal fonts don't distinguish font weights other\n// than normal and bold.\nconst FG_END = '39'\nconst FG_START = '38'\nconst INV_END = '27'\nconst INV_START = '7'\nconst ITALIC_END = '23'\nconst ITALIC_START = '3'\nconst OVER_END = '55'\nconst OVER_START = '53'\nconst STRIKE_END = '29'\nconst STRIKE_START = '9'\nconst UNDERLINE_END = '24'\nconst UNDERLINE_START = '4'\nconst UNDERLINE_START_2 = '21' // WHYYYYYY\n\nconst NAMED_RE = /^(3|4|9|10)([0-7])$/\nconst NAMED_FG = '3'\nconst NAMED_BG = '4'\nconst NAMED_FG_BRIGHT = '9'\nconst NAMED_BG_BRIGHT = '10'\n\n// verifies that the style code is something that a Style object can handle,\n// and captures the first code and its parameter.\n// first code: $1\n// href: $2\n// styles: $3\nconst VALID_CODE = () =>\n new RegExp(\n '\\x1b\\\\]8;;' + // OSC hyperlink\n '(.*?)' + // href\n '(?:\\x1b|\\x07)' + // ST\n '|' +\n '\\x1b\\\\[' + // style codes\n '([0-9]*(?:;[0-9]*)*)' + // code numbers\n 'm', // end style codes\n 'g',\n )\n\ntype ParsedValidCode =\n | null\n | (RegExpExecArray &\n ([string, string, undefined] | [string, undefined, string]))\n\n/**\n * The properties that can be set on Style objects\n */\nexport type StyleProps = {\n /** may be either a hex string, or a named color */\n background?: string\n bold?: boolean\n /** may be either a hex string, or a named color */\n color?: string\n dim?: boolean\n inverse?: boolean\n italic?: boolean\n overline?: boolean\n strike?: boolean\n underline?: boolean\n /** hyperlink target, must be a valid url or `''` */\n href?: string\n}\n\nconst RESET_STYLE: StyleProps = {\n background: '',\n bold: false,\n color: '',\n dim: false,\n inverse: false,\n italic: false,\n overline: false,\n strike: false,\n underline: false,\n}\nconst RESET_PROPS: StyleProps = {\n ...RESET_STYLE,\n href: '',\n}\n\nconst namedColor = (c: string, bright = false): string => {\n if (!c) return c\n c = c.toLowerCase()\n const code = nameCodes[c as Names]\n if (typeof code === 'number') {\n return (bright ? namedBrightColors[code] : namedColors[code]) as string\n }\n if (c.includes('bright') && !bright) {\n return namedColor(c.replace(/bright/g, ''), true)\n }\n return rgbToHex(hexToRgb(c))\n}\n\nconst SEEN = new Map<string, Style>()\n\n/**\n * An immutable representation of an ANSI style. Used by Terminal and Block\n * to represent the styles in use for text to be printed.\n * If a Style object is created with the same properties as a\n * formerly seen Style object, the same object will be returned.\n *\n * For example:\n *\n * ```js\n * const a = new Style({ bold: true })\n * const b = new Style({ bold: true })\n * assert.equal(a, b) // passes\n * ```\n *\n * This optimization cuts down considerably on object creation,\n * because a Style is created for each styled character written to\n * the Terminal buffer. It also means that Style objects can be\n * compared directly with `===` to test for equivalence.\n */\nexport class Style {\n #css?: string\n\n #background!: string\n #bold!: boolean\n #color!: string\n #dim!: boolean\n #inverse!: boolean\n #italic!: boolean\n #overline!: boolean\n #strike!: boolean\n #underline!: boolean\n #ansi!: string\n #href!: string\n\n constructor(styles: StyleProps | string) {\n const {\n background = '',\n bold = false,\n color = '',\n dim = false,\n inverse = false,\n italic = false,\n overline = false,\n strike = false,\n underline = false,\n href = '',\n } = typeof styles !== 'string' ? styles : Style.ansiProperties(styles)\n\n const ansi = Style.propertiesAnsi({\n background,\n bold,\n color,\n dim,\n inverse,\n italic,\n overline,\n strike,\n underline,\n href,\n })\n\n // same style = same object\n const seen = SEEN.get(ansi)\n if (seen) return seen\n SEEN.set(ansi, this)\n\n this.#ansi = ansi\n this.#background = namedColor(background)\n this.#bold = bold\n this.#color = namedColor(color)\n this.#dim = dim\n this.#inverse = inverse\n this.#italic = italic\n this.#overline = overline\n this.#strike = strike\n this.#underline = underline\n try {\n this.#href = href && String(new URL(href))\n } catch {\n this.#href = ''\n }\n }\n\n /**\n * True if this style is a full reset of all properties.\n */\n get isReset() {\n return this === RESET\n }\n\n /** corresponding ANSI code sequence for this style */\n get ansi() {\n return this.#ansi\n }\n\n /** Convert a set of properties to an ANSI style code */\n static propertiesAnsi(styles: StyleProps): string {\n const {\n background,\n bold,\n color,\n dim,\n inverse,\n italic,\n overline,\n strike,\n underline,\n href = '',\n } = styles\n const codes = [\n // always do a reset at the start\n 0,\n ...(color ? [FG_START, 2, ...hexToRgb(namedColor(color))] : []),\n ...(background ?\n [BG_START, 2, ...hexToRgb(namedColor(background))]\n : []),\n ...(bold ? [BOLD_START] : []),\n ...(dim ? [DIM_START] : []),\n ...(inverse ? [INV_START] : []),\n ...(italic ? [ITALIC_START] : []),\n ...(overline ? [OVER_START] : []),\n ...(strike ? [STRIKE_START] : []),\n ...(underline ? [UNDERLINE_START] : []),\n ]\n return `\\x1b]8;;${href}\\x1b\\\\\\x1b[${codes.join(';')}m`\n }\n\n /**\n * If the input string is a sequence of *only* ANSI style and\n * OSC href codes, returns the array of codes and their parameters.\n * Otherwise, returns false.\n */\n static validStyleCodes(s: string): null | [string, string][] {\n let c = 0\n let m: ParsedValidCode\n const results: [string, string][] = []\n const vc = VALID_CODE()\n while ((m = vc.exec(s) as ParsedValidCode)) {\n if (c !== m.index) {\n return null\n }\n c += m[0].length\n results.push([m[0], m[1] ?? m[2]])\n }\n return results.length === 0 ? null : results\n }\n\n /** a Style object that resets all properties */\n static get RESET() {\n return RESET\n }\n\n /** Convert an ANSI style code to a set of properties */\n static ansiProperties(code: string): StyleProps {\n const codes = Style.validStyleCodes(code)\n if (!codes) {\n throw new Error('invalid ansi style code: ' + JSON.stringify(code))\n }\n const style: StyleProps = {}\n for (const code of codes) {\n if (code[0].startsWith('\\x1b]8;;')) {\n style.href = code[1]\n continue\n }\n const codes = code[1].split(';')\n for (let i = 0; i < codes.length; i++) {\n const c = codes[i] as string\n switch (c) {\n case '':\n case ALL_END:\n Object.assign(style, RESET_STYLE)\n continue\n case BOLD_END:\n style.bold = false\n style.dim = false\n continue\n case ITALIC_END:\n style.italic = false\n continue\n case STRIKE_END:\n style.strike = false\n continue\n case OVER_END:\n style.overline = false\n continue\n case UNDERLINE_END:\n style.underline = false\n continue\n case INV_END:\n style.inverse = false\n continue\n case FG_END:\n style.color = ''\n continue\n case BG_END:\n style.background = ''\n continue\n case BOLD_START:\n style.bold = true\n continue\n case INV_START:\n style.inverse = true\n continue\n case UNDERLINE_START:\n case UNDERLINE_START_2:\n style.underline = true\n continue\n case DIM_START:\n style.dim = true\n continue\n case OVER_START:\n style.overline = true\n continue\n case ITALIC_START:\n style.italic = true\n continue\n case STRIKE_START:\n style.strike = true\n continue\n case BG_START:\n case FG_START: {\n // 2 for rgb, 5 for xterm\n const next = codes[i + 1]\n const prop = c == FG_START ? 'color' : 'background'\n switch (next) {\n case '5':\n const xt = codes[i + 2]\n const code = xt && xtermCode(parseInt(xt, 10))\n if (code) {\n i += 2\n style[prop] = code\n }\n continue\n case '2':\n const sr = codes[i + 2]\n const sg = codes[i + 3]\n const sb = codes[i + 4]\n if (sr && sg && sb) {\n const r = parseInt(sr, 10)\n const g = parseInt(sg, 10)\n const b = parseInt(sb, 10)\n const hex = rgbToHex([r, g, b])\n if (\n r <= 255 &&\n r >= 0 &&\n g <= 255 &&\n g >= 0 &&\n b <= 255 &&\n b >= 0\n ) {\n i += 4\n style[prop] = hex\n }\n }\n }\n continue\n }\n // named color/bg\n default: {\n const m = c.match(NAMED_RE) as\n | null\n | (RegExpMatchArray & [string, string, string])\n if (!m) continue\n const color = parseInt(m[2], 10) as NameCodes\n switch (m[1]) {\n case NAMED_FG:\n style.color = namedColors[color]\n continue\n case NAMED_BG:\n style.background = namedColors[color]\n continue\n case NAMED_FG_BRIGHT:\n style.color = namedBrightColors[color]\n continue\n case NAMED_BG_BRIGHT:\n style.background = namedBrightColors[color]\n continue\n }\n }\n }\n }\n }\n return style\n }\n\n /**\n * Return a new Style with this one plus the updated properties.\n *\n * If a string is provided, must be a valid set of style and OSC hyperlink\n * ANSI code, though unrecognized parameters within that code will be ignored\n * rather than throwing an error.\n */\n update(properties: StyleProps | string): Style {\n const {\n background = this.#background,\n bold = this.#bold,\n color = this.#color,\n dim = this.#dim,\n inverse = this.#inverse,\n italic = this.#italic,\n overline = this.#overline,\n strike = this.#strike,\n underline = this.#underline,\n href = this.#href,\n } =\n typeof properties === 'string' ?\n Style.ansiProperties(properties)\n : properties\n\n return (\n background === this.#background &&\n bold === this.#bold &&\n color === this.#color &&\n dim === this.#dim &&\n inverse === this.#inverse &&\n italic === this.#italic &&\n overline === this.#overline &&\n strike === this.#strike &&\n underline === this.#underline &&\n href === this.#href\n ) ?\n this\n : new Style({\n background,\n bold,\n color,\n dim,\n inverse,\n italic,\n overline,\n strike,\n underline,\n href,\n })\n }\n\n [Symbol.for('nodejs.util.inspect.custom')](\n _: any,\n { colors }: { colors: boolean } = { colors: false },\n ) {\n const { ansi } = this\n return `Style { ${colors ? ansi : ''}${ansi.replace(/\\x1b/g, '^[')}${\n colors ? '\\x1b]8;;\\x1b\\\\\\x1b[m' : ''\n } }`\n }\n\n /**\n * Wrap the input string in the appropriate HTML for this style\n */\n wrap(s: string) {\n const css = this.toString()\n const href = this.#href\n if (!css && !href) return htmlEscape(s)\n const tag = href ? `a` : 'span'\n return `<${tag}${href ? ` href=\"${href}\"` : ''}${\n css ? ` style=\"${css}\"` : ''\n }>${htmlEscape(s)}</${tag}>`\n }\n\n /**\n * Return just the CSS for the styles. Href is not relevant.\n */\n toString() {\n if (this.#css) return this.#css\n let color = this.#inverse ? this.#background : this.#color\n let background = this.#inverse ? this.#color : this.#background\n if (this.#inverse) {\n color ||= defaultBackground()\n background ||= defaultColor()\n }\n // dim text is a different color, unless the background is the same\n // color, and set to something other than default. !?!? hwyyyyyyy idgi\n if (this.#dim && !(color && color === background)) {\n color = dimColor(color || defaultColor())\n }\n const textDecoration = [\n ...(this.#underline ? ['underline'] : []),\n ...(this.#overline ? ['overline'] : []),\n ...(this.#strike ? ['line-through'] : []),\n ].join(' ')\n\n return (this.#css = [\n ...(textDecoration ? [`text-decoration:${textDecoration}`] : []),\n ...(this.#bold ? ['font-weight:bold']\n : this.#dim ? ['font-weight:100']\n : []),\n ...(this.#italic ? ['font-style:italic'] : []),\n ...(color ? [`color:${color}`] : []),\n ...(background ? [`background:${background}`] : []),\n ].join(';'))\n }\n}\n\nconst RESET = new Style(RESET_PROPS)\n", "import { InspectOptions } from 'util'\nimport { fixEmoji } from './fix-emoji.js'\nimport { Style } from './style.js'\n\n/**\n * A representation of a run of text in a given style\n */\nexport class Block {\n #style?: Style\n #text: string\n\n constructor(text: string, style?: Style) {\n this.#text = text\n this.#style = style\n }\n\n [Symbol.for('nodejs.util.inspect.custom')](\n _: any,\n opts: InspectOptions,\n inspect: typeof import('util').inspect,\n ) {\n return `Block {${\n this.#style ? ' ' + inspect(this.#style, opts) : ''\n } ${inspect(this.#text, opts)} }`\n }\n\n /** return the block as a styled `<span>` tag */\n toString() {\n return this.#toString(false)\n }\n\n /** a representation of the block as an ANSI styled string */\n get ansi() {\n return this.#toString(true)\n }\n\n #toString(ansi: boolean) {\n return (\n !this.#text ? ''\n : ansi ? (this.#style ?? Style.RESET).ansi + this.#text\n : fixEmoji((this.#style ?? Style.RESET).wrap(this.#text))\n )\n }\n\n /** append text to the block */\n write(c: string) {\n this.#text += c\n return this\n }\n\n /** the raw text that will be written */\n get text() {\n return this.#text\n }\n\n /** the Style used by this block */\n get style() {\n return this.#style\n }\n}\n", "import { InspectOptions } from 'util'\nimport { Block } from './block.js'\nimport { defaultBackground, defaultColor } from './default-colors.js'\nimport { Style, StyleProps } from './style.js'\nconst CODES_RE =\n /^\\u001b\\[([0-9]*[A-GJKSTg]|([0-9;]*)m|([0-9]*;?[0-9]*)?[Hf]|\\?[0-9]+[hl])/\n\nconst OSC_RE = /^\\u001b\\](.*?)(?:\\u0007|\\u001b\\\\)/\nconst OSC_TITLE = '0;'\nconst OSC_HREF = '8;;'\n\n/**\n * A representation of a virtual \"terminal\" where we write out the character\n * and style information as we parse through the ANSI encoded stream.\n *\n * Important: this is *not* a full-fledged Stream class. You can write to it\n * multiple times, and it will update appropriately, but it does zero buffering\n * or input validation, so writing a partial ANSI code sequence will result in\n * mochibake in the output.\n *\n * The virtual terminal is an infinitely high and wide screen, with no\n * scrollback buffer. So, when `scrollDown(n)` is called (either explicitly, or\n * with a `\\x1b[<n>S` ANSI code), `n` lines are removed from the top of the\n * \"screen\". When `scrollUp(n)` is called (explicitly or via a `\\x1b[<n>T` ANSI\n * code), `n` _empty_ lines are added to the top of the screen; the lines lost\n * to a previous `scrollDown` action are not restored when scrolling up.\n *\n * Also, actions that move the cursor down or to the right, which would on a\n * normal physical terminal be limited to the height/width of the terminal, are\n * unbounded. For example, on an actual terminal, `echo $'\\x1b[1000Bhello'`\n * will print \"hello\" at the bottom of the screen (unless your screen happens\n * to be more than 1000 lines high); in this virtual terminal, it will create\n * 1000 empty lines.\n *\n * Most of the methods (other than `toString()` of course) return `this`,\n * allowing for things like this:\n *\n * ```js\n * console.log(\n * new Terminal()\n * .setStyle({ color: '#ff0000' })\n * .write('hello, ')\n * .down(1)\n * .setStyle({ inverse: true })\n * .write('world!').ansi\n * )\n * ```\n */\nexport class Terminal {\n // note: 0-indexed, but all the ansi codes are 1-indexed\n #cursor: [number, number] = [0, 0]\n // character data\n #text: string[][] = []\n // the style used to write it\n #style: (Style | undefined)[][] = []\n // the current style we use to paint characters to our \"screen\"\n #brush: Style = new Style({})\n\n #title: string = ''\n #blocks?: Block[]\n\n constructor(input?: string) {\n if (input) this.write(input)\n }\n\n /**\n * Set the style that the terminal will use for text writes.\n *\n * If a string, must be a valid `\\x1b[...m` ANSI style code.\n *\n * The styles provided will be appended onto the current style in use, just\n * as they would be by a real terminal if the relevant ANSI code is\n * encountered.\n */\n setStyle(style: string | StyleProps): Terminal {\n this.#brush = this.#brush.update(style)\n return this\n }\n\n /** Move the cursor up `n` lines, stopping at the top. */\n up(n: number): Terminal {\n this.#cursor[0] = Math.max(this.#cursor[0] - n, 0)\n return this\n }\n\n /** Move the cursor down `n` lines, without limit. */\n down(n: number): Terminal {\n // move down\n // in real life, this would be maxed to the size of the screen buffer,\n // but since this virtual terminal is an infinitely high and wide screen,\n // we just let it create new lines.\n this.#cursor[0] += n\n return this\n }\n\n /**\n * Prepend `n` empty lines at the start of the buffer, effectively moving the\n * cursor up as a result.\n */\n scrollUp(n: number): Terminal {\n // add n lines at the start of the buffer\n // leaves the cursor at the same index it was at before, effectively\n // moving it up as a result.\n for (let i = 0; i < n; i++) {\n this.#text.unshift([])\n this.#style.unshift([])\n }\n return this\n }\n\n /**\n * Remove `n` lines from the start of the buffer, effectively moving the\n * cursor down as a result.\n */\n scrollDown(n: number): Terminal {\n // remove lines from the top of the buffer, effectively moving\n // the cursor down as a result.\n // TODO: Maybe it would be good to keep a scrollback buffer,\n // and move lines into/out of there on scroll?\n for (let i = 0; i < n; i++) {\n this.#text.shift()\n this.#style.shift()\n }\n return this\n }\n\n /** Move the cursor forward `n` columns, without limit. */\n forward(n: number): Terminal {\n this.#cursor[1] += n\n return this\n }\n\n /** Move the cursor back `n` columns, stopping at the first column. */\n back(n: number): Terminal {\n this.#cursor[1] = Math.max(0, this.#cursor[1] - n)\n return this\n }\n\n /** Move to the start of the `n`-th next line. */\n nextLine(n: number): Terminal {\n this.#cursor[0] += n\n this.#cursor[1] = 0\n return this\n }\n\n /**\n * Move to the start of the `n`-th previous line, stopping at the top of the\n * screen.\n */\n prevLine(n: number): Terminal {\n this.#cursor[0] = Math.max(0, this.#cursor[0] - n)\n this.#cursor[1] = 0\n return this\n }\n\n /**\n * Move to the `n`-th column (1-indexed), limited by the left-most column.\n */\n horizontalPosition(n: number): Terminal {\n this.#cursor[1] = Math.max(0, n - 1)\n return this\n }\n\n /**\n * Move to the 1-indexed row and column specified, limited by the top and\n * left sides of the screen.\n */\n position(row: number, col: number): Terminal {\n this.#cursor[0] = Math.max(row - 1, 0)\n this.#cursor[1] = Math.max(col - 1, 0)\n return this\n }\n\n /**\n * Delete all printed data from the screen.\n *\n * Note that this is used for both `\\x1b[2J` _and_ `\\x1b[3J`, because there\n * is no scrollback buffer in this virtual terminal.\n */\n eraseScreen(): Terminal {\n // erase entire screen\n this.#text.length = 0\n this.#style.length = 0\n return this\n }\n\n /** Delete all printed data from the cursor to the end of the screen. */\n eraseScreenToEnd(): Terminal {\n // erase from cursor to end of screen\n this.#text.splice(this.#cursor[0] + 1)\n this.#style.splice(this.#cursor[0] + 1)\n this.eraseLineToEnd()\n return this\n }\n\n /** Delete all printed data from the top of the screen to the cursor. */\n eraseScreenFromStart(): Terminal {\n // erase from beginning of screen to cursor\n let i\n for (i = 0; i < this.#cursor[0]; i++) {\n const line = this.#text[i]\n const sline = this.#style[i]\n /* c8 ignore start */\n if (!line || !sline) continue\n /* c8 ignore stop */\n line.length = 0\n sline.length = 0\n }\n this.eraseLineFromStart()\n return this\n }\n\n /** Delete the contents of the current line. */\n eraseLine(): Terminal {\n const line = this.#text[this.#cursor[0]]\n const sline = this.#style[this.#cursor[0]]\n if (!line || !sline) return this\n line.length = 0\n sline.length = 0\n return this\n }\n\n /**\n * Delete printed data from the cursor to the end of the current line.\n */\n eraseLineToEnd(): Terminal {\n const line = this.#text[this.#cursor[0]]\n const sline = this.#style[this.#cursor[0]]\n if (!line || !sline) return this\n // from cursor to end of line\n line.splice(this.#cursor[1])\n sline.splice(this.#cursor[1])\n return this\n }\n\n /**\n * Delete printed data from the start of the current line to the cursor.\n */\n eraseLineFromStart(): Terminal {\n if (this.#cursor[1] === 0) return this.eraseLine()\n /* c8 ignore start */\n const line = this.#text[this.#cursor[0]]\n const sline = this.#style[this.#cursor[0]]\n /* c8 ignore stop */\n if (!line || !sline) return this\n for (let i = 0; i < this.#cursor[1]; i++) {\n line[i] = ' '\n sline[i] = undefined\n }\n return this\n }\n\n /**\n * Parse the ANSI encoded string provided, updating the internal character\n * and style buffers appropriately.\n */\n write(input: string): Terminal {\n this.#blocks = undefined\n // remove title-setting sequences\n for (let c = 0; c < input.length; ) {\n while (input.charAt(c) === '\\x1b') {\n // codes that don't use the OSC or CSI code\n switch (input.charAt(c + 1)) {\n case 'B':\n this.horizontalPosition(1)\n c += 2\n continue\n case 'H':\n // tab stops, not supported, ignore\n c += 2\n continue\n case 'D':\n this.scrollDown(1)\n c += 2\n continue\n case 'M':\n this.scrollUp(1)\n c += 2\n continue\n }\n\n // cursor/screen motion/erase commands\n const code = input.substring(c).match(CODES_RE) as\n | null\n | (RegExpMatchArray & [string, string])\n if (code) {\n c += code[0].length\n if (code[1].endsWith('m')) {\n // style code\n this.setStyle(code[0])\n continue\n } else {\n const x = code[1].charAt(code[1].length - 1)\n if (x === 'H' || x === 'f') {\n // cursor position\n const [n, m] = code[1].replace(/[Hf]$/, '').split(';')\n const row = Math.max(1, parseInt(n || '1', 10))\n const col = Math.max(1, parseInt(m || '1', 10))\n this.position(row, col)\n continue\n }\n // these all have an optional 1-indexed parameter\n // that defaults to 1, except J and K which default to 0\n const p = code[1].match(/^([0-9]+)/)?.[1]\n const n = parseInt(p || '1', 10)\n const z = parseInt(p || '0', 10)\n switch (x) {\n case 'A':\n this.up(n)\n continue\n case 'T':\n this.scrollUp(n)\n continue\n case 'B':\n this.down(n)\n continue\n case 'S':\n this.scrollDown(n)\n continue\n case 'C':\n this.forward(n)\n continue\n case 'D':\n this.back(n)\n continue\n case 'E':\n this.nextLine(n)\n continue\n case 'F':\n this.prevLine(n)\n continue\n case 'G':\n this.horizontalPosition(n)\n continue\n case 'J': {\n switch (z) {\n case 0:\n this.eraseScreenToEnd()\n continue\n case 1:\n this.eraseScreenFromStart()\n continue\n case 2:\n case 3:\n this.eraseScreen()\n continue\n }\n continue\n }\n case 'K': {\n switch (z) {\n case 0:\n this.eraseLineToEnd()\n continue\n case 1:\n this.eraseLineFromStart()\n continue\n case 2:\n this.eraseLine()\n continue\n }\n continue\n }\n }\n }\n continue\n }\n\n // check for OSC (title and hyperlinks)\n const osc = input.substring(c).match(OSC_RE) as\n | null\n | (RegExpMatchArray & [string, string])\n if (osc?.index === 0) {\n c += osc[0].length\n const cmd = osc[1]\n if (cmd.startsWith(OSC_TITLE)) {\n this.setTitle(cmd.substring(OSC_TITLE.length))\n continue\n }\n if (cmd.startsWith(OSC_HREF)) {\n this.setStyle({ href: cmd.substring(OSC_HREF.length) })\n continue\n }\n continue\n }\n\n // some other code we don't support, treat as text\n break\n }\n\n // end parsing ansi codes, might have walked off the input\n if (c >= input.length) break\n\n const ch = input.charAt(c++)\n\n if (ch === '\\r') {\n this.horizontalPosition(1)\n continue\n }\n if (ch === '\\n') {\n this.nextLine(1)\n continue\n }\n\n // write a character\n // if we are off the painted terminal, paint up to that point\n while (this.#text.length < this.#cursor[0]) {\n this.#text.push([])\n this.#style.push([])\n }\n const sline = this.#style[this.#cursor[0]] || []\n const line = this.#text[this.#cursor[0]] || []\n while (line.length < this.#cursor[1]) {\n line.push(' ')\n }\n while (sline.length < this.#cursor[1]) {\n sline.push(undefined)\n }\n line[this.#cursor[1]] = ch\n sline[this.#cursor[1]] =\n this.#brush.isReset ? undefined : this.#brush\n this.#style[this.#cursor[0]] = sline\n this.#text[this.#cursor[0]] = line\n this.forward(1)\n }\n return this\n }\n\n /**\n * Called when an OSC code of `\\x1b]0;...\\x1b\\` is encountered.\n *\n * Sets the `title` attribute on the root `<pre>` in html output,\n * and creates a corresponding OSC title sequence in the ansi output.\n */\n setTitle(s: string) {\n this.#title = s\n return this\n }\n\n /** the raw unstyled text of each line */\n get text() {\n return this.#text.map(l => l.join(''))\n }\n\n [Symbol.for('nodejs.util.inspect.custom')](\n _: any,\n opts: InspectOptions,\n inspect: typeof import('util').inspect,\n ) {\n const ins = inspect(\n {\n cursor: this.#cursor,\n brush: this.#brush,\n text: this.#text.map(l => l.join('')),\n blocks: this.blocks,\n },\n opts,\n )\n return `Terminal ${ins}`\n }\n\n /**\n * Output the results of the style and character buffers as ANSI\n * styled text. This effectively normalizes all color codes to explicit\n * RGB values and resolves all cursor motions and other control codes,\n * and styling runs of identical styles with a single code.\n */\n get ansi() {\n return this.#toString(true)\n }\n\n /**\n * Output the results of the style and character buffers as a `<pre>`\n * tag with `<span>` elements setting effective styles.\n */\n toString() {\n return this.#toString(false)\n }\n\n /**\n * An array of `Block` objects each representing a string of text with a\n * given style.\n */\n get blocks(): Block[] {\n if (this.#blocks) return this.#blocks\n let cur: Block = new Block('')\n const blocks: Block[] = [cur]\n for (let i = 0; i < this.#text.length; i++) {\n /* c8 ignore start */\n const line = this.#text[i] || []\n const sline = this.#style[i] || []\n /* c8 ignore stop */\n for (let j = 0; j < line.length; j++) {\n const st = sline[j]\n // will always be set\n /* c8 ignore start */\n const ch = line[j] || ''\n /* c8 ignore stop */\n if (st === cur.style) cur.write(ch)\n else blocks.push((cur = new Block(ch, st)))\n }\n // append a \\n only if we're not at the end\n if (this.#text[i + 1]) cur.write('\\n')\n }\n return (this.#blocks = blocks.filter(b => !!b.text))\n }\n\n #toString(ansi: boolean) {\n // turn into an array of [string, Style?], concatenating runs\n // of the same style into a single string.\n const contents = this.blocks\n .map(b => (ansi ? b.ansi : b.toString()))\n .join('')\n if (ansi) {\n const title = this.#title ? `\\x1b]0;${this.#title}\\x1b\\\\` : ''\n return title + contents + '\\x1b[m'\n }\n const css = Object.entries({\n color: defaultColor(),\n background: defaultBackground(),\n position: 'relative',\n })\n .map(kv => kv.join(':'))\n .join(';')\n const preStyle = `style=\"${css}\"`\n const preTitle = this.#title ? ` title=\"${this.#title}\"` : ''\n return `<pre ${preStyle}${preTitle}>${contents}</pre>`\n }\n}\n", "export * from './block.js'\nexport * from './default-colors.js'\nexport * from './named.js'\nexport * from './xterm.js'\nexport * from './style.js'\nexport * from './terminal.js'\nexport * from './theme.js'\nimport { Terminal } from './terminal.js'\n\n/**\n * Convert a string of ANSI text into an HTML `<pre>` tag.\n */\nexport const ansiToPre = (input: string) => String(new Terminal(input))\n\n/**\n * Convert a string of ANSI text into a string of ANSI text with normalized\n * RGB color codes and all cursor control sequences resolved.\n */\nexport const ansiToAnsi = (input: string) => new Terminal(input).ansi\n", "const ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi16 = (offset = 0) => code => `\\u001B[${code + offset}m`;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nconst styles = {\n\tmodifier: {\n\t\treset: [0, 0],\n\t\t// 21 isn't widely supported and 22 does the same thing\n\t\tbold: [1, 22],\n\t\tdim: [2, 22],\n\t\titalic: [3, 23],\n\t\tunderline: [4, 24],\n\t\toverline: [53, 55],\n\t\tinverse: [7, 27],\n\t\thidden: [8, 28],\n\t\tstrikethrough: [9, 29],\n\t},\n\tcolor: {\n\t\tblack: [30, 39],\n\t\tred: [31, 39],\n\t\tgreen: [32, 39],\n\t\tyellow: [33, 39],\n\t\tblue: [34, 39],\n\t\tmagenta: [35, 39],\n\t\tcyan: [36, 39],\n\t\twhite: [37, 39],\n\n\t\t// Bright color\n\t\tblackBright: [90, 39],\n\t\tgray: [90, 39], // Alias of `blackBright`\n\t\tgrey: [90, 39], // Alias of `blackBright`\n\t\tredBright: [91, 39],\n\t\tgreenBright: [92, 39],\n\t\tyellowBright: [93, 39],\n\t\tblueBright: [94, 39],\n\t\tmagentaBright: [95, 39],\n\t\tcyanBright: [96, 39],\n\t\twhiteBright: [97, 39],\n\t},\n\tbgColor: {\n\t\tbgBlack: [40, 49],\n\t\tbgRed: [41, 49],\n\t\tbgGreen: [42, 49],\n\t\tbgYellow: [43, 49],\n\t\tbgBlue: [44, 49],\n\t\tbgMagenta: [45, 49],\n\t\tbgCyan: [46, 49],\n\t\tbgWhite: [47, 49],\n\n\t\t// Bright color\n\t\tbgBlackBright: [100, 49],\n\t\tbgGray: [100, 49], // Alias of `bgBlackBright`\n\t\tbgGrey: [100, 49], // Alias of `bgBlackBright`\n\t\tbgRedBright: [101, 49],\n\t\tbgGreenBright: [102, 49],\n\t\tbgYellowBright: [103, 49],\n\t\tbgBlueBright: [104, 49],\n\t\tbgMagentaBright: [105, 49],\n\t\tbgCyanBright: [106, 49],\n\t\tbgWhiteBright: [107, 49],\n\t},\n};\n\nexport const modifierNames = Object.keys(styles.modifier);\nexport const foregroundColorNames = Object.keys(styles.color);\nexport const backgroundColorNames = Object.keys(styles.bgColor);\nexport const colorNames = [...foregroundColorNames, ...backgroundColorNames];\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`,\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false,\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = wrapAnsi16();\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue(red, green, blue) {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16\n\t\t\t\t\t+ (36 * Math.round(red / 255 * 5))\n\t\t\t\t\t+ (6 * Math.round(green / 255 * 5))\n\t\t\t\t\t+ Math.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue(hex) {\n\t\t\t\tconst matches = /[a-f\\d]{6}|[a-f\\d]{3}/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet [colorString] = matches;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = [...colorString].map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t/* eslint-disable no-bitwise */\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF,\n\t\t\t\t\t/* eslint-enable no-bitwise */\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t\tansi256ToAnsi: {\n\t\t\tvalue(code) {\n\t\t\t\tif (code < 8) {\n\t\t\t\t\treturn 30 + code;\n\t\t\t\t}\n\n\t\t\t\tif (code < 16) {\n\t\t\t\t\treturn 90 + (code - 8);\n\t\t\t\t}\n\n\t\t\t\tlet red;\n\t\t\t\tlet green;\n\t\t\t\tlet blue;\n\n\t\t\t\tif (code >= 232) {\n\t\t\t\t\tred = (((code - 232) * 10) + 8) / 255;\n\t\t\t\t\tgreen = red;\n\t\t\t\t\tblue = red;\n\t\t\t\t} else {\n\t\t\t\t\tcode -= 16;\n\n\t\t\t\t\tconst remainder = code % 36;\n\n\t\t\t\t\tred = Math.floor(code / 36) / 5;\n\t\t\t\t\tgreen = Math.floor(remainder / 6) / 5;\n\t\t\t\t\tblue = (remainder % 6) / 5;\n\t\t\t\t}\n\n\t\t\t\tconst value = Math.max(red, green, blue) * 2;\n\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn 30;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t\tlet result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));\n\n\t\t\t\tif (value === 2) {\n\t\t\t\t\tresult += 60;\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\trgbToAnsi: {\n\t\t\tvalue: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi: {\n\t\t\tvalue: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t});\n\n\treturn styles;\n}\n\nconst ansiStyles = assembleStyles();\n\nexport default ansiStyles;\n", "import process from 'node:process';\nimport os from 'node:os';\nimport tty from 'node:tty';\n\n// From: https://github.com/sindresorhus/has-flag/blob/main/index.js\n/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {\nfunction hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n}\n\nconst {env} = process;\n\nlet flagForceColor;\nif (\n\thasFlag('no-color')\n\t|| hasFlag('no-colors')\n\t|| hasFlag('color=false')\n\t|| hasFlag('color=never')\n) {\n\tflagForceColor = 0;\n} else if (\n\thasFlag('color')\n\t|| hasFlag('colors')\n\t|| hasFlag('color=true')\n\t|| hasFlag('color=always')\n) {\n\tflagForceColor = 1;\n}\n\nfunction envForceColor() {\n\tif ('FORCE_COLOR' in env) {\n\t\tif (env.FORCE_COLOR === 'true') {\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (env.FORCE_COLOR === 'false') {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3,\n\t};\n}\n\nfunction _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {\n\tconst noFlagForceColor = envForceColor();\n\tif (noFlagForceColor !== undefined) {\n\t\tflagForceColor = noFlagForceColor;\n\t}\n\n\tconst forceColor = sniffFlags ? flagForceColor : noFlagForceColor;\n\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (sniffFlags) {\n\t\tif (hasFlag('color=16m')\n\t\t\t|| hasFlag('color=full')\n\t\t\t|| hasFlag('color=truecolor')) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (hasFlag('color=256')) {\n\t\t\treturn 2;\n\t\t}\n\t}\n\n\t// Check for Azure DevOps pipelines.\n\t// Has to be above the `!streamIsTTY` check.\n\tif ('TF_BUILD' in env && 'AGENT_NAME' in env) {\n\t\treturn 1;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10\n\t\t\t&& Number(osRelease[2]) >= 10_586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14_931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif ('GITHUB_ACTIONS' in env || 'GITEA_ACTIONS' in env) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-kitty') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app': {\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\t}\n\n\t\t\tcase 'Apple_Terminal': {\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nexport function createSupportsColor(stream, options = {}) {\n\tconst level = _supportsColor(stream, {\n\t\tstreamIsTTY: stream && stream.isTTY,\n\t\t...options,\n\t});\n\n\treturn translateLevel(level);\n}\n\nconst supportsColor = {\n\tstdout: createSupportsColor({isTTY: tty.isatty(1)}),\n\tstderr: createSupportsColor({isTTY: tty.isatty(2)}),\n};\n\nexport default supportsColor;\n", "// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.\nexport function stringReplaceAll(string, substring, replacer) {\n\tlet index = string.indexOf(substring);\n\tif (index === -1) {\n\t\treturn string;\n\t}\n\n\tconst substringLength = substring.length;\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\treturnValue += string.slice(endIndex, index) + substring + replacer;\n\t\tendIndex = index + substringLength;\n\t\tindex = string.indexOf(substring, endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n\nexport function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\tconst gotCR = string[index - 1] === '\\r';\n\t\treturnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\\r\\n' : '\\n') + postfix;\n\t\tendIndex = index + 1;\n\t\tindex = string.indexOf('\\n', endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n", "import ansiStyles from '#ansi-styles';\nimport supportsColor from '#supports-color';\nimport { // eslint-disable-line import/order\n\tstringReplaceAll,\n\tstringEncaseCRLFWithFirstIndex,\n} from './utilities.js';\n\nconst {stdout: stdoutColor, stderr: stderrColor} = supportsColor;\n\nconst GENERATOR = Symbol('GENERATOR');\nconst STYLER = Symbol('STYLER');\nconst IS_EMPTY = Symbol('IS_EMPTY');\n\n// `supportsColor.level` \u2192 `ansiStyles.color[name]` mapping\nconst levelMapping = [\n\t'ansi',\n\t'ansi',\n\t'ansi256',\n\t'ansi16m',\n];\n\nconst styles = Object.create(null);\n\nconst applyOptions = (object, options = {}) => {\n\tif (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {\n\t\tthrow new Error('The `level` option should be an integer from 0 to 3');\n\t}\n\n\t// Detect level if not set manually\n\tconst colorLevel = stdoutColor ? stdoutColor.level : 0;\n\tobject.level = options.level === undefined ? colorLevel : options.level;\n};\n\nexport class Chalk {\n\tconstructor(options) {\n\t\t// eslint-disable-next-line no-constructor-return\n\t\treturn chalkFactory(options);\n\t}\n}\n\nconst chalkFactory = options => {\n\tconst chalk = (...strings) => strings.join(' ');\n\tapplyOptions(chalk, options);\n\n\tObject.setPrototypeOf(chalk, createChalk.prototype);\n\n\treturn chalk;\n};\n\nfunction createChalk(options) {\n\treturn chalkFactory(options);\n}\n\nObject.setPrototypeOf(createChalk.prototype, Function.prototype);\n\nfor (const [styleName, style] of Object.entries(ansiStyles)) {\n\tstyles[styleName] = {\n\t\tget() {\n\t\t\tconst builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);\n\t\t\tObject.defineProperty(this, styleName, {value: builder});\n\t\t\treturn builder;\n\t\t},\n\t};\n}\n\nstyles.visible = {\n\tget() {\n\t\tconst builder = createBuilder(this, this[STYLER], true);\n\t\tObject.defineProperty(this, 'visible', {value: builder});\n\t\treturn builder;\n\t},\n};\n\nconst getModelAnsi = (model, level, type, ...arguments_) => {\n\tif (model === 'rgb') {\n\t\tif (level === 'ansi16m') {\n\t\t\treturn ansiStyles[type].ansi16m(...arguments_);\n\t\t}\n\n\t\tif (level === 'ansi256') {\n\t\t\treturn ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));\n\t\t}\n\n\t\treturn ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));\n\t}\n\n\tif (model === 'hex') {\n\t\treturn getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));\n\t}\n\n\treturn ansiStyles[type][model](...arguments_);\n};\n\nconst usedModels = ['rgb', 'hex', 'ansi256'];\n\nfor (const model of usedModels) {\n\tstyles[model] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n\n\tconst bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);\n\tstyles[bgModel] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n}\n\nconst proto = Object.defineProperties(() => {}, {\n\t...styles,\n\tlevel: {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn this[GENERATOR].level;\n\t\t},\n\t\tset(level) {\n\t\t\tthis[GENERATOR].level = level;\n\t\t},\n\t},\n});\n\nconst createStyler = (open, close, parent) => {\n\tlet openAll;\n\tlet closeAll;\n\tif (parent === undefined) {\n\t\topenAll = open;\n\t\tcloseAll = close;\n\t} else {\n\t\topenAll = parent.openAll + open;\n\t\tcloseAll = close + parent.closeAll;\n\t}\n\n\treturn {\n\t\topen,\n\t\tclose,\n\t\topenAll,\n\t\tcloseAll,\n\t\tparent,\n\t};\n};\n\nconst createBuilder = (self, _styler, _isEmpty) => {\n\t// Single argument is hot path, implicit coercion is faster than anything\n\t// eslint-disable-next-line no-implicit-coercion\n\tconst builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));\n\n\t// We alter the prototype because we must return a function, but there is\n\t// no way to create a function with a different prototype\n\tObject.setPrototypeOf(builder, proto);\n\n\tbuilder[GENERATOR] = self;\n\tbuilder[STYLER] = _styler;\n\tbuilder[IS_EMPTY] = _isEmpty;\n\n\treturn builder;\n};\n\nconst applyStyle = (self, string) => {\n\tif (self.level <= 0 || !string) {\n\t\treturn self[IS_EMPTY] ? '' : string;\n\t}\n\n\tlet styler = self[STYLER];\n\n\tif (styler === undefined) {\n\t\treturn string;\n\t}\n\n\tconst {openAll, closeAll} = styler;\n\tif (string.includes('\\u001B')) {\n\t\twhile (styler !== undefined) {\n\t\t\t// Replace any instances already present with a re-opening code\n\t\t\t// otherwise only the part of the string until said closing code\n\t\t\t// will be colored, and the rest will simply be 'plain'.\n\t\t\tstring = stringReplaceAll(string, styler.close, styler.open);\n\n\t\t\tstyler = styler.parent;\n\t\t}\n\t}\n\n\t// We can move both next actions out of loop, because remaining actions in loop won't have\n\t// any/visible effect on parts we add here. Close the styling before a linebreak and reopen\n\t// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92\n\tconst lfIndex = string.indexOf('\\n');\n\tif (lfIndex !== -1) {\n\t\tstring = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);\n\t}\n\n\treturn openAll + string + closeAll;\n};\n\nObject.defineProperties(createChalk.prototype, styles);\n\nconst chalk = createChalk();\nexport const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0});\n\nexport {\n\tmodifierNames,\n\tforegroundColorNames,\n\tbackgroundColorNames,\n\tcolorNames,\n\n\t// TODO: Remove these aliases in the next major version\n\tmodifierNames as modifiers,\n\tforegroundColorNames as foregroundColors,\n\tbackgroundColorNames as backgroundColors,\n\tcolorNames as colors,\n} from './vendor/ansi-styles/index.js';\n\nexport {\n\tstdoutColor as supportsColor,\n\tstderrColor as supportsColorStderr,\n};\n\nexport default chalk;\n", "/**\n * Implementation shared between `vlt run`, `vlt run-exec`, and `vlt exec`\n */\n\nimport { error } from '@vltpkg/error-cause'\nimport type {\n exec,\n execFG,\n ExecOptions,\n run,\n runExec,\n runExecFG,\n RunExecOptions,\n runFG,\n RunOptions,\n RunResult,\n} from '@vltpkg/run'\nimport { isRunResult } from '@vltpkg/run'\nimport { Monorepo, Workspace } from '@vltpkg/workspaces'\nimport { ansiToAnsi } from 'ansi-to-pre'\nimport chalk from 'chalk'\nimport { LoadedConfig } from './config/index.js'\n\nexport type RunnerBG = typeof exec | typeof run | typeof runExec\nexport type RunnerFG = typeof execFG | typeof runExecFG | typeof runFG\nexport type RunnerOptions = ExecOptions & RunExecOptions & RunOptions\n\nexport class ExecCommand<B extends RunnerBG, F extends RunnerFG> {\n bg: B\n fg: F\n arg0?: string\n args: string[]\n monorepo?: Monorepo\n /** how many places are we doing things in? */\n spaces: number\n conf: LoadedConfig\n projectRoot: string\n\n constructor(conf: LoadedConfig, bg: B, fg: F) {\n this.conf = conf\n this.bg = bg\n this.fg = fg\n const {\n projectRoot,\n positionals: [arg0, ...args],\n } = conf\n this.arg0 = arg0\n this.args = args\n\n const paths = conf.get('workspace')\n const groups = conf.get('workspace-group')\n const recursive = conf.get('recursive')\n this.monorepo =\n paths?.length || groups?.length || recursive ?\n Monorepo.load(projectRoot, { load: { paths, groups } })\n : undefined\n this.spaces = this.monorepo?.size ?? 1\n this.projectRoot = projectRoot\n }\n\n async run() {\n if (this.spaces === 1) {\n const arg = this.fgArg()\n if (!arg) return\n const result = await this.fg(arg)\n console.log(result)\n return result\n }\n const m = this.monorepo\n if (!m || this.spaces === 0) {\n throw error('no matching workspaces found', {\n /* c8 ignore next - already guarded */\n validOptions: [...(this.monorepo?.load().paths() ?? [])],\n })\n }\n const arg0 = this.arg0\n if (!arg0) {\n this.noArgsMulti()\n return\n }\n // run across workspaces\n let failed = false\n const resultMap = await m.run(async ws => {\n if (!failed) console.error(`${ws.path} ${arg0}`)\n const result = await this.bg(this.bgArg(ws)).catch(\n (er: unknown) => {\n if (\n er instanceof Error &&\n er.cause &&\n isRunResult(er.cause)\n ) {\n this.printResult(ws, er.cause)\n }\n failed = true\n throw er\n },\n )\n if (!failed) this.printResult(ws, result)\n return result\n })\n\n const results: Record<string, RunResult> = {}\n for (const [ws, result] of resultMap) {\n if (result.status === 0 && result.signal === null) {\n result.stdout = ''\n result.stderr = ''\n }\n results[ws.path] = result\n }\n return results\n }\n\n printResult(ws: Workspace, result: RunResult) {\n if (result.status === 0 && result.signal === null) {\n console.log(ws.path, 'ok')\n } else {\n console.log(\n chalk.bgWhiteBright.black.bold(ws.path + ' failure'),\n {\n status: result.status,\n signal: result.signal,\n },\n )\n /* c8 ignore start */\n if (result.stderr) console.error(ansiToAnsi(result.stderr))\n if (result.stdout) console.log(ansiToAnsi(result.stdout))\n process.exitCode = process.exitCode || (result.status ?? 1)\n /* c8 ignore stop */\n }\n }\n\n /* c8 ignore start - env specific */\n interactiveShell(): string {\n return (\n process.env.SHELL ??\n this.conf.get('script-shell') ??\n (process.platform === 'win32' ? 'cmd.exe' : '/bin/sh')\n )\n }\n /* c8 ignore stop */\n\n // overridden by 'vlt run' to print options and return undefined\n defaultArg0(): string | undefined {\n return this.interactiveShell()\n }\n\n fgArg(): RunnerOptions | undefined {\n const ws = this.monorepo?.values().next().value\n const cwd = ws?.fullpath ?? this.projectRoot\n const arg0 = this.arg0 ?? this.defaultArg0()\n if (!arg0) {\n return undefined\n }\n\n return {\n cwd,\n /* c8 ignore next - already guarded */\n arg0,\n args: this.args,\n projectRoot: this.projectRoot,\n packageJson: this.monorepo?.packageJson,\n 'script-shell':\n this.arg0 ? this.conf.get('script-shell') : false,\n }\n }\n\n /** If this returns undefined, then nothing to do */\n bgArg(ws: Workspace): RunnerOptions {\n /* c8 ignore start - already guarded */\n if (!this.arg0)\n throw error(\n 'Cannot spawn interactive shells in multiple workspaces',\n )\n /* c8 ignore stop */\n\n return {\n cwd: ws.fullpath,\n acceptFail: !this.conf.get('bail'),\n ignoreMissing: true,\n arg0: this.arg0,\n args: this.args,\n projectRoot: this.projectRoot,\n packageJson: this.monorepo?.packageJson,\n 'script-shell': this.conf.get('script-shell'),\n }\n }\n\n // overridden in `vlt run` to print available scripts\n noArgsMulti() {\n throw error(\n 'Cannot spawn interactive shells in multiple workspaces',\n )\n }\n}\n", "import { exec, execFG } from '@vltpkg/run'\nimport { LoadedConfig } from '../config/index.js'\nimport { ExecCommand } from '../exec-command.js'\n\nexport const usage = `vlt exec [command]\nRuns the command with all installed bins in the $PATH\nIf no command specified, an interactive subshell is spawned.`\n\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,UAAU;IAE3D;EACF;;EAGA,mBAAgB;AACd,WACE,QAAQ,IAAI,SACZ,KAAK,KAAK,IAAI,cAAc,MAC3B,QAAQ,aAAa,UAAU,YAAY;EAEhD;;;EAIA,cAAW;AACT,WAAO,KAAK,iBAAgB;EAC9B;EAEA,QAAK;AACH,UAAM,KAAK,KAAK,UAAU,OAAM,EAAG,KAAI,EAAG;AAC1C,UAAM,MAAM,IAAI,YAAY,KAAK;AACjC,UAAM,OAAO,KAAK,QAAQ,KAAK,YAAW;AAC1C,QAAI,CAAC,MAAM;AACT,aAAO;IACT;AAEA,WAAO;MACL;;MAEA;MACA,MAAM,KAAK;MACX,aAAa,KAAK;MAClB,aAAa,KAAK,UAAU;MAC5B,gBACE,KAAK,OAAO,KAAK,KAAK,IAAI,cAAc,IAAI;;EAElD;;EAGA,MAAM,IAAa;AAEjB,QAAI,CAAC,KAAK;AACR,YAAM,MACJ,wDAAwD;AAI5D,WAAO;MACL,KAAK,GAAG;MACR,YAAY,CAAC,KAAK,KAAK,IAAI,MAAM;MACjC,eAAe;MACf,MAAM,KAAK;MACX,MAAM,KAAK;MACX,aAAa,KAAK;MAClB,aAAa,KAAK,UAAU;MAC5B,gBAAgB,KAAK,KAAK,IAAI,cAAc;;EAEhD;;EAGA,cAAW;AACT,UAAM,MACJ,wDAAwD;EAE5D;;;;AC5LK,IAAM,QAAQ;;;AAId,IAAM,UAAU,OAAO,SAC5B,MAAM,IAAI,YAAY,MAAM,MAAM,MAAM,EAAE,IAAG;",
6
- "names": ["sync", "path", "sync", "path", "sync", "path", "resolve", "path", "resolve", "ext", "path", "env", "match", "path", "command", "path", "escape", "parse", "command", "parse", "spawn", "command", "expand", "command", "proc", "process", "global", "spawn", "spawn", "crossSpawn", "resolve", "resolve", "path", "env", "resolve", "env", "patch", "build", "pr", "M", "m", "z", "resolve", "range", "path", "t", "delimiter", "delimiter", "readFileSync", "statSync", "glob", "i", "acc", "ext", "glob", "re", "hasMagic", "start", "final", "ext", "qmark", "star", "expand", "regExpEscape", "re", "fileURLToPath", "getOptions", "v", "bf", "p", "ret", "resolve", "res", "path", "p", "resolve", "sep", "filter", "process", "sync", "defaultPlatform", "path", "rest", "path", "abs", "target", "defaultPlatform", "fileURLToPath", "d", "path", "n", "resolve", "posix", "path", "resolve", "readFileSync", "filter", "group", "glob", "posix", "ws", "statSync", "load", "emojiRegex", "r", "g", "b", "c", "styles", "code", "codes", "hex", "colors", "inspect", "n", "inspect", "hex", "process", "stream", "styles", "chalk", "styles"]
4
+ "sourcesContent": ["module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction checkPathExt (path, options) {\n var pathext = options.pathExt !== undefined ?\n options.pathExt : process.env.PATHEXT\n\n if (!pathext) {\n return true\n }\n\n pathext = pathext.split(';')\n if (pathext.indexOf('') !== -1) {\n return true\n }\n for (var i = 0; i < pathext.length; i++) {\n var p = pathext[i].toLowerCase()\n if (p && path.substr(-p.length).toLowerCase() === p) {\n return true\n }\n }\n return false\n}\n\nfunction checkStat (stat, path, options) {\n if (!stat.isSymbolicLink() && !stat.isFile()) {\n return false\n }\n return checkPathExt(path, options)\n}\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, path, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), path, options)\n}\n", "module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), options)\n}\n\nfunction checkStat (stat, options) {\n return stat.isFile() && checkMode(stat, options)\n}\n\nfunction checkMode (stat, options) {\n var mod = stat.mode\n var uid = stat.uid\n var gid = stat.gid\n\n var myUid = options.uid !== undefined ?\n options.uid : process.getuid && process.getuid()\n var myGid = options.gid !== undefined ?\n options.gid : process.getgid && process.getgid()\n\n var u = parseInt('100', 8)\n var g = parseInt('010', 8)\n var o = parseInt('001', 8)\n var ug = u | g\n\n var ret = (mod & o) ||\n (mod & g) && gid === myGid ||\n (mod & u) && uid === myUid ||\n (mod & ug) && myUid === 0\n\n return ret\n}\n", "var fs = require('fs')\nvar core\nif (process.platform === 'win32' || global.TESTING_WINDOWS) {\n core = require('./windows.js')\n} else {\n core = require('./mode.js')\n}\n\nmodule.exports = isexe\nisexe.sync = sync\n\nfunction isexe (path, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = {}\n }\n\n if (!cb) {\n if (typeof Promise !== 'function') {\n throw new TypeError('callback not provided')\n }\n\n return new Promise(function (resolve, reject) {\n isexe(path, options || {}, function (er, is) {\n if (er) {\n reject(er)\n } else {\n resolve(is)\n }\n })\n })\n }\n\n core(path, options || {}, function (er, is) {\n // ignore EACCES because that just means we aren't allowed to run it\n if (er) {\n if (er.code === 'EACCES' || options && options.ignoreErrors) {\n er = null\n is = false\n }\n }\n cb(er, is)\n })\n}\n\nfunction sync (path, options) {\n // my kingdom for a filtered catch\n try {\n return core.sync(path, options || {})\n } catch (er) {\n if (options && options.ignoreErrors || er.code === 'EACCES') {\n return false\n } else {\n throw er\n }\n }\n}\n", "const isWindows = process.platform === 'win32' ||\n process.env.OSTYPE === 'cygwin' ||\n process.env.OSTYPE === 'msys'\n\nconst path = require('path')\nconst COLON = isWindows ? ';' : ':'\nconst isexe = require('isexe')\n\nconst getNotFoundError = (cmd) =>\n Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, opt) => {\n const colon = opt.colon || COLON\n\n // If it has a slash, then we don't bother searching the pathenv.\n // just check the file itself, and that's it.\n const pathEnv = cmd.match(/\\//) || isWindows && cmd.match(/\\\\/) ? ['']\n : (\n [\n // windows always checks the cwd first\n ...(isWindows ? [process.cwd()] : []),\n ...(opt.path || process.env.PATH ||\n /* istanbul ignore next: very unusual */ '').split(colon),\n ]\n )\n const pathExtExe = isWindows\n ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'\n : ''\n const pathExt = isWindows ? pathExtExe.split(colon) : ['']\n\n if (isWindows) {\n if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')\n pathExt.unshift('')\n }\n\n return {\n pathEnv,\n pathExt,\n pathExtExe,\n }\n}\n\nconst which = (cmd, opt, cb) => {\n if (typeof opt === 'function') {\n cb = opt\n opt = {}\n }\n if (!opt)\n opt = {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n const step = i => new Promise((resolve, reject) => {\n if (i === pathEnv.length)\n return opt.all && found.length ? resolve(found)\n : reject(getNotFoundError(cmd))\n\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n resolve(subStep(p, i, 0))\n })\n\n const subStep = (p, i, ii) => new Promise((resolve, reject) => {\n if (ii === pathExt.length)\n return resolve(step(i + 1))\n const ext = pathExt[ii]\n isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {\n if (!er && is) {\n if (opt.all)\n found.push(p + ext)\n else\n return resolve(p + ext)\n }\n return resolve(subStep(p, i, ii + 1))\n })\n })\n\n return cb ? step(0).then(res => cb(null, res), cb) : step(0)\n}\n\nconst whichSync = (cmd, opt) => {\n opt = opt || {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n for (let i = 0; i < pathEnv.length; i ++) {\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n for (let j = 0; j < pathExt.length; j ++) {\n const cur = p + pathExt[j]\n try {\n const is = isexe.sync(cur, { pathExt: pathExtExe })\n if (is) {\n if (opt.all)\n found.push(cur)\n else\n return cur\n }\n } catch (ex) {}\n }\n }\n\n if (opt.all && found.length)\n return found\n\n if (opt.nothrow)\n return null\n\n throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n", "'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n", "'use strict';\n\nconst path = require('path');\nconst which = require('which');\nconst getPathKey = require('path-key');\n\nfunction resolveCommandAttempt(parsed, withoutPathExt) {\n const env = parsed.options.env || process.env;\n const cwd = process.cwd();\n const hasCustomCwd = parsed.options.cwd != null;\n // Worker threads do not have process.chdir()\n const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;\n\n // If a custom `cwd` was specified, we need to change the process cwd\n // because `which` will do stat calls but does not support a custom cwd\n if (shouldSwitchCwd) {\n try {\n process.chdir(parsed.options.cwd);\n } catch (err) {\n /* Empty */\n }\n }\n\n let resolved;\n\n try {\n resolved = which.sync(parsed.command, {\n path: env[getPathKey({ env })],\n pathExt: withoutPathExt ? path.delimiter : undefined,\n });\n } catch (e) {\n /* Empty */\n } finally {\n if (shouldSwitchCwd) {\n process.chdir(cwd);\n }\n }\n\n // If we successfully resolved, ensure that an absolute path is returned\n // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it\n if (resolved) {\n resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);\n }\n\n return resolved;\n}\n\nfunction resolveCommand(parsed) {\n return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);\n}\n\nmodule.exports = resolveCommand;\n", "'use strict';\n\n// See http://www.robvanderwoude.com/escapechars.php\nconst metaCharsRegExp = /([()\\][%!^\"`<>&|;, *?])/g;\n\nfunction escapeCommand(arg) {\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n return arg;\n}\n\nfunction escapeArgument(arg, doubleEscapeMetaChars) {\n // Convert to string\n arg = `${arg}`;\n\n // Algorithm below is based on https://qntm.org/cmd\n\n // Sequence of backslashes followed by a double quote:\n // double up all the backslashes and escape the double quote\n arg = arg.replace(/(\\\\*)\"/g, '$1$1\\\\\"');\n\n // Sequence of backslashes followed by the end of the string\n // (which will become a double quote later):\n // double up all the backslashes\n arg = arg.replace(/(\\\\*)$/, '$1$1');\n\n // All other backslashes occur literally\n\n // Quote the whole thing:\n arg = `\"${arg}\"`;\n\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n // Double escape meta chars if necessary\n if (doubleEscapeMetaChars) {\n arg = arg.replace(metaCharsRegExp, '^$1');\n }\n\n return arg;\n}\n\nmodule.exports.command = escapeCommand;\nmodule.exports.argument = escapeArgument;\n", "'use strict';\nmodule.exports = /^#!(.*)/;\n", "'use strict';\nconst shebangRegex = require('shebang-regex');\n\nmodule.exports = (string = '') => {\n\tconst match = string.match(shebangRegex);\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tconst [path, argument] = match[0].replace(/#! ?/, '').split(' ');\n\tconst binary = path.split('/').pop();\n\n\tif (binary === 'env') {\n\t\treturn argument;\n\t}\n\n\treturn argument ? `${binary} ${argument}` : binary;\n};\n", "'use strict';\n\nconst fs = require('fs');\nconst shebangCommand = require('shebang-command');\n\nfunction readShebang(command) {\n // Read the first 150 bytes from the file\n const size = 150;\n const buffer = Buffer.alloc(size);\n\n let fd;\n\n try {\n fd = fs.openSync(command, 'r');\n fs.readSync(fd, buffer, 0, size, 0);\n fs.closeSync(fd);\n } catch (e) { /* Empty */ }\n\n // Attempt to extract shebang (null is returned if not a shebang)\n return shebangCommand(buffer.toString());\n}\n\nmodule.exports = readShebang;\n", "'use strict';\n\nconst path = require('path');\nconst resolveCommand = require('./util/resolveCommand');\nconst escape = require('./util/escape');\nconst readShebang = require('./util/readShebang');\n\nconst isWin = process.platform === 'win32';\nconst isExecutableRegExp = /\\.(?:com|exe)$/i;\nconst isCmdShimRegExp = /node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;\n\nfunction detectShebang(parsed) {\n parsed.file = resolveCommand(parsed);\n\n const shebang = parsed.file && readShebang(parsed.file);\n\n if (shebang) {\n parsed.args.unshift(parsed.file);\n parsed.command = shebang;\n\n return resolveCommand(parsed);\n }\n\n return parsed.file;\n}\n\nfunction parseNonShell(parsed) {\n if (!isWin) {\n return parsed;\n }\n\n // Detect & add support for shebangs\n const commandFile = detectShebang(parsed);\n\n // We don't need a shell if the command filename is an executable\n const needsShell = !isExecutableRegExp.test(commandFile);\n\n // If a shell is required, use cmd.exe and take care of escaping everything correctly\n // Note that `forceShell` is an hidden option used only in tests\n if (parsed.options.forceShell || needsShell) {\n // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`\n // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument\n // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,\n // we need to double escape them\n const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);\n\n // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\\bar)\n // This is necessary otherwise it will always fail with ENOENT in those cases\n parsed.command = path.normalize(parsed.command);\n\n // Escape command & arguments\n parsed.command = escape.command(parsed.command);\n parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));\n\n const shellCommand = [parsed.command].concat(parsed.args).join(' ');\n\n parsed.args = ['/d', '/s', '/c', `\"${shellCommand}\"`];\n parsed.command = process.env.comspec || 'cmd.exe';\n parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped\n }\n\n return parsed;\n}\n\nfunction parse(command, args, options) {\n // Normalize arguments, similar to nodejs\n if (args && !Array.isArray(args)) {\n options = args;\n args = null;\n }\n\n args = args ? args.slice(0) : []; // Clone array to avoid changing the original\n options = Object.assign({}, options); // Clone object to avoid changing the original\n\n // Build our parsed object\n const parsed = {\n command,\n args,\n options,\n file: undefined,\n original: {\n command,\n args,\n },\n };\n\n // Delegate further parsing to shell or non-shell\n return options.shell ? parsed : parseNonShell(parsed);\n}\n\nmodule.exports = parse;\n", "'use strict';\n\nconst isWin = process.platform === 'win32';\n\nfunction notFoundError(original, syscall) {\n return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {\n code: 'ENOENT',\n errno: 'ENOENT',\n syscall: `${syscall} ${original.command}`,\n path: original.command,\n spawnargs: original.args,\n });\n}\n\nfunction hookChildProcess(cp, parsed) {\n if (!isWin) {\n return;\n }\n\n const originalEmit = cp.emit;\n\n cp.emit = function (name, arg1) {\n // If emitting \"exit\" event and exit code is 1, we need to check if\n // the command exists and emit an \"error\" instead\n // See https://github.com/IndigoUnited/node-cross-spawn/issues/16\n if (name === 'exit') {\n const err = verifyENOENT(arg1, parsed, 'spawn');\n\n if (err) {\n return originalEmit.call(cp, 'error', err);\n }\n }\n\n return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params\n };\n}\n\nfunction verifyENOENT(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawn');\n }\n\n return null;\n}\n\nfunction verifyENOENTSync(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawnSync');\n }\n\n return null;\n}\n\nmodule.exports = {\n hookChildProcess,\n verifyENOENT,\n verifyENOENTSync,\n notFoundError,\n};\n", "'use strict';\n\nconst cp = require('child_process');\nconst parse = require('./lib/parse');\nconst enoent = require('./lib/enoent');\n\nfunction spawn(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);\n\n // Hook into child process \"exit\" event to emit an error if the command\n // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n enoent.hookChildProcess(spawned, parsed);\n\n return spawned;\n}\n\nfunction spawnSync(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);\n\n // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);\n\n return result;\n}\n\nmodule.exports = spawn;\nmodule.exports.spawn = spawn;\nmodule.exports.sync = spawnSync;\n\nmodule.exports._parse = parse;\nmodule.exports._enoent = enoent;\n", "'use strict';\nmodule.exports = balanced;\nfunction balanced(a, b, str) {\n if (a instanceof RegExp) a = maybeMatch(a, str);\n if (b instanceof RegExp) b = maybeMatch(b, str);\n\n var r = range(a, b, str);\n\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + a.length, r[1]),\n post: str.slice(r[1] + b.length)\n };\n}\n\nfunction maybeMatch(reg, str) {\n var m = str.match(reg);\n return m ? m[0] : null;\n}\n\nbalanced.range = range;\nfunction range(a, b, str) {\n var begs, beg, left, right, result;\n var ai = str.indexOf(a);\n var bi = str.indexOf(b, ai + 1);\n var i = ai;\n\n if (ai >= 0 && bi > 0) {\n if(a===b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n\n while (i >= 0 && !result) {\n if (i == ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length == 1) {\n result = [ begs.pop(), bi ];\n } else {\n beg = begs.pop();\n if (beg < left) {\n left = beg;\n right = bi;\n }\n\n bi = str.indexOf(b, i + 1);\n }\n\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n\n if (begs.length) {\n result = [ left, right ];\n }\n }\n\n return result;\n}\n", "var balanced = require('balanced-match');\n\nmodule.exports = expandTop;\n\nvar escSlash = '\\0SLASH'+Math.random()+'\\0';\nvar escOpen = '\\0OPEN'+Math.random()+'\\0';\nvar escClose = '\\0CLOSE'+Math.random()+'\\0';\nvar escComma = '\\0COMMA'+Math.random()+'\\0';\nvar escPeriod = '\\0PERIOD'+Math.random()+'\\0';\n\nfunction numeric(str) {\n return parseInt(str, 10) == str\n ? parseInt(str, 10)\n : str.charCodeAt(0);\n}\n\nfunction escapeBraces(str) {\n return str.split('\\\\\\\\').join(escSlash)\n .split('\\\\{').join(escOpen)\n .split('\\\\}').join(escClose)\n .split('\\\\,').join(escComma)\n .split('\\\\.').join(escPeriod);\n}\n\nfunction unescapeBraces(str) {\n return str.split(escSlash).join('\\\\')\n .split(escOpen).join('{')\n .split(escClose).join('}')\n .split(escComma).join(',')\n .split(escPeriod).join('.');\n}\n\n\n// Basically just str.split(\",\"), but handling cases\n// where we have nested braced sections, which should be\n// treated as individual members, like {a,{b,c},d}\nfunction parseCommaParts(str) {\n if (!str)\n return [''];\n\n var parts = [];\n var m = balanced('{', '}', str);\n\n if (!m)\n return str.split(',');\n\n var pre = m.pre;\n var body = m.body;\n var post = m.post;\n var p = pre.split(',');\n\n p[p.length-1] += '{' + body + '}';\n var postParts = parseCommaParts(post);\n if (post.length) {\n p[p.length-1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n\n parts.push.apply(parts, p);\n\n return parts;\n}\n\nfunction expandTop(str) {\n if (!str)\n return [];\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.substr(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.substr(2);\n }\n\n return expand(escapeBraces(str), true).map(unescapeBraces);\n}\n\nfunction embrace(str) {\n return '{' + str + '}';\n}\nfunction isPadded(el) {\n return /^-?0\\d/.test(el);\n}\n\nfunction lte(i, y) {\n return i <= y;\n}\nfunction gte(i, y) {\n return i >= y;\n}\n\nfunction expand(str, isTop) {\n var expansions = [];\n\n var m = balanced('{', '}', str);\n if (!m) return [str];\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n var pre = m.pre;\n var post = m.post.length\n ? expand(m.post, false)\n : [''];\n\n if (/\\$$/.test(m.pre)) { \n for (var k = 0; k < post.length; k++) {\n var expansion = pre+ '{' + m.body + '}' + post[k];\n expansions.push(expansion);\n }\n } else {\n var isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n var isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n var isSequence = isNumericSequence || isAlphaSequence;\n var isOptions = m.body.indexOf(',') >= 0;\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,.*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post;\n return expand(str);\n }\n return [str];\n }\n\n var n;\n if (isSequence) {\n n = m.body.split(/\\.\\./);\n } else {\n n = parseCommaParts(m.body);\n if (n.length === 1) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand(n[0], false).map(embrace);\n if (n.length === 1) {\n return post.map(function(p) {\n return m.pre + n[0] + p;\n });\n }\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n var N;\n\n if (isSequence) {\n var x = numeric(n[0]);\n var y = numeric(n[1]);\n var width = Math.max(n[0].length, n[1].length)\n var incr = n.length == 3\n ? Math.abs(numeric(n[2]))\n : 1;\n var test = lte;\n var reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n var pad = n.some(isPadded);\n\n N = [];\n\n for (var i = x; test(i, y); i += incr) {\n var c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === '\\\\')\n c = '';\n } else {\n c = String(i);\n if (pad) {\n var need = width - c.length;\n if (need > 0) {\n var z = new Array(need + 1).join('0');\n if (i < 0)\n c = '-' + z + c.slice(1);\n else\n c = z + c;\n }\n }\n }\n N.push(c);\n }\n } else {\n N = [];\n\n for (var j = 0; j < n.length; j++) {\n N.push.apply(N, expand(n[j], false));\n }\n }\n\n for (var j = 0; j < N.length; j++) {\n for (var k = 0; k < post.length; k++) {\n var expansion = pre + N[j] + post[k];\n if (!isTop || isSequence || expansion)\n expansions.push(expansion);\n }\n }\n }\n\n return expansions;\n}\n\n", "module.exports = () => {\n\t// https://mths.be/emoji\n\treturn /[#*0-9]\\uFE0F?\\u20E3|[\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u231A\\u231B\\u2328\\u23CF\\u23ED-\\u23EF\\u23F1\\u23F2\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB\\u25FC\\u25FE\\u2600-\\u2604\\u260E\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u2648-\\u2653\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u267F\\u2692\\u2694-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A7\\u26AA\\u26B0\\u26B1\\u26BD\\u26BE\\u26C4\\u26C8\\u26CF\\u26D1\\u26E9\\u26F0-\\u26F5\\u26F7\\u26F8\\u26FA\\u2702\\u2708\\u2709\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u27A1\\u2934\\u2935\\u2B05-\\u2B07\\u2B1B\\u2B1C\\u2B55\\u3030\\u303D\\u3297\\u3299]\\uFE0F?|[\\u261D\\u270C\\u270D](?:\\uFE0F|\\uD83C[\\uDFFB-\\uDFFF])?|[\\u270A\\u270B](?:\\uD83C[\\uDFFB-\\uDFFF])?|[\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u2693\\u26A1\\u26AB\\u26C5\\u26CE\\u26D4\\u26EA\\u26FD\\u2705\\u2728\\u274C\\u274E\\u2753-\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\\u2B1B|\\uD83D\\uDD25))?|\\uDC3B(?:\\u200D\\u2744\\uFE0F?)?|\\uDC41\\uFE0F?(?:\\u200D\\uD83D\\uDDE8\\uFE0F?)?|\\uDC68(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDC68\\uDC69]\\u200D\\uD83D(?:\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?)|[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?)|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFC-\\uDFFF])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])))?|\\uDFFD(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])))?|\\uDFFE(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])))?|\\uDFFF(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFE])))?))?|\\uDC69(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?[\\uDC68\\uDC69]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?|\\uDC69\\u200D\\uD83D(?:\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?))|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFC-\\uDFFF])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])))?|\\uDFFD(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])))?|\\uDFFE(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])))?|\\uDFFF(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB-\\uDFFE])))?))?|\\uDC6F(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|\\uDD75(?:\\uFE0F|\\uD83C[\\uDFFB-\\uDFFF])?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|\\uDE2E(?:\\u200D\\uD83D\\uDCA8)?|\\uDE35(?:\\u200D\\uD83D\\uDCAB)?|\\uDE36(?:\\u200D\\uD83C\\uDF2B\\uFE0F?)?|\\uDE42(?:\\u200D[\\u2194\\u2195]\\uFE0F?)?|\\uDEB6(?:\\uD83C[\\uDFFB-\\uDFFF])?(?:\\u200D(?:[\\u2640\\u2642]\\uFE0F?(?:\\u200D\\u27A1\\uFE0F?)?|\\u27A1\\uFE0F?))?)|\\uD83E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D1|\\uDDD1\\u200D\\uD83E\\uDDD2(?:\\u200D\\uD83E\\uDDD2)?|\\uDDD2(?:\\u200D\\uD83E\\uDDD2)?))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1\\uD83C[\\uDFFC-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFF])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1\\uD83C[\\uDFFB\\uDFFD-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFF])))?|\\uDFFD(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\u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FFB\\uDFFD-\\uDFFF])?|\\uDFFD(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])?|\\uDFFE(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])?|\\uDFFF(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB-\\uDFFE])?))?)/g;\n};\n", "import type { IncomingMessage } from 'http'\n\n/**\n * Codification of vlt's Error.cause conventions\n *\n * Add new properties to this list as needed.\n *\n * Several of these types are just very basic duck-typing, because referencing\n * internal types directly would create a workspace dependency cycle.\n */\nexport type ErrorCauseObject = {\n /**\n * The `cause` field within a `cause` object should\n * always be an `Error` object that was previously thrown. Note\n * that the `cause` on an Error itself might _also_ be a\n * previously thrown error, if no additional information could be\n * usefully added beyond improving the message.\n */\n cause?: ErrorCause\n\n /** the name of something */\n name?: string\n\n /** byte offset in a Buffer or file */\n offset?: number\n\n /**\n * This should only be a string code that we set. See {@link Codes} for\n * the supported options. Lower-level system codes like `ENOENT` should\n * remain on the errors that generated them.\n */\n code?: Codes\n\n /** target of a file system operation */\n path?: string\n\n /**\n * file path origin of a resolution that failed, for example in the case\n * of `file://` specifiers.\n */\n from?: string\n\n /** path on disk that is being written, linked, or extracted to */\n target?: string\n\n /** Spec object/string relevant to an operation that failed */\n spec?:\n | string\n | {\n type: 'file' | 'git' | 'registry' | 'remote' | 'workspace'\n spec: string\n [k: number | string | symbol]: any\n }\n\n /** exit code of a process, or HTTP response status code */\n status?: number | null\n\n /** null or a signal that a process received */\n signal?: NodeJS.Signals | null\n\n /** the root of a project */\n projectRoot?: string\n\n /** the current working directory of a process */\n cwd?: string\n\n /** a command being run in a child process */\n command?: string\n\n /** the arguments passed to a process */\n args?: string[]\n\n /** standard output from a process */\n stdout?: Buffer | string | null\n\n /** standard error from a process */\n stderr?: Buffer | string | null\n\n /**\n * Array of valid options when something is not a valid option.\n * (For use in `did you mean X?` output.)\n */\n validOptions?: any[]\n\n /**\n * message indicating what bit of work this might be a part of, what feature\n * needs to be implemented, etc. Eg, `{ todo: 'nested workspace support' }`.\n */\n todo?: string\n\n /**\n * A desired value that was not found, or a regular expression or other\n * pattern describing it.\n */\n wanted?: any\n\n /** actual value, which was not wanted */\n found?: any\n\n /** HTTP message, fetch.Response, or `@vltpkg/registry-client.CacheEntry` */\n response?:\n | IncomingMessage\n | Response\n | {\n statusCode: number\n headers: Buffer[] | Record<string, string[] | string>\n text: () => string\n [k: number | string | symbol]: any\n }\n\n /** string or URL object */\n url?: URL | string\n\n /** git repository remote or path */\n repository?: string\n\n /** string or `@vltpkg/semver.Version` object */\n version?:\n | string\n | {\n raw: string\n major: number\n minor: number\n patch: number\n [k: number | string | symbol]: any\n }\n\n /** string or `@vltpkg/semver.Range` object */\n range?:\n | string\n | {\n raw: string\n isAny: boolean\n includePrerelease: boolean\n [k: number | string | symbol]: any\n }\n\n /** a package manifest, either from `package.json` or a registry */\n manifest?: DuckTypeManifest\n\n /** registry top-level package document */\n packument?: {\n name: string\n 'dist-tags': Record<string, string>\n versions: Record<string, DuckTypeManifest>\n time?: Record<string, string>\n }\n\n /** maximum value, which was exceeded */\n max?: any\n\n /** minimum value, which was not met */\n min?: any\n}\n\nexport type DuckTypeManifest = Record<string, any> & {\n name?: string\n version?: string\n deprecated?: string\n engines?: Record<string, string>\n os?: string[] | string\n arch?: string[] | string\n dist?: {\n integrity?: string\n shasum?: string\n tarball?: string\n fileCount?: number\n unpackedSize?: number\n signatures?: {\n keyid: string\n sig: string\n }[]\n }\n}\n\nexport type ErrorCause = Error | ErrorCauseObject\n\n/**\n * Valid properties for the 'code' field in an Error cause.\n * Add new options to this list as needed.\n */\nexport type Codes =\n | 'EEXIST'\n | 'EINTEGRITY'\n | 'EINVAL'\n | 'ELIFECYCLE'\n | 'EMAXREDIRECT'\n | 'ENEEDAUTH'\n | 'ENOENT'\n | 'ENOGIT'\n | 'ERESOLVE'\n | 'EUNKNOWN'\n\nconst create = (\n cls: typeof Error,\n defaultFrom: ((...a: any[]) => any) | (new (...a: any[]) => any),\n message: string,\n cause?: ErrorCause,\n from:\n | ((...a: any[]) => any)\n | (new (...a: any[]) => any) = defaultFrom,\n) => {\n const er = new cls(message, cause ? { cause } : undefined)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n Error.captureStackTrace?.(er, from)\n return er\n}\n\nexport const error = (\n message: string,\n cause?: ErrorCause,\n from?: ((...a: any[]) => any) | (new (...a: any[]) => any),\n) => create(Error, error, message, cause, from)\n\nexport const typeError = (\n message: string,\n cause?: ErrorCause,\n from?: ((...a: any[]) => any) | (new (...a: any[]) => any),\n) => create(TypeError, typeError, message, cause, from)\n\nexport const syntaxError = (\n message: string,\n cause?: ErrorCause,\n from?: ((...a: any[]) => any) | (new (...a: any[]) => any),\n) => create(SyntaxError, syntaxError, message, cause, from)\n", "import { error } from '@vltpkg/error-cause'\n\n/** anything that can be encoded in JSON */\nexport type JSONField =\n | JSONField[]\n | boolean\n | number\n | string\n | { [k: string]: JSONField }\n | null\n\n/** sha512 SRI string */\nexport type Integrity = `sha512-${string}`\n\n/** SHA256 key identifier */\nexport type KeyID = `SHA256:${string}`\n\n/** The Manifest['dist'] field present in registry manifests */\nexport type Dist = {\n integrity?: Integrity\n shasum?: string\n tarball?: string\n fileCount?: number\n unpackedSize?: number\n signatures?: {\n keyid: KeyID\n sig: string\n }[]\n}\n\n/** An object used to mark some peerDeps as optional */\nexport type PeerDependenciesMetaValue = {\n optional?: boolean\n}\n\n// Don't use Record here since TS cant do circular references with that\n// https://github.com/microsoft/TypeScript/issues/41164#issuecomment-1427073368\nexport type ConditionalValueObject = {\n [k: string]: ConditionalValue\n}\nexport type ConditionalValue =\n | ConditionalValue[]\n | ConditionalValueObject\n | string\n | null\n\nexport type ExportsSubpaths = {\n [path in '.' | `./${string}`]?: ConditionalValue\n}\n\nexport type Exports =\n | Exclude<ConditionalValue, null>\n | ExportsSubpaths\n\nexport type Imports = Record<`#${string}`, ConditionalValue>\n\nexport type FundingEntry = string | { url: string }\nexport type Funding = FundingEntry | FundingEntry[]\n\nexport type ManifestRegistry = Manifest & {\n name: string\n version: string\n dist: Dist\n}\n\nexport type ManifestMinified = {\n /** The name of the package. optional because {} is a valid package.json */\n name?: string\n /** The version of the package. optional because {} is a valid package.json */\n version?: string\n /** production dependencies, name:specifier */\n dependencies?: Record<string, string>\n /** development dependencies, name:specifier */\n devDependencies?: Record<string, string>\n /** optional dependencies, name:specifier */\n optionalDependencies?: Record<string, string>\n /** peer dependencies, name:specifier */\n peerDependencies?: Record<string, string>\n /** peer dependencies marked as optional */\n peerDependenciesMeta?: Record<string, PeerDependenciesMetaValue>\n /** dependency ranges that are acceptable, but not forced */\n acceptDependencies?: Record<string, string>\n /** names of dependencies included in the package tarball */\n bundleDependencies?: string[]\n /** a message indicating that this is not to be used */\n deprecated?: string\n /** executable built and linked by this package */\n bin?: Record<string, string> | string\n /** run-script actions for this package */\n scripts?: Record<string, string>\n /** supported run-time platforms this package can run on */\n engines?: Record<string, string>\n /** supported operating systems this package can run on */\n os?: string[] | string\n /** supported CPU architectures this package can run on */\n cpu?: string[] | string\n /** URLs that can be visited to fund this project */\n funding?: Funding\n /**\n * Only present in Manifests served by a registry. Contains information\n * about the artifact served for this package release.\n */\n dist?: Dist\n}\n\nexport type Person =\n | string\n | {\n name: string\n url?: string\n email?: string\n }\n\nexport type Repository =\n | string\n | {\n type: string\n url: string\n }\n\nexport type Bugs =\n | string\n | {\n url?: string\n email?: string\n }\n\nexport type Manifest = ManifestMinified &\n Record<string, JSONField> & {\n /** a short description of the package */\n description?: string\n /** search keywords */\n keywords?: string[]\n /** where to go to file issues */\n bugs?: Bugs\n /** where the development happens */\n repository?: Repository\n /** whether this is ESM or CommonJS by default */\n type?: 'commonjs' | 'module'\n /** the main module, if exports['.'] is not set */\n main?: string\n /** named subpath exports */\n exports?: Exports\n /** named #identifier imports */\n imports?: Imports\n /**\n * the HEAD of the git repo this was published from\n * only present in published packages\n */\n gitHead?: string\n }\n\nexport type PackumentBase = {\n name: string\n 'dist-tags': Record<string, string>\n}\nexport type PackumentMinified = PackumentBase & {\n versions: Record<string, ManifestMinified>\n modified?: string\n}\n\nexport type Packument = PackumentBase &\n Record<string, JSONField> & {\n versions: Record<string, Manifest>\n time?: Record<string, string>\n readme?: string\n }\n\nconst integrityRE = /^sha512-[a-zA-Z0-9/+]{86}==$/\nexport const isIntegrity = (i: unknown): i is Integrity =>\n typeof i === 'string' && integrityRE.test(i)\n\nexport const asIntegrity = (i: unknown): Integrity => {\n if (!isIntegrity(i)) {\n throw error(\n 'invalid integrity',\n {\n found: i,\n wanted: integrityRE,\n },\n asIntegrity,\n )\n }\n return i\n}\n\nexport const assertIntegrity: (\n i: unknown,\n) => asserts i is Integrity = i => {\n asIntegrity(i)\n}\n\nconst keyIDRE = /^SHA256:[a-zA-Z0-9/+]{43}$/\nexport const isKeyID = (k: unknown): k is KeyID =>\n typeof k === 'string' && keyIDRE.test(k)\n\nexport const asKeyID = (k: unknown): KeyID => {\n if (!isKeyID(k)) {\n throw error(\n 'invalid key ID',\n {\n found: k,\n wanted: keyIDRE,\n },\n asKeyID,\n )\n }\n return k\n}\n\nexport const assertKeyID: (k: unknown) => asserts k is KeyID = k => {\n asKeyID(k)\n}\n\nconst maybeRecordStringString = (\n o: unknown,\n): o is Record<string, string> | undefined =>\n o === undefined || isRecordStringString(o)\n\nconst isRecordStringString = (\n o: unknown,\n): o is Record<string, string> =>\n isRecordStringT<string>(o, s => typeof s === 'string')\n\nconst isRecordStringT = <T>(\n o: unknown,\n check: (o: unknown) => boolean,\n): o is Record<string, T> =>\n !!o &&\n typeof o === 'object' &&\n Object.entries(o).every(\n ([k, v]) => typeof k === 'string' && check(v),\n )\n\nconst isRecordStringManifest = (\n o: unknown,\n): o is Record<string, Manifest> =>\n isRecordStringT<Manifest>(o, v => isManifest(v))\n\nconst maybePeerDependenciesMetaSet = (\n o: unknown,\n): o is Record<string, PeerDependenciesMetaValue> | undefined =>\n o === undefined ||\n isRecordStringT<PeerDependenciesMetaValue>(o, v =>\n isPeerDependenciesMetaValue(v),\n )\n\nconst maybeBoolean = (o: unknown): o is boolean =>\n o === undefined || typeof o === 'boolean'\n\nconst isPeerDependenciesMetaValue = (\n o: any,\n): o is PeerDependenciesMetaValue =>\n !!o && typeof o === 'object' && maybeBoolean(o.optional)\n\nconst maybeString = (a: unknown): a is string | undefined =>\n a === undefined || typeof a === 'string'\n\nconst maybeDist = (a: any): a is Manifest['dist'] =>\n a === undefined ||\n (!!a && typeof a === 'object' && maybeString(a.tarball))\n\nexport const isManifest = (m: any): m is Manifest =>\n !!m &&\n typeof m === 'object' &&\n !Array.isArray(m) &&\n maybeString(m.name) &&\n maybeString(m.version) &&\n maybeRecordStringString(m.dependencies) &&\n maybeRecordStringString(m.devDependencies) &&\n maybeRecordStringString(m.optionalDependencies) &&\n maybeRecordStringString(m.peerDependencies) &&\n maybeRecordStringString(m.acceptDependencies) &&\n maybePeerDependenciesMetaSet(m.peerDependenciesMeta) &&\n maybeDist(m.dist)\n\nexport const isManifestRegistry = (\n m: unknown,\n): m is ManifestRegistry =>\n isManifest(m) && !!m.dist && !!m.name && !!m.version\n\nexport const asManifest = (\n m: unknown,\n from?: (...a: any[]) => any,\n): Manifest => {\n if (!isManifest(m)) {\n throw error('invalid manifest', { found: m }, from ?? asManifest)\n }\n return m\n}\n\nexport const asManifestMinified = (\n m: unknown,\n from?: (...a: any[]) => any,\n): ManifestMinified => asManifest(m, from ?? asManifestMinified)\n\nexport const asManifestRegistry = (\n m: unknown,\n from?: (...a: any[]) => any,\n): ManifestRegistry => {\n if (!isManifestRegistry(m)) {\n throw error(\n 'invalid registry manifest',\n { found: m },\n from ?? asManifestRegistry,\n )\n }\n return m\n}\n\nexport const assertManifest: (\n m: unknown,\n) => asserts m is Manifest = m => {\n asManifest(m, assertManifest)\n}\nexport const assertManifestMinified: (\n m: unknown,\n) => asserts m is Manifest = m => {\n asManifestMinified(m, assertManifestMinified)\n}\nexport const assertManifestRegistry: (\n m: unknown,\n) => asserts m is ManifestRegistry = m => {\n asManifestRegistry(m, assertManifestRegistry)\n}\n\nexport const isPackument = (p: any): p is Packument =>\n !!p &&\n typeof p === 'object' &&\n typeof p.name === 'string' &&\n isRecordStringString(p['dist-tags']) &&\n isRecordStringManifest(p.versions) &&\n maybeRecordStringString(p.time) &&\n Object.values(p['dist-tags']).every(\n v => !!p.versions[v] && p.versions[v].name == p.name,\n )\n\nexport const isPackumentMinified = (\n p: unknown,\n): p is PackumentMinified => isPackument(p)\nexport const asPackumentMinified = (p: unknown): PackumentMinified =>\n asPackument(p, asPackumentMinified)\n\nexport const asPackument = (\n p: unknown,\n from?: (...a: unknown[]) => any,\n): Packument => {\n if (!isPackument(p)) {\n throw error(\n 'invalid packument',\n { found: p },\n from ?? asPackument,\n )\n }\n return p\n}\n\nexport const assertPackument: (\n m: unknown,\n) => asserts m is Packument = m => {\n asPackument(m)\n}\nexport const assertPackumentMinified: (\n m: unknown,\n) => asserts m is PackumentMinified = m => {\n asPackumentMinified(m)\n}\n", "import { error, ErrorCauseObject } from '@vltpkg/error-cause'\nimport { asManifest, Manifest } from '@vltpkg/types'\nimport { readFileSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { parse, stringify } from 'polite-json'\n\nexport class PackageJson {\n /**\n * cache of `package.json` loads\n */\n #cache = new Map<string, Manifest>()\n\n /**\n * cache of `package.json` paths by manifest\n */\n #pathCache = new Map<Manifest, string>()\n\n /**\n * cache of load errors\n */\n #errCache = new Map<string, ErrorCauseObject>()\n\n /**\n * Reads and parses contents of a `package.json` file at a directory `dir`.\n * `reload` will optionally skip reading from the cache when set to `true`.\n */\n read(dir: string, { reload }: { reload?: boolean } = {}): Manifest {\n const cachedPackageJson = !reload && this.#cache.get(dir)\n if (cachedPackageJson) {\n return cachedPackageJson\n }\n\n const filename = resolve(dir, 'package.json')\n\n const fail = (err: ErrorCauseObject) =>\n error('Could not read package.json file', err, this.read)\n\n const cachedError = !reload && this.#errCache.get(dir)\n if (cachedError) {\n throw fail(cachedError)\n }\n\n try {\n const res: Manifest = asManifest(\n parse(readFileSync(filename, { encoding: 'utf8' })),\n )\n this.#cache.set(dir, res)\n this.#pathCache.set(res, dir)\n return res\n } catch (err) {\n const ec: ErrorCauseObject = {\n path: filename,\n cause: err as Error,\n }\n this.#errCache.set(dir, ec)\n throw fail(ec)\n }\n }\n\n write(dir: string, manifest: Manifest): void {\n const filename = resolve(dir, 'package.json')\n\n try {\n // This assumes kIndent and kNewline are already present on the manifest because we would\n // only write a package.json after reading it which will set those properties.\n writeFileSync(filename, stringify(manifest))\n this.#cache.set(dir, manifest)\n this.#pathCache.set(manifest, dir)\n } catch (err) {\n // If there was an error writing to this package.json then also delete it from our cache\n // just in case a future read would get stale data.\n this.#cache.delete(dir)\n this.#pathCache.delete(manifest)\n throw error(\n 'Could not write package.json file',\n {\n path: filename,\n cause: err as Error,\n },\n this.write,\n )\n }\n }\n\n save(manifest: Manifest): void {\n const dir = this.#pathCache.get(manifest)\n if (!dir) {\n throw error(\n 'Could not save manifest',\n {\n manifest,\n },\n this.save,\n )\n }\n this.write(dir, manifest)\n }\n}\n", "/**\n * Copyright 2017 Kat Marchán\n * Copyright npm, Inc.\n * Copyright 2023 Isaac Z. Schlueter\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n * ---\n *\n * 'polite-json' is a fork of 'json-parse-even-better-errors',\n * extended and distributed under the terms of the MIT license\n * above.\n *\n * 'json-parse-even-better-errors' is a fork of\n * 'json-parse-better-errors' by Kat Marchán, extended and\n * distributed under the terms of the MIT license above.\n */\n\n// version specific\n/* c8 ignore start */\nconst hexify = (s: string) =>\n Array.from(s)\n .map(\n c => '0x' + c.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')\n )\n .join('')\n/* c8 ignore stop */\n\ntype ParseErrorMeta = {\n message: string\n position: number\n}\nconst parseError = (e: Error, txt: string, context: number): ParseErrorMeta => {\n if (!txt) {\n return {\n message: e.message + ' while parsing empty string',\n position: 0,\n }\n }\n const badToken = e.message.match(/^Unexpected (?:token (.*?))?/i)\n const atPos = e.message.match(/at positions? (\\d+)/)\n\n // version specific\n /* c8 ignore start */\n const errIdx = /^Unexpected end of JSON|Unterminated string in JSON/i.test(\n e.message\n )\n ? txt.length - 1\n : atPos && atPos[1]\n ? +atPos[1]\n : /is not valid JSON$/.test(e.message)\n ? 0\n : null\n\n const msg =\n badToken && badToken[1]\n ? e.message.replace(\n /^Unexpected token ./,\n `Unexpected token ${JSON.stringify(badToken[1])} (${hexify(\n badToken[1]\n )})`\n )\n : e.message\n /* c8 ignore stop */\n\n if (errIdx !== null && errIdx !== undefined) {\n const start = errIdx <= context ? 0 : errIdx - context\n\n const end = errIdx + context >= txt.length ? txt.length : errIdx + context\n\n const slice =\n (start === 0 ? '' : '...') +\n txt.slice(start, end) +\n (end === txt.length ? '' : '...')\n\n const near = txt === slice ? '' : 'near '\n\n return {\n message: msg + ` while parsing ${near}${JSON.stringify(slice)}`,\n position: errIdx,\n }\n } else {\n return {\n message: msg + ` while parsing '${txt.slice(0, context * 2)}'`,\n position: 0,\n }\n }\n}\n\nexport class JSONParseError extends SyntaxError {\n code: 'EJSONPARSE'\n cause: Error\n position: number\n constructor(\n er: Error,\n txt: string,\n context: number = 20,\n caller?: Function | ((...a: any[]) => any)\n ) {\n const { message, position } = parseError(er, txt, context)\n super(message)\n this.cause = er\n this.position = position\n this.code = 'EJSONPARSE'\n Error.captureStackTrace(this, caller || this.constructor)\n }\n get name() {\n return this.constructor.name\n }\n set name(_) {}\n get [Symbol.toStringTag]() {\n return this.constructor.name\n }\n}\n\nexport const kIndent = Symbol.for('indent')\nexport const kNewline = Symbol.for('newline')\n// only respect indentation if we got a line break, otherwise squash it\n// things other than objects and arrays aren't indented, so ignore those\n// Important: in both of these regexps, the $1 capture group is the newline\n// or undefined, and the $2 capture group is the indent, or undefined.\nconst formatRE = /^\\s*[{\\[]((?:\\r?\\n)+)([\\s\\t]*)/\nconst emptyRE = /^(?:\\{\\}|\\[\\])((?:\\r?\\n)+)?$/\n\nexport type Reviver = (this: any, key: string, value: any) => any\nexport type Replacer =\n | ((this: any, key: string, value: any) => any)\n | (string | number)[]\n | null\nexport type Scalar = string | number | null\nexport type JSONResult =\n | {\n [k: string]: JSONResult\n [kIndent]?: string\n [kNewline]?: string\n }\n | (JSONResult[] & { [kIndent]?: string; [kNewline]?: string })\n | Scalar\n\nexport const parse = (\n txt: string | Buffer,\n reviver?: Reviver | null,\n context?: number\n): JSONResult => {\n const parseText = stripBOM(String(txt))\n if (!reviver) reviver = undefined\n context = context || 20\n try {\n // get the indentation so that we can save it back nicely\n // if the file starts with {\" then we have an indent of '', ie, none\n // otherwise, pick the indentation of the next line after the first \\n\n // If the pattern doesn't match, then it means no indentation.\n // JSON.stringify ignores symbols, so this is reasonably safe.\n // if the string is '{}' or '[]', then use the default 2-space indent.\n const [, newline = '\\n', indent = ' '] = parseText.match(emptyRE) ||\n parseText.match(formatRE) || [, '', '']\n\n const result = JSON.parse(parseText, reviver)\n if (result && typeof result === 'object') {\n result[kNewline] = newline\n result[kIndent] = indent\n }\n return result\n } catch (e) {\n if (typeof txt !== 'string' && !Buffer.isBuffer(txt)) {\n const isEmptyArray =\n Array.isArray(txt) && (txt as Array<any>).length === 0\n throw Object.assign(\n new TypeError(\n `Cannot parse ${isEmptyArray ? 'an empty array' : String(txt)}`\n ),\n {\n code: 'EJSONPARSE',\n systemError: e,\n }\n )\n }\n\n throw new JSONParseError(e as Error, parseText, context, parse)\n }\n}\n\nexport const parseNoExceptions = (txt: string | Buffer, reviver?: Reviver) => {\n try {\n return JSON.parse(stripBOM(String(txt)), reviver)\n } catch (e) {}\n}\n\n// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n// because the buffer-to-string conversion in `fs.readFileSync()`\n// translates it to FEFF, the UTF-16 BOM.\nconst stripBOM = (txt: string) => String(txt).replace(/^\\uFEFF/, '')\n\nexport const stringify = (\n obj: any,\n replacer?: Replacer,\n indent?: string | number\n) => {\n const space = indent === undefined ? obj[kIndent] : indent\n // TS is so weird with parameter overloads\n const res =\n /* c8 ignore start */\n typeof replacer === 'function'\n ? JSON.stringify(obj, replacer, space)\n : JSON.stringify(obj, replacer, space)\n /* c8 ignore stop */\n const nl = obj[kNewline] || '\\n'\n return space ? (nl === '\\n' ? res : res.split('\\n').join(nl)) + nl : res\n}\n", "import { error } from '@vltpkg/error-cause'\nimport {\n ChildProcess,\n IOType,\n spawn,\n SpawnOptions,\n StdioOptions,\n} from 'child_process'\n\nconst isPipe = (\n stdio:\n | Exclude<StdioOptions, IOType>[number]\n | StdioOptions = 'pipe',\n fd: number,\n): stdio is IOTypePipe =>\n stdio === 'pipe' || stdio === 'overlapped' || stdio === null ? true\n : Array.isArray(stdio) ? isPipe(stdio[fd], fd)\n : false\n\nexport type IOTypeNoPipe = Exclude<IOType, IOTypePipe>\nexport type IOTypePipe = 'overlapped' | 'pipe' | null | undefined\nexport type PromiseSpawnOptions = SpawnOptions & {\n stdioString?: boolean\n acceptFail?: boolean\n}\nexport type PromiseSpawnOptionsString = PromiseSpawnOptions & {\n stdioString?: true\n}\nexport type PromiseSpawnOptionsBuffer = PromiseSpawnOptions & {\n stdioString: false\n}\nexport type PromiseSpawnOptionsStdin = PromiseSpawnOptions & {\n stdio?:\n | Exclude<IOTypePipe, null>\n | [\n stdin?: IOTypePipe,\n stdout?: Exclude<StdioOptions, IOType>[number],\n stderr?: Exclude<StdioOptions, IOType>[number],\n ]\n}\nexport type PromiseSpawnOptionsNoStdin = PromiseSpawnOptions & {\n stdio:\n | IOTypeNoPipe\n | IOTypeNoPipe[]\n | [\n stdin: IOTypeNoPipe | number,\n stdout?: Exclude<StdioOptions, IOType>[number],\n stderr?: Exclude<StdioOptions, IOType>[number],\n ]\n}\nexport type PromiseSpawnOptionsStdout = PromiseSpawnOptions & {\n stdio?:\n | Exclude<IOTypePipe, null>\n | [\n stdin: Exclude<StdioOptions, IOType>[number] | undefined,\n stdout?: IOTypePipe,\n stderr?: Exclude<StdioOptions, IOType>[number],\n ]\n}\nexport type PromiseSpawnOptionsStdoutString =\n PromiseSpawnOptionsStdout & {\n stdioString?: true\n }\nexport type PromiseSpawnOptionsStdoutBuffer =\n PromiseSpawnOptionsStdout & {\n stdioString: false\n }\nexport type PromiseSpawnOptionsNoStdout = PromiseSpawnOptions & {\n stdio:\n | IOTypeNoPipe\n | IOTypeNoPipe[]\n | [\n stdin: Exclude<StdioOptions, IOType>[number] | undefined,\n stdout?: IOTypeNoPipe,\n stderr?: Exclude<StdioOptions, IOType>[number],\n ]\n}\n/* c8 ignore start - weird windows coverage bug */\nexport type PromiseSpawnOptionsStderr = PromiseSpawnOptions & {\n stdio?:\n | Exclude<IOTypePipe, null>\n | [\n stdin: Exclude<StdioOptions, IOType>[number] | undefined,\n stdout: Exclude<StdioOptions, IOType>[number] | undefined,\n stderr?: IOTypePipe,\n ]\n}\n/* c8 ignore stop */\nexport type PromiseSpawnOptionsStderrString =\n PromiseSpawnOptionsStderr & {\n stdioString?: true\n }\nexport type PromiseSpawnOptionsStderrBuffer =\n PromiseSpawnOptionsStderr & {\n stdioString: false\n }\nexport type PromiseSpawnOptionsNoStderr = PromiseSpawnOptions & {\n stdio:\n | IOTypeNoPipe\n | IOTypeNoPipe[]\n | [\n stdin: Exclude<StdioOptions, IOType>[number] | undefined,\n stdout: Exclude<StdioOptions, IOType>[number] | undefined,\n stderr: IOTypeNoPipe,\n ]\n}\n\nfunction stdioResult<O extends PromiseSpawnOptions>(\n stdout: Buffer[],\n stderr: Buffer[],\n o: O,\n): {\n stdout: SpawnResultByOptions<O>['stdout']\n stderr: SpawnResultByOptions<O>['stderr']\n} {\n return {\n stdout: (!isPipe(o.stdio, 1) ? null\n : o.stdioString !== false ?\n Buffer.concat(stdout).toString().trim()\n : Buffer.concat(stdout)) as SpawnResultByOptions<O>['stdout'],\n stderr: (!isPipe(o.stdio, 2) ? null\n : o.stdioString !== false ?\n Buffer.concat(stderr).toString().trim()\n : Buffer.concat(stderr)) as SpawnResultByOptions<O>['stderr'],\n }\n}\n\nexport type SpawnResult = {\n command: string\n args: string[]\n cwd: string\n status: number | null\n signal: NodeJS.Signals | null\n stdout: Buffer | string | null\n stderr: Buffer | string | null\n}\nexport type SpawnResultString = SpawnResult & {\n stdout: string | null\n stderr: string | null\n}\nexport type SpawnResultBuffer = SpawnResult & {\n stdout: Buffer | null\n stderr: Buffer | null\n}\nexport type SpawnResultStdout = SpawnResult & {\n stdout: Buffer | string\n}\nexport type SpawnResultStdoutString = SpawnResultString & {\n stdout: string\n}\nexport type SpawnResultStdoutBuffer = SpawnResultBuffer & {\n stdout: Buffer\n}\nexport type SpawnResultNoStdout = SpawnResult & {\n stdout: null\n}\nexport type SpawnResultStderr = SpawnResult & {\n stderr: Buffer | string\n}\nexport type SpawnResultStderrString = SpawnResultString & {\n stderr: string\n}\nexport type SpawnResultStderrBuffer = SpawnResultBuffer & {\n stderr: Buffer\n}\nexport type SpawnResultNoStderr = SpawnResult & {\n stderr: null\n}\n\nexport type SpawnResultNoStdio = SpawnResult & {\n stderr: null\n stdout: null\n}\nexport type SpawnResultStdioStrings = SpawnResult & {\n stdout: string\n stderr: string\n}\nexport type SpawnResultStdioBuffers = SpawnResult & {\n stdout: Buffer\n stderr: Buffer\n}\n\nexport type SpawnResultByOptions<T extends PromiseSpawnOptions> =\n SpawnResult & {\n stdout: T extends PromiseSpawnOptionsNoStdout ? null\n : T extends PromiseSpawnOptionsStdoutBuffer ? Buffer\n : T extends PromiseSpawnOptionsStdoutString ? string\n : T extends PromiseSpawnOptionsBuffer ? Buffer | null\n : T extends PromiseSpawnOptionsString ? string | null\n : Buffer | string | null\n stderr: T extends PromiseSpawnOptionsNoStderr ? null\n : T extends PromiseSpawnOptionsStderrBuffer ? Buffer\n : T extends PromiseSpawnOptionsStderrString ? string\n : T extends PromiseSpawnOptionsBuffer ? Buffer | null\n : T extends PromiseSpawnOptionsString ? string | null\n : Buffer | string | null\n }\n\nexport type ChildProcessByOptions<T extends PromiseSpawnOptions> =\n ChildProcess & {\n stdin: T extends PromiseSpawnOptionsNoStdin ? null\n : Exclude<ChildProcess['stdin'], null>\n stdout: T extends PromiseSpawnOptionsNoStdout ? null\n : Exclude<ChildProcess['stdout'], null>\n stderr: T extends PromiseSpawnOptionsNoStderr ? null\n : Exclude<ChildProcess['stderr'], null>\n }\n\n/**\n * Subtype of Promise returned by {@link spawnPromise}.\n *\n * Resolution value is inferred from the provided options.\n */\nexport class SpawnPromise<\n O extends PromiseSpawnOptions,\n T extends object = object,\n> extends Promise<SpawnResultByOptions<O> & T> {\n [Symbol.toStringTag] = 'SpawnPromise'\n\n /** The spawned process this promise references */\n process!: ChildProcessByOptions<O>\n\n /** Expose the child process stdin, if available */\n stdin!: ChildProcessByOptions<O>['stdin']\n\n /**\n * Set static `Symbol.species` back to the base Promise class so that\n * v8 doesn't get confused by the changed constructor signature.\n */\n static get [Symbol.species]() {\n return Promise\n }\n\n constructor(\n command: string,\n args: string[],\n opts: O,\n extra: T = {} as T,\n ) {\n let proc!: ChildProcessByOptions<O>\n super((res, rej) => {\n proc = spawn(command, args, opts) as ChildProcessByOptions<O>\n const stdout: Buffer[] = []\n const stderr: Buffer[] = []\n const reject = (er: Error) =>\n rej(\n error('command failed', {\n command,\n args,\n cwd: opts.cwd ?? process.cwd(),\n ...stdioResult(stdout, stderr, opts),\n ...extra,\n cause: er,\n }),\n )\n proc.on('error', reject)\n if (proc.stdout) {\n proc.stdout\n .on('data', c => stdout.push(c))\n .on('error', er => reject(er))\n }\n if (proc.stderr) {\n proc.stderr\n .on('data', c => stderr.push(c))\n .on('error', er => reject(er))\n }\n proc.on('close', (status, signal) => {\n const result = {\n command,\n args,\n cwd: opts.cwd ?? process.cwd(),\n /* c8 ignore next 2 - because windows */\n status: status ?? null,\n signal: signal ?? null,\n ...stdioResult(stdout, stderr, opts),\n ...extra,\n } as SpawnResultByOptions<O> & T\n if ((status || signal) && !opts.acceptFail)\n rej(error('command failed', result))\n else res(result)\n })\n })\n this.process = proc\n this.stdin = proc.stdin\n }\n}\n\n/**\n * Spawn the specified command, and return a promise that resolves when\n * the process closes or has an error.\n */\nexport function promiseSpawn<\n O extends PromiseSpawnOptions = PromiseSpawnOptionsStderrString &\n PromiseSpawnOptionsStdoutString,\n E extends object = object,\n>(command: string, args: string[], opts = {} as O, extra = {} as E) {\n return new SpawnPromise<O, E>(command, args, opts, extra)\n}\n", "import {\n ChildProcessByStdio,\n SendHandle,\n Serializable,\n spawn as nodeSpawn,\n SpawnOptions,\n ChildProcess,\n} from 'child_process'\nimport crossSpawn from 'cross-spawn'\nimport { onExit } from 'signal-exit'\nimport { proxySignals } from './proxy-signals.js'\nimport { watchdog } from './watchdog.js'\n\n/* c8 ignore start */\nconst spawn = process?.platform === 'win32' ? crossSpawn : nodeSpawn\n/* c8 ignore stop */\n\n/**\n * The signature for the cleanup method.\n *\n * Arguments indicate the exit status of the child process.\n *\n * If a Promise is returned, then the process is not terminated\n * until it resolves, and the resolution value is treated as the\n * exit status (if a number) or signal exit (if a signal string).\n *\n * If `undefined` is returned, then no change is made, and the parent\n * exits in the same way that the child exited.\n *\n * If boolean `false` is returned, then the parent's exit is canceled.\n *\n * If a number is returned, then the parent process exits with the number\n * as its exitCode.\n *\n * If a signal string is returned, then the parent process is killed with\n * the same signal that caused the child to exit.\n */\nexport type Cleanup = (\n code: number | null,\n signal: null | NodeJS.Signals,\n processInfo: {\n watchdogPid?: ChildProcess['pid']\n },\n) =>\n | void\n | undefined\n | number\n | NodeJS.Signals\n | false\n | Promise<void | undefined | number | NodeJS.Signals | false>\n\nexport type FgArgs =\n | [program: string | [cmd: string, ...args: string[]], cleanup?: Cleanup]\n | [\n program: [cmd: string, ...args: string[]],\n opts?: SpawnOptions,\n cleanup?: Cleanup,\n ]\n | [program: string, cleanup?: Cleanup]\n | [program: string, opts?: SpawnOptions, cleanup?: Cleanup]\n | [program: string, args?: string[], cleanup?: Cleanup]\n | [\n program: string,\n args?: string[],\n opts?: SpawnOptions,\n cleanup?: Cleanup,\n ]\n\n/**\n * Normalizes the arguments passed to `foregroundChild`.\n *\n * Exposed for testing.\n *\n * @internal\n */\nexport const normalizeFgArgs = (\n fgArgs: FgArgs,\n): [\n program: string,\n args: string[],\n spawnOpts: SpawnOptions,\n cleanup: Cleanup,\n] => {\n let [program, args = [], spawnOpts = {}, cleanup = () => {}] = fgArgs\n if (typeof args === 'function') {\n cleanup = args\n spawnOpts = {}\n args = []\n } else if (!!args && typeof args === 'object' && !Array.isArray(args)) {\n if (typeof spawnOpts === 'function') cleanup = spawnOpts\n spawnOpts = args\n args = []\n } else if (typeof spawnOpts === 'function') {\n cleanup = spawnOpts\n spawnOpts = {}\n }\n if (Array.isArray(program)) {\n const [pp, ...pa] = program\n program = pp\n args = pa\n }\n return [program, args, { ...spawnOpts }, cleanup]\n}\n\n/**\n * Spawn the specified program as a \"foreground\" process, or at least as\n * close as is possible given node's lack of exec-without-fork.\n *\n * Cleanup method may be used to modify or ignore the result of the child's\n * exit code or signal. If cleanup returns undefined (or a Promise that\n * resolves to undefined), then the parent will exit in the same way that\n * the child did.\n *\n * Return boolean `false` to prevent the parent's exit entirely.\n */\nexport function foregroundChild(\n cmd: string | [cmd: string, ...args: string[]],\n cleanup?: Cleanup,\n): ChildProcessByStdio<null, null, null>\nexport function foregroundChild(\n program: string,\n args?: string[],\n cleanup?: Cleanup,\n): ChildProcessByStdio<null, null, null>\nexport function foregroundChild(\n program: string,\n spawnOpts?: SpawnOptions,\n cleanup?: Cleanup,\n): ChildProcessByStdio<null, null, null>\nexport function foregroundChild(\n program: string,\n args?: string[],\n spawnOpts?: SpawnOptions,\n cleanup?: Cleanup,\n): ChildProcessByStdio<null, null, null>\nexport function foregroundChild(\n ...fgArgs: FgArgs\n): ChildProcessByStdio<null, null, null> {\n const [program, args, spawnOpts, cleanup] = normalizeFgArgs(fgArgs)\n\n spawnOpts.stdio = [0, 1, 2]\n if (process.send) {\n spawnOpts.stdio.push('ipc')\n }\n\n const child = spawn(program, args, spawnOpts) as ChildProcessByStdio<\n null,\n null,\n null\n >\n\n const childHangup = () => {\n try {\n child.kill('SIGHUP')\n\n /* c8 ignore start */\n } catch (_) {\n // SIGHUP is weird on windows\n child.kill('SIGTERM')\n }\n /* c8 ignore stop */\n }\n const removeOnExit = onExit(childHangup)\n\n proxySignals(child)\n const dog = watchdog(child)\n\n let done = false\n child.on('close', async (code, signal) => {\n /* c8 ignore start */\n if (done) return\n /* c8 ignore stop */\n done = true\n const result = cleanup(code, signal, {\n watchdogPid: dog.pid,\n })\n const res = isPromise(result) ? await result : result\n removeOnExit()\n\n if (res === false) return\n else if (typeof res === 'string') {\n signal = res\n code = null\n } else if (typeof res === 'number') {\n code = res\n signal = null\n }\n\n if (signal) {\n // If there is nothing else keeping the event loop alive,\n // then there's a race between a graceful exit and getting\n // the signal to this process. Put this timeout here to\n // make sure we're still alive to get the signal, and thus\n // exit with the intended signal code.\n /* istanbul ignore next */\n setTimeout(() => {}, 2000)\n try {\n process.kill(process.pid, signal)\n /* c8 ignore start */\n } catch (_) {\n process.kill(process.pid, 'SIGTERM')\n }\n /* c8 ignore stop */\n } else {\n process.exit(code || 0)\n }\n })\n\n if (process.send) {\n process.removeAllListeners('message')\n\n child.on('message', (message, sendHandle) => {\n process.send?.(message, sendHandle)\n })\n\n process.on('message', (message, sendHandle) => {\n child.send(\n message as Serializable,\n sendHandle as SendHandle | undefined,\n )\n })\n }\n\n return child\n}\n\nconst isPromise = (o: any): o is Promise<any> =>\n !!o && typeof o === 'object' && typeof o.then === 'function'\n", "/**\n * This is not the set of all possible signals.\n *\n * It IS, however, the set of all signals that trigger\n * an exit on either Linux or BSD systems. Linux is a\n * superset of the signal names supported on BSD, and\n * the unknown signals just fail to register, so we can\n * catch that easily enough.\n *\n * Windows signals are a different set, since there are\n * signals that terminate Windows processes, but don't\n * terminate (or don't even exist) on Posix systems.\n *\n * Don't bother with SIGKILL. It's uncatchable, which\n * means that we can't fire any callbacks anyway.\n *\n * If a user does happen to register a handler on a non-\n * fatal signal like SIGWINCH or something, and then\n * exit, it'll end up firing `process.emit('exit')`, so\n * the handler will be fired anyway.\n *\n * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised\n * artificially, inherently leave the process in a\n * state from which it is not safe to try and enter JS\n * listeners.\n */\nexport const signals: NodeJS.Signals[] = []\nsignals.push('SIGHUP', 'SIGINT', 'SIGTERM')\n\nif (process.platform !== 'win32') {\n signals.push(\n 'SIGALRM',\n 'SIGABRT',\n 'SIGVTALRM',\n 'SIGXCPU',\n 'SIGXFSZ',\n 'SIGUSR2',\n 'SIGTRAP',\n 'SIGSYS',\n 'SIGQUIT',\n 'SIGIOT'\n // should detect profiler and enable/disable accordingly.\n // see #21\n // 'SIGPROF'\n )\n}\n\nif (process.platform === 'linux') {\n signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT')\n}\n", "// Note: since nyc uses this module to output coverage, any lines\n// that are in the direct sync flow of nyc's outputCoverage are\n// ignored, since we can never get coverage for them.\n// grab a reference to node's real process object right away\nimport { signals } from './signals.js'\nexport { signals }\n\n// just a loosened process type so we can do some evil things\ntype ProcessRE = NodeJS.Process & {\n reallyExit: (code?: number | undefined | null) => any\n emit: (ev: string, ...a: any[]) => any\n}\n\nconst processOk = (process: any): process is ProcessRE =>\n !!process &&\n typeof process === 'object' &&\n typeof process.removeListener === 'function' &&\n typeof process.emit === 'function' &&\n typeof process.reallyExit === 'function' &&\n typeof process.listeners === 'function' &&\n typeof process.kill === 'function' &&\n typeof process.pid === 'number' &&\n typeof process.on === 'function'\n\nconst kExitEmitter = Symbol.for('signal-exit emitter')\nconst global: typeof globalThis & { [kExitEmitter]?: Emitter } = globalThis\nconst ObjectDefineProperty = Object.defineProperty.bind(Object)\n\n/**\n * A function that takes an exit code and signal as arguments\n *\n * In the case of signal exits *only*, a return value of true\n * will indicate that the signal is being handled, and we should\n * not synthetically exit with the signal we received. Regardless\n * of the handler return value, the handler is unloaded when an\n * otherwise fatal signal is received, so you get exactly 1 shot\n * at it, unless you add another onExit handler at that point.\n *\n * In the case of numeric code exits, we may already have committed\n * to exiting the process, for example via a fatal exception or\n * unhandled promise rejection, so it is impossible to stop safely.\n */\nexport type Handler = (\n code: number | null | undefined,\n signal: NodeJS.Signals | null\n) => true | void\ntype ExitEvent = 'afterExit' | 'exit'\ntype Emitted = { [k in ExitEvent]: boolean }\ntype Listeners = { [k in ExitEvent]: Handler[] }\n\n// teeny special purpose ee\nclass Emitter {\n emitted: Emitted = {\n afterExit: false,\n exit: false,\n }\n\n listeners: Listeners = {\n afterExit: [],\n exit: [],\n }\n\n count: number = 0\n id: number = Math.random()\n\n constructor() {\n if (global[kExitEmitter]) {\n return global[kExitEmitter]\n }\n ObjectDefineProperty(global, kExitEmitter, {\n value: this,\n writable: false,\n enumerable: false,\n configurable: false,\n })\n }\n\n on(ev: ExitEvent, fn: Handler) {\n this.listeners[ev].push(fn)\n }\n\n removeListener(ev: ExitEvent, fn: Handler) {\n const list = this.listeners[ev]\n const i = list.indexOf(fn)\n /* c8 ignore start */\n if (i === -1) {\n return\n }\n /* c8 ignore stop */\n if (i === 0 && list.length === 1) {\n list.length = 0\n } else {\n list.splice(i, 1)\n }\n }\n\n emit(\n ev: ExitEvent,\n code: number | null | undefined,\n signal: NodeJS.Signals | null\n ): boolean {\n if (this.emitted[ev]) {\n return false\n }\n this.emitted[ev] = true\n let ret: boolean = false\n for (const fn of this.listeners[ev]) {\n ret = fn(code, signal) === true || ret\n }\n if (ev === 'exit') {\n ret = this.emit('afterExit', code, signal) || ret\n }\n return ret\n }\n}\n\nabstract class SignalExitBase {\n abstract onExit(cb: Handler, opts?: { alwaysLast?: boolean }): () => void\n abstract load(): void\n abstract unload(): void\n}\n\nconst signalExitWrap = <T extends SignalExitBase>(handler: T) => {\n return {\n onExit(cb: Handler, opts?: { alwaysLast?: boolean }) {\n return handler.onExit(cb, opts)\n },\n load() {\n return handler.load()\n },\n unload() {\n return handler.unload()\n },\n }\n}\n\nclass SignalExitFallback extends SignalExitBase {\n onExit() {\n return () => {}\n }\n load() {}\n unload() {}\n}\n\nclass SignalExit extends SignalExitBase {\n // \"SIGHUP\" throws an `ENOSYS` error on Windows,\n // so use a supported signal instead\n /* c8 ignore start */\n #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP'\n /* c8 ignore stop */\n #emitter = new Emitter()\n #process: ProcessRE\n #originalProcessEmit: ProcessRE['emit']\n #originalProcessReallyExit: ProcessRE['reallyExit']\n\n #sigListeners: { [k in NodeJS.Signals]?: () => void } = {}\n #loaded: boolean = false\n\n constructor(process: ProcessRE) {\n super()\n this.#process = process\n // { <signal>: <listener fn>, ... }\n this.#sigListeners = {}\n for (const sig of signals) {\n this.#sigListeners[sig] = () => {\n // If there are no other listeners, an exit is coming!\n // Simplest way: remove us and then re-send the signal.\n // We know that this will kill the process, so we can\n // safely emit now.\n const listeners = this.#process.listeners(sig)\n let { count } = this.#emitter\n // This is a workaround for the fact that signal-exit v3 and signal\n // exit v4 are not aware of each other, and each will attempt to let\n // the other handle it, so neither of them do. To correct this, we\n // detect if we're the only handler *except* for previous versions\n // of signal-exit, and increment by the count of listeners it has\n // created.\n /* c8 ignore start */\n const p = process as unknown as {\n __signal_exit_emitter__?: { count: number }\n }\n if (\n typeof p.__signal_exit_emitter__ === 'object' &&\n typeof p.__signal_exit_emitter__.count === 'number'\n ) {\n count += p.__signal_exit_emitter__.count\n }\n /* c8 ignore stop */\n if (listeners.length === count) {\n this.unload()\n const ret = this.#emitter.emit('exit', null, sig)\n /* c8 ignore start */\n const s = sig === 'SIGHUP' ? this.#hupSig : sig\n if (!ret) process.kill(process.pid, s)\n /* c8 ignore stop */\n }\n }\n }\n\n this.#originalProcessReallyExit = process.reallyExit\n this.#originalProcessEmit = process.emit\n }\n\n onExit(cb: Handler, opts?: { alwaysLast?: boolean }) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return () => {}\n }\n /* c8 ignore stop */\n\n if (this.#loaded === false) {\n this.load()\n }\n\n const ev = opts?.alwaysLast ? 'afterExit' : 'exit'\n this.#emitter.on(ev, cb)\n return () => {\n this.#emitter.removeListener(ev, cb)\n if (\n this.#emitter.listeners['exit'].length === 0 &&\n this.#emitter.listeners['afterExit'].length === 0\n ) {\n this.unload()\n }\n }\n }\n\n load() {\n if (this.#loaded) {\n return\n }\n this.#loaded = true\n\n // This is the number of onSignalExit's that are in play.\n // It's important so that we can count the correct number of\n // listeners on signals, and don't wait for the other one to\n // handle it instead of us.\n this.#emitter.count += 1\n\n for (const sig of signals) {\n try {\n const fn = this.#sigListeners[sig]\n if (fn) this.#process.on(sig, fn)\n } catch (_) {}\n }\n\n this.#process.emit = (ev: string, ...a: any[]) => {\n return this.#processEmit(ev, ...a)\n }\n this.#process.reallyExit = (code?: number | null | undefined) => {\n return this.#processReallyExit(code)\n }\n }\n\n unload() {\n if (!this.#loaded) {\n return\n }\n this.#loaded = false\n\n signals.forEach(sig => {\n const listener = this.#sigListeners[sig]\n /* c8 ignore start */\n if (!listener) {\n throw new Error('Listener not defined for signal: ' + sig)\n }\n /* c8 ignore stop */\n try {\n this.#process.removeListener(sig, listener)\n /* c8 ignore start */\n } catch (_) {}\n /* c8 ignore stop */\n })\n this.#process.emit = this.#originalProcessEmit\n this.#process.reallyExit = this.#originalProcessReallyExit\n this.#emitter.count -= 1\n }\n\n #processReallyExit(code?: number | null | undefined) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return 0\n }\n this.#process.exitCode = code || 0\n /* c8 ignore stop */\n\n this.#emitter.emit('exit', this.#process.exitCode, null)\n return this.#originalProcessReallyExit.call(\n this.#process,\n this.#process.exitCode\n )\n }\n\n #processEmit(ev: string, ...args: any[]): any {\n const og = this.#originalProcessEmit\n if (ev === 'exit' && processOk(this.#process)) {\n if (typeof args[0] === 'number') {\n this.#process.exitCode = args[0]\n /* c8 ignore start */\n }\n /* c8 ignore start */\n const ret = og.call(this.#process, ev, ...args)\n /* c8 ignore start */\n this.#emitter.emit('exit', this.#process.exitCode, null)\n /* c8 ignore stop */\n return ret\n } else {\n return og.call(this.#process, ev, ...args)\n }\n }\n}\n\nconst process = globalThis.process\n// wrap so that we call the method on the actual handler, without\n// exporting it directly.\nexport const {\n /**\n * Called when the process is exiting, whether via signal, explicit\n * exit, or running out of stuff to do.\n *\n * If the global process object is not suitable for instrumentation,\n * then this will be a no-op.\n *\n * Returns a function that may be used to unload signal-exit.\n */\n onExit,\n\n /**\n * Load the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\n load,\n\n /**\n * Unload the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\n unload,\n} = signalExitWrap(\n processOk(process) ? new SignalExit(process) : new SignalExitFallback()\n)\n", "import constants from 'node:constants'\nexport const allSignals =\n // this is the full list of signals that Node will let us do anything with\n Object.keys(constants).filter(\n k =>\n k.startsWith('SIG') &&\n // https://github.com/tapjs/signal-exit/issues/21\n k !== 'SIGPROF' &&\n // no sense trying to listen for SIGKILL, it's impossible\n k !== 'SIGKILL',\n ) as NodeJS.Signals[]\n\n// These are some obscure signals that are reported by kill -l\n// on macOS, Linux, or Windows, but which don't have any mapping\n// in Node.js. No sense trying if they're just going to throw\n// every time on every platform.\n//\n// 'SIGEMT',\n// 'SIGLOST',\n// 'SIGPOLL',\n// 'SIGRTMAX',\n// 'SIGRTMAX-1',\n// 'SIGRTMAX-10',\n// 'SIGRTMAX-11',\n// 'SIGRTMAX-12',\n// 'SIGRTMAX-13',\n// 'SIGRTMAX-14',\n// 'SIGRTMAX-15',\n// 'SIGRTMAX-2',\n// 'SIGRTMAX-3',\n// 'SIGRTMAX-4',\n// 'SIGRTMAX-5',\n// 'SIGRTMAX-6',\n// 'SIGRTMAX-7',\n// 'SIGRTMAX-8',\n// 'SIGRTMAX-9',\n// 'SIGRTMIN',\n// 'SIGRTMIN+1',\n// 'SIGRTMIN+10',\n// 'SIGRTMIN+11',\n// 'SIGRTMIN+12',\n// 'SIGRTMIN+13',\n// 'SIGRTMIN+14',\n// 'SIGRTMIN+15',\n// 'SIGRTMIN+16',\n// 'SIGRTMIN+2',\n// 'SIGRTMIN+3',\n// 'SIGRTMIN+4',\n// 'SIGRTMIN+5',\n// 'SIGRTMIN+6',\n// 'SIGRTMIN+7',\n// 'SIGRTMIN+8',\n// 'SIGRTMIN+9',\n// 'SIGSTKFLT',\n// 'SIGUNUSED',\n", "import { type ChildProcess } from 'child_process'\nimport { allSignals } from './all-signals.js'\n\n/**\n * Starts forwarding signals to `child` through `parent`.\n */\nexport const proxySignals = (child: ChildProcess) => {\n const listeners = new Map()\n\n for (const sig of allSignals) {\n const listener = () => {\n // some signals can only be received, not sent\n try {\n child.kill(sig)\n /* c8 ignore start */\n } catch (_) {}\n /* c8 ignore stop */\n }\n try {\n // if it's a signal this system doesn't recognize, skip it\n process.on(sig, listener)\n listeners.set(sig, listener)\n /* c8 ignore start */\n } catch (_) {}\n /* c8 ignore stop */\n }\n\n const unproxy = () => {\n for (const [sig, listener] of listeners) {\n process.removeListener(sig, listener)\n }\n }\n child.on('exit', unproxy)\n return unproxy\n}\n", "// this spawns a child process that listens for SIGHUP when the\n// parent process exits, and after 200ms, sends a SIGKILL to the\n// child, in case it did not terminate.\n\nimport { ChildProcess, spawn } from 'child_process'\n\nconst watchdogCode = String.raw`\nconst pid = parseInt(process.argv[1], 10)\nprocess.title = 'node (foreground-child watchdog pid=' + pid + ')'\nif (!isNaN(pid)) {\n let barked = false\n // keepalive\n const interval = setInterval(() => {}, 60000)\n const bark = () => {\n clearInterval(interval)\n if (barked) return\n barked = true\n process.removeListener('SIGHUP', bark)\n setTimeout(() => {\n try {\n process.kill(pid, 'SIGKILL')\n setTimeout(() => process.exit(), 200)\n } catch (_) {}\n }, 500)\n })\n process.on('SIGHUP', bark)\n}\n`\n\n/**\n * Pass in a ChildProcess, and this will spawn a watchdog process that\n * will make sure it exits if the parent does, thus preventing any\n * dangling detached zombie processes.\n *\n * If the child ends before the parent, then the watchdog will terminate.\n */\nexport const watchdog = (child: ChildProcess) => {\n let dogExited = false\n const dog = spawn(\n process.execPath,\n ['-e', watchdogCode, String(child.pid)],\n {\n stdio: 'ignore',\n },\n )\n dog.on('exit', () => (dogExited = true))\n child.on('exit', () => {\n if (!dogExited) dog.kill('SIGKILL')\n })\n return dog\n}\n", "import { error } from '@vltpkg/error-cause'\nimport { PackageJson } from '@vltpkg/package-json'\nimport {\n promiseSpawn,\n PromiseSpawnOptions,\n type SpawnResultNoStdio,\n type SpawnResultStdioStrings,\n} from '@vltpkg/promise-spawn'\nimport { Manifest } from '@vltpkg/types'\nimport { foregroundChild } from 'foreground-child'\nimport { proxySignals } from 'foreground-child/proxy-signals'\nimport { statSync } from 'node:fs'\nimport { delimiter, resolve } from 'node:path'\nimport { walkUp } from 'walk-up-path'\n\n/** map of which node_modules/.bin folders exist */\nconst dotBins = new Map<string, boolean>()\n\n/** Check if a directory exists, and cache result */\nconst dirExists = (p: string) => {\n const cached = dotBins.get(p)\n if (cached !== undefined) return cached\n try {\n const isDir = statSync(p).isDirectory()\n dotBins.set(p, isDir)\n return isDir\n } catch {\n dotBins.set(p, false)\n return false\n }\n}\n\n/**\n * Add all exsting `node_modules/.bin` folders to the PATH that\n * exist between the cwd and the projectRoot, so dependency bins\n * are found, with closer paths higher priority.\n */\nconst addPaths = (\n projectRoot: string,\n cwd: string,\n env: NodeJS.ProcessEnv,\n): NodeJS.ProcessEnv => {\n const { PATH = '' } = env\n const paths = new Set<string>()\n for (const p of walkUp(cwd)) {\n const dotBin = resolve(p, 'node_modules/.bin')\n if (dirExists(dotBin)) paths.add(dotBin)\n if (p === projectRoot) break\n }\n for (const p of PATH.split(delimiter)) {\n /* c8 ignore next - pretty rare to have an empty entry */\n if (p) paths.add(p)\n }\n env.PATH = [...paths].join(delimiter)\n return env\n}\n\n/** options shared by run() and exec() */\nexport type SharedOptions = PromiseSpawnOptions & {\n /** additional arguments to pass to the command */\n args?: string[]\n /** the root of the project, which we don't walk up past */\n projectRoot: string\n\n /** the directory where the package.json lives and the script runs */\n cwd: string\n /**\n * environment variables to set. `process.env` is always included,\n * to omit fields, set them explicitly to undefined.\n *\n * vlt will add some of its own, as well:\n * - npm_lifecycle_event: the event name\n * - npm_lifecycle_script: the command in package.json#scripts\n * - npm_package_json: path to the package.json file\n * - VLT_* envs for all vlt configuration values that are set\n */\n env?: NodeJS.ProcessEnv\n /**\n * the shell to run the script in. If not set, then the default\n * platform-specific shell will be used.\n */\n 'script-shell'?: boolean | string\n}\n\n/**\n * Options for run() and runFG()\n */\nexport type RunOptions = SharedOptions & {\n /** the name of the thing in package.json#scripts */\n arg0: string\n /**\n * pass in a @vltpkg/package-json.PackageJson instance, and\n * it'll be used for reading the package.json file. Optional,\n * may improve performance somewhat.\n */\n packageJson?: PackageJson\n\n /**\n * Pass in a manifest to avoid having to read it at all\n */\n manifest?: Manifest\n\n /**\n * if the script is not defined in package.json#scripts, just ignore it and\n * treat as success. Otherwise, treat as an error. Default false.\n */\n ignoreMissing?: boolean\n\n /**\n * skip the pre/post commands, just run the one specified.\n * This can be used to run JUST the specified script, without any\n * pre/post commands.\n */\n ignorePrePost?: boolean\n}\n\n/**\n * Options for exec() and execFG()\n */\nexport type ExecOptions = SharedOptions & {\n /** the command to execute */\n arg0: string\n}\n\n/**\n * Options for runExec() and runExecFG()\n */\nexport type RunExecOptions = SharedOptions & {\n /**\n * Either the command to be executed, or the event to be run\n */\n arg0: string\n /**\n * pass in a @vltpkg/package-json.PackageJson instance, and\n * it'll be used for reading the package.json file. Optional,\n * may improve performance somewhat.\n */\n packageJson?: PackageJson\n}\n\n/**\n * Run a package.json#scripts event in the background\n */\nexport const run = async (options: RunOptions): Promise<RunResult> =>\n runImpl(options, exec, '')\n\n/**\n * Run a package.json#scripts event in the foreground\n */\nexport const runFG = async (\n options: RunOptions,\n): Promise<RunFGResult> => runImpl(options, execFG, null)\n\n/** Return type of {@link run} */\nexport type RunResult = SpawnResultStdioStrings & {\n pre?: SpawnResultStdioStrings\n post?: SpawnResultStdioStrings\n}\n\n/** Return type of {@link runFG} */\nexport type RunFGResult = SpawnResultNoStdio & {\n pre?: SpawnResultNoStdio\n post?: SpawnResultNoStdio\n}\n\nexport const isRunResult = (v: unknown): v is RunResult =>\n !!v &&\n typeof v === 'object' &&\n !Array.isArray(v) &&\n 'stdout' in v &&\n 'stderr' in v &&\n 'status' in v &&\n 'signal' in v\n\n/**\n * Return type of {@link run} or {@link runFG}, as determined by their base\n * type\n *\n * @internal\n */\nexport type RunImplResult<\n R extends SpawnResultNoStdio | SpawnResultStdioStrings,\n> = R & { pre?: R; post?: R }\n\n/**\n * Internal implementation of run() and runFG(), since they're mostly identical\n */\nconst runImpl = async <\n R extends SpawnResultNoStdio | SpawnResultStdioStrings,\n>(\n options: RunOptions,\n execImpl: (options: ExecOptions) => Promise<R>,\n empty: R['stdout'],\n): Promise<RunImplResult<R>> => {\n const {\n arg0,\n packageJson = new PackageJson(),\n ignoreMissing = false,\n manifest,\n ...execArgs\n } = options\n const pjPath = resolve(options.cwd, 'package.json')\n const pj = manifest ?? packageJson.read(options.cwd)\n const { scripts } = pj\n const command = scripts?.[arg0]\n if (!command) {\n if (ignoreMissing) {\n return {\n command: '',\n /* c8 ignore next */\n args: execArgs.args ?? [],\n cwd: options.cwd,\n status: 0,\n signal: null,\n stdout: empty,\n stderr: empty,\n // `as` to workaround \"could be instantiated with arbitrary type\".\n // it's private and used in 2 places, we know that it isn't.\n } as R\n }\n throw error('Script not defined in package.json', {\n name: arg0,\n cwd: options.cwd,\n args: options.args,\n path: pjPath,\n manifest: pj,\n })\n }\n\n const precommand = !options.ignorePrePost && scripts[`pre${arg0}`]\n const pre =\n precommand ?\n await execImpl({\n arg0: precommand,\n ...execArgs,\n args: [],\n env: {\n ...execArgs.env,\n npm_package_json: pjPath,\n npm_lifecycle_event: `pre${arg0}`,\n npm_lifecycle_script: precommand,\n },\n })\n : undefined\n if (pre && (pre.status || pre.signal)) {\n return pre as RunImplResult<R>\n }\n const result: RunImplResult<R> = await execImpl({\n arg0: command,\n ...execArgs,\n env: {\n ...execArgs.env,\n npm_package_json: pjPath,\n npm_lifecycle_event: arg0,\n npm_lifecycle_script: command,\n },\n })\n result.pre = pre\n if (result.signal || result.status) {\n return result\n }\n\n const postcommand = !options.ignorePrePost && scripts[`post${arg0}`]\n if (!postcommand) return result\n\n const post = await execImpl({\n arg0: postcommand,\n ...execArgs,\n args: [],\n env: {\n ...execArgs.env,\n npm_package_json: pjPath,\n npm_lifecycle_event: `post${arg0}`,\n npm_lifecycle_script: postcommand,\n },\n })\n\n if (post.status || post.signal) {\n const { status, signal } = post\n return Object.assign(result, { post, status, signal })\n }\n result.post = post\n return result\n}\n\n/**\n * Execute an arbitrary command in the background\n */\nexport const exec = async (\n options: ExecOptions,\n): Promise<SpawnResultStdioStrings> => {\n const {\n arg0,\n args = [],\n cwd,\n env = {},\n projectRoot,\n 'script-shell': shell = true,\n ...spawnOptions\n } = options\n\n const p = promiseSpawn(arg0, args, {\n ...spawnOptions,\n shell,\n stdio: 'pipe',\n stdioString: true,\n cwd,\n env: addPaths(projectRoot, cwd, {\n ...process.env,\n ...env,\n }),\n windowsHide: true,\n })\n proxySignals(p.process)\n return await p\n}\n\n/**\n * Execute an arbitrary command in the foreground\n */\nexport const execFG = async (\n options: ExecOptions,\n): Promise<SpawnResultNoStdio> => {\n const {\n arg0,\n args = [],\n cwd,\n projectRoot,\n env = {},\n 'script-shell': shell = true,\n ...spawnOptions\n } = options\n\n return new Promise<SpawnResultNoStdio>(res => {\n foregroundChild(\n arg0,\n args,\n {\n ...spawnOptions,\n shell,\n cwd,\n env: addPaths(projectRoot, cwd, {\n ...process.env,\n ...env,\n }),\n },\n (status, signal) => {\n res({\n command: arg0,\n args,\n cwd,\n stdout: null,\n stderr: null,\n status,\n signal,\n })\n return false\n },\n )\n })\n}\n\nconst runExecImpl = async <\n R extends SpawnResultNoStdio | SpawnResultStdioStrings,\n>(\n options: RunExecOptions,\n runImpl: (options: RunOptions) => Promise<RunImplResult<R>>,\n execImpl: (options: ExecOptions) => Promise<R>,\n): Promise<R | RunImplResult<R>> => {\n const { arg0, packageJson = new PackageJson(), ...args } = options\n const pj = packageJson.read(options.cwd)\n const { scripts } = pj\n const command = scripts?.[arg0]\n if (command) {\n return runImpl({ ...args, packageJson, arg0 })\n } else {\n return execImpl({ ...args, arg0 })\n }\n}\n\n/**\n * If the arg0 is a defined package.json script, then run(), otherwise exec()\n */\nexport const runExec = async (\n options: RunExecOptions,\n): Promise<RunResult | SpawnResultStdioStrings> =>\n runExecImpl<SpawnResultStdioStrings>(options, run, exec)\n\n/**\n * If the arg0 is a defined package.json script, then runFG(), otherwise\n * execFG()\n */\nexport const runExecFG = async (\n options: RunExecOptions,\n): Promise<RunFGResult | SpawnResultNoStdio> =>\n runExecImpl<SpawnResultNoStdio>(options, runFG, execFG)\n", "import { dirname, resolve } from 'path'\nexport const walkUp = function* (path: string) {\n for (path = resolve(path); path;) {\n yield path\n const pp = dirname(path)\n if (pp === path) {\n break\n } else {\n path = pp\n }\n }\n}\n", "/** utility types to turn a null/undefined/void return into string */\nexport type NullToString<T> = VoidReplace<T>\n\n/** Utility type to replace null/undefined with a given type */\nexport type NullReplace<T, R = string> =\n T extends NonNullable<T> ? T : NonNullable<T> | R\n\n/** Utility type to replace void with a given type */\nexport type VoidReplace<T, R = string> =\n undefined extends T ? NullReplace<Exclude<T, void>, R> | R\n : NullReplace<T, R>\n\n/**\n * Split a string by a string delimiter, optionally limiting the number\n * of parts parsed, and/or transforming the string parts into some other\n * type of value.\n *\n * Pass `-1` as the `limit` parameter to get all parts (useful if an `onPart`\n * method is provided)\n *\n * If an `onPart` method is provided, and returns `undefined`, then the\n * original string part is included in the result set.\n *\n * ```ts\n * import { fastSplit } from '@vltpkg/fast-split'\n *\n * // say we want to split a string on '.' characters\n * const str = getSomeStringSomehow()\n *\n * // basic usage, just like str.split('.'), gives us an array\n * const parts = fastSplit(str, '.')\n *\n * // get just the first two parts, leave the rest intact\n * // Note: unlike str.split('.', 3), the 'rest' here will\n * // include the entire rest of the string.\n * // If you do `str.split('.', 3)`, then the last item in the\n * // returned array is truncated at the next delimiter\n * const [first, second, rest] = fastSplit(str, '.', 3)\n *\n * // If you need to transform it, say if it's an IPv4 address\n * // that you want to turn into numbers, you can do that by\n * // providing the onPart method, which will be slightly faster\n * // than getting an array and subsequently looping over it\n * // pass `-1` as the limit to give us all parts\n * const nums = fastSplit(str, '.', -1, (part, parts, index) => Number(s))\n * ```\n */\nexport function fastSplit<T = string>(\n str: string,\n delim: string,\n limit: number,\n onPart: (part: string, parts: NullToString<T>[], i: number) => T,\n): NullToString<T>[]\nexport function fastSplit(\n str: string,\n delim: string,\n limit?: number,\n): string[]\nexport function fastSplit<T = string>(\n str: string,\n delim: string,\n limit = -1,\n onPart?: (\n part: string,\n parts: NullToString<T>[],\n i: number,\n ) => T | undefined,\n): NullToString<T>[] {\n let i = 0\n let p = 0\n const l = delim.length\n const parts: NullToString<T>[] = []\n while (i !== -1) {\n i = str.indexOf(delim, p)\n const part =\n i === -1 || parts.length === limit - 1 ?\n str.substring(p)\n : str.substring(p, i)\n parts.push((onPart?.(part, parts, i) ?? part) as NullToString<T>)\n if (parts.length === limit) {\n // push the rest into the last part\n return parts\n }\n p = i + l\n }\n return parts\n}\n", "import { syntaxError, typeError } from '@vltpkg/error-cause'\nimport { fastSplit } from '@vltpkg/fast-split'\nimport { type Range } from './range.js'\n\nconst maybeNumber = (s: string): number | string => {\n if (!/^[0-9]+$/.test(s)) return s\n const n = Number(s)\n return n <= Number.MAX_SAFE_INTEGER ? n : s\n}\n\nconst safeNumber = (\n s: string,\n version: string,\n field: string,\n): number => {\n const n = Number(s)\n if (n > Number.MAX_SAFE_INTEGER) {\n throw invalidVersion(\n version,\n `invalid ${field}, must be <= ${Number.MAX_SAFE_INTEGER}`,\n )\n }\n return n\n}\n\nconst re = {\n prefix: /^[ v=]+/,\n main: /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)/,\n prerelease: /-([0-9a-zA-Z_.-]+)(?:$|\\+)/,\n build: /\\+([0-9a-zA-Z_.-]+)$/,\n full: /^[ v=]*(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-([0-9a-zA-Z_.-]+))?(?:\\+([0-9a-zA-Z_.-]+))?$/,\n} as const\n\nconst invalidVersion = (\n version: string,\n message: string,\n): SyntaxError => {\n const er = syntaxError(\n `invalid version: ${message}`,\n { version },\n Version,\n )\n return er\n}\n\n/**\n * Types of incrementing supported by {@link Version#inc}\n */\nexport type IncrementType =\n | 'major'\n | 'minor'\n | 'patch'\n | 'pre'\n | 'premajor'\n | 'preminor'\n | 'prepatch'\n | 'prerelease'\n\n/**\n * A parsed object representation of a SemVer version string\n *\n * This is a bit less forgiving than node-semver, in that prerelease versions\n * MUST start with '-'. Otherwise, the allowed syntax is identical.\n */\nexport class Version {\n /** raw string provided to create this Version */\n raw: string\n\n /** major version number */\n major: number\n /** minor version number */\n minor: number\n /** patch version number */\n patch: number\n /**\n * List of `'.'`-separated strings and numbers indicating that this\n * version is a prerelease.\n *\n * This is undefined if the version does not have a prerelease section.\n */\n prerelease?: (number | string)[]\n /**\n * List of `'.'`-separated strings in the `build` section.\n *\n * This is undefined if the version does not have a build.\n */\n build?: string[]\n\n /** Canonical strict form of this version */\n toString() {\n return `${this.major}.${this.minor}.${this.patch}${\n this.prerelease ? '-' + this.prerelease.join('.') : ''\n }${this.build ? '+' + this.build.join('.') : ''}`\n }\n\n /** Generate a `Version` object from a SemVer string */\n static parse(version: string) {\n version = version.replace(re.prefix, '').trim()\n if (version.length > 256) {\n throw invalidVersion(\n version,\n 'must be less than 256 characters',\n )\n }\n\n const parsed = version.match(re.full)\n if (!parsed) {\n const main = version.match(re.main)\n if (!main) {\n throw invalidVersion(\n version,\n 'no Major.minor.patch tuple present',\n )\n } else {\n throw invalidVersion(\n version,\n 'invalid build or patch section',\n )\n }\n }\n const [_, major_, minor_, patch_, prerelease, build] = parsed as [\n string,\n string,\n string,\n string,\n string | undefined,\n string | undefined,\n ]\n const major = safeNumber(major_, version, 'major')\n const minor = safeNumber(minor_, version, 'minor')\n const patch = safeNumber(patch_, version, 'patch')\n\n return new Version(\n version,\n major,\n minor,\n patch,\n prerelease,\n build,\n )\n }\n\n constructor(\n version: string,\n major: number,\n minor: number,\n patch: number,\n prerelease: string | undefined,\n build: string | undefined,\n ) {\n this.raw = version\n this.major = major\n this.minor = minor\n this.patch = patch\n\n // has prerelease and/or build\n if (prerelease) {\n this.prerelease = fastSplit(prerelease, '.', -1, c => {\n if (!c) {\n throw invalidVersion(\n version,\n 'invalid prerelease, empty identifiers not allowed',\n )\n }\n return maybeNumber(c)\n })\n }\n if (build) {\n this.build = fastSplit(build, '.', -1, c => {\n if (!c) {\n throw invalidVersion(\n version,\n 'invalid build metadata, empty identifiers not allowed',\n )\n }\n })\n }\n }\n\n /**\n * Return 1 if this is > the provided version, -1 if we're less, or 0 if\n * they are equal.\n *\n * No special handling for prerelease versions, this is just a precedence\n * comparison.\n *\n * This can be used to sort a list of versions by precedence:\n *\n * ```ts\n * const versions: Version[] = getVersionsSomehow()\n * const sorted = versions.sort((a, b) => a.compare(b))\n * ```\n */\n compare(v: Version): -1 | 0 | 1 {\n if (this.major > v.major) return 1\n if (this.major < v.major) return -1\n if (this.minor > v.minor) return 1\n if (this.minor < v.minor) return -1\n if (this.patch > v.patch) return 1\n if (this.patch < v.patch) return -1\n // main tuple is equal now\n // if the version has no pr, we're definitely less than or equal to\n if (!v.prerelease?.length)\n return !this.prerelease?.length ? 0 : -1\n // v has a pr. if we don't, we're > it\n if (!this.prerelease?.length) return 1\n // we both have prereleases\n const len = Math.max(this.prerelease.length, v.prerelease.length)\n const me = this.prerelease\n const thee = v.prerelease\n for (let i = 0; i < len; i++) {\n const m = me[i]\n const t = thee[i]\n if (m === t) continue\n // having a field is > not having it\n if (t === undefined) return 1\n if (m === undefined) return -1\n // string parts are higher precedence than\n if (typeof m !== typeof t) {\n return typeof m === 'string' ? 1 : -1\n }\n return m > t ? 1 : -1\n }\n return 0\n }\n\n /**\n * The inverse of compare, for sorting version lists in reverse order\n */\n rcompare(v: Version) {\n return -1 * this.compare(v)\n }\n\n /** true if this version is > the argument */\n greaterThan(v: Version) {\n return this.compare(v) === 1\n }\n\n /** true if this version is >= the argument */\n greaterThanEqual(v: Version) {\n return this.compare(v) > -1\n }\n\n /** true if this version is < the argument */\n lessThan(v: Version) {\n return this.compare(v) === -1\n }\n\n /** true if this version is <= the argument */\n lessThanEqual(v: Version) {\n return this.compare(v) < 1\n }\n\n /** true if these two versions have equal SemVer precedence */\n equals(v: Version) {\n return this.compare(v) === 0\n }\n\n /** just compare the M.m.p parts of the version */\n tupleEquals(v: Version) {\n return (\n this.major === v.major &&\n this.minor === v.minor &&\n this.patch === v.patch\n )\n }\n\n /** true if this version satisfies the range */\n satisfies(r: Range) {\n return r.test(this)\n }\n\n /**\n * Increment the version in place, in the manner specified.\n *\n * See {@link index.inc} for full description.\n */\n inc(part: IncrementType, prereleaseIdentifier?: string) {\n switch (part) {\n case 'premajor':\n this.prerelease = undefined\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', prereleaseIdentifier)\n break\n\n case 'preminor':\n this.prerelease = undefined\n this.patch = 0\n this.minor++\n this.inc('pre', prereleaseIdentifier)\n break\n\n case 'prepatch':\n this.prerelease = undefined\n this.inc('patch')\n this.inc('pre', prereleaseIdentifier)\n break\n\n case 'prerelease':\n if (!this.prerelease?.length)\n this.inc('patch', prereleaseIdentifier)\n this.inc('pre', prereleaseIdentifier)\n break\n\n case 'pre': {\n // this is a bit different than node-semver's logic, but simpler\n // always do zero-based incrementing, and either bump the existing\n // numeric pr value, or add a `.0` after the identifier.\n if (!prereleaseIdentifier) {\n if (!this.prerelease?.length) {\n this.prerelease = [0]\n break\n }\n const last = this.prerelease[this.prerelease.length - 1]\n if (typeof last === 'number') {\n this.prerelease[this.prerelease.length - 1] = last + 1\n } else {\n this.prerelease.push(0)\n }\n break\n }\n if (!this.prerelease?.length) {\n this.prerelease = [prereleaseIdentifier]\n break\n }\n const i = this.prerelease.indexOf(\n maybeNumber(prereleaseIdentifier),\n )\n if (i === -1) {\n this.prerelease = [prereleaseIdentifier]\n break\n }\n const baseValue = this.prerelease[i + 1]\n if (typeof baseValue === 'number') {\n this.prerelease[i + 1] = baseValue + 1\n break\n }\n if (i === this.prerelease.length - 1) {\n this.prerelease.push(0)\n break\n }\n this.prerelease.splice(i + 1, 0, 0)\n break\n }\n\n case 'major':\n if (!this.prerelease?.length || this.minor || this.patch)\n this.major++\n this.prerelease = undefined\n this.patch = 0\n this.minor = 0\n break\n\n case 'minor':\n if (!this.prerelease?.length || this.patch) this.minor++\n this.prerelease = undefined\n this.patch = 0\n break\n\n case 'patch':\n if (!this.prerelease?.length) this.patch++\n this.prerelease = undefined\n break\n\n default:\n throw typeError(\n 'Invalid increment identifier',\n {\n version: this,\n found: part,\n validOptions: [\n 'major',\n 'minor',\n 'patch',\n 'premajor',\n 'preminor',\n 'prepatch',\n 'prerelease',\n 'pre',\n ],\n },\n this.inc,\n )\n }\n\n this.raw = this.toString()\n return this\n }\n}\n", "// TODO: it might be faster to not have Version objects in the\n// comparator tuples, and instead just keep the parsed number arrays?\nimport { syntaxError } from '@vltpkg/error-cause'\nimport { fastSplit } from '@vltpkg/fast-split'\nimport { Version } from './version.js'\n\n/** all comparators are expressed in terms of these operators */\nexport type SimpleOperator = '' | '<' | '<=' | '>' | '>='\n/** operators that are expanded to simpler forms */\nexport type ComplexOperator = '^' | '~' | '~>'\n\nconst isOperator = (\n o?: string,\n): o is ComplexOperator | SimpleOperator =>\n !!o &&\n (o === '>' ||\n o === '<' ||\n o === '>=' ||\n o === '<=' ||\n o === '' ||\n o === '~' ||\n o === '^' ||\n o === '~>')\n\n/** comparator expressed as a [operator,version] tuple */\nexport type OVTuple = [SimpleOperator, Version]\n\nconst preJunk = new Set('=v \\t')\n\nconst invalidComp = (c: string, message: string): SyntaxError =>\n syntaxError(\n `invalid comparator: '${c}' ${message}`,\n { found: c },\n Comparator,\n )\n\nconst assertNumber = (value: string, c: string, field: string) => {\n const n = Number(value)\n if (n !== n) {\n throw invalidComp(\n c,\n `${field} must be numeric or 'x', got: '${value}'`,\n )\n }\n return n\n}\n\nconst assertVersion = (v: string, comp: string) => {\n if (!v) {\n throw invalidComp(comp, 'no value provided for operator')\n }\n}\n\nconst assertMissing = (\n value: string | undefined,\n c: string,\n field: string,\n) => {\n if (value && !isX(value)) {\n throw invalidComp(\n c,\n `cannot omit '${field}' and include subsequent fields`,\n )\n }\n}\n\nconst MAJOR = 0\nconst MINOR = 1\nconst PATCH = 2\n\nconst isX = (c?: string) => !c || c === 'X' || c === 'x' || c === '*'\n\n/**\n * The result of parsing a version value that might be either a full\n * version like `1.2.3` or an X-Range like `1.2.x`\n */\nexport type ParsedXRange =\n | ParsedXMajor\n | ParsedXMinor\n | ParsedXPatch\n | ParsedXVersion\n/**\n * a {@link ParsedXRange} that is just a `*`\n */\nexport type ParsedXMajor = []\n/**\n * a {@link ParsedXRange} that is just a major version\n */\nexport type ParsedXMinor = [number]\n/**\n * a {@link ParsedXRange} that is just a major and minor version\n */\nexport type ParsedXPatch = [number, number]\n/**\n * a {@link ParsedXRange} that is a full version\n */\nexport type ParsedXVersion = [\n M: number,\n m: number,\n p: number,\n pr?: string | undefined,\n b?: string | undefined,\n]\n\nconst isFullVersion = (\n parsed: ParsedXRange,\n): parsed is ParsedXVersion => undefined !== parsed[PATCH]\nconst isXPatch = (parsed: ParsedXRange): parsed is ParsedXPatch =>\n undefined !== parsed[MINOR] && undefined === parsed[PATCH]\nconst isXMinor = (parsed: ParsedXRange): parsed is ParsedXMinor =>\n undefined !== parsed[MAJOR] && undefined === parsed[MINOR]\nconst isXMajor = (parsed: ParsedXRange): parsed is ParsedXMajor =>\n undefined === parsed[MAJOR]\n\n/**\n * Class used to parse the `||` separated portions\n * of a range, and evaluate versions against it.\n *\n * This does most of the heavy lifting of range testing, and provides\n * little affordance for improperly formatted strings. It should be\n * considered an internal class, and usually not accessed directly.\n *\n * @internal\n */\nexport class Comparator {\n /**\n * does this range include prereleases, even when they do not\n * match the tuple in the comparator?\n */\n includePrerelease: boolean\n /** raw string used to create this comparator */\n raw: string\n /** tokens extracted from the raw string input */\n tokens: string[]\n /**\n * Either the `any` comparator, the `none` comparator, or an operator\n * and a {@link ParsedXRange}\n */\n tuples: (Comparator | OVTuple)[] = []\n /** true if this comparator can not match anything */\n isNone = false\n /**\n * true if this comparator is a `'*'` type of range.\n *\n * Note that it still will not match versions with a prerelease value,\n * unless the tuple in the version matches the tuple provided to the\n * comparator, and the comparator version also has a prerelease value,\n * unless `includePrerelease` is set.\n */\n isAny = false\n\n /** the canonical strict simplified parsed form of this constructor */\n toString() {\n return (\n this.isNone ? '<0.0.0-0'\n : this.isAny ? '*'\n : /* c8 ignore next */\n this.tuples.map(c => (isAny(c) ? '*' : c.join(''))).join(' ')\n )\n }\n\n constructor(comp: string, includePrerelease = false) {\n this.includePrerelease = includePrerelease\n comp = comp.trim()\n this.raw = comp\n let hyphen = false\n const rawComps = fastSplit(comp, ' ', -1, (part, parts, i) => {\n if (part === '-') {\n if (hyphen) {\n throw invalidComp(\n comp,\n 'multiple hyphen ranges not allowed',\n )\n }\n if (parts.length !== 1 || i === -1) {\n throw invalidComp(\n comp,\n 'hyphen must be between two versions',\n )\n }\n hyphen = true\n } else if (hyphen && parts.length !== 2) {\n throw invalidComp(comp, 'hyphen range must be alone')\n }\n })\n\n // remove excess spaces, `> 1 2` => `>1 2`\n const comps: string[] = []\n let followingOperator = false\n\n let l = 0\n for (const c of rawComps) {\n if (c === '') continue\n if (!followingOperator) {\n followingOperator = isOperator(c)\n comps.push(c)\n l++\n continue\n }\n // we know this is not undefined since followingOperator guards that\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n comps[l - 1]! += c\n followingOperator = false\n }\n\n // TS mistakenly thinks hyphen is always false here\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (hyphen) {\n const [min, _, max] = comps\n /* c8 ignore start - defense in depth for TS, already guaranteed */\n if (!min || !max) {\n throw invalidComp(comp, 'hyphen must be between two versions')\n }\n /* c8 ignore stop */\n this.#parseHyphenRange(min, max)\n } else if (\n !comps.length ||\n (comps.length === 1 && isX(comps[0]))\n ) {\n this.tuples.push(this.#getComparatorAny())\n } else {\n for (const c of comps) {\n this.#parse(c)\n if (this.isNone) break\n }\n }\n this.tokens = comps\n this.isAny = true\n for (const c of this.tuples) {\n if (Array.isArray(c) || !c.isAny) {\n this.isAny = false\n break\n }\n }\n }\n\n // inclusive min\n #xInclusiveMin(raw: string): Comparator | OVTuple {\n const z = this.includePrerelease ? '0' : undefined\n const [M, m = 0, p = 0, pr = z, build] = this.#parseX(raw)\n return M === undefined ?\n this.#getComparatorAny()\n : ['>=', new Version(raw, M, m, p, pr, build)]\n }\n\n // exclusive min\n #xExclusiveMin(raw: string): Comparator | OVTuple {\n const parsed = this.#parseX(raw)\n if (isFullVersion(parsed)) {\n return ['>', new Version(raw, ...parsed)]\n }\n const z = this.includePrerelease ? '0' : undefined\n if (isXPatch(parsed)) {\n // >1.2 => >=1.3.0\n return [\n '>=',\n new Version(\n raw,\n parsed[MAJOR],\n parsed[MINOR] + 1,\n 0,\n z,\n undefined,\n ),\n ]\n }\n if (isXMinor(parsed)) {\n // >1 => >=2.0.0\n return [\n '>=',\n new Version(raw, parsed[MAJOR] + 1, 0, 0, z, undefined),\n ]\n }\n this.isNone = true\n this.tuples.length = 0\n return comparatorNone\n }\n\n #xInclusiveMax(raw: string): Comparator | OVTuple {\n const parsed = this.#parseX(raw)\n return (\n isFullVersion(parsed) ? ['<=', new Version(raw, ...parsed)]\n : isXPatch(parsed) ?\n [\n '<',\n new Version(\n raw,\n parsed[MAJOR],\n parsed[MINOR] + 1,\n 0,\n '0',\n undefined,\n ),\n ]\n : isXMinor(parsed) ?\n [\n '<',\n new Version(raw, parsed[MAJOR] + 1, 0, 0, '0', undefined),\n ]\n : this.#getComparatorAny()\n )\n }\n\n #xExclusiveMax(raw: string): Comparator | OVTuple {\n const z = this.includePrerelease ? '0' : undefined\n const [M = 0, m = 0, p = 0, pr = z, build] = this.#parseX(raw)\n if (M === 0 && m === 0 && p === 0 && pr === '0') {\n this.isNone = true\n this.tuples.length = 0\n return comparatorNone\n }\n return ['<', new Version(raw, M, m, p, pr, build)]\n }\n\n #validXM(raw: string, m?: string, p?: string): ParsedXMajor {\n assertMissing(m, raw, 'major')\n assertMissing(p, raw, 'major')\n if (m === '' || p === '') {\n throw invalidComp(raw, `(Did you mean '*'?)`)\n }\n return []\n }\n #validXm(\n raw: string,\n M: string,\n m?: string,\n p?: string,\n ): ParsedXMinor {\n assertMissing(p, raw, 'major')\n if (m === '' || p === '') {\n throw invalidComp(raw, `(Did you mean '${M}'?)`)\n }\n return [assertNumber(M, raw, 'major')]\n }\n #validXp(\n raw: string,\n M: string,\n m: string,\n p?: string,\n ): ParsedXPatch {\n if (p === '') {\n throw invalidComp(raw, `(Did you mean '${M}.${m}'?)`)\n }\n return [\n assertNumber(M, raw, 'major'),\n assertNumber(m, raw, 'minor'),\n ]\n }\n #validTuple(\n raw: string,\n M: string,\n m: string,\n p: string,\n ): ParsedXVersion {\n return [\n assertNumber(M, raw, 'major'),\n assertNumber(m, raw, 'minor'),\n assertNumber(p, raw, 'patch'),\n ]\n }\n #validXbuild(\n raw: string,\n M: string,\n m: string,\n p: string,\n pl: number,\n ): ParsedXVersion {\n // build, no prerelease\n const patch = p.substring(0, pl)\n const build = p.substring(pl + 1)\n if (!patch) {\n throw invalidComp(raw, 'cannot specify build without patch')\n }\n if (!build) {\n throw invalidComp(raw, `encountered '+', but no build value`)\n }\n return [\n assertNumber(M, raw, 'major'),\n assertNumber(m, raw, 'minor'),\n assertNumber(patch, raw, 'patch'),\n undefined,\n build,\n ]\n }\n\n #validXpr(\n raw: string,\n M: string,\n m: string,\n p: string,\n hy: number,\n ): ParsedXVersion {\n {\n // prerelease, no build\n const patch = p.substring(0, hy)\n const pr = p.substring(hy + 1)\n if (!patch) {\n throw invalidComp(\n raw,\n 'cannot specify prerelease without patch',\n )\n }\n if (!pr) {\n throw invalidComp(\n raw,\n `encountered '-', but no prerelease value`,\n )\n }\n return [\n assertNumber(M, raw, 'major'),\n assertNumber(m, raw, 'minor'),\n assertNumber(patch, raw, 'patch'),\n pr,\n undefined,\n ]\n }\n }\n #validXprbuild(\n raw: string,\n M: string,\n m: string,\n p: string,\n hy: number,\n pl: number,\n ): ParsedXVersion {\n // both prerelease and build\n const patch = p.substring(0, hy)\n const pr = p.substring(hy + 1, pl)\n const build = p.substring(pl + 1)\n if (!patch) {\n throw invalidComp(\n raw,\n 'cannot specify prerelease without patch',\n )\n }\n if (!pr) {\n throw invalidComp(\n raw,\n `encountered '-', but no prerelease value`,\n )\n }\n if (!build) {\n throw invalidComp(raw, `encountered '+', but no build value`)\n }\n return [\n assertNumber(M, raw, 'major'),\n assertNumber(m, raw, 'minor'),\n assertNumber(patch, raw, 'patch'),\n pr,\n build,\n ]\n }\n\n // pull the relevant values out of an X-range or version\n // return the fields for creating a Version object.\n // only call once operator is stripped off\n #parseX(raw: string): ParsedXRange {\n let [M, m, p] = fastSplit(raw, '.', 3)\n let prune = 0\n while (M && preJunk.has(M.charAt(prune))) prune++\n if (M !== undefined && prune !== 0) M = M.substring(prune)\n // the `|| !M` is so TS knows we've handled undefined\n if (!M || isX(M)) return this.#validXM(raw, m, p)\n if (!m || isX(m)) return this.#validXm(raw, M, m, p)\n if (!p || isX(p)) return this.#validXp(raw, M, m, p)\n\n const hy = p.indexOf('-')\n const pl = p.indexOf('+')\n if (pl === -1 && hy === -1) return this.#validTuple(raw, M, m, p)\n if (pl === -1) return this.#validXpr(raw, M, m, p, hy)\n if (hy === -1) return this.#validXbuild(raw, M, m, p, pl)\n return this.#validXprbuild(raw, M, m, p, hy, pl)\n }\n\n #parseHyphenRange(min: string, max: string) {\n const minv = this.#xInclusiveMin(min)\n const maxv = this.#xInclusiveMax(max)\n const minAny = isAny(minv)\n const maxAny = isAny(maxv)\n if (minAny && maxAny) this.tuples.push(this.#getComparatorAny())\n else if (minAny) this.tuples.push(maxv)\n else if (maxAny) this.tuples.push(minv)\n else this.tuples.push(minv, maxv)\n }\n\n #parse(comp: string) {\n const first = comp.charAt(0)\n const first2 = comp.substring(0, 2)\n const v1 = comp.substring(1)\n const v2 = comp.substring(2)\n switch (first2) {\n case '~>':\n assertVersion(v2, comp)\n return this.#parseTilde(v2)\n case '>=':\n assertVersion(v2, comp)\n return this.tuples.push(this.#xInclusiveMin(v2))\n case '<=':\n assertVersion(v2, comp)\n return this.tuples.push(this.#xInclusiveMax(v2))\n }\n switch (first) {\n case '~':\n assertVersion(v1, comp)\n return this.#parseTilde(v1)\n case '^':\n assertVersion(v1, comp)\n return this.#parseCaret(v1)\n case '>':\n assertVersion(v1, comp)\n return this.tuples.push(this.#xExclusiveMin(v1))\n case '<':\n assertVersion(v1, comp)\n return this.tuples.push(this.#xExclusiveMax(v1))\n }\n return this.#parseEq(comp)\n }\n\n #parseTilde(comp: string) {\n const parsed = this.#parseX(comp)\n if (isXMajor(parsed)) {\n this.tuples.push(this.#getComparatorAny())\n return\n }\n const z = this.includePrerelease ? '0' : undefined\n if (isXMinor(parsed)) {\n const [M] = parsed\n this.tuples.push(\n ['>=', new Version(comp, M, 0, 0, z, undefined)],\n ['<', new Version(comp, M + 1, 0, 0, '0', undefined)],\n )\n return\n }\n if (isXPatch(parsed)) {\n const [M, m] = parsed\n const z = this.includePrerelease ? '0' : undefined\n this.tuples.push(\n ['>=', new Version(comp, M, m, 0, z, undefined)],\n ['<', new Version(comp, M, m + 1, 0, '0', undefined)],\n )\n return\n }\n const [M, m, p, pr = z, build] = parsed\n this.tuples.push(\n ['>=', new Version(comp, M, m, p, pr, build)],\n ['<', new Version(comp, M, m + 1, 0, '0', build)],\n )\n }\n\n #parseCaret(comp: string) {\n const min = this.#xInclusiveMin(comp)\n if (isAny(min)) {\n this.tuples.push(min)\n return\n }\n const minv = min[1]\n if (minv.major !== 0) {\n this.tuples.push(min, [\n '<',\n new Version(comp, minv.major + 1, 0, 0, '0', undefined),\n ])\n } else if (minv.minor !== 0) {\n this.tuples.push(min, [\n '<',\n new Version(\n comp,\n minv.major,\n minv.minor + 1,\n 0,\n '0',\n undefined,\n ),\n ])\n } else if (!minv.prerelease?.length) {\n this.tuples.push(['', minv])\n } else {\n this.tuples.push(min, [\n '<',\n new Version(\n comp,\n minv.major,\n minv.minor,\n minv.patch + 1,\n '0',\n undefined,\n ),\n ])\n }\n }\n\n #parseEq(comp: string) {\n const parsed = this.#parseX(comp)\n const z = this.includePrerelease ? '0' : undefined\n if (isFullVersion(parsed)) {\n this.tuples.push(['', new Version(comp, ...parsed)])\n } else if (isXMajor(parsed)) {\n this.tuples.push(this.#getComparatorAny())\n } else if (isXMinor(parsed)) {\n this.tuples.push([\n '>=',\n new Version(comp, parsed[MAJOR], 0, 0, z, undefined),\n ])\n this.tuples.push([\n '<',\n new Version(comp, parsed[MAJOR] + 1, 0, 0, '0', undefined),\n ])\n } else if (isXPatch(parsed)) {\n this.tuples.push(\n [\n '>=',\n new Version(\n comp,\n parsed[MAJOR],\n parsed[MINOR],\n 0,\n z,\n undefined,\n ),\n ],\n [\n '<',\n new Version(\n comp,\n parsed[MAJOR],\n parsed[MINOR] + 1,\n 0,\n '0',\n undefined,\n ),\n ],\n )\n }\n }\n\n /** return true if the version is a match for this comparator */\n test(v: Version) {\n if (this.isNone) return false\n const ip = this.includePrerelease\n const hasPR = !!v.prerelease?.length\n let prOK = ip || !hasPR\n for (const c of this.tuples) {\n if (isAny(c)) {\n continue\n }\n const [op, cv] = c\n prOK ||= !!cv.prerelease?.length && v.tupleEquals(cv)\n switch (op) {\n case '':\n if (!v.equals(cv)) return false\n continue\n case '>':\n if (!v.greaterThan(cv)) return false\n continue\n case '>=':\n if (!v.greaterThanEqual(cv)) return false\n continue\n case '<':\n if (!v.lessThan(cv)) return false\n continue\n case '<=':\n if (!v.lessThanEqual(cv)) return false\n continue\n }\n }\n // they all passed, so it can only fail for having a prerelease\n // if we allow prereleases, or saw a matching tuple, that's ok.\n return prOK\n }\n\n #getComparatorAny() {\n return this.includePrerelease ? comparatorAnyPR : comparatorAny\n }\n}\n\nconst isAny = (c: Comparator | OVTuple): c is Comparator =>\n c === comparatorAny || c === comparatorAnyPR\nconst comparatorAny = {\n isAny: true,\n toString: () => '*',\n includePrerelease: false,\n test: (v: Version) => !v.prerelease?.length,\n} as Comparator\nconst comparatorAnyPR = {\n isAny: true,\n toString: () => '*',\n includePrerelease: true,\n test: (_: Version) => true,\n} as Comparator\nconst comparatorNone = {\n isNone: true,\n toString: () => '<0.0.0-0',\n includePrerelease: false,\n test: (_: Version) => false,\n} as unknown as Comparator\n", "import { fastSplit } from '@vltpkg/fast-split'\nimport { Comparator } from './comparator.js'\nimport { Version } from './version.js'\n\n/**\n * A representation of a semver range, used to test versions.\n *\n * Includes a set of comparators representing the `||`-separated\n * sections of the range string\n */\nexport class Range {\n /** raw string used to create this Range */\n raw: string\n\n /** true if the range is `*` */\n isAny: boolean\n\n /** true if the range is a single semver version */\n isSingle: boolean\n\n /** true if the range cannot match anything */\n\n /**\n * set of {@link Comparator} objects representing the `||`-separated sections\n * of the range. If at least one of these matches, then the version is a\n * match.\n */\n set: Comparator[] = []\n\n /** true if all prerelease versions should be included */\n includePrerelease: boolean\n\n /** cached toString */\n #toString?: string\n\n constructor(range: string, includePrerelease = false) {\n this.raw = range\n this.includePrerelease = includePrerelease\n this.isAny = false\n let isFirst = true\n this.isSingle = false\n fastSplit(range, '||', -1, part => {\n if (this.isAny) return\n const cmp = new Comparator(part, this.includePrerelease)\n if (cmp.isAny) {\n this.set = [cmp]\n this.isAny = true\n return\n }\n this.set.push(cmp)\n if (!isFirst) this.isSingle = false\n else if (\n Array.isArray(cmp.tuples) &&\n cmp.tuples.length === 1 &&\n Array.isArray(cmp.tuples[0]) &&\n cmp.tuples[0][0] === ''\n ) {\n this.isSingle = true\n }\n isFirst = false\n })\n }\n\n /**\n * test a {@link Version} against the range\n */\n test(v: Version) {\n return this.set.some(c => c.test(v))\n }\n\n /** return the simplified canonical form of this range */\n toString() {\n if (this.#toString) return this.#toString\n if (this.isSingle) {\n this.#toString = String(this.set[0])\n return this.#toString\n }\n this.#toString = this.set.map(c => String(c)).join(' || ')\n return this.#toString\n }\n}\n", "import { Range } from './range.js'\nimport { IncrementType, Version } from './version.js'\nimport { syntaxError } from '@vltpkg/error-cause'\n\nexport * from './comparator.js'\nexport * from './range.js'\nexport * from './version.js'\n\n/** Return the parsed version string, or `undefined` if invalid */\nexport const parse = (version: Version | string) => {\n if (version instanceof Version) return version\n try {\n return Version.parse(String(version))\n } catch {\n return undefined\n }\n}\n\n/** Return the parsed version range, or `undefined` if invalid */\nexport const parseRange = (\n range: Range | string,\n includePrerelease = false,\n) => {\n if (typeof range === 'object') {\n if (range.includePrerelease === includePrerelease) return range\n range = range.raw\n }\n try {\n return new Range(range, includePrerelease)\n } catch {\n return undefined\n }\n}\n\n/**\n * return true if the version is valid\n *\n * Note: do not use this if you intend to immediately parse the version if it's\n * valid. Just use {@link parse}, and guard the possible undefined value, or\n * use `Version.parse(..)` to throw on invalid values.\n */\nexport const valid = (version: Version | string) => !!parse(version)\n\n/**\n * return true if the range is valid\n *\n * Note: do not use this if you intend to immediately parse the range if it's\n * valid. Just use {@link parseRange}, and guard the possible undefined value,\n * or use `new Range(..)` to throw on invalid values.\n */\nexport const validRange = (range: Range | string) =>\n !!parseRange(range)\n\n/**\n * Return true if the version satisfies the range.\n */\nexport const satisfies = (\n version: Version | string,\n range: Range | string,\n includePrerelease = false,\n) => {\n if (typeof version === 'string') {\n const parsed = parse(version)\n if (!parsed) return false\n version = parsed\n }\n if (typeof range === 'string') {\n const parsed = parseRange(range, includePrerelease)\n if (!parsed) return false\n range = parsed\n }\n return version.satisfies(range)\n}\n\n/**\n * Increment the specified part of the version, and return the resulting\n * object. If a Version object is provided, it will be modified in-place.\n *\n * Part behaviors:\n *\n * - `'major'` If the version is a `M.0.0-...` version with a prerelease, then\n * simply drop the prerelease. Otherwise, set the minor and patch to 0, and\n * increment the major. So `1.0.0-beta` becomes `1.0.0`, and `1.2.3` becomes\n * `2.0.0`\n *\n * - `'minor'` If the version is a `M.m.0-...` version with a prerelease, then\n * simply drop the prerelease. Otherwise, set the patch to 0, and increment the\n * minor. So `1.2.0-beta` becomes `1.2.0`, and `1.2.3` becomes `1.3.0`.\n *\n * - `'patch'` If the version has a prerelease, then simply drop the\n * prerelease. Otherwise, increment the patch value. So `1.2.3-beta` becomes\n * `1.2.3` and `1.2.3` becomes `1.2.4`.\n *\n * - `'premajor'` Set the patch and minor versions to `0`, increment the major\n * version, and add a prerelease, using the optional identifier.\n *\n * - `'preminor'` Set the patch version to `0`, increment the minor version,\n * and add a prerelease, using the optional identifier.\n *\n * - `'prepatch'` If a prerelease is already present, increment the patch\n * version, otherwise leave it untouched, and add a prerelease, using the\n * optional identifier.\n *\n * - `'prerelease'` If a prerelease version is present, then behave the same as\n * `'prepatch'`. Otherwise, add a prerelease, using the optional identifier.\n *\n * - `'pre'` This is mostly for use by the other prerelease incrementers.\n *\n * - If a prerelease identifier is provided:\n *\n * Update that named portion of the prerelease. For example,\n * `inc('1.2.3-beta.4', 'pre', 'beta')` would result in `1.2.3-beta.5`.\n *\n * If there is no prerelease identifier by that name, then replace the\n * prerelease with `[name]`. So `inc('1.2.3-alpha.4', 'pre', 'beta')`\n * would result in `1.2.3-beta`.\n *\n * If the prerelease identifer is present, but has no numeric value\n * following it, then add `0`. So `inc('1.2.3-beta', 'pre', 'beta')`\n * would result in `1.2.3-beta.0`.\n *\n * - If no prerelease identifier is provided:\n *\n * If there is no current prerelease, then set the prerelease to `0`. So,\n * `inc('1.2.3', 'pre')` becomes `1.2.3-0`.\n *\n * If the last item in the prerelease is numeric, then increment it. So,\n * `inc('1.2.3-beta.3', 'pre')` becomes `1.2.3-beta.4`.\n */\nexport const inc = (\n version: Version | string,\n part: IncrementType,\n prereleaseIdentifier?: string,\n) =>\n (typeof version === 'string' ?\n Version.parse(version)\n : version\n ).inc(part, prereleaseIdentifier)\n\n/**\n * The method used by {@link sort}, exported for passing directly to\n * `Array.sort`.\n *\n * Usage:\n *\n * ```ts\n * import { sortMethod } from '@vltpkg/semver'\n * const versions = ['1.2.3', '5.2.3', '2.3.4']\n * console.log(versions.sort(sortMethod))\n * // ['1.2.3', '2.3.4', '5.2.3']\n * ```\n */\nexport const sortMethod = (\n a: Version | string,\n b: Version | string,\n) => {\n const pa = parse(a)\n const pb = parse(b)\n /* c8 ignore start - nondeterministic */\n if (!pa && !pb) return String(a).localeCompare(String(b), 'en')\n if (!pa) return 1\n if (!pb) return -1\n /* c8 ignore stop */\n return pa.compare(pb)\n}\n\n/**\n * Sort an array of version strings or objects in ascending SemVer precedence\n * order (ie, lowest versions first).\n *\n * Invalid version strings are sorted to the end of the array in ascending\n * alphabetical order.\n *\n * Note: when using this method, the list is cloned prior to sorting, to\n * prevent surprising mutation. To sort the list in place, see\n * {@link sortMethod}.\n */\nexport const sort = <T extends Version | string = Version | string>(\n list: T[],\n): T[] => list.slice().sort(sortMethod)\n\n/**\n * Sort an array of version strings or objects in descending SemVer\n * precedence order (ie, highest versions first).\n *\n * Invalid version strings are sorted to the end of the array in ascending\n * alphabetical order.\n *\n * Note: when using this method, the list is cloned prior to sorting, to\n * prevent surprising mutation. To sort the list in place, see\n * {@link rsortMethod}.\n */\nexport const rsort = <T extends Version | string = Version | string>(\n list: T[],\n): T[] => list.slice().sort(rsortMethod)\n\n/**\n * The method used by {@link rsort}, exported for passing directly to\n * `Array.sort`.\n *\n * Usage:\n *\n * ```ts\n * import { rsortMethod } from '@vltpkg/semver'\n * const versions = ['1.2.3', '5.2.3', '2.3.4']\n * console.log(versions.sort(rsortMethod))\n * // ['5.2.3', '2.3.4', '1.2.3']\n * ```\n */\nexport const rsortMethod = (\n a: Version | string,\n b: Version | string,\n) => {\n const pa = parse(a)\n const pb = parse(b)\n /* c8 ignore start - nondeterministic */\n if (!pa && !pb) return String(a).localeCompare(String(b), 'en')\n if (!pa) return 1\n if (!pb) return -1\n /* c8 ignore stop */\n return pa.rcompare(pb)\n}\n\n/**\n * Method used by {@link filter}, for use in `Array.filter` directly.\n *\n * Usage:\n *\n * ```ts\n * import { filterMethod } from '@vltpkg/semver'\n * const versions = ['1.2.3', '5.2.3', '2.3.4']\n * console.log(versions.filter(filterMethod('>=2.x')))\n * // ['5.2.3', '2.3.4']\n * ```\n */\nexport const filterMethod = (\n range: Range | string,\n includePrerelease = false,\n): ((version: Version | string) => boolean) => {\n const r = parseRange(range, includePrerelease)\n return !r ?\n () => false\n : version => satisfies(version, r, r.includePrerelease)\n}\n\n/**\n * Filter a list of versions to find all that match a given range.\n */\nexport const filter = <T extends Version | string = Version | string>(\n list: T[],\n range: Range | string,\n includePrerelease = false,\n): T[] => list.filter(filterMethod(range, includePrerelease))\n\n/**\n * Find the highest-precedence match for a range within a list of versions\n *\n * Returns `undefined` if no match was found.\n */\nexport const highest = (\n list: (Version | string)[],\n range: Range | string,\n includePrerelease = false,\n): Version | undefined => {\n const r = parseRange(range, includePrerelease)\n if (!r) return undefined\n let max: Version | undefined = undefined\n for (const v of list) {\n const version = parse(v)\n if (!version) continue\n if (!version.satisfies(r)) continue\n if (!max) max = version\n else if (version.greaterThan(max)) max = version\n }\n return max\n}\n\n/**\n * Faster form of {@link highest}, for use when the list is sorted\n * in precedence order (lower-precedence versions first).\n *\n * Note: This stops at the first match, and will produce incorrect results\n * when the list is not properly sorted!\n */\nexport const sortedHighest = (\n list: (Version | string)[],\n range: Range | string,\n includePrerelease = false,\n): Version | undefined => {\n const r = parseRange(range, includePrerelease)\n if (!r) return undefined\n for (let i = list.length - 1; i >= 0; i--) {\n const v = list[i]\n /* c8 ignore next */\n if (!v) continue\n const version = parse(v)\n if (!version) continue\n if (!version.satisfies(r)) continue\n return version\n }\n}\n\n/**\n * Faster form of {@link highest}, for use when the list is sorted\n * in reverse precedence order (higher-precedence versions first).\n *\n * Note: This stops at the first match, and will produce incorrect results\n * when the list is not properly sorted!\n */\nexport const rsortedHighest = (\n list: (Version | string)[],\n range: Range | string,\n includePrerelease = false,\n): Version | undefined => {\n const r = parseRange(range, includePrerelease)\n if (!r) return undefined\n for (const v of list) {\n const version = parse(v)\n if (!version) continue\n if (!version.satisfies(r)) continue\n return version\n }\n}\n\n/**\n * Find the lowest-precedence match for a range within a list of versions\n *\n * Returns `undefined` if no match was found.\n */\nexport const lowest = (\n list: (Version | string)[],\n range: Range | string,\n includePrerelease = false,\n): Version | undefined => {\n const r = parseRange(range, includePrerelease)\n if (!r) return undefined\n let min: Version | undefined = undefined\n for (const v of list) {\n const version = parse(v)\n if (!version) continue\n if (!version.satisfies(r)) continue\n if (!min) min = version\n else if (version.lessThan(min)) min = version\n }\n return min\n}\n\n/**\n * Faster form of {@link lowest}, for use when the list is sorted\n * in precedence order (lower-precedence versions first).\n *\n * Note: This stops at the first match, and will produce incorrect results\n * when the list is not properly sorted!\n */\nexport const sortedLowest = (\n list: (Version | string)[],\n range: Range | string,\n includePrerelease = false,\n): Version | undefined =>\n rsortedHighest(list, range, includePrerelease)\n\n/**\n * Faster form of {@link lowest}, for use when the list is sorted\n * in reverse precedence order (higher-precedence versions first).\n *\n * Note: This stops at the first match, and will produce incorrect results\n * when the list is not properly sorted!\n */\nexport const rsortedLowest = (\n list: (Version | string)[],\n range: Range | string,\n includePrerelease = false,\n): Version | undefined =>\n sortedHighest(list, range, includePrerelease)\n\n/**\n * Same as {@link sortMethod}, but throws if either version is not valid.\n * 1 if versionA is higher precedence than versionB\n * -1 if versionA is lower precedence than versionB\n * 0 if they have equal precedence\n */\nexport const compare = (\n versionA: Version | string,\n versionB: Version | string,\n) => {\n const a = parse(versionA)\n if (!a) {\n throw syntaxError('invalid version', { found: versionA })\n }\n const b = parse(versionB)\n if (!b) {\n throw syntaxError('invalid version', { found: versionB })\n }\n return a.compare(b)\n}\n\n/**\n * Inverse of {@link compare}\n *\n * Same as {@link rsortMethod}, but throws if either version is not valid.\n *\n * -1 if versionA is higher precedence than versionB\n * 1 if versionA is lower precedence than versionB\n * 0 if they have equal precedence\n */\nexport const rcompare = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionB, versionA)\n\n/** true if versionA is > versionB. throws on invalid values */\nexport const gt = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionA, versionB) > 0\n/** true if versionA is >= versionB. throws on invalid values */\nexport const gte = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionA, versionB) >= 0\n/** true if versionA is < versionB. throws on invalid values */\nexport const lt = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionA, versionB) < 0\n/** true if versionA is <= versionB. throws on invalid values */\nexport const lte = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionA, versionB) <= 0\n/** true if versionA is not equal to versionB. throws on invalid values */\nexport const neq = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionA, versionB) !== 0\n/** true if versionA is equal to versionB. throws on invalid values */\nexport const eq = (\n versionA: Version | string,\n versionB: Version | string,\n) => compare(versionA, versionB) === 0\n\n/** extract the major version number, or undefined if invalid */\nexport const major = (version: Version | string) =>\n parse(version)?.major\n/** extract the minor version number, or undefined if invalid */\nexport const minor = (version: Version | string) =>\n parse(version)?.minor\n/** extract the patch version number, or undefined if invalid */\nexport const patch = (version: Version | string) =>\n parse(version)?.patch\n/**\n * extract the list of prerelease identifiers, or undefined if the version\n * is invalid. If no prerelease identifiers are present, returns `[]`.\n */\nexport const prerelease = (version: Version | string) => {\n const p = parse(version)\n if (!p) return undefined\n return p.prerelease ?? []\n}\n/**\n * extract the list of build identifiers, or undefined if the version\n * is invalid. If no build identifiers are present, returns `[]`.\n */\nexport const build = (version: Version | string) => {\n const p = parse(version)\n if (!p) return undefined\n return p.build ?? []\n}\n\n/** return all versions that do not have any prerelease identifiers */\nexport const stable = <T extends Version | string = Version | string>(\n versions: T[],\n): T[] =>\n versions.filter(v => {\n const p = parse(v)\n if (!p) return false\n return !p.prerelease?.length\n })\n", "import {\n error,\n ErrorCauseObject,\n typeError,\n} from '@vltpkg/error-cause'\nimport { parseRange, type Range } from '@vltpkg/semver'\nimport { homedir } from 'node:os'\nimport {\n isAbsolute,\n join,\n resolve,\n win32 as winPath,\n} from 'node:path'\nimport { inspect, InspectOptions } from 'node:util'\nimport {\n GitSelectorParsed,\n Scope,\n SpecLike,\n SpecOptions,\n SpecOptionsFilled,\n} from './types.js'\n\nexport * from './types.js'\n\nexport const kCustomInspect = Symbol.for('nodejs.util.inspect.custom')\n\nconst defaultRegistry = 'https://registry.npmjs.org/'\n\nexport const defaultRegistries = {\n npm: 'https://registry.npmjs.org/',\n}\n\nexport const defaultGitHosts = {\n github: 'git+ssh://git@github.com:$1/$2.git',\n bitbucket: 'git+ssh://git@bitbucket.org:$1/$2.git',\n gitlab: 'git+ssh://git@gitlab.com:$1/$2.git',\n gist: 'git+ssh://git@gist.github.com/$1.git',\n}\n\nexport const defaultGitHostArchives = {\n github: 'https://codeload.github.com/$1/$2/tar.gz/$committish',\n bitbucket: 'https://bitbucket.org/$1/$2/get/$committish.tar.gz',\n gist: 'https://codeload.github.com/gist/$1/tar.gz/$committish',\n gitlab:\n 'https://gitlab.com/$1/$2/repository/archive.tar.gz?ref=$committish',\n}\n\n/**\n * These are just for legacy support of urls that are supported by npm\n * and observed in the wild.\n *\n * Not configurable, because no more will be added. If you wish to define\n * custom git hosts, use it with the `'git-hosts'` and `'git-host-archives'`\n * options.\n */\nexport const gitHostWebsites = {\n github: 'https://github.com/',\n bitbucket: 'https://bitbucket.org/',\n gist: 'https://gist.github.com/',\n gitlab: 'https://gitlab.com/',\n}\n\nconst getOptions = (options: SpecOptions): SpecOptionsFilled => ({\n ...options,\n registry: options.registry ?? defaultRegistry,\n 'scope-registries': options['scope-registries'] ?? {},\n 'git-hosts':\n options['git-hosts'] ?\n {\n ...defaultGitHosts,\n ...options['git-hosts'],\n }\n : defaultGitHosts,\n registries:\n options.registries ?\n {\n ...defaultRegistries,\n ...options.registries,\n }\n : defaultRegistries,\n 'git-host-archives':\n options['git-host-archives'] ?\n {\n ...defaultGitHostArchives,\n ...options['git-host-archives'],\n }\n : defaultGitHostArchives,\n})\n\n/**\n * Various nameless scenarios that are handled in the\n * standard spec parsing and should return an unknown name.\n *\n * Returns `true` if the name can not be inferred, `false` otherwise.\n */\nconst startsWithSpecIdentifier = (\n spec: string,\n options: SpecOptionsFilled,\n): boolean =>\n spec.startsWith('/') ||\n spec.startsWith('./') ||\n spec.startsWith('../') ||\n spec.startsWith('file:') ||\n spec.startsWith('http:') ||\n spec.startsWith('https:') ||\n spec.startsWith('workspace:') ||\n spec.startsWith('git@') ||\n spec.startsWith('git://') ||\n spec.startsWith('git+ssh://') ||\n spec.startsWith('git+http://') ||\n spec.startsWith('git+https://') ||\n spec.startsWith('git+file://') ||\n spec.startsWith('git@github.com') ||\n spec.startsWith('registry:') ||\n // anything that starts with a known git host key, or a\n // custom registered registry protocol e.g: `github:`, `custom:`\n [\n ...Object.keys(options['git-hosts']),\n ...Object.keys(options.registries),\n ].some(key => spec.startsWith(`${key}:`))\n\n/**\n * Returns the location in which the first `@` value is found in a given\n * string, also takes into account that a string starting with @ is\n * using a scoped-name.\n */\nconst findFirstAt = (spec: string, hasScope: boolean) =>\n spec.indexOf('@', hasScope ? 1 : 0)\n\n/**\n * Return `true` if a given spec string is likely to be a git spec.\n */\nconst findGitIdentifier = (spec: string): boolean =>\n spec.indexOf('#') > 2\n\n/**\n * Return `true` if a given spec string is likely to be a file spec.\n */\nconst findFileIdentifier = (spec: string): boolean =>\n spec.includes('/')\n\nexport class Spec implements SpecLike<Spec> {\n /**\n * Create a Spec object from a full spec, name+bareSpec, or Spec object\n *\n * Note: If a Spec object is provided, it is returned as-is, without\n * investigating whether the options match.\n */\n static parse(\n name: string,\n bareSpec: string,\n options?: SpecOptions,\n ): Spec\n static parse(spec: string, options?: SpecOptions): Spec\n static parse(spec: Spec, options?: SpecOptions): Spec\n static parse(\n spec: Spec | string,\n bareOrOptions?: SpecOptions | string,\n options?: SpecOptions,\n ): Spec {\n return typeof spec === 'object' ? spec : (\n new Spec(spec, bareOrOptions, options)\n )\n }\n\n static parseArgs(specOrBareSpec: string, opts?: SpecOptions): Spec {\n const options = getOptions(opts ?? {})\n\n if (startsWithSpecIdentifier(specOrBareSpec, options)) {\n const parsed = Spec.parse('(unknown)', specOrBareSpec, options)\n // try to look into a potential parsed subspec for a name\n if (parsed.subspec) {\n parsed.name = parsed.subspec.name\n parsed.spec = `${parsed.name}@${parsed.bareSpec}`\n }\n return parsed\n } else {\n const hasScope = specOrBareSpec.startsWith('@')\n const at = findFirstAt(specOrBareSpec, hasScope)\n if (at > -1) {\n return Spec.parse(\n specOrBareSpec.substring(0, at),\n specOrBareSpec.substring(at + 1),\n options,\n )\n } else if (\n findGitIdentifier(specOrBareSpec) ||\n (!hasScope && findFileIdentifier(specOrBareSpec))\n ) {\n return Spec.parse('(unknown)', specOrBareSpec, options)\n } else {\n // doesn't have an @, so it's just a name with no version\n return Spec.parse(`${specOrBareSpec}@`, options)\n }\n }\n }\n\n type: 'file' | 'git' | 'registry' | 'remote' | 'workspace'\n spec: string\n options: SpecOptionsFilled\n name: string\n scope?: Scope\n scopeRegistry?: string\n bareSpec: string\n gitRemote?: string\n gitSelector?: string\n gitSelectorParsed?: GitSelectorParsed\n gitCommittish?: string\n namedGitHost?: string\n namedGitHostPath?: string\n workspaceSpec?: string\n workspace?: string\n namedRegistry?: string\n registry?: string\n registrySpec?: string\n conventionalRegistryTarball?: string\n semver?: string\n range?: Range\n distTag?: string\n remoteURL?: string\n file?: string\n subspec?: Spec\n #final?: Spec\n #toString?: string\n\n /**\n * Return the final entry in the chain of subspecs\n * When deciding which thing to actually fetch, spec.final is the thing\n * to look at.\n */\n get final(): Spec {\n if (this.#final) return this.#final\n return (this.#final = this.subspec ? this.subspec.final : this)\n }\n\n /**\n * Normally, the string value of a Spec is just the string passed in to\n * be parsed. However, in the case of a chain of subspecs, like\n * `foo@npm:bar@npm:baz@npm:quux@latest`, this simplifies out the middle\n * parts of the chain, returning just `foo@npm:quux@latest`\n */\n toString() {\n if (this.#toString !== undefined) return this.#toString\n let sub: Spec = this\n // we want the SECOND from the last in the chain\n while (sub.subspec?.subspec) sub = sub.subspec\n if (sub.subspec && sub.subspec.type !== 'registry')\n sub = sub.subspec\n return (this.#toString = this.name + '@' + sub.bareSpec)\n }\n\n constructor(name: string, bareSpec: string, options?: SpecOptions)\n constructor(spec: string, options?: SpecOptions)\n constructor(\n spec: Spec | string,\n bareOrOptions?: SpecOptions | string,\n options?: SpecOptions,\n )\n constructor(\n spec: string,\n bareOrOptions?: SpecOptions | string,\n options: SpecOptions = {},\n ) {\n if (bareOrOptions && typeof bareOrOptions === 'object') {\n options = bareOrOptions\n bareOrOptions = undefined\n }\n this.options = getOptions(options)\n\n if (typeof bareOrOptions === 'string') {\n this.name = spec\n this.#parseScope(spec)\n this.bareSpec = bareOrOptions\n this.spec = `${this.name}@${bareOrOptions}`\n } else {\n this.spec = spec\n const hasScope = spec.startsWith('@')\n let at = findFirstAt(spec, hasScope)\n if (at === -1) {\n // assume that an unadorned spec is just a name at the default\n // registry\n at = spec.length\n spec += '@'\n }\n this.name = spec.substring(0, at)\n if (hasScope) this.#parseScope(this.name)\n this.bareSpec = spec.substring(at + 1)\n }\n\n // legacy affordance: allow project urls like\n // 'https://github.com/user/project#commitish' because npm suports it and\n // this pattern is observed in the wild.\n if (this.bareSpec.startsWith('https://')) {\n for (const [name, origin] of Object.entries(gitHostWebsites)) {\n if (this.bareSpec.startsWith(origin)) {\n const parsed = new URL(this.bareSpec)\n const [user, project] = parsed.pathname\n .replace(/\\.git$/, '')\n .replace(/\\/+/g, ' ')\n .trim()\n .split(' ')\n if (user && project) {\n this.bareSpec = `${name}:${user}/${project}${parsed.hash}`\n this.spec = `${this.name}@${this.bareSpec}`\n break\n }\n }\n }\n }\n\n if (this.bareSpec.startsWith('workspace:')) {\n this.type = 'workspace'\n const ws = this.bareSpec.substring('workspace:'.length).trim()\n const w = ws.lastIndexOf('@')\n if (w === -1) {\n this.workspace = this.name\n } else {\n const wsName = ws.substring(0, w)\n if (\n !wsName ||\n wsName === '*' ||\n wsName === '~' ||\n wsName === '^' ||\n (wsName.startsWith('@') ?\n wsName.split('/').length !== 2 ||\n wsName.substring(1).includes('@')\n : wsName.includes('@'))\n ) {\n throw this.#error(\n 'workspace: name must be a path or valid package name',\n { found: wsName },\n )\n }\n this.workspace = wsName\n }\n // workspace: is the same as workspace:*\n const wss = w === -1 ? ws : ws.substring(w + 1) || '*'\n const range = wss === '*' ? undefined : parseRange(wss)\n if (wss !== '*' && wss !== '~' && wss !== '^' && !range) {\n throw this.#error(\n 'workspace: spec must be one of *, ~, or ^, or a valid semver range',\n {\n found: wss,\n wanted: `'*'|'~'|'^'|SemverRange`,\n },\n )\n }\n this.workspaceSpec = wss\n if (range) {\n this.semver = wss\n this.range = range\n }\n return\n }\n\n if (\n this.bareSpec.startsWith('git://') ||\n this.bareSpec.startsWith('git+ssh://') ||\n this.bareSpec.startsWith('git+http://') ||\n this.bareSpec.startsWith('git+https://') ||\n this.bareSpec.startsWith('git+file://') ||\n // legacy affordance\n this.bareSpec.startsWith('git@github.com')\n ) {\n if (this.bareSpec.startsWith('git@')) {\n this.bareSpec = `git+ssh://${this.bareSpec}`\n this.spec = `${this.name}@${this.bareSpec}`\n }\n this.type = 'git'\n // see if it's one of the known named hosts, and if so, prefer\n // the shorter syntax.\n for (const [name, host] of Object.entries(\n this.options['git-hosts'],\n )) {\n const s = host.indexOf('$')\n if (s > 0 && this.bareSpec.startsWith(host.substring(0, s))) {\n const p = this.bareSpec\n .substring(s)\n .replace(/\\.git(#.*)?$/, '$1')\n this.bareSpec = `${name}:${p}`\n this.spec = `${this.name}@${this.bareSpec}`\n this.#parseHostedGit(name, host)\n this.type = 'git'\n return\n }\n }\n this.#parseGitSelector(this.bareSpec)\n return\n }\n\n // spooky\n const ghosts = Object.entries(this.options['git-hosts'])\n for (const [name, template] of ghosts) {\n if (this.#parseHostedGit(name, template)) {\n this.type = 'git'\n return\n }\n }\n\n if (this.bareSpec.startsWith('registry:')) {\n const reg = this.bareSpec.substring('registry:'.length)\n const h = reg.indexOf('#')\n if (h === -1) {\n throw this.#error('registry: must include name/version')\n }\n this.type = 'registry'\n let url = reg.substring(0, h)\n if (!url.endsWith('/')) url += '/'\n const regSpec = reg.substring(h + 1)\n for (let [name, u] of Object.entries(this.options.registries)) {\n if (!u.endsWith('/')) {\n u += '/'\n this.options.registries[name] = u\n }\n if (u === url) this.namedRegistry = name\n }\n this.#parseRegistrySpec(regSpec, url)\n this.#guessRegistryTarball()\n return\n }\n\n const regs = Object.entries(this.options.registries)\n for (const [host, url] of regs) {\n const h = `${host}:`\n if (this.bareSpec.startsWith(h)) {\n this.type = 'registry'\n this.namedRegistry = host\n this.#parseRegistrySpec(\n this.bareSpec.substring(h.length),\n url,\n ).namedRegistry ??= host\n this.#guessRegistryTarball()\n return\n }\n }\n\n if (\n this.bareSpec.startsWith('https://') ||\n this.bareSpec.startsWith('http://')\n ) {\n this.remoteURL = this.bareSpec\n this.type = 'remote'\n return\n }\n\n // explicit file: url\n if (this.bareSpec.startsWith('file:')) {\n this.type = 'file'\n const [path, uri] = normalizeFile(this.bareSpec, this)\n this.file = path\n this.bareSpec = uri.replace(/\\/+$/, '')\n this.spec = `${this.name}@${this.bareSpec}`\n return\n }\n\n // legacy! once upon a time, `user/project` was a shorthand for pulling\n // packages from github, instead of the more verbose and explicit\n // `github:user/project`.\n if (\n !this.bareSpec.startsWith('./') &&\n !this.bareSpec.startsWith('../') &&\n this.options['git-hosts'].github\n ) {\n const hash = this.bareSpec.indexOf('#')\n const up =\n hash === -1 ? this.bareSpec : this.bareSpec.substring(0, hash)\n if (up.split('/').length === 2) {\n this.bareSpec = `github:${this.bareSpec}`\n this.spec = `${this.name}@${this.bareSpec}`\n this.#parseHostedGit(\n 'github',\n this.options['git-hosts'].github,\n )\n this.type = 'git'\n return\n }\n }\n\n // if it contains a / and isn't picked up in the github shorthand,\n // then convert to file: specifier\n if (\n this.bareSpec.includes('/') ||\n this.bareSpec === '.' ||\n this.bareSpec === '..'\n ) {\n this.type = 'file'\n const [file, uri] = normalizeFile(`file:${this.bareSpec}`, this)\n this.bareSpec = uri\n this.spec = `${this.name}@${this.bareSpec}`\n this.file = file\n return\n }\n\n // at this point, must be either semver range or dist-tag\n this.type = 'registry'\n const range = parseRange(this.bareSpec)\n if (range) {\n this.semver = this.bareSpec.trim()\n this.range = range\n } else {\n this.distTag = this.bareSpec\n }\n this.registrySpec = this.bareSpec\n const { 'scope-registries': scopeRegs, registry } = this.options\n const scopeReg = this.scope && scopeRegs[this.scope]\n this.registry = scopeReg ?? registry\n this.#guessRegistryTarball()\n }\n\n #parseScope(name: string) {\n if (!name.startsWith('@')) return\n const s = name.indexOf('/')\n if (s > 1 && s < name.length - 1) {\n const scope = name.substring(0, s) as Scope\n this.registry = this.scopeRegistry =\n this.options['scope-registries'][scope]\n this.scope = scope\n }\n }\n\n #parseHostedGit(name: string, template: string) {\n if (this.bareSpec.startsWith(`${name}:`)) {\n const h = this.bareSpec.indexOf('#')\n const bare =\n h === -1 ? this.bareSpec : this.bareSpec.substring(0, h)\n const hash = h === -1 ? '' : this.bareSpec.substring(h)\n const hostPath = bare.substring(name.length + 1)\n if (!hostPath) {\n throw error('invalid named git host specifier', {\n spec: this,\n })\n }\n const split = hostPath.split('/')\n let t = template\n for (let i = 0; i < split.length; i++) {\n t = t.split(`$${i + 1}`).join(split[i])\n }\n t += hash\n this.namedGitHost = name\n this.namedGitHostPath = hostPath\n this.#parseGitSelector(t)\n if (this.gitCommittish && !this.gitSelectorParsed?.path) {\n const archiveHost = this.options['git-host-archives'][name]\n if (archiveHost) {\n this.type = 'remote'\n let t = archiveHost\n t = t.split('$committish').join(this.gitCommittish)\n for (let i = 0; i < split.length; i++) {\n t = t.split(`$${i + 1}`).join(split[i])\n }\n this.remoteURL = t\n }\n }\n return true\n }\n return false\n }\n\n [kCustomInspect](\n _depth?: number,\n options?: InspectOptions,\n ): string {\n const str = inspect(\n Object.fromEntries(\n Object.entries(this).filter(([k, v]) => {\n return k !== 'options' && v !== undefined\n }),\n ),\n options,\n )\n return `@vltpkg/spec.Spec ${str}`\n }\n\n #guessRegistryTarball() {\n // only try to guess if it's a single comparator for a single version\n const { name, registry, range } = this.final\n if (!registry || !range?.isSingle) return\n const stripScope = /^@[^/]+\\//\n this.conventionalRegistryTarball = String(\n new URL(\n `/${name}/-/${name.replace(stripScope, '')}-${range}.tgz`,\n registry,\n ),\n )\n }\n\n #parseRegistrySpec(s: string, url: string) {\n // note: this takes priority over the scoped registry, if set\n this.registry = url\n this.subspec = Spec.parse(s, {\n ...this.options,\n registry: url,\n })\n return this.subspec\n }\n\n #error(message: string, extra: ErrorCauseObject = {}) {\n return error(message, { spec: this.spec, ...extra }, this.#error)\n }\n\n #parseGitSelector(s: string) {\n const h = s.indexOf('#')\n if (h === -1) {\n this.gitRemote = s\n return\n }\n this.gitRemote = s.substring(0, h)\n this.gitSelector = s.substring(h + 1)\n const [selectorParsed, committish, range] = Spec.parseGitSelector(\n this.gitSelector,\n this,\n )\n this.range = range\n this.gitCommittish = committish\n this.gitSelectorParsed = selectorParsed\n }\n\n /**\n * Should only ever be called with the bit that comes AFTER the #\n * in the git remote url.\n */\n static parseGitSelector(\n selector: string,\n spec?: Spec,\n ): [parsed: GitSelectorParsed, committish?: string, range?: Range] {\n if (!selector) return [{}]\n const split = selector.split('::')\n const first = split[0]\n let committish: string | undefined = undefined\n let range: Range | undefined = undefined\n const parsed: GitSelectorParsed = {}\n\n /* c8 ignore start - for TS's benefit */\n if (typeof first !== 'string') {\n throw typeError('impossible', {\n found: first,\n wanted: String,\n })\n }\n /* c8 ignore stop */\n if (!first.includes(':')) {\n committish = first\n split.shift()\n }\n for (const kv of split) {\n const c = kv.indexOf(':')\n /* c8 ignore next */\n if (c === -1) continue\n const k = kv.substring(0, c)\n const v = kv.substring(c + 1)\n if (k === 'semver') {\n if (committish) {\n throw error(\n 'Cannot specify a semver range and committish value',\n { spec },\n )\n }\n range = parseRange(v)\n if (!range) {\n throw error(`Invalid git tag semver range: ${v}`, { spec })\n }\n }\n if (k === 'semver' || k === 'path') {\n if (k === 'path') {\n if (isAbsolute(v) || /(^|\\/|\\\\)\\.\\.($|\\\\|\\/)/.test(v)) {\n throw error('Invalid path in git selector', { spec })\n }\n // normalize\n parsed.path = join('/', v).substring(1).replace(/\\\\/g, '/')\n } else {\n parsed[k] = v\n }\n }\n }\n return [parsed, committish, range]\n }\n}\n\n// normalize our kinda-sorta spec compliant `file:` specifiers\n//\n// For historical reasons, we need to support a lot of non-spec-compliant\n// behaviors, but this massages the result into a *slightly* less offensive\n// shape.\n//\n// The result will be either a fully compliant `file://` with an absolute path,\n// or a `file:` with a relative path starting with `~`, `./`, or `../`.\nconst normalizeFile = (\n bareSpec: string,\n spec: Spec,\n): [path: string, uri: string] => {\n const slashes = bareSpec.substring('file:'.length, 'file://'.length)\n const pref = `file:${slashes === '//' ? slashes : ''}`\n const rest = bareSpec.substring(pref.length)\n\n // default to '/' because eol == '/' for parsing purposes\n const [a = '', b = '/', c = '/', d = '/'] = rest.split('', 4)\n\n if (!a) {\n // file:// => file:.\n // file: => file:.\n return ['.', 'file:.']\n }\n\n if (\n (a === '/' && b === '~' && c !== '/') ||\n (a === '~' && b !== '/')\n ) {\n throw error(\n `invalid file: specifier. '~username' not supported`,\n { spec },\n )\n }\n\n if (a === '~') {\n // file://~ => file:~\n // file://~/x => file:~/x\n return [resolve(homedir(), rest.substring(2)), `file:${rest}`]\n }\n\n if (a === '/' && b === '~') {\n // file:///~ => file:~\n // file:/~/x => file:~/x\n return [\n resolve(homedir(), rest.substring(3)),\n `file:${rest.substring(1)}`,\n ]\n }\n\n if (\n a === '/' &&\n b === '.' &&\n (c === '/' || (c === '.' && d === '/'))\n ) {\n // file:/./x => file:./x\n // file:///./x => file:./x\n // file:/../x => file:../x\n // file://../x => file:../x\n return [rest.substring(1), `file:${rest.substring(1)}`]\n }\n\n if (a === '.' && (b === '/' || (b === '.' && c === '/'))) {\n // file://. => file:.\n // file://./x => file:./x\n // file://../x => file:../x\n return [rest, `file:${rest}`]\n }\n\n if (slashes === '//') {\n // must be valid URI, since we ruled out relative and homedir above\n\n // not relative, but note that file://host/share is\n // windows-specific and does not work on darwin, so disallow it.\n try {\n const parsed = new URL(bareSpec)\n if (parsed.host) {\n if (parsed.host !== 'localhost') {\n throw error(\n `invalid file:// specifier. host must be empty or 'localhost'`,\n {\n spec,\n found: parsed.host,\n validOptions: ['', 'localhost'],\n },\n )\n }\n }\n // normalize blank authority\n // file://X:/foo => file:///X:/foo\n // file://localhost/x => file:///x\n // interpret a `file:///D:/x` as `D:/x` though\n return [\n parsed.pathname.replace(/^\\/([a-zA-Z]:\\/)/, '$1'),\n `file://${parsed.pathname}`,\n ]\n } catch (er) {\n // invalid URI for other reasons, eg file://x\\u0000y/z\n throw error('invalid file:// specifier', {\n spec,\n cause: er as Error,\n })\n }\n }\n\n // no //, no authority, be ungovernable\n\n if (winPath.isAbsolute(rest)) {\n // file:/absolute => file:///absolute\n // file:/D:/foo => file:///D:/foo\n return [rest, `file://${rest}`]\n }\n\n // file:x => file:./x\n return [`./${rest}`, `file:./${rest}`]\n}\n", "import { error } from '@vltpkg/error-cause'\nimport { Spec, SpecOptions } from '@vltpkg/spec'\nimport { Manifest } from '@vltpkg/types'\n\nexport const delimiter: Delimiter = '·'\nexport type Delimiter = '·'\n\n/**\n * Dependency IDs are a URI-encoded set of strings, separated\n * by the {@link Delimiter} character (`'·'`).\n *\n * The first entry is always the specifier type. The rest depend on the\n * type. `git`, `registry`, and `workspace` entries have 3 fields, the rest\n * have 2.\n *\n * - `registry`: `'registry·<registry>·name@specifier'`\n * The `<registry>` portion can be a known named registry name, or a\n * url to a registry. If empty, it is the default registry.\n * Examples:\n * - `··some-package@2.0.1`\n * - `·npm·whatever@1.2.3'\n * - `·http%3A%2F%2Fvlt.sh%2F·x@1.2.3`\n * - `git`: `'git·<git remote>·<git selector>`. For example:\n * - `git·github:user/project·branchname`\n * - `git·git%2Bssh%3A%2F%2Fuser%40host%3Aproject.git·semver:1.x`\n * - `workspace`: `'workspace·<path>`. For example:\n * - `workspace·src/mything`\n * - `remote`: `'remote·<url>'`\n * - `file`: `'file·<path>`\n *\n * Lastly, the final portion can contain arbitrary string data, and is\n * used to store peer dep resolutions to maintain the peerDep contract.\n */\nexport type DepID =\n | `${'' | 'git'}${Delimiter}${string}${Delimiter}${string}${Delimiter}${string}`\n | `${'' | 'git'}${Delimiter}${string}${Delimiter}${string}`\n | `${'file' | 'remote' | 'workspace'}${Delimiter}${string}${Delimiter}${string}`\n | `${'file' | 'remote' | 'workspace'}${Delimiter}${string}`\n\n/**\n * A {@link DepID}, split apart and URI-decoded\n */\nexport type DepIDTuple =\n | [\n type: 'git',\n gitRemote: string,\n gitSelector: string,\n extra?: string,\n ]\n | [\n type: 'registry',\n registry: string,\n registrySpec: string,\n extra?: string,\n ]\n | [type: 'file', path: string, extra?: string]\n | [type: 'remote', url: string, extra?: string]\n | [type: 'workspace', workspace: string, extra?: string]\n\nconst depIDRegExp = new RegExp(\n `^((git)?${delimiter}[^${delimiter}]*${delimiter}[^${delimiter}]*(${\n delimiter\n }[^${delimiter}]*)?$` +\n `|` +\n `^(file|remote|workspace)${delimiter}[^${\n delimiter\n }]*)(${delimiter}[^${delimiter}]*)?$`,\n)\n\nexport const isDepID = (str: unknown): str is DepID =>\n typeof str === 'string' && depIDRegExp.test(str)\n\nexport const asDepID = (str: string): DepID => {\n if (!isDepID(str)) {\n throw error('Expected dep id', {\n found: str,\n })\n }\n return str\n}\n\n/**\n * turn a {@link DepIDTuple} into a {@link DepID}\n */\nexport const joinDepIDTuple = (list: DepIDTuple): DepID => {\n const [type, first, second, extra] = list\n const f = encode(first)\n switch (type) {\n case 'registry':\n return `${delimiter}${f}${delimiter}${encode(second)}${extra ? `${delimiter}${encode(extra)}` : ''}`\n case 'git':\n return `${type}${delimiter}${f}${delimiter}${encode(second)}${extra ? `${delimiter}${encode(extra)}` : ''}`\n default:\n return `${type}${delimiter}${f}${second ? `${delimiter}${encode(second)}` : ''}`\n }\n}\n\n// allow @, but otherwise, escape everything urls do\nconst encode = (s: string): string =>\n encodeURIComponent(s).replaceAll('%40', '@')\n\n/**\n * turn a {@link DepID} into a {@link DepIDTuple}\n */\nexport const splitDepID = (id: string): DepIDTuple => {\n const [type, first = '', second, extra] = id.split(delimiter, 4)\n const f = decodeURIComponent(first)\n switch (type) {\n case 'git':\n case '': {\n if (second === undefined) {\n throw error(`invalid ${type} id`, { found: id })\n }\n const t: DepIDTuple = [\n type || 'registry',\n f,\n decodeURIComponent(second),\n ]\n if (extra) t.push(decodeURIComponent(extra))\n return t\n }\n case 'file':\n case 'remote':\n case 'workspace': {\n const t: DepIDTuple = [type, f]\n if (second) t.push(decodeURIComponent(second))\n return t\n }\n default: {\n throw error('invalid DepID type', {\n found: type,\n validOptions: ['git', 'file', 'workspace', 'remote', ''],\n })\n }\n }\n}\n\n/**\n * Turn a {@link DepID} into a {@link Spec} object\n */\nexport const hydrate = (\n id: DepID,\n name?: string,\n options: SpecOptions = {},\n): Spec => hydrateTuple(splitDepID(id), name, options)\n\n/**\n * Turn a {@link DepIDTuple} into a {@link Spec} object\n */\nexport const hydrateTuple = (\n tuple: DepIDTuple,\n name?: string,\n options: SpecOptions = {},\n) => {\n const [type, first, second] = tuple\n switch (type) {\n case 'remote': {\n if (!first)\n throw error('no remoteURL found on remote id', {\n found: tuple,\n })\n return Spec.parse(name ?? '(unknown)', first)\n }\n case 'file': {\n if (!first) {\n throw error('no file path found on remote id', {\n found: tuple,\n })\n }\n return Spec.parse(name ?? '(unknown)', `file:${first}`, options)\n }\n case 'registry': {\n if (typeof first !== 'string') {\n throw error('no registry url or name in registry ID', {\n found: tuple,\n })\n }\n if (!second) {\n throw error('no name/specifier in registry ID', {\n found: tuple,\n })\n }\n if (!first) {\n // just a normal name@version on the default registry\n const s = Spec.parse(second)\n if (name && s.name !== name) {\n return Spec.parse(`${name}@npm:${second}`)\n } else {\n return s\n }\n }\n if (!/^https?:\\/\\//.test(first)) {\n const reg = options.registries?.[first]\n if (first !== 'npm' && !reg) {\n throw error('named registry not found in options', {\n name: first,\n found: tuple,\n })\n }\n return Spec.parse(\n name ?? '(unknown)',\n `${first}:${second}`,\n options,\n )\n }\n const s = Spec.parse(\n name ?? '(unknown)',\n `registry:${first}#${second}`,\n options,\n )\n return name && s.final.name !== name ?\n Spec.parse(s.final.name + '@' + s.bareSpec)\n : s\n }\n case 'git': {\n if (!first) {\n throw error('no git remote in git ID', {\n found: tuple,\n })\n }\n return Spec.parse(\n name ?? '(unknown)',\n first + '#' + second,\n options,\n )\n }\n case 'workspace': {\n if (!first) {\n throw error('no name/path on workspace id', { found: tuple })\n }\n return name && name !== first ?\n Spec.parse(name, `workspace:${first}@*`, options)\n : Spec.parse(first, `workspace:*`, options)\n }\n }\n}\n\n// Strip out the default registry, there's no need to store that\nconst omitDefReg = (s?: string): string =>\n (\n !s ||\n s === 'https://registry.npmjs.org' ||\n s === 'https://registry.npmjs.org/'\n ) ?\n ''\n : s\n\n/**\n * Get the {@link DepIDTuple} for a given {@link Spec} and {@link Manifest}.\n * The Manifest is used to get the name and version, if possible. If not found\n * in the manifest, registry ID types will use the name or bareSpec from the\n * specifier, so at least there's something to use later.\n */\nexport const getTuple = (spec: Spec, mani: Manifest): DepIDTuple => {\n const f = spec.final\n switch (f.type) {\n case 'registry': {\n // try to shorten to a known name if we can.\n const reg = omitDefReg(f.registry)\n if (!f.namedRegistry && reg) {\n for (const [alias, host] of Object.entries(\n spec.options.registries,\n )) {\n if (reg === host) {\n f.namedRegistry = alias\n break\n }\n }\n }\n return [\n f.type,\n f.namedRegistry ?? reg,\n `${mani.name ?? spec.name}@${mani.version ?? spec.bareSpec}`,\n ]\n }\n case 'git': {\n const {\n namedGitHost,\n namedGitHostPath,\n gitRemote,\n gitSelector = '',\n } = f\n if (!gitRemote)\n throw error('no host on git specifier', { spec })\n if (namedGitHost) {\n if (!namedGitHostPath) {\n throw error('named git host without path portion', {\n spec,\n })\n }\n return [\n f.type,\n `${namedGitHost}:${namedGitHostPath}`,\n gitSelector,\n ]\n } else {\n return [f.type, gitRemote, gitSelector]\n }\n }\n case 'remote': {\n const { remoteURL } = f\n if (!remoteURL)\n throw error('no URL on remote specifier', { spec })\n return [f.type, remoteURL]\n }\n case 'file':\n case 'workspace':\n throw error('Path-based dep ids are not supported', { spec })\n }\n}\n\n/**\n * Get the {@link DepID} for a given {@link Spec} and {@link Manifest}. The\n * Manifest is used to get the name and version, if possible. If not found in\n * the manifest, registry ID types will use the name or bareSpec from the\n * specifier, so at least there's something to use later.\n */\nexport const getId = (spec: Spec, mani: Manifest): DepID =>\n joinDepIDTuple(getTuple(spec, mani))\n", "import { DepID, joinDepIDTuple } from '@vltpkg/dep-id'\nimport { error } from '@vltpkg/error-cause'\nimport { PackageJson } from '@vltpkg/package-json'\nimport { Manifest } from '@vltpkg/types'\nimport { readFileSync, statSync } from 'fs'\nimport { GlobOptionsWithFileTypesFalse, globSync } from 'glob'\nimport { DepResults, graphRun, graphRunSync } from 'graph-run'\nimport { basename, resolve, posix } from 'path'\nimport { Path, PathScurry } from 'path-scurry'\nimport { parse } from 'polite-json'\nimport { minimatch } from 'minimatch'\n\nexport type WorkspacesLoadedConfig = {\n workspace?: string[]\n 'workspace-group'?: string[]\n}\n\n/**\n * The object passed to the constructor or {@link Monorepo#load} to limit which\n * {@link Workspace Workspaces} get loaded.\n */\nexport type LoadQuery = {\n /**\n * A glob pattern string, or an array of them. Only workspaces found\n * in paths matched will be loaded.\n */\n paths?: string[] | string\n /**\n * A string, or an array of strings. If set, only workspaces in the\n * specified groups named will be included, if set.\n */\n groups?: string[] | string\n}\n\n/**\n * Canonical form of the {@link WorkspaceConfig}, used\n * internally for consistency.\n */\nexport type WorkspaceConfigObject = Record<string, string[]>\n\n/**\n * Allowed datatype in the `vlt-workspaces.json` file.\n */\nexport type WorkspaceConfig =\n | string[]\n | WorkspaceConfigObject\n | string\n\n/**\n * Turn a {@link WorkspaceConfig} into a\n * {@link WorkspaceConfigObject}, or throw if it's not valid.\n */\nexport const asWSConfig = (\n conf: unknown,\n path?: string,\n): WorkspaceConfigObject => {\n assertWSConfig(conf, path)\n return (\n typeof conf === 'string' ? { packages: [conf] }\n : Array.isArray(conf) ? { packages: conf }\n : conf\n )\n}\n\n/**\n * Throw if the provided value is not a valid {@link WorkspaceConfig}\n */\nexport const assertWSConfig: (\n conf: unknown,\n path?: string,\n) => asserts conf is WorkspaceConfig = (\n conf: unknown,\n path?: string,\n) => {\n if (typeof conf === 'string') return conf\n\n if (Array.isArray(conf)) {\n for (const c of conf) {\n if (typeof c !== 'string') {\n throw error('Invalid workspace definition', {\n path,\n found: c,\n wanted: 'string',\n })\n }\n }\n return\n }\n\n if (conf && typeof conf === 'object') {\n for (const [group, value] of Object.entries(conf)) {\n if (typeof value === 'string') continue\n if (Array.isArray(value)) {\n for (const c of value) {\n if (typeof c !== 'string') {\n throw error('Invalid workspace definition', {\n path,\n name: group,\n found: c,\n wanted: 'string',\n })\n }\n }\n continue\n }\n throw error('Invalid workspace definition', {\n path,\n name: group,\n found: value,\n wanted: 'string | string[]',\n })\n }\n return\n }\n\n throw error('Invalid workspace definition', {\n path,\n found: conf,\n wanted:\n 'string | string[] | { [group: string]: string | string[] }',\n })\n}\n\nexport type MonorepoOptions = {\n /**\n * A {@link PackageJson} object, for sharing manifest caches\n */\n packageJson?: PackageJson\n /**\n * A {@link PathScurry} object, for use in globs\n */\n scurry?: PathScurry\n /** Parsed normalized contents of a `vlt-workspaces.json` file */\n config?: WorkspaceConfigObject\n /**\n * If set, then {@link Monorepo#load} will be called immediately with\n * this argument.\n */\n load?: LoadQuery\n}\n\n/**\n * Class representing a Monorepo containing multiple workspaces.\n *\n * Does not automatically look up the root, but that can be provided by\n * running `Config.load()`, since it stops seeking the route when a\n * `vlt-workspaces.json` file is encountered.\n */\nexport class Monorepo {\n /** The project root where vlt-workspaces.json is found */\n projectRoot: string\n /** Scurry object to cache all filesystem calls (mostly globs) */\n scurry: PathScurry\n\n // maps both name and path to the workspace objects\n #workspaces = new Map<string, Workspace>()\n #groups = new Map<string, Set<Workspace>>()\n #config?: WorkspaceConfigObject\n packageJson: PackageJson\n\n /**\n * Number of {@link Workspace} objects loaded in this Monorepo\n */\n get size(): number {\n return [...this.values()].length\n }\n\n constructor(projectRoot: string, options: MonorepoOptions = {}) {\n this.projectRoot = resolve(projectRoot)\n this.scurry = options.scurry ?? new PathScurry(projectRoot)\n this.packageJson = options.packageJson ?? new PackageJson()\n this.#config = options.config\n if (options.load) this.load(options.load)\n }\n\n /**\n * Load the workspace definitions from vlt-workspaces.json,\n * canonicalizing the result into the effective `{[group:string]:string[]}`\n * form.\n *\n * Eg:\n * - `\"src/*\"` => `{packages:[\"src/*\"]}`\n * - `{\"apps\": \"src/*\"}` => `{apps: [\"src/*\"]}`\n */\n get config(): WorkspaceConfigObject {\n if (this.#config) return this.#config\n const file = resolve(this.projectRoot, 'vlt-workspaces.json')\n let confData: string\n try {\n confData = readFileSync(file, 'utf8')\n } catch (er) {\n throw error('Not in a monorepo, no vlt-workspaces.json found', {\n path: this.projectRoot,\n cause: er as Error,\n })\n }\n let parsed: unknown\n try {\n parsed = parse(confData)\n } catch (er) {\n throw error('Invalid vlt-workspaces.json file', {\n path: this.projectRoot,\n cause: er as Error,\n })\n }\n this.#config = asWSConfig(parsed, file)\n return this.#config\n }\n\n /**\n * Iterating the Monorepo object yields the workspace objects, in as close to\n * topological dependency order as possible.\n */\n *[Symbol.iterator](): Generator<Workspace, void, void> {\n const [ws] = [...this.values()]\n if (!ws) return\n // leverage the fact that graphRun returns results in\n // as close to topological order as possible.\n for (const workspace of this.runSync(() => {}).keys()) {\n yield workspace\n }\n }\n\n /**\n * Iterating the Monorepo object yields the workspace objects, in as close to\n * topological dependency order as possible.\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<\n Workspace,\n void,\n void\n > {\n const [ws] = [...this.values()]\n if (!ws) return\n for (const workspace of (await this.run(() => {})).keys()) {\n yield workspace\n }\n }\n\n /**\n * By default, loads all workspaces reachable in the Monorepo.\n *\n * If provided with one (`string`)or more (`string[]`) group names in\n * the {@link LoadQuery#groups} field, then only Workspaces in the named\n * group(s) will be considered. Note that group names are unique string\n * matches, not globs.\n *\n * If provided with a set of arbitrary path arguments, then only paths\n * patching the provided pattern(s) will be included.\n *\n * These two options intersect, so\n * `load({groups:'foo', paths:'./foo/[xy]*'})` will only load the workspaces\n * in the group `foo` that match the paths glob.\n */\n load(query: LoadQuery = {}): this {\n const paths = new Set(\n typeof query.paths === 'string' ?\n [query.paths]\n : (query.paths ?? []),\n )\n const groups = new Set(\n typeof query.groups === 'string' ?\n [query.groups]\n : (query.groups ?? []),\n )\n\n const groupsExpanded: Record<string, Set<string>> = {}\n for (const [group, pattern] of Object.entries(this.config)) {\n if (groups.size && !groups.has(group)) continue\n groupsExpanded[group] = this.#glob(pattern)\n }\n const filter = paths.size ? this.#glob([...paths]) : paths\n\n // if we specified paths, but none matched, nothing to do\n if (paths.size && !filter.size) return this\n\n for (const [group, matches] of Object.entries(groupsExpanded)) {\n for (const path of matches) {\n if (filter.size && !filter.has(path)) continue\n this.#loadWS(path, group)\n }\n }\n\n return this\n }\n\n // Either load a workspace from disk, or from our internal set,\n // and assign it to the named group\n #loadWS(path: string, group?: string): Workspace {\n const fullpath = resolve(this.projectRoot, path)\n const loaded = this.#workspaces.get(fullpath)\n if (loaded) return loaded\n const fromCache = workspaceCache.get(fullpath)\n const manifest =\n fromCache?.manifest ?? this.packageJson.read(fullpath)\n const ws = fromCache ?? new Workspace(path, manifest, fullpath)\n if (group) ws.groups.push(group)\n this.#workspaces.set(ws.fullpath, ws)\n this.#workspaces.set(ws.path, ws)\n this.#workspaces.set(ws.name, ws)\n for (const name of ws.groups) {\n const group = this.#groups.get(name) ?? new Set()\n group.add(ws)\n this.#groups.set(name, group)\n }\n return ws\n }\n\n // can't be cached, because it's dependent on the matches set\n // but still worthwhile to have it defined in one place\n #globOptions(matches: Set<string>): GlobOptionsWithFileTypesFalse {\n // if the entry or any of its parent dirs are already matched,\n // then we should not explore further down that directory tree.\n // if we hit the projectRoot then stop searching.\n const inMatches = (p?: Path): boolean => {\n return (\n !!p?.relativePosix() &&\n (matches.has(p.relativePosix()) || inMatches(p.parent))\n )\n }\n\n return {\n root: this.projectRoot,\n cwd: this.projectRoot,\n posix: true,\n scurry: this.scurry,\n withFileTypes: false,\n ignore: {\n childrenIgnored: p =>\n basename(p.relativePosix()) === 'node_modules' ||\n inMatches(p),\n // ignore if fails to load package.json\n ignored: p => {\n p.lstatSync()\n const rel = p.relativePosix()\n if (!rel) return true\n const maybeDelete: string[] = []\n for (const m of matches) {\n if (rel.startsWith(m + '/')) return true\n if (m.startsWith(rel + '/')) {\n maybeDelete.push(m)\n }\n }\n if (!p.isDirectory()) return true\n const pj = p.resolve('package.json').lstatSync()\n if (!pj?.isFile()) return true\n try {\n this.packageJson.read(p.fullpath())\n } catch {\n return true\n }\n for (const m of maybeDelete) {\n matches.delete(m)\n }\n matches.add(rel)\n return false\n },\n },\n }\n }\n\n #glob(pattern: string[] | string) {\n const matches = new Set<string>()\n globSync(pattern, this.#globOptions(matches))\n return matches\n }\n\n /**\n * Return the array of workspace dependencies that are found in\n * the loaded set, for use in calculating dependency graph order for\n * build operations.\n *\n * This does *not* get the full set of dependencies, or expand any\n * `workspace:` dependencies that are not loaded.\n *\n * Call with the `forceLoad` param set to `true` to attempt a full\n * load if any deps are not currently loaded.\n */\n getDeps(ws: Workspace, forceLoad = false): Workspace[] {\n // load manifest and find workspace: deps\n // filter by those loaded\n const { manifest } = ws\n const depWorkspaces: Workspace[] = []\n let didForceLoad = false\n for (const depType of [\n 'dependencies',\n 'devDependencies',\n 'optionalDependencies',\n 'peerDependencies',\n ]) {\n const deps = manifest[depType] as Manifest['dependencies']\n if (!deps) continue\n for (const [dep, spec] of Object.entries(deps)) {\n if (spec.startsWith('workspace:')) {\n let depWS = this.#workspaces.get(dep)\n if (!depWS) {\n if (!forceLoad) continue\n if (didForceLoad) continue\n didForceLoad = true\n this.load()\n depWS = this.#workspaces.get(dep)\n if (!depWS) continue\n }\n depWorkspaces.push(depWS)\n }\n }\n }\n return depWorkspaces\n }\n\n /** @todo */\n onCycle(\n _ws: Workspace,\n _cycle: Workspace[],\n _depPath: Workspace[],\n ) {\n // XXX - process logging? Need to say something like:\n // Cyclical workspace dependency warning!\n // When evaluating dependency ${ws.name} via ${\n // path.map(ws => ws.name).join(' -> ')\n // }, a dependency cycle was detected: ${\n // cycle.map(ws => ws.name).join(' -> ')\n // }. Operation will continue, but dependency order not guaranteed.`\n }\n\n /**\n * Return the set of workspaces in the named group.\n * If the group is not one we know about, then undefined is returned.\n */\n group(group: string) {\n return this.#groups.get(group)\n }\n\n /**\n * Get a loaded workspace by path or name.\n *\n * Note that this can only return workspaces that were ingested via a\n * previous call to {@link Monorepo#load}.\n */\n get(nameOrPath: string) {\n return this.#workspaces.get(nameOrPath)\n }\n\n /**\n * get the list of all loaded workspace names used as keys\n */\n *names() {\n for (const [key, ws] of this.#workspaces) {\n if (key === ws.name) yield key\n }\n }\n\n /**\n * get the list of all loaded workspace paths used as keys\n */\n *paths() {\n for (const [key, ws] of this.#workspaces) {\n if (key === ws.path) yield key\n }\n }\n\n /**\n * get the workspace objects in no particular order.\n * this is ever so slightly faster than iterating, because it doesn't\n * explore the graph to yield results in topological dependency order,\n * and should be used instead when order doesn't matter.\n */\n *values() {\n const seen = new Set<string>()\n for (const ws of this.#workspaces.values()) {\n if (seen.has(ws.fullpath)) continue\n seen.add(ws.fullpath)\n yield ws\n }\n }\n\n /**\n * Get all the keys (package names and paths) for loaded workspaces.\n * Union of {@link Monorepo#names} and {@link Monorepo#paths}\n */\n *keys() {\n for (const ws of this.values()) {\n yield ws.path\n if (ws.name !== ws.path) yield ws.name\n }\n }\n\n /**\n * Filter the monorepo object yielding the workspace objects that matches\n * either of the {@link WorkspacesLoadedConfig} options provided, in as close\n * to topological dependency order as possible.\n */\n *filter({\n workspace: namesOrPaths,\n 'workspace-group': groupName,\n }: WorkspacesLoadedConfig) {\n const globPatternChecks = namesOrPaths?.map(glob =>\n minimatch.filter(posix.join(glob)),\n )\n for (const ws of this) {\n // check if any group has any of the provided group names\n if (groupName?.some(i => ws.groups.includes(i))) {\n yield ws\n continue\n }\n // check if any workspace-provided name directly matches any of the\n // configured workspaces by either name or file path\n if (\n namesOrPaths\n ?.map(i => posix.join(i))\n .some(i => ws.keys.includes(i))\n ) {\n yield ws\n continue\n }\n // check if one of the workspace values are matching glob patterns\n if (\n ws.keys.some(key => globPatternChecks?.some(fn => fn(key)))\n ) {\n yield ws\n }\n }\n }\n\n /**\n * Run an operation asynchronously over all loaded workspaces\n *\n * If the `forceLoad` param is true, then it will attempt to do a full load\n * when encountering a `workspace:` dependency that isn't loaded.\n *\n * Note that because the return type appears in the parameters of the\n * operation function, it must be set explicitly either in the operation\n * function signature or by calling `run<MyType>` or it'll fall back to\n * `unknown`, similar to `Array.reduce()`, and for the same reason.\n */\n async run<R>(\n operation: (\n s: Workspace,\n signal: AbortSignal,\n depResults: DepResults<Workspace, R>,\n ) => Promise<R> | R,\n forceLoad = false,\n ) {\n const [ws, ...rest] = [...this.#workspaces.values()]\n if (!ws) {\n throw error('No workspaces loaded', undefined, this.run)\n }\n\n return graphRun<Workspace, R>({\n graph: [ws, ...rest],\n getDeps: ws => this.getDeps(ws, forceLoad),\n visit: async (ws, signal, _, depResults) =>\n await operation(ws, signal, depResults),\n onCycle: (ws, cycle, path) => this.onCycle(ws, cycle, path),\n })\n }\n\n /**\n * Run an operation synchronously over all loaded workspaces\n *\n * If the `forceLoad` param is true, then it will attempt to do a full load\n * when encountering a `workspace:` dependency that isn't loaded.\n *\n * Note that because the return type appears in the parameters of the\n * operation function, it must be set explicitly either in the operation\n * function signature or by calling `runSync<MyType>` or it'll fall back to\n * `unknown`, similar to `Array.reduce()`, and for the same reason.\n */\n runSync<R>(\n operation: (\n s: Workspace,\n signal: AbortSignal,\n depResults: DepResults<Workspace, R>,\n ) => R,\n forceLoad = false,\n ) {\n const [ws, ...rest] = [...this.#workspaces.values()]\n if (!ws) {\n throw error('No workspaces loaded', undefined, this.run)\n }\n\n return graphRunSync<Workspace, R>({\n graph: [ws, ...rest],\n getDeps: ws => this.getDeps(ws, forceLoad),\n visit: (ws, signal, _, depResults) =>\n operation(ws, signal, depResults),\n onCycle: (ws, cycle, path) => this.onCycle(ws, cycle, path),\n })\n }\n\n /**\n * Convenience method to instantiate and load in one call.\n * Returns undefined if the project is not a monorepo workspaces\n * root, otherwise returns the loaded Monorepo.\n */\n static maybeLoad(\n projectRoot: string,\n options: MonorepoOptions = { load: {} },\n ) {\n try {\n if (\n !statSync(\n resolve(projectRoot, 'vlt-workspaces.json'),\n ).isFile()\n ) {\n return\n }\n } catch {\n return\n }\n const { load = {} } = options\n return new Monorepo(projectRoot, { ...options, load })\n }\n\n /**\n * Convenience method to instantiate and load in one call.\n * Throws if called on a directory that is not a workspaces root.\n */\n static load(\n projectRoot: string,\n options: MonorepoOptions = { load: {} },\n ) {\n const { load = {} } = options\n return new Monorepo(projectRoot, { ...options, load })\n }\n}\n\nexport const workspaceCache = new Map<string, Workspace>()\n\n/**\n * Class representing a single Workspace in a {@link Monorepo}\n */\nexport class Workspace {\n id: DepID\n path: string\n fullpath: string\n manifest: Manifest\n groups: string[] = []\n name: string\n #keys?: string[]\n\n constructor(path: string, manifest: Manifest, fullpath: string) {\n this.id = joinDepIDTuple(['workspace', path])\n workspaceCache.set(fullpath, this)\n this.path = path\n this.fullpath = fullpath\n this.manifest = manifest\n this.name = manifest.name ?? path\n }\n\n get keys(): string[] {\n if (this.#keys) {\n return this.#keys\n }\n this.#keys = [this.name, this.path, this.fullpath]\n return this.#keys\n }\n}\n", "import expand from 'brace-expansion'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { AST, ExtglobType } from './ast.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\ntype Platform =\n | 'aix'\n | 'android'\n | 'darwin'\n | 'freebsd'\n | 'haiku'\n | 'linux'\n | 'openbsd'\n | 'sunos'\n | 'win32'\n | 'cygwin'\n | 'netbsd'\n\nexport interface MinimatchOptions {\n nobrace?: boolean\n nocomment?: boolean\n nonegate?: boolean\n debug?: boolean\n noglobstar?: boolean\n noext?: boolean\n nonull?: boolean\n windowsPathsNoEscape?: boolean\n allowWindowsEscape?: boolean\n partial?: boolean\n dot?: boolean\n nocase?: boolean\n nocaseMagicOnly?: boolean\n magicalBraces?: boolean\n matchBase?: boolean\n flipNegate?: boolean\n preserveMultipleSlashes?: boolean\n optimizationLevel?: number\n platform?: Platform\n windowsNoMagicRoot?: boolean\n}\n\nexport const minimatch = (\n p: string,\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n assertValidPattern(pattern)\n\n // shortcut: comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n return false\n }\n\n return new Minimatch(pattern, options).match(p)\n}\n\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?\\*\\[\\(]*)$/\nconst starDotExtTest = (ext: string) => (f: string) =>\n !f.startsWith('.') && f.endsWith(ext)\nconst starDotExtTestDot = (ext: string) => (f: string) => f.endsWith(ext)\nconst starDotExtTestNocase = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => !f.startsWith('.') && f.toLowerCase().endsWith(ext)\n}\nconst starDotExtTestNocaseDot = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => f.toLowerCase().endsWith(ext)\n}\nconst starDotStarRE = /^\\*+\\.\\*+$/\nconst starDotStarTest = (f: string) => !f.startsWith('.') && f.includes('.')\nconst starDotStarTestDot = (f: string) =>\n f !== '.' && f !== '..' && f.includes('.')\nconst dotStarRE = /^\\.\\*+$/\nconst dotStarTest = (f: string) => f !== '.' && f !== '..' && f.startsWith('.')\nconst starRE = /^\\*+$/\nconst starTest = (f: string) => f.length !== 0 && !f.startsWith('.')\nconst starTestDot = (f: string) => f.length !== 0 && f !== '.' && f !== '..'\nconst qmarksRE = /^\\?+([^+@!?\\*\\[\\(]*)?$/\nconst qmarksTestNocase = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestNocaseDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTest = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTestNoExt = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && !f.startsWith('.')\n}\nconst qmarksTestNoExtDot = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && f !== '.' && f !== '..'\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n typeof process === 'object' && process\n ? (typeof process.env === 'object' &&\n process.env &&\n process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n process.platform\n : 'posix'\n) as Platform\ntype Sep = '\\\\' | '/'\nconst path: { [k: string]: { sep: Sep } } = {\n win32: { sep: '\\\\' },\n posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed. Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?'\n\nexport const filter =\n (pattern: string, options: MinimatchOptions = {}) =>\n (p: string) =>\n minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n return minimatch\n }\n\n const orig = minimatch\n\n const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n orig(p, pattern, ext(def, options))\n\n return Object.assign(m, {\n Minimatch: class Minimatch extends orig.Minimatch {\n constructor(pattern: string, options: MinimatchOptions = {}) {\n super(pattern, ext(def, options))\n }\n static defaults(options: MinimatchOptions) {\n return orig.defaults(ext(def, options)).Minimatch\n }\n },\n\n AST: class AST extends orig.AST {\n /* c8 ignore start */\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {}\n ) {\n super(type, parent, ext(def, options))\n }\n /* c8 ignore stop */\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n return orig.AST.fromGlob(pattern, ext(def, options))\n }\n },\n\n unescape: (\n s: string,\n options: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n ) => orig.unescape(s, ext(def, options)),\n\n escape: (\n s: string,\n options: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n ) => orig.escape(s, ext(def, options)),\n\n filter: (pattern: string, options: MinimatchOptions = {}) =>\n orig.filter(pattern, ext(def, options)),\n\n defaults: (options: MinimatchOptions) => orig.defaults(ext(def, options)),\n\n makeRe: (pattern: string, options: MinimatchOptions = {}) =>\n orig.makeRe(pattern, ext(def, options)),\n\n braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n orig.braceExpand(pattern, ext(def, options)),\n\n match: (list: string[], pattern: string, options: MinimatchOptions = {}) =>\n orig.match(list, pattern, ext(def, options)),\n\n sep: orig.sep,\n GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n assertValidPattern(pattern)\n\n // Thanks to Yeting Li <https://github.com/yetingli> for\n // improving this regexp to avoid a ReDOS vulnerability.\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n // shortcut. no need to expand.\n return [pattern]\n }\n\n return expand(pattern)\n}\nminimatch.braceExpand = braceExpand\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion. Otherwise, any series\n// of * is equivalent to a single *. Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\n\nexport const makeRe = (pattern: string, options: MinimatchOptions = {}) =>\n new Minimatch(pattern, options).makeRe()\nminimatch.makeRe = makeRe\n\nexport const match = (\n list: string[],\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n const mm = new Minimatch(pattern, options)\n list = list.filter(f => mm.match(f))\n if (mm.options.nonull && !list.length) {\n list.push(pattern)\n }\n return list\n}\nminimatch.match = match\n\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\nexport type MMRegExp = RegExp & {\n _src?: string\n _glob?: string\n}\n\nexport type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR\nexport type ParseReturn = ParseReturnFiltered | false\n\nexport class Minimatch {\n options: MinimatchOptions\n set: ParseReturnFiltered[][]\n pattern: string\n\n windowsPathsNoEscape: boolean\n nonegate: boolean\n negate: boolean\n comment: boolean\n empty: boolean\n preserveMultipleSlashes: boolean\n partial: boolean\n globSet: string[]\n globParts: string[][]\n nocase: boolean\n\n isWindows: boolean\n platform: Platform\n windowsNoMagicRoot: boolean\n\n regexp: false | null | MMRegExp\n constructor(pattern: string, options: MinimatchOptions = {}) {\n assertValidPattern(pattern)\n\n options = options || {}\n this.options = options\n this.pattern = pattern\n this.platform = options.platform || defaultPlatform\n this.isWindows = this.platform === 'win32'\n this.windowsPathsNoEscape =\n !!options.windowsPathsNoEscape || options.allowWindowsEscape === false\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, '/')\n }\n this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n this.regexp = null\n this.negate = false\n this.nonegate = !!options.nonegate\n this.comment = false\n this.empty = false\n this.partial = !!options.partial\n this.nocase = !!this.options.nocase\n this.windowsNoMagicRoot =\n options.windowsNoMagicRoot !== undefined\n ? options.windowsNoMagicRoot\n : !!(this.isWindows && this.nocase)\n\n this.globSet = []\n this.globParts = []\n this.set = []\n\n // make the set of regexps etc.\n this.make()\n }\n\n hasMagic(): boolean {\n if (this.options.magicalBraces && this.set.length > 1) {\n return true\n }\n for (const pattern of this.set) {\n for (const part of pattern) {\n if (typeof part !== 'string') return true\n }\n }\n return false\n }\n\n debug(..._: any[]) {}\n\n make() {\n const pattern = this.pattern\n const options = this.options\n\n // empty patterns and comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n this.comment = true\n return\n }\n\n if (!pattern) {\n this.empty = true\n return\n }\n\n // step 1: figure out negation, etc.\n this.parseNegate()\n\n // step 2: expand braces\n this.globSet = [...new Set(this.braceExpand())]\n\n if (options.debug) {\n this.debug = (...args: any[]) => console.error(...args)\n }\n\n this.debug(this.pattern, this.globSet)\n\n // step 3: now we have a set, so turn each one into a series of\n // path-portion matching patterns.\n // These will be regexps, except in the case of \"**\", which is\n // set to the GLOBSTAR object for globstar behavior,\n // and will not contain any / characters\n //\n // First, we preprocess to make the glob pattern sets a bit simpler\n // and deduped. There are some perf-killing patterns that can cause\n // problems with a glob walk, but we can simplify them down a bit.\n const rawGlobParts = this.globSet.map(s => this.slashSplit(s))\n this.globParts = this.preprocess(rawGlobParts)\n this.debug(this.pattern, this.globParts)\n\n // glob --> regexps\n let set = this.globParts.map((s, _, __) => {\n if (this.isWindows && this.windowsNoMagicRoot) {\n // check if it's a drive or unc path.\n const isUNC =\n s[0] === '' &&\n s[1] === '' &&\n (s[2] === '?' || !globMagic.test(s[2])) &&\n !globMagic.test(s[3])\n const isDrive = /^[a-z]:/i.test(s[0])\n if (isUNC) {\n return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]\n } else if (isDrive) {\n return [s[0], ...s.slice(1).map(ss => this.parse(ss))]\n }\n }\n return s.map(ss => this.parse(ss))\n })\n\n this.debug(this.pattern, set)\n\n // filter out everything that didn't compile properly.\n this.set = set.filter(\n s => s.indexOf(false) === -1\n ) as ParseReturnFiltered[][]\n\n // do not treat the ? in UNC paths as magic\n if (this.isWindows) {\n for (let i = 0; i < this.set.length; i++) {\n const p = this.set[i]\n if (\n p[0] === '' &&\n p[1] === '' &&\n this.globParts[i][2] === '?' &&\n typeof p[3] === 'string' &&\n /^[a-z]:$/i.test(p[3])\n ) {\n p[2] = '?'\n }\n }\n }\n\n this.debug(this.pattern, this.set)\n }\n\n // various transforms to equivalent pattern sets that are\n // faster to process in a filesystem walk. The goal is to\n // eliminate what we can, and push all ** patterns as far\n // to the right as possible, even if it increases the number\n // of patterns that we have to process.\n preprocess(globParts: string[][]) {\n // if we're not in globstar mode, then turn all ** into *\n if (this.options.noglobstar) {\n for (let i = 0; i < globParts.length; i++) {\n for (let j = 0; j < globParts[i].length; j++) {\n if (globParts[i][j] === '**') {\n globParts[i][j] = '*'\n }\n }\n }\n }\n\n const { optimizationLevel = 1 } = this.options\n\n if (optimizationLevel >= 2) {\n // aggressive optimization for the purpose of fs walking\n globParts = this.firstPhasePreProcess(globParts)\n globParts = this.secondPhasePreProcess(globParts)\n } else if (optimizationLevel >= 1) {\n // just basic optimizations to remove some .. parts\n globParts = this.levelOneOptimize(globParts)\n } else {\n // just collapse multiple ** portions into one\n globParts = this.adjascentGlobstarOptimize(globParts)\n }\n\n return globParts\n }\n\n // just get rid of adjascent ** portions\n adjascentGlobstarOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let i = gs\n while (parts[i + 1] === '**') {\n i++\n }\n if (i !== gs) {\n parts.splice(gs, i - gs)\n }\n }\n return parts\n })\n }\n\n // get rid of adjascent ** and resolve .. portions\n levelOneOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n parts = parts.reduce((set: string[], part) => {\n const prev = set[set.length - 1]\n if (part === '**' && prev === '**') {\n return set\n }\n if (part === '..') {\n if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n set.pop()\n return set\n }\n }\n set.push(part)\n return set\n }, [])\n return parts.length === 0 ? [''] : parts\n })\n }\n\n levelTwoFileOptimize(parts: string | string[]) {\n if (!Array.isArray(parts)) {\n parts = this.slashSplit(parts)\n }\n let didSomething: boolean = false\n do {\n didSomething = false\n // <pre>/<e>/<rest> -> <pre>/<rest>\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i]\n // don't squeeze out UNC patterns\n if (i === 1 && p === '' && parts[0] === '') continue\n if (p === '.' || p === '') {\n didSomething = true\n parts.splice(i, 1)\n i--\n }\n }\n if (\n parts[0] === '.' &&\n parts.length === 2 &&\n (parts[1] === '.' || parts[1] === '')\n ) {\n didSomething = true\n parts.pop()\n }\n }\n\n // <pre>/<p>/../<rest> -> <pre>/<rest>\n let dd: number = 0\n while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n const p = parts[dd - 1]\n if (p && p !== '.' && p !== '..' && p !== '**') {\n didSomething = true\n parts.splice(dd - 1, 2)\n dd -= 2\n }\n }\n } while (didSomething)\n return parts.length === 0 ? [''] : parts\n }\n\n // First phase: single-pattern processing\n // <pre> is 1 or more portions\n // <rest> is 1 or more portions\n // <p> is any portion other than ., .., '', or **\n // <e> is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}\n // <pre>/<e>/<rest> -> <pre>/<rest>\n // <pre>/<p>/../<rest> -> <pre>/<rest>\n // **/**/<rest> -> **/<rest>\n //\n // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow\n // this WOULD be allowed if ** did follow symlinks, or * didn't\n firstPhasePreProcess(globParts: string[][]) {\n let didSomething = false\n do {\n didSomething = false\n // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n // <pre>/**/**/<rest> -> <pre>/**/<rest>\n gss++\n }\n // eg, if gs is 2 and gss is 4, that means we have 3 **\n // parts, and can remove 2 of them.\n if (gss > gs) {\n parts.splice(gs + 1, gss - gs)\n }\n\n let next = parts[gs + 1]\n const p = parts[gs + 2]\n const p2 = parts[gs + 3]\n if (next !== '..') continue\n if (\n !p ||\n p === '.' ||\n p === '..' ||\n !p2 ||\n p2 === '.' ||\n p2 === '..'\n ) {\n continue\n }\n didSomething = true\n // edit parts in place, and push the new one\n parts.splice(gs, 1)\n const other = parts.slice(0)\n other[gs] = '**'\n globParts.push(other)\n gs--\n }\n\n // <pre>/<e>/<rest> -> <pre>/<rest>\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i]\n // don't squeeze out UNC patterns\n if (i === 1 && p === '' && parts[0] === '') continue\n if (p === '.' || p === '') {\n didSomething = true\n parts.splice(i, 1)\n i--\n }\n }\n if (\n parts[0] === '.' &&\n parts.length === 2 &&\n (parts[1] === '.' || parts[1] === '')\n ) {\n didSomething = true\n parts.pop()\n }\n }\n\n // <pre>/<p>/../<rest> -> <pre>/<rest>\n let dd: number = 0\n while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n const p = parts[dd - 1]\n if (p && p !== '.' && p !== '..' && p !== '**') {\n didSomething = true\n const needDot = dd === 1 && parts[dd + 1] === '**'\n const splin = needDot ? ['.'] : []\n parts.splice(dd - 1, 2, ...splin)\n if (parts.length === 0) parts.push('')\n dd -= 2\n }\n }\n }\n } while (didSomething)\n\n return globParts\n }\n\n // second phase: multi-pattern dedupes\n // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>\n // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>\n // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>\n //\n // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>\n // ^-- not valid because ** doens't follow symlinks\n secondPhasePreProcess(globParts: string[][]): string[][] {\n for (let i = 0; i < globParts.length - 1; i++) {\n for (let j = i + 1; j < globParts.length; j++) {\n const matched = this.partsMatch(\n globParts[i],\n globParts[j],\n !this.preserveMultipleSlashes\n )\n if (matched) {\n globParts[i] = []\n globParts[j] = matched\n break\n }\n }\n }\n return globParts.filter(gs => gs.length)\n }\n\n partsMatch(\n a: string[],\n b: string[],\n emptyGSMatch: boolean = false\n ): false | string[] {\n let ai = 0\n let bi = 0\n let result: string[] = []\n let which: string = ''\n while (ai < a.length && bi < b.length) {\n if (a[ai] === b[bi]) {\n result.push(which === 'b' ? b[bi] : a[ai])\n ai++\n bi++\n } else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n result.push(a[ai])\n ai++\n } else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n result.push(b[bi])\n bi++\n } else if (\n a[ai] === '*' &&\n b[bi] &&\n (this.options.dot || !b[bi].startsWith('.')) &&\n b[bi] !== '**'\n ) {\n if (which === 'b') return false\n which = 'a'\n result.push(a[ai])\n ai++\n bi++\n } else if (\n b[bi] === '*' &&\n a[ai] &&\n (this.options.dot || !a[ai].startsWith('.')) &&\n a[ai] !== '**'\n ) {\n if (which === 'a') return false\n which = 'b'\n result.push(b[bi])\n ai++\n bi++\n } else {\n return false\n }\n }\n // if we fall out of the loop, it means they two are identical\n // as long as their lengths match\n return a.length === b.length && result\n }\n\n parseNegate() {\n if (this.nonegate) return\n\n const pattern = this.pattern\n let negate = false\n let negateOffset = 0\n\n for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n negate = !negate\n negateOffset++\n }\n\n if (negateOffset) this.pattern = pattern.slice(negateOffset)\n this.negate = negate\n }\n\n // set partial to true to test if, for example,\n // \"/a/b\" matches the start of \"/*/b/*/d\"\n // Partial means, if you run out of file before you run\n // out of pattern, then that's fine, as long as all\n // the parts match.\n matchOne(file: string[], pattern: ParseReturn[], partial: boolean = false) {\n const options = this.options\n\n // UNC paths like //?/X:/... can match X:/... and vice versa\n // Drive letters in absolute drive or unc paths are always compared\n // case-insensitively.\n if (this.isWindows) {\n const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n const fileUNC =\n !fileDrive &&\n file[0] === '' &&\n file[1] === '' &&\n file[2] === '?' &&\n /^[a-z]:$/i.test(file[3])\n\n const patternDrive =\n typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n const patternUNC =\n !patternDrive &&\n pattern[0] === '' &&\n pattern[1] === '' &&\n pattern[2] === '?' &&\n typeof pattern[3] === 'string' &&\n /^[a-z]:$/i.test(pattern[3])\n\n const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined\n const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined\n if (typeof fdi === 'number' && typeof pdi === 'number') {\n const [fd, pd]: [string, string] = [file[fdi], pattern[pdi] as string]\n if (fd.toLowerCase() === pd.toLowerCase()) {\n pattern[pdi] = fd\n if (pdi > fdi) {\n pattern = pattern.slice(pdi)\n } else if (fdi > pdi) {\n file = file.slice(fdi)\n }\n }\n }\n }\n\n // resolve and reduce . and .. portions in the file as well.\n // dont' need to do the second phase, because it's only one string[]\n const { optimizationLevel = 1 } = this.options\n if (optimizationLevel >= 2) {\n file = this.levelTwoFileOptimize(file)\n }\n\n this.debug('matchOne', this, { file, pattern })\n this.debug('matchOne', file.length, pattern.length)\n\n for (\n var fi = 0, pi = 0, fl = file.length, pl = pattern.length;\n fi < fl && pi < pl;\n fi++, pi++\n ) {\n this.debug('matchOne loop')\n var p = pattern[pi]\n var f = file[fi]\n\n this.debug(pattern, p, f)\n\n // should be impossible.\n // some invalid regexp stuff in the set.\n /* c8 ignore start */\n if (p === false) {\n return false\n }\n /* c8 ignore stop */\n\n if (p === GLOBSTAR) {\n this.debug('GLOBSTAR', [pattern, p, f])\n\n // \"**\"\n // a/**/b/**/c would match the following:\n // a/b/x/y/z/c\n // a/x/y/z/b/c\n // a/b/x/b/x/c\n // a/b/c\n // To do this, take the rest of the pattern after\n // the **, and see if it would match the file remainder.\n // If so, return success.\n // If not, the ** \"swallows\" a segment, and try again.\n // This is recursively awful.\n //\n // a/**/b/**/c matching a/b/x/y/z/c\n // - a matches a\n // - doublestar\n // - matchOne(b/x/y/z/c, b/**/c)\n // - b matches b\n // - doublestar\n // - matchOne(x/y/z/c, c) -> no\n // - matchOne(y/z/c, c) -> no\n // - matchOne(z/c, c) -> no\n // - matchOne(c, c) yes, hit\n var fr = fi\n var pr = pi + 1\n if (pr === pl) {\n this.debug('** at the end')\n // a ** at the end will just swallow the rest.\n // We have found a match.\n // however, it will not swallow /.x, unless\n // options.dot is set.\n // . and .. are *never* matched by **, for explosively\n // exponential reasons.\n for (; fi < fl; fi++) {\n if (\n file[fi] === '.' ||\n file[fi] === '..' ||\n (!options.dot && file[fi].charAt(0) === '.')\n )\n return false\n }\n return true\n }\n\n // ok, let's see if we can swallow whatever we can.\n while (fr < fl) {\n var swallowee = file[fr]\n\n this.debug('\\nglobstar while', file, fr, pattern, pr, swallowee)\n\n // XXX remove this slice. Just pass the start index.\n if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {\n this.debug('globstar found match!', fr, fl, swallowee)\n // found a match.\n return true\n } else {\n // can't swallow \".\" or \"..\" ever.\n // can only swallow \".foo\" when explicitly asked.\n if (\n swallowee === '.' ||\n swallowee === '..' ||\n (!options.dot && swallowee.charAt(0) === '.')\n ) {\n this.debug('dot detected!', file, fr, pattern, pr)\n break\n }\n\n // ** swallows a segment, and continue.\n this.debug('globstar swallow a segment, and continue')\n fr++\n }\n }\n\n // no match was found.\n // However, in partial mode, we can't say this is necessarily over.\n /* c8 ignore start */\n if (partial) {\n // ran out of file\n this.debug('\\n>>> no match, partial?', file, fr, pattern, pr)\n if (fr === fl) {\n return true\n }\n }\n /* c8 ignore stop */\n return false\n }\n\n // something other than **\n // non-magic patterns just have to match exactly\n // patterns with magic have been turned into regexps.\n let hit: boolean\n if (typeof p === 'string') {\n hit = f === p\n this.debug('string match', p, f, hit)\n } else {\n hit = p.test(f)\n this.debug('pattern match', p, f, hit)\n }\n\n if (!hit) return false\n }\n\n // Note: ending in / means that we'll get a final \"\"\n // at the end of the pattern. This can only match a\n // corresponding \"\" at the end of the file.\n // If the file ends in /, then it can only match a\n // a pattern that ends in /, unless the pattern just\n // doesn't have any more for it. But, a/b/ should *not*\n // match \"a/b/*\", even though \"\" matches against the\n // [^/]*? pattern, except in partial mode, where it might\n // simply not be reached yet.\n // However, a/b/ should still satisfy a/*\n\n // now either we fell off the end of the pattern, or we're done.\n if (fi === fl && pi === pl) {\n // ran out of pattern and filename at the same time.\n // an exact hit!\n return true\n } else if (fi === fl) {\n // ran out of file, but still had pattern left.\n // this is ok if we're doing the match as part of\n // a glob fs traversal.\n return partial\n } else if (pi === pl) {\n // ran out of pattern, still have file left.\n // this is only acceptable if we're on the very last\n // empty segment of a file with a trailing slash.\n // a/* should match a/b/\n return fi === fl - 1 && file[fi] === ''\n\n /* c8 ignore start */\n } else {\n // should be unreachable.\n throw new Error('wtf?')\n }\n /* c8 ignore stop */\n }\n\n braceExpand() {\n return braceExpand(this.pattern, this.options)\n }\n\n parse(pattern: string): ParseReturn {\n assertValidPattern(pattern)\n\n const options = this.options\n\n // shortcuts\n if (pattern === '**') return GLOBSTAR\n if (pattern === '') return ''\n\n // far and away, the most common glob pattern parts are\n // *, *.*, and *.<ext> Add a fast check method for those.\n let m: RegExpMatchArray | null\n let fastTest: null | ((f: string) => boolean) = null\n if ((m = pattern.match(starRE))) {\n fastTest = options.dot ? starTestDot : starTest\n } else if ((m = pattern.match(starDotExtRE))) {\n fastTest = (\n options.nocase\n ? options.dot\n ? starDotExtTestNocaseDot\n : starDotExtTestNocase\n : options.dot\n ? starDotExtTestDot\n : starDotExtTest\n )(m[1])\n } else if ((m = pattern.match(qmarksRE))) {\n fastTest = (\n options.nocase\n ? options.dot\n ? qmarksTestNocaseDot\n : qmarksTestNocase\n : options.dot\n ? qmarksTestDot\n : qmarksTest\n )(m)\n } else if ((m = pattern.match(starDotStarRE))) {\n fastTest = options.dot ? starDotStarTestDot : starDotStarTest\n } else if ((m = pattern.match(dotStarRE))) {\n fastTest = dotStarTest\n }\n\n const re = AST.fromGlob(pattern, this.options).toMMPattern()\n if (fastTest && typeof re === 'object') {\n // Avoids overriding in frozen environments\n Reflect.defineProperty(re, 'test', { value: fastTest })\n }\n return re\n }\n\n makeRe() {\n if (this.regexp || this.regexp === false) return this.regexp\n\n // at this point, this.set is a 2d array of partial\n // pattern strings, or \"**\".\n //\n // It's better to use .match(). This function shouldn't\n // be used, really, but it's pretty convenient sometimes,\n // when you just want to work with a regex.\n const set = this.set\n\n if (!set.length) {\n this.regexp = false\n return this.regexp\n }\n const options = this.options\n\n const twoStar = options.noglobstar\n ? star\n : options.dot\n ? twoStarDot\n : twoStarNoDot\n const flags = new Set(options.nocase ? ['i'] : [])\n\n // regexpify non-globstar patterns\n // if ** is only item, then we just do one twoStar\n // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n // if ** is last, append (\\/twoStar|) to previous\n // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n // then filter out GLOBSTAR symbols\n let re = set\n .map(pattern => {\n const pp: (string | typeof GLOBSTAR)[] = pattern.map(p => {\n if (p instanceof RegExp) {\n for (const f of p.flags.split('')) flags.add(f)\n }\n return typeof p === 'string'\n ? regExpEscape(p)\n : p === GLOBSTAR\n ? GLOBSTAR\n : p._src\n }) as (string | typeof GLOBSTAR)[]\n pp.forEach((p, i) => {\n const next = pp[i + 1]\n const prev = pp[i - 1]\n if (p !== GLOBSTAR || prev === GLOBSTAR) {\n return\n }\n if (prev === undefined) {\n if (next !== undefined && next !== GLOBSTAR) {\n pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next\n } else {\n pp[i] = twoStar\n }\n } else if (next === undefined) {\n pp[i - 1] = prev + '(?:\\\\/|' + twoStar + ')?'\n } else if (next !== GLOBSTAR) {\n pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next\n pp[i + 1] = GLOBSTAR\n }\n })\n return pp.filter(p => p !== GLOBSTAR).join('/')\n })\n .join('|')\n\n // need to wrap in parens if we had more than one thing with |,\n // otherwise only the first will be anchored to ^ and the last to $\n const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']\n // must match entire pattern\n // ending in a * or ** will make it less strict.\n re = '^' + open + re + close + '$'\n\n // can match anything, as long as it's not this.\n if (this.negate) re = '^(?!' + re + ').+$'\n\n try {\n this.regexp = new RegExp(re, [...flags].join(''))\n /* c8 ignore start */\n } catch (ex) {\n // should be impossible\n this.regexp = false\n }\n /* c8 ignore stop */\n return this.regexp\n }\n\n slashSplit(p: string) {\n // if p starts with // on windows, we preserve that\n // so that UNC paths aren't broken. Otherwise, any number of\n // / characters are coalesced into one, unless\n // preserveMultipleSlashes is set to true.\n if (this.preserveMultipleSlashes) {\n return p.split('/')\n } else if (this.isWindows && /^\\/\\/[^\\/]+/.test(p)) {\n // add an extra '' for the one we lose\n return ['', ...p.split(/\\/+/)]\n } else {\n return p.split(/\\/+/)\n }\n }\n\n match(f: string, partial = this.partial) {\n this.debug('match', f, this.pattern)\n // short-circuit in the case of busted things.\n // comments, etc.\n if (this.comment) {\n return false\n }\n if (this.empty) {\n return f === ''\n }\n\n if (f === '/' && partial) {\n return true\n }\n\n const options = this.options\n\n // windows: need to use /, not \\\n if (this.isWindows) {\n f = f.split('\\\\').join('/')\n }\n\n // treat the test path as a set of pathparts.\n const ff = this.slashSplit(f)\n this.debug(this.pattern, 'split', ff)\n\n // just ONE of the pattern sets in this.set needs to match\n // in order for it to be valid. If negating, then just one\n // match means that we have failed.\n // Either way, return on the first hit.\n\n const set = this.set\n this.debug(this.pattern, 'set', set)\n\n // Find the basename of the path by looking for the last non-empty segment\n let filename: string = ff[ff.length - 1]\n if (!filename) {\n for (let i = ff.length - 2; !filename && i >= 0; i--) {\n filename = ff[i]\n }\n }\n\n for (let i = 0; i < set.length; i++) {\n const pattern = set[i]\n let file = ff\n if (options.matchBase && pattern.length === 1) {\n file = [filename]\n }\n const hit = this.matchOne(file, pattern, partial)\n if (hit) {\n if (options.flipNegate) {\n return true\n }\n return !this.negate\n }\n }\n\n // didn't get any hits. this is success if it's a negative\n // pattern, failure otherwise.\n if (options.flipNegate) {\n return false\n }\n return this.negate\n }\n\n static defaults(def: MinimatchOptions) {\n return minimatch.defaults(def).Minimatch\n }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js'\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\n/* c8 ignore stop */\nminimatch.AST = AST\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n", "const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: any) => void = (\n pattern: any\n): asserts pattern is string => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern')\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long')\n }\n}\n", "// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { <posix class>: [<translation>, /u flag required, negated]\nconst posixClasses: { [k: string]: [e: string, u: boolean, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n '[:cntrl:]': ['\\\\p{Cc}', true],\n '[:digit:]': ['\\\\p{Nd}', true],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n '[:lower:]': ['\\\\p{Ll}', true],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}', true],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n '[:upper:]': ['\\\\p{Lu}', true],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n '[:xdigit:]': ['A-Fa-f0-9', false],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n// escape all regexp magic characters\nconst regexpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges: string[]): string => ranges.join('')\n\nexport type ParseClassResult = [\n src: string,\n uFlag: boolean,\n consumed: number,\n hasMagic: boolean\n]\n\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (\n glob: string,\n position: number\n): ParseClassResult => {\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let uflag = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = glob.charAt(i)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return ['$.', false, glob.length - pos, true]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n uflag = uflag || u\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (c > rangeStart) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c))\n } else if (c === rangeStart) {\n ranges.push(braceEscape(c))\n }\n rangeStart = ''\n i++\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c<more...>] or c] at this point\n if (glob.startsWith('-]', i + 1)) {\n ranges.push(braceEscape(c + '-'))\n i += 2\n continue\n }\n if (glob.startsWith('-', i + 1)) {\n rangeStart = c\n i += 2\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(c))\n i++\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return ['', false, 0, false]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return ['$.', false, glob.length - pos, true]\n }\n\n // if we got one positive range, and it's a single character, then that's\n // not actually a magic pattern, it's just that one literal character.\n // we should not treat that as \"magic\", we should just return the literal\n // character. [_] is a perfectly valid way to escape glob magic chars.\n if (\n negs.length === 0 &&\n ranges.length === 1 &&\n /^\\\\?.$/.test(ranges[0]) &&\n !negate\n ) {\n const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]\n return [regexpEscape(r), false, endPos - pos, false]\n }\n\n const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'\n const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'\n const comb =\n ranges.length && negs.length\n ? '(' + sranges + '|' + snegs + ')'\n : ranges.length\n ? sranges\n : snegs\n\n return [comb, uflag, endPos - pos, true]\n}\n", "import { MinimatchOptions } from './index.js'\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link windowsPathsNoEscape} option is used, then square-brace\n * escapes are removed, but not backslash escapes. For example, it will turn\n * the string `'[*]'` into `*`, but it will not turn `'\\\\*'` into `'*'`,\n * becuase `\\` is a path separator in `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both brace escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n */\nexport const unescape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n) => {\n return windowsPathsNoEscape\n ? s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2').replace(/\\\\([^\\/])/g, '$1')\n}\n", "// parse a single path portion\n\nimport { parseClass } from './brace-expressions.js'\nimport { MinimatchOptions, MMRegExp } from './index.js'\nimport { unescape } from './unescape.js'\n\n// classes [] are handled by the parseClass method\n// for positive extglobs, we sub-parse the contents, and combine,\n// with the appropriate regexp close.\n// for negative extglobs, we sub-parse the contents, but then\n// have to include the rest of the pattern, then the parent, etc.,\n// as the thing that cannot be because RegExp negative lookaheads\n// are different from globs.\n//\n// So for example:\n// a@(i|w!(x|y)z|j)b => ^a(i|w((!?(x|y)zb).*)z|j)b$\n// 1 2 3 4 5 6 1 2 3 46 5 6\n//\n// Assembling the extglob requires not just the negated patterns themselves,\n// but also anything following the negative patterns up to the boundary\n// of the current pattern, plus anything following in the parent pattern.\n//\n//\n// So, first, we parse the string into an AST of extglobs, without turning\n// anything into regexps yet.\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y']}, 'z'], ['j']]}, 'b']\n//\n// Then, for all the negative extglobs, we append whatever comes after in\n// each parent as their tail\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y'], 'z', 'b'}, 'z'], ['j']]}, 'b']\n//\n// Lastly, we turn each of these pieces into a regexp, and join\n//\n// v----- .* because there's more following,\n// v v otherwise, .+ because it must be\n// v v *something* there.\n// ['^a', {@ ['i', 'w(?:(!?(?:x|y).*zb$).*)z', 'j' ]}, 'b$']\n// copy what follows into here--^^^^^\n// ['^a', '(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)', 'b$']\n// ['^a(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)b$']\n\nexport type ExtglobType = '!' | '?' | '+' | '*' | '@'\nconst types = new Set<ExtglobType>(['!', '?', '+', '*', '@'])\nconst isExtglobType = (c: string): c is ExtglobType =>\n types.has(c as ExtglobType)\n\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))'\nconst startNoDot = '(?!\\\\.)'\n\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.'])\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.'])\nconst reSpecials = new Set('().*{}+?[]^$\\\\!')\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// any single thing other than /\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?'\n\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\n\nexport class AST {\n type: ExtglobType | null\n readonly #root: AST\n\n #hasMagic?: boolean\n #uflag: boolean = false\n #parts: (string | AST)[] = []\n readonly #parent?: AST\n readonly #parentIndex: number\n #negs: AST[]\n #filledNegs: boolean = false\n #options: MinimatchOptions\n #toString?: string\n // set to true if it's an extglob with no children\n // (which really means one child of '')\n #emptyExt: boolean = false\n\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {}\n ) {\n this.type = type\n // extglobs are inherently magical\n if (type) this.#hasMagic = true\n this.#parent = parent\n this.#root = this.#parent ? this.#parent.#root : this\n this.#options = this.#root === this ? options : this.#root.#options\n this.#negs = this.#root === this ? [] : this.#root.#negs\n if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this)\n this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0\n }\n\n get hasMagic(): boolean | undefined {\n /* c8 ignore start */\n if (this.#hasMagic !== undefined) return this.#hasMagic\n /* c8 ignore stop */\n for (const p of this.#parts) {\n if (typeof p === 'string') continue\n if (p.type || p.hasMagic) return (this.#hasMagic = true)\n }\n // note: will be undefined until we generate the regexp src and find out\n return this.#hasMagic\n }\n\n // reconstructs the pattern\n toString(): string {\n if (this.#toString !== undefined) return this.#toString\n if (!this.type) {\n return (this.#toString = this.#parts.map(p => String(p)).join(''))\n } else {\n return (this.#toString =\n this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')')\n }\n }\n\n #fillNegs() {\n /* c8 ignore start */\n if (this !== this.#root) throw new Error('should only call on root')\n if (this.#filledNegs) return this\n /* c8 ignore stop */\n\n // call toString() once to fill this out\n this.toString()\n this.#filledNegs = true\n let n: AST | undefined\n while ((n = this.#negs.pop())) {\n if (n.type !== '!') continue\n // walk up the tree, appending everthing that comes AFTER parentIndex\n let p: AST | undefined = n\n let pp = p.#parent\n while (pp) {\n for (\n let i = p.#parentIndex + 1;\n !pp.type && i < pp.#parts.length;\n i++\n ) {\n for (const part of n.#parts) {\n /* c8 ignore start */\n if (typeof part === 'string') {\n throw new Error('string part in extglob AST??')\n }\n /* c8 ignore stop */\n part.copyIn(pp.#parts[i])\n }\n }\n p = pp\n pp = p.#parent\n }\n }\n return this\n }\n\n push(...parts: (string | AST)[]) {\n for (const p of parts) {\n if (p === '') continue\n /* c8 ignore start */\n if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {\n throw new Error('invalid part: ' + p)\n }\n /* c8 ignore stop */\n this.#parts.push(p)\n }\n }\n\n toJSON() {\n const ret: any[] =\n this.type === null\n ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))\n : [this.type, ...this.#parts.map(p => (p as AST).toJSON())]\n if (this.isStart() && !this.type) ret.unshift([])\n if (\n this.isEnd() &&\n (this === this.#root ||\n (this.#root.#filledNegs && this.#parent?.type === '!'))\n ) {\n ret.push({})\n }\n return ret\n }\n\n isStart(): boolean {\n if (this.#root === this) return true\n // if (this.type) return !!this.#parent?.isStart()\n if (!this.#parent?.isStart()) return false\n if (this.#parentIndex === 0) return true\n // if everything AHEAD of this is a negation, then it's still the \"start\"\n const p = this.#parent\n for (let i = 0; i < this.#parentIndex; i++) {\n const pp = p.#parts[i]\n if (!(pp instanceof AST && pp.type === '!')) {\n return false\n }\n }\n return true\n }\n\n isEnd(): boolean {\n if (this.#root === this) return true\n if (this.#parent?.type === '!') return true\n if (!this.#parent?.isEnd()) return false\n if (!this.type) return this.#parent?.isEnd()\n // if not root, it'll always have a parent\n /* c8 ignore start */\n const pl = this.#parent ? this.#parent.#parts.length : 0\n /* c8 ignore stop */\n return this.#parentIndex === pl - 1\n }\n\n copyIn(part: AST | string) {\n if (typeof part === 'string') this.push(part)\n else this.push(part.clone(this))\n }\n\n clone(parent: AST) {\n const c = new AST(this.type, parent)\n for (const p of this.#parts) {\n c.copyIn(p)\n }\n return c\n }\n\n static #parseAST(\n str: string,\n ast: AST,\n pos: number,\n opt: MinimatchOptions\n ): number {\n let escaping = false\n let inBrace = false\n let braceStart = -1\n let braceNeg = false\n if (ast.type === null) {\n // outside of a extglob, append until we find a start\n let i = pos\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {\n ast.push(acc)\n acc = ''\n const ext = new AST(c, ast)\n i = AST.#parseAST(str, ext, i, opt)\n ast.push(ext)\n continue\n }\n acc += c\n }\n ast.push(acc)\n return i\n }\n\n // some kind of extglob, pos is at the (\n // find the next | or )\n let i = pos + 1\n let part = new AST(null, ast)\n const parts: AST[] = []\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n if (isExtglobType(c) && str.charAt(i) === '(') {\n part.push(acc)\n acc = ''\n const ext = new AST(c, part)\n part.push(ext)\n i = AST.#parseAST(str, ext, i, opt)\n continue\n }\n if (c === '|') {\n part.push(acc)\n acc = ''\n parts.push(part)\n part = new AST(null, ast)\n continue\n }\n if (c === ')') {\n if (acc === '' && ast.#parts.length === 0) {\n ast.#emptyExt = true\n }\n part.push(acc)\n acc = ''\n ast.push(...parts, part)\n return i\n }\n acc += c\n }\n\n // unfinished extglob\n // if we got here, it was a malformed extglob! not an extglob, but\n // maybe something else in there.\n ast.type = null\n ast.#hasMagic = undefined\n ast.#parts = [str.substring(pos - 1)]\n return i\n }\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n const ast = new AST(null, undefined, options)\n AST.#parseAST(pattern, ast, 0, options)\n return ast\n }\n\n // returns the regular expression if there's magic, or the unescaped\n // string if not.\n toMMPattern(): MMRegExp | string {\n // should only be called on root\n /* c8 ignore start */\n if (this !== this.#root) return this.#root.toMMPattern()\n /* c8 ignore stop */\n const glob = this.toString()\n const [re, body, hasMagic, uflag] = this.toRegExpSource()\n // if we're in nocase mode, and not nocaseMagicOnly, then we do\n // still need a regular expression if we have to case-insensitively\n // match capital/lowercase characters.\n const anyMagic =\n hasMagic ||\n this.#hasMagic ||\n (this.#options.nocase &&\n !this.#options.nocaseMagicOnly &&\n glob.toUpperCase() !== glob.toLowerCase())\n if (!anyMagic) {\n return body\n }\n\n const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '')\n return Object.assign(new RegExp(`^${re}$`, flags), {\n _src: re,\n _glob: glob,\n })\n }\n\n get options() {\n return this.#options\n }\n\n // returns the string match, the regexp source, whether there's magic\n // in the regexp (so a regular expression is required) and whether or\n // not the uflag is needed for the regular expression (for posix classes)\n // TODO: instead of injecting the start/end at this point, just return\n // the BODY of the regexp, along with the start/end portions suitable\n // for binding the start/end in either a joined full-path makeRe context\n // (where we bind to (^|/), or a standalone matchPart context (where\n // we bind to ^, and not /). Otherwise slashes get duped!\n //\n // In part-matching mode, the start is:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n // - if dots allowed or not possible: ^\n // - if dots possible and not allowed: ^(?!\\.)\n // end is:\n // - if not isEnd(): nothing\n // - else: $\n //\n // In full-path matching mode, we put the slash at the START of the\n // pattern, so start is:\n // - if first pattern: same as part-matching mode\n // - if not isStart(): nothing\n // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n // - if dots allowed or not possible: /\n // - if dots possible and not allowed: /(?!\\.)\n // end is:\n // - if last pattern, same as part-matching mode\n // - else nothing\n //\n // Always put the (?:$|/) on negated tails, though, because that has to be\n // there to bind the end of the negated pattern portion, and it's easier to\n // just stick it in now rather than try to inject it later in the middle of\n // the pattern.\n //\n // We can just always return the same end, and leave it up to the caller\n // to know whether it's going to be used joined or in parts.\n // And, if the start is adjusted slightly, can do the same there:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n // - if dots allowed or not possible: (?:/|^)\n // - if dots possible and not allowed: (?:/|^)(?!\\.)\n //\n // But it's better to have a simpler binding without a conditional, for\n // performance, so probably better to return both start options.\n //\n // Then the caller just ignores the end if it's not the first pattern,\n // and the start always gets applied.\n //\n // But that's always going to be $ if it's the ending pattern, or nothing,\n // so the caller can just attach $ at the end of the pattern when building.\n //\n // So the todo is:\n // - better detect what kind of start is needed\n // - return both flavors of starting pattern\n // - attach $ at the end of the pattern when creating the actual RegExp\n //\n // Ah, but wait, no, that all only applies to the root when the first pattern\n // is not an extglob. If the first pattern IS an extglob, then we need all\n // that dot prevention biz to live in the extglob portions, because eg\n // +(*|.x*) can match .xy but not .yx.\n //\n // So, return the two flavors if it's #root and the first child is not an\n // AST, otherwise leave it to the child AST to handle it, and there,\n // use the (?:^|/) style of start binding.\n //\n // Even simplified further:\n // - Since the start for a join is eg /(?!\\.) and the start for a part\n // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n // or start or whatever) and prepend ^ or / at the Regexp construction.\n toRegExpSource(\n allowDot?: boolean\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n const dot = allowDot ?? !!this.#options.dot\n if (this.#root === this) this.#fillNegs()\n if (!this.type) {\n const noEmpty = this.isStart() && this.isEnd()\n const src = this.#parts\n .map(p => {\n const [re, _, hasMagic, uflag] =\n typeof p === 'string'\n ? AST.#parseGlob(p, this.#hasMagic, noEmpty)\n : p.toRegExpSource(allowDot)\n this.#hasMagic = this.#hasMagic || hasMagic\n this.#uflag = this.#uflag || uflag\n return re\n })\n .join('')\n\n let start = ''\n if (this.isStart()) {\n if (typeof this.#parts[0] === 'string') {\n // this is the string that will match the start of the pattern,\n // so we need to protect against dots and such.\n\n // '.' and '..' cannot match unless the pattern is that exactly,\n // even if it starts with . or dot:true is set.\n const dotTravAllowed =\n this.#parts.length === 1 && justDots.has(this.#parts[0])\n if (!dotTravAllowed) {\n const aps = addPatternStart\n // check if we have a possibility of matching . or ..,\n // and prevent that.\n const needNoTrav =\n // dots are allowed, and the pattern starts with [ or .\n (dot && aps.has(src.charAt(0))) ||\n // the pattern starts with \\., and then [ or .\n (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n // the pattern starts with \\.\\., and then [ or .\n (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)))\n // no need to prevent dots if it can't match a dot, or if a\n // sub-pattern will be preventing it anyway.\n const needNoDot = !dot && !allowDot && aps.has(src.charAt(0))\n\n start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''\n }\n }\n }\n\n // append the \"end of path portion\" pattern to negation tails\n let end = ''\n if (\n this.isEnd() &&\n this.#root.#filledNegs &&\n this.#parent?.type === '!'\n ) {\n end = '(?:$|\\\\/)'\n }\n const final = start + src + end\n return [\n final,\n unescape(src),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n // We need to calculate the body *twice* if it's a repeat pattern\n // at the start, once in nodot mode, then again in dot mode, so a\n // pattern like *(?) can match 'x.y'\n\n const repeated = this.type === '*' || this.type === '+'\n // some kind of extglob\n const start = this.type === '!' ? '(?:(?!(?:' : '(?:'\n let body = this.#partsToRegExp(dot)\n\n if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n // invalid extglob, has to at least be *something* present, if it's\n // the entire path portion.\n const s = this.toString()\n this.#parts = [s]\n this.type = null\n this.#hasMagic = undefined\n return [s, unescape(this.toString()), false, false]\n }\n\n // XXX abstract out this map method\n let bodyDotAllowed =\n !repeated || allowDot || dot || !startNoDot\n ? ''\n : this.#partsToRegExp(true)\n if (bodyDotAllowed === body) {\n bodyDotAllowed = ''\n }\n if (bodyDotAllowed) {\n body = `(?:${body})(?:${bodyDotAllowed})*?`\n }\n\n // an empty !() is exactly equivalent to a starNoEmpty\n let final = ''\n if (this.type === '!' && this.#emptyExt) {\n final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty\n } else {\n const close =\n this.type === '!'\n ? // !() must match something,but !(x) can match ''\n '))' +\n (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n star +\n ')'\n : this.type === '@'\n ? ')'\n : this.type === '?'\n ? ')?'\n : this.type === '+' && bodyDotAllowed\n ? ')'\n : this.type === '*' && bodyDotAllowed\n ? `)?`\n : `)${this.type}`\n final = start + body + close\n }\n return [\n final,\n unescape(body),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n #partsToRegExp(dot: boolean) {\n return this.#parts\n .map(p => {\n // extglob ASTs should only contain parent ASTs\n /* c8 ignore start */\n if (typeof p === 'string') {\n throw new Error('string type in extglob ast??')\n }\n /* c8 ignore stop */\n // can ignore hasMagic, because extglobs are already always magic\n const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot)\n this.#uflag = this.#uflag || uflag\n return re\n })\n .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n .join('|')\n }\n\n static #parseGlob(\n glob: string,\n hasMagic: boolean | undefined,\n noEmpty: boolean = false\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n let escaping = false\n let re = ''\n let uflag = false\n for (let i = 0; i < glob.length; i++) {\n const c = glob.charAt(i)\n if (escaping) {\n escaping = false\n re += (reSpecials.has(c) ? '\\\\' : '') + c\n continue\n }\n if (c === '\\\\') {\n if (i === glob.length - 1) {\n re += '\\\\\\\\'\n } else {\n escaping = true\n }\n continue\n }\n if (c === '[') {\n const [src, needUflag, consumed, magic] = parseClass(glob, i)\n if (consumed) {\n re += src\n uflag = uflag || needUflag\n i += consumed - 1\n hasMagic = hasMagic || magic\n continue\n }\n }\n if (c === '*') {\n if (noEmpty && glob === '*') re += starNoEmpty\n else re += star\n hasMagic = true\n continue\n }\n if (c === '?') {\n re += qmark\n hasMagic = true\n continue\n }\n re += regExpEscape(c)\n }\n return [re, unescape(glob), !!hasMagic, uflag]\n }\n}\n", "import { MinimatchOptions } from './index.js'\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n */\nexport const escape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n return windowsPathsNoEscape\n ? s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n", "import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n FSOption,\n Path,\n PathScurry,\n PathScurryDarwin,\n PathScurryPosix,\n PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude<Minimatch['globParts'], undefined>\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n /**\n * Set to `true` to always receive absolute paths for\n * matched files. Set to `false` to always return relative paths.\n *\n * When this option is not set, absolute paths are returned for patterns\n * that are absolute, and otherwise paths are returned that are relative\n * to the `cwd` setting.\n *\n * This does _not_ make an extra system call to get\n * the realpath, it only does string path resolution.\n *\n * Conflicts with {@link withFileTypes}\n */\n absolute?: boolean\n\n /**\n * Set to false to enable {@link windowsPathsNoEscape}\n *\n * @deprecated\n */\n allowWindowsEscape?: boolean\n\n /**\n * The current working directory in which to search. Defaults to\n * `process.cwd()`.\n *\n * May be eiher a string path or a `file://` URL object or string.\n */\n cwd?: string | URL\n\n /**\n * Include `.dot` files in normal matches and `globstar`\n * matches. Note that an explicit dot in a portion of the pattern\n * will always match dot files.\n */\n dot?: boolean\n\n /**\n * Prepend all relative path strings with `./` (or `.\\` on Windows).\n *\n * Without this option, returned relative paths are \"bare\", so instead of\n * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n *\n * Relative patterns starting with `'../'` are not prepended with `./`, even\n * if this option is set.\n */\n dotRelative?: boolean\n\n /**\n * Follow symlinked directories when expanding `**`\n * patterns. This can result in a lot of duplicate references in\n * the presence of cyclic links, and make performance quite bad.\n *\n * By default, a `**` in a pattern will follow 1 symbolic link if\n * it is not the first item in the pattern, or none if it is the\n * first item in the pattern, following the same behavior as Bash.\n */\n follow?: boolean\n\n /**\n * string or string[], or an object with `ignore` and `ignoreChildren`\n * methods.\n *\n * If a string or string[] is provided, then this is treated as a glob\n * pattern or array of glob patterns to exclude from matches. To ignore all\n * children within a directory, as well as the entry itself, append `'/**'`\n * to the ignore pattern.\n *\n * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n * any other settings.\n *\n * If an object is provided that has `ignored(path)` and/or\n * `childrenIgnored(path)` methods, then these methods will be called to\n * determine whether any Path is a match or if its children should be\n * traversed, respectively.\n */\n ignore?: string | string[] | IgnoreLike\n\n /**\n * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n * effect if {@link nobrace} is set.\n *\n * Only has effect on the {@link hasMagic} function.\n */\n magicalBraces?: boolean\n\n /**\n * Add a `/` character to directory matches. Note that this requires\n * additional stat calls in some cases.\n */\n mark?: boolean\n\n /**\n * Perform a basename-only match if the pattern does not contain any slash\n * characters. That is, `*.js` would be treated as equivalent to\n * `**\\/*.js`, matching all js files in all directories.\n */\n matchBase?: boolean\n\n /**\n * Limit the directory traversal to a given depth below the cwd.\n * Note that this does NOT prevent traversal to sibling folders,\n * root patterns, and so on. It only limits the maximum folder depth\n * that the walk will descend, relative to the cwd.\n */\n maxDepth?: number\n\n /**\n * Do not expand `{a,b}` and `{1..3}` brace sets.\n */\n nobrace?: boolean\n\n /**\n * Perform a case-insensitive match. This defaults to `true` on macOS and\n * Windows systems, and `false` on all others.\n *\n * **Note** `nocase` should only be explicitly set when it is\n * known that the filesystem's case sensitivity differs from the\n * platform default. If set `true` on case-sensitive file\n * systems, or `false` on case-insensitive file systems, then the\n * walk may return more or less results than expected.\n */\n nocase?: boolean\n\n /**\n * Do not match directories, only files. (Note: to match\n * _only_ directories, put a `/` at the end of the pattern.)\n */\n nodir?: boolean\n\n /**\n * Do not match \"extglob\" patterns such as `+(a|b)`.\n */\n noext?: boolean\n\n /**\n * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n * `*` instead.)\n *\n * Conflicts with {@link matchBase}\n */\n noglobstar?: boolean\n\n /**\n * Defaults to value of `process.platform` if available, or `'linux'` if\n * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n * behavior.\n */\n platform?: NodeJS.Platform\n\n /**\n * Set to true to call `fs.realpath` on all of the\n * results. In the case of an entry that cannot be resolved, the\n * entry is omitted. This incurs a slight performance penalty, of\n * course, because of the added system calls.\n */\n realpath?: boolean\n\n /**\n *\n * A string path resolved against the `cwd` option, which\n * is used as the starting point for absolute patterns that start\n * with `/`, (but not drive letters or UNC paths on Windows).\n *\n * Note that this _doesn't_ necessarily limit the walk to the\n * `root` directory, and doesn't affect the cwd starting point for\n * non-absolute patterns. A pattern containing `..` will still be\n * able to traverse out of the root directory, if it is not an\n * actual root directory on the filesystem, and any non-absolute\n * patterns will be matched in the `cwd`. For example, the\n * pattern `/../*` with `{root:'/some/path'}` will return all\n * files in `/some`, not all files in `/some/path`. The pattern\n * `*` with `{root:'/some/path'}` will return all the entries in\n * the cwd, not the entries in `/some/path`.\n *\n * To start absolute and non-absolute patterns in the same\n * path, you can use `{root:''}`. However, be aware that on\n * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n * _always_ start in the `x:/` or `//host/share` directory,\n * regardless of the `root` setting.\n */\n root?: string\n\n /**\n * A [PathScurry](http://npm.im/path-scurry) object used\n * to traverse the file system. If the `nocase` option is set\n * explicitly, then any provided `scurry` object must match this\n * setting.\n */\n scurry?: PathScurry\n\n /**\n * Call `lstat()` on all entries, whether required or not to determine\n * if it's a valid match. When used with {@link withFileTypes}, this means\n * that matches will include data such as modified time, permissions, and\n * so on. Note that this will incur a performance cost due to the added\n * system calls.\n */\n stat?: boolean\n\n /**\n * An AbortSignal which will cancel the Glob walk when\n * triggered.\n */\n signal?: AbortSignal\n\n /**\n * Use `\\\\` as a path separator _only_, and\n * _never_ as an escape character. If set, all `\\\\` characters are\n * replaced with `/` in the pattern.\n *\n * Note that this makes it **impossible** to match against paths\n * containing literal glob pattern characters, but allows matching\n * with patterns constructed using `path.join()` and\n * `path.resolve()` on Windows platforms, mimicking the (buggy!)\n * behavior of Glob v7 and before on Windows. Please use with\n * caution, and be mindful of [the caveat below about Windows\n * paths](#windows). (For legacy reasons, this is also set if\n * `allowWindowsEscape` is set to the exact value `false`.)\n */\n windowsPathsNoEscape?: boolean\n\n /**\n * Return [PathScurry](http://npm.im/path-scurry)\n * `Path` objects instead of strings. These are similar to a\n * NodeJS `Dirent` object, but with additional methods and\n * properties.\n *\n * Conflicts with {@link absolute}\n */\n withFileTypes?: boolean\n\n /**\n * An fs implementation to override some or all of the defaults. See\n * http://npm.im/path-scurry for details about what can be overridden.\n */\n fs?: FSOption\n\n /**\n * Just passed along to Minimatch. Note that this makes all pattern\n * matching operations slower and *extremely* noisy.\n */\n debug?: boolean\n\n /**\n * Return `/` delimited paths, even on Windows.\n *\n * On posix systems, this has no effect. But, on Windows, it means that\n * paths will be `/` delimited, and absolute paths will be their full\n * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n * `'//?/C:/foo/bar'`\n */\n posix?: boolean\n\n /**\n * Do not match any children of any matches. For example, the pattern\n * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n *\n * This is especially useful for cases like \"find all `node_modules`\n * folders, but not the ones in `node_modules`\".\n *\n * In order to support this, the `Ignore` implementation must support an\n * `add(pattern: string)` method. If using the default `Ignore` class, then\n * this is fine, but if this is set to `false`, and a custom `Ignore` is\n * provided that does not have an `add()` method, then it will throw an\n * error.\n *\n * **Caveat** It *only* ignores matches that would be a descendant of a\n * previous match, and only if that descendant is matched *after* the\n * ancestor is encountered. Since the file system walk happens in\n * indeterminate order, it's possible that a match will already be added\n * before its ancestor, if multiple or braced patterns are used.\n *\n * For example:\n *\n * ```ts\n * const results = await glob([\n * // likely to match first, since it's just a stat\n * 'a/b/c/d/e/f',\n *\n * // this pattern is more complicated! It must to various readdir()\n * // calls and test the results against a regular expression, and that\n * // is certainly going to take a little bit longer.\n * //\n * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n * // late to ignore a/b/c/d/e/f, because it's already been emitted.\n * 'a/[bdf]/?/[a-z]/*',\n * ], { includeChildMatches: false })\n * ```\n *\n * It's best to only set this to `false` if you can be reasonably sure that\n * no components of the pattern will potentially match one another's file\n * system descendants, or if the occasional included child entry will not\n * cause problems.\n *\n * @default true\n */\n includeChildMatches?: boolean\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n withFileTypes: true\n // string options not relevant if returning Path objects.\n absolute?: undefined\n mark?: undefined\n posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n withFileTypes?: undefined\n}\n\nexport type Result<Opts> =\n Opts extends GlobOptionsWithFileTypesTrue ? Path\n : Opts extends GlobOptionsWithFileTypesFalse ? string\n : Opts extends GlobOptionsWithFileTypesUnset ? string\n : string | Path\nexport type Results<Opts> = Result<Opts>[]\n\nexport type FileTypes<Opts> =\n Opts extends GlobOptionsWithFileTypesTrue ? true\n : Opts extends GlobOptionsWithFileTypesFalse ? false\n : Opts extends GlobOptionsWithFileTypesUnset ? false\n : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob<Opts extends GlobOptions> implements GlobOptions {\n absolute?: boolean\n cwd: string\n root?: string\n dot: boolean\n dotRelative: boolean\n follow: boolean\n ignore?: string | string[] | IgnoreLike\n magicalBraces: boolean\n mark?: boolean\n matchBase: boolean\n maxDepth: number\n nobrace: boolean\n nocase: boolean\n nodir: boolean\n noext: boolean\n noglobstar: boolean\n pattern: string[]\n platform: NodeJS.Platform\n realpath: boolean\n scurry: PathScurry\n stat: boolean\n signal?: AbortSignal\n windowsPathsNoEscape: boolean\n withFileTypes: FileTypes<Opts>\n includeChildMatches: boolean\n\n /**\n * The options provided to the constructor.\n */\n opts: Opts\n\n /**\n * An array of parsed immutable {@link Pattern} objects.\n */\n patterns: Pattern[]\n\n /**\n * All options are stored as properties on the `Glob` object.\n *\n * See {@link GlobOptions} for full options descriptions.\n *\n * Note that a previous `Glob` object can be passed as the\n * `GlobOptions` to another `Glob` instantiation to re-use settings\n * and caches with a new pattern.\n *\n * Traversal functions can be called multiple times to run the walk\n * again.\n */\n constructor(pattern: string | string[], opts: Opts) {\n /* c8 ignore start */\n if (!opts) throw new TypeError('glob options required')\n /* c8 ignore stop */\n this.withFileTypes = !!opts.withFileTypes as FileTypes<Opts>\n this.signal = opts.signal\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.dotRelative = !!opts.dotRelative\n this.nodir = !!opts.nodir\n this.mark = !!opts.mark\n if (!opts.cwd) {\n this.cwd = ''\n } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n opts.cwd = fileURLToPath(opts.cwd)\n }\n this.cwd = opts.cwd || ''\n this.root = opts.root\n this.magicalBraces = !!opts.magicalBraces\n this.nobrace = !!opts.nobrace\n this.noext = !!opts.noext\n this.realpath = !!opts.realpath\n this.absolute = opts.absolute\n this.includeChildMatches = opts.includeChildMatches !== false\n\n this.noglobstar = !!opts.noglobstar\n this.matchBase = !!opts.matchBase\n this.maxDepth =\n typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n this.stat = !!opts.stat\n this.ignore = opts.ignore\n\n if (this.withFileTypes && this.absolute !== undefined) {\n throw new Error('cannot set absolute and withFileTypes:true')\n }\n\n if (typeof pattern === 'string') {\n pattern = [pattern]\n }\n\n this.windowsPathsNoEscape =\n !!opts.windowsPathsNoEscape ||\n (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n false\n\n if (this.windowsPathsNoEscape) {\n pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n }\n\n if (this.matchBase) {\n if (opts.noglobstar) {\n throw new TypeError('base matching requires globstar')\n }\n pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n }\n\n this.pattern = pattern\n\n this.platform = opts.platform || defaultPlatform\n this.opts = { ...opts, platform: this.platform }\n if (opts.scurry) {\n this.scurry = opts.scurry\n if (\n opts.nocase !== undefined &&\n opts.nocase !== opts.scurry.nocase\n ) {\n throw new Error('nocase option contradicts provided scurry option')\n }\n } else {\n const Scurry =\n opts.platform === 'win32' ? PathScurryWin32\n : opts.platform === 'darwin' ? PathScurryDarwin\n : opts.platform ? PathScurryPosix\n : PathScurry\n this.scurry = new Scurry(this.cwd, {\n nocase: opts.nocase,\n fs: opts.fs,\n })\n }\n this.nocase = this.scurry.nocase\n\n // If you do nocase:true on a case-sensitive file system, then\n // we need to use regexps instead of strings for non-magic\n // path portions, because statting `aBc` won't return results\n // for the file `AbC` for example.\n const nocaseMagicOnly =\n this.platform === 'darwin' || this.platform === 'win32'\n\n const mmo: MinimatchOptions = {\n // default nocase based on platform\n ...opts,\n dot: this.dot,\n matchBase: this.matchBase,\n nobrace: this.nobrace,\n nocase: this.nocase,\n nocaseMagicOnly,\n nocomment: true,\n noext: this.noext,\n nonegate: true,\n optimizationLevel: 2,\n platform: this.platform,\n windowsPathsNoEscape: this.windowsPathsNoEscape,\n debug: !!this.opts.debug,\n }\n\n const mms = this.pattern.map(p => new Minimatch(p, mmo))\n const [matchSet, globParts] = mms.reduce(\n (set: [MatchSet, GlobParts], m) => {\n set[0].push(...m.set)\n set[1].push(...m.globParts)\n return set\n },\n [[], []],\n )\n this.patterns = matchSet.map((set, i) => {\n const g = globParts[i]\n /* c8 ignore start */\n if (!g) throw new Error('invalid pattern object')\n /* c8 ignore stop */\n return new Pattern(set, g, 0, this.platform)\n })\n }\n\n /**\n * Returns a Promise that resolves to the results array.\n */\n async walk(): Promise<Results<Opts>>\n async walk(): Promise<(string | Path)[]> {\n // Walkers always return array of Path objects, so we just have to\n // coerce them into the right shape. It will have already called\n // realpath() if the option was set to do so, so we know that's cached.\n // start out knowing the cwd, at least\n return [\n ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walk()),\n ]\n }\n\n /**\n * synchronous {@link Glob.walk}\n */\n walkSync(): Results<Opts>\n walkSync(): (string | Path)[] {\n return [\n ...new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walkSync(),\n ]\n }\n\n /**\n * Stream results asynchronously.\n */\n stream(): Minipass<Result<Opts>, Result<Opts>>\n stream(): Minipass<string | Path, string | Path> {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).stream()\n }\n\n /**\n * Stream results synchronously.\n */\n streamSync(): Minipass<Result<Opts>, Result<Opts>>\n streamSync(): Minipass<string | Path, string | Path> {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).streamSync()\n }\n\n /**\n * Default sync iteration function. Returns a Generator that\n * iterates over the results.\n */\n iterateSync(): Generator<Result<Opts>, void, void> {\n return this.streamSync()[Symbol.iterator]()\n }\n [Symbol.iterator]() {\n return this.iterateSync()\n }\n\n /**\n * Default async iteration function. Returns an AsyncGenerator that\n * iterates over the results.\n */\n iterate(): AsyncGenerator<Result<Opts>, void, void> {\n return this.stream()[Symbol.asyncIterator]()\n }\n [Symbol.asyncIterator]() {\n return this.iterate()\n }\n}\n", "/**\n * @module LRUCache\n */\n\n// module-private names and types\ntype Perf = { now: () => number }\nconst perf: Perf =\n typeof performance === 'object' &&\n performance &&\n typeof performance.now === 'function'\n ? performance\n : Date\n\nconst warned = new Set<string>()\n\n// either a function or a class\ntype ForC = ((...a: any[]) => any) | { new (...a: any[]): any }\n\n/* c8 ignore start */\nconst PROCESS = (\n typeof process === 'object' && !!process ? process : {}\n) as { [k: string]: any }\n/* c8 ignore start */\n\nconst emitWarning = (\n msg: string,\n type: string,\n code: string,\n fn: ForC\n) => {\n typeof PROCESS.emitWarning === 'function'\n ? PROCESS.emitWarning(msg, type, code, fn)\n : console.error(`[${code}] ${type}: ${msg}`)\n}\n\nlet AC = globalThis.AbortController\nlet AS = globalThis.AbortSignal\n\n/* c8 ignore start */\nif (typeof AC === 'undefined') {\n //@ts-ignore\n AS = class AbortSignal {\n onabort?: (...a: any[]) => any\n _onabort: ((...a: any[]) => any)[] = []\n reason?: any\n aborted: boolean = false\n addEventListener(_: string, fn: (...a: any[]) => any) {\n this._onabort.push(fn)\n }\n }\n //@ts-ignore\n AC = class AbortController {\n constructor() {\n warnACPolyfill()\n }\n signal = new AS()\n abort(reason: any) {\n if (this.signal.aborted) return\n //@ts-ignore\n this.signal.reason = reason\n //@ts-ignore\n this.signal.aborted = true\n //@ts-ignore\n for (const fn of this.signal._onabort) {\n fn(reason)\n }\n this.signal.onabort?.(reason)\n }\n }\n let printACPolyfillWarning =\n PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'\n const warnACPolyfill = () => {\n if (!printACPolyfillWarning) return\n printACPolyfillWarning = false\n emitWarning(\n 'AbortController is not defined. If using lru-cache in ' +\n 'node 14, load an AbortController polyfill from the ' +\n '`node-abort-controller` package. A minimal polyfill is ' +\n 'provided for use by LRUCache.fetch(), but it should not be ' +\n 'relied upon in other contexts (eg, passing it to other APIs that ' +\n 'use AbortController/AbortSignal might have undesirable effects). ' +\n 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.',\n 'NO_ABORT_CONTROLLER',\n 'ENOTSUP',\n warnACPolyfill\n )\n }\n}\n/* c8 ignore stop */\n\nconst shouldWarn = (code: string) => !warned.has(code)\n\nconst TYPE = Symbol('type')\nexport type PosInt = number & { [TYPE]: 'Positive Integer' }\nexport type Index = number & { [TYPE]: 'LRUCache Index' }\n\nconst isPosInt = (n: any): n is PosInt =>\n n && n === Math.floor(n) && n > 0 && isFinite(n)\n\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array\nexport type NumberArray = UintArray | number[]\n\n/* c8 ignore start */\n// This is a little bit ridiculous, tbh.\n// The maximum array length is 2^32-1 or thereabouts on most JS impls.\n// And well before that point, you're caching the entire world, I mean,\n// that's ~32GB of just integers for the next/prev links, plus whatever\n// else to hold that many keys and values. Just filling the memory with\n// zeroes at init time is brutal when you get that big.\n// But why not be complete?\n// Maybe in the future, these limits will have expanded.\nconst getUintArray = (max: number) =>\n !isPosInt(max)\n ? null\n : max <= Math.pow(2, 8)\n ? Uint8Array\n : max <= Math.pow(2, 16)\n ? Uint16Array\n : max <= Math.pow(2, 32)\n ? Uint32Array\n : max <= Number.MAX_SAFE_INTEGER\n ? ZeroArray\n : null\n/* c8 ignore stop */\n\nclass ZeroArray extends Array<number> {\n constructor(size: number) {\n super(size)\n this.fill(0)\n }\n}\nexport type { ZeroArray }\nexport type { Stack }\n\nexport type StackLike = Stack | Index[]\nclass Stack {\n heap: NumberArray\n length: number\n // private constructor\n static #constructing: boolean = false\n static create(max: number): StackLike {\n const HeapCls = getUintArray(max)\n if (!HeapCls) return []\n Stack.#constructing = true\n const s = new Stack(max, HeapCls)\n Stack.#constructing = false\n return s\n }\n constructor(\n max: number,\n HeapCls: { new (n: number): NumberArray }\n ) {\n /* c8 ignore start */\n if (!Stack.#constructing) {\n throw new TypeError('instantiate Stack using Stack.create(n)')\n }\n /* c8 ignore stop */\n this.heap = new HeapCls(max)\n this.length = 0\n }\n push(n: Index) {\n this.heap[this.length++] = n\n }\n pop(): Index {\n return this.heap[--this.length] as Index\n }\n}\n\n/**\n * Promise representing an in-progress {@link LRUCache#fetch} call\n */\nexport type BackgroundFetch<V> = Promise<V | undefined> & {\n __returned: BackgroundFetch<V> | undefined\n __abortController: AbortController\n __staleWhileFetching: V | undefined\n}\n\nexport type DisposeTask<K, V> = [\n value: V,\n key: K,\n reason: LRUCache.DisposeReason\n]\n\nexport namespace LRUCache {\n /**\n * An integer greater than 0, reflecting the calculated size of items\n */\n export type Size = number\n\n /**\n * Integer greater than 0, representing some number of milliseconds, or the\n * time at which a TTL started counting from.\n */\n export type Milliseconds = number\n\n /**\n * An integer greater than 0, reflecting a number of items\n */\n export type Count = number\n\n /**\n * The reason why an item was removed from the cache, passed\n * to the {@link Disposer} methods.\n *\n * - `evict`: The item was evicted because it is the least recently used,\n * and the cache is full.\n * - `set`: A new value was set, overwriting the old value being disposed.\n * - `delete`: The item was explicitly deleted, either by calling\n * {@link LRUCache#delete}, {@link LRUCache#clear}, or\n * {@link LRUCache#set} with an undefined value.\n * - `expire`: The item was removed due to exceeding its TTL.\n * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n * `undefined` or was aborted, causing the item to be deleted.\n */\n export type DisposeReason =\n | 'evict'\n | 'set'\n | 'delete'\n | 'expire'\n | 'fetch'\n /**\n * A method called upon item removal, passed as the\n * {@link OptionsBase.dispose} and/or\n * {@link OptionsBase.disposeAfter} options.\n */\n export type Disposer<K, V> = (\n value: V,\n key: K,\n reason: DisposeReason\n ) => void\n\n /**\n * A function that returns the effective calculated size\n * of an entry in the cache.\n */\n export type SizeCalculator<K, V> = (value: V, key: K) => Size\n\n /**\n * Options provided to the\n * {@link OptionsBase.fetchMethod} function.\n */\n export interface FetcherOptions<K, V, FC = unknown> {\n signal: AbortSignal\n options: FetcherFetchOptions<K, V, FC>\n /**\n * Object provided in the {@link FetchOptions.context} option to\n * {@link LRUCache#fetch}\n */\n context: FC\n }\n\n /**\n * Occasionally, it may be useful to track the internal behavior of the\n * cache, particularly for logging, debugging, or for behavior within the\n * `fetchMethod`. To do this, you can pass a `status` object to the\n * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n *\n * The `status` option should be a plain JavaScript object. The following\n * fields will be set on it appropriately, depending on the situation.\n */\n export interface Status<V> {\n /**\n * The status of a set() operation.\n *\n * - add: the item was not found in the cache, and was added\n * - update: the item was in the cache, with the same value provided\n * - replace: the item was in the cache, and replaced\n * - miss: the item was not added to the cache for some reason\n */\n set?: 'add' | 'update' | 'replace' | 'miss'\n\n /**\n * the ttl stored for the item, or undefined if ttls are not used.\n */\n ttl?: Milliseconds\n\n /**\n * the start time for the item, or undefined if ttls are not used.\n */\n start?: Milliseconds\n\n /**\n * The timestamp used for TTL calculation\n */\n now?: Milliseconds\n\n /**\n * the remaining ttl for the item, or undefined if ttls are not used.\n */\n remainingTTL?: Milliseconds\n\n /**\n * The calculated size for the item, if sizes are used.\n */\n entrySize?: Size\n\n /**\n * The total calculated size of the cache, if sizes are used.\n */\n totalCalculatedSize?: Size\n\n /**\n * A flag indicating that the item was not stored, due to exceeding the\n * {@link OptionsBase.maxEntrySize}\n */\n maxEntrySizeExceeded?: true\n\n /**\n * The old value, specified in the case of `set:'update'` or\n * `set:'replace'`\n */\n oldValue?: V\n\n /**\n * The results of a {@link LRUCache#has} operation\n *\n * - hit: the item was found in the cache\n * - stale: the item was found in the cache, but is stale\n * - miss: the item was not found in the cache\n */\n has?: 'hit' | 'stale' | 'miss'\n\n /**\n * The status of a {@link LRUCache#fetch} operation.\n * Note that this can change as the underlying fetch() moves through\n * various states.\n *\n * - inflight: there is another fetch() for this key which is in process\n * - get: there is no {@link OptionsBase.fetchMethod}, so\n * {@link LRUCache#get} was called.\n * - miss: the item is not in cache, and will be fetched.\n * - hit: the item is in the cache, and was resolved immediately.\n * - stale: the item is in the cache, but stale.\n * - refresh: the item is in the cache, and not stale, but\n * {@link FetchOptions.forceRefresh} was specified.\n */\n fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'\n\n /**\n * The {@link OptionsBase.fetchMethod} was called\n */\n fetchDispatched?: true\n\n /**\n * The cached value was updated after a successful call to\n * {@link OptionsBase.fetchMethod}\n */\n fetchUpdated?: true\n\n /**\n * The reason for a fetch() rejection. Either the error raised by the\n * {@link OptionsBase.fetchMethod}, or the reason for an\n * AbortSignal.\n */\n fetchError?: Error\n\n /**\n * The fetch received an abort signal\n */\n fetchAborted?: true\n\n /**\n * The abort signal received was ignored, and the fetch was allowed to\n * continue.\n */\n fetchAbortIgnored?: true\n\n /**\n * The fetchMethod promise resolved successfully\n */\n fetchResolved?: true\n\n /**\n * The fetchMethod promise was rejected\n */\n fetchRejected?: true\n\n /**\n * The status of a {@link LRUCache#get} operation.\n *\n * - fetching: The item is currently being fetched. If a previous value\n * is present and allowed, that will be returned.\n * - stale: The item is in the cache, and is stale.\n * - hit: the item is in the cache\n * - miss: the item is not in the cache\n */\n get?: 'stale' | 'hit' | 'miss'\n\n /**\n * A fetch or get operation returned a stale value.\n */\n returnedStale?: true\n }\n\n /**\n * options which override the options set in the LRUCache constructor\n * when calling {@link LRUCache#fetch}.\n *\n * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n * {@link OptionsBase.noDeleteOnFetchRejection},\n * {@link OptionsBase.allowStaleOnFetchRejection},\n * {@link FetchOptions.forceRefresh}, and\n * {@link FetcherOptions.context}\n *\n * Any of these may be modified in the {@link OptionsBase.fetchMethod}\n * function, but the {@link GetOptions} fields will of course have no\n * effect, as the {@link LRUCache#get} call already happened by the time\n * the fetchMethod is called.\n */\n export interface FetcherFetchOptions<K, V, FC = unknown>\n extends Pick<\n OptionsBase<K, V, FC>,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n | 'noDeleteOnFetchRejection'\n | 'allowStaleOnFetchRejection'\n | 'ignoreFetchAbort'\n | 'allowStaleOnFetchAbort'\n > {\n status?: Status<V>\n size?: Size\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#fetch} method.\n */\n export interface FetchOptions<K, V, FC>\n extends FetcherFetchOptions<K, V, FC> {\n /**\n * Set to true to force a re-load of the existing data, even if it\n * is not yet stale.\n */\n forceRefresh?: boolean\n /**\n * Context provided to the {@link OptionsBase.fetchMethod} as\n * the {@link FetcherOptions.context} param.\n *\n * If the FC type is specified as unknown (the default),\n * undefined or void, then this is optional. Otherwise, it will\n * be required.\n */\n context?: FC\n signal?: AbortSignal\n status?: Status<V>\n }\n /**\n * Options provided to {@link LRUCache#fetch} when the FC type is something\n * other than `unknown`, `undefined`, or `void`\n */\n export interface FetchOptionsWithContext<K, V, FC>\n extends FetchOptions<K, V, FC> {\n context: FC\n }\n /**\n * Options provided to {@link LRUCache#fetch} when the FC type is\n * `undefined` or `void`\n */\n export interface FetchOptionsNoContext<K, V>\n extends FetchOptions<K, V, undefined> {\n context?: undefined\n }\n\n export interface MemoOptions<K, V, FC = unknown>\n extends Pick<\n OptionsBase<K, V, FC>,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n | 'noDeleteOnFetchRejection'\n | 'allowStaleOnFetchRejection'\n | 'ignoreFetchAbort'\n | 'allowStaleOnFetchAbort'\n > {\n /**\n * Set to true to force a re-load of the existing data, even if it\n * is not yet stale.\n */\n forceRefresh?: boolean\n /**\n * Context provided to the {@link OptionsBase.memoMethod} as\n * the {@link MemoizerOptions.context} param.\n *\n * If the FC type is specified as unknown (the default),\n * undefined or void, then this is optional. Otherwise, it will\n * be required.\n */\n context?: FC\n status?: Status<V>\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is something\n * other than `unknown`, `undefined`, or `void`\n */\n export interface MemoOptionsWithContext<K, V, FC>\n extends MemoOptions<K, V, FC> {\n context: FC\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is\n * `undefined` or `void`\n */\n export interface MemoOptionsNoContext<K, V>\n extends MemoOptions<K, V, undefined> {\n context?: undefined\n }\n\n /**\n * Options provided to the\n * {@link OptionsBase.memoMethod} function.\n */\n export interface MemoizerOptions<K, V, FC = unknown> {\n options: MemoizerMemoOptions<K, V, FC>\n /**\n * Object provided in the {@link MemoOptions.context} option to\n * {@link LRUCache#memo}\n */\n context: FC\n }\n\n /**\n * options which override the options set in the LRUCache constructor\n * when calling {@link LRUCache#memo}.\n *\n * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n * {@link MemoOptions.forceRefresh}, and\n * {@link MemoerOptions.context}\n *\n * Any of these may be modified in the {@link OptionsBase.memoMethod}\n * function, but the {@link GetOptions} fields will of course have no\n * effect, as the {@link LRUCache#get} call already happened by the time\n * the memoMethod is called.\n */\n export interface MemoizerMemoOptions<K, V, FC = unknown>\n extends Pick<\n OptionsBase<K, V, FC>,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n > {\n status?: Status<V>\n size?: Size\n start?: Milliseconds\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#has} method.\n */\n export interface HasOptions<K, V, FC>\n extends Pick<OptionsBase<K, V, FC>, 'updateAgeOnHas'> {\n status?: Status<V>\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#get} method.\n */\n export interface GetOptions<K, V, FC>\n extends Pick<\n OptionsBase<K, V, FC>,\n 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'\n > {\n status?: Status<V>\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#peek} method.\n */\n export interface PeekOptions<K, V, FC>\n extends Pick<OptionsBase<K, V, FC>, 'allowStale'> {}\n\n /**\n * Options that may be passed to the {@link LRUCache#set} method.\n */\n export interface SetOptions<K, V, FC>\n extends Pick<\n OptionsBase<K, V, FC>,\n 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'\n > {\n /**\n * If size tracking is enabled, then setting an explicit size\n * in the {@link LRUCache#set} call will prevent calling the\n * {@link OptionsBase.sizeCalculation} function.\n */\n size?: Size\n /**\n * If TTL tracking is enabled, then setting an explicit start\n * time in the {@link LRUCache#set} call will override the\n * default time from `performance.now()` or `Date.now()`.\n *\n * Note that it must be a valid value for whichever time-tracking\n * method is in use.\n */\n start?: Milliseconds\n status?: Status<V>\n }\n\n /**\n * The type signature for the {@link OptionsBase.fetchMethod} option.\n */\n export type Fetcher<K, V, FC = unknown> = (\n key: K,\n staleValue: V | undefined,\n options: FetcherOptions<K, V, FC>\n ) => Promise<V | undefined | void> | V | undefined | void\n\n /**\n * the type signature for the {@link OptionsBase.memoMethod} option.\n */\n export type Memoizer<K, V, FC = unknown> = (\n key: K,\n staleValue: V | undefined,\n options: MemoizerOptions<K, V, FC>\n ) => V\n\n /**\n * Options which may be passed to the {@link LRUCache} constructor.\n *\n * Most of these may be overridden in the various options that use\n * them.\n *\n * Despite all being technically optional, the constructor requires that\n * a cache is at minimum limited by one or more of {@link OptionsBase.max},\n * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.\n *\n * If {@link OptionsBase.ttl} is used alone, then it is strongly advised\n * (and in fact required by the type definitions here) that the cache\n * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially\n * unbounded storage.\n *\n * All options are also available on the {@link LRUCache} instance, making\n * it safe to pass an LRUCache instance as the options argumemnt to\n * make another empty cache of the same type.\n *\n * Some options are marked as read-only, because changing them after\n * instantiation is not safe. Changing any of the other options will of\n * course only have an effect on subsequent method calls.\n */\n export interface OptionsBase<K, V, FC> {\n /**\n * The maximum number of items to store in the cache before evicting\n * old entries. This is read-only on the {@link LRUCache} instance,\n * and may not be overridden.\n *\n * If set, then storage space will be pre-allocated at construction\n * time, and the cache will perform significantly faster.\n *\n * Note that significantly fewer items may be stored, if\n * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also\n * set.\n *\n * **It is strongly recommended to set a `max` to prevent unbounded growth\n * of the cache.**\n */\n max?: Count\n\n /**\n * Max time in milliseconds for items to live in cache before they are\n * considered stale. Note that stale items are NOT preemptively removed by\n * default, and MAY live in the cache, contributing to its LRU max, long\n * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n * set.\n *\n * If set to `0` (the default value), then that means \"do not track\n * TTL\", not \"expire immediately\".\n *\n * Also, as this cache is optimized for LRU/MRU operations, some of\n * the staleness/TTL checks will reduce performance, as they will incur\n * overhead by deleting items.\n *\n * This is not primarily a TTL cache, and does not make strong TTL\n * guarantees. There is no pre-emptive pruning of expired items, but you\n * _may_ set a TTL on the cache, and it will treat expired items as missing\n * when they are fetched, and delete them.\n *\n * Optional, but must be a non-negative integer in ms if specified.\n *\n * This may be overridden by passing an options object to `cache.set()`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if ttl tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\n *\n * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n * and `ttlAutopurge` is not set, then a warning will be emitted\n * cautioning about the potential for unbounded memory consumption.\n * (The TypeScript definitions will also discourage this.)\n */\n ttl?: Milliseconds\n\n /**\n * Minimum amount of time in ms in which to check for staleness.\n * Defaults to 1, which means that the current time is checked\n * at most once per millisecond.\n *\n * Set to 0 to check the current time every time staleness is tested.\n * (This reduces performance, and is theoretically unnecessary.)\n *\n * Setting this to a higher value will improve performance somewhat\n * while using ttl tracking, albeit at the expense of keeping stale\n * items around a bit longer than their TTLs would indicate.\n *\n * @default 1\n */\n ttlResolution?: Milliseconds\n\n /**\n * Preemptively remove stale items from the cache.\n *\n * Note that this may *significantly* degrade performance, especially if\n * the cache is storing a large number of items. It is almost always best\n * to just leave the stale items in the cache, and let them fall out as new\n * items are added.\n *\n * Note that this means that {@link OptionsBase.allowStale} is a bit\n * pointless, as stale items will be deleted almost as soon as they\n * expire.\n *\n * Use with caution!\n */\n ttlAutopurge?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever it is retrieved from cache with\n * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n * of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n */\n updateAgeOnGet?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever its presence in the cache is\n * checked with {@link LRUCache#has}, causing it to not expire. (It can\n * still fall out of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\n */\n updateAgeOnHas?: boolean\n\n /**\n * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return\n * stale data, if available.\n *\n * By default, if you set `ttl`, stale items will only be deleted from the\n * cache when you `get(key)`. That is, it's not preemptively pruning items,\n * unless {@link OptionsBase.ttlAutopurge} is set.\n *\n * If you set `allowStale:true`, it'll return the stale value *as well as*\n * deleting it. If you don't set this, then it'll return `undefined` when\n * you try to get a stale entry.\n *\n * Note that when a stale entry is fetched, _even if it is returned due to\n * `allowStale` being set_, it is removed from the cache immediately. You\n * can suppress this behavior by setting\n * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n * the options provided to {@link LRUCache#get}.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n * The `cache.has()` method will always return `false` for stale items.\n *\n * Only relevant if a ttl is set.\n */\n allowStale?: boolean\n\n /**\n * Function that is called on items when they are dropped from the\n * cache, as `dispose(value, key, reason)`.\n *\n * This can be handy if you want to close file descriptors or do\n * other cleanup tasks when items are no longer stored in the cache.\n *\n * **NOTE**: It is called _before_ the item has been fully removed\n * from the cache, so if you want to put it right back in, you need\n * to wait until the next tick. If you try to add it back in during\n * the `dispose()` function call, it will break things in subtle and\n * weird ways.\n *\n * Unlike several other options, this may _not_ be overridden by\n * passing an option to `set()`, for performance reasons.\n *\n * The `reason` will be one of the following strings, corresponding\n * to the reason for the item's deletion:\n *\n * - `evict` Item was evicted to make space for a new addition\n * - `set` Item was overwritten by a new value\n * - `expire` Item expired its TTL\n * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n * fetchMethod returning `undefined.\n * - `delete` Item was removed by explicit `cache.delete(key)`,\n * `cache.clear()`, or `cache.set(key, undefined)`.\n */\n dispose?: Disposer<K, V>\n\n /**\n * The same as {@link OptionsBase.dispose}, but called *after* the entry\n * is completely removed and the cache is once again in a clean state.\n *\n * It is safe to add an item right back into the cache at this point.\n * However, note that it is *very* easy to inadvertently create infinite\n * recursion this way.\n */\n disposeAfter?: Disposer<K, V>\n\n /**\n * Set to true to suppress calling the\n * {@link OptionsBase.dispose} function if the entry key is\n * still accessible within the cache.\n *\n * This may be overridden by passing an options object to\n * {@link LRUCache#set}.\n *\n * Only relevant if `dispose` or `disposeAfter` are set.\n */\n noDisposeOnSet?: boolean\n\n /**\n * Boolean flag to tell the cache to not update the TTL when setting a new\n * value for an existing key (ie, when updating a value rather than\n * inserting a new value). Note that the TTL value is _always_ set (if\n * provided) when adding a new entry into the cache.\n *\n * Has no effect if a {@link OptionsBase.ttl} is not set.\n *\n * May be passed as an option to {@link LRUCache#set}.\n */\n noUpdateTTL?: boolean\n\n /**\n * Set to a positive integer to track the sizes of items added to the\n * cache, and automatically evict items in order to stay below this size.\n * Note that this may result in fewer than `max` items being stored.\n *\n * Attempting to add an item to the cache whose calculated size is greater\n * that this amount will be a no-op. The item will not be cached, and no\n * other items will be evicted.\n *\n * Optional, must be a positive integer if provided.\n *\n * Sets `maxEntrySize` to the same value, unless a different value is\n * provided for `maxEntrySize`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if size tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\n *\n * Note also that size tracking can negatively impact performance,\n * though for most cases, only minimally.\n */\n maxSize?: Size\n\n /**\n * The maximum allowed size for any single item in the cache.\n *\n * If a larger item is passed to {@link LRUCache#set} or returned by a\n * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then\n * it will not be stored in the cache.\n *\n * Attempting to add an item whose calculated size is greater than\n * this amount will not cache the item or evict any old items, but\n * WILL delete an existing value if one is already present.\n *\n * Optional, must be a positive integer if provided. Defaults to\n * the value of `maxSize` if provided.\n */\n maxEntrySize?: Size\n\n /**\n * A function that returns a number indicating the item's size.\n *\n * Requires {@link OptionsBase.maxSize} to be set.\n *\n * If not provided, and {@link OptionsBase.maxSize} or\n * {@link OptionsBase.maxEntrySize} are set, then all\n * {@link LRUCache#set} calls **must** provide an explicit\n * {@link SetOptions.size} or sizeCalculation param.\n */\n sizeCalculation?: SizeCalculator<K, V>\n\n /**\n * Method that provides the implementation for {@link LRUCache#fetch}\n *\n * ```ts\n * fetchMethod(key, staleValue, { signal, options, context })\n * ```\n *\n * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n * to `Promise.resolve(cache.get(key))`.\n *\n * If at any time, `signal.aborted` is set to `true`, or if the\n * `signal.onabort` method is called, or if it emits an `'abort'` event\n * which you can listen to with `addEventListener`, then that means that\n * the fetch should be abandoned. This may be passed along to async\n * functions aware of AbortController/AbortSignal behavior.\n *\n * The `fetchMethod` should **only** return `undefined` or a Promise\n * resolving to `undefined` if the AbortController signaled an `abort`\n * event. In all other cases, it should return or resolve to a value\n * suitable for adding to the cache.\n *\n * The `options` object is a union of the options that may be provided to\n * `set()` and `get()`. If they are modified, then that will result in\n * modifying the settings to `cache.set()` when the value is resolved, and\n * in the case of\n * {@link OptionsBase.noDeleteOnFetchRejection} and\n * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n * `fetchMethod` failures.\n *\n * For example, a DNS cache may update the TTL based on the value returned\n * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n */\n fetchMethod?: Fetcher<K, V, FC>\n\n /**\n * Method that provides the implementation for {@link LRUCache#memo}\n */\n memoMethod?: Memoizer<K, V, FC>\n\n /**\n * Set to true to suppress the deletion of stale data when a\n * {@link OptionsBase.fetchMethod} returns a rejected promise.\n */\n noDeleteOnFetchRejection?: boolean\n\n /**\n * Do not delete stale items when they are retrieved with\n * {@link LRUCache#get}.\n *\n * Note that the `get` return value will still be `undefined`\n * unless {@link OptionsBase.allowStale} is true.\n *\n * When using time-expiring entries with `ttl`, by default stale\n * items will be removed from the cache when the key is accessed\n * with `cache.get()`.\n *\n * Setting this option will cause stale items to remain in the cache, until\n * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n * `noDeleteOnStaleGet` set to `false`.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n *\n * Only relevant if a ttl is used.\n */\n noDeleteOnStaleGet?: boolean\n\n /**\n * Set to true to allow returning stale data when a\n * {@link OptionsBase.fetchMethod} throws an error or returns a rejected\n * promise.\n *\n * This differs from using {@link OptionsBase.allowStale} in that stale\n * data will ONLY be returned in the case that the {@link LRUCache#fetch}\n * fails, not any other times.\n *\n * If a `fetchMethod` fails, and there is no stale value available, the\n * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n * suppressed.\n *\n * Implies `noDeleteOnFetchRejection`.\n *\n * This may be set in calls to `fetch()`, or defaulted on the constructor,\n * or overridden by modifying the options object in the `fetchMethod`.\n */\n allowStaleOnFetchRejection?: boolean\n\n /**\n * Set to true to return a stale value from the cache when the\n * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches\n * an `'abort'` event, whether user-triggered, or due to internal cache\n * behavior.\n *\n * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying\n * {@link OptionsBase.fetchMethod} will still be considered canceled, and\n * any value it returns will be ignored and not cached.\n *\n * Caveat: since fetches are aborted when a new value is explicitly\n * set in the cache, this can lead to fetch returning a stale value,\n * since that was the fallback value _at the moment the `fetch()` was\n * initiated_, even though the new updated value is now present in\n * the cache.\n *\n * For example:\n *\n * ```ts\n * const cache = new LRUCache<string, any>({\n * ttl: 100,\n * fetchMethod: async (url, oldValue, { signal }) => {\n * const res = await fetch(url, { signal })\n * return await res.json()\n * }\n * })\n * cache.set('https://example.com/', { some: 'data' })\n * // 100ms go by...\n * const result = cache.fetch('https://example.com/')\n * cache.set('https://example.com/', { other: 'thing' })\n * console.log(await result) // { some: 'data' }\n * console.log(cache.get('https://example.com/')) // { other: 'thing' }\n * ```\n */\n allowStaleOnFetchAbort?: boolean\n\n /**\n * Set to true to ignore the `abort` event emitted by the `AbortSignal`\n * object passed to {@link OptionsBase.fetchMethod}, and still cache the\n * resulting resolution value, as long as it is not `undefined`.\n *\n * When used on its own, this means aborted {@link LRUCache#fetch} calls\n * are not immediately resolved or rejected when they are aborted, and\n * instead take the full time to await.\n *\n * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted\n * {@link LRUCache#fetch} calls will resolve immediately to their stale\n * cached value or `undefined`, and will continue to process and eventually\n * update the cache when they resolve, as long as the resulting value is\n * not `undefined`, thus supporting a \"return stale on timeout while\n * refreshing\" mechanism by passing `AbortSignal.timeout(n)` as the signal.\n *\n * For example:\n *\n * ```ts\n * const c = new LRUCache({\n * ttl: 100,\n * ignoreFetchAbort: true,\n * allowStaleOnFetchAbort: true,\n * fetchMethod: async (key, oldValue, { signal }) => {\n * // note: do NOT pass the signal to fetch()!\n * // let's say this fetch can take a long time.\n * const res = await fetch(`https://slow-backend-server/${key}`)\n * return await res.json()\n * },\n * })\n *\n * // this will return the stale value after 100ms, while still\n * // updating in the background for next time.\n * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n * ```\n *\n * **Note**: regardless of this setting, an `abort` event _is still\n * emitted on the `AbortSignal` object_, so may result in invalid results\n * when passed to other underlying APIs that use AbortSignals.\n *\n * This may be overridden in the {@link OptionsBase.fetchMethod} or the\n * call to {@link LRUCache#fetch}.\n */\n ignoreFetchAbort?: boolean\n }\n\n export interface OptionsMaxLimit<K, V, FC>\n extends OptionsBase<K, V, FC> {\n max: Count\n }\n export interface OptionsTTLLimit<K, V, FC>\n extends OptionsBase<K, V, FC> {\n ttl: Milliseconds\n ttlAutopurge: boolean\n }\n export interface OptionsSizeLimit<K, V, FC>\n extends OptionsBase<K, V, FC> {\n maxSize: Size\n }\n\n /**\n * The valid safe options for the {@link LRUCache} constructor\n */\n export type Options<K, V, FC> =\n | OptionsMaxLimit<K, V, FC>\n | OptionsSizeLimit<K, V, FC>\n | OptionsTTLLimit<K, V, FC>\n\n /**\n * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},\n * and returned by {@link LRUCache#info}.\n */\n export interface Entry<V> {\n value: V\n ttl?: Milliseconds\n size?: Size\n start?: Milliseconds\n }\n}\n\n/**\n * Default export, the thing you're using this module to get.\n *\n * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache<K extends {}, V extends {}, FC = unknown>\n implements Map<K, V>\n{\n // options that cannot be changed without disaster\n readonly #max: LRUCache.Count\n readonly #maxSize: LRUCache.Size\n readonly #dispose?: LRUCache.Disposer<K, V>\n readonly #disposeAfter?: LRUCache.Disposer<K, V>\n readonly #fetchMethod?: LRUCache.Fetcher<K, V, FC>\n readonly #memoMethod?: LRUCache.Memoizer<K, V, FC>\n\n /**\n * {@link LRUCache.OptionsBase.ttl}\n */\n ttl: LRUCache.Milliseconds\n\n /**\n * {@link LRUCache.OptionsBase.ttlResolution}\n */\n ttlResolution: LRUCache.Milliseconds\n /**\n * {@link LRUCache.OptionsBase.ttlAutopurge}\n */\n ttlAutopurge: boolean\n /**\n * {@link LRUCache.OptionsBase.updateAgeOnGet}\n */\n updateAgeOnGet: boolean\n /**\n * {@link LRUCache.OptionsBase.updateAgeOnHas}\n */\n updateAgeOnHas: boolean\n /**\n * {@link LRUCache.OptionsBase.allowStale}\n */\n allowStale: boolean\n\n /**\n * {@link LRUCache.OptionsBase.noDisposeOnSet}\n */\n noDisposeOnSet: boolean\n /**\n * {@link LRUCache.OptionsBase.noUpdateTTL}\n */\n noUpdateTTL: boolean\n /**\n * {@link LRUCache.OptionsBase.maxEntrySize}\n */\n maxEntrySize: LRUCache.Size\n /**\n * {@link LRUCache.OptionsBase.sizeCalculation}\n */\n sizeCalculation?: LRUCache.SizeCalculator<K, V>\n /**\n * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n */\n noDeleteOnFetchRejection: boolean\n /**\n * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n */\n noDeleteOnStaleGet: boolean\n /**\n * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n */\n allowStaleOnFetchAbort: boolean\n /**\n * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n */\n allowStaleOnFetchRejection: boolean\n /**\n * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n */\n ignoreFetchAbort: boolean\n\n // computed properties\n #size: LRUCache.Count\n #calculatedSize: LRUCache.Size\n #keyMap: Map<K, Index>\n #keyList: (K | undefined)[]\n #valList: (V | BackgroundFetch<V> | undefined)[]\n #next: NumberArray\n #prev: NumberArray\n #head: Index\n #tail: Index\n #free: StackLike\n #disposed?: DisposeTask<K, V>[]\n #sizes?: ZeroArray\n #starts?: ZeroArray\n #ttls?: ZeroArray\n\n #hasDispose: boolean\n #hasFetchMethod: boolean\n #hasDisposeAfter: boolean\n\n /**\n * Do not call this method unless you need to inspect the\n * inner workings of the cache. If anything returned by this\n * object is modified in any way, strange breakage may occur.\n *\n * These fields are private for a reason!\n *\n * @internal\n */\n static unsafeExposeInternals<\n K extends {},\n V extends {},\n FC extends unknown = unknown\n >(c: LRUCache<K, V, FC>) {\n return {\n // properties\n starts: c.#starts,\n ttls: c.#ttls,\n sizes: c.#sizes,\n keyMap: c.#keyMap as Map<K, number>,\n keyList: c.#keyList,\n valList: c.#valList,\n next: c.#next,\n prev: c.#prev,\n get head() {\n return c.#head\n },\n get tail() {\n return c.#tail\n },\n free: c.#free,\n // methods\n isBackgroundFetch: (p: any) => c.#isBackgroundFetch(p),\n backgroundFetch: (\n k: K,\n index: number | undefined,\n options: LRUCache.FetchOptions<K, V, FC>,\n context: any\n ): BackgroundFetch<V> =>\n c.#backgroundFetch(\n k,\n index as Index | undefined,\n options,\n context\n ),\n moveToTail: (index: number): void =>\n c.#moveToTail(index as Index),\n indexes: (options?: { allowStale: boolean }) =>\n c.#indexes(options),\n rindexes: (options?: { allowStale: boolean }) =>\n c.#rindexes(options),\n isStale: (index: number | undefined) =>\n c.#isStale(index as Index),\n }\n }\n\n // Protected read-only members\n\n /**\n * {@link LRUCache.OptionsBase.max} (read-only)\n */\n get max(): LRUCache.Count {\n return this.#max\n }\n /**\n * {@link LRUCache.OptionsBase.maxSize} (read-only)\n */\n get maxSize(): LRUCache.Count {\n return this.#maxSize\n }\n /**\n * The total computed size of items in the cache (read-only)\n */\n get calculatedSize(): LRUCache.Size {\n return this.#calculatedSize\n }\n /**\n * The number of items stored in the cache (read-only)\n */\n get size(): LRUCache.Count {\n return this.#size\n }\n /**\n * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n */\n get fetchMethod(): LRUCache.Fetcher<K, V, FC> | undefined {\n return this.#fetchMethod\n }\n get memoMethod(): LRUCache.Memoizer<K, V, FC> | undefined {\n return this.#memoMethod\n }\n /**\n * {@link LRUCache.OptionsBase.dispose} (read-only)\n */\n get dispose() {\n return this.#dispose\n }\n /**\n * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n */\n get disposeAfter() {\n return this.#disposeAfter\n }\n\n constructor(\n options: LRUCache.Options<K, V, FC> | LRUCache<K, V, FC>\n ) {\n const {\n max = 0,\n ttl,\n ttlResolution = 1,\n ttlAutopurge,\n updateAgeOnGet,\n updateAgeOnHas,\n allowStale,\n dispose,\n disposeAfter,\n noDisposeOnSet,\n noUpdateTTL,\n maxSize = 0,\n maxEntrySize = 0,\n sizeCalculation,\n fetchMethod,\n memoMethod,\n noDeleteOnFetchRejection,\n noDeleteOnStaleGet,\n allowStaleOnFetchRejection,\n allowStaleOnFetchAbort,\n ignoreFetchAbort,\n } = options\n\n if (max !== 0 && !isPosInt(max)) {\n throw new TypeError('max option must be a nonnegative integer')\n }\n\n const UintArray = max ? getUintArray(max) : Array\n if (!UintArray) {\n throw new Error('invalid max value: ' + max)\n }\n\n this.#max = max\n this.#maxSize = maxSize\n this.maxEntrySize = maxEntrySize || this.#maxSize\n this.sizeCalculation = sizeCalculation\n if (this.sizeCalculation) {\n if (!this.#maxSize && !this.maxEntrySize) {\n throw new TypeError(\n 'cannot set sizeCalculation without setting maxSize or maxEntrySize'\n )\n }\n if (typeof this.sizeCalculation !== 'function') {\n throw new TypeError('sizeCalculation set to non-function')\n }\n }\n\n if (\n memoMethod !== undefined &&\n typeof memoMethod !== 'function'\n ) {\n throw new TypeError('memoMethod must be a function if defined')\n }\n this.#memoMethod = memoMethod\n\n if (\n fetchMethod !== undefined &&\n typeof fetchMethod !== 'function'\n ) {\n throw new TypeError(\n 'fetchMethod must be a function if specified'\n )\n }\n this.#fetchMethod = fetchMethod\n this.#hasFetchMethod = !!fetchMethod\n\n this.#keyMap = new Map()\n this.#keyList = new Array(max).fill(undefined)\n this.#valList = new Array(max).fill(undefined)\n this.#next = new UintArray(max)\n this.#prev = new UintArray(max)\n this.#head = 0 as Index\n this.#tail = 0 as Index\n this.#free = Stack.create(max)\n this.#size = 0\n this.#calculatedSize = 0\n\n if (typeof dispose === 'function') {\n this.#dispose = dispose\n }\n if (typeof disposeAfter === 'function') {\n this.#disposeAfter = disposeAfter\n this.#disposed = []\n } else {\n this.#disposeAfter = undefined\n this.#disposed = undefined\n }\n this.#hasDispose = !!this.#dispose\n this.#hasDisposeAfter = !!this.#disposeAfter\n\n this.noDisposeOnSet = !!noDisposeOnSet\n this.noUpdateTTL = !!noUpdateTTL\n this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection\n this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection\n this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort\n this.ignoreFetchAbort = !!ignoreFetchAbort\n\n // NB: maxEntrySize is set to maxSize if it's set\n if (this.maxEntrySize !== 0) {\n if (this.#maxSize !== 0) {\n if (!isPosInt(this.#maxSize)) {\n throw new TypeError(\n 'maxSize must be a positive integer if specified'\n )\n }\n }\n if (!isPosInt(this.maxEntrySize)) {\n throw new TypeError(\n 'maxEntrySize must be a positive integer if specified'\n )\n }\n this.#initializeSizeTracking()\n }\n\n this.allowStale = !!allowStale\n this.noDeleteOnStaleGet = !!noDeleteOnStaleGet\n this.updateAgeOnGet = !!updateAgeOnGet\n this.updateAgeOnHas = !!updateAgeOnHas\n this.ttlResolution =\n isPosInt(ttlResolution) || ttlResolution === 0\n ? ttlResolution\n : 1\n this.ttlAutopurge = !!ttlAutopurge\n this.ttl = ttl || 0\n if (this.ttl) {\n if (!isPosInt(this.ttl)) {\n throw new TypeError(\n 'ttl must be a positive integer if specified'\n )\n }\n this.#initializeTTLTracking()\n }\n\n // do not allow completely unbounded caches\n if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {\n throw new TypeError(\n 'At least one of max, maxSize, or ttl is required'\n )\n }\n if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {\n const code = 'LRU_CACHE_UNBOUNDED'\n if (shouldWarn(code)) {\n warned.add(code)\n const msg =\n 'TTL caching without ttlAutopurge, max, or maxSize can ' +\n 'result in unbounded memory consumption.'\n emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache)\n }\n }\n }\n\n /**\n * Return the number of ms left in the item's TTL. If item is not in cache,\n * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\n */\n getRemainingTTL(key: K) {\n return this.#keyMap.has(key) ? Infinity : 0\n }\n\n #initializeTTLTracking() {\n const ttls = new ZeroArray(this.#max)\n const starts = new ZeroArray(this.#max)\n this.#ttls = ttls\n this.#starts = starts\n\n this.#setItemTTL = (index, ttl, start = perf.now()) => {\n starts[index] = ttl !== 0 ? start : 0\n ttls[index] = ttl\n if (ttl !== 0 && this.ttlAutopurge) {\n const t = setTimeout(() => {\n if (this.#isStale(index)) {\n this.#delete(this.#keyList[index] as K, 'expire')\n }\n }, ttl + 1)\n // unref() not supported on all platforms\n /* c8 ignore start */\n if (t.unref) {\n t.unref()\n }\n /* c8 ignore stop */\n }\n }\n\n this.#updateItemAge = index => {\n starts[index] = ttls[index] !== 0 ? perf.now() : 0\n }\n\n this.#statusTTL = (status, index) => {\n if (ttls[index]) {\n const ttl = ttls[index]\n const start = starts[index]\n /* c8 ignore next */\n if (!ttl || !start) return\n status.ttl = ttl\n status.start = start\n status.now = cachedNow || getNow()\n const age = status.now - start\n status.remainingTTL = ttl - age\n }\n }\n\n // debounce calls to perf.now() to 1s so we're not hitting\n // that costly call repeatedly.\n let cachedNow = 0\n const getNow = () => {\n const n = perf.now()\n if (this.ttlResolution > 0) {\n cachedNow = n\n const t = setTimeout(\n () => (cachedNow = 0),\n this.ttlResolution\n )\n // not available on all platforms\n /* c8 ignore start */\n if (t.unref) {\n t.unref()\n }\n /* c8 ignore stop */\n }\n return n\n }\n\n this.getRemainingTTL = key => {\n const index = this.#keyMap.get(key)\n if (index === undefined) {\n return 0\n }\n const ttl = ttls[index]\n const start = starts[index]\n if (!ttl || !start) {\n return Infinity\n }\n const age = (cachedNow || getNow()) - start\n return ttl - age\n }\n\n this.#isStale = index => {\n const s = starts[index]\n const t = ttls[index]\n return !!t && !!s && (cachedNow || getNow()) - s > t\n }\n }\n\n // conditionally set private methods related to TTL\n #updateItemAge: (index: Index) => void = () => {}\n #statusTTL: (status: LRUCache.Status<V>, index: Index) => void =\n () => {}\n #setItemTTL: (\n index: Index,\n ttl: LRUCache.Milliseconds,\n start?: LRUCache.Milliseconds\n // ignore because we never call this if we're not already in TTL mode\n /* c8 ignore start */\n ) => void = () => {}\n /* c8 ignore stop */\n\n #isStale: (index: Index) => boolean = () => false\n\n #initializeSizeTracking() {\n const sizes = new ZeroArray(this.#max)\n this.#calculatedSize = 0\n this.#sizes = sizes\n this.#removeItemSize = index => {\n this.#calculatedSize -= sizes[index] as number\n sizes[index] = 0\n }\n this.#requireSize = (k, v, size, sizeCalculation) => {\n // provisionally accept background fetches.\n // actual value size will be checked when they return.\n if (this.#isBackgroundFetch(v)) {\n return 0\n }\n if (!isPosInt(size)) {\n if (sizeCalculation) {\n if (typeof sizeCalculation !== 'function') {\n throw new TypeError('sizeCalculation must be a function')\n }\n size = sizeCalculation(v, k)\n if (!isPosInt(size)) {\n throw new TypeError(\n 'sizeCalculation return invalid (expect positive integer)'\n )\n }\n } else {\n throw new TypeError(\n 'invalid size value (must be positive integer). ' +\n 'When maxSize or maxEntrySize is used, sizeCalculation ' +\n 'or size must be set.'\n )\n }\n }\n return size\n }\n this.#addItemSize = (\n index: Index,\n size: LRUCache.Size,\n status?: LRUCache.Status<V>\n ) => {\n sizes[index] = size\n if (this.#maxSize) {\n const maxSize = this.#maxSize - (sizes[index] as number)\n while (this.#calculatedSize > maxSize) {\n this.#evict(true)\n }\n }\n this.#calculatedSize += sizes[index] as number\n if (status) {\n status.entrySize = size\n status.totalCalculatedSize = this.#calculatedSize\n }\n }\n }\n\n #removeItemSize: (index: Index) => void = _i => {}\n #addItemSize: (\n index: Index,\n size: LRUCache.Size,\n status?: LRUCache.Status<V>\n ) => void = (_i, _s, _st) => {}\n #requireSize: (\n k: K,\n v: V | BackgroundFetch<V>,\n size?: LRUCache.Size,\n sizeCalculation?: LRUCache.SizeCalculator<K, V>\n ) => LRUCache.Size = (\n _k: K,\n _v: V | BackgroundFetch<V>,\n size?: LRUCache.Size,\n sizeCalculation?: LRUCache.SizeCalculator<K, V>\n ) => {\n if (size || sizeCalculation) {\n throw new TypeError(\n 'cannot set size without setting maxSize or maxEntrySize on cache'\n )\n }\n return 0\n };\n\n *#indexes({ allowStale = this.allowStale } = {}) {\n if (this.#size) {\n for (let i = this.#tail; true; ) {\n if (!this.#isValidIndex(i)) {\n break\n }\n if (allowStale || !this.#isStale(i)) {\n yield i\n }\n if (i === this.#head) {\n break\n } else {\n i = this.#prev[i] as Index\n }\n }\n }\n }\n\n *#rindexes({ allowStale = this.allowStale } = {}) {\n if (this.#size) {\n for (let i = this.#head; true; ) {\n if (!this.#isValidIndex(i)) {\n break\n }\n if (allowStale || !this.#isStale(i)) {\n yield i\n }\n if (i === this.#tail) {\n break\n } else {\n i = this.#next[i] as Index\n }\n }\n }\n }\n\n #isValidIndex(index: Index) {\n return (\n index !== undefined &&\n this.#keyMap.get(this.#keyList[index] as K) === index\n )\n }\n\n /**\n * Return a generator yielding `[key, value]` pairs,\n * in order from most recently used to least recently used.\n */\n *entries() {\n for (const i of this.#indexes()) {\n if (\n this.#valList[i] !== undefined &&\n this.#keyList[i] !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield [this.#keyList[i], this.#valList[i]] as [K, V]\n }\n }\n }\n\n /**\n * Inverse order version of {@link LRUCache.entries}\n *\n * Return a generator yielding `[key, value]` pairs,\n * in order from least recently used to most recently used.\n */\n *rentries() {\n for (const i of this.#rindexes()) {\n if (\n this.#valList[i] !== undefined &&\n this.#keyList[i] !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield [this.#keyList[i], this.#valList[i]]\n }\n }\n }\n\n /**\n * Return a generator yielding the keys in the cache,\n * in order from most recently used to least recently used.\n */\n *keys() {\n for (const i of this.#indexes()) {\n const k = this.#keyList[i]\n if (\n k !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield k\n }\n }\n }\n\n /**\n * Inverse order version of {@link LRUCache.keys}\n *\n * Return a generator yielding the keys in the cache,\n * in order from least recently used to most recently used.\n */\n *rkeys() {\n for (const i of this.#rindexes()) {\n const k = this.#keyList[i]\n if (\n k !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield k\n }\n }\n }\n\n /**\n * Return a generator yielding the values in the cache,\n * in order from most recently used to least recently used.\n */\n *values() {\n for (const i of this.#indexes()) {\n const v = this.#valList[i]\n if (\n v !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield this.#valList[i] as V\n }\n }\n }\n\n /**\n * Inverse order version of {@link LRUCache.values}\n *\n * Return a generator yielding the values in the cache,\n * in order from least recently used to most recently used.\n */\n *rvalues() {\n for (const i of this.#rindexes()) {\n const v = this.#valList[i]\n if (\n v !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield this.#valList[i]\n }\n }\n }\n\n /**\n * Iterating over the cache itself yields the same results as\n * {@link LRUCache.entries}\n */\n [Symbol.iterator]() {\n return this.entries()\n }\n\n /**\n * A String value that is used in the creation of the default string\n * description of an object. Called by the built-in method\n * `Object.prototype.toString`.\n */\n [Symbol.toStringTag] = 'LRUCache'\n\n /**\n * Find a value for which the supplied fn method returns a truthy value,\n * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.\n */\n find(\n fn: (v: V, k: K, self: LRUCache<K, V, FC>) => boolean,\n getOptions: LRUCache.GetOptions<K, V, FC> = {}\n ) {\n for (const i of this.#indexes()) {\n const v = this.#valList[i]\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) continue\n if (fn(value, this.#keyList[i] as K, this)) {\n return this.get(this.#keyList[i] as K, getOptions)\n }\n }\n }\n\n /**\n * Call the supplied function on each item in the cache, in order from most\n * recently used to least recently used.\n *\n * `fn` is called as `fn(value, key, cache)`.\n *\n * If `thisp` is provided, function will be called in the `this`-context of\n * the provided object, or the cache if no `thisp` object is provided.\n *\n * Does not update age or recenty of use, or iterate over stale values.\n */\n forEach(\n fn: (v: V, k: K, self: LRUCache<K, V, FC>) => any,\n thisp: any = this\n ) {\n for (const i of this.#indexes()) {\n const v = this.#valList[i]\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) continue\n fn.call(thisp, value, this.#keyList[i] as K, this)\n }\n }\n\n /**\n * The same as {@link LRUCache.forEach} but items are iterated over in\n * reverse order. (ie, less recently used items are iterated over first.)\n */\n rforEach(\n fn: (v: V, k: K, self: LRUCache<K, V, FC>) => any,\n thisp: any = this\n ) {\n for (const i of this.#rindexes()) {\n const v = this.#valList[i]\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) continue\n fn.call(thisp, value, this.#keyList[i] as K, this)\n }\n }\n\n /**\n * Delete any stale entries. Returns true if anything was removed,\n * false otherwise.\n */\n purgeStale() {\n let deleted = false\n for (const i of this.#rindexes({ allowStale: true })) {\n if (this.#isStale(i)) {\n this.#delete(this.#keyList[i] as K, 'expire')\n deleted = true\n }\n }\n return deleted\n }\n\n /**\n * Get the extended info about a given entry, to get its value, size, and\n * TTL info simultaneously. Returns `undefined` if the key is not present.\n *\n * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n * serialization, the `start` value is always the current timestamp, and the\n * `ttl` is a calculated remaining time to live (negative if expired).\n *\n * Always returns stale values, if their info is found in the cache, so be\n * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n * if relevant.\n */\n info(key: K): LRUCache.Entry<V> | undefined {\n const i = this.#keyMap.get(key)\n if (i === undefined) return undefined\n const v = this.#valList[i]\n const value: V | undefined = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) return undefined\n const entry: LRUCache.Entry<V> = { value }\n if (this.#ttls && this.#starts) {\n const ttl = this.#ttls[i]\n const start = this.#starts[i]\n if (ttl && start) {\n const remain = ttl - (perf.now() - start)\n entry.ttl = remain\n entry.start = Date.now()\n }\n }\n if (this.#sizes) {\n entry.size = this.#sizes[i]\n }\n return entry\n }\n\n /**\n * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n * passed to {@link LRLUCache#load}.\n *\n * The `start` fields are calculated relative to a portable `Date.now()`\n * timestamp, even if `performance.now()` is available.\n *\n * Stale entries are always included in the `dump`, even if\n * {@link LRUCache.OptionsBase.allowStale} is false.\n *\n * Note: this returns an actual array, not a generator, so it can be more\n * easily passed around.\n */\n dump() {\n const arr: [K, LRUCache.Entry<V>][] = []\n for (const i of this.#indexes({ allowStale: true })) {\n const key = this.#keyList[i]\n const v = this.#valList[i]\n const value: V | undefined = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined || key === undefined) continue\n const entry: LRUCache.Entry<V> = { value }\n if (this.#ttls && this.#starts) {\n entry.ttl = this.#ttls[i]\n // always dump the start relative to a portable timestamp\n // it's ok for this to be a bit slow, it's a rare operation.\n const age = perf.now() - (this.#starts[i] as number)\n entry.start = Math.floor(Date.now() - age)\n }\n if (this.#sizes) {\n entry.size = this.#sizes[i]\n }\n arr.unshift([key, entry])\n }\n return arr\n }\n\n /**\n * Reset the cache and load in the items in entries in the order listed.\n *\n * The shape of the resulting cache may be different if the same options are\n * not used in both caches.\n *\n * The `start` fields are assumed to be calculated relative to a portable\n * `Date.now()` timestamp, even if `performance.now()` is available.\n */\n load(arr: [K, LRUCache.Entry<V>][]) {\n this.clear()\n for (const [key, entry] of arr) {\n if (entry.start) {\n // entry.start is a portable timestamp, but we may be using\n // node's performance.now(), so calculate the offset, so that\n // we get the intended remaining TTL, no matter how long it's\n // been on ice.\n //\n // it's ok for this to be a bit slow, it's a rare operation.\n const age = Date.now() - entry.start\n entry.start = perf.now() - age\n }\n this.set(key, entry.value, entry)\n }\n }\n\n /**\n * Add a value to the cache.\n *\n * Note: if `undefined` is specified as a value, this is an alias for\n * {@link LRUCache#delete}\n *\n * Fields on the {@link LRUCache.SetOptions} options param will override\n * their corresponding values in the constructor options for the scope\n * of this single `set()` operation.\n *\n * If `start` is provided, then that will set the effective start\n * time for the TTL calculation. Note that this must be a previous\n * value of `performance.now()` if supported, or a previous value of\n * `Date.now()` if not.\n *\n * Options object may also include `size`, which will prevent\n * calling the `sizeCalculation` function and just use the specified\n * number if it is a positive integer, and `noDisposeOnSet` which\n * will prevent calling a `dispose` function in the case of\n * overwrites.\n *\n * If the `size` (or return value of `sizeCalculation`) for a given\n * entry is greater than `maxEntrySize`, then the item will not be\n * added to the cache.\n *\n * Will update the recency of the entry.\n *\n * If the value is `undefined`, then this is an alias for\n * `cache.delete(key)`. `undefined` is never stored in the cache.\n */\n set(\n k: K,\n v: V | BackgroundFetch<V> | undefined,\n setOptions: LRUCache.SetOptions<K, V, FC> = {}\n ) {\n if (v === undefined) {\n this.delete(k)\n return this\n }\n const {\n ttl = this.ttl,\n start,\n noDisposeOnSet = this.noDisposeOnSet,\n sizeCalculation = this.sizeCalculation,\n status,\n } = setOptions\n let { noUpdateTTL = this.noUpdateTTL } = setOptions\n\n const size = this.#requireSize(\n k,\n v,\n setOptions.size || 0,\n sizeCalculation\n )\n // if the item doesn't fit, don't do anything\n // NB: maxEntrySize set to maxSize by default\n if (this.maxEntrySize && size > this.maxEntrySize) {\n if (status) {\n status.set = 'miss'\n status.maxEntrySizeExceeded = true\n }\n // have to delete, in case something is there already.\n this.#delete(k, 'set')\n return this\n }\n let index = this.#size === 0 ? undefined : this.#keyMap.get(k)\n if (index === undefined) {\n // addition\n index = (\n this.#size === 0\n ? this.#tail\n : this.#free.length !== 0\n ? this.#free.pop()\n : this.#size === this.#max\n ? this.#evict(false)\n : this.#size\n ) as Index\n this.#keyList[index] = k\n this.#valList[index] = v\n this.#keyMap.set(k, index)\n this.#next[this.#tail] = index\n this.#prev[index] = this.#tail\n this.#tail = index\n this.#size++\n this.#addItemSize(index, size, status)\n if (status) status.set = 'add'\n noUpdateTTL = false\n } else {\n // update\n this.#moveToTail(index)\n const oldVal = this.#valList[index] as V | BackgroundFetch<V>\n if (v !== oldVal) {\n if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {\n oldVal.__abortController.abort(new Error('replaced'))\n const { __staleWhileFetching: s } = oldVal\n if (s !== undefined && !noDisposeOnSet) {\n if (this.#hasDispose) {\n this.#dispose?.(s as V, k, 'set')\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([s as V, k, 'set'])\n }\n }\n } else if (!noDisposeOnSet) {\n if (this.#hasDispose) {\n this.#dispose?.(oldVal as V, k, 'set')\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([oldVal as V, k, 'set'])\n }\n }\n this.#removeItemSize(index)\n this.#addItemSize(index, size, status)\n this.#valList[index] = v\n if (status) {\n status.set = 'replace'\n const oldValue =\n oldVal && this.#isBackgroundFetch(oldVal)\n ? oldVal.__staleWhileFetching\n : oldVal\n if (oldValue !== undefined) status.oldValue = oldValue\n }\n } else if (status) {\n status.set = 'update'\n }\n }\n if (ttl !== 0 && !this.#ttls) {\n this.#initializeTTLTracking()\n }\n if (this.#ttls) {\n if (!noUpdateTTL) {\n this.#setItemTTL(index, ttl, start)\n }\n if (status) this.#statusTTL(status, index)\n }\n if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n return this\n }\n\n /**\n * Evict the least recently used item, returning its value or\n * `undefined` if cache is empty.\n */\n pop(): V | undefined {\n try {\n while (this.#size) {\n const val = this.#valList[this.#head]\n this.#evict(true)\n if (this.#isBackgroundFetch(val)) {\n if (val.__staleWhileFetching) {\n return val.__staleWhileFetching\n }\n } else if (val !== undefined) {\n return val\n }\n }\n } finally {\n if (this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n }\n }\n\n #evict(free: boolean) {\n const head = this.#head\n const k = this.#keyList[head] as K\n const v = this.#valList[head] as V\n if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('evicted'))\n } else if (this.#hasDispose || this.#hasDisposeAfter) {\n if (this.#hasDispose) {\n this.#dispose?.(v, k, 'evict')\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v, k, 'evict'])\n }\n }\n this.#removeItemSize(head)\n // if we aren't about to use the index, then null these out\n if (free) {\n this.#keyList[head] = undefined\n this.#valList[head] = undefined\n this.#free.push(head)\n }\n if (this.#size === 1) {\n this.#head = this.#tail = 0 as Index\n this.#free.length = 0\n } else {\n this.#head = this.#next[head] as Index\n }\n this.#keyMap.delete(k)\n this.#size--\n return head\n }\n\n /**\n * Check if a key is in the cache, without updating the recency of use.\n * Will return false if the item is stale, even though it is technically\n * in the cache.\n *\n * Check if a key is in the cache, without updating the recency of\n * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n * to `true` in either the options or the constructor.\n *\n * Will return `false` if the item is stale, even though it is technically in\n * the cache. The difference can be determined (if it matters) by using a\n * `status` argument, and inspecting the `has` field.\n *\n * Will not update item age unless\n * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n */\n has(k: K, hasOptions: LRUCache.HasOptions<K, V, FC> = {}) {\n const { updateAgeOnHas = this.updateAgeOnHas, status } =\n hasOptions\n const index = this.#keyMap.get(k)\n if (index !== undefined) {\n const v = this.#valList[index]\n if (\n this.#isBackgroundFetch(v) &&\n v.__staleWhileFetching === undefined\n ) {\n return false\n }\n if (!this.#isStale(index)) {\n if (updateAgeOnHas) {\n this.#updateItemAge(index)\n }\n if (status) {\n status.has = 'hit'\n this.#statusTTL(status, index)\n }\n return true\n } else if (status) {\n status.has = 'stale'\n this.#statusTTL(status, index)\n }\n } else if (status) {\n status.has = 'miss'\n }\n return false\n }\n\n /**\n * Like {@link LRUCache#get} but doesn't update recency or delete stale\n * items.\n *\n * Returns `undefined` if the item is stale, unless\n * {@link LRUCache.OptionsBase.allowStale} is set.\n */\n peek(k: K, peekOptions: LRUCache.PeekOptions<K, V, FC> = {}) {\n const { allowStale = this.allowStale } = peekOptions\n const index = this.#keyMap.get(k)\n if (\n index === undefined ||\n (!allowStale && this.#isStale(index))\n ) {\n return\n }\n const v = this.#valList[index]\n // either stale and allowed, or forcing a refresh of non-stale value\n return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n }\n\n #backgroundFetch(\n k: K,\n index: Index | undefined,\n options: LRUCache.FetchOptions<K, V, FC>,\n context: any\n ): BackgroundFetch<V> {\n const v = index === undefined ? undefined : this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n return v\n }\n\n const ac = new AC()\n const { signal } = options\n // when/if our AC signals, then stop listening to theirs.\n signal?.addEventListener('abort', () => ac.abort(signal.reason), {\n signal: ac.signal,\n })\n\n const fetchOpts = {\n signal: ac.signal,\n options,\n context,\n }\n\n const cb = (\n v: V | undefined,\n updateCache = false\n ): V | undefined => {\n const { aborted } = ac.signal\n const ignoreAbort = options.ignoreFetchAbort && v !== undefined\n if (options.status) {\n if (aborted && !updateCache) {\n options.status.fetchAborted = true\n options.status.fetchError = ac.signal.reason\n if (ignoreAbort) options.status.fetchAbortIgnored = true\n } else {\n options.status.fetchResolved = true\n }\n }\n if (aborted && !ignoreAbort && !updateCache) {\n return fetchFail(ac.signal.reason)\n }\n // either we didn't abort, and are still here, or we did, and ignored\n const bf = p as BackgroundFetch<V>\n if (this.#valList[index as Index] === p) {\n if (v === undefined) {\n if (bf.__staleWhileFetching) {\n this.#valList[index as Index] = bf.__staleWhileFetching\n } else {\n this.#delete(k, 'fetch')\n }\n } else {\n if (options.status) options.status.fetchUpdated = true\n this.set(k, v, fetchOpts.options)\n }\n }\n return v\n }\n\n const eb = (er: any) => {\n if (options.status) {\n options.status.fetchRejected = true\n options.status.fetchError = er\n }\n return fetchFail(er)\n }\n\n const fetchFail = (er: any): V | undefined => {\n const { aborted } = ac.signal\n const allowStaleAborted =\n aborted && options.allowStaleOnFetchAbort\n const allowStale =\n allowStaleAborted || options.allowStaleOnFetchRejection\n const noDelete = allowStale || options.noDeleteOnFetchRejection\n const bf = p as BackgroundFetch<V>\n if (this.#valList[index as Index] === p) {\n // if we allow stale on fetch rejections, then we need to ensure that\n // the stale value is not removed from the cache when the fetch fails.\n const del = !noDelete || bf.__staleWhileFetching === undefined\n if (del) {\n this.#delete(k, 'fetch')\n } else if (!allowStaleAborted) {\n // still replace the *promise* with the stale value,\n // since we are done with the promise at this point.\n // leave it untouched if we're still waiting for an\n // aborted background fetch that hasn't yet returned.\n this.#valList[index as Index] = bf.__staleWhileFetching\n }\n }\n if (allowStale) {\n if (options.status && bf.__staleWhileFetching !== undefined) {\n options.status.returnedStale = true\n }\n return bf.__staleWhileFetching\n } else if (bf.__returned === bf) {\n throw er\n }\n }\n\n const pcall = (\n res: (v: V | undefined) => void,\n rej: (e: any) => void\n ) => {\n const fmp = this.#fetchMethod?.(k, v, fetchOpts)\n if (fmp && fmp instanceof Promise) {\n fmp.then(v => res(v === undefined ? undefined : v), rej)\n }\n // ignored, we go until we finish, regardless.\n // defer check until we are actually aborting,\n // so fetchMethod can override.\n ac.signal.addEventListener('abort', () => {\n if (\n !options.ignoreFetchAbort ||\n options.allowStaleOnFetchAbort\n ) {\n res(undefined)\n // when it eventually resolves, update the cache.\n if (options.allowStaleOnFetchAbort) {\n res = v => cb(v, true)\n }\n }\n })\n }\n\n if (options.status) options.status.fetchDispatched = true\n const p = new Promise(pcall).then(cb, eb)\n const bf: BackgroundFetch<V> = Object.assign(p, {\n __abortController: ac,\n __staleWhileFetching: v,\n __returned: undefined,\n })\n\n if (index === undefined) {\n // internal, don't expose status.\n this.set(k, bf, { ...fetchOpts.options, status: undefined })\n index = this.#keyMap.get(k)\n } else {\n this.#valList[index] = bf\n }\n return bf\n }\n\n #isBackgroundFetch(p: any): p is BackgroundFetch<V> {\n if (!this.#hasFetchMethod) return false\n const b = p as BackgroundFetch<V>\n return (\n !!b &&\n b instanceof Promise &&\n b.hasOwnProperty('__staleWhileFetching') &&\n b.__abortController instanceof AC\n )\n }\n\n /**\n * Make an asynchronous cached fetch using the\n * {@link LRUCache.OptionsBase.fetchMethod} function.\n *\n * If the value is in the cache and not stale, then the returned\n * Promise resolves to the value.\n *\n * If not in the cache, or beyond its TTL staleness, then\n * `fetchMethod(key, staleValue, { options, signal, context })` is\n * called, and the value returned will be added to the cache once\n * resolved.\n *\n * If called with `allowStale`, and an asynchronous fetch is\n * currently in progress to reload a stale value, then the former\n * stale value will be returned.\n *\n * If called with `forceRefresh`, then the cached item will be\n * re-fetched, even if it is not stale. However, if `allowStale` is also\n * set, then the old value will still be returned. This is useful\n * in cases where you want to force a reload of a cached value. If\n * a background fetch is already in progress, then `forceRefresh`\n * has no effect.\n *\n * If multiple fetches for the same key are issued, then they will all be\n * coalesced into a single call to fetchMethod.\n *\n * Note that this means that handling options such as\n * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},\n * {@link LRUCache.FetchOptions.signal},\n * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be\n * determined by the FIRST fetch() call for a given key.\n *\n * This is a known (fixable) shortcoming which will be addresed on when\n * someone complains about it, as the fix would involve added complexity and\n * may not be worth the costs for this edge case.\n *\n * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n * effectively an alias for `Promise.resolve(cache.get(key))`.\n *\n * When the fetch method resolves to a value, if the fetch has not\n * been aborted due to deletion, eviction, or being overwritten,\n * then it is added to the cache using the options provided.\n *\n * If the key is evicted or deleted before the `fetchMethod`\n * resolves, then the AbortSignal passed to the `fetchMethod` will\n * receive an `abort` event, and the promise returned by `fetch()`\n * will reject with the reason for the abort.\n *\n * If a `signal` is passed to the `fetch()` call, then aborting the\n * signal will abort the fetch and cause the `fetch()` promise to\n * reject with the reason provided.\n *\n * **Setting `context`**\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the {@link LRUCache} constructor, then all\n * calls to `cache.fetch()` _must_ provide a `context` option. If\n * set to `undefined` or `void`, then calls to fetch _must not_\n * provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that\n * might be relevant in the course of fetching the data. It is only\n * relevant for the course of a single `fetch()` operation, and\n * discarded afterwards.\n *\n * **Note: `fetch()` calls are inflight-unique**\n *\n * If you call `fetch()` multiple times with the same key value,\n * then every call after the first will resolve on the same\n * promise<sup>1</sup>,\n * _even if they have different settings that would otherwise change\n * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n * or `ignoreFetchAbort`.\n *\n * In most cases, this is not a problem (in fact, only fetching\n * something once is what you probably want, if you're caching in\n * the first place). If you are changing the fetch() options\n * dramatically between runs, there's a good chance that you might\n * be trying to fit divergent semantics into a single object, and\n * would be better off with multiple cache instances.\n *\n * **1**: Ie, they're not the \"same Promise\", but they resolve at\n * the same time, because they're both waiting on the same\n * underlying fetchMethod response.\n */\n\n fetch(\n k: K,\n fetchOptions: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : LRUCache.FetchOptionsWithContext<K, V, FC>\n ): Promise<undefined | V>\n\n // this overload not allowed if context is required\n fetch(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n fetchOptions?: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : never\n ): Promise<undefined | V>\n\n async fetch(\n k: K,\n fetchOptions: LRUCache.FetchOptions<K, V, FC> = {}\n ): Promise<undefined | V> {\n const {\n // get options\n allowStale = this.allowStale,\n updateAgeOnGet = this.updateAgeOnGet,\n noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n // set options\n ttl = this.ttl,\n noDisposeOnSet = this.noDisposeOnSet,\n size = 0,\n sizeCalculation = this.sizeCalculation,\n noUpdateTTL = this.noUpdateTTL,\n // fetch exclusive options\n noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,\n allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,\n ignoreFetchAbort = this.ignoreFetchAbort,\n allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,\n context,\n forceRefresh = false,\n status,\n signal,\n } = fetchOptions\n\n if (!this.#hasFetchMethod) {\n if (status) status.fetch = 'get'\n return this.get(k, {\n allowStale,\n updateAgeOnGet,\n noDeleteOnStaleGet,\n status,\n })\n }\n\n const options = {\n allowStale,\n updateAgeOnGet,\n noDeleteOnStaleGet,\n ttl,\n noDisposeOnSet,\n size,\n sizeCalculation,\n noUpdateTTL,\n noDeleteOnFetchRejection,\n allowStaleOnFetchRejection,\n allowStaleOnFetchAbort,\n ignoreFetchAbort,\n status,\n signal,\n }\n\n let index = this.#keyMap.get(k)\n if (index === undefined) {\n if (status) status.fetch = 'miss'\n const p = this.#backgroundFetch(k, index, options, context)\n return (p.__returned = p)\n } else {\n // in cache, maybe already fetching\n const v = this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n const stale =\n allowStale && v.__staleWhileFetching !== undefined\n if (status) {\n status.fetch = 'inflight'\n if (stale) status.returnedStale = true\n }\n return stale ? v.__staleWhileFetching : (v.__returned = v)\n }\n\n // if we force a refresh, that means do NOT serve the cached value,\n // unless we are already in the process of refreshing the cache.\n const isStale = this.#isStale(index)\n if (!forceRefresh && !isStale) {\n if (status) status.fetch = 'hit'\n this.#moveToTail(index)\n if (updateAgeOnGet) {\n this.#updateItemAge(index)\n }\n if (status) this.#statusTTL(status, index)\n return v\n }\n\n // ok, it is stale or a forced refresh, and not already fetching.\n // refresh the cache.\n const p = this.#backgroundFetch(k, index, options, context)\n const hasStale = p.__staleWhileFetching !== undefined\n const staleVal = hasStale && allowStale\n if (status) {\n status.fetch = isStale ? 'stale' : 'refresh'\n if (staleVal && isStale) status.returnedStale = true\n }\n return staleVal ? p.__staleWhileFetching : (p.__returned = p)\n }\n }\n\n /**\n * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n * because `ignoreFetchAbort` was specified (either to the constructor or\n * in the {@link LRUCache.FetchOptions}). Also, the\n * {@link OptionsBase.fetchMethod} may return `undefined` or `void`, making\n * the test even more complicated.\n *\n * Because inferring the cases where `undefined` might be returned are so\n * cumbersome, but testing for `undefined` can also be annoying, this method\n * can be used, which will reject if `this.fetch()` resolves to undefined.\n */\n forceFetch(\n k: K,\n fetchOptions: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : LRUCache.FetchOptionsWithContext<K, V, FC>\n ): Promise<V>\n // this overload not allowed if context is required\n forceFetch(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n fetchOptions?: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : never\n ): Promise<V>\n async forceFetch(\n k: K,\n fetchOptions: LRUCache.FetchOptions<K, V, FC> = {}\n ): Promise<V> {\n const v = await this.fetch(\n k,\n fetchOptions as unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : LRUCache.FetchOptionsWithContext<K, V, FC>\n )\n if (v === undefined) throw new Error('fetch() returned undefined')\n return v\n }\n\n /**\n * If the key is found in the cache, then this is equivalent to\n * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n * _must_ provide a `context` option. If set to `undefined` or `void`, then\n * calls to memo _must not_ provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that might be\n * relevant in the course of fetching the data. It is only relevant for the\n * course of a single `memo()` operation, and discarded afterwards.\n */\n memo(\n k: K,\n memoOptions: unknown extends FC\n ? LRUCache.MemoOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext<K, V>\n : LRUCache.MemoOptionsWithContext<K, V, FC>\n ): V\n // this overload not allowed if context is required\n memo(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n memoOptions?: unknown extends FC\n ? LRUCache.MemoOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext<K, V>\n : never\n ): V\n memo(k: K, memoOptions: LRUCache.MemoOptions<K, V, FC> = {}) {\n const memoMethod = this.#memoMethod\n if (!memoMethod) {\n throw new Error('no memoMethod provided to constructor')\n }\n const { context, forceRefresh, ...options } = memoOptions\n const v = this.get(k, options)\n if (!forceRefresh && v !== undefined) return v\n const vv = memoMethod(k, v, {\n options,\n context,\n } as LRUCache.MemoizerOptions<K, V, FC>)\n this.set(k, vv, options)\n return vv\n }\n\n /**\n * Return a value from the cache. Will update the recency of the cache\n * entry found.\n *\n * If the key is not found, get() will return `undefined`.\n */\n get(k: K, getOptions: LRUCache.GetOptions<K, V, FC> = {}) {\n const {\n allowStale = this.allowStale,\n updateAgeOnGet = this.updateAgeOnGet,\n noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n status,\n } = getOptions\n const index = this.#keyMap.get(k)\n if (index !== undefined) {\n const value = this.#valList[index]\n const fetching = this.#isBackgroundFetch(value)\n if (status) this.#statusTTL(status, index)\n if (this.#isStale(index)) {\n if (status) status.get = 'stale'\n // delete only if not an in-flight background fetch\n if (!fetching) {\n if (!noDeleteOnStaleGet) {\n this.#delete(k, 'expire')\n }\n if (status && allowStale) status.returnedStale = true\n return allowStale ? value : undefined\n } else {\n if (\n status &&\n allowStale &&\n value.__staleWhileFetching !== undefined\n ) {\n status.returnedStale = true\n }\n return allowStale ? value.__staleWhileFetching : undefined\n }\n } else {\n if (status) status.get = 'hit'\n // if we're currently fetching it, we don't actually have it yet\n // it's not stale, which means this isn't a staleWhileRefetching.\n // If it's not stale, and fetching, AND has a __staleWhileFetching\n // value, then that means the user fetched with {forceRefresh:true},\n // so it's safe to return that value.\n if (fetching) {\n return value.__staleWhileFetching\n }\n this.#moveToTail(index)\n if (updateAgeOnGet) {\n this.#updateItemAge(index)\n }\n return value\n }\n } else if (status) {\n status.get = 'miss'\n }\n }\n\n #connect(p: Index, n: Index) {\n this.#prev[n] = p\n this.#next[p] = n\n }\n\n #moveToTail(index: Index): void {\n // if tail already, nothing to do\n // if head, move head to next[index]\n // else\n // move next[prev[index]] to next[index] (head has no prev)\n // move prev[next[index]] to prev[index]\n // prev[index] = tail\n // next[tail] = index\n // tail = index\n if (index !== this.#tail) {\n if (index === this.#head) {\n this.#head = this.#next[index] as Index\n } else {\n this.#connect(\n this.#prev[index] as Index,\n this.#next[index] as Index\n )\n }\n this.#connect(this.#tail, index)\n this.#tail = index\n }\n }\n\n /**\n * Deletes a key out of the cache.\n *\n * Returns true if the key was deleted, false otherwise.\n */\n delete(k: K) {\n return this.#delete(k, 'delete')\n }\n\n #delete(k: K, reason: LRUCache.DisposeReason) {\n let deleted = false\n if (this.#size !== 0) {\n const index = this.#keyMap.get(k)\n if (index !== undefined) {\n deleted = true\n if (this.#size === 1) {\n this.#clear(reason)\n } else {\n this.#removeItemSize(index)\n const v = this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('deleted'))\n } else if (this.#hasDispose || this.#hasDisposeAfter) {\n if (this.#hasDispose) {\n this.#dispose?.(v as V, k, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k, reason])\n }\n }\n this.#keyMap.delete(k)\n this.#keyList[index] = undefined\n this.#valList[index] = undefined\n if (index === this.#tail) {\n this.#tail = this.#prev[index] as Index\n } else if (index === this.#head) {\n this.#head = this.#next[index] as Index\n } else {\n const pi = this.#prev[index] as number\n this.#next[pi] = this.#next[index] as number\n const ni = this.#next[index] as number\n this.#prev[ni] = this.#prev[index] as number\n }\n this.#size--\n this.#free.push(index)\n }\n }\n }\n if (this.#hasDisposeAfter && this.#disposed?.length) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n return deleted\n }\n\n /**\n * Clear the cache entirely, throwing away all values.\n */\n clear() {\n return this.#clear('delete')\n }\n #clear(reason: LRUCache.DisposeReason) {\n for (const index of this.#rindexes({ allowStale: true })) {\n const v = this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('deleted'))\n } else {\n const k = this.#keyList[index]\n if (this.#hasDispose) {\n this.#dispose?.(v as V, k as K, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k as K, reason])\n }\n }\n }\n\n this.#keyMap.clear()\n this.#valList.fill(undefined)\n this.#keyList.fill(undefined)\n if (this.#ttls && this.#starts) {\n this.#ttls.fill(0)\n this.#starts.fill(0)\n }\n if (this.#sizes) {\n this.#sizes.fill(0)\n }\n this.#head = 0 as Index\n this.#tail = 0 as Index\n this.#free.length = 0\n this.#calculatedSize = 0\n this.#size = 0\n if (this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n }\n}\n", "import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n lstatSync,\n readdir as readdirCB,\n readdirSync,\n readlinkSync,\n realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods. Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n * readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n * - lstat\n * - readdir (Dirent variant only)\n * - readlink\n * - realpath\n */\nexport interface FSOption {\n lstatSync?: (path: string) => Stats\n readdir?: (\n path: string,\n options: { withFileTypes: true },\n cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n ) => void\n readdirSync?: (\n path: string,\n options: { withFileTypes: true },\n ) => Dirent[]\n readlinkSync?: (path: string) => string\n realpathSync?: (path: string) => string\n promises?: {\n lstat?: (path: string) => Promise<Stats>\n readdir?: (\n path: string,\n options: { withFileTypes: true },\n ) => Promise<Dirent[]>\n readlink?: (path: string) => Promise<string>\n realpath?: (path: string) => Promise<string>\n [k: string]: any\n }\n [k: string]: any\n}\n\ninterface FSValue {\n lstatSync: (path: string) => Stats\n readdir: (\n path: string,\n options: { withFileTypes: true },\n cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n ) => void\n readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n readlinkSync: (path: string) => string\n realpathSync: (path: string) => string\n promises: {\n lstat: (path: string) => Promise<Stats>\n readdir: (\n path: string,\n options: { withFileTypes: true },\n ) => Promise<Dirent[]>\n readlink: (path: string) => Promise<string>\n realpath: (path: string) => Promise<string>\n [k: string]: any\n }\n [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n lstatSync,\n readdir: readdirCB,\n readdirSync,\n readlinkSync,\n realpathSync,\n promises: {\n lstat,\n readdir,\n readlink,\n realpath,\n },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n defaultFS\n : {\n ...defaultFS,\n ...fsOption,\n promises: {\n ...defaultFS.promises,\n ...(fsOption.promises || {}),\n },\n }\n\n// turn something like //?/c:/ into c:\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncToDrive = (rootPath: string): string =>\n rootPath.replace(/\\//g, '\\\\').replace(uncDriveRegexp, '$1\\\\')\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n | 'Unknown'\n | 'FIFO'\n | 'CharacterDevice'\n | 'Directory'\n | 'BlockDevice'\n | 'File'\n | 'SymbolicLink'\n | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n s.isFile() ? IFREG\n : s.isDirectory() ? IFDIR\n : s.isSymbolicLink() ? IFLNK\n : s.isCharacterDevice() ? IFCHR\n : s.isBlockDevice() ? IFBLK\n : s.isSocket() ? IFSOCK\n : s.isFIFO() ? IFIFO\n : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new Map<string, string>()\nconst normalize = (s: string) => {\n const c = normalizeCache.get(s)\n if (c) return c\n const n = s.normalize('NFKD')\n normalizeCache.set(s, n)\n return n\n}\n\nconst normalizeNocaseCache = new Map<string, string>()\nconst normalizeNocase = (s: string) => {\n const c = normalizeNocaseCache.get(s)\n if (c) return c\n const n = normalize(s.toLowerCase())\n normalizeNocaseCache.set(s, n)\n return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n fullpath?: string\n relative?: string\n relativePosix?: string\n parent?: PathBase\n /**\n * See {@link FSOption}\n */\n fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache<string, string> {\n constructor() {\n super({ max: 256 })\n }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent. At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache. This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache<PathBase, Children> {\n constructor(maxSize: number = 16 * 1024) {\n super({\n maxSize,\n // parent + children\n sizeCalculation: a => a.length + 1,\n })\n }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n /**\n * the basename of this path\n *\n * **Important**: *always* test the path name against any test string\n * usingthe {@link isNamed} method, and not by directly comparing this\n * string. Otherwise, unicode path strings that the system sees as identical\n * will not be properly treated as the same path, leading to incorrect\n * behavior and possible security issues.\n */\n name: string\n /**\n * the Path entry corresponding to the path root.\n *\n * @internal\n */\n root: PathBase\n /**\n * All roots found within the current PathScurry family\n *\n * @internal\n */\n roots: { [k: string]: PathBase }\n /**\n * a reference to the parent path, or undefined in the case of root entries\n *\n * @internal\n */\n parent?: PathBase\n /**\n * boolean indicating whether paths are compared case-insensitively\n * @internal\n */\n nocase: boolean\n\n /**\n * boolean indicating that this path is the current working directory\n * of the PathScurry collection that contains it.\n */\n isCWD: boolean = false\n\n /**\n * the string or regexp used to split paths. On posix, it is `'/'`, and on\n * windows it is a RegExp matching either `'/'` or `'\\\\'`\n */\n abstract splitSep: string | RegExp\n /**\n * The path separator string to use when joining paths\n */\n abstract sep: string\n\n // potential default fs override\n #fs: FSValue\n\n // Stats fields\n #dev?: number\n get dev() {\n return this.#dev\n }\n #mode?: number\n get mode() {\n return this.#mode\n }\n #nlink?: number\n get nlink() {\n return this.#nlink\n }\n #uid?: number\n get uid() {\n return this.#uid\n }\n #gid?: number\n get gid() {\n return this.#gid\n }\n #rdev?: number\n get rdev() {\n return this.#rdev\n }\n #blksize?: number\n get blksize() {\n return this.#blksize\n }\n #ino?: number\n get ino() {\n return this.#ino\n }\n #size?: number\n get size() {\n return this.#size\n }\n #blocks?: number\n get blocks() {\n return this.#blocks\n }\n #atimeMs?: number\n get atimeMs() {\n return this.#atimeMs\n }\n #mtimeMs?: number\n get mtimeMs() {\n return this.#mtimeMs\n }\n #ctimeMs?: number\n get ctimeMs() {\n return this.#ctimeMs\n }\n #birthtimeMs?: number\n get birthtimeMs() {\n return this.#birthtimeMs\n }\n #atime?: Date\n get atime() {\n return this.#atime\n }\n #mtime?: Date\n get mtime() {\n return this.#mtime\n }\n #ctime?: Date\n get ctime() {\n return this.#ctime\n }\n #birthtime?: Date\n get birthtime() {\n return this.#birthtime\n }\n\n #matchName: string\n #depth?: number\n #fullpath?: string\n #fullpathPosix?: string\n #relative?: string\n #relativePosix?: string\n #type: number\n #children: ChildrenCache\n #linkTarget?: PathBase\n #realpath?: PathBase\n\n /**\n * This property is for compatibility with the Dirent class as of\n * Node v20, where Dirent['parentPath'] refers to the path of the\n * directory that was passed to readdir. For root entries, it's the path\n * to the entry itself.\n */\n get parentPath(): string {\n return (this.parent || this).fullpath()\n }\n\n /**\n * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n * this property refers to the *parent* path, not the path object itself.\n *\n * @deprecated\n */\n get path(): string {\n return this.parentPath\n }\n\n /**\n * Do not create new Path objects directly. They should always be accessed\n * via the PathScurry class or other methods on the Path class.\n *\n * @internal\n */\n constructor(\n name: string,\n type: number = UNKNOWN,\n root: PathBase | undefined,\n roots: { [k: string]: PathBase },\n nocase: boolean,\n children: ChildrenCache,\n opts: PathOpts,\n ) {\n this.name = name\n this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n this.#type = type & TYPEMASK\n this.nocase = nocase\n this.roots = roots\n this.root = root || this\n this.#children = children\n this.#fullpath = opts.fullpath\n this.#relative = opts.relative\n this.#relativePosix = opts.relativePosix\n this.parent = opts.parent\n if (this.parent) {\n this.#fs = this.parent.#fs\n } else {\n this.#fs = fsFromOption(opts.fs)\n }\n }\n\n /**\n * Returns the depth of the Path object from its root.\n *\n * For example, a path at `/foo/bar` would have a depth of 2.\n */\n depth(): number {\n if (this.#depth !== undefined) return this.#depth\n if (!this.parent) return (this.#depth = 0)\n return (this.#depth = this.parent.depth() + 1)\n }\n\n /**\n * @internal\n */\n abstract getRootString(path: string): string\n /**\n * @internal\n */\n abstract getRoot(rootPath: string): PathBase\n /**\n * @internal\n */\n abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n /**\n * @internal\n */\n childrenCache() {\n return this.#children\n }\n\n /**\n * Get the Path object referenced by the string path, resolved from this Path\n */\n resolve(path?: string): PathBase {\n if (!path) {\n return this\n }\n const rootPath = this.getRootString(path)\n const dir = path.substring(rootPath.length)\n const dirParts = dir.split(this.splitSep)\n const result: PathBase =\n rootPath ?\n this.getRoot(rootPath).#resolveParts(dirParts)\n : this.#resolveParts(dirParts)\n return result\n }\n\n #resolveParts(dirParts: string[]) {\n let p: PathBase = this\n for (const part of dirParts) {\n p = p.child(part)\n }\n return p\n }\n\n /**\n * Returns the cached children Path objects, if still available. If they\n * have fallen out of the cache, then returns an empty array, and resets the\n * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n * lookup.\n *\n * @internal\n */\n children(): Children {\n const cached = this.#children.get(this)\n if (cached) {\n return cached\n }\n const children: Children = Object.assign([], { provisional: 0 })\n this.#children.set(this, children)\n this.#type &= ~READDIR_CALLED\n return children\n }\n\n /**\n * Resolves a path portion and returns or creates the child Path.\n *\n * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n * `'..'`.\n *\n * This should not be called directly. If `pathPart` contains any path\n * separators, it will lead to unsafe undefined behavior.\n *\n * Use `Path.resolve()` instead.\n *\n * @internal\n */\n child(pathPart: string, opts?: PathOpts): PathBase {\n if (pathPart === '' || pathPart === '.') {\n return this\n }\n if (pathPart === '..') {\n return this.parent || this\n }\n\n // find the child\n const children = this.children()\n const name =\n this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n for (const p of children) {\n if (p.#matchName === name) {\n return p\n }\n }\n\n // didn't find it, create provisional child, since it might not\n // actually exist. If we know the parent isn't a dir, then\n // in fact it CAN'T exist.\n const s = this.parent ? this.sep : ''\n const fullpath =\n this.#fullpath ? this.#fullpath + s + pathPart : undefined\n const pchild = this.newChild(pathPart, UNKNOWN, {\n ...opts,\n parent: this,\n fullpath,\n })\n\n if (!this.canReaddir()) {\n pchild.#type |= ENOENT\n }\n\n // don't have to update provisional, because if we have real children,\n // then provisional is set to children.length, otherwise a lower number\n children.push(pchild)\n return pchild\n }\n\n /**\n * The relative path from the cwd. If it does not share an ancestor with\n * the cwd, then this ends up being equivalent to the fullpath()\n */\n relative(): string {\n if (this.isCWD) return ''\n if (this.#relative !== undefined) {\n return this.#relative\n }\n const name = this.name\n const p = this.parent\n if (!p) {\n return (this.#relative = this.name)\n }\n const pv = p.relative()\n return pv + (!pv || !p.parent ? '' : this.sep) + name\n }\n\n /**\n * The relative path from the cwd, using / as the path separator.\n * If it does not share an ancestor with\n * the cwd, then this ends up being equivalent to the fullpathPosix()\n * On posix systems, this is identical to relative().\n */\n relativePosix(): string {\n if (this.sep === '/') return this.relative()\n if (this.isCWD) return ''\n if (this.#relativePosix !== undefined) return this.#relativePosix\n const name = this.name\n const p = this.parent\n if (!p) {\n return (this.#relativePosix = this.fullpathPosix())\n }\n const pv = p.relativePosix()\n return pv + (!pv || !p.parent ? '' : '/') + name\n }\n\n /**\n * The fully resolved path string for this Path entry\n */\n fullpath(): string {\n if (this.#fullpath !== undefined) {\n return this.#fullpath\n }\n const name = this.name\n const p = this.parent\n if (!p) {\n return (this.#fullpath = this.name)\n }\n const pv = p.fullpath()\n const fp = pv + (!p.parent ? '' : this.sep) + name\n return (this.#fullpath = fp)\n }\n\n /**\n * On platforms other than windows, this is identical to fullpath.\n *\n * On windows, this is overridden to return the forward-slash form of the\n * full UNC path.\n */\n fullpathPosix(): string {\n if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n if (!this.parent) {\n const p = this.fullpath().replace(/\\\\/g, '/')\n if (/^[a-z]:\\//i.test(p)) {\n return (this.#fullpathPosix = `//?/${p}`)\n } else {\n return (this.#fullpathPosix = p)\n }\n }\n const p = this.parent\n const pfpp = p.fullpathPosix()\n const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n return (this.#fullpathPosix = fpp)\n }\n\n /**\n * Is the Path of an unknown type?\n *\n * Note that we might know *something* about it if there has been a previous\n * filesystem operation, for example that it does not exist, or is not a\n * link, or whether it has child entries.\n */\n isUnknown(): boolean {\n return (this.#type & IFMT) === UNKNOWN\n }\n\n isType(type: Type): boolean {\n return this[`is${type}`]()\n }\n\n getType(): Type {\n return (\n this.isUnknown() ? 'Unknown'\n : this.isDirectory() ? 'Directory'\n : this.isFile() ? 'File'\n : this.isSymbolicLink() ? 'SymbolicLink'\n : this.isFIFO() ? 'FIFO'\n : this.isCharacterDevice() ? 'CharacterDevice'\n : this.isBlockDevice() ? 'BlockDevice'\n : /* c8 ignore start */ this.isSocket() ? 'Socket'\n : 'Unknown'\n )\n /* c8 ignore stop */\n }\n\n /**\n * Is the Path a regular file?\n */\n isFile(): boolean {\n return (this.#type & IFMT) === IFREG\n }\n\n /**\n * Is the Path a directory?\n */\n isDirectory(): boolean {\n return (this.#type & IFMT) === IFDIR\n }\n\n /**\n * Is the path a character device?\n */\n isCharacterDevice(): boolean {\n return (this.#type & IFMT) === IFCHR\n }\n\n /**\n * Is the path a block device?\n */\n isBlockDevice(): boolean {\n return (this.#type & IFMT) === IFBLK\n }\n\n /**\n * Is the path a FIFO pipe?\n */\n isFIFO(): boolean {\n return (this.#type & IFMT) === IFIFO\n }\n\n /**\n * Is the path a socket?\n */\n isSocket(): boolean {\n return (this.#type & IFMT) === IFSOCK\n }\n\n /**\n * Is the path a symbolic link?\n */\n isSymbolicLink(): boolean {\n return (this.#type & IFLNK) === IFLNK\n }\n\n /**\n * Return the entry if it has been subject of a successful lstat, or\n * undefined otherwise.\n *\n * Does not read the filesystem, so an undefined result *could* simply\n * mean that we haven't called lstat on it.\n */\n lstatCached(): PathBase | undefined {\n return this.#type & LSTAT_CALLED ? this : undefined\n }\n\n /**\n * Return the cached link target if the entry has been the subject of a\n * successful readlink, or undefined otherwise.\n *\n * Does not read the filesystem, so an undefined result *could* just mean we\n * don't have any cached data. Only use it if you are very sure that a\n * readlink() has been called at some point.\n */\n readlinkCached(): PathBase | undefined {\n return this.#linkTarget\n }\n\n /**\n * Returns the cached realpath target if the entry has been the subject\n * of a successful realpath, or undefined otherwise.\n *\n * Does not read the filesystem, so an undefined result *could* just mean we\n * don't have any cached data. Only use it if you are very sure that a\n * realpath() has been called at some point.\n */\n realpathCached(): PathBase | undefined {\n return this.#realpath\n }\n\n /**\n * Returns the cached child Path entries array if the entry has been the\n * subject of a successful readdir(), or [] otherwise.\n *\n * Does not read the filesystem, so an empty array *could* just mean we\n * don't have any cached data. Only use it if you are very sure that a\n * readdir() has been called recently enough to still be valid.\n */\n readdirCached(): PathBase[] {\n const children = this.children()\n return children.slice(0, children.provisional)\n }\n\n /**\n * Return true if it's worth trying to readlink. Ie, we don't (yet) have\n * any indication that readlink will definitely fail.\n *\n * Returns false if the path is known to not be a symlink, if a previous\n * readlink failed, or if the entry does not exist.\n */\n canReadlink(): boolean {\n if (this.#linkTarget) return true\n if (!this.parent) return false\n // cases where it cannot possibly succeed\n const ifmt = this.#type & IFMT\n return !(\n (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n this.#type & ENOREADLINK ||\n this.#type & ENOENT\n )\n }\n\n /**\n * Return true if readdir has previously been successfully called on this\n * path, indicating that cachedReaddir() is likely valid.\n */\n calledReaddir(): boolean {\n return !!(this.#type & READDIR_CALLED)\n }\n\n /**\n * Returns true if the path is known to not exist. That is, a previous lstat\n * or readdir failed to verify its existence when that would have been\n * expected, or a parent entry was marked either enoent or enotdir.\n */\n isENOENT(): boolean {\n return !!(this.#type & ENOENT)\n }\n\n /**\n * Return true if the path is a match for the given path name. This handles\n * case sensitivity and unicode normalization.\n *\n * Note: even on case-sensitive systems, it is **not** safe to test the\n * equality of the `.name` property to determine whether a given pathname\n * matches, due to unicode normalization mismatches.\n *\n * Always use this method instead of testing the `path.name` property\n * directly.\n */\n isNamed(n: string): boolean {\n return !this.nocase ?\n this.#matchName === normalize(n)\n : this.#matchName === normalizeNocase(n)\n }\n\n /**\n * Return the Path object corresponding to the target of a symbolic link.\n *\n * If the Path is not a symbolic link, or if the readlink call fails for any\n * reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n */\n async readlink(): Promise<PathBase | undefined> {\n const target = this.#linkTarget\n if (target) {\n return target\n }\n if (!this.canReadlink()) {\n return undefined\n }\n /* c8 ignore start */\n // already covered by the canReadlink test, here for ts grumples\n if (!this.parent) {\n return undefined\n }\n /* c8 ignore stop */\n try {\n const read = await this.#fs.promises.readlink(this.fullpath())\n const linkTarget = (await this.parent.realpath())?.resolve(read)\n if (linkTarget) {\n return (this.#linkTarget = linkTarget)\n }\n } catch (er) {\n this.#readlinkFail((er as NodeJS.ErrnoException).code)\n return undefined\n }\n }\n\n /**\n * Synchronous {@link PathBase.readlink}\n */\n readlinkSync(): PathBase | undefined {\n const target = this.#linkTarget\n if (target) {\n return target\n }\n if (!this.canReadlink()) {\n return undefined\n }\n /* c8 ignore start */\n // already covered by the canReadlink test, here for ts grumples\n if (!this.parent) {\n return undefined\n }\n /* c8 ignore stop */\n try {\n const read = this.#fs.readlinkSync(this.fullpath())\n const linkTarget = this.parent.realpathSync()?.resolve(read)\n if (linkTarget) {\n return (this.#linkTarget = linkTarget)\n }\n } catch (er) {\n this.#readlinkFail((er as NodeJS.ErrnoException).code)\n return undefined\n }\n }\n\n #readdirSuccess(children: Children) {\n // succeeded, mark readdir called bit\n this.#type |= READDIR_CALLED\n // mark all remaining provisional children as ENOENT\n for (let p = children.provisional; p < children.length; p++) {\n const c = children[p]\n if (c) c.#markENOENT()\n }\n }\n\n #markENOENT() {\n // mark as UNKNOWN and ENOENT\n if (this.#type & ENOENT) return\n this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n this.#markChildrenENOENT()\n }\n\n #markChildrenENOENT() {\n // all children are provisional and do not exist\n const children = this.children()\n children.provisional = 0\n for (const p of children) {\n p.#markENOENT()\n }\n }\n\n #markENOREALPATH() {\n this.#type |= ENOREALPATH\n this.#markENOTDIR()\n }\n\n // save the information when we know the entry is not a dir\n #markENOTDIR() {\n // entry is not a directory, so any children can't exist.\n // this *should* be impossible, since any children created\n // after it's been marked ENOTDIR should be marked ENOENT,\n // so it won't even get to this point.\n /* c8 ignore start */\n if (this.#type & ENOTDIR) return\n /* c8 ignore stop */\n let t = this.#type\n // this could happen if we stat a dir, then delete it,\n // then try to read it or one of its children.\n if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n this.#type = t | ENOTDIR\n this.#markChildrenENOENT()\n }\n\n #readdirFail(code: string = '') {\n // markENOTDIR and markENOENT also set provisional=0\n if (code === 'ENOTDIR' || code === 'EPERM') {\n this.#markENOTDIR()\n } else if (code === 'ENOENT') {\n this.#markENOENT()\n } else {\n this.children().provisional = 0\n }\n }\n\n #lstatFail(code: string = '') {\n // Windows just raises ENOENT in this case, disable for win CI\n /* c8 ignore start */\n if (code === 'ENOTDIR') {\n // already know it has a parent by this point\n const p = this.parent as PathBase\n p.#markENOTDIR()\n } else if (code === 'ENOENT') {\n /* c8 ignore stop */\n this.#markENOENT()\n }\n }\n\n #readlinkFail(code: string = '') {\n let ter = this.#type\n ter |= ENOREADLINK\n if (code === 'ENOENT') ter |= ENOENT\n // windows gets a weird error when you try to readlink a file\n if (code === 'EINVAL' || code === 'UNKNOWN') {\n // exists, but not a symlink, we don't know WHAT it is, so remove\n // all IFMT bits.\n ter &= IFMT_UNKNOWN\n }\n this.#type = ter\n // windows just gets ENOENT in this case. We do cover the case,\n // just disabled because it's impossible on Windows CI\n /* c8 ignore start */\n if (code === 'ENOTDIR' && this.parent) {\n this.parent.#markENOTDIR()\n }\n /* c8 ignore stop */\n }\n\n #readdirAddChild(e: Dirent, c: Children) {\n return (\n this.#readdirMaybePromoteChild(e, c) ||\n this.#readdirAddNewChild(e, c)\n )\n }\n\n #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n // alloc new entry at head, so it's never provisional\n const type = entToType(e)\n const child = this.newChild(e.name, type, { parent: this })\n const ifmt = child.#type & IFMT\n if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n child.#type |= ENOTDIR\n }\n c.unshift(child)\n c.provisional++\n return child\n }\n\n #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n for (let p = c.provisional; p < c.length; p++) {\n const pchild = c[p]\n const name =\n this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n if (name !== pchild!.#matchName) {\n continue\n }\n\n return this.#readdirPromoteChild(e, pchild!, p, c)\n }\n }\n\n #readdirPromoteChild(\n e: Dirent,\n p: PathBase,\n index: number,\n c: Children,\n ): PathBase {\n const v = p.name\n // retain any other flags, but set ifmt from dirent\n p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n // case sensitivity fixing when we learn the true name.\n if (v !== e.name) p.name = e.name\n\n // just advance provisional index (potentially off the list),\n // otherwise we have to splice/pop it out and re-insert at head\n if (index !== c.provisional) {\n if (index === c.length - 1) c.pop()\n else c.splice(index, 1)\n c.unshift(p)\n }\n c.provisional++\n return p\n }\n\n /**\n * Call lstat() on this Path, and update all known information that can be\n * determined.\n *\n * Note that unlike `fs.lstat()`, the returned value does not contain some\n * information, such as `mode`, `dev`, `nlink`, and `ino`. If that\n * information is required, you will need to call `fs.lstat` yourself.\n *\n * If the Path refers to a nonexistent file, or if the lstat call fails for\n * any reason, `undefined` is returned. Otherwise the updated Path object is\n * returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n */\n async lstat(): Promise<PathBase | undefined> {\n if ((this.#type & ENOENT) === 0) {\n try {\n this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n return this\n } catch (er) {\n this.#lstatFail((er as NodeJS.ErrnoException).code)\n }\n }\n }\n\n /**\n * synchronous {@link PathBase.lstat}\n */\n lstatSync(): PathBase | undefined {\n if ((this.#type & ENOENT) === 0) {\n try {\n this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n return this\n } catch (er) {\n this.#lstatFail((er as NodeJS.ErrnoException).code)\n }\n }\n }\n\n #applyStat(st: Stats) {\n const {\n atime,\n atimeMs,\n birthtime,\n birthtimeMs,\n blksize,\n blocks,\n ctime,\n ctimeMs,\n dev,\n gid,\n ino,\n mode,\n mtime,\n mtimeMs,\n nlink,\n rdev,\n size,\n uid,\n } = st\n this.#atime = atime\n this.#atimeMs = atimeMs\n this.#birthtime = birthtime\n this.#birthtimeMs = birthtimeMs\n this.#blksize = blksize\n this.#blocks = blocks\n this.#ctime = ctime\n this.#ctimeMs = ctimeMs\n this.#dev = dev\n this.#gid = gid\n this.#ino = ino\n this.#mode = mode\n this.#mtime = mtime\n this.#mtimeMs = mtimeMs\n this.#nlink = nlink\n this.#rdev = rdev\n this.#size = size\n this.#uid = uid\n const ifmt = entToType(st)\n // retain any other flags, but set the ifmt\n this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n this.#type |= ENOTDIR\n }\n }\n\n #onReaddirCB: ((\n er: NodeJS.ErrnoException | null,\n entries: Path[],\n ) => any)[] = []\n #readdirCBInFlight: boolean = false\n #callOnReaddirCB(children: Path[]) {\n this.#readdirCBInFlight = false\n const cbs = this.#onReaddirCB.slice()\n this.#onReaddirCB.length = 0\n cbs.forEach(cb => cb(null, children))\n }\n\n /**\n * Standard node-style callback interface to get list of directory entries.\n *\n * If the Path cannot or does not contain any children, then an empty array\n * is returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n *\n * @param cb The callback called with (er, entries). Note that the `er`\n * param is somewhat extraneous, as all readdir() errors are handled and\n * simply result in an empty set of entries being returned.\n * @param allowZalgo Boolean indicating that immediately known results should\n * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n * zalgo at your peril, the dark pony lord is devious and unforgiving.\n */\n readdirCB(\n cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n allowZalgo: boolean = false,\n ): void {\n if (!this.canReaddir()) {\n if (allowZalgo) cb(null, [])\n else queueMicrotask(() => cb(null, []))\n return\n }\n\n const children = this.children()\n if (this.calledReaddir()) {\n const c = children.slice(0, children.provisional)\n if (allowZalgo) cb(null, c)\n else queueMicrotask(() => cb(null, c))\n return\n }\n\n // don't have to worry about zalgo at this point.\n this.#onReaddirCB.push(cb)\n if (this.#readdirCBInFlight) {\n return\n }\n this.#readdirCBInFlight = true\n\n // else read the directory, fill up children\n // de-provisionalize any provisional children.\n const fullpath = this.fullpath()\n this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n if (er) {\n this.#readdirFail((er as NodeJS.ErrnoException).code)\n children.provisional = 0\n } else {\n // if we didn't get an error, we always get entries.\n //@ts-ignore\n for (const e of entries) {\n this.#readdirAddChild(e, children)\n }\n this.#readdirSuccess(children)\n }\n this.#callOnReaddirCB(children.slice(0, children.provisional))\n return\n })\n }\n\n #asyncReaddirInFlight?: Promise<void>\n\n /**\n * Return an array of known child entries.\n *\n * If the Path cannot or does not contain any children, then an empty array\n * is returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n */\n async readdir(): Promise<PathBase[]> {\n if (!this.canReaddir()) {\n return []\n }\n\n const children = this.children()\n if (this.calledReaddir()) {\n return children.slice(0, children.provisional)\n }\n\n // else read the directory, fill up children\n // de-provisionalize any provisional children.\n const fullpath = this.fullpath()\n if (this.#asyncReaddirInFlight) {\n await this.#asyncReaddirInFlight\n } else {\n /* c8 ignore start */\n let resolve: () => void = () => {}\n /* c8 ignore stop */\n this.#asyncReaddirInFlight = new Promise<void>(\n res => (resolve = res),\n )\n try {\n for (const e of await this.#fs.promises.readdir(fullpath, {\n withFileTypes: true,\n })) {\n this.#readdirAddChild(e, children)\n }\n this.#readdirSuccess(children)\n } catch (er) {\n this.#readdirFail((er as NodeJS.ErrnoException).code)\n children.provisional = 0\n }\n this.#asyncReaddirInFlight = undefined\n resolve()\n }\n return children.slice(0, children.provisional)\n }\n\n /**\n * synchronous {@link PathBase.readdir}\n */\n readdirSync(): PathBase[] {\n if (!this.canReaddir()) {\n return []\n }\n\n const children = this.children()\n if (this.calledReaddir()) {\n return children.slice(0, children.provisional)\n }\n\n // else read the directory, fill up children\n // de-provisionalize any provisional children.\n const fullpath = this.fullpath()\n try {\n for (const e of this.#fs.readdirSync(fullpath, {\n withFileTypes: true,\n })) {\n this.#readdirAddChild(e, children)\n }\n this.#readdirSuccess(children)\n } catch (er) {\n this.#readdirFail((er as NodeJS.ErrnoException).code)\n children.provisional = 0\n }\n return children.slice(0, children.provisional)\n }\n\n canReaddir() {\n if (this.#type & ENOCHILD) return false\n const ifmt = IFMT & this.#type\n // we always set ENOTDIR when setting IFMT, so should be impossible\n /* c8 ignore start */\n if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n return false\n }\n /* c8 ignore stop */\n return true\n }\n\n shouldWalk(\n dirs: Set<PathBase | undefined>,\n walkFilter?: (e: PathBase) => boolean,\n ): boolean {\n return (\n (this.#type & IFDIR) === IFDIR &&\n !(this.#type & ENOCHILD) &&\n !dirs.has(this) &&\n (!walkFilter || walkFilter(this))\n )\n }\n\n /**\n * Return the Path object corresponding to path as resolved\n * by realpath(3).\n *\n * If the realpath call fails for any reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n * On success, returns a Path object.\n */\n async realpath(): Promise<PathBase | undefined> {\n if (this.#realpath) return this.#realpath\n if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n try {\n const rp = await this.#fs.promises.realpath(this.fullpath())\n return (this.#realpath = this.resolve(rp))\n } catch (_) {\n this.#markENOREALPATH()\n }\n }\n\n /**\n * Synchronous {@link realpath}\n */\n realpathSync(): PathBase | undefined {\n if (this.#realpath) return this.#realpath\n if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n try {\n const rp = this.#fs.realpathSync(this.fullpath())\n return (this.#realpath = this.resolve(rp))\n } catch (_) {\n this.#markENOREALPATH()\n }\n }\n\n /**\n * Internal method to mark this Path object as the scurry cwd,\n * called by {@link PathScurry#chdir}\n *\n * @internal\n */\n [setAsCwd](oldCwd: PathBase): void {\n if (oldCwd === this) return\n oldCwd.isCWD = false\n this.isCWD = true\n\n const changed = new Set<PathBase>([])\n let rp = []\n let p: PathBase = this\n while (p && p.parent) {\n changed.add(p)\n p.#relative = rp.join(this.sep)\n p.#relativePosix = rp.join('/')\n p = p.parent\n rp.push('..')\n }\n // now un-memoize parents of old cwd\n p = oldCwd\n while (p && p.parent && !changed.has(p)) {\n p.#relative = undefined\n p.#relativePosix = undefined\n p = p.parent\n }\n }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n /**\n * Separator for generating path strings.\n */\n sep: '\\\\' = '\\\\'\n /**\n * Separator for parsing path strings.\n */\n splitSep: RegExp = eitherSep\n\n /**\n * Do not create new Path objects directly. They should always be accessed\n * via the PathScurry class or other methods on the Path class.\n *\n * @internal\n */\n constructor(\n name: string,\n type: number = UNKNOWN,\n root: PathBase | undefined,\n roots: { [k: string]: PathBase },\n nocase: boolean,\n children: ChildrenCache,\n opts: PathOpts,\n ) {\n super(name, type, root, roots, nocase, children, opts)\n }\n\n /**\n * @internal\n */\n newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n return new PathWin32(\n name,\n type,\n this.root,\n this.roots,\n this.nocase,\n this.childrenCache(),\n opts,\n )\n }\n\n /**\n * @internal\n */\n getRootString(path: string): string {\n return win32.parse(path).root\n }\n\n /**\n * @internal\n */\n getRoot(rootPath: string): PathBase {\n rootPath = uncToDrive(rootPath.toUpperCase())\n if (rootPath === this.root.name) {\n return this.root\n }\n // ok, not that one, check if it matches another we know about\n for (const [compare, root] of Object.entries(this.roots)) {\n if (this.sameRoot(rootPath, compare)) {\n return (this.roots[rootPath] = root)\n }\n }\n // otherwise, have to create a new one.\n return (this.roots[rootPath] = new PathScurryWin32(\n rootPath,\n this,\n ).root)\n }\n\n /**\n * @internal\n */\n sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n // windows can (rarely) have case-sensitive filesystem, but\n // UNC and drive letters are always case-insensitive, and canonically\n // represented uppercase.\n rootPath = rootPath\n .toUpperCase()\n .replace(/\\//g, '\\\\')\n .replace(uncDriveRegexp, '$1\\\\')\n return rootPath === compare\n }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n /**\n * separator for parsing path strings\n */\n splitSep: '/' = '/'\n /**\n * separator for generating path strings\n */\n sep: '/' = '/'\n\n /**\n * Do not create new Path objects directly. They should always be accessed\n * via the PathScurry class or other methods on the Path class.\n *\n * @internal\n */\n constructor(\n name: string,\n type: number = UNKNOWN,\n root: PathBase | undefined,\n roots: { [k: string]: PathBase },\n nocase: boolean,\n children: ChildrenCache,\n opts: PathOpts,\n ) {\n super(name, type, root, roots, nocase, children, opts)\n }\n\n /**\n * @internal\n */\n getRootString(path: string): string {\n return path.startsWith('/') ? '/' : ''\n }\n\n /**\n * @internal\n */\n getRoot(_rootPath: string): PathBase {\n return this.root\n }\n\n /**\n * @internal\n */\n newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n return new PathPosix(\n name,\n type,\n this.root,\n this.roots,\n this.nocase,\n this.childrenCache(),\n opts,\n )\n }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n /**\n * perform case-insensitive path matching. Default based on platform\n * subclass.\n */\n nocase?: boolean\n /**\n * Number of Path entries to keep in the cache of Path child references.\n *\n * Setting this higher than 65536 will dramatically increase the data\n * consumption and construction time overhead of each PathScurry.\n *\n * Setting this value to 256 or lower will significantly reduce the data\n * consumption and construction time overhead, but may also reduce resolve()\n * and readdir() performance on large filesystems.\n *\n * Default `16384`.\n */\n childrenCacheSize?: number\n /**\n * An object that overrides the built-in functions from the fs and\n * fs/promises modules.\n *\n * See {@link FSOption}\n */\n fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n /**\n * The root Path entry for the current working directory of this Scurry\n */\n root: PathBase\n /**\n * The string path for the root of this Scurry's current working directory\n */\n rootPath: string\n /**\n * A collection of all roots encountered, referenced by rootPath\n */\n roots: { [k: string]: PathBase }\n /**\n * The Path entry corresponding to this PathScurry's current working directory.\n */\n cwd: PathBase\n #resolveCache: ResolveCache\n #resolvePosixCache: ResolveCache\n #children: ChildrenCache\n /**\n * Perform path comparisons case-insensitively.\n *\n * Defaults true on Darwin and Windows systems, false elsewhere.\n */\n nocase: boolean\n\n /**\n * The path separator used for parsing paths\n *\n * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n */\n abstract sep: string | RegExp\n\n #fs: FSValue\n\n /**\n * This class should not be instantiated directly.\n *\n * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n *\n * @internal\n */\n constructor(\n cwd: URL | string = process.cwd(),\n pathImpl: typeof win32 | typeof posix,\n sep: string | RegExp,\n {\n nocase,\n childrenCacheSize = 16 * 1024,\n fs = defaultFS,\n }: PathScurryOpts = {},\n ) {\n this.#fs = fsFromOption(fs)\n if (cwd instanceof URL || cwd.startsWith('file://')) {\n cwd = fileURLToPath(cwd)\n }\n // resolve and split root, and then add to the store.\n // this is the only time we call path.resolve()\n const cwdPath = pathImpl.resolve(cwd)\n this.roots = Object.create(null)\n this.rootPath = this.parseRootPath(cwdPath)\n this.#resolveCache = new ResolveCache()\n this.#resolvePosixCache = new ResolveCache()\n this.#children = new ChildrenCache(childrenCacheSize)\n\n const split = cwdPath.substring(this.rootPath.length).split(sep)\n // resolve('/') leaves '', splits to [''], we don't want that.\n if (split.length === 1 && !split[0]) {\n split.pop()\n }\n /* c8 ignore start */\n if (nocase === undefined) {\n throw new TypeError(\n 'must provide nocase setting to PathScurryBase ctor',\n )\n }\n /* c8 ignore stop */\n this.nocase = nocase\n this.root = this.newRoot(this.#fs)\n this.roots[this.rootPath] = this.root\n let prev: PathBase = this.root\n let len = split.length - 1\n const joinSep = pathImpl.sep\n let abs = this.rootPath\n let sawFirst = false\n for (const part of split) {\n const l = len--\n prev = prev.child(part, {\n relative: new Array(l).fill('..').join(joinSep),\n relativePosix: new Array(l).fill('..').join('/'),\n fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n })\n sawFirst = true\n }\n this.cwd = prev\n }\n\n /**\n * Get the depth of a provided path, string, or the cwd\n */\n depth(path: Path | string = this.cwd): number {\n if (typeof path === 'string') {\n path = this.cwd.resolve(path)\n }\n return path.depth()\n }\n\n /**\n * Parse the root portion of a path string\n *\n * @internal\n */\n abstract parseRootPath(dir: string): string\n /**\n * create a new Path to use as root during construction.\n *\n * @internal\n */\n abstract newRoot(fs: FSValue): PathBase\n /**\n * Determine whether a given path string is absolute\n */\n abstract isAbsolute(p: string): boolean\n\n /**\n * Return the cache of child entries. Exposed so subclasses can create\n * child Path objects in a platform-specific way.\n *\n * @internal\n */\n childrenCache() {\n return this.#children\n }\n\n /**\n * Resolve one or more path strings to a resolved string\n *\n * Same interface as require('path').resolve.\n *\n * Much faster than path.resolve() when called multiple times for the same\n * path, because the resolved Path objects are cached. Much slower\n * otherwise.\n */\n resolve(...paths: string[]): string {\n // first figure out the minimum number of paths we have to test\n // we always start at cwd, but any absolutes will bump the start\n let r = ''\n for (let i = paths.length - 1; i >= 0; i--) {\n const p = paths[i]\n if (!p || p === '.') continue\n r = r ? `${p}/${r}` : p\n if (this.isAbsolute(p)) {\n break\n }\n }\n const cached = this.#resolveCache.get(r)\n if (cached !== undefined) {\n return cached\n }\n const result = this.cwd.resolve(r).fullpath()\n this.#resolveCache.set(r, result)\n return result\n }\n\n /**\n * Resolve one or more path strings to a resolved string, returning\n * the posix path. Identical to .resolve() on posix systems, but on\n * windows will return a forward-slash separated UNC path.\n *\n * Same interface as require('path').resolve.\n *\n * Much faster than path.resolve() when called multiple times for the same\n * path, because the resolved Path objects are cached. Much slower\n * otherwise.\n */\n resolvePosix(...paths: string[]): string {\n // first figure out the minimum number of paths we have to test\n // we always start at cwd, but any absolutes will bump the start\n let r = ''\n for (let i = paths.length - 1; i >= 0; i--) {\n const p = paths[i]\n if (!p || p === '.') continue\n r = r ? `${p}/${r}` : p\n if (this.isAbsolute(p)) {\n break\n }\n }\n const cached = this.#resolvePosixCache.get(r)\n if (cached !== undefined) {\n return cached\n }\n const result = this.cwd.resolve(r).fullpathPosix()\n this.#resolvePosixCache.set(r, result)\n return result\n }\n\n /**\n * find the relative path from the cwd to the supplied path string or entry\n */\n relative(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.relative()\n }\n\n /**\n * find the relative path from the cwd to the supplied path string or\n * entry, using / as the path delimiter, even on Windows.\n */\n relativePosix(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.relativePosix()\n }\n\n /**\n * Return the basename for the provided string or Path object\n */\n basename(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.name\n }\n\n /**\n * Return the dirname for the provided string or Path object\n */\n dirname(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return (entry.parent || entry).fullpath()\n }\n\n /**\n * Return an array of known child entries.\n *\n * First argument may be either a string, or a Path object.\n *\n * If the Path cannot or does not contain any children, then an empty array\n * is returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n *\n * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n * `{ withFileTypes: false }` to return strings.\n */\n\n readdir(): Promise<PathBase[]>\n readdir(opts: { withFileTypes: true }): Promise<PathBase[]>\n readdir(opts: { withFileTypes: false }): Promise<string[]>\n readdir(opts: { withFileTypes: boolean }): Promise<PathBase[] | string[]>\n readdir(entry: PathBase | string): Promise<PathBase[]>\n readdir(\n entry: PathBase | string,\n opts: { withFileTypes: true },\n ): Promise<PathBase[]>\n readdir(\n entry: PathBase | string,\n opts: { withFileTypes: false },\n ): Promise<string[]>\n readdir(\n entry: PathBase | string,\n opts: { withFileTypes: boolean },\n ): Promise<PathBase[] | string[]>\n async readdir(\n entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n opts: { withFileTypes: boolean } = {\n withFileTypes: true,\n },\n ): Promise<PathBase[] | string[]> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const { withFileTypes } = opts\n if (!entry.canReaddir()) {\n return []\n } else {\n const p = await entry.readdir()\n return withFileTypes ? p : p.map(e => e.name)\n }\n }\n\n /**\n * synchronous {@link PathScurryBase.readdir}\n */\n readdirSync(): PathBase[]\n readdirSync(opts: { withFileTypes: true }): PathBase[]\n readdirSync(opts: { withFileTypes: false }): string[]\n readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n readdirSync(entry: PathBase | string): PathBase[]\n readdirSync(\n entry: PathBase | string,\n opts: { withFileTypes: true },\n ): PathBase[]\n readdirSync(\n entry: PathBase | string,\n opts: { withFileTypes: false },\n ): string[]\n readdirSync(\n entry: PathBase | string,\n opts: { withFileTypes: boolean },\n ): PathBase[] | string[]\n readdirSync(\n entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n opts: { withFileTypes: boolean } = {\n withFileTypes: true,\n },\n ): PathBase[] | string[] {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const { withFileTypes = true } = opts\n if (!entry.canReaddir()) {\n return []\n } else if (withFileTypes) {\n return entry.readdirSync()\n } else {\n return entry.readdirSync().map(e => e.name)\n }\n }\n\n /**\n * Call lstat() on the string or Path object, and update all known\n * information that can be determined.\n *\n * Note that unlike `fs.lstat()`, the returned value does not contain some\n * information, such as `mode`, `dev`, `nlink`, and `ino`. If that\n * information is required, you will need to call `fs.lstat` yourself.\n *\n * If the Path refers to a nonexistent file, or if the lstat call fails for\n * any reason, `undefined` is returned. Otherwise the updated Path object is\n * returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n */\n async lstat(\n entry: string | PathBase = this.cwd,\n ): Promise<PathBase | undefined> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.lstat()\n }\n\n /**\n * synchronous {@link PathScurryBase.lstat}\n */\n lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.lstatSync()\n }\n\n /**\n * Return the Path object or string path corresponding to the target of a\n * symbolic link.\n *\n * If the path is not a symbolic link, or if the readlink call fails for any\n * reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n *\n * `{withFileTypes}` option defaults to `false`.\n *\n * On success, returns a Path object if `withFileTypes` option is true,\n * otherwise a string.\n */\n readlink(): Promise<string | undefined>\n readlink(opt: { withFileTypes: false }): Promise<string | undefined>\n readlink(opt: { withFileTypes: true }): Promise<PathBase | undefined>\n readlink(opt: {\n withFileTypes: boolean\n }): Promise<PathBase | string | undefined>\n readlink(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): Promise<string | undefined>\n readlink(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): Promise<PathBase | undefined>\n readlink(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): Promise<string | PathBase | undefined>\n async readlink(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): Promise<string | PathBase | undefined> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = await entry.readlink()\n return withFileTypes ? e : e?.fullpath()\n }\n\n /**\n * synchronous {@link PathScurryBase.readlink}\n */\n readlinkSync(): string | undefined\n readlinkSync(opt: { withFileTypes: false }): string | undefined\n readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n readlinkSync(opt: {\n withFileTypes: boolean\n }): PathBase | string | undefined\n readlinkSync(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): string | undefined\n readlinkSync(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): PathBase | undefined\n readlinkSync(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): string | PathBase | undefined\n readlinkSync(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): string | PathBase | undefined {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = entry.readlinkSync()\n return withFileTypes ? e : e?.fullpath()\n }\n\n /**\n * Return the Path object or string path corresponding to path as resolved\n * by realpath(3).\n *\n * If the realpath call fails for any reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n *\n * `{withFileTypes}` option defaults to `false`.\n *\n * On success, returns a Path object if `withFileTypes` option is true,\n * otherwise a string.\n */\n realpath(): Promise<string | undefined>\n realpath(opt: { withFileTypes: false }): Promise<string | undefined>\n realpath(opt: { withFileTypes: true }): Promise<PathBase | undefined>\n realpath(opt: {\n withFileTypes: boolean\n }): Promise<PathBase | string | undefined>\n realpath(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): Promise<string | undefined>\n realpath(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): Promise<PathBase | undefined>\n realpath(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): Promise<string | PathBase | undefined>\n async realpath(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): Promise<string | PathBase | undefined> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = await entry.realpath()\n return withFileTypes ? e : e?.fullpath()\n }\n\n realpathSync(): string | undefined\n realpathSync(opt: { withFileTypes: false }): string | undefined\n realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n realpathSync(opt: {\n withFileTypes: boolean\n }): PathBase | string | undefined\n realpathSync(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): string | undefined\n realpathSync(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): PathBase | undefined\n realpathSync(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): string | PathBase | undefined\n realpathSync(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): string | PathBase | undefined {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = entry.realpathSync()\n return withFileTypes ? e : e?.fullpath()\n }\n\n /**\n * Asynchronously walk the directory tree, returning an array of\n * all path strings or Path objects found.\n *\n * Note that this will be extremely memory-hungry on large filesystems.\n * In such cases, it may be better to use the stream or async iterator\n * walk implementation.\n */\n walk(): Promise<PathBase[]>\n walk(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Promise<PathBase[]>\n walk(opts: WalkOptionsWithFileTypesFalse): Promise<string[]>\n walk(opts: WalkOptions): Promise<string[] | PathBase[]>\n walk(entry: string | PathBase): Promise<PathBase[]>\n walk(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Promise<PathBase[]>\n walk(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Promise<string[]>\n walk(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Promise<PathBase[] | string[]>\n async walk(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Promise<PathBase[] | string[]> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results: (string | PathBase)[] = []\n if (!filter || filter(entry)) {\n results.push(withFileTypes ? entry : entry.fullpath())\n }\n const dirs = new Set<PathBase>()\n const walk = (\n dir: PathBase,\n cb: (er?: NodeJS.ErrnoException) => void,\n ) => {\n dirs.add(dir)\n dir.readdirCB((er, entries) => {\n /* c8 ignore start */\n if (er) {\n return cb(er)\n }\n /* c8 ignore stop */\n let len = entries.length\n if (!len) return cb()\n const next = () => {\n if (--len === 0) {\n cb()\n }\n }\n for (const e of entries) {\n if (!filter || filter(e)) {\n results.push(withFileTypes ? e : e.fullpath())\n }\n if (follow && e.isSymbolicLink()) {\n e.realpath()\n .then(r => (r?.isUnknown() ? r.lstat() : r))\n .then(r =>\n r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n )\n } else {\n if (e.shouldWalk(dirs, walkFilter)) {\n walk(e, next)\n } else {\n next()\n }\n }\n }\n }, true) // zalgooooooo\n }\n\n const start = entry\n return new Promise<PathBase[] | string[]>((res, rej) => {\n walk(start, er => {\n /* c8 ignore start */\n if (er) return rej(er)\n /* c8 ignore stop */\n res(results as PathBase[] | string[])\n })\n })\n }\n\n /**\n * Synchronously walk the directory tree, returning an array of\n * all path strings or Path objects found.\n *\n * Note that this will be extremely memory-hungry on large filesystems.\n * In such cases, it may be better to use the stream or async iterator\n * walk implementation.\n */\n walkSync(): PathBase[]\n walkSync(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): PathBase[]\n walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n walkSync(opts: WalkOptions): string[] | PathBase[]\n walkSync(entry: string | PathBase): PathBase[]\n walkSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n ): PathBase[]\n walkSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): string[]\n walkSync(\n entry: string | PathBase,\n opts: WalkOptions,\n ): PathBase[] | string[]\n walkSync(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): PathBase[] | string[] {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results: (string | PathBase)[] = []\n if (!filter || filter(entry)) {\n results.push(withFileTypes ? entry : entry.fullpath())\n }\n const dirs = new Set<PathBase>([entry])\n for (const dir of dirs) {\n const entries = dir.readdirSync()\n for (const e of entries) {\n if (!filter || filter(e)) {\n results.push(withFileTypes ? e : e.fullpath())\n }\n let r: PathBase | undefined = e\n if (e.isSymbolicLink()) {\n if (!(follow && (r = e.realpathSync()))) continue\n if (r.isUnknown()) r.lstatSync()\n }\n if (r.shouldWalk(dirs, walkFilter)) {\n dirs.add(r)\n }\n }\n }\n return results as string[] | PathBase[]\n }\n\n /**\n * Support for `for await`\n *\n * Alias for {@link PathScurryBase.iterate}\n *\n * Note: As of Node 19, this is very slow, compared to other methods of\n * walking. Consider using {@link PathScurryBase.stream} if memory overhead\n * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n */\n [Symbol.asyncIterator]() {\n return this.iterate()\n }\n\n /**\n * Async generator form of {@link PathScurryBase.walk}\n *\n * Note: As of Node 19, this is very slow, compared to other methods of\n * walking, especially if most/all of the directory tree has been previously\n * walked. Consider using {@link PathScurryBase.stream} if memory overhead\n * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n */\n iterate(): AsyncGenerator<PathBase, void, void>\n iterate(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): AsyncGenerator<PathBase, void, void>\n iterate(\n opts: WalkOptionsWithFileTypesFalse,\n ): AsyncGenerator<string, void, void>\n iterate(opts: WalkOptions): AsyncGenerator<string | PathBase, void, void>\n iterate(entry: string | PathBase): AsyncGenerator<PathBase, void, void>\n iterate(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): AsyncGenerator<PathBase, void, void>\n iterate(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): AsyncGenerator<string, void, void>\n iterate(\n entry: string | PathBase,\n opts: WalkOptions,\n ): AsyncGenerator<PathBase | string, void, void>\n iterate(\n entry: string | PathBase | WalkOptions = this.cwd,\n options: WalkOptions = {},\n ): AsyncGenerator<PathBase | string, void, void> {\n // iterating async over the stream is significantly more performant,\n // especially in the warm-cache scenario, because it buffers up directory\n // entries in the background instead of waiting for a yield for each one.\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n options = entry\n entry = this.cwd\n }\n return this.stream(entry, options)[Symbol.asyncIterator]()\n }\n\n /**\n * Iterating over a PathScurry performs a synchronous walk.\n *\n * Alias for {@link PathScurryBase.iterateSync}\n */\n [Symbol.iterator]() {\n return this.iterateSync()\n }\n\n iterateSync(): Generator<PathBase, void, void>\n iterateSync(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Generator<PathBase, void, void>\n iterateSync(\n opts: WalkOptionsWithFileTypesFalse,\n ): Generator<string, void, void>\n iterateSync(opts: WalkOptions): Generator<string | PathBase, void, void>\n iterateSync(entry: string | PathBase): Generator<PathBase, void, void>\n iterateSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Generator<PathBase, void, void>\n iterateSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Generator<string, void, void>\n iterateSync(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Generator<PathBase | string, void, void>\n *iterateSync(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Generator<PathBase | string, void, void> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n if (!filter || filter(entry)) {\n yield withFileTypes ? entry : entry.fullpath()\n }\n const dirs = new Set<PathBase>([entry])\n for (const dir of dirs) {\n const entries = dir.readdirSync()\n for (const e of entries) {\n if (!filter || filter(e)) {\n yield withFileTypes ? e : e.fullpath()\n }\n let r: PathBase | undefined = e\n if (e.isSymbolicLink()) {\n if (!(follow && (r = e.realpathSync()))) continue\n if (r.isUnknown()) r.lstatSync()\n }\n if (r.shouldWalk(dirs, walkFilter)) {\n dirs.add(r)\n }\n }\n }\n }\n\n /**\n * Stream form of {@link PathScurryBase.walk}\n *\n * Returns a Minipass stream that emits {@link PathBase} objects by default,\n * or strings if `{ withFileTypes: false }` is set in the options.\n */\n stream(): Minipass<PathBase>\n stream(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Minipass<PathBase>\n stream(opts: WalkOptionsWithFileTypesFalse): Minipass<string>\n stream(opts: WalkOptions): Minipass<string | PathBase>\n stream(entry: string | PathBase): Minipass<PathBase>\n stream(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n ): Minipass<PathBase>\n stream(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Minipass<string>\n stream(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Minipass<string> | Minipass<PathBase>\n stream(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Minipass<string> | Minipass<PathBase> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results = new Minipass<string | PathBase>({ objectMode: true })\n if (!filter || filter(entry)) {\n results.write(withFileTypes ? entry : entry.fullpath())\n }\n const dirs = new Set<PathBase>()\n const queue: PathBase[] = [entry]\n let processing = 0\n const process = () => {\n let paused = false\n while (!paused) {\n const dir = queue.shift()\n if (!dir) {\n if (processing === 0) results.end()\n return\n }\n\n processing++\n dirs.add(dir)\n\n const onReaddir = (\n er: null | NodeJS.ErrnoException,\n entries: PathBase[],\n didRealpaths: boolean = false,\n ) => {\n /* c8 ignore start */\n if (er) return results.emit('error', er)\n /* c8 ignore stop */\n if (follow && !didRealpaths) {\n const promises: Promise<PathBase | undefined>[] = []\n for (const e of entries) {\n if (e.isSymbolicLink()) {\n promises.push(\n e\n .realpath()\n .then((r: PathBase | undefined) =>\n r?.isUnknown() ? r.lstat() : r,\n ),\n )\n }\n }\n if (promises.length) {\n Promise.all(promises).then(() =>\n onReaddir(null, entries, true),\n )\n return\n }\n }\n\n for (const e of entries) {\n if (e && (!filter || filter(e))) {\n if (!results.write(withFileTypes ? e : e.fullpath())) {\n paused = true\n }\n }\n }\n\n processing--\n for (const e of entries) {\n const r = e.realpathCached() || e\n if (r.shouldWalk(dirs, walkFilter)) {\n queue.push(r)\n }\n }\n if (paused && !results.flowing) {\n results.once('drain', process)\n } else if (!sync) {\n process()\n }\n }\n\n // zalgo containment\n let sync = true\n dir.readdirCB(onReaddir, true)\n sync = false\n }\n }\n process()\n return results as Minipass<string> | Minipass<PathBase>\n }\n\n /**\n * Synchronous form of {@link PathScurryBase.stream}\n *\n * Returns a Minipass stream that emits {@link PathBase} objects by default,\n * or strings if `{ withFileTypes: false }` is set in the options.\n *\n * Will complete the walk in a single tick if the stream is consumed fully.\n * Otherwise, will pause as needed for stream backpressure.\n */\n streamSync(): Minipass<PathBase>\n streamSync(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Minipass<PathBase>\n streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass<string>\n streamSync(opts: WalkOptions): Minipass<string | PathBase>\n streamSync(entry: string | PathBase): Minipass<PathBase>\n streamSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n ): Minipass<PathBase>\n streamSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Minipass<string>\n streamSync(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Minipass<string> | Minipass<PathBase>\n streamSync(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Minipass<string> | Minipass<PathBase> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results = new Minipass<string | PathBase>({ objectMode: true })\n const dirs = new Set<PathBase>()\n if (!filter || filter(entry)) {\n results.write(withFileTypes ? entry : entry.fullpath())\n }\n const queue: PathBase[] = [entry]\n let processing = 0\n const process = () => {\n let paused = false\n while (!paused) {\n const dir = queue.shift()\n if (!dir) {\n if (processing === 0) results.end()\n return\n }\n processing++\n dirs.add(dir)\n\n const entries = dir.readdirSync()\n for (const e of entries) {\n if (!filter || filter(e)) {\n if (!results.write(withFileTypes ? e : e.fullpath())) {\n paused = true\n }\n }\n }\n processing--\n for (const e of entries) {\n let r: PathBase | undefined = e\n if (e.isSymbolicLink()) {\n if (!(follow && (r = e.realpathSync()))) continue\n if (r.isUnknown()) r.lstatSync()\n }\n if (r.shouldWalk(dirs, walkFilter)) {\n queue.push(r)\n }\n }\n }\n if (paused && !results.flowing) results.once('drain', process)\n }\n process()\n return results as Minipass<string> | Minipass<PathBase>\n }\n\n chdir(path: string | Path = this.cwd) {\n const oldCwd = this.cwd\n this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n this.cwd[setAsCwd](oldCwd)\n }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n /**\n * Return results as {@link PathBase} objects rather than strings.\n * When set to false, results are fully resolved paths, as returned by\n * {@link PathBase.fullpath}.\n * @default true\n */\n withFileTypes?: boolean\n\n /**\n * Attempt to read directory entries from symbolic links. Otherwise, only\n * actual directories are traversed. Regardless of this setting, a given\n * target path will only ever be walked once, meaning that a symbolic link\n * to a previously traversed directory will never be followed.\n *\n * Setting this imposes a slight performance penalty, because `readlink`\n * must be called on all symbolic links encountered, in order to avoid\n * infinite cycles.\n * @default false\n */\n follow?: boolean\n\n /**\n * Only return entries where the provided function returns true.\n *\n * This will not prevent directories from being traversed, even if they do\n * not pass the filter, though it will prevent directories themselves from\n * being included in the result set. See {@link walkFilter}\n *\n * Asynchronous functions are not supported here.\n *\n * By default, if no filter is provided, all entries and traversed\n * directories are included.\n */\n filter?: (entry: PathBase) => boolean\n\n /**\n * Only traverse directories (and in the case of {@link follow} being set to\n * true, symbolic links to directories) if the provided function returns\n * true.\n *\n * This will not prevent directories from being included in the result set,\n * even if they do not pass the supplied filter function. See {@link filter}\n * to do that.\n *\n * Asynchronous functions are not supported here.\n */\n walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings. Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n /**\n * separator for generating path strings\n */\n sep: '\\\\' = '\\\\'\n\n constructor(\n cwd: URL | string = process.cwd(),\n opts: PathScurryOpts = {},\n ) {\n const { nocase = true } = opts\n super(cwd, win32, '\\\\', { ...opts, nocase })\n this.nocase = nocase\n for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n p.nocase = this.nocase\n }\n }\n\n /**\n * @internal\n */\n parseRootPath(dir: string): string {\n // if the path starts with a single separator, it's not a UNC, and we'll\n // just get separator as the root, and driveFromUNC will return \\\n // In that case, mount \\ on the root from the cwd.\n return win32.parse(dir).root.toUpperCase()\n }\n\n /**\n * @internal\n */\n newRoot(fs: FSValue) {\n return new PathWin32(\n this.rootPath,\n IFDIR,\n undefined,\n this.roots,\n this.nocase,\n this.childrenCache(),\n { fs },\n )\n }\n\n /**\n * Return true if the provided path string is an absolute path\n */\n isAbsolute(p: string): boolean {\n return (\n p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n )\n }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n /**\n * separator for generating path strings\n */\n sep: '/' = '/'\n constructor(\n cwd: URL | string = process.cwd(),\n opts: PathScurryOpts = {},\n ) {\n const { nocase = false } = opts\n super(cwd, posix, '/', { ...opts, nocase })\n this.nocase = nocase\n }\n\n /**\n * @internal\n */\n parseRootPath(_dir: string): string {\n return '/'\n }\n\n /**\n * @internal\n */\n newRoot(fs: FSValue) {\n return new PathPosix(\n this.rootPath,\n IFDIR,\n undefined,\n this.roots,\n this.nocase,\n this.childrenCache(),\n { fs },\n )\n }\n\n /**\n * Return true if the provided path string is an absolute path\n */\n isAbsolute(p: string): boolean {\n return p.startsWith('/')\n }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n constructor(\n cwd: URL | string = process.cwd(),\n opts: PathScurryOpts = {},\n ) {\n const { nocase = true } = opts\n super(cwd, { ...opts, nocase })\n }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType<typeof Path>\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n | typeof PathScurryWin32\n | typeof PathScurryDarwin\n | typeof PathScurryPosix =\n process.platform === 'win32' ? PathScurryWin32\n : process.platform === 'darwin' ? PathScurryDarwin\n : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType<typeof PathScurry>\n", "const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe<T extends unknown> {\n src: Minipass<T>\n dest: Minipass<any, T>\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass<any, T>\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors<T> extends Pipe<T> {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrors = er => dest.emit('error', er)\n src.on('error', this.proxyErrors)\n }\n}\n\nexport namespace Minipass {\n /**\n * Encoding used to create a stream that outputs strings rather than\n * Buffer objects.\n */\n export type Encoding = BufferEncoding | 'buffer' | null\n\n /**\n * Any stream that Minipass can pipe into\n */\n export type Writable =\n | Minipass<any, any, any>\n | NodeJS.WriteStream\n | (NodeJS.WriteStream & { fd: number })\n | (EventEmitter & {\n end(): any\n write(chunk: any, ...args: any[]): any\n })\n\n /**\n * Any stream that can be read from\n */\n export type Readable =\n | Minipass<any, any, any>\n | NodeJS.ReadStream\n | (NodeJS.ReadStream & { fd: number })\n | (EventEmitter & {\n pause(): any\n resume(): any\n pipe(...destArgs: any[]): any\n })\n\n /**\n * Utility type that can be iterated sync or async\n */\n export type DualIterable<T> = Iterable<T> & AsyncIterable<T>\n\n type EventArguments = Record<string | symbol, unknown[]>\n\n /**\n * The listing of events that a Minipass class can emit.\n * Extend this when extending the Minipass class, and pass as\n * the third template argument. The key is the name of the event,\n * and the value is the argument list.\n *\n * Any undeclared events will still be allowed, but the handler will get\n * arguments as `unknown[]`.\n */\n export interface Events<RType extends any = Buffer>\n extends EventArguments {\n readable: []\n data: [chunk: RType]\n error: [er: unknown]\n abort: [reason: unknown]\n drain: []\n resume: []\n end: []\n finish: []\n prefinish: []\n close: []\n [DESTROYED]: [er?: unknown]\n [ERROR]: [er: unknown]\n }\n\n /**\n * String or buffer-like data that can be joined and sliced\n */\n export type ContiguousData =\n | Buffer\n | ArrayBufferLike\n | ArrayBufferView\n | string\n export type BufferOrString = Buffer | string\n\n /**\n * Options passed to the Minipass constructor.\n */\n export type SharedOptions = {\n /**\n * Defer all data emission and other events until the end of the\n * current tick, similar to Node core streams\n */\n async?: boolean\n /**\n * A signal which will abort the stream\n */\n signal?: AbortSignal\n /**\n * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n * emit Buffer objects rather than strings.\n *\n * Conflicts with `objectMode`\n */\n encoding?: BufferEncoding | null | 'buffer'\n /**\n * Output data exactly as it was written, supporting non-buffer/string\n * data (such as arbitrary objects, falsey values, etc.)\n *\n * Conflicts with `encoding`\n */\n objectMode?: boolean\n }\n\n /**\n * Options for a string encoded output\n */\n export type EncodingOptions = SharedOptions & {\n encoding: BufferEncoding\n objectMode?: false\n }\n\n /**\n * Options for contiguous data buffer output\n */\n export type BufferOptions = SharedOptions & {\n encoding?: null | 'buffer'\n objectMode?: false\n }\n\n /**\n * Options for objectMode arbitrary output\n */\n export type ObjectModeOptions = SharedOptions & {\n objectMode: true\n encoding?: null\n }\n\n /**\n * Utility type to determine allowed options based on read type\n */\n export type Options<T> =\n | ObjectModeOptions\n | (T extends string\n ? EncodingOptions\n : T extends Buffer\n ? BufferOptions\n : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n RType extends unknown = Buffer,\n WType extends unknown = RType extends Minipass.BufferOrString\n ? Minipass.ContiguousData\n : RType,\n Events extends Minipass.Events<RType> = Minipass.Events<RType>\n >\n extends EventEmitter\n implements Minipass.DualIterable<RType>\n{\n [FLOWING]: boolean = false;\n [PAUSED]: boolean = false;\n [PIPES]: Pipe<RType>[] = [];\n [BUFFER]: RType[] = [];\n [OBJECTMODE]: boolean;\n [ENCODING]: BufferEncoding | null;\n [ASYNC]: boolean;\n [DECODER]: SD | null;\n [EOF]: boolean = false;\n [EMITTED_END]: boolean = false;\n [EMITTING_END]: boolean = false;\n [CLOSED]: boolean = false;\n [EMITTED_ERROR]: unknown = null;\n [BUFFERLENGTH]: number = 0;\n [DESTROYED]: boolean = false;\n [SIGNAL]?: AbortSignal;\n [ABORTED]: boolean = false;\n [DATALISTENERS]: number = 0;\n [DISCARDED]: boolean = false\n\n /**\n * true if the stream can be written\n */\n writable: boolean = true\n /**\n * true if the stream can be read\n */\n readable: boolean = true\n\n /**\n * If `RType` is Buffer, then options do not need to be provided.\n * Otherwise, an options object must be provided to specify either\n * {@link Minipass.SharedOptions.objectMode} or\n * {@link Minipass.SharedOptions.encoding}, as appropriate.\n */\n constructor(\n ...args:\n | [Minipass.ObjectModeOptions]\n | (RType extends Buffer\n ? [] | [Minipass.Options<RType>]\n : [Minipass.Options<RType>])\n ) {\n const options: Minipass.Options<RType> = (args[0] ||\n {}) as Minipass.Options<RType>\n super()\n if (options.objectMode && typeof options.encoding === 'string') {\n throw new TypeError(\n 'Encoding and objectMode may not be used together'\n )\n }\n if (isObjectModeOptions(options)) {\n this[OBJECTMODE] = true\n this[ENCODING] = null\n } else if (isEncodingOptions(options)) {\n this[ENCODING] = options.encoding\n this[OBJECTMODE] = false\n } else {\n this[OBJECTMODE] = false\n this[ENCODING] = null\n }\n this[ASYNC] = !!options.async\n this[DECODER] = this[ENCODING]\n ? (new StringDecoder(this[ENCODING]) as SD)\n : null\n\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposeBuffer === true) {\n Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n }\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposePipes === true) {\n Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n }\n\n const { signal } = options\n if (signal) {\n this[SIGNAL] = signal\n if (signal.aborted) {\n this[ABORT]()\n } else {\n signal.addEventListener('abort', () => this[ABORT]())\n }\n }\n }\n\n /**\n * The amount of data stored in the buffer waiting to be read.\n *\n * For Buffer strings, this will be the total byte length.\n * For string encoding streams, this will be the string character length,\n * according to JavaScript's `string.length` logic.\n * For objectMode streams, this is a count of the items waiting to be\n * emitted.\n */\n get bufferLength() {\n return this[BUFFERLENGTH]\n }\n\n /**\n * The `BufferEncoding` currently in use, or `null`\n */\n get encoding() {\n return this[ENCODING]\n }\n\n /**\n * @deprecated - This is a read only property\n */\n set encoding(_enc) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * @deprecated - Encoding may only be set at instantiation time\n */\n setEncoding(_enc: Minipass.Encoding) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * True if this is an objectMode stream\n */\n get objectMode() {\n return this[OBJECTMODE]\n }\n\n /**\n * @deprecated - This is a read-only property\n */\n set objectMode(_om) {\n throw new Error('objectMode must be set at instantiation time')\n }\n\n /**\n * true if this is an async stream\n */\n get ['async'](): boolean {\n return this[ASYNC]\n }\n /**\n * Set to true to make this stream async.\n *\n * Once set, it cannot be unset, as this would potentially cause incorrect\n * behavior. Ie, a sync stream can be made async, but an async stream\n * cannot be safely made sync.\n */\n set ['async'](a: boolean) {\n this[ASYNC] = this[ASYNC] || !!a\n }\n\n // drop everything and get out of the flow completely\n [ABORT]() {\n this[ABORTED] = true\n this.emit('abort', this[SIGNAL]?.reason)\n this.destroy(this[SIGNAL]?.reason)\n }\n\n /**\n * True if the stream has been aborted.\n */\n get aborted() {\n return this[ABORTED]\n }\n /**\n * No-op setter. Stream aborted status is set via the AbortSignal provided\n * in the constructor options.\n */\n set aborted(_) {}\n\n /**\n * Write data into the stream\n *\n * If the chunk written is a string, and encoding is not specified, then\n * `utf8` will be assumed. If the stream encoding matches the encoding of\n * a written string, and the state of the string decoder allows it, then\n * the string will be passed through to either the output or the internal\n * buffer without any processing. Otherwise, it will be turned into a\n * Buffer object for processing into the desired encoding.\n *\n * If provided, `cb` function is called immediately before return for\n * sync streams, or on next tick for async streams, because for this\n * base class, a chunk is considered \"processed\" once it is accepted\n * and either emitted or buffered. That is, the callback does not indicate\n * that the chunk has been eventually emitted, though of course child\n * classes can override this function to do whatever processing is required\n * and call `super.write(...)` only once processing is completed.\n */\n write(chunk: WType, cb?: () => void): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding,\n cb?: () => void\n ): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): boolean {\n if (this[ABORTED]) return false\n if (this[EOF]) throw new Error('write after end')\n\n if (this[DESTROYED]) {\n this.emit(\n 'error',\n Object.assign(\n new Error('Cannot call write after a stream was destroyed'),\n { code: 'ERR_STREAM_DESTROYED' }\n )\n )\n return true\n }\n\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n\n if (!encoding) encoding = 'utf8'\n\n const fn = this[ASYNC] ? defer : nodefer\n\n // convert array buffers and typed array views into buffers\n // at some point in the future, we may want to do the opposite!\n // leave strings and buffers as-is\n // anything is only allowed if in object mode, so throw\n if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n if (isArrayBufferView(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n )\n } else if (isArrayBufferLike(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(chunk)\n } else if (typeof chunk !== 'string') {\n throw new Error(\n 'Non-contiguous data written to non-objectMode stream'\n )\n }\n }\n\n // handle object mode up front, since it's simpler\n // this yields better performance, fewer checks later.\n if (this[OBJECTMODE]) {\n // maybe impossible?\n /* c8 ignore start */\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n /* c8 ignore stop */\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n // at this point the chunk is a buffer or string\n // don't buffer it up or send it to the decoder\n if (!(chunk as Minipass.BufferOrString).length) {\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n if (cb) fn(cb)\n return this[FLOWING]\n }\n\n // fast-path writing strings of same encoding to a stream with\n // an empty buffer, skipping the buffer/decoder dance\n if (\n typeof chunk === 'string' &&\n // unless it is a string already ready for us to use\n !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n ) {\n //@ts-ignore - sinful unsafe type change\n chunk = Buffer.from(chunk, encoding)\n }\n\n if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n //@ts-ignore - sinful unsafe type change\n chunk = this[DECODER].write(chunk)\n }\n\n // Note: flushing CAN potentially switch us into not-flowing mode\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n /**\n * Low-level explicit read method.\n *\n * In objectMode, the argument is ignored, and one item is returned if\n * available.\n *\n * `n` is the number of bytes (or in the case of encoding streams,\n * characters) to consume. If `n` is not provided, then the entire buffer\n * is returned, or `null` is returned if no data is available.\n *\n * If `n` is greater that the amount of data in the internal buffer,\n * then `null` is returned.\n */\n read(n?: number | null): RType | null {\n if (this[DESTROYED]) return null\n this[DISCARDED] = false\n\n if (\n this[BUFFERLENGTH] === 0 ||\n n === 0 ||\n (n && n > this[BUFFERLENGTH])\n ) {\n this[MAYBE_EMIT_END]()\n return null\n }\n\n if (this[OBJECTMODE]) n = null\n\n if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n // not object mode, so if we have an encoding, then RType is string\n // otherwise, must be Buffer\n this[BUFFER] = [\n (this[ENCODING]\n ? this[BUFFER].join('')\n : Buffer.concat(\n this[BUFFER] as Buffer[],\n this[BUFFERLENGTH]\n )) as RType,\n ]\n }\n\n const ret = this[READ](n || null, this[BUFFER][0] as RType)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [READ](n: number | null, chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n else {\n const c = chunk as Minipass.BufferOrString\n if (n === c.length || n === null) this[BUFFERSHIFT]()\n else if (typeof c === 'string') {\n this[BUFFER][0] = c.slice(n) as RType\n chunk = c.slice(0, n) as RType\n this[BUFFERLENGTH] -= n\n } else {\n this[BUFFER][0] = c.subarray(n) as RType\n chunk = c.subarray(0, n) as RType\n this[BUFFERLENGTH] -= n\n }\n }\n\n this.emit('data', chunk)\n\n if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n return chunk\n }\n\n /**\n * End the stream, optionally providing a final write.\n *\n * See {@link Minipass#write} for argument descriptions\n */\n end(cb?: () => void): this\n end(chunk: WType, cb?: () => void): this\n end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n end(\n chunk?: WType | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): this {\n if (typeof chunk === 'function') {\n cb = chunk as () => void\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n if (chunk !== undefined) this.write(chunk, encoding)\n if (cb) this.once('end', cb)\n this[EOF] = true\n this.writable = false\n\n // if we haven't written anything, then go ahead and emit,\n // even if we're not reading.\n // we'll re-emit if a new 'end' listener is added anyway.\n // This makes MP more suitable to write-only use cases.\n if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n return this\n }\n\n // don't let the internal resume be overwritten\n [RESUME]() {\n if (this[DESTROYED]) return\n\n if (!this[DATALISTENERS] && !this[PIPES].length) {\n this[DISCARDED] = true\n }\n this[PAUSED] = false\n this[FLOWING] = true\n this.emit('resume')\n if (this[BUFFER].length) this[FLUSH]()\n else if (this[EOF]) this[MAYBE_EMIT_END]()\n else this.emit('drain')\n }\n\n /**\n * Resume the stream if it is currently in a paused state\n *\n * If called when there are no pipe destinations or `data` event listeners,\n * this will place the stream in a \"discarded\" state, where all data will\n * be thrown away. The discarded state is removed if a pipe destination or\n * data handler is added, if pause() is called, or if any synchronous or\n * asynchronous iteration is started.\n */\n resume() {\n return this[RESUME]()\n }\n\n /**\n * Pause the stream\n */\n pause() {\n this[FLOWING] = false\n this[PAUSED] = true\n this[DISCARDED] = false\n }\n\n /**\n * true if the stream has been forcibly destroyed\n */\n get destroyed() {\n return this[DESTROYED]\n }\n\n /**\n * true if the stream is currently in a flowing state, meaning that\n * any writes will be immediately emitted.\n */\n get flowing() {\n return this[FLOWING]\n }\n\n /**\n * true if the stream is currently in a paused state\n */\n get paused() {\n return this[PAUSED]\n }\n\n [BUFFERPUSH](chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n this[BUFFER].push(chunk)\n }\n\n [BUFFERSHIFT](): RType {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n else\n this[BUFFERLENGTH] -= (\n this[BUFFER][0] as Minipass.BufferOrString\n ).length\n return this[BUFFER].shift() as RType\n }\n\n [FLUSH](noDrain: boolean = false) {\n do {} while (\n this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n this[BUFFER].length\n )\n\n if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n }\n\n [FLUSHCHUNK](chunk: RType) {\n this.emit('data', chunk)\n return this[FLOWING]\n }\n\n /**\n * Pipe all data emitted by this stream into the destination provided.\n *\n * Triggers the flow of data.\n */\n pipe<W extends Minipass.Writable>(dest: W, opts?: PipeOptions): W {\n if (this[DESTROYED]) return dest\n this[DISCARDED] = false\n\n const ended = this[EMITTED_END]\n opts = opts || {}\n if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n else opts.end = opts.end !== false\n opts.proxyErrors = !!opts.proxyErrors\n\n // piping an ended stream ends immediately\n if (ended) {\n if (opts.end) dest.end()\n } else {\n // \"as\" here just ignores the WType, which pipes don't care about,\n // since they're only consuming from us, and writing to the dest\n this[PIPES].push(\n !opts.proxyErrors\n ? new Pipe<RType>(this as Minipass<RType>, dest, opts)\n : new PipeProxyErrors<RType>(this as Minipass<RType>, dest, opts)\n )\n if (this[ASYNC]) defer(() => this[RESUME]())\n else this[RESUME]()\n }\n\n return dest\n }\n\n /**\n * Fully unhook a piped destination stream.\n *\n * If the destination stream was the only consumer of this stream (ie,\n * there are no other piped destinations or `'data'` event listeners)\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n unpipe<W extends Minipass.Writable>(dest: W) {\n const p = this[PIPES].find(p => p.dest === dest)\n if (p) {\n if (this[PIPES].length === 1) {\n if (this[FLOWING] && this[DATALISTENERS] === 0) {\n this[FLOWING] = false\n }\n this[PIPES] = []\n } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n p.unpipe()\n }\n }\n\n /**\n * Alias for {@link Minipass#on}\n */\n addListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n return this.on(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.on`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * - Adding a 'data' event handler will trigger the flow of data\n *\n * - Adding a 'readable' event handler when there is data waiting to be read\n * will cause 'readable' to be emitted immediately.\n *\n * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n * already passed will cause the event to be emitted immediately and all\n * handlers removed.\n *\n * - Adding an 'error' event handler after an error has been emitted will\n * cause the event to be re-emitted immediately with the error previously\n * raised.\n */\n on<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n const ret = super.on(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n if (ev === 'data') {\n this[DISCARDED] = false\n this[DATALISTENERS]++\n if (!this[PIPES].length && !this[FLOWING]) {\n this[RESUME]()\n }\n } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n super.emit('readable')\n } else if (isEndish(ev) && this[EMITTED_END]) {\n super.emit(ev)\n this.removeAllListeners(ev)\n } else if (ev === 'error' && this[EMITTED_ERROR]) {\n const h = handler as (...a: Events['error']) => any\n if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n else h.call(this, this[EMITTED_ERROR])\n }\n return ret\n }\n\n /**\n * Alias for {@link Minipass#off}\n */\n removeListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n return this.off(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.off`\n *\n * If a 'data' event handler is removed, and it was the last consumer\n * (ie, there are no pipe destinations or other 'data' event listeners),\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n off<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n const ret = super.off(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n // if we previously had listeners, and now we don't, and we don't\n // have any pipes, then stop the flow, unless it's been explicitly\n // put in a discarded flowing state via stream.resume().\n if (ev === 'data') {\n this[DATALISTENERS] = this.listeners('data').length\n if (\n this[DATALISTENERS] === 0 &&\n !this[DISCARDED] &&\n !this[PIPES].length\n ) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * Mostly identical to `EventEmitter.removeAllListeners`\n *\n * If all 'data' event handlers are removed, and they were the last consumer\n * (ie, there are no pipe destinations), then the flow of data will stop\n * until there is another consumer or {@link Minipass#resume} is explicitly\n * called.\n */\n removeAllListeners<Event extends keyof Events>(ev?: Event) {\n const ret = super.removeAllListeners(ev as string | symbol | undefined)\n if (ev === 'data' || ev === undefined) {\n this[DATALISTENERS] = 0\n if (!this[DISCARDED] && !this[PIPES].length) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * true if the 'end' event has been emitted\n */\n get emittedEnd() {\n return this[EMITTED_END]\n }\n\n [MAYBE_EMIT_END]() {\n if (\n !this[EMITTING_END] &&\n !this[EMITTED_END] &&\n !this[DESTROYED] &&\n this[BUFFER].length === 0 &&\n this[EOF]\n ) {\n this[EMITTING_END] = true\n this.emit('end')\n this.emit('prefinish')\n this.emit('finish')\n if (this[CLOSED]) this.emit('close')\n this[EMITTING_END] = false\n }\n }\n\n /**\n * Mostly identical to `EventEmitter.emit`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * If the stream has been destroyed, and the event is something other\n * than 'close' or 'error', then `false` is returned and no handlers\n * are called.\n *\n * If the event is 'end', and has already been emitted, then the event\n * is ignored. If the stream is in a paused or non-flowing state, then\n * the event will be deferred until data flow resumes. If the stream is\n * async, then handlers will be called on the next tick rather than\n * immediately.\n *\n * If the event is 'close', and 'end' has not yet been emitted, then\n * the event will be deferred until after 'end' is emitted.\n *\n * If the event is 'error', and an AbortSignal was provided for the stream,\n * and there are no listeners, then the event is ignored, matching the\n * behavior of node core streams in the presense of an AbortSignal.\n *\n * If the event is 'finish' or 'prefinish', then all listeners will be\n * removed after emitting the event, to prevent double-firing.\n */\n emit<Event extends keyof Events>(\n ev: Event,\n ...args: Events[Event]\n ): boolean {\n const data = args[0]\n // error and close are only events allowed after calling destroy()\n if (\n ev !== 'error' &&\n ev !== 'close' &&\n ev !== DESTROYED &&\n this[DESTROYED]\n ) {\n return false\n } else if (ev === 'data') {\n return !this[OBJECTMODE] && !data\n ? false\n : this[ASYNC]\n ? (defer(() => this[EMITDATA](data as RType)), true)\n : this[EMITDATA](data as RType)\n } else if (ev === 'end') {\n return this[EMITEND]()\n } else if (ev === 'close') {\n this[CLOSED] = true\n // don't emit close before 'end' and 'finish'\n if (!this[EMITTED_END] && !this[DESTROYED]) return false\n const ret = super.emit('close')\n this.removeAllListeners('close')\n return ret\n } else if (ev === 'error') {\n this[EMITTED_ERROR] = data\n super.emit(ERROR, data)\n const ret =\n !this[SIGNAL] || this.listeners('error').length\n ? super.emit('error', data)\n : false\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'resume') {\n const ret = super.emit('resume')\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'finish' || ev === 'prefinish') {\n const ret = super.emit(ev)\n this.removeAllListeners(ev)\n return ret\n }\n\n // Some other unknown event\n const ret = super.emit(ev as string, ...args)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITDATA](data: RType) {\n for (const p of this[PIPES]) {\n if (p.dest.write(data as RType) === false) this.pause()\n }\n const ret = this[DISCARDED] ? false : super.emit('data', data)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITEND]() {\n if (this[EMITTED_END]) return false\n\n this[EMITTED_END] = true\n this.readable = false\n return this[ASYNC]\n ? (defer(() => this[EMITEND2]()), true)\n : this[EMITEND2]()\n }\n\n [EMITEND2]() {\n if (this[DECODER]) {\n const data = this[DECODER].end()\n if (data) {\n for (const p of this[PIPES]) {\n p.dest.write(data as RType)\n }\n if (!this[DISCARDED]) super.emit('data', data)\n }\n }\n\n for (const p of this[PIPES]) {\n p.end()\n }\n const ret = super.emit('end')\n this.removeAllListeners('end')\n return ret\n }\n\n /**\n * Return a Promise that resolves to an array of all emitted data once\n * the stream ends.\n */\n async collect(): Promise<RType[] & { dataLength: number }> {\n const buf: RType[] & { dataLength: number } = Object.assign([], {\n dataLength: 0,\n })\n if (!this[OBJECTMODE]) buf.dataLength = 0\n // set the promise first, in case an error is raised\n // by triggering the flow here.\n const p = this.promise()\n this.on('data', c => {\n buf.push(c)\n if (!this[OBJECTMODE])\n buf.dataLength += (c as Minipass.BufferOrString).length\n })\n await p\n return buf\n }\n\n /**\n * Return a Promise that resolves to the concatenation of all emitted data\n * once the stream ends.\n *\n * Not allowed on objectMode streams.\n */\n async concat(): Promise<RType> {\n if (this[OBJECTMODE]) {\n throw new Error('cannot concat in objectMode')\n }\n const buf = await this.collect()\n return (\n this[ENCODING]\n ? buf.join('')\n : Buffer.concat(buf as Buffer[], buf.dataLength)\n ) as RType\n }\n\n /**\n * Return a void Promise that resolves once the stream ends.\n */\n async promise(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n this.on('error', er => reject(er))\n this.on('end', () => resolve())\n })\n }\n\n /**\n * Asynchronous `for await of` iteration.\n *\n * This will continue emitting all chunks until the stream terminates.\n */\n [Symbol.asyncIterator](): AsyncGenerator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = async (): Promise<IteratorReturnResult<void>> => {\n this.pause()\n stopped = true\n return { value: undefined, done: true }\n }\n const next = (): Promise<IteratorResult<RType, void>> => {\n if (stopped) return stop()\n const res = this.read()\n if (res !== null) return Promise.resolve({ done: false, value: res })\n\n if (this[EOF]) return stop()\n\n let resolve!: (res: IteratorResult<RType>) => void\n let reject!: (er: unknown) => void\n const onerr = (er: unknown) => {\n this.off('data', ondata)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n stop()\n reject(er)\n }\n const ondata = (value: RType) => {\n this.off('error', onerr)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n this.pause()\n resolve({ value, done: !!this[EOF] })\n }\n const onend = () => {\n this.off('error', onerr)\n this.off('data', ondata)\n this.off(DESTROYED, ondestroy)\n stop()\n resolve({ done: true, value: undefined })\n }\n const ondestroy = () => onerr(new Error('stream destroyed'))\n return new Promise<IteratorResult<RType>>((res, rej) => {\n reject = rej\n resolve = res\n this.once(DESTROYED, ondestroy)\n this.once('error', onerr)\n this.once('end', onend)\n this.once('data', ondata)\n })\n }\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.asyncIterator]() {\n return this\n },\n }\n }\n\n /**\n * Synchronous `for of` iteration.\n *\n * The iteration will terminate when the internal buffer runs out, even\n * if the stream has not yet terminated.\n */\n [Symbol.iterator](): Generator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = (): IteratorReturnResult<void> => {\n this.pause()\n this.off(ERROR, stop)\n this.off(DESTROYED, stop)\n this.off('end', stop)\n stopped = true\n return { done: true, value: undefined }\n }\n\n const next = (): IteratorResult<RType, void> => {\n if (stopped) return stop()\n const value = this.read()\n return value === null ? stop() : { done: false, value }\n }\n\n this.once('end', stop)\n this.once(ERROR, stop)\n this.once(DESTROYED, stop)\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n /**\n * Destroy a stream, preventing it from being used for any further purpose.\n *\n * If the stream has a `close()` method, then it will be called on\n * destruction.\n *\n * After destruction, any attempt to write data, read data, or emit most\n * events will be ignored.\n *\n * If an error argument is provided, then it will be emitted in an\n * 'error' event.\n */\n destroy(er?: unknown) {\n if (this[DESTROYED]) {\n if (er) this.emit('error', er)\n else this.emit(DESTROYED)\n return this\n }\n\n this[DESTROYED] = true\n this[DISCARDED] = true\n\n // throw away all buffered data, it's never coming out\n this[BUFFER].length = 0\n this[BUFFERLENGTH] = 0\n\n const wc = this as Minipass<RType, WType, Events> & {\n close?: () => void\n }\n if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n if (er) this.emit('error', er)\n // if no error to emit, still reject pending promises\n else this.emit(DESTROYED)\n\n return this\n }\n\n /**\n * Alias for {@link isStream}\n *\n * Former export location, maintained for backwards compatibility.\n *\n * @deprecated\n */\n static get isStream() {\n return isStream\n }\n}\n", "// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n p0: '',\n p1: '',\n p2: string,\n p3: string,\n ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n readonly #patternList: PatternList\n readonly #globList: GlobList\n readonly #index: number\n readonly length: number\n readonly #platform: NodeJS.Platform\n #rest?: Pattern | null\n #globString?: string\n #isDrive?: boolean\n #isUNC?: boolean\n #isAbsolute?: boolean\n #followGlobstar: boolean = true\n\n constructor(\n patternList: MMPattern[],\n globList: string[],\n index: number,\n platform: NodeJS.Platform,\n ) {\n if (!isPatternList(patternList)) {\n throw new TypeError('empty pattern list')\n }\n if (!isGlobList(globList)) {\n throw new TypeError('empty glob list')\n }\n if (globList.length !== patternList.length) {\n throw new TypeError('mismatched pattern list and glob list lengths')\n }\n this.length = patternList.length\n if (index < 0 || index >= this.length) {\n throw new TypeError('index out of range')\n }\n this.#patternList = patternList\n this.#globList = globList\n this.#index = index\n this.#platform = platform\n\n // normalize root entries of absolute patterns on initial creation.\n if (this.#index === 0) {\n // c: => ['c:/']\n // C:/ => ['C:/']\n // C:/x => ['C:/', 'x']\n // //host/share => ['//host/share/']\n // //host/share/ => ['//host/share/']\n // //host/share/x => ['//host/share/', 'x']\n // /etc => ['/', 'etc']\n // / => ['/']\n if (this.isUNC()) {\n // '' / '' / 'host' / 'share'\n const [p0, p1, p2, p3, ...prest] = this.#patternList\n const [g0, g1, g2, g3, ...grest] = this.#globList\n if (prest[0] === '') {\n // ends in /\n prest.shift()\n grest.shift()\n }\n const p = [p0, p1, p2, p3, ''].join('/')\n const g = [g0, g1, g2, g3, ''].join('/')\n this.#patternList = [p, ...prest]\n this.#globList = [g, ...grest]\n this.length = this.#patternList.length\n } else if (this.isDrive() || this.isAbsolute()) {\n const [p1, ...prest] = this.#patternList\n const [g1, ...grest] = this.#globList\n if (prest[0] === '') {\n // ends in /\n prest.shift()\n grest.shift()\n }\n const p = (p1 as string) + '/'\n const g = g1 + '/'\n this.#patternList = [p, ...prest]\n this.#globList = [g, ...grest]\n this.length = this.#patternList.length\n }\n }\n }\n\n /**\n * The first entry in the parsed list of patterns\n */\n pattern(): MMPattern {\n return this.#patternList[this.#index] as MMPattern\n }\n\n /**\n * true of if pattern() returns a string\n */\n isString(): boolean {\n return typeof this.#patternList[this.#index] === 'string'\n }\n /**\n * true of if pattern() returns GLOBSTAR\n */\n isGlobstar(): boolean {\n return this.#patternList[this.#index] === GLOBSTAR\n }\n /**\n * true if pattern() returns a regexp\n */\n isRegExp(): boolean {\n return this.#patternList[this.#index] instanceof RegExp\n }\n\n /**\n * The /-joined set of glob parts that make up this pattern\n */\n globString(): string {\n return (this.#globString =\n this.#globString ||\n (this.#index === 0 ?\n this.isAbsolute() ?\n this.#globList[0] + this.#globList.slice(1).join('/')\n : this.#globList.join('/')\n : this.#globList.slice(this.#index).join('/')))\n }\n\n /**\n * true if there are more pattern parts after this one\n */\n hasMore(): boolean {\n return this.length > this.#index + 1\n }\n\n /**\n * The rest of the pattern after this part, or null if this is the end\n */\n rest(): Pattern | null {\n if (this.#rest !== undefined) return this.#rest\n if (!this.hasMore()) return (this.#rest = null)\n this.#rest = new Pattern(\n this.#patternList,\n this.#globList,\n this.#index + 1,\n this.#platform,\n )\n this.#rest.#isAbsolute = this.#isAbsolute\n this.#rest.#isUNC = this.#isUNC\n this.#rest.#isDrive = this.#isDrive\n return this.#rest\n }\n\n /**\n * true if the pattern represents a //unc/path/ on windows\n */\n isUNC(): boolean {\n const pl = this.#patternList\n return this.#isUNC !== undefined ?\n this.#isUNC\n : (this.#isUNC =\n this.#platform === 'win32' &&\n this.#index === 0 &&\n pl[0] === '' &&\n pl[1] === '' &&\n typeof pl[2] === 'string' &&\n !!pl[2] &&\n typeof pl[3] === 'string' &&\n !!pl[3])\n }\n\n // pattern like C:/...\n // split = ['C:', ...]\n // XXX: would be nice to handle patterns like `c:*` to test the cwd\n // in c: for *, but I don't know of a way to even figure out what that\n // cwd is without actually chdir'ing into it?\n /**\n * True if the pattern starts with a drive letter on Windows\n */\n isDrive(): boolean {\n const pl = this.#patternList\n return this.#isDrive !== undefined ?\n this.#isDrive\n : (this.#isDrive =\n this.#platform === 'win32' &&\n this.#index === 0 &&\n this.length > 1 &&\n typeof pl[0] === 'string' &&\n /^[a-z]:$/i.test(pl[0]))\n }\n\n // pattern = '/' or '/...' or '/x/...'\n // split = ['', ''] or ['', ...] or ['', 'x', ...]\n // Drive and UNC both considered absolute on windows\n /**\n * True if the pattern is rooted on an absolute path\n */\n isAbsolute(): boolean {\n const pl = this.#patternList\n return this.#isAbsolute !== undefined ?\n this.#isAbsolute\n : (this.#isAbsolute =\n (pl[0] === '' && pl.length > 1) ||\n this.isDrive() ||\n this.isUNC())\n }\n\n /**\n * consume the root of the pattern, and return it\n */\n root(): string {\n const p = this.#patternList[0]\n return (\n typeof p === 'string' && this.isAbsolute() && this.#index === 0\n ) ?\n p\n : ''\n }\n\n /**\n * Check to see if the current globstar pattern is allowed to follow\n * a symbolic link.\n */\n checkFollowGlobstar(): boolean {\n return !(\n this.#index === 0 ||\n !this.isGlobstar() ||\n !this.#followGlobstar\n )\n }\n\n /**\n * Mark that the current globstar pattern is following a symbolic link\n */\n markFollowGlobstar(): boolean {\n if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n return false\n this.#followGlobstar = false\n return true\n }\n}\n", "// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n ignored?: (p: Path) => boolean\n childrenIgnored?: (p: Path) => boolean\n add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n relative: Minimatch[]\n relativeChildren: Minimatch[]\n absolute: Minimatch[]\n absoluteChildren: Minimatch[]\n platform: NodeJS.Platform\n mmopts: MinimatchOptions\n\n constructor(\n ignored: string[],\n {\n nobrace,\n nocase,\n noext,\n noglobstar,\n platform = defaultPlatform,\n }: GlobWalkerOpts,\n ) {\n this.relative = []\n this.absolute = []\n this.relativeChildren = []\n this.absoluteChildren = []\n this.platform = platform\n this.mmopts = {\n dot: true,\n nobrace,\n nocase,\n noext,\n noglobstar,\n optimizationLevel: 2,\n platform,\n nocomment: true,\n nonegate: true,\n }\n for (const ign of ignored) this.add(ign)\n }\n\n add(ign: string) {\n // this is a little weird, but it gives us a clean set of optimized\n // minimatch matchers, without getting tripped up if one of them\n // ends in /** inside a brace section, and it's only inefficient at\n // the start of the walk, not along it.\n // It'd be nice if the Pattern class just had a .test() method, but\n // handling globstars is a bit of a pita, and that code already lives\n // in minimatch anyway.\n // Another way would be if maybe Minimatch could take its set/globParts\n // as an option, and then we could at least just use Pattern to test\n // for absolute-ness.\n // Yet another way, Minimatch could take an array of glob strings, and\n // a cwd option, and do the right thing.\n const mm = new Minimatch(ign, this.mmopts)\n for (let i = 0; i < mm.set.length; i++) {\n const parsed = mm.set[i]\n const globParts = mm.globParts[i]\n /* c8 ignore start */\n if (!parsed || !globParts) {\n throw new Error('invalid pattern object')\n }\n // strip off leading ./ portions\n // https://github.com/isaacs/node-glob/issues/570\n while (parsed[0] === '.' && globParts[0] === '.') {\n parsed.shift()\n globParts.shift()\n }\n /* c8 ignore stop */\n const p = new Pattern(parsed, globParts, 0, this.platform)\n const m = new Minimatch(p.globString(), this.mmopts)\n const children = globParts[globParts.length - 1] === '**'\n const absolute = p.isAbsolute()\n if (absolute) this.absolute.push(m)\n else this.relative.push(m)\n if (children) {\n if (absolute) this.absoluteChildren.push(m)\n else this.relativeChildren.push(m)\n }\n }\n }\n\n ignored(p: Path): boolean {\n const fullpath = p.fullpath()\n const fullpaths = `${fullpath}/`\n const relative = p.relative() || '.'\n const relatives = `${relative}/`\n for (const m of this.relative) {\n if (m.match(relative) || m.match(relatives)) return true\n }\n for (const m of this.absolute) {\n if (m.match(fullpath) || m.match(fullpaths)) return true\n }\n return false\n }\n\n childrenIgnored(p: Path): boolean {\n const fullpath = p.fullpath() + '/'\n const relative = (p.relative() || '.') + '/'\n for (const m of this.relativeChildren) {\n if (m.match(relative)) return true\n }\n for (const m of this.absoluteChildren) {\n if (m.match(fullpath)) return true\n }\n return false\n }\n}\n", "// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n store: Map<string, Set<string>>\n constructor(store: Map<string, Set<string>> = new Map()) {\n this.store = store\n }\n copy() {\n return new HasWalkedCache(new Map(this.store))\n }\n hasWalked(target: Path, pattern: Pattern) {\n return this.store.get(target.fullpath())?.has(pattern.globString())\n }\n storeWalked(target: Path, pattern: Pattern) {\n const fullpath = target.fullpath()\n const cached = this.store.get(fullpath)\n if (cached) cached.add(pattern.globString())\n else this.store.set(fullpath, new Set([pattern.globString()]))\n }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n store: Map<Path, number> = new Map()\n add(target: Path, absolute: boolean, ifDir: boolean) {\n const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n const current = this.store.get(target)\n this.store.set(target, current === undefined ? n : n & current)\n }\n // match, absolute, ifdir\n entries(): [Path, boolean, boolean][] {\n return [...this.store.entries()].map(([path, n]) => [\n path,\n !!(n & 2),\n !!(n & 1),\n ])\n }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n store: Map<Path, Pattern[]> = new Map()\n add(target: Path, pattern: Pattern) {\n if (!target.canReaddir()) {\n return\n }\n const subs = this.store.get(target)\n if (subs) {\n if (!subs.find(p => p.globString() === pattern.globString())) {\n subs.push(pattern)\n }\n } else this.store.set(target, [pattern])\n }\n get(target: Path): Pattern[] {\n const subs = this.store.get(target)\n /* c8 ignore start */\n if (!subs) {\n throw new Error('attempting to walk unknown path')\n }\n /* c8 ignore stop */\n return subs\n }\n entries(): [Path, Pattern[]][] {\n return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n }\n keys(): Path[] {\n return [...this.store.keys()].filter(t => t.canReaddir())\n }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n hasWalkedCache: HasWalkedCache\n matches = new MatchRecord()\n subwalks = new SubWalks()\n patterns?: Pattern[]\n follow: boolean\n dot: boolean\n opts: GlobWalkerOpts\n\n constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n this.opts = opts\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.hasWalkedCache =\n hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n }\n\n processPatterns(target: Path, patterns: Pattern[]) {\n this.patterns = patterns\n const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n // map of paths to the magic-starting subwalks they need to walk\n // first item in patterns is the filter\n\n for (let [t, pattern] of processingSet) {\n this.hasWalkedCache.storeWalked(t, pattern)\n\n const root = pattern.root()\n const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n // start absolute patterns at root\n if (root) {\n t = t.resolve(\n root === '/' && this.opts.root !== undefined ?\n this.opts.root\n : root,\n )\n const rest = pattern.rest()\n if (!rest) {\n this.matches.add(t, true, false)\n continue\n } else {\n pattern = rest\n }\n }\n\n if (t.isENOENT()) continue\n\n let p: MMPattern\n let rest: Pattern | null\n let changed = false\n while (\n typeof (p = pattern.pattern()) === 'string' &&\n (rest = pattern.rest())\n ) {\n const c = t.resolve(p)\n t = c\n pattern = rest\n changed = true\n }\n p = pattern.pattern()\n rest = pattern.rest()\n if (changed) {\n if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n this.hasWalkedCache.storeWalked(t, pattern)\n }\n\n // now we have either a final string for a known entry,\n // more strings for an unknown entry,\n // or a pattern starting with magic, mounted on t.\n if (typeof p === 'string') {\n // must not be final entry, otherwise we would have\n // concatenated it earlier.\n const ifDir = p === '..' || p === '' || p === '.'\n this.matches.add(t.resolve(p), absolute, ifDir)\n continue\n } else if (p === GLOBSTAR) {\n // if no rest, match and subwalk pattern\n // if rest, process rest and subwalk pattern\n // if it's a symlink, but we didn't get here by way of a\n // globstar match (meaning it's the first time THIS globstar\n // has traversed a symlink), then we follow it. Otherwise, stop.\n if (\n !t.isSymbolicLink() ||\n this.follow ||\n pattern.checkFollowGlobstar()\n ) {\n this.subwalks.add(t, pattern)\n }\n const rp = rest?.pattern()\n const rrest = rest?.rest()\n if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n // only HAS to be a dir if it ends in **/ or **/.\n // but ending in ** will match files as well.\n this.matches.add(t, absolute, rp === '' || rp === '.')\n } else {\n if (rp === '..') {\n // this would mean you're matching **/.. at the fs root,\n // and no thanks, I'm not gonna test that specific case.\n /* c8 ignore start */\n const tp = t.parent || t\n /* c8 ignore stop */\n if (!rrest) this.matches.add(tp, absolute, true)\n else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n this.subwalks.add(tp, rrest)\n }\n }\n }\n } else if (p instanceof RegExp) {\n this.subwalks.add(t, pattern)\n }\n }\n\n return this\n }\n\n subwalkTargets(): Path[] {\n return this.subwalks.keys()\n }\n\n child() {\n return new Processor(this.opts, this.hasWalkedCache)\n }\n\n // return a new Processor containing the subwalks for each\n // child entry, and a set of matches, and\n // a hasWalkedCache that's a copy of this one\n // then we're going to call\n filterEntries(parent: Path, entries: Path[]): Processor {\n const patterns = this.subwalks.get(parent)\n // put matches and entry walks into the results processor\n const results = this.child()\n for (const e of entries) {\n for (const pattern of patterns) {\n const absolute = pattern.isAbsolute()\n const p = pattern.pattern()\n const rest = pattern.rest()\n if (p === GLOBSTAR) {\n results.testGlobstar(e, pattern, rest, absolute)\n } else if (p instanceof RegExp) {\n results.testRegExp(e, p, rest, absolute)\n } else {\n results.testString(e, p, rest, absolute)\n }\n }\n }\n return results\n }\n\n testGlobstar(\n e: Path,\n pattern: Pattern,\n rest: Pattern | null,\n absolute: boolean,\n ) {\n if (this.dot || !e.name.startsWith('.')) {\n if (!pattern.hasMore()) {\n this.matches.add(e, absolute, false)\n }\n if (e.canReaddir()) {\n // if we're in follow mode or it's not a symlink, just keep\n // testing the same pattern. If there's more after the globstar,\n // then this symlink consumes the globstar. If not, then we can\n // follow at most ONE symlink along the way, so we mark it, which\n // also checks to ensure that it wasn't already marked.\n if (this.follow || !e.isSymbolicLink()) {\n this.subwalks.add(e, pattern)\n } else if (e.isSymbolicLink()) {\n if (rest && pattern.checkFollowGlobstar()) {\n this.subwalks.add(e, rest)\n } else if (pattern.markFollowGlobstar()) {\n this.subwalks.add(e, pattern)\n }\n }\n }\n }\n // if the NEXT thing matches this entry, then also add\n // the rest.\n if (rest) {\n const rp = rest.pattern()\n if (\n typeof rp === 'string' &&\n // dots and empty were handled already\n rp !== '..' &&\n rp !== '' &&\n rp !== '.'\n ) {\n this.testString(e, rp, rest.rest(), absolute)\n } else if (rp === '..') {\n /* c8 ignore start */\n const ep = e.parent || e\n /* c8 ignore stop */\n this.subwalks.add(ep, rest)\n } else if (rp instanceof RegExp) {\n this.testRegExp(e, rp, rest.rest(), absolute)\n }\n }\n }\n\n testRegExp(\n e: Path,\n p: MMRegExp,\n rest: Pattern | null,\n absolute: boolean,\n ) {\n if (!p.test(e.name)) return\n if (!rest) {\n this.matches.add(e, absolute, false)\n } else {\n this.subwalks.add(e, rest)\n }\n }\n\n testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n // should never happen?\n if (!e.isNamed(p)) return\n if (!rest) {\n this.matches.add(e, absolute, false)\n } else {\n this.subwalks.add(e, rest)\n }\n }\n}\n", "/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed? that'd speed\n// things up a lot. Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n absolute?: boolean\n allowWindowsEscape?: boolean\n cwd?: string | URL\n dot?: boolean\n dotRelative?: boolean\n follow?: boolean\n ignore?: string | string[] | IgnoreLike\n mark?: boolean\n matchBase?: boolean\n // Note: maxDepth here means \"maximum actual Path.depth()\",\n // not \"maximum depth beyond cwd\"\n maxDepth?: number\n nobrace?: boolean\n nocase?: boolean\n nodir?: boolean\n noext?: boolean\n noglobstar?: boolean\n platform?: NodeJS.Platform\n posix?: boolean\n realpath?: boolean\n root?: string\n stat?: boolean\n signal?: AbortSignal\n windowsPathsNoEscape?: boolean\n withFileTypes?: boolean\n includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n withFileTypes?: undefined\n}\n\nexport type Result<O extends GlobWalkerOpts> =\n O extends GWOFileTypesTrue ? Path\n : O extends GWOFileTypesFalse ? string\n : O extends GWOFileTypesUnset ? string\n : Path | string\n\nexport type Matches<O extends GlobWalkerOpts> =\n O extends GWOFileTypesTrue ? Set<Path>\n : O extends GWOFileTypesFalse ? Set<string>\n : O extends GWOFileTypesUnset ? Set<string>\n : Set<Path | string>\n\nexport type MatchStream<O extends GlobWalkerOpts> = Minipass<\n Result<O>,\n Result<O>\n>\n\nconst makeIgnore = (\n ignore: string | string[] | IgnoreLike,\n opts: GlobWalkerOpts,\n): IgnoreLike =>\n typeof ignore === 'string' ? new Ignore([ignore], opts)\n : Array.isArray(ignore) ? new Ignore(ignore, opts)\n : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil<O extends GlobWalkerOpts = GlobWalkerOpts> {\n path: Path\n patterns: Pattern[]\n opts: O\n seen: Set<Path> = new Set<Path>()\n paused: boolean = false\n aborted: boolean = false\n #onResume: (() => any)[] = []\n #ignore?: IgnoreLike\n #sep: '\\\\' | '/'\n signal?: AbortSignal\n maxDepth: number\n includeChildMatches: boolean\n\n constructor(patterns: Pattern[], path: Path, opts: O)\n constructor(patterns: Pattern[], path: Path, opts: O) {\n this.patterns = patterns\n this.path = path\n this.opts = opts\n this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n this.includeChildMatches = opts.includeChildMatches !== false\n if (opts.ignore || !this.includeChildMatches) {\n this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n if (\n !this.includeChildMatches &&\n typeof this.#ignore.add !== 'function'\n ) {\n const m = 'cannot ignore child matches, ignore lacks add() method.'\n throw new Error(m)\n }\n }\n // ignore, always set with maxDepth, but it's optional on the\n // GlobOptions type\n /* c8 ignore start */\n this.maxDepth = opts.maxDepth || Infinity\n /* c8 ignore stop */\n if (opts.signal) {\n this.signal = opts.signal\n this.signal.addEventListener('abort', () => {\n this.#onResume.length = 0\n })\n }\n }\n\n #ignored(path: Path): boolean {\n return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n }\n #childrenIgnored(path: Path): boolean {\n return !!this.#ignore?.childrenIgnored?.(path)\n }\n\n // backpressure mechanism\n pause() {\n this.paused = true\n }\n resume() {\n /* c8 ignore start */\n if (this.signal?.aborted) return\n /* c8 ignore stop */\n this.paused = false\n let fn: (() => any) | undefined = undefined\n while (!this.paused && (fn = this.#onResume.shift())) {\n fn()\n }\n }\n onResume(fn: () => any) {\n if (this.signal?.aborted) return\n /* c8 ignore start */\n if (!this.paused) {\n fn()\n } else {\n /* c8 ignore stop */\n this.#onResume.push(fn)\n }\n }\n\n // do the requisite realpath/stat checking, and return the path\n // to add or undefined to filter it out.\n async matchCheck(e: Path, ifDir: boolean): Promise<Path | undefined> {\n if (ifDir && this.opts.nodir) return undefined\n let rpc: Path | undefined\n if (this.opts.realpath) {\n rpc = e.realpathCached() || (await e.realpath())\n if (!rpc) return undefined\n e = rpc\n }\n const needStat = e.isUnknown() || this.opts.stat\n const s = needStat ? await e.lstat() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = await s.realpath()\n /* c8 ignore start */\n if (target && (target.isUnknown() || this.opts.stat)) {\n await target.lstat()\n }\n /* c8 ignore stop */\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n return (\n e &&\n (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n (!ifDir || e.canReaddir()) &&\n (!this.opts.nodir || !e.isDirectory()) &&\n (!this.opts.nodir ||\n !this.opts.follow ||\n !e.isSymbolicLink() ||\n !e.realpathCached()?.isDirectory()) &&\n !this.#ignored(e)\n ) ?\n e\n : undefined\n }\n\n matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n if (ifDir && this.opts.nodir) return undefined\n let rpc: Path | undefined\n if (this.opts.realpath) {\n rpc = e.realpathCached() || e.realpathSync()\n if (!rpc) return undefined\n e = rpc\n }\n const needStat = e.isUnknown() || this.opts.stat\n const s = needStat ? e.lstatSync() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = s.realpathSync()\n if (target && (target?.isUnknown() || this.opts.stat)) {\n target.lstatSync()\n }\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n abstract matchEmit(p: Result<O>): void\n abstract matchEmit(p: string | Path): void\n\n matchFinish(e: Path, absolute: boolean) {\n if (this.#ignored(e)) return\n // we know we have an ignore if this is false, but TS doesn't\n if (!this.includeChildMatches && this.#ignore?.add) {\n const ign = `${e.relativePosix()}/**`\n this.#ignore.add(ign)\n }\n const abs =\n this.opts.absolute === undefined ? absolute : this.opts.absolute\n this.seen.add(e)\n const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n // ok, we have what we need!\n if (this.opts.withFileTypes) {\n this.matchEmit(e)\n } else if (abs) {\n const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n this.matchEmit(abs + mark)\n } else {\n const rel = this.opts.posix ? e.relativePosix() : e.relative()\n const pre =\n this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n '.' + this.#sep\n : ''\n this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n }\n }\n\n async match(e: Path, absolute: boolean, ifDir: boolean): Promise<void> {\n const p = await this.matchCheck(e, ifDir)\n if (p) this.matchFinish(p, absolute)\n }\n\n matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n const p = this.matchCheckSync(e, ifDir)\n if (p) this.matchFinish(p, absolute)\n }\n\n walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n /* c8 ignore start */\n if (this.signal?.aborted) cb()\n /* c8 ignore stop */\n this.walkCB2(target, patterns, new Processor(this.opts), cb)\n }\n\n walkCB2(\n target: Path,\n patterns: Pattern[],\n processor: Processor,\n cb: () => any,\n ) {\n if (this.#childrenIgnored(target)) return cb()\n if (this.signal?.aborted) cb()\n if (this.paused) {\n this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n return\n }\n processor.processPatterns(target, patterns)\n\n // done processing. all of the above is sync, can be abstracted out.\n // subwalks is a map of paths to the entry filters they need\n // matches is a map of paths to [absolute, ifDir] tuples.\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n tasks++\n this.match(m, absolute, ifDir).then(() => next())\n }\n\n for (const t of processor.subwalkTargets()) {\n if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n continue\n }\n tasks++\n const childrenCached = t.readdirCached()\n if (t.calledReaddir())\n this.walkCB3(t, childrenCached, processor, next)\n else {\n t.readdirCB(\n (_, entries) => this.walkCB3(t, entries, processor, next),\n true,\n )\n }\n }\n\n next()\n }\n\n walkCB3(\n target: Path,\n entries: Path[],\n processor: Processor,\n cb: () => any,\n ) {\n processor = processor.filterEntries(target, entries)\n\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n tasks++\n this.match(m, absolute, ifDir).then(() => next())\n }\n for (const [target, patterns] of processor.subwalks.entries()) {\n tasks++\n this.walkCB2(target, patterns, processor.child(), next)\n }\n\n next()\n }\n\n walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n /* c8 ignore start */\n if (this.signal?.aborted) cb()\n /* c8 ignore stop */\n this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n }\n\n walkCB2Sync(\n target: Path,\n patterns: Pattern[],\n processor: Processor,\n cb: () => any,\n ) {\n if (this.#childrenIgnored(target)) return cb()\n if (this.signal?.aborted) cb()\n if (this.paused) {\n this.onResume(() =>\n this.walkCB2Sync(target, patterns, processor, cb),\n )\n return\n }\n processor.processPatterns(target, patterns)\n\n // done processing. all of the above is sync, can be abstracted out.\n // subwalks is a map of paths to the entry filters they need\n // matches is a map of paths to [absolute, ifDir] tuples.\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n this.matchSync(m, absolute, ifDir)\n }\n\n for (const t of processor.subwalkTargets()) {\n if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n continue\n }\n tasks++\n const children = t.readdirSync()\n this.walkCB3Sync(t, children, processor, next)\n }\n\n next()\n }\n\n walkCB3Sync(\n target: Path,\n entries: Path[],\n processor: Processor,\n cb: () => any,\n ) {\n processor = processor.filterEntries(target, entries)\n\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n this.matchSync(m, absolute, ifDir)\n }\n for (const [target, patterns] of processor.subwalks.entries()) {\n tasks++\n this.walkCB2Sync(target, patterns, processor.child(), next)\n }\n\n next()\n }\n}\n\nexport class GlobWalker<\n O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil<O> {\n matches = new Set<Result<O>>()\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n }\n\n matchEmit(e: Result<O>): void {\n this.matches.add(e)\n }\n\n async walk(): Promise<Set<Result<O>>> {\n if (this.signal?.aborted) throw this.signal.reason\n if (this.path.isUnknown()) {\n await this.path.lstat()\n }\n await new Promise((res, rej) => {\n this.walkCB(this.path, this.patterns, () => {\n if (this.signal?.aborted) {\n rej(this.signal.reason)\n } else {\n res(this.matches)\n }\n })\n })\n return this.matches\n }\n\n walkSync(): Set<Result<O>> {\n if (this.signal?.aborted) throw this.signal.reason\n if (this.path.isUnknown()) {\n this.path.lstatSync()\n }\n // nothing for the callback to do, because this never pauses\n this.walkCBSync(this.path, this.patterns, () => {\n if (this.signal?.aborted) throw this.signal.reason\n })\n return this.matches\n }\n}\n\nexport class GlobStream<\n O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil<O> {\n results: Minipass<Result<O>, Result<O>>\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n this.results = new Minipass<Result<O>, Result<O>>({\n signal: this.signal,\n objectMode: true,\n })\n this.results.on('drain', () => this.resume())\n this.results.on('resume', () => this.resume())\n }\n\n matchEmit(e: Result<O>): void {\n this.results.write(e)\n if (!this.results.flowing) this.pause()\n }\n\n stream(): MatchStream<O> {\n const target = this.path\n if (target.isUnknown()) {\n target.lstat().then(() => {\n this.walkCB(target, this.patterns, () => this.results.end())\n })\n } else {\n this.walkCB(target, this.patterns, () => this.results.end())\n }\n return this.results\n }\n\n streamSync(): MatchStream<O> {\n if (this.path.isUnknown()) {\n this.path.lstatSync()\n }\n this.walkCBSync(this.path, this.patterns, () => this.results.end())\n return this.results\n }\n}\n", "import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n pattern: string | string[],\n options: GlobOptions = {},\n): boolean => {\n if (!Array.isArray(pattern)) {\n pattern = [pattern]\n }\n for (const p of pattern) {\n if (new Minimatch(p, options).hasMagic()) return true\n }\n return false\n}\n", "import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n FSOption,\n Path,\n WalkOptions,\n WalkOptionsWithFileTypesTrue,\n WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass<Path, Path>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass<string, string>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesUnset,\n): Minipass<string, string>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass<Path, Path> | Minipass<string, string>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass<string, string>\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass<Path, Path>\nexport function globStream(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass<string, string>\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass<Path, Path> | Minipass<string, string>\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise<string[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Promise<Path[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Promise<string[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions,\n): Promise<Path[] | string[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator<string, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Generator<Path, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Generator<string, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions,\n): Generator<Path, void, void> | Generator<string, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator<string, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator<Path, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator<string, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions,\n): AsyncGenerator<Path, void, void> | AsyncGenerator<string, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n stream: globStreamSync,\n iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n glob: glob_,\n globSync,\n sync,\n globStream,\n stream,\n globStreamSync,\n streamSync,\n globIterate,\n iterate,\n globIterateSync,\n iterateSync,\n Glob,\n hasMagic,\n escape,\n unescape,\n})\nglob.glob = glob\n", "import { setMaxListeners } from 'node:events'\n\n/**\n * Options that define the graph and how to traverse it\n */\nexport interface RunnerOptions<Node, Result = void> {\n /** Array of one or more entry nodes. */\n graph: [node: Node, ...rest: Node[]]\n\n /** get the dependencies of a given node */\n getDeps: (node: Node) => Node[] | Promise<Node[]>\n\n /** action to take on each node */\n visit: (\n node: Node,\n signal: AbortSignal,\n path: Node[],\n depResults: DepResults<Node, Result>,\n ) => Result | Promise<Result>\n\n /**\n * Called when a cycle is encountered.\n * Throw in this method to enforce a DAG graph.\n * If left undefined, then cycles are silently ignored and skipped.\n *\n * `node` parameter is the dependency that is being skipped.\n *\n * `cycle` is the route from the dependent back to itself via\n * the parent.\n *\n * `path` is the path to the dependent who wanted this dep to be\n * loaded.\n */\n onCycle?: (\n node: Node,\n cycle: Node[],\n path: Node[],\n ) => void | Promise<void>\n\n /**\n * Set to `false` to continue operations even if errors occur.\n * If set to false, then an AggregateError will be raised on failure\n * containing all failures (even if only one). If true, then a normal\n * Error will be raised on failure.\n *\n * @default true\n */\n failFast?: boolean\n\n /** a signal that will trigger the graph traversal to end prematurely */\n signal?: AbortSignal\n}\n\nexport type DepResults<Node, Result> = Map<Node, Result | undefined>\n\n/**\n * Options that can define a synchronous graph traversal.\n *\n * Note that if the visit() method is async, then the *promises themselves*\n * will be used as the `Result` type, which is likely not what you want!\n */\nexport interface RunnerOptionsSync<Node, Result = void>\n extends RunnerOptions<Node, Result> {\n /** Get a set of dependency nodes synchronously */\n getDeps: (node: Node) => Node[]\n\n /** Visit a node synchronously */\n visit: (\n node: Node,\n signal: AbortSignal,\n path: Node[],\n depResults: DepResults<Node, Result>,\n ) => Result\n\n /** Handle cycles synchronously */\n onCycle?: (node: Node, cycle: Node[], path: Node[]) => void\n}\n\n/** A map of nodes to their PromiseSettledResult value */\nexport type SettledMap<Node, Result = void> = Map<\n Node,\n PromiseSettledResult<Result>\n>\n\n/** Any function or class. Used for Error.captureStackTrace */\nexport type Callable =\n | Function\n | ((...a: unknown[]) => unknown)\n | {\n new (...a: unknown[]): unknown\n }\n\n/** Base class of Runner and RunnerSync */\nexport abstract class RunnerBase<\n /** The type of thing to be found in this graph */\n Node,\n /** Type returned by the visit() method */\n Result = void,\n Sync extends boolean = false,\n O extends Sync extends true ? RunnerOptionsSync<Node, Result>\n : RunnerOptions<Node, Result> = Sync extends true ?\n RunnerOptionsSync<Node, Result>\n : RunnerOptions<Node, Result>,\n> {\n /** The map of traversal results */\n readonly results: Map<Node, Result> = new Map()\n\n /** The map of PromiseSettledResult objects */\n readonly settled: SettledMap<Node, Result> = new Map()\n\n /** Set of dependents (direct & transitive) on each node */\n readonly dependents: Map<Node, Set<Node>> = new Map()\n\n /** Set of direct dependents on each node */\n readonly directDependents: Map<Node, Set<Node>> = new Map()\n\n /** Options provided to constructor */\n readonly options: O\n\n /**\n * AbortController used internally to abort the process.\n *\n * This is internal only, and triggering it at the wrong time may cause\n * undefined and unsupported behavior. Do not use!\n *\n * Instead, if you want to be able to abort the walk at any time, provide\n * your own AbortSignal in the opions.\n *\n * @internal\n */\n readonly abortController: AbortController\n\n /** True if we are in failFast mode */\n readonly failFast: boolean\n\n /** Rejections and Errors encountered in the traversal */\n readonly errors: unknown[] = []\n\n /**\n * Function defining the callsite where the traversal was initiated,\n * used for Error.captureStackTrace.\n */\n readonly from: Callable\n\n constructor(options: O, from?: Callable) {\n const ac = new AbortController()\n this.from = from ?? this.constructor\n this.abortController = ac\n setMaxListeners(Infinity, ac.signal)\n this.options = options\n if (!options.graph.length) {\n const er = new Error('no nodes provided to graph traversal', {\n cause: {\n found: options.graph,\n wanted: '[first: Node, ...rest: Node[]]',\n },\n })\n Error.captureStackTrace(er, from)\n throw er\n }\n this.failFast = options.failFast !== false\n const { signal } = options\n if (signal !== undefined) {\n signal.addEventListener('abort', reason => ac.abort(reason), {\n once: true,\n signal: ac.signal,\n })\n }\n }\n\n /** Initiate the graph traversal, resolving/returning when complete */\n abstract run(): Sync extends true ? void : Promise<void>\n\n /** Get the dependencies of a given node */\n abstract getDeps(\n n: Node,\n ): Sync extends true ? Node[] : Promise<Node[]>\n\n /** Visit a node. Calls `options.visit()` */\n abstract visit(\n n: Node,\n path: Node[],\n depResults: DepResults<Node, Result>,\n ): Sync extends true ? Result : Promise<Result>\n\n /**\n * Calls the `options.onCycle()` method when a cycle is detected.\n */\n abstract onCycle(\n n: Node,\n cycle: Node[],\n path: Node[],\n ): Sync extends true ? void : void | Promise<void>\n\n /**\n * For a Node `n` that depends directly or transitively on Node `d`, find the\n * shortest known dependency path from `n` to `d`. This is done by walking\n * backwards breadth-first up the dependency relations from `d` until `n` is\n * found.\n *\n * If no known path can be found, then `undefined` is returned. Otherwise,\n * a path array is returned that starts with `n` and ends with `d`.\n *\n * Note that self-referential links are never considered, since they're\n * by definition cyclical.\n */\n route(n: Node, d: Node): undefined | [n: Node, ...path: Node[]] {\n const dependents = this.dependents.get(d)\n if (!dependents?.has(n)) return undefined\n const directDependents = this.directDependents.get(d)\n /* c8 ignore next */\n if (!directDependents) return undefined\n if (directDependents.has(n)) {\n return [n, d]\n }\n const queue: [n: Node, ...r: Node[]][] = [\n ...directDependents,\n ].map(dd => [dd, d])\n let step: undefined | [n: Node, ...r: Node[]] = undefined\n while (undefined !== (step = queue.shift())) {\n /* c8 ignore next */\n if (!dependents.has(step[0])) continue\n if (step[0] === n) {\n return step\n }\n const ddd = this.directDependents.get(step[0])\n if (ddd) {\n for (const d of ddd) {\n queue.push([d, ...step])\n }\n }\n }\n }\n\n /**\n * If the dependency from `n -> d` at the specified path would\n * cause a cycle, then call the onCycle method and return true.\n * Oherwise, assign the appropriate entries in the dependency\n * tracking sets, and return false.\n *\n * @internal\n */\n cycleCheck(n: Node, path: Node[], d: Node) {\n /* c8 ignore next */\n const dependents = this.dependents.get(n) ?? new Set()\n this.dependents.set(n, dependents)\n const isCycle = dependents.has(d)\n if (isCycle) {\n const cycle = this.route(d, n)\n /* c8 ignore start - impossible */\n if (!cycle) {\n throw new Error('cycle detected, but cycle route not found')\n }\n /* c8 ignore stop */\n cycle.unshift(n)\n this.onCycle(d, cycle, path)\n return true\n }\n\n const depDD = this.directDependents.get(d) ?? new Set()\n this.directDependents.set(d, depDD)\n depDD.add(n)\n\n const depDependents = this.dependents.get(d) ?? new Set()\n this.dependents.set(d, depDependents)\n for (const n of dependents) {\n depDependents.add(n)\n }\n depDependents.add(n)\n return false\n }\n\n /**\n * Method that handles errors raised by visits.\n *\n * @internal\n */\n handleError(er: unknown, n: Node, path: Node[]) {\n this.errors.push(er)\n this.settled.set(n, {\n status: 'rejected',\n reason: er,\n })\n if (this.failFast) {\n this.abortController.abort(er)\n const e = new Error('failed graph traversal', {\n cause: {\n node: n,\n path,\n cause: er as Error,\n },\n })\n Error.captureStackTrace(e, this.from)\n throw e\n }\n }\n\n /**\n * Method that handles successful visit results\n *\n * @internal\n */\n handleValue(value: Result, n: Node) {\n this.results.set(n, value)\n this.settled.set(n, {\n status: 'fulfilled',\n value,\n })\n }\n}\n\n/** Asynchronous graph runner */\nexport class Runner<Node, Result> extends RunnerBase<\n Node,\n Result,\n false,\n RunnerOptions<Node, Result>\n> {\n /** Map of nodes currently awaiting completion */\n readonly running = new Map<Node, Promise<void>>()\n\n async getDeps(n: Node) {\n /* c8 ignore next */\n if (this.abortController.signal.aborted) return []\n const deps = await this.options.getDeps(n);\n for (const d of deps) {\n const dependents = this.dependents.get(d) ?? new Set()\n this.dependents.set(d, dependents)\n dependents.add(n)\n const depDD = this.directDependents.get(d) ?? new Set()\n this.directDependents.set(d, depDD)\n depDD.add(n)\n }\n return deps\n }\n\n async visit(\n n: Node,\n path: Node[],\n depResults: DepResults<Node, Result>,\n ) {\n const { signal } = this.abortController\n return this.options.visit(n, signal, path, depResults)\n }\n\n async onCycle(n: Node, cycle: Node[], path: Node[]) {\n /* c8 ignore next */\n if (this.abortController.signal.aborted) return\n await this.options.onCycle?.(n, cycle, path)\n }\n\n async #walk(n: Node, path: Node[]) {\n const r = this.running.get(n)\n /* c8 ignore next */\n if (r) return r\n /* c8 ignore start */\n if (this.settled.get(n)) return\n /* c8 ignore stop */\n const p = this.#step(n, path).then(\n () => {\n this.running.delete(n)\n },\n /* c8 ignore start - handled deeper in the chain */\n er => {\n this.running.delete(n)\n throw er\n },\n /* c8 ignore stop */\n )\n this.running.set(n, p)\n return p\n }\n\n async #step(n: Node, path: Node[]) {\n const dependents = this.dependents.get(n) ?? new Set()\n this.dependents.set(n, dependents)\n\n const deps = await this.getDeps(n)\n const awaiting: Promise<void>[] = []\n const depPath = [...path, n]\n\n for (const d of deps) {\n /* c8 ignore next */\n if (this.abortController.signal.aborted) return\n // self-link, skip\n if (d === n) continue\n if (this.cycleCheck(n, depPath, d)) continue\n /* c8 ignore next */\n if (this.settled.get(d)) continue\n awaiting.push(this.running.get(d) ?? this.#walk(d, depPath))\n }\n\n /* c8 ignore next */\n if (this.abortController.signal.aborted) return\n await Promise.all(awaiting)\n if (this.abortController.signal.aborted) return\n const depRes = new Map<Node, Result | undefined>(\n deps.map(d => [d, this.results.get(d)]),\n )\n try {\n this.handleValue(await this.visit(n, path, depRes), n)\n } catch (er) {\n this.handleError(er, n, path)\n }\n }\n\n async run(): Promise<void> {\n const promises: Promise<void>[] = []\n for (const n of this.options.graph) {\n promises.push(this.#walk(n, []))\n }\n await Promise.all(promises)\n }\n}\n\n/** Synchronous graph runner */\nexport class RunnerSync<Node, Result> extends RunnerBase<\n Node,\n Result,\n true,\n RunnerOptionsSync<Node, Result>\n> {\n getDeps(n: Node) {\n if (this.abortController.signal.aborted) return []\n return this.options.getDeps(n)\n }\n\n visit(n: Node, path: Node[], depResults: DepResults<Node, Result>) {\n const { signal } = this.abortController\n return this.options.visit(n, signal, path, depResults)\n }\n\n onCycle(n: Node, cycle: Node[], path: Node[]) {\n /* c8 ignore next */\n if (this.abortController.signal.aborted) return\n this.options.onCycle?.(n, cycle, path)\n }\n\n #walk(n: Node, path: Node[]) {\n /* c8 ignore start */\n if (this.settled.get(n)) return\n /* c8 ignore stop */\n this.#step(n, path)\n }\n\n #step(n: Node, path: Node[]) {\n const dependents = this.dependents.get(n) ?? new Set()\n this.dependents.set(n, dependents)\n\n const deps = this.getDeps(n)\n const depPath = [...path, n]\n for (const d of deps) {\n if (this.abortController.signal.aborted) return\n /* c8 ignore next */\n if (d === n) continue\n if (this.cycleCheck(n, depPath, d)) continue\n if (!this.settled.get(d)) this.#walk(d, depPath)\n }\n\n if (this.abortController.signal.aborted) return\n const depRes = new Map<Node, Result | undefined>(\n deps.map(d => [d, this.results.get(d)]),\n )\n try {\n this.handleValue(this.visit(n, path, depRes), n)\n } catch (er) {\n this.handleError(er, n, path)\n }\n }\n\n run(): Map<Node, Result> {\n for (const n of this.options.graph) {\n this.#walk(n, [])\n }\n return this.results\n }\n}\n\n/**\n * Asynchronous graph traversal method\n *\n * If `failFast:false` is set in the options, then an AggregateError\n * will be raised if there were any failures. Otherwise, a normal Error\n * is raised on failure.\n */\nexport const graphRun = async <Node, Result>(\n options: RunnerOptions<Node, Result>,\n): Promise<Map<Node, Result>> => {\n const runner = new Runner(options, graphRun)\n await runner.run()\n if (runner.errors.length) {\n const e = new AggregateError(\n runner.errors,\n 'failed graph traversal',\n )\n Error.captureStackTrace(e, graphRun)\n throw e\n }\n return runner.results\n}\n\n/**\n * Synchronous graph traversal method\n *\n * If `failFast:false` is set in the options, then an AggregateError\n * will be thrown if there were any failures. Otherwise, a normal Error\n * is thrown on failure.\n */\nexport const graphRunSync = <Node, Result>(\n options: RunnerOptionsSync<Node, Result>,\n): Map<Node, Result> => {\n const runner = new RunnerSync(options, graphRunSync)\n runner.run()\n if (runner.errors.length) {\n const e = new AggregateError(\n runner.errors,\n 'failed graph traversal',\n )\n Error.captureStackTrace(e, graphRunSync)\n throw e\n }\n return runner.results\n}\n\n/**\n * Asynchronous graph traversal, capturing all error/result\n * statuses.\n */\nexport const allSettled = async <Node, Result>(\n options: RunnerOptions<Node, Result>,\n): Promise<SettledMap<Node, Result>> => {\n const runner = new Runner(\n { ...options, failFast: false },\n allSettled,\n )\n await runner.run()\n return runner.settled\n}\n\n/**\n * Synchronous graph traversal, capturing all error/result\n * statuses.\n */\nexport const allSettledSync = <Node, Result>(\n options: RunnerOptionsSync<Node, Result>,\n): SettledMap<Node, Result> => {\n const runner = new RunnerSync(\n { ...options, failFast: false },\n allSettledSync,\n )\n runner.run()\n return runner.settled\n}\n\n/**\n * Asynchronous graph traversal, returning the first successful visit.\n * If all visits fail, then an AggregateError is raised with all errors\n * encountered.\n */\nexport const any = async <Node, Result>(\n options: RunnerOptions<Node, Result>,\n): Promise<Result> => {\n const ac = new AbortController()\n let result!: Result\n let found: boolean = false\n const runner = new Runner<Node, Result>(\n {\n ...options,\n failFast: false,\n signal: ac.signal,\n visit: async (node, signal, path, depResults) => {\n try {\n result = await options.visit(node, signal, path, depResults)\n found = true\n ac.abort('found')\n } finally {\n return result\n }\n },\n },\n any,\n )\n await runner.run()\n if (!found) {\n const e = new AggregateError(\n runner.errors,\n 'failed graph traversal',\n )\n Error.captureStackTrace(e, any)\n throw e\n }\n return result\n}\n\n/**\n * Synchronous graph traversal, returning the first successful visit.\n * If all visits fail, then an AggregateError is thrown with all errors\n * encountered.\n */\nexport const anySync = <Node, Result>(\n options: RunnerOptionsSync<Node, Result>,\n): Result => {\n const ac = new AbortController()\n let result!: Result\n let found: boolean = false\n const runner = new RunnerSync<Node, Result>(\n {\n ...options,\n failFast: false,\n signal: ac.signal,\n visit: (node, signal, path, depResults) => {\n try {\n result = options.visit(node, signal, path, depResults)\n found = true\n ac.abort('found')\n } finally {\n return result\n }\n },\n },\n anySync,\n )\n runner.run()\n if (!found) {\n const e = new AggregateError(\n runner.errors,\n 'failed graph traversal',\n )\n Error.captureStackTrace(e, anySync)\n throw e\n }\n return result\n}\n\n/**\n * Asynchronous graph traversal, resolving or rejecting when the first visit\n * resolves or rejects.\n */\nexport const race = async <Node, Result>(\n options: RunnerOptions<Node, Result>,\n): Promise<Result> => {\n const ac = new AbortController()\n let result!: Result\n const runner = new Runner<Node, Result>(\n {\n ...options,\n failFast: true,\n signal: ac.signal,\n visit: async (node, signal, path, depResults) => {\n try {\n result = await options.visit(node, signal, path, depResults)\n ac.abort('found')\n } finally {\n return result\n }\n },\n },\n race,\n )\n await runner.run()\n return result\n}\n\n/**\n * Synchronous graph traversal, returning or throwing when the first visit\n * is completed.\n */\nexport const raceSync = <Node, Result>(\n options: RunnerOptionsSync<Node, Result>,\n): Result => {\n const ac = new AbortController()\n let result!: Result\n const runner = new RunnerSync<Node, Result>(\n {\n ...options,\n failFast: true,\n signal: ac.signal,\n visit: (node, signal, path, depResults) => {\n try {\n result = options.visit(node, signal, path, depResults)\n ac.abort('found')\n } finally {\n return result\n }\n },\n },\n race,\n )\n runner.run()\n return result\n}\n", "// Handling emoji is hard.\n// because many/most emoji are 2-character width, give or take,\n// but have bizarre line-height and spacing in most fonts, replace emojis\n// in the html string with an absolute-position wrapper and 2 spaces for\n// them to float above.\n// *Some* emojis are 1 character wide, so this ends up being a bit wrong\n// sometimes, but better too much space than have things be cut off or\n// overlapping, which looks broken.\n// Due to limitations of the emoji-regex, some complex emojis will render\n// as their constituent parts rather than the conjoined glyph.\n\nimport emojiRegex from 'emoji-regex'\nconst EMOJI_RE = emojiRegex()\nconst replaceWide = (c: string) => replaceNarrow(c) + ' '\nconst replaceNarrow = (c: string) =>\n `<span style=\"position:absolute;line-height:1;margin-top:0.3ex\">${c}</span> `\nexport const fixEmoji = (s: string): string => {\n return s\n .replace(/[\\u2500-\\u25FF]/g, replaceNarrow)\n .replace(EMOJI_RE, replaceWide)\n}\n", "let COLOR = '#eeeeee'\nlet BACKGROUND = '#222222'\n\nexport const defaultColor = (s?: string) => {\n if (s) COLOR = s\n return COLOR\n}\n\nexport const defaultBackground = (s?: string) => {\n if (s) BACKGROUND = s\n return BACKGROUND\n}\n", "export const hexToRgb = (c: string): [number, number, number] => {\n c = c.replace(/^#/, '')\n if (c.length === 3) {\n const r = c.charAt(0)\n const g = c.charAt(1)\n const b = c.charAt(2)\n return hexToRgb(`${r}${r}${g}${g}${b}${b}`)\n }\n if (c.length !== 6) {\n throw new Error('invalid hex string: ' + c)\n }\n const r = parseInt(c.substring(0, 2), 16)\n const g = parseInt(c.substring(2, 4), 16)\n const b = parseInt(c.substring(4, 6), 16)\n if (r !== r || g !== g || b !== b) {\n throw new Error('invalid hex string: ' + c)\n }\n return [r, g, b]\n}\n", "export const rgbToHex = ([r, g, b]: [number, number, number]): string => {\n if (r !== r || g !== g || b !== b) {\n throw new Error('invalid RGB: ' + [r, g, b].join(','))\n }\n return `#${\n Math.max(0, Math.min(r, 255)).toString(16).padStart(2, '0') +\n Math.max(0, Math.min(g, 255)).toString(16).padStart(2, '0') +\n Math.max(0, Math.min(b, 255)).toString(16).padStart(2, '0')\n }`\n}\n", "import { hexToRgb } from './hex-to-rgb.js'\nimport { rgbToHex } from './rgb-to-hex.js'\n\nconst DIMLEVEL = 0.75\nexport const dimColor = (c: string): string =>\n rgbToHex(\n hexToRgb(c).map(c => Math.floor(c * DIMLEVEL)) as [\n number,\n number,\n number,\n ],\n )\n", "export const htmlEscape = (s: string): string =>\n s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n", "export type Names =\n | 'black'\n | 'red'\n | 'green'\n | 'yellow'\n | 'blue'\n | 'magenta'\n | 'cyan'\n | 'white'\n\nexport type NameCodes = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7\n\nexport const nameCodes: { [name in Names]: NameCodes } = {\n black: 0b000,\n red: 0b001,\n green: 0b010,\n yellow: 0b011,\n blue: 0b100,\n magenta: 0b101,\n cyan: 0b110,\n white: 0b111,\n}\n\nexport const codeNames: ReadonlyArray<Names> = [\n 'black',\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'white',\n] as const\n\nexport const namedColors: Omit<string[], number> & {\n 0: string\n 1: string\n 2: string\n 3: string\n 4: string\n 5: string\n 6: string\n 7: string\n} = [\n '#000000',\n '#ff0000',\n '#00a000',\n '#e0e000',\n '#0040e0',\n '#e000e0',\n '#00b0b0',\n '#e0e0e0',\n]\n\nexport const namedBrightColors: Omit<string[], number> & {\n 0: string\n 1: string\n 2: string\n 3: string\n 4: string\n 5: string\n 6: string\n 7: string\n} = [\n '#404040',\n '#ff3030',\n '#00ff00',\n '#ffff00',\n '#0080ff',\n '#ff33ff',\n '#00ffff',\n '#ffffff',\n]\n", "import { NameCodes, namedBrightColors, namedColors } from './named.js'\n\nconst hex = (n: number) => n.toString(16).padStart(2, '0')\n\nconst colors = [\n ...(function* () {\n for (let red = 0; red < 6; red++) {\n for (let green = 0; green < 6; green++) {\n for (let blue = 0; blue < 6; blue++) {\n const r = red ? red * 40 + 55 : 0\n const g = green ? green * 40 + 55 : 0\n const b = blue ? blue * 40 + 55 : 0\n yield `#${hex(r)}${hex(g)}${hex(b)}`\n }\n }\n }\n })(),\n]\n\nconst grays = [\n ...(function* () {\n for (let gray = 0; gray < 24; gray++) {\n const g = gray * 10 + 8\n yield `#${hex(g).repeat(3)}`\n }\n })(),\n]\n\nexport const xtermCode = (n: number) => {\n if (n < 8) return namedColors[n as NameCodes]\n if (n < 16) return namedBrightColors[(n - 8) as NameCodes]\n if (n < Math.pow(6, 3)) return colors[n - 16] as string\n if (n < 256) return grays[n - 232] as string\n}\n", "// this object is deposited into the style buffer in the Terminal\n// every time a character is written to the character buffer.\n// Handles all parsing of \\x1b[...m ANSI codes and conversion to CSS.\nimport { defaultBackground, defaultColor } from './default-colors.js'\nimport { dimColor } from './dim-color.js'\nimport { hexToRgb } from './hex-to-rgb.js'\nimport { htmlEscape } from './html-escape.js'\nimport {\n NameCodes,\n nameCodes,\n namedBrightColors,\n namedColors,\n Names,\n} from './named.js'\nimport { rgbToHex } from './rgb-to-hex.js'\nimport { xtermCode } from './xterm.js'\n\nconst ALL_END = '0'\nconst BG_END = '49'\nconst BG_START = '48'\nconst BOLD_END = '22'\nconst BOLD_START = '1'\nconst DIM_START = '2'\n// DIM_END is the same as BOLD_END because it's really \"font-weight:normal\"\n// In practice, dim modifies color, not font-weight, since modern screens\n// have colors, and most terminal fonts don't distinguish font weights other\n// than normal and bold.\nconst FG_END = '39'\nconst FG_START = '38'\nconst INV_END = '27'\nconst INV_START = '7'\nconst ITALIC_END = '23'\nconst ITALIC_START = '3'\nconst OVER_END = '55'\nconst OVER_START = '53'\nconst STRIKE_END = '29'\nconst STRIKE_START = '9'\nconst UNDERLINE_END = '24'\nconst UNDERLINE_START = '4'\nconst UNDERLINE_START_2 = '21' // WHYYYYYY\n\nconst NAMED_RE = /^(3|4|9|10)([0-7])$/\nconst NAMED_FG = '3'\nconst NAMED_BG = '4'\nconst NAMED_FG_BRIGHT = '9'\nconst NAMED_BG_BRIGHT = '10'\n\n// verifies that the style code is something that a Style object can handle,\n// and captures the first code and its parameter.\n// first code: $1\n// href: $2\n// styles: $3\nconst VALID_CODE = () =>\n new RegExp(\n '\\x1b\\\\]8;;' + // OSC hyperlink\n '(.*?)' + // href\n '(?:\\x1b|\\x07)' + // ST\n '|' +\n '\\x1b\\\\[' + // style codes\n '([0-9]*(?:;[0-9]*)*)' + // code numbers\n 'm', // end style codes\n 'g',\n )\n\ntype ParsedValidCode =\n | null\n | (RegExpExecArray &\n ([string, string, undefined] | [string, undefined, string]))\n\n/**\n * The properties that can be set on Style objects\n */\nexport type StyleProps = {\n /** may be either a hex string, or a named color */\n background?: string\n bold?: boolean\n /** may be either a hex string, or a named color */\n color?: string\n dim?: boolean\n inverse?: boolean\n italic?: boolean\n overline?: boolean\n strike?: boolean\n underline?: boolean\n /** hyperlink target, must be a valid url or `''` */\n href?: string\n}\n\nconst RESET_STYLE: StyleProps = {\n background: '',\n bold: false,\n color: '',\n dim: false,\n inverse: false,\n italic: false,\n overline: false,\n strike: false,\n underline: false,\n}\nconst RESET_PROPS: StyleProps = {\n ...RESET_STYLE,\n href: '',\n}\n\nconst namedColor = (c: string, bright = false): string => {\n if (!c) return c\n c = c.toLowerCase()\n const code = nameCodes[c as Names]\n if (typeof code === 'number') {\n return (bright ? namedBrightColors[code] : namedColors[code]) as string\n }\n if (c.includes('bright') && !bright) {\n return namedColor(c.replace(/bright/g, ''), true)\n }\n return rgbToHex(hexToRgb(c))\n}\n\nconst SEEN = new Map<string, Style>()\n\n/**\n * An immutable representation of an ANSI style. Used by Terminal and Block\n * to represent the styles in use for text to be printed.\n * If a Style object is created with the same properties as a\n * formerly seen Style object, the same object will be returned.\n *\n * For example:\n *\n * ```js\n * const a = new Style({ bold: true })\n * const b = new Style({ bold: true })\n * assert.equal(a, b) // passes\n * ```\n *\n * This optimization cuts down considerably on object creation,\n * because a Style is created for each styled character written to\n * the Terminal buffer. It also means that Style objects can be\n * compared directly with `===` to test for equivalence.\n */\nexport class Style {\n #css?: string\n\n #background!: string\n #bold!: boolean\n #color!: string\n #dim!: boolean\n #inverse!: boolean\n #italic!: boolean\n #overline!: boolean\n #strike!: boolean\n #underline!: boolean\n #ansi!: string\n #href!: string\n\n constructor(styles: StyleProps | string) {\n const {\n background = '',\n bold = false,\n color = '',\n dim = false,\n inverse = false,\n italic = false,\n overline = false,\n strike = false,\n underline = false,\n href = '',\n } = typeof styles !== 'string' ? styles : Style.ansiProperties(styles)\n\n const ansi = Style.propertiesAnsi({\n background,\n bold,\n color,\n dim,\n inverse,\n italic,\n overline,\n strike,\n underline,\n href,\n })\n\n // same style = same object\n const seen = SEEN.get(ansi)\n if (seen) return seen\n SEEN.set(ansi, this)\n\n this.#ansi = ansi\n this.#background = namedColor(background)\n this.#bold = bold\n this.#color = namedColor(color)\n this.#dim = dim\n this.#inverse = inverse\n this.#italic = italic\n this.#overline = overline\n this.#strike = strike\n this.#underline = underline\n try {\n this.#href = href && String(new URL(href))\n } catch {\n this.#href = ''\n }\n }\n\n /**\n * True if this style is a full reset of all properties.\n */\n get isReset() {\n return this === RESET\n }\n\n /** corresponding ANSI code sequence for this style */\n get ansi() {\n return this.#ansi\n }\n\n /** Convert a set of properties to an ANSI style code */\n static propertiesAnsi(styles: StyleProps): string {\n const {\n background,\n bold,\n color,\n dim,\n inverse,\n italic,\n overline,\n strike,\n underline,\n href = '',\n } = styles\n const codes = [\n // always do a reset at the start\n 0,\n ...(color ? [FG_START, 2, ...hexToRgb(namedColor(color))] : []),\n ...(background ?\n [BG_START, 2, ...hexToRgb(namedColor(background))]\n : []),\n ...(bold ? [BOLD_START] : []),\n ...(dim ? [DIM_START] : []),\n ...(inverse ? [INV_START] : []),\n ...(italic ? [ITALIC_START] : []),\n ...(overline ? [OVER_START] : []),\n ...(strike ? [STRIKE_START] : []),\n ...(underline ? [UNDERLINE_START] : []),\n ]\n return `\\x1b]8;;${href}\\x1b\\\\\\x1b[${codes.join(';')}m`\n }\n\n /**\n * If the input string is a sequence of *only* ANSI style and\n * OSC href codes, returns the array of codes and their parameters.\n * Otherwise, returns false.\n */\n static validStyleCodes(s: string): null | [string, string][] {\n let c = 0\n let m: ParsedValidCode\n const results: [string, string][] = []\n const vc = VALID_CODE()\n while ((m = vc.exec(s) as ParsedValidCode)) {\n if (c !== m.index) {\n return null\n }\n c += m[0].length\n results.push([m[0], m[1] ?? m[2]])\n }\n return results.length === 0 ? null : results\n }\n\n /** a Style object that resets all properties */\n static get RESET() {\n return RESET\n }\n\n /** Convert an ANSI style code to a set of properties */\n static ansiProperties(code: string): StyleProps {\n const codes = Style.validStyleCodes(code)\n if (!codes) {\n throw new Error('invalid ansi style code: ' + JSON.stringify(code))\n }\n const style: StyleProps = {}\n for (const code of codes) {\n if (code[0].startsWith('\\x1b]8;;')) {\n style.href = code[1]\n continue\n }\n const codes = code[1].split(';')\n for (let i = 0; i < codes.length; i++) {\n const c = codes[i] as string\n switch (c) {\n case '':\n case ALL_END:\n Object.assign(style, RESET_STYLE)\n continue\n case BOLD_END:\n style.bold = false\n style.dim = false\n continue\n case ITALIC_END:\n style.italic = false\n continue\n case STRIKE_END:\n style.strike = false\n continue\n case OVER_END:\n style.overline = false\n continue\n case UNDERLINE_END:\n style.underline = false\n continue\n case INV_END:\n style.inverse = false\n continue\n case FG_END:\n style.color = ''\n continue\n case BG_END:\n style.background = ''\n continue\n case BOLD_START:\n style.bold = true\n continue\n case INV_START:\n style.inverse = true\n continue\n case UNDERLINE_START:\n case UNDERLINE_START_2:\n style.underline = true\n continue\n case DIM_START:\n style.dim = true\n continue\n case OVER_START:\n style.overline = true\n continue\n case ITALIC_START:\n style.italic = true\n continue\n case STRIKE_START:\n style.strike = true\n continue\n case BG_START:\n case FG_START: {\n // 2 for rgb, 5 for xterm\n const next = codes[i + 1]\n const prop = c == FG_START ? 'color' : 'background'\n switch (next) {\n case '5':\n const xt = codes[i + 2]\n const code = xt && xtermCode(parseInt(xt, 10))\n if (code) {\n i += 2\n style[prop] = code\n }\n continue\n case '2':\n const sr = codes[i + 2]\n const sg = codes[i + 3]\n const sb = codes[i + 4]\n if (sr && sg && sb) {\n const r = parseInt(sr, 10)\n const g = parseInt(sg, 10)\n const b = parseInt(sb, 10)\n const hex = rgbToHex([r, g, b])\n if (\n r <= 255 &&\n r >= 0 &&\n g <= 255 &&\n g >= 0 &&\n b <= 255 &&\n b >= 0\n ) {\n i += 4\n style[prop] = hex\n }\n }\n }\n continue\n }\n // named color/bg\n default: {\n const m = c.match(NAMED_RE) as\n | null\n | (RegExpMatchArray & [string, string, string])\n if (!m) continue\n const color = parseInt(m[2], 10) as NameCodes\n switch (m[1]) {\n case NAMED_FG:\n style.color = namedColors[color]\n continue\n case NAMED_BG:\n style.background = namedColors[color]\n continue\n case NAMED_FG_BRIGHT:\n style.color = namedBrightColors[color]\n continue\n case NAMED_BG_BRIGHT:\n style.background = namedBrightColors[color]\n continue\n }\n }\n }\n }\n }\n return style\n }\n\n /**\n * Return a new Style with this one plus the updated properties.\n *\n * If a string is provided, must be a valid set of style and OSC hyperlink\n * ANSI code, though unrecognized parameters within that code will be ignored\n * rather than throwing an error.\n */\n update(properties: StyleProps | string): Style {\n const {\n background = this.#background,\n bold = this.#bold,\n color = this.#color,\n dim = this.#dim,\n inverse = this.#inverse,\n italic = this.#italic,\n overline = this.#overline,\n strike = this.#strike,\n underline = this.#underline,\n href = this.#href,\n } =\n typeof properties === 'string' ?\n Style.ansiProperties(properties)\n : properties\n\n return (\n background === this.#background &&\n bold === this.#bold &&\n color === this.#color &&\n dim === this.#dim &&\n inverse === this.#inverse &&\n italic === this.#italic &&\n overline === this.#overline &&\n strike === this.#strike &&\n underline === this.#underline &&\n href === this.#href\n ) ?\n this\n : new Style({\n background,\n bold,\n color,\n dim,\n inverse,\n italic,\n overline,\n strike,\n underline,\n href,\n })\n }\n\n [Symbol.for('nodejs.util.inspect.custom')](\n _: any,\n { colors }: { colors: boolean } = { colors: false },\n ) {\n const { ansi } = this\n return `Style { ${colors ? ansi : ''}${ansi.replace(/\\x1b/g, '^[')}${\n colors ? '\\x1b]8;;\\x1b\\\\\\x1b[m' : ''\n } }`\n }\n\n /**\n * Wrap the input string in the appropriate HTML for this style\n */\n wrap(s: string) {\n const css = this.toString()\n const href = this.#href\n if (!css && !href) return htmlEscape(s)\n const tag = href ? `a` : 'span'\n return `<${tag}${href ? ` href=\"${href}\"` : ''}${\n css ? ` style=\"${css}\"` : ''\n }>${htmlEscape(s)}</${tag}>`\n }\n\n /**\n * Return just the CSS for the styles. Href is not relevant.\n */\n toString() {\n if (this.#css) return this.#css\n let color = this.#inverse ? this.#background : this.#color\n let background = this.#inverse ? this.#color : this.#background\n if (this.#inverse) {\n color ||= defaultBackground()\n background ||= defaultColor()\n }\n // dim text is a different color, unless the background is the same\n // color, and set to something other than default. !?!? hwyyyyyyy idgi\n if (this.#dim && !(color && color === background)) {\n color = dimColor(color || defaultColor())\n }\n const textDecoration = [\n ...(this.#underline ? ['underline'] : []),\n ...(this.#overline ? ['overline'] : []),\n ...(this.#strike ? ['line-through'] : []),\n ].join(' ')\n\n return (this.#css = [\n ...(textDecoration ? [`text-decoration:${textDecoration}`] : []),\n ...(this.#bold ? ['font-weight:bold']\n : this.#dim ? ['font-weight:100']\n : []),\n ...(this.#italic ? ['font-style:italic'] : []),\n ...(color ? [`color:${color}`] : []),\n ...(background ? [`background:${background}`] : []),\n ].join(';'))\n }\n}\n\nconst RESET = new Style(RESET_PROPS)\n", "import { InspectOptions } from 'util'\nimport { fixEmoji } from './fix-emoji.js'\nimport { Style } from './style.js'\n\n/**\n * A representation of a run of text in a given style\n */\nexport class Block {\n #style?: Style\n #text: string\n\n constructor(text: string, style?: Style) {\n this.#text = text\n this.#style = style\n }\n\n [Symbol.for('nodejs.util.inspect.custom')](\n _: any,\n opts: InspectOptions,\n inspect: typeof import('util').inspect,\n ) {\n return `Block {${\n this.#style ? ' ' + inspect(this.#style, opts) : ''\n } ${inspect(this.#text, opts)} }`\n }\n\n /** return the block as a styled `<span>` tag */\n toString() {\n return this.#toString(false)\n }\n\n /** a representation of the block as an ANSI styled string */\n get ansi() {\n return this.#toString(true)\n }\n\n #toString(ansi: boolean) {\n return (\n !this.#text ? ''\n : ansi ? (this.#style ?? Style.RESET).ansi + this.#text\n : fixEmoji((this.#style ?? Style.RESET).wrap(this.#text))\n )\n }\n\n /** append text to the block */\n write(c: string) {\n this.#text += c\n return this\n }\n\n /** the raw text that will be written */\n get text() {\n return this.#text\n }\n\n /** the Style used by this block */\n get style() {\n return this.#style\n }\n}\n", "import { InspectOptions } from 'util'\nimport { Block } from './block.js'\nimport { defaultBackground, defaultColor } from './default-colors.js'\nimport { Style, StyleProps } from './style.js'\nconst CODES_RE =\n /^\\u001b\\[([0-9]*[A-GJKSTg]|([0-9;]*)m|([0-9]*;?[0-9]*)?[Hf]|\\?[0-9]+[hl])/\n\nconst OSC_RE = /^\\u001b\\](.*?)(?:\\u0007|\\u001b\\\\)/\nconst OSC_TITLE = '0;'\nconst OSC_HREF = '8;;'\n\n/**\n * A representation of a virtual \"terminal\" where we write out the character\n * and style information as we parse through the ANSI encoded stream.\n *\n * Important: this is *not* a full-fledged Stream class. You can write to it\n * multiple times, and it will update appropriately, but it does zero buffering\n * or input validation, so writing a partial ANSI code sequence will result in\n * mochibake in the output.\n *\n * The virtual terminal is an infinitely high and wide screen, with no\n * scrollback buffer. So, when `scrollDown(n)` is called (either explicitly, or\n * with a `\\x1b[<n>S` ANSI code), `n` lines are removed from the top of the\n * \"screen\". When `scrollUp(n)` is called (explicitly or via a `\\x1b[<n>T` ANSI\n * code), `n` _empty_ lines are added to the top of the screen; the lines lost\n * to a previous `scrollDown` action are not restored when scrolling up.\n *\n * Also, actions that move the cursor down or to the right, which would on a\n * normal physical terminal be limited to the height/width of the terminal, are\n * unbounded. For example, on an actual terminal, `echo $'\\x1b[1000Bhello'`\n * will print \"hello\" at the bottom of the screen (unless your screen happens\n * to be more than 1000 lines high); in this virtual terminal, it will create\n * 1000 empty lines.\n *\n * Most of the methods (other than `toString()` of course) return `this`,\n * allowing for things like this:\n *\n * ```js\n * console.log(\n * new Terminal()\n * .setStyle({ color: '#ff0000' })\n * .write('hello, ')\n * .down(1)\n * .setStyle({ inverse: true })\n * .write('world!').ansi\n * )\n * ```\n */\nexport class Terminal {\n // note: 0-indexed, but all the ansi codes are 1-indexed\n #cursor: [number, number] = [0, 0]\n // character data\n #text: string[][] = []\n // the style used to write it\n #style: (Style | undefined)[][] = []\n // the current style we use to paint characters to our \"screen\"\n #brush: Style = new Style({})\n\n #title: string = ''\n #blocks?: Block[]\n\n constructor(input?: string) {\n if (input) this.write(input)\n }\n\n /**\n * Set the style that the terminal will use for text writes.\n *\n * If a string, must be a valid `\\x1b[...m` ANSI style code.\n *\n * The styles provided will be appended onto the current style in use, just\n * as they would be by a real terminal if the relevant ANSI code is\n * encountered.\n */\n setStyle(style: string | StyleProps): Terminal {\n this.#brush = this.#brush.update(style)\n return this\n }\n\n /** Move the cursor up `n` lines, stopping at the top. */\n up(n: number): Terminal {\n this.#cursor[0] = Math.max(this.#cursor[0] - n, 0)\n return this\n }\n\n /** Move the cursor down `n` lines, without limit. */\n down(n: number): Terminal {\n // move down\n // in real life, this would be maxed to the size of the screen buffer,\n // but since this virtual terminal is an infinitely high and wide screen,\n // we just let it create new lines.\n this.#cursor[0] += n\n return this\n }\n\n /**\n * Prepend `n` empty lines at the start of the buffer, effectively moving the\n * cursor up as a result.\n */\n scrollUp(n: number): Terminal {\n // add n lines at the start of the buffer\n // leaves the cursor at the same index it was at before, effectively\n // moving it up as a result.\n for (let i = 0; i < n; i++) {\n this.#text.unshift([])\n this.#style.unshift([])\n }\n return this\n }\n\n /**\n * Remove `n` lines from the start of the buffer, effectively moving the\n * cursor down as a result.\n */\n scrollDown(n: number): Terminal {\n // remove lines from the top of the buffer, effectively moving\n // the cursor down as a result.\n // TODO: Maybe it would be good to keep a scrollback buffer,\n // and move lines into/out of there on scroll?\n for (let i = 0; i < n; i++) {\n this.#text.shift()\n this.#style.shift()\n }\n return this\n }\n\n /** Move the cursor forward `n` columns, without limit. */\n forward(n: number): Terminal {\n this.#cursor[1] += n\n return this\n }\n\n /** Move the cursor back `n` columns, stopping at the first column. */\n back(n: number): Terminal {\n this.#cursor[1] = Math.max(0, this.#cursor[1] - n)\n return this\n }\n\n /** Move to the start of the `n`-th next line. */\n nextLine(n: number): Terminal {\n this.#cursor[0] += n\n this.#cursor[1] = 0\n return this\n }\n\n /**\n * Move to the start of the `n`-th previous line, stopping at the top of the\n * screen.\n */\n prevLine(n: number): Terminal {\n this.#cursor[0] = Math.max(0, this.#cursor[0] - n)\n this.#cursor[1] = 0\n return this\n }\n\n /**\n * Move to the `n`-th column (1-indexed), limited by the left-most column.\n */\n horizontalPosition(n: number): Terminal {\n this.#cursor[1] = Math.max(0, n - 1)\n return this\n }\n\n /**\n * Move to the 1-indexed row and column specified, limited by the top and\n * left sides of the screen.\n */\n position(row: number, col: number): Terminal {\n this.#cursor[0] = Math.max(row - 1, 0)\n this.#cursor[1] = Math.max(col - 1, 0)\n return this\n }\n\n /**\n * Delete all printed data from the screen.\n *\n * Note that this is used for both `\\x1b[2J` _and_ `\\x1b[3J`, because there\n * is no scrollback buffer in this virtual terminal.\n */\n eraseScreen(): Terminal {\n // erase entire screen\n this.#text.length = 0\n this.#style.length = 0\n return this\n }\n\n /** Delete all printed data from the cursor to the end of the screen. */\n eraseScreenToEnd(): Terminal {\n // erase from cursor to end of screen\n this.#text.splice(this.#cursor[0] + 1)\n this.#style.splice(this.#cursor[0] + 1)\n this.eraseLineToEnd()\n return this\n }\n\n /** Delete all printed data from the top of the screen to the cursor. */\n eraseScreenFromStart(): Terminal {\n // erase from beginning of screen to cursor\n let i\n for (i = 0; i < this.#cursor[0]; i++) {\n const line = this.#text[i]\n const sline = this.#style[i]\n /* c8 ignore start */\n if (!line || !sline) continue\n /* c8 ignore stop */\n line.length = 0\n sline.length = 0\n }\n this.eraseLineFromStart()\n return this\n }\n\n /** Delete the contents of the current line. */\n eraseLine(): Terminal {\n const line = this.#text[this.#cursor[0]]\n const sline = this.#style[this.#cursor[0]]\n if (!line || !sline) return this\n line.length = 0\n sline.length = 0\n return this\n }\n\n /**\n * Delete printed data from the cursor to the end of the current line.\n */\n eraseLineToEnd(): Terminal {\n const line = this.#text[this.#cursor[0]]\n const sline = this.#style[this.#cursor[0]]\n if (!line || !sline) return this\n // from cursor to end of line\n line.splice(this.#cursor[1])\n sline.splice(this.#cursor[1])\n return this\n }\n\n /**\n * Delete printed data from the start of the current line to the cursor.\n */\n eraseLineFromStart(): Terminal {\n if (this.#cursor[1] === 0) return this.eraseLine()\n /* c8 ignore start */\n const line = this.#text[this.#cursor[0]]\n const sline = this.#style[this.#cursor[0]]\n /* c8 ignore stop */\n if (!line || !sline) return this\n for (let i = 0; i < this.#cursor[1]; i++) {\n line[i] = ' '\n sline[i] = undefined\n }\n return this\n }\n\n /**\n * Parse the ANSI encoded string provided, updating the internal character\n * and style buffers appropriately.\n */\n write(input: string): Terminal {\n this.#blocks = undefined\n // remove title-setting sequences\n for (let c = 0; c < input.length; ) {\n while (input.charAt(c) === '\\x1b') {\n // codes that don't use the OSC or CSI code\n switch (input.charAt(c + 1)) {\n case 'B':\n this.horizontalPosition(1)\n c += 2\n continue\n case 'H':\n // tab stops, not supported, ignore\n c += 2\n continue\n case 'D':\n this.scrollDown(1)\n c += 2\n continue\n case 'M':\n this.scrollUp(1)\n c += 2\n continue\n }\n\n // cursor/screen motion/erase commands\n const code = input.substring(c).match(CODES_RE) as\n | null\n | (RegExpMatchArray & [string, string])\n if (code) {\n c += code[0].length\n if (code[1].endsWith('m')) {\n // style code\n this.setStyle(code[0])\n continue\n } else {\n const x = code[1].charAt(code[1].length - 1)\n if (x === 'H' || x === 'f') {\n // cursor position\n const [n, m] = code[1].replace(/[Hf]$/, '').split(';')\n const row = Math.max(1, parseInt(n || '1', 10))\n const col = Math.max(1, parseInt(m || '1', 10))\n this.position(row, col)\n continue\n }\n // these all have an optional 1-indexed parameter\n // that defaults to 1, except J and K which default to 0\n const p = code[1].match(/^([0-9]+)/)?.[1]\n const n = parseInt(p || '1', 10)\n const z = parseInt(p || '0', 10)\n switch (x) {\n case 'A':\n this.up(n)\n continue\n case 'T':\n this.scrollUp(n)\n continue\n case 'B':\n this.down(n)\n continue\n case 'S':\n this.scrollDown(n)\n continue\n case 'C':\n this.forward(n)\n continue\n case 'D':\n this.back(n)\n continue\n case 'E':\n this.nextLine(n)\n continue\n case 'F':\n this.prevLine(n)\n continue\n case 'G':\n this.horizontalPosition(n)\n continue\n case 'J': {\n switch (z) {\n case 0:\n this.eraseScreenToEnd()\n continue\n case 1:\n this.eraseScreenFromStart()\n continue\n case 2:\n case 3:\n this.eraseScreen()\n continue\n }\n continue\n }\n case 'K': {\n switch (z) {\n case 0:\n this.eraseLineToEnd()\n continue\n case 1:\n this.eraseLineFromStart()\n continue\n case 2:\n this.eraseLine()\n continue\n }\n continue\n }\n }\n }\n continue\n }\n\n // check for OSC (title and hyperlinks)\n const osc = input.substring(c).match(OSC_RE) as\n | null\n | (RegExpMatchArray & [string, string])\n if (osc?.index === 0) {\n c += osc[0].length\n const cmd = osc[1]\n if (cmd.startsWith(OSC_TITLE)) {\n this.setTitle(cmd.substring(OSC_TITLE.length))\n continue\n }\n if (cmd.startsWith(OSC_HREF)) {\n this.setStyle({ href: cmd.substring(OSC_HREF.length) })\n continue\n }\n continue\n }\n\n // some other code we don't support, treat as text\n break\n }\n\n // end parsing ansi codes, might have walked off the input\n if (c >= input.length) break\n\n const ch = input.charAt(c++)\n\n if (ch === '\\r') {\n this.horizontalPosition(1)\n continue\n }\n if (ch === '\\n') {\n this.nextLine(1)\n continue\n }\n\n // write a character\n // if we are off the painted terminal, paint up to that point\n while (this.#text.length < this.#cursor[0]) {\n this.#text.push([])\n this.#style.push([])\n }\n const sline = this.#style[this.#cursor[0]] || []\n const line = this.#text[this.#cursor[0]] || []\n while (line.length < this.#cursor[1]) {\n line.push(' ')\n }\n while (sline.length < this.#cursor[1]) {\n sline.push(undefined)\n }\n line[this.#cursor[1]] = ch\n sline[this.#cursor[1]] =\n this.#brush.isReset ? undefined : this.#brush\n this.#style[this.#cursor[0]] = sline\n this.#text[this.#cursor[0]] = line\n this.forward(1)\n }\n return this\n }\n\n /**\n * Called when an OSC code of `\\x1b]0;...\\x1b\\` is encountered.\n *\n * Sets the `title` attribute on the root `<pre>` in html output,\n * and creates a corresponding OSC title sequence in the ansi output.\n */\n setTitle(s: string) {\n this.#title = s\n return this\n }\n\n /** the raw unstyled text of each line */\n get text() {\n return this.#text.map(l => l.join(''))\n }\n\n [Symbol.for('nodejs.util.inspect.custom')](\n _: any,\n opts: InspectOptions,\n inspect: typeof import('util').inspect,\n ) {\n const ins = inspect(\n {\n cursor: this.#cursor,\n brush: this.#brush,\n text: this.#text.map(l => l.join('')),\n blocks: this.blocks,\n },\n opts,\n )\n return `Terminal ${ins}`\n }\n\n /**\n * Output the results of the style and character buffers as ANSI\n * styled text. This effectively normalizes all color codes to explicit\n * RGB values and resolves all cursor motions and other control codes,\n * and styling runs of identical styles with a single code.\n */\n get ansi() {\n return this.#toString(true)\n }\n\n /**\n * Output the results of the style and character buffers as a `<pre>`\n * tag with `<span>` elements setting effective styles.\n */\n toString() {\n return this.#toString(false)\n }\n\n /**\n * An array of `Block` objects each representing a string of text with a\n * given style.\n */\n get blocks(): Block[] {\n if (this.#blocks) return this.#blocks\n let cur: Block = new Block('')\n const blocks: Block[] = [cur]\n for (let i = 0; i < this.#text.length; i++) {\n /* c8 ignore start */\n const line = this.#text[i] || []\n const sline = this.#style[i] || []\n /* c8 ignore stop */\n for (let j = 0; j < line.length; j++) {\n const st = sline[j]\n // will always be set\n /* c8 ignore start */\n const ch = line[j] || ''\n /* c8 ignore stop */\n if (st === cur.style) cur.write(ch)\n else blocks.push((cur = new Block(ch, st)))\n }\n // append a \\n only if we're not at the end\n if (this.#text[i + 1]) cur.write('\\n')\n }\n return (this.#blocks = blocks.filter(b => !!b.text))\n }\n\n #toString(ansi: boolean) {\n // turn into an array of [string, Style?], concatenating runs\n // of the same style into a single string.\n const contents = this.blocks\n .map(b => (ansi ? b.ansi : b.toString()))\n .join('')\n if (ansi) {\n const title = this.#title ? `\\x1b]0;${this.#title}\\x1b\\\\` : ''\n return title + contents + '\\x1b[m'\n }\n const css = Object.entries({\n color: defaultColor(),\n background: defaultBackground(),\n position: 'relative',\n })\n .map(kv => kv.join(':'))\n .join(';')\n const preStyle = `style=\"${css}\"`\n const preTitle = this.#title ? ` title=\"${this.#title}\"` : ''\n return `<pre ${preStyle}${preTitle}>${contents}</pre>`\n }\n}\n", "export * from './block.js'\nexport * from './default-colors.js'\nexport * from './named.js'\nexport * from './xterm.js'\nexport * from './style.js'\nexport * from './terminal.js'\nexport * from './theme.js'\nimport { Terminal } from './terminal.js'\n\n/**\n * Convert a string of ANSI text into an HTML `<pre>` tag.\n */\nexport const ansiToPre = (input: string) => String(new Terminal(input))\n\n/**\n * Convert a string of ANSI text into a string of ANSI text with normalized\n * RGB color codes and all cursor control sequences resolved.\n */\nexport const ansiToAnsi = (input: string) => new Terminal(input).ansi\n", "const ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi16 = (offset = 0) => code => `\\u001B[${code + offset}m`;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nconst styles = {\n\tmodifier: {\n\t\treset: [0, 0],\n\t\t// 21 isn't widely supported and 22 does the same thing\n\t\tbold: [1, 22],\n\t\tdim: [2, 22],\n\t\titalic: [3, 23],\n\t\tunderline: [4, 24],\n\t\toverline: [53, 55],\n\t\tinverse: [7, 27],\n\t\thidden: [8, 28],\n\t\tstrikethrough: [9, 29],\n\t},\n\tcolor: {\n\t\tblack: [30, 39],\n\t\tred: [31, 39],\n\t\tgreen: [32, 39],\n\t\tyellow: [33, 39],\n\t\tblue: [34, 39],\n\t\tmagenta: [35, 39],\n\t\tcyan: [36, 39],\n\t\twhite: [37, 39],\n\n\t\t// Bright color\n\t\tblackBright: [90, 39],\n\t\tgray: [90, 39], // Alias of `blackBright`\n\t\tgrey: [90, 39], // Alias of `blackBright`\n\t\tredBright: [91, 39],\n\t\tgreenBright: [92, 39],\n\t\tyellowBright: [93, 39],\n\t\tblueBright: [94, 39],\n\t\tmagentaBright: [95, 39],\n\t\tcyanBright: [96, 39],\n\t\twhiteBright: [97, 39],\n\t},\n\tbgColor: {\n\t\tbgBlack: [40, 49],\n\t\tbgRed: [41, 49],\n\t\tbgGreen: [42, 49],\n\t\tbgYellow: [43, 49],\n\t\tbgBlue: [44, 49],\n\t\tbgMagenta: [45, 49],\n\t\tbgCyan: [46, 49],\n\t\tbgWhite: [47, 49],\n\n\t\t// Bright color\n\t\tbgBlackBright: [100, 49],\n\t\tbgGray: [100, 49], // Alias of `bgBlackBright`\n\t\tbgGrey: [100, 49], // Alias of `bgBlackBright`\n\t\tbgRedBright: [101, 49],\n\t\tbgGreenBright: [102, 49],\n\t\tbgYellowBright: [103, 49],\n\t\tbgBlueBright: [104, 49],\n\t\tbgMagentaBright: [105, 49],\n\t\tbgCyanBright: [106, 49],\n\t\tbgWhiteBright: [107, 49],\n\t},\n};\n\nexport const modifierNames = Object.keys(styles.modifier);\nexport const foregroundColorNames = Object.keys(styles.color);\nexport const backgroundColorNames = Object.keys(styles.bgColor);\nexport const colorNames = [...foregroundColorNames, ...backgroundColorNames];\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`,\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false,\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = wrapAnsi16();\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue(red, green, blue) {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16\n\t\t\t\t\t+ (36 * Math.round(red / 255 * 5))\n\t\t\t\t\t+ (6 * Math.round(green / 255 * 5))\n\t\t\t\t\t+ Math.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue(hex) {\n\t\t\t\tconst matches = /[a-f\\d]{6}|[a-f\\d]{3}/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet [colorString] = matches;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = [...colorString].map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t/* eslint-disable no-bitwise */\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF,\n\t\t\t\t\t/* eslint-enable no-bitwise */\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t\tansi256ToAnsi: {\n\t\t\tvalue(code) {\n\t\t\t\tif (code < 8) {\n\t\t\t\t\treturn 30 + code;\n\t\t\t\t}\n\n\t\t\t\tif (code < 16) {\n\t\t\t\t\treturn 90 + (code - 8);\n\t\t\t\t}\n\n\t\t\t\tlet red;\n\t\t\t\tlet green;\n\t\t\t\tlet blue;\n\n\t\t\t\tif (code >= 232) {\n\t\t\t\t\tred = (((code - 232) * 10) + 8) / 255;\n\t\t\t\t\tgreen = red;\n\t\t\t\t\tblue = red;\n\t\t\t\t} else {\n\t\t\t\t\tcode -= 16;\n\n\t\t\t\t\tconst remainder = code % 36;\n\n\t\t\t\t\tred = Math.floor(code / 36) / 5;\n\t\t\t\t\tgreen = Math.floor(remainder / 6) / 5;\n\t\t\t\t\tblue = (remainder % 6) / 5;\n\t\t\t\t}\n\n\t\t\t\tconst value = Math.max(red, green, blue) * 2;\n\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn 30;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t\tlet result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));\n\n\t\t\t\tif (value === 2) {\n\t\t\t\t\tresult += 60;\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\trgbToAnsi: {\n\t\t\tvalue: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi: {\n\t\t\tvalue: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t});\n\n\treturn styles;\n}\n\nconst ansiStyles = assembleStyles();\n\nexport default ansiStyles;\n", "import process from 'node:process';\nimport os from 'node:os';\nimport tty from 'node:tty';\n\n// From: https://github.com/sindresorhus/has-flag/blob/main/index.js\n/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {\nfunction hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n}\n\nconst {env} = process;\n\nlet flagForceColor;\nif (\n\thasFlag('no-color')\n\t|| hasFlag('no-colors')\n\t|| hasFlag('color=false')\n\t|| hasFlag('color=never')\n) {\n\tflagForceColor = 0;\n} else if (\n\thasFlag('color')\n\t|| hasFlag('colors')\n\t|| hasFlag('color=true')\n\t|| hasFlag('color=always')\n) {\n\tflagForceColor = 1;\n}\n\nfunction envForceColor() {\n\tif ('FORCE_COLOR' in env) {\n\t\tif (env.FORCE_COLOR === 'true') {\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (env.FORCE_COLOR === 'false') {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3,\n\t};\n}\n\nfunction _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {\n\tconst noFlagForceColor = envForceColor();\n\tif (noFlagForceColor !== undefined) {\n\t\tflagForceColor = noFlagForceColor;\n\t}\n\n\tconst forceColor = sniffFlags ? flagForceColor : noFlagForceColor;\n\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (sniffFlags) {\n\t\tif (hasFlag('color=16m')\n\t\t\t|| hasFlag('color=full')\n\t\t\t|| hasFlag('color=truecolor')) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (hasFlag('color=256')) {\n\t\t\treturn 2;\n\t\t}\n\t}\n\n\t// Check for Azure DevOps pipelines.\n\t// Has to be above the `!streamIsTTY` check.\n\tif ('TF_BUILD' in env && 'AGENT_NAME' in env) {\n\t\treturn 1;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10\n\t\t\t&& Number(osRelease[2]) >= 10_586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14_931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif ('GITHUB_ACTIONS' in env || 'GITEA_ACTIONS' in env) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-kitty') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app': {\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\t}\n\n\t\t\tcase 'Apple_Terminal': {\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nexport function createSupportsColor(stream, options = {}) {\n\tconst level = _supportsColor(stream, {\n\t\tstreamIsTTY: stream && stream.isTTY,\n\t\t...options,\n\t});\n\n\treturn translateLevel(level);\n}\n\nconst supportsColor = {\n\tstdout: createSupportsColor({isTTY: tty.isatty(1)}),\n\tstderr: createSupportsColor({isTTY: tty.isatty(2)}),\n};\n\nexport default supportsColor;\n", "// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.\nexport function stringReplaceAll(string, substring, replacer) {\n\tlet index = string.indexOf(substring);\n\tif (index === -1) {\n\t\treturn string;\n\t}\n\n\tconst substringLength = substring.length;\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\treturnValue += string.slice(endIndex, index) + substring + replacer;\n\t\tendIndex = index + substringLength;\n\t\tindex = string.indexOf(substring, endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n\nexport function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\tconst gotCR = string[index - 1] === '\\r';\n\t\treturnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\\r\\n' : '\\n') + postfix;\n\t\tendIndex = index + 1;\n\t\tindex = string.indexOf('\\n', endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n", "import ansiStyles from '#ansi-styles';\nimport supportsColor from '#supports-color';\nimport { // eslint-disable-line import/order\n\tstringReplaceAll,\n\tstringEncaseCRLFWithFirstIndex,\n} from './utilities.js';\n\nconst {stdout: stdoutColor, stderr: stderrColor} = supportsColor;\n\nconst GENERATOR = Symbol('GENERATOR');\nconst STYLER = Symbol('STYLER');\nconst IS_EMPTY = Symbol('IS_EMPTY');\n\n// `supportsColor.level` \u2192 `ansiStyles.color[name]` mapping\nconst levelMapping = [\n\t'ansi',\n\t'ansi',\n\t'ansi256',\n\t'ansi16m',\n];\n\nconst styles = Object.create(null);\n\nconst applyOptions = (object, options = {}) => {\n\tif (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {\n\t\tthrow new Error('The `level` option should be an integer from 0 to 3');\n\t}\n\n\t// Detect level if not set manually\n\tconst colorLevel = stdoutColor ? stdoutColor.level : 0;\n\tobject.level = options.level === undefined ? colorLevel : options.level;\n};\n\nexport class Chalk {\n\tconstructor(options) {\n\t\t// eslint-disable-next-line no-constructor-return\n\t\treturn chalkFactory(options);\n\t}\n}\n\nconst chalkFactory = options => {\n\tconst chalk = (...strings) => strings.join(' ');\n\tapplyOptions(chalk, options);\n\n\tObject.setPrototypeOf(chalk, createChalk.prototype);\n\n\treturn chalk;\n};\n\nfunction createChalk(options) {\n\treturn chalkFactory(options);\n}\n\nObject.setPrototypeOf(createChalk.prototype, Function.prototype);\n\nfor (const [styleName, style] of Object.entries(ansiStyles)) {\n\tstyles[styleName] = {\n\t\tget() {\n\t\t\tconst builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);\n\t\t\tObject.defineProperty(this, styleName, {value: builder});\n\t\t\treturn builder;\n\t\t},\n\t};\n}\n\nstyles.visible = {\n\tget() {\n\t\tconst builder = createBuilder(this, this[STYLER], true);\n\t\tObject.defineProperty(this, 'visible', {value: builder});\n\t\treturn builder;\n\t},\n};\n\nconst getModelAnsi = (model, level, type, ...arguments_) => {\n\tif (model === 'rgb') {\n\t\tif (level === 'ansi16m') {\n\t\t\treturn ansiStyles[type].ansi16m(...arguments_);\n\t\t}\n\n\t\tif (level === 'ansi256') {\n\t\t\treturn ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));\n\t\t}\n\n\t\treturn ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));\n\t}\n\n\tif (model === 'hex') {\n\t\treturn getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));\n\t}\n\n\treturn ansiStyles[type][model](...arguments_);\n};\n\nconst usedModels = ['rgb', 'hex', 'ansi256'];\n\nfor (const model of usedModels) {\n\tstyles[model] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n\n\tconst bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);\n\tstyles[bgModel] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n}\n\nconst proto = Object.defineProperties(() => {}, {\n\t...styles,\n\tlevel: {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn this[GENERATOR].level;\n\t\t},\n\t\tset(level) {\n\t\t\tthis[GENERATOR].level = level;\n\t\t},\n\t},\n});\n\nconst createStyler = (open, close, parent) => {\n\tlet openAll;\n\tlet closeAll;\n\tif (parent === undefined) {\n\t\topenAll = open;\n\t\tcloseAll = close;\n\t} else {\n\t\topenAll = parent.openAll + open;\n\t\tcloseAll = close + parent.closeAll;\n\t}\n\n\treturn {\n\t\topen,\n\t\tclose,\n\t\topenAll,\n\t\tcloseAll,\n\t\tparent,\n\t};\n};\n\nconst createBuilder = (self, _styler, _isEmpty) => {\n\t// Single argument is hot path, implicit coercion is faster than anything\n\t// eslint-disable-next-line no-implicit-coercion\n\tconst builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));\n\n\t// We alter the prototype because we must return a function, but there is\n\t// no way to create a function with a different prototype\n\tObject.setPrototypeOf(builder, proto);\n\n\tbuilder[GENERATOR] = self;\n\tbuilder[STYLER] = _styler;\n\tbuilder[IS_EMPTY] = _isEmpty;\n\n\treturn builder;\n};\n\nconst applyStyle = (self, string) => {\n\tif (self.level <= 0 || !string) {\n\t\treturn self[IS_EMPTY] ? '' : string;\n\t}\n\n\tlet styler = self[STYLER];\n\n\tif (styler === undefined) {\n\t\treturn string;\n\t}\n\n\tconst {openAll, closeAll} = styler;\n\tif (string.includes('\\u001B')) {\n\t\twhile (styler !== undefined) {\n\t\t\t// Replace any instances already present with a re-opening code\n\t\t\t// otherwise only the part of the string until said closing code\n\t\t\t// will be colored, and the rest will simply be 'plain'.\n\t\t\tstring = stringReplaceAll(string, styler.close, styler.open);\n\n\t\t\tstyler = styler.parent;\n\t\t}\n\t}\n\n\t// We can move both next actions out of loop, because remaining actions in loop won't have\n\t// any/visible effect on parts we add here. Close the styling before a linebreak and reopen\n\t// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92\n\tconst lfIndex = string.indexOf('\\n');\n\tif (lfIndex !== -1) {\n\t\tstring = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);\n\t}\n\n\treturn openAll + string + closeAll;\n};\n\nObject.defineProperties(createChalk.prototype, styles);\n\nconst chalk = createChalk();\nexport const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0});\n\nexport {\n\tmodifierNames,\n\tforegroundColorNames,\n\tbackgroundColorNames,\n\tcolorNames,\n\n\t// TODO: Remove these aliases in the next major version\n\tmodifierNames as modifiers,\n\tforegroundColorNames as foregroundColors,\n\tbackgroundColorNames as backgroundColors,\n\tcolorNames as colors,\n} from './vendor/ansi-styles/index.js';\n\nexport {\n\tstdoutColor as supportsColor,\n\tstderrColor as supportsColorStderr,\n};\n\nexport default chalk;\n", "/**\n * Implementation shared between `vlt run`, `vlt run-exec`, and `vlt exec`\n */\n\nimport { error } from '@vltpkg/error-cause'\nimport type {\n exec,\n execFG,\n ExecOptions,\n run,\n runExec,\n runExecFG,\n RunExecOptions,\n runFG,\n RunOptions,\n RunResult,\n} from '@vltpkg/run'\nimport { isRunResult } from '@vltpkg/run'\nimport { Monorepo, Workspace } from '@vltpkg/workspaces'\nimport { ansiToAnsi } from 'ansi-to-pre'\nimport chalk from 'chalk'\nimport { LoadedConfig } from './config/index.js'\n\nexport type RunnerBG = typeof exec | typeof run | typeof runExec\nexport type RunnerFG = typeof execFG | typeof runExecFG | typeof runFG\nexport type RunnerOptions = ExecOptions & RunExecOptions & RunOptions\n\nexport class ExecCommand<B extends RunnerBG, F extends RunnerFG> {\n bg: B\n fg: F\n arg0?: string\n args: string[]\n monorepo?: Monorepo\n /** how many places are we doing things in? */\n spaces: number\n conf: LoadedConfig\n projectRoot: string\n\n constructor(conf: LoadedConfig, bg: B, fg: F) {\n this.conf = conf\n this.bg = bg\n this.fg = fg\n const {\n projectRoot,\n positionals: [arg0, ...args],\n } = conf\n this.arg0 = arg0\n this.args = args\n\n const paths = conf.get('workspace')\n const groups = conf.get('workspace-group')\n const recursive = conf.get('recursive')\n this.monorepo =\n paths?.length || groups?.length || recursive ?\n Monorepo.load(projectRoot, { load: { paths, groups } })\n : undefined\n this.spaces = this.monorepo?.size ?? 1\n this.projectRoot = projectRoot\n }\n\n async run() {\n if (this.spaces === 1) {\n const arg = this.fgArg()\n if (!arg) return\n const result = await this.fg(arg)\n console.log(result)\n return result\n }\n const m = this.monorepo\n if (!m || this.spaces === 0) {\n throw error('no matching workspaces found', {\n /* c8 ignore next - already guarded */\n validOptions: [...(this.monorepo?.load().paths() ?? [])],\n })\n }\n const arg0 = this.arg0\n if (!arg0) {\n this.noArgsMulti()\n return\n }\n // run across workspaces\n let failed = false\n const resultMap = await m.run(async ws => {\n if (!failed) console.error(`${ws.path} ${arg0}`)\n const result = await this.bg(this.bgArg(ws)).catch(\n (er: unknown) => {\n if (\n er instanceof Error &&\n er.cause &&\n isRunResult(er.cause)\n ) {\n this.printResult(ws, er.cause)\n }\n failed = true\n throw er\n },\n )\n if (!failed) this.printResult(ws, result)\n return result\n })\n\n const results: Record<string, RunResult> = {}\n for (const [ws, result] of resultMap) {\n if (result.status === 0 && result.signal === null) {\n result.stdout = ''\n result.stderr = ''\n }\n results[ws.path] = result\n }\n return results\n }\n\n printResult(ws: Workspace, result: RunResult) {\n if (result.status === 0 && result.signal === null) {\n console.log(ws.path, 'ok')\n } else {\n console.log(\n chalk.bgWhiteBright.black.bold(ws.path + ' failure'),\n {\n status: result.status,\n signal: result.signal,\n },\n )\n /* c8 ignore start */\n if (result.stderr) console.error(ansiToAnsi(result.stderr))\n if (result.stdout) console.log(ansiToAnsi(result.stdout))\n process.exitCode = process.exitCode || (result.status ?? 1)\n /* c8 ignore stop */\n }\n }\n\n /* c8 ignore start - env specific */\n interactiveShell(): string {\n return (\n process.env.SHELL ??\n this.conf.get('script-shell') ??\n (process.platform === 'win32' ? 'cmd.exe' : '/bin/sh')\n )\n }\n /* c8 ignore stop */\n\n // overridden by 'vlt run' to print options and return undefined\n defaultArg0(): string | undefined {\n return this.interactiveShell()\n }\n\n fgArg(): RunnerOptions | undefined {\n const ws = this.monorepo?.values().next().value\n const cwd = ws?.fullpath ?? this.projectRoot\n const arg0 = this.arg0 ?? this.defaultArg0()\n if (!arg0) {\n return undefined\n }\n\n return {\n cwd,\n /* c8 ignore next - already guarded */\n arg0,\n args: this.args,\n projectRoot: this.projectRoot,\n packageJson: this.monorepo?.packageJson,\n 'script-shell':\n this.arg0 ? this.conf.get('script-shell') : false,\n }\n }\n\n /** If this returns undefined, then nothing to do */\n bgArg(ws: Workspace): RunnerOptions {\n /* c8 ignore start - already guarded */\n if (!this.arg0)\n throw error(\n 'Cannot spawn interactive shells in multiple workspaces',\n )\n /* c8 ignore stop */\n\n return {\n cwd: ws.fullpath,\n acceptFail: !this.conf.get('bail'),\n ignoreMissing: true,\n arg0: this.arg0,\n args: this.args,\n projectRoot: this.projectRoot,\n packageJson: this.monorepo?.packageJson,\n 'script-shell': this.conf.get('script-shell'),\n }\n }\n\n // overridden in `vlt run` to print available scripts\n noArgsMulti() {\n throw error(\n 'Cannot spawn interactive shells in multiple workspaces',\n )\n }\n}\n", "import { exec, execFG } from '@vltpkg/run'\nimport { LoadedConfig } from '../config/index.js'\nimport { ExecCommand } from '../exec-command.js'\n\nexport const usage = `vlt exec [command]\nRuns the command with all installed bins in the $PATH\nIf no command specified, an interactive subshell is spawned.`\n\nexport const command = async (conf: LoadedConfig) =>\n await new ExecCommand(conf, exec, execFG).run()\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,WAAO,UAAU;AACjB,UAAM,OAAOA;AAEb,QAAI,KAAK,UAAQ,SAAI;AAErB,aAAS,aAAcC,OAAM,SAAS;AACpC,UAAI,UAAU,QAAQ,YAAY,SAChC,QAAQ,UAAU,QAAQ,IAAI;AAEhC,UAAI,CAAC,SAAS;AACZ,eAAO;AAAA,MACT;AAEA,gBAAU,QAAQ,MAAM,GAAG;AAC3B,UAAI,QAAQ,QAAQ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"path", "sync", "path", "resolve", "path", "resolve", "ext", "path", "env", "match", "path", "command", "path", "escape", "parse", "command", "parse", "spawn", "command", "expand", "command", "proc", "process", "global", "spawn", "spawn", "crossSpawn", "resolve", "resolve", "path", "env", "resolve", "env", "M", "m", "z", "resolve", "range", "path", "t", "delimiter", "delimiter", "readFileSync", "statSync", "glob", "i", "acc", "ext", "glob", "re", "hasMagic", "start", "final", "ext", "qmark", "star", "expand", "regExpEscape", "re", "fileURLToPath", "getOptions", "v", "bf", "p", "ret", "resolve", "res", "path", "p", "resolve", "sep", "filter", "process", "sync", "defaultPlatform", "path", "rest", "path", "abs", "target", "defaultPlatform", "fileURLToPath", "d", "path", "n", "resolve", "posix", "path", "resolve", "readFileSync", "filter", "group", "glob", "posix", "ws", "statSync", "load", "emojiRegex", "r", "g", "b", "c", "styles", "code", "codes", "hex", "colors", "inspect", "n", "inspect", "hex", "process", "stream", "styles", "chalk", "styles"]
7
7
  }