@elpapi42/pi-fleet 0.1.0-beta.0 → 0.1.0-beta.10
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.
- package/CHANGELOG.md +162 -3
- package/README.md +170 -104
- package/bin/pifleet-runtime.mjs +1 -1
- package/dist/cli-meta.json +5464 -82
- package/dist/cli.mjs +3481 -253
- package/dist/cli.mjs.map +4 -4
- package/dist/installer-meta.json +87 -13
- package/dist/installer.mjs +555 -95
- package/dist/installer.mjs.map +4 -4
- package/dist/runtime-manifest.json +37 -43
- package/dist/runtime-meta.json +2976 -2868
- package/dist/runtime.mjs +6316 -5247
- package/dist/runtime.mjs.map +4 -4
- package/dist/sqlite-worker-meta.json +6 -6
- package/dist/sqlite-worker.mjs +95 -40
- package/dist/sqlite-worker.mjs.map +2 -2
- package/package.json +11 -5
package/dist/cli.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/entry/cli.ts", "../node_modules/commander/lib/error.js", "../node_modules/commander/lib/argument.js", "../node_modules/commander/lib/command.js", "../node_modules/commander/lib/help.js", "../node_modules/commander/lib/option.js", "../node_modules/commander/lib/suggestSimilar.js", "../node_modules/commander/index.js", "../src/cli/argv.ts", "../src/shared/product-identity.ts", "../src/
|
|
4
|
-
"sourcesContent": ["import { randomUUID } from \"node:crypto\";\nimport { pathToFileURL } from \"node:url\";\nimport { CommanderError } from \"commander\";\n\nimport { splitArgv } from \"../cli/argv.js\";\nimport type { CliDependencies as Dependencies } from \"../cli/context.js\";\nimport { createProgram } from \"../cli/program.js\";\nimport { writeError } from \"../cli/output.js\";\nimport { SocketFleetClient } from \"../client/socket-fleet-client.js\";\nimport { ensureRuntime } from \"../platform/client/start-runtime.js\";\nimport { resolveFleetPaths } from \"../platform/shared/paths.js\";\n\nexport type CliDependencies = Dependencies;\n\nfunction defaultDependencies(): CliDependencies {\n const abort = new AbortController();\n const paths = resolveFleetPaths();\n return {\n client: new SocketFleetClient({\n socketPath: paths.socketPath,\n beforeConnect: () => ensureRuntime({ socketPath: paths.socketPath, env: process.env }),\n }),\n cwd: process.cwd(),\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n signal: abort.signal,\n operationIds: () => ({ operationId: randomUUID(), createdAt: new Date().toISOString() }),\n };\n}\n\nexport async function runCli(\n argv: readonly string[],\n dependencies: CliDependencies = defaultDependencies(),\n): Promise<number> {\n const split = splitArgv(argv);\n const commandName = split.fleetArgv[0];\n const human = commandName !== \"watch\" && split.fleetArgv.includes(\"--human\");\n\n if (split.piArgv.length > 0 && commandName !== \"create\") {\n writeError(\n dependencies.stderr,\n { code: \"invalid_arguments\", message: \"Only create accepts Pi arguments after --.\" },\n human,\n );\n return 1;\n }\n\n let exitCode = 0;\n const program = createProgram({ ...dependencies, piArgv: split.piArgv }, (value) => {\n exitCode = value;\n });\n\n if (split.fleetArgv.length === 0) {\n program.outputHelp();\n return 0;\n }\n\n try {\n await program.parseAsync([...split.fleetArgv], { from: \"user\" });\n return exitCode;\n } catch (error: unknown) {\n if (error instanceof CommanderError) {\n if (error.code === \"commander.helpDisplayed\" || error.code === \"commander.version\") return 0;\n writeError(\n dependencies.stderr,\n { code: \"invalid_arguments\", message: error.message.replace(/^error:\\s*/i, \"\") },\n human,\n );\n return 1;\n }\n const message = error instanceof Error ? error.message : \"Unexpected CLI error\";\n writeError(dependencies.stderr, { code: \"invalid_arguments\", message }, human);\n return 1;\n }\n}\n\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exitCode = await runCli(process.argv.slice(2));\n}\n", "/**\n * CommanderError class\n */\nexport class CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nexport class InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n", "import { InvalidArgumentError } from './error.js';\n\nexport class Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.endsWith('...')) {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nexport function humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n", "import { EventEmitter } from 'node:events';\nimport childProcess from 'node:child_process';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport process from 'node:process';\nimport { stripVTControlCharacters } from 'node:util';\n\nimport { Argument, humanReadableArgName } from './argument.js';\nimport { CommanderError } from './error.js';\nimport { Help } from './help.js';\nimport { Option, DualOptions } from './option.js';\nimport { suggestSimilar } from './suggestSimilar.js';\n\nexport class Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = false;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n this._savedState = null; // used in save/restoreStateBeforeParse\n\n // see configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n outputError: (str, write) => write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n getOutHasColors: () =>\n useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),\n getErrHasColors: () =>\n useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),\n stripColor: (str) => stripVTControlCharacters(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n /** @type {string | undefined} */\n this._helpGroupHeading = undefined; // soft initialised when added to parent\n /** @type {string | undefined} */\n this._defaultCommandGroup = undefined;\n /** @type {string | undefined} */\n this._defaultOptionGroup = undefined;\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // change how output being written, defaults to stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // change how output being written for errors, defaults to writeErr\n * outputError(str, write) // used for displaying errors and not used for displaying help\n * // specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // color support, currently only used with Help\n * getOutHasColors()\n * getErrHasColors()\n * stripColor() // used to remove ANSI escape codes if output does not have colors\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n this._outputConfiguration = {\n ...this._outputConfiguration,\n ...configuration,\n };\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom argument processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, parseArg, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof parseArg === 'function') {\n argument.default(defaultValue).argParser(parseArg);\n } else {\n argument.default(parseArg);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument?.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n if (enableOrNameAndArgs && this._defaultCommandGroup) {\n // make the command to store the group\n this._initCommandGroup(this._getHelpCommand());\n }\n return this;\n }\n\n const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n // init group unless lazy create\n if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n this._initCommandGroup(helpCommand);\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this._initOptionGroup(option);\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this._initCommandGroup(command);\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._collectValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n _prepareForParse() {\n // Save the state the first time, then restore the state before each subsequent parse.\n if (this._savedState === null) {\n // Do the special default of lone negated option to true, now that we have all the options.\n // Filter for negated options that have not been processed already.\n this.options\n .filter(\n (option) =>\n option.negate &&\n option.defaultValue === undefined &&\n this.getOptionValue(option.attributeName()) === undefined,\n )\n .forEach((option) => {\n // check for lone negated option: --no-foo without a --foo option\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n option.attributeName(),\n true,\n 'default',\n );\n }\n });\n\n this.saveStateBeforeParse();\n } else {\n this.restoreStateBeforeParse();\n }\n }\n\n /**\n * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state saved.\n */\n saveStateBeforeParse() {\n this._savedState = {\n // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing\n _name: this._name,\n // option values before parse have default values (including false for negated options)\n // shallow clones\n _optionValues: { ...this._optionValues },\n _optionValueSources: { ...this._optionValueSources },\n };\n }\n\n /**\n * Restore state before parse for calls after the first.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state restored.\n */\n restoreStateBeforeParse() {\n if (this._storeOptionsAsProperties)\n throw new Error(`Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties`);\n\n // clear state from _prepareUserArgs\n this._name = this._savedState._name;\n this._scriptPath = null;\n this.rawArgs = [];\n // clear state from setOptionValueWithSource\n this._optionValues = { ...this._savedState._optionValues };\n this._optionValueSources = { ...this._savedState._optionValueSources };\n // clear state from _parseCommand\n this.args = [];\n // clear state from _processArguments\n this.processedArgs = [];\n }\n\n /**\n * Throw if expected executable is missing. Add lots of help for author.\n *\n * @param {string} executableFile\n * @param {string} executableDir\n * @param {string} subcommandName\n */\n _checkForMissingExecutable(executableFile, executableDir, subcommandName) {\n if (fs.existsSync(executableFile)) return;\n\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n const launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n subCommand._prepareForParse();\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise?.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent?.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Side effects: modifies command by storing options. Does not reset state if called again.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} args\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(args) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n const negativeNumberArg = (arg) => {\n // return false if not a negative number\n if (!/^-(\\d+|\\d*\\.\\d+)(e[+-]?\\d+)?$/.test(arg)) return false;\n // negative number is ok unless digit used as an option in command hierarchy\n return !this._getCommandAndAncestors().some((cmd) =>\n cmd.options\n .map((opt) => opt.short)\n .some((short) => /^-\\d$/.test(short)),\n );\n };\n\n // parse options\n let activeVariadicOption = null;\n let activeGroup = null; // working through group of short options, like -abc\n let i = 0;\n while (i < args.length || activeGroup) {\n const arg = activeGroup ?? args[i++];\n activeGroup = null;\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args.slice(i));\n break;\n }\n\n if (\n activeVariadicOption &&\n (!maybeOption(arg) || negativeNumberArg(arg))\n ) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args[i++];\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (\n i < args.length &&\n (!maybeOption(args[i]) || negativeNumberArg(args[i]))\n ) {\n value = args[i++];\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option\n this.emit(`option:${option.name()}`);\n // remove the processed option and keep processing group\n activeGroup = `-${arg.slice(2)}`;\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n // A negative number in a leaf command is not an unknown option.\n if (\n dest === operands &&\n maybeOption(arg) &&\n !(this.commands.length === 0 && negativeNumberArg(arg))\n ) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n unknown.push(...args.slice(i));\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg, ...args.slice(i));\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg, ...args.slice(i));\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg, ...args.slice(i));\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const received = receivedArgs.length;\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const details = receivedArgs.join(', ');\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set/get the help group heading for this subcommand in parent command's help.\n *\n * @param {string} [heading]\n * @return {Command | string}\n */\n\n helpGroup(heading) {\n if (heading === undefined) return this._helpGroupHeading ?? '';\n this._helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for subcommands added to this command.\n * (This does not override a group set directly on the subcommand using .helpGroup().)\n *\n * @example\n * program.commandsGroup('Development Commands:);\n * program.command('watch')...\n * program.command('lint')...\n * ...\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n commandsGroup(heading) {\n if (heading === undefined) return this._defaultCommandGroup ?? '';\n this._defaultCommandGroup = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for options added to this command.\n * (This does not override a group set directly on the option using .helpGroup().)\n *\n * @example\n * program\n * .optionsGroup('Development Options:')\n * .option('-d, --debug', 'output extra debugging')\n * .option('-p, --profile', 'output profiling information')\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n optionsGroup(heading) {\n if (heading === undefined) return this._defaultOptionGroup ?? '';\n this._defaultOptionGroup = heading;\n return this;\n }\n\n /**\n * @param {Option} option\n * @private\n */\n _initOptionGroup(option) {\n if (this._defaultOptionGroup && !option.helpGroupHeading)\n option.helpGroup(this._defaultOptionGroup);\n }\n\n /**\n * @param {Command} cmd\n * @private\n */\n _initCommandGroup(cmd) {\n if (this._defaultCommandGroup && !cmd.helpGroup())\n cmd.helpGroup(this._defaultCommandGroup);\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or import.meta.filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(import.meta.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(import.meta.dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n const context = this._getOutputContext(contextOptions);\n helper.prepareContext({\n error: context.error,\n helpWidth: context.helpWidth,\n outputHasColors: context.hasColors,\n });\n const text = helper.formatHelp(this, helper);\n if (context.hasColors) return text;\n return this._outputConfiguration.stripColor(text);\n }\n\n /**\n * @typedef HelpContext\n * @type {object}\n * @property {boolean} error\n * @property {number} helpWidth\n * @property {boolean} hasColors\n * @property {function} write - includes stripColor if needed\n *\n * @returns {HelpContext}\n * @private\n */\n\n _getOutputContext(contextOptions) {\n contextOptions = contextOptions || {};\n const error = !!contextOptions.error;\n let baseWrite;\n let hasColors;\n let helpWidth;\n if (error) {\n baseWrite = (str) => this._outputConfiguration.writeErr(str);\n hasColors = this._outputConfiguration.getErrHasColors();\n helpWidth = this._outputConfiguration.getErrHelpWidth();\n } else {\n baseWrite = (str) => this._outputConfiguration.writeOut(str);\n hasColors = this._outputConfiguration.getOutHasColors();\n helpWidth = this._outputConfiguration.getOutHelpWidth();\n }\n const write = (str) => {\n if (!hasColors) str = this._outputConfiguration.stripColor(str);\n return baseWrite(str);\n };\n return { error, write, hasColors, helpWidth };\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n\n const outputContext = this._getOutputContext(contextOptions);\n /** @type {HelpTextEventContext} */\n const eventContext = {\n error: outputContext.error,\n write: outputContext.write,\n command: this,\n };\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', eventContext));\n this.emit('beforeHelp', eventContext);\n\n let helpInformation = this.helpInformation({ error: outputContext.error });\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n outputContext.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', eventContext);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', eventContext),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support enabling/disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n if (this._helpOption === null) this._helpOption = undefined; // reenable\n if (this._defaultOptionGroup) {\n // make the option to store the group\n this._initOptionGroup(this._getHelpOption());\n }\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n this._helpOption = this.createOption(\n flags ?? '-h, --help',\n description ?? 'display help for command',\n );\n // init group unless lazy create\n if (flags || description) this._initOptionGroup(this._helpOption);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n this._initOptionGroup(option);\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * // Do a little typing to coordinate emit and listener for the help text events.\n * @typedef HelpTextEventContext\n * @type {object}\n * @property {boolean} error\n * @property {Command} command\n * @property {function} write\n */\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\n/**\n * Exported for using from tests, not otherwise used outside this file.\n *\n * @returns {boolean | undefined}\n * @package\n */\nexport function useColor() {\n // Test for common conventions.\n // NB: the observed behaviour is in combination with how author adds color! For example:\n // - we do not test NODE_DISABLE_COLORS, but util:styletext does\n // - we do test NO_COLOR, but Chalk does not\n //\n // References:\n // https://no-color.org\n // https://bixense.com/clicolors/\n // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109\n // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33\n // (https://force-color.org recent web page from 2023, does not match major javascript implementations)\n\n if (\n process.env.NO_COLOR ||\n process.env.FORCE_COLOR === '0' ||\n process.env.FORCE_COLOR === 'false'\n )\n return false;\n if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)\n return true;\n return undefined;\n}\n", "import { humanReadableArgName } from './argument.js';\nimport { stripVTControlCharacters } from 'node:util';\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nexport class Help {\n constructor() {\n this.helpWidth = undefined;\n this.minWidthToWrap = 40;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`\n * and just before calling `formatHelp()`.\n *\n * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.\n *\n * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions\n */\n prepareContext(contextOptions) {\n this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleSubcommandTerm(helper.subcommandTerm(command)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (option.description) {\n return `${option.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n return argument.description;\n }\n\n /**\n * Format a list of items, given a heading and an array of formatted items.\n *\n * @param {string} heading\n * @param {string[]} items\n * @param {Help} helper\n * @returns string[]\n */\n formatItemList(heading, items, helper) {\n if (items.length === 0) return [];\n\n return [helper.styleTitle(heading), ...items, ''];\n }\n\n /**\n * Group items by their help group heading.\n *\n * @param {Command[] | Option[]} unsortedItems\n * @param {Command[] | Option[]} visibleItems\n * @param {Function} getGroup\n * @returns {Map<string, Command[] | Option[]>}\n */\n groupItems(unsortedItems, visibleItems, getGroup) {\n const result = new Map();\n // Add groups in order of appearance in unsortedItems.\n unsortedItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) result.set(group, []);\n });\n // Add items in order of appearance in visibleItems.\n visibleItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) {\n result.set(group, []);\n }\n result.get(group).push(item);\n });\n return result;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called\n\n function callFormatItem(term, description) {\n return helper.formatItem(term, termWidth, description, helper);\n }\n\n // Usage\n let output = [\n `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n '',\n ];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.boxWrap(\n helper.styleCommandDescription(commandDescription),\n helpWidth,\n ),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return callFormatItem(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n helper.styleArgumentDescription(helper.argumentDescription(argument)),\n );\n });\n output = output.concat(\n this.formatItemList('Arguments:', argumentList, helper),\n );\n\n // Options\n const optionGroups = this.groupItems(\n cmd.options,\n helper.visibleOptions(cmd),\n (option) => option.helpGroupHeading ?? 'Options:',\n );\n optionGroups.forEach((options, group) => {\n const optionList = options.map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(this.formatItemList(group, optionList, helper));\n });\n\n if (helper.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(\n this.formatItemList('Global Options:', globalOptionList, helper),\n );\n }\n\n // Commands\n const commandGroups = this.groupItems(\n cmd.commands,\n helper.visibleCommands(cmd),\n (sub) => sub.helpGroup() || 'Commands:',\n );\n commandGroups.forEach((commands, group) => {\n const commandList = commands.map((sub) => {\n return callFormatItem(\n helper.styleSubcommandTerm(helper.subcommandTerm(sub)),\n helper.styleSubcommandDescription(helper.subcommandDescription(sub)),\n );\n });\n output = output.concat(this.formatItemList(group, commandList, helper));\n });\n\n return output.join('\\n');\n }\n\n /**\n * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.\n *\n * @param {string} str\n * @returns {number}\n */\n displayWidth(str) {\n return stripVTControlCharacters(str).length;\n }\n\n /**\n * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.\n *\n * @param {string} str\n * @returns {string}\n */\n styleTitle(str) {\n return str;\n }\n\n styleUsage(str) {\n // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:\n // command subcommand [options] [command] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word === '[command]') return this.styleSubcommandText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleCommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleCommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleOptionDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleSubcommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleArgumentDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleDescriptionText(str) {\n return str;\n }\n styleOptionTerm(str) {\n return this.styleOptionText(str);\n }\n styleSubcommandTerm(str) {\n // This is very like usage with lots of parts! Assume default string which is formed like:\n // subcommand [options] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleSubcommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleArgumentTerm(str) {\n return this.styleArgumentText(str);\n }\n styleOptionText(str) {\n return str;\n }\n styleArgumentText(str) {\n return str;\n }\n styleSubcommandText(str) {\n return str;\n }\n styleCommandText(str) {\n return str;\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Detect manually wrapped and indented strings by checking for line break followed by whitespace.\n *\n * @param {string} str\n * @returns {boolean}\n */\n preformatted(str) {\n return /\\n[^\\S\\r\\n]/.test(str);\n }\n\n /**\n * Format the \"item\", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.\n *\n * So \"TTT\", 5, \"DDD DDDD DD DDD\" might be formatted for this.helpWidth=17 like so:\n * TTT DDD DDDD\n * DD DDD\n *\n * @param {string} term\n * @param {number} termWidth\n * @param {string} description\n * @param {Help} helper\n * @returns {string}\n */\n formatItem(term, termWidth, description, helper) {\n const itemIndent = 2;\n const itemIndentStr = ' '.repeat(itemIndent);\n if (!description) return itemIndentStr + term;\n\n // Pad the term out to a consistent width, so descriptions are aligned.\n const paddedTerm = term.padEnd(\n termWidth + term.length - helper.displayWidth(term),\n );\n\n // Format the description.\n const spacerWidth = 2; // between term and description\n const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called\n const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;\n let formattedDescription;\n if (\n remainingWidth < this.minWidthToWrap ||\n helper.preformatted(description)\n ) {\n formattedDescription = description;\n } else {\n const wrappedDescription = helper.boxWrap(description, remainingWidth);\n formattedDescription = wrappedDescription.replace(\n /\\n/g,\n '\\n' + ' '.repeat(termWidth + spacerWidth),\n );\n }\n\n // Construct and overall indent.\n return (\n itemIndentStr +\n paddedTerm +\n ' '.repeat(spacerWidth) +\n formattedDescription.replace(/\\n/g, `\\n${itemIndentStr}`)\n );\n }\n\n /**\n * Wrap a string at whitespace, preserving existing line breaks.\n * Wrapping is skipped if the width is less than `minWidthToWrap`.\n *\n * @param {string} str\n * @param {number} width\n * @returns {string}\n */\n boxWrap(str, width) {\n if (width < this.minWidthToWrap) return str;\n\n const rawLines = str.split(/\\r\\n|\\n/);\n // split up text by whitespace\n const chunkPattern = /[\\s]*[^\\s]+/g;\n const wrappedLines = [];\n rawLines.forEach((line) => {\n const chunks = line.match(chunkPattern);\n if (chunks === null) {\n wrappedLines.push('');\n return;\n }\n\n let sumChunks = [chunks.shift()];\n let sumWidth = this.displayWidth(sumChunks[0]);\n chunks.forEach((chunk) => {\n const visibleWidth = this.displayWidth(chunk);\n // Accumulate chunks while they fit into width.\n if (sumWidth + visibleWidth <= width) {\n sumChunks.push(chunk);\n sumWidth += visibleWidth;\n return;\n }\n wrappedLines.push(sumChunks.join(''));\n\n const nextChunk = chunk.trimStart(); // trim space at line break\n sumChunks = [nextChunk];\n sumWidth = this.displayWidth(nextChunk);\n });\n wrappedLines.push(sumChunks.join(''));\n });\n\n return wrappedLines.join('\\n');\n }\n}\n", "import { InvalidArgumentError } from './error.js';\n\nexport class Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n this.helpGroupHeading = undefined; // soft initialised when option added to command\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as an object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n if (this.negate) {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n return camelcase(this.name());\n }\n\n /**\n * Set the help group heading.\n *\n * @param {string} heading\n * @return {Option}\n */\n helpGroup(heading) {\n this.helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nexport class DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // short flag, single dash and single character\n const shortFlagExp = /^-[^-]$/;\n // long flag, double dash and at least one character\n const longFlagExp = /^--[^-]/;\n\n const flagParts = flags.split(/[ |,]+/).concat('guard');\n // Normal is short and/or long.\n if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();\n if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();\n // Long then short. Rarely used but fine.\n if (!shortFlag && shortFlagExp.test(flagParts[0]))\n shortFlag = flagParts.shift();\n // Allow two long flags, like '--ws, --workspace'\n // This is the supported way to have a shortish option flag.\n if (!shortFlag && longFlagExp.test(flagParts[0])) {\n shortFlag = longFlag;\n longFlag = flagParts.shift();\n }\n\n // Check for unprocessed flag. Fail noisily rather than silently ignore.\n if (flagParts[0].startsWith('-')) {\n const unsupportedFlag = flagParts[0];\n const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;\n if (/^-[^-][^-]/.test(unsupportedFlag))\n throw new Error(\n `${baseError}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,\n );\n if (shortFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many short flags`);\n if (longFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many long flags`);\n\n throw new Error(`${baseError}\n- unrecognised flag format`);\n }\n if (shortFlag === undefined && longFlag === undefined)\n throw new Error(\n `option creation failed due to no flags found in '${flags}'.`,\n );\n\n return { shortFlag, longFlag };\n}\n", "const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau\u2013Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nexport function suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n", "import { Argument } from './lib/argument.js';\nimport { Command } from './lib/command.js';\nimport { CommanderError, InvalidArgumentError } from './lib/error.js';\nimport { Help } from './lib/help.js';\nimport { Option } from './lib/option.js';\n\nexport const program = new Command();\n\nexport const createCommand = (name) => new Command(name);\nexport const createOption = (flags, description) =>\n new Option(flags, description);\nexport const createArgument = (name, description) =>\n new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexport { Command, Option, Argument, Help };\nexport { CommanderError, InvalidArgumentError };\nexport { InvalidArgumentError as InvalidOptionArgumentError }; // Deprecated\n", "export interface SplitArgv {\n readonly fleetArgv: readonly string[];\n readonly piArgv: readonly string[];\n readonly hadSeparator: boolean;\n}\n\nexport function splitArgv(argv: readonly string[]): SplitArgv {\n const separator = argv.indexOf(\"--\");\n if (separator < 0) {\n return { fleetArgv: [...argv], piArgv: [], hadSeparator: false };\n }\n return {\n fleetArgv: argv.slice(0, separator),\n piArgv: argv.slice(separator + 1),\n hadSeparator: true,\n };\n}\n", "export const PRODUCT_NAME = \"Pi Fleet\";\nexport const PRODUCT_BINARY = \"pifleet\";\nexport const PRODUCT_VERSION = \"0.1.0-beta.0\";\n", "import { resolve } from \"node:path\";\n\nimport { isAgentName } from \"../../shared/identifiers.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { resolveMessageInput } from \"../input.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport interface CreateCommandInput {\n readonly name: string;\n readonly instructions?: string;\n readonly cwd?: string;\n readonly human: boolean;\n}\n\nexport async function runCreate(\n input: CreateCommandInput,\n context: CommandContext,\n): Promise<number> {\n if (!isAgentName(input.name)) throw new Error(\"invalid agent name\");\n const instructions =\n input.instructions === undefined\n ? undefined\n : await resolveMessageInput(input.instructions, context.stdin);\n const result = await context.client.create(\n {\n name: input.name,\n ...(instructions === undefined ? {} : { instructions }),\n cwd: resolve(context.cwd, input.cwd ?? \".\"),\n piArgv: context.piArgv,\n },\n { signal: context.signal, operation: context.operationIds() },\n );\n return finishFinite(result, context, input.human);\n}\n", "export type AgentName = string & { readonly __brand: \"AgentName\" };\n\nconst AGENT_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nexport function isAgentName(value: string): value is AgentName {\n return AGENT_NAME_PATTERN.test(value);\n}\n", "import type { Readable } from \"node:stream\";\n\nconst DEFAULT_MAX_INPUT_BYTES = 1024 * 1024;\n\nexport async function resolveMessageInput(\n value: string,\n stdin: Readable,\n maxBytes = DEFAULT_MAX_INPUT_BYTES,\n): Promise<string> {\n if (value !== \"-\") return requireContent(value);\n\n const chunks: Buffer[] = [];\n let bytes = 0;\n for await (const chunk of stdin) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));\n bytes += buffer.length;\n if (bytes > maxBytes) throw new Error(`stdin exceeds the ${maxBytes}-byte limit`);\n chunks.push(buffer);\n }\n return requireContent(Buffer.concat(chunks).toString(\"utf8\"));\n}\n\nfunction requireContent(value: string): string {\n if (value.trim().length === 0) throw new Error(\"message must not be empty or whitespace-only\");\n return value;\n}\n", "import type { Writable } from \"node:stream\";\n\nimport type {\n CreateResult,\n DestroyResult,\n FleetClientError,\n ListResult,\n ReceiveResult,\n SendResult,\n StatusResult,\n} from \"../client/fleet-client.js\";\n\ntype FiniteResult =\n | CreateResult\n | SendResult\n | ReceiveResult\n | StatusResult\n | ListResult\n | DestroyResult;\n\nexport function writeResult(stream: Writable, result: FiniteResult, human: boolean): void {\n stream.write(human ? `${renderHuman(result)}\\n` : `${JSON.stringify(result)}\\n`);\n}\n\nexport function writeError(stream: Writable, error: FleetClientError, human: boolean): void {\n if (human) {\n stream.write(`${error.message}\\n`);\n return;\n }\n stream.write(`${JSON.stringify({ schemaVersion: 1, type: \"error\", error })}\\n`);\n}\n\nfunction renderHuman(result: FiniteResult): string {\n switch (result.type) {\n case \"agent.created\":\n return `${result.agent.name}: ${result.agent.state} (${result.agent.process.state})`;\n case \"message.accepted\":\n return `${result.agent.name}: message accepted`;\n case \"response\":\n return result.response.text;\n case \"agent.status\":\n return `${result.agent.name}: ${result.agent.state} (${result.agent.process.state})`;\n case \"agent.list\":\n return result.agents.length === 0\n ? \"No agents\"\n : result.agents\n .map((agent) => `${agent.name}\\t${agent.state}\\t${agent.process.state}`)\n .join(\"\\n\");\n case \"agent.destroyed\":\n return `${result.agent.name}: destroyed`;\n }\n}\n", "import type { FleetClientError } from \"../../client/fleet-client.js\";\nimport type { Result } from \"../../shared/result.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { writeError, writeResult } from \"../output.js\";\n\nexport function finishFinite<T extends Parameters<typeof writeResult>[1]>(\n result: Result<T, FleetClientError>,\n context: CommandContext,\n human: boolean,\n): number {\n if (result.ok) {\n writeResult(context.stdout, result.value, human);\n return 0;\n }\n writeError(context.stderr, result.error, human);\n return result.error.code === \"timeout\" ? 124 : 1;\n}\n\nexport function invalidArguments(message: string): FleetClientError {\n return { code: \"invalid_arguments\", message };\n}\n", "import { isAgentName } from \"../../shared/identifiers.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport async function runDestroy(\n input: { readonly name: string; readonly human: boolean },\n context: CommandContext,\n): Promise<number> {\n if (!isAgentName(input.name)) throw new Error(\"invalid agent name\");\n const result = await context.client.destroy(\n { name: input.name },\n { signal: context.signal, operation: context.operationIds() },\n );\n return finishFinite(result, context, input.human);\n}\n", "import type { CommandContext } from \"../context.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport async function runList(\n input: { readonly human: boolean },\n context: CommandContext,\n): Promise<number> {\n const result = await context.client.list({ signal: context.signal });\n return finishFinite(result, context, input.human);\n}\n", "export type Result<Value, Error> =\n | { readonly ok: true; readonly value: Value }\n | { readonly ok: false; readonly error: Error };\n\nexport function ok<Value>(value: Value): Result<Value, never> {\n return { ok: true, value };\n}\n\nexport function err<Error>(error: Error): Result<never, Error> {\n return { ok: false, error };\n}\n", "import { err, ok, type Result } from \"./result.js\";\n\ntype DurationParseError = \"invalid_duration\";\n\nconst UNIT_TO_MILLISECONDS = {\n ms: 1,\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n} as const;\n\nexport function parseDuration(input: string): Result<number, DurationParseError> {\n const match = /^(\\d+)(ms|s|m|h)?$/.exec(input);\n\n if (match === null) {\n return err(\"invalid_duration\");\n }\n\n const amount = Number(match[1]);\n const unit = match[2] ?? \"ms\";\n\n return ok(amount * UNIT_TO_MILLISECONDS[unit as keyof typeof UNIT_TO_MILLISECONDS]);\n}\n", "import { isAgentName } from \"../../shared/identifiers.js\";\nimport { parseDuration } from \"../../shared/duration.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport interface ReceiveCommandInput {\n readonly name: string;\n readonly timeout?: string;\n readonly human: boolean;\n}\n\nexport async function runReceive(\n input: ReceiveCommandInput,\n context: CommandContext,\n): Promise<number> {\n if (!isAgentName(input.name)) throw new Error(\"invalid agent name\");\n const parsedTimeout = input.timeout === undefined ? undefined : parseDuration(input.timeout);\n if (parsedTimeout !== undefined && !parsedTimeout.ok) throw new Error(\"invalid timeout duration\");\n const timeoutMs = parsedTimeout?.ok === true ? parsedTimeout.value : undefined;\n const result = await context.client.receive(\n { name: input.name },\n { signal: context.signal, ...(timeoutMs === undefined ? {} : { timeoutMs }) },\n );\n return finishFinite(result, context, input.human);\n}\n", "import { isAgentName } from \"../../shared/identifiers.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { resolveMessageInput } from \"../input.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport interface SendCommandInput {\n readonly name: string;\n readonly message: string;\n readonly human: boolean;\n}\n\nexport async function runSend(input: SendCommandInput, context: CommandContext): Promise<number> {\n if (!isAgentName(input.name)) throw new Error(\"invalid agent name\");\n const message = await resolveMessageInput(input.message, context.stdin);\n const result = await context.client.send(\n { name: input.name, message },\n { signal: context.signal, operation: context.operationIds() },\n );\n return finishFinite(result, context, input.human);\n}\n", "import { isAgentName } from \"../../shared/identifiers.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport async function runStatus(\n input: { readonly name: string; readonly human: boolean },\n context: CommandContext,\n): Promise<number> {\n if (!isAgentName(input.name)) throw new Error(\"invalid agent name\");\n const result = await context.client.status({ name: input.name }, { signal: context.signal });\n return finishFinite(result, context, input.human);\n}\n", "import { once } from \"node:events\";\n\nimport { isAgentName } from \"../../shared/identifiers.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { writeError } from \"../output.js\";\n\nexport async function runWatch(name: string, context: CommandContext): Promise<number> {\n if (!isAgentName(name)) throw new Error(\"invalid agent name\");\n for await (const result of context.client.watchSession({ name }, { signal: context.signal })) {\n if (!result.ok) {\n writeError(context.stderr, result.error, false);\n return 1;\n }\n if (!context.stdout.write(result.value.bytes)) await once(context.stdout, \"drain\");\n }\n return 0;\n}\n", "import { Command } from \"commander\";\n\nimport { PRODUCT_BINARY, PRODUCT_VERSION } from \"../shared/product-identity.js\";\nimport type { CommandContext } from \"./context.js\";\nimport { runCreate } from \"./commands/create.js\";\nimport { runDestroy } from \"./commands/destroy.js\";\nimport { runList } from \"./commands/list.js\";\nimport { runReceive } from \"./commands/receive.js\";\nimport { runSend } from \"./commands/send.js\";\nimport { runStatus } from \"./commands/status.js\";\nimport { runWatch } from \"./commands/watch.js\";\n\nexport function createProgram(\n context: CommandContext,\n setExitCode: (exitCode: number) => void,\n): Command {\n const program = new Command()\n .name(PRODUCT_BINARY)\n .description(\"Manage named Pi agents\")\n .version(PRODUCT_VERSION)\n .exitOverride()\n .showHelpAfterError(false)\n .showSuggestionAfterError(false)\n .configureOutput({\n writeOut: (text) => context.stdout.write(text),\n writeErr: () => undefined,\n });\n\n program\n .command(\"create\")\n .description(\"Create a named Pi agent\")\n .argument(\"<name>\")\n .argument(\"[instructions]\")\n .option(\"--cwd <path>\")\n .option(\"--human\")\n .action(async (name: string, instructions: string | undefined, options: CreateOptions) => {\n setExitCode(\n await runCreate(\n {\n name,\n ...(instructions === undefined ? {} : { instructions }),\n ...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n human: options.human ?? false,\n },\n context,\n ),\n );\n });\n\n program\n .command(\"send\")\n .description(\"Send ordinary Pi input\")\n .argument(\"<name>\")\n .argument(\"<message>\")\n .option(\"--human\")\n .action(async (name: string, message: string, options: HumanOptions) => {\n setExitCode(await runSend({ name, message, human: options.human ?? false }, context));\n });\n\n program\n .command(\"receive\")\n .description(\"Wait for idle and return the latest assistant message\")\n .argument(\"<name>\")\n .option(\"--timeout <duration>\")\n .option(\"--human\")\n .action(async (name: string, options: ReceiveOptions) => {\n setExitCode(\n await runReceive(\n {\n name,\n ...(options.timeout === undefined ? {} : { timeout: options.timeout }),\n human: options.human ?? false,\n },\n context,\n ),\n );\n });\n\n program\n .command(\"status\")\n .description(\"Inspect one agent without waking it\")\n .argument(\"<name>\")\n .option(\"--human\")\n .action(async (name: string, options: HumanOptions) => {\n setExitCode(await runStatus({ name, human: options.human ?? false }, context));\n });\n\n program\n .command(\"list\")\n .description(\"List named agents without waking them\")\n .option(\"--human\")\n .action(async (options: HumanOptions) => {\n setExitCode(await runList({ human: options.human ?? false }, context));\n });\n\n program\n .command(\"watch\")\n .description(\"Tail new records from the selected Pi session\")\n .argument(\"<name>\")\n .action(async (name: string) => {\n setExitCode(await runWatch(name, context));\n });\n\n program\n .command(\"destroy\")\n .description(\"Stop managing an agent without deleting its Pi session\")\n .argument(\"<name>\")\n .option(\"--human\")\n .action(async (name: string, options: HumanOptions) => {\n setExitCode(await runDestroy({ name, human: options.human ?? false }, context));\n });\n\n return program;\n}\n\ninterface HumanOptions {\n readonly human?: boolean;\n}\n\ninterface CreateOptions extends HumanOptions {\n readonly cwd?: string;\n}\n\ninterface ReceiveOptions extends HumanOptions {\n readonly timeout?: string;\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { createConnection, type Socket } from \"node:net\";\n\nimport { readJsonLines, writeJsonLine } from \"../protocol/jsonl.js\";\nimport { PROTOCOL_VERSION } from \"../protocol/version.js\";\nimport { err, ok, type Result } from \"../shared/result.js\";\nimport type {\n CreateInput,\n CreateResult,\n DestroyInput,\n DestroyResult,\n FleetClient,\n FleetClientError,\n ListResult,\n MutationOptions,\n RawSessionChunk,\n ReceiveInput,\n ReceiveResult,\n RequestOptions,\n SendInput,\n SendResult,\n StatusInput,\n StatusResult,\n WatchInput,\n} from \"./fleet-client.js\";\n\nexport class SocketFleetClient implements FleetClient {\n constructor(\n private readonly options: {\n readonly socketPath: string;\n readonly beforeConnect?: () => Promise<void>;\n },\n ) {}\n\n create(\n input: CreateInput,\n options: MutationOptions,\n ): Promise<Result<CreateResult, FleetClientError>> {\n return this.#request(\"agent.create\", input, options);\n }\n\n send(input: SendInput, options: MutationOptions): Promise<Result<SendResult, FleetClientError>> {\n return this.#request(\"agent.send\", input, options);\n }\n\n receive(\n input: ReceiveInput,\n options: RequestOptions,\n ): Promise<Result<ReceiveResult, FleetClientError>> {\n return this.#request(\"agent.receive\", { ...input, timeoutMs: options.timeoutMs }, options);\n }\n\n status(\n input: StatusInput,\n options: RequestOptions,\n ): Promise<Result<StatusResult, FleetClientError>> {\n return this.#request(\"agent.status\", input, options);\n }\n\n list(options: RequestOptions): Promise<Result<ListResult, FleetClientError>> {\n return this.#request(\"agent.list\", {}, options);\n }\n\n async *watchSession(\n input: WatchInput,\n options: RequestOptions,\n ): AsyncIterable<Result<RawSessionChunk, FleetClientError>> {\n let socket: Socket;\n try {\n await this.options.beforeConnect?.();\n socket = await connect(this.options.socketPath, options.signal);\n } catch (error: unknown) {\n yield err(connectionError(error));\n return;\n }\n\n const requestId = randomUUID();\n const frames = frameIterator(socket, options.signal);\n writeJsonLine(socket, {\n v: PROTOCOL_VERSION,\n requestId,\n method: \"agent.watch\",\n params: input,\n });\n\n let endedExplicitly = false;\n try {\n for await (const frame of frames) {\n if (!isRecord(frame) || frame.requestId !== requestId) continue;\n if (frame.stream === \"ready\") continue;\n if (frame.stream === \"end\") {\n endedExplicitly = true;\n return;\n }\n if (frame.stream === \"chunk\" && typeof frame.data === \"string\") {\n yield ok({ bytes: Buffer.from(frame.data, \"base64\") });\n continue;\n }\n if (frame.stream === \"error\" && isErrorRecord(frame.error)) {\n yield err(frame.error);\n return;\n }\n yield err({ code: \"protocol_error\", message: \"Invalid watch stream frame.\" });\n return;\n }\n if (!endedExplicitly && !options.signal.aborted) {\n yield err({\n code: \"runtime_unavailable\",\n message: \"Runtime connection closed before the watch stream ended.\",\n });\n }\n } catch (error: unknown) {\n if (!options.signal.aborted) yield err(connectionError(error));\n } finally {\n socket.destroy();\n }\n }\n\n destroy(\n input: DestroyInput,\n options: MutationOptions,\n ): Promise<Result<DestroyResult, FleetClientError>> {\n return this.#request(\"agent.destroy\", input, options);\n }\n\n async #request<T>(\n method: string,\n params: object,\n options: RequestOptions | MutationOptions,\n ): Promise<Result<T, FleetClientError>> {\n let socket: Socket;\n try {\n await this.options.beforeConnect?.();\n socket = await connect(this.options.socketPath, options.signal);\n } catch (error: unknown) {\n return err(connectionError(error));\n }\n\n const requestId = randomUUID();\n const response = firstMatchingFrame(socket, requestId, options.signal);\n writeJsonLine(socket, {\n v: PROTOCOL_VERSION,\n requestId,\n method,\n params,\n ...(isMutationOptions(options) ? { operation: options.operation } : {}),\n });\n\n try {\n const frame = await response;\n if (!isRecord(frame) || frame.requestId !== requestId || typeof frame.ok !== \"boolean\") {\n return err({ code: \"protocol_error\", message: \"Invalid runtime response.\" });\n }\n if (frame.ok) return ok(frame.result as T);\n if (isErrorRecord(frame.error)) return err(frame.error);\n return err({ code: \"protocol_error\", message: \"Runtime returned an invalid error.\" });\n } catch (error: unknown) {\n return err(connectionError(error));\n } finally {\n socket.destroy();\n }\n }\n}\n\nfunction isMutationOptions(options: RequestOptions | MutationOptions): options is MutationOptions {\n return \"operation\" in options;\n}\n\nfunction connect(socketPath: string, signal: AbortSignal): Promise<Socket> {\n return new Promise((resolveConnect, rejectConnect) => {\n if (signal.aborted) {\n rejectConnect(new Error(\"Request cancelled\"));\n return;\n }\n const socket = createConnection(socketPath);\n const onAbort = () => socket.destroy(new Error(\"Request cancelled\"));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n socket.once(\"connect\", () => {\n signal.removeEventListener(\"abort\", onAbort);\n resolveConnect(socket);\n });\n socket.once(\"error\", rejectConnect);\n });\n}\n\nfunction firstMatchingFrame(\n socket: Socket,\n requestId: string,\n signal: AbortSignal,\n): Promise<unknown> {\n return new Promise((resolveFrame, rejectFrame) => {\n let settled = false;\n const finish = (action: () => void) => {\n if (settled) return;\n settled = true;\n stop();\n signal.removeEventListener(\"abort\", onAbort);\n action();\n };\n const stop = readJsonLines(\n socket,\n (frame) => {\n if (!isRecord(frame) || frame.requestId !== requestId) return;\n finish(() => resolveFrame(frame));\n },\n (error) => finish(() => rejectFrame(error)),\n );\n const onAbort = () => finish(() => rejectFrame(new Error(\"Request cancelled\")));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n socket.once(\"close\", () =>\n finish(() => rejectFrame(new Error(\"Runtime connection closed before responding\"))),\n );\n });\n}\n\nexport async function* frameIterator(\n socket: Socket,\n signal: AbortSignal,\n maxQueuedBytes = 1024 * 1024,\n): AsyncIterable<unknown> {\n const queue: { readonly value: unknown; readonly bytes: number }[] = [];\n let queuedBytes = 0;\n let paused = false;\n let ended = false;\n let failure: Error | null = null;\n let wake: (() => void) | null = null;\n const notify = () => {\n wake?.();\n wake = null;\n };\n const stop = readJsonLines(\n socket,\n (frame) => {\n const bytes = Buffer.byteLength(JSON.stringify(frame), \"utf8\");\n queue.push({ value: frame, bytes });\n queuedBytes += bytes;\n if (queuedBytes >= maxQueuedBytes && !paused) {\n socket.pause();\n paused = true;\n }\n notify();\n },\n (error) => {\n failure = error;\n ended = true;\n notify();\n },\n );\n socket.once(\"end\", () => {\n failure = new Error(\"Runtime connection closed before completing the stream\");\n ended = true;\n notify();\n });\n const onAbort = () => {\n failure = new Error(\"Request cancelled\");\n ended = true;\n notify();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n\n try {\n while (!ended || queue.length > 0) {\n if (queue.length === 0) {\n await new Promise<void>((resolveWake) => {\n wake = resolveWake;\n });\n continue;\n }\n const item = queue.shift();\n if (item === undefined) continue;\n queuedBytes -= item.bytes;\n if (paused && queuedBytes < maxQueuedBytes / 2) {\n socket.resume();\n paused = false;\n }\n yield item.value;\n }\n if (failure !== null) throw failure;\n } finally {\n stop();\n signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isErrorRecord(value: unknown): value is FleetClientError {\n return isRecord(value) && typeof value.code === \"string\" && typeof value.message === \"string\";\n}\n\nfunction connectionError(error: unknown): FleetClientError {\n return {\n code: \"runtime_unavailable\",\n message: error instanceof Error ? error.message : \"Unable to connect to Pi Fleet runtime.\",\n };\n}\n", "export const PROTOCOL_VERSION = 1 as const;\nexport const MAX_PROTOCOL_FRAME_BYTES = 1024 * 1024;\n", "import type { Socket } from \"node:net\";\n\nimport { MAX_PROTOCOL_FRAME_BYTES } from \"./version.js\";\n\nexport function readJsonLines(\n socket: Socket,\n onValue: (value: unknown) => void,\n onError: (error: Error) => void,\n maxFrameBytes = MAX_PROTOCOL_FRAME_BYTES,\n): () => void {\n let buffer = Buffer.alloc(0);\n const onData = (chunk: Buffer) => {\n buffer = Buffer.concat([buffer, chunk]);\n while (true) {\n const newline = buffer.indexOf(0x0a);\n if (newline < 0) {\n if (buffer.length > maxFrameBytes) {\n onError(new Error(\"Protocol frame exceeds maximum size\"));\n }\n return;\n }\n if (newline > maxFrameBytes) {\n onError(new Error(\"Protocol frame exceeds maximum size\"));\n return;\n }\n const line = buffer.subarray(0, newline).toString(\"utf8\").replace(/\\r$/, \"\");\n buffer = buffer.subarray(newline + 1);\n if (line.length === 0) continue;\n try {\n onValue(JSON.parse(line));\n } catch {\n onError(new Error(\"Malformed JSON protocol frame\"));\n return;\n }\n }\n };\n socket.on(\"data\", onData);\n return () => socket.off(\"data\", onData);\n}\n\nexport function writeJsonLine(socket: Socket, value: unknown): boolean {\n return socket.write(`${JSON.stringify(value)}\\n`);\n}\n", "import { execFile, spawn } from \"node:child_process\";\nimport { access, readFile } from \"node:fs/promises\";\nimport { createConnection } from \"node:net\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { promisify } from \"node:util\";\n\nimport { materializeRuntime } from \"../install/runtime-release.js\";\nimport { resolveApplicationRoot, resolveFleetPaths } from \"../shared/paths.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport async function ensureRuntime(options: {\n readonly socketPath: string;\n readonly env?: NodeJS.ProcessEnv;\n readonly timeoutMs?: number;\n readonly sourceRoot?: string;\n readonly applicationRoot?: string;\n readonly home?: string;\n}): Promise<void> {\n if (await canConnect(options.socketPath)) return;\n\n const env = { ...process.env, ...options.env };\n const registered =\n env.PIFLEET_DISABLE_REGISTERED_SERVICE === \"1\"\n ? false\n : await startRegisteredRuntime({\n env,\n ...(options.home === undefined ? {} : { home: options.home }),\n });\n if (!registered) {\n const sourceRoot =\n options.sourceRoot ?? (await findPackageRoot(fileURLToPath(import.meta.url)));\n const release = await materializeRuntime({\n sourceRoot,\n applicationRoot: options.applicationRoot ?? resolveApplicationRoot(env),\n });\n const runtimePath = join(release, \"bin\", \"pifleet-runtime.mjs\");\n const child = spawn(process.execPath, [runtimePath], {\n detached: true,\n env,\n stdio: \"ignore\",\n });\n child.unref();\n }\n\n const deadline = Date.now() + (options.timeoutMs ?? 5_000);\n while (Date.now() < deadline) {\n if (await canConnect(options.socketPath)) return;\n await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));\n }\n throw new Error(`Pi Fleet runtime did not become ready at ${options.socketPath}`);\n}\n\nasync function startRegisteredRuntime(options: {\n readonly env: NodeJS.ProcessEnv;\n readonly home?: string;\n}): Promise<boolean> {\n const home = options.home ?? homedir();\n if (process.platform === \"linux\") {\n const unit = join(home, \".config\", \"systemd\", \"user\", \"pi-fleet.service\");\n if (!(await exists(unit))) return false;\n await assertRegisteredStateRoot(unit, \"linux\", options.env);\n await execFileAsync(\"systemctl\", [\"--user\", \"start\", \"pi-fleet.service\"]);\n return true;\n }\n if (process.platform === \"darwin\") {\n const plist = join(home, \"Library\", \"LaunchAgents\", \"works.elpapi.pifleet.plist\");\n if (!(await exists(plist))) return false;\n await assertRegisteredStateRoot(plist, \"darwin\", options.env);\n const domain = `gui/${process.getuid?.() ?? 0}`;\n await execFileAsync(\"launchctl\", [\"kickstart\", `${domain}/works.elpapi.pifleet`]);\n return true;\n }\n return false;\n}\n\nexport function installedServiceStateRoot(\n contents: string,\n platform: \"linux\" | \"darwin\",\n): string | undefined {\n const encoded =\n platform === \"linux\"\n ? /^Environment=PIFLEET_STATE_ROOT=(.+)$/m.exec(contents)?.[1]\n : /<key>PIFLEET_STATE_ROOT<\\/key><string>([^<]+)<\\/string>/.exec(contents)?.[1];\n if (encoded === undefined) return undefined;\n if (platform === \"linux\") return encoded;\n return encoded\n .replaceAll(\"'\", \"'\")\n .replaceAll(\""\", '\"')\n .replaceAll(\">\", \">\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\"&\", \"&\");\n}\n\nasync function assertRegisteredStateRoot(\n definitionPath: string,\n platform: \"linux\" | \"darwin\",\n env: NodeJS.ProcessEnv,\n): Promise<void> {\n const installed = installedServiceStateRoot(await readFile(definitionPath, \"utf8\"), platform);\n const requested = resolve(resolveFleetPaths(env).stateRoot);\n if (installed === undefined) {\n if (env.PIFLEET_STATE_ROOT === undefined) return;\n throw new Error(\n `Registered Pi Fleet service uses the default state root, but this command requested ${requested}. Run the Pi Fleet installer with PIFLEET_STATE_ROOT=${requested} to repair the service, or omit the override.`,\n );\n }\n if (resolve(installed) !== requested) {\n throw new Error(\n `Registered Pi Fleet service uses state root ${installed}, but this command requested ${requested}. Repair the service with the intended PIFLEET_STATE_ROOT before retrying.`,\n );\n }\n}\n\nasync function findPackageRoot(modulePath: string): Promise<string> {\n let candidate = dirname(modulePath);\n for (let depth = 0; depth < 6; depth += 1) {\n if (await exists(join(candidate, \"dist\", \"runtime-manifest.json\"))) return candidate;\n const parent = dirname(candidate);\n if (parent === candidate) break;\n candidate = parent;\n }\n throw new Error(\"Unable to locate the Pi Fleet package runtime manifest.\");\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction canConnect(socketPath: string): Promise<boolean> {\n return new Promise((resolveConnect) => {\n const socket = createConnection(socketPath);\n const timer = setTimeout(() => {\n socket.destroy();\n resolveConnect(false);\n }, 100);\n socket.once(\"connect\", () => {\n clearTimeout(timer);\n socket.destroy();\n resolveConnect(true);\n });\n socket.once(\"error\", () => {\n clearTimeout(timer);\n resolveConnect(false);\n });\n });\n}\n", "import { createHash, randomUUID } from \"node:crypto\";\nimport { chmod, cp, lstat, mkdir, readFile, rename, rm, stat } from \"node:fs/promises\";\nimport { join, resolve, sep } from \"node:path\";\n\nimport { hashDirectoryTree, type TreeIntegrity } from \"./tree-integrity.js\";\n\ninterface RuntimeManifest {\n readonly schemaVersion: 2;\n readonly package: { readonly name: string; readonly version: string };\n readonly files: readonly {\n readonly path: string;\n readonly bytes: number;\n readonly sha256: string;\n }[];\n readonly trees: readonly TreeIntegrity[];\n}\n\nexport async function materializeRuntime(options: {\n readonly sourceRoot: string;\n readonly applicationRoot: string;\n}): Promise<string> {\n const sourceRoot = resolve(options.sourceRoot);\n const applicationRoot = resolve(options.applicationRoot);\n await ensurePrivateDirectory(applicationRoot);\n const manifestBytes = await readFile(join(sourceRoot, \"dist\", \"runtime-manifest.json\"));\n const manifest = JSON.parse(manifestBytes.toString(\"utf8\")) as RuntimeManifest;\n const manifestHash = createHash(\"sha256\").update(manifestBytes).digest(\"hex\").slice(0, 16);\n const releasesRoot = join(applicationRoot, \"releases\");\n await ensurePrivateDirectory(releasesRoot);\n const destination = join(releasesRoot, `${manifest.package.version}-${manifestHash}`);\n\n if (await pathExists(destination)) {\n await verifyRuntime(destination, manifest);\n return destination;\n }\n\n const staging = join(releasesRoot, `.staging-${randomUUID()}`);\n await mkdir(staging, { mode: 0o700 });\n try {\n await cp(join(sourceRoot, \"dist\"), join(staging, \"dist\"), {\n recursive: true,\n dereference: true,\n });\n await cp(join(sourceRoot, \"bin\"), join(staging, \"bin\"), { recursive: true, dereference: true });\n await cp(join(sourceRoot, \"package.json\"), join(staging, \"package.json\"));\n for (const tree of manifest.trees) {\n const source = resolveInside(sourceRoot, tree.path);\n const destination = resolveInside(staging, tree.path);\n await mkdir(resolve(destination, \"..\"), { recursive: true, mode: 0o700 });\n await cp(source, destination, { recursive: true, dereference: true });\n }\n await verifyRuntime(staging, manifest);\n await chmod(staging, 0o700);\n await rename(staging, destination);\n return destination;\n } catch (error: unknown) {\n await rm(staging, { recursive: true, force: true });\n throw error;\n }\n}\n\nexport async function verifyRuntime(root: string, manifest?: RuntimeManifest): Promise<void> {\n const expected =\n manifest ??\n (JSON.parse(\n await readFile(join(root, \"dist\", \"runtime-manifest.json\"), \"utf8\"),\n ) as RuntimeManifest);\n const resolvedRoot = resolve(root);\n for (const file of expected.files) {\n const path = resolveInside(resolvedRoot, file.path);\n const info = await stat(path);\n if (!info.isFile() || info.size !== file.bytes) {\n throw new Error(`Runtime artifact ${file.path} has changed`);\n }\n const hash = createHash(\"sha256\")\n .update(await readFile(path))\n .digest(\"hex\");\n if (hash !== file.sha256) {\n throw new Error(`Runtime artifact ${file.path} failed verification`);\n }\n }\n for (const expectedTree of expected.trees) {\n const treeRoot = resolveInside(resolvedRoot, expectedTree.path);\n const actualTree = await hashDirectoryTree(treeRoot, expectedTree.path);\n if (\n actualTree.files !== expectedTree.files ||\n actualTree.bytes !== expectedTree.bytes ||\n actualTree.sha256 !== expectedTree.sha256\n ) {\n throw new Error(`Runtime dependency tree ${expectedTree.path} failed verification`);\n }\n }\n}\n\nfunction resolveInside(root: string, path: string): string {\n const resolved = resolve(root, path);\n if (!resolved.startsWith(`${root}${sep}`)) {\n throw new Error(`Runtime manifest contains an unsafe path ${path}`);\n }\n return resolved;\n}\n\nasync function ensurePrivateDirectory(path: string): Promise<void> {\n await mkdir(path, { recursive: true, mode: 0o700 });\n const info = await lstat(path);\n if (!info.isDirectory() || info.isSymbolicLink()) {\n throw new Error(`Refusing unsafe runtime release path ${path}`);\n }\n if (typeof process.getuid === \"function\" && info.uid !== process.getuid()) {\n throw new Error(`Runtime release path ${path} is not owned by the current user`);\n }\n await chmod(path, 0o700);\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await lstat(path);\n return true;\n } catch (error: unknown) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw error;\n }\n}\n", "import { createHash } from \"node:crypto\";\nimport { lstat, readFile, readdir, stat } from \"node:fs/promises\";\nimport { join, relative, resolve, sep } from \"node:path\";\n\nexport interface TreeIntegrity {\n readonly path: string;\n readonly files: number;\n readonly bytes: number;\n readonly sha256: string;\n}\n\nexport async function hashDirectoryTree(\n root: string,\n manifestPath: string,\n): Promise<TreeIntegrity> {\n const resolvedRoot = resolve(root);\n const entries = await collectFiles(resolvedRoot, resolvedRoot);\n const hash = createHash(\"sha256\");\n let bytes = 0;\n for (const entry of entries) {\n const contents = await readFile(entry.absolutePath);\n bytes += contents.length;\n hash.update(entry.relativePath);\n hash.update(\"\\0\");\n hash.update(String(contents.length));\n hash.update(\"\\0\");\n hash.update(contents);\n hash.update(\"\\0\");\n }\n return {\n path: manifestPath,\n files: entries.length,\n bytes,\n sha256: hash.digest(\"hex\"),\n };\n}\n\nasync function collectFiles(\n root: string,\n directory: string,\n): Promise<Array<{ readonly absolutePath: string; readonly relativePath: string }>> {\n const output: Array<{ absolutePath: string; relativePath: string }> = [];\n for (const name of (await readdir(directory)).sort()) {\n const absolutePath = join(directory, name);\n const linkInfo = await lstat(absolutePath);\n const info = linkInfo.isSymbolicLink() ? await stat(absolutePath) : linkInfo;\n if (info.isDirectory()) {\n if (linkInfo.isSymbolicLink()) {\n throw new Error(`Runtime dependency tree contains a directory symlink: ${absolutePath}`);\n }\n output.push(...(await collectFiles(root, absolutePath)));\n continue;\n }\n if (!info.isFile()) {\n throw new Error(`Runtime dependency tree contains an unsupported entry: ${absolutePath}`);\n }\n const relativePath = relative(root, absolutePath).split(sep).join(\"/\");\n if (relativePath.length === 0 || relativePath.startsWith(\"../\")) {\n throw new Error(`Runtime dependency path escapes its root: ${absolutePath}`);\n }\n output.push({ absolutePath, relativePath });\n }\n return output.sort((left, right) => left.relativePath.localeCompare(right.relativePath));\n}\n", "import { homedir, tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\nexport interface FleetPaths {\n readonly runtimeRoot: string;\n readonly stateRoot: string;\n readonly socketPath: string;\n readonly databasePath: string;\n}\n\nexport function resolveApplicationRoot(env: NodeJS.ProcessEnv = process.env): string {\n return (\n env.PIFLEET_APPLICATION_ROOT ??\n (process.platform === \"darwin\"\n ? join(homedir(), \"Library\", \"Application Support\", \"Pi Fleet\", \"runtime\")\n : join(env.XDG_DATA_HOME ?? join(homedir(), \".local\", \"share\"), \"pi-fleet\"))\n );\n}\n\nexport function resolveFleetPaths(env: NodeJS.ProcessEnv = process.env): FleetPaths {\n const explicitRoot = env.PIFLEET_STATE_ROOT;\n if (explicitRoot !== undefined) {\n const root = resolve(explicitRoot);\n return {\n runtimeRoot: root,\n stateRoot: root,\n socketPath: join(root, \"control.sock\"),\n databasePath: join(root, \"fleet.sqlite\"),\n };\n }\n\n const runtimeRoot = join(\n env.XDG_RUNTIME_DIR ?? tmpdir(),\n `pifleet-${process.getuid?.() ?? \"user\"}`,\n );\n const stateRoot =\n process.platform === \"darwin\"\n ? join(homedir(), \"Library\", \"Application Support\", \"Pi Fleet\")\n : join(env.XDG_STATE_HOME ?? join(homedir(), \".local\", \"state\"), \"pi-fleet\");\n return {\n runtimeRoot,\n stateRoot,\n socketPath: join(runtimeRoot, \"control.sock\"),\n databasePath: join(stateRoot, \"fleet.sqlite\"),\n };\n}\n"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AAED,MAAI,MAAM,UAAU,WAAW,GAAG;AAChC,IAAAA,SAAQ,WAAW;AACnB,WAAO;AAAA,EACT;AAEA,MAAI;AACF,UAAMA,SAAQ,WAAW,CAAC,GAAG,MAAM,SAAS,GAAG,EAAE,MAAM,OAAO,CAAC;AAC/D,WAAO;AAAA,EACT,SAAS,OAAgB;AACvB,QAAI,iBAAiB,gBAAgB;AACnC,UAAI,MAAM,SAAS,6BAA6B,MAAM,SAAS,oBAAqB,QAAO;AAC3F;AAAA,QACE,aAAa;AAAA,QACb,EAAE,MAAM,qBAAqB,SAAS,MAAM,QAAQ,QAAQ,eAAe,EAAE,EAAE;AAAA,QAC/E;AAAA,MACF;AACA,aAAO;AAAA,IACT;AACA,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;AACzD,eAAW,aAAa,QAAQ,EAAE,MAAM,qBAAqB,QAAQ,GAAG,KAAK;AAC7E,WAAO;AAAA,EACT;AACF;AAEA,IAAI,QAAQ,KAAK,CAAC,MAAM,UAAa,YAAY,QAAQ,cAAc,QAAQ,KAAK,CAAC,CAAC,EAAE,MAAM;AAC5F,UAAQ,WAAW,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,CAAC;AACvD;",
|
|
6
|
-
"names": ["randomUUID", "process", "stripVTControlCharacters", "cmd", "str", "process", "stripVTControlCharacters", "err", "option", "path", "program", "readFile", "createConnection", "homedir", "join", "resolve", "createHash", "randomUUID", "lstat", "readFile", "
|
|
3
|
+
"sources": ["../src/entry/cli.ts", "../node_modules/commander/lib/error.js", "../node_modules/commander/lib/argument.js", "../node_modules/commander/lib/command.js", "../node_modules/commander/lib/help.js", "../node_modules/commander/lib/option.js", "../node_modules/commander/lib/suggestSimilar.js", "../node_modules/commander/index.js", "../src/cli/argv.ts", "../src/shared/product-identity.ts", "../src/shared/identifiers.ts", "../src/cli/output.ts", "../src/cli/commands/common.ts", "../src/cli/commands/compact.ts", "../src/cli/commands/create.ts", "../src/cli/input.ts", "../src/cli/commands/destroy.ts", "../src/cli/commands/list.ts", "../src/shared/result.ts", "../src/shared/duration.ts", "../src/cli/commands/receive.ts", "../src/cli/commands/send.ts", "../src/cli/commands/status.ts", "../src/cli/commands/watch.ts", "../src/cli/program.ts", "../src/client/socket-fleet-client.ts", "../src/protocol/version.ts", "../src/protocol/jsonl.ts", "../node_modules/@sinclair/typebox/build/esm/type/guard/value.mjs", "../node_modules/@sinclair/typebox/build/esm/type/clone/value.mjs", "../node_modules/@sinclair/typebox/build/esm/type/clone/type.mjs", "../node_modules/@sinclair/typebox/build/esm/value/guard/guard.mjs", "../node_modules/@sinclair/typebox/build/esm/system/policy.mjs", "../node_modules/@sinclair/typebox/build/esm/type/create/immutable.mjs", "../node_modules/@sinclair/typebox/build/esm/type/create/type.mjs", "../node_modules/@sinclair/typebox/build/esm/type/error/error.mjs", "../node_modules/@sinclair/typebox/build/esm/type/symbols/symbols.mjs", "../node_modules/@sinclair/typebox/build/esm/type/guard/kind.mjs", "../node_modules/@sinclair/typebox/build/esm/type/guard/type.mjs", "../node_modules/@sinclair/typebox/build/esm/type/patterns/patterns.mjs", "../node_modules/@sinclair/typebox/build/esm/type/sets/set.mjs", "../node_modules/@sinclair/typebox/build/esm/type/any/any.mjs", "../node_modules/@sinclair/typebox/build/esm/type/array/array.mjs", "../node_modules/@sinclair/typebox/build/esm/type/argument/argument.mjs", "../node_modules/@sinclair/typebox/build/esm/type/async-iterator/async-iterator.mjs", "../node_modules/@sinclair/typebox/build/esm/type/computed/computed.mjs", "../node_modules/@sinclair/typebox/build/esm/type/discard/discard.mjs", "../node_modules/@sinclair/typebox/build/esm/type/never/never.mjs", "../node_modules/@sinclair/typebox/build/esm/type/mapped/mapped-result.mjs", "../node_modules/@sinclair/typebox/build/esm/type/constructor/constructor.mjs", "../node_modules/@sinclair/typebox/build/esm/type/function/function.mjs", "../node_modules/@sinclair/typebox/build/esm/type/union/union-create.mjs", "../node_modules/@sinclair/typebox/build/esm/type/union/union-evaluated.mjs", "../node_modules/@sinclair/typebox/build/esm/type/union/union.mjs", "../node_modules/@sinclair/typebox/build/esm/type/template-literal/parse.mjs", "../node_modules/@sinclair/typebox/build/esm/type/template-literal/finite.mjs", "../node_modules/@sinclair/typebox/build/esm/type/template-literal/generate.mjs", "../node_modules/@sinclair/typebox/build/esm/type/literal/literal.mjs", "../node_modules/@sinclair/typebox/build/esm/type/boolean/boolean.mjs", "../node_modules/@sinclair/typebox/build/esm/type/bigint/bigint.mjs", "../node_modules/@sinclair/typebox/build/esm/type/number/number.mjs", "../node_modules/@sinclair/typebox/build/esm/type/string/string.mjs", "../node_modules/@sinclair/typebox/build/esm/type/template-literal/syntax.mjs", "../node_modules/@sinclair/typebox/build/esm/type/template-literal/pattern.mjs", "../node_modules/@sinclair/typebox/build/esm/type/template-literal/union.mjs", "../node_modules/@sinclair/typebox/build/esm/type/template-literal/template-literal.mjs", "../node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-property-keys.mjs", "../node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-result.mjs", "../node_modules/@sinclair/typebox/build/esm/type/indexed/indexed.mjs", "../node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-key.mjs", "../node_modules/@sinclair/typebox/build/esm/type/iterator/iterator.mjs", "../node_modules/@sinclair/typebox/build/esm/type/object/object.mjs", "../node_modules/@sinclair/typebox/build/esm/type/promise/promise.mjs", "../node_modules/@sinclair/typebox/build/esm/type/readonly/readonly.mjs", "../node_modules/@sinclair/typebox/build/esm/type/readonly/readonly-from-mapped-result.mjs", "../node_modules/@sinclair/typebox/build/esm/type/tuple/tuple.mjs", "../node_modules/@sinclair/typebox/build/esm/type/mapped/mapped.mjs", "../node_modules/@sinclair/typebox/build/esm/type/optional/optional.mjs", "../node_modules/@sinclair/typebox/build/esm/type/optional/optional-from-mapped-result.mjs", "../node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-create.mjs", "../node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-evaluated.mjs", "../node_modules/@sinclair/typebox/build/esm/type/intersect/intersect.mjs", "../node_modules/@sinclair/typebox/build/esm/type/ref/ref.mjs", "../node_modules/@sinclair/typebox/build/esm/type/awaited/awaited.mjs", "../node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-property-keys.mjs", "../node_modules/@sinclair/typebox/build/esm/type/keyof/keyof.mjs", "../node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-from-mapped-result.mjs", "../node_modules/@sinclair/typebox/build/esm/type/composite/composite.mjs", "../node_modules/@sinclair/typebox/build/esm/type/date/date.mjs", "../node_modules/@sinclair/typebox/build/esm/type/null/null.mjs", "../node_modules/@sinclair/typebox/build/esm/type/symbol/symbol.mjs", "../node_modules/@sinclair/typebox/build/esm/type/undefined/undefined.mjs", "../node_modules/@sinclair/typebox/build/esm/type/uint8array/uint8array.mjs", "../node_modules/@sinclair/typebox/build/esm/type/unknown/unknown.mjs", "../node_modules/@sinclair/typebox/build/esm/type/const/const.mjs", "../node_modules/@sinclair/typebox/build/esm/type/constructor-parameters/constructor-parameters.mjs", "../node_modules/@sinclair/typebox/build/esm/type/enum/enum.mjs", "../node_modules/@sinclair/typebox/build/esm/type/extends/extends-check.mjs", "../node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-result.mjs", "../node_modules/@sinclair/typebox/build/esm/type/extends/extends.mjs", "../node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-key.mjs", "../node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-template-literal.mjs", "../node_modules/@sinclair/typebox/build/esm/type/exclude/exclude.mjs", "../node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-mapped-result.mjs", "../node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-template-literal.mjs", "../node_modules/@sinclair/typebox/build/esm/type/extract/extract.mjs", "../node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-mapped-result.mjs", "../node_modules/@sinclair/typebox/build/esm/type/instance-type/instance-type.mjs", "../node_modules/@sinclair/typebox/build/esm/type/readonly-optional/readonly-optional.mjs", "../node_modules/@sinclair/typebox/build/esm/type/record/record.mjs", "../node_modules/@sinclair/typebox/build/esm/type/instantiate/instantiate.mjs", "../node_modules/@sinclair/typebox/build/esm/type/integer/integer.mjs", "../node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic-from-mapped-key.mjs", "../node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic.mjs", "../node_modules/@sinclair/typebox/build/esm/type/intrinsic/capitalize.mjs", "../node_modules/@sinclair/typebox/build/esm/type/intrinsic/lowercase.mjs", "../node_modules/@sinclair/typebox/build/esm/type/intrinsic/uncapitalize.mjs", "../node_modules/@sinclair/typebox/build/esm/type/intrinsic/uppercase.mjs", "../node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-result.mjs", "../node_modules/@sinclair/typebox/build/esm/type/omit/omit.mjs", "../node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-key.mjs", "../node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-result.mjs", "../node_modules/@sinclair/typebox/build/esm/type/pick/pick.mjs", "../node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-key.mjs", "../node_modules/@sinclair/typebox/build/esm/type/partial/partial.mjs", "../node_modules/@sinclair/typebox/build/esm/type/partial/partial-from-mapped-result.mjs", "../node_modules/@sinclair/typebox/build/esm/type/required/required.mjs", "../node_modules/@sinclair/typebox/build/esm/type/required/required-from-mapped-result.mjs", "../node_modules/@sinclair/typebox/build/esm/type/module/compute.mjs", "../node_modules/@sinclair/typebox/build/esm/type/module/module.mjs", "../node_modules/@sinclair/typebox/build/esm/type/not/not.mjs", "../node_modules/@sinclair/typebox/build/esm/type/parameters/parameters.mjs", "../node_modules/@sinclair/typebox/build/esm/type/recursive/recursive.mjs", "../node_modules/@sinclair/typebox/build/esm/type/regexp/regexp.mjs", "../node_modules/@sinclair/typebox/build/esm/type/rest/rest.mjs", "../node_modules/@sinclair/typebox/build/esm/type/return-type/return-type.mjs", "../node_modules/@sinclair/typebox/build/esm/type/transform/transform.mjs", "../node_modules/@sinclair/typebox/build/esm/type/unsafe/unsafe.mjs", "../node_modules/@sinclair/typebox/build/esm/type/void/void.mjs", "../node_modules/@sinclair/typebox/build/esm/type/type/type.mjs", "../node_modules/@sinclair/typebox/build/esm/type/type/index.mjs", "../src/protocol/pi-identity.ts", "../src/pi/external-installation.ts", "../src/pi/process.ts", "../src/pi/external-target.ts", "../src/platform/client/start-runtime.ts", "../src/platform/install/runtime-release.ts", "../src/platform/install/tree-integrity.ts", "../src/platform/shared/paths.ts"],
|
|
4
|
+
"sourcesContent": ["import { randomUUID } from \"node:crypto\";\nimport { pathToFileURL } from \"node:url\";\nimport { CommanderError } from \"commander\";\n\nimport { splitArgv } from \"../cli/argv.js\";\nimport type { CliDependencies as Dependencies } from \"../cli/context.js\";\nimport { createProgram } from \"../cli/program.js\";\nimport { writeError } from \"../cli/output.js\";\nimport { SocketFleetClient } from \"../client/socket-fleet-client.js\";\nimport { resolveExternalPiInstallation } from \"../pi/external-installation.js\";\nimport { installationIdentity } from \"../pi/external-target.js\";\nimport { assertRegisteredPiSelection, ensureRuntime } from \"../platform/client/start-runtime.js\";\nimport { resolveFleetPaths } from \"../platform/shared/paths.js\";\n\nexport type CliDependencies = Dependencies;\n\nfunction defaultDependencies(): CliDependencies {\n const abort = new AbortController();\n const paths = resolveFleetPaths();\n let installation: ReturnType<typeof resolveExternalPiInstallation> | undefined;\n const selectedPi = () => (installation ??= resolveExternalPiInstallation({ env: process.env }));\n const mutationPi = async () => {\n const selected = await selectedPi();\n if (process.env.PIFLEET_DISABLE_REGISTERED_SERVICE !== \"1\") {\n await assertRegisteredPiSelection({\n selectedPath: selected.selectedPath,\n nodePath: selected.nodePath,\n });\n }\n return selected;\n };\n return {\n client: new SocketFleetClient({\n socketPath: paths.socketPath,\n beforeConnect: () =>\n ensureRuntime({\n socketPath: paths.socketPath,\n env: process.env,\n piInstallation: selectedPi,\n }),\n piIdentity: async () => installationIdentity(await mutationPi()),\n }),\n cwd: process.cwd(),\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n signal: abort.signal,\n operationIds: () => ({ operationId: randomUUID(), createdAt: new Date().toISOString() }),\n };\n}\n\nexport async function runCli(\n argv: readonly string[],\n dependencies: CliDependencies = defaultDependencies(),\n): Promise<number> {\n const split = splitArgv(argv);\n const commandName = split.fleetArgv[0];\n const human = commandName !== \"watch\" && split.fleetArgv.includes(\"--human\");\n\n if (split.piArgv.length > 0 && commandName !== \"create\") {\n writeError(\n dependencies.stderr,\n { code: \"invalid_arguments\", message: \"Only create accepts Pi arguments after --.\" },\n human,\n );\n return 1;\n }\n\n let exitCode = 0;\n const program = createProgram({ ...dependencies, piArgv: split.piArgv }, (value) => {\n exitCode = value;\n });\n\n if (split.fleetArgv.length === 0) {\n program.outputHelp();\n return 0;\n }\n\n try {\n await program.parseAsync([...split.fleetArgv], { from: \"user\" });\n return exitCode;\n } catch (error: unknown) {\n if (error instanceof CommanderError) {\n if (error.code === \"commander.helpDisplayed\" || error.code === \"commander.version\") return 0;\n writeError(\n dependencies.stderr,\n { code: \"invalid_arguments\", message: error.message.replace(/^error:\\s*/i, \"\") },\n human,\n );\n return 1;\n }\n const message = error instanceof Error ? error.message : \"Unexpected CLI error\";\n writeError(dependencies.stderr, { code: \"invalid_arguments\", message }, human);\n return 1;\n }\n}\n\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exitCode = await runCli(process.argv.slice(2));\n}\n", "/**\n * CommanderError class\n */\nexport class CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nexport class InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n", "import { InvalidArgumentError } from './error.js';\n\nexport class Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.endsWith('...')) {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nexport function humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n", "import { EventEmitter } from 'node:events';\nimport childProcess from 'node:child_process';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport process from 'node:process';\nimport { stripVTControlCharacters } from 'node:util';\n\nimport { Argument, humanReadableArgName } from './argument.js';\nimport { CommanderError } from './error.js';\nimport { Help } from './help.js';\nimport { Option, DualOptions } from './option.js';\nimport { suggestSimilar } from './suggestSimilar.js';\n\nexport class Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = false;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n this._savedState = null; // used in save/restoreStateBeforeParse\n\n // see configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n outputError: (str, write) => write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n getOutHasColors: () =>\n useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),\n getErrHasColors: () =>\n useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),\n stripColor: (str) => stripVTControlCharacters(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n /** @type {string | undefined} */\n this._helpGroupHeading = undefined; // soft initialised when added to parent\n /** @type {string | undefined} */\n this._defaultCommandGroup = undefined;\n /** @type {string | undefined} */\n this._defaultOptionGroup = undefined;\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // change how output being written, defaults to stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // change how output being written for errors, defaults to writeErr\n * outputError(str, write) // used for displaying errors and not used for displaying help\n * // specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // color support, currently only used with Help\n * getOutHasColors()\n * getErrHasColors()\n * stripColor() // used to remove ANSI escape codes if output does not have colors\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n this._outputConfiguration = {\n ...this._outputConfiguration,\n ...configuration,\n };\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom argument processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, parseArg, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof parseArg === 'function') {\n argument.default(defaultValue).argParser(parseArg);\n } else {\n argument.default(parseArg);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument?.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n if (enableOrNameAndArgs && this._defaultCommandGroup) {\n // make the command to store the group\n this._initCommandGroup(this._getHelpCommand());\n }\n return this;\n }\n\n const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n // init group unless lazy create\n if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n this._initCommandGroup(helpCommand);\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this._initOptionGroup(option);\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this._initCommandGroup(command);\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._collectValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n _prepareForParse() {\n // Save the state the first time, then restore the state before each subsequent parse.\n if (this._savedState === null) {\n // Do the special default of lone negated option to true, now that we have all the options.\n // Filter for negated options that have not been processed already.\n this.options\n .filter(\n (option) =>\n option.negate &&\n option.defaultValue === undefined &&\n this.getOptionValue(option.attributeName()) === undefined,\n )\n .forEach((option) => {\n // check for lone negated option: --no-foo without a --foo option\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n option.attributeName(),\n true,\n 'default',\n );\n }\n });\n\n this.saveStateBeforeParse();\n } else {\n this.restoreStateBeforeParse();\n }\n }\n\n /**\n * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state saved.\n */\n saveStateBeforeParse() {\n this._savedState = {\n // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing\n _name: this._name,\n // option values before parse have default values (including false for negated options)\n // shallow clones\n _optionValues: { ...this._optionValues },\n _optionValueSources: { ...this._optionValueSources },\n };\n }\n\n /**\n * Restore state before parse for calls after the first.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state restored.\n */\n restoreStateBeforeParse() {\n if (this._storeOptionsAsProperties)\n throw new Error(`Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties`);\n\n // clear state from _prepareUserArgs\n this._name = this._savedState._name;\n this._scriptPath = null;\n this.rawArgs = [];\n // clear state from setOptionValueWithSource\n this._optionValues = { ...this._savedState._optionValues };\n this._optionValueSources = { ...this._savedState._optionValueSources };\n // clear state from _parseCommand\n this.args = [];\n // clear state from _processArguments\n this.processedArgs = [];\n }\n\n /**\n * Throw if expected executable is missing. Add lots of help for author.\n *\n * @param {string} executableFile\n * @param {string} executableDir\n * @param {string} subcommandName\n */\n _checkForMissingExecutable(executableFile, executableDir, subcommandName) {\n if (fs.existsSync(executableFile)) return;\n\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n const launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n subCommand._prepareForParse();\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise?.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent?.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Side effects: modifies command by storing options. Does not reset state if called again.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} args\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(args) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n const negativeNumberArg = (arg) => {\n // return false if not a negative number\n if (!/^-(\\d+|\\d*\\.\\d+)(e[+-]?\\d+)?$/.test(arg)) return false;\n // negative number is ok unless digit used as an option in command hierarchy\n return !this._getCommandAndAncestors().some((cmd) =>\n cmd.options\n .map((opt) => opt.short)\n .some((short) => /^-\\d$/.test(short)),\n );\n };\n\n // parse options\n let activeVariadicOption = null;\n let activeGroup = null; // working through group of short options, like -abc\n let i = 0;\n while (i < args.length || activeGroup) {\n const arg = activeGroup ?? args[i++];\n activeGroup = null;\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args.slice(i));\n break;\n }\n\n if (\n activeVariadicOption &&\n (!maybeOption(arg) || negativeNumberArg(arg))\n ) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args[i++];\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (\n i < args.length &&\n (!maybeOption(args[i]) || negativeNumberArg(args[i]))\n ) {\n value = args[i++];\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option\n this.emit(`option:${option.name()}`);\n // remove the processed option and keep processing group\n activeGroup = `-${arg.slice(2)}`;\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n // A negative number in a leaf command is not an unknown option.\n if (\n dest === operands &&\n maybeOption(arg) &&\n !(this.commands.length === 0 && negativeNumberArg(arg))\n ) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n unknown.push(...args.slice(i));\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg, ...args.slice(i));\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg, ...args.slice(i));\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg, ...args.slice(i));\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const received = receivedArgs.length;\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const details = receivedArgs.join(', ');\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set/get the help group heading for this subcommand in parent command's help.\n *\n * @param {string} [heading]\n * @return {Command | string}\n */\n\n helpGroup(heading) {\n if (heading === undefined) return this._helpGroupHeading ?? '';\n this._helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for subcommands added to this command.\n * (This does not override a group set directly on the subcommand using .helpGroup().)\n *\n * @example\n * program.commandsGroup('Development Commands:);\n * program.command('watch')...\n * program.command('lint')...\n * ...\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n commandsGroup(heading) {\n if (heading === undefined) return this._defaultCommandGroup ?? '';\n this._defaultCommandGroup = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for options added to this command.\n * (This does not override a group set directly on the option using .helpGroup().)\n *\n * @example\n * program\n * .optionsGroup('Development Options:')\n * .option('-d, --debug', 'output extra debugging')\n * .option('-p, --profile', 'output profiling information')\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n optionsGroup(heading) {\n if (heading === undefined) return this._defaultOptionGroup ?? '';\n this._defaultOptionGroup = heading;\n return this;\n }\n\n /**\n * @param {Option} option\n * @private\n */\n _initOptionGroup(option) {\n if (this._defaultOptionGroup && !option.helpGroupHeading)\n option.helpGroup(this._defaultOptionGroup);\n }\n\n /**\n * @param {Command} cmd\n * @private\n */\n _initCommandGroup(cmd) {\n if (this._defaultCommandGroup && !cmd.helpGroup())\n cmd.helpGroup(this._defaultCommandGroup);\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or import.meta.filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(import.meta.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(import.meta.dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n const context = this._getOutputContext(contextOptions);\n helper.prepareContext({\n error: context.error,\n helpWidth: context.helpWidth,\n outputHasColors: context.hasColors,\n });\n const text = helper.formatHelp(this, helper);\n if (context.hasColors) return text;\n return this._outputConfiguration.stripColor(text);\n }\n\n /**\n * @typedef HelpContext\n * @type {object}\n * @property {boolean} error\n * @property {number} helpWidth\n * @property {boolean} hasColors\n * @property {function} write - includes stripColor if needed\n *\n * @returns {HelpContext}\n * @private\n */\n\n _getOutputContext(contextOptions) {\n contextOptions = contextOptions || {};\n const error = !!contextOptions.error;\n let baseWrite;\n let hasColors;\n let helpWidth;\n if (error) {\n baseWrite = (str) => this._outputConfiguration.writeErr(str);\n hasColors = this._outputConfiguration.getErrHasColors();\n helpWidth = this._outputConfiguration.getErrHelpWidth();\n } else {\n baseWrite = (str) => this._outputConfiguration.writeOut(str);\n hasColors = this._outputConfiguration.getOutHasColors();\n helpWidth = this._outputConfiguration.getOutHelpWidth();\n }\n const write = (str) => {\n if (!hasColors) str = this._outputConfiguration.stripColor(str);\n return baseWrite(str);\n };\n return { error, write, hasColors, helpWidth };\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n\n const outputContext = this._getOutputContext(contextOptions);\n /** @type {HelpTextEventContext} */\n const eventContext = {\n error: outputContext.error,\n write: outputContext.write,\n command: this,\n };\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', eventContext));\n this.emit('beforeHelp', eventContext);\n\n let helpInformation = this.helpInformation({ error: outputContext.error });\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n outputContext.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', eventContext);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', eventContext),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support enabling/disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n if (this._helpOption === null) this._helpOption = undefined; // reenable\n if (this._defaultOptionGroup) {\n // make the option to store the group\n this._initOptionGroup(this._getHelpOption());\n }\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n this._helpOption = this.createOption(\n flags ?? '-h, --help',\n description ?? 'display help for command',\n );\n // init group unless lazy create\n if (flags || description) this._initOptionGroup(this._helpOption);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n this._initOptionGroup(option);\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * // Do a little typing to coordinate emit and listener for the help text events.\n * @typedef HelpTextEventContext\n * @type {object}\n * @property {boolean} error\n * @property {Command} command\n * @property {function} write\n */\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\n/**\n * Exported for using from tests, not otherwise used outside this file.\n *\n * @returns {boolean | undefined}\n * @package\n */\nexport function useColor() {\n // Test for common conventions.\n // NB: the observed behaviour is in combination with how author adds color! For example:\n // - we do not test NODE_DISABLE_COLORS, but util:styletext does\n // - we do test NO_COLOR, but Chalk does not\n //\n // References:\n // https://no-color.org\n // https://bixense.com/clicolors/\n // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109\n // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33\n // (https://force-color.org recent web page from 2023, does not match major javascript implementations)\n\n if (\n process.env.NO_COLOR ||\n process.env.FORCE_COLOR === '0' ||\n process.env.FORCE_COLOR === 'false'\n )\n return false;\n if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)\n return true;\n return undefined;\n}\n", "import { humanReadableArgName } from './argument.js';\nimport { stripVTControlCharacters } from 'node:util';\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nexport class Help {\n constructor() {\n this.helpWidth = undefined;\n this.minWidthToWrap = 40;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`\n * and just before calling `formatHelp()`.\n *\n * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.\n *\n * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions\n */\n prepareContext(contextOptions) {\n this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleSubcommandTerm(helper.subcommandTerm(command)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (option.description) {\n return `${option.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n return argument.description;\n }\n\n /**\n * Format a list of items, given a heading and an array of formatted items.\n *\n * @param {string} heading\n * @param {string[]} items\n * @param {Help} helper\n * @returns string[]\n */\n formatItemList(heading, items, helper) {\n if (items.length === 0) return [];\n\n return [helper.styleTitle(heading), ...items, ''];\n }\n\n /**\n * Group items by their help group heading.\n *\n * @param {Command[] | Option[]} unsortedItems\n * @param {Command[] | Option[]} visibleItems\n * @param {Function} getGroup\n * @returns {Map<string, Command[] | Option[]>}\n */\n groupItems(unsortedItems, visibleItems, getGroup) {\n const result = new Map();\n // Add groups in order of appearance in unsortedItems.\n unsortedItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) result.set(group, []);\n });\n // Add items in order of appearance in visibleItems.\n visibleItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) {\n result.set(group, []);\n }\n result.get(group).push(item);\n });\n return result;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called\n\n function callFormatItem(term, description) {\n return helper.formatItem(term, termWidth, description, helper);\n }\n\n // Usage\n let output = [\n `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n '',\n ];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.boxWrap(\n helper.styleCommandDescription(commandDescription),\n helpWidth,\n ),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return callFormatItem(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n helper.styleArgumentDescription(helper.argumentDescription(argument)),\n );\n });\n output = output.concat(\n this.formatItemList('Arguments:', argumentList, helper),\n );\n\n // Options\n const optionGroups = this.groupItems(\n cmd.options,\n helper.visibleOptions(cmd),\n (option) => option.helpGroupHeading ?? 'Options:',\n );\n optionGroups.forEach((options, group) => {\n const optionList = options.map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(this.formatItemList(group, optionList, helper));\n });\n\n if (helper.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(\n this.formatItemList('Global Options:', globalOptionList, helper),\n );\n }\n\n // Commands\n const commandGroups = this.groupItems(\n cmd.commands,\n helper.visibleCommands(cmd),\n (sub) => sub.helpGroup() || 'Commands:',\n );\n commandGroups.forEach((commands, group) => {\n const commandList = commands.map((sub) => {\n return callFormatItem(\n helper.styleSubcommandTerm(helper.subcommandTerm(sub)),\n helper.styleSubcommandDescription(helper.subcommandDescription(sub)),\n );\n });\n output = output.concat(this.formatItemList(group, commandList, helper));\n });\n\n return output.join('\\n');\n }\n\n /**\n * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.\n *\n * @param {string} str\n * @returns {number}\n */\n displayWidth(str) {\n return stripVTControlCharacters(str).length;\n }\n\n /**\n * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.\n *\n * @param {string} str\n * @returns {string}\n */\n styleTitle(str) {\n return str;\n }\n\n styleUsage(str) {\n // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:\n // command subcommand [options] [command] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word === '[command]') return this.styleSubcommandText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleCommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleCommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleOptionDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleSubcommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleArgumentDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleDescriptionText(str) {\n return str;\n }\n styleOptionTerm(str) {\n return this.styleOptionText(str);\n }\n styleSubcommandTerm(str) {\n // This is very like usage with lots of parts! Assume default string which is formed like:\n // subcommand [options] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleSubcommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleArgumentTerm(str) {\n return this.styleArgumentText(str);\n }\n styleOptionText(str) {\n return str;\n }\n styleArgumentText(str) {\n return str;\n }\n styleSubcommandText(str) {\n return str;\n }\n styleCommandText(str) {\n return str;\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Detect manually wrapped and indented strings by checking for line break followed by whitespace.\n *\n * @param {string} str\n * @returns {boolean}\n */\n preformatted(str) {\n return /\\n[^\\S\\r\\n]/.test(str);\n }\n\n /**\n * Format the \"item\", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.\n *\n * So \"TTT\", 5, \"DDD DDDD DD DDD\" might be formatted for this.helpWidth=17 like so:\n * TTT DDD DDDD\n * DD DDD\n *\n * @param {string} term\n * @param {number} termWidth\n * @param {string} description\n * @param {Help} helper\n * @returns {string}\n */\n formatItem(term, termWidth, description, helper) {\n const itemIndent = 2;\n const itemIndentStr = ' '.repeat(itemIndent);\n if (!description) return itemIndentStr + term;\n\n // Pad the term out to a consistent width, so descriptions are aligned.\n const paddedTerm = term.padEnd(\n termWidth + term.length - helper.displayWidth(term),\n );\n\n // Format the description.\n const spacerWidth = 2; // between term and description\n const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called\n const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;\n let formattedDescription;\n if (\n remainingWidth < this.minWidthToWrap ||\n helper.preformatted(description)\n ) {\n formattedDescription = description;\n } else {\n const wrappedDescription = helper.boxWrap(description, remainingWidth);\n formattedDescription = wrappedDescription.replace(\n /\\n/g,\n '\\n' + ' '.repeat(termWidth + spacerWidth),\n );\n }\n\n // Construct and overall indent.\n return (\n itemIndentStr +\n paddedTerm +\n ' '.repeat(spacerWidth) +\n formattedDescription.replace(/\\n/g, `\\n${itemIndentStr}`)\n );\n }\n\n /**\n * Wrap a string at whitespace, preserving existing line breaks.\n * Wrapping is skipped if the width is less than `minWidthToWrap`.\n *\n * @param {string} str\n * @param {number} width\n * @returns {string}\n */\n boxWrap(str, width) {\n if (width < this.minWidthToWrap) return str;\n\n const rawLines = str.split(/\\r\\n|\\n/);\n // split up text by whitespace\n const chunkPattern = /[\\s]*[^\\s]+/g;\n const wrappedLines = [];\n rawLines.forEach((line) => {\n const chunks = line.match(chunkPattern);\n if (chunks === null) {\n wrappedLines.push('');\n return;\n }\n\n let sumChunks = [chunks.shift()];\n let sumWidth = this.displayWidth(sumChunks[0]);\n chunks.forEach((chunk) => {\n const visibleWidth = this.displayWidth(chunk);\n // Accumulate chunks while they fit into width.\n if (sumWidth + visibleWidth <= width) {\n sumChunks.push(chunk);\n sumWidth += visibleWidth;\n return;\n }\n wrappedLines.push(sumChunks.join(''));\n\n const nextChunk = chunk.trimStart(); // trim space at line break\n sumChunks = [nextChunk];\n sumWidth = this.displayWidth(nextChunk);\n });\n wrappedLines.push(sumChunks.join(''));\n });\n\n return wrappedLines.join('\\n');\n }\n}\n", "import { InvalidArgumentError } from './error.js';\n\nexport class Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n this.helpGroupHeading = undefined; // soft initialised when option added to command\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as an object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n if (this.negate) {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n return camelcase(this.name());\n }\n\n /**\n * Set the help group heading.\n *\n * @param {string} heading\n * @return {Option}\n */\n helpGroup(heading) {\n this.helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nexport class DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // short flag, single dash and single character\n const shortFlagExp = /^-[^-]$/;\n // long flag, double dash and at least one character\n const longFlagExp = /^--[^-]/;\n\n const flagParts = flags.split(/[ |,]+/).concat('guard');\n // Normal is short and/or long.\n if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();\n if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();\n // Long then short. Rarely used but fine.\n if (!shortFlag && shortFlagExp.test(flagParts[0]))\n shortFlag = flagParts.shift();\n // Allow two long flags, like '--ws, --workspace'\n // This is the supported way to have a shortish option flag.\n if (!shortFlag && longFlagExp.test(flagParts[0])) {\n shortFlag = longFlag;\n longFlag = flagParts.shift();\n }\n\n // Check for unprocessed flag. Fail noisily rather than silently ignore.\n if (flagParts[0].startsWith('-')) {\n const unsupportedFlag = flagParts[0];\n const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;\n if (/^-[^-][^-]/.test(unsupportedFlag))\n throw new Error(\n `${baseError}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,\n );\n if (shortFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many short flags`);\n if (longFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many long flags`);\n\n throw new Error(`${baseError}\n- unrecognised flag format`);\n }\n if (shortFlag === undefined && longFlag === undefined)\n throw new Error(\n `option creation failed due to no flags found in '${flags}'.`,\n );\n\n return { shortFlag, longFlag };\n}\n", "const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau\u2013Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nexport function suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n", "import { Argument } from './lib/argument.js';\nimport { Command } from './lib/command.js';\nimport { CommanderError, InvalidArgumentError } from './lib/error.js';\nimport { Help } from './lib/help.js';\nimport { Option } from './lib/option.js';\n\nexport const program = new Command();\n\nexport const createCommand = (name) => new Command(name);\nexport const createOption = (flags, description) =>\n new Option(flags, description);\nexport const createArgument = (name, description) =>\n new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexport { Command, Option, Argument, Help };\nexport { CommanderError, InvalidArgumentError };\nexport { InvalidArgumentError as InvalidOptionArgumentError }; // Deprecated\n", "export interface SplitArgv {\n readonly fleetArgv: readonly string[];\n readonly piArgv: readonly string[];\n readonly hadSeparator: boolean;\n}\n\nexport function splitArgv(argv: readonly string[]): SplitArgv {\n const separator = argv.indexOf(\"--\");\n if (separator < 0) {\n return { fleetArgv: [...argv], piArgv: [], hadSeparator: false };\n }\n return {\n fleetArgv: argv.slice(0, separator),\n piArgv: argv.slice(separator + 1),\n hadSeparator: true,\n };\n}\n", "export const PRODUCT_NAME = \"pi-fleet\";\nexport const PRODUCT_BINARY = \"pifleet\";\nexport const PRODUCT_VERSION = \"0.1.0-beta.10\";\n", "export type AgentName = string & { readonly __brand: \"AgentName\" };\n\nconst AGENT_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\nexport function isAgentName(value: string): value is AgentName {\n return AGENT_NAME_PATTERN.test(value);\n}\n", "import type { Writable } from \"node:stream\";\n\nimport type {\n CompactResult,\n CreateResult,\n DestroyResult,\n FleetClientError,\n ListResult,\n ReceiveResult,\n SendResult,\n StatusResult,\n} from \"../client/fleet-client.js\";\n\ntype FiniteResult =\n | CreateResult\n | SendResult\n | ReceiveResult\n | StatusResult\n | ListResult\n | DestroyResult\n | CompactResult;\n\nexport function writeResult(stream: Writable, result: FiniteResult, human: boolean): void {\n stream.write(human ? `${renderHuman(result)}\\n` : `${JSON.stringify(result)}\\n`);\n}\n\nexport function writeWatchReady(stream: Writable, name: string): void {\n stream.write(`${JSON.stringify({ schemaVersion: 1, type: \"watch.ready\", agent: { name } })}\\n`);\n}\n\nexport function writeError(stream: Writable, error: FleetClientError, human: boolean): void {\n if (human) {\n stream.write(`${error.message}\\n`);\n return;\n }\n stream.write(`${JSON.stringify({ schemaVersion: 1, type: \"error\", error })}\\n`);\n}\n\nfunction renderHuman(result: FiniteResult): string {\n switch (result.type) {\n case \"agent.created\":\n return `${result.agent.name}: ${result.agent.state} (${result.agent.process.state})`;\n case \"message.accepted\":\n return `${result.agent.name}: message accepted`;\n case \"response\":\n return result.response.text;\n case \"agent.status\":\n return `${result.agent.name}: ${result.agent.state} (${result.agent.process.state})`;\n case \"agent.list\":\n return result.agents.length === 0\n ? \"No agents\"\n : result.agents\n .map((agent) => `${agent.name}\\t${agent.state}\\t${agent.process.state}`)\n .join(\"\\n\");\n case \"agent.destroyed\":\n return `${result.agent.name}: destroyed`;\n case \"agent.compacted\":\n return `${result.agent.name}: compacted (${String(result.compaction.tokensBefore)} \u2192 ${String(result.compaction.estimatedTokensAfter ?? \"unknown\")} estimated tokens)`;\n }\n}\n", "import type { FleetClientError } from \"../../client/fleet-client.js\";\nimport type { Result } from \"../../shared/result.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { writeError, writeResult } from \"../output.js\";\n\nexport function finishFinite<T extends Parameters<typeof writeResult>[1]>(\n result: Result<T, FleetClientError>,\n context: CommandContext,\n human: boolean,\n): number {\n if (result.ok) {\n writeResult(context.stdout, result.value, human);\n return 0;\n }\n writeError(context.stderr, result.error, human);\n return result.error.code === \"timeout\" ? 124 : 1;\n}\n\nexport function invalidArguments(message: string): FleetClientError {\n return { code: \"invalid_arguments\", message };\n}\n", "import { isAgentName } from \"../../shared/identifiers.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport async function runCompact(\n input: { readonly name: string; readonly human: boolean },\n context: CommandContext,\n): Promise<number> {\n if (!isAgentName(input.name)) throw new Error(\"invalid agent name\");\n const result = await context.client.compact(\n { name: input.name },\n { signal: context.signal, operation: context.operationIds() },\n );\n return finishFinite(result, context, input.human);\n}\n", "import { resolve } from \"node:path\";\n\nimport { isAgentName } from \"../../shared/identifiers.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { resolveMessageInput } from \"../input.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport interface CreateCommandInput {\n readonly name: string;\n readonly instructions?: string;\n readonly cwd?: string;\n readonly human: boolean;\n}\n\nexport async function runCreate(\n input: CreateCommandInput,\n context: CommandContext,\n): Promise<number> {\n if (!isAgentName(input.name)) throw new Error(\"invalid agent name\");\n const instructions =\n input.instructions === undefined\n ? undefined\n : await resolveMessageInput(input.instructions, context.stdin);\n const result = await context.client.create(\n {\n name: input.name,\n ...(instructions === undefined ? {} : { instructions }),\n cwd: resolve(context.cwd, input.cwd ?? \".\"),\n piArgv: context.piArgv,\n },\n { signal: context.signal, operation: context.operationIds() },\n );\n return finishFinite(result, context, input.human);\n}\n", "import type { Readable } from \"node:stream\";\n\nconst DEFAULT_MAX_INPUT_BYTES = 512 * 1024;\n\nexport async function resolveMessageInput(\n value: string,\n stdin: Readable,\n maxBytes = DEFAULT_MAX_INPUT_BYTES,\n): Promise<string> {\n if (value !== \"-\") return requireContent(value);\n\n const chunks: Buffer[] = [];\n let bytes = 0;\n for await (const chunk of stdin) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));\n bytes += buffer.length;\n if (bytes > maxBytes) throw new Error(`stdin exceeds the ${maxBytes}-byte limit`);\n chunks.push(buffer);\n }\n let decoded: string;\n try {\n decoded = new TextDecoder(\"utf-8\", { fatal: true }).decode(Buffer.concat(chunks));\n } catch {\n throw new Error(\"stdin must be valid UTF-8\");\n }\n return requireContent(decoded);\n}\n\nfunction requireContent(value: string): string {\n if (value.trim().length === 0) throw new Error(\"message must not be empty or whitespace-only\");\n return value;\n}\n", "import { isAgentName } from \"../../shared/identifiers.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport async function runDestroy(\n input: { readonly name: string; readonly human: boolean },\n context: CommandContext,\n): Promise<number> {\n if (!isAgentName(input.name)) throw new Error(\"invalid agent name\");\n const result = await context.client.destroy(\n { name: input.name },\n { signal: context.signal, operation: context.operationIds() },\n );\n return finishFinite(result, context, input.human);\n}\n", "import type { CommandContext } from \"../context.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport async function runList(\n input: { readonly human: boolean },\n context: CommandContext,\n): Promise<number> {\n const result = await context.client.list({ signal: context.signal });\n return finishFinite(result, context, input.human);\n}\n", "export type Result<Value, Error> =\n | { readonly ok: true; readonly value: Value }\n | { readonly ok: false; readonly error: Error };\n\nexport function ok<Value>(value: Value): Result<Value, never> {\n return { ok: true, value };\n}\n\nexport function err<Error>(error: Error): Result<never, Error> {\n return { ok: false, error };\n}\n", "import { err, ok, type Result } from \"./result.js\";\n\ntype DurationParseError = \"invalid_duration\";\n\nconst UNIT_TO_MILLISECONDS = {\n ms: 1,\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n} as const;\n\nexport function parseDuration(input: string): Result<number, DurationParseError> {\n const match = /^(\\d+)(ms|s|m|h)?$/.exec(input);\n\n if (match === null) {\n return err(\"invalid_duration\");\n }\n\n const amount = Number(match[1]);\n const unit = match[2] ?? \"ms\";\n\n return ok(amount * UNIT_TO_MILLISECONDS[unit as keyof typeof UNIT_TO_MILLISECONDS]);\n}\n", "import { isAgentName } from \"../../shared/identifiers.js\";\nimport { parseDuration } from \"../../shared/duration.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport interface ReceiveCommandInput {\n readonly name: string;\n readonly timeout?: string;\n readonly human: boolean;\n}\n\nexport async function runReceive(\n input: ReceiveCommandInput,\n context: CommandContext,\n): Promise<number> {\n if (!isAgentName(input.name)) throw new Error(\"invalid agent name\");\n const parsedTimeout = input.timeout === undefined ? undefined : parseDuration(input.timeout);\n if (parsedTimeout !== undefined && !parsedTimeout.ok) throw new Error(\"invalid timeout duration\");\n const timeoutMs = parsedTimeout?.ok === true ? parsedTimeout.value : undefined;\n const result = await context.client.receive(\n { name: input.name },\n { signal: context.signal, ...(timeoutMs === undefined ? {} : { timeoutMs }) },\n );\n return finishFinite(result, context, input.human);\n}\n", "import { isAgentName } from \"../../shared/identifiers.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { resolveMessageInput } from \"../input.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport interface SendCommandInput {\n readonly name: string;\n readonly message: string;\n readonly human: boolean;\n}\n\nexport async function runSend(input: SendCommandInput, context: CommandContext): Promise<number> {\n if (!isAgentName(input.name)) throw new Error(\"invalid agent name\");\n const message = await resolveMessageInput(input.message, context.stdin);\n const result = await context.client.send(\n { name: input.name, message },\n { signal: context.signal, operation: context.operationIds() },\n );\n return finishFinite(result, context, input.human);\n}\n", "import { isAgentName } from \"../../shared/identifiers.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { finishFinite } from \"./common.js\";\n\nexport async function runStatus(\n input: { readonly name: string; readonly human: boolean },\n context: CommandContext,\n): Promise<number> {\n if (!isAgentName(input.name)) throw new Error(\"invalid agent name\");\n const result = await context.client.status({ name: input.name }, { signal: context.signal });\n return finishFinite(result, context, input.human);\n}\n", "import { once } from \"node:events\";\n\nimport { isAgentName } from \"../../shared/identifiers.js\";\nimport type { CommandContext } from \"../context.js\";\nimport { writeError, writeWatchReady } from \"../output.js\";\n\nexport async function runWatch(name: string, context: CommandContext): Promise<number> {\n if (!isAgentName(name)) throw new Error(\"invalid agent name\");\n try {\n for await (const result of context.client.watch({ name }, { signal: context.signal })) {\n if (!result.ok) {\n writeError(context.stderr, result.error, false);\n return 1;\n }\n if (result.value.type === \"ready\") {\n writeWatchReady(context.stderr, name);\n continue;\n }\n if (!context.stdout.write(result.value.bytes)) await once(context.stdout, \"drain\");\n }\n return 0;\n } catch (error: unknown) {\n if ((error as NodeJS.ErrnoException).code === \"EPIPE\") return 0;\n throw error;\n }\n}\n", "import { Command } from \"commander\";\n\nimport { PRODUCT_BINARY, PRODUCT_VERSION } from \"../shared/product-identity.js\";\nimport type { CommandContext } from \"./context.js\";\nimport { runCompact } from \"./commands/compact.js\";\nimport { runCreate } from \"./commands/create.js\";\nimport { runDestroy } from \"./commands/destroy.js\";\nimport { runList } from \"./commands/list.js\";\nimport { runReceive } from \"./commands/receive.js\";\nimport { runSend } from \"./commands/send.js\";\nimport { runStatus } from \"./commands/status.js\";\nimport { runWatch } from \"./commands/watch.js\";\n\nexport function createProgram(\n context: CommandContext,\n setExitCode: (exitCode: number) => void,\n): Command {\n const program = new Command()\n .name(PRODUCT_BINARY)\n .description(\"Pi-native execution infrastructure for programmatic orchestration\")\n .version(PRODUCT_VERSION)\n .exitOverride()\n .showHelpAfterError(false)\n .showSuggestionAfterError(false)\n .configureOutput({\n writeOut: (text) => context.stdout.write(text),\n writeErr: () => undefined,\n });\n\n program\n .command(\"create\")\n .description(\"Create a Pi agent with a stable local name\")\n .argument(\"<name>\")\n .argument(\"[instructions]\")\n .option(\"--cwd <path>\")\n .option(\"--human\")\n .action(async (name: string, instructions: string | undefined, options: CreateOptions) => {\n setExitCode(\n await runCreate(\n {\n name,\n ...(instructions === undefined ? {} : { instructions }),\n ...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n human: options.human ?? false,\n },\n context,\n ),\n );\n });\n\n program\n .command(\"send\")\n .description(\"Submit or steer Pi input\")\n .argument(\"<name>\")\n .argument(\"<message>\")\n .option(\"--human\")\n .action(async (name: string, message: string, options: HumanOptions) => {\n setExitCode(await runSend({ name, message, human: options.human ?? false }, context));\n });\n\n program\n .command(\"receive\")\n .description(\"Wait for idle and return the exact latest assistant text\")\n .argument(\"<name>\")\n .option(\"--timeout <duration>\")\n .option(\"--human\")\n .action(async (name: string, options: ReceiveOptions) => {\n setExitCode(\n await runReceive(\n {\n name,\n ...(options.timeout === undefined ? {} : { timeout: options.timeout }),\n human: options.human ?? false,\n },\n context,\n ),\n );\n });\n\n program\n .command(\"status\")\n .description(\"Inspect an agent without waking Pi\")\n .argument(\"<name>\")\n .option(\"--human\")\n .action(async (name: string, options: HumanOptions) => {\n setExitCode(await runStatus({ name, human: options.human ?? false }, context));\n });\n\n program\n .command(\"list\")\n .description(\"List agents without waking Pi\")\n .option(\"--human\")\n .action(async (options: HumanOptions) => {\n setExitCode(await runList({ human: options.human ?? false }, context));\n });\n\n program\n .command(\"watch\")\n .description(\"Stream live raw Pi RPC JSONL\")\n .argument(\"<name>\")\n .action(async (name: string) => {\n setExitCode(await runWatch(name, context));\n });\n\n program\n .command(\"compact\")\n .description(\"Compact an idle Pi agent session\")\n .argument(\"<name>\")\n .option(\"--human\")\n .action(async (name: string, options: HumanOptions) => {\n setExitCode(await runCompact({ name, human: options.human ?? false }, context));\n });\n\n program\n .command(\"destroy\")\n .description(\"Destroy an agent without deleting its Pi session\")\n .argument(\"<name>\")\n .option(\"--human\")\n .action(async (name: string, options: HumanOptions) => {\n setExitCode(await runDestroy({ name, human: options.human ?? false }, context));\n });\n\n return program;\n}\n\ninterface HumanOptions {\n readonly human?: boolean;\n}\n\ninterface CreateOptions extends HumanOptions {\n readonly cwd?: string;\n}\n\ninterface ReceiveOptions extends HumanOptions {\n readonly timeout?: string;\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { createConnection, type Socket } from \"node:net\";\n\nimport { readJsonLines, writeJsonLine } from \"../protocol/jsonl.js\";\nimport { MANAGED_PI_RUNTIME_IDENTITY, type PiRuntimeIdentity } from \"../protocol/pi-identity.js\";\nimport { PROTOCOL_VERSION } from \"../protocol/version.js\";\nimport { err, ok, type Result } from \"../shared/result.js\";\nimport type {\n CreateInput,\n CompactInput,\n CompactResult,\n CreateResult,\n DestroyInput,\n DestroyResult,\n FleetClient,\n FleetClientError,\n ListResult,\n MutationOptions,\n WatchStreamItem,\n ReceiveInput,\n ReceiveResult,\n RequestOptions,\n SendInput,\n SendResult,\n StatusInput,\n StatusResult,\n WatchInput,\n} from \"./fleet-client.js\";\n\nexport class SocketFleetClient implements FleetClient {\n constructor(\n private readonly options: {\n readonly socketPath: string;\n readonly beforeConnect?: () => Promise<void>;\n readonly piIdentity?: PiRuntimeIdentity | (() => Promise<PiRuntimeIdentity>);\n },\n ) {}\n\n create(\n input: CreateInput,\n options: MutationOptions,\n ): Promise<Result<CreateResult, FleetClientError>> {\n return this.#request(\"agent.create\", input, options);\n }\n\n send(input: SendInput, options: MutationOptions): Promise<Result<SendResult, FleetClientError>> {\n return this.#request(\"agent.send\", input, options);\n }\n\n receive(\n input: ReceiveInput,\n options: RequestOptions,\n ): Promise<Result<ReceiveResult, FleetClientError>> {\n return this.#request(\"agent.receive\", { ...input, timeoutMs: options.timeoutMs }, options);\n }\n\n status(\n input: StatusInput,\n options: RequestOptions,\n ): Promise<Result<StatusResult, FleetClientError>> {\n return this.#request(\"agent.status\", input, options);\n }\n\n list(options: RequestOptions): Promise<Result<ListResult, FleetClientError>> {\n return this.#request(\"agent.list\", {}, options);\n }\n\n async *watch(\n input: WatchInput,\n options: RequestOptions,\n ): AsyncIterable<Result<WatchStreamItem, FleetClientError>> {\n let socket: Socket;\n try {\n await this.options.beforeConnect?.();\n socket = await connect(this.options.socketPath, options.signal);\n } catch (error: unknown) {\n yield err(connectionError(error));\n return;\n }\n\n const requestId = randomUUID();\n const frames = frameIterator(socket, options.signal);\n writeJsonLine(socket, {\n v: PROTOCOL_VERSION,\n requestId,\n method: \"agent.watch\",\n params: input,\n });\n\n let endedExplicitly = false;\n try {\n for await (const frame of frames) {\n if (!isRecord(frame) || frame.requestId !== requestId) continue;\n if (frame.v !== PROTOCOL_VERSION) {\n yield err({\n code: \"protocol_incompatible\",\n message:\n \"The running pi-fleet runtime is incompatible with this client; repair or restart it.\",\n });\n return;\n }\n if (frame.stream === \"ready\") {\n yield ok({ type: \"ready\" });\n continue;\n }\n if (frame.stream === \"end\") {\n endedExplicitly = true;\n return;\n }\n if (frame.stream === \"chunk\" && typeof frame.data === \"string\") {\n yield ok({ type: \"chunk\", bytes: Buffer.from(frame.data, \"base64\") });\n continue;\n }\n if (frame.stream === \"error\" && isErrorRecord(frame.error)) {\n yield err(frame.error);\n return;\n }\n yield err({ code: \"protocol_error\", message: \"Invalid watch stream frame.\" });\n return;\n }\n if (!endedExplicitly && !options.signal.aborted) {\n yield err({\n code: \"runtime_unavailable\",\n message: \"Runtime connection closed before the watch stream ended.\",\n });\n }\n } catch (error: unknown) {\n if (!options.signal.aborted) yield err(connectionError(error));\n } finally {\n socket.destroy();\n }\n }\n\n destroy(\n input: DestroyInput,\n options: MutationOptions,\n ): Promise<Result<DestroyResult, FleetClientError>> {\n return this.#request(\"agent.destroy\", input, options);\n }\n\n compact(\n input: CompactInput,\n options: MutationOptions,\n ): Promise<Result<CompactResult, FleetClientError>> {\n return this.#request(\"agent.compact\", input, options);\n }\n\n async #request<T>(\n method: string,\n params: object,\n options: RequestOptions | MutationOptions,\n ): Promise<Result<T, FleetClientError>> {\n let socket: Socket;\n try {\n await this.options.beforeConnect?.();\n socket = await connect(this.options.socketPath, options.signal);\n } catch (error: unknown) {\n return err(connectionError(error));\n }\n\n const requestId = randomUUID();\n let piIdentity: PiRuntimeIdentity | undefined;\n try {\n piIdentity = requiresPiIdentity(method) ? await this.#piIdentity() : undefined;\n } catch (error: unknown) {\n socket.destroy();\n return err(piSelectionError(error));\n }\n const response = firstMatchingFrame(socket, requestId, options.signal);\n writeJsonLine(socket, {\n v: PROTOCOL_VERSION,\n requestId,\n method,\n params,\n ...(isMutationOptions(options) ? { operation: options.operation } : {}),\n ...(piIdentity === undefined ? {} : { runtime: { pi: piIdentity } }),\n });\n\n try {\n const frame = await response;\n if (!isRecord(frame) || frame.requestId !== requestId || typeof frame.ok !== \"boolean\") {\n return err({ code: \"protocol_error\", message: \"Invalid runtime response.\" });\n }\n if (frame.v !== PROTOCOL_VERSION) {\n return err({\n code: \"protocol_incompatible\",\n message:\n \"The running pi-fleet runtime is incompatible with this client; repair or restart it.\",\n });\n }\n if (frame.ok) return ok(frame.result as T);\n if (\n method === \"agent.compact\" &&\n isErrorRecord(frame.error) &&\n frame.error.code === \"invalid_request\" &&\n frame.error.message === \"Invalid protocol request: /method\"\n ) {\n return err({\n code: \"protocol_incompatible\",\n message: \"The running pi-fleet runtime does not support compact; upgrade or repair it.\",\n });\n }\n if (isErrorRecord(frame.error)) return err(frame.error);\n return err({ code: \"protocol_error\", message: \"Runtime returned an invalid error.\" });\n } catch (error: unknown) {\n return err(connectionError(error));\n } finally {\n socket.destroy();\n }\n }\n\n async #piIdentity(): Promise<PiRuntimeIdentity> {\n const configured = this.options.piIdentity;\n if (configured === undefined) return MANAGED_PI_RUNTIME_IDENTITY;\n return typeof configured === \"function\" ? configured() : configured;\n }\n}\n\nfunction piSelectionError(error: unknown): FleetClientError {\n const code = (error as { code?: unknown }).code;\n if (\n code === \"pi_not_found\" ||\n code === \"pi_not_executable\" ||\n code === \"pi_version_unavailable\" ||\n code === \"pi_version_unsupported\" ||\n code === \"pi_installation_changed\" ||\n code === \"pi_service_mismatch\"\n ) {\n return { code, message: error instanceof Error ? error.message : \"Pi is unavailable.\" };\n }\n return { code: \"internal_error\", message: \"Pi selection failed.\" };\n}\n\nfunction isMutationOptions(options: RequestOptions | MutationOptions): options is MutationOptions {\n return \"operation\" in options;\n}\n\nfunction requiresPiIdentity(method: string): boolean {\n return method === \"agent.create\" || method === \"agent.send\" || method === \"agent.compact\";\n}\n\nfunction connect(socketPath: string, signal: AbortSignal): Promise<Socket> {\n return new Promise((resolveConnect, rejectConnect) => {\n if (signal.aborted) {\n rejectConnect(new Error(\"Request cancelled\"));\n return;\n }\n const socket = createConnection(socketPath);\n const onAbort = () => socket.destroy(new Error(\"Request cancelled\"));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n socket.once(\"connect\", () => {\n signal.removeEventListener(\"abort\", onAbort);\n resolveConnect(socket);\n });\n socket.once(\"error\", rejectConnect);\n });\n}\n\nfunction firstMatchingFrame(\n socket: Socket,\n requestId: string,\n signal: AbortSignal,\n): Promise<unknown> {\n return new Promise((resolveFrame, rejectFrame) => {\n let settled = false;\n const finish = (action: () => void) => {\n if (settled) return;\n settled = true;\n stop();\n signal.removeEventListener(\"abort\", onAbort);\n action();\n };\n const stop = readJsonLines(\n socket,\n (frame) => {\n if (!isRecord(frame) || frame.requestId !== requestId) return;\n finish(() => resolveFrame(frame));\n },\n (error) => finish(() => rejectFrame(error)),\n );\n const onAbort = () => finish(() => rejectFrame(new Error(\"Request cancelled\")));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n socket.once(\"close\", () =>\n finish(() => rejectFrame(new Error(\"Runtime connection closed before responding\"))),\n );\n });\n}\n\nexport async function* frameIterator(\n socket: Socket,\n signal: AbortSignal,\n maxQueuedBytes = 1024 * 1024,\n): AsyncIterable<unknown> {\n const queue: { readonly value: unknown; readonly bytes: number }[] = [];\n let queuedBytes = 0;\n let paused = false;\n let ended = false;\n let failure: Error | null = null;\n let wake: (() => void) | null = null;\n const notify = () => {\n wake?.();\n wake = null;\n };\n const stop = readJsonLines(\n socket,\n (frame) => {\n const bytes = Buffer.byteLength(JSON.stringify(frame), \"utf8\");\n queue.push({ value: frame, bytes });\n queuedBytes += bytes;\n if (queuedBytes >= maxQueuedBytes && !paused) {\n socket.pause();\n paused = true;\n }\n notify();\n },\n (error) => {\n failure = error;\n ended = true;\n notify();\n },\n );\n socket.once(\"end\", () => {\n failure = new Error(\"Runtime connection closed before completing the stream\");\n ended = true;\n notify();\n });\n const onAbort = () => {\n failure = new Error(\"Request cancelled\");\n ended = true;\n notify();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n\n try {\n while (!ended || queue.length > 0) {\n if (queue.length === 0) {\n await new Promise<void>((resolveWake) => {\n wake = resolveWake;\n });\n continue;\n }\n const item = queue.shift();\n if (item === undefined) continue;\n queuedBytes -= item.bytes;\n if (paused && queuedBytes < maxQueuedBytes / 2) {\n socket.resume();\n paused = false;\n }\n yield item.value;\n }\n if (failure !== null) throw failure;\n } finally {\n stop();\n signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isErrorRecord(value: unknown): value is FleetClientError {\n return isRecord(value) && typeof value.code === \"string\" && typeof value.message === \"string\";\n}\n\nfunction connectionError(error: unknown): FleetClientError {\n return {\n code: \"runtime_unavailable\",\n message: error instanceof Error ? error.message : \"Unable to connect to pi-fleet runtime.\",\n };\n}\n", "export const PROTOCOL_VERSION = 2 as const;\nexport const MAX_PROTOCOL_FRAME_BYTES = 1024 * 1024;\n", "import type { Socket } from \"node:net\";\n\nimport { MAX_PROTOCOL_FRAME_BYTES } from \"./version.js\";\n\nexport function readJsonLines(\n socket: Socket,\n onValue: (value: unknown) => void,\n onError: (error: Error) => void,\n maxFrameBytes = MAX_PROTOCOL_FRAME_BYTES,\n): () => void {\n let buffer = Buffer.alloc(0);\n const onData = (chunk: Buffer) => {\n buffer = Buffer.concat([buffer, chunk]);\n while (true) {\n const newline = buffer.indexOf(0x0a);\n if (newline < 0) {\n if (buffer.length > maxFrameBytes) {\n onError(new Error(\"Protocol frame exceeds maximum size\"));\n }\n return;\n }\n if (newline > maxFrameBytes) {\n onError(new Error(\"Protocol frame exceeds maximum size\"));\n return;\n }\n const line = buffer.subarray(0, newline).toString(\"utf8\").replace(/\\r$/, \"\");\n buffer = buffer.subarray(newline + 1);\n if (line.length === 0) continue;\n try {\n onValue(JSON.parse(line));\n } catch {\n onError(new Error(\"Malformed JSON protocol frame\"));\n return;\n }\n }\n };\n socket.on(\"data\", onData);\n return () => socket.off(\"data\", onData);\n}\n\nexport function writeJsonLine(socket: Socket, value: unknown): boolean {\n return socket.write(`${JSON.stringify(value)}\\n`);\n}\n", "// --------------------------------------------------------------------------\n// PropertyKey\n// --------------------------------------------------------------------------\n/** Returns true if this value has this property key */\nexport function HasPropertyKey(value, key) {\n return key in value;\n}\n// --------------------------------------------------------------------------\n// Object Instances\n// --------------------------------------------------------------------------\n/** Returns true if this value is an async iterator */\nexport function IsAsyncIterator(value) {\n return IsObject(value) && !IsArray(value) && !IsUint8Array(value) && Symbol.asyncIterator in value;\n}\n/** Returns true if this value is an array */\nexport function IsArray(value) {\n return Array.isArray(value);\n}\n/** Returns true if this value is bigint */\nexport function IsBigInt(value) {\n return typeof value === 'bigint';\n}\n/** Returns true if this value is a boolean */\nexport function IsBoolean(value) {\n return typeof value === 'boolean';\n}\n/** Returns true if this value is a Date object */\nexport function IsDate(value) {\n return value instanceof globalThis.Date;\n}\n/** Returns true if this value is a function */\nexport function IsFunction(value) {\n return typeof value === 'function';\n}\n/** Returns true if this value is an iterator */\nexport function IsIterator(value) {\n return IsObject(value) && !IsArray(value) && !IsUint8Array(value) && Symbol.iterator in value;\n}\n/** Returns true if this value is null */\nexport function IsNull(value) {\n return value === null;\n}\n/** Returns true if this value is number */\nexport function IsNumber(value) {\n return typeof value === 'number';\n}\n/** Returns true if this value is an object */\nexport function IsObject(value) {\n return typeof value === 'object' && value !== null;\n}\n/** Returns true if this value is RegExp */\nexport function IsRegExp(value) {\n return value instanceof globalThis.RegExp;\n}\n/** Returns true if this value is string */\nexport function IsString(value) {\n return typeof value === 'string';\n}\n/** Returns true if this value is symbol */\nexport function IsSymbol(value) {\n return typeof value === 'symbol';\n}\n/** Returns true if this value is a Uint8Array */\nexport function IsUint8Array(value) {\n return value instanceof globalThis.Uint8Array;\n}\n/** Returns true if this value is undefined */\nexport function IsUndefined(value) {\n return value === undefined;\n}\n", "import * as ValueGuard from '../guard/value.mjs';\nfunction ArrayType(value) {\n return value.map((value) => Visit(value));\n}\nfunction DateType(value) {\n return new Date(value.getTime());\n}\nfunction Uint8ArrayType(value) {\n return new Uint8Array(value);\n}\nfunction RegExpType(value) {\n return new RegExp(value.source, value.flags);\n}\nfunction ObjectType(value) {\n const result = {};\n for (const key of Object.getOwnPropertyNames(value)) {\n result[key] = Visit(value[key]);\n }\n for (const key of Object.getOwnPropertySymbols(value)) {\n result[key] = Visit(value[key]);\n }\n return result;\n}\n// prettier-ignore\nfunction Visit(value) {\n return (ValueGuard.IsArray(value) ? ArrayType(value) :\n ValueGuard.IsDate(value) ? DateType(value) :\n ValueGuard.IsUint8Array(value) ? Uint8ArrayType(value) :\n ValueGuard.IsRegExp(value) ? RegExpType(value) :\n ValueGuard.IsObject(value) ? ObjectType(value) :\n value);\n}\n/** Clones a value */\nexport function Clone(value) {\n return Visit(value);\n}\n", "import { Clone } from './value.mjs';\n/** Clones a Rest */\nexport function CloneRest(schemas) {\n return schemas.map((schema) => CloneType(schema));\n}\n/** Clones a Type */\nexport function CloneType(schema, options) {\n return options === undefined ? Clone(schema) : Clone({ ...options, ...schema });\n}\n", "// --------------------------------------------------------------------------\n// Iterators\n// --------------------------------------------------------------------------\n/** Returns true if this value is an async iterator */\nexport function IsAsyncIterator(value) {\n return IsObject(value) && globalThis.Symbol.asyncIterator in value;\n}\n/** Returns true if this value is an iterator */\nexport function IsIterator(value) {\n return IsObject(value) && globalThis.Symbol.iterator in value;\n}\n// --------------------------------------------------------------------------\n// Object Instances\n// --------------------------------------------------------------------------\n/** Returns true if this value is not an instance of a class */\nexport function IsStandardObject(value) {\n return IsObject(value) && (globalThis.Object.getPrototypeOf(value) === Object.prototype || globalThis.Object.getPrototypeOf(value) === null);\n}\n/** Returns true if this value is an instance of a class */\nexport function IsInstanceObject(value) {\n return IsObject(value) && !IsArray(value) && IsFunction(value.constructor) && value.constructor.name !== 'Object';\n}\n// --------------------------------------------------------------------------\n// JavaScript\n// --------------------------------------------------------------------------\n/** Returns true if this value is a Promise */\nexport function IsPromise(value) {\n return value instanceof globalThis.Promise;\n}\n/** Returns true if this value is a Date */\nexport function IsDate(value) {\n return value instanceof Date && globalThis.Number.isFinite(value.getTime());\n}\n/** Returns true if this value is an instance of Map<K, T> */\nexport function IsMap(value) {\n return value instanceof globalThis.Map;\n}\n/** Returns true if this value is an instance of Set<T> */\nexport function IsSet(value) {\n return value instanceof globalThis.Set;\n}\n/** Returns true if this value is RegExp */\nexport function IsRegExp(value) {\n return value instanceof globalThis.RegExp;\n}\n/** Returns true if this value is a typed array */\nexport function IsTypedArray(value) {\n return globalThis.ArrayBuffer.isView(value);\n}\n/** Returns true if the value is a Int8Array */\nexport function IsInt8Array(value) {\n return value instanceof globalThis.Int8Array;\n}\n/** Returns true if the value is a Uint8Array */\nexport function IsUint8Array(value) {\n return value instanceof globalThis.Uint8Array;\n}\n/** Returns true if the value is a Uint8ClampedArray */\nexport function IsUint8ClampedArray(value) {\n return value instanceof globalThis.Uint8ClampedArray;\n}\n/** Returns true if the value is a Int16Array */\nexport function IsInt16Array(value) {\n return value instanceof globalThis.Int16Array;\n}\n/** Returns true if the value is a Uint16Array */\nexport function IsUint16Array(value) {\n return value instanceof globalThis.Uint16Array;\n}\n/** Returns true if the value is a Int32Array */\nexport function IsInt32Array(value) {\n return value instanceof globalThis.Int32Array;\n}\n/** Returns true if the value is a Uint32Array */\nexport function IsUint32Array(value) {\n return value instanceof globalThis.Uint32Array;\n}\n/** Returns true if the value is a Float32Array */\nexport function IsFloat32Array(value) {\n return value instanceof globalThis.Float32Array;\n}\n/** Returns true if the value is a Float64Array */\nexport function IsFloat64Array(value) {\n return value instanceof globalThis.Float64Array;\n}\n/** Returns true if the value is a BigInt64Array */\nexport function IsBigInt64Array(value) {\n return value instanceof globalThis.BigInt64Array;\n}\n/** Returns true if the value is a BigUint64Array */\nexport function IsBigUint64Array(value) {\n return value instanceof globalThis.BigUint64Array;\n}\n// --------------------------------------------------------------------------\n// PropertyKey\n// --------------------------------------------------------------------------\n/** Returns true if this value has this property key */\nexport function HasPropertyKey(value, key) {\n return key in value;\n}\n// --------------------------------------------------------------------------\n// Standard\n// --------------------------------------------------------------------------\n/** Returns true of this value is an object type */\nexport function IsObject(value) {\n return value !== null && typeof value === 'object';\n}\n/** Returns true if this value is an array, but not a typed array */\nexport function IsArray(value) {\n return globalThis.Array.isArray(value) && !globalThis.ArrayBuffer.isView(value);\n}\n/** Returns true if this value is an undefined */\nexport function IsUndefined(value) {\n return value === undefined;\n}\n/** Returns true if this value is an null */\nexport function IsNull(value) {\n return value === null;\n}\n/** Returns true if this value is an boolean */\nexport function IsBoolean(value) {\n return typeof value === 'boolean';\n}\n/** Returns true if this value is an number */\nexport function IsNumber(value) {\n return typeof value === 'number';\n}\n/** Returns true if this value is an integer */\nexport function IsInteger(value) {\n return globalThis.Number.isInteger(value);\n}\n/** Returns true if this value is bigint */\nexport function IsBigInt(value) {\n return typeof value === 'bigint';\n}\n/** Returns true if this value is string */\nexport function IsString(value) {\n return typeof value === 'string';\n}\n/** Returns true if this value is a function */\nexport function IsFunction(value) {\n return typeof value === 'function';\n}\n/** Returns true if this value is a symbol */\nexport function IsSymbol(value) {\n return typeof value === 'symbol';\n}\n/** Returns true if this value is a value type such as number, string, boolean */\nexport function IsValueType(value) {\n // prettier-ignore\n return (IsBigInt(value) ||\n IsBoolean(value) ||\n IsNull(value) ||\n IsNumber(value) ||\n IsString(value) ||\n IsSymbol(value) ||\n IsUndefined(value));\n}\n", "import { IsObject, IsArray, IsNumber, IsUndefined } from '../value/guard/index.mjs';\nexport var TypeSystemPolicy;\n(function (TypeSystemPolicy) {\n // ------------------------------------------------------------------\n // TypeSystemPolicy: Instancing\n // ------------------------------------------------------------------\n /**\n * Configures the instantiation behavior of TypeBox types. The `default` option assigns raw JavaScript\n * references for embedded types, which may cause side effects if type properties are explicitly updated\n * outside the TypeBox type builder. The `clone` option creates copies of any shared types upon creation,\n * preventing unintended side effects. The `freeze` option applies `Object.freeze()` to the type, making\n * it fully readonly and immutable. Implementations should use `default` whenever possible, as it is the\n * fastest way to instantiate types. The default setting is `default`.\n */\n TypeSystemPolicy.InstanceMode = 'default';\n // ------------------------------------------------------------------\n // TypeSystemPolicy: Checking\n // ------------------------------------------------------------------\n /** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */\n TypeSystemPolicy.ExactOptionalPropertyTypes = false;\n /** Sets whether arrays should be treated as a kind of objects. The default is `false` */\n TypeSystemPolicy.AllowArrayObject = false;\n /** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */\n TypeSystemPolicy.AllowNaN = false;\n /** Sets whether `null` should validate for void types. The default is `false` */\n TypeSystemPolicy.AllowNullVoid = false;\n /** Checks this value using the ExactOptionalPropertyTypes policy */\n function IsExactOptionalProperty(value, key) {\n return TypeSystemPolicy.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined;\n }\n TypeSystemPolicy.IsExactOptionalProperty = IsExactOptionalProperty;\n /** Checks this value using the AllowArrayObjects policy */\n function IsObjectLike(value) {\n const isObject = IsObject(value);\n return TypeSystemPolicy.AllowArrayObject ? isObject : isObject && !IsArray(value);\n }\n TypeSystemPolicy.IsObjectLike = IsObjectLike;\n /** Checks this value as a record using the AllowArrayObjects policy */\n function IsRecordLike(value) {\n return IsObjectLike(value) && !(value instanceof Date) && !(value instanceof Uint8Array);\n }\n TypeSystemPolicy.IsRecordLike = IsRecordLike;\n /** Checks this value using the AllowNaN policy */\n function IsNumberLike(value) {\n return TypeSystemPolicy.AllowNaN ? IsNumber(value) : Number.isFinite(value);\n }\n TypeSystemPolicy.IsNumberLike = IsNumberLike;\n /** Checks this value using the AllowVoidNull policy */\n function IsVoidLike(value) {\n const isUndefined = IsUndefined(value);\n return TypeSystemPolicy.AllowNullVoid ? isUndefined || value === null : isUndefined;\n }\n TypeSystemPolicy.IsVoidLike = IsVoidLike;\n})(TypeSystemPolicy || (TypeSystemPolicy = {}));\n", "import * as ValueGuard from '../guard/value.mjs';\nfunction ImmutableArray(value) {\n return globalThis.Object.freeze(value).map((value) => Immutable(value));\n}\nfunction ImmutableDate(value) {\n return value;\n}\nfunction ImmutableUint8Array(value) {\n return value;\n}\nfunction ImmutableRegExp(value) {\n return value;\n}\nfunction ImmutableObject(value) {\n const result = {};\n for (const key of Object.getOwnPropertyNames(value)) {\n result[key] = Immutable(value[key]);\n }\n for (const key of Object.getOwnPropertySymbols(value)) {\n result[key] = Immutable(value[key]);\n }\n return globalThis.Object.freeze(result);\n}\n/** Specialized deep immutable value. Applies freeze recursively to the given value */\n// prettier-ignore\nexport function Immutable(value) {\n return (ValueGuard.IsArray(value) ? ImmutableArray(value) :\n ValueGuard.IsDate(value) ? ImmutableDate(value) :\n ValueGuard.IsUint8Array(value) ? ImmutableUint8Array(value) :\n ValueGuard.IsRegExp(value) ? ImmutableRegExp(value) :\n ValueGuard.IsObject(value) ? ImmutableObject(value) :\n value);\n}\n", "import { TypeSystemPolicy } from '../../system/policy.mjs';\nimport { Immutable } from './immutable.mjs';\nimport { Clone } from '../clone/value.mjs';\n/** Creates TypeBox schematics using the configured InstanceMode */\nexport function CreateType(schema, options) {\n const result = options !== undefined ? { ...options, ...schema } : schema;\n switch (TypeSystemPolicy.InstanceMode) {\n case 'freeze':\n return Immutable(result);\n case 'clone':\n return Clone(result);\n default:\n return result;\n }\n}\n", "/** The base Error type thrown for all TypeBox exceptions */\nexport class TypeBoxError extends Error {\n constructor(message) {\n super(message);\n }\n}\n", "/** Symbol key applied to transform types */\nexport const TransformKind = Symbol.for('TypeBox.Transform');\n/** Symbol key applied to readonly types */\nexport const ReadonlyKind = Symbol.for('TypeBox.Readonly');\n/** Symbol key applied to optional types */\nexport const OptionalKind = Symbol.for('TypeBox.Optional');\n/** Symbol key applied to types */\nexport const Hint = Symbol.for('TypeBox.Hint');\n/** Symbol key applied to types */\nexport const Kind = Symbol.for('TypeBox.Kind');\n", "import * as ValueGuard from './value.mjs';\nimport { Kind, Hint, TransformKind, ReadonlyKind, OptionalKind } from '../symbols/index.mjs';\n/** `[Kind-Only]` Returns true if this value has a Readonly symbol */\nexport function IsReadonly(value) {\n return ValueGuard.IsObject(value) && value[ReadonlyKind] === 'Readonly';\n}\n/** `[Kind-Only]` Returns true if this value has a Optional symbol */\nexport function IsOptional(value) {\n return ValueGuard.IsObject(value) && value[OptionalKind] === 'Optional';\n}\n/** `[Kind-Only]` Returns true if the given value is TAny */\nexport function IsAny(value) {\n return IsKindOf(value, 'Any');\n}\n/** `[Kind-Only]` Returns true if the given value is TArgument */\nexport function IsArgument(value) {\n return IsKindOf(value, 'Argument');\n}\n/** `[Kind-Only]` Returns true if the given value is TArray */\nexport function IsArray(value) {\n return IsKindOf(value, 'Array');\n}\n/** `[Kind-Only]` Returns true if the given value is TAsyncIterator */\nexport function IsAsyncIterator(value) {\n return IsKindOf(value, 'AsyncIterator');\n}\n/** `[Kind-Only]` Returns true if the given value is TBigInt */\nexport function IsBigInt(value) {\n return IsKindOf(value, 'BigInt');\n}\n/** `[Kind-Only]` Returns true if the given value is TBoolean */\nexport function IsBoolean(value) {\n return IsKindOf(value, 'Boolean');\n}\n/** `[Kind-Only]` Returns true if the given value is TComputed */\nexport function IsComputed(value) {\n return IsKindOf(value, 'Computed');\n}\n/** `[Kind-Only]` Returns true if the given value is TConstructor */\nexport function IsConstructor(value) {\n return IsKindOf(value, 'Constructor');\n}\n/** `[Kind-Only]` Returns true if the given value is TDate */\nexport function IsDate(value) {\n return IsKindOf(value, 'Date');\n}\n/** `[Kind-Only]` Returns true if the given value is TFunction */\nexport function IsFunction(value) {\n return IsKindOf(value, 'Function');\n}\n/** `[Kind-Only]` Returns true if the given value is TInteger */\nexport function IsImport(value) {\n return IsKindOf(value, 'Import');\n}\n/** `[Kind-Only]` Returns true if the given value is TInteger */\nexport function IsInteger(value) {\n return IsKindOf(value, 'Integer');\n}\n/** `[Kind-Only]` Returns true if the given schema is TProperties */\nexport function IsProperties(value) {\n return ValueGuard.IsObject(value);\n}\n/** `[Kind-Only]` Returns true if the given value is TIntersect */\nexport function IsIntersect(value) {\n return IsKindOf(value, 'Intersect');\n}\n/** `[Kind-Only]` Returns true if the given value is TIterator */\nexport function IsIterator(value) {\n return IsKindOf(value, 'Iterator');\n}\n/** `[Kind-Only]` Returns true if the given value is a TKind with the given name. */\nexport function IsKindOf(value, kind) {\n return ValueGuard.IsObject(value) && Kind in value && value[Kind] === kind;\n}\n/** `[Kind-Only]` Returns true if the given value is TLiteral<string> */\nexport function IsLiteralString(value) {\n return IsLiteral(value) && ValueGuard.IsString(value.const);\n}\n/** `[Kind-Only]` Returns true if the given value is TLiteral<number> */\nexport function IsLiteralNumber(value) {\n return IsLiteral(value) && ValueGuard.IsNumber(value.const);\n}\n/** `[Kind-Only]` Returns true if the given value is TLiteral<boolean> */\nexport function IsLiteralBoolean(value) {\n return IsLiteral(value) && ValueGuard.IsBoolean(value.const);\n}\n/** `[Kind-Only]` Returns true if the given value is TLiteralValue */\nexport function IsLiteralValue(value) {\n return ValueGuard.IsBoolean(value) || ValueGuard.IsNumber(value) || ValueGuard.IsString(value);\n}\n/** `[Kind-Only]` Returns true if the given value is TLiteral */\nexport function IsLiteral(value) {\n return IsKindOf(value, 'Literal');\n}\n/** `[Kind-Only]` Returns true if the given value is a TMappedKey */\nexport function IsMappedKey(value) {\n return IsKindOf(value, 'MappedKey');\n}\n/** `[Kind-Only]` Returns true if the given value is TMappedResult */\nexport function IsMappedResult(value) {\n return IsKindOf(value, 'MappedResult');\n}\n/** `[Kind-Only]` Returns true if the given value is TNever */\nexport function IsNever(value) {\n return IsKindOf(value, 'Never');\n}\n/** `[Kind-Only]` Returns true if the given value is TNot */\nexport function IsNot(value) {\n return IsKindOf(value, 'Not');\n}\n/** `[Kind-Only]` Returns true if the given value is TNull */\nexport function IsNull(value) {\n return IsKindOf(value, 'Null');\n}\n/** `[Kind-Only]` Returns true if the given value is TNumber */\nexport function IsNumber(value) {\n return IsKindOf(value, 'Number');\n}\n/** `[Kind-Only]` Returns true if the given value is TObject */\nexport function IsObject(value) {\n return IsKindOf(value, 'Object');\n}\n/** `[Kind-Only]` Returns true if the given value is TPromise */\nexport function IsPromise(value) {\n return IsKindOf(value, 'Promise');\n}\n/** `[Kind-Only]` Returns true if the given value is TRecord */\nexport function IsRecord(value) {\n return IsKindOf(value, 'Record');\n}\n/** `[Kind-Only]` Returns true if this value is TRecursive */\nexport function IsRecursive(value) {\n return ValueGuard.IsObject(value) && Hint in value && value[Hint] === 'Recursive';\n}\n/** `[Kind-Only]` Returns true if the given value is TRef */\nexport function IsRef(value) {\n return IsKindOf(value, 'Ref');\n}\n/** `[Kind-Only]` Returns true if the given value is TRegExp */\nexport function IsRegExp(value) {\n return IsKindOf(value, 'RegExp');\n}\n/** `[Kind-Only]` Returns true if the given value is TString */\nexport function IsString(value) {\n return IsKindOf(value, 'String');\n}\n/** `[Kind-Only]` Returns true if the given value is TSymbol */\nexport function IsSymbol(value) {\n return IsKindOf(value, 'Symbol');\n}\n/** `[Kind-Only]` Returns true if the given value is TTemplateLiteral */\nexport function IsTemplateLiteral(value) {\n return IsKindOf(value, 'TemplateLiteral');\n}\n/** `[Kind-Only]` Returns true if the given value is TThis */\nexport function IsThis(value) {\n return IsKindOf(value, 'This');\n}\n/** `[Kind-Only]` Returns true of this value is TTransform */\nexport function IsTransform(value) {\n return ValueGuard.IsObject(value) && TransformKind in value;\n}\n/** `[Kind-Only]` Returns true if the given value is TTuple */\nexport function IsTuple(value) {\n return IsKindOf(value, 'Tuple');\n}\n/** `[Kind-Only]` Returns true if the given value is TUndefined */\nexport function IsUndefined(value) {\n return IsKindOf(value, 'Undefined');\n}\n/** `[Kind-Only]` Returns true if the given value is TUnion */\nexport function IsUnion(value) {\n return IsKindOf(value, 'Union');\n}\n/** `[Kind-Only]` Returns true if the given value is TUint8Array */\nexport function IsUint8Array(value) {\n return IsKindOf(value, 'Uint8Array');\n}\n/** `[Kind-Only]` Returns true if the given value is TUnknown */\nexport function IsUnknown(value) {\n return IsKindOf(value, 'Unknown');\n}\n/** `[Kind-Only]` Returns true if the given value is a raw TUnsafe */\nexport function IsUnsafe(value) {\n return IsKindOf(value, 'Unsafe');\n}\n/** `[Kind-Only]` Returns true if the given value is TVoid */\nexport function IsVoid(value) {\n return IsKindOf(value, 'Void');\n}\n/** `[Kind-Only]` Returns true if the given value is TKind */\nexport function IsKind(value) {\n return ValueGuard.IsObject(value) && Kind in value && ValueGuard.IsString(value[Kind]);\n}\n/** `[Kind-Only]` Returns true if the given value is TSchema */\nexport function IsSchema(value) {\n // prettier-ignore\n return (IsAny(value) ||\n IsArgument(value) ||\n IsArray(value) ||\n IsBoolean(value) ||\n IsBigInt(value) ||\n IsAsyncIterator(value) ||\n IsComputed(value) ||\n IsConstructor(value) ||\n IsDate(value) ||\n IsFunction(value) ||\n IsInteger(value) ||\n IsIntersect(value) ||\n IsIterator(value) ||\n IsLiteral(value) ||\n IsMappedKey(value) ||\n IsMappedResult(value) ||\n IsNever(value) ||\n IsNot(value) ||\n IsNull(value) ||\n IsNumber(value) ||\n IsObject(value) ||\n IsPromise(value) ||\n IsRecord(value) ||\n IsRef(value) ||\n IsRegExp(value) ||\n IsString(value) ||\n IsSymbol(value) ||\n IsTemplateLiteral(value) ||\n IsThis(value) ||\n IsTuple(value) ||\n IsUndefined(value) ||\n IsUnion(value) ||\n IsUint8Array(value) ||\n IsUnknown(value) ||\n IsUnsafe(value) ||\n IsVoid(value) ||\n IsKind(value));\n}\n", "import * as ValueGuard from './value.mjs';\nimport { Kind, Hint, TransformKind, ReadonlyKind, OptionalKind } from '../symbols/index.mjs';\nimport { TypeBoxError } from '../error/index.mjs';\nexport class TypeGuardUnknownTypeError extends TypeBoxError {\n}\nconst KnownTypes = [\n 'Argument',\n 'Any',\n 'Array',\n 'AsyncIterator',\n 'BigInt',\n 'Boolean',\n 'Computed',\n 'Constructor',\n 'Date',\n 'Enum',\n 'Function',\n 'Integer',\n 'Intersect',\n 'Iterator',\n 'Literal',\n 'MappedKey',\n 'MappedResult',\n 'Not',\n 'Null',\n 'Number',\n 'Object',\n 'Promise',\n 'Record',\n 'Ref',\n 'RegExp',\n 'String',\n 'Symbol',\n 'TemplateLiteral',\n 'This',\n 'Tuple',\n 'Undefined',\n 'Union',\n 'Uint8Array',\n 'Unknown',\n 'Void',\n];\nfunction IsPattern(value) {\n try {\n new RegExp(value);\n return true;\n }\n catch {\n return false;\n }\n}\nfunction IsControlCharacterFree(value) {\n if (!ValueGuard.IsString(value))\n return false;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if ((code >= 7 && code <= 13) || code === 27 || code === 127) {\n return false;\n }\n }\n return true;\n}\nfunction IsAdditionalProperties(value) {\n return IsOptionalBoolean(value) || IsSchema(value);\n}\nfunction IsOptionalBigInt(value) {\n return ValueGuard.IsUndefined(value) || ValueGuard.IsBigInt(value);\n}\nfunction IsOptionalNumber(value) {\n return ValueGuard.IsUndefined(value) || ValueGuard.IsNumber(value);\n}\nfunction IsOptionalBoolean(value) {\n return ValueGuard.IsUndefined(value) || ValueGuard.IsBoolean(value);\n}\nfunction IsOptionalString(value) {\n return ValueGuard.IsUndefined(value) || ValueGuard.IsString(value);\n}\nfunction IsOptionalPattern(value) {\n return ValueGuard.IsUndefined(value) || (ValueGuard.IsString(value) && IsControlCharacterFree(value) && IsPattern(value));\n}\nfunction IsOptionalFormat(value) {\n return ValueGuard.IsUndefined(value) || (ValueGuard.IsString(value) && IsControlCharacterFree(value));\n}\nfunction IsOptionalSchema(value) {\n return ValueGuard.IsUndefined(value) || IsSchema(value);\n}\n// ------------------------------------------------------------------\n// Modifiers\n// ------------------------------------------------------------------\n/** Returns true if this value has a Readonly symbol */\nexport function IsReadonly(value) {\n return ValueGuard.IsObject(value) && value[ReadonlyKind] === 'Readonly';\n}\n/** Returns true if this value has a Optional symbol */\nexport function IsOptional(value) {\n return ValueGuard.IsObject(value) && value[OptionalKind] === 'Optional';\n}\n// ------------------------------------------------------------------\n// Types\n// ------------------------------------------------------------------\n/** Returns true if the given value is TAny */\nexport function IsAny(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Any') &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TArgument */\nexport function IsArgument(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Argument') &&\n ValueGuard.IsNumber(value.index));\n}\n/** Returns true if the given value is TArray */\nexport function IsArray(value) {\n return (IsKindOf(value, 'Array') &&\n value.type === 'array' &&\n IsOptionalString(value.$id) &&\n IsSchema(value.items) &&\n IsOptionalNumber(value.minItems) &&\n IsOptionalNumber(value.maxItems) &&\n IsOptionalBoolean(value.uniqueItems) &&\n IsOptionalSchema(value.contains) &&\n IsOptionalNumber(value.minContains) &&\n IsOptionalNumber(value.maxContains));\n}\n/** Returns true if the given value is TAsyncIterator */\nexport function IsAsyncIterator(value) {\n // prettier-ignore\n return (IsKindOf(value, 'AsyncIterator') &&\n value.type === 'AsyncIterator' &&\n IsOptionalString(value.$id) &&\n IsSchema(value.items));\n}\n/** Returns true if the given value is TBigInt */\nexport function IsBigInt(value) {\n // prettier-ignore\n return (IsKindOf(value, 'BigInt') &&\n value.type === 'bigint' &&\n IsOptionalString(value.$id) &&\n IsOptionalBigInt(value.exclusiveMaximum) &&\n IsOptionalBigInt(value.exclusiveMinimum) &&\n IsOptionalBigInt(value.maximum) &&\n IsOptionalBigInt(value.minimum) &&\n IsOptionalBigInt(value.multipleOf));\n}\n/** Returns true if the given value is TBoolean */\nexport function IsBoolean(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Boolean') &&\n value.type === 'boolean' &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TComputed */\nexport function IsComputed(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Computed') &&\n ValueGuard.IsString(value.target) &&\n ValueGuard.IsArray(value.parameters) &&\n value.parameters.every((schema) => IsSchema(schema)));\n}\n/** Returns true if the given value is TConstructor */\nexport function IsConstructor(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Constructor') &&\n value.type === 'Constructor' &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsArray(value.parameters) &&\n value.parameters.every(schema => IsSchema(schema)) &&\n IsSchema(value.returns));\n}\n/** Returns true if the given value is TDate */\nexport function IsDate(value) {\n return (IsKindOf(value, 'Date') &&\n value.type === 'Date' &&\n IsOptionalString(value.$id) &&\n IsOptionalNumber(value.exclusiveMaximumTimestamp) &&\n IsOptionalNumber(value.exclusiveMinimumTimestamp) &&\n IsOptionalNumber(value.maximumTimestamp) &&\n IsOptionalNumber(value.minimumTimestamp) &&\n IsOptionalNumber(value.multipleOfTimestamp));\n}\n/** Returns true if the given value is TFunction */\nexport function IsFunction(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Function') &&\n value.type === 'Function' &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsArray(value.parameters) &&\n value.parameters.every(schema => IsSchema(schema)) &&\n IsSchema(value.returns));\n}\n/** Returns true if the given value is TImport */\nexport function IsImport(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Import') &&\n ValueGuard.HasPropertyKey(value, '$defs') &&\n ValueGuard.IsObject(value.$defs) &&\n IsProperties(value.$defs) &&\n ValueGuard.HasPropertyKey(value, '$ref') &&\n ValueGuard.IsString(value.$ref) &&\n value.$ref in value.$defs // required\n );\n}\n/** Returns true if the given value is TInteger */\nexport function IsInteger(value) {\n return (IsKindOf(value, 'Integer') &&\n value.type === 'integer' &&\n IsOptionalString(value.$id) &&\n IsOptionalNumber(value.exclusiveMaximum) &&\n IsOptionalNumber(value.exclusiveMinimum) &&\n IsOptionalNumber(value.maximum) &&\n IsOptionalNumber(value.minimum) &&\n IsOptionalNumber(value.multipleOf));\n}\n/** Returns true if the given schema is TProperties */\nexport function IsProperties(value) {\n // prettier-ignore\n return (ValueGuard.IsObject(value) &&\n Object.entries(value).every(([key, schema]) => IsControlCharacterFree(key) && IsSchema(schema)));\n}\n/** Returns true if the given value is TIntersect */\nexport function IsIntersect(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Intersect') &&\n (ValueGuard.IsString(value.type) && value.type !== 'object' ? false : true) &&\n ValueGuard.IsArray(value.allOf) &&\n value.allOf.every(schema => IsSchema(schema) && !IsTransform(schema)) &&\n IsOptionalString(value.type) &&\n (IsOptionalBoolean(value.unevaluatedProperties) || IsOptionalSchema(value.unevaluatedProperties)) &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TIterator */\nexport function IsIterator(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Iterator') &&\n value.type === 'Iterator' &&\n IsOptionalString(value.$id) &&\n IsSchema(value.items));\n}\n/** Returns true if the given value is a TKind with the given name. */\nexport function IsKindOf(value, kind) {\n return ValueGuard.IsObject(value) && Kind in value && value[Kind] === kind;\n}\n/** Returns true if the given value is TLiteral<string> */\nexport function IsLiteralString(value) {\n return IsLiteral(value) && ValueGuard.IsString(value.const);\n}\n/** Returns true if the given value is TLiteral<number> */\nexport function IsLiteralNumber(value) {\n return IsLiteral(value) && ValueGuard.IsNumber(value.const);\n}\n/** Returns true if the given value is TLiteral<boolean> */\nexport function IsLiteralBoolean(value) {\n return IsLiteral(value) && ValueGuard.IsBoolean(value.const);\n}\n/** Returns true if the given value is TLiteral */\nexport function IsLiteral(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Literal') &&\n IsOptionalString(value.$id) && IsLiteralValue(value.const));\n}\n/** Returns true if the given value is a TLiteralValue */\nexport function IsLiteralValue(value) {\n return ValueGuard.IsBoolean(value) || ValueGuard.IsNumber(value) || ValueGuard.IsString(value);\n}\n/** Returns true if the given value is a TMappedKey */\nexport function IsMappedKey(value) {\n // prettier-ignore\n return (IsKindOf(value, 'MappedKey') &&\n ValueGuard.IsArray(value.keys) &&\n value.keys.every(key => ValueGuard.IsNumber(key) || ValueGuard.IsString(key)));\n}\n/** Returns true if the given value is TMappedResult */\nexport function IsMappedResult(value) {\n // prettier-ignore\n return (IsKindOf(value, 'MappedResult') &&\n IsProperties(value.properties));\n}\n/** Returns true if the given value is TNever */\nexport function IsNever(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Never') &&\n ValueGuard.IsObject(value.not) &&\n Object.getOwnPropertyNames(value.not).length === 0);\n}\n/** Returns true if the given value is TNot */\nexport function IsNot(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Not') &&\n IsSchema(value.not));\n}\n/** Returns true if the given value is TNull */\nexport function IsNull(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Null') &&\n value.type === 'null' &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TNumber */\nexport function IsNumber(value) {\n return (IsKindOf(value, 'Number') &&\n value.type === 'number' &&\n IsOptionalString(value.$id) &&\n IsOptionalNumber(value.exclusiveMaximum) &&\n IsOptionalNumber(value.exclusiveMinimum) &&\n IsOptionalNumber(value.maximum) &&\n IsOptionalNumber(value.minimum) &&\n IsOptionalNumber(value.multipleOf));\n}\n/** Returns true if the given value is TObject */\nexport function IsObject(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Object') &&\n value.type === 'object' &&\n IsOptionalString(value.$id) &&\n IsProperties(value.properties) &&\n IsAdditionalProperties(value.additionalProperties) &&\n IsOptionalNumber(value.minProperties) &&\n IsOptionalNumber(value.maxProperties));\n}\n/** Returns true if the given value is TPromise */\nexport function IsPromise(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Promise') &&\n value.type === 'Promise' &&\n IsOptionalString(value.$id) &&\n IsSchema(value.item));\n}\n/** Returns true if the given value is TRecord */\nexport function IsRecord(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Record') &&\n value.type === 'object' &&\n IsOptionalString(value.$id) &&\n IsAdditionalProperties(value.additionalProperties) &&\n ValueGuard.IsObject(value.patternProperties) &&\n ((schema) => {\n const keys = Object.getOwnPropertyNames(schema.patternProperties);\n return (keys.length === 1 &&\n IsPattern(keys[0]) &&\n ValueGuard.IsObject(schema.patternProperties) &&\n IsSchema(schema.patternProperties[keys[0]]));\n })(value));\n}\n/** Returns true if this value is TRecursive */\nexport function IsRecursive(value) {\n return ValueGuard.IsObject(value) && Hint in value && value[Hint] === 'Recursive';\n}\n/** Returns true if the given value is TRef */\nexport function IsRef(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Ref') &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsString(value.$ref));\n}\n/** Returns true if the given value is TRegExp */\nexport function IsRegExp(value) {\n // prettier-ignore\n return (IsKindOf(value, 'RegExp') &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsString(value.source) &&\n ValueGuard.IsString(value.flags) &&\n IsOptionalNumber(value.maxLength) &&\n IsOptionalNumber(value.minLength));\n}\n/** Returns true if the given value is TString */\nexport function IsString(value) {\n // prettier-ignore\n return (IsKindOf(value, 'String') &&\n value.type === 'string' &&\n IsOptionalString(value.$id) &&\n IsOptionalNumber(value.minLength) &&\n IsOptionalNumber(value.maxLength) &&\n IsOptionalPattern(value.pattern) &&\n IsOptionalFormat(value.format));\n}\n/** Returns true if the given value is TSymbol */\nexport function IsSymbol(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Symbol') &&\n value.type === 'symbol' &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TTemplateLiteral */\nexport function IsTemplateLiteral(value) {\n // prettier-ignore\n return (IsKindOf(value, 'TemplateLiteral') &&\n value.type === 'string' &&\n ValueGuard.IsString(value.pattern) &&\n value.pattern[0] === '^' &&\n value.pattern[value.pattern.length - 1] === '$');\n}\n/** Returns true if the given value is TThis */\nexport function IsThis(value) {\n // prettier-ignore\n return (IsKindOf(value, 'This') &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsString(value.$ref));\n}\n/** Returns true of this value is TTransform */\nexport function IsTransform(value) {\n return ValueGuard.IsObject(value) && TransformKind in value;\n}\n/** Returns true if the given value is TTuple */\nexport function IsTuple(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Tuple') &&\n value.type === 'array' &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsNumber(value.minItems) &&\n ValueGuard.IsNumber(value.maxItems) &&\n value.minItems === value.maxItems &&\n (( // empty\n ValueGuard.IsUndefined(value.items) &&\n ValueGuard.IsUndefined(value.additionalItems) &&\n value.minItems === 0) || (ValueGuard.IsArray(value.items) &&\n value.items.every(schema => IsSchema(schema)))));\n}\n/** Returns true if the given value is TUndefined */\nexport function IsUndefined(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Undefined') &&\n value.type === 'undefined' &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TUnion<Literal<string | number>[]> */\nexport function IsUnionLiteral(value) {\n return IsUnion(value) && value.anyOf.every((schema) => IsLiteralString(schema) || IsLiteralNumber(schema));\n}\n/** Returns true if the given value is TUnion */\nexport function IsUnion(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Union') &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsObject(value) &&\n ValueGuard.IsArray(value.anyOf) &&\n value.anyOf.every(schema => IsSchema(schema)));\n}\n/** Returns true if the given value is TUint8Array */\nexport function IsUint8Array(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Uint8Array') &&\n value.type === 'Uint8Array' &&\n IsOptionalString(value.$id) &&\n IsOptionalNumber(value.minByteLength) &&\n IsOptionalNumber(value.maxByteLength));\n}\n/** Returns true if the given value is TUnknown */\nexport function IsUnknown(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Unknown') &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is a raw TUnsafe */\nexport function IsUnsafe(value) {\n return IsKindOf(value, 'Unsafe');\n}\n/** Returns true if the given value is TVoid */\nexport function IsVoid(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Void') &&\n value.type === 'void' &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TKind */\nexport function IsKind(value) {\n return ValueGuard.IsObject(value) && Kind in value && ValueGuard.IsString(value[Kind]) && !KnownTypes.includes(value[Kind]);\n}\n/** Returns true if the given value is TSchema */\nexport function IsSchema(value) {\n // prettier-ignore\n return (ValueGuard.IsObject(value)) && (IsAny(value) ||\n IsArgument(value) ||\n IsArray(value) ||\n IsBoolean(value) ||\n IsBigInt(value) ||\n IsAsyncIterator(value) ||\n IsComputed(value) ||\n IsConstructor(value) ||\n IsDate(value) ||\n IsFunction(value) ||\n IsInteger(value) ||\n IsIntersect(value) ||\n IsIterator(value) ||\n IsLiteral(value) ||\n IsMappedKey(value) ||\n IsMappedResult(value) ||\n IsNever(value) ||\n IsNot(value) ||\n IsNull(value) ||\n IsNumber(value) ||\n IsObject(value) ||\n IsPromise(value) ||\n IsRecord(value) ||\n IsRef(value) ||\n IsRegExp(value) ||\n IsString(value) ||\n IsSymbol(value) ||\n IsTemplateLiteral(value) ||\n IsThis(value) ||\n IsTuple(value) ||\n IsUndefined(value) ||\n IsUnion(value) ||\n IsUint8Array(value) ||\n IsUnknown(value) ||\n IsUnsafe(value) ||\n IsVoid(value) ||\n IsKind(value));\n}\n", "export const PatternBoolean = '(true|false)';\nexport const PatternNumber = '(0|[1-9][0-9]*)';\nexport const PatternString = '(.*)';\nexport const PatternNever = '(?!.*)';\nexport const PatternBooleanExact = `^${PatternBoolean}$`;\nexport const PatternNumberExact = `^${PatternNumber}$`;\nexport const PatternStringExact = `^${PatternString}$`;\nexport const PatternNeverExact = `^${PatternNever}$`;\n", "/** Returns true if element right is in the set of left */\n// prettier-ignore\nexport function SetIncludes(T, S) {\n return T.includes(S);\n}\n/** Returns true if left is a subset of right */\nexport function SetIsSubset(T, S) {\n return T.every((L) => SetIncludes(S, L));\n}\n/** Returns a distinct set of elements */\nexport function SetDistinct(T) {\n return [...new Set(T)];\n}\n/** Returns the Intersect of the given sets */\nexport function SetIntersect(T, S) {\n return T.filter((L) => S.includes(L));\n}\n/** Returns the Union of the given sets */\nexport function SetUnion(T, S) {\n return [...T, ...S];\n}\n/** Returns the Complement by omitting elements in T that are in S */\n// prettier-ignore\nexport function SetComplement(T, S) {\n return T.filter(L => !S.includes(L));\n}\n// prettier-ignore\nfunction SetIntersectManyResolve(T, Init) {\n return T.reduce((Acc, L) => {\n return SetIntersect(Acc, L);\n }, Init);\n}\n// prettier-ignore\nexport function SetIntersectMany(T) {\n return (T.length === 1\n ? T[0]\n // Use left to initialize the accumulator for resolve\n : T.length > 1\n ? SetIntersectManyResolve(T.slice(1), T[0])\n : []);\n}\n/** Returns the Union of multiple sets */\nexport function SetUnionMany(T) {\n const Acc = [];\n for (const L of T)\n Acc.push(...L);\n return Acc;\n}\n", "import { CreateType } from '../create/index.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates an Any type */\nexport function Any(options) {\n return CreateType({ [Kind]: 'Any' }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates an Array type */\nexport function Array(items, options) {\n return CreateType({ [Kind]: 'Array', type: 'array', items }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates an Argument Type. */\nexport function Argument(index) {\n return CreateType({ [Kind]: 'Argument', index });\n}\n", "import { Kind } from '../symbols/index.mjs';\nimport { CreateType } from '../create/type.mjs';\n/** `[JavaScript]` Creates a AsyncIterator type */\nexport function AsyncIterator(items, options) {\n return CreateType({ [Kind]: 'AsyncIterator', type: 'AsyncIterator', items }, options);\n}\n", "import { CreateType } from '../create/index.mjs';\nimport { Kind } from '../symbols/symbols.mjs';\n/** `[Internal]` Creates a deferred computed type. This type is used exclusively in modules to defer resolution of computable types that contain interior references */\nexport function Computed(target, parameters, options) {\n return CreateType({ [Kind]: 'Computed', target, parameters }, options);\n}\n", "function DiscardKey(value, key) {\n const { [key]: _, ...rest } = value;\n return rest;\n}\n/** Discards property keys from the given value. This function returns a shallow Clone. */\nexport function Discard(value, keys) {\n return keys.reduce((acc, key) => DiscardKey(acc, key), value);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Never type */\nexport function Never(options) {\n return CreateType({ [Kind]: 'Never', not: {} }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n// prettier-ignore\nexport function MappedResult(properties) {\n return CreateType({\n [Kind]: 'MappedResult',\n properties\n });\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Constructor type */\nexport function Constructor(parameters, returns, options) {\n return CreateType({ [Kind]: 'Constructor', type: 'Constructor', parameters, returns }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Function type */\nexport function Function(parameters, returns, options) {\n return CreateType({ [Kind]: 'Function', type: 'Function', parameters, returns }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\nexport function UnionCreate(T, options) {\n return CreateType({ [Kind]: 'Union', anyOf: T }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { OptionalKind } from '../symbols/index.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { Optional } from '../optional/index.mjs';\nimport { UnionCreate } from './union-create.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsOptional } from '../guard/kind.mjs';\n// prettier-ignore\nfunction IsUnionOptional(types) {\n return types.some(type => IsOptional(type));\n}\n// prettier-ignore\nfunction RemoveOptionalFromRest(types) {\n return types.map(left => IsOptional(left) ? RemoveOptionalFromType(left) : left);\n}\n// prettier-ignore\nfunction RemoveOptionalFromType(T) {\n return (Discard(T, [OptionalKind]));\n}\n// prettier-ignore\nfunction ResolveUnion(types, options) {\n const isOptional = IsUnionOptional(types);\n return (isOptional\n ? Optional(UnionCreate(RemoveOptionalFromRest(types), options))\n : UnionCreate(RemoveOptionalFromRest(types), options));\n}\n/** `[Json]` Creates an evaluated Union type */\nexport function UnionEvaluated(T, options) {\n // prettier-ignore\n return (T.length === 1 ? CreateType(T[0], options) :\n T.length === 0 ? Never(options) :\n ResolveUnion(T, options));\n}\n", "import { Never } from '../never/index.mjs';\nimport { CreateType } from '../create/type.mjs';\nimport { UnionCreate } from './union-create.mjs';\n/** `[Json]` Creates a Union type */\nexport function Union(types, options) {\n // prettier-ignore\n return (types.length === 0 ? Never(options) :\n types.length === 1 ? CreateType(types[0], options) :\n UnionCreate(types, options));\n}\n", "import { TypeBoxError } from '../error/index.mjs';\n// ------------------------------------------------------------------\n// TemplateLiteralParserError\n// ------------------------------------------------------------------\nexport class TemplateLiteralParserError extends TypeBoxError {\n}\n// -------------------------------------------------------------------\n// Unescape\n//\n// Unescape for these control characters specifically. Note that this\n// function is only called on non union group content, and where we\n// still want to allow the user to embed control characters in that\n// content. For review.\n// -------------------------------------------------------------------\n// prettier-ignore\nfunction Unescape(pattern) {\n return pattern\n .replace(/\\\\\\$/g, '$')\n .replace(/\\\\\\*/g, '*')\n .replace(/\\\\\\^/g, '^')\n .replace(/\\\\\\|/g, '|')\n .replace(/\\\\\\(/g, '(')\n .replace(/\\\\\\)/g, ')');\n}\n// -------------------------------------------------------------------\n// Control Characters\n// -------------------------------------------------------------------\nfunction IsNonEscaped(pattern, index, char) {\n return pattern[index] === char && pattern.charCodeAt(index - 1) !== 92;\n}\nfunction IsOpenParen(pattern, index) {\n return IsNonEscaped(pattern, index, '(');\n}\nfunction IsCloseParen(pattern, index) {\n return IsNonEscaped(pattern, index, ')');\n}\nfunction IsSeparator(pattern, index) {\n return IsNonEscaped(pattern, index, '|');\n}\n// -------------------------------------------------------------------\n// Control Groups\n// -------------------------------------------------------------------\nfunction IsGroup(pattern) {\n if (!(IsOpenParen(pattern, 0) && IsCloseParen(pattern, pattern.length - 1)))\n return false;\n let count = 0;\n for (let index = 0; index < pattern.length; index++) {\n if (IsOpenParen(pattern, index))\n count += 1;\n if (IsCloseParen(pattern, index))\n count -= 1;\n if (count === 0 && index !== pattern.length - 1)\n return false;\n }\n return true;\n}\n// prettier-ignore\nfunction InGroup(pattern) {\n return pattern.slice(1, pattern.length - 1);\n}\n// prettier-ignore\nfunction IsPrecedenceOr(pattern) {\n let count = 0;\n for (let index = 0; index < pattern.length; index++) {\n if (IsOpenParen(pattern, index))\n count += 1;\n if (IsCloseParen(pattern, index))\n count -= 1;\n if (IsSeparator(pattern, index) && count === 0)\n return true;\n }\n return false;\n}\n// prettier-ignore\nfunction IsPrecedenceAnd(pattern) {\n for (let index = 0; index < pattern.length; index++) {\n if (IsOpenParen(pattern, index))\n return true;\n }\n return false;\n}\n// prettier-ignore\nfunction Or(pattern) {\n let [count, start] = [0, 0];\n const expressions = [];\n for (let index = 0; index < pattern.length; index++) {\n if (IsOpenParen(pattern, index))\n count += 1;\n if (IsCloseParen(pattern, index))\n count -= 1;\n if (IsSeparator(pattern, index) && count === 0) {\n const range = pattern.slice(start, index);\n if (range.length > 0)\n expressions.push(TemplateLiteralParse(range));\n start = index + 1;\n }\n }\n const range = pattern.slice(start);\n if (range.length > 0)\n expressions.push(TemplateLiteralParse(range));\n if (expressions.length === 0)\n return { type: 'const', const: '' };\n if (expressions.length === 1)\n return expressions[0];\n return { type: 'or', expr: expressions };\n}\n// prettier-ignore\nfunction And(pattern) {\n function Group(value, index) {\n if (!IsOpenParen(value, index))\n throw new TemplateLiteralParserError(`TemplateLiteralParser: Index must point to open parens`);\n let count = 0;\n for (let scan = index; scan < value.length; scan++) {\n if (IsOpenParen(value, scan))\n count += 1;\n if (IsCloseParen(value, scan))\n count -= 1;\n if (count === 0)\n return [index, scan];\n }\n throw new TemplateLiteralParserError(`TemplateLiteralParser: Unclosed group parens in expression`);\n }\n function Range(pattern, index) {\n for (let scan = index; scan < pattern.length; scan++) {\n if (IsOpenParen(pattern, scan))\n return [index, scan];\n }\n return [index, pattern.length];\n }\n const expressions = [];\n for (let index = 0; index < pattern.length; index++) {\n if (IsOpenParen(pattern, index)) {\n const [start, end] = Group(pattern, index);\n const range = pattern.slice(start, end + 1);\n expressions.push(TemplateLiteralParse(range));\n index = end;\n }\n else {\n const [start, end] = Range(pattern, index);\n const range = pattern.slice(start, end);\n if (range.length > 0)\n expressions.push(TemplateLiteralParse(range));\n index = end - 1;\n }\n }\n return ((expressions.length === 0) ? { type: 'const', const: '' } :\n (expressions.length === 1) ? expressions[0] :\n { type: 'and', expr: expressions });\n}\n// ------------------------------------------------------------------\n// TemplateLiteralParse\n// ------------------------------------------------------------------\n/** Parses a pattern and returns an expression tree */\nexport function TemplateLiteralParse(pattern) {\n // prettier-ignore\n return (IsGroup(pattern) ? TemplateLiteralParse(InGroup(pattern)) :\n IsPrecedenceOr(pattern) ? Or(pattern) :\n IsPrecedenceAnd(pattern) ? And(pattern) :\n { type: 'const', const: Unescape(pattern) });\n}\n// ------------------------------------------------------------------\n// TemplateLiteralParseExact\n// ------------------------------------------------------------------\n/** Parses a pattern and strips forward and trailing ^ and $ */\nexport function TemplateLiteralParseExact(pattern) {\n return TemplateLiteralParse(pattern.slice(1, pattern.length - 1));\n}\n", "import { TemplateLiteralParseExact } from './parse.mjs';\nimport { TypeBoxError } from '../error/index.mjs';\n// ------------------------------------------------------------------\n// TemplateLiteralFiniteError\n// ------------------------------------------------------------------\nexport class TemplateLiteralFiniteError extends TypeBoxError {\n}\n// ------------------------------------------------------------------\n// IsTemplateLiteralFiniteCheck\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction IsNumberExpression(expression) {\n return (expression.type === 'or' &&\n expression.expr.length === 2 &&\n expression.expr[0].type === 'const' &&\n expression.expr[0].const === '0' &&\n expression.expr[1].type === 'const' &&\n expression.expr[1].const === '[1-9][0-9]*');\n}\n// prettier-ignore\nfunction IsBooleanExpression(expression) {\n return (expression.type === 'or' &&\n expression.expr.length === 2 &&\n expression.expr[0].type === 'const' &&\n expression.expr[0].const === 'true' &&\n expression.expr[1].type === 'const' &&\n expression.expr[1].const === 'false');\n}\n// prettier-ignore\nfunction IsStringExpression(expression) {\n return expression.type === 'const' && expression.const === '.*';\n}\n// ------------------------------------------------------------------\n// IsTemplateLiteralExpressionFinite\n// ------------------------------------------------------------------\n// prettier-ignore\nexport function IsTemplateLiteralExpressionFinite(expression) {\n return (IsNumberExpression(expression) || IsStringExpression(expression) ? false :\n IsBooleanExpression(expression) ? true :\n (expression.type === 'and') ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) :\n (expression.type === 'or') ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) :\n (expression.type === 'const') ? true :\n (() => { throw new TemplateLiteralFiniteError(`Unknown expression type`); })());\n}\n/** Returns true if this TemplateLiteral resolves to a finite set of values */\nexport function IsTemplateLiteralFinite(schema) {\n const expression = TemplateLiteralParseExact(schema.pattern);\n return IsTemplateLiteralExpressionFinite(expression);\n}\n", "import { IsTemplateLiteralExpressionFinite } from './finite.mjs';\nimport { TemplateLiteralParseExact } from './parse.mjs';\nimport { TypeBoxError } from '../error/index.mjs';\n// ------------------------------------------------------------------\n// TemplateLiteralGenerateError\n// ------------------------------------------------------------------\nexport class TemplateLiteralGenerateError extends TypeBoxError {\n}\n// ------------------------------------------------------------------\n// TemplateLiteralExpressionGenerate\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction* GenerateReduce(buffer) {\n if (buffer.length === 1)\n return yield* buffer[0];\n for (const left of buffer[0]) {\n for (const right of GenerateReduce(buffer.slice(1))) {\n yield `${left}${right}`;\n }\n }\n}\n// prettier-ignore\nfunction* GenerateAnd(expression) {\n return yield* GenerateReduce(expression.expr.map((expr) => [...TemplateLiteralExpressionGenerate(expr)]));\n}\n// prettier-ignore\nfunction* GenerateOr(expression) {\n for (const expr of expression.expr)\n yield* TemplateLiteralExpressionGenerate(expr);\n}\n// prettier-ignore\nfunction* GenerateConst(expression) {\n return yield expression.const;\n}\nexport function* TemplateLiteralExpressionGenerate(expression) {\n return expression.type === 'and'\n ? yield* GenerateAnd(expression)\n : expression.type === 'or'\n ? yield* GenerateOr(expression)\n : expression.type === 'const'\n ? yield* GenerateConst(expression)\n : (() => {\n throw new TemplateLiteralGenerateError('Unknown expression');\n })();\n}\n/** Generates a tuple of strings from the given TemplateLiteral. Returns an empty tuple if infinite. */\nexport function TemplateLiteralGenerate(schema) {\n const expression = TemplateLiteralParseExact(schema.pattern);\n // prettier-ignore\n return (IsTemplateLiteralExpressionFinite(expression)\n ? [...TemplateLiteralExpressionGenerate(expression)]\n : []);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Literal type */\nexport function Literal(value, options) {\n return CreateType({\n [Kind]: 'Literal',\n const: value,\n type: typeof value,\n }, options);\n}\n", "import { Kind } from '../symbols/index.mjs';\nimport { CreateType } from '../create/index.mjs';\n/** `[Json]` Creates a Boolean type */\nexport function Boolean(options) {\n return CreateType({ [Kind]: 'Boolean', type: 'boolean' }, options);\n}\n", "import { Kind } from '../symbols/index.mjs';\nimport { CreateType } from '../create/index.mjs';\n/** `[JavaScript]` Creates a BigInt type */\nexport function BigInt(options) {\n return CreateType({ [Kind]: 'BigInt', type: 'bigint' }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Number type */\nexport function Number(options) {\n return CreateType({ [Kind]: 'Number', type: 'number' }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a String type */\nexport function String(options) {\n return CreateType({ [Kind]: 'String', type: 'string' }, options);\n}\n", "import { Literal } from '../literal/index.mjs';\nimport { Boolean } from '../boolean/index.mjs';\nimport { BigInt } from '../bigint/index.mjs';\nimport { Number } from '../number/index.mjs';\nimport { String } from '../string/index.mjs';\nimport { UnionEvaluated } from '../union/index.mjs';\nimport { Never } from '../never/index.mjs';\n// ------------------------------------------------------------------\n// SyntaxParsers\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction* FromUnion(syntax) {\n const trim = syntax.trim().replace(/\"|'/g, '');\n return (trim === 'boolean' ? yield Boolean() :\n trim === 'number' ? yield Number() :\n trim === 'bigint' ? yield BigInt() :\n trim === 'string' ? yield String() :\n yield (() => {\n const literals = trim.split('|').map((literal) => Literal(literal.trim()));\n return (literals.length === 0 ? Never() :\n literals.length === 1 ? literals[0] :\n UnionEvaluated(literals));\n })());\n}\n// prettier-ignore\nfunction* FromTerminal(syntax) {\n if (syntax[1] !== '{') {\n const L = Literal('$');\n const R = FromSyntax(syntax.slice(1));\n return yield* [L, ...R];\n }\n for (let i = 2; i < syntax.length; i++) {\n if (syntax[i] === '}') {\n const L = FromUnion(syntax.slice(2, i));\n const R = FromSyntax(syntax.slice(i + 1));\n return yield* [...L, ...R];\n }\n }\n yield Literal(syntax);\n}\n// prettier-ignore\nfunction* FromSyntax(syntax) {\n for (let i = 0; i < syntax.length; i++) {\n if (syntax[i] === '$') {\n const L = Literal(syntax.slice(0, i));\n const R = FromTerminal(syntax.slice(i));\n return yield* [L, ...R];\n }\n }\n yield Literal(syntax);\n}\n/** Parses TemplateLiteralSyntax and returns a tuple of TemplateLiteralKinds */\nexport function TemplateLiteralSyntax(syntax) {\n return [...FromSyntax(syntax)];\n}\n", "import { PatternNumber, PatternString, PatternBoolean } from '../patterns/index.mjs';\nimport { Kind } from '../symbols/index.mjs';\nimport { TypeBoxError } from '../error/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsTemplateLiteral, IsUnion, IsNumber, IsInteger, IsBigInt, IsString, IsLiteral, IsBoolean } from '../guard/kind.mjs';\n// ------------------------------------------------------------------\n// TemplateLiteralPatternError\n// ------------------------------------------------------------------\nexport class TemplateLiteralPatternError extends TypeBoxError {\n}\n// ------------------------------------------------------------------\n// TemplateLiteralPattern\n// ------------------------------------------------------------------\nfunction Escape(value) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n// prettier-ignore\nfunction Visit(schema, acc) {\n return (IsTemplateLiteral(schema) ? schema.pattern.slice(1, schema.pattern.length - 1) :\n IsUnion(schema) ? `(${schema.anyOf.map((schema) => Visit(schema, acc)).join('|')})` :\n IsNumber(schema) ? `${acc}${PatternNumber}` :\n IsInteger(schema) ? `${acc}${PatternNumber}` :\n IsBigInt(schema) ? `${acc}${PatternNumber}` :\n IsString(schema) ? `${acc}${PatternString}` :\n IsLiteral(schema) ? `${acc}${Escape(schema.const.toString())}` :\n IsBoolean(schema) ? `${acc}${PatternBoolean}` :\n (() => { throw new TemplateLiteralPatternError(`Unexpected Kind '${schema[Kind]}'`); })());\n}\nexport function TemplateLiteralPattern(kinds) {\n return `^${kinds.map((schema) => Visit(schema, '')).join('')}\\$`;\n}\n", "import { UnionEvaluated } from '../union/index.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { TemplateLiteralGenerate } from './generate.mjs';\n/** Returns a Union from the given TemplateLiteral */\nexport function TemplateLiteralToUnion(schema) {\n const R = TemplateLiteralGenerate(schema);\n const L = R.map((S) => Literal(S));\n return UnionEvaluated(L);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { TemplateLiteralSyntax } from './syntax.mjs';\nimport { TemplateLiteralPattern } from './pattern.mjs';\nimport { IsString } from '../guard/value.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a TemplateLiteral type */\n// prettier-ignore\nexport function TemplateLiteral(unresolved, options) {\n const pattern = IsString(unresolved)\n ? TemplateLiteralPattern(TemplateLiteralSyntax(unresolved))\n : TemplateLiteralPattern(unresolved);\n return CreateType({ [Kind]: 'TemplateLiteral', type: 'string', pattern }, options);\n}\n", "import { TemplateLiteralGenerate } from '../template-literal/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsTemplateLiteral, IsUnion, IsLiteral, IsNumber, IsInteger } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromTemplateLiteral(templateLiteral) {\n const keys = TemplateLiteralGenerate(templateLiteral);\n return keys.map(key => key.toString());\n}\n// prettier-ignore\nfunction FromUnion(types) {\n const result = [];\n for (const type of types)\n result.push(...IndexPropertyKeys(type));\n return result;\n}\n// prettier-ignore\nfunction FromLiteral(literalValue) {\n return ([literalValue.toString()] // TS 5.4 observes TLiteralValue as not having a toString()\n );\n}\n/** Returns a tuple of PropertyKeys derived from the given TSchema */\n// prettier-ignore\nexport function IndexPropertyKeys(type) {\n return [...new Set((IsTemplateLiteral(type) ? FromTemplateLiteral(type) :\n IsUnion(type) ? FromUnion(type.anyOf) :\n IsLiteral(type) ? FromLiteral(type.const) :\n IsNumber(type) ? ['[number]'] :\n IsInteger(type) ? ['[number]'] :\n []))];\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { IndexPropertyKeys } from './indexed-property-keys.mjs';\nimport { Index } from './index.mjs';\n// prettier-ignore\nfunction FromProperties(type, properties, options) {\n const result = {};\n for (const K2 of Object.getOwnPropertyNames(properties)) {\n result[K2] = Index(type, IndexPropertyKeys(properties[K2]), options);\n }\n return result;\n}\n// prettier-ignore\nfunction FromMappedResult(type, mappedResult, options) {\n return FromProperties(type, mappedResult.properties, options);\n}\n// prettier-ignore\nexport function IndexFromMappedResult(type, mappedResult, options) {\n const properties = FromMappedResult(type, mappedResult, options);\n return MappedResult(properties);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { TypeBoxError } from '../error/index.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { IntersectEvaluated } from '../intersect/index.mjs';\nimport { UnionEvaluated } from '../union/index.mjs';\nimport { IndexPropertyKeys } from './indexed-property-keys.mjs';\nimport { IndexFromMappedKey } from './indexed-from-mapped-key.mjs';\nimport { IndexFromMappedResult } from './indexed-from-mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsArray, IsIntersect, IsObject, IsMappedKey, IsMappedResult, IsNever, IsSchema, IsTuple, IsUnion, IsRef } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromRest(types, key) {\n return types.map(type => IndexFromPropertyKey(type, key));\n}\n// prettier-ignore\nfunction FromIntersectRest(types) {\n return types.filter(type => !IsNever(type));\n}\n// prettier-ignore\nfunction FromIntersect(types, key) {\n return (IntersectEvaluated(FromIntersectRest(FromRest(types, key))));\n}\n// prettier-ignore\nfunction FromUnionRest(types) {\n return (types.some(L => IsNever(L))\n ? []\n : types);\n}\n// prettier-ignore\nfunction FromUnion(types, key) {\n return (UnionEvaluated(FromUnionRest(FromRest(types, key))));\n}\n// prettier-ignore\nfunction FromTuple(types, key) {\n return (key in types ? types[key] :\n key === '[number]' ? UnionEvaluated(types) :\n Never());\n}\n// prettier-ignore\nfunction FromArray(type, key) {\n return (key === '[number]'\n ? type\n : Never());\n}\n// prettier-ignore\nfunction FromProperty(properties, propertyKey) {\n return (propertyKey in properties ? properties[propertyKey] : Never());\n}\n// prettier-ignore\nexport function IndexFromPropertyKey(type, propertyKey) {\n return (IsIntersect(type) ? FromIntersect(type.allOf, propertyKey) :\n IsUnion(type) ? FromUnion(type.anyOf, propertyKey) :\n IsTuple(type) ? FromTuple(type.items ?? [], propertyKey) :\n IsArray(type) ? FromArray(type.items, propertyKey) :\n IsObject(type) ? FromProperty(type.properties, propertyKey) :\n Never());\n}\n// prettier-ignore\nexport function IndexFromPropertyKeys(type, propertyKeys) {\n return propertyKeys.map(propertyKey => IndexFromPropertyKey(type, propertyKey));\n}\n// prettier-ignore\nfunction FromSchema(type, propertyKeys) {\n return (UnionEvaluated(IndexFromPropertyKeys(type, propertyKeys)));\n}\n// prettier-ignore\nexport function IndexFromComputed(type, key) {\n return Computed('Index', [type, key]);\n}\n/** `[Json]` Returns an Indexed property type for the given keys */\nexport function Index(type, key, options) {\n // computed-type\n if (IsRef(type) || IsRef(key)) {\n const error = `Index types using Ref parameters require both Type and Key to be of TSchema`;\n if (!IsSchema(type) || !IsSchema(key))\n throw new TypeBoxError(error);\n return Computed('Index', [type, key]);\n }\n // mapped-types\n if (IsMappedResult(key))\n return IndexFromMappedResult(type, key, options);\n if (IsMappedKey(key))\n return IndexFromMappedKey(type, key, options);\n // prettier-ignore\n return CreateType(IsSchema(key)\n ? FromSchema(type, IndexPropertyKeys(key))\n : FromSchema(type, key), options);\n}\n", "import { Index } from './indexed.mjs';\nimport { MappedResult } from '../mapped/index.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction MappedIndexPropertyKey(type, key, options) {\n return { [key]: Index(type, [key], Clone(options)) };\n}\n// prettier-ignore\nfunction MappedIndexPropertyKeys(type, propertyKeys, options) {\n return propertyKeys.reduce((result, left) => {\n return { ...result, ...MappedIndexPropertyKey(type, left, options) };\n }, {});\n}\n// prettier-ignore\nfunction MappedIndexProperties(type, mappedKey, options) {\n return MappedIndexPropertyKeys(type, mappedKey.keys, options);\n}\n// prettier-ignore\nexport function IndexFromMappedKey(type, mappedKey, options) {\n const properties = MappedIndexProperties(type, mappedKey, options);\n return MappedResult(properties);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates an Iterator type */\nexport function Iterator(items, options) {\n return CreateType({ [Kind]: 'Iterator', type: 'Iterator', items }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsOptional } from '../guard/kind.mjs';\n/** Creates a RequiredArray derived from the given TProperties value. */\nfunction RequiredArray(properties) {\n return globalThis.Object.keys(properties).filter((key) => !IsOptional(properties[key]));\n}\n/** `[Json]` Creates an Object type */\nfunction _Object_(properties, options) {\n const required = RequiredArray(properties);\n const schema = required.length > 0 ? { [Kind]: 'Object', type: 'object', required, properties } : { [Kind]: 'Object', type: 'object', properties };\n return CreateType(schema, options);\n}\n// ------------------------------------------------------------------\n// TypeScript 7: CommonJS TS2441\n//\n// TypeScript generates a CommonJS shim that patches local variables\n// via an unqualified reference to Object (e.g. the __esModule shim's\n// Object.defineProperty call). Other compiler tools have been\n// observed patching in the same way, but TypeScript 7 has correctly\n// begun flagging variables named Object in CommonJS, since they\n// conflict with the shim and can cause \"used before definition\"\n// errors. This is CommonJS-specific; no such shim exists for ESM.\n//\n// TypeBox works around this using a `var` declaration, which is\n// known to avoid use-before-definition errors. TypeBox 1.x employs\n// a similar strategy.\n// ------------------------------------------------------------------\n/** `[Json]` Creates an Object type */\n// @ts-ignore - error TS2441: Duplicate identifier 'Object'. Compiler reserves name 'Object' in top level scope of a module.\nexport var Object = _Object_;\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Promise type */\nexport function Promise(item, options) {\n return CreateType({ [Kind]: 'Promise', type: 'Promise', item }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { ReadonlyKind } from '../symbols/index.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { ReadonlyFromMappedResult } from './readonly-from-mapped-result.mjs';\nimport { IsMappedResult } from '../guard/kind.mjs';\nfunction RemoveReadonly(schema) {\n return CreateType(Discard(schema, [ReadonlyKind]));\n}\nfunction AddReadonly(schema) {\n return CreateType({ ...schema, [ReadonlyKind]: 'Readonly' });\n}\n// prettier-ignore\nfunction ReadonlyWithFlag(schema, F) {\n return (F === false\n ? RemoveReadonly(schema)\n : AddReadonly(schema));\n}\n/** `[Json]` Creates a Readonly property */\nexport function Readonly(schema, enable) {\n const F = enable ?? true;\n return IsMappedResult(schema) ? ReadonlyFromMappedResult(schema, F) : ReadonlyWithFlag(schema, F);\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Readonly } from './readonly.mjs';\n// prettier-ignore\nfunction FromProperties(K, F) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(K))\n Acc[K2] = Readonly(K[K2], F);\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(R, F) {\n return FromProperties(R.properties, F);\n}\n// prettier-ignore\nexport function ReadonlyFromMappedResult(R, F) {\n const P = FromMappedResult(R, F);\n return MappedResult(P);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Tuple type */\nexport function Tuple(types, options) {\n // prettier-ignore\n return CreateType(types.length > 0 ?\n { [Kind]: 'Tuple', type: 'array', items: types, additionalItems: false, minItems: types.length, maxItems: types.length } :\n { [Kind]: 'Tuple', type: 'array', minItems: types.length, maxItems: types.length }, options);\n}\n", "import { Kind, OptionalKind, ReadonlyKind } from '../symbols/index.mjs';\nimport { Discard } from '../discard/index.mjs';\n// evaluation types\nimport { Array } from '../array/index.mjs';\nimport { AsyncIterator } from '../async-iterator/index.mjs';\nimport { Constructor } from '../constructor/index.mjs';\nimport { Function as FunctionType } from '../function/index.mjs';\nimport { IndexPropertyKeys } from '../indexed/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Iterator } from '../iterator/index.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Object as _Object_ } from '../object/index.mjs';\nimport { Optional } from '../optional/index.mjs';\nimport { Promise } from '../promise/index.mjs';\nimport { Readonly } from '../readonly/index.mjs';\nimport { Tuple } from '../tuple/index.mjs';\nimport { Union } from '../union/index.mjs';\n// operator\nimport { SetIncludes } from '../sets/index.mjs';\n// mapping types\nimport { MappedResult } from './mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsArray, IsAsyncIterator, IsConstructor, IsFunction, IsIntersect, IsIterator, IsReadonly, IsMappedResult, IsMappedKey, IsObject, IsOptional, IsPromise, IsSchema, IsTuple, IsUnion } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromMappedResult(K, P) {\n return (K in P\n ? FromSchemaType(K, P[K])\n : MappedResult(P));\n}\n// prettier-ignore\nfunction MappedKeyToKnownMappedResultProperties(K) {\n return { [K]: Literal(K) };\n}\n// prettier-ignore\nfunction MappedKeyToUnknownMappedResultProperties(P) {\n const Acc = {};\n for (const L of P)\n Acc[L] = Literal(L);\n return Acc;\n}\n// prettier-ignore\nfunction MappedKeyToMappedResultProperties(K, P) {\n return (SetIncludes(P, K)\n ? MappedKeyToKnownMappedResultProperties(K)\n : MappedKeyToUnknownMappedResultProperties(P));\n}\n// prettier-ignore\nfunction FromMappedKey(K, P) {\n const R = MappedKeyToMappedResultProperties(K, P);\n return FromMappedResult(K, R);\n}\n// prettier-ignore\nfunction FromRest(K, T) {\n return T.map(L => FromSchemaType(K, L));\n}\n// prettier-ignore\nfunction FromProperties(K, T) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(T))\n Acc[K2] = FromSchemaType(K, T[K2]);\n return Acc;\n}\n// prettier-ignore\nfunction FromSchemaType(K, T) {\n // required to retain user defined options for mapped type\n const options = { ...T };\n return (\n // unevaluated modifier types\n IsOptional(T) ? Optional(FromSchemaType(K, Discard(T, [OptionalKind]))) :\n IsReadonly(T) ? Readonly(FromSchemaType(K, Discard(T, [ReadonlyKind]))) :\n // unevaluated mapped types\n IsMappedResult(T) ? FromMappedResult(K, T.properties) :\n IsMappedKey(T) ? FromMappedKey(K, T.keys) :\n // unevaluated types\n IsConstructor(T) ? Constructor(FromRest(K, T.parameters), FromSchemaType(K, T.returns), options) :\n IsFunction(T) ? FunctionType(FromRest(K, T.parameters), FromSchemaType(K, T.returns), options) :\n IsAsyncIterator(T) ? AsyncIterator(FromSchemaType(K, T.items), options) :\n IsIterator(T) ? Iterator(FromSchemaType(K, T.items), options) :\n IsIntersect(T) ? Intersect(FromRest(K, T.allOf), options) :\n IsUnion(T) ? Union(FromRest(K, T.anyOf), options) :\n IsTuple(T) ? Tuple(FromRest(K, T.items ?? []), options) :\n IsObject(T) ? _Object_(FromProperties(K, T.properties), options) :\n IsArray(T) ? Array(FromSchemaType(K, T.items), options) :\n IsPromise(T) ? Promise(FromSchemaType(K, T.item), options) :\n T);\n}\n// prettier-ignore\nexport function MappedFunctionReturnType(K, T) {\n const Acc = {};\n for (const L of K)\n Acc[L] = FromSchemaType(L, T);\n return Acc;\n}\n/** `[Json]` Creates a Mapped object type */\nexport function Mapped(key, map, options) {\n const K = IsSchema(key) ? IndexPropertyKeys(key) : key;\n const RT = map({ [Kind]: 'MappedKey', keys: K });\n const R = MappedFunctionReturnType(K, RT);\n return _Object_(R, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { OptionalKind } from '../symbols/index.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { OptionalFromMappedResult } from './optional-from-mapped-result.mjs';\nimport { IsMappedResult } from '../guard/kind.mjs';\nfunction RemoveOptional(schema) {\n return CreateType(Discard(schema, [OptionalKind]));\n}\nfunction AddOptional(schema) {\n return CreateType({ ...schema, [OptionalKind]: 'Optional' });\n}\n// prettier-ignore\nfunction OptionalWithFlag(schema, F) {\n return (F === false\n ? RemoveOptional(schema)\n : AddOptional(schema));\n}\n/** `[Json]` Creates a Optional property */\nexport function Optional(schema, enable) {\n const F = enable ?? true;\n return IsMappedResult(schema) ? OptionalFromMappedResult(schema, F) : OptionalWithFlag(schema, F);\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Optional } from './optional.mjs';\n// prettier-ignore\nfunction FromProperties(P, F) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(P))\n Acc[K2] = Optional(P[K2], F);\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(R, F) {\n return FromProperties(R.properties, F);\n}\n// prettier-ignore\nexport function OptionalFromMappedResult(R, F) {\n const P = FromMappedResult(R, F);\n return MappedResult(P);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsObject, IsSchema } from '../guard/kind.mjs';\n// ------------------------------------------------------------------\n// IntersectCreate\n// ------------------------------------------------------------------\n// prettier-ignore\nexport function IntersectCreate(T, options = {}) {\n const allObjects = T.every((schema) => IsObject(schema));\n const clonedUnevaluatedProperties = IsSchema(options.unevaluatedProperties)\n ? { unevaluatedProperties: options.unevaluatedProperties }\n : {};\n return CreateType((options.unevaluatedProperties === false || IsSchema(options.unevaluatedProperties) || allObjects\n ? { ...clonedUnevaluatedProperties, [Kind]: 'Intersect', type: 'object', allOf: T }\n : { ...clonedUnevaluatedProperties, [Kind]: 'Intersect', allOf: T }), options);\n}\n", "import { OptionalKind } from '../symbols/index.mjs';\nimport { CreateType } from '../create/type.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { Optional } from '../optional/index.mjs';\nimport { IntersectCreate } from './intersect-create.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsOptional, IsTransform } from '../guard/kind.mjs';\n// prettier-ignore\nfunction IsIntersectOptional(types) {\n return types.every(left => IsOptional(left));\n}\n// prettier-ignore\nfunction RemoveOptionalFromType(type) {\n return (Discard(type, [OptionalKind]));\n}\n// prettier-ignore\nfunction RemoveOptionalFromRest(types) {\n return types.map(left => IsOptional(left) ? RemoveOptionalFromType(left) : left);\n}\n// prettier-ignore\nfunction ResolveIntersect(types, options) {\n return (IsIntersectOptional(types)\n ? Optional(IntersectCreate(RemoveOptionalFromRest(types), options))\n : IntersectCreate(RemoveOptionalFromRest(types), options));\n}\n/** `[Json]` Creates an evaluated Intersect type */\nexport function IntersectEvaluated(types, options = {}) {\n if (types.length === 1)\n return CreateType(types[0], options);\n if (types.length === 0)\n return Never(options);\n if (types.some((schema) => IsTransform(schema)))\n throw new Error('Cannot intersect transform types');\n return ResolveIntersect(types, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Never } from '../never/index.mjs';\nimport { IntersectCreate } from './intersect-create.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsTransform } from '../guard/kind.mjs';\n/** `[Json]` Creates an evaluated Intersect type */\nexport function Intersect(types, options) {\n if (types.length === 1)\n return CreateType(types[0], options);\n if (types.length === 0)\n return Never(options);\n if (types.some((schema) => IsTransform(schema)))\n throw new Error('Cannot intersect transform types');\n return IntersectCreate(types, options);\n}\n", "import { TypeBoxError } from '../error/index.mjs';\nimport { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Ref type. The referenced type must contain a $id */\nexport function Ref(...args) {\n const [$ref, options] = typeof args[0] === 'string' ? [args[0], args[1]] : [args[0].$id, args[1]];\n if (typeof $ref !== 'string')\n throw new TypeBoxError('Ref: $ref must be a string');\n return CreateType({ [Kind]: 'Ref', $ref }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { Ref } from '../ref/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsIntersect, IsUnion, IsPromise, IsRef, IsComputed } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromComputed(target, parameters) {\n return Computed('Awaited', [Computed(target, parameters)]);\n}\n// prettier-ignore\nfunction FromRef($ref) {\n return Computed('Awaited', [Ref($ref)]);\n}\n// prettier-ignore\nfunction FromIntersect(types) {\n return Intersect(FromRest(types));\n}\n// prettier-ignore\nfunction FromUnion(types) {\n return Union(FromRest(types));\n}\n// prettier-ignore\nfunction FromPromise(type) {\n return Awaited(type);\n}\n// prettier-ignore\nfunction FromRest(types) {\n return types.map(type => Awaited(type));\n}\n/** `[JavaScript]` Constructs a type by recursively unwrapping Promise types */\nexport function Awaited(type, options) {\n return CreateType(IsComputed(type) ? FromComputed(type.target, type.parameters) : IsIntersect(type) ? FromIntersect(type.allOf) : IsUnion(type) ? FromUnion(type.anyOf) : IsPromise(type) ? FromPromise(type.item) : IsRef(type) ? FromRef(type.$ref) : type, options);\n}\n", "import { SetUnionMany, SetIntersectMany } from '../sets/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsIntersect, IsUnion, IsTuple, IsArray, IsObject, IsRecord } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromRest(types) {\n const result = [];\n for (const L of types)\n result.push(KeyOfPropertyKeys(L));\n return result;\n}\n// prettier-ignore\nfunction FromIntersect(types) {\n const propertyKeysArray = FromRest(types);\n const propertyKeys = SetUnionMany(propertyKeysArray);\n return propertyKeys;\n}\n// prettier-ignore\nfunction FromUnion(types) {\n const propertyKeysArray = FromRest(types);\n const propertyKeys = SetIntersectMany(propertyKeysArray);\n return propertyKeys;\n}\n// prettier-ignore\nfunction FromTuple(types) {\n return types.map((_, indexer) => indexer.toString());\n}\n// prettier-ignore\nfunction FromArray(_) {\n return (['[number]']);\n}\n// prettier-ignore\nfunction FromProperties(T) {\n return (globalThis.Object.getOwnPropertyNames(T));\n}\n// ------------------------------------------------------------------\n// FromPatternProperties\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromPatternProperties(patternProperties) {\n if (!includePatternProperties)\n return [];\n const patternPropertyKeys = globalThis.Object.getOwnPropertyNames(patternProperties);\n return patternPropertyKeys.map(key => {\n return (key[0] === '^' && key[key.length - 1] === '$')\n ? key.slice(1, key.length - 1)\n : key;\n });\n}\n/** Returns a tuple of PropertyKeys derived from the given TSchema. */\n// prettier-ignore\nexport function KeyOfPropertyKeys(type) {\n return (IsIntersect(type) ? FromIntersect(type.allOf) :\n IsUnion(type) ? FromUnion(type.anyOf) :\n IsTuple(type) ? FromTuple(type.items ?? []) :\n IsArray(type) ? FromArray(type.items) :\n IsObject(type) ? FromProperties(type.properties) :\n IsRecord(type) ? FromPatternProperties(type.patternProperties) :\n []);\n}\n// ----------------------------------------------------------------\n// KeyOfPattern\n// ----------------------------------------------------------------\nlet includePatternProperties = false;\n/** Returns a regular expression pattern derived from the given TSchema */\nexport function KeyOfPattern(schema) {\n includePatternProperties = true;\n const keys = KeyOfPropertyKeys(schema);\n includePatternProperties = false;\n const pattern = keys.map((key) => `(${key})`);\n return `^(${pattern.join('|')})$`;\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Number } from '../number/index.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Ref } from '../ref/index.mjs';\nimport { KeyOfPropertyKeys } from './keyof-property-keys.mjs';\nimport { UnionEvaluated } from '../union/index.mjs';\nimport { KeyOfFromMappedResult } from './keyof-from-mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedResult, IsRef, IsComputed } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromComputed(target, parameters) {\n return Computed('KeyOf', [Computed(target, parameters)]);\n}\n// prettier-ignore\nfunction FromRef($ref) {\n return Computed('KeyOf', [Ref($ref)]);\n}\n// prettier-ignore\nfunction KeyOfFromType(type, options) {\n const propertyKeys = KeyOfPropertyKeys(type);\n const propertyKeyTypes = KeyOfPropertyKeysToRest(propertyKeys);\n const result = UnionEvaluated(propertyKeyTypes);\n return CreateType(result, options);\n}\n// prettier-ignore\nexport function KeyOfPropertyKeysToRest(propertyKeys) {\n return propertyKeys.map(L => L === '[number]' ? Number() : Literal(L));\n}\n/** `[Json]` Creates a KeyOf type */\nexport function KeyOf(type, options) {\n return (IsComputed(type) ? FromComputed(type.target, type.parameters) : IsRef(type) ? FromRef(type.$ref) : IsMappedResult(type) ? KeyOfFromMappedResult(type, options) : KeyOfFromType(type, options));\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { KeyOf } from './keyof.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromProperties(properties, options) {\n const result = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(properties))\n result[K2] = KeyOf(properties[K2], Clone(options));\n return result;\n}\n// prettier-ignore\nfunction FromMappedResult(mappedResult, options) {\n return FromProperties(mappedResult.properties, options);\n}\n// prettier-ignore\nexport function KeyOfFromMappedResult(mappedResult, options) {\n const properties = FromMappedResult(mappedResult, options);\n return MappedResult(properties);\n}\n", "import { IntersectEvaluated } from '../intersect/index.mjs';\nimport { IndexFromPropertyKeys } from '../indexed/index.mjs';\nimport { KeyOfPropertyKeys } from '../keyof/index.mjs';\nimport { Object as _Object_ } from '../object/index.mjs';\nimport { SetDistinct } from '../sets/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsNever } from '../guard/kind.mjs';\n// prettier-ignore\nfunction CompositeKeys(T) {\n const Acc = [];\n for (const L of T)\n Acc.push(...KeyOfPropertyKeys(L));\n return SetDistinct(Acc);\n}\n// prettier-ignore\nfunction FilterNever(T) {\n return T.filter(L => !IsNever(L));\n}\n// prettier-ignore\nfunction CompositeProperty(T, K) {\n const Acc = [];\n for (const L of T)\n Acc.push(...IndexFromPropertyKeys(L, [K]));\n return FilterNever(Acc);\n}\n// prettier-ignore\nfunction CompositeProperties(T, K) {\n const Acc = {};\n for (const L of K) {\n Acc[L] = IntersectEvaluated(CompositeProperty(T, L));\n }\n return Acc;\n}\n// prettier-ignore\nexport function Composite(T, options) {\n const K = CompositeKeys(T);\n const P = CompositeProperties(T, K);\n const R = _Object_(P, options);\n return R;\n}\n", "import { Kind } from '../symbols/index.mjs';\nimport { CreateType } from '../create/type.mjs';\n/** `[JavaScript]` Creates a Date type */\nexport function Date(options) {\n return CreateType({ [Kind]: 'Date', type: 'Date' }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Null type */\nexport function Null(options) {\n return CreateType({ [Kind]: 'Null', type: 'null' }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Symbol type */\nexport function Symbol(options) {\n return CreateType({ [Kind]: 'Symbol', type: 'symbol' }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Undefined type */\nexport function Undefined(options) {\n return CreateType({ [Kind]: 'Undefined', type: 'undefined' }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Uint8Array type */\nexport function Uint8Array(options) {\n return CreateType({ [Kind]: 'Uint8Array', type: 'Uint8Array' }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates an Unknown type */\nexport function Unknown(options) {\n return CreateType({ [Kind]: 'Unknown' }, options);\n}\n", "import { Any } from '../any/index.mjs';\nimport { BigInt } from '../bigint/index.mjs';\nimport { Date } from '../date/index.mjs';\nimport { Function as FunctionType } from '../function/index.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Null } from '../null/index.mjs';\nimport { Object as _Object_ } from '../object/index.mjs';\nimport { Symbol } from '../symbol/index.mjs';\nimport { Tuple } from '../tuple/index.mjs';\nimport { Readonly } from '../readonly/index.mjs';\nimport { Undefined } from '../undefined/index.mjs';\nimport { Uint8Array } from '../uint8array/index.mjs';\nimport { Unknown } from '../unknown/index.mjs';\nimport { CreateType } from '../create/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { IsArray, IsNumber, IsBigInt, IsUint8Array, IsDate, IsIterator, IsObject, IsAsyncIterator, IsFunction, IsUndefined, IsNull, IsSymbol, IsBoolean, IsString } from '../guard/value.mjs';\n// prettier-ignore\nfunction FromArray(T) {\n return T.map(L => FromValue(L, false));\n}\n// prettier-ignore\nfunction FromProperties(value) {\n const Acc = {};\n for (const K of globalThis.Object.getOwnPropertyNames(value))\n Acc[K] = Readonly(FromValue(value[K], false));\n return Acc;\n}\nfunction ConditionalReadonly(T, root) {\n return (root === true ? T : Readonly(T));\n}\n// prettier-ignore\nfunction FromValue(value, root) {\n return (IsAsyncIterator(value) ? ConditionalReadonly(Any(), root) :\n IsIterator(value) ? ConditionalReadonly(Any(), root) :\n IsArray(value) ? Readonly(Tuple(FromArray(value))) :\n IsUint8Array(value) ? Uint8Array() :\n IsDate(value) ? Date() :\n IsObject(value) ? ConditionalReadonly(_Object_(FromProperties(value)), root) :\n IsFunction(value) ? ConditionalReadonly(FunctionType([], Unknown()), root) :\n IsUndefined(value) ? Undefined() :\n IsNull(value) ? Null() :\n IsSymbol(value) ? Symbol() :\n IsBigInt(value) ? BigInt() :\n IsNumber(value) ? Literal(value) :\n IsBoolean(value) ? Literal(value) :\n IsString(value) ? Literal(value) :\n _Object_({}));\n}\n/** `[JavaScript]` Creates a readonly const type from the given value. */\nexport function Const(T, options) {\n return CreateType(FromValue(T, true), options);\n}\n", "import { Tuple } from '../tuple/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport * as KindGuard from '../guard/kind.mjs';\n/** `[JavaScript]` Extracts the ConstructorParameters from the given Constructor type */\nexport function ConstructorParameters(schema, options) {\n return (KindGuard.IsConstructor(schema) ? Tuple(schema.parameters, options) : Never(options));\n}\n", "import { Literal } from '../literal/index.mjs';\nimport { Kind, Hint } from '../symbols/index.mjs';\nimport { Union } from '../union/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { IsUndefined } from '../guard/value.mjs';\n/** `[Json]` Creates a Enum type */\nexport function Enum(item, options) {\n if (IsUndefined(item))\n throw new Error('Enum undefined or empty');\n const values1 = globalThis.Object.getOwnPropertyNames(item)\n .filter((key) => isNaN(key))\n .map((key) => item[key]);\n const values2 = [...new Set(values1)];\n const anyOf = values2.map((value) => Literal(value));\n return Union(anyOf, { ...options, [Hint]: 'Enum' });\n}\n", "import { Any } from '../any/index.mjs';\nimport { Function as FunctionType } from '../function/index.mjs';\nimport { Number } from '../number/index.mjs';\nimport { String } from '../string/index.mjs';\nimport { Unknown } from '../unknown/index.mjs';\nimport { TemplateLiteralToUnion } from '../template-literal/index.mjs';\nimport { PatternNumberExact, PatternStringExact } from '../patterns/index.mjs';\nimport { Kind, Hint } from '../symbols/index.mjs';\nimport { TypeBoxError } from '../error/index.mjs';\nimport { TypeGuard, ValueGuard } from '../guard/index.mjs';\nexport class ExtendsResolverError extends TypeBoxError {\n}\nexport var ExtendsResult;\n(function (ExtendsResult) {\n ExtendsResult[ExtendsResult[\"Union\"] = 0] = \"Union\";\n ExtendsResult[ExtendsResult[\"True\"] = 1] = \"True\";\n ExtendsResult[ExtendsResult[\"False\"] = 2] = \"False\";\n})(ExtendsResult || (ExtendsResult = {}));\n// ------------------------------------------------------------------\n// IntoBooleanResult\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction IntoBooleanResult(result) {\n return result === ExtendsResult.False ? result : ExtendsResult.True;\n}\n// ------------------------------------------------------------------\n// Throw\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction Throw(message) {\n throw new ExtendsResolverError(message);\n}\n// ------------------------------------------------------------------\n// StructuralRight\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction IsStructuralRight(right) {\n return (TypeGuard.IsNever(right) ||\n TypeGuard.IsIntersect(right) ||\n TypeGuard.IsUnion(right) ||\n TypeGuard.IsUnknown(right) ||\n TypeGuard.IsAny(right));\n}\n// prettier-ignore\nfunction StructuralRight(left, right) {\n return (TypeGuard.IsNever(right) ? FromNeverRight(left, right) :\n TypeGuard.IsIntersect(right) ? FromIntersectRight(left, right) :\n TypeGuard.IsUnion(right) ? FromUnionRight(left, right) :\n TypeGuard.IsUnknown(right) ? FromUnknownRight(left, right) :\n TypeGuard.IsAny(right) ? FromAnyRight(left, right) :\n Throw('StructuralRight'));\n}\n// ------------------------------------------------------------------\n// Any\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromAnyRight(left, right) {\n return ExtendsResult.True;\n}\n// prettier-ignore\nfunction FromAny(left, right) {\n return (TypeGuard.IsIntersect(right) ? FromIntersectRight(left, right) :\n (TypeGuard.IsUnion(right) && right.anyOf.some((schema) => TypeGuard.IsAny(schema) || TypeGuard.IsUnknown(schema))) ? ExtendsResult.True :\n TypeGuard.IsUnion(right) ? ExtendsResult.Union :\n TypeGuard.IsUnknown(right) ? ExtendsResult.True :\n TypeGuard.IsAny(right) ? ExtendsResult.True :\n ExtendsResult.Union);\n}\n// ------------------------------------------------------------------\n// Array\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromArrayRight(left, right) {\n return (TypeGuard.IsUnknown(left) ? ExtendsResult.False :\n TypeGuard.IsAny(left) ? ExtendsResult.Union :\n TypeGuard.IsNever(left) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromArray(left, right) {\n return (TypeGuard.IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True :\n IsStructuralRight(right) ? StructuralRight(left, right) :\n !TypeGuard.IsArray(right) ? ExtendsResult.False :\n IntoBooleanResult(Visit(left.items, right.items)));\n}\n// ------------------------------------------------------------------\n// AsyncIterator\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromAsyncIterator(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n !TypeGuard.IsAsyncIterator(right) ? ExtendsResult.False :\n IntoBooleanResult(Visit(left.items, right.items)));\n}\n// ------------------------------------------------------------------\n// BigInt\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromBigInt(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsBigInt(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Boolean\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromBooleanRight(left, right) {\n return (TypeGuard.IsLiteralBoolean(left) ? ExtendsResult.True :\n TypeGuard.IsBoolean(left) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromBoolean(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsBoolean(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Constructor\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromConstructor(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n !TypeGuard.IsConstructor(right) ? ExtendsResult.False :\n left.parameters.length > right.parameters.length ? ExtendsResult.False :\n (!left.parameters.every((schema, index) => IntoBooleanResult(Visit(right.parameters[index], schema)) === ExtendsResult.True)) ? ExtendsResult.False :\n IntoBooleanResult(Visit(left.returns, right.returns)));\n}\n// ------------------------------------------------------------------\n// Date\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromDate(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsDate(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Function\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromFunction(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n !TypeGuard.IsFunction(right) ? ExtendsResult.False :\n left.parameters.length > right.parameters.length ? ExtendsResult.False :\n (!left.parameters.every((schema, index) => IntoBooleanResult(Visit(right.parameters[index], schema)) === ExtendsResult.True)) ? ExtendsResult.False :\n IntoBooleanResult(Visit(left.returns, right.returns)));\n}\n// ------------------------------------------------------------------\n// Integer\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromIntegerRight(left, right) {\n return (TypeGuard.IsLiteral(left) && ValueGuard.IsNumber(left.const) ? ExtendsResult.True :\n TypeGuard.IsNumber(left) || TypeGuard.IsInteger(left) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromInteger(left, right) {\n return (TypeGuard.IsInteger(right) || TypeGuard.IsNumber(right) ? ExtendsResult.True :\n IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Intersect\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromIntersectRight(left, right) {\n return right.allOf.every((schema) => Visit(left, schema) === ExtendsResult.True)\n ? ExtendsResult.True\n : ExtendsResult.False;\n}\n// prettier-ignore\nfunction FromIntersect(left, right) {\n return left.allOf.some((schema) => Visit(schema, right) === ExtendsResult.True)\n ? ExtendsResult.True\n : ExtendsResult.False;\n}\n// ------------------------------------------------------------------\n// Iterator\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromIterator(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n !TypeGuard.IsIterator(right) ? ExtendsResult.False :\n IntoBooleanResult(Visit(left.items, right.items)));\n}\n// ------------------------------------------------------------------\n// Literal\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromLiteral(left, right) {\n return (TypeGuard.IsLiteral(right) && right.const === left.const ? ExtendsResult.True :\n IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsString(right) ? FromStringRight(left, right) :\n TypeGuard.IsNumber(right) ? FromNumberRight(left, right) :\n TypeGuard.IsInteger(right) ? FromIntegerRight(left, right) :\n TypeGuard.IsBoolean(right) ? FromBooleanRight(left, right) :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Never\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromNeverRight(left, right) {\n return ExtendsResult.False;\n}\n// prettier-ignore\nfunction FromNever(left, right) {\n return ExtendsResult.True;\n}\n// ------------------------------------------------------------------\n// Not\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction UnwrapTNot(schema) {\n let [current, depth] = [schema, 0];\n while (true) {\n if (!TypeGuard.IsNot(current))\n break;\n current = current.not;\n depth += 1;\n }\n return depth % 2 === 0 ? current : Unknown();\n}\n// prettier-ignore\nfunction FromNot(left, right) {\n // TypeScript has no concept of negated types, and attempts to correctly check the negated\n // type at runtime would put TypeBox at odds with TypeScripts ability to statically infer\n // the type. Instead we unwrap to either unknown or T and continue evaluating.\n // prettier-ignore\n return (TypeGuard.IsNot(left) ? Visit(UnwrapTNot(left), right) :\n TypeGuard.IsNot(right) ? Visit(left, UnwrapTNot(right)) :\n Throw('Invalid fallthrough for Not'));\n}\n// ------------------------------------------------------------------\n// Null\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromNull(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsNull(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Number\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromNumberRight(left, right) {\n return (TypeGuard.IsLiteralNumber(left) ? ExtendsResult.True :\n TypeGuard.IsNumber(left) || TypeGuard.IsInteger(left) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromNumber(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsInteger(right) || TypeGuard.IsNumber(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Object\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction IsObjectPropertyCount(schema, count) {\n return Object.getOwnPropertyNames(schema.properties).length === count;\n}\n// prettier-ignore\nfunction IsObjectStringLike(schema) {\n return IsObjectArrayLike(schema);\n}\n// prettier-ignore\nfunction IsObjectSymbolLike(schema) {\n return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'description' in schema.properties && TypeGuard.IsUnion(schema.properties.description) && schema.properties.description.anyOf.length === 2 && ((TypeGuard.IsString(schema.properties.description.anyOf[0]) &&\n TypeGuard.IsUndefined(schema.properties.description.anyOf[1])) || (TypeGuard.IsString(schema.properties.description.anyOf[1]) &&\n TypeGuard.IsUndefined(schema.properties.description.anyOf[0]))));\n}\n// prettier-ignore\nfunction IsObjectNumberLike(schema) {\n return IsObjectPropertyCount(schema, 0);\n}\n// prettier-ignore\nfunction IsObjectBooleanLike(schema) {\n return IsObjectPropertyCount(schema, 0);\n}\n// prettier-ignore\nfunction IsObjectBigIntLike(schema) {\n return IsObjectPropertyCount(schema, 0);\n}\n// prettier-ignore\nfunction IsObjectDateLike(schema) {\n return IsObjectPropertyCount(schema, 0);\n}\n// prettier-ignore\nfunction IsObjectUint8ArrayLike(schema) {\n return IsObjectArrayLike(schema);\n}\n// prettier-ignore\nfunction IsObjectFunctionLike(schema) {\n const length = Number();\n return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'length' in schema.properties && IntoBooleanResult(Visit(schema.properties['length'], length)) === ExtendsResult.True);\n}\n// prettier-ignore\nfunction IsObjectConstructorLike(schema) {\n return IsObjectPropertyCount(schema, 0);\n}\n// prettier-ignore\nfunction IsObjectArrayLike(schema) {\n const length = Number();\n return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'length' in schema.properties && IntoBooleanResult(Visit(schema.properties['length'], length)) === ExtendsResult.True);\n}\n// prettier-ignore\nfunction IsObjectPromiseLike(schema) {\n const then = FunctionType([Any()], Any());\n return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'then' in schema.properties && IntoBooleanResult(Visit(schema.properties['then'], then)) === ExtendsResult.True);\n}\n// ------------------------------------------------------------------\n// Property\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction Property(left, right) {\n return (Visit(left, right) === ExtendsResult.False ? ExtendsResult.False :\n TypeGuard.IsOptional(left) && !TypeGuard.IsOptional(right) ? ExtendsResult.False :\n ExtendsResult.True);\n}\n// prettier-ignore\nfunction FromObjectRight(left, right) {\n return (TypeGuard.IsUnknown(left) ? ExtendsResult.False :\n TypeGuard.IsAny(left) ? ExtendsResult.Union : (TypeGuard.IsNever(left) ||\n (TypeGuard.IsLiteralString(left) && IsObjectStringLike(right)) ||\n (TypeGuard.IsLiteralNumber(left) && IsObjectNumberLike(right)) ||\n (TypeGuard.IsLiteralBoolean(left) && IsObjectBooleanLike(right)) ||\n (TypeGuard.IsSymbol(left) && IsObjectSymbolLike(right)) ||\n (TypeGuard.IsBigInt(left) && IsObjectBigIntLike(right)) ||\n (TypeGuard.IsString(left) && IsObjectStringLike(right)) ||\n (TypeGuard.IsSymbol(left) && IsObjectSymbolLike(right)) ||\n (TypeGuard.IsNumber(left) && IsObjectNumberLike(right)) ||\n (TypeGuard.IsInteger(left) && IsObjectNumberLike(right)) ||\n (TypeGuard.IsBoolean(left) && IsObjectBooleanLike(right)) ||\n (TypeGuard.IsUint8Array(left) && IsObjectUint8ArrayLike(right)) ||\n (TypeGuard.IsDate(left) && IsObjectDateLike(right)) ||\n (TypeGuard.IsConstructor(left) && IsObjectConstructorLike(right)) ||\n (TypeGuard.IsFunction(left) && IsObjectFunctionLike(right))) ? ExtendsResult.True :\n (TypeGuard.IsRecord(left) && TypeGuard.IsString(RecordKey(left))) ? (() => {\n // When expressing a Record with literal key values, the Record is converted into a Object with\n // the Hint assigned as `Record`. This is used to invert the extends logic.\n return right[Hint] === 'Record' ? ExtendsResult.True : ExtendsResult.False;\n })() :\n (TypeGuard.IsRecord(left) && TypeGuard.IsNumber(RecordKey(left))) ? (() => {\n return IsObjectPropertyCount(right, 0) ? ExtendsResult.True : ExtendsResult.False;\n })() :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromObject(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n !TypeGuard.IsObject(right) ? ExtendsResult.False :\n (() => {\n for (const key of Object.getOwnPropertyNames(right.properties)) {\n if (!(key in left.properties) && !TypeGuard.IsOptional(right.properties[key])) {\n return ExtendsResult.False;\n }\n if (TypeGuard.IsOptional(right.properties[key])) {\n return ExtendsResult.True;\n }\n if (Property(left.properties[key], right.properties[key]) === ExtendsResult.False) {\n return ExtendsResult.False;\n }\n }\n return ExtendsResult.True;\n })());\n}\n// ------------------------------------------------------------------\n// Promise\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromPromise(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) && IsObjectPromiseLike(right) ? ExtendsResult.True :\n !TypeGuard.IsPromise(right) ? ExtendsResult.False :\n IntoBooleanResult(Visit(left.item, right.item)));\n}\n// ------------------------------------------------------------------\n// Record\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction RecordKey(schema) {\n return (PatternNumberExact in schema.patternProperties ? Number() :\n PatternStringExact in schema.patternProperties ? String() :\n Throw('Unknown record key pattern'));\n}\n// prettier-ignore\nfunction RecordValue(schema) {\n return (PatternNumberExact in schema.patternProperties ? schema.patternProperties[PatternNumberExact] :\n PatternStringExact in schema.patternProperties ? schema.patternProperties[PatternStringExact] :\n Throw('Unable to get record value schema'));\n}\n// prettier-ignore\nfunction FromRecordRight(left, right) {\n const [Key, Value] = [RecordKey(right), RecordValue(right)];\n return ((TypeGuard.IsLiteralString(left) && TypeGuard.IsNumber(Key) && IntoBooleanResult(Visit(left, Value)) === ExtendsResult.True) ? ExtendsResult.True :\n TypeGuard.IsUint8Array(left) && TypeGuard.IsNumber(Key) ? Visit(left, Value) :\n TypeGuard.IsString(left) && TypeGuard.IsNumber(Key) ? Visit(left, Value) :\n TypeGuard.IsArray(left) && TypeGuard.IsNumber(Key) ? Visit(left, Value) :\n TypeGuard.IsObject(left) ? (() => {\n for (const key of Object.getOwnPropertyNames(left.properties)) {\n if (Property(Value, left.properties[key]) === ExtendsResult.False) {\n return ExtendsResult.False;\n }\n }\n return ExtendsResult.True;\n })() :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromRecord(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n !TypeGuard.IsRecord(right) ? ExtendsResult.False :\n Visit(RecordValue(left), RecordValue(right)));\n}\n// ------------------------------------------------------------------\n// RegExp\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromRegExp(left, right) {\n // Note: RegExp types evaluate as strings, not RegExp objects.\n // Here we remap either into string and continue evaluating.\n const L = TypeGuard.IsRegExp(left) ? String() : left;\n const R = TypeGuard.IsRegExp(right) ? String() : right;\n return Visit(L, R);\n}\n// ------------------------------------------------------------------\n// String\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromStringRight(left, right) {\n return (TypeGuard.IsLiteral(left) && ValueGuard.IsString(left.const) ? ExtendsResult.True :\n TypeGuard.IsString(left) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromString(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsString(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Symbol\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromSymbol(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsSymbol(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// TemplateLiteral\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromTemplateLiteral(left, right) {\n // TemplateLiteral types are resolved to either unions for finite expressions or string\n // for infinite expressions. Here we call to TemplateLiteralResolver to resolve for\n // either type and continue evaluating.\n return (TypeGuard.IsTemplateLiteral(left) ? Visit(TemplateLiteralToUnion(left), right) :\n TypeGuard.IsTemplateLiteral(right) ? Visit(left, TemplateLiteralToUnion(right)) :\n Throw('Invalid fallthrough for TemplateLiteral'));\n}\n// ------------------------------------------------------------------\n// Tuple\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction IsArrayOfTuple(left, right) {\n return (TypeGuard.IsArray(right) &&\n left.items !== undefined &&\n left.items.every((schema) => Visit(schema, right.items) === ExtendsResult.True));\n}\n// prettier-ignore\nfunction FromTupleRight(left, right) {\n return (TypeGuard.IsNever(left) ? ExtendsResult.True :\n TypeGuard.IsUnknown(left) ? ExtendsResult.False :\n TypeGuard.IsAny(left) ? ExtendsResult.Union :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromTuple(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True :\n TypeGuard.IsArray(right) && IsArrayOfTuple(left, right) ? ExtendsResult.True :\n !TypeGuard.IsTuple(right) ? ExtendsResult.False :\n (ValueGuard.IsUndefined(left.items) && !ValueGuard.IsUndefined(right.items)) || (!ValueGuard.IsUndefined(left.items) && ValueGuard.IsUndefined(right.items)) ? ExtendsResult.False :\n (ValueGuard.IsUndefined(left.items) && !ValueGuard.IsUndefined(right.items)) ? ExtendsResult.True :\n left.items.every((schema, index) => Visit(schema, right.items[index]) === ExtendsResult.True) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Uint8Array\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromUint8Array(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsUint8Array(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Undefined\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromUndefined(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsVoid(right) ? FromVoidRight(left, right) :\n TypeGuard.IsUndefined(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Union\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromUnionRight(left, right) {\n return right.anyOf.some((schema) => Visit(left, schema) === ExtendsResult.True)\n ? ExtendsResult.True\n : ExtendsResult.False;\n}\n// prettier-ignore\nfunction FromUnion(left, right) {\n return left.anyOf.every((schema) => Visit(schema, right) === ExtendsResult.True)\n ? ExtendsResult.True\n : ExtendsResult.False;\n}\n// ------------------------------------------------------------------\n// Unknown\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromUnknownRight(left, right) {\n return ExtendsResult.True;\n}\n// prettier-ignore\nfunction FromUnknown(left, right) {\n return (TypeGuard.IsNever(right) ? FromNeverRight(left, right) :\n TypeGuard.IsIntersect(right) ? FromIntersectRight(left, right) :\n TypeGuard.IsUnion(right) ? FromUnionRight(left, right) :\n TypeGuard.IsAny(right) ? FromAnyRight(left, right) :\n TypeGuard.IsString(right) ? FromStringRight(left, right) :\n TypeGuard.IsNumber(right) ? FromNumberRight(left, right) :\n TypeGuard.IsInteger(right) ? FromIntegerRight(left, right) :\n TypeGuard.IsBoolean(right) ? FromBooleanRight(left, right) :\n TypeGuard.IsArray(right) ? FromArrayRight(left, right) :\n TypeGuard.IsTuple(right) ? FromTupleRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsUnknown(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Void\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromVoidRight(left, right) {\n return (TypeGuard.IsUndefined(left) ? ExtendsResult.True :\n TypeGuard.IsUndefined(left) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromVoid(left, right) {\n return (TypeGuard.IsIntersect(right) ? FromIntersectRight(left, right) :\n TypeGuard.IsUnion(right) ? FromUnionRight(left, right) :\n TypeGuard.IsUnknown(right) ? FromUnknownRight(left, right) :\n TypeGuard.IsAny(right) ? FromAnyRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsVoid(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction Visit(left, right) {\n return (\n // resolvable\n (TypeGuard.IsTemplateLiteral(left) || TypeGuard.IsTemplateLiteral(right)) ? FromTemplateLiteral(left, right) :\n (TypeGuard.IsRegExp(left) || TypeGuard.IsRegExp(right)) ? FromRegExp(left, right) :\n (TypeGuard.IsNot(left) || TypeGuard.IsNot(right)) ? FromNot(left, right) :\n // standard\n TypeGuard.IsAny(left) ? FromAny(left, right) :\n TypeGuard.IsArray(left) ? FromArray(left, right) :\n TypeGuard.IsBigInt(left) ? FromBigInt(left, right) :\n TypeGuard.IsBoolean(left) ? FromBoolean(left, right) :\n TypeGuard.IsAsyncIterator(left) ? FromAsyncIterator(left, right) :\n TypeGuard.IsConstructor(left) ? FromConstructor(left, right) :\n TypeGuard.IsDate(left) ? FromDate(left, right) :\n TypeGuard.IsFunction(left) ? FromFunction(left, right) :\n TypeGuard.IsInteger(left) ? FromInteger(left, right) :\n TypeGuard.IsIntersect(left) ? FromIntersect(left, right) :\n TypeGuard.IsIterator(left) ? FromIterator(left, right) :\n TypeGuard.IsLiteral(left) ? FromLiteral(left, right) :\n TypeGuard.IsNever(left) ? FromNever(left, right) :\n TypeGuard.IsNull(left) ? FromNull(left, right) :\n TypeGuard.IsNumber(left) ? FromNumber(left, right) :\n TypeGuard.IsObject(left) ? FromObject(left, right) :\n TypeGuard.IsRecord(left) ? FromRecord(left, right) :\n TypeGuard.IsString(left) ? FromString(left, right) :\n TypeGuard.IsSymbol(left) ? FromSymbol(left, right) :\n TypeGuard.IsTuple(left) ? FromTuple(left, right) :\n TypeGuard.IsPromise(left) ? FromPromise(left, right) :\n TypeGuard.IsUint8Array(left) ? FromUint8Array(left, right) :\n TypeGuard.IsUndefined(left) ? FromUndefined(left, right) :\n TypeGuard.IsUnion(left) ? FromUnion(left, right) :\n TypeGuard.IsUnknown(left) ? FromUnknown(left, right) :\n TypeGuard.IsVoid(left) ? FromVoid(left, right) :\n Throw(`Unknown left type operand '${left[Kind]}'`));\n}\nexport function ExtendsCheck(left, right) {\n return Visit(left, right);\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Extends } from './extends.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromProperties(P, Right, True, False, options) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(P))\n Acc[K2] = Extends(P[K2], Right, True, False, Clone(options));\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(Left, Right, True, False, options) {\n return FromProperties(Left.properties, Right, True, False, options);\n}\n// prettier-ignore\nexport function ExtendsFromMappedResult(Left, Right, True, False, options) {\n const P = FromMappedResult(Left, Right, True, False, options);\n return MappedResult(P);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Union } from '../union/index.mjs';\nimport { ExtendsCheck, ExtendsResult } from './extends-check.mjs';\nimport { ExtendsFromMappedKey } from './extends-from-mapped-key.mjs';\nimport { ExtendsFromMappedResult } from './extends-from-mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedKey, IsMappedResult } from '../guard/kind.mjs';\n// prettier-ignore\nfunction ExtendsResolve(left, right, trueType, falseType) {\n const R = ExtendsCheck(left, right);\n return (R === ExtendsResult.Union ? Union([trueType, falseType]) :\n R === ExtendsResult.True ? trueType :\n falseType);\n}\n/** `[Json]` Creates a Conditional type */\nexport function Extends(L, R, T, F, options) {\n // prettier-ignore\n return (IsMappedResult(L) ? ExtendsFromMappedResult(L, R, T, F, options) :\n IsMappedKey(L) ? CreateType(ExtendsFromMappedKey(L, R, T, F, options)) :\n CreateType(ExtendsResolve(L, R, T, F), options));\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Extends } from './extends.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromPropertyKey(K, U, L, R, options) {\n return {\n [K]: Extends(Literal(K), U, L, R, Clone(options))\n };\n}\n// prettier-ignore\nfunction FromPropertyKeys(K, U, L, R, options) {\n return K.reduce((Acc, LK) => {\n return { ...Acc, ...FromPropertyKey(LK, U, L, R, options) };\n }, {});\n}\n// prettier-ignore\nfunction FromMappedKey(K, U, L, R, options) {\n return FromPropertyKeys(K.keys, U, L, R, options);\n}\n// prettier-ignore\nexport function ExtendsFromMappedKey(T, U, L, R, options) {\n const P = FromMappedKey(T, U, L, R, options);\n return MappedResult(P);\n}\n", "import { Exclude } from './exclude.mjs';\nimport { TemplateLiteralToUnion } from '../template-literal/index.mjs';\nexport function ExcludeFromTemplateLiteral(L, R) {\n return Exclude(TemplateLiteralToUnion(L), R);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Union } from '../union/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { ExtendsCheck, ExtendsResult } from '../extends/index.mjs';\nimport { ExcludeFromMappedResult } from './exclude-from-mapped-result.mjs';\nimport { ExcludeFromTemplateLiteral } from './exclude-from-template-literal.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedResult, IsTemplateLiteral, IsUnion } from '../guard/kind.mjs';\nfunction ExcludeRest(L, R) {\n const excluded = L.filter((inner) => ExtendsCheck(inner, R) === ExtendsResult.False);\n return excluded.length === 1 ? excluded[0] : Union(excluded);\n}\n/** `[Json]` Constructs a type by excluding from unionType all union members that are assignable to excludedMembers */\nexport function Exclude(L, R, options = {}) {\n // overloads\n if (IsTemplateLiteral(L))\n return CreateType(ExcludeFromTemplateLiteral(L, R), options);\n if (IsMappedResult(L))\n return CreateType(ExcludeFromMappedResult(L, R), options);\n // prettier-ignore\n return CreateType(IsUnion(L) ? ExcludeRest(L.anyOf, R) :\n ExtendsCheck(L, R) !== ExtendsResult.False ? Never() : L, options);\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Exclude } from './exclude.mjs';\n// prettier-ignore\nfunction FromProperties(P, U) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(P))\n Acc[K2] = Exclude(P[K2], U);\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(R, T) {\n return FromProperties(R.properties, T);\n}\n// prettier-ignore\nexport function ExcludeFromMappedResult(R, T) {\n const P = FromMappedResult(R, T);\n return MappedResult(P);\n}\n", "import { Extract } from './extract.mjs';\nimport { TemplateLiteralToUnion } from '../template-literal/index.mjs';\nexport function ExtractFromTemplateLiteral(L, R) {\n return Extract(TemplateLiteralToUnion(L), R);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Union } from '../union/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { ExtendsCheck, ExtendsResult } from '../extends/index.mjs';\nimport { ExtractFromMappedResult } from './extract-from-mapped-result.mjs';\nimport { ExtractFromTemplateLiteral } from './extract-from-template-literal.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedResult, IsTemplateLiteral, IsUnion } from '../guard/kind.mjs';\nfunction ExtractRest(L, R) {\n const extracted = L.filter((inner) => ExtendsCheck(inner, R) !== ExtendsResult.False);\n return extracted.length === 1 ? extracted[0] : Union(extracted);\n}\n/** `[Json]` Constructs a type by extracting from type all union members that are assignable to union */\nexport function Extract(L, R, options) {\n // overloads\n if (IsTemplateLiteral(L))\n return CreateType(ExtractFromTemplateLiteral(L, R), options);\n if (IsMappedResult(L))\n return CreateType(ExtractFromMappedResult(L, R), options);\n // prettier-ignore\n return CreateType(IsUnion(L) ? ExtractRest(L.anyOf, R) :\n ExtendsCheck(L, R) !== ExtendsResult.False ? L : Never(), options);\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Extract } from './extract.mjs';\n// prettier-ignore\nfunction FromProperties(P, T) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(P))\n Acc[K2] = Extract(P[K2], T);\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(R, T) {\n return FromProperties(R.properties, T);\n}\n// prettier-ignore\nexport function ExtractFromMappedResult(R, T) {\n const P = FromMappedResult(R, T);\n return MappedResult(P);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Never } from '../never/index.mjs';\nimport * as KindGuard from '../guard/kind.mjs';\n/** `[JavaScript]` Extracts the InstanceType from the given Constructor type */\nexport function InstanceType(schema, options) {\n return (KindGuard.IsConstructor(schema) ? CreateType(schema.returns, options) : Never(options));\n}\n", "import { Readonly } from '../readonly/index.mjs';\nimport { Optional } from '../optional/index.mjs';\n/** `[Json]` Creates a Readonly and Optional property */\nexport function ReadonlyOptional(schema) {\n return Readonly(Optional(schema));\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind, Hint } from '../symbols/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { Number } from '../number/index.mjs';\nimport { Object as _Object_ } from '../object/index.mjs';\nimport { String } from '../string/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { IsTemplateLiteralFinite } from '../template-literal/index.mjs';\nimport { PatternStringExact, PatternNumberExact, PatternNeverExact } from '../patterns/index.mjs';\nimport { IndexPropertyKeys } from '../indexed/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { IsUndefined } from '../guard/value.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsInteger, IsLiteral, IsAny, IsBoolean, IsNever, IsNumber, IsString, IsRegExp, IsTemplateLiteral, IsUnion } from '../guard/kind.mjs';\n// ------------------------------------------------------------------\n// RecordCreateFromPattern\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction RecordCreateFromPattern(pattern, T, options) {\n return CreateType({ [Kind]: 'Record', type: 'object', patternProperties: { [pattern]: T } }, options);\n}\n// ------------------------------------------------------------------\n// RecordCreateFromKeys\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction RecordCreateFromKeys(K, T, options) {\n const result = {};\n for (const K2 of K)\n result[K2] = T;\n return _Object_(result, { ...options, [Hint]: 'Record' });\n}\n// prettier-ignore\nfunction FromTemplateLiteralKey(K, T, options) {\n return (IsTemplateLiteralFinite(K)\n ? RecordCreateFromKeys(IndexPropertyKeys(K), T, options)\n : RecordCreateFromPattern(K.pattern, T, options));\n}\n// prettier-ignore\nfunction FromUnionKey(key, type, options) {\n return RecordCreateFromKeys(IndexPropertyKeys(Union(key)), type, options);\n}\n// prettier-ignore\nfunction FromLiteralKey(key, type, options) {\n return RecordCreateFromKeys([key.toString()], type, options);\n}\n// prettier-ignore\nfunction FromRegExpKey(key, type, options) {\n return RecordCreateFromPattern(key.source, type, options);\n}\n// prettier-ignore\nfunction FromStringKey(key, type, options) {\n const pattern = IsUndefined(key.pattern) ? PatternStringExact : key.pattern;\n return RecordCreateFromPattern(pattern, type, options);\n}\n// prettier-ignore\nfunction FromAnyKey(_, type, options) {\n return RecordCreateFromPattern(PatternStringExact, type, options);\n}\n// prettier-ignore\nfunction FromNeverKey(_key, type, options) {\n return RecordCreateFromPattern(PatternNeverExact, type, options);\n}\n// prettier-ignore\nfunction FromBooleanKey(_key, type, options) {\n return _Object_({ true: type, false: type }, options);\n}\n// prettier-ignore\nfunction FromIntegerKey(_key, type, options) {\n return RecordCreateFromPattern(PatternNumberExact, type, options);\n}\n// prettier-ignore\nfunction FromNumberKey(_, type, options) {\n return RecordCreateFromPattern(PatternNumberExact, type, options);\n}\n// ------------------------------------------------------------------\n// TRecordOrObject\n// ------------------------------------------------------------------\n/** `[Json]` Creates a Record type */\nexport function Record(key, type, options = {}) {\n // prettier-ignore\n return (IsUnion(key) ? FromUnionKey(key.anyOf, type, options) :\n IsTemplateLiteral(key) ? FromTemplateLiteralKey(key, type, options) :\n IsLiteral(key) ? FromLiteralKey(key.const, type, options) :\n IsBoolean(key) ? FromBooleanKey(key, type, options) :\n IsInteger(key) ? FromIntegerKey(key, type, options) :\n IsNumber(key) ? FromNumberKey(key, type, options) :\n IsRegExp(key) ? FromRegExpKey(key, type, options) :\n IsString(key) ? FromStringKey(key, type, options) :\n IsAny(key) ? FromAnyKey(key, type, options) :\n IsNever(key) ? FromNeverKey(key, type, options) :\n Never(options));\n}\n// ------------------------------------------------------------------\n// Record Utilities\n// ------------------------------------------------------------------\n/** Gets the Records Pattern */\nexport function RecordPattern(record) {\n return globalThis.Object.getOwnPropertyNames(record.patternProperties)[0];\n}\n/** Gets the Records Key Type */\n// prettier-ignore\nexport function RecordKey(type) {\n const pattern = RecordPattern(type);\n return (pattern === PatternStringExact ? String() :\n pattern === PatternNumberExact ? Number() :\n String({ pattern }));\n}\n/** Gets a Record Value Type */\n// prettier-ignore\nexport function RecordValue(type) {\n return type.patternProperties[RecordPattern(type)];\n}\n", "import { CloneType } from '../clone/type.mjs';\nimport { Unknown } from '../unknown/index.mjs';\nimport { ReadonlyOptional } from '../readonly-optional/index.mjs';\nimport { Readonly } from '../readonly/index.mjs';\nimport { Optional } from '../optional/index.mjs';\nimport { Object as _Object_ } from '../object/index.mjs';\nimport { Record, RecordKey, RecordValue } from '../record/index.mjs';\nimport * as ValueGuard from '../guard/value.mjs';\nimport * as KindGuard from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromConstructor(args, type) {\n type.parameters = FromTypes(args, type.parameters);\n type.returns = FromType(args, type.returns);\n return type;\n}\n// prettier-ignore\nfunction FromFunction(args, type) {\n type.parameters = FromTypes(args, type.parameters);\n type.returns = FromType(args, type.returns);\n return type;\n}\n// prettier-ignore\nfunction FromIntersect(args, type) {\n type.allOf = FromTypes(args, type.allOf);\n return type;\n}\n// prettier-ignore\nfunction FromUnion(args, type) {\n type.anyOf = FromTypes(args, type.anyOf);\n return type;\n}\n// prettier-ignore\nfunction FromTuple(args, type) {\n if (ValueGuard.IsUndefined(type.items))\n return type;\n type.items = FromTypes(args, type.items);\n return type;\n}\n// prettier-ignore\nfunction FromArray(args, type) {\n type.items = FromType(args, type.items);\n return type;\n}\n// prettier-ignore\nfunction FromAsyncIterator(args, type) {\n type.items = FromType(args, type.items);\n return type;\n}\n// prettier-ignore\nfunction FromIterator(args, type) {\n type.items = FromType(args, type.items);\n return type;\n}\n// prettier-ignore\nfunction FromPromise(args, type) {\n type.item = FromType(args, type.item);\n return type;\n}\n// prettier-ignore\nfunction FromObject(args, type) {\n const mappedProperties = FromProperties(args, type.properties);\n return { ...type, ..._Object_(mappedProperties) }; // retain options\n}\n// prettier-ignore\nfunction FromRecord(args, type) {\n const mappedKey = FromType(args, RecordKey(type));\n const mappedValue = FromType(args, RecordValue(type));\n const result = Record(mappedKey, mappedValue);\n return { ...type, ...result }; // retain options\n}\n// prettier-ignore\nfunction FromArgument(args, argument) {\n return argument.index in args ? args[argument.index] : Unknown();\n}\n// prettier-ignore\nfunction FromProperty(args, type) {\n const isReadonly = KindGuard.IsReadonly(type);\n const isOptional = KindGuard.IsOptional(type);\n const mapped = FromType(args, type);\n return (isReadonly && isOptional ? ReadonlyOptional(mapped) :\n isReadonly && !isOptional ? Readonly(mapped) :\n !isReadonly && isOptional ? Optional(mapped) :\n mapped);\n}\n// prettier-ignore\nfunction FromProperties(args, properties) {\n return globalThis.Object.getOwnPropertyNames(properties).reduce((result, key) => {\n return { ...result, [key]: FromProperty(args, properties[key]) };\n }, {});\n}\n// prettier-ignore\nexport function FromTypes(args, types) {\n return types.map(type => FromType(args, type));\n}\n// prettier-ignore\nfunction FromType(args, type) {\n return (KindGuard.IsConstructor(type) ? FromConstructor(args, type) :\n KindGuard.IsFunction(type) ? FromFunction(args, type) :\n KindGuard.IsIntersect(type) ? FromIntersect(args, type) :\n KindGuard.IsUnion(type) ? FromUnion(args, type) :\n KindGuard.IsTuple(type) ? FromTuple(args, type) :\n KindGuard.IsArray(type) ? FromArray(args, type) :\n KindGuard.IsAsyncIterator(type) ? FromAsyncIterator(args, type) :\n KindGuard.IsIterator(type) ? FromIterator(args, type) :\n KindGuard.IsPromise(type) ? FromPromise(args, type) :\n KindGuard.IsObject(type) ? FromObject(args, type) :\n KindGuard.IsRecord(type) ? FromRecord(args, type) :\n KindGuard.IsArgument(type) ? FromArgument(args, type) :\n type);\n}\n/** `[JavaScript]` Instantiates a type with the given parameters */\n// prettier-ignore\nexport function Instantiate(type, args) {\n return FromType(args, CloneType(type));\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates an Integer type */\nexport function Integer(options) {\n return CreateType({ [Kind]: 'Integer', type: 'integer' }, options);\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Intrinsic } from './intrinsic.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction MappedIntrinsicPropertyKey(K, M, options) {\n return {\n [K]: Intrinsic(Literal(K), M, Clone(options))\n };\n}\n// prettier-ignore\nfunction MappedIntrinsicPropertyKeys(K, M, options) {\n const result = K.reduce((Acc, L) => {\n return { ...Acc, ...MappedIntrinsicPropertyKey(L, M, options) };\n }, {});\n return result;\n}\n// prettier-ignore\nfunction MappedIntrinsicProperties(T, M, options) {\n return MappedIntrinsicPropertyKeys(T['keys'], M, options);\n}\n// prettier-ignore\nexport function IntrinsicFromMappedKey(T, M, options) {\n const P = MappedIntrinsicProperties(T, M, options);\n return MappedResult(P);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { TemplateLiteral, TemplateLiteralParseExact, IsTemplateLiteralExpressionFinite, TemplateLiteralExpressionGenerate } from '../template-literal/index.mjs';\nimport { IntrinsicFromMappedKey } from './intrinsic-from-mapped-key.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Union } from '../union/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedKey, IsTemplateLiteral, IsUnion, IsLiteral } from '../guard/kind.mjs';\n// ------------------------------------------------------------------\n// Apply\n// ------------------------------------------------------------------\nfunction ApplyUncapitalize(value) {\n const [first, rest] = [value.slice(0, 1), value.slice(1)];\n return [first.toLowerCase(), rest].join('');\n}\nfunction ApplyCapitalize(value) {\n const [first, rest] = [value.slice(0, 1), value.slice(1)];\n return [first.toUpperCase(), rest].join('');\n}\nfunction ApplyUppercase(value) {\n return value.toUpperCase();\n}\nfunction ApplyLowercase(value) {\n return value.toLowerCase();\n}\nfunction FromTemplateLiteral(schema, mode, options) {\n // note: template literals require special runtime handling as they are encoded in string patterns.\n // This diverges from the mapped type which would otherwise map on the template literal kind.\n const expression = TemplateLiteralParseExact(schema.pattern);\n const finite = IsTemplateLiteralExpressionFinite(expression);\n if (!finite)\n return { ...schema, pattern: FromLiteralValue(schema.pattern, mode) };\n const strings = [...TemplateLiteralExpressionGenerate(expression)];\n const literals = strings.map((value) => Literal(value));\n const mapped = FromRest(literals, mode);\n const union = Union(mapped);\n return TemplateLiteral([union], options);\n}\n// prettier-ignore\nfunction FromLiteralValue(value, mode) {\n return (typeof value === 'string' ? (mode === 'Uncapitalize' ? ApplyUncapitalize(value) :\n mode === 'Capitalize' ? ApplyCapitalize(value) :\n mode === 'Uppercase' ? ApplyUppercase(value) :\n mode === 'Lowercase' ? ApplyLowercase(value) :\n value) : value.toString());\n}\n// prettier-ignore\nfunction FromRest(T, M) {\n return T.map(L => Intrinsic(L, M));\n}\n/** Applies an intrinsic string manipulation to the given type. */\nexport function Intrinsic(schema, mode, options = {}) {\n // prettier-ignore\n return (\n // Intrinsic-Mapped-Inference\n IsMappedKey(schema) ? IntrinsicFromMappedKey(schema, mode, options) :\n // Standard-Inference\n IsTemplateLiteral(schema) ? FromTemplateLiteral(schema, mode, options) :\n IsUnion(schema) ? Union(FromRest(schema.anyOf, mode), options) :\n IsLiteral(schema) ? Literal(FromLiteralValue(schema.const, mode), options) :\n // Default Type\n CreateType(schema, options));\n}\n", "import { Intrinsic } from './intrinsic.mjs';\n/** `[Json]` Intrinsic function to Capitalize LiteralString types */\nexport function Capitalize(T, options = {}) {\n return Intrinsic(T, 'Capitalize', options);\n}\n", "import { Intrinsic } from './intrinsic.mjs';\n/** `[Json]` Intrinsic function to Lowercase LiteralString types */\nexport function Lowercase(T, options = {}) {\n return Intrinsic(T, 'Lowercase', options);\n}\n", "import { Intrinsic } from './intrinsic.mjs';\n/** `[Json]` Intrinsic function to Uncapitalize LiteralString types */\nexport function Uncapitalize(T, options = {}) {\n return Intrinsic(T, 'Uncapitalize', options);\n}\n", "import { Intrinsic } from './intrinsic.mjs';\n/** `[Json]` Intrinsic function to Uppercase LiteralString types */\nexport function Uppercase(T, options = {}) {\n return Intrinsic(T, 'Uppercase', options);\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Omit } from './omit.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromProperties(properties, propertyKeys, options) {\n const result = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(properties))\n result[K2] = Omit(properties[K2], propertyKeys, Clone(options));\n return result;\n}\n// prettier-ignore\nfunction FromMappedResult(mappedResult, propertyKeys, options) {\n return FromProperties(mappedResult.properties, propertyKeys, options);\n}\n// prettier-ignore\nexport function OmitFromMappedResult(mappedResult, propertyKeys, options) {\n const properties = FromMappedResult(mappedResult, propertyKeys, options);\n return MappedResult(properties);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Discard } from '../discard/discard.mjs';\nimport { TransformKind } from '../symbols/symbols.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { IndexPropertyKeys } from '../indexed/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { Object as _Object_ } from '../object/index.mjs';\n// ------------------------------------------------------------------\n// Mapped\n// ------------------------------------------------------------------\nimport { OmitFromMappedKey } from './omit-from-mapped-key.mjs';\nimport { OmitFromMappedResult } from './omit-from-mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedKey, IsIntersect, IsUnion, IsObject, IsSchema, IsMappedResult, IsLiteralValue, IsRef } from '../guard/kind.mjs';\nimport { IsArray as IsArrayValue } from '../guard/value.mjs';\n// prettier-ignore\nfunction FromIntersect(types, propertyKeys) {\n return types.map((type) => OmitResolve(type, propertyKeys));\n}\n// prettier-ignore\nfunction FromUnion(types, propertyKeys) {\n return types.map((type) => OmitResolve(type, propertyKeys));\n}\n// ------------------------------------------------------------------\n// FromProperty\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromProperty(properties, key) {\n const { [key]: _, ...R } = properties;\n return R;\n}\n// prettier-ignore\nfunction FromProperties(properties, propertyKeys) {\n return propertyKeys.reduce((T, K2) => FromProperty(T, K2), properties);\n}\n// prettier-ignore\nfunction FromObject(type, propertyKeys, properties) {\n const options = Discard(type, [TransformKind, '$id', 'required', 'properties']);\n const mappedProperties = FromProperties(properties, propertyKeys);\n return _Object_(mappedProperties, options);\n}\n// prettier-ignore\nfunction UnionFromPropertyKeys(propertyKeys) {\n const result = propertyKeys.reduce((result, key) => IsLiteralValue(key) ? [...result, Literal(key)] : result, []);\n return Union(result);\n}\n// prettier-ignore\nfunction OmitResolve(type, propertyKeys) {\n return (IsIntersect(type) ? Intersect(FromIntersect(type.allOf, propertyKeys)) :\n IsUnion(type) ? Union(FromUnion(type.anyOf, propertyKeys)) :\n IsObject(type) ? FromObject(type, propertyKeys, type.properties) :\n _Object_({}));\n}\n/** `[Json]` Constructs a type whose keys are picked from the given type */\n// prettier-ignore\nexport function Omit(type, key, options) {\n const typeKey = IsArrayValue(key) ? UnionFromPropertyKeys(key) : key;\n const propertyKeys = IsSchema(key) ? IndexPropertyKeys(key) : key;\n const isTypeRef = IsRef(type);\n const isKeyRef = IsRef(key);\n return (IsMappedResult(type) ? OmitFromMappedResult(type, propertyKeys, options) :\n IsMappedKey(key) ? OmitFromMappedKey(type, key, options) :\n (isTypeRef && isKeyRef) ? Computed('Omit', [type, typeKey], options) :\n (!isTypeRef && isKeyRef) ? Computed('Omit', [type, typeKey], options) :\n (isTypeRef && !isKeyRef) ? Computed('Omit', [type, typeKey], options) :\n CreateType({ ...OmitResolve(type, propertyKeys), ...options }));\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Omit } from './omit.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromPropertyKey(type, key, options) {\n return { [key]: Omit(type, [key], Clone(options)) };\n}\n// prettier-ignore\nfunction FromPropertyKeys(type, propertyKeys, options) {\n return propertyKeys.reduce((Acc, LK) => {\n return { ...Acc, ...FromPropertyKey(type, LK, options) };\n }, {});\n}\n// prettier-ignore\nfunction FromMappedKey(type, mappedKey, options) {\n return FromPropertyKeys(type, mappedKey.keys, options);\n}\n// prettier-ignore\nexport function OmitFromMappedKey(type, mappedKey, options) {\n const properties = FromMappedKey(type, mappedKey, options);\n return MappedResult(properties);\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Pick } from './pick.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromProperties(properties, propertyKeys, options) {\n const result = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(properties))\n result[K2] = Pick(properties[K2], propertyKeys, Clone(options));\n return result;\n}\n// prettier-ignore\nfunction FromMappedResult(mappedResult, propertyKeys, options) {\n return FromProperties(mappedResult.properties, propertyKeys, options);\n}\n// prettier-ignore\nexport function PickFromMappedResult(mappedResult, propertyKeys, options) {\n const properties = FromMappedResult(mappedResult, propertyKeys, options);\n return MappedResult(properties);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Discard } from '../discard/discard.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Object as _Object_ } from '../object/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { IndexPropertyKeys } from '../indexed/index.mjs';\nimport { TransformKind } from '../symbols/symbols.mjs';\n// ------------------------------------------------------------------\n// Guards\n// ------------------------------------------------------------------\nimport { IsMappedKey, IsMappedResult, IsIntersect, IsUnion, IsObject, IsSchema, IsLiteralValue, IsRef } from '../guard/kind.mjs';\nimport { IsArray as IsArrayValue } from '../guard/value.mjs';\n// ------------------------------------------------------------------\n// Infrastructure\n// ------------------------------------------------------------------\nimport { PickFromMappedKey } from './pick-from-mapped-key.mjs';\nimport { PickFromMappedResult } from './pick-from-mapped-result.mjs';\nfunction FromIntersect(types, propertyKeys) {\n return types.map((type) => PickResolve(type, propertyKeys));\n}\n// prettier-ignore\nfunction FromUnion(types, propertyKeys) {\n return types.map((type) => PickResolve(type, propertyKeys));\n}\n// prettier-ignore\nfunction FromProperties(properties, propertyKeys) {\n const result = {};\n for (const K2 of propertyKeys)\n if (K2 in properties)\n result[K2] = properties[K2];\n return result;\n}\n// prettier-ignore\nfunction FromObject(Type, keys, properties) {\n const options = Discard(Type, [TransformKind, '$id', 'required', 'properties']);\n const mappedProperties = FromProperties(properties, keys);\n return _Object_(mappedProperties, options);\n}\n// prettier-ignore\nfunction UnionFromPropertyKeys(propertyKeys) {\n const result = propertyKeys.reduce((result, key) => IsLiteralValue(key) ? [...result, Literal(key)] : result, []);\n return Union(result);\n}\n// prettier-ignore\nfunction PickResolve(type, propertyKeys) {\n return (IsIntersect(type) ? Intersect(FromIntersect(type.allOf, propertyKeys)) :\n IsUnion(type) ? Union(FromUnion(type.anyOf, propertyKeys)) :\n IsObject(type) ? FromObject(type, propertyKeys, type.properties) :\n _Object_({}));\n}\n/** `[Json]` Constructs a type whose keys are picked from the given type */\n// prettier-ignore\nexport function Pick(type, key, options) {\n const typeKey = IsArrayValue(key) ? UnionFromPropertyKeys(key) : key;\n const propertyKeys = IsSchema(key) ? IndexPropertyKeys(key) : key;\n const isTypeRef = IsRef(type);\n const isKeyRef = IsRef(key);\n return (IsMappedResult(type) ? PickFromMappedResult(type, propertyKeys, options) :\n IsMappedKey(key) ? PickFromMappedKey(type, key, options) :\n (isTypeRef && isKeyRef) ? Computed('Pick', [type, typeKey], options) :\n (!isTypeRef && isKeyRef) ? Computed('Pick', [type, typeKey], options) :\n (isTypeRef && !isKeyRef) ? Computed('Pick', [type, typeKey], options) :\n CreateType({ ...PickResolve(type, propertyKeys), ...options }));\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Pick } from './pick.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromPropertyKey(type, key, options) {\n return {\n [key]: Pick(type, [key], Clone(options))\n };\n}\n// prettier-ignore\nfunction FromPropertyKeys(type, propertyKeys, options) {\n return propertyKeys.reduce((result, leftKey) => {\n return { ...result, ...FromPropertyKey(type, leftKey, options) };\n }, {});\n}\n// prettier-ignore\nfunction FromMappedKey(type, mappedKey, options) {\n return FromPropertyKeys(type, mappedKey.keys, options);\n}\n// prettier-ignore\nexport function PickFromMappedKey(type, mappedKey, options) {\n const properties = FromMappedKey(type, mappedKey, options);\n return MappedResult(properties);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Optional } from '../optional/index.mjs';\nimport { Object as _Object_ } from '../object/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { Ref } from '../ref/index.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { TransformKind } from '../symbols/index.mjs';\nimport { PartialFromMappedResult } from './partial-from-mapped-result.mjs';\n// ------------------------------------------------------------------\n// KindGuard\n// ------------------------------------------------------------------\nimport * as KindGuard from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromComputed(target, parameters) {\n return Computed('Partial', [Computed(target, parameters)]);\n}\n// prettier-ignore\nfunction FromRef($ref) {\n return Computed('Partial', [Ref($ref)]);\n}\n// prettier-ignore\nfunction FromProperties(properties) {\n const partialProperties = {};\n for (const K of globalThis.Object.getOwnPropertyNames(properties))\n partialProperties[K] = Optional(properties[K]);\n return partialProperties;\n}\n// prettier-ignore\nfunction FromObject(type, properties) {\n const options = Discard(type, [TransformKind, '$id', 'required', 'properties']);\n const mappedProperties = FromProperties(properties);\n return _Object_(mappedProperties, options);\n}\n// prettier-ignore\nfunction FromRest(types) {\n return types.map(type => PartialResolve(type));\n}\n// ------------------------------------------------------------------\n// PartialResolve\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction PartialResolve(type) {\n return (\n // Mappable\n KindGuard.IsComputed(type) ? FromComputed(type.target, type.parameters) :\n KindGuard.IsRef(type) ? FromRef(type.$ref) :\n KindGuard.IsIntersect(type) ? Intersect(FromRest(type.allOf)) :\n KindGuard.IsUnion(type) ? Union(FromRest(type.anyOf)) :\n KindGuard.IsObject(type) ? FromObject(type, type.properties) :\n // Intrinsic\n KindGuard.IsBigInt(type) ? type :\n KindGuard.IsBoolean(type) ? type :\n KindGuard.IsInteger(type) ? type :\n KindGuard.IsLiteral(type) ? type :\n KindGuard.IsNull(type) ? type :\n KindGuard.IsNumber(type) ? type :\n KindGuard.IsString(type) ? type :\n KindGuard.IsSymbol(type) ? type :\n KindGuard.IsUndefined(type) ? type :\n // Passthrough\n _Object_({}));\n}\n/** `[Json]` Constructs a type where all properties are optional */\nexport function Partial(type, options) {\n if (KindGuard.IsMappedResult(type)) {\n return PartialFromMappedResult(type, options);\n }\n else {\n // special: mapping types require overridable options\n return CreateType({ ...PartialResolve(type), ...options });\n }\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Partial } from './partial.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromProperties(K, options) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(K))\n Acc[K2] = Partial(K[K2], Clone(options));\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(R, options) {\n return FromProperties(R.properties, options);\n}\n// prettier-ignore\nexport function PartialFromMappedResult(R, options) {\n const P = FromMappedResult(R, options);\n return MappedResult(P);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Object as _Object_ } from '../object/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { Ref } from '../ref/index.mjs';\nimport { OptionalKind, TransformKind } from '../symbols/index.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { RequiredFromMappedResult } from './required-from-mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport * as KindGuard from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromComputed(target, parameters) {\n return Computed('Required', [Computed(target, parameters)]);\n}\n// prettier-ignore\nfunction FromRef($ref) {\n return Computed('Required', [Ref($ref)]);\n}\n// prettier-ignore\nfunction FromProperties(properties) {\n const requiredProperties = {};\n for (const K of globalThis.Object.getOwnPropertyNames(properties))\n requiredProperties[K] = Discard(properties[K], [OptionalKind]);\n return requiredProperties;\n}\n// prettier-ignore\nfunction FromObject(type, properties) {\n const options = Discard(type, [TransformKind, '$id', 'required', 'properties']);\n const mappedProperties = FromProperties(properties);\n return _Object_(mappedProperties, options);\n}\n// prettier-ignore\nfunction FromRest(types) {\n return types.map(type => RequiredResolve(type));\n}\n// ------------------------------------------------------------------\n// RequiredResolve\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction RequiredResolve(type) {\n return (\n // Mappable\n KindGuard.IsComputed(type) ? FromComputed(type.target, type.parameters) :\n KindGuard.IsRef(type) ? FromRef(type.$ref) :\n KindGuard.IsIntersect(type) ? Intersect(FromRest(type.allOf)) :\n KindGuard.IsUnion(type) ? Union(FromRest(type.anyOf)) :\n KindGuard.IsObject(type) ? FromObject(type, type.properties) :\n // Intrinsic\n KindGuard.IsBigInt(type) ? type :\n KindGuard.IsBoolean(type) ? type :\n KindGuard.IsInteger(type) ? type :\n KindGuard.IsLiteral(type) ? type :\n KindGuard.IsNull(type) ? type :\n KindGuard.IsNumber(type) ? type :\n KindGuard.IsString(type) ? type :\n KindGuard.IsSymbol(type) ? type :\n KindGuard.IsUndefined(type) ? type :\n // Passthrough\n _Object_({}));\n}\n/** `[Json]` Constructs a type where all properties are required */\nexport function Required(type, options) {\n if (KindGuard.IsMappedResult(type)) {\n return RequiredFromMappedResult(type, options);\n }\n else {\n // special: mapping types require overridable options\n return CreateType({ ...RequiredResolve(type), ...options });\n }\n}\n", "import { MappedResult } from '../mapped/index.mjs';\nimport { Required } from './required.mjs';\n// prettier-ignore\nfunction FromProperties(P, options) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(P))\n Acc[K2] = Required(P[K2], options);\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(R, options) {\n return FromProperties(R.properties, options);\n}\n// prettier-ignore\nexport function RequiredFromMappedResult(R, options) {\n const P = FromMappedResult(R, options);\n return MappedResult(P);\n}\n", "import { CreateType } from '../create/index.mjs';\nimport { CloneType } from '../clone/index.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { Array } from '../array/index.mjs';\nimport { Awaited } from '../awaited/index.mjs';\nimport { AsyncIterator } from '../async-iterator/index.mjs';\nimport { Constructor } from '../constructor/index.mjs';\nimport { Index } from '../indexed/index.mjs';\nimport { Function as FunctionType } from '../function/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Iterator } from '../iterator/index.mjs';\nimport { KeyOf } from '../keyof/index.mjs';\nimport { Object as _Object_ } from '../object/index.mjs';\nimport { Omit } from '../omit/index.mjs';\nimport { Pick } from '../pick/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { Partial } from '../partial/index.mjs';\nimport { RecordValue, RecordPattern } from '../record/index.mjs';\nimport { Required } from '../required/index.mjs';\nimport { Tuple } from '../tuple/index.mjs';\nimport { Union } from '../union/index.mjs';\n// ------------------------------------------------------------------\n// Symbols\n// ------------------------------------------------------------------\nimport { TransformKind, OptionalKind, ReadonlyKind } from '../symbols/index.mjs';\n// ------------------------------------------------------------------\n// KindGuard\n// ------------------------------------------------------------------\nimport * as KindGuard from '../guard/kind.mjs';\n// prettier-ignore\nfunction DereferenceParameters(moduleProperties, types) {\n return types.map((type) => {\n return KindGuard.IsRef(type)\n ? Dereference(moduleProperties, type.$ref)\n : FromType(moduleProperties, type);\n });\n}\n// prettier-ignore\nfunction Dereference(moduleProperties, ref) {\n return (ref in moduleProperties\n ? KindGuard.IsRef(moduleProperties[ref])\n ? Dereference(moduleProperties, moduleProperties[ref].$ref)\n : FromType(moduleProperties, moduleProperties[ref])\n : Never());\n}\n// prettier-ignore\nfunction FromAwaited(parameters) {\n return Awaited(parameters[0]);\n}\n// prettier-ignore\nfunction FromIndex(parameters) {\n return Index(parameters[0], parameters[1]);\n}\n// prettier-ignore\nfunction FromKeyOf(parameters) {\n return KeyOf(parameters[0]);\n}\n// prettier-ignore\nfunction FromPartial(parameters) {\n return Partial(parameters[0]);\n}\n// prettier-ignore\nfunction FromOmit(parameters) {\n return Omit(parameters[0], parameters[1]);\n}\n// prettier-ignore\nfunction FromPick(parameters) {\n return Pick(parameters[0], parameters[1]);\n}\n// prettier-ignore\nfunction FromRequired(parameters) {\n return Required(parameters[0]);\n}\n// prettier-ignore\nfunction FromComputed(moduleProperties, target, parameters) {\n const dereferenced = DereferenceParameters(moduleProperties, parameters);\n return (target === 'Awaited' ? FromAwaited(dereferenced) :\n target === 'Index' ? FromIndex(dereferenced) :\n target === 'KeyOf' ? FromKeyOf(dereferenced) :\n target === 'Partial' ? FromPartial(dereferenced) :\n target === 'Omit' ? FromOmit(dereferenced) :\n target === 'Pick' ? FromPick(dereferenced) :\n target === 'Required' ? FromRequired(dereferenced) :\n Never());\n}\nfunction FromArray(moduleProperties, type) {\n return Array(FromType(moduleProperties, type));\n}\nfunction FromAsyncIterator(moduleProperties, type) {\n return AsyncIterator(FromType(moduleProperties, type));\n}\n// prettier-ignore\nfunction FromConstructor(moduleProperties, parameters, instanceType) {\n return Constructor(FromTypes(moduleProperties, parameters), FromType(moduleProperties, instanceType));\n}\n// prettier-ignore\nfunction FromFunction(moduleProperties, parameters, returnType) {\n return FunctionType(FromTypes(moduleProperties, parameters), FromType(moduleProperties, returnType));\n}\nfunction FromIntersect(moduleProperties, types) {\n return Intersect(FromTypes(moduleProperties, types));\n}\nfunction FromIterator(moduleProperties, type) {\n return Iterator(FromType(moduleProperties, type));\n}\nfunction FromObject(moduleProperties, properties) {\n return _Object_(globalThis.Object.keys(properties).reduce((result, key) => {\n return { ...result, [key]: FromType(moduleProperties, properties[key]) };\n }, {}));\n}\n// prettier-ignore\nfunction FromRecord(moduleProperties, type) {\n const [value, pattern] = [FromType(moduleProperties, RecordValue(type)), RecordPattern(type)];\n const result = CloneType(type);\n result.patternProperties[pattern] = value;\n return result;\n}\n// prettier-ignore\nfunction FromTransform(moduleProperties, transform) {\n return (KindGuard.IsRef(transform))\n ? { ...Dereference(moduleProperties, transform.$ref), [TransformKind]: transform[TransformKind] }\n : transform;\n}\nfunction FromTuple(moduleProperties, types) {\n return Tuple(FromTypes(moduleProperties, types));\n}\nfunction FromUnion(moduleProperties, types) {\n return Union(FromTypes(moduleProperties, types));\n}\nfunction FromTypes(moduleProperties, types) {\n return types.map((type) => FromType(moduleProperties, type));\n}\n// prettier-ignore\nexport function FromType(moduleProperties, type) {\n return (\n // Modifiers\n KindGuard.IsOptional(type) ? CreateType(FromType(moduleProperties, Discard(type, [OptionalKind])), type) :\n KindGuard.IsReadonly(type) ? CreateType(FromType(moduleProperties, Discard(type, [ReadonlyKind])), type) :\n // Transform\n KindGuard.IsTransform(type) ? CreateType(FromTransform(moduleProperties, type), type) :\n // Types\n KindGuard.IsArray(type) ? CreateType(FromArray(moduleProperties, type.items), type) :\n KindGuard.IsAsyncIterator(type) ? CreateType(FromAsyncIterator(moduleProperties, type.items), type) :\n KindGuard.IsComputed(type) ? CreateType(FromComputed(moduleProperties, type.target, type.parameters)) :\n KindGuard.IsConstructor(type) ? CreateType(FromConstructor(moduleProperties, type.parameters, type.returns), type) :\n KindGuard.IsFunction(type) ? CreateType(FromFunction(moduleProperties, type.parameters, type.returns), type) :\n KindGuard.IsIntersect(type) ? CreateType(FromIntersect(moduleProperties, type.allOf), type) :\n KindGuard.IsIterator(type) ? CreateType(FromIterator(moduleProperties, type.items), type) :\n KindGuard.IsObject(type) ? CreateType(FromObject(moduleProperties, type.properties), type) :\n KindGuard.IsRecord(type) ? CreateType(FromRecord(moduleProperties, type)) :\n KindGuard.IsTuple(type) ? CreateType(FromTuple(moduleProperties, type.items || []), type) :\n KindGuard.IsUnion(type) ? CreateType(FromUnion(moduleProperties, type.anyOf), type) :\n type);\n}\n// prettier-ignore\nexport function ComputeType(moduleProperties, key) {\n return (key in moduleProperties\n ? FromType(moduleProperties, moduleProperties[key])\n : Never());\n}\n// prettier-ignore\nexport function ComputeModuleProperties(moduleProperties) {\n return globalThis.Object.getOwnPropertyNames(moduleProperties).reduce((result, key) => {\n return { ...result, [key]: ComputeType(moduleProperties, key) };\n }, {});\n}\n", "import { CreateType } from '../create/index.mjs';\nimport { Kind } from '../symbols/index.mjs';\n// ------------------------------------------------------------------\n// Module Infrastructure Types\n// ------------------------------------------------------------------\nimport { ComputeModuleProperties } from './compute.mjs';\n// ------------------------------------------------------------------\n// Module\n// ------------------------------------------------------------------\n// prettier-ignore\nexport class TModule {\n constructor($defs) {\n const computed = ComputeModuleProperties($defs);\n const identified = this.WithIdentifiers(computed);\n this.$defs = identified;\n }\n /** `[Json]` Imports a Type by Key. */\n Import(key, options) {\n const $defs = { ...this.$defs, [key]: CreateType(this.$defs[key], options) };\n return CreateType({ [Kind]: 'Import', $defs, $ref: key });\n }\n // prettier-ignore\n WithIdentifiers($defs) {\n return globalThis.Object.getOwnPropertyNames($defs).reduce((result, key) => {\n return { ...result, [key]: { ...$defs[key], $id: key } };\n }, {});\n }\n}\n/** `[Json]` Creates a Type Definition Module. */\nexport function Module(properties) {\n return new TModule(properties);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Not type */\nexport function Not(type, options) {\n return CreateType({ [Kind]: 'Not', not: type }, options);\n}\n", "import { Tuple } from '../tuple/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport * as KindGuard from '../guard/kind.mjs';\n/** `[JavaScript]` Extracts the Parameters from the given Function type */\nexport function Parameters(schema, options) {\n return (KindGuard.IsFunction(schema) ? Tuple(schema.parameters, options) : Never());\n}\n", "import { CloneType } from '../clone/type.mjs';\nimport { CreateType } from '../create/type.mjs';\nimport { IsUndefined } from '../guard/value.mjs';\nimport { Kind, Hint } from '../symbols/index.mjs';\n// Auto Tracked For Recursive Types without ID's\nlet Ordinal = 0;\n/** `[Json]` Creates a Recursive type */\nexport function Recursive(callback, options = {}) {\n if (IsUndefined(options.$id))\n options.$id = `T${Ordinal++}`;\n const thisType = CloneType(callback({ [Kind]: 'This', $ref: `${options.$id}` }));\n thisType.$id = options.$id;\n // prettier-ignore\n return CreateType({ [Hint]: 'Recursive', ...thisType }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { IsString } from '../guard/value.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a RegExp type */\nexport function RegExp(unresolved, options) {\n const expr = IsString(unresolved) ? new globalThis.RegExp(unresolved) : unresolved;\n return CreateType({ [Kind]: 'RegExp', type: 'RegExp', source: expr.source, flags: expr.flags }, options);\n}\n", "// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsIntersect, IsUnion, IsTuple } from '../guard/kind.mjs';\n// prettier-ignore\nfunction RestResolve(T) {\n return (IsIntersect(T) ? T.allOf :\n IsUnion(T) ? T.anyOf :\n IsTuple(T) ? T.items ?? [] :\n []);\n}\n/** `[Json]` Extracts interior Rest elements from Tuple, Intersect and Union types */\nexport function Rest(T) {\n return RestResolve(T);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Never } from '../never/index.mjs';\nimport * as KindGuard from '../guard/kind.mjs';\n/** `[JavaScript]` Extracts the ReturnType from the given Function type */\nexport function ReturnType(schema, options) {\n return (KindGuard.IsFunction(schema) ? CreateType(schema.returns, options) : Never(options));\n}\n", "import { TransformKind } from '../symbols/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsTransform } from '../guard/kind.mjs';\n// ------------------------------------------------------------------\n// TransformBuilders\n// ------------------------------------------------------------------\nexport class TransformDecodeBuilder {\n constructor(schema) {\n this.schema = schema;\n }\n Decode(decode) {\n return new TransformEncodeBuilder(this.schema, decode);\n }\n}\n// prettier-ignore\nexport class TransformEncodeBuilder {\n constructor(schema, decode) {\n this.schema = schema;\n this.decode = decode;\n }\n EncodeTransform(encode, schema) {\n const Encode = (value) => schema[TransformKind].Encode(encode(value));\n const Decode = (value) => this.decode(schema[TransformKind].Decode(value));\n const Codec = { Encode: Encode, Decode: Decode };\n return { ...schema, [TransformKind]: Codec };\n }\n EncodeSchema(encode, schema) {\n const Codec = { Decode: this.decode, Encode: encode };\n return { ...schema, [TransformKind]: Codec };\n }\n Encode(encode) {\n return (IsTransform(this.schema) ? this.EncodeTransform(encode, this.schema) : this.EncodeSchema(encode, this.schema));\n }\n}\n/** `[Json]` Creates a Transform type */\nexport function Transform(schema) {\n return new TransformDecodeBuilder(schema);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Unsafe type that will infers as the generic argument T */\nexport function Unsafe(options = {}) {\n return CreateType({ [Kind]: options[Kind] ?? 'Unsafe' }, options);\n}\n", "import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Void type */\nexport function Void(options) {\n return CreateType({ [Kind]: 'Void', type: 'void' }, options);\n}\n", "// ------------------------------------------------------------------\n// Type: Module\n// ------------------------------------------------------------------\nexport { Any } from '../any/index.mjs';\nexport { Argument } from '../argument/index.mjs';\nexport { Array } from '../array/index.mjs';\nexport { AsyncIterator } from '../async-iterator/index.mjs';\nexport { Awaited } from '../awaited/index.mjs';\nexport { BigInt } from '../bigint/index.mjs';\nexport { Boolean } from '../boolean/index.mjs';\nexport { Composite } from '../composite/index.mjs';\nexport { Const } from '../const/index.mjs';\nexport { Constructor } from '../constructor/index.mjs';\nexport { ConstructorParameters } from '../constructor-parameters/index.mjs';\nexport { Date } from '../date/index.mjs';\nexport { Enum } from '../enum/index.mjs';\nexport { Exclude } from '../exclude/index.mjs';\nexport { Extends } from '../extends/index.mjs';\nexport { Extract } from '../extract/index.mjs';\nexport { Function } from '../function/index.mjs';\nexport { Index } from '../indexed/index.mjs';\nexport { InstanceType } from '../instance-type/index.mjs';\nexport { Instantiate } from '../instantiate/index.mjs';\nexport { Integer } from '../integer/index.mjs';\nexport { Intersect } from '../intersect/index.mjs';\nexport { Capitalize, Uncapitalize, Lowercase, Uppercase } from '../intrinsic/index.mjs';\nexport { Iterator } from '../iterator/index.mjs';\nexport { KeyOf } from '../keyof/index.mjs';\nexport { Literal } from '../literal/index.mjs';\nexport { Mapped } from '../mapped/index.mjs';\nexport { Module } from '../module/index.mjs';\nexport { Never } from '../never/index.mjs';\nexport { Not } from '../not/index.mjs';\nexport { Null } from '../null/index.mjs';\nexport { Number } from '../number/index.mjs';\nexport { Object } from '../object/index.mjs';\nexport { Omit } from '../omit/index.mjs';\nexport { Optional } from '../optional/index.mjs';\nexport { Parameters } from '../parameters/index.mjs';\nexport { Partial } from '../partial/index.mjs';\nexport { Pick } from '../pick/index.mjs';\nexport { Promise } from '../promise/index.mjs';\nexport { Readonly } from '../readonly/index.mjs';\nexport { ReadonlyOptional } from '../readonly-optional/index.mjs';\nexport { Record } from '../record/index.mjs';\nexport { Recursive } from '../recursive/index.mjs';\nexport { Ref } from '../ref/index.mjs';\nexport { RegExp } from '../regexp/index.mjs';\nexport { Required } from '../required/index.mjs';\nexport { Rest } from '../rest/index.mjs';\nexport { ReturnType } from '../return-type/index.mjs';\nexport { String } from '../string/index.mjs';\nexport { Symbol } from '../symbol/index.mjs';\nexport { TemplateLiteral } from '../template-literal/index.mjs';\nexport { Transform } from '../transform/index.mjs';\nexport { Tuple } from '../tuple/index.mjs';\nexport { Uint8Array } from '../uint8array/index.mjs';\nexport { Undefined } from '../undefined/index.mjs';\nexport { Union } from '../union/index.mjs';\nexport { Unknown } from '../unknown/index.mjs';\nexport { Unsafe } from '../unsafe/index.mjs';\nexport { Void } from '../void/index.mjs';\n", "// ------------------------------------------------------------------\n// JsonTypeBuilder\n// ------------------------------------------------------------------\nexport { JsonTypeBuilder } from './json.mjs';\n// ------------------------------------------------------------------\n// JavaScriptTypeBuilder\n// ------------------------------------------------------------------\nimport * as TypeBuilder from './type.mjs';\nimport { JavaScriptTypeBuilder } from './javascript.mjs';\n/** JavaScript Type Builder with Static Resolution for TypeScript */\nconst Type = TypeBuilder;\nexport { JavaScriptTypeBuilder };\nexport { Type };\n", "import { Type, type Static } from \"@sinclair/typebox\";\n\nexport const MANAGED_PI_ARTIFACT_ID = \"@earendil-works/pi-coding-agent@0.80.10\";\n\nexport const PiRuntimeIdentitySchema = Type.Union([\n Type.Object(\n {\n mode: Type.Literal(\"managed\"),\n artifactId: Type.String({ minLength: 1 }),\n },\n { additionalProperties: false },\n ),\n Type.Object(\n {\n mode: Type.Literal(\"external\"),\n selectedPath: Type.String({ minLength: 1 }),\n nodePath: Type.String({ minLength: 1 }),\n realPath: Type.String({ minLength: 1 }),\n version: Type.String({ minLength: 1 }),\n fingerprint: Type.String({ minLength: 1 }),\n },\n { additionalProperties: false },\n ),\n]);\n\nexport type PiRuntimeIdentity = Static<typeof PiRuntimeIdentitySchema>;\n\nexport const MANAGED_PI_RUNTIME_IDENTITY: PiRuntimeIdentity = Object.freeze({\n mode: \"managed\",\n artifactId: MANAGED_PI_ARTIFACT_ID,\n});\n\nexport function samePiRuntimeIdentity(left: PiRuntimeIdentity, right: PiRuntimeIdentity): boolean {\n if (left.mode !== right.mode) return false;\n if (left.mode === \"managed\" && right.mode === \"managed\") {\n return left.artifactId === right.artifactId;\n }\n if (left.mode === \"external\" && right.mode === \"external\") {\n return (\n left.selectedPath === right.selectedPath &&\n left.nodePath === right.nodePath &&\n left.realPath === right.realPath &&\n left.version === right.version &&\n left.fingerprint === right.fingerprint\n );\n }\n return false;\n}\n", "import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { createReadStream } from \"node:fs\";\nimport { access, realpath, stat } from \"node:fs/promises\";\nimport { delimiter, dirname, isAbsolute, join } from \"node:path\";\n\nconst VERSION_TIMEOUT_MS = 3_000;\nconst MAX_VERSION_OUTPUT_BYTES = 4 * 1024;\n\nexport type ExternalPiResolutionErrorCode =\n | \"invalid_arguments\"\n | \"pi_not_found\"\n | \"pi_not_executable\"\n | \"pi_version_unavailable\"\n | \"pi_installation_changed\";\n\nexport class ExternalPiResolutionError extends Error {\n constructor(\n readonly code: ExternalPiResolutionErrorCode,\n message: string,\n ) {\n super(message);\n this.name = \"ExternalPiResolutionError\";\n }\n}\n\nexport interface PiInstallation {\n readonly selectedPath: string;\n readonly realPath: string;\n readonly version: string;\n readonly nodePath: string;\n readonly fingerprint: string;\n}\n\nexport interface ExternalPiResolverOptions {\n readonly env?: NodeJS.ProcessEnv;\n readonly nodePath?: string;\n readonly versionCommand?: (executable: string) => Promise<string>;\n readonly versionTimeoutMs?: number;\n readonly maxVersionOutputBytes?: number;\n}\n\nexport async function resolveExternalPiInstallation(\n options: ExternalPiResolverOptions = {},\n): Promise<PiInstallation> {\n const env = options.env ?? process.env;\n const selectedPath = await resolveSelectedPath(env);\n const nodePath = options.nodePath ?? (await resolveNodePath(env));\n await inspectNode(nodePath);\n\n const executionEnv = externalPiExecutionEnvironment(env, selectedPath, nodePath);\n for (let attempt = 0; attempt < 2; attempt += 1) {\n const observation = await observeInstallation(selectedPath, executionEnv, options);\n if (observation !== null) {\n return {\n selectedPath,\n nodePath,\n ...observation,\n };\n }\n }\n\n throw new ExternalPiResolutionError(\n \"pi_installation_changed\",\n \"Pi changed while its installation was being observed.\",\n );\n}\n\nexport function externalPiExecutionEnvironment(\n env: NodeJS.ProcessEnv,\n selectedPath: string,\n nodePath: string,\n): NodeJS.ProcessEnv {\n return {\n ...env,\n PATH: [dirname(nodePath), dirname(selectedPath), env.PATH]\n .filter((value): value is string => value !== undefined && value.length > 0)\n .join(delimiter),\n };\n}\n\nasync function observeInstallation(\n selectedPath: string,\n env: NodeJS.ProcessEnv,\n options: ExternalPiResolverOptions,\n): Promise<Omit<PiInstallation, \"selectedPath\" | \"nodePath\"> | null> {\n const beforeRealPath = await inspectExecutable(selectedPath, \"Pi\");\n const beforeHash = await hashFile(beforeRealPath);\n const versionOutput = await (\n options.versionCommand ??\n ((executable: string) =>\n readVersion(executable, env, options.versionTimeoutMs, options.maxVersionOutputBytes))\n )(selectedPath);\n const version = parseVersion(versionOutput);\n const afterRealPath = await inspectExecutable(selectedPath, \"Pi\");\n const afterHash = await hashFile(afterRealPath);\n\n if (beforeRealPath !== afterRealPath || beforeHash !== afterHash) return null;\n\n return {\n realPath: afterRealPath,\n version,\n fingerprint: createHash(\"sha256\")\n .update(JSON.stringify([selectedPath, afterRealPath, version, afterHash]))\n .digest(\"hex\"),\n };\n}\n\nasync function resolveSelectedPath(env: NodeJS.ProcessEnv): Promise<string> {\n const explicit = env.PIFLEET_PI_EXECUTABLE;\n if (explicit !== undefined) {\n if (!isAbsolute(explicit)) {\n throw new ExternalPiResolutionError(\n \"invalid_arguments\",\n \"PIFLEET_PI_EXECUTABLE must be an absolute path.\",\n );\n }\n return explicit;\n }\n return resolvePathExecutable(env, \"pi\", \"Pi\", \"pi_not_found\");\n}\n\nasync function resolveNodePath(env: NodeJS.ProcessEnv): Promise<string> {\n return resolvePathExecutable(env, \"node\", \"Node\", \"pi_not_executable\");\n}\n\nasync function resolvePathExecutable(\n env: NodeJS.ProcessEnv,\n name: string,\n label: \"Pi\" | \"Node\",\n missingCode: \"pi_not_found\" | \"pi_not_executable\",\n): Promise<string> {\n const path = env.PATH;\n if (path === undefined || path.length === 0) {\n throw new ExternalPiResolutionError(missingCode, `${label} was not found on PATH.`);\n }\n for (const directory of path.split(delimiter)) {\n if (!isAbsolute(directory)) {\n throw new ExternalPiResolutionError(\n \"invalid_arguments\",\n `PATH entries used to select ${label} must be absolute paths.`,\n );\n }\n const candidate = join(directory, name);\n try {\n await inspectExecutable(candidate, label);\n return candidate;\n } catch (error: unknown) {\n if (\n !(error instanceof ExternalPiResolutionError) ||\n (error.code !== \"pi_not_executable\" && error.code !== \"pi_not_found\")\n ) {\n throw error;\n }\n }\n }\n throw new ExternalPiResolutionError(missingCode, `${label} was not found on PATH.`);\n}\n\nasync function inspectExecutable(path: string, label: \"Pi\" | \"Node\"): Promise<string> {\n try {\n const target = await realpath(path);\n const metadata = await stat(target);\n if (!metadata.isFile()) {\n throw new ExternalPiResolutionError(\"pi_not_executable\", `${label} is not a file: ${path}`);\n }\n await access(path, constants.X_OK);\n return target;\n } catch (error: unknown) {\n if (error instanceof ExternalPiResolutionError) throw error;\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new ExternalPiResolutionError(\"pi_not_found\", `${label} was not found: ${path}`);\n }\n throw new ExternalPiResolutionError(\"pi_not_executable\", `${label} is not executable: ${path}`);\n }\n}\n\nasync function inspectNode(nodePath: string): Promise<void> {\n if (!isAbsolute(nodePath)) {\n throw new ExternalPiResolutionError(\"invalid_arguments\", \"Node must be an absolute path.\");\n }\n try {\n await inspectExecutable(nodePath, \"Node\");\n } catch {\n throw new ExternalPiResolutionError(\"pi_not_executable\", `Node is not executable: ${nodePath}`);\n }\n}\n\nasync function hashFile(path: string): Promise<string> {\n const hash = createHash(\"sha256\");\n await new Promise<void>((resolveHash, rejectHash) => {\n const stream = createReadStream(path);\n stream.on(\"data\", (chunk: string | Buffer) => hash.update(chunk));\n stream.once(\"error\", rejectHash);\n stream.once(\"end\", resolveHash);\n });\n return hash.digest(\"hex\");\n}\n\nasync function readVersion(\n executable: string,\n env: NodeJS.ProcessEnv,\n timeoutMs = VERSION_TIMEOUT_MS,\n maxOutputBytes = MAX_VERSION_OUTPUT_BYTES,\n): Promise<string> {\n const child = spawn(executable, [\"--version\"], {\n detached: process.platform !== \"win32\",\n env,\n shell: false,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n const chunks: Buffer[] = [];\n let outputBytes = 0;\n let terminalError: ExternalPiResolutionError | null = null;\n let terminated = false;\n\n const terminate = () => {\n if (terminated) return;\n terminated = true;\n if (process.platform !== \"win32\" && child.pid !== undefined) {\n try {\n process.kill(-child.pid, \"SIGKILL\");\n return;\n } catch {\n // The group may have already exited; kill the direct child as a fallback.\n }\n }\n child.kill(\"SIGKILL\");\n };\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n if (terminalError !== null) return;\n outputBytes += chunk.byteLength;\n if (outputBytes > maxOutputBytes) {\n terminalError = new ExternalPiResolutionError(\n \"pi_version_unavailable\",\n \"Pi version output exceeded its limit.\",\n );\n terminate();\n return;\n }\n chunks.push(chunk);\n });\n child.stderr.resume();\n\n return new Promise((resolveVersion, rejectVersion) => {\n const timer = setTimeout(() => {\n terminalError = new ExternalPiResolutionError(\n \"pi_version_unavailable\",\n \"Pi version command timed out.\",\n );\n terminate();\n }, timeoutMs);\n child.once(\"error\", () => {\n terminalError ??= new ExternalPiResolutionError(\n \"pi_version_unavailable\",\n \"Pi version command failed.\",\n );\n });\n child.once(\"close\", (code) => {\n clearTimeout(timer);\n if (terminalError !== null) {\n rejectVersion(terminalError);\n return;\n }\n if (code !== 0) {\n rejectVersion(\n new ExternalPiResolutionError(\"pi_version_unavailable\", \"Pi version command failed.\"),\n );\n return;\n }\n try {\n resolveVersion(new TextDecoder(\"utf-8\", { fatal: true }).decode(Buffer.concat(chunks)));\n } catch {\n rejectVersion(\n new ExternalPiResolutionError(\n \"pi_version_unavailable\",\n \"Pi version command returned invalid UTF-8.\",\n ),\n );\n }\n });\n });\n}\n\nfunction parseVersion(output: string): string {\n const match = /^(?:pi\\s+)?(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)\\s*$/i.exec(output);\n if (match?.[1] === undefined) {\n throw new ExternalPiResolutionError(\n \"pi_version_unavailable\",\n \"Pi version command returned an invalid version.\",\n );\n }\n return match[1];\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { once } from \"node:events\";\nimport { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\n\nimport { signalProcessTree, waitForProcessGroupExit } from \"../platform/runtime/process-tree.js\";\n\nconst DEFAULT_MAX_STDOUT_FRAME_BYTES = 8 * 1024 * 1024;\n\nexport class PiRpcRejectedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PiRpcRejectedError\";\n }\n}\n\nexport interface PiCompactionResult {\n readonly tokensBefore: number;\n readonly estimatedTokensAfter?: number;\n}\n\nexport class PiCompactionError extends Error {\n constructor(readonly code: \"nothing_to_compact\" | \"compaction_failed\") {\n super(code);\n this.name = \"PiCompactionError\";\n }\n}\n\nexport class PiCleanupUncertainError extends Error {\n constructor(\n readonly pid: number,\n readonly startupError: unknown,\n readonly cleanupError: unknown,\n ) {\n super(`Pi process group ${String(pid)} could not be cleaned up after startup failed`);\n this.name = \"PiCleanupUncertainError\";\n }\n}\n\nexport interface PiState {\n readonly isStreaming: boolean;\n readonly isCompacting: boolean;\n readonly pendingMessageCount: number;\n readonly sessionFile?: string;\n readonly sessionId: string;\n}\n\nexport interface PiFrame {\n readonly id?: string;\n readonly type?: string;\n readonly command?: string;\n readonly success?: boolean;\n readonly error?: string;\n readonly data?: Record<string, unknown>;\n readonly [key: string]: unknown;\n}\n\nexport interface PiProcessStartOptions {\n readonly executable: string;\n readonly argvPrefix?: readonly string[];\n readonly piArgv: readonly string[];\n readonly cwd: string;\n readonly env?: NodeJS.ProcessEnv;\n readonly maxStdoutFrameBytes?: number;\n readonly onSpawn?: (pid: number) => Promise<void>;\n readonly onStdoutBytes?: (bytes: Buffer) => void;\n}\n\ninterface ResponseWaiter {\n readonly resolve: (frame: PiFrame) => void;\n readonly reject: (error: Error) => void;\n readonly timer: NodeJS.Timeout;\n}\n\nexport class PiProcess {\n readonly #child: ChildProcessWithoutNullStreams;\n readonly #responses = new Map<string, ResponseWaiter>();\n readonly #listeners = new Set<(frame: PiFrame) => void>();\n readonly #exitListeners = new Set<(error: Error | null) => void>();\n #stdoutBuffer = Buffer.alloc(0);\n #stderr = \"\";\n #stopping = false;\n #handledExit = false;\n readonly #exitHandled: Promise<void>;\n #resolveExitHandled: () => void = () => undefined;\n readonly #maxStdoutFrameBytes: number;\n\n private constructor(options: PiProcessStartOptions) {\n this.#exitHandled = new Promise((resolve) => {\n this.#resolveExitHandled = resolve;\n });\n this.#maxStdoutFrameBytes = options.maxStdoutFrameBytes ?? DEFAULT_MAX_STDOUT_FRAME_BYTES;\n this.#child = spawn(\n options.executable,\n [...(options.argvPrefix ?? []), \"--mode\", \"rpc\", ...options.piArgv],\n {\n cwd: options.cwd,\n env: { ...process.env, ...options.env },\n detached: process.platform !== \"win32\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n },\n );\n this.#child.stderr.setEncoding(\"utf8\");\n this.#child.stdout.on(\"data\", (chunk: Buffer) => {\n options.onStdoutBytes?.(chunk);\n this.#consumeStdout(chunk);\n });\n this.#child.stderr.on(\"data\", (chunk: string) => {\n this.#stderr = `${this.#stderr}${chunk}`.slice(-65_536);\n });\n this.#child.once(\"exit\", (code, signal) => this.#handleExit(code, signal));\n this.#child.once(\"error\", (error) => this.#handleExit(null, null, error));\n }\n\n static async start(options: PiProcessStartOptions): Promise<PiProcess> {\n const process = new PiProcess(options);\n try {\n await options.onSpawn?.(process.pid);\n await process.getState();\n return process;\n } catch (error: unknown) {\n try {\n await process.stop();\n } catch (cleanupError: unknown) {\n throw new PiCleanupUncertainError(process.pid, error, cleanupError);\n }\n throw error;\n }\n }\n\n get pid(): number {\n if (this.#child.pid === undefined) throw new Error(\"Pi process has no PID\");\n return this.#child.pid;\n }\n\n get stderr(): string {\n return this.#stderr;\n }\n\n onFrame(listener: (frame: PiFrame) => void): () => void {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n\n onExit(listener: (error: Error | null) => void): () => void {\n this.#exitListeners.add(listener);\n return () => this.#exitListeners.delete(listener);\n }\n\n async getState(): Promise<PiState> {\n const frame = await this.request({ type: \"get_state\" });\n return frame.data as unknown as PiState;\n }\n\n async prompt(message: string): Promise<void> {\n await this.request({ type: \"prompt\", message, streamingBehavior: \"steer\" });\n }\n\n async compact(): Promise<PiCompactionResult> {\n let frame: PiFrame;\n try {\n frame = await this.request({ type: \"compact\" });\n } catch (error: unknown) {\n if (!(error instanceof PiRpcRejectedError)) throw error;\n const code =\n error.message === \"Already compacted\" || error.message.startsWith(\"Nothing to compact\")\n ? \"nothing_to_compact\"\n : \"compaction_failed\";\n throw new PiCompactionError(code);\n }\n const tokensBefore = frame.data?.tokensBefore;\n const estimatedTokensAfter = frame.data?.estimatedTokensAfter;\n if (\n typeof tokensBefore !== \"number\" ||\n !Number.isFinite(tokensBefore) ||\n tokensBefore < 0 ||\n (estimatedTokensAfter !== undefined &&\n (typeof estimatedTokensAfter !== \"number\" ||\n !Number.isFinite(estimatedTokensAfter) ||\n estimatedTokensAfter < 0))\n ) {\n throw new Error(\"Pi returned an invalid compaction result\");\n }\n return {\n tokensBefore,\n ...(estimatedTokensAfter === undefined ? {} : { estimatedTokensAfter }),\n };\n }\n\n async getLastAssistantText(): Promise<string | null> {\n const frame = await this.request({ type: \"get_last_assistant_text\" });\n return typeof frame.data?.text === \"string\" ? frame.data.text : null;\n }\n\n async request(command: Record<string, unknown>, timeoutMs = 15_000): Promise<PiFrame> {\n if (this.#child.exitCode !== null) throw new Error(\"Pi process is not running\");\n const id = randomUUID();\n const response = new Promise<PiFrame>((resolveResponse, rejectResponse) => {\n const timer = setTimeout(() => {\n this.#responses.delete(id);\n rejectResponse(new Error(\"Pi RPC request timed out\"));\n }, timeoutMs);\n this.#responses.set(id, { resolve: resolveResponse, reject: rejectResponse, timer });\n });\n try {\n await this.#write({ ...command, id });\n } catch (error: unknown) {\n const waiter = this.#responses.get(id);\n if (waiter !== undefined) {\n clearTimeout(waiter.timer);\n this.#responses.delete(id);\n waiter.reject(error instanceof Error ? error : new Error(\"Pi RPC write failed\"));\n }\n }\n const frame = await response;\n if (frame.success !== true) {\n throw new PiRpcRejectedError(frame.error ?? `Pi rejected ${String(command.type)}`);\n }\n return frame;\n }\n\n async stop(): Promise<void> {\n if (this.#stopping) {\n if (!(await this.#waitForExit(1_000))) {\n throw new Error(`Pi process group ${String(this.pid)} is still running`);\n }\n return;\n }\n this.#stopping = true;\n if (this.#child.exitCode === null) this.#child.stdin.end();\n if (await this.#waitForExit(500)) return;\n signalProcessTree(this.pid, \"SIGTERM\");\n if (await this.#waitForExit(1_000)) return;\n signalProcessTree(this.pid, \"SIGKILL\");\n if (!(await this.#waitForExit(1_000))) {\n throw new Error(`Pi process group ${String(this.pid)} did not exit after SIGKILL`);\n }\n }\n\n async #waitForExit(timeoutMs: number): Promise<boolean> {\n if (!(await waitForProcessGroupExit(this.pid, timeoutMs))) return false;\n await this.#exitHandled;\n return true;\n }\n\n async #write(frame: PiFrame): Promise<void> {\n if (this.#child.stdin.write(`${JSON.stringify(frame)}\\n`)) return;\n await once(this.#child.stdin, \"drain\");\n }\n\n #consumeStdout(chunk: Buffer): void {\n this.#stdoutBuffer = Buffer.concat([this.#stdoutBuffer, chunk]);\n while (true) {\n const newline = this.#stdoutBuffer.indexOf(0x0a);\n if (newline < 0) {\n if (this.#stdoutBuffer.length > this.#maxStdoutFrameBytes) {\n signalProcessTree(this.pid, \"SIGTERM\");\n }\n return;\n }\n if (newline > this.#maxStdoutFrameBytes) {\n signalProcessTree(this.pid, \"SIGTERM\");\n return;\n }\n let lineBytes = this.#stdoutBuffer.subarray(0, newline);\n this.#stdoutBuffer = this.#stdoutBuffer.subarray(newline + 1);\n if (lineBytes.at(-1) === 0x0d) lineBytes = lineBytes.subarray(0, -1);\n if (lineBytes.length === 0) continue;\n let frame: PiFrame;\n try {\n const line = new TextDecoder(\"utf-8\", { fatal: true }).decode(lineBytes);\n frame = JSON.parse(line) as PiFrame;\n } catch {\n signalProcessTree(this.pid, \"SIGTERM\");\n return;\n }\n if (\n frame.type === \"extension_ui_request\" &&\n typeof frame.id === \"string\" &&\n [\"select\", \"confirm\", \"input\", \"editor\"].includes(String(frame.method))\n ) {\n void this.#write({ type: \"extension_ui_response\", id: frame.id, cancelled: true }).catch(\n () => undefined,\n );\n }\n if (frame.type === \"response\" && frame.id !== undefined) {\n const waiter = this.#responses.get(frame.id);\n if (waiter !== undefined) {\n clearTimeout(waiter.timer);\n this.#responses.delete(frame.id);\n waiter.resolve(frame);\n }\n }\n for (const listener of this.#listeners) listener(frame);\n }\n }\n\n #handleExit(code: number | null, signal: NodeJS.Signals | null, cause?: Error): void {\n if (this.#handledExit) return;\n this.#handledExit = true;\n const error =\n this.#stopping && (code === 0 || signal === \"SIGTERM\")\n ? null\n : (cause ??\n new Error(`Pi exited unexpectedly (code=${String(code)}, signal=${String(signal)})`));\n try {\n for (const waiter of this.#responses.values()) {\n clearTimeout(waiter.timer);\n waiter.reject(error ?? new Error(\"Pi stopped before responding\"));\n }\n this.#responses.clear();\n for (const listener of this.#exitListeners) listener(error);\n } finally {\n this.#resolveExitHandled();\n }\n }\n}\n", "import { type PiRuntimeIdentity, samePiRuntimeIdentity } from \"../protocol/pi-identity.js\";\nimport {\n ExternalPiResolutionError,\n externalPiExecutionEnvironment,\n resolveExternalPiInstallation,\n type PiInstallation,\n} from \"./external-installation.js\";\nimport { PiExecutionUnavailableError, RealPiLauncher, type PiLauncher } from \"./adapter.js\";\n\nexport interface ExternalPiTarget {\n readonly launcher: PiLauncher;\n readonly identity: PiRuntimeIdentity;\n}\n\nexport async function createExternalPiTarget(\n env: NodeJS.ProcessEnv,\n maxStdoutFrameBytes?: number,\n): Promise<ExternalPiTarget> {\n const selectedPath = env.PIFLEET_PI_EXECUTABLE;\n const nodePath = env.PIFLEET_PI_NODE;\n if (selectedPath === undefined || nodePath === undefined) {\n return unavailableTarget(\n selectedPath ?? \"<unconfigured>\",\n nodePath ?? \"<unconfigured>\",\n \"pi_not_found\",\n );\n }\n\n let initial: PiInstallation;\n try {\n initial = await resolveExternalPiInstallation({\n env: { ...env, PIFLEET_PI_EXECUTABLE: selectedPath },\n nodePath,\n });\n } catch (error: unknown) {\n return unavailableTarget(selectedPath, nodePath, resolutionCode(error));\n }\n const identity = installationIdentity(initial);\n const launcher = new RealPiLauncher({\n executable: initial.selectedPath,\n artifactId: \"external-pi\",\n env: externalPiExecutionEnvironment(env, initial.selectedPath, initial.nodePath),\n ...(maxStdoutFrameBytes === undefined ? {} : { maxStdoutFrameBytes }),\n preflight: async () => {\n let current: PiInstallation;\n try {\n current = await resolveExternalPiInstallation({\n env: { ...env, PIFLEET_PI_EXECUTABLE: selectedPath },\n nodePath,\n });\n } catch (error: unknown) {\n throw new PiExecutionUnavailableError(resolutionCode(error));\n }\n if (!samePiRuntimeIdentity(identity, installationIdentity(current))) {\n throw new PiExecutionUnavailableError(\"pi_installation_changed\");\n }\n },\n });\n return { launcher, identity };\n}\n\nexport function installationIdentity(installation: PiInstallation): PiRuntimeIdentity {\n return {\n mode: \"external\",\n selectedPath: installation.selectedPath,\n nodePath: installation.nodePath,\n realPath: installation.realPath,\n version: installation.version,\n fingerprint: installation.fingerprint,\n };\n}\n\nfunction unavailableTarget(\n selectedPath: string,\n nodePath: string,\n code: PiExecutionUnavailableError[\"code\"],\n): ExternalPiTarget {\n const launcher: PiLauncher = {\n artifactId: \"external-pi\",\n async preflight() {\n throw new PiExecutionUnavailableError(code);\n },\n async start() {\n throw new PiExecutionUnavailableError(code);\n },\n };\n return {\n launcher,\n identity: {\n mode: \"external\",\n selectedPath,\n nodePath,\n realPath: selectedPath,\n version: \"unavailable\",\n fingerprint: \"unavailable\",\n },\n };\n}\n\nfunction resolutionCode(error: unknown): PiExecutionUnavailableError[\"code\"] {\n if (error instanceof ExternalPiResolutionError) {\n if (error.code === \"invalid_arguments\") return \"pi_not_executable\";\n return error.code;\n }\n return \"pi_version_unavailable\";\n}\n", "import { execFile, spawn } from \"node:child_process\";\nimport { access, readFile } from \"node:fs/promises\";\nimport { createConnection } from \"node:net\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { promisify } from \"node:util\";\n\nimport type { PiInstallation } from \"../../pi/external-installation.js\";\nimport { materializeRuntime } from \"../install/runtime-release.js\";\nimport { resolveApplicationRoot, resolveFleetPaths } from \"../shared/paths.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport async function ensureRuntime(options: {\n readonly socketPath: string;\n readonly env?: NodeJS.ProcessEnv;\n readonly timeoutMs?: number;\n readonly sourceRoot?: string;\n readonly applicationRoot?: string;\n readonly home?: string;\n readonly piInstallation?: () => Promise<PiInstallation>;\n readonly registeredRuntimeStarter?: (env: NodeJS.ProcessEnv) => Promise<boolean>;\n}): Promise<void> {\n if (await canConnect(options.socketPath)) return;\n\n let env = { ...process.env, ...options.env };\n const registered =\n env.PIFLEET_DISABLE_REGISTERED_SERVICE === \"1\"\n ? false\n : options.registeredRuntimeStarter !== undefined\n ? await options.registeredRuntimeStarter(env)\n : await startRegisteredRuntime({\n env,\n ...(options.home === undefined ? {} : { home: options.home }),\n });\n if (!registered) {\n if (options.piInstallation !== undefined) {\n const installation = await options.piInstallation();\n env = {\n ...env,\n PIFLEET_PI_EXECUTABLE: installation.selectedPath,\n PIFLEET_PI_NODE: installation.nodePath,\n };\n }\n const sourceRoot =\n options.sourceRoot ?? (await findPackageRoot(fileURLToPath(import.meta.url)));\n const release = await materializeRuntime({\n sourceRoot,\n applicationRoot: options.applicationRoot ?? resolveApplicationRoot(env),\n });\n const runtimePath = join(release, \"bin\", \"pifleet-runtime.mjs\");\n const child = spawn(process.execPath, [runtimePath], {\n detached: true,\n env,\n stdio: \"ignore\",\n });\n child.unref();\n }\n\n const deadline = Date.now() + (options.timeoutMs ?? 5_000);\n while (Date.now() < deadline) {\n if (await canConnect(options.socketPath)) return;\n await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));\n }\n throw new Error(`pi-fleet runtime did not become ready at ${options.socketPath}`);\n}\n\nasync function startRegisteredRuntime(options: {\n readonly env: NodeJS.ProcessEnv;\n readonly home?: string;\n}): Promise<boolean> {\n const home = options.home ?? homedir();\n if (process.platform === \"linux\") {\n const unit = join(home, \".config\", \"systemd\", \"user\", \"pi-fleet.service\");\n if (!(await exists(unit))) return false;\n await assertRegisteredStateRoot(unit, \"linux\", options.env);\n await execFileAsync(\"systemctl\", [\"--user\", \"start\", \"pi-fleet.service\"]);\n return true;\n }\n if (process.platform === \"darwin\") {\n const plist = join(home, \"Library\", \"LaunchAgents\", \"works.elpapi.pifleet.plist\");\n if (!(await exists(plist))) return false;\n await assertRegisteredStateRoot(plist, \"darwin\", options.env);\n const domain = `gui/${process.getuid?.() ?? 0}`;\n await execFileAsync(\"launchctl\", [\"kickstart\", `${domain}/works.elpapi.pifleet`]);\n return true;\n }\n return false;\n}\n\nexport function installedServiceStateRoot(\n contents: string,\n platform: \"linux\" | \"darwin\",\n): string | undefined {\n const encoded =\n platform === \"linux\"\n ? /^Environment=PIFLEET_STATE_ROOT=(.+)$/m.exec(contents)?.[1]\n : /<key>PIFLEET_STATE_ROOT<\\/key><string>([^<]+)<\\/string>/.exec(contents)?.[1];\n if (encoded === undefined) return undefined;\n if (platform === \"linux\") return encoded;\n return encoded\n .replaceAll(\"'\", \"'\")\n .replaceAll(\""\", '\"')\n .replaceAll(\">\", \">\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\"&\", \"&\");\n}\n\nexport class PiServiceMismatchError extends Error {\n readonly code = \"pi_service_mismatch\";\n\n constructor(message: string) {\n super(message);\n this.name = \"PiServiceMismatchError\";\n }\n}\n\nexport async function assertRegisteredPiSelection(options: {\n readonly selectedPath: string;\n readonly nodePath: string;\n readonly home?: string;\n}): Promise<void> {\n const home = options.home ?? homedir();\n const platform = process.platform;\n if (platform !== \"linux\" && platform !== \"darwin\") return;\n const path =\n platform === \"linux\"\n ? join(home, \".config\", \"systemd\", \"user\", \"pi-fleet.service\")\n : join(home, \"Library\", \"LaunchAgents\", \"works.elpapi.pifleet.plist\");\n if (!(await exists(path))) return;\n const contents = await readFile(path, \"utf8\");\n const installed = installedServicePiExecutable(contents, platform);\n const installedNode = installedServicePiNode(contents, platform);\n if (\n installed === undefined ||\n installedNode === undefined ||\n resolve(installed) !== resolve(options.selectedPath) ||\n resolve(installedNode) !== resolve(options.nodePath)\n ) {\n throw new PiServiceMismatchError(\n `The installed pi-fleet service uses a different Pi executable or Node interpreter; repair it from the environment selecting ${options.selectedPath}.`,\n );\n }\n}\n\nexport function installedServicePiExecutable(\n contents: string,\n platform: \"linux\" | \"darwin\",\n): string | undefined {\n return installedServiceEnvironmentValue(contents, platform, \"PIFLEET_PI_EXECUTABLE\");\n}\n\nexport function installedServicePiNode(\n contents: string,\n platform: \"linux\" | \"darwin\",\n): string | undefined {\n return installedServiceEnvironmentValue(contents, platform, \"PIFLEET_PI_NODE\");\n}\n\nfunction installedServiceEnvironmentValue(\n contents: string,\n platform: \"linux\" | \"darwin\",\n key: \"PIFLEET_PI_EXECUTABLE\" | \"PIFLEET_PI_NODE\",\n): string | undefined {\n const encoded =\n platform === \"linux\"\n ? new RegExp(`Environment=(?:\"${key}=([^\"\\\\\\\\]*(?:\\\\\\\\.[^\"\\\\\\\\]*)*)\"|${key}=(.+))$`, \"m\")\n .exec(contents)\n ?.slice(1)\n .find(Boolean)\n : new RegExp(`<key>${key}<\\\\/key><string>([^<]+)<\\\\/string>`).exec(contents)?.[1];\n if (encoded === undefined) return undefined;\n if (platform === \"darwin\") {\n return encoded\n .replaceAll(\"'\", \"'\")\n .replaceAll(\""\", '\"')\n .replaceAll(\">\", \">\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\"&\", \"&\");\n }\n return encoded.replaceAll('\\\\\"', '\"').replaceAll(\"\\\\\\\\\", \"\\\\\");\n}\n\nasync function assertRegisteredStateRoot(\n definitionPath: string,\n platform: \"linux\" | \"darwin\",\n env: NodeJS.ProcessEnv,\n): Promise<void> {\n const installed = installedServiceStateRoot(await readFile(definitionPath, \"utf8\"), platform);\n const requested = resolve(resolveFleetPaths(env).stateRoot);\n if (installed === undefined) {\n if (env.PIFLEET_STATE_ROOT === undefined) return;\n throw new Error(\n `Registered pi-fleet service uses the default state root, but this command requested ${requested}. Run the pi-fleet installer with PIFLEET_STATE_ROOT=${requested} to repair the service, or omit the override.`,\n );\n }\n if (resolve(installed) !== requested) {\n throw new Error(\n `Registered pi-fleet service uses state root ${installed}, but this command requested ${requested}. Repair the service with the intended PIFLEET_STATE_ROOT before retrying.`,\n );\n }\n}\n\nasync function findPackageRoot(modulePath: string): Promise<string> {\n let candidate = dirname(modulePath);\n for (let depth = 0; depth < 6; depth += 1) {\n if (await exists(join(candidate, \"dist\", \"runtime-manifest.json\"))) return candidate;\n const parent = dirname(candidate);\n if (parent === candidate) break;\n candidate = parent;\n }\n throw new Error(\"Unable to locate the pi-fleet package runtime manifest.\");\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction canConnect(socketPath: string): Promise<boolean> {\n return new Promise((resolveConnect) => {\n const socket = createConnection(socketPath);\n const timer = setTimeout(() => {\n socket.destroy();\n resolveConnect(false);\n }, 100);\n socket.once(\"connect\", () => {\n clearTimeout(timer);\n socket.destroy();\n resolveConnect(true);\n });\n socket.once(\"error\", () => {\n clearTimeout(timer);\n resolveConnect(false);\n });\n });\n}\n", "import { createHash, randomUUID } from \"node:crypto\";\nimport { chmod, cp, lstat, mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { join, posix, resolve, sep } from \"node:path\";\n\nimport { hashDirectoryTree, type TreeIntegrity } from \"./tree-integrity.js\";\n\ninterface RuntimeManifestFile {\n readonly path: string;\n readonly bytes: number;\n readonly sha256: string;\n}\n\ninterface RuntimeDependency {\n readonly path: string;\n readonly name: string;\n readonly version: string;\n}\n\ninterface RuntimeClosure {\n readonly sourceManifestSha256: string;\n readonly tree: TreeIntegrity;\n}\n\ninterface RuntimeManifest {\n readonly schemaVersion: 4;\n readonly package: { readonly name: string; readonly version: string };\n readonly piRuntime: { readonly mode: \"external\" };\n readonly files: readonly RuntimeManifestFile[];\n readonly dependencies: readonly RuntimeDependency[];\n readonly closure?: RuntimeClosure;\n}\n\ninterface PackageMetadata {\n readonly name: string;\n readonly version: string;\n readonly dependencies: Readonly<Record<string, string>>;\n}\n\nconst requiredRuntimeArtifacts = new Set([\n \"package.json\",\n \"bin/pifleet.mjs\",\n \"bin/pifleet-runtime.mjs\",\n \"dist/cli.mjs\",\n \"dist/runtime.mjs\",\n \"dist/sqlite-worker.mjs\",\n]);\nconst dependencyTreePath = \"node_modules\";\n\nexport async function materializeRuntime(options: {\n readonly sourceRoot: string;\n readonly applicationRoot: string;\n readonly hooks?: {\n readonly afterDependencyCopy?: () => Promise<void>;\n };\n}): Promise<string> {\n const sourceRoot = resolve(options.sourceRoot);\n const manifestBytes = await readFile(join(sourceRoot, \"dist\", \"runtime-manifest.json\"));\n const sourceManifest = await parseRuntimeManifest(manifestBytes, sourceRoot);\n if (sourceManifest.closure !== undefined) {\n await verifyRuntime(sourceRoot);\n return sourceRoot;\n }\n await verifyRuntimeFiles(sourceRoot, sourceManifest);\n await verifyDependencyIdentities(sourceRoot, sourceManifest.dependencies);\n\n const sourceTreeRoot = resolveInside(sourceRoot, dependencyTreePath);\n const sourceTreeBefore = await hashDirectoryTree(sourceTreeRoot, dependencyTreePath);\n const sourceManifestSha256 = createHash(\"sha256\").update(manifestBytes).digest(\"hex\");\n const materializedManifest: RuntimeManifest = {\n ...sourceManifest,\n closure: { sourceManifestSha256, tree: sourceTreeBefore },\n };\n const materializedManifestBytes = serializeManifest(materializedManifest);\n const closureHash = createHash(\"sha256\")\n .update(sourceManifestSha256)\n .update(\"\\0\")\n .update(JSON.stringify(sourceTreeBefore))\n .digest(\"hex\")\n .slice(0, 16);\n\n const applicationRoot = resolve(options.applicationRoot);\n await ensurePrivateDirectory(applicationRoot);\n const releasesRoot = join(applicationRoot, \"releases\");\n await ensurePrivateDirectory(releasesRoot);\n const destination = join(releasesRoot, `${sourceManifest.package.version}-${closureHash}`);\n\n if (await pathExists(destination)) {\n await verifyExpectedRuntime(destination, materializedManifest, materializedManifestBytes);\n return destination;\n }\n\n const staging = join(releasesRoot, `.staging-${randomUUID()}`);\n await mkdir(staging, { mode: 0o700 });\n try {\n await cp(join(sourceRoot, \"dist\"), join(staging, \"dist\"), {\n recursive: true,\n dereference: true,\n });\n await cp(join(sourceRoot, \"bin\"), join(staging, \"bin\"), {\n recursive: true,\n dereference: true,\n });\n await cp(join(sourceRoot, \"package.json\"), join(staging, \"package.json\"));\n await cp(sourceTreeRoot, join(staging, dependencyTreePath), {\n recursive: true,\n dereference: true,\n });\n await options.hooks?.afterDependencyCopy?.();\n\n const stagedTree = await hashDirectoryTree(\n join(staging, dependencyTreePath),\n dependencyTreePath,\n );\n assertSameTree(sourceTreeBefore, stagedTree, \"copied dependency closure\");\n const sourceTreeAfter = await hashDirectoryTree(sourceTreeRoot, dependencyTreePath);\n assertSameTree(sourceTreeBefore, sourceTreeAfter, \"source dependency closure\");\n\n await writeFile(join(staging, \"dist\", \"runtime-manifest.json\"), materializedManifestBytes);\n await verifyExpectedRuntime(staging, materializedManifest, materializedManifestBytes);\n await chmod(staging, 0o700);\n try {\n await rename(staging, destination);\n } catch (error: unknown) {\n if (!isDestinationRace(error) || !(await pathExists(destination))) throw error;\n await verifyExpectedRuntime(destination, materializedManifest, materializedManifestBytes);\n }\n return destination;\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n}\n\nexport async function verifyRuntime(root: string): Promise<void> {\n const resolvedRoot = resolve(root);\n const manifestBytes = await readFile(join(resolvedRoot, \"dist\", \"runtime-manifest.json\"));\n const manifest = await parseRuntimeManifest(manifestBytes, resolvedRoot);\n if (manifest.closure === undefined) {\n throw new Error(\"Runtime release manifest is missing its materialized closure\");\n }\n await verifyRuntimeFiles(resolvedRoot, manifest);\n await verifyDependencyIdentities(resolvedRoot, manifest.dependencies);\n const actualTree = await hashDirectoryTree(\n resolveInside(resolvedRoot, dependencyTreePath),\n dependencyTreePath,\n );\n assertSameTree(manifest.closure.tree, actualTree, \"materialized dependency closure\");\n}\n\nasync function verifyExpectedRuntime(\n root: string,\n expected: RuntimeManifest,\n expectedBytes: Buffer,\n): Promise<void> {\n const manifestPath = join(root, \"dist\", \"runtime-manifest.json\");\n const actualBytes = await readFile(manifestPath);\n if (!actualBytes.equals(expectedBytes)) {\n throw new Error(\"Materialized runtime manifest does not match the expected closure\");\n }\n const actual = await parseRuntimeManifest(actualBytes, root);\n if (actual.closure === undefined || expected.closure === undefined) {\n throw new Error(\"Materialized runtime manifest is missing its closure\");\n }\n await verifyRuntimeFiles(root, actual);\n await verifyDependencyIdentities(root, actual.dependencies);\n const actualTree = await hashDirectoryTree(\n resolveInside(root, dependencyTreePath),\n dependencyTreePath,\n );\n assertSameTree(expected.closure.tree, actualTree, \"materialized dependency closure\");\n}\n\nasync function verifyRuntimeFiles(root: string, manifest: RuntimeManifest): Promise<void> {\n for (const file of manifest.files) {\n const path = resolveInside(root, file.path);\n const info = await lstat(path);\n if (info.isSymbolicLink()) {\n throw new Error(`Runtime artifact ${file.path} must not be a symbolic link`);\n }\n if (!info.isFile() || info.size !== file.bytes) {\n throw new Error(`Runtime artifact ${file.path} has changed`);\n }\n const hash = createHash(\"sha256\")\n .update(await readFile(path))\n .digest(\"hex\");\n if (hash !== file.sha256) {\n throw new Error(`Runtime artifact ${file.path} failed verification`);\n }\n }\n}\n\nasync function verifyDependencyIdentities(\n root: string,\n dependencies: readonly RuntimeDependency[],\n): Promise<void> {\n const nodeModules = resolveInside(root, dependencyTreePath);\n const modulesInfo = await lstat(nodeModules);\n if (!modulesInfo.isDirectory() || modulesInfo.isSymbolicLink()) {\n throw new Error(\"Runtime dependency closure must be a regular directory\");\n }\n for (const dependency of dependencies) {\n const packageRoot = resolveInside(root, dependency.path);\n const packageInfo = await lstat(packageRoot);\n if (!packageInfo.isDirectory() || packageInfo.isSymbolicLink()) {\n throw new Error(`Runtime dependency ${dependency.name} must be a regular directory`);\n }\n const packageJsonPath = join(packageRoot, \"package.json\");\n const packageJsonInfo = await lstat(packageJsonPath);\n if (!packageJsonInfo.isFile() || packageJsonInfo.isSymbolicLink()) {\n throw new Error(`Runtime dependency ${dependency.name} has an unsafe package.json`);\n }\n const identity = await readPackageMetadata(packageRoot);\n if (identity.name !== dependency.name || identity.version !== dependency.version) {\n throw new Error(`Runtime dependency ${dependency.name} has an unexpected identity`);\n }\n }\n}\n\nasync function parseRuntimeManifest(bytes: Buffer, root: string): Promise<RuntimeManifest> {\n let candidate: unknown;\n try {\n candidate = JSON.parse(bytes.toString(\"utf8\"));\n } catch {\n throw new Error(\"Runtime manifest is not valid JSON\");\n }\n await validateRuntimeManifest(candidate, root);\n return candidate as RuntimeManifest;\n}\n\nasync function validateRuntimeManifest(candidate: unknown, root: string): Promise<void> {\n if (!isRecord(candidate) || candidate.schemaVersion !== 4) {\n throw new Error(\"Runtime manifest has an unsupported schema version\");\n }\n if (\n !isRecord(candidate.package) ||\n typeof candidate.package.name !== \"string\" ||\n typeof candidate.package.version !== \"string\" ||\n !isRecord(candidate.piRuntime) ||\n candidate.piRuntime.mode !== \"external\"\n ) {\n throw new Error(\"Runtime manifest has an invalid package identity\");\n }\n const packageMetadata = await readPackageMetadata(root);\n if (\n candidate.package.name !== packageMetadata.name ||\n candidate.package.version !== packageMetadata.version\n ) {\n throw new Error(\"Runtime manifest package identity does not match package.json\");\n }\n if (!Array.isArray(candidate.files) || !Array.isArray(candidate.dependencies)) {\n throw new Error(\"Runtime manifest has invalid artifact lists\");\n }\n\n const filePaths = new Set<string>();\n for (const file of candidate.files) {\n if (\n !isRecord(file) ||\n !isManifestPath(file.path) ||\n !isValidSize(file.bytes) ||\n !isSha256(file.sha256)\n ) {\n throw new Error(\"Runtime manifest contains an invalid artifact\");\n }\n if (filePaths.has(file.path)) {\n throw new Error(`Runtime manifest has duplicate path ${file.path}`);\n }\n filePaths.add(file.path);\n }\n for (const required of requiredRuntimeArtifacts) {\n if (!filePaths.has(required)) {\n throw new Error(`Runtime manifest is missing required artifact ${required}`);\n }\n }\n\n const dependencyPaths = new Set<string>();\n const dependencyNames = new Set<string>();\n for (const dependency of candidate.dependencies) {\n if (\n !isRecord(dependency) ||\n !isManifestPath(dependency.path) ||\n typeof dependency.name !== \"string\" ||\n dependency.name.length === 0 ||\n typeof dependency.version !== \"string\" ||\n dependency.version.length === 0 ||\n dependency.path !== `node_modules/${dependency.name}`\n ) {\n throw new Error(\"Runtime manifest contains an invalid dependency declaration\");\n }\n if (dependencyPaths.has(dependency.path) || dependencyNames.has(dependency.name)) {\n throw new Error(`Runtime manifest has duplicate dependency ${dependency.name}`);\n }\n dependencyPaths.add(dependency.path);\n dependencyNames.add(dependency.name);\n }\n const expectedDependencies = packageMetadata.dependencies;\n if (\n dependencyNames.size !== Object.keys(expectedDependencies).length ||\n [...dependencyNames].some(\n (name) =>\n expectedDependencies[name] !==\n (candidate.dependencies as Array<Record<string, unknown>>).find(\n (dependency) => dependency.name === name,\n )?.version,\n )\n ) {\n throw new Error(\"Runtime manifest dependencies do not match package.json\");\n }\n\n for (const filePath of filePaths) {\n for (const dependencyPath of dependencyPaths) {\n if (\n filePath === dependencyPath ||\n filePath.startsWith(`${dependencyPath}/`) ||\n dependencyPath.startsWith(`${filePath}/`)\n ) {\n throw new Error(`Runtime manifest has overlapping paths ${filePath} and ${dependencyPath}`);\n }\n }\n }\n\n if (candidate.closure !== undefined) {\n if (\n !isRecord(candidate.closure) ||\n !isSha256(candidate.closure.sourceManifestSha256) ||\n !isTreeIntegrity(candidate.closure.tree) ||\n candidate.closure.tree.path !== dependencyTreePath\n ) {\n throw new Error(\"Runtime manifest contains an invalid materialized closure\");\n }\n }\n}\n\nasync function readPackageMetadata(root: string): Promise<PackageMetadata> {\n let candidate: unknown;\n try {\n candidate = JSON.parse(await readFile(join(root, \"package.json\"), \"utf8\"));\n } catch {\n throw new Error(\"Runtime package.json is not valid JSON\");\n }\n if (\n !isRecord(candidate) ||\n typeof candidate.name !== \"string\" ||\n typeof candidate.version !== \"string\" ||\n (candidate.dependencies !== undefined && !isRecord(candidate.dependencies)) ||\n (isRecord(candidate.dependencies) &&\n Object.values(candidate.dependencies).some((version) => typeof version !== \"string\"))\n ) {\n throw new Error(\"Runtime package.json has invalid package metadata\");\n }\n return {\n name: candidate.name,\n version: candidate.version,\n dependencies: isRecord(candidate.dependencies)\n ? (candidate.dependencies as Record<string, string>)\n : {},\n };\n}\n\nfunction serializeManifest(manifest: RuntimeManifest): Buffer {\n return Buffer.from(`${JSON.stringify(manifest, null, 2)}\\n`);\n}\n\nfunction assertSameTree(expected: TreeIntegrity, actual: TreeIntegrity, label: string): void {\n if (\n expected.path !== actual.path ||\n expected.files !== actual.files ||\n expected.bytes !== actual.bytes ||\n expected.sha256 !== actual.sha256\n ) {\n throw new Error(`Runtime ${label} changed during materialization`);\n }\n}\n\nfunction resolveInside(root: string, path: string): string {\n if (!isManifestPath(path)) throw new Error(`Runtime manifest contains an unsafe path ${path}`);\n const resolved = resolve(root, path);\n if (!resolved.startsWith(`${root}${sep}`)) {\n throw new Error(`Runtime manifest contains an unsafe path ${path}`);\n }\n return resolved;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isManifestPath(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n !value.includes(\"\\\\\") &&\n !value.startsWith(\"/\") &&\n posix.normalize(value) === value &&\n value.split(\"/\").every((part) => part.length > 0 && part !== \".\" && part !== \"..\")\n );\n}\n\nfunction isValidSize(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction isSha256(value: unknown): value is string {\n return typeof value === \"string\" && /^[a-f0-9]{64}$/.test(value);\n}\n\nfunction isTreeIntegrity(value: unknown): value is TreeIntegrity {\n return (\n isRecord(value) &&\n isManifestPath(value.path) &&\n isValidSize(value.files) &&\n isValidSize(value.bytes) &&\n isSha256(value.sha256)\n );\n}\n\nfunction isDestinationRace(error: unknown): boolean {\n const code = (error as NodeJS.ErrnoException).code;\n return code === \"EEXIST\" || code === \"ENOTEMPTY\";\n}\n\nasync function ensurePrivateDirectory(path: string): Promise<void> {\n await mkdir(path, { recursive: true, mode: 0o700 });\n const info = await lstat(path);\n if (!info.isDirectory() || info.isSymbolicLink()) {\n throw new Error(`Refusing unsafe runtime release path ${path}`);\n }\n if (typeof process.getuid === \"function\" && info.uid !== process.getuid()) {\n throw new Error(`Runtime release path ${path} is not owned by the current user`);\n }\n await chmod(path, 0o700);\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await lstat(path);\n return true;\n } catch (error: unknown) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw error;\n }\n}\n", "import { createHash } from \"node:crypto\";\nimport { lstat, readFile, readdir, realpath, stat } from \"node:fs/promises\";\nimport { join, relative, resolve, sep } from \"node:path\";\n\nexport interface TreeIntegrity {\n readonly path: string;\n readonly files: number;\n readonly bytes: number;\n readonly sha256: string;\n}\n\nexport async function hashDirectoryTree(\n root: string,\n manifestPath: string,\n): Promise<TreeIntegrity> {\n const resolvedRoot = resolve(root);\n const entries = await collectFiles(resolvedRoot, resolvedRoot);\n const hash = createHash(\"sha256\");\n let bytes = 0;\n for (const entry of entries) {\n const contents = await readFile(entry.absolutePath);\n bytes += contents.length;\n hash.update(entry.relativePath);\n hash.update(\"\\0\");\n hash.update(String(contents.length));\n hash.update(\"\\0\");\n hash.update(contents);\n hash.update(\"\\0\");\n }\n return {\n path: manifestPath,\n files: entries.length,\n bytes,\n sha256: hash.digest(\"hex\"),\n };\n}\n\nasync function collectFiles(\n root: string,\n directory: string,\n): Promise<Array<{ readonly absolutePath: string; readonly relativePath: string }>> {\n const output: Array<{ absolutePath: string; relativePath: string }> = [];\n for (const name of (await readdir(directory)).sort()) {\n const absolutePath = join(directory, name);\n const linkInfo = await lstat(absolutePath);\n const info = linkInfo.isSymbolicLink() ? await stat(absolutePath) : linkInfo;\n if (info.isDirectory()) {\n if (linkInfo.isSymbolicLink()) {\n throw new Error(`Runtime dependency tree contains a directory symlink: ${absolutePath}`);\n }\n output.push(...(await collectFiles(root, absolutePath)));\n continue;\n }\n if (!info.isFile()) {\n throw new Error(`Runtime dependency tree contains an unsupported entry: ${absolutePath}`);\n }\n if (linkInfo.isSymbolicLink()) {\n const target = await realpath(absolutePath);\n if (target !== root && !target.startsWith(`${root}${sep}`)) {\n throw new Error(\n `Runtime dependency tree contains an external file symlink: ${absolutePath}`,\n );\n }\n }\n const relativePath = relative(root, absolutePath).split(sep).join(\"/\");\n if (relativePath.length === 0 || relativePath.startsWith(\"../\")) {\n throw new Error(`Runtime dependency path escapes its root: ${absolutePath}`);\n }\n output.push({ absolutePath, relativePath });\n }\n return output.sort((left, right) => left.relativePath.localeCompare(right.relativePath));\n}\n", "import { homedir, tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\nexport interface FleetPaths {\n readonly runtimeRoot: string;\n readonly stateRoot: string;\n readonly socketPath: string;\n readonly databasePath: string;\n}\n\nexport function resolveApplicationRoot(env: NodeJS.ProcessEnv = process.env): string {\n return (\n env.PIFLEET_APPLICATION_ROOT ??\n (process.platform === \"darwin\"\n ? join(homedir(), \"Library\", \"Application Support\", \"pi-fleet\", \"runtime\")\n : join(env.XDG_DATA_HOME ?? join(homedir(), \".local\", \"share\"), \"pi-fleet\"))\n );\n}\n\nexport function resolveFleetPaths(env: NodeJS.ProcessEnv = process.env): FleetPaths {\n const explicitRoot = env.PIFLEET_STATE_ROOT;\n if (explicitRoot !== undefined) {\n const root = resolve(explicitRoot);\n return {\n runtimeRoot: root,\n stateRoot: root,\n socketPath: join(root, \"control.sock\"),\n databasePath: join(root, \"fleet.sqlite\"),\n };\n }\n\n const runtimeRoot = join(\n env.XDG_RUNTIME_DIR ?? tmpdir(),\n `pifleet-${process.getuid?.() ?? \"user\"}`,\n );\n const stateRoot =\n process.platform === \"darwin\"\n ? join(homedir(), \"Library\", \"Application Support\", \"pi-fleet\")\n : join(env.XDG_STATE_HOME ?? join(homedir(), \".local\", \"state\"), \"pi-fleet\");\n return {\n runtimeRoot,\n stateRoot,\n socketPath: join(runtimeRoot, \"control.sock\"),\n databasePath: join(stateRoot, \"fleet.sqlite\"),\n };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;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ACF;AACA,aAAO;AAAA,IACT;AACA,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;AACzD,eAAW,aAAa,QAAQ,EAAE,MAAM,qBAAqB,QAAQ,GAAG,KAAK;AAC7E,WAAO;AAAA,EACT;AACF;AAEA,IAAI,QAAQ,KAAK,CAAC,MAAM,UAAa,YAAY,QAAQ,cAAc,QAAQ,KAAK,CAAC,CAAC,EAAE,MAAM;AAC5F,UAAQ,WAAW,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,CAAC;AACvD;",
|
|
6
|
+
"names": ["randomUUID", "process", "stripVTControlCharacters", "cmd", "str", "process", "stripVTControlCharacters", "err", "option", "path", "program", "value", "IsObject", "IsArray", "IsUndefined", "IsNumber", "TypeSystemPolicy", "IsObject", "IsArray", "IsNumber", "IsUndefined", "value", "IsArray", "IsAsyncIterator", "IsBigInt", "IsBoolean", "IsDate", "IsFunction", "IsIterator", "IsNull", "IsNumber", "IsObject", "IsRegExp", "IsString", "IsSymbol", "IsUndefined", "IsUint8Array", "IsArray", "IsBoolean", "IsBigInt", "IsAsyncIterator", "IsDate", "IsFunction", "IsIterator", "IsNull", "IsNumber", "IsObject", "IsAny", "IsArgument", "IsArray", "IsAsyncIterator", "IsBigInt", "IsBoolean", "IsComputed", "IsConstructor", "IsDate", "IsFunction", "IsInteger", "IsIntersect", "IsIterator", "IsKind", "IsKindOf", "IsLiteral", "IsLiteralValue", "IsMappedKey", "IsMappedResult", "IsNever", "IsNot", "IsNull", "IsNumber", "IsObject", "IsOptional", "IsPromise", "IsReadonly", "IsRecord", "IsRef", "IsRegExp", "IsSchema", "IsString", "IsSymbol", "IsTemplateLiteral", "IsThis", "IsTransform", "IsTuple", "IsUint8Array", "IsUndefined", "IsUnion", "IsUnknown", "IsUnsafe", "IsVoid", "IsSchema", "IsReadonly", "IsOptional", "IsAny", "IsKindOf", "IsArgument", "IsArray", "IsAsyncIterator", "IsBigInt", "IsBoolean", "IsComputed", "IsConstructor", "IsDate", "IsFunction", "IsInteger", "IsIntersect", "IsTransform", "IsIterator", "IsLiteral", "IsLiteralValue", "IsMappedKey", "IsMappedResult", "IsNever", "IsNot", "IsNull", "IsNumber", "IsObject", "IsPromise", "IsRecord", "IsRef", "IsRegExp", "IsString", "IsSymbol", "IsTemplateLiteral", "IsThis", "IsTuple", "IsUndefined", "IsUnion", "IsUint8Array", "IsUnknown", "IsUnsafe", "IsVoid", "IsKind", "Array", "Argument", "range", "pattern", "Boolean", "Number", "String", "Boolean", "Number", "String", "Visit", "schema", "IsNumber", "IsBigInt", "IsString", "IsBoolean", "FromUnion", "IsNumber", "FromUnion", "IsArray", "IsObject", "Object", "Promise", "FromProperties", "FromMappedResult", "FromMappedResult", "FromRest", "FromProperties", "IsFunction", "IsAsyncIterator", "IsIterator", "IsObject", "Object", "IsArray", "Array", "Promise", "FromProperties", "FromMappedResult", "IsObject", "RemoveOptionalFromType", "RemoveOptionalFromRest", "FromIntersect", "FromRest", "FromUnion", "FromRest", "FromIntersect", "FromUnion", "FromTuple", "FromArray", "FromProperties", "IsArray", "IsObject", "FromComputed", "FromRef", "Number", "FromProperties", "FromMappedResult", "Object", "Date", "Symbol", "Uint8Array", "FromArray", "FromProperties", "Uint8Array", "Date", "Object", "Symbol", "ExtendsResult", "FromArray", "Visit", "FromIntersect", "FromLiteral", "Number", "FromPromise", "String", "FromTemplateLiteral", "FromTuple", "FromUnion", "FromProperties", "FromMappedResult", "FromMappedKey", "FromProperties", "FromMappedResult", "FromProperties", "FromMappedResult", "Object", "IsBoolean", "IsNumber", "IsRegExp", "IsString", "RecordKey", "String", "Number", "RecordValue", "FromConstructor", "FromFunction", "FromIntersect", "FromUnion", "FromTuple", "FromArray", "FromAsyncIterator", "FromIterator", "FromPromise", "FromObject", "FromProperties", "Object", "FromRecord", "RecordKey", "RecordValue", "FromProperty", "IsFunction", "IsArray", "IsAsyncIterator", "IsIterator", "IsObject", "FromTemplateLiteral", "FromRest", "FromProperties", "FromMappedResult", "FromIntersect", "FromUnion", "FromProperty", "FromProperties", "FromObject", "Object", "result", "IsObject", "FromPropertyKey", "FromPropertyKeys", "FromMappedKey", "FromProperties", "FromMappedResult", "FromIntersect", "FromUnion", "FromProperties", "FromObject", "Type", "Object", "UnionFromPropertyKeys", "result", "IsObject", "FromPropertyKey", "FromPropertyKeys", "FromMappedKey", "FromComputed", "FromRef", "FromProperties", "FromObject", "Object", "FromRest", "IsObject", "IsBigInt", "IsBoolean", "IsNull", "IsNumber", "IsString", "IsSymbol", "IsUndefined", "FromProperties", "FromMappedResult", "FromComputed", "FromRef", "FromProperties", "FromObject", "Object", "FromRest", "IsObject", "IsBigInt", "IsBoolean", "IsNull", "IsNumber", "IsString", "IsSymbol", "IsUndefined", "FromProperties", "FromMappedResult", "FromType", "FromComputed", "FromArray", "Array", "FromAsyncIterator", "FromConstructor", "FromTypes", "FromFunction", "FromIntersect", "FromIterator", "FromObject", "Object", "FromRecord", "RecordValue", "FromTuple", "FromUnion", "IsArray", "IsAsyncIterator", "IsFunction", "IsIterator", "IsObject", "IsFunction", "RegExp", "IsFunction", "type_exports", "Argument", "Array", "Boolean", "Date", "Number", "Object", "Promise", "RegExp", "String", "Symbol", "Uint8Array", "type_exports", "path", "spawn", "access", "readFile", "createConnection", "homedir", "dirname", "join", "resolve", "createHash", "randomUUID", "lstat", "readFile", "join", "resolve", "sep", "createHash", "realpath", "stat", "join", "resolve", "resolve", "readFile", "join", "createHash", "randomUUID", "path", "lstat", "isRecord", "sep", "join", "resolve", "join", "spawn", "homedir", "path", "readFile", "resolve", "dirname", "access", "createConnection", "randomUUID", "program"]
|
|
7
7
|
}
|