PHP WebShell
Текущая директория: /usr/lib/node_modules/bitgo/node_modules/@gql.tada/cli-utils/dist/chunks
Просмотр файла: index-chunk.mjs.map
{"version":3,"file":"index-chunk.mjs","sources":["../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/constants.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/errors.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/format.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/utils.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/Command.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/core.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/HelpCommand.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/Cli.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/platform/browser.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Boolean.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/String.mjs","../../src/utils/error.ts","../../src/term/csi.ts","../../src/term/write.ts","../../src/term/symbols.ts","../../src/term/github.ts","../../src/term/tty.ts","../../src/commands/shared/logger.ts","../../src/commands/shared/utils.ts","../../src/commands/generate-output/logger.ts","../../src/commands/generate-output/runner.ts","../../src/commands/generate-output/index.ts","../../src/commands/generate-persisted/logger.ts","../../src/commands/generate-persisted/runner.ts","../../src/commands/generate-persisted/index.ts","../../../../node_modules/.pnpm/typanion@3.14.0/node_modules/typanion/lib/index.mjs","../../src/commands/generate-schema/runner.ts","../../src/commands/generate-schema/logger.ts","../../src/commands/generate-schema/index.ts","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Array.mjs","../../src/commands/turbo/logger.ts","../../src/commands/turbo/runner.ts","../../src/commands/turbo/index.ts","../../src/commands/check/logger.ts","../../src/commands/check/runner.ts","../../src/commands/check/index.ts","../../../../node_modules/.pnpm/semiver@1.1.0/node_modules/semiver/dist/semiver.mjs","../../src/utils/semver.ts","../../src/ts/utils.ts","../../src/ts/vendor/typescript-vfs.ts","../../../../node_modules/.pnpm/muggle-string@0.4.1/node_modules/muggle-string/out/binarySearch.js","../../../../node_modules/.pnpm/muggle-string@0.4.1/node_modules/muggle-string/out/track.js","../../../../node_modules/.pnpm/muggle-string@0.4.1/node_modules/muggle-string/out/types.js","../../../../node_modules/.pnpm/muggle-string@0.4.1/node_modules/muggle-string/out/index.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/binarySearch.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/translateOffset.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/sourceMap.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/buildMappings.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/lib/buildStacks.js","../../../../node_modules/.pnpm/@volar+source-map@2.1.6/node_modules/@volar/source-map/index.js","../../src/ts/mapping.ts","../../src/ts/container.ts","../../src/ts/transformers.ts","../../src/ts/factory.ts","../../src/commands/doctor/helpers/fs.ts","../../src/commands/doctor/helpers/graphqlConfig.ts","../../src/commands/doctor/helpers/workspaceRoot.ts","../../src/commands/doctor/helpers/versions.ts","../../src/commands/doctor/helpers/vscode.ts","../../src/commands/doctor/logger.ts","../../src/commands/doctor/runner.ts","../../src/commands/doctor/index.ts","../../../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js","../../../../node_modules/.pnpm/picocolors@1.0.1/node_modules/picocolors/picocolors.browser.js","../../../../node_modules/.pnpm/@clack+core@0.3.4/node_modules/@clack/core/dist/index.mjs","../../../../node_modules/.pnpm/@clack+prompts@0.7.0/node_modules/@clack/prompts/dist/index.mjs","../../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js","../../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js","../../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js","../../../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js","../../../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js","../../../../node_modules/.pnpm/cross-spawn@7.0.3/node_modules/cross-spawn/lib/util/resolveCommand.js","../../../../node_modules/.pnpm/cross-spawn@7.0.3/node_modules/cross-spawn/lib/util/escape.js","../../../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js","../../../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js","../../../../node_modules/.pnpm/cross-spawn@7.0.3/node_modules/cross-spawn/lib/util/readShebang.js","../../../../node_modules/.pnpm/cross-spawn@7.0.3/node_modules/cross-spawn/lib/parse.js","../../../../node_modules/.pnpm/cross-spawn@7.0.3/node_modules/cross-spawn/lib/enoent.js","../../../../node_modules/.pnpm/cross-spawn@7.0.3/node_modules/cross-spawn/index.js","../../../../node_modules/.pnpm/path-key@4.0.0/node_modules/path-key/index.js","../../../../node_modules/.pnpm/npm-run-path@5.3.0/node_modules/npm-run-path/index.js","../../../../node_modules/.pnpm/mimic-fn@4.0.0/node_modules/mimic-fn/index.js","../../../../node_modules/.pnpm/onetime@6.0.0/node_modules/onetime/index.js","../../../../node_modules/.pnpm/human-signals@5.0.0/node_modules/human-signals/build/src/realtime.js","../../../../node_modules/.pnpm/human-signals@5.0.0/node_modules/human-signals/build/src/core.js","../../../../node_modules/.pnpm/human-signals@5.0.0/node_modules/human-signals/build/src/signals.js","../../../../node_modules/.pnpm/human-signals@5.0.0/node_modules/human-signals/build/src/main.js","../../../../node_modules/.pnpm/execa@8.0.1/node_modules/execa/lib/error.js","../../../../node_modules/.pnpm/execa@8.0.1/node_modules/execa/lib/stdio.js","../../../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/signals.js","../../../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/index.js","../../../../node_modules/.pnpm/execa@8.0.1/node_modules/execa/lib/kill.js","../../../../node_modules/.pnpm/is-stream@3.0.0/node_modules/is-stream/index.js","../../../../node_modules/.pnpm/execa@8.0.1/node_modules/execa/lib/pipe.js","../../../../node_modules/.pnpm/get-stream@8.0.1/node_modules/get-stream/source/contents.js","../../../../node_modules/.pnpm/get-stream@8.0.1/node_modules/get-stream/source/utils.js","../../../../node_modules/.pnpm/get-stream@8.0.1/node_modules/get-stream/source/array-buffer.js","../../../../node_modules/.pnpm/get-stream@8.0.1/node_modules/get-stream/source/buffer.js","../../../../node_modules/.pnpm/get-stream@8.0.1/node_modules/get-stream/source/string.js","../../../../node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js","../../../../node_modules/.pnpm/execa@8.0.1/node_modules/execa/lib/stream.js","../../../../node_modules/.pnpm/execa@8.0.1/node_modules/execa/lib/promise.js","../../../../node_modules/.pnpm/execa@8.0.1/node_modules/execa/lib/command.js","../../../../node_modules/.pnpm/execa@8.0.1/node_modules/execa/lib/verbose.js","../../../../node_modules/.pnpm/execa@8.0.1/node_modules/execa/index.js","../../../../node_modules/.pnpm/strip-final-newline@3.0.0/node_modules/strip-final-newline/index.js","../../src/commands/init/runner.ts","../../src/commands/init/index.ts","../../src/index.ts"],"sourcesContent":["var SpecialToken;\n(function (SpecialToken) {\n SpecialToken[\"StartOfInput\"] = \"\\0\";\n SpecialToken[\"EndOfInput\"] = \"\\u0001\";\n SpecialToken[\"EndOfPartialInput\"] = \"\\u0002\";\n})(SpecialToken || (SpecialToken = {}));\nvar NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"InitialNode\"] = 0] = \"InitialNode\";\n NodeType[NodeType[\"SuccessNode\"] = 1] = \"SuccessNode\";\n NodeType[NodeType[\"ErrorNode\"] = 2] = \"ErrorNode\";\n NodeType[NodeType[\"CustomNode\"] = 3] = \"CustomNode\";\n})(NodeType || (NodeType = {}));\nconst HELP_COMMAND_INDEX = -1;\nconst HELP_REGEX = /^(-h|--help)(?:=([0-9]+))?$/;\nconst OPTION_REGEX = /^(--[a-z]+(?:-[a-z]+)*|-[a-zA-Z]+)$/;\nconst BATCH_REGEX = /^-[a-zA-Z]{2,}$/;\nconst BINDING_REGEX = /^([^=]+)=([\\s\\S]*)$/;\nconst IS_DEBUG = process.env.DEBUG_CLI === `1`;\n\nexport { BATCH_REGEX, BINDING_REGEX, HELP_COMMAND_INDEX, HELP_REGEX, IS_DEBUG, NodeType, OPTION_REGEX, SpecialToken };\n","import { SpecialToken } from './constants.mjs';\n\n/**\n * A generic usage error with the name `UsageError`.\n *\n * It should be used over `Error` only when it's the user's fault.\n */\nclass UsageError extends Error {\n constructor(message) {\n super(message);\n this.clipanion = { type: `usage` };\n this.name = `UsageError`;\n }\n}\nclass UnknownSyntaxError extends Error {\n constructor(input, candidates) {\n super();\n this.input = input;\n this.candidates = candidates;\n this.clipanion = { type: `none` };\n this.name = `UnknownSyntaxError`;\n if (this.candidates.length === 0) {\n this.message = `Command not found, but we're not sure what's the alternative.`;\n }\n else if (this.candidates.every(candidate => candidate.reason !== null && candidate.reason === candidates[0].reason)) {\n const [{ reason }] = this.candidates;\n this.message = `${reason}\\n\\n${this.candidates.map(({ usage }) => `$ ${usage}`).join(`\\n`)}`;\n }\n else if (this.candidates.length === 1) {\n const [{ usage }] = this.candidates;\n this.message = `Command not found; did you mean:\\n\\n$ ${usage}\\n${whileRunning(input)}`;\n }\n else {\n this.message = `Command not found; did you mean one of:\\n\\n${this.candidates.map(({ usage }, index) => {\n return `${`${index}.`.padStart(4)} ${usage}`;\n }).join(`\\n`)}\\n\\n${whileRunning(input)}`;\n }\n }\n}\nclass AmbiguousSyntaxError extends Error {\n constructor(input, usages) {\n super();\n this.input = input;\n this.usages = usages;\n this.clipanion = { type: `none` };\n this.name = `AmbiguousSyntaxError`;\n this.message = `Cannot find which to pick amongst the following alternatives:\\n\\n${this.usages.map((usage, index) => {\n return `${`${index}.`.padStart(4)} ${usage}`;\n }).join(`\\n`)}\\n\\n${whileRunning(input)}`;\n }\n}\nconst whileRunning = (input) => `While running ${input.filter(token => {\n return token !== SpecialToken.EndOfInput && token !== SpecialToken.EndOfPartialInput;\n}).map(token => {\n const json = JSON.stringify(token);\n if (token.match(/\\s/) || token.length === 0 || json !== `\"${token}\"`) {\n return json;\n }\n else {\n return token;\n }\n}).join(` `)}`;\n\nexport { AmbiguousSyntaxError, UnknownSyntaxError, UsageError };\n","const MAX_LINE_LENGTH = 80;\nconst richLine = Array(MAX_LINE_LENGTH).fill(`━`);\nfor (let t = 0; t <= 24; ++t)\n richLine[richLine.length - t] = `\\x1b[38;5;${232 + t}m━`;\nconst richFormat = {\n header: str => `\\x1b[1m━━━ ${str}${str.length < MAX_LINE_LENGTH - 5 ? ` ${richLine.slice(str.length + 5).join(``)}` : `:`}\\x1b[0m`,\n bold: str => `\\x1b[1m${str}\\x1b[22m`,\n error: str => `\\x1b[31m\\x1b[1m${str}\\x1b[22m\\x1b[39m`,\n code: str => `\\x1b[36m${str}\\x1b[39m`,\n};\nconst textFormat = {\n header: str => str,\n bold: str => str,\n error: str => str,\n code: str => str,\n};\nfunction dedent(text) {\n const lines = text.split(`\\n`);\n const nonEmptyLines = lines.filter(line => line.match(/\\S/));\n const indent = nonEmptyLines.length > 0 ? nonEmptyLines.reduce((minLength, line) => Math.min(minLength, line.length - line.trimStart().length), Number.MAX_VALUE) : 0;\n return lines\n .map(line => line.slice(indent).trimRight())\n .join(`\\n`);\n}\n/**\n * Formats markdown text to be displayed to the console. Not all markdown features are supported.\n *\n * @param text The markdown text to format.\n * @param opts.format The format to use.\n * @param opts.paragraphs Whether to cut the text into paragraphs of 80 characters at most.\n */\nfunction formatMarkdownish(text, { format, paragraphs }) {\n // Enforce \\n as newline character\n text = text.replace(/\\r\\n?/g, `\\n`);\n // Remove the indentation, since it got messed up with the JS indentation\n text = dedent(text);\n // Remove surrounding newlines, since they got added for JS formatting\n text = text.replace(/^\\n+|\\n+$/g, ``);\n // List items always end with at least two newlines (in order to not be collapsed)\n text = text.replace(/^(\\s*)-([^\\n]*?)\\n+/gm, `$1-$2\\n\\n`);\n // Single newlines are removed; larger than that are collapsed into one\n text = text.replace(/\\n(\\n)?\\n*/g, ($0, $1) => $1 ? $1 : ` `);\n if (paragraphs) {\n text = text.split(/\\n/).map(paragraph => {\n // Does the paragraph starts with a list?\n const bulletMatch = paragraph.match(/^\\s*[*-][\\t ]+(.*)/);\n if (!bulletMatch)\n // No, cut the paragraphs into segments of 80 characters\n return paragraph.match(/(.{1,80})(?: |$)/g).join(`\\n`);\n const indent = paragraph.length - paragraph.trimStart().length;\n // Yes, cut the paragraphs into segments of (78 - indent) characters (to account for the prefix)\n return bulletMatch[1].match(new RegExp(`(.{1,${78 - indent}})(?: |$)`, `g`)).map((line, index) => {\n return ` `.repeat(indent) + (index === 0 ? `- ` : ` `) + line;\n }).join(`\\n`);\n }).join(`\\n\\n`);\n }\n // Highlight the code segments\n text = text.replace(/(`+)((?:.|[\\n])*?)\\1/g, ($0, $1, $2) => {\n return format.code($1 + $2 + $1);\n });\n // Highlight the bold segments\n text = text.replace(/(\\*\\*)((?:.|[\\n])*?)\\1/g, ($0, $1, $2) => {\n return format.bold($1 + $2 + $1);\n });\n return text ? `${text}\\n` : ``;\n}\n\nexport { formatMarkdownish, richFormat, textFormat };\n","import { UsageError } from '../../errors.mjs';\n\nconst isOptionSymbol = Symbol(`clipanion/isOption`);\nfunction makeCommandOption(spec) {\n // We lie! But it's for the good cause: the cli engine will turn the specs into proper values after instantiation.\n return { ...spec, [isOptionSymbol]: true };\n}\nfunction rerouteArguments(a, b) {\n if (typeof a === `undefined`)\n return [a, b];\n if (typeof a === `object` && a !== null && !Array.isArray(a)) {\n return [undefined, a];\n }\n else {\n return [a, b];\n }\n}\nfunction cleanValidationError(message, { mergeName = false } = {}) {\n const match = message.match(/^([^:]+): (.*)$/m);\n if (!match)\n return `validation failed`;\n let [, path, line] = match;\n if (mergeName)\n line = line[0].toLowerCase() + line.slice(1);\n line = path !== `.` || !mergeName\n ? `${path.replace(/^\\.(\\[|$)/, `$1`)}: ${line}`\n : `: ${line}`;\n return line;\n}\nfunction formatError(message, errors) {\n if (errors.length === 1) {\n return new UsageError(`${message}${cleanValidationError(errors[0], { mergeName: true })}`);\n }\n else {\n return new UsageError(`${message}:\\n${errors.map(error => `\\n- ${cleanValidationError(error)}`).join(``)}`);\n }\n}\nfunction applyValidator(name, value, validator) {\n if (typeof validator === `undefined`)\n return value;\n const errors = [];\n const coercions = [];\n const coercion = (v) => {\n const orig = value;\n value = v;\n return coercion.bind(null, orig);\n };\n const check = validator(value, { errors, coercions, coercion });\n if (!check)\n throw formatError(`Invalid value for ${name}`, errors);\n for (const [, op] of coercions)\n op();\n return value;\n}\n\nexport { applyValidator, cleanValidationError, formatError, isOptionSymbol, makeCommandOption, rerouteArguments };\n","import { formatError, isOptionSymbol } from './options/utils.mjs';\n\n/**\n * Base abstract class for CLI commands. The main thing to remember is to\n * declare an async `execute` member function that will be called when the\n * command is invoked from the CLI, and optionally a `paths` property to\n * declare the set of paths under which the command should be exposed.\n */\nclass Command {\n constructor() {\n /**\n * Predefined that will be set to true if `-h,--help` has been used, in\n * which case `Command#execute` won't be called.\n */\n this.help = false;\n }\n /**\n * Defines the usage information for the given command.\n */\n static Usage(usage) {\n return usage;\n }\n /**\n * Standard error handler which will simply rethrow the error. Can be used\n * to add custom logic to handle errors from the command or simply return\n * the parent class error handling.\n */\n async catch(error) {\n throw error;\n }\n async validateAndExecute() {\n const commandClass = this.constructor;\n const cascade = commandClass.schema;\n if (Array.isArray(cascade)) {\n const { isDict, isUnknown, applyCascade } = await import('typanion');\n const schema = applyCascade(isDict(isUnknown()), cascade);\n const errors = [];\n const coercions = [];\n const check = schema(this, { errors, coercions });\n if (!check)\n throw formatError(`Invalid option schema`, errors);\n for (const [, op] of coercions) {\n op();\n }\n }\n else if (cascade != null) {\n throw new Error(`Invalid command schema`);\n }\n const exitCode = await this.execute();\n if (typeof exitCode !== `undefined`) {\n return exitCode;\n }\n else {\n return 0;\n }\n }\n}\n/**\n * Used to detect option definitions.\n */\nCommand.isOption = isOptionSymbol;\n/**\n * Just an helper to use along with the `paths` fields, to make it\n * clearer that a command is the default one.\n *\n * @example\n * class MyCommand extends Command {\n * static paths = [Command.Default];\n * }\n */\nCommand.Default = [];\n\nexport { Command };\n","import { IS_DEBUG, NodeType, SpecialToken, HELP_COMMAND_INDEX, BATCH_REGEX, BINDING_REGEX, OPTION_REGEX, HELP_REGEX } from './constants.mjs';\nimport { UnknownSyntaxError, AmbiguousSyntaxError } from './errors.mjs';\n\n// ------------------------------------------------------------------------\nfunction debug(str) {\n if (IS_DEBUG) {\n console.log(str);\n }\n}\nconst basicHelpState = {\n candidateUsage: null,\n requiredOptions: [],\n errorMessage: null,\n ignoreOptions: false,\n path: [],\n positionals: [],\n options: [],\n remainder: null,\n selectedIndex: HELP_COMMAND_INDEX,\n tokens: [],\n};\nfunction makeStateMachine() {\n const stateMachine = {\n nodes: [],\n };\n for (let t = 0; t < NodeType.CustomNode; ++t)\n stateMachine.nodes.push(makeNode());\n return stateMachine;\n}\nfunction makeAnyOfMachine(inputs) {\n const output = makeStateMachine();\n const heads = [];\n let offset = output.nodes.length;\n for (const input of inputs) {\n heads.push(offset);\n for (let t = 0; t < input.nodes.length; ++t)\n if (!isTerminalNode(t))\n output.nodes.push(cloneNode(input.nodes[t], offset));\n offset += input.nodes.length - NodeType.CustomNode + 1;\n }\n for (const head of heads)\n registerShortcut(output, NodeType.InitialNode, head);\n return output;\n}\nfunction injectNode(machine, node) {\n machine.nodes.push(node);\n return machine.nodes.length - 1;\n}\nfunction simplifyMachine(input) {\n const visited = new Set();\n const process = (node) => {\n if (visited.has(node))\n return;\n visited.add(node);\n const nodeDef = input.nodes[node];\n for (const transitions of Object.values(nodeDef.statics))\n for (const { to } of transitions)\n process(to);\n for (const [, { to }] of nodeDef.dynamics)\n process(to);\n for (const { to } of nodeDef.shortcuts)\n process(to);\n const shortcuts = new Set(nodeDef.shortcuts.map(({ to }) => to));\n while (nodeDef.shortcuts.length > 0) {\n const { to } = nodeDef.shortcuts.shift();\n const toDef = input.nodes[to];\n for (const [segment, transitions] of Object.entries(toDef.statics)) {\n const store = !Object.prototype.hasOwnProperty.call(nodeDef.statics, segment)\n ? nodeDef.statics[segment] = []\n : nodeDef.statics[segment];\n for (const transition of transitions) {\n if (!store.some(({ to }) => transition.to === to)) {\n store.push(transition);\n }\n }\n }\n for (const [test, transition] of toDef.dynamics)\n if (!nodeDef.dynamics.some(([otherTest, { to }]) => test === otherTest && transition.to === to))\n nodeDef.dynamics.push([test, transition]);\n for (const transition of toDef.shortcuts) {\n if (!shortcuts.has(transition.to)) {\n nodeDef.shortcuts.push(transition);\n shortcuts.add(transition.to);\n }\n }\n }\n };\n process(NodeType.InitialNode);\n}\nfunction debugMachine(machine, { prefix = `` } = {}) {\n // Don't iterate unless it's needed\n if (IS_DEBUG) {\n debug(`${prefix}Nodes are:`);\n for (let t = 0; t < machine.nodes.length; ++t) {\n debug(`${prefix} ${t}: ${JSON.stringify(machine.nodes[t])}`);\n }\n }\n}\nfunction runMachineInternal(machine, input, partial = false) {\n debug(`Running a vm on ${JSON.stringify(input)}`);\n let branches = [{\n node: NodeType.InitialNode,\n state: {\n candidateUsage: null,\n requiredOptions: [],\n errorMessage: null,\n ignoreOptions: false,\n options: [],\n path: [],\n positionals: [],\n remainder: null,\n selectedIndex: null,\n tokens: [],\n },\n }];\n debugMachine(machine, { prefix: ` ` });\n const tokens = [SpecialToken.StartOfInput, ...input];\n for (let t = 0; t < tokens.length; ++t) {\n const segment = tokens[t];\n const isEOI = segment === SpecialToken.EndOfInput || segment === SpecialToken.EndOfPartialInput;\n // The -1 is because we added a START_OF_INPUT token\n const segmentIndex = t - 1;\n debug(` Processing ${JSON.stringify(segment)}`);\n const nextBranches = [];\n for (const { node, state } of branches) {\n debug(` Current node is ${node}`);\n const nodeDef = machine.nodes[node];\n if (node === NodeType.ErrorNode) {\n nextBranches.push({ node, state });\n continue;\n }\n console.assert(nodeDef.shortcuts.length === 0, `Shortcuts should have been eliminated by now`);\n const hasExactMatch = Object.prototype.hasOwnProperty.call(nodeDef.statics, segment);\n if (!partial || t < tokens.length - 1 || hasExactMatch) {\n if (hasExactMatch) {\n const transitions = nodeDef.statics[segment];\n for (const { to, reducer } of transitions) {\n nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });\n debug(` Static transition to ${to} found`);\n }\n }\n else {\n debug(` No static transition found`);\n }\n }\n else {\n let hasMatches = false;\n for (const candidate of Object.keys(nodeDef.statics)) {\n if (!candidate.startsWith(segment))\n continue;\n if (segment === candidate) {\n for (const { to, reducer } of nodeDef.statics[candidate]) {\n nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });\n debug(` Static transition to ${to} found`);\n }\n }\n else {\n for (const { to } of nodeDef.statics[candidate]) {\n nextBranches.push({ node: to, state: { ...state, remainder: candidate.slice(segment.length) } });\n debug(` Static transition to ${to} found (partial match)`);\n }\n }\n hasMatches = true;\n }\n if (!hasMatches) {\n debug(` No partial static transition found`);\n }\n }\n if (!isEOI) {\n for (const [test, { to, reducer }] of nodeDef.dynamics) {\n if (execute(tests, test, state, segment, segmentIndex)) {\n nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });\n debug(` Dynamic transition to ${to} found (via ${test})`);\n }\n }\n }\n }\n if (nextBranches.length === 0 && isEOI && input.length === 1) {\n return [{\n node: NodeType.InitialNode,\n state: basicHelpState,\n }];\n }\n if (nextBranches.length === 0) {\n throw new UnknownSyntaxError(input, branches.filter(({ node }) => {\n return node !== NodeType.ErrorNode;\n }).map(({ state }) => {\n return { usage: state.candidateUsage, reason: null };\n }));\n }\n if (nextBranches.every(({ node }) => node === NodeType.ErrorNode)) {\n throw new UnknownSyntaxError(input, nextBranches.map(({ state }) => {\n return { usage: state.candidateUsage, reason: state.errorMessage };\n }));\n }\n branches = trimSmallerBranches(nextBranches);\n }\n if (branches.length > 0) {\n debug(` Results:`);\n for (const branch of branches) {\n debug(` - ${branch.node} -> ${JSON.stringify(branch.state)}`);\n }\n }\n else {\n debug(` No results`);\n }\n return branches;\n}\nfunction runMachine(machine, input, { endToken = SpecialToken.EndOfInput } = {}) {\n const branches = runMachineInternal(machine, [...input, endToken]);\n return selectBestState(input, branches.map(({ state }) => {\n return state;\n }));\n}\nfunction trimSmallerBranches(branches) {\n let maxPathSize = 0;\n for (const { state } of branches)\n if (state.path.length > maxPathSize)\n maxPathSize = state.path.length;\n return branches.filter(({ state }) => {\n return state.path.length === maxPathSize;\n });\n}\nfunction selectBestState(input, states) {\n const terminalStates = states.filter(state => {\n return state.selectedIndex !== null;\n });\n if (terminalStates.length === 0)\n throw new Error();\n const requiredOptionsSetStates = terminalStates.filter(state => state.selectedIndex === HELP_COMMAND_INDEX || state.requiredOptions.every(names => names.some(name => state.options.find(opt => opt.name === name))));\n if (requiredOptionsSetStates.length === 0) {\n throw new UnknownSyntaxError(input, terminalStates.map(state => ({\n usage: state.candidateUsage,\n reason: null,\n })));\n }\n let maxPathSize = 0;\n for (const state of requiredOptionsSetStates)\n if (state.path.length > maxPathSize)\n maxPathSize = state.path.length;\n const bestPathBranches = requiredOptionsSetStates.filter(state => {\n return state.path.length === maxPathSize;\n });\n const getPositionalCount = (state) => state.positionals.filter(({ extra }) => {\n return !extra;\n }).length + state.options.length;\n const statesWithPositionalCount = bestPathBranches.map(state => {\n return { state, positionalCount: getPositionalCount(state) };\n });\n let maxPositionalCount = 0;\n for (const { positionalCount } of statesWithPositionalCount)\n if (positionalCount > maxPositionalCount)\n maxPositionalCount = positionalCount;\n const bestPositionalStates = statesWithPositionalCount.filter(({ positionalCount }) => {\n return positionalCount === maxPositionalCount;\n }).map(({ state }) => {\n return state;\n });\n const fixedStates = aggregateHelpStates(bestPositionalStates);\n if (fixedStates.length > 1)\n throw new AmbiguousSyntaxError(input, fixedStates.map(state => state.candidateUsage));\n return fixedStates[0];\n}\nfunction aggregateHelpStates(states) {\n const notHelps = [];\n const helps = [];\n for (const state of states) {\n if (state.selectedIndex === HELP_COMMAND_INDEX) {\n helps.push(state);\n }\n else {\n notHelps.push(state);\n }\n }\n if (helps.length > 0) {\n notHelps.push({\n ...basicHelpState,\n path: findCommonPrefix(...helps.map(state => state.path)),\n options: helps.reduce((options, state) => options.concat(state.options), []),\n });\n }\n return notHelps;\n}\nfunction findCommonPrefix(firstPath, secondPath, ...rest) {\n if (secondPath === undefined)\n return Array.from(firstPath);\n return findCommonPrefix(firstPath.filter((segment, i) => segment === secondPath[i]), ...rest);\n}\nfunction makeNode() {\n return {\n dynamics: [],\n shortcuts: [],\n statics: {},\n };\n}\nfunction isTerminalNode(node) {\n return node === NodeType.SuccessNode || node === NodeType.ErrorNode;\n}\nfunction cloneTransition(input, offset = 0) {\n const to = !isTerminalNode(input.to)\n ? input.to >= NodeType.CustomNode\n ? input.to + offset - NodeType.CustomNode + 1\n : input.to + offset\n : input.to;\n return {\n to,\n reducer: input.reducer,\n };\n}\nfunction cloneNode(input, offset = 0) {\n const output = makeNode();\n for (const [test, transition] of input.dynamics)\n output.dynamics.push([test, cloneTransition(transition, offset)]);\n for (const transition of input.shortcuts)\n output.shortcuts.push(cloneTransition(transition, offset));\n for (const [segment, transitions] of Object.entries(input.statics))\n output.statics[segment] = transitions.map(transition => cloneTransition(transition, offset));\n return output;\n}\nfunction registerDynamic(machine, from, test, to, reducer) {\n machine.nodes[from].dynamics.push([\n test,\n { to, reducer: reducer },\n ]);\n}\nfunction registerShortcut(machine, from, to, reducer) {\n machine.nodes[from].shortcuts.push({ to, reducer: reducer });\n}\nfunction registerStatic(machine, from, test, to, reducer) {\n const store = !Object.prototype.hasOwnProperty.call(machine.nodes[from].statics, test)\n ? machine.nodes[from].statics[test] = []\n : machine.nodes[from].statics[test];\n store.push({ to, reducer: reducer });\n}\nfunction execute(store, callback, state, segment, segmentIndex) {\n // TypeScript's control flow can't properly narrow\n // generic conditionals for some mysterious reason\n if (Array.isArray(callback)) {\n const [name, ...args] = callback;\n return store[name](state, segment, segmentIndex, ...args);\n }\n else {\n return store[callback](state, segment, segmentIndex);\n }\n}\nconst tests = {\n always: () => {\n return true;\n },\n isOptionLike: (state, segment) => {\n return !state.ignoreOptions && (segment !== `-` && segment.startsWith(`-`));\n },\n isNotOptionLike: (state, segment) => {\n return state.ignoreOptions || segment === `-` || !segment.startsWith(`-`);\n },\n isOption: (state, segment, segmentIndex, name) => {\n return !state.ignoreOptions && segment === name;\n },\n isBatchOption: (state, segment, segmentIndex, names) => {\n return !state.ignoreOptions && BATCH_REGEX.test(segment) && [...segment.slice(1)].every(name => names.has(`-${name}`));\n },\n isBoundOption: (state, segment, segmentIndex, names, options) => {\n const optionParsing = segment.match(BINDING_REGEX);\n return !state.ignoreOptions && !!optionParsing && OPTION_REGEX.test(optionParsing[1]) && names.has(optionParsing[1])\n // Disallow bound options with no arguments (i.e. booleans)\n && options.filter(opt => opt.nameSet.includes(optionParsing[1])).every(opt => opt.allowBinding);\n },\n isNegatedOption: (state, segment, segmentIndex, name) => {\n return !state.ignoreOptions && segment === `--no-${name.slice(2)}`;\n },\n isHelp: (state, segment) => {\n return !state.ignoreOptions && HELP_REGEX.test(segment);\n },\n isUnsupportedOption: (state, segment, segmentIndex, names) => {\n return !state.ignoreOptions && segment.startsWith(`-`) && OPTION_REGEX.test(segment) && !names.has(segment);\n },\n isInvalidOption: (state, segment) => {\n return !state.ignoreOptions && segment.startsWith(`-`) && !OPTION_REGEX.test(segment);\n },\n};\nconst reducers = {\n setCandidateState: (state, segment, segmentIndex, candidateState) => {\n return { ...state, ...candidateState };\n },\n setSelectedIndex: (state, segment, segmentIndex, index) => {\n return { ...state, selectedIndex: index };\n },\n pushBatch: (state, segment, segmentIndex, names) => {\n const options = state.options.slice();\n const tokens = state.tokens.slice();\n for (let t = 1; t < segment.length; ++t) {\n const name = names.get(`-${segment[t]}`);\n const slice = t === 1 ? [0, 2] : [t, t + 1];\n options.push({ name, value: true });\n tokens.push({ segmentIndex, type: `option`, option: name, slice });\n }\n return { ...state, options, tokens };\n },\n pushBound: (state, segment, segmentIndex) => {\n const [, name, value] = segment.match(BINDING_REGEX);\n const options = state.options.concat({ name, value });\n const tokens = state.tokens.concat([\n { segmentIndex, type: `option`, slice: [0, name.length], option: name },\n { segmentIndex, type: `assign`, slice: [name.length, name.length + 1] },\n { segmentIndex, type: `value`, slice: [name.length + 1, name.length + value.length + 1] },\n ]);\n return { ...state, options, tokens };\n },\n pushPath: (state, segment, segmentIndex) => {\n const path = state.path.concat(segment);\n const tokens = state.tokens.concat({ segmentIndex, type: `path` });\n return { ...state, path, tokens };\n },\n pushPositional: (state, segment, segmentIndex) => {\n const positionals = state.positionals.concat({ value: segment, extra: false });\n const tokens = state.tokens.concat({ segmentIndex, type: `positional` });\n return { ...state, positionals, tokens };\n },\n pushExtra: (state, segment, segmentIndex) => {\n const positionals = state.positionals.concat({ value: segment, extra: true });\n const tokens = state.tokens.concat({ segmentIndex, type: `positional` });\n return { ...state, positionals, tokens };\n },\n pushExtraNoLimits: (state, segment, segmentIndex) => {\n const positionals = state.positionals.concat({ value: segment, extra: NoLimits });\n const tokens = state.tokens.concat({ segmentIndex, type: `positional` });\n return { ...state, positionals, tokens };\n },\n pushTrue: (state, segment, segmentIndex, name) => {\n const options = state.options.concat({ name, value: true });\n const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: name });\n return { ...state, options, tokens };\n },\n pushFalse: (state, segment, segmentIndex, name) => {\n const options = state.options.concat({ name, value: false });\n const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: name });\n return { ...state, options, tokens };\n },\n pushUndefined: (state, segment, segmentIndex, name) => {\n const options = state.options.concat({ name: segment, value: undefined });\n const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: segment });\n return { ...state, options, tokens };\n },\n pushStringValue: (state, segment, segmentIndex) => {\n var _a;\n const lastOption = state.options[state.options.length - 1];\n const options = state.options.slice();\n const tokens = state.tokens.concat({ segmentIndex, type: `value` });\n lastOption.value = ((_a = lastOption.value) !== null && _a !== void 0 ? _a : []).concat([segment]);\n return { ...state, options, tokens };\n },\n setStringValue: (state, segment, segmentIndex) => {\n const lastOption = state.options[state.options.length - 1];\n const options = state.options.slice();\n const tokens = state.tokens.concat({ segmentIndex, type: `value` });\n lastOption.value = segment;\n return { ...state, options, tokens };\n },\n inhibateOptions: (state) => {\n return { ...state, ignoreOptions: true };\n },\n useHelp: (state, segment, segmentIndex, command) => {\n const [, /* name */ , index] = segment.match(HELP_REGEX);\n if (typeof index !== `undefined`) {\n return { ...state, options: [{ name: `-c`, value: String(command) }, { name: `-i`, value: index }] };\n }\n else {\n return { ...state, options: [{ name: `-c`, value: String(command) }] };\n }\n },\n setError: (state, segment, segmentIndex, errorMessage) => {\n if (segment === SpecialToken.EndOfInput || segment === SpecialToken.EndOfPartialInput) {\n return { ...state, errorMessage: `${errorMessage}.` };\n }\n else {\n return { ...state, errorMessage: `${errorMessage} (\"${segment}\").` };\n }\n },\n setOptionArityError: (state, segment) => {\n const lastOption = state.options[state.options.length - 1];\n return { ...state, errorMessage: `Not enough arguments to option ${lastOption.name}.` };\n },\n};\n// ------------------------------------------------------------------------\nconst NoLimits = Symbol();\nclass CommandBuilder {\n constructor(cliIndex, cliOpts) {\n this.allOptionNames = new Map();\n this.arity = { leading: [], trailing: [], extra: [], proxy: false };\n this.options = [];\n this.paths = [];\n this.cliIndex = cliIndex;\n this.cliOpts = cliOpts;\n }\n addPath(path) {\n this.paths.push(path);\n }\n setArity({ leading = this.arity.leading, trailing = this.arity.trailing, extra = this.arity.extra, proxy = this.arity.proxy }) {\n Object.assign(this.arity, { leading, trailing, extra, proxy });\n }\n addPositional({ name = `arg`, required = true } = {}) {\n if (!required && this.arity.extra === NoLimits)\n throw new Error(`Optional parameters cannot be declared when using .rest() or .proxy()`);\n if (!required && this.arity.trailing.length > 0)\n throw new Error(`Optional parameters cannot be declared after the required trailing positional arguments`);\n if (!required && this.arity.extra !== NoLimits) {\n this.arity.extra.push(name);\n }\n else if (this.arity.extra !== NoLimits && this.arity.extra.length === 0) {\n this.arity.leading.push(name);\n }\n else {\n this.arity.trailing.push(name);\n }\n }\n addRest({ name = `arg`, required = 0 } = {}) {\n if (this.arity.extra === NoLimits)\n throw new Error(`Infinite lists cannot be declared multiple times in the same command`);\n if (this.arity.trailing.length > 0)\n throw new Error(`Infinite lists cannot be declared after the required trailing positional arguments`);\n for (let t = 0; t < required; ++t)\n this.addPositional({ name });\n this.arity.extra = NoLimits;\n }\n addProxy({ required = 0 } = {}) {\n this.addRest({ required });\n this.arity.proxy = true;\n }\n addOption({ names: nameSet, description, arity = 0, hidden = false, required = false, allowBinding = true }) {\n if (!allowBinding && arity > 1)\n throw new Error(`The arity cannot be higher than 1 when the option only supports the --arg=value syntax`);\n if (!Number.isInteger(arity))\n throw new Error(`The arity must be an integer, got ${arity}`);\n if (arity < 0)\n throw new Error(`The arity must be positive, got ${arity}`);\n const preferredName = nameSet.reduce((longestName, name) => {\n return name.length > longestName.length ? name : longestName;\n }, ``);\n for (const name of nameSet)\n this.allOptionNames.set(name, preferredName);\n this.options.push({ preferredName, nameSet, description, arity, hidden, required, allowBinding });\n }\n setContext(context) {\n this.context = context;\n }\n usage({ detailed = true, inlineOptions = true } = {}) {\n const segments = [this.cliOpts.binaryName];\n const detailedOptionList = [];\n if (this.paths.length > 0)\n segments.push(...this.paths[0]);\n if (detailed) {\n for (const { preferredName, nameSet, arity, hidden, description, required } of this.options) {\n if (hidden)\n continue;\n const args = [];\n for (let t = 0; t < arity; ++t)\n args.push(` #${t}`);\n const definition = `${nameSet.join(`,`)}${args.join(``)}`;\n if (!inlineOptions && description) {\n detailedOptionList.push({ preferredName, nameSet, definition, description, required });\n }\n else {\n segments.push(required ? `<${definition}>` : `[${definition}]`);\n }\n }\n segments.push(...this.arity.leading.map(name => `<${name}>`));\n if (this.arity.extra === NoLimits)\n segments.push(`...`);\n else\n segments.push(...this.arity.extra.map(name => `[${name}]`));\n segments.push(...this.arity.trailing.map(name => `<${name}>`));\n }\n const usage = segments.join(` `);\n return { usage, options: detailedOptionList };\n }\n compile() {\n if (typeof this.context === `undefined`)\n throw new Error(`Assertion failed: No context attached`);\n const machine = makeStateMachine();\n let firstNode = NodeType.InitialNode;\n const candidateUsage = this.usage().usage;\n const requiredOptions = this.options\n .filter(opt => opt.required)\n .map(opt => opt.nameSet);\n firstNode = injectNode(machine, makeNode());\n registerStatic(machine, NodeType.InitialNode, SpecialToken.StartOfInput, firstNode, [`setCandidateState`, { candidateUsage, requiredOptions }]);\n const positionalArgument = this.arity.proxy\n ? `always`\n : `isNotOptionLike`;\n const paths = this.paths.length > 0\n ? this.paths\n : [[]];\n for (const path of paths) {\n let lastPathNode = firstNode;\n // We allow options to be specified before the path. Note that we\n // only do this when there is a path, otherwise there would be\n // some redundancy with the options attached later.\n if (path.length > 0) {\n const optionPathNode = injectNode(machine, makeNode());\n registerShortcut(machine, lastPathNode, optionPathNode);\n this.registerOptions(machine, optionPathNode);\n lastPathNode = optionPathNode;\n }\n for (let t = 0; t < path.length; ++t) {\n const nextPathNode = injectNode(machine, makeNode());\n registerStatic(machine, lastPathNode, path[t], nextPathNode, `pushPath`);\n lastPathNode = nextPathNode;\n if (t + 1 < path.length) {\n // Allow to pass `-h` (without anything after it) after each part of a path.\n // Note that we do not do this for the last part, otherwise there would be\n // some redundancy with the `useHelp` attached later.\n const helpNode = injectNode(machine, makeNode());\n registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]);\n registerStatic(machine, helpNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, HELP_COMMAND_INDEX]);\n }\n }\n if (this.arity.leading.length > 0 || !this.arity.proxy) {\n const helpNode = injectNode(machine, makeNode());\n registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]);\n registerDynamic(machine, helpNode, `always`, helpNode, `pushExtra`);\n registerStatic(machine, helpNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, HELP_COMMAND_INDEX]);\n this.registerOptions(machine, lastPathNode);\n }\n if (this.arity.leading.length > 0) {\n registerStatic(machine, lastPathNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, lastPathNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n let lastLeadingNode = lastPathNode;\n for (let t = 0; t < this.arity.leading.length; ++t) {\n const nextLeadingNode = injectNode(machine, makeNode());\n if (!this.arity.proxy || t + 1 !== this.arity.leading.length)\n this.registerOptions(machine, nextLeadingNode);\n if (this.arity.trailing.length > 0 || t + 1 !== this.arity.leading.length) {\n registerStatic(machine, nextLeadingNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, nextLeadingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n registerDynamic(machine, lastLeadingNode, `isNotOptionLike`, nextLeadingNode, `pushPositional`);\n lastLeadingNode = nextLeadingNode;\n }\n let lastExtraNode = lastLeadingNode;\n if (this.arity.extra === NoLimits || this.arity.extra.length > 0) {\n const extraShortcutNode = injectNode(machine, makeNode());\n registerShortcut(machine, lastLeadingNode, extraShortcutNode);\n if (this.arity.extra === NoLimits) {\n const extraNode = injectNode(machine, makeNode());\n if (!this.arity.proxy)\n this.registerOptions(machine, extraNode);\n registerDynamic(machine, lastLeadingNode, positionalArgument, extraNode, `pushExtraNoLimits`);\n registerDynamic(machine, extraNode, positionalArgument, extraNode, `pushExtraNoLimits`);\n registerShortcut(machine, extraNode, extraShortcutNode);\n }\n else {\n for (let t = 0; t < this.arity.extra.length; ++t) {\n const nextExtraNode = injectNode(machine, makeNode());\n if (!this.arity.proxy || t > 0)\n this.registerOptions(machine, nextExtraNode);\n registerDynamic(machine, lastExtraNode, positionalArgument, nextExtraNode, `pushExtra`);\n registerShortcut(machine, nextExtraNode, extraShortcutNode);\n lastExtraNode = nextExtraNode;\n }\n }\n lastExtraNode = extraShortcutNode;\n }\n if (this.arity.trailing.length > 0) {\n registerStatic(machine, lastExtraNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, lastExtraNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n let lastTrailingNode = lastExtraNode;\n for (let t = 0; t < this.arity.trailing.length; ++t) {\n const nextTrailingNode = injectNode(machine, makeNode());\n if (!this.arity.proxy)\n this.registerOptions(machine, nextTrailingNode);\n if (t + 1 < this.arity.trailing.length) {\n registerStatic(machine, nextTrailingNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, nextTrailingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n registerDynamic(machine, lastTrailingNode, `isNotOptionLike`, nextTrailingNode, `pushPositional`);\n lastTrailingNode = nextTrailingNode;\n }\n registerDynamic(machine, lastTrailingNode, positionalArgument, NodeType.ErrorNode, [`setError`, `Extraneous positional argument`]);\n registerStatic(machine, lastTrailingNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n registerStatic(machine, lastTrailingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n return {\n machine,\n context: this.context,\n };\n }\n registerOptions(machine, node) {\n registerDynamic(machine, node, [`isOption`, `--`], node, `inhibateOptions`);\n registerDynamic(machine, node, [`isBatchOption`, this.allOptionNames], node, [`pushBatch`, this.allOptionNames]);\n registerDynamic(machine, node, [`isBoundOption`, this.allOptionNames, this.options], node, `pushBound`);\n registerDynamic(machine, node, [`isUnsupportedOption`, this.allOptionNames], NodeType.ErrorNode, [`setError`, `Unsupported option name`]);\n registerDynamic(machine, node, [`isInvalidOption`], NodeType.ErrorNode, [`setError`, `Invalid option name`]);\n for (const option of this.options) {\n if (option.arity === 0) {\n for (const name of option.nameSet) {\n registerDynamic(machine, node, [`isOption`, name], node, [`pushTrue`, option.preferredName]);\n if (name.startsWith(`--`) && !name.startsWith(`--no-`)) {\n registerDynamic(machine, node, [`isNegatedOption`, name], node, [`pushFalse`, option.preferredName]);\n }\n }\n }\n else {\n // We inject a new node at the end of the state machine\n let lastNode = injectNode(machine, makeNode());\n // We register transitions from the starting node to this new node\n for (const name of option.nameSet)\n registerDynamic(machine, node, [`isOption`, name], lastNode, [`pushUndefined`, option.preferredName]);\n // For each argument, we inject a new node at the end and we\n // register a transition from the current node to this new node\n for (let t = 0; t < option.arity; ++t) {\n const nextNode = injectNode(machine, makeNode());\n // We can provide better errors when another option or EndOfInput is encountered\n registerStatic(machine, lastNode, SpecialToken.EndOfInput, NodeType.ErrorNode, `setOptionArityError`);\n registerStatic(machine, lastNode, SpecialToken.EndOfPartialInput, NodeType.ErrorNode, `setOptionArityError`);\n registerDynamic(machine, lastNode, `isOptionLike`, NodeType.ErrorNode, `setOptionArityError`);\n // If the option has a single argument, no need to store it in an array\n const action = option.arity === 1\n ? `setStringValue`\n : `pushStringValue`;\n registerDynamic(machine, lastNode, `isNotOptionLike`, nextNode, action);\n lastNode = nextNode;\n }\n // In the end, we register a shortcut from\n // the last node back to the starting node\n registerShortcut(machine, lastNode, node);\n }\n }\n }\n}\nclass CliBuilder {\n constructor({ binaryName = `...` } = {}) {\n this.builders = [];\n this.opts = { binaryName };\n }\n static build(cbs, opts = {}) {\n return new CliBuilder(opts).commands(cbs).compile();\n }\n getBuilderByIndex(n) {\n if (!(n >= 0 && n < this.builders.length))\n throw new Error(`Assertion failed: Out-of-bound command index (${n})`);\n return this.builders[n];\n }\n commands(cbs) {\n for (const cb of cbs)\n cb(this.command());\n return this;\n }\n command() {\n const builder = new CommandBuilder(this.builders.length, this.opts);\n this.builders.push(builder);\n return builder;\n }\n compile() {\n const machines = [];\n const contexts = [];\n for (const builder of this.builders) {\n const { machine, context } = builder.compile();\n machines.push(machine);\n contexts.push(context);\n }\n const machine = makeAnyOfMachine(machines);\n simplifyMachine(machine);\n return {\n machine,\n contexts,\n process: (input, { partial } = {}) => {\n const endToken = partial\n ? SpecialToken.EndOfPartialInput\n : SpecialToken.EndOfInput;\n return runMachine(machine, input, { endToken });\n },\n };\n }\n}\n\nexport { CliBuilder, CommandBuilder, NoLimits, aggregateHelpStates, cloneNode, cloneTransition, debug, debugMachine, execute, injectNode, isTerminalNode, makeAnyOfMachine, makeNode, makeStateMachine, reducers, registerDynamic, registerShortcut, registerStatic, runMachineInternal, selectBestState, simplifyMachine, tests, trimSmallerBranches };\n","import { Command } from './Command.mjs';\n\nclass HelpCommand extends Command {\n constructor(contexts) {\n super();\n this.contexts = contexts;\n this.commands = [];\n }\n static from(state, contexts) {\n const command = new HelpCommand(contexts);\n command.path = state.path;\n for (const opt of state.options) {\n switch (opt.name) {\n case `-c`:\n {\n command.commands.push(Number(opt.value));\n }\n break;\n case `-i`:\n {\n command.index = Number(opt.value);\n }\n break;\n }\n }\n return command;\n }\n async execute() {\n let commands = this.commands;\n if (typeof this.index !== `undefined` && this.index >= 0 && this.index < commands.length)\n commands = [commands[this.index]];\n if (commands.length === 0) {\n this.context.stdout.write(this.cli.usage());\n }\n else if (commands.length === 1) {\n this.context.stdout.write(this.cli.usage(this.contexts[commands[0]].commandClass, { detailed: true }));\n }\n else if (commands.length > 1) {\n this.context.stdout.write(`Multiple commands match your selection:\\n`);\n this.context.stdout.write(`\\n`);\n let index = 0;\n for (const command of this.commands)\n this.context.stdout.write(this.cli.usage(this.contexts[command].commandClass, { prefix: `${index++}. `.padStart(5) }));\n this.context.stdout.write(`\\n`);\n this.context.stdout.write(`Run again with -h=<index> to see the longer details of any of those commands.\\n`);\n }\n }\n}\n\nexport { HelpCommand };\n","import { HELP_COMMAND_INDEX } from '../constants.mjs';\nimport { CliBuilder } from '../core.mjs';\nimport { formatMarkdownish, richFormat, textFormat } from '../format.mjs';\nimport { getCaptureActivator, getDefaultColorDepth } from '../platform/node.mjs';\nimport { Command } from './Command.mjs';\nimport { HelpCommand } from './HelpCommand.mjs';\n\nconst errorCommandSymbol = Symbol(`clipanion/errorCommand`);\nasync function runExit(...args) {\n const { resolvedOptions, resolvedCommandClasses, resolvedArgv, resolvedContext, } = resolveRunParameters(args);\n const cli = Cli.from(resolvedCommandClasses, resolvedOptions);\n return cli.runExit(resolvedArgv, resolvedContext);\n}\nasync function run(...args) {\n const { resolvedOptions, resolvedCommandClasses, resolvedArgv, resolvedContext, } = resolveRunParameters(args);\n const cli = Cli.from(resolvedCommandClasses, resolvedOptions);\n return cli.run(resolvedArgv, resolvedContext);\n}\nfunction resolveRunParameters(args) {\n let resolvedOptions;\n let resolvedCommandClasses;\n let resolvedArgv;\n let resolvedContext;\n if (typeof process !== `undefined` && typeof process.argv !== `undefined`)\n resolvedArgv = process.argv.slice(2);\n switch (args.length) {\n case 1:\n {\n resolvedCommandClasses = args[0];\n }\n break;\n case 2:\n {\n if (args[0] && (args[0].prototype instanceof Command) || Array.isArray(args[0])) {\n resolvedCommandClasses = args[0];\n if (Array.isArray(args[1])) {\n resolvedArgv = args[1];\n }\n else {\n resolvedContext = args[1];\n }\n }\n else {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n }\n }\n break;\n case 3:\n {\n if (Array.isArray(args[2])) {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n resolvedArgv = args[2];\n }\n else if (args[0] && (args[0].prototype instanceof Command) || Array.isArray(args[0])) {\n resolvedCommandClasses = args[0];\n resolvedArgv = args[1];\n resolvedContext = args[2];\n }\n else {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n resolvedContext = args[2];\n }\n }\n break;\n default:\n {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n resolvedArgv = args[2];\n resolvedContext = args[3];\n }\n break;\n }\n if (typeof resolvedArgv === `undefined`)\n throw new Error(`The argv parameter must be provided when running Clipanion outside of a Node context`);\n return {\n resolvedOptions,\n resolvedCommandClasses,\n resolvedArgv,\n resolvedContext,\n };\n}\n/**\n * @template Context The context shared by all commands. Contexts are a set of values, defined when calling the `run`/`runExit` functions from the CLI instance, that will be made available to the commands via `this.context`.\n */\nclass Cli {\n constructor({ binaryLabel, binaryName: binaryNameOpt = `...`, binaryVersion, enableCapture = false, enableColors } = {}) {\n this.registrations = new Map();\n this.builder = new CliBuilder({ binaryName: binaryNameOpt });\n this.binaryLabel = binaryLabel;\n this.binaryName = binaryNameOpt;\n this.binaryVersion = binaryVersion;\n this.enableCapture = enableCapture;\n this.enableColors = enableColors;\n }\n /**\n * Creates a new Cli and registers all commands passed as parameters.\n *\n * @param commandClasses The Commands to register\n * @returns The created `Cli` instance\n */\n static from(commandClasses, options = {}) {\n const cli = new Cli(options);\n const resolvedCommandClasses = Array.isArray(commandClasses)\n ? commandClasses\n : [commandClasses];\n for (const commandClass of resolvedCommandClasses)\n cli.register(commandClass);\n return cli;\n }\n /**\n * Registers a command inside the CLI.\n */\n register(commandClass) {\n var _a;\n const specs = new Map();\n const command = new commandClass();\n for (const key in command) {\n const value = command[key];\n if (typeof value === `object` && value !== null && value[Command.isOption]) {\n specs.set(key, value);\n }\n }\n const builder = this.builder.command();\n const index = builder.cliIndex;\n const paths = (_a = commandClass.paths) !== null && _a !== void 0 ? _a : command.paths;\n if (typeof paths !== `undefined`)\n for (const path of paths)\n builder.addPath(path);\n this.registrations.set(commandClass, { specs, builder, index });\n for (const [key, { definition }] of specs.entries())\n definition(builder, key);\n builder.setContext({\n commandClass,\n });\n }\n process(opts, contextArg) {\n const { input, context: userContext, partial } = typeof opts === `object` && Array.isArray(opts)\n ? { input: opts, context: contextArg }\n : opts;\n const { contexts, process } = this.builder.compile();\n const state = process(input, { partial });\n const context = {\n ...Cli.defaultContext,\n ...userContext,\n };\n switch (state.selectedIndex) {\n case HELP_COMMAND_INDEX:\n {\n const command = HelpCommand.from(state, contexts);\n command.context = context;\n command.tokens = state.tokens;\n return command;\n }\n default:\n {\n const { commandClass } = contexts[state.selectedIndex];\n const record = this.registrations.get(commandClass);\n if (typeof record === `undefined`)\n throw new Error(`Assertion failed: Expected the command class to have been registered.`);\n const command = new commandClass();\n command.context = context;\n command.tokens = state.tokens;\n command.path = state.path;\n try {\n for (const [key, { transformer }] of record.specs.entries())\n command[key] = transformer(record.builder, key, state, context);\n return command;\n }\n catch (error) {\n error[errorCommandSymbol] = command;\n throw error;\n }\n }\n break;\n }\n }\n async run(input, userContext) {\n var _a, _b;\n let command;\n const context = {\n ...Cli.defaultContext,\n ...userContext,\n };\n const colored = (_a = this.enableColors) !== null && _a !== void 0 ? _a : context.colorDepth > 1;\n if (!Array.isArray(input)) {\n command = input;\n }\n else {\n try {\n command = this.process(input, context);\n }\n catch (error) {\n context.stdout.write(this.error(error, { colored }));\n return 1;\n }\n }\n if (command.help) {\n context.stdout.write(this.usage(command, { colored, detailed: true }));\n return 0;\n }\n command.context = context;\n command.cli = {\n binaryLabel: this.binaryLabel,\n binaryName: this.binaryName,\n binaryVersion: this.binaryVersion,\n enableCapture: this.enableCapture,\n enableColors: this.enableColors,\n definitions: () => this.definitions(),\n definition: command => this.definition(command),\n error: (error, opts) => this.error(error, opts),\n format: colored => this.format(colored),\n process: (input, subContext) => this.process(input, { ...context, ...subContext }),\n run: (input, subContext) => this.run(input, { ...context, ...subContext }),\n usage: (command, opts) => this.usage(command, opts),\n };\n const activate = this.enableCapture\n ? (_b = getCaptureActivator(context)) !== null && _b !== void 0 ? _b : noopCaptureActivator\n : noopCaptureActivator;\n let exitCode;\n try {\n exitCode = await activate(() => command.validateAndExecute().catch(error => command.catch(error).then(() => 0)));\n }\n catch (error) {\n context.stdout.write(this.error(error, { colored, command }));\n return 1;\n }\n return exitCode;\n }\n async runExit(input, context) {\n process.exitCode = await this.run(input, context);\n }\n definition(commandClass, { colored = false } = {}) {\n if (!commandClass.usage)\n return null;\n const { usage: path } = this.getUsageByRegistration(commandClass, { detailed: false });\n const { usage, options } = this.getUsageByRegistration(commandClass, { detailed: true, inlineOptions: false });\n const category = typeof commandClass.usage.category !== `undefined`\n ? formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false })\n : undefined;\n const description = typeof commandClass.usage.description !== `undefined`\n ? formatMarkdownish(commandClass.usage.description, { format: this.format(colored), paragraphs: false })\n : undefined;\n const details = typeof commandClass.usage.details !== `undefined`\n ? formatMarkdownish(commandClass.usage.details, { format: this.format(colored), paragraphs: true })\n : undefined;\n const examples = typeof commandClass.usage.examples !== `undefined`\n ? commandClass.usage.examples.map(([label, cli]) => [formatMarkdownish(label, { format: this.format(colored), paragraphs: false }), cli.replace(/\\$0/g, this.binaryName)])\n : undefined;\n return { path, usage, category, description, details, examples, options };\n }\n definitions({ colored = false } = {}) {\n const data = [];\n for (const commandClass of this.registrations.keys()) {\n const usage = this.definition(commandClass, { colored });\n if (!usage)\n continue;\n data.push(usage);\n }\n return data;\n }\n usage(command = null, { colored, detailed = false, prefix = `$ ` } = {}) {\n var _a;\n // In case the default command is the only one, we can just show the command help rather than the general one\n if (command === null) {\n for (const commandClass of this.registrations.keys()) {\n const paths = commandClass.paths;\n const isDocumented = typeof commandClass.usage !== `undefined`;\n const isExclusivelyDefault = !paths || paths.length === 0 || (paths.length === 1 && paths[0].length === 0);\n const isDefault = isExclusivelyDefault || ((_a = paths === null || paths === void 0 ? void 0 : paths.some(path => path.length === 0)) !== null && _a !== void 0 ? _a : false);\n if (isDefault) {\n if (command) {\n command = null;\n break;\n }\n else {\n command = commandClass;\n }\n }\n else {\n if (isDocumented) {\n command = null;\n continue;\n }\n }\n }\n if (command) {\n detailed = true;\n }\n }\n // @ts-ignore\n const commandClass = command !== null && command instanceof Command\n ? command.constructor\n : command;\n let result = ``;\n if (!commandClass) {\n const commandsByCategories = new Map();\n for (const [commandClass, { index }] of this.registrations.entries()) {\n if (typeof commandClass.usage === `undefined`)\n continue;\n const category = typeof commandClass.usage.category !== `undefined`\n ? formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false })\n : null;\n let categoryCommands = commandsByCategories.get(category);\n if (typeof categoryCommands === `undefined`)\n commandsByCategories.set(category, categoryCommands = []);\n const { usage } = this.getUsageByIndex(index);\n categoryCommands.push({ commandClass, usage });\n }\n const categoryNames = Array.from(commandsByCategories.keys()).sort((a, b) => {\n if (a === null)\n return -1;\n if (b === null)\n return +1;\n return a.localeCompare(b, `en`, { usage: `sort`, caseFirst: `upper` });\n });\n const hasLabel = typeof this.binaryLabel !== `undefined`;\n const hasVersion = typeof this.binaryVersion !== `undefined`;\n if (hasLabel || hasVersion) {\n if (hasLabel && hasVersion)\n result += `${this.format(colored).header(`${this.binaryLabel} - ${this.binaryVersion}`)}\\n\\n`;\n else if (hasLabel)\n result += `${this.format(colored).header(`${this.binaryLabel}`)}\\n`;\n else\n result += `${this.format(colored).header(`${this.binaryVersion}`)}\\n`;\n result += ` ${this.format(colored).bold(prefix)}${this.binaryName} <command>\\n`;\n }\n else {\n result += `${this.format(colored).bold(prefix)}${this.binaryName} <command>\\n`;\n }\n for (const categoryName of categoryNames) {\n const commands = commandsByCategories.get(categoryName).slice().sort((a, b) => {\n return a.usage.localeCompare(b.usage, `en`, { usage: `sort`, caseFirst: `upper` });\n });\n const header = categoryName !== null\n ? categoryName.trim()\n : `General commands`;\n result += `\\n`;\n result += `${this.format(colored).header(`${header}`)}\\n`;\n for (const { commandClass, usage } of commands) {\n const doc = commandClass.usage.description || `undocumented`;\n result += `\\n`;\n result += ` ${this.format(colored).bold(usage)}\\n`;\n result += ` ${formatMarkdownish(doc, { format: this.format(colored), paragraphs: false })}`;\n }\n }\n result += `\\n`;\n result += formatMarkdownish(`You can also print more details about any of these commands by calling them with the \\`-h,--help\\` flag right after the command name.`, { format: this.format(colored), paragraphs: true });\n }\n else {\n if (!detailed) {\n const { usage } = this.getUsageByRegistration(commandClass);\n result += `${this.format(colored).bold(prefix)}${usage}\\n`;\n }\n else {\n const { description = ``, details = ``, examples = [], } = commandClass.usage || {};\n if (description !== ``) {\n result += formatMarkdownish(description, { format: this.format(colored), paragraphs: false }).replace(/^./, $0 => $0.toUpperCase());\n result += `\\n`;\n }\n if (details !== `` || examples.length > 0) {\n result += `${this.format(colored).header(`Usage`)}\\n`;\n result += `\\n`;\n }\n const { usage, options } = this.getUsageByRegistration(commandClass, { inlineOptions: false });\n result += `${this.format(colored).bold(prefix)}${usage}\\n`;\n if (options.length > 0) {\n result += `\\n`;\n result += `${this.format(colored).header(`Options`)}\\n`;\n const maxDefinitionLength = options.reduce((length, option) => {\n return Math.max(length, option.definition.length);\n }, 0);\n result += `\\n`;\n for (const { definition, description } of options) {\n result += ` ${this.format(colored).bold(definition.padEnd(maxDefinitionLength))} ${formatMarkdownish(description, { format: this.format(colored), paragraphs: false })}`;\n }\n }\n if (details !== ``) {\n result += `\\n`;\n result += `${this.format(colored).header(`Details`)}\\n`;\n result += `\\n`;\n result += formatMarkdownish(details, { format: this.format(colored), paragraphs: true });\n }\n if (examples.length > 0) {\n result += `\\n`;\n result += `${this.format(colored).header(`Examples`)}\\n`;\n for (const [description, example] of examples) {\n result += `\\n`;\n result += formatMarkdownish(description, { format: this.format(colored), paragraphs: false });\n result += `${example\n .replace(/^/m, ` ${this.format(colored).bold(prefix)}`)\n .replace(/\\$0/g, this.binaryName)}\\n`;\n }\n }\n }\n }\n return result;\n }\n error(error, _a) {\n var _b;\n var { colored, command = (_b = error[errorCommandSymbol]) !== null && _b !== void 0 ? _b : null } = _a === void 0 ? {} : _a;\n if (!error || typeof error !== `object` || !(`stack` in error))\n error = new Error(`Execution failed with a non-error rejection (rejected value: ${JSON.stringify(error)})`);\n let result = ``;\n let name = error.name.replace(/([a-z])([A-Z])/g, `$1 $2`);\n if (name === `Error`)\n name = `Internal Error`;\n result += `${this.format(colored).error(name)}: ${error.message}\\n`;\n const meta = error.clipanion;\n if (typeof meta !== `undefined`) {\n if (meta.type === `usage`) {\n result += `\\n`;\n result += this.usage(command);\n }\n }\n else {\n if (error.stack) {\n result += `${error.stack.replace(/^.*\\n/, ``)}\\n`;\n }\n }\n return result;\n }\n format(colored) {\n var _a;\n return ((_a = colored !== null && colored !== void 0 ? colored : this.enableColors) !== null && _a !== void 0 ? _a : Cli.defaultContext.colorDepth > 1) ? richFormat : textFormat;\n }\n getUsageByRegistration(klass, opts) {\n const record = this.registrations.get(klass);\n if (typeof record === `undefined`)\n throw new Error(`Assertion failed: Unregistered command`);\n return this.getUsageByIndex(record.index, opts);\n }\n getUsageByIndex(n, opts) {\n return this.builder.getBuilderByIndex(n).usage(opts);\n }\n}\n/**\n * The default context of the CLI.\n *\n * Contains the stdio of the current `process`.\n */\nCli.defaultContext = {\n env: process.env,\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n colorDepth: getDefaultColorDepth(),\n};\nfunction noopCaptureActivator(fn) {\n return fn();\n}\n\nexport { Cli, run, runExit };\n","function getDefaultColorDepth() {\n return 1;\n}\nfunction getCaptureActivator() {\n throw new Error(`The enableCapture option cannot be used from within a browser environment`);\n}\n\nexport { getCaptureActivator, getDefaultColorDepth };\n","import { makeCommandOption, rerouteArguments } from './utils.mjs';\n\nfunction Boolean(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n allowBinding: false,\n arity: 0,\n hidden: opts.hidden,\n description: opts.description,\n required: opts.required,\n });\n },\n transformer(builer, key, state) {\n let currentValue = initialValue;\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n currentValue = value;\n }\n return currentValue;\n },\n });\n}\n\nexport { Boolean };\n","import { NoLimits } from '../../core.mjs';\nimport { makeCommandOption, applyValidator, rerouteArguments } from './utils.mjs';\n\nfunction StringOption(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const { arity = 1 } = opts;\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n arity: opts.tolerateBoolean ? 0 : arity,\n hidden: opts.hidden,\n description: opts.description,\n required: opts.required,\n });\n },\n transformer(builder, key, state, context) {\n let usedName;\n let currentValue = initialValue;\n if (typeof opts.env !== `undefined` && context.env[opts.env]) {\n usedName = opts.env;\n currentValue = context.env[opts.env];\n }\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n usedName = name;\n currentValue = value;\n }\n if (typeof currentValue === `string`) {\n return applyValidator(usedName !== null && usedName !== void 0 ? usedName : key, currentValue, opts.validator);\n }\n else {\n return currentValue;\n }\n },\n });\n}\nfunction StringPositional(opts = {}) {\n const { required = true } = opts;\n return makeCommandOption({\n definition(builder, key) {\n var _a;\n builder.addPositional({\n name: (_a = opts.name) !== null && _a !== void 0 ? _a : key,\n required: opts.required,\n });\n },\n transformer(builder, key, state) {\n var _a;\n for (let i = 0; i < state.positionals.length; ++i) {\n // We skip NoLimits extras. We only care about\n // required and optional finite positionals.\n if (state.positionals[i].extra === NoLimits)\n continue;\n // We skip optional positionals when we only\n // care about required positionals.\n if (required && state.positionals[i].extra === true)\n continue;\n // We skip required positionals when we only\n // care about optional positionals.\n if (!required && state.positionals[i].extra === false)\n continue;\n // We remove the positional from the list\n const [positional] = state.positionals.splice(i, 1);\n return applyValidator((_a = opts.name) !== null && _a !== void 0 ? _a : key, positional.value, opts.validator);\n }\n return undefined;\n },\n });\n}\n// This function is badly typed, but it doesn't matter because the overloads provide the true public typings\nfunction String(descriptor, ...args) {\n if (typeof descriptor === `string`) {\n return StringOption(descriptor, ...args);\n }\n else {\n return StringPositional(descriptor);\n }\n}\n\nexport { String };\n","export const enum TadaErrorCode {\n VUE_SUPPORT,\n SVELTE_SUPPORT,\n UNKNOWN_EXTERNAL_FILE,\n}\n\nexport class TadaError extends Error {\n static isTadaError(error: unknown): error is TadaError {\n return !!(typeof error === 'object' && error && 'name' in error && error.name === 'TadaError');\n }\n\n readonly code: TadaErrorCode;\n constructor(code: TadaErrorCode, message: string) {\n super(message);\n this.code = code;\n this.name = 'TadaError';\n }\n}\n\nexport const exitCode = () => {\n const { exitCode } = process;\n return typeof exitCode === 'string' ? parseInt(exitCode, 10) || 0 : exitCode;\n};\n","let hasColor = false;\n\nexport function _setColor(color: boolean) {\n hasColor = color;\n}\n\n// See: http://xtermjs.org/docs/api/vtfeatures/#csi\nconst enum CSI {\n InsertChars = '@',\n ScrollLeft = 'SP@',\n Up = 'A',\n ScrollRight = 'SPA',\n Down = 'B',\n Forward = 'C',\n Backward = 'D',\n NextLine = 'E',\n PrevLine = 'F',\n ToColumn = 'G',\n ToPosition = 'H',\n Tab = 'I',\n Erase = 'J',\n EraseLine = 'K',\n InsertLines = 'L',\n DeleteLines = 'M',\n DeleteChars = 'P',\n ScrollUp = 'S',\n ScrollDown = 'T',\n EraseChars = 'X',\n TabBackwards = 'Z',\n RepeatChar = 'b',\n ToRow = 'd',\n DownLine = 'e',\n TabClear = 'g',\n SetMode = 'h',\n UnsetMode = 'l',\n SetPrivateMode = '?h',\n UnsetPrivateMode = '?l',\n ResetPrivateMode = '?r',\n Style = 'm',\n Reset = '!p',\n Protect = '\"q',\n Cursor = 'SPq',\n SetMargin = 'r',\n SaveCursor = 's',\n RestoreCursor = 'u',\n InsertColumns = \"'}\",\n DeleteColumns = \"'~\",\n}\n\nconst enum TabClear {\n Current = 0,\n All = 3,\n}\n\nconst enum Erase {\n Forward = 0,\n Backward = 1,\n All = 2,\n Scrollback = 3,\n}\n\nconst enum EraseLine {\n Forward = 0,\n Backward = 1,\n All = 2,\n}\n\nconst enum Protect {\n Insert = 4,\n AutomaticNewline = 20,\n}\n\nconst enum Mode {\n Insert = 4,\n AutomaticNewline = 20,\n}\n\nconst enum PrivateMode {\n AppCursorKeys = 1,\n USASCII = 2,\n Column132 = 3,\n OriginMode = 6,\n AutoWrap = 7,\n AutoRepeat = 8,\n X10Mouse = 9,\n BlinkCursor = 12,\n ShowCursor = 25,\n ReverseWrapAround = 45,\n AlternativeScreenBuffer = 47,\n AppKeypad = 66,\n X11Mouse = 1000,\n CellMotionMouseTracking = 1002,\n AllMotionMouseTracking = 1003,\n FocusEvents = 1004,\n Utf8Mouse = 1005,\n SGRMouse = 1006,\n UrxvtMouse = 1015,\n SGRPixelsMouse = 1016,\n SaveCursor = 1048,\n BracketedPaste = 2004,\n}\n\nconst enum Cursor {\n Empty = 0,\n Block = 1,\n BlinkBlock = 2,\n Underline = 3,\n BlinkUnderline = 4,\n Bar = 5,\n BlinkBar = 6,\n}\n\nconst enum Style {\n Reset = 0,\n Bold = 1,\n Faint = 2,\n Italic = 3,\n Underline = 4,\n Blink = 5,\n RapidBlink = 6,\n Invert = 7,\n Invisible = 8,\n Strikethrough = 9,\n DoubleUnderlined = 21,\n Normal = 22, // No Bold, No Faint\n NoItalic = 23,\n NoUnderline = 24,\n NoBlink = 25,\n NoInvert = 27,\n Visible = 28,\n NoStrikethrough = 29,\n\n Black = 30,\n Red = 31,\n Green = 32,\n Yellow = 33,\n Blue = 34,\n Magenta = 35,\n Cyan = 36,\n White = 37,\n Foreground = 39,\n\n OnBlack = 40,\n OnRed = 41,\n OnGreen = 42,\n OnYellow = 43,\n OnBlue = 44,\n OnMagenta = 45,\n OnCyan = 46,\n OnWhite = 47,\n OnBackground = 49,\n\n BrightBlack = 90,\n BrightRed = 91,\n BrightGreen = 92,\n BrightYellow = 93,\n BrightBlue = 94,\n BrightMagenta = 95,\n BrightCyan = 96,\n BrightWhite = 97,\n\n OnBrightBlack = 100,\n OnBrightRed = 101,\n OnBrightGreen = 102,\n OnBrightYellow = 103,\n OnBrightBlue = 104,\n OnBrightMagenta = 105,\n OnBrightCyan = 106,\n OnBrightWhite = 107,\n\n DoubleUnderline = '4:2',\n CurlyUnderline = '4:3',\n DottedUnderline = '4:4',\n DashedUnderline = '4:5',\n}\n\ntype escapeCSI = '\\x1B[';\nconst escapeCSI = '\\x1B[';\n\ntype CommandNoParam = CSI.Reset | CSI.SaveCursor | CSI.RestoreCursor | CSI.ResetPrivateMode;\n\ntype CommandSingleParam =\n | CSI.ScrollLeft\n | CSI.ScrollRight\n | CSI.ScrollUp\n | CSI.ScrollDown\n | CSI.Up\n | CSI.Down\n | CSI.Backward\n | CSI.Forward\n | CSI.PrevLine\n | CSI.NextLine\n | CSI.DownLine\n | CSI.ToColumn\n | CSI.ToRow\n | CSI.Tab\n | CSI.TabBackwards\n | CSI.InsertChars\n | CSI.InsertLines\n | CSI.InsertColumns\n | CSI.DeleteChars\n | CSI.DeleteLines\n | CSI.DeleteColumns\n | CSI.RepeatChar;\n\ntype CommandParam =\n | number\n | TabClear\n | Erase\n | EraseLine\n | Protect\n | Cursor\n | Mode\n | PrivateMode\n | Style\n | readonly Mode[]\n | readonly PrivateMode[]\n | readonly Style[];\n\nfunction cmd(code: CommandNoParam): `${escapeCSI}${CommandNoParam}`;\nfunction cmd(\n code: CommandSingleParam,\n count?: number\n): `${escapeCSI}${number}${CommandSingleParam}`;\nfunction cmd(code: CSI.TabClear, mode?: TabClear): `${escapeCSI}${TabClear}${CSI.TabClear}`;\nfunction cmd(code: CSI.Erase, mode?: Erase): `${escapeCSI}${Erase}${CSI.Erase}`;\nfunction cmd(code: CSI.EraseLine, mode?: EraseLine): `${escapeCSI}${EraseLine}${CSI.EraseLine}`;\nfunction cmd(code: CSI.Protect, mode?: Protect): `${escapeCSI}${Protect}${CSI.Protect}`;\nfunction cmd(code: CSI.Cursor, style: Cursor): `${escapeCSI}${Cursor}${CSI.Cursor}`;\n\nfunction cmd(\n code: CSI.ToPosition,\n row: number,\n column: number\n): `${escapeCSI}${number};${number}${CSI.ToPosition}`;\n\nfunction cmd(\n code: CSI.SetMargin,\n top: number,\n bottom: number\n): `${escapeCSI}${number};${number}${CSI.SetMargin}`;\n\nfunction cmd(code: CSI.SetMode, modes: Mode | readonly Mode[]): `${escapeCSI}${Mode}${CSI.SetMode}`;\n\nfunction cmd(\n code: CSI.SetPrivateMode,\n modes: PrivateMode | readonly PrivateMode[]\n): `${escapeCSI}?${PrivateMode}${CSI.SetMode}`;\n\nfunction cmd(\n code: CSI.UnsetMode,\n modes: Mode | readonly Mode[]\n): `${escapeCSI}${Mode}${CSI.UnsetMode}`;\n\nfunction cmd(\n code: CSI.UnsetPrivateMode,\n modes: PrivateMode | readonly PrivateMode[]\n): `${escapeCSI}?${PrivateMode}${CSI.UnsetMode}`;\n\nfunction cmd(code: CSI.Style, styles: Style | readonly Style[]): `${escapeCSI}${Style}${CSI.Style}`;\n\nfunction cmd(code: CSI, a?: CommandParam, b?: number): cmdCode {\n if (!hasColor && code === CSI.Style) return '';\n let out = escapeCSI;\n if (code === CSI.SetPrivateMode) {\n out += '?';\n code = CSI.SetMode;\n } else if (code === CSI.UnsetPrivateMode) {\n out += '?';\n code = CSI.UnsetMode;\n }\n if (Array.isArray(a)) {\n out += a.join(';');\n } else if (a != null) {\n out += `${a}`;\n if (b != null) out += `;${b}`;\n }\n out += code;\n return out as cmdCode;\n}\n\nexport type cmdCode = `${escapeCSI}${string}${CSI}` | '';\n\nexport { cmd, CSI, TabClear, Erase, EraseLine, Protect, Mode, PrivateMode, Cursor, Style };\n","import type { Source } from 'wonka';\n\nimport {\n pipe,\n fromAsyncIterable,\n fromValue,\n concatMap,\n never,\n merge,\n takeUntil,\n takeLast,\n filter,\n share,\n scan,\n map,\n} from 'wonka';\n\nimport { cmd, CSI, EraseLine, Style } from './csi';\n\nconst ansiRegex = /([\\x1B\\x9B][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><])/g;\n\nexport const stripAnsi = (input: string) => input.replace(ansiRegex, '');\n\nexport class CLIError extends Error {\n output: string;\n exit: number;\n constructor(message: string, exitCode?: number) {\n super(stripAnsi(message));\n this.output = message;\n this.exit = exitCode != null ? exitCode : 1;\n }\n\n toString() {\n return this.output;\n }\n}\n\nfunction text(input: readonly string[], ...args: readonly string[]): string;\nfunction text(...input: readonly string[]): string;\n\nfunction text(input: string | readonly string[], ...args: readonly string[]): string {\n let out = '';\n if (Array.isArray(input)) {\n let argIndex = 0;\n for (let index = 0; index < input.length; index++) {\n out += input[index];\n if (argIndex < args.length) out += args[argIndex++];\n }\n } else if (typeof input === 'string') {\n out += input;\n for (const arg of args) out += arg;\n }\n return out;\n}\n\nfunction error(input: readonly string[], ...args: readonly string[]): CLIError;\nfunction error(arg: string | number, ...input: readonly string[]): CLIError;\nfunction error(...input: readonly string[]): CLIError;\n\nfunction error(arg: readonly string[] | string | number, ...input: readonly string[]): CLIError {\n return typeof arg === 'number'\n ? new CLIError(text(...input), arg)\n : new CLIError(text(arg as string, ...input));\n}\n\nfunction clear(text: string) {\n let lines = 0;\n for (let index = 0; index < text.length; index++)\n if (text.charCodeAt(index) === 10 /*'\\n'*/) lines++;\n if (lines) {\n return cmd(CSI.PrevLine, lines) + cmd(CSI.DeleteLines, lines + 1);\n } else if (stripAnsi(text)) {\n return cmd(CSI.EraseLine, EraseLine.Backward) + cmd(CSI.ToColumn, 1);\n } else {\n return '';\n }\n}\n\ntype ComposeInput = undefined | string | CLIError | Source<string> | AsyncIterable<ComposeInput>;\n\nasync function* convertError(outputs: AsyncIterable<ComposeInput>): AsyncIterable<ComposeInput> {\n try {\n yield* outputs;\n } catch (error) {\n if (error instanceof CLIError) {\n process.exitCode = error.exit;\n yield error;\n } else {\n yield ('' + error).trim();\n }\n }\n\n yield '\\n';\n}\n\nfunction compose(outputs: AsyncIterable<ComposeInput>): Source<string | CLIError> {\n const reset = cmd(CSI.Style, [Style.Reset, Style.NoInvert]);\n const outputs$ = pipe(\n fromAsyncIterable(convertError(outputs)),\n concatMap((output) => {\n return typeof output === 'object' && !(output instanceof CLIError)\n ? compose(output)\n : fromValue(output);\n }),\n filter(<T>(x: T): x is Exclude<T, undefined> => x != null),\n share\n );\n\n return pipe(\n outputs$,\n concatMap((output) => {\n const output$ = pipe(\n typeof output === 'string' || output instanceof CLIError\n ? fromValue(output)\n : merge([output, never]),\n takeUntil(outputs$),\n share\n );\n return pipe(\n merge([\n pipe(\n output$,\n takeLast(1),\n map((output) => (typeof output === 'string' && !output.endsWith('\\n') ? '' : output))\n ),\n output$,\n ]),\n scan((prev: CLIError | string, output) => {\n return typeof output === 'string'\n ? clear(typeof prev === 'string' ? prev : '') + output + reset\n : output;\n }, '')\n );\n }),\n takeUntil(pipe(outputs$, takeLast(1)))\n );\n}\n\nexport type { ComposeInput };\nexport { text, error, compose, clear };\n","export const enum Chars {\n Bell = '\\x07',\n Newline = '\\x0a',\n Tab = '\\x09',\n Space = ' ',\n Ellipsis = '…',\n}\n\nexport const enum Box {\n TopLeft = '┌',\n TopRight = '┐',\n BottomLeft = '└',\n BottomRight = '┘',\n Vertical = '│',\n VerticalRight = '├',\n VerticalLeft = '┤',\n Horizontal = '─',\n HorizontalDown = '┬',\n HorizontalUp = '┴',\n Cross = '┼',\n}\n\nexport const enum HeavyBox {\n TopLeft = '┏',\n TopRight = '┓',\n BottomLeft = '┗',\n BottomRight = '┛',\n Vertical = '┃',\n VerticalRight = '┣',\n VerticalLeft = '┫',\n Horizontal = '━',\n HorizontalDown = '┳',\n HorizontalUp = '┻',\n Cross = '╋',\n}\n\nexport const enum DoubleBox {\n TopLeft = '╔',\n TopRight = '╗',\n BottomLeft = '╚',\n BottomRight = '╝',\n Vertical = '║',\n VerticalRight = '╠',\n VerticalLeft = '╣',\n Horizontal = '═',\n HorizontalDown = '╦',\n HorizontalUp = '╩',\n Cross = '╬',\n}\n\nexport enum RoundedBox {\n TopLeft = '╭',\n TopRight = '╮',\n BottomLeft = '╰',\n BottomRight = '╯',\n Vertical = '│',\n VerticalRight = '├',\n VerticalLeft = '┤',\n Horizontal = '─',\n HorizontalDown = '┬',\n HorizontalUp = '┴',\n Cross = '┼',\n}\n\nexport const enum Arrow {\n Right = '→',\n Left = '←',\n Up = '↑',\n Down = '↓',\n LeftRight = '↔',\n UpDown = '↕',\n}\n\nexport const enum Triangle {\n Right = '▶',\n Left = '◀',\n Up = '▲',\n Down = '▼',\n}\n\nexport const enum SmallTriangle {\n Right = '▸',\n Left = '◂',\n Up = '▴',\n Down = '▾',\n}\n\nexport const enum Line {\n DiagonalCross = '╳',\n Diagonalbackwards = '╲',\n Diagonal = '╱',\n VerticalDashed = '┆',\n VerticalDashedHeavy = '┇',\n Vertical = '│',\n VerticalHeavy = '┃',\n HorizontalDashed = '┄',\n HorizontalDashedHeavy = '┅',\n Horizontal = '─',\n HorizontalHeavy = '━',\n}\n\nexport const enum Circle {\n Filled = '●',\n Outline = '◯',\n OutlineFilled = '◉',\n Dotted = '◌',\n Doubled = '◎',\n Small = '•',\n HalfLeft = '◐',\n HalfTop = '◓',\n HalfRight = '◑',\n HalfBottom = '◒',\n}\n\nexport const enum Chevron {\n Default = '',\n Small = '›',\n Heavy = '❯',\n}\n\nexport const enum Diamond {\n Default = '◆',\n Outline = '◇',\n}\n\nexport const enum Square {\n Default = '■',\n Outline = '☐',\n Crossed = '☒',\n}\n\nexport const enum Heart {\n Default = '❤︎',\n Outline = '♥',\n}\n\nexport const enum Icons {\n Tick = '✓',\n TickSwoosh = '✔',\n Cross = '✖',\n CrossSwoosh = '✘',\n Home = '⌂',\n Note = '♪',\n Warning = '⚠',\n Info = 'ℹ',\n Star = '★',\n}\n\nexport const enum Shade {\n Light = '░',\n Medium = '▒',\n Heavy = '▓',\n}\n\nexport const dotSpinner = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\nexport const circleSpinner = ['◐', '◓', '◑', '◒'];\n","export const isGithubCI = !!process.env.GITHUB_ACTIONS;\n\nexport interface AnnotationProperties {\n title?: string;\n file?: string;\n line?: number;\n endLine?: number;\n col?: number;\n endColumn?: number;\n}\n\nconst toCommandValue = (input: unknown): string =>\n typeof input == 'string' || input == null\n ? '' + (input ? '' + input : '')\n : JSON.stringify(input);\n\nconst escapeData = (input: unknown) =>\n toCommandValue(input).replace(/%/g, '%25').replace(/\\r/g, '%0D').replace(/\\n/g, '%0A');\n\nconst escapeProperty = (input: unknown): string =>\n toCommandValue(input)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C');\n\nexport function githubAnnotation(\n kind: 'error' | 'warning' | 'notice',\n message: string,\n properties?: AnnotationProperties\n) {\n if (isGithubCI) {\n let out = `::${kind}`;\n let propsOut = '';\n if (properties) {\n for (const key in properties) {\n if (properties) propsOut += ',';\n if (properties[key]) propsOut += `${key}=${escapeProperty(properties[key])}`;\n }\n }\n if (propsOut) out += ` ${propsOut}`;\n out += `::${escapeData(message)}\\n`;\n process.stdout.write(out);\n }\n}\n","import {\n fromValue,\n make,\n concat,\n pipe,\n filter,\n share,\n takeUntil,\n toPromise,\n onPush,\n onStart,\n onEnd,\n} from 'wonka';\n\nimport type { Source } from 'wonka';\nimport type { WriteStream, ReadStream } from 'node:tty';\nimport { emitKeypressEvents } from 'node:readline';\n\nimport type { ComposeInput, CLIError } from './write';\nimport { text, compose } from './write';\nimport { cmd, _setColor, CSI, Mode, PrivateMode } from './csi';\nimport { isGithubCI } from './github';\n\nexport interface TTYParams {\n disableTTY?: boolean;\n}\n\nexport interface KeypressEvent {\n data?: string;\n sequence: string;\n name: string;\n ctrl: boolean;\n meta: boolean;\n shift: boolean;\n}\n\nexport interface TTY {\n isInteractive: boolean;\n\n output: WriteStream;\n pipeTo: WriteStream | null;\n inputSource: Source<KeypressEvent>;\n cancelSource: Source<unknown>;\n\n write(input: readonly string[], ...args: readonly string[]): void;\n write(...input: readonly string[]): void;\n\n start(outputs: AsyncIterable<ComposeInput>, disableInput?: boolean): Promise<string | CLIError>;\n\n mode(...modes: readonly (Mode | PrivateMode)[]): void;\n modeOff(...modes: readonly (Mode | PrivateMode)[]): void;\n}\n\nfunction fromReadStream(stream: ReadStream): Source<KeypressEvent> {\n return make((observer) => {\n function onKeypress(data: string | undefined, event: KeypressEvent) {\n switch (event.name) {\n case 'c':\n case 'd':\n case 'x':\n if (event.ctrl) cleanup();\n case 'escape':\n cleanup();\n default:\n observer.next({ ...event, data });\n }\n }\n\n function cleanup() {\n if (stream.isTTY) stream.setRawMode(false);\n observer.complete();\n stream.removeListener('keypress', onKeypress);\n stream.unref();\n }\n\n if (stream.isTTY) stream.setRawMode(true);\n emitKeypressEvents(stream);\n stream.setEncoding('utf8');\n stream.resume();\n stream.addListener('keypress', onKeypress);\n return cleanup;\n });\n}\n\nexport function initTTY(params: TTYParams = {}): TTY {\n let isTTY = process.env.TERM !== 'dumb' && !process.env.CI && !params.disableTTY;\n let pipeTo: WriteStream | null = null;\n let output: WriteStream = process.stdout;\n if (isGithubCI) {\n output = process.stderr;\n } else if (!output.isTTY && process.stderr.isTTY) {\n output = process.stderr;\n pipeTo = process.stdout;\n } else {\n isTTY = output.isTTY;\n }\n\n const hasColorArg = process.argv.includes('--color');\n const hasColorEnv = 'FORCE_COLOR' in process.env || (!process.env.NO_COLOR && !process.env.CI);\n _setColor((isTTY && hasColorEnv) || hasColorArg || isGithubCI);\n\n function _start() {\n _setColor((isTTY && hasColorEnv) || hasColorArg);\n if (isTTY) {\n output.write(cmd(CSI.UnsetPrivateMode, PrivateMode.ShowCursor));\n }\n }\n\n function _end() {\n if (isTTY) {\n output.write(\n cmd(CSI.Reset) + cmd(CSI.ResetPrivateMode) + cmd(CSI.SetPrivateMode, PrivateMode.ShowCursor)\n );\n }\n }\n\n const inputSource = pipe(fromReadStream(process.stdin), onStart(_start), onEnd(_end), share);\n\n const cancelSource = pipe(\n concat([\n pipe(\n inputSource,\n filter(() => false)\n ),\n fromValue(null),\n ]),\n share\n );\n\n function write(...input: any[]) {\n output.write(text(...input));\n }\n\n function start(outputs: AsyncIterable<ComposeInput>): Promise<string | CLIError> {\n const write = (input: string | CLIError) => output.write('' + input);\n if (params.disableTTY) {\n return pipe(compose(outputs), onPush(write), toPromise);\n } else {\n return pipe(compose(outputs), onPush(write), takeUntil(cancelSource), toPromise);\n }\n }\n\n function mode(...modes: readonly (Mode | PrivateMode)[]): void {\n if (isTTY) {\n const normalModes: Mode[] = [];\n const privateModes: PrivateMode[] = [];\n for (const mode of modes) {\n if (mode === Mode.Insert || mode === Mode.AutomaticNewline) {\n normalModes.push(mode);\n } else {\n privateModes.push(mode);\n }\n }\n if (normalModes.length) output.write(cmd(CSI.SetMode, normalModes));\n if (privateModes.length) output.write(cmd(CSI.SetPrivateMode, privateModes));\n }\n }\n\n function modeOff(...modes: readonly (Mode | PrivateMode)[]): void {\n if (isTTY) {\n const normalModes: Mode[] = [];\n const privateModes: PrivateMode[] = [];\n for (const mode of modes) {\n if (mode === Mode.Insert || mode === Mode.AutomaticNewline) {\n normalModes.push(mode);\n } else {\n privateModes.push(mode);\n }\n }\n if (normalModes.length) output.write(cmd(CSI.UnsetMode, normalModes));\n if (privateModes.length) output.write(cmd(CSI.UnsetPrivateMode, privateModes));\n }\n }\n\n return {\n isInteractive: isTTY,\n output,\n pipeTo,\n inputSource,\n cancelSource,\n write,\n start,\n mode,\n modeOff,\n };\n}\n","import * as t from '../../term';\n\nexport function indent(text: string, indent: string) {\n if (text.includes('\\n')) {\n const out = text\n .trim()\n .split('\\n')\n .join(t.text([t.Chars.Newline, indent]));\n return text.endsWith('\\n') ? out + '\\n' : out;\n } else {\n return text;\n }\n}\n\nexport function code(text: string) {\n return t.text`${t.cmd(t.CSI.Style, t.Style.Underline)}${text}${t.cmd(\n t.CSI.Style,\n t.Style.NoUnderline\n )}`;\n}\n\nexport function bold(text: string) {\n return t.text`${t.cmd(t.CSI.Style, t.Style.Bold)}${text}${t.cmd(t.CSI.Style, t.Style.Normal)}`;\n}\n\nexport function hint(text: string) {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${t.Icons.Info} `,\n t.cmd(t.CSI.Style, t.Style.Blue),\n indent(text, ' '),\n ]);\n}\n\nexport function errorMessage(message: string) {\n return t.error([\n '\\n',\n t.cmd(t.CSI.Style, [t.Style.Red, t.Style.Invert]),\n ` ${t.Icons.Warning} Error `,\n t.cmd(t.CSI.Style, t.Style.NoInvert),\n `\\n${message.trim()}\\n`,\n ]);\n}\n\nexport function externalError(message: string, error: unknown) {\n let title: string;\n let text: string;\n if (error && typeof error === 'object') {\n if (\n 'name' in error &&\n (error.name === 'TSError' || error.name === 'TadaError' || 'code' in error)\n ) {\n title = 'code' in error ? 'System Error' : 'Error';\n text =\n error.name === 'TadaError'\n ? t.text([t.cmd(t.CSI.Style, t.Style.Blue), (error as Error).message])\n : (error as Error).message.trim();\n } else if ('stack' in error && typeof error.stack === 'string') {\n title = 'Unexpected Error';\n text = `${error.stack}`;\n } else if ('message' in error && typeof error.message === 'string') {\n title = 'Unexpected Error';\n text = `${error.message}`;\n } else {\n title = 'Unexpected Error';\n text = `${error}`;\n }\n } else {\n title = 'Unexpected Error';\n text = `${error}`;\n }\n\n return t.error([\n '\\n',\n t.cmd(t.CSI.Style, [t.Style.Red, t.Style.Invert]),\n ` ${t.Icons.Warning} ${title} `,\n t.cmd(t.CSI.Style, t.Style.NoInvert),\n `\\n${message.trim()}\\n`,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n indent(!text.endsWith('\\n') ? text + '\\n' : text, ' '),\n ]);\n}\n\nexport function experimentMessage(message: string) {\n return t.error([\n t.cmd(t.CSI.Style, [t.Style.Yellow, t.Style.Bold]),\n `${t.Icons.Warning} Note: `,\n t.cmd(t.CSI.Style, t.Style.Reset),\n `${message.trim()}\\n\\n`,\n ]);\n}\n","import type { WriteStream } from 'node:tty';\nimport type { PathLike } from 'node:fs';\nimport { dirname } from 'node:path';\nimport * as fs from 'node:fs/promises';\n\n/** Checks whether a directory exists on disk */\nconst directoryExists = async (file: PathLike): Promise<boolean> => {\n try {\n const stat = await fs.stat(file);\n if (stat.isDirectory()) {\n return true;\n } else if (stat.isSymbolicLink()) {\n return directoryExists(await fs.realpath(file));\n } else {\n return false;\n }\n } catch {\n return false;\n }\n};\n\n/** Checks whether a file exists on disk */\nconst fileExists = (file: PathLike): Promise<boolean> =>\n fs\n .stat(file)\n .then((stat) => stat.isFile())\n .catch(() => false);\n\nconst touchFile = async (file: PathLike): Promise<void> => {\n try {\n const now = new Date();\n await fs.utimes(file, now, now);\n } catch (_error) {}\n};\n\nexport type WriteTarget = PathLike | WriteStream;\n\n/** Writes a file to a swapfile then moves it into place to prevent excess change events. */\nexport const writeOutput = async (target: WriteTarget, contents: string): Promise<void> => {\n if (target && typeof target === 'object' && 'writable' in target) {\n // If we get a WritableStream (e.g. stdout), we write to that\n // but we listen for errors and wait for it to flush fully\n return await new Promise((resolve, reject) => {\n target.write(contents, (error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n }\n\n const targetDirectory = dirname(typeof target !== 'string' ? await fs.realpath(target) : target);\n if (!(await directoryExists(targetDirectory))) {\n await fs.mkdir(targetDirectory, { recursive: true });\n }\n\n if (!(await fileExists(target))) {\n // If the file doesn't exist, we can write directly, and not\n // try-catch so the error falls through\n await fs.writeFile(target, contents);\n } else {\n // If the file exists, we write to a swap-file, then rename (i.e. move)\n // the file into place. No try-catch around `writeFile` for proper\n // directory/permission errors\n const tempTarget = target + '.tmp';\n await fs.writeFile(tempTarget, contents);\n try {\n await fs.rename(tempTarget, target);\n } catch (error) {\n await fs.unlink(tempTarget);\n throw error;\n } finally {\n // When we move the file into place, we also update its access and\n // modification time manually, in case the rename doesn't trigger\n // a change event\n await touchFile(target);\n }\n }\n};\n","import * as t from '../../term';\n\nimport { hint, code } from '../shared/logger';\nexport * from '../shared/logger';\n\nexport function summary(showHint?: boolean) {\n let out = t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Introspection output was generated successfully\\n`,\n ]);\n if (showHint) {\n out += hint(\n `The pipe output was generated in the ${code('.d.ts')} format.\\n` +\n `For the ${code('.ts')} format, pass the ${code('--force-ts-format')} argument.\\n`\n );\n }\n return out;\n}\n","import * as path from 'node:path';\nimport type { GraphQLSPConfig, LoadConfigResult } from '@gql.tada/internal';\n\nimport {\n loadRef,\n loadConfig,\n parseConfig,\n minifyIntrospection,\n outputIntrospectionFile,\n} from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { WriteTarget } from '../shared';\nimport { writeOutput } from '../shared';\nimport * as logger from './logger';\n\nexport interface OutputOptions {\n /** Whether to output the `.ts` format when the CLI's standard output is piped to an output file.\n * @defaultValue `false` */\n forceTSFormat?: boolean;\n /** Whether to disable the optimized output format for `.d.ts` files.\n * @defaultValue `false` */\n disablePreprocessing?: boolean;\n /** The filename to write the cache file to.\n * @defaultValue The `tadaTurboLocation` configuration option */\n output: string | undefined;\n /** The `tsconfig.json` to use for configurations and the TypeScript program.\n * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n tsconfig: string | undefined;\n}\n\nexport async function* run(tty: TTY, opts: OutputOptions): AsyncIterable<ComposeInput> {\n let configResult: LoadConfigResult;\n let pluginConfig: GraphQLSPConfig;\n try {\n configResult = await loadConfig(opts.tsconfig);\n pluginConfig = parseConfig(configResult.pluginConfig, configResult.rootPath);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n let schemaRef = loadRef(pluginConfig);\n try {\n schemaRef = await schemaRef.load({ rootPath: path.dirname(configResult.configPath) });\n } catch (error) {\n throw logger.externalError('Failed to load schema(s).', error);\n }\n\n const projectPath = path.dirname(configResult.configPath);\n if ('schema' in pluginConfig) {\n const schema = schemaRef.current!;\n\n let destination: WriteTarget;\n if (!opts.output && tty.pipeTo) {\n destination = tty.pipeTo;\n } else if (opts.output) {\n destination = path.resolve(process.cwd(), opts.output);\n } else if (pluginConfig.tadaOutputLocation) {\n destination = pluginConfig.tadaOutputLocation;\n } else {\n throw logger.errorMessage(\n 'No output path was specified to write the output file to.\\n' +\n logger.hint(\n `You have to either set ${logger.code(\n '\"tadaOutputLocation\"'\n )} in your configuration,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n }\n\n let contents: string;\n try {\n contents = outputIntrospectionFile(minifyIntrospection(schema.introspection), {\n fileType:\n destination && typeof destination === 'string'\n ? destination\n : opts.forceTSFormat\n ? '.ts'\n : '.d.ts',\n shouldPreprocess: !opts.disablePreprocessing,\n });\n } catch (error) {\n throw logger.externalError('Could not generate introspection output', error);\n }\n\n try {\n await writeOutput(destination, contents);\n } catch (error) {\n throw logger.externalError(\n 'Something went wrong while writing the introspection file',\n error\n );\n }\n\n yield logger.summary(!opts.forceTSFormat && typeof destination !== 'string');\n } else {\n if (opts.output) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple schemas are configured.\\n' +\n logger.hint(\n `You can only output all schemas to their ${logger.code(\n '\"tadaOutputLocation\"'\n )} options\\n` + `when multiple ${logger.code('schemas')} are set up.`\n )\n );\n }\n\n for (const schemaName in schemaRef.multi) {\n const schema = schemaRef.multi[schemaName];\n if (!schema) {\n continue;\n } else if (!schema.tadaOutputLocation) {\n throw logger.errorMessage(\n `No output path was specified to write the '${schemaName}' schema to.\\n` +\n logger.hint(\n `You have to set ${logger.code('\"tadaOutputLocation\"')} in each schema configuration.`\n )\n );\n }\n\n let contents: string;\n try {\n contents = outputIntrospectionFile(minifyIntrospection(schema.introspection), {\n fileType: schema.tadaOutputLocation,\n shouldPreprocess: !opts.disablePreprocessing,\n });\n } catch (error) {\n throw logger.externalError(\n `Could not generate any output for the '${schemaName}' schema`,\n error\n );\n }\n\n try {\n await writeOutput(path.resolve(projectPath, schema.tadaOutputLocation), contents);\n } catch (error) {\n throw logger.externalError(\n `Something went wrong while writing the '${schemaName}' schema's output`,\n error\n );\n }\n }\n\n yield logger.summary();\n }\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { OutputOptions } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class GenerateOutputCommand extends Command {\n static paths = [['generate-output'], ['generate', 'output']];\n\n forceTSFormat = Option.Boolean('--force-ts-format', false, {\n description: 'Forces the `.ts` output format when the output is piped',\n hidden: true,\n });\n\n disablePreprocessing = Option.Boolean('--disable-preprocessing', false, {\n description:\n 'Disables pre-processing, which is an internal introspection format generated ahead of time',\n });\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` used to read, unless `--output` is passed.',\n });\n\n output = Option.String('--output,-o', {\n description:\n 'Specifies where to output the file to.\\tDefault: The `tadaOutputLocation` configuration option',\n });\n\n async execute() {\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n forceTSFormat: this.forceTSFormat,\n disablePreprocessing: this.disablePreprocessing,\n output: this.output,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Outputs the `gql.tada` output file manually.\n *\n * @remarks\n * Loads the schema from the specified `schema` configuration option and writes the output file\n * to the specified output location.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generateoutput}\n */\nexport async function generateOutput(opts: OutputOptions): Promise<void> {\n const tty = initTTY({ disableTTY: true });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","import { pipe, interval, map } from 'wonka';\n\nimport * as path from 'node:path';\nimport * as t from '../../term';\n\nimport type { PersistedWarning } from './types';\nimport { indent } from '../shared/logger';\n\nexport * from '../shared/logger';\n\nconst CWD = process.cwd();\nconst INDENT = ' ';\n\nexport function warningFile(filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n if (!relativePath.startsWith('..')) filePath = relativePath;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Underline),\n filePath,\n t.cmd(t.CSI.Style, t.Style.NoUnderline),\n '\\n',\n ]);\n}\n\nexport function warningMessage(message: PersistedWarning) {\n return t.text([\n INDENT,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${message.line}:${message.col}`,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n indent(message.message.trim(), t.text([INDENT, t.Chars.Tab])),\n t.Chars.Newline,\n ]);\n}\n\nconst documentSummary = (documentCount: number | Record<string, number>) => {\n let out = '';\n if (\n typeof documentCount !== 'number'\n ? Object.values(documentCount).every((value) => !value)\n : !documentCount\n ) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.Blue),\n `${t.Icons.Info} No persisted documents were found `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(Persisted manifests were not generated)\\n`,\n ]);\n } else if (typeof documentCount === 'number') {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Persisted manifest was generated successfully `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(${documentCount} documents extracted)\\n`,\n ]);\n } else {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Persisted manifests were generated successfully.\\n`,\n ]);\n for (const schemaName in documentCount) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${documentCount[schemaName]} documents extracted for the '${schemaName}' schema\\n`,\n ]);\n }\n }\n return out;\n};\n\nexport function warningSummary(warningCount: number) {\n return t.error([t.cmd(t.CSI.Style, t.Style.Red), `${t.Icons.Cross} ${warningCount} warnings\\n`]);\n}\n\nexport function infoSummary(warningCount: number, documentCount: number | Record<string, number>) {\n let out = '';\n if (warningCount) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ` ${warningCount} warnings\\n`,\n ]);\n }\n out += documentSummary(documentCount);\n return out;\n}\n\nexport function warningGithub(message: PersistedWarning): void {\n t.githubAnnotation('warning', message.message, {\n file: message.file,\n line: message.line,\n col: message.col,\n });\n}\n\nexport function runningPersisted(file?: number, ofFiles?: number) {\n const progress = file ? (ofFiles ? `(${file}/${ofFiles})` : `(${file})`) : '';\n return pipe(\n interval(150),\n map((state) => {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.dotSpinner[state % t.dotSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n `Scanning files${t.Chars.Ellipsis} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n progress,\n ]);\n })\n );\n}\n","import * as path from 'node:path';\nimport type { GraphQLSPConfig, LoadConfigResult } from '@gql.tada/internal';\n\nimport { loadConfig, parseConfig } from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { WriteTarget } from '../shared';\nimport { writeOutput } from '../shared';\nimport type { PersistedDocument } from './types';\nimport * as logger from './logger';\n\nexport interface PersistedOptions {\n /** Whether to disable normalization of GraphQL documents in the output.\n * @defaultValue `false`\n * @remarks\n * Normalizing a GraphQL document means to parse then print them, which\n * removes comments and normalizes formatting.\n */\n disableNormalization?: boolean;\n /** The `tsconfig.json` to use for configurations and the TypeScript program.\n * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n tsconfig: string | undefined;\n /** The filename to write the persisted JSON manifest to.\n * @defaultValue The `schema` configuration option */\n output: string | undefined;\n /** Whether to fail instead of just logging a warning. */\n failOnWarn: boolean;\n}\n\nexport async function* run(tty: TTY, opts: PersistedOptions): AsyncIterable<ComposeInput> {\n const { runPersisted } = await import('./thread');\n\n let configResult: LoadConfigResult;\n let pluginConfig: GraphQLSPConfig;\n try {\n configResult = await loadConfig(opts.tsconfig);\n pluginConfig = parseConfig(configResult.pluginConfig, configResult.rootPath);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n if (tty.isInteractive) yield logger.runningPersisted();\n\n const generator = runPersisted({\n disableNormalization: !!opts.disableNormalization,\n rootPath: configResult.rootPath,\n configPath: configResult.configPath,\n pluginConfig,\n });\n\n const documents: PersistedDocument[] = [];\n let warnings = 0;\n let totalFileCount = 0;\n let fileCount = 0;\n\n try {\n if (tty.isInteractive) yield logger.runningPersisted();\n\n for await (const signal of generator) {\n if (signal.kind === 'EXTERNAL_WARNING') {\n yield logger.experimentMessage(\n `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n );\n } else if (signal.kind === 'FILE_COUNT') {\n totalFileCount = signal.fileCount;\n } else {\n fileCount++;\n documents.push(...signal.documents);\n warnings += signal.warnings.length;\n if (signal.warnings.length) {\n let buffer = logger.warningFile(signal.filePath);\n for (const warning of signal.warnings) {\n buffer += logger.warningMessage(warning);\n logger.warningGithub(warning);\n }\n yield buffer + '\\n';\n }\n }\n\n if (tty.isInteractive) yield logger.runningPersisted(fileCount, totalFileCount);\n }\n } catch (error) {\n throw logger.externalError('Could not generate persisted manifest file', error);\n }\n\n const projectPath = path.dirname(configResult.configPath);\n if ('schema' in pluginConfig) {\n let destination: WriteTarget;\n if (!opts.output && tty.pipeTo) {\n destination = tty.pipeTo;\n } else if (opts.output) {\n destination = path.resolve(process.cwd(), opts.output);\n } else if (pluginConfig.tadaPersistedLocation) {\n destination = path.resolve(\n path.dirname(configResult.configPath),\n pluginConfig.tadaPersistedLocation\n );\n } else {\n throw logger.errorMessage(\n 'No output path was specified to write the persisted manifest file to.\\n' +\n logger.hint(\n `You have to either set ${logger.code(\n '\"tadaPersistedLocation\"'\n )} in your configuration,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n }\n\n if (warnings && opts.failOnWarn) {\n throw logger.warningSummary(warnings);\n } else if (documents.length) {\n try {\n const json: Record<string, string> = {};\n for (const item of documents) json[item.hashKey] = item.document;\n const contents = JSON.stringify(json, null, 2);\n await writeOutput(destination, contents);\n } catch (error) {\n throw logger.externalError(\n 'Something went wrong while writing the persisted manifest file.',\n error\n );\n }\n }\n\n yield logger.infoSummary(warnings, documents.length);\n } else {\n if (opts.output) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple schemas are configured.\\n' +\n logger.hint(\n `You can only output all schemas to their ${logger.code(\n '\"tadaPersistedLocation\"'\n )} options\\n` + `when multiple ${logger.code('schemas')} are set up.`\n )\n );\n }\n\n const documentCount: Record<string, number> = {};\n for (const schemaConfig of pluginConfig.schemas) {\n const { name, tadaPersistedLocation } = schemaConfig;\n if (!tadaPersistedLocation) {\n throw logger.errorMessage(\n `No output path was specified to write the '${name}' schema to.\\n` +\n logger.hint(\n `You have to set ${logger.code(\n '\"tadaPersistedLocation\"'\n )} in each schema configuration.`\n )\n );\n }\n\n try {\n documentCount[name] = 0;\n const json: Record<string, string> = {};\n for (const item of documents) {\n if (item.schemaName === name) {\n json[item.hashKey] = item.document;\n documentCount[name]++;\n }\n }\n if (documentCount[name]) {\n const contents = JSON.stringify(json, null, 2);\n await writeOutput(path.resolve(projectPath, tadaPersistedLocation), contents);\n }\n } catch (error) {\n throw logger.externalError(\n `Something went wrong while writing the '${name}' schema's persisted manifest file.`,\n error\n );\n }\n }\n\n if (warnings && opts.failOnWarn) {\n throw logger.warningSummary(warnings);\n } else {\n yield logger.infoSummary(warnings, documentCount);\n }\n }\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { PersistedOptions } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class GeneratePersisted extends Command {\n static paths = [['generate-persisted'], ['generate', 'persisted']];\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` used to read, unless `--output` is passed.',\n });\n\n disableNormalization = Option.Boolean('--disable-normalization', false, {\n description: 'Disables normalizing of GraphQL documents (parsing then printing documents)',\n });\n\n failOnWarn = Option.Boolean('--fail-on-warn', false, {\n description: 'Triggers an error and a non-zero exit code if any warnings have been reported',\n });\n\n output = Option.String('--output,-o', {\n description:\n 'Specifies where to output the file to.\\tDefault: The `tadaPersistedLocation` configuration option',\n });\n\n async execute() {\n // TODO: Add verbose/log/list/debug/trace option that outputs discovered documents (by name) per file\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n disableNormalization: this.disableNormalization,\n failOnWarn: this.failOnWarn,\n output: this.output,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Generates a JSON manifest file of all `graphql.persisted()` documents.\n *\n * @remarks\n * Scans your code for `graphql.persisted()` calls and generates a JSON\n * manifest file containing a mapping of document IDs to the GraphQL document strings.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generatepersisted}\n */\nexport async function generatePersisted(opts: PersistedOptions) {\n const tty = initTTY({ disableTTY: true });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","const simpleKeyRegExp = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\nfunction getPrintable(value) {\n if (value === null)\n return `null`;\n if (value === undefined)\n return `undefined`;\n if (value === ``)\n return `an empty string`;\n if (typeof value === 'symbol')\n return `<${value.toString()}>`;\n if (Array.isArray(value))\n return `an array`;\n return JSON.stringify(value);\n}\nfunction getPrintableArray(value, conjunction) {\n if (value.length === 0)\n return `nothing`;\n if (value.length === 1)\n return getPrintable(value[0]);\n const rest = value.slice(0, -1);\n const trailing = value[value.length - 1];\n const separator = value.length > 2\n ? `, ${conjunction} `\n : ` ${conjunction} `;\n return `${rest.map(value => getPrintable(value)).join(`, `)}${separator}${getPrintable(trailing)}`;\n}\nfunction computeKey(state, key) {\n var _a, _b, _c;\n if (typeof key === `number`) {\n return `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}[${key}]`;\n }\n else if (simpleKeyRegExp.test(key)) {\n return `${(_b = state === null || state === void 0 ? void 0 : state.p) !== null && _b !== void 0 ? _b : ``}.${key}`;\n }\n else {\n return `${(_c = state === null || state === void 0 ? void 0 : state.p) !== null && _c !== void 0 ? _c : `.`}[${JSON.stringify(key)}]`;\n }\n}\nfunction plural(n, singular, plural) {\n return n === 1 ? singular : plural;\n}\n\nconst colorStringRegExp = /^#[0-9a-f]{6}$/i;\nconst colorStringAlphaRegExp = /^#[0-9a-f]{6}([0-9a-f]{2})?$/i;\n// https://stackoverflow.com/a/475217/880703\nconst base64RegExp = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n// https://stackoverflow.com/a/14166194/880703\nconst uuid4RegExp = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$/i;\n// https://stackoverflow.com/a/28022901/880703 + https://www.debuggex.com/r/bl8J35wMKk48a7u_\nconst iso8601RegExp = /^(?:[1-9]\\d{3}(-?)(?:(?:0[1-9]|1[0-2])\\1(?:0[1-9]|1\\d|2[0-8])|(?:0[13-9]|1[0-2])\\1(?:29|30)|(?:0[13578]|1[02])(?:\\1)31|00[1-9]|0[1-9]\\d|[12]\\d{2}|3(?:[0-5]\\d|6[0-5]))|(?:[1-9]\\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)(?:(-?)02(?:\\2)29|-?366))T(?:[01]\\d|2[0-3])(:?)[0-5]\\d(?:\\3[0-5]\\d)?(?:Z|[+-][01]\\d(?:\\3[0-5]\\d)?)$/;\n\nfunction pushError({ errors, p } = {}, message) {\n errors === null || errors === void 0 ? void 0 : errors.push(`${p !== null && p !== void 0 ? p : `.`}: ${message}`);\n return false;\n}\nfunction makeSetter(target, key) {\n return (v) => {\n target[key] = v;\n };\n}\nfunction makeCoercionFn(target, key) {\n return (v) => {\n const previous = target[key];\n target[key] = v;\n return makeCoercionFn(target, key).bind(null, previous);\n };\n}\nfunction makeLazyCoercionFn(fn, orig, generator) {\n const commit = () => {\n fn(generator());\n return revert;\n };\n const revert = () => {\n fn(orig);\n return commit;\n };\n return commit;\n}\n\n/**\n * Create a validator that always returns true and never refines the type.\n */\nfunction isUnknown() {\n return makeValidator({\n test: (value, state) => {\n return true;\n },\n });\n}\nfunction isLiteral(expected) {\n return makeValidator({\n test: (value, state) => {\n if (value !== expected)\n return pushError(state, `Expected ${getPrintable(expected)} (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a string.\n * Refines the type to `string`.\n */\nfunction isString() {\n return makeValidator({\n test: (value, state) => {\n if (typeof value !== `string`)\n return pushError(state, `Expected a string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\nfunction isEnum(enumSpec) {\n const valuesArray = Array.isArray(enumSpec) ? enumSpec : Object.values(enumSpec);\n const isAlphaNum = valuesArray.every(item => typeof item === 'string' || typeof item === 'number');\n const values = new Set(valuesArray);\n if (values.size === 1)\n return isLiteral([...values][0]);\n return makeValidator({\n test: (value, state) => {\n if (!values.has(value)) {\n if (isAlphaNum) {\n return pushError(state, `Expected one of ${getPrintableArray(valuesArray, `or`)} (got ${getPrintable(value)})`);\n }\n else {\n return pushError(state, `Expected a valid enumeration value (got ${getPrintable(value)})`);\n }\n }\n return true;\n },\n });\n}\nconst BOOLEAN_COERCIONS = new Map([\n [`true`, true],\n [`True`, true],\n [`1`, true],\n [1, true],\n [`false`, false],\n [`False`, false],\n [`0`, false],\n [0, false],\n]);\n/**\n * Create a validator that only returns true when the tested value is a\n * boolean. Refines the type to `boolean`.\n *\n * Supports coercion:\n * - 'true' / 'True' / '1' / 1 will turn to `true`\n * - 'false' / 'False' / '0' / 0 will turn to `false`\n */\nfunction isBoolean() {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof value !== `boolean`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const coercion = BOOLEAN_COERCIONS.get(value);\n if (typeof coercion !== `undefined`) {\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);\n return true;\n }\n }\n return pushError(state, `Expected a boolean (got ${getPrintable(value)})`);\n }\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a\n * number (including floating numbers; use `cascade` and `isInteger` to\n * restrict the range further). Refines the type to `number`.\n *\n * Supports coercion.\n */\nfunction isNumber() {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof value !== `number`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n let coercion;\n if (typeof value === `string`) {\n let val;\n try {\n val = JSON.parse(value);\n }\n catch (_b) { }\n // We check against JSON.stringify that the output is the same to ensure that the number can be safely represented in JS\n if (typeof val === `number`) {\n if (JSON.stringify(val) === value) {\n coercion = val;\n }\n else {\n return pushError(state, `Received a number that can't be safely represented by the runtime (${value})`);\n }\n }\n }\n if (typeof coercion !== `undefined`) {\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);\n return true;\n }\n }\n return pushError(state, `Expected a number (got ${getPrintable(value)})`);\n }\n return true;\n },\n });\n}\n/**\n * Important: This validator only makes sense when used in conjunction with\n * coercion! It will always error when used without.\n *\n * Create a validator that only returns true when the tested value is a\n * JSON representation of the expected type. Refines the type to the\n * expected type, and casts the value into its inner value.\n */\nfunction isPayload(spec) {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) === `undefined`)\n return pushError(state, `The isPayload predicate can only be used with coercion enabled`);\n if (typeof state.coercion === `undefined`)\n return pushError(state, `Unbound coercion result`);\n if (typeof value !== `string`)\n return pushError(state, `Expected a string (got ${getPrintable(value)})`);\n let inner;\n try {\n inner = JSON.parse(value);\n }\n catch (_b) {\n return pushError(state, `Expected a JSON string (got ${getPrintable(value)})`);\n }\n const wrapper = { value: inner };\n if (!spec(inner, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(wrapper, `value`) })))\n return false;\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, wrapper.value)]);\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a\n * valid date. Refines the type to `Date`.\n *\n * Supports coercion via one of the following formats:\n * - ISO86001 strings\n * - Unix timestamps\n */\nfunction isDate() {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (!(value instanceof Date)) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n let coercion;\n if (typeof value === `string` && iso8601RegExp.test(value)) {\n coercion = new Date(value);\n }\n else {\n let timestamp;\n if (typeof value === `string`) {\n let val;\n try {\n val = JSON.parse(value);\n }\n catch (_b) { }\n if (typeof val === `number`) {\n timestamp = val;\n }\n }\n else if (typeof value === `number`) {\n timestamp = value;\n }\n if (typeof timestamp !== `undefined`) {\n if (Number.isSafeInteger(timestamp) || !Number.isSafeInteger(timestamp * 1000)) {\n coercion = new Date(timestamp * 1000);\n }\n else {\n return pushError(state, `Received a timestamp that can't be safely represented by the runtime (${value})`);\n }\n }\n }\n if (typeof coercion !== `undefined`) {\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);\n return true;\n }\n }\n return pushError(state, `Expected a date (got ${getPrintable(value)})`);\n }\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * array whose all values match the provided subspec. Refines the type to\n * `Array<T>`, with `T` being the subspec inferred type.\n *\n * Supports coercion if the `delimiter` option is set, in which case strings\n * will be split accordingly.\n */\nfunction isArray(spec, { delimiter } = {}) {\n return makeValidator({\n test: (value, state) => {\n var _a;\n const originalValue = value;\n if (typeof value === `string` && typeof delimiter !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n value = value.split(delimiter);\n }\n }\n if (!Array.isArray(value))\n return pushError(state, `Expected an array (got ${getPrintable(value)})`);\n let valid = true;\n for (let t = 0, T = value.length; t < T; ++t) {\n valid = spec(value[t], Object.assign(Object.assign({}, state), { p: computeKey(state, t), coercion: makeCoercionFn(value, t) })) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n if (value !== originalValue)\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);\n return valid;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * set whose all values match the provided subspec. Refines the type to\n * `Set<T>`, with `T` being the subspec inferred type.\n *\n * Supports coercion from arrays (or anything that can be coerced into an\n * array).\n */\nfunction isSet(spec, { delimiter } = {}) {\n const isArrayValidator = isArray(spec, { delimiter });\n return makeValidator({\n test: (value, state) => {\n var _a, _b;\n if (Object.getPrototypeOf(value).toString() === `[object Set]`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const originalValues = [...value];\n const coercedValues = [...value];\n if (!isArrayValidator(coercedValues, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n const updateValue = () => coercedValues.some((val, t) => val !== originalValues[t])\n ? new Set(coercedValues)\n : value;\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, makeLazyCoercionFn(state.coercion, value, updateValue)]);\n return true;\n }\n else {\n let valid = true;\n for (const subValue of value) {\n valid = spec(subValue, Object.assign({}, state)) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n return valid;\n }\n }\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const store = { value };\n if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(store, `value`) })))\n return false;\n state.coercions.push([(_b = state.p) !== null && _b !== void 0 ? _b : `.`, makeLazyCoercionFn(state.coercion, value, () => new Set(store.value))]);\n return true;\n }\n return pushError(state, `Expected a set (got ${getPrintable(value)})`);\n }\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * map whose all values match the provided subspecs. Refines the type to\n * `Map<U, V>`, with `U` being the key subspec inferred type and `V` being\n * the value subspec inferred type.\n *\n * Supports coercion from array of tuples (or anything that can be coerced into\n * an array of tuples).\n */\nfunction isMap(keySpec, valueSpec) {\n const isArrayValidator = isArray(isTuple([keySpec, valueSpec]));\n const isRecordValidator = isRecord(valueSpec, { keys: keySpec });\n return makeValidator({\n test: (value, state) => {\n var _a, _b, _c;\n if (Object.getPrototypeOf(value).toString() === `[object Map]`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const originalValues = [...value];\n const coercedValues = [...value];\n if (!isArrayValidator(coercedValues, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n const updateValue = () => coercedValues.some((val, t) => val[0] !== originalValues[t][0] || val[1] !== originalValues[t][1])\n ? new Map(coercedValues)\n : value;\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, makeLazyCoercionFn(state.coercion, value, updateValue)]);\n return true;\n }\n else {\n let valid = true;\n for (const [key, subValue] of value) {\n valid = keySpec(key, Object.assign({}, state)) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n valid = valueSpec(subValue, Object.assign(Object.assign({}, state), { p: computeKey(state, key) })) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n return valid;\n }\n }\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const store = { value };\n if (Array.isArray(value)) {\n if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n state.coercions.push([(_b = state.p) !== null && _b !== void 0 ? _b : `.`, makeLazyCoercionFn(state.coercion, value, () => new Map(store.value))]);\n return true;\n }\n else {\n if (!isRecordValidator(value, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(store, `value`) })))\n return false;\n state.coercions.push([(_c = state.p) !== null && _c !== void 0 ? _c : `.`, makeLazyCoercionFn(state.coercion, value, () => new Map(Object.entries(store.value)))]);\n return true;\n }\n }\n return pushError(state, `Expected a map (got ${getPrintable(value)})`);\n }\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a\n * tuple whose each value matches the corresponding subspec. Refines the type\n * into a tuple whose each item has the type inferred by the corresponding\n * tuple.\n *\n * Supports coercion if the `delimiter` option is set, in which case strings\n * will be split accordingly.\n */\nfunction isTuple(spec, { delimiter } = {}) {\n const lengthValidator = hasExactLength(spec.length);\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof value === `string` && typeof delimiter !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n value = value.split(delimiter);\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);\n }\n }\n if (!Array.isArray(value))\n return pushError(state, `Expected a tuple (got ${getPrintable(value)})`);\n let valid = lengthValidator(value, Object.assign({}, state));\n for (let t = 0, T = value.length; t < T && t < spec.length; ++t) {\n valid = spec[t](value[t], Object.assign(Object.assign({}, state), { p: computeKey(state, t), coercion: makeCoercionFn(value, t) })) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n return valid;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object with any amount of properties that must all match the provided\n * subspec. Refines the type to `Record<string, T>`, with `T` being the\n * subspec inferred type.\n *\n * Keys can be optionally validated as well by using the `keys` optional\n * subspec parameter.\n */\nfunction isRecord(spec, { keys: keySpec = null, } = {}) {\n const isArrayValidator = isArray(isTuple([keySpec !== null && keySpec !== void 0 ? keySpec : isString(), spec]));\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (Array.isArray(value)) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n value = Object.fromEntries(value);\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);\n return true;\n }\n }\n if (typeof value !== `object` || value === null)\n return pushError(state, `Expected an object (got ${getPrintable(value)})`);\n const keys = Object.keys(value);\n let valid = true;\n for (let t = 0, T = keys.length; t < T && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null); ++t) {\n const key = keys[t];\n const sub = value[key];\n if (key === `__proto__` || key === `constructor`) {\n valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`);\n continue;\n }\n if (keySpec !== null && !keySpec(key, state)) {\n valid = false;\n continue;\n }\n if (!spec(sub, Object.assign(Object.assign({}, state), { p: computeKey(state, key), coercion: makeCoercionFn(value, key) }))) {\n valid = false;\n continue;\n }\n }\n return valid;\n },\n });\n}\n/**\n * @deprecated Replace `isDict` by `isRecord`\n */\nfunction isDict(spec, opts = {}) {\n return isRecord(spec, opts);\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object whose all properties match their corresponding subspec. Refines\n * the type into an object whose each property has the type inferred by the\n * corresponding subspec.\n *\n * Unlike `t.isPartial`, `t.isObject` doesn't allow extraneous properties by\n * default. This behaviour can be altered by using the `extra` optional\n * subspec parameter, which will be called to validate an object only\n * containing the extraneous properties.\n *\n * Calling `t.isObject(..., {extra: t.isRecord(t.isUnknown())})` is\n * essentially the same as calling `t.isPartial(...)`.\n */\nfunction isObject(props, { extra: extraSpec = null, } = {}) {\n const specKeys = Object.keys(props);\n const validator = makeValidator({\n test: (value, state) => {\n if (typeof value !== `object` || value === null)\n return pushError(state, `Expected an object (got ${getPrintable(value)})`);\n const keys = new Set([...specKeys, ...Object.keys(value)]);\n const extra = {};\n let valid = true;\n for (const key of keys) {\n if (key === `constructor` || key === `__proto__`) {\n valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`);\n }\n else {\n const spec = Object.prototype.hasOwnProperty.call(props, key)\n ? props[key]\n : undefined;\n const sub = Object.prototype.hasOwnProperty.call(value, key)\n ? value[key]\n : undefined;\n if (typeof spec !== `undefined`) {\n valid = spec(sub, Object.assign(Object.assign({}, state), { p: computeKey(state, key), coercion: makeCoercionFn(value, key) })) && valid;\n }\n else if (extraSpec === null) {\n valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Extraneous property (got ${getPrintable(sub)})`);\n }\n else {\n Object.defineProperty(extra, key, {\n enumerable: true,\n get: () => sub,\n set: makeSetter(value, key)\n });\n }\n }\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n if (extraSpec !== null && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null))\n valid = extraSpec(extra, state) && valid;\n return valid;\n },\n });\n return Object.assign(validator, {\n properties: props,\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object whose all properties match their corresponding subspec. Refines\n * the type into an object whose each property has the type inferred by the\n * corresponding subspec.\n *\n * Unlike `t.isObject`, `t.isPartial` allows extraneous properties. The\n * resulting type will reflect this behaviour by including an index\n * signature (each extraneous property being typed `unknown`).\n *\n * Calling `t.isPartial(...)` is essentially the same as calling\n * `t.isObject(..., {extra: t.isRecord(t.isUnknown())})`.\n */\nfunction isPartial(props) {\n return isObject(props, { extra: isRecord(isUnknown()) });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object whose prototype is derived from the given class. Refines the type\n * into a class instance.\n */\nconst isInstanceOf = (constructor) => makeValidator({\n test: (value, state) => {\n if (!(value instanceof constructor))\n return pushError(state, `Expected an instance of ${constructor.name} (got ${getPrintable(value)})`);\n return true;\n },\n});\n/**\n * Create a validator that only returns true when the tested value is an\n * object matching any of the provided subspecs. If the optional `exclusive`\n * parameter is set to `true`, the behaviour changes so that the validator\n * only returns true when exactly one subspec matches.\n */\nconst isOneOf = (specs, { exclusive = false, } = {}) => makeValidator({\n test: (value, state) => {\n var _a, _b, _c;\n const matches = [];\n const errorBuffer = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined`\n ? [] : undefined;\n for (let t = 0, T = specs.length; t < T; ++t) {\n const subErrors = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined`\n ? [] : undefined;\n const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`\n ? [] : undefined;\n if (specs[t](value, Object.assign(Object.assign({}, state), { errors: subErrors, coercions: subCoercions, p: `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}#${t + 1}` }))) {\n matches.push([`#${t + 1}`, subCoercions]);\n if (!exclusive) {\n break;\n }\n }\n else {\n errorBuffer === null || errorBuffer === void 0 ? void 0 : errorBuffer.push(subErrors[0]);\n }\n }\n if (matches.length === 1) {\n const [, subCoercions] = matches[0];\n if (typeof subCoercions !== `undefined`)\n (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 ? void 0 : _b.push(...subCoercions);\n return true;\n }\n if (matches.length > 1)\n pushError(state, `Expected to match exactly a single predicate (matched ${matches.join(`, `)})`);\n else\n (_c = state === null || state === void 0 ? void 0 : state.errors) === null || _c === void 0 ? void 0 : _c.push(...errorBuffer);\n return false;\n },\n});\n\nfunction makeTrait(value) {\n return () => {\n return value;\n };\n}\nfunction makeValidator({ test }) {\n return makeTrait(test)();\n}\nclass TypeAssertionError extends Error {\n constructor({ errors } = {}) {\n let errorMessage = `Type mismatch`;\n if (errors && errors.length > 0) {\n errorMessage += `\\n`;\n for (const error of errors) {\n errorMessage += `\\n- ${error}`;\n }\n }\n super(errorMessage);\n }\n}\n/**\n * Check that the specified value matches the given validator, and throws an\n * exception if it doesn't. Refine the type if it passes.\n */\nfunction assert(val, validator) {\n if (!validator(val)) {\n throw new TypeAssertionError();\n }\n}\n/**\n * Check that the specified value matches the given validator, and throws an\n * exception if it doesn't. Refine the type if it passes.\n *\n * Thrown exceptions include details about what exactly looks invalid in the\n * tested value.\n */\nfunction assertWithErrors(val, validator) {\n const errors = [];\n if (!validator(val, { errors })) {\n throw new TypeAssertionError({ errors });\n }\n}\n/**\n * Compile-time only. Refine the type as if the validator was matching the\n * tested value, but doesn't actually run it. Similar to the classic `as`\n * operator in TypeScript.\n */\nfunction softAssert(val, validator) {\n // It's a soft assert; we tell TypeScript about the type, but we don't need to check it\n}\nfunction as(value, validator, { coerce = false, errors: storeErrors, throw: throws } = {}) {\n const errors = storeErrors ? [] : undefined;\n if (!coerce) {\n if (validator(value, { errors })) {\n return throws ? value : { value, errors: undefined };\n }\n else if (!throws) {\n return { value: undefined, errors: errors !== null && errors !== void 0 ? errors : true };\n }\n else {\n throw new TypeAssertionError({ errors });\n }\n }\n const state = { value };\n const coercion = makeCoercionFn(state, `value`);\n const coercions = [];\n if (!validator(value, { errors, coercion, coercions })) {\n if (!throws) {\n return { value: undefined, errors: errors !== null && errors !== void 0 ? errors : true };\n }\n else {\n throw new TypeAssertionError({ errors });\n }\n }\n for (const [, apply] of coercions)\n apply();\n if (throws) {\n return state.value;\n }\n else {\n return { value: state.value, errors: undefined };\n }\n}\n/**\n * Create and return a new function that apply the given validators to each\n * corresponding argument passed to the function and throws an exception in\n * case of a mismatch.\n */\nfunction fn(validators, fn) {\n const isValidArgList = isTuple(validators);\n return ((...args) => {\n const check = isValidArgList(args);\n if (!check)\n throw new TypeAssertionError();\n return fn(...args);\n });\n}\n\n/**\n * Create a validator that checks that the tested array or string has at least\n * the specified length.\n */\nfunction hasMinLength(length) {\n return makeValidator({\n test: (value, state) => {\n if (!(value.length >= length))\n return pushError(state, `Expected to have a length of at least ${length} elements (got ${value.length})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested array or string has at most\n * the specified length.\n */\nfunction hasMaxLength(length) {\n return makeValidator({\n test: (value, state) => {\n if (!(value.length <= length))\n return pushError(state, `Expected to have a length of at most ${length} elements (got ${value.length})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested array or string has exactly\n * the specified length.\n */\nfunction hasExactLength(length) {\n return makeValidator({\n test: (value, state) => {\n if (!(value.length === length))\n return pushError(state, `Expected to have a length of exactly ${length} elements (got ${value.length})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested array only contains unique\n * elements. The optional `map` parameter lets you define a transform to\n * apply before making the check (the result of this transform will be\n * discarded afterwards).\n */\nfunction hasUniqueItems({ map, } = {}) {\n return makeValidator({\n test: (value, state) => {\n const set = new Set();\n const dup = new Set();\n for (let t = 0, T = value.length; t < T; ++t) {\n const sub = value[t];\n const key = typeof map !== `undefined`\n ? map(sub)\n : sub;\n if (set.has(key)) {\n if (dup.has(key))\n continue;\n pushError(state, `Expected to contain unique elements; got a duplicate with ${getPrintable(value)}`);\n dup.add(key);\n }\n else {\n set.add(key);\n }\n }\n return dup.size === 0;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is strictly less than 0.\n */\nfunction isNegative() {\n return makeValidator({\n test: (value, state) => {\n if (!(value <= 0))\n return pushError(state, `Expected to be negative (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is equal or greater\n * than 0.\n */\nfunction isPositive() {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= 0))\n return pushError(state, `Expected to be positive (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is equal or greater\n * than the specified reference.\n */\nfunction isAtLeast(n) {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= n))\n return pushError(state, `Expected to be at least ${n} (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is equal or smaller\n * than the specified reference.\n */\nfunction isAtMost(n) {\n return makeValidator({\n test: (value, state) => {\n if (!(value <= n))\n return pushError(state, `Expected to be at most ${n} (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is between the\n * specified references (including the upper boundary).\n */\nfunction isInInclusiveRange(a, b) {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= a && value <= b))\n return pushError(state, `Expected to be in the [${a}; ${b}] range (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is between the\n * specified references (excluding the upper boundary).\n */\nfunction isInExclusiveRange(a, b) {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= a && value < b))\n return pushError(state, `Expected to be in the [${a}; ${b}[ range (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is an integer.\n *\n * By default Typanion will also check that it's a *safe* integer. For example,\n * 2^53 wouldn't be a safe integer because 2^53+1 would be rounded to 2^53,\n * which could put your applications at risk when used in loops.\n */\nfunction isInteger({ unsafe = false, } = {}) {\n return makeValidator({\n test: (value, state) => {\n if (value !== Math.round(value))\n return pushError(state, `Expected to be an integer (got ${value})`);\n if (!unsafe && !Number.isSafeInteger(value))\n return pushError(state, `Expected to be a safe integer (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string matches the given\n * regular expression.\n */\nfunction matchesRegExp(regExp) {\n return makeValidator({\n test: (value, state) => {\n if (!regExp.test(value))\n return pushError(state, `Expected to match the pattern ${regExp.toString()} (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string only contain lowercase\n * characters.\n */\nfunction isLowerCase() {\n return makeValidator({\n test: (value, state) => {\n if (value !== value.toLowerCase())\n return pushError(state, `Expected to be all-lowercase (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string only contain uppercase\n * characters.\n */\nfunction isUpperCase() {\n return makeValidator({\n test: (value, state) => {\n if (value !== value.toUpperCase())\n return pushError(state, `Expected to be all-uppercase (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is a valid UUID v4.\n */\nfunction isUUID4() {\n return makeValidator({\n test: (value, state) => {\n if (!uuid4RegExp.test(value))\n return pushError(state, `Expected to be a valid UUID v4 (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is a valid ISO8601\n * date.\n */\nfunction isISO8601() {\n return makeValidator({\n test: (value, state) => {\n if (!iso8601RegExp.test(value))\n return pushError(state, `Expected to be a valid ISO 8601 date string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is a valid hexadecimal\n * color. Setting the optional `alpha` parameter to `true` allows an additional\n * transparency channel to be included.\n */\nfunction isHexColor({ alpha = false, }) {\n return makeValidator({\n test: (value, state) => {\n const res = alpha\n ? colorStringRegExp.test(value)\n : colorStringAlphaRegExp.test(value);\n if (!res)\n return pushError(state, `Expected to be a valid hexadecimal color string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is valid base64.\n */\nfunction isBase64() {\n return makeValidator({\n test: (value, state) => {\n if (!base64RegExp.test(value))\n return pushError(state, `Expected to be a valid base 64 string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is valid JSON. A\n * optional spec can be passed as parameter, in which case the data will be\n * deserialized and validated against the spec (coercion will be disabled\n * for this check, and even if successful the returned value will still be\n * the original string).\n */\nfunction isJSON(spec = isUnknown()) {\n return makeValidator({\n test: (value, state) => {\n let data;\n try {\n data = JSON.parse(value);\n }\n catch (_a) {\n return pushError(state, `Expected to be a valid JSON string (got ${getPrintable(value)})`);\n }\n return spec(data, state);\n },\n });\n}\n\nfunction cascade(spec, ...followups) {\n const resolvedFollowups = Array.isArray(followups[0])\n ? followups[0]\n : followups;\n return makeValidator({\n test: (value, state) => {\n var _a, _b;\n const context = { value: value };\n const subCoercion = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`\n ? makeCoercionFn(context, `value`) : undefined;\n const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`\n ? [] : undefined;\n if (!spec(value, Object.assign(Object.assign({}, state), { coercion: subCoercion, coercions: subCoercions })))\n return false;\n const reverts = [];\n if (typeof subCoercions !== `undefined`)\n for (const [, coercion] of subCoercions)\n reverts.push(coercion());\n try {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (context.value !== value) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, context.value)]);\n }\n (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 ? void 0 : _b.push(...subCoercions);\n }\n return resolvedFollowups.every(spec => {\n return spec(context.value, state);\n });\n }\n finally {\n for (const revert of reverts) {\n revert();\n }\n }\n },\n });\n}\nfunction applyCascade(spec, ...followups) {\n const resolvedFollowups = Array.isArray(followups[0])\n ? followups[0]\n : followups;\n return cascade(spec, resolvedFollowups);\n}\n/**\n * Wraps the given spec to also allow `undefined`.\n */\nfunction isOptional(spec) {\n return makeValidator({\n test: (value, state) => {\n if (typeof value === `undefined`)\n return true;\n return spec(value, state);\n },\n });\n}\n/**\n * Wraps the given spec to also allow `null`.\n */\nfunction isNullable(spec) {\n return makeValidator({\n test: (value, state) => {\n if (value === null)\n return true;\n return spec(value, state);\n },\n });\n}\nconst checks = {\n missing: (keys, key) => keys.has(key),\n undefined: (keys, key, value) => keys.has(key) && typeof value[key] !== `undefined`,\n nil: (keys, key, value) => keys.has(key) && value[key] != null,\n falsy: (keys, key, value) => keys.has(key) && !!value[key],\n};\n/**\n * Create a validator that checks that the tested object contains the specified\n * keys.\n*/\nfunction hasRequiredKeys(requiredKeys, options) {\n var _a;\n const requiredSet = new Set(requiredKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n const problems = [];\n for (const key of requiredSet)\n if (!check(keys, key, value))\n problems.push(key);\n if (problems.length > 0)\n return pushError(state, `Missing required ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, `and`)}`);\n return true;\n },\n });\n}\n/**\n* Create a validator that checks that the tested object contains at least one\n* of the specified keys.\n*/\nfunction hasAtLeastOneKey(requiredKeys, options) {\n var _a;\n const requiredSet = new Set(requiredKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = Object.keys(value);\n const valid = keys.some(key => check(requiredSet, key, value));\n if (!valid)\n return pushError(state, `Missing at least one property from ${getPrintableArray(Array.from(requiredSet), `or`)}`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested object contains none of the\n * specified keys.\n*/\nfunction hasForbiddenKeys(forbiddenKeys, options) {\n var _a;\n const forbiddenSet = new Set(forbiddenKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n const problems = [];\n for (const key of forbiddenSet)\n if (check(keys, key, value))\n problems.push(key);\n if (problems.length > 0)\n return pushError(state, `Forbidden ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, `and`)}`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested object contains at most one\n * of the specified keys.\n */\nfunction hasMutuallyExclusiveKeys(exclusiveKeys, options) {\n var _a;\n const exclusiveSet = new Set(exclusiveKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n const used = [];\n for (const key of exclusiveSet)\n if (check(keys, key, value))\n used.push(key);\n if (used.length > 1)\n return pushError(state, `Mutually exclusive properties ${getPrintableArray(used, `and`)}`);\n return true;\n },\n });\n}\nvar KeyRelationship;\n(function (KeyRelationship) {\n KeyRelationship[\"Forbids\"] = \"Forbids\";\n KeyRelationship[\"Requires\"] = \"Requires\";\n})(KeyRelationship || (KeyRelationship = {}));\nconst keyRelationships = {\n [KeyRelationship.Forbids]: {\n expect: false,\n message: `forbids using`,\n },\n [KeyRelationship.Requires]: {\n expect: true,\n message: `requires using`,\n },\n};\n/**\n * Create a validator that checks that, when the specified subject property is\n * set, the relationship is satisfied.\n */\nfunction hasKeyRelationship(subject, relationship, others, options) {\n var _a, _b;\n const skipped = new Set((_a = options === null || options === void 0 ? void 0 : options.ignore) !== null && _a !== void 0 ? _a : []);\n const check = checks[(_b = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _b !== void 0 ? _b : 'missing'];\n const otherSet = new Set(others);\n const spec = keyRelationships[relationship];\n const conjunction = relationship === KeyRelationship.Forbids\n ? `or`\n : `and`;\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n if (!check(keys, subject, value) || skipped.has(value[subject]))\n return true;\n const problems = [];\n for (const key of otherSet)\n if ((check(keys, key, value) && !skipped.has(value[key])) !== spec.expect)\n problems.push(key);\n if (problems.length >= 1)\n return pushError(state, `Property \"${subject}\" ${spec.message} ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, conjunction)}`);\n return true;\n },\n });\n}\n\nexport { KeyRelationship, TypeAssertionError, applyCascade, as, assert, assertWithErrors, cascade, fn, hasAtLeastOneKey, hasExactLength, hasForbiddenKeys, hasKeyRelationship, hasMaxLength, hasMinLength, hasMutuallyExclusiveKeys, hasRequiredKeys, hasUniqueItems, isArray, isAtLeast, isAtMost, isBase64, isBoolean, isDate, isDict, isEnum, isHexColor, isISO8601, isInExclusiveRange, isInInclusiveRange, isInstanceOf, isInteger, isJSON, isLiteral, isLowerCase, isMap, isNegative, isNullable, isNumber, isObject, isOneOf, isOptional, isPartial, isPayload, isPositive, isRecord, isSet, isString, isTuple, isUUID4, isUnknown, isUpperCase, makeTrait, makeValidator, matchesRegExp, softAssert };\n","import path from 'node:path';\nimport { printSchema } from 'graphql';\nimport type { GraphQLSchema } from 'graphql';\nimport type { GraphQLSPConfig, LoadConfigResult } from '@gql.tada/internal';\nimport { load, loadConfig, parseConfig } from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { WriteTarget } from '../shared';\nimport { writeOutput } from '../shared';\nimport * as logger from './logger';\n\nexport interface SchemaOptions {\n /** The filename to a `.graphql` SDL file, introspection JSON, or URL to a GraphQL API to introspect. */\n input: string;\n /** Object of headers to send when introspection a GraphQL API. */\n headers: Record<string, string> | undefined;\n /** The filename to write the GraphQL SDL file to.\n * @defaultValue The `schema` configuration option */\n output: string | undefined;\n /** The `tsconfig.json` to use for configurations and the TypeScript program.\n * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n tsconfig: string | undefined;\n}\n\nexport async function* run(tty: TTY, opts: SchemaOptions): AsyncIterable<ComposeInput> {\n const origin = opts.headers ? { url: opts.input, headers: opts.headers } : opts.input;\n const loader = load({ rootPath: process.cwd(), origin });\n\n let schema: GraphQLSchema;\n try {\n const loadResult = await loader.load();\n schema = loadResult.schema;\n } catch (error) {\n throw logger.externalError('Failed to load schema.', error);\n }\n\n let destination: WriteTarget;\n if (!opts.output && tty.pipeTo) {\n destination = tty.pipeTo;\n } else if (opts.output) {\n destination = path.resolve(process.cwd(), opts.output);\n } else {\n let configResult: LoadConfigResult;\n let pluginConfig: GraphQLSPConfig;\n try {\n configResult = await loadConfig(opts.tsconfig);\n pluginConfig = parseConfig(configResult.pluginConfig, configResult.rootPath);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n if (\n 'schema' in pluginConfig &&\n typeof pluginConfig.schema === 'string' &&\n path.extname(pluginConfig.schema) === '.graphql'\n ) {\n destination = path.resolve(path.dirname(configResult.configPath), pluginConfig.schema);\n } else if (!('schema' in pluginConfig)) {\n throw logger.errorMessage(\n `Output path cannot be automatically determined when multiple schemas are configured,\\n` +\n `because multiple ${logger.code('schemas')} are set up.` +\n logger.hint(\n `You have to explicitly pass an ${logger.code(\n '--output'\n )} argument to this command,\\n` + 'or pipe this command to an output file.'\n )\n );\n } else {\n throw logger.errorMessage(\n `Output path cannot be automatically determined,\\n` +\n `because ${logger.code('schema')} is not a file path.\\n` +\n logger.hint(\n `You have to either set ${logger.code(\n '\"schema\"'\n )} in your configuration to a ${logger.code('.graphql')} file,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n }\n }\n\n try {\n await writeOutput(destination, printSchema(schema));\n } catch (error) {\n throw logger.externalError('Something went wrong while writing the introspection file', error);\n }\n\n yield logger.summary();\n}\n","import * as t from '../../term';\n\nexport * from '../shared/logger';\n\nexport function summary() {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Schema was generated successfully\\n`,\n ]);\n}\n","import * as t from 'typanion';\nimport { Command, Option } from 'clipanion';\n\nimport { exitCode } from '../../utils/error';\nimport type { SchemaOptions } from './runner';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nconst isHeaderEntries = t.isArray(t.cascade(t.isString(), t.matchesRegExp(/^[\\w-]+[ ]*:[ ]*.+/i)));\n\nconst parseHeaders = (\n headers: readonly string[] | undefined\n): Record<string, string> | undefined => {\n if (headers && headers.length) {\n return (headers || []).reduce((headers, entry) => {\n const index = entry.indexOf(':');\n const key = entry.slice(0, index);\n const value = entry.slice(index + 1);\n headers[key.trimEnd()] = value.trimStart();\n return headers;\n }, {});\n }\n};\n\nexport class GenerateSchema extends Command {\n static paths = [['generate-schema'], ['generate', 'schema']];\n\n input = Option.String({\n name: 'schema',\n required: true,\n });\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` used to read, unless `--output` is passed.',\n });\n\n output = Option.String('--output,-o', {\n description:\n \"Specify where to output the file to.\\tDefault: The `schema` configuration option, if it's a file path\",\n });\n\n headers = Option.Array('--header', {\n description: 'Headers to be used when introspection a schema from a remote URL',\n validator: isHeaderEntries,\n });\n\n async execute() {\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n input: this.input,\n headers: parseHeaders(this.headers),\n output: this.output,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Generates a GraphQL SDL file from a given GraphQL API URL or schema file.\n *\n * @remarks\n * Introspects a targeted GraphQL API by URL, a `.graphql` SDL or introspection\n * JSON file, and outputs a `.graphql` SDL file.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generateschema}\n */\nexport async function generateSchema(opts: SchemaOptions) {\n const tty = initTTY({ disableTTY: true });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","import { makeCommandOption, applyValidator, rerouteArguments } from './utils.mjs';\n\nfunction Array(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const { arity = 1 } = opts;\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n arity,\n hidden: opts === null || opts === void 0 ? void 0 : opts.hidden,\n description: opts === null || opts === void 0 ? void 0 : opts.description,\n required: opts.required,\n });\n },\n transformer(builder, key, state) {\n let usedName;\n let currentValue = typeof initialValue !== `undefined`\n ? [...initialValue]\n : undefined;\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n usedName = name;\n currentValue = currentValue !== null && currentValue !== void 0 ? currentValue : [];\n currentValue.push(value);\n }\n if (typeof currentValue !== `undefined`) {\n return applyValidator(usedName !== null && usedName !== void 0 ? usedName : key, currentValue, opts.validator);\n }\n else {\n return currentValue;\n }\n },\n });\n}\n\nexport { Array };\n","import { pipe, interval, map } from 'wonka';\n\nimport * as path from 'node:path';\nimport * as t from '../../term';\n\nimport type { TurboWarning } from './types';\nimport { indent } from '../shared/logger';\n\nexport * from '../shared/logger';\n\nconst CWD = process.cwd();\nconst INDENT = ' ';\n\nexport function warningFile(filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n if (!relativePath.startsWith('..')) filePath = relativePath;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Underline),\n filePath,\n t.cmd(t.CSI.Style, t.Style.NoUnderline),\n '\\n',\n ]);\n}\n\nexport function warningMessage(message: TurboWarning) {\n return t.text([\n INDENT,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${message.line}:${message.col}`,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n indent(message.message.trim(), t.text([INDENT, t.Chars.Tab])),\n t.Chars.Newline,\n ]);\n}\n\nconst documentSummary = (documentCount: number | Record<string, number>) => {\n let out = '';\n if (typeof documentCount === 'number') {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Type cache was generated successfully `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `(${documentCount} document types cached)\\n`,\n ]);\n } else {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightGreen),\n `${t.Icons.Tick} Type caches were generated successfully.\\n`,\n ]);\n for (const schemaName in documentCount) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${documentCount[schemaName]} document types cached for the '${schemaName}' schema\\n`,\n ]);\n }\n }\n return out;\n};\n\nexport function warningSummary(warningCount: number) {\n return t.error([t.cmd(t.CSI.Style, t.Style.Red), `${t.Icons.Cross} ${warningCount} warnings\\n`]);\n}\n\nexport function infoSummary(warningCount: number, documentCount: number | Record<string, number>) {\n let out = '';\n if (warningCount) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ` ${warningCount} warnings\\n`,\n ]);\n }\n out += documentSummary(documentCount);\n return out;\n}\n\nexport function warningGithub(message: TurboWarning): void {\n t.githubAnnotation('warning', message.message, {\n file: message.file,\n line: message.line,\n col: message.col,\n });\n}\n\nexport function runningTurbo(file?: number, ofFiles?: number) {\n const progress = file ? (ofFiles ? `(${file}/${ofFiles})` : `(${file})`) : '';\n return pipe(\n interval(150),\n map((state) => {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.dotSpinner[state % t.dotSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n `Scanning files${t.Chars.Ellipsis} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n progress,\n ]);\n })\n );\n}\n\nexport function hintMessage(message: string) {\n return t.error([\n t.cmd(t.CSI.Style, [t.Style.Yellow, t.Style.Bold]),\n `${t.Icons.Warning} Note: `,\n t.cmd(t.CSI.Style, t.Style.Reset),\n `${message.trim()}\\n\\n`,\n ]);\n}\n","import * as path from 'node:path';\nimport type { GraphQLSPConfig, LoadConfigResult } from '@gql.tada/internal';\n\nimport { loadConfig, parseConfig } from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { WriteTarget } from '../shared';\nimport { writeOutput } from '../shared';\nimport type { TurboDocument, GraphQLSourceFile, TurboPath } from './types';\nimport * as logger from './logger';\n\nconst PREAMBLE_IGNORE = ['/* eslint-disable */', '/* prettier-ignore */'].join('\\n') + '\\n';\n\nexport interface TurboOptions {\n /** Whether to fail instead of just logging a warning. */\n failOnWarn: boolean;\n /** The `tsconfig.json` to use for configurations and the TypeScript program.\n * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n tsconfig: string | undefined;\n /** The filename to write the cache file to.\n * @defaultValue The `tadaTurboLocation` configuration option */\n output: string | undefined;\n}\n\nexport async function* run(tty: TTY, opts: TurboOptions): AsyncIterable<ComposeInput> {\n const { runTurbo } = await import('./thread');\n\n let configResult: LoadConfigResult;\n let pluginConfig: GraphQLSPConfig;\n try {\n configResult = await loadConfig(opts.tsconfig);\n pluginConfig = parseConfig(configResult.pluginConfig, configResult.rootPath);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n const projectPath = path.dirname(configResult.configPath);\n\n let destination: WriteTarget;\n const destinations: TurboPath[] = [];\n if ('schema' in pluginConfig) {\n if (!opts.output && tty.pipeTo) {\n destination = tty.pipeTo;\n } else if (opts.output) {\n destination = path.resolve(process.cwd(), opts.output);\n } else if (pluginConfig.tadaTurboLocation) {\n destination = path.resolve(projectPath, pluginConfig.tadaTurboLocation);\n } else if (pluginConfig.tadaOutputLocation) {\n destination = path.resolve(\n projectPath,\n pluginConfig.tadaOutputLocation,\n '..',\n 'graphql-cache.d.ts'\n );\n yield logger.hintMessage(\n 'No output location was specified.\\n' +\n `The turbo cache will by default be saved as ${logger.code('\"graphql-cache.d.ts\"')}.\\n` +\n logger.hint(\n `To change this, add a ${logger.code('\"tadaTurboLocation\"')} in your configuration,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n } else {\n throw logger.errorMessage(\n 'No output path was specified to write the output file to.\\n' +\n logger.hint(\n `You have to either set ${logger.code('\"tadaTurboLocation\"')} in your configuration,\\n` +\n `pass an ${logger.code('--output')} argument to this command,\\n` +\n 'or pipe this command to an output file.'\n )\n );\n }\n } else if ('schemas' in pluginConfig) {\n for (const schemaConfig of pluginConfig.schemas) {\n if (schemaConfig.tadaTurboLocation)\n destinations.push({\n path: path.resolve(projectPath, schemaConfig.tadaTurboLocation),\n schemaName: schemaConfig.name,\n });\n }\n }\n\n const generator = runTurbo({\n rootPath: configResult.rootPath,\n configPath: configResult.configPath,\n pluginConfig,\n turboOutputPath: typeof destination! === 'string' ? destination : destinations,\n });\n\n const documents: TurboDocument[] = [];\n let graphqlSources: GraphQLSourceFile[] = [];\n let warnings = 0;\n let totalFileCount = 0;\n let fileCount = 0;\n\n try {\n if (tty.isInteractive) yield logger.runningTurbo();\n\n for await (const signal of generator) {\n if (signal.kind === 'EXTERNAL_WARNING') {\n yield logger.experimentMessage(\n `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n );\n } else if (signal.kind === 'FILE_COUNT') {\n totalFileCount = signal.fileCount;\n } else if (signal.kind === 'GRAPHQL_SOURCES') {\n graphqlSources = signal.sources;\n } else {\n fileCount++;\n documents.push(...signal.documents);\n warnings += signal.warnings.length;\n if (signal.warnings.length) {\n let buffer = logger.warningFile(signal.filePath);\n for (const warning of signal.warnings) {\n buffer += logger.warningMessage(warning);\n logger.warningGithub(warning);\n }\n yield buffer + '\\n';\n }\n }\n\n if (tty.isInteractive) yield logger.runningTurbo(fileCount, totalFileCount);\n }\n } catch (error) {\n throw logger.externalError('Could not build cache', error);\n }\n\n if ('schema' in pluginConfig) {\n if (warnings && opts.failOnWarn) {\n throw logger.warningSummary(warnings);\n }\n\n try {\n const cache: Record<string, string> = {};\n for (const item of documents) cache[item.argumentKey] = item.documentType;\n const contents = createCacheContents(cache, graphqlSources, destination!);\n await writeOutput(destination!, contents);\n } catch (error) {\n throw logger.externalError('Something went wrong while writing the type cache file', error);\n }\n\n yield logger.infoSummary(warnings, documents.length);\n } else {\n if (opts.output) {\n throw logger.errorMessage(\n 'Output path was specified, while multiple schemas are configured.\\n' +\n logger.hint(\n `You can only output all schemas to their ${logger.code(\n '\"tadaTurboLocation\"'\n )} options\\n` + `when multiple ${logger.code('schemas')} are set up.`\n )\n );\n }\n\n const documentCount: Record<string, number> = {};\n for (const schemaConfig of pluginConfig.schemas) {\n const { name, tadaTurboLocation } = schemaConfig;\n if (!tadaTurboLocation) {\n throw logger.errorMessage(\n `No output path was specified to write the '${name}' type cache to.\\n` +\n logger.hint(\n `You have to set ${logger.code('\"tadaTurboLocation\"')} in each schema configuration.`\n )\n );\n }\n\n try {\n documentCount[name] = 0;\n const cache: Record<string, string> = {};\n for (const item of documents) {\n if (item.schemaName === name) {\n cache[item.argumentKey] = item.documentType;\n documentCount[name]++;\n }\n }\n const destination = path.resolve(projectPath, tadaTurboLocation);\n const contents = createCacheContents(cache, graphqlSources, destination);\n await writeOutput(destination, contents);\n } catch (error) {\n throw logger.externalError(\n `Something went wrong while writing the '${name}' schema's type cache file.`,\n error\n );\n }\n }\n\n if (warnings && opts.failOnWarn) {\n throw logger.warningSummary(warnings);\n } else {\n yield logger.infoSummary(warnings, documentCount);\n }\n }\n}\n\nfunction createCacheContents(\n cache: Record<string, string>,\n graphqlSources: GraphQLSourceFile[],\n turboDestination: WriteTarget\n): string {\n let output = '';\n for (const key in cache) {\n if (output) output += '\\n';\n output += ` ${key}:\\n ${cache[key]};`;\n }\n\n let imports = \"import type { TadaDocumentNode, $tada } from 'gql.tada';\\n\";\n\n const isFilePath =\n typeof turboDestination === 'string' ||\n (turboDestination &&\n typeof turboDestination === 'object' &&\n 'toString' in turboDestination &&\n !('writable' in turboDestination));\n\n const addedImports = new Set<string>();\n for (const source of graphqlSources) {\n for (const importInfo of source.imports) {\n if (isFilePath) {\n const turboPath = turboDestination.toString();\n const sourceDir = path.dirname(source.absolutePath);\n const absoluteImportPath = path.resolve(sourceDir, importInfo.specifier);\n const absoluteTurboPath = path.resolve(turboPath);\n\n if (absoluteImportPath === absoluteTurboPath || addedImports.has(importInfo.specifier))\n continue;\n\n addedImports.add(importInfo.specifier);\n }\n\n imports += importInfo.importClause + '\\n';\n }\n }\n\n return (\n PREAMBLE_IGNORE +\n imports +\n '\\n' +\n \"declare module 'gql.tada' {\\n\" +\n ' interface setupCache {\\n' +\n output +\n '\\n }' +\n '\\n}\\n'\n );\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { TurboOptions } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class TurboCommand extends Command {\n static paths = [['generate', 'turbo'], ['turbo']];\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` read for configuration.',\n });\n\n failOnWarn = Option.Boolean('--fail-on-warn,-w', false, {\n description: 'Triggers an error and a non-zero exit code if any warnings have been reported',\n });\n\n output = Option.String('--output,-o', {\n description:\n 'Specifies where to output the file to.\\tDefault: The `tadaTurboLocation` configuration option',\n });\n\n async execute() {\n // TODO: Add verbose/log/list/debug/trace option that outputs discovered documents (by name) per file\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n failOnWarn: this.failOnWarn,\n output: this.output,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n\n/** Generates a cache typings file for all GraphQL document types ahead of time.\n *\n * @remarks\n * The `generateTurbo()` function generates a cache for all GraphQL document types ahead of time.\n * This cache speeds up type evaluation and is especially useful when it's checked into the\n * repository after making changes to GraphQL documents, which speeds up all further type\n * checks and evaluation.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generateturbo}\n */\nexport async function generateTurbo(opts: TurboOptions) {\n const tty = initTTY({ disableTTY: true });\n const result = await tty.start(run(tty, opts));\n if (result instanceof Error) {\n throw result;\n }\n}\n","import { pipe, interval, map } from 'wonka';\n\nimport * as path from 'node:path';\nimport * as t from '../../term';\nimport type { DiagnosticMessage } from './types';\nimport type { SeveritySummary } from './types';\n\nexport * from '../shared/logger';\nimport { indent } from '../shared/logger';\n\nconst CWD = process.cwd();\nconst INDENT = ' ';\n\nexport function diagnosticFile(filePath: string) {\n const relativePath = path.relative(CWD, filePath);\n if (!relativePath.startsWith('..')) filePath = relativePath;\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Underline),\n filePath,\n t.cmd(t.CSI.Style, t.Style.NoUnderline),\n '\\n',\n ]);\n}\n\nexport function diagnosticMessage(message: DiagnosticMessage) {\n let color = t.Style.Foreground;\n if (message.severity === 'info') {\n color = t.Style.BrightBlue;\n } else if (message.severity === 'warn') {\n color = t.Style.BrightYellow;\n } else if (message.severity === 'error') {\n color = t.Style.BrightRed;\n }\n\n return t.text([\n INDENT,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${message.line}:${message.col}`,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, color),\n message.severity,\n t.Chars.Tab,\n t.cmd(t.CSI.Style, t.Style.Foreground),\n indent(message.message.trim(), t.text([INDENT, t.Chars.Tab, t.Chars.Tab])),\n t.Chars.Newline,\n ]);\n}\n\nexport function infoSummary(summary: SeveritySummary) {\n const { info, error, warn } = summary;\n let out = '';\n if (info) {\n out += t.text([t.cmd(t.CSI.Style, t.Style.Blue), t.Icons.Info, ` ${info} notices\\n`]);\n }\n if (error || warn) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ` ${error + warn} problems (${error} errors, ${warn} warnings)\\n`,\n ]);\n } else {\n out += t.text([t.cmd(t.CSI.Style, t.Style.BrightGreen), t.Icons.Tick, ` No problems found\\n`]);\n }\n return out;\n}\n\nexport function problemsSummary(summary: SeveritySummary) {\n const { info, error, warn } = summary;\n let out = '';\n if (info) {\n out += t.text([t.cmd(t.CSI.Style, t.Style.Blue), t.Icons.Info, ` ${info} notices\\n`]);\n }\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.Red),\n t.Icons.Cross,\n ` ${error + warn} problems (${error} errors, ${warn} warnings)\\n`,\n ]);\n return t.error(out);\n}\n\nexport function diagnosticMessageGithub(message: DiagnosticMessage): void {\n const kind =\n message.severity === 'warn' ? 'warning' : message.severity === 'error' ? 'error' : 'notice';\n t.githubAnnotation(kind, message.message, {\n file: message.file,\n line: message.line,\n col: message.col,\n endLine: message.endLine,\n endColumn: message.endColumn,\n });\n}\n\nexport function runningDiagnostics(file?: number, ofFiles?: number) {\n const progress = file ? (ofFiles ? `(${file}/${ofFiles})` : `(${file})`) : '';\n return pipe(\n interval(150),\n map((state) => {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.dotSpinner[state % t.dotSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n `Checking files${t.Chars.Ellipsis} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n progress,\n ]);\n })\n );\n}\n","import type { GraphQLSPConfig, LoadConfigResult } from '@gql.tada/internal';\nimport { loadConfig, parseConfig } from '@gql.tada/internal';\n\nimport * as logger from './logger';\nimport type { TTY, ComposeInput } from '../../term';\nimport type { Severity, SeveritySummary } from './types';\n\nconst isMinSeverity = (severity: Severity, minSeverity: Severity) => {\n switch (severity) {\n case 'info':\n return minSeverity !== 'warn' && minSeverity !== 'error';\n case 'warn':\n return minSeverity !== 'error';\n case 'error':\n return true;\n }\n};\n\nexport interface FormattedDisplayableDiagnostic {\n severity: Severity;\n message: string;\n line: number;\n col: number;\n file: string | undefined;\n}\n\nexport interface Options {\n failOnWarn: boolean | undefined;\n minSeverity: Severity;\n tsconfig: string | undefined;\n}\n\nexport async function* run(tty: TTY, opts: Options): AsyncIterable<ComposeInput> {\n const { runDiagnostics } = await import('./thread');\n\n let configResult: LoadConfigResult;\n let pluginConfig: GraphQLSPConfig;\n try {\n configResult = await loadConfig(opts.tsconfig);\n pluginConfig = parseConfig(configResult.pluginConfig, configResult.rootPath);\n } catch (error) {\n throw logger.externalError('Failed to load configuration.', error);\n }\n\n const summary: SeveritySummary = { warn: 0, error: 0, info: 0 };\n const minSeverity = opts.minSeverity;\n const generator = runDiagnostics({\n rootPath: configResult.rootPath,\n configPath: configResult.configPath,\n pluginConfig,\n });\n\n let totalFileCount = 0;\n let fileCount = 0;\n\n try {\n if (tty.isInteractive) yield logger.runningDiagnostics();\n\n for await (const signal of generator) {\n if (signal.kind === 'EXTERNAL_WARNING') {\n yield logger.experimentMessage(\n `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n );\n } else if (signal.kind === 'FILE_COUNT') {\n totalFileCount = signal.fileCount;\n } else {\n fileCount++;\n let buffer = '';\n for (const message of signal.messages) {\n summary[message.severity]++;\n if (isMinSeverity(message.severity, minSeverity)) {\n buffer += logger.diagnosticMessage(message);\n logger.diagnosticMessageGithub(message);\n }\n }\n if (buffer) {\n yield logger.diagnosticFile(signal.filePath) + buffer + '\\n';\n }\n }\n\n if (tty.isInteractive) yield logger.runningDiagnostics(fileCount, totalFileCount);\n }\n } catch (error: any) {\n throw logger.externalError('Could not check files', error);\n }\n\n // Reset notice count if it's outside of min severity\n if (minSeverity !== 'info') summary.info = 0;\n\n if ((opts.failOnWarn && summary.warn) || summary.error) {\n throw logger.problemsSummary(summary);\n } else {\n yield logger.infoSummary(summary);\n }\n}\n","import * as t from 'typanion';\nimport { Command, Option } from 'clipanion';\n\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class CheckCommand extends Command {\n static paths = [['check']];\n\n tsconfig = Option.String('--tsconfig,-c', {\n description: 'Specify the `tsconfig.json` used to read',\n });\n\n failOnWarn = Option.Boolean('--fail-on-warn,-w', false, {\n description: 'Triggers an error and a non-zero exit code if any warnings have been reported',\n });\n\n minSeverity =\n Option.String('--level,-l', {\n description: 'The minimum severity of diagnostics to display (info, warn, error)',\n validator: t.isOneOf([t.isLiteral('info'), t.isLiteral('warn'), t.isLiteral('error')]),\n }) || 'info';\n\n async execute() {\n const tty = initTTY();\n const result = await tty.start(\n run(tty, {\n failOnWarn: this.failOnWarn,\n minSeverity: this.minSeverity,\n tsconfig: this.tsconfig,\n })\n );\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n","var fn = new Intl.Collator(0, { numeric:1 }).compare;\n\nexport default function (a, b, bool) {\n\ta = a.split('.');\n\tb = b.split('.');\n\n\treturn fn(a[0], b[0]) || fn(a[1], b[1]) || (\n\t\tb[2] = b.slice(2).join('.'),\n\t\tbool = /[.-]/.test(a[2] = a.slice(2).join('.')),\n\t\tbool == /[.-]/.test(b[2]) ? fn(a[2], b[2]) : bool ? -1 : 1\n\t);\n}\n","import semiver from 'semiver';\n\nexport const MINIMUM_VERSIONS = {\n typescript_embed_lsp: '5.5.0',\n typescript: '4.1.0',\n tada: '1.0.0',\n lsp: '1.0.0',\n};\n\nexport const semverComply = (version: string, compare: string) => {\n const match = version.match(/\\d+\\.\\d+\\.\\d+/);\n return match ? semiver(match[0], compare) >= 0 : false;\n};\n","import type ts from 'typescript';\n\nexport interface SourcePosition {\n fileName: string;\n line: number;\n col: number;\n endLine: number | undefined;\n endColumn: number | undefined;\n}\n\nexport const spanToFilePosition = (\n file: ts.SourceFile,\n span: ts.TextSpan | number\n): SourcePosition => {\n const output: SourcePosition = {\n fileName: file.fileName,\n line: 1,\n col: 1,\n endLine: undefined,\n endColumn: undefined,\n };\n let lineAndChar = file.getLineAndCharacterOfPosition(\n typeof span === 'number' ? span : span.start\n );\n output.line = lineAndChar.line + 1;\n output.col = lineAndChar.character + 1;\n if (typeof span !== 'number' && span.length > 1) {\n lineAndChar = file.getLineAndCharacterOfPosition(span.start + span.length - 1);\n output.endLine = lineAndChar.line + 1;\n output.endColumn = lineAndChar.character + 1;\n }\n return output;\n};\n","/**!\n * The MIT License (MIT)\n * Copyright (c) Microsoft Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and\n * associated documentation files (the \"Software\"), to deal in the Software without restriction,\n * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial\n * portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n * @see {@link https://github.com/microsoft/TypeScript-Website/blob/7f1c6e0577a0df9f945530a876ec87145a8b1fee/packages/typescript-vfs/src/index.ts}\n */\n\nimport type {\n System,\n CompilerOptions,\n CustomTransformers,\n LanguageServiceHost,\n CompilerHost,\n SourceFile,\n} from 'typescript';\n\nimport * as path from 'node:path';\nimport * as fs from 'node:fs';\n\ntype TS = typeof import('typescript');\n\nexport interface VirtualTypeScriptEnvironment {\n sys: System;\n languageService: import('typescript').LanguageService;\n getSourceFile: (fileName: string) => import('typescript').SourceFile | undefined;\n createFile: (fileName: string, content: string) => void;\n updateFile: (\n fileName: string,\n content: string,\n replaceTextSpan?: import('typescript').TextSpan\n ) => void;\n}\n\n/**\n * Makes a virtual copy of the TypeScript environment. This is the main API you want to be using with\n * `@typescript/vfs`. A lot of the other exposed functions are used by this function to get set up.\n *\n * @param sys - an object which conforms to the TS Sys (a shim over read/write access to the fs)\n * @param rootFiles - a list of files which are considered inside the project\n * @param ts - a copy of the TypeScript module\n * @param compilerOptions - the options for this compiler run\n * @param customTransformers - custom transformers for this compiler run\n */\nexport function createVirtualTypeScriptEnvironment(\n sys: System,\n rootFiles: string[],\n ts: TS,\n compilerOptions: CompilerOptions = {},\n customTransformers?: CustomTransformers\n): VirtualTypeScriptEnvironment {\n const mergedCompilerOpts = { ...defaultCompilerOptions(ts), ...compilerOptions };\n\n const { languageServiceHost, updateFile } = createVirtualLanguageServiceHost(\n sys,\n rootFiles,\n mergedCompilerOpts,\n ts,\n customTransformers\n );\n const languageService = ts.createLanguageService(languageServiceHost);\n const diagnostics = languageService.getCompilerOptionsDiagnostics();\n\n if (diagnostics.length) {\n const compilerHost = createVirtualCompilerHost(sys, compilerOptions, ts);\n throw new Error(ts.formatDiagnostics(diagnostics, compilerHost.compilerHost));\n }\n\n return {\n // @ts-ignore\n name: 'vfs',\n sys,\n languageService,\n getSourceFile: (fileName) => languageService.getProgram()?.getSourceFile(fileName),\n\n createFile: (fileName, content) => {\n updateFile(ts.createSourceFile(fileName, content, mergedCompilerOpts.target!, false));\n },\n updateFile: (fileName, content, optPrevTextSpan) => {\n const prevSourceFile = languageService.getProgram()!.getSourceFile(fileName);\n if (!prevSourceFile) {\n throw new Error('Did not find a source file for ' + fileName);\n }\n const prevFullContents = prevSourceFile.text;\n\n // TODO: Validate if the default text span has a fencepost error?\n const prevTextSpan = optPrevTextSpan ?? ts.createTextSpan(0, prevFullContents.length);\n const newText =\n prevFullContents.slice(0, prevTextSpan.start) +\n content +\n prevFullContents.slice(prevTextSpan.start + prevTextSpan.length);\n const newSourceFile = ts.updateSourceFile(prevSourceFile, newText, {\n span: prevTextSpan,\n newLength: content.length,\n });\n\n updateFile(newSourceFile);\n },\n };\n}\n\n// TODO: This could be replaced by grabbing: https://github.com/microsoft/TypeScript/blob/main/src/lib/libs.json\n// and then using that to generate the list of files from the server, but it is not included in the npm package\n\n/**\n * Grab the list of lib files for a particular target, will return a bit more than necessary (by including\n * the dom) but that's OK, we're really working with the constraint that you can't get a list of files\n * when running in a browser.\n *\n * @param target - The compiler settings target baseline\n * @param ts - A copy of the TypeScript module\n */\nexport const knownLibFilesForCompilerOptions = (compilerOptions: CompilerOptions, ts: TS) => {\n const target = compilerOptions.target || ts.ScriptTarget.ES5;\n const lib = compilerOptions.lib || [];\n\n // Note that this will include files which can't be found for particular versions of TS\n // TODO: Replace this with some sort of API call if https://github.com/microsoft/TypeScript/pull/54011\n // or similar is merged.\n const files = [\n 'lib.d.ts',\n 'lib.decorators.d.ts',\n 'lib.decorators.legacy.d.ts',\n 'lib.dom.d.ts',\n 'lib.dom.iterable.d.ts',\n 'lib.webworker.d.ts',\n 'lib.webworker.importscripts.d.ts',\n 'lib.webworker.iterable.d.ts',\n 'lib.scripthost.d.ts',\n 'lib.es5.d.ts',\n 'lib.es6.d.ts',\n 'lib.es2015.collection.d.ts',\n 'lib.es2015.core.d.ts',\n 'lib.es2015.d.ts',\n 'lib.es2015.generator.d.ts',\n 'lib.es2015.iterable.d.ts',\n 'lib.es2015.promise.d.ts',\n 'lib.es2015.proxy.d.ts',\n 'lib.es2015.reflect.d.ts',\n 'lib.es2015.symbol.d.ts',\n 'lib.es2015.symbol.wellknown.d.ts',\n 'lib.es2016.array.include.d.ts',\n 'lib.es2016.d.ts',\n 'lib.es2016.full.d.ts',\n 'lib.es2017.d.ts',\n 'lib.es2017.date.d.ts',\n 'lib.es2017.full.d.ts',\n 'lib.es2017.intl.d.ts',\n 'lib.es2017.object.d.ts',\n 'lib.es2017.sharedmemory.d.ts',\n 'lib.es2017.string.d.ts',\n 'lib.es2017.typedarrays.d.ts',\n 'lib.es2018.asyncgenerator.d.ts',\n 'lib.es2018.asynciterable.d.ts',\n 'lib.es2018.d.ts',\n 'lib.es2018.full.d.ts',\n 'lib.es2018.intl.d.ts',\n 'lib.es2018.promise.d.ts',\n 'lib.es2018.regexp.d.ts',\n 'lib.es2019.array.d.ts',\n 'lib.es2019.d.ts',\n 'lib.es2019.full.d.ts',\n 'lib.es2019.intl.d.ts',\n 'lib.es2019.object.d.ts',\n 'lib.es2019.string.d.ts',\n 'lib.es2019.symbol.d.ts',\n 'lib.es2020.bigint.d.ts',\n 'lib.es2020.d.ts',\n 'lib.es2020.date.d.ts',\n 'lib.es2020.full.d.ts',\n 'lib.es2020.intl.d.ts',\n 'lib.es2020.number.d.ts',\n 'lib.es2020.promise.d.ts',\n 'lib.es2020.sharedmemory.d.ts',\n 'lib.es2020.string.d.ts',\n 'lib.es2020.symbol.wellknown.d.ts',\n 'lib.es2021.d.ts',\n 'lib.es2021.full.d.ts',\n 'lib.es2021.intl.d.ts',\n 'lib.es2021.promise.d.ts',\n 'lib.es2021.string.d.ts',\n 'lib.es2021.weakref.d.ts',\n 'lib.es2022.array.d.ts',\n 'lib.es2022.d.ts',\n 'lib.es2022.error.d.ts',\n 'lib.es2022.full.d.ts',\n 'lib.es2022.intl.d.ts',\n 'lib.es2022.object.d.ts',\n 'lib.es2022.regexp.d.ts',\n 'lib.es2022.sharedmemory.d.ts',\n 'lib.es2022.string.d.ts',\n 'lib.es2023.array.d.ts',\n 'lib.es2023.collection.d.ts',\n 'lib.es2023.d.ts',\n 'lib.es2023.full.d.ts',\n 'lib.esnext.array.d.ts',\n 'lib.esnext.asynciterable.d.ts',\n 'lib.esnext.bigint.d.ts',\n 'lib.esnext.d.ts',\n 'lib.esnext.decorators.d.ts',\n 'lib.esnext.disposable.d.ts',\n 'lib.esnext.full.d.ts',\n 'lib.esnext.intl.d.ts',\n 'lib.esnext.promise.d.ts',\n 'lib.esnext.string.d.ts',\n 'lib.esnext.symbol.d.ts',\n 'lib.esnext.weakref.d.ts',\n ];\n\n const targetToCut = ts.ScriptTarget[target];\n const matches = files.filter((f) => f.startsWith(`lib.${targetToCut.toLowerCase()}`));\n const targetCutIndex = files.indexOf(matches.pop()!);\n\n const getMax = (array: number[]) =>\n array && array.length\n ? array.reduce((max, current) => (current > max ? current : max))\n : undefined;\n\n // Find the index for everything in\n const indexesForCutting = lib.map((lib) => {\n const matches = files.filter((f) => f.startsWith(`lib.${lib.toLowerCase()}`));\n if (matches.length === 0) return 0;\n\n const cutIndex = files.indexOf(matches.pop()!);\n return cutIndex;\n });\n\n const libCutIndex = getMax(indexesForCutting) || 0;\n\n const finalCutIndex = Math.max(targetCutIndex, libCutIndex);\n return files.slice(0, finalCutIndex + 1);\n};\n\n/**\n * Sets up a Map with lib contents by grabbing the necessary files from\n * the local copy of typescript via the file system.\n *\n * The first two args are un-used, but kept around so as to not cause a\n * semver major bump for no gain to module users.\n */\nexport const createDefaultMapFromNodeModules = (\n _compilerOptions: CompilerOptions,\n _ts?: typeof import('typescript'),\n tsLibDirectory?: string\n) => {\n const getLib = (name: string) => {\n const lib = tsLibDirectory || path.dirname(require.resolve('typescript'));\n return fs.readFileSync(path.join(lib, name), 'utf8');\n };\n\n const libFiles = fs.readdirSync(tsLibDirectory || path.dirname(require.resolve('typescript')));\n const knownLibFiles = libFiles.filter((f) => f.startsWith('lib.') && f.endsWith('.d.ts'));\n\n const fsMap = new Map<string, string>();\n knownLibFiles.forEach((lib) => {\n fsMap.set('/' + lib, getLib(lib));\n });\n return fsMap;\n};\n\n/**\n * Adds recursively files from the FS into the map based on the folder\n */\nexport const addAllFilesFromFolder = (map: Map<string, string>, workingDir: string): void => {\n const walk = function (dir: string) {\n let results: string[] = [];\n const list = fs.readdirSync(dir);\n list.forEach(function (file: string) {\n file = path.join(dir, file);\n const stat = fs.statSync(file);\n if (stat && stat.isDirectory()) {\n /* Recurse into a subdirectory */\n results = results.concat(walk(file));\n } else {\n /* Is a file */\n results.push(file);\n }\n });\n return results;\n };\n\n const allFiles = walk(workingDir);\n\n allFiles.forEach((lib) => {\n const fsPath = '/node_modules/@types' + lib.replace(workingDir, '');\n const content = fs.readFileSync(lib, 'utf8');\n const validExtensions = ['.ts', '.tsx'];\n\n if (validExtensions.includes(path.extname(fsPath))) {\n map.set(fsPath, content);\n }\n });\n};\n\n/** Adds all files from `node_modules/@types` into the FS Map */\nexport const addFilesForTypesIntoFolder = (map: Map<string, string>) =>\n addAllFilesFromFolder(map, 'node_modules/@types');\n\nfunction notImplemented(methodName: string): any {\n throw new Error(`Method '${methodName}' is not implemented.`);\n}\n\n/** The default compiler options if TypeScript could ever change the compiler options */\nconst defaultCompilerOptions = (ts: typeof import('typescript')): CompilerOptions => {\n return {\n ...ts.getDefaultCompilerOptions(),\n jsx: ts.JsxEmit.React,\n strict: true,\n esModuleInterop: true,\n module: ts.ModuleKind.ESNext,\n suppressOutputPathCheck: true,\n skipLibCheck: true,\n skipDefaultLibCheck: true,\n moduleResolution: ts.ModuleResolutionKind.NodeJs,\n };\n};\n\n// \"/DOM.d.ts\" => \"/lib.dom.d.ts\"\nconst libize = (path: string) => path.replace('/', '/lib.').toLowerCase();\n\n/**\n * Creates an in-memory System object which can be used in a TypeScript program, this\n * is what provides read/write aspects of the virtual fs\n */\nexport function createSystem(files: Map<string, string>): System {\n return {\n args: [],\n createDirectory: () => notImplemented('createDirectory'),\n // TODO: could make a real file tree\n directoryExists: (directory) => {\n return Array.from(files.keys()).some((path) => path.startsWith(directory));\n },\n exit: () => notImplemented('exit'),\n fileExists: (fileName) => files.has(fileName) || files.has(libize(fileName)),\n getCurrentDirectory: () => '/',\n getDirectories: () => [],\n getExecutingFilePath: () => notImplemented('getExecutingFilePath'),\n readDirectory: (directory) => (directory === '/' ? Array.from(files.keys()) : []),\n readFile: (fileName) => files.get(fileName) || files.get(libize(fileName)),\n resolvePath: (path) => path,\n newLine: '\\n',\n useCaseSensitiveFileNames: true,\n write: () => notImplemented('write'),\n writeFile: (fileName, contents) => {\n files.set(fileName, contents);\n },\n };\n}\n\n/**\n * Creates a file-system backed System object which can be used in a TypeScript program, you provide\n * a set of virtual files which are prioritised over the FS versions, then a path to the root of your\n * project (basically the folder your node_modules lives)\n */\nexport function createFSBackedSystem(\n files: Map<string, string>,\n _projectRoot: string,\n ts: TS,\n tsLibDirectory?: string\n): System {\n // We need to make an isolated folder for the tsconfig, but also need to be able to resolve the\n // existing node_modules structures going back through the history\n const root = _projectRoot + '/vfs';\n\n // The default System in TypeScript\n const nodeSys = ts.sys;\n const tsLib = tsLibDirectory ?? path.dirname(require.resolve('typescript'));\n\n return {\n // @ts-ignore\n name: 'fs-vfs',\n root,\n args: [],\n realpath: (directory) => {\n if (nodeSys.realpath) return nodeSys.realpath(directory);\n return directory;\n },\n createDirectory: () => notImplemented('createDirectory'),\n // TODO: could make a real file tree\n directoryExists: (directory) => {\n return (\n Array.from(files.keys()).some((path) => path.startsWith(directory)) ||\n nodeSys.directoryExists(directory)\n );\n },\n exit: nodeSys.exit,\n fileExists: (fileName) => {\n if (files.has(fileName)) return true;\n // Don't let other tsconfigs end up touching the vfs\n if (fileName.includes('tsconfig.json') || fileName.includes('tsconfig.json')) return false;\n if (fileName.startsWith('/lib')) {\n const tsLibName = `${tsLib}/${fileName.replace('/', '')}`;\n return nodeSys.fileExists(tsLibName);\n }\n return nodeSys.fileExists(fileName);\n },\n getCurrentDirectory: () => root,\n getDirectories: nodeSys.getDirectories,\n getExecutingFilePath: () => notImplemented('getExecutingFilePath'),\n readDirectory: (...args) => {\n if (args[0] === '/') {\n return Array.from(files.keys());\n } else {\n return nodeSys.readDirectory(...args);\n }\n },\n readFile: (fileName) => {\n if (files.has(fileName)) return files.get(fileName);\n if (fileName.startsWith('/lib')) {\n const tsLibName = `${tsLib}/${fileName.replace('/', '')}`;\n const result = nodeSys.readFile(tsLibName);\n if (!result) {\n const libs = nodeSys.readDirectory(tsLib);\n throw new Error(\n `TSVFS: A request was made for ${tsLibName} but there wasn't a file found in the file map. You likely have a mismatch in the compiler options for the CDN download vs the compiler program. Existing Libs: ${libs}.`\n );\n }\n return result;\n }\n return nodeSys.readFile(fileName);\n },\n resolvePath: (path) => {\n if (files.has(path)) return path;\n return nodeSys.resolvePath(path);\n },\n newLine: '\\n',\n useCaseSensitiveFileNames: true,\n write: () => notImplemented('write'),\n writeFile: (fileName, contents) => {\n files.set(fileName, contents);\n },\n };\n}\n\n/**\n * Creates an in-memory CompilerHost -which is essentially an extra wrapper to System\n * which works with TypeScript objects - returns both a compiler host, and a way to add new SourceFile\n * instances to the in-memory file system.\n */\nexport function createVirtualCompilerHost(sys: System, compilerOptions: CompilerOptions, ts: TS) {\n const sourceFiles = new Map<string, SourceFile>();\n const save = (sourceFile: SourceFile) => {\n sourceFiles.set(sourceFile.fileName, sourceFile);\n return sourceFile;\n };\n\n type Return = {\n compilerHost: CompilerHost;\n updateFile: (sourceFile: SourceFile) => boolean;\n };\n\n const vHost: Return = {\n compilerHost: {\n ...sys,\n getCanonicalFileName: (fileName) => fileName,\n getDefaultLibFileName: () => '/' + ts.getDefaultLibFileName(compilerOptions), // '/lib.d.ts',\n // getDefaultLibLocation: () => '/',\n getDirectories: () => [],\n getNewLine: () => sys.newLine,\n getSourceFile: (fileName) => {\n return (\n sourceFiles.get(fileName) ||\n save(\n ts.createSourceFile(\n fileName,\n sys.readFile(fileName)!,\n compilerOptions.target || defaultCompilerOptions(ts).target!,\n false\n )\n )\n );\n },\n useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,\n },\n updateFile: (sourceFile) => {\n const alreadyExists = sourceFiles.has(sourceFile.fileName);\n sys.writeFile(sourceFile.fileName, sourceFile.text);\n sourceFiles.set(sourceFile.fileName, sourceFile);\n return alreadyExists;\n },\n };\n return vHost;\n}\n\n/**\n * Creates an object which can host a language service against the virtual file-system\n */\nexport function createVirtualLanguageServiceHost(\n sys: System,\n rootFiles: string[],\n compilerOptions: CompilerOptions,\n ts: TS,\n customTransformers?: CustomTransformers\n) {\n const fileNames = [...rootFiles];\n const { compilerHost, updateFile } = createVirtualCompilerHost(sys, compilerOptions, ts);\n const fileVersions = new Map<string, string>();\n let projectVersion = 0;\n const languageServiceHost: LanguageServiceHost = {\n ...compilerHost,\n getProjectVersion: () => projectVersion.toString(),\n getCompilationSettings: () => compilerOptions,\n getCustomTransformers: () => customTransformers,\n // A couple weeks of 4.8 TypeScript nightlies had a bug where the Program's\n // list of files was just a reference to the array returned by this host method,\n // which means mutations by the host that ought to result in a new Program being\n // created were not detected, since the old list of files and the new list of files\n // were in fact a reference to the same underlying array. That was fixed in\n // https://github.com/microsoft/TypeScript/pull/49813, but since the twoslash runner\n // is used in bisecting for changes, it needs to guard against being busted in that\n // couple-week period, so we defensively make a slice here.\n getScriptFileNames: () => fileNames.slice(),\n getScriptSnapshot: (fileName) => {\n const contents = sys.readFile(fileName);\n if (contents) {\n return ts.ScriptSnapshot.fromString(contents);\n }\n return;\n },\n getScriptVersion: (fileName) => {\n return fileVersions.get(fileName) || '0';\n },\n writeFile: sys.writeFile,\n };\n\n type Return = {\n languageServiceHost: LanguageServiceHost;\n updateFile: (sourceFile: import('typescript').SourceFile) => void;\n };\n\n const lsHost: Return = {\n languageServiceHost,\n updateFile: (sourceFile) => {\n projectVersion++;\n fileVersions.set(sourceFile.fileName, projectVersion.toString());\n if (!fileNames.includes(sourceFile.fileName)) {\n fileNames.push(sourceFile.fileName);\n }\n updateFile(sourceFile);\n },\n };\n return lsHost;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.binarySearch = void 0;\nfunction binarySearch(offsets, start) {\n let low = 0;\n let high = offsets.length - 1;\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const midValue = offsets[mid];\n if (midValue < start) {\n low = mid + 1;\n }\n else if (midValue > start) {\n high = mid - 1;\n }\n else {\n low = mid;\n high = mid;\n break;\n }\n }\n return Math.max(Math.min(low, high, offsets.length - 1), 0);\n}\nexports.binarySearch = binarySearch;\n//# sourceMappingURL=binarySearch.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getStack = exports.track = exports.resetOffsetStack = exports.offsetStack = exports.setTracking = void 0;\nlet tracking = true;\nlet stackOffset = 0;\nfunction setTracking(value) {\n tracking = value;\n}\nexports.setTracking = setTracking;\nfunction offsetStack() {\n stackOffset++;\n}\nexports.offsetStack = offsetStack;\nfunction resetOffsetStack() {\n stackOffset--;\n}\nexports.resetOffsetStack = resetOffsetStack;\nfunction track(segments, stacks = []) {\n return [\n new Proxy(segments, {\n get(target, prop, receiver) {\n if (tracking) {\n if (prop === 'push')\n return push;\n if (prop === 'pop')\n return pop;\n if (prop === 'shift')\n return shift;\n if (prop === 'unshift')\n return unshift;\n if (prop === 'splice')\n return splice;\n if (prop === 'sort')\n return sort;\n if (prop === 'reverse')\n return reverse;\n }\n return Reflect.get(target, prop, receiver);\n }\n }),\n stacks,\n ];\n function push(...items) {\n stacks.push({ stack: getStack(), length: items.length });\n return segments.push(...items);\n }\n function pop() {\n if (stacks.length) {\n const last = stacks[stacks.length - 1];\n if (last.length > 1) {\n last.length--;\n }\n else {\n stacks.pop();\n }\n }\n return segments.pop();\n }\n function shift() {\n if (stacks.length) {\n const first = stacks[0];\n if (first.length > 1) {\n first.length--;\n }\n else {\n stacks.shift();\n }\n }\n return segments.shift();\n }\n function unshift(...items) {\n stacks.unshift({ stack: getStack(), length: items.length });\n return segments.unshift(...items);\n }\n function splice(start, deleteCount, ...items) {\n if (deleteCount === undefined) {\n deleteCount = segments.length - start;\n }\n let _stackStart = 0;\n let operateIndex;\n for (let i = 0; i < stacks.length; i++) {\n const stack = stacks[i];\n const stackStart = _stackStart;\n const stackEnd = stackStart + stack.length;\n _stackStart = stackEnd;\n if (start >= stackStart) {\n operateIndex = i + 1;\n const originalLength = stack.length;\n stack.length = start - stackStart;\n stacks.splice(operateIndex, 0, { stack: stack.stack, length: originalLength - stack.length });\n break;\n }\n }\n if (operateIndex === undefined) {\n throw new Error('Invalid splice operation');\n }\n let _deleteCount = deleteCount;\n for (let i = operateIndex; i < stacks.length; i++) {\n const stack = stacks[i];\n while (_deleteCount > 0 && stack.length > 0) {\n stack.length--;\n _deleteCount--;\n }\n if (_deleteCount === 0) {\n break;\n }\n }\n stacks.splice(operateIndex, 0, { stack: getStack(), length: items.length });\n return segments.splice(start, deleteCount, ...items);\n }\n function sort(compareFn) {\n stacks.splice(0, stacks.length, { stack: getStack(), length: segments.length });\n return segments.sort(compareFn);\n }\n function reverse() {\n stacks.splice(0, stacks.length, { stack: getStack(), length: segments.length });\n return segments.reverse();\n }\n}\nexports.track = track;\nfunction getStack() {\n const stack = new Error().stack;\n let source = stack.split('\\n')[3 + stackOffset].trim();\n if (source.endsWith(')')) {\n source = source.slice(source.lastIndexOf('(') + 1, -1);\n }\n else {\n source = source.slice(source.lastIndexOf(' ') + 1);\n }\n return source;\n}\nexports.getStack = getStack;\n//# sourceMappingURL=track.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=types.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.replaceRange = exports.replaceSourceRange = exports.replaceAll = exports.replace = exports.create = exports.toString = exports.getLength = void 0;\nconst binarySearch_1 = require(\"./binarySearch\");\nconst track_1 = require(\"./track\");\n__exportStar(require(\"./types\"), exports);\n__exportStar(require(\"./track\"), exports);\nfunction getLength(segments) {\n let length = 0;\n for (const segment of segments) {\n length += typeof segment == 'string' ? segment.length : segment[0].length;\n }\n return length;\n}\nexports.getLength = getLength;\nfunction toString(segments) {\n return segments.map(s => typeof s === 'string' ? s : s[0]).join('');\n}\nexports.toString = toString;\nfunction create(source) {\n return [[source, undefined, 0]];\n}\nexports.create = create;\nfunction replace(segments, pattern, ...replacers) {\n const str = toString(segments);\n const match = str.match(pattern);\n if (match && match.index !== undefined) {\n const startOffset = match.index;\n const endOffset = startOffset + match[0].length;\n (0, track_1.offsetStack)();\n replaceRange(segments, startOffset, endOffset, ...replacers.map(replacer => typeof replacer === 'function' ? replacer(match[0]) : replacer));\n (0, track_1.resetOffsetStack)();\n }\n}\nexports.replace = replace;\nfunction replaceAll(segments, pattern, ...replacers) {\n const str = toString(segments);\n const allMatch = str.matchAll(pattern);\n let length = str.length;\n let lengthDiff = 0;\n for (const match of allMatch) {\n if (match.index !== undefined) {\n const startOffset = match.index + lengthDiff;\n const endOffset = startOffset + match[0].length;\n (0, track_1.offsetStack)();\n replaceRange(segments, startOffset, endOffset, ...replacers.map(replacer => typeof replacer === 'function' ? replacer(match[0]) : replacer));\n (0, track_1.resetOffsetStack)();\n const newLength = getLength(segments);\n lengthDiff += newLength - length;\n length = newLength;\n }\n }\n}\nexports.replaceAll = replaceAll;\nfunction replaceSourceRange(segments, source, startOffset, endOffset, ...newSegments) {\n for (const segment of segments) {\n if (typeof segment === 'string') {\n continue;\n }\n if (segment[1] === source) {\n const segmentStart = segment[2];\n const segmentEnd = segment[2] + segment[0].length;\n if (segmentStart <= startOffset && segmentEnd >= endOffset) {\n const inserts = [];\n if (startOffset > segmentStart) {\n inserts.push(trimSegmentEnd(segment, startOffset - segmentStart));\n }\n for (const newSegment of newSegments) {\n inserts.push(newSegment);\n }\n if (endOffset < segmentEnd) {\n inserts.push(trimSegmentStart(segment, endOffset - segmentEnd));\n }\n combineStrings(inserts);\n (0, track_1.offsetStack)();\n segments.splice(segments.indexOf(segment), 1, ...inserts);\n (0, track_1.resetOffsetStack)();\n return true;\n }\n }\n }\n return false;\n}\nexports.replaceSourceRange = replaceSourceRange;\nfunction replaceRange(segments, startOffset, endOffset, ...newSegments) {\n const offsets = toOffsets(segments);\n const startIndex = (0, binarySearch_1.binarySearch)(offsets, startOffset);\n const endIndex = (0, binarySearch_1.binarySearch)(offsets, endOffset);\n const startSegment = segments[startIndex];\n const endSegment = segments[endIndex];\n const startSegmentStart = offsets[startIndex];\n const endSegmentStart = offsets[endIndex];\n const endSegmentEnd = offsets[endIndex] + (typeof endSegment === 'string' ? endSegment.length : endSegment[0].length);\n const inserts = [];\n if (startOffset > startSegmentStart) {\n inserts.push(trimSegmentEnd(startSegment, startOffset - startSegmentStart));\n }\n for (const newSegment of newSegments) {\n inserts.push(newSegment);\n }\n if (endOffset < endSegmentEnd) {\n inserts.push(trimSegmentStart(endSegment, endOffset - endSegmentStart));\n }\n combineStrings(inserts);\n (0, track_1.offsetStack)();\n segments.splice(startIndex, endIndex - startIndex + 1, ...inserts);\n (0, track_1.resetOffsetStack)();\n}\nexports.replaceRange = replaceRange;\nfunction combineStrings(segments) {\n for (let i = segments.length - 1; i >= 1; i--) {\n if (typeof segments[i] === 'string' && typeof segments[i - 1] === 'string') {\n segments[i - 1] = segments[i - 1] + segments[i];\n (0, track_1.offsetStack)();\n segments.splice(i, 1);\n (0, track_1.resetOffsetStack)();\n }\n }\n}\nfunction trimSegmentEnd(segment, trimEnd) {\n if (typeof segment === 'string') {\n return segment.slice(0, trimEnd);\n }\n return [\n segment[0].slice(0, trimEnd),\n ...segment.slice(1),\n ];\n}\nfunction trimSegmentStart(segment, trimStart) {\n if (typeof segment === 'string') {\n return segment.slice(trimStart);\n }\n if (trimStart < 0) {\n trimStart += segment[0].length;\n }\n return [\n segment[0].slice(trimStart),\n segment[1],\n segment[2] + trimStart,\n ...segment.slice(3),\n ];\n}\nfunction toOffsets(segments) {\n const offsets = [];\n let offset = 0;\n for (const segment of segments) {\n offsets.push(offset);\n offset += typeof segment == 'string' ? segment.length : segment[0].length;\n }\n return offsets;\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.binarySearch = void 0;\nfunction binarySearch(values, searchValue) {\n let low = 0;\n let high = values.length - 1;\n let match;\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const midValue = values[mid];\n if (midValue < searchValue) {\n low = mid + 1;\n }\n else if (midValue > searchValue) {\n high = mid - 1;\n }\n else {\n low = mid;\n high = mid;\n match = mid;\n break;\n }\n }\n const finalLow = Math.max(Math.min(low, high, values.length - 1), 0);\n const finalHigh = Math.min(Math.max(low, high, 0), values.length - 1);\n return { low: finalLow, high: finalHigh, match };\n}\nexports.binarySearch = binarySearch;\n//# sourceMappingURL=binarySearch.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.translateOffset = void 0;\nfunction translateOffset(start, fromOffsets, toOffsets, lengths) {\n for (let i = 0; i < fromOffsets.length; i++) {\n const fromOffset = fromOffsets[i];\n const toOffset = toOffsets[i];\n const length = lengths[i];\n if (start >= fromOffset && start <= fromOffset + length) {\n return toOffset + start - fromOffset;\n }\n }\n}\nexports.translateOffset = translateOffset;\n//# sourceMappingURL=translateOffset.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SourceMap = void 0;\nconst binarySearch_1 = require(\"./binarySearch\");\nconst translateOffset_1 = require(\"./translateOffset\");\nclass SourceMap {\n constructor(mappings) {\n this.mappings = mappings;\n }\n getSourceOffset(generatedOffset) {\n for (const mapped of this.findMatching(generatedOffset, 'generatedOffsets', 'sourceOffsets')) {\n return mapped;\n }\n }\n getGeneratedOffset(sourceOffset) {\n for (const mapped of this.findMatching(sourceOffset, 'sourceOffsets', 'generatedOffsets')) {\n return mapped;\n }\n }\n getSourceOffsets(generatedOffset) {\n return this.findMatching(generatedOffset, 'generatedOffsets', 'sourceOffsets');\n }\n getGeneratedOffsets(sourceOffset) {\n return this.findMatching(sourceOffset, 'sourceOffsets', 'generatedOffsets');\n }\n *findMatching(offset, fromRange, toRange) {\n const memo = this.getMemoBasedOnRange(fromRange);\n if (memo.offsets.length === 0) {\n return;\n }\n const { low: start, high: end } = (0, binarySearch_1.binarySearch)(memo.offsets, offset);\n const skip = new Set();\n for (let i = start; i <= end; i++) {\n for (const mapping of memo.mappings[i]) {\n if (skip.has(mapping)) {\n continue;\n }\n skip.add(mapping);\n const mapped = (0, translateOffset_1.translateOffset)(offset, mapping[fromRange], mapping[toRange], mapping.lengths);\n if (mapped !== undefined) {\n yield [mapped, mapping];\n }\n }\n }\n }\n getMemoBasedOnRange(fromRange) {\n return fromRange === 'sourceOffsets'\n ? this.sourceCodeOffsetsMemo ??= this.createMemo('sourceOffsets')\n : this.generatedCodeOffsetsMemo ??= this.createMemo('generatedOffsets');\n }\n createMemo(key) {\n const offsetsSet = new Set();\n for (const mapping of this.mappings) {\n for (let i = 0; i < mapping[key].length; i++) {\n offsetsSet.add(mapping[key][i]);\n offsetsSet.add(mapping[key][i] + mapping.lengths[i]);\n }\n }\n const offsets = [...offsetsSet].sort((a, b) => a - b);\n const mappings = offsets.map(() => new Set());\n for (const mapping of this.mappings) {\n for (let i = 0; i < mapping[key].length; i++) {\n const startIndex = (0, binarySearch_1.binarySearch)(offsets, mapping[key][i]).match;\n const endIndex = (0, binarySearch_1.binarySearch)(offsets, mapping[key][i] + mapping.lengths[i]).match;\n for (let i = startIndex; i <= endIndex; i++) {\n mappings[i].add(mapping);\n }\n }\n }\n return { offsets, mappings };\n }\n}\nexports.SourceMap = SourceMap;\n//# sourceMappingURL=sourceMap.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.buildMappings = void 0;\nfunction buildMappings(chunks) {\n let length = 0;\n const mappings = [];\n for (const segment of chunks) {\n if (typeof segment === 'string') {\n length += segment.length;\n }\n else {\n mappings.push({\n source: segment[1],\n sourceOffsets: [segment[2]],\n generatedOffsets: [length],\n lengths: [segment[0].length],\n data: segment[3],\n });\n length += segment[0].length;\n }\n }\n return mappings;\n}\nexports.buildMappings = buildMappings;\n//# sourceMappingURL=buildMappings.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.buildStacks = void 0;\nfunction buildStacks(chunks, stacks) {\n let offset = 0;\n let index = 0;\n const result = [];\n for (const stack of stacks) {\n const start = offset;\n for (let i = 0; i < stack.length; i++) {\n const segment = chunks[index + i];\n if (typeof segment === 'string') {\n offset += segment.length;\n }\n else {\n offset += segment[0].length;\n }\n }\n index += stack.length;\n result.push({\n source: stack.stack,\n range: [start, offset],\n });\n }\n return result;\n}\nexports.buildStacks = buildStacks;\n//# sourceMappingURL=buildStacks.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"muggle-string\"), exports);\n__exportStar(require(\"./lib/sourceMap\"), exports);\n__exportStar(require(\"./lib/translateOffset\"), exports);\n__exportStar(require(\"./lib/buildMappings\"), exports);\n__exportStar(require(\"./lib/buildStacks\"), exports);\n//# sourceMappingURL=index.js.map","import type ts from 'typescript';\nimport { SourceMap } from '@volar/source-map';\nimport type { Mapping } from '@volar/source-map';\n\nexport type VirtualMap = Map<string, SourceMappedFile>;\nexport type { Mapping };\n\nexport interface FileSpan extends ts.TextSpan {\n fileName: string;\n}\n\nexport class SourceMappedFile extends SourceMap {\n readonly sourceFile: ts.SourceFile;\n readonly sourceFileId: string;\n readonly generatedFileId: string;\n\n constructor(\n mappings: readonly Mapping[],\n params: {\n sourceFile: ts.SourceFile;\n sourceFileId: string;\n generatedFileId: string;\n }\n ) {\n super(mappings as Mapping[]);\n this.sourceFile = params.sourceFile;\n this.sourceFileId = params.sourceFileId;\n this.generatedFileId = params.generatedFileId;\n }\n\n getSourceSpan(span: ts.TextSpan | number): FileSpan {\n const sourceStart = this.getSourceOffset(typeof span === 'number' ? span : span.start);\n if (sourceStart != null) {\n const sourceEnd =\n typeof span !== 'number' ? this.getSourceOffset(span.start + span.length - 1) : null;\n return {\n fileName: this.sourceFileId,\n start: sourceStart[0],\n length:\n sourceEnd != null\n ? sourceEnd[0] - sourceStart[0] + 1\n : typeof span !== 'number'\n ? span.length\n : 1,\n };\n } else {\n return {\n fileName: this.generatedFileId,\n start: typeof span !== 'number' ? span.start : span,\n length: typeof span !== 'number' ? span.length : 1,\n };\n }\n }\n}\n","import ts from 'typescript';\nimport * as path from 'node:path';\nimport type { GraphQLSPConfig } from '@gql.tada/internal';\nimport { createVirtualLanguageServiceHost } from './vendor/typescript-vfs';\n\nimport type { VirtualMap, SourceMappedFile, FileSpan } from './mapping';\n\nimport type { SourcePosition } from './utils';\nimport { spanToFilePosition } from './utils';\n\nfunction maybeBind<T extends Function>(that: object, fn: T | undefined): T {\n return fn ? fn.bind(that) : fn;\n}\n\nexport interface PluginCreateInfo<Config extends {} = GraphQLSPConfig>\n extends ts.server.PluginCreateInfo {\n config: Config;\n}\n\nexport interface ProgramContainer {\n readonly program: ts.Program;\n readonly languageService: ts.LanguageService;\n buildPluginInfo<Config extends {}>(config: Config): PluginCreateInfo<Config>;\n\n getSourceFile(fileId: string): ts.SourceFile | undefined;\n getSourceFiles(): readonly ts.SourceFile[];\n getSourceMappedFile(fileId: string | ts.SourceFile): SourceMappedFile | undefined;\n getSourceSpan(fileId: string | ts.SourceFile, span: ts.TextSpan | number): FileSpan;\n getSourcePosition(fileId: string | ts.SourceFile, span: ts.TextSpan | number): SourcePosition;\n}\n\nexport interface ContainerParams {\n virtualMap: VirtualMap;\n projectRoot: string;\n compilerHost: ts.CompilerHost;\n rootNames: readonly string[];\n options: ts.CompilerOptions;\n system: ts.System;\n}\n\nexport const buildContainer = (params: ContainerParams): ProgramContainer => {\n let program: ts.Program | undefined;\n let service: ts.LanguageService | undefined;\n let serviceHost: ts.LanguageServiceHost | undefined;\n let pluginInfo: PluginCreateInfo<any> | undefined;\n\n const getLanguageServiceHost = () =>\n serviceHost ||\n (serviceHost = createVirtualLanguageServiceHost(\n params.system,\n [...params.rootNames],\n params.options,\n ts\n ).languageServiceHost);\n\n const getLanguageService = () =>\n service ||\n (service = buildLanguageService({\n system: params.system,\n rootNames: params.rootNames,\n virtualMap: params.virtualMap,\n options: params.options,\n projectRoot: params.projectRoot,\n languageServiceHost: getLanguageServiceHost(),\n }));\n\n const getProgram = () => {\n if (!program) {\n program =\n getLanguageService().getProgram() ||\n ts.createProgram({\n rootNames: params.rootNames,\n options: params.options,\n host: params.compilerHost,\n });\n }\n return program;\n };\n\n return {\n get program() {\n return getProgram();\n },\n get languageService() {\n return getLanguageService();\n },\n buildPluginInfo(config) {\n return (\n pluginInfo ||\n (pluginInfo = buildPluginInfo({\n getLanguageService,\n getLanguageServiceHost,\n projectRoot: params.projectRoot,\n rootNames: params.rootNames,\n system: params.system,\n options: params.options,\n config,\n }))\n );\n },\n\n getSourceFile(fileId) {\n return getProgram().getSourceFile(fileId);\n },\n getSourceFiles() {\n return getProgram().getSourceFiles();\n },\n getSourceMappedFile(file) {\n const fileId = typeof file !== 'string' ? file.fileName : file;\n return params.virtualMap.get(fileId);\n },\n getSourceSpan(file, span) {\n const fileId = typeof file !== 'string' ? file.fileName : file;\n const mappedFile = params.virtualMap.get(fileId);\n return mappedFile\n ? mappedFile.getSourceSpan(span)\n : {\n fileName: fileId,\n start: typeof span !== 'number' ? span.start : span,\n length: typeof span !== 'number' ? span.length : 1,\n };\n },\n getSourcePosition(file, position) {\n const fileId = typeof file !== 'string' ? file.fileName : file;\n const mappedFile = params.virtualMap.get(fileId);\n if (mappedFile) {\n const span = mappedFile.getSourceSpan(position);\n if (span.fileName === mappedFile.sourceFileId)\n return spanToFilePosition(mappedFile.sourceFile, span);\n }\n return spanToFilePosition(\n typeof file === 'string' ? getProgram().getSourceFile(file)! : file,\n position\n );\n },\n };\n};\n\nconst buildProgram = (params: {\n program: ts.Program;\n virtualMap: VirtualMap;\n projectRoot: string;\n}): ts.Program => {\n const { program, virtualMap, projectRoot } = params;\n\n const isSourceFileFromExternalLibrary = maybeBind(\n program,\n program.isSourceFileFromExternalLibrary\n );\n const getModeForResolutionAtIndex = maybeBind(program, program.getModeForResolutionAtIndex);\n const getSourceFile = maybeBind(program, program.getSourceFile);\n const getSourceFiles = maybeBind(program, program.getSourceFiles);\n\n /** Remap source file to generated source file if it's a mapped file */\n const mapSourceFileFn =\n <TReturn, TArgs extends readonly any[]>(\n fileFn: (file: ts.SourceFile, ...args: TArgs) => TReturn\n ) =>\n (file: ts.SourceFile | undefined, ...args: TArgs): TReturn => {\n const mappedFile = file && virtualMap.get(file.fileName);\n if (mappedFile && mappedFile.sourceFileId === file?.fileName)\n file = getSourceFile(mappedFile.generatedFileId) || file;\n return fileFn.call(program, file!, ...args);\n };\n\n return Object.assign(program, {\n getSyntacticDiagnostics: mapSourceFileFn(program.getSyntacticDiagnostics),\n getSemanticDiagnostics: mapSourceFileFn(program.getSemanticDiagnostics),\n getDeclarationDiagnostics: mapSourceFileFn(program.getDeclarationDiagnostics),\n isSourceFileDefaultLibrary: mapSourceFileFn(program.isSourceFileDefaultLibrary),\n getModeForUsageLocation: mapSourceFileFn(program.getModeForUsageLocation),\n\n isSourceFileFromExternalLibrary(source) {\n const mappedFile = virtualMap.get(source.fileName);\n return (\n !!(mappedFile && mappedFile.sourceFileId === source.fileName) ||\n isSourceFileFromExternalLibrary(source)\n );\n },\n\n getSourceFiles() {\n const sourceFiles: ts.SourceFile[] = [];\n for (const sourceFile of getSourceFiles()) {\n const relativePath = path.relative(projectRoot, sourceFile.fileName);\n if (\n !relativePath.startsWith('..') &&\n !program.isSourceFileFromExternalLibrary(sourceFile)\n ) {\n sourceFiles.push(sourceFile);\n }\n }\n return sourceFiles;\n },\n\n getSourceFile(fileId) {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) fileId = mappedFile.generatedFileId;\n return getSourceFile(fileId);\n },\n\n getModeForResolutionAtIndex(file, index) {\n const mappedFile = virtualMap.get(file.fileName);\n if (mappedFile && mappedFile.sourceFileId === file.fileName) {\n file = getSourceFile(mappedFile.generatedFileId) || file;\n index = mappedFile.getGeneratedOffset(index)?.[0] ?? index;\n }\n return getModeForResolutionAtIndex(file, index);\n },\n } satisfies Partial<ts.Program>);\n};\n\nconst buildLanguageService = (params: {\n virtualMap: VirtualMap;\n languageServiceHost: ts.LanguageServiceHost;\n system: ts.System;\n rootNames: readonly string[];\n projectRoot: string;\n options: ts.CompilerOptions;\n}): ts.LanguageService => {\n const { virtualMap } = params;\n const languageService = ts.createLanguageService(params.languageServiceHost);\n const getProgram = maybeBind(languageService, languageService.getProgram);\n\n /** Remap filename to generated file if it's a mapped file */\n const mapFileFn =\n <TReturn, TArgs extends readonly any[]>(fileFn: (fileId: string, ...args: TArgs) => TReturn) =>\n (fileId: string, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) fileId = mappedFile.generatedFileId;\n return fileFn.call(languageService, fileId, ...args);\n };\n\n /** Remap input to generated file and span if it's a mapped file */\n const mapFileTextSpanFn =\n <TReturn, TArgs extends readonly any[]>(\n textSpanFn: (fileId: string, span: ts.TextSpan, ...args: TArgs) => TReturn\n ) =>\n (fileId: string, span: ts.TextSpan, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) {\n fileId = mappedFile.generatedFileId;\n const start = mappedFile.getGeneratedOffset(span.start)?.[0];\n const end = mappedFile.getGeneratedOffset(span.start + span.length - 1)?.[0];\n if (start != null) {\n span = { start, length: span.length };\n if (end != null) span.length = end - start + 1;\n }\n }\n return textSpanFn.call(languageService, fileId, span, ...args);\n };\n\n /** Remap input to generated file and range if it's a mapped file */\n const mapFileTextRangeFn =\n <TReturn, TArgs extends readonly any[]>(\n textSpanFn: (fileId: string, range: ts.TextRange, ...args: TArgs) => TReturn\n ) =>\n (fileId: string, range: ts.TextRange, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) {\n fileId = mappedFile.generatedFileId;\n const pos = mappedFile.getGeneratedOffset(range.pos)?.[0];\n const end = mappedFile.getGeneratedOffset(range.end)?.[0];\n if (pos != null) {\n range = { pos, end: pos + (range.end - range.pos) };\n if (end != null) range.end = end;\n }\n }\n return textSpanFn.call(languageService, fileId, range, ...args);\n };\n\n /** Remap input to generated file and position if it's a mapped file */\n const mapFilePositionFn =\n <TReturn, TArgs extends readonly any[]>(\n positionFn: (fileId: string, position: number, ...args: TArgs) => TReturn\n ) =>\n (fileId: string, position: number, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) {\n fileId = mappedFile.generatedFileId;\n position = mappedFile.getGeneratedOffset(position)?.[0] ?? position;\n }\n return positionFn.call(languageService, fileId, position, ...args);\n };\n\n /** Remap input to generated file and position if it's a mapped file */\n const mapFileStartEndFn =\n <TReturn, TArgs extends readonly any[]>(\n positionFn: (fileId: string, start: number, end: number, ...args: TArgs) => TReturn\n ) =>\n (fileId: string, start: number, end: number, ...args: TArgs): TReturn => {\n const mappedFile = virtualMap.get(fileId);\n if (mappedFile && mappedFile.sourceFileId === fileId) {\n fileId = mappedFile.generatedFileId;\n start = mappedFile.getGeneratedOffset(start)?.[0] ?? start;\n end = mappedFile.getGeneratedOffset(end)?.[0] ?? end;\n }\n return positionFn.call(languageService, fileId, start, end, ...args);\n };\n\n let program: ts.Program | undefined;\n\n return Object.assign(languageService, {\n getProgram() {\n if (program) {\n return program;\n } else {\n const serviceProgram = getProgram();\n return serviceProgram\n ? (program = buildProgram({\n program: serviceProgram,\n virtualMap: params.virtualMap,\n projectRoot: params.projectRoot,\n }))\n : undefined;\n }\n },\n\n getReferencesAtPosition: mapFilePositionFn(languageService.getReferencesAtPosition),\n findReferences: mapFilePositionFn(languageService.findReferences),\n getDefinitionAtPosition: mapFilePositionFn(languageService.getDefinitionAtPosition),\n getDefinitionAndBoundSpan: mapFilePositionFn(languageService.getDefinitionAndBoundSpan),\n getTypeDefinitionAtPosition: mapFilePositionFn(languageService.getTypeDefinitionAtPosition),\n getImplementationAtPosition: mapFilePositionFn(languageService.getImplementationAtPosition),\n getCompletionsAtPosition: mapFilePositionFn(languageService.getCompletionsAtPosition),\n getCompletionEntryDetails: mapFilePositionFn(languageService.getCompletionEntryDetails),\n getCompletionEntrySymbol: mapFilePositionFn(languageService.getCompletionEntrySymbol),\n getQuickInfoAtPosition: mapFilePositionFn(languageService.getQuickInfoAtPosition),\n getBreakpointStatementAtPosition: mapFilePositionFn(\n languageService.getBreakpointStatementAtPosition\n ),\n getSignatureHelpItems: mapFilePositionFn(languageService.getSignatureHelpItems),\n getRenameInfo: mapFilePositionFn(languageService.getRenameInfo),\n getSmartSelectionRange: mapFilePositionFn(languageService.getSmartSelectionRange),\n getDocumentHighlights: mapFilePositionFn(languageService.getDocumentHighlights),\n prepareCallHierarchy: mapFilePositionFn(languageService.prepareCallHierarchy),\n provideCallHierarchyIncomingCalls: mapFilePositionFn(\n languageService.provideCallHierarchyIncomingCalls\n ),\n provideCallHierarchyOutgoingCalls: mapFilePositionFn(\n languageService.provideCallHierarchyOutgoingCalls\n ),\n getBraceMatchingAtPosition: mapFilePositionFn(languageService.getBraceMatchingAtPosition),\n getIndentationAtPosition: mapFilePositionFn(languageService.getIndentationAtPosition),\n getFormattingEditsAfterKeystroke: mapFilePositionFn(\n languageService.getFormattingEditsAfterKeystroke\n ),\n getDocCommentTemplateAtPosition: mapFilePositionFn(\n languageService.getDocCommentTemplateAtPosition\n ),\n isValidBraceCompletionAtPosition: mapFilePositionFn(\n languageService.isValidBraceCompletionAtPosition\n ),\n getJsxClosingTagAtPosition: mapFilePositionFn(languageService.getJsxClosingTagAtPosition),\n getLinkedEditingRangeAtPosition: mapFilePositionFn(\n languageService.getLinkedEditingRangeAtPosition\n ),\n getSpanOfEnclosingComment: mapFilePositionFn(languageService.getSpanOfEnclosingComment),\n\n getSyntacticClassifications: mapFileTextSpanFn(\n languageService.getSyntacticClassifications\n ) as typeof languageService.getSyntacticClassifications,\n getSemanticClassifications: mapFileTextSpanFn(\n languageService.getSemanticClassifications\n ) as typeof languageService.getSemanticClassifications,\n getEncodedSyntacticClassifications: mapFileTextSpanFn(\n languageService.getEncodedSyntacticClassifications\n ),\n getEncodedSemanticClassifications: mapFileTextSpanFn(\n languageService.getEncodedSemanticClassifications\n ),\n provideInlayHints: mapFileTextSpanFn(languageService.provideInlayHints),\n\n getNameOrDottedNameSpan: mapFileStartEndFn(languageService.getNameOrDottedNameSpan),\n getFormattingEditsForRange: mapFileStartEndFn(languageService.getFormattingEditsForRange),\n getCodeFixesAtPosition: mapFileStartEndFn(languageService.getCodeFixesAtPosition),\n\n getFileReferences: mapFileFn(languageService.getFileReferences),\n getNavigationBarItems: mapFileFn(languageService.getNavigationBarItems),\n getNavigationTree: mapFileFn(languageService.getNavigationTree),\n getOutliningSpans: mapFileFn(languageService.getOutliningSpans),\n getTodoComments: mapFileFn(languageService.getTodoComments),\n getFormattingEditsForDocument: mapFileFn(languageService.getFormattingEditsForDocument),\n getEditsForRefactor: mapFileFn(languageService.getEditsForRefactor),\n getEmitOutput: mapFileFn(languageService.getEmitOutput),\n getSuggestionDiagnostics: mapFileFn(languageService.getSuggestionDiagnostics),\n getSemanticDiagnostics: mapFileFn(languageService.getSemanticDiagnostics),\n getSyntacticDiagnostics: mapFileFn(languageService.getSyntacticDiagnostics),\n getSupportedCodeFixes: mapFileFn(languageService.getSupportedCodeFixes),\n\n toggleLineComment: mapFileTextRangeFn(languageService.toggleLineComment),\n toggleMultilineComment: mapFileTextRangeFn(languageService.toggleMultilineComment),\n commentSelection: mapFileTextRangeFn(languageService.commentSelection),\n uncommentSelection: mapFileTextRangeFn(languageService.uncommentSelection),\n } satisfies Partial<ts.LanguageService>);\n};\n\nconst buildPluginInfo = <Config extends {}>(params: {\n config: Config;\n projectRoot: string;\n getLanguageService(): ts.LanguageService;\n getLanguageServiceHost(): ts.LanguageServiceHost;\n system: ts.System;\n rootNames: readonly string[];\n options: ts.CompilerOptions;\n}): PluginCreateInfo<Config> => {\n let languageServiceHost: ts.LanguageServiceHost | undefined;\n return {\n config: params.config,\n\n get languageService() {\n return params.getLanguageService();\n },\n\n get languageServiceHost() {\n return (\n languageServiceHost ||\n (languageServiceHost = createVirtualLanguageServiceHost(\n params.system,\n [...params.rootNames],\n params.options,\n ts\n ).languageServiceHost)\n );\n },\n\n // NOTE: this is an inexact and incomplete implementation\n project: {\n getProjectName: () => params.projectRoot,\n projectService: { logger: console } as any,\n } as PluginCreateInfo['project'],\n\n // NOTE: this is an inexact and incomplete implementation\n serverHost: {\n ...params.system,\n setImmediate,\n clearImmediate,\n } as PluginCreateInfo['serverHost'],\n };\n};\n","import type ts from 'typescript';\nimport * as path from 'node:path';\n\nimport { TadaError, TadaErrorCode } from '../utils/error';\n\nlet _svelte: typeof import('@gql.tada/svelte-support');\nlet _vue: typeof import('@gql.tada/vue-support');\n\nconst transformSvelte = async (\n ...args: Parameters<typeof _svelte.transform>\n): Promise<ReturnType<typeof _svelte.transform>> => {\n if (!_svelte) {\n try {\n _svelte = await import('@gql.tada/svelte-support');\n } catch (_error) {\n throw new TadaError(\n TadaErrorCode.SVELTE_SUPPORT,\n 'For Svelte support the `@gql.tada/svelte-support` package must be installed.\\n' +\n 'Install the package and try again.'\n );\n }\n }\n return _svelte.transform(...args);\n};\n\nconst transformVue = async (\n ...args: Parameters<typeof _vue.transform>\n): Promise<ReturnType<typeof _vue.transform>> => {\n if (!_vue) {\n try {\n _vue = await import('@gql.tada/vue-support');\n } catch (_error) {\n throw new TadaError(\n TadaErrorCode.VUE_SUPPORT,\n 'For Vue support the `@gql.tada/vue-support` package must be installed.\\n' +\n 'Install the package and try again.'\n );\n }\n }\n return _vue.transform(...args);\n};\n\nconst checkVue = async (): Promise<void> => {\n if (!_vue) {\n try {\n _vue = await import('@gql.tada/vue-support');\n } catch (_error) {\n throw new TadaError(\n TadaErrorCode.VUE_SUPPORT,\n 'For Vue support the `@gql.tada/vue-support` package must be installed.\\n' +\n 'Install the package and try again.'\n );\n }\n }\n return _vue.check();\n};\n\nexport const transformExtensions = ['.svelte', '.vue'] as const;\n\nexport const transform = async (sourceFile: ts.SourceFile) => {\n const extname = path.extname(sourceFile.fileName);\n if (extname === '.svelte') {\n return transformSvelte(sourceFile);\n } else if (extname === '.vue') {\n await checkVue();\n return transformVue(sourceFile);\n } else {\n throw new TadaError(\n TadaErrorCode.UNKNOWN_EXTERNAL_FILE,\n `Tried transforming unknown file type \"${extname}\". Supported: ${transformExtensions.join(\n ', '\n )}`\n );\n }\n};\n","import ts from 'typescript';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { init } from '@0no-co/graphqlsp/api';\n\nimport { createFSBackedSystem, createVirtualCompilerHost } from './vendor/typescript-vfs';\n\nimport type { VirtualMap, Mapping } from './mapping';\nimport type { ProgramContainer } from './container';\nimport { SourceMappedFile } from './mapping';\nimport { buildContainer } from './container';\nimport { transform, transformExtensions } from './transformers';\n\nexport type VirtualExtension = (typeof transformExtensions)[number];\n\nexport interface ProgramFactoryParams {\n rootPath: string;\n configPath: string;\n}\n\nexport interface SourceFileParams {\n fileId: string;\n sourceText: string | ts.IScriptSnapshot;\n scriptKind?: ts.ScriptKind;\n}\n\nexport interface MappedFileParams {\n fileId: string;\n mappings: readonly Mapping[];\n}\n\nexport interface ProgramFactory {\n readonly projectPath: string;\n readonly projectDirectories: readonly string[];\n\n createSourceFile(params: SourceFileParams, scriptKind?: ts.ScriptKind): ts.SourceFile;\n createExternalFiles(exts?: readonly VirtualExtension[]): readonly ts.SourceFile[];\n\n addSourceFile(file: SourceFileParams | ts.SourceFile): this;\n addMappedFile(file: SourceFileParams | ts.SourceFile, params: MappedFileParams): this;\n\n addVirtualFiles(files: readonly ts.SourceFile[]): Promise<this>;\n\n resolveModuleName(importSpecifier: string, fromPath: string, toPath: string): string;\n\n build(): ProgramContainer;\n}\n\n/** Bumps the Error stack traces to a length of 25 for better debugging. */\nconst bumpStackTraceLimit = () => {\n if ('stackTraceLimit' in Error && Error.stackTraceLimit < 25) {\n Error.stackTraceLimit = 25;\n }\n};\n\nexport const programFactory = (params: ProgramFactoryParams): ProgramFactory => {\n const vfsMap = new Map<string, string>();\n const virtualMap: VirtualMap = new Map();\n\n const system = createFSBackedSystem(vfsMap, params.rootPath, ts, resolveDefaultLibsPath(params));\n const config = resolveConfig(params, system);\n\n const rootNames = new Set(config.fileNames);\n const options = {\n ...ts.getDefaultCompilerOptions(),\n getDefaultLibFilePath: ts.getDefaultLibFilePath(config.options),\n ...config.options,\n };\n\n // NOTE: Using \"NodeNext\" instead of \"Bundler\" is almost always a mistake\n if (\n 'Bundler' in ts.ModuleResolutionKind &&\n (options.moduleResolution === ts.ModuleResolutionKind.NodeNext ||\n options.moduleResolution === ts.ModuleResolutionKind.Node16)\n ) {\n options.moduleResolution = ts.ModuleResolutionKind.Bundler;\n }\n\n const host = createVirtualCompilerHost(system, options, ts);\n\n const factory: ProgramFactory = {\n get projectPath() {\n return params.rootPath;\n },\n\n get projectDirectories() {\n const directories = new Set([params.rootPath]);\n for (const rootName of rootNames) directories.add(path.dirname(rootName));\n return [...directories];\n },\n\n createSourceFile(params, scriptKind) {\n return ts.createSourceFile(\n params.fileId,\n typeof params.sourceText === 'object'\n ? params.sourceText.getText(0, params.sourceText.getLength())\n : params.sourceText,\n options.target || ts.ScriptTarget.ESNext,\n /*setParentNodes*/ true,\n scriptKind || (params.scriptKind != null ? params.scriptKind : ts.ScriptKind.TSX)\n );\n },\n\n createExternalFiles(exts: readonly VirtualExtension[] = transformExtensions) {\n const files: ts.SourceFile[] = [];\n const seen = new Set(rootNames);\n const directories = new Set([params.rootPath]);\n for (const rootName of rootNames) directories.add(path.dirname(rootName));\n for (const directory of directories) {\n for (const fileId of system.readDirectory(directory, exts, ['**/node_modules'])) {\n if (!seen.has(fileId)) {\n seen.add(fileId);\n const contents = system.readFile(fileId, 'utf8');\n if (contents) {\n files.push(\n factory.createSourceFile(\n {\n fileId,\n sourceText: contents,\n },\n ts.ScriptKind.External\n )\n );\n }\n }\n }\n }\n return files;\n },\n\n addSourceFile(input) {\n const sourceFile =\n 'fileName' in input ? input : factory.createSourceFile(input, ts.ScriptKind.TSX);\n host.updateFile(sourceFile);\n rootNames.add(sourceFile.fileName);\n return factory;\n },\n\n addMappedFile(input, params) {\n const sourceFile =\n 'fileName' in input ? input : factory.createSourceFile(input, ts.ScriptKind.External);\n if (params.mappings.length) rootNames.delete(sourceFile.fileName);\n const sourceMappedFile = new SourceMappedFile(params.mappings, {\n sourceFile,\n sourceFileId: sourceFile.fileName,\n generatedFileId: params.fileId,\n });\n virtualMap.set(sourceMappedFile.sourceFileId, sourceMappedFile);\n virtualMap.set(sourceMappedFile.generatedFileId, sourceMappedFile);\n return factory;\n },\n\n async addVirtualFiles(sourceFiles) {\n for (const sourceFile of sourceFiles) {\n const virtualFileId = `${sourceFile.fileName}.ts`;\n const virtualCode = await transform(sourceFile);\n if (virtualCode) {\n factory\n .addSourceFile({\n fileId: virtualFileId,\n sourceText: virtualCode.snapshot,\n })\n .addMappedFile(sourceFile, {\n mappings: virtualCode.mappings,\n fileId: virtualFileId,\n });\n }\n }\n return factory;\n },\n\n resolveModuleName(importSpecifier: string, fromPath: string, toPath: string): string {\n // For absolute imports (including path-mapped ones), keep them as-is\n // TypeScript's module resolution will handle them correctly\n if (!importSpecifier.startsWith('.')) {\n return importSpecifier;\n }\n\n // For relative imports, we need to adjust the path using the virtual compiler host\n const compilerOptions = options;\n\n // First, resolve the import from the original location to get the actual file\n const resolved = ts.resolveModuleName(\n importSpecifier,\n fromPath,\n compilerOptions,\n host.compilerHost\n );\n\n if (resolved.resolvedModule) {\n const targetFilePath = resolved.resolvedModule.resolvedFileName;\n\n // Now create a relative path from the new location (toPath) to the target\n const fromDir = path.dirname(toPath);\n let relativePath = path.relative(fromDir, targetFilePath);\n\n // Ensure it starts with ./ or ../\n if (!relativePath.startsWith('.')) {\n relativePath = './' + relativePath;\n }\n\n // Convert Windows backslashes to forward slashes for imports\n return relativePath.replace(/\\\\/g, '/');\n }\n\n // Fallback to simple path resolution if TypeScript resolution fails\n const fromDir = path.dirname(fromPath);\n const toDir = path.dirname(toPath);\n\n const absoluteImportPath = path.resolve(fromDir, importSpecifier);\n let relativeImportPath = path.relative(toDir, absoluteImportPath);\n\n // Ensure it starts with ./ if it's a relative path\n if (!relativeImportPath.startsWith('.')) {\n relativeImportPath = './' + relativeImportPath;\n }\n\n // Convert Windows backslashes to forward slashes for imports\n return relativeImportPath.replace(/\\\\/g, '/');\n },\n\n build() {\n bumpStackTraceLimit();\n\n // NOTE: This is necessary for `@0no-co/graphqlsp/api` to use the right instance\n // of the typescript library\n init({ typescript: ts });\n\n return buildContainer({\n virtualMap,\n projectRoot: params.rootPath,\n compilerHost: host.compilerHost,\n rootNames: [...rootNames],\n options,\n system,\n });\n },\n };\n\n return factory;\n};\n\nconst resolveDefaultLibsPath = (params: ProgramFactoryParams): string => {\n const target = ts.getDefaultLibFilePath({});\n if (!ts.sys.fileExists(target)) {\n const require = createRequire(params.configPath);\n const request = 'typescript/package.json';\n try {\n return path.dirname(\n require.resolve(request, {\n paths: [\n path.join(path.dirname(params.configPath), 'node_modules'),\n path.join(params.rootPath, 'node_modules'),\n ...(require.resolve.paths(request) || []),\n ],\n })\n );\n } catch (_error) {\n return path.resolve(params.rootPath, 'node_modules', 'typescript', 'lib');\n }\n } else {\n return path.dirname(target);\n }\n};\n\nconst resolveConfig = (params: ProgramFactoryParams, system: ts.System): ts.ParsedCommandLine => {\n const text = system.readFile(params.configPath, 'utf8') || '{}';\n const parseResult = ts.parseConfigFileTextToJson(params.configPath, text);\n if (parseResult.error != null) throw new Error(parseResult.error.messageText.toString());\n const projectRoot = path.dirname(params.configPath);\n return ts.parseJsonConfigFileContent(\n parseResult.config,\n system,\n projectRoot,\n ts.getDefaultCompilerOptions(),\n params.configPath\n );\n};\n","import * as fs from 'node:fs/promises';\n\nexport const enum FileType {\n File,\n Directory,\n}\n\nexport const stat = async (file: string, type = FileType.File): Promise<boolean> =>\n await fs\n .stat(file)\n .then((stat) => {\n switch (type) {\n case FileType.File:\n return stat.isFile();\n case FileType.Directory:\n return stat.isDirectory();\n }\n })\n .catch(() => false);\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport { stat, FileType } from './fs';\nimport { findWorkspaceRoot } from './workspaceRoot';\n\nconst configFileRe = /^(?:graphql\\.config|\\.graphqlrc)\\.(?:cjs|[jt]s|json|toml|ya?ml)$/i;\n\n/** Loads list of suggested in-repo VSCode extensions */\nexport const findGraphQLConfig = async (targetPath?: string): Promise<string | null> => {\n let target = targetPath || process.cwd();\n const rootPath = path.resolve(target, '/');\n while (target !== rootPath) {\n let dir: readonly string[] = [];\n try {\n dir = await fs.readdir(target);\n } catch (_error) {}\n const configFile = dir.find((item) => configFileRe.test(item));\n if (configFile) return configFile;\n if (await stat(path.resolve(target, '.git'), FileType.Directory)) {\n break;\n } else if (await stat(path.resolve(target, '.vscode'), FileType.Directory)) {\n break;\n }\n target = path.resolve(target, '..');\n }\n\n const workspaceRoot = await findWorkspaceRoot(targetPath);\n if (workspaceRoot) {\n const packageJsonPath = path.resolve(workspaceRoot, 'package.json');\n if (await stat(packageJsonPath)) {\n try {\n const meta = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));\n if (\n meta &&\n typeof meta === 'object' &&\n 'graphql' in meta &&\n meta.graphql &&\n typeof meta.graphql === 'object'\n ) {\n return packageJsonPath;\n }\n } catch (_error) {}\n }\n }\n\n return null;\n};\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { stat, FileType } from './fs';\n\nexport const findWorkspaceRoot = async (targetPath?: string): Promise<string | null> => {\n let target = targetPath || process.cwd();\n const rootPath = path.resolve(target, '/');\n while (target !== rootPath) {\n if (await stat(path.resolve(target, '.git'), FileType.Directory)) {\n return target;\n } else if (await stat(path.resolve(target, '.vscode'), FileType.Directory)) {\n return target;\n } else if (await stat(path.resolve(target, 'pnpm-workspace.yml'))) {\n return target;\n }\n const packageJsonPath = path.resolve(target, 'package.json');\n if (await stat(packageJsonPath)) {\n try {\n const meta = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));\n if (meta && typeof meta === 'object' && Array.isArray(meta.workspaces)) {\n return target;\n }\n } catch (_error) {}\n }\n target = path.resolve(target, '..');\n }\n return null;\n};\n","/**\n * Version resolution utilities with support for workspace catalogs.\n *\n * Supports catalog-based dependency management for:\n * - pnpm (pnpm-workspace.yaml format)\n * - bun (package.json workspaces format)\n *\n * Catalog references follow the format:\n * - \"catalog:\" for default catalog\n * - \"catalog:name\" for named catalogs\n */\n\nimport { createRequire } from 'node:module';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nexport interface PackageJson {\n name?: string;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n}\n\nexport interface WorkspaceConfig {\n packages?: string[];\n catalog?: Record<string, string>;\n catalogs?: Record<string, Record<string, string>>;\n}\n\nexport interface PnpmWorkspaceConfig extends WorkspaceConfig {\n // Inherits from WorkspaceConfig - supports pnpm-workspace.yaml format\n}\n\nexport interface BunWorkspaceConfig extends WorkspaceConfig {\n // Inherits from WorkspaceConfig - supports package.json workspaces format\n}\n\nconst parseYaml = (content: string): PnpmWorkspaceConfig => {\n const lines = content.split('\\n');\n const result: PnpmWorkspaceConfig = {};\n let currentSection: string | null = null;\n let currentCatalog: string | null = null;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n if (trimmed.endsWith(':') && !trimmed.includes(' ')) {\n const key = trimmed.slice(0, -1).replace(/['\"]/g, '');\n if (key === 'packages') {\n currentSection = 'packages';\n result.packages = [];\n } else if (key === 'catalog') {\n currentSection = 'catalog';\n result.catalog = {};\n } else if (key === 'catalogs') {\n currentSection = 'catalogs';\n result.catalogs = {};\n } else if (currentSection === 'catalogs') {\n currentCatalog = key;\n result.catalogs![key] = {};\n }\n } else if (trimmed.startsWith('- ')) {\n if (currentSection === 'packages') {\n result.packages!.push(trimmed.slice(2).replace(/['\"]/g, ''));\n }\n } else if (trimmed.includes(':')) {\n const colonIndex = trimmed.indexOf(':');\n const key = trimmed.slice(0, colonIndex).trim().replace(/['\"]/g, '');\n const value = trimmed\n .slice(colonIndex + 1)\n .trim()\n .replace(/['\"]/g, '');\n\n if (currentSection === 'catalog') {\n result.catalog![key] = value;\n } else if (currentSection === 'catalogs' && currentCatalog) {\n result.catalogs![currentCatalog][key] = value;\n }\n }\n }\n\n return result;\n};\n\nconst findPnpmWorkspaceroot = async (startPath: string = process.cwd()): Promise<string | null> => {\n let currentPath = startPath;\n const root = path.parse(currentPath).root;\n\n while (currentPath !== root) {\n const workspaceFile = path.join(currentPath, 'pnpm-workspace.yaml');\n try {\n await fs.access(workspaceFile);\n return currentPath;\n } catch {\n // File doesn't exist, continue searching\n }\n currentPath = path.dirname(currentPath);\n }\n\n return null;\n};\n\nconst findBunWorkspaceRoot = async (startPath: string = process.cwd()): Promise<string | null> => {\n let currentPath = startPath;\n const root = path.parse(currentPath).root;\n\n while (currentPath !== root) {\n const packageJsonFile = path.join(currentPath, 'package.json');\n try {\n await fs.access(packageJsonFile);\n const content = await fs.readFile(packageJsonFile, 'utf-8');\n const packageJson: PackageJson & { workspaces?: any } = JSON.parse(content);\n\n // Check if this package.json has workspaces with catalog/catalogs\n // Bun stores catalogs in workspaces.catalog and workspaces.catalogs\n if (\n packageJson.workspaces &&\n (packageJson.workspaces.catalog || packageJson.workspaces.catalogs)\n ) {\n return currentPath;\n }\n } catch {\n // File doesn't exist or can't be parsed, continue searching\n }\n currentPath = path.dirname(currentPath);\n }\n\n return null;\n};\n\nconst loadPnpmWorkspaceCatalogs = async (): Promise<PnpmWorkspaceConfig | null> => {\n const workspaceRoot = await findPnpmWorkspaceroot();\n if (!workspaceRoot) return null;\n\n try {\n const workspaceFile = path.join(workspaceRoot, 'pnpm-workspace.yaml');\n const content = await fs.readFile(workspaceFile, 'utf-8');\n return parseYaml(content);\n } catch {\n return null;\n }\n};\n\nconst loadBunWorkspaceCatalogs = async (): Promise<BunWorkspaceConfig | null> => {\n const workspaceRoot = await findBunWorkspaceRoot();\n if (!workspaceRoot) return null;\n\n try {\n const packageJsonFile = path.join(workspaceRoot, 'package.json');\n const content = await fs.readFile(packageJsonFile, 'utf-8');\n const packageJson: PackageJson & { workspaces?: any } = JSON.parse(content);\n\n if (!packageJson.workspaces) return null;\n\n const result: BunWorkspaceConfig = {};\n\n if (packageJson.workspaces.packages) {\n result.packages = packageJson.workspaces.packages;\n }\n\n if (packageJson.workspaces.catalog) {\n result.catalog = packageJson.workspaces.catalog;\n }\n\n if (packageJson.workspaces.catalogs) {\n result.catalogs = packageJson.workspaces.catalogs;\n }\n\n return result;\n } catch {\n return null;\n }\n};\n\nconst loadWorkspaceCatalogs = async (): Promise<WorkspaceConfig | null> => {\n const pnpmCatalogs = await loadPnpmWorkspaceCatalogs();\n if (pnpmCatalogs) return pnpmCatalogs;\n\n const bunCatalogs = await loadBunWorkspaceCatalogs();\n if (bunCatalogs) return bunCatalogs;\n\n return null;\n};\n\nconst resolveCatalogVersion = (catalogRef: string): string | null => {\n if (!catalogRef.startsWith('catalog:')) return null;\n\n const catalogName = catalogRef.slice(8); // Remove 'catalog:' prefix\n\n if (!catalogName || catalogName === 'default') {\n return null; // Will be resolved by package name lookup\n }\n\n return catalogName;\n};\n\nconst getVersionFromCatalog = (\n packageName: string,\n catalogName: string | null,\n catalogs: WorkspaceConfig\n): string | null => {\n if (catalogName) {\n // Named catalog\n return catalogs.catalogs?.[catalogName]?.[packageName] || null;\n } else {\n // Default catalog\n return catalogs.catalog?.[packageName] || null;\n }\n};\n\nconst getPackageVersion = async (\n packageName: string,\n meta: PackageJson\n): Promise<string | null> => {\n const devVersion = meta.devDependencies?.[packageName];\n if (devVersion) {\n if (devVersion.startsWith('catalog:')) {\n const catalogs = await loadWorkspaceCatalogs();\n if (catalogs) {\n const catalogName = resolveCatalogVersion(devVersion);\n const resolvedVersion = getVersionFromCatalog(packageName, catalogName, catalogs);\n if (resolvedVersion) return resolvedVersion;\n }\n } else {\n return devVersion;\n }\n }\n\n const depVersion = meta.dependencies?.[packageName];\n if (depVersion) {\n if (depVersion.startsWith('catalog:')) {\n const catalogs = await loadWorkspaceCatalogs();\n if (catalogs) {\n const catalogName = resolveCatalogVersion(depVersion);\n const resolvedVersion = getVersionFromCatalog(packageName, catalogName, catalogs);\n if (resolvedVersion) return resolvedVersion;\n }\n } else {\n return depVersion;\n }\n }\n\n return null;\n};\n\nexport const readPackageJson = async (): Promise<PackageJson> => {\n const packageJsonPath = path.resolve(process.cwd(), 'package.json');\n const file = path.resolve(packageJsonPath);\n return JSON.parse(await fs.readFile(file, 'utf-8'));\n};\n\nexport const getTypeScriptVersion = async (meta: PackageJson): Promise<string | null> => {\n const pkg = 'typescript';\n\n // Try to get version with catalog support\n const catalogVersion = await getPackageVersion(pkg, meta);\n if (catalogVersion) return catalogVersion;\n\n // Fallback to direct resolution\n try {\n return (await import(pkg)).version || null;\n } catch (_error) {\n return null;\n }\n};\n\nexport const getGraphQLSPVersion = async (meta: PackageJson): Promise<string | null> => {\n const pkg = '@0no-co/graphqlsp';\n\n // Try to get version with catalog support\n const catalogVersion = await getPackageVersion(pkg, meta);\n if (catalogVersion) return catalogVersion;\n\n // Fallback to direct resolution\n try {\n // NOTE: Resolved from current folder, since it's a child dependency\n return createRequire(__dirname)(`${pkg}/package.json`)?.version || null;\n } catch (_error) {\n return null;\n }\n};\n\nexport const getGqlTadaVersion = async (meta: PackageJson): Promise<string | null> => {\n const pkg = 'gql.tada';\n\n // Try to get version with catalog support\n const catalogVersion = await getPackageVersion(pkg, meta);\n if (catalogVersion) return catalogVersion;\n\n // Fallback to direct resolution\n try {\n // NOTE: Resolved from working directory, since it's a parent dependency\n return createRequire(process.cwd())(`${pkg}/package.json`)?.version || null;\n } catch (_error) {\n return null;\n }\n};\n\nconst hasPackageSupport = async (packageName: string, meta: PackageJson): Promise<boolean> => {\n // Check if package is listed in dependencies with catalog support\n const catalogVersion = await getPackageVersion(packageName, meta);\n if (catalogVersion) return true;\n\n // Fallback to direct resolution\n try {\n // NOTE: Resolved from current folder, since it's a child dependency\n return !!createRequire(__dirname)(`${packageName}/package.json`)?.version;\n } catch (_error) {\n return false;\n }\n};\n\nexport const hasSvelteSupport = async (meta: PackageJson): Promise<boolean> => {\n return hasPackageSupport('@gql.tada/svelte-support', meta);\n};\n\nexport const hasVueSupport = async (meta: PackageJson): Promise<boolean> => {\n return hasPackageSupport('@gql.tada/vue-support', meta);\n};\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport ts from 'typescript';\nimport { stat, FileType } from './fs';\n\nconst jsonParse = async (fileName: string): Promise<unknown> => {\n const contents = await fs.readFile(fileName, 'utf8');\n const sourceFile = ts.parseJsonText(fileName, contents);\n return ts.convertToObject(sourceFile, []);\n};\n\nexport const isVSCodeInstalled = async (): Promise<boolean> => {\n if (!process.env.HOME) return false;\n const vscodeFolder = path.resolve(process.env.HOME, '.vscode');\n return !!(await stat(vscodeFolder, FileType.Directory));\n};\n\n/** Loads list of suggested in-repo VSCode extensions */\nexport const loadSuggestedExtensionsList = async (\n targetPath?: string\n): Promise<readonly string[]> => {\n let target = targetPath || process.cwd();\n const rootPath = path.resolve(target, '/');\n while (target !== rootPath) {\n if (await stat(path.resolve(target, '.git'), FileType.Directory)) {\n break;\n } else if (await stat(path.resolve(target, '.vscode'), FileType.Directory)) {\n break;\n }\n target = path.resolve(target, '..');\n }\n const configFile = path.resolve(target, '.vscode', 'extensions.json');\n if (!(await stat(configFile))) return [];\n let json: unknown;\n try {\n json = await jsonParse(configFile);\n } catch (_error) {\n return [];\n }\n if (json && typeof json === 'object' && 'recommendations' in json) {\n return Array.isArray(json.recommendations)\n ? json.recommendations\n .filter((x): x is string => x && typeof x === 'string')\n .map((x) => `${x}`.toLowerCase())\n : [];\n } else {\n return [];\n }\n};\n\n/** Loads list of installed VSCode extensions */\nexport const loadExtensionsList = async (): Promise<readonly string[]> => {\n if (!process.env.HOME) return [];\n const vscodeFolder = path.resolve(process.env.HOME, '.vscode');\n const configFile = path.resolve(vscodeFolder, 'extensions', 'extensions.json');\n if (!(await stat(configFile))) return [];\n let json: unknown;\n try {\n json = await jsonParse(configFile);\n } catch (_error) {\n return [];\n }\n return (Array.isArray(json) ? json : [])\n .map((entry) => {\n if (!entry || typeof entry !== 'object' || !('identifier' in entry)) return null;\n if (!entry.identifier || typeof entry.identifier !== 'object' || !('id' in entry.identifier))\n return null;\n return entry.identifier.id && typeof entry.identifier.id === 'string'\n ? `${entry.identifier.id}`.toLowerCase()\n : null;\n })\n .filter((x): x is string => !!x);\n};\n","import { pipe, interval, map } from 'wonka';\n\nimport * as t from '../../term';\nimport { indent } from '../shared/logger';\n\nexport * from '../shared/logger';\n\nexport function console(error: any) {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.BottomLeft} `,\n error && error instanceof Error ? error.message : `${error}`,\n ]);\n}\n\nexport function emptyLine() {\n return t.text([t.cmd(t.CSI.Style, t.Style.BrightBlack), t.HeavyBox.Vertical, '\\n']);\n}\n\nexport function title(title: string, description?: string) {\n let out = t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n t.HeavyBox.TopLeft,\n ' ',\n t.cmd(t.CSI.Style, [t.Style.Magenta, t.Style.Invert]),\n ` ${title.trim()} `,\n t.cmd(t.CSI.Style, [t.Style.NoInvert]),\n '\\n',\n ]);\n if (description) {\n out += t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n t.HeavyBox.Vertical,\n ` ${description}\\n`,\n ]);\n }\n return out;\n}\n\nexport function completedTask(description: string, isLast = false) {\n return t.text([\n emptyLine(),\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n isLast ? t.HeavyBox.BottomLeft : t.HeavyBox.VerticalRight,\n ' ',\n t.cmd(t.CSI.Style, t.Style.Green),\n t.Icons.TickSwoosh,\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n description,\n '\\n',\n ]);\n}\n\nexport function failedTask(description: string) {\n return t.text([\n emptyLine(),\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n t.HeavyBox.BottomLeft,\n ' ',\n t.cmd(t.CSI.Style, t.Style.BrightRed),\n t.Icons.CrossSwoosh,\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n description,\n '\\n',\n ]);\n}\n\nexport function warningTask(description: string) {\n return t.text([\n emptyLine(),\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n t.HeavyBox.VerticalRight,\n ' ',\n t.cmd(t.CSI.Style, t.Style.BrightYellow),\n t.Icons.Warning,\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n description,\n '\\n',\n ]);\n}\n\nexport function hintMessage(text: string) {\n return t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.VerticalRight} `,\n t.cmd(t.CSI.Style, t.Style.BrightBlue),\n `${t.Icons.Info} `,\n t.cmd(t.CSI.Style, t.Style.Blue),\n indent(\n text,\n t.text([\n t.cmd(t.CSI.Style, t.Style.BrightBlack),\n `${t.HeavyBox.Vertical} `,\n t.cmd(t.CSI.Style, t.Style.Blue),\n ])\n ),\n ]);\n}\n\nexport function runningTask(description: string) {\n return pipe(\n interval(150),\n map((state) => {\n return t.text([\n emptyLine(),\n t.cmd(t.CSI.Style, t.Style.Magenta),\n t.circleSpinner[state % t.circleSpinner.length],\n ' ',\n t.cmd(t.CSI.Style, t.Style.Foreground),\n description.trim(),\n ]);\n })\n );\n}\n\nexport function success() {\n return t.text([\n '\\n',\n t.cmd(t.CSI.Style, [t.Style.Green, t.Style.Invert]),\n ' Done ',\n t.cmd(t.CSI.Style, t.Style.NoInvert),\n t.Chars.Space,\n 'You are all set and ready to go.\\n',\n ]);\n}\n\nexport function errorMessage(message: string) {\n return t.error([\n '\\n',\n t.cmd(t.CSI.Style, [t.Style.Red, t.Style.Invert]),\n ` ${t.Icons.Warning} Error `,\n t.cmd(t.CSI.Style, t.Style.NoInvert),\n `\\n${message.trim()}\\n`,\n ]);\n}\n","import type ts from 'typescript';\nimport path from 'node:path';\n\nimport type { GraphQLSPConfig, LoadConfigResult } from '@gql.tada/internal';\nimport { loadRef, loadConfig, parseConfig } from '@gql.tada/internal';\n\nimport type { ComposeInput } from '../../term';\nimport { MINIMUM_VERSIONS, semverComply } from '../../utils/semver';\nimport { programFactory } from '../../ts';\nimport { findGraphQLConfig } from './helpers/graphqlConfig';\nimport * as versions from './helpers/versions';\nimport * as vscode from './helpers/vscode';\nimport * as logger from './logger';\n\n// NOTE: Currently, most tasks in this command complete too quickly\n// We slow them down to make the CLI output easier to follow along to\nconst delay = (ms = 700) => {\n if (process.env.CI) {\n return Promise.resolve();\n } else {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n};\n\nconst enum Messages {\n TITLE = 'Doctor',\n DESCRIPTION = 'Detects problems with your setup',\n CHECK_TS_VERSION = 'Checking TypeScript version',\n CHECK_DEPENDENCIES = 'Checking installed dependencies',\n CHECK_TSCONFIG = 'Checking tsconfig.json',\n CHECK_EXTERNAL_FILES = 'Checking external files support',\n CHECK_VSCODE = 'Checking VSCode setup',\n CHECK_SCHEMA = 'Checking schema',\n}\n\nexport async function* run(): AsyncIterable<ComposeInput> {\n yield logger.title(Messages.TITLE, Messages.DESCRIPTION);\n yield logger.runningTask(Messages.CHECK_TS_VERSION);\n await delay();\n\n // Check TypeScript version\n let packageJson: versions.PackageJson;\n try {\n packageJson = await versions.readPackageJson();\n } catch (_error) {\n yield logger.failedTask(Messages.CHECK_TS_VERSION);\n throw logger.errorMessage(\n `A ${logger.code('package.json')} file was not found in the current working directory.\\n` +\n logger.hint('Try running the doctor command in your workspace folder.')\n );\n }\n\n const typeScriptVersion = await versions.getTypeScriptVersion(packageJson);\n if (!typeScriptVersion) {\n yield logger.failedTask(Messages.CHECK_TS_VERSION);\n throw logger.errorMessage(\n `A version of ${logger.code('typescript')} was not found in your dependencies.\\n` +\n logger.hint(`Is ${logger.code('typescript')} installed in this package?`)\n );\n } else if (!semverComply(typeScriptVersion, MINIMUM_VERSIONS.typescript)) {\n // TypeScript version lower than v4.1 which is when they introduced template lits\n yield logger.failedTask(Messages.CHECK_TS_VERSION);\n throw logger.errorMessage(\n `The version of ${logger.code('typescript')} in your dependencies is out of date.\\n` +\n logger.hint(\n `${logger.code('gql.tada')} requires at least ${logger.bold(MINIMUM_VERSIONS.typescript)}`\n )\n );\n }\n\n yield logger.completedTask(Messages.CHECK_TS_VERSION);\n yield logger.runningTask(Messages.CHECK_DEPENDENCIES);\n await delay();\n\n const supportsEmbeddedLsp = semverComply(\n typeScriptVersion,\n MINIMUM_VERSIONS.typescript_embed_lsp\n );\n if (!supportsEmbeddedLsp) {\n const gqlspVersion = await versions.getGraphQLSPVersion(packageJson);\n if (!gqlspVersion) {\n yield logger.failedTask(Messages.CHECK_DEPENDENCIES);\n throw logger.errorMessage(\n `A version of ${logger.code('@0no-co/graphqlsp')} was not found in your dependencies.\\n` +\n logger.hint(`Is ${logger.code('@0no-co/graphqlsp')} installed?`)\n );\n } else if (!semverComply(gqlspVersion, MINIMUM_VERSIONS.lsp)) {\n yield logger.failedTask(Messages.CHECK_DEPENDENCIES);\n throw logger.errorMessage(\n `The version of ${logger.code(\n '@0no-co/graphqlsp'\n )} in your dependencies is out of date.\\n` +\n logger.hint(\n `${logger.code('gql.tada')} requires at least ${logger.bold(MINIMUM_VERSIONS.lsp)}`\n )\n );\n }\n }\n\n const gqlTadaVersion = await versions.getGqlTadaVersion(packageJson);\n if (!gqlTadaVersion) {\n yield logger.failedTask(Messages.CHECK_DEPENDENCIES);\n throw logger.errorMessage(\n `A version of ${logger.code('gql.tada')} was not found in your dependencies.\\n` +\n logger.hint(`Is ${logger.code('gql.tada')} installed?`)\n );\n } else if (!semverComply(gqlTadaVersion, '1.0.0')) {\n yield logger.failedTask(Messages.CHECK_DEPENDENCIES);\n throw logger.errorMessage(\n `The version of ${logger.code('gql.tada')} in your dependencies is out of date.\\n` +\n logger.hint(\n `It's recommended to upgrade ${logger.code('gql.tada')} to at least ${logger.bold(\n MINIMUM_VERSIONS.lsp\n )}`\n )\n );\n }\n\n yield logger.completedTask(Messages.CHECK_DEPENDENCIES);\n yield logger.runningTask(Messages.CHECK_TSCONFIG);\n await delay();\n\n let configResult: LoadConfigResult;\n try {\n configResult = await loadConfig();\n } catch (error) {\n yield logger.failedTask(Messages.CHECK_TSCONFIG);\n throw logger.externalError(\n `A ${logger.code('tsconfig.json')} file was not found in the current working directory.`,\n error\n );\n }\n\n let pluginConfig: GraphQLSPConfig;\n try {\n pluginConfig = parseConfig(configResult.pluginConfig, configResult.rootPath);\n } catch (error) {\n yield logger.failedTask(Messages.CHECK_TSCONFIG);\n throw logger.externalError(\n `The plugin configuration for ${logger.code(\n supportsEmbeddedLsp ? '\"gql.tada/ts-plugin\"' : '\"@0no-co/graphqlsp\"'\n )} seems to be invalid.`,\n error\n );\n }\n\n yield logger.completedTask(Messages.CHECK_TSCONFIG);\n\n yield* runExternalFilesChecks(configResult, packageJson);\n\n yield* runVSCodeChecks();\n\n yield logger.runningTask(Messages.CHECK_SCHEMA);\n await delay();\n\n try {\n await loadRef(pluginConfig).load({ rootPath: path.dirname(configResult.configPath) });\n } catch (error) {\n yield logger.failedTask(Messages.CHECK_SCHEMA);\n throw logger.externalError('Failed to load schema.', error);\n }\n\n yield logger.completedTask(Messages.CHECK_SCHEMA, true);\n await delay();\n\n yield logger.success();\n}\n\nasync function* runVSCodeChecks(): AsyncIterable<ComposeInput> {\n const suggestedExtensions = await vscode.loadSuggestedExtensionsList();\n const isVSCodeInstalled = await vscode.isVSCodeInstalled();\n if (suggestedExtensions.length || isVSCodeInstalled) {\n yield logger.runningTask(Messages.CHECK_VSCODE);\n await delay();\n\n let hasEndedTask = false;\n let userExtensions: readonly string[] = [];\n if (isVSCodeInstalled) {\n userExtensions = await vscode.loadExtensionsList();\n if (!userExtensions.includes('graphql.vscode-graphql-syntax')) {\n if (!hasEndedTask) {\n hasEndedTask = true;\n yield logger.warningTask(Messages.CHECK_VSCODE);\n }\n yield logger.hintMessage(\n `We recommend you to install the ${logger.code(\n '\"GraphQL: Syntax Highlighting\"'\n )} extension for VSCode.\\n` +\n 'See: https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql-syntax\\n'\n );\n }\n }\n\n const hasProblemExtension =\n userExtensions.includes('graphql.vscode-graphql') ||\n suggestedExtensions.includes('graphql.vscode-graphql');\n const graphqlConfig = await findGraphQLConfig();\n if (hasProblemExtension && !!graphqlConfig) {\n if (!hasEndedTask) {\n hasEndedTask = true;\n yield logger.warningTask(Messages.CHECK_VSCODE);\n }\n const fileName = path.basename(graphqlConfig);\n yield logger.hintMessage(\n `The ${logger.code(\n '\"GraphQL: Language Feature Support\"'\n )} VSCode extension can cause problems!\\n` +\n `When enabled it may display invalid diagnostic errors for ${logger.code(\n 'gql.tada'\n )} code.\\n` +\n `Check whether your ${logger.code(fileName)} config only targets ${logger.code(\n '.graphql'\n )} documents.\\n`\n );\n }\n\n if (!hasEndedTask) {\n yield logger.completedTask(Messages.CHECK_VSCODE);\n }\n }\n}\n\nasync function* runExternalFilesChecks(\n configResult: LoadConfigResult,\n packageJson: versions.PackageJson\n): AsyncIterable<ComposeInput> {\n let externalFiles: readonly ts.SourceFile[] = [];\n try {\n const factory = programFactory(configResult);\n externalFiles = factory.createExternalFiles();\n } catch (_error) {\n // NOTE: If the project fails to load, we currently just ignore this check and move on\n return;\n }\n\n if (externalFiles.length) {\n yield logger.runningTask(Messages.CHECK_EXTERNAL_FILES);\n await delay();\n\n const extensions = new Set(\n externalFiles.map((sourceFile) => path.extname(sourceFile.fileName))\n );\n\n if (extensions.has('.svelte') && !(await versions.hasSvelteSupport(packageJson))) {\n yield logger.failedTask(Messages.CHECK_EXTERNAL_FILES);\n throw logger.errorMessage(\n `A version of ${logger.code(\n '@gql.tada/svelte-support'\n )} must be installed for Svelte file support.\\n` +\n logger.hint(`Have you installed ${logger.code('@gql.tada/svelte-support')}?`)\n );\n }\n\n if (extensions.has('.vue') && !(await versions.hasVueSupport(packageJson))) {\n yield logger.failedTask(Messages.CHECK_EXTERNAL_FILES);\n throw logger.errorMessage(\n `A version of ${logger.code(\n '@gql.tada/vue-support'\n )} must be installed for Vue file support.\\n` +\n logger.hint(`Have you installed ${logger.code('@gql.tada/vue-support')}?`)\n );\n }\n\n yield logger.completedTask(Messages.CHECK_EXTERNAL_FILES);\n }\n}\n","import { Command } from 'clipanion';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class DoctorCommand extends Command {\n static paths = [['doctor']];\n\n async execute() {\n const result = await initTTY().start(run());\n return exitCode() || (typeof result === 'object' ? result.exit : 0);\n }\n}\n","'use strict';\n\nconst ESC = '\\x1B';\nconst CSI = `${ESC}[`;\nconst beep = '\\u0007';\n\nconst cursor = {\n to(x, y) {\n if (!y) return `${CSI}${x + 1}G`;\n return `${CSI}${y + 1};${x + 1}H`;\n },\n move(x, y) {\n let ret = '';\n\n if (x < 0) ret += `${CSI}${-x}D`;\n else if (x > 0) ret += `${CSI}${x}C`;\n\n if (y < 0) ret += `${CSI}${-y}A`;\n else if (y > 0) ret += `${CSI}${y}B`;\n\n return ret;\n },\n up: (count = 1) => `${CSI}${count}A`,\n down: (count = 1) => `${CSI}${count}B`,\n forward: (count = 1) => `${CSI}${count}C`,\n backward: (count = 1) => `${CSI}${count}D`,\n nextLine: (count = 1) => `${CSI}E`.repeat(count),\n prevLine: (count = 1) => `${CSI}F`.repeat(count),\n left: `${CSI}G`,\n hide: `${CSI}?25l`,\n show: `${CSI}?25h`,\n save: `${ESC}7`,\n restore: `${ESC}8`\n}\n\nconst scroll = {\n up: (count = 1) => `${CSI}S`.repeat(count),\n down: (count = 1) => `${CSI}T`.repeat(count)\n}\n\nconst erase = {\n screen: `${CSI}2J`,\n up: (count = 1) => `${CSI}1J`.repeat(count),\n down: (count = 1) => `${CSI}J`.repeat(count),\n line: `${CSI}2K`,\n lineEnd: `${CSI}K`,\n lineStart: `${CSI}1K`,\n lines(count) {\n let clear = '';\n for (let i = 0; i < count; i++)\n clear += this.line + (i < count - 1 ? cursor.up() : '');\n if (count)\n clear += cursor.left;\n return clear;\n }\n}\n\nmodule.exports = { cursor, scroll, erase, beep };\n","var x=String;\nvar create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x}};\nmodule.exports=create();\nmodule.exports.createColors = create;\n","import{cursor as l,erase as d}from\"sisteransi\";import{stdin as $,stdout as k}from\"node:process\";import*as f from\"node:readline\";import _ from\"node:readline\";import{WriteStream as U}from\"node:tty\";import c from\"picocolors\";function q({onlyFirst:t=!1}={}){const u=[\"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)\",\"(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-ntqry=><~]))\"].join(\"|\");return new RegExp(u,t?void 0:\"g\")}function S(t){if(typeof t!=\"string\")throw new TypeError(`Expected a \\`string\\`, got \\`${typeof t}\\``);return t.replace(q(),\"\")}function j(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,\"default\")?t.default:t}var M={exports:{}};(function(t){var u={};t.exports=u,u.eastAsianWidth=function(e){var s=e.charCodeAt(0),C=e.length==2?e.charCodeAt(1):0,D=s;return 55296<=s&&s<=56319&&56320<=C&&C<=57343&&(s&=1023,C&=1023,D=s<<10|C,D+=65536),D==12288||65281<=D&&D<=65376||65504<=D&&D<=65510?\"F\":D==8361||65377<=D&&D<=65470||65474<=D&&D<=65479||65482<=D&&D<=65487||65490<=D&&D<=65495||65498<=D&&D<=65500||65512<=D&&D<=65518?\"H\":4352<=D&&D<=4447||4515<=D&&D<=4519||4602<=D&&D<=4607||9001<=D&&D<=9002||11904<=D&&D<=11929||11931<=D&&D<=12019||12032<=D&&D<=12245||12272<=D&&D<=12283||12289<=D&&D<=12350||12353<=D&&D<=12438||12441<=D&&D<=12543||12549<=D&&D<=12589||12593<=D&&D<=12686||12688<=D&&D<=12730||12736<=D&&D<=12771||12784<=D&&D<=12830||12832<=D&&D<=12871||12880<=D&&D<=13054||13056<=D&&D<=19903||19968<=D&&D<=42124||42128<=D&&D<=42182||43360<=D&&D<=43388||44032<=D&&D<=55203||55216<=D&&D<=55238||55243<=D&&D<=55291||63744<=D&&D<=64255||65040<=D&&D<=65049||65072<=D&&D<=65106||65108<=D&&D<=65126||65128<=D&&D<=65131||110592<=D&&D<=110593||127488<=D&&D<=127490||127504<=D&&D<=127546||127552<=D&&D<=127560||127568<=D&&D<=127569||131072<=D&&D<=194367||177984<=D&&D<=196605||196608<=D&&D<=262141?\"W\":32<=D&&D<=126||162<=D&&D<=163||165<=D&&D<=166||D==172||D==175||10214<=D&&D<=10221||10629<=D&&D<=10630?\"Na\":D==161||D==164||167<=D&&D<=168||D==170||173<=D&&D<=174||176<=D&&D<=180||182<=D&&D<=186||188<=D&&D<=191||D==198||D==208||215<=D&&D<=216||222<=D&&D<=225||D==230||232<=D&&D<=234||236<=D&&D<=237||D==240||242<=D&&D<=243||247<=D&&D<=250||D==252||D==254||D==257||D==273||D==275||D==283||294<=D&&D<=295||D==299||305<=D&&D<=307||D==312||319<=D&&D<=322||D==324||328<=D&&D<=331||D==333||338<=D&&D<=339||358<=D&&D<=359||D==363||D==462||D==464||D==466||D==468||D==470||D==472||D==474||D==476||D==593||D==609||D==708||D==711||713<=D&&D<=715||D==717||D==720||728<=D&&D<=731||D==733||D==735||768<=D&&D<=879||913<=D&&D<=929||931<=D&&D<=937||945<=D&&D<=961||963<=D&&D<=969||D==1025||1040<=D&&D<=1103||D==1105||D==8208||8211<=D&&D<=8214||8216<=D&&D<=8217||8220<=D&&D<=8221||8224<=D&&D<=8226||8228<=D&&D<=8231||D==8240||8242<=D&&D<=8243||D==8245||D==8251||D==8254||D==8308||D==8319||8321<=D&&D<=8324||D==8364||D==8451||D==8453||D==8457||D==8467||D==8470||8481<=D&&D<=8482||D==8486||D==8491||8531<=D&&D<=8532||8539<=D&&D<=8542||8544<=D&&D<=8555||8560<=D&&D<=8569||D==8585||8592<=D&&D<=8601||8632<=D&&D<=8633||D==8658||D==8660||D==8679||D==8704||8706<=D&&D<=8707||8711<=D&&D<=8712||D==8715||D==8719||D==8721||D==8725||D==8730||8733<=D&&D<=8736||D==8739||D==8741||8743<=D&&D<=8748||D==8750||8756<=D&&D<=8759||8764<=D&&D<=8765||D==8776||D==8780||D==8786||8800<=D&&D<=8801||8804<=D&&D<=8807||8810<=D&&D<=8811||8814<=D&&D<=8815||8834<=D&&D<=8835||8838<=D&&D<=8839||D==8853||D==8857||D==8869||D==8895||D==8978||9312<=D&&D<=9449||9451<=D&&D<=9547||9552<=D&&D<=9587||9600<=D&&D<=9615||9618<=D&&D<=9621||9632<=D&&D<=9633||9635<=D&&D<=9641||9650<=D&&D<=9651||9654<=D&&D<=9655||9660<=D&&D<=9661||9664<=D&&D<=9665||9670<=D&&D<=9672||D==9675||9678<=D&&D<=9681||9698<=D&&D<=9701||D==9711||9733<=D&&D<=9734||D==9737||9742<=D&&D<=9743||9748<=D&&D<=9749||D==9756||D==9758||D==9792||D==9794||9824<=D&&D<=9825||9827<=D&&D<=9829||9831<=D&&D<=9834||9836<=D&&D<=9837||D==9839||9886<=D&&D<=9887||9918<=D&&D<=9919||9924<=D&&D<=9933||9935<=D&&D<=9953||D==9955||9960<=D&&D<=9983||D==10045||D==10071||10102<=D&&D<=10111||11093<=D&&D<=11097||12872<=D&&D<=12879||57344<=D&&D<=63743||65024<=D&&D<=65039||D==65533||127232<=D&&D<=127242||127248<=D&&D<=127277||127280<=D&&D<=127337||127344<=D&&D<=127386||917760<=D&&D<=917999||983040<=D&&D<=1048573||1048576<=D&&D<=1114109?\"A\":\"N\"},u.characterLength=function(e){var s=this.eastAsianWidth(e);return s==\"F\"||s==\"W\"||s==\"A\"?2:1};function F(e){return e.match(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[^\\uD800-\\uDFFF]/g)||[]}u.length=function(e){for(var s=F(e),C=0,D=0;D<s.length;D++)C=C+this.characterLength(s[D]);return C},u.slice=function(e,s,C){textLen=u.length(e),s=s||0,C=C||1,s<0&&(s=textLen+s),C<0&&(C=textLen+C);for(var D=\"\",i=0,n=F(e),E=0;E<n.length;E++){var h=n[E],o=u.length(h);if(i>=s-(o==2?1:0))if(i+o<=C)D+=h;else break;i+=o}return D}})(M);var J=M.exports;const Q=j(J);var X=function(){return/\\uD83C\\uDFF4\\uDB40\\uDC67\\uDB40\\uDC62(?:\\uDB40\\uDC77\\uDB40\\uDC6C\\uDB40\\uDC73|\\uDB40\\uDC73\\uDB40\\uDC63\\uDB40\\uDC74|\\uDB40\\uDC65\\uDB40\\uDC6E\\uDB40\\uDC67)\\uDB40\\uDC7F|(?:\\uD83E\\uDDD1\\uD83C\\uDFFF\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFF\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB-\\uDFFE])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFE\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFE\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFD\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFD\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFC\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFC\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFB\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFB\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFC-\\uDFFF])|\\uD83D\\uDC68(?:\\uD83C\\uDFFB(?:\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF]))|\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFC-\\uDFFF])|[\\u2695\\u2696\\u2708]\\uFE0F|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD]))?|(?:\\uD83C[\\uDFFC-\\uDFFF])\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFF]))|\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83D\\uDC68|(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFF\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFE])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFE\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFD\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFC\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|(?:\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])\\uFE0F|\\u200D(?:(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83D[\\uDC66\\uDC67])|\\uD83C\\uDFFF|\\uD83C\\uDFFE|\\uD83C\\uDFFD|\\uD83C\\uDFFC)?|(?:\\uD83D\\uDC69(?:\\uD83C\\uDFFB\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69])|(?:\\uD83C[\\uDFFC-\\uDFFF])\\u200D\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69]))|\\uD83E\\uDDD1(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1)(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC69\\u200D\\uD83D\\uDC69\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|\\uD83D\\uDC69(?:\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69])|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFF\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFE\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFD\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\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F3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFC\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFB\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD]))|\\uD83D\\uDC69\\u200D\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC69\\u200D\\uD83D\\uDC69\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83D\\uDC69\\u200D\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67])|(?:\\uD83D\\uDC41\\uFE0F\\u200D\\uD83D\\uDDE8|\\uD83E\\uDDD1(?:\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFB\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])|\\uD83D\\uDC69(?:\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFB\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])|\\uD83D\\uDE36\\u200D\\uD83C\\uDF2B|\\uD83C\\uDFF3\\uFE0F\\u200D\\u26A7|\\uD83D\\uDC3B\\u200D\\u2744|(?:(?:\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC70\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD35\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDCD-\\uDDCF\\uDDD4\\uDDD6-\\uDDDD])(?:\\uD83C[\\uDFFB-\\uDFFF])|\\uD83D\\uDC6F|\\uD83E[\\uDD3C\\uDDDE\\uDDDF])\\u200D[\\u2640\\u2642]|(?:\\u26F9|\\uD83C[\\uDFCB\\uDFCC]|\\uD83D\\uDD75)(?:\\uFE0F|\\uD83C[\\uDFFB-\\uDFFF])\\u200D[\\u2640\\u2642]|\\uD83C\\uDFF4\\u200D\\u2620|(?:\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC70\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD35\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDCD-\\uDDCF\\uDDD4\\uDDD6-\\uDDDD])\\u200D[\\u2640\\u2642]|[\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u2328\\u23CF\\u23ED-\\u23EF\\u23F1\\u23F2\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB\\u25FC\\u2600-\\u2604\\u260E\\u2611\\u2618\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u2692\\u2694-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A7\\u26B0\\u26B1\\u26C8\\u26CF\\u26D1\\u26D3\\u26E9\\u26F0\\u26F1\\u26F4\\u26F7\\u26F8\\u2702\\u2708\\u2709\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2733\\u2734\\u2744\\u2747\\u2763\\u27A1\\u2934\\u2935\\u2B05-\\u2B07\\u3030\\u303D\\u3297\\u3299]|\\uD83C[\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDE02\\uDE37\\uDF21\\uDF24-\\uDF2C\\uDF36\\uDF7D\\uDF96\\uDF97\\uDF99-\\uDF9B\\uDF9E\\uDF9F\\uDFCD\\uDFCE\\uDFD4-\\uDFDF\\uDFF5\\uDFF7]|\\uD83D[\\uDC3F\\uDCFD\\uDD49\\uDD4A\\uDD6F\\uDD70\\uDD73\\uDD76-\\uDD79\\uDD87\\uDD8A-\\uDD8D\\uDDA5\\uDDA8\\uDDB1\\uDDB2\\uDDBC\\uDDC2-\\uDDC4\\uDDD1-\\uDDD3\\uDDDC-\\uDDDE\\uDDE1\\uDDE3\\uDDE8\\uDDEF\\uDDF3\\uDDFA\\uDECB\\uDECD-\\uDECF\\uDEE0-\\uDEE5\\uDEE9\\uDEF0\\uDEF3])\\uFE0F|\\uD83C\\uDFF3\\uFE0F\\u200D\\uD83C\\uDF08|\\uD83D\\uDC69\\u200D\\uD83D\\uDC67|\\uD83D\\uDC69\\u200D\\uD83D\\uDC66|\\uD83D\\uDE35\\u200D\\uD83D\\uDCAB|\\uD83D\\uDE2E\\u200D\\uD83D\\uDCA8|\\uD83D\\uDC15\\u200D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\\uDC43\\uDC46-\\uDC50\\uDC66\\uDC67\\uDC6B-\\uDC6D\\uDC72\\uDC74-\\uDC76\\uDC78\\uDC7C\\uDC83\\uDC85\\uDC8F\\uDC91\\uDCAA\\uDD7A\\uDD95\\uDD96\\uDE2E\\uDE35\\uDE36\\uDE4C\\uDE4F\\uDEC0\\uDECC]|\\uD83E[\\uDD0C\\uDD0F\\uDD18-\\uDD1C\\uDD1E\\uDD1F\\uDD30-\\uDD34\\uDD36\\uDD77\\uDDB5\\uDDB6\\uDDBB\\uDDD2\\uDDD3\\uDDD5]|\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC70\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD35\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDCD-\\uDDCF\\uDDD4\\uDDD6-\\uDDDD]|\\uD83D\\uDC6F|\\uD83E[\\uDD3C\\uDDDE\\uDDDF]|[\\u231A\\u231B\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u25FE\\u2614\\u2615\\u2648-\\u2653\\u267F\\u2693\\u26A1\\u26AA\\u26AB\\u26BD\\u26BE\\u26C4\\u26C5\\u26CE\\u26D4\\u26EA\\u26F2\\u26F3\\u26F5\\u26FA\\u26FD\\u2705\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2795-\\u2797\\u27B0\\u27BF\\u2B1B\\u2B1C\\u2B50\\u2B55]|\\uD83C[\\uDC04\\uDCCF\\uDD8E\\uDD91-\\uDD9A\\uDE01\\uDE1A\\uDE2F\\uDE32-\\uDE36\\uDE38-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF20\\uDF2D-\\uDF35\\uDF37-\\uDF7C\\uDF7E-\\uDF84\\uDF86-\\uDF93\\uDFA0-\\uDFC1\\uDFC5\\uDFC6\\uDFC8\\uDFC9\\uDFCF-\\uDFD3\\uDFE0-\\uDFF0\\uDFF8-\\uDFFF]|\\uD83D[\\uDC00-\\uDC07\\uDC09-\\uDC14\\uDC16-\\uDC3A\\uDC3C-\\uDC3E\\uDC40\\uDC44\\uDC45\\uDC51-\\uDC65\\uDC6A\\uDC79-\\uDC7B\\uDC7D-\\uDC80\\uDC84\\uDC88-\\uDC8E\\uDC90\\uDC92-\\uDCA9\\uDCAB-\\uDCFC\\uDCFF-\\uDD3D\\uDD4B-\\uDD4E\\uDD50-\\uDD67\\uDDA4\\uDDFB-\\uDE2D\\uDE2F-\\uDE34\\uDE37-\\uDE44\\uDE48-\\uDE4A\\uDE80-\\uDEA2\\uDEA4-\\uDEB3\\uDEB7-\\uDEBF\\uDEC1-\\uDEC5\\uDED0-\\uDED2\\uDED5-\\uDED7\\uDEEB\\uDEEC\\uDEF4-\\uDEFC\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0D\\uDD0E\\uDD10-\\uDD17\\uDD1D\\uDD20-\\uDD25\\uDD27-\\uDD2F\\uDD3A\\uDD3F-\\uDD45\\uDD47-\\uDD76\\uDD78\\uDD7A-\\uDDB4\\uDDB7\\uDDBA\\uDDBC-\\uDDCB\\uDDD0\\uDDE0-\\uDDFF\\uDE70-\\uDE74\\uDE78-\\uDE7A\\uDE80-\\uDE86\\uDE90-\\uDEA8\\uDEB0-\\uDEB6\\uDEC0-\\uDEC2\\uDED0-\\uDED6]|(?:[\\u231A\\u231B\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u25FE\\u2614\\u2615\\u2648-\\u2653\\u267F\\u2693\\u26A1\\u26AA\\u26AB\\u26BD\\u26BE\\u26C4\\u26C5\\u26CE\\u26D4\\u26EA\\u26F2\\u26F3\\u26F5\\u26FA\\u26FD\\u2705\\u270A\\u270B\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2795-\\u2797\\u27B0\\u27BF\\u2B1B\\u2B1C\\u2B50\\u2B55]|\\uD83C[\\uDC04\\uDCCF\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE1A\\uDE2F\\uDE32-\\uDE36\\uDE38-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF20\\uDF2D-\\uDF35\\uDF37-\\uDF7C\\uDF7E-\\uDF93\\uDFA0-\\uDFCA\\uDFCF-\\uDFD3\\uDFE0-\\uDFF0\\uDFF4\\uDFF8-\\uDFFF]|\\uD83D[\\uDC00-\\uDC3E\\uDC40\\uDC42-\\uDCFC\\uDCFF-\\uDD3D\\uDD4B-\\uDD4E\\uDD50-\\uDD67\\uDD7A\\uDD95\\uDD96\\uDDA4\\uDDFB-\\uDE4F\\uDE80-\\uDEC5\\uDECC\\uDED0-\\uDED2\\uDED5-\\uDED7\\uDEEB\\uDEEC\\uDEF4-\\uDEFC\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0C-\\uDD3A\\uDD3C-\\uDD45\\uDD47-\\uDD78\\uDD7A-\\uDDCB\\uDDCD-\\uDDFF\\uDE70-\\uDE74\\uDE78-\\uDE7A\\uDE80-\\uDE86\\uDE90-\\uDEA8\\uDEB0-\\uDEB6\\uDEC0-\\uDEC2\\uDED0-\\uDED6])|(?:[#\\*0-9\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u231A\\u231B\\u2328\\u23CF\\u23E9-\\u23F3\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB-\\u25FE\\u2600-\\u2604\\u260E\\u2611\\u2614\\u2615\\u2618\\u261D\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u2648-\\u2653\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u267F\\u2692-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A1\\u26A7\\u26AA\\u26AB\\u26B0\\u26B1\\u26BD\\u26BE\\u26C4\\u26C5\\u26C8\\u26CE\\u26CF\\u26D1\\u26D3\\u26D4\\u26E9\\u26EA\\u26F0-\\u26F5\\u26F7-\\u26FA\\u26FD\\u2702\\u2705\\u2708-\\u270D\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2728\\u2733\\u2734\\u2744\\u2747\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2763\\u2764\\u2795-\\u2797\\u27A1\\u27B0\\u27BF\\u2934\\u2935\\u2B05-\\u2B07\\u2B1B\\u2B1C\\u2B50\\u2B55\\u3030\\u303D\\u3297\\u3299]|\\uD83C[\\uDC04\\uDCCF\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE02\\uDE1A\\uDE2F\\uDE32-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF21\\uDF24-\\uDF93\\uDF96\\uDF97\\uDF99-\\uDF9B\\uDF9E-\\uDFF0\\uDFF3-\\uDFF5\\uDFF7-\\uDFFF]|\\uD83D[\\uDC00-\\uDCFD\\uDCFF-\\uDD3D\\uDD49-\\uDD4E\\uDD50-\\uDD67\\uDD6F\\uDD70\\uDD73-\\uDD7A\\uDD87\\uDD8A-\\uDD8D\\uDD90\\uDD95\\uDD96\\uDDA4\\uDDA5\\uDDA8\\uDDB1\\uDDB2\\uDDBC\\uDDC2-\\uDDC4\\uDDD1-\\uDDD3\\uDDDC-\\uDDDE\\uDDE1\\uDDE3\\uDDE8\\uDDEF\\uDDF3\\uDDFA-\\uDE4F\\uDE80-\\uDEC5\\uDECB-\\uDED2\\uDED5-\\uDED7\\uDEE0-\\uDEE5\\uDEE9\\uDEEB\\uDEEC\\uDEF0\\uDEF3-\\uDEFC\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0C-\\uDD3A\\uDD3C-\\uDD45\\uDD47-\\uDD78\\uDD7A-\\uDDCB\\uDDCD-\\uDDFF\\uDE70-\\uDE74\\uDE78-\\uDE7A\\uDE80-\\uDE86\\uDE90-\\uDEA8\\uDEB0-\\uDEB6\\uDEC0-\\uDEC2\\uDED0-\\uDED6])\\uFE0F|(?:[\\u261D\\u26F9\\u270A-\\u270D]|\\uD83C[\\uDF85\\uDFC2-\\uDFC4\\uDFC7\\uDFCA-\\uDFCC]|\\uD83D[\\uDC42\\uDC43\\uDC46-\\uDC50\\uDC66-\\uDC78\\uDC7C\\uDC81-\\uDC83\\uDC85-\\uDC87\\uDC8F\\uDC91\\uDCAA\\uDD74\\uDD75\\uDD7A\\uDD90\\uDD95\\uDD96\\uDE45-\\uDE47\\uDE4B-\\uDE4F\\uDEA3\\uDEB4-\\uDEB6\\uDEC0\\uDECC]|\\uD83E[\\uDD0C\\uDD0F\\uDD18-\\uDD1F\\uDD26\\uDD30-\\uDD39\\uDD3C-\\uDD3E\\uDD77\\uDDB5\\uDDB6\\uDDB8\\uDDB9\\uDDBB\\uDDCD-\\uDDCF\\uDDD1-\\uDDDD])/g};const DD=j(X);function A(t,u={}){if(typeof t!=\"string\"||t.length===0||(u={ambiguousIsNarrow:!0,...u},t=S(t),t.length===0))return 0;t=t.replace(DD(),\" \");const F=u.ambiguousIsNarrow?1:2;let e=0;for(const s of t){const C=s.codePointAt(0);if(C<=31||C>=127&&C<=159||C>=768&&C<=879)continue;switch(Q.eastAsianWidth(s)){case\"F\":case\"W\":e+=2;break;case\"A\":e+=F;break;default:e+=1}}return e}const m=10,T=(t=0)=>u=>`\\x1B[${u+t}m`,P=(t=0)=>u=>`\\x1B[${38+t};5;${u}m`,W=(t=0)=>(u,F,e)=>`\\x1B[${38+t};2;${u};${F};${e}m`,r={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(r.modifier);const uD=Object.keys(r.color),FD=Object.keys(r.bgColor);[...uD,...FD];function tD(){const t=new Map;for(const[u,F]of Object.entries(r)){for(const[e,s]of Object.entries(F))r[e]={open:`\\x1B[${s[0]}m`,close:`\\x1B[${s[1]}m`},F[e]=r[e],t.set(s[0],s[1]);Object.defineProperty(r,u,{value:F,enumerable:!1})}return Object.defineProperty(r,\"codes\",{value:t,enumerable:!1}),r.color.close=\"\\x1B[39m\",r.bgColor.close=\"\\x1B[49m\",r.color.ansi=T(),r.color.ansi256=P(),r.color.ansi16m=W(),r.bgColor.ansi=T(m),r.bgColor.ansi256=P(m),r.bgColor.ansi16m=W(m),Object.defineProperties(r,{rgbToAnsi256:{value:(u,F,e)=>u===F&&F===e?u<8?16:u>248?231:Math.round((u-8)/247*24)+232:16+36*Math.round(u/255*5)+6*Math.round(F/255*5)+Math.round(e/255*5),enumerable:!1},hexToRgb:{value:u=>{const F=/[a-f\\d]{6}|[a-f\\d]{3}/i.exec(u.toString(16));if(!F)return[0,0,0];let[e]=F;e.length===3&&(e=[...e].map(C=>C+C).join(\"\"));const s=Number.parseInt(e,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:u=>r.rgbToAnsi256(...r.hexToRgb(u)),enumerable:!1},ansi256ToAnsi:{value:u=>{if(u<8)return 30+u;if(u<16)return 90+(u-8);let F,e,s;if(u>=232)F=((u-232)*10+8)/255,e=F,s=F;else{u-=16;const i=u%36;F=Math.floor(u/36)/5,e=Math.floor(i/6)/5,s=i%6/5}const C=Math.max(F,e,s)*2;if(C===0)return 30;let D=30+(Math.round(s)<<2|Math.round(e)<<1|Math.round(F));return C===2&&(D+=60),D},enumerable:!1},rgbToAnsi:{value:(u,F,e)=>r.ansi256ToAnsi(r.rgbToAnsi256(u,F,e)),enumerable:!1},hexToAnsi:{value:u=>r.ansi256ToAnsi(r.hexToAnsi256(u)),enumerable:!1}}),r}const eD=tD(),g=new Set([\"\\x1B\",\"\\x9B\"]),sD=39,b=\"\\x07\",O=\"[\",CD=\"]\",I=\"m\",w=`${CD}8;;`,N=t=>`${g.values().next().value}${O}${t}${I}`,L=t=>`${g.values().next().value}${w}${t}${b}`,iD=t=>t.split(\" \").map(u=>A(u)),y=(t,u,F)=>{const e=[...u];let s=!1,C=!1,D=A(S(t[t.length-1]));for(const[i,n]of e.entries()){const E=A(n);if(D+E<=F?t[t.length-1]+=n:(t.push(n),D=0),g.has(n)&&(s=!0,C=e.slice(i+1).join(\"\").startsWith(w)),s){C?n===b&&(s=!1,C=!1):n===I&&(s=!1);continue}D+=E,D===F&&i<e.length-1&&(t.push(\"\"),D=0)}!D&&t[t.length-1].length>0&&t.length>1&&(t[t.length-2]+=t.pop())},rD=t=>{const u=t.split(\" \");let F=u.length;for(;F>0&&!(A(u[F-1])>0);)F--;return F===u.length?t:u.slice(0,F).join(\" \")+u.slice(F).join(\"\")},ED=(t,u,F={})=>{if(F.trim!==!1&&t.trim()===\"\")return\"\";let e=\"\",s,C;const D=iD(t);let i=[\"\"];for(const[E,h]of t.split(\" \").entries()){F.trim!==!1&&(i[i.length-1]=i[i.length-1].trimStart());let o=A(i[i.length-1]);if(E!==0&&(o>=u&&(F.wordWrap===!1||F.trim===!1)&&(i.push(\"\"),o=0),(o>0||F.trim===!1)&&(i[i.length-1]+=\" \",o++)),F.hard&&D[E]>u){const B=u-o,p=1+Math.floor((D[E]-B-1)/u);Math.floor((D[E]-1)/u)<p&&i.push(\"\"),y(i,h,u);continue}if(o+D[E]>u&&o>0&&D[E]>0){if(F.wordWrap===!1&&o<u){y(i,h,u);continue}i.push(\"\")}if(o+D[E]>u&&F.wordWrap===!1){y(i,h,u);continue}i[i.length-1]+=h}F.trim!==!1&&(i=i.map(E=>rD(E)));const n=[...i.join(`\n`)];for(const[E,h]of n.entries()){if(e+=h,g.has(h)){const{groups:B}=new RegExp(`(?:\\\\${O}(?<code>\\\\d+)m|\\\\${w}(?<uri>.*)${b})`).exec(n.slice(E).join(\"\"))||{groups:{}};if(B.code!==void 0){const p=Number.parseFloat(B.code);s=p===sD?void 0:p}else B.uri!==void 0&&(C=B.uri.length===0?void 0:B.uri)}const o=eD.codes.get(Number(s));n[E+1]===`\n`?(C&&(e+=L(\"\")),s&&o&&(e+=N(o))):h===`\n`&&(s&&o&&(e+=N(s)),C&&(e+=L(C)))}return e};function R(t,u,F){return String(t).normalize().replace(/\\r\\n/g,`\n`).split(`\n`).map(e=>ED(e,u,F)).join(`\n`)}var oD=Object.defineProperty,nD=(t,u,F)=>u in t?oD(t,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):t[u]=F,a=(t,u,F)=>(nD(t,typeof u!=\"symbol\"?u+\"\":u,F),F);function aD(t,u){if(t===u)return;const F=t.split(`\n`),e=u.split(`\n`),s=[];for(let C=0;C<Math.max(F.length,e.length);C++)F[C]!==e[C]&&s.push(C);return s}const V=Symbol(\"clack:cancel\");function hD(t){return t===V}function v(t,u){t.isTTY&&t.setRawMode(u)}const z=new Map([[\"k\",\"up\"],[\"j\",\"down\"],[\"h\",\"left\"],[\"l\",\"right\"]]),lD=new Set([\"up\",\"down\",\"left\",\"right\",\"space\",\"enter\"]);class x{constructor({render:u,input:F=$,output:e=k,...s},C=!0){a(this,\"input\"),a(this,\"output\"),a(this,\"rl\"),a(this,\"opts\"),a(this,\"_track\",!1),a(this,\"_render\"),a(this,\"_cursor\",0),a(this,\"state\",\"initial\"),a(this,\"value\"),a(this,\"error\",\"\"),a(this,\"subscribers\",new Map),a(this,\"_prevFrame\",\"\"),this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=u.bind(this),this._track=C,this.input=F,this.output=e}prompt(){const u=new U(0);return u._write=(F,e,s)=>{this._track&&(this.value=this.rl.line.replace(/\\t/g,\"\"),this._cursor=this.rl.cursor,this.emit(\"value\",this.value)),s()},this.input.pipe(u),this.rl=_.createInterface({input:this.input,output:u,tabSize:2,prompt:\"\",escapeCodeTimeout:50}),_.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on(\"keypress\",this.onKeypress),v(this.input,!0),this.output.on(\"resize\",this.render),this.render(),new Promise((F,e)=>{this.once(\"submit\",()=>{this.output.write(l.show),this.output.off(\"resize\",this.render),v(this.input,!1),F(this.value)}),this.once(\"cancel\",()=>{this.output.write(l.show),this.output.off(\"resize\",this.render),v(this.input,!1),F(V)})})}on(u,F){const e=this.subscribers.get(u)??[];e.push({cb:F}),this.subscribers.set(u,e)}once(u,F){const e=this.subscribers.get(u)??[];e.push({cb:F,once:!0}),this.subscribers.set(u,e)}emit(u,...F){const e=this.subscribers.get(u)??[],s=[];for(const C of e)C.cb(...F),C.once&&s.push(()=>e.splice(e.indexOf(C),1));for(const C of s)C()}unsubscribe(){this.subscribers.clear()}onKeypress(u,F){if(this.state===\"error\"&&(this.state=\"active\"),F?.name&&!this._track&&z.has(F.name)&&this.emit(\"cursor\",z.get(F.name)),F?.name&&lD.has(F.name)&&this.emit(\"cursor\",F.name),u&&(u.toLowerCase()===\"y\"||u.toLowerCase()===\"n\")&&this.emit(\"confirm\",u.toLowerCase()===\"y\"),u===\"\t\"&&this.opts.placeholder&&(this.value||(this.rl.write(this.opts.placeholder),this.emit(\"value\",this.opts.placeholder))),u&&this.emit(\"key\",u.toLowerCase()),F?.name===\"return\"){if(this.opts.validate){const e=this.opts.validate(this.value);e&&(this.error=e,this.state=\"error\",this.rl.write(this.value))}this.state!==\"error\"&&(this.state=\"submit\")}u===\"\u0003\"&&(this.state=\"cancel\"),(this.state===\"submit\"||this.state===\"cancel\")&&this.emit(\"finalize\"),this.render(),(this.state===\"submit\"||this.state===\"cancel\")&&this.close()}close(){this.input.unpipe(),this.input.removeListener(\"keypress\",this.onKeypress),this.output.write(`\n`),v(this.input,!1),this.rl.close(),this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){const u=R(this._prevFrame,process.stdout.columns,{hard:!0}).split(`\n`).length-1;this.output.write(l.move(-999,u*-1))}render(){const u=R(this._render(this)??\"\",process.stdout.columns,{hard:!0});if(u!==this._prevFrame){if(this.state===\"initial\")this.output.write(l.hide);else{const F=aD(this._prevFrame,u);if(this.restoreCursor(),F&&F?.length===1){const e=F[0];this.output.write(l.move(0,e)),this.output.write(d.lines(1));const s=u.split(`\n`);this.output.write(s[e]),this._prevFrame=u,this.output.write(l.move(0,s.length-e-1));return}else if(F&&F?.length>1){const e=F[0];this.output.write(l.move(0,e)),this.output.write(d.down());const s=u.split(`\n`).slice(e);this.output.write(s.join(`\n`)),this._prevFrame=u;return}this.output.write(d.down())}this.output.write(u),this.state===\"initial\"&&(this.state=\"active\"),this._prevFrame=u}}}class xD extends x{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(u){super(u,!1),this.value=!!u.initialValue,this.on(\"value\",()=>{this.value=this._value}),this.on(\"confirm\",F=>{this.output.write(l.move(0,-1)),this.value=F,this.state=\"submit\",this.close()}),this.on(\"cursor\",()=>{this.value=!this.value})}}var BD=Object.defineProperty,cD=(t,u,F)=>u in t?BD(t,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):t[u]=F,G=(t,u,F)=>(cD(t,typeof u!=\"symbol\"?u+\"\":u,F),F);let AD=class extends x{constructor(u){super(u,!1),G(this,\"options\"),G(this,\"cursor\",0);const{options:F}=u;this.options=Object.entries(F).flatMap(([e,s])=>[{value:e,group:!0,label:e},...s.map(C=>({...C,group:e}))]),this.value=[...u.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:e})=>e===u.cursorAt),0),this.on(\"cursor\",e=>{switch(e){case\"left\":case\"up\":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case\"down\":case\"right\":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case\"space\":this.toggleValue();break}})}getGroupItems(u){return this.options.filter(F=>F.group===u)}isGroupSelected(u){return this.getGroupItems(u).every(F=>this.value.includes(F.value))}toggleValue(){const u=this.options[this.cursor];if(u.group===!0){const F=u.value,e=this.getGroupItems(F);this.isGroupSelected(F)?this.value=this.value.filter(s=>e.findIndex(C=>C.value===s)===-1):this.value=[...this.value,...e.map(s=>s.value)],this.value=Array.from(new Set(this.value))}else{const F=this.value.includes(u.value);this.value=F?this.value.filter(e=>e!==u.value):[...this.value,u.value]}}};var pD=Object.defineProperty,fD=(t,u,F)=>u in t?pD(t,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):t[u]=F,K=(t,u,F)=>(fD(t,typeof u!=\"symbol\"?u+\"\":u,F),F);let gD=class extends x{constructor(u){super(u,!1),K(this,\"options\"),K(this,\"cursor\",0),this.options=u.options,this.value=[...u.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:F})=>F===u.cursorAt),0),this.on(\"key\",F=>{F===\"a\"&&this.toggleAll()}),this.on(\"cursor\",F=>{switch(F){case\"left\":case\"up\":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case\"down\":case\"right\":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case\"space\":this.toggleValue();break}})}get _value(){return this.options[this.cursor].value}toggleAll(){const u=this.value.length===this.options.length;this.value=u?[]:this.options.map(F=>F.value)}toggleValue(){const u=this.value.includes(this._value);this.value=u?this.value.filter(F=>F!==this._value):[...this.value,this._value]}};var vD=Object.defineProperty,dD=(t,u,F)=>u in t?vD(t,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):t[u]=F,Y=(t,u,F)=>(dD(t,typeof u!=\"symbol\"?u+\"\":u,F),F);class mD extends x{constructor({mask:u,...F}){super(F),Y(this,\"valueWithCursor\",\"\"),Y(this,\"_mask\",\"\\u2022\"),this._mask=u??\"\\u2022\",this.on(\"finalize\",()=>{this.valueWithCursor=this.masked}),this.on(\"value\",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${c.inverse(c.hidden(\"_\"))}`;else{const e=this.masked.slice(0,this.cursor),s=this.masked.slice(this.cursor);this.valueWithCursor=`${e}${c.inverse(s[0])}${s.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}}var bD=Object.defineProperty,wD=(t,u,F)=>u in t?bD(t,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):t[u]=F,Z=(t,u,F)=>(wD(t,typeof u!=\"symbol\"?u+\"\":u,F),F);let yD=class extends x{constructor(u){super(u,!1),Z(this,\"options\"),Z(this,\"cursor\",0),this.options=u.options,this.cursor=this.options.findIndex(({value:F})=>F===u.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on(\"cursor\",F=>{switch(F){case\"left\":case\"up\":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case\"down\":case\"right\":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}};var $D=Object.defineProperty,kD=(t,u,F)=>u in t?$D(t,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):t[u]=F,H=(t,u,F)=>(kD(t,typeof u!=\"symbol\"?u+\"\":u,F),F);class _D extends x{constructor(u){super(u,!1),H(this,\"options\"),H(this,\"cursor\",0),this.options=u.options;const F=this.options.map(({value:[e]})=>e?.toLowerCase());this.cursor=Math.max(F.indexOf(u.initialValue),0),this.on(\"key\",e=>{if(!F.includes(e))return;const s=this.options.find(({value:[C]})=>C?.toLowerCase()===e);s&&(this.value=s.value,this.state=\"submit\",this.emit(\"submit\"))})}}var SD=Object.defineProperty,jD=(t,u,F)=>u in t?SD(t,u,{enumerable:!0,configurable:!0,writable:!0,value:F}):t[u]=F,MD=(t,u,F)=>(jD(t,typeof u!=\"symbol\"?u+\"\":u,F),F);class TD extends x{constructor(u){super(u),MD(this,\"valueWithCursor\",\"\"),this.on(\"finalize\",()=>{this.value||(this.value=u.defaultValue),this.valueWithCursor=this.value}),this.on(\"value\",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.value}${c.inverse(c.hidden(\"_\"))}`;else{const F=this.value.slice(0,this.cursor),e=this.value.slice(this.cursor);this.valueWithCursor=`${F}${c.inverse(e[0])}${e.slice(1)}`}})}get cursor(){return this._cursor}}const PD=globalThis.process.platform.startsWith(\"win\");function WD({input:t=$,output:u=k,overwrite:F=!0,hideCursor:e=!0}={}){const s=f.createInterface({input:t,output:u,prompt:\"\",tabSize:1});f.emitKeypressEvents(t,s),t.isTTY&&t.setRawMode(!0);const C=(D,{name:i})=>{if(String(D)===\"\u0003\"&&process.exit(0),!F)return;let n=i===\"return\"?0:-1,E=i===\"return\"?-1:0;f.moveCursor(u,n,E,()=>{f.clearLine(u,1,()=>{t.once(\"keypress\",C)})})};return e&&process.stdout.write(l.hide),t.once(\"keypress\",C),()=>{t.off(\"keypress\",C),e&&process.stdout.write(l.show),t.isTTY&&!PD&&t.setRawMode(!1),s.terminal=!1,s.close()}}export{xD as ConfirmPrompt,AD as GroupMultiSelectPrompt,gD as MultiSelectPrompt,mD as PasswordPrompt,x as Prompt,_D as SelectKeyPrompt,yD as SelectPrompt,TD as TextPrompt,WD as block,hD as isCancel};\n//# sourceMappingURL=index.mjs.map\n","import{TextPrompt as V,PasswordPrompt as j,ConfirmPrompt as N,SelectPrompt as k,SelectKeyPrompt as W,MultiSelectPrompt as D,GroupMultiSelectPrompt as L,isCancel as G,block as F}from\"@clack/core\";export{isCancel}from\"@clack/core\";import h from\"node:process\";import e from\"picocolors\";import{cursor as T,erase as A}from\"sisteransi\";function q(){return h.platform!==\"win32\"?h.env.TERM!==\"linux\":Boolean(h.env.CI)||Boolean(h.env.WT_SESSION)||Boolean(h.env.TERMINUS_SUBLIME)||h.env.ConEmuTask===\"{cmd::Cmder}\"||h.env.TERM_PROGRAM===\"Terminus-Sublime\"||h.env.TERM_PROGRAM===\"vscode\"||h.env.TERM===\"xterm-256color\"||h.env.TERM===\"alacritty\"||h.env.TERMINAL_EMULATOR===\"JetBrains-JediTerm\"}const _=q(),o=(r,n)=>_?r:n,H=o(\"\\u25C6\",\"*\"),I=o(\"\\u25A0\",\"x\"),x=o(\"\\u25B2\",\"x\"),S=o(\"\\u25C7\",\"o\"),K=o(\"\\u250C\",\"T\"),a=o(\"\\u2502\",\"|\"),d=o(\"\\u2514\",\"\\u2014\"),b=o(\"\\u25CF\",\">\"),E=o(\"\\u25CB\",\" \"),C=o(\"\\u25FB\",\"[\\u2022]\"),w=o(\"\\u25FC\",\"[+]\"),M=o(\"\\u25FB\",\"[ ]\"),U=o(\"\\u25AA\",\"\\u2022\"),B=o(\"\\u2500\",\"-\"),Z=o(\"\\u256E\",\"+\"),z=o(\"\\u251C\",\"+\"),X=o(\"\\u256F\",\"+\"),J=o(\"\\u25CF\",\"\\u2022\"),Y=o(\"\\u25C6\",\"*\"),Q=o(\"\\u25B2\",\"!\"),ee=o(\"\\u25A0\",\"x\"),y=r=>{switch(r){case\"initial\":case\"active\":return e.cyan(H);case\"cancel\":return e.red(I);case\"error\":return e.yellow(x);case\"submit\":return e.green(S)}},te=r=>new V({validate:r.validate,placeholder:r.placeholder,defaultValue:r.defaultValue,initialValue:r.initialValue,render(){const n=`${e.gray(a)}\n${y(this.state)} ${r.message}\n`,i=r.placeholder?e.inverse(r.placeholder[0])+e.dim(r.placeholder.slice(1)):e.inverse(e.hidden(\"_\")),t=this.value?this.valueWithCursor:i;switch(this.state){case\"error\":return`${n.trim()}\n${e.yellow(a)} ${t}\n${e.yellow(d)} ${e.yellow(this.error)}\n`;case\"submit\":return`${n}${e.gray(a)} ${e.dim(this.value||r.placeholder)}`;case\"cancel\":return`${n}${e.gray(a)} ${e.strikethrough(e.dim(this.value??\"\"))}${this.value?.trim()?`\n`+e.gray(a):\"\"}`;default:return`${n}${e.cyan(a)} ${t}\n${e.cyan(d)}\n`}}}).prompt(),re=r=>new j({validate:r.validate,mask:r.mask??U,render(){const n=`${e.gray(a)}\n${y(this.state)} ${r.message}\n`,i=this.valueWithCursor,t=this.masked;switch(this.state){case\"error\":return`${n.trim()}\n${e.yellow(a)} ${t}\n${e.yellow(d)} ${e.yellow(this.error)}\n`;case\"submit\":return`${n}${e.gray(a)} ${e.dim(t)}`;case\"cancel\":return`${n}${e.gray(a)} ${e.strikethrough(e.dim(t??\"\"))}${t?`\n`+e.gray(a):\"\"}`;default:return`${n}${e.cyan(a)} ${i}\n${e.cyan(d)}\n`}}}).prompt(),se=r=>{const n=r.active??\"Yes\",i=r.inactive??\"No\";return new N({active:n,inactive:i,initialValue:r.initialValue??!0,render(){const t=`${e.gray(a)}\n${y(this.state)} ${r.message}\n`,s=this.value?n:i;switch(this.state){case\"submit\":return`${t}${e.gray(a)} ${e.dim(s)}`;case\"cancel\":return`${t}${e.gray(a)} ${e.strikethrough(e.dim(s))}\n${e.gray(a)}`;default:return`${t}${e.cyan(a)} ${this.value?`${e.green(b)} ${n}`:`${e.dim(E)} ${e.dim(n)}`} ${e.dim(\"/\")} ${this.value?`${e.dim(E)} ${e.dim(i)}`:`${e.green(b)} ${i}`}\n${e.cyan(d)}\n`}}}).prompt()},ie=r=>{const n=(t,s)=>{const c=t.label??String(t.value);return s===\"active\"?`${e.green(b)} ${c} ${t.hint?e.dim(`(${t.hint})`):\"\"}`:s===\"selected\"?`${e.dim(c)}`:s===\"cancelled\"?`${e.strikethrough(e.dim(c))}`:`${e.dim(E)} ${e.dim(c)}`};let i=0;return new k({options:r.options,initialValue:r.initialValue,render(){const t=`${e.gray(a)}\n${y(this.state)} ${r.message}\n`;switch(this.state){case\"submit\":return`${t}${e.gray(a)} ${n(this.options[this.cursor],\"selected\")}`;case\"cancel\":return`${t}${e.gray(a)} ${n(this.options[this.cursor],\"cancelled\")}\n${e.gray(a)}`;default:{const s=r.maxItems===void 0?1/0:Math.max(r.maxItems,5);this.cursor>=i+s-3?i=Math.max(Math.min(this.cursor-s+3,this.options.length-s),0):this.cursor<i+2&&(i=Math.max(this.cursor-2,0));const c=s<this.options.length&&i>0,l=s<this.options.length&&i+s<this.options.length;return`${t}${e.cyan(a)} ${this.options.slice(i,i+s).map((u,m,$)=>m===0&&c?e.dim(\"...\"):m===$.length-1&&l?e.dim(\"...\"):n(u,m+i===this.cursor?\"active\":\"inactive\")).join(`\n${e.cyan(a)} `)}\n${e.cyan(d)}\n`}}}}).prompt()},ne=r=>{const n=(i,t=\"inactive\")=>{const s=i.label??String(i.value);return t===\"selected\"?`${e.dim(s)}`:t===\"cancelled\"?`${e.strikethrough(e.dim(s))}`:t===\"active\"?`${e.bgCyan(e.gray(` ${i.value} `))} ${s} ${i.hint?e.dim(`(${i.hint})`):\"\"}`:`${e.gray(e.bgWhite(e.inverse(` ${i.value} `)))} ${s} ${i.hint?e.dim(`(${i.hint})`):\"\"}`};return new W({options:r.options,initialValue:r.initialValue,render(){const i=`${e.gray(a)}\n${y(this.state)} ${r.message}\n`;switch(this.state){case\"submit\":return`${i}${e.gray(a)} ${n(this.options.find(t=>t.value===this.value),\"selected\")}`;case\"cancel\":return`${i}${e.gray(a)} ${n(this.options[0],\"cancelled\")}\n${e.gray(a)}`;default:return`${i}${e.cyan(a)} ${this.options.map((t,s)=>n(t,s===this.cursor?\"active\":\"inactive\")).join(`\n${e.cyan(a)} `)}\n${e.cyan(d)}\n`}}}).prompt()},ae=r=>{const n=(i,t)=>{const s=i.label??String(i.value);return t===\"active\"?`${e.cyan(C)} ${s} ${i.hint?e.dim(`(${i.hint})`):\"\"}`:t===\"selected\"?`${e.green(w)} ${e.dim(s)}`:t===\"cancelled\"?`${e.strikethrough(e.dim(s))}`:t===\"active-selected\"?`${e.green(w)} ${s} ${i.hint?e.dim(`(${i.hint})`):\"\"}`:t===\"submitted\"?`${e.dim(s)}`:`${e.dim(M)} ${e.dim(s)}`};return new D({options:r.options,initialValues:r.initialValues,required:r.required??!0,cursorAt:r.cursorAt,validate(i){if(this.required&&i.length===0)return`Please select at least one option.\n${e.reset(e.dim(`Press ${e.gray(e.bgWhite(e.inverse(\" space \")))} to select, ${e.gray(e.bgWhite(e.inverse(\" enter \")))} to submit`))}`},render(){let i=`${e.gray(a)}\n${y(this.state)} ${r.message}\n`;switch(this.state){case\"submit\":return`${i}${e.gray(a)} ${this.options.filter(({value:t})=>this.value.includes(t)).map(t=>n(t,\"submitted\")).join(e.dim(\", \"))||e.dim(\"none\")}`;case\"cancel\":{const t=this.options.filter(({value:s})=>this.value.includes(s)).map(s=>n(s,\"cancelled\")).join(e.dim(\", \"));return`${i}${e.gray(a)} ${t.trim()?`${t}\n${e.gray(a)}`:\"\"}`}case\"error\":{const t=this.error.split(`\n`).map((s,c)=>c===0?`${e.yellow(d)} ${e.yellow(s)}`:` ${s}`).join(`\n`);return i+e.yellow(a)+\" \"+this.options.map((s,c)=>{const l=this.value.includes(s.value),u=c===this.cursor;return u&&l?n(s,\"active-selected\"):l?n(s,\"selected\"):n(s,u?\"active\":\"inactive\")}).join(`\n${e.yellow(a)} `)+`\n`+t+`\n`}default:return`${i}${e.cyan(a)} ${this.options.map((t,s)=>{const c=this.value.includes(t.value),l=s===this.cursor;return l&&c?n(t,\"active-selected\"):c?n(t,\"selected\"):n(t,l?\"active\":\"inactive\")}).join(`\n${e.cyan(a)} `)}\n${e.cyan(d)}\n`}}}).prompt()},ce=r=>{const n=(i,t,s=[])=>{const c=i.label??String(i.value),l=typeof i.group==\"string\",u=l&&(s[s.indexOf(i)+1]??{group:!0}),m=l&&u.group===!0,$=l?`${m?d:a} `:\"\";return t===\"active\"?`${e.dim($)}${e.cyan(C)} ${c} ${i.hint?e.dim(`(${i.hint})`):\"\"}`:t===\"group-active\"?`${$}${e.cyan(C)} ${e.dim(c)}`:t===\"group-active-selected\"?`${$}${e.green(w)} ${e.dim(c)}`:t===\"selected\"?`${e.dim($)}${e.green(w)} ${e.dim(c)}`:t===\"cancelled\"?`${e.strikethrough(e.dim(c))}`:t===\"active-selected\"?`${e.dim($)}${e.green(w)} ${c} ${i.hint?e.dim(`(${i.hint})`):\"\"}`:t===\"submitted\"?`${e.dim(c)}`:`${e.dim($)}${e.dim(M)} ${e.dim(c)}`};return new L({options:r.options,initialValues:r.initialValues,required:r.required??!0,cursorAt:r.cursorAt,validate(i){if(this.required&&i.length===0)return`Please select at least one option.\n${e.reset(e.dim(`Press ${e.gray(e.bgWhite(e.inverse(\" space \")))} to select, ${e.gray(e.bgWhite(e.inverse(\" enter \")))} to submit`))}`},render(){let i=`${e.gray(a)}\n${y(this.state)} ${r.message}\n`;switch(this.state){case\"submit\":return`${i}${e.gray(a)} ${this.options.filter(({value:t})=>this.value.includes(t)).map(t=>n(t,\"submitted\")).join(e.dim(\", \"))}`;case\"cancel\":{const t=this.options.filter(({value:s})=>this.value.includes(s)).map(s=>n(s,\"cancelled\")).join(e.dim(\", \"));return`${i}${e.gray(a)} ${t.trim()?`${t}\n${e.gray(a)}`:\"\"}`}case\"error\":{const t=this.error.split(`\n`).map((s,c)=>c===0?`${e.yellow(d)} ${e.yellow(s)}`:` ${s}`).join(`\n`);return`${i}${e.yellow(a)} ${this.options.map((s,c,l)=>{const u=this.value.includes(s.value)||s.group===!0&&this.isGroupSelected(`${s.value}`),m=c===this.cursor;return!m&&typeof s.group==\"string\"&&this.options[this.cursor].value===s.group?n(s,u?\"group-active-selected\":\"group-active\",l):m&&u?n(s,\"active-selected\",l):u?n(s,\"selected\",l):n(s,m?\"active\":\"inactive\",l)}).join(`\n${e.yellow(a)} `)}\n${t}\n`}default:return`${i}${e.cyan(a)} ${this.options.map((t,s,c)=>{const l=this.value.includes(t.value)||t.group===!0&&this.isGroupSelected(`${t.value}`),u=s===this.cursor;return!u&&typeof t.group==\"string\"&&this.options[this.cursor].value===t.group?n(t,l?\"group-active-selected\":\"group-active\",c):u&&l?n(t,\"active-selected\",c):l?n(t,\"selected\",c):n(t,u?\"active\":\"inactive\",c)}).join(`\n${e.cyan(a)} `)}\n${e.cyan(d)}\n`}}}).prompt()},R=r=>r.replace(me(),\"\"),le=(r=\"\",n=\"\")=>{const i=`\n${r}\n`.split(`\n`),t=R(n).length,s=Math.max(i.reduce((l,u)=>(u=R(u),u.length>l?u.length:l),0),t)+2,c=i.map(l=>`${e.gray(a)} ${e.dim(l)}${\" \".repeat(s-R(l).length)}${e.gray(a)}`).join(`\n`);process.stdout.write(`${e.gray(a)}\n${e.green(S)} ${e.reset(n)} ${e.gray(B.repeat(Math.max(s-t-1,1))+Z)}\n${c}\n${e.gray(z+B.repeat(s+2)+X)}\n`)},ue=(r=\"\")=>{process.stdout.write(`${e.gray(d)} ${e.red(r)}\n\n`)},oe=(r=\"\")=>{process.stdout.write(`${e.gray(K)} ${r}\n`)},$e=(r=\"\")=>{process.stdout.write(`${e.gray(a)}\n${e.gray(d)} ${r}\n\n`)},f={message:(r=\"\",{symbol:n=e.gray(a)}={})=>{const i=[`${e.gray(a)}`];if(r){const[t,...s]=r.split(`\n`);i.push(`${n} ${t}`,...s.map(c=>`${e.gray(a)} ${c}`))}process.stdout.write(`${i.join(`\n`)}\n`)},info:r=>{f.message(r,{symbol:e.blue(J)})},success:r=>{f.message(r,{symbol:e.green(Y)})},step:r=>{f.message(r,{symbol:e.green(S)})},warn:r=>{f.message(r,{symbol:e.yellow(Q)})},warning:r=>{f.warn(r)},error:r=>{f.message(r,{symbol:e.red(ee)})}},de=()=>{const r=_?[\"\\u25D2\",\"\\u25D0\",\"\\u25D3\",\"\\u25D1\"]:[\"\\u2022\",\"o\",\"O\",\"0\"],n=_?80:120;let i,t,s=!1,c=\"\";const l=(v=\"\")=>{s=!0,i=F(),c=v.replace(/\\.+$/,\"\"),process.stdout.write(`${e.gray(a)}\n`);let g=0,p=0;t=setInterval(()=>{const O=e.magenta(r[g]),P=\".\".repeat(Math.floor(p)).slice(0,3);process.stdout.write(T.move(-999,0)),process.stdout.write(A.down(1)),process.stdout.write(`${O} ${c}${P}`),g=g+1<r.length?g+1:0,p=p<r.length?p+.125:0},n)},u=(v=\"\",g=0)=>{c=v??c,s=!1,clearInterval(t);const p=g===0?e.green(S):g===1?e.red(I):e.red(x);process.stdout.write(T.move(-999,0)),process.stdout.write(A.down(1)),process.stdout.write(`${p} ${c}\n`),i()},m=(v=\"\")=>{c=v??c},$=v=>{const g=v>1?\"Something went wrong\":\"Canceled\";s&&u(g,v)};return process.on(\"uncaughtExceptionMonitor\",()=>$(2)),process.on(\"unhandledRejection\",()=>$(2)),process.on(\"SIGINT\",()=>$(1)),process.on(\"SIGTERM\",()=>$(1)),process.on(\"exit\",$),{start:l,stop:u,message:m}};function me(){const r=[\"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)\",\"(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-nq-uy=><~]))\"].join(\"|\");return new RegExp(r,\"g\")}const he=async(r,n)=>{const i={},t=Object.keys(r);for(const s of t){const c=r[s],l=await c({results:i})?.catch(u=>{throw u});if(typeof n?.onCancel==\"function\"&&G(l)){i[s]=\"canceled\",n.onCancel({results:i});continue}i[s]=l}return i};export{ue as cancel,se as confirm,he as group,ce as groupMultiselect,oe as intro,f as log,ae as multiselect,le as note,$e as outro,re as password,ie as select,ne as selectKey,de as spinner,te as text};\n","var fs = require('fs')\nvar core\nif (process.platform === 'win32' || global.TESTING_WINDOWS) {\n core = require('./windows.js')\n} else {\n core = require('./mode.js')\n}\n\nmodule.exports = isexe\nisexe.sync = sync\n\nfunction isexe (path, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = {}\n }\n\n if (!cb) {\n if (typeof Promise !== 'function') {\n throw new TypeError('callback not provided')\n }\n\n return new Promise(function (resolve, reject) {\n isexe(path, options || {}, function (er, is) {\n if (er) {\n reject(er)\n } else {\n resolve(is)\n }\n })\n })\n }\n\n core(path, options || {}, function (er, is) {\n // ignore EACCES because that just means we aren't allowed to run it\n if (er) {\n if (er.code === 'EACCES' || options && options.ignoreErrors) {\n er = null\n is = false\n }\n }\n cb(er, is)\n })\n}\n\nfunction sync (path, options) {\n // my kingdom for a filtered catch\n try {\n return core.sync(path, options || {})\n } catch (er) {\n if (options && options.ignoreErrors || er.code === 'EACCES') {\n return false\n } else {\n throw er\n }\n }\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction checkPathExt (path, options) {\n var pathext = options.pathExt !== undefined ?\n options.pathExt : process.env.PATHEXT\n\n if (!pathext) {\n return true\n }\n\n pathext = pathext.split(';')\n if (pathext.indexOf('') !== -1) {\n return true\n }\n for (var i = 0; i < pathext.length; i++) {\n var p = pathext[i].toLowerCase()\n if (p && path.substr(-p.length).toLowerCase() === p) {\n return true\n }\n }\n return false\n}\n\nfunction checkStat (stat, path, options) {\n if (!stat.isSymbolicLink() && !stat.isFile()) {\n return false\n }\n return checkPathExt(path, options)\n}\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, path, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), path, options)\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), options)\n}\n\nfunction checkStat (stat, options) {\n return stat.isFile() && checkMode(stat, options)\n}\n\nfunction checkMode (stat, options) {\n var mod = stat.mode\n var uid = stat.uid\n var gid = stat.gid\n\n var myUid = options.uid !== undefined ?\n options.uid : process.getuid && process.getuid()\n var myGid = options.gid !== undefined ?\n options.gid : process.getgid && process.getgid()\n\n var u = parseInt('100', 8)\n var g = parseInt('010', 8)\n var o = parseInt('001', 8)\n var ug = u | g\n\n var ret = (mod & o) ||\n (mod & g) && gid === myGid ||\n (mod & u) && uid === myUid ||\n (mod & ug) && myUid === 0\n\n return ret\n}\n","const isWindows = process.platform === 'win32' ||\n process.env.OSTYPE === 'cygwin' ||\n process.env.OSTYPE === 'msys'\n\nconst path = require('path')\nconst COLON = isWindows ? ';' : ':'\nconst isexe = require('isexe')\n\nconst getNotFoundError = (cmd) =>\n Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, opt) => {\n const colon = opt.colon || COLON\n\n // If it has a slash, then we don't bother searching the pathenv.\n // just check the file itself, and that's it.\n const pathEnv = cmd.match(/\\//) || isWindows && cmd.match(/\\\\/) ? ['']\n : (\n [\n // windows always checks the cwd first\n ...(isWindows ? [process.cwd()] : []),\n ...(opt.path || process.env.PATH ||\n /* istanbul ignore next: very unusual */ '').split(colon),\n ]\n )\n const pathExtExe = isWindows\n ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'\n : ''\n const pathExt = isWindows ? pathExtExe.split(colon) : ['']\n\n if (isWindows) {\n if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')\n pathExt.unshift('')\n }\n\n return {\n pathEnv,\n pathExt,\n pathExtExe,\n }\n}\n\nconst which = (cmd, opt, cb) => {\n if (typeof opt === 'function') {\n cb = opt\n opt = {}\n }\n if (!opt)\n opt = {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n const step = i => new Promise((resolve, reject) => {\n if (i === pathEnv.length)\n return opt.all && found.length ? resolve(found)\n : reject(getNotFoundError(cmd))\n\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n resolve(subStep(p, i, 0))\n })\n\n const subStep = (p, i, ii) => new Promise((resolve, reject) => {\n if (ii === pathExt.length)\n return resolve(step(i + 1))\n const ext = pathExt[ii]\n isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {\n if (!er && is) {\n if (opt.all)\n found.push(p + ext)\n else\n return resolve(p + ext)\n }\n return resolve(subStep(p, i, ii + 1))\n })\n })\n\n return cb ? step(0).then(res => cb(null, res), cb) : step(0)\n}\n\nconst whichSync = (cmd, opt) => {\n opt = opt || {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n for (let i = 0; i < pathEnv.length; i ++) {\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n for (let j = 0; j < pathExt.length; j ++) {\n const cur = p + pathExt[j]\n try {\n const is = isexe.sync(cur, { pathExt: pathExtExe })\n if (is) {\n if (opt.all)\n found.push(cur)\n else\n return cur\n }\n } catch (ex) {}\n }\n }\n\n if (opt.all && found.length)\n return found\n\n if (opt.nothrow)\n return null\n\n throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n","'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n","'use strict';\n\nconst path = require('path');\nconst which = require('which');\nconst getPathKey = require('path-key');\n\nfunction resolveCommandAttempt(parsed, withoutPathExt) {\n const env = parsed.options.env || process.env;\n const cwd = process.cwd();\n const hasCustomCwd = parsed.options.cwd != null;\n // Worker threads do not have process.chdir()\n const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;\n\n // If a custom `cwd` was specified, we need to change the process cwd\n // because `which` will do stat calls but does not support a custom cwd\n if (shouldSwitchCwd) {\n try {\n process.chdir(parsed.options.cwd);\n } catch (err) {\n /* Empty */\n }\n }\n\n let resolved;\n\n try {\n resolved = which.sync(parsed.command, {\n path: env[getPathKey({ env })],\n pathExt: withoutPathExt ? path.delimiter : undefined,\n });\n } catch (e) {\n /* Empty */\n } finally {\n if (shouldSwitchCwd) {\n process.chdir(cwd);\n }\n }\n\n // If we successfully resolved, ensure that an absolute path is returned\n // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it\n if (resolved) {\n resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);\n }\n\n return resolved;\n}\n\nfunction resolveCommand(parsed) {\n return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);\n}\n\nmodule.exports = resolveCommand;\n","'use strict';\n\n// See http://www.robvanderwoude.com/escapechars.php\nconst metaCharsRegExp = /([()\\][%!^\"`<>&|;, *?])/g;\n\nfunction escapeCommand(arg) {\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n return arg;\n}\n\nfunction escapeArgument(arg, doubleEscapeMetaChars) {\n // Convert to string\n arg = `${arg}`;\n\n // Algorithm below is based on https://qntm.org/cmd\n\n // Sequence of backslashes followed by a double quote:\n // double up all the backslashes and escape the double quote\n arg = arg.replace(/(\\\\*)\"/g, '$1$1\\\\\"');\n\n // Sequence of backslashes followed by the end of the string\n // (which will become a double quote later):\n // double up all the backslashes\n arg = arg.replace(/(\\\\*)$/, '$1$1');\n\n // All other backslashes occur literally\n\n // Quote the whole thing:\n arg = `\"${arg}\"`;\n\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n // Double escape meta chars if necessary\n if (doubleEscapeMetaChars) {\n arg = arg.replace(metaCharsRegExp, '^$1');\n }\n\n return arg;\n}\n\nmodule.exports.command = escapeCommand;\nmodule.exports.argument = escapeArgument;\n","'use strict';\nconst shebangRegex = require('shebang-regex');\n\nmodule.exports = (string = '') => {\n\tconst match = string.match(shebangRegex);\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tconst [path, argument] = match[0].replace(/#! ?/, '').split(' ');\n\tconst binary = path.split('/').pop();\n\n\tif (binary === 'env') {\n\t\treturn argument;\n\t}\n\n\treturn argument ? `${binary} ${argument}` : binary;\n};\n","'use strict';\nmodule.exports = /^#!(.*)/;\n","'use strict';\n\nconst fs = require('fs');\nconst shebangCommand = require('shebang-command');\n\nfunction readShebang(command) {\n // Read the first 150 bytes from the file\n const size = 150;\n const buffer = Buffer.alloc(size);\n\n let fd;\n\n try {\n fd = fs.openSync(command, 'r');\n fs.readSync(fd, buffer, 0, size, 0);\n fs.closeSync(fd);\n } catch (e) { /* Empty */ }\n\n // Attempt to extract shebang (null is returned if not a shebang)\n return shebangCommand(buffer.toString());\n}\n\nmodule.exports = readShebang;\n","'use strict';\n\nconst path = require('path');\nconst resolveCommand = require('./util/resolveCommand');\nconst escape = require('./util/escape');\nconst readShebang = require('./util/readShebang');\n\nconst isWin = process.platform === 'win32';\nconst isExecutableRegExp = /\\.(?:com|exe)$/i;\nconst isCmdShimRegExp = /node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;\n\nfunction detectShebang(parsed) {\n parsed.file = resolveCommand(parsed);\n\n const shebang = parsed.file && readShebang(parsed.file);\n\n if (shebang) {\n parsed.args.unshift(parsed.file);\n parsed.command = shebang;\n\n return resolveCommand(parsed);\n }\n\n return parsed.file;\n}\n\nfunction parseNonShell(parsed) {\n if (!isWin) {\n return parsed;\n }\n\n // Detect & add support for shebangs\n const commandFile = detectShebang(parsed);\n\n // We don't need a shell if the command filename is an executable\n const needsShell = !isExecutableRegExp.test(commandFile);\n\n // If a shell is required, use cmd.exe and take care of escaping everything correctly\n // Note that `forceShell` is an hidden option used only in tests\n if (parsed.options.forceShell || needsShell) {\n // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`\n // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument\n // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,\n // we need to double escape them\n const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);\n\n // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\\bar)\n // This is necessary otherwise it will always fail with ENOENT in those cases\n parsed.command = path.normalize(parsed.command);\n\n // Escape command & arguments\n parsed.command = escape.command(parsed.command);\n parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));\n\n const shellCommand = [parsed.command].concat(parsed.args).join(' ');\n\n parsed.args = ['/d', '/s', '/c', `\"${shellCommand}\"`];\n parsed.command = process.env.comspec || 'cmd.exe';\n parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped\n }\n\n return parsed;\n}\n\nfunction parse(command, args, options) {\n // Normalize arguments, similar to nodejs\n if (args && !Array.isArray(args)) {\n options = args;\n args = null;\n }\n\n args = args ? args.slice(0) : []; // Clone array to avoid changing the original\n options = Object.assign({}, options); // Clone object to avoid changing the original\n\n // Build our parsed object\n const parsed = {\n command,\n args,\n options,\n file: undefined,\n original: {\n command,\n args,\n },\n };\n\n // Delegate further parsing to shell or non-shell\n return options.shell ? parsed : parseNonShell(parsed);\n}\n\nmodule.exports = parse;\n","'use strict';\n\nconst isWin = process.platform === 'win32';\n\nfunction notFoundError(original, syscall) {\n return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {\n code: 'ENOENT',\n errno: 'ENOENT',\n syscall: `${syscall} ${original.command}`,\n path: original.command,\n spawnargs: original.args,\n });\n}\n\nfunction hookChildProcess(cp, parsed) {\n if (!isWin) {\n return;\n }\n\n const originalEmit = cp.emit;\n\n cp.emit = function (name, arg1) {\n // If emitting \"exit\" event and exit code is 1, we need to check if\n // the command exists and emit an \"error\" instead\n // See https://github.com/IndigoUnited/node-cross-spawn/issues/16\n if (name === 'exit') {\n const err = verifyENOENT(arg1, parsed, 'spawn');\n\n if (err) {\n return originalEmit.call(cp, 'error', err);\n }\n }\n\n return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params\n };\n}\n\nfunction verifyENOENT(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawn');\n }\n\n return null;\n}\n\nfunction verifyENOENTSync(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawnSync');\n }\n\n return null;\n}\n\nmodule.exports = {\n hookChildProcess,\n verifyENOENT,\n verifyENOENTSync,\n notFoundError,\n};\n","'use strict';\n\nconst cp = require('child_process');\nconst parse = require('./lib/parse');\nconst enoent = require('./lib/enoent');\n\nfunction spawn(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);\n\n // Hook into child process \"exit\" event to emit an error if the command\n // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n enoent.hookChildProcess(spawned, parsed);\n\n return spawned;\n}\n\nfunction spawnSync(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);\n\n // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);\n\n return result;\n}\n\nmodule.exports = spawn;\nmodule.exports.spawn = spawn;\nmodule.exports.sync = spawnSync;\n\nmodule.exports._parse = parse;\nmodule.exports._enoent = enoent;\n","export default function pathKey(options = {}) {\n\tconst {\n\t\tenv = process.env,\n\t\tplatform = process.platform\n\t} = options;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(env).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n}\n","import process from 'node:process';\nimport path from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport pathKey from 'path-key';\n\nexport const npmRunPath = ({\n\tcwd = process.cwd(),\n\tpath: pathOption = process.env[pathKey()],\n\tpreferLocal = true,\n\texecPath = process.execPath,\n\taddExecPath = true,\n} = {}) => {\n\tconst cwdString = cwd instanceof URL ? fileURLToPath(cwd) : cwd;\n\tconst cwdPath = path.resolve(cwdString);\n\tconst result = [];\n\n\tif (preferLocal) {\n\t\tapplyPreferLocal(result, cwdPath);\n\t}\n\n\tif (addExecPath) {\n\t\tapplyExecPath(result, execPath, cwdPath);\n\t}\n\n\treturn [...result, pathOption].join(path.delimiter);\n};\n\nconst applyPreferLocal = (result, cwdPath) => {\n\tlet previous;\n\n\twhile (previous !== cwdPath) {\n\t\tresult.push(path.join(cwdPath, 'node_modules/.bin'));\n\t\tprevious = cwdPath;\n\t\tcwdPath = path.resolve(cwdPath, '..');\n\t}\n};\n\n// Ensure the running `node` binary is used\nconst applyExecPath = (result, execPath, cwdPath) => {\n\tconst execPathString = execPath instanceof URL ? fileURLToPath(execPath) : execPath;\n\tresult.push(path.resolve(cwdPath, execPathString, '..'));\n};\n\nexport const npmRunPathEnv = ({env = process.env, ...options} = {}) => {\n\tenv = {...env};\n\n\tconst pathName = pathKey({env});\n\toptions.path = env[pathName];\n\tenv[pathName] = npmRunPath(options);\n\n\treturn env;\n};\n","const copyProperty = (to, from, property, ignoreNonConfigurable) => {\n\t// `Function#length` should reflect the parameters of `to` not `from` since we keep its body.\n\t// `Function#prototype` is non-writable and non-configurable so can never be modified.\n\tif (property === 'length' || property === 'prototype') {\n\t\treturn;\n\t}\n\n\t// `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here.\n\tif (property === 'arguments' || property === 'caller') {\n\t\treturn;\n\t}\n\n\tconst toDescriptor = Object.getOwnPropertyDescriptor(to, property);\n\tconst fromDescriptor = Object.getOwnPropertyDescriptor(from, property);\n\n\tif (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {\n\t\treturn;\n\t}\n\n\tObject.defineProperty(to, property, fromDescriptor);\n};\n\n// `Object.defineProperty()` throws if the property exists, is not configurable and either:\n// - one its descriptors is changed\n// - it is non-writable and its value is changed\nconst canCopyProperty = function (toDescriptor, fromDescriptor) {\n\treturn toDescriptor === undefined || toDescriptor.configurable || (\n\t\ttoDescriptor.writable === fromDescriptor.writable &&\n\t\ttoDescriptor.enumerable === fromDescriptor.enumerable &&\n\t\ttoDescriptor.configurable === fromDescriptor.configurable &&\n\t\t(toDescriptor.writable || toDescriptor.value === fromDescriptor.value)\n\t);\n};\n\nconst changePrototype = (to, from) => {\n\tconst fromPrototype = Object.getPrototypeOf(from);\n\tif (fromPrototype === Object.getPrototypeOf(to)) {\n\t\treturn;\n\t}\n\n\tObject.setPrototypeOf(to, fromPrototype);\n};\n\nconst wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\\n${fromBody}`;\n\nconst toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');\nconst toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name');\n\n// We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.\n// We use `bind()` instead of a closure for the same reason.\n// Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.\nconst changeToString = (to, from, name) => {\n\tconst withName = name === '' ? '' : `with ${name.trim()}() `;\n\tconst newToString = wrappedToString.bind(null, withName, from.toString());\n\t// Ensure `to.toString.toString` is non-enumerable and has the same `same`\n\tObject.defineProperty(newToString, 'name', toStringName);\n\tObject.defineProperty(to, 'toString', {...toStringDescriptor, value: newToString});\n};\n\nexport default function mimicFunction(to, from, {ignoreNonConfigurable = false} = {}) {\n\tconst {name} = to;\n\n\tfor (const property of Reflect.ownKeys(from)) {\n\t\tcopyProperty(to, from, property, ignoreNonConfigurable);\n\t}\n\n\tchangePrototype(to, from);\n\tchangeToString(to, from, name);\n\n\treturn to;\n}\n","import mimicFunction from 'mimic-fn';\n\nconst calledFunctions = new WeakMap();\n\nconst onetime = (function_, options = {}) => {\n\tif (typeof function_ !== 'function') {\n\t\tthrow new TypeError('Expected a function');\n\t}\n\n\tlet returnValue;\n\tlet callCount = 0;\n\tconst functionName = function_.displayName || function_.name || '<anonymous>';\n\n\tconst onetime = function (...arguments_) {\n\t\tcalledFunctions.set(onetime, ++callCount);\n\n\t\tif (callCount === 1) {\n\t\t\treturnValue = function_.apply(this, arguments_);\n\t\t\tfunction_ = null;\n\t\t} else if (options.throw === true) {\n\t\t\tthrow new Error(`Function \\`${functionName}\\` can only be called once`);\n\t\t}\n\n\t\treturn returnValue;\n\t};\n\n\tmimicFunction(onetime, function_);\n\tcalledFunctions.set(onetime, callCount);\n\n\treturn onetime;\n};\n\nonetime.callCount = function_ => {\n\tif (!calledFunctions.has(function_)) {\n\t\tthrow new Error(`The given function \\`${function_.name}\\` is not wrapped by the \\`onetime\\` package`);\n\t}\n\n\treturn calledFunctions.get(function_);\n};\n\nexport default onetime;\n","\nexport const getRealtimeSignals=()=>{\nconst length=SIGRTMAX-SIGRTMIN+1;\nreturn Array.from({length},getRealtimeSignal)\n};\n\nconst getRealtimeSignal=(value,index)=>({\nname:`SIGRT${index+1}`,\nnumber:SIGRTMIN+index,\naction:\"terminate\",\ndescription:\"Application-specific signal (realtime)\",\nstandard:\"posix\"\n});\n\nconst SIGRTMIN=34;\nexport const SIGRTMAX=64;","\n\nexport const SIGNALS=[\n{\nname:\"SIGHUP\",\nnumber:1,\naction:\"terminate\",\ndescription:\"Terminal closed\",\nstandard:\"posix\"\n},\n{\nname:\"SIGINT\",\nnumber:2,\naction:\"terminate\",\ndescription:\"User interruption with CTRL-C\",\nstandard:\"ansi\"\n},\n{\nname:\"SIGQUIT\",\nnumber:3,\naction:\"core\",\ndescription:\"User interruption with CTRL-\\\\\",\nstandard:\"posix\"\n},\n{\nname:\"SIGILL\",\nnumber:4,\naction:\"core\",\ndescription:\"Invalid machine instruction\",\nstandard:\"ansi\"\n},\n{\nname:\"SIGTRAP\",\nnumber:5,\naction:\"core\",\ndescription:\"Debugger breakpoint\",\nstandard:\"posix\"\n},\n{\nname:\"SIGABRT\",\nnumber:6,\naction:\"core\",\ndescription:\"Aborted\",\nstandard:\"ansi\"\n},\n{\nname:\"SIGIOT\",\nnumber:6,\naction:\"core\",\ndescription:\"Aborted\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGBUS\",\nnumber:7,\naction:\"core\",\ndescription:\n\"Bus error due to misaligned, non-existing address or paging error\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGEMT\",\nnumber:7,\naction:\"terminate\",\ndescription:\"Command should be emulated but is not implemented\",\nstandard:\"other\"\n},\n{\nname:\"SIGFPE\",\nnumber:8,\naction:\"core\",\ndescription:\"Floating point arithmetic error\",\nstandard:\"ansi\"\n},\n{\nname:\"SIGKILL\",\nnumber:9,\naction:\"terminate\",\ndescription:\"Forced termination\",\nstandard:\"posix\",\nforced:true\n},\n{\nname:\"SIGUSR1\",\nnumber:10,\naction:\"terminate\",\ndescription:\"Application-specific signal\",\nstandard:\"posix\"\n},\n{\nname:\"SIGSEGV\",\nnumber:11,\naction:\"core\",\ndescription:\"Segmentation fault\",\nstandard:\"ansi\"\n},\n{\nname:\"SIGUSR2\",\nnumber:12,\naction:\"terminate\",\ndescription:\"Application-specific signal\",\nstandard:\"posix\"\n},\n{\nname:\"SIGPIPE\",\nnumber:13,\naction:\"terminate\",\ndescription:\"Broken pipe or socket\",\nstandard:\"posix\"\n},\n{\nname:\"SIGALRM\",\nnumber:14,\naction:\"terminate\",\ndescription:\"Timeout or timer\",\nstandard:\"posix\"\n},\n{\nname:\"SIGTERM\",\nnumber:15,\naction:\"terminate\",\ndescription:\"Termination\",\nstandard:\"ansi\"\n},\n{\nname:\"SIGSTKFLT\",\nnumber:16,\naction:\"terminate\",\ndescription:\"Stack is empty or overflowed\",\nstandard:\"other\"\n},\n{\nname:\"SIGCHLD\",\nnumber:17,\naction:\"ignore\",\ndescription:\"Child process terminated, paused or unpaused\",\nstandard:\"posix\"\n},\n{\nname:\"SIGCLD\",\nnumber:17,\naction:\"ignore\",\ndescription:\"Child process terminated, paused or unpaused\",\nstandard:\"other\"\n},\n{\nname:\"SIGCONT\",\nnumber:18,\naction:\"unpause\",\ndescription:\"Unpaused\",\nstandard:\"posix\",\nforced:true\n},\n{\nname:\"SIGSTOP\",\nnumber:19,\naction:\"pause\",\ndescription:\"Paused\",\nstandard:\"posix\",\nforced:true\n},\n{\nname:\"SIGTSTP\",\nnumber:20,\naction:\"pause\",\ndescription:\"Paused using CTRL-Z or \\\"suspend\\\"\",\nstandard:\"posix\"\n},\n{\nname:\"SIGTTIN\",\nnumber:21,\naction:\"pause\",\ndescription:\"Background process cannot read terminal input\",\nstandard:\"posix\"\n},\n{\nname:\"SIGBREAK\",\nnumber:21,\naction:\"terminate\",\ndescription:\"User interruption with CTRL-BREAK\",\nstandard:\"other\"\n},\n{\nname:\"SIGTTOU\",\nnumber:22,\naction:\"pause\",\ndescription:\"Background process cannot write to terminal output\",\nstandard:\"posix\"\n},\n{\nname:\"SIGURG\",\nnumber:23,\naction:\"ignore\",\ndescription:\"Socket received out-of-band data\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGXCPU\",\nnumber:24,\naction:\"core\",\ndescription:\"Process timed out\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGXFSZ\",\nnumber:25,\naction:\"core\",\ndescription:\"File too big\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGVTALRM\",\nnumber:26,\naction:\"terminate\",\ndescription:\"Timeout or timer\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGPROF\",\nnumber:27,\naction:\"terminate\",\ndescription:\"Timeout or timer\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGWINCH\",\nnumber:28,\naction:\"ignore\",\ndescription:\"Terminal window size changed\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGIO\",\nnumber:29,\naction:\"terminate\",\ndescription:\"I/O is available\",\nstandard:\"other\"\n},\n{\nname:\"SIGPOLL\",\nnumber:29,\naction:\"terminate\",\ndescription:\"Watched event\",\nstandard:\"other\"\n},\n{\nname:\"SIGINFO\",\nnumber:29,\naction:\"ignore\",\ndescription:\"Request for process information\",\nstandard:\"other\"\n},\n{\nname:\"SIGPWR\",\nnumber:30,\naction:\"terminate\",\ndescription:\"Device running out of power\",\nstandard:\"systemv\"\n},\n{\nname:\"SIGSYS\",\nnumber:31,\naction:\"core\",\ndescription:\"Invalid system call\",\nstandard:\"other\"\n},\n{\nname:\"SIGUNUSED\",\nnumber:31,\naction:\"terminate\",\ndescription:\"Invalid system call\",\nstandard:\"other\"\n}];","import{constants}from\"node:os\";\n\nimport{SIGNALS}from\"./core.js\";\nimport{getRealtimeSignals}from\"./realtime.js\";\n\n\n\nexport const getSignals=()=>{\nconst realtimeSignals=getRealtimeSignals();\nconst signals=[...SIGNALS,...realtimeSignals].map(normalizeSignal);\nreturn signals\n};\n\n\n\n\n\n\n\nconst normalizeSignal=({\nname,\nnumber:defaultNumber,\ndescription,\naction,\nforced=false,\nstandard\n})=>{\nconst{\nsignals:{[name]:constantSignal}\n}=constants;\nconst supported=constantSignal!==undefined;\nconst number=supported?constantSignal:defaultNumber;\nreturn{name,number,description,supported,action,forced,standard}\n};","import{constants}from\"node:os\";\n\nimport{SIGRTMAX}from\"./realtime.js\";\nimport{getSignals}from\"./signals.js\";\n\n\n\nconst getSignalsByName=()=>{\nconst signals=getSignals();\nreturn Object.fromEntries(signals.map(getSignalByName))\n};\n\nconst getSignalByName=({\nname,\nnumber,\ndescription,\nsupported,\naction,\nforced,\nstandard\n})=>[name,{name,number,description,supported,action,forced,standard}];\n\nexport const signalsByName=getSignalsByName();\n\n\n\n\nconst getSignalsByNumber=()=>{\nconst signals=getSignals();\nconst length=SIGRTMAX+1;\nconst signalsA=Array.from({length},(value,number)=>\ngetSignalByNumber(number,signals)\n);\nreturn Object.assign({},...signalsA)\n};\n\nconst getSignalByNumber=(number,signals)=>{\nconst signal=findSignalByNumber(number,signals);\n\nif(signal===undefined){\nreturn{}\n}\n\nconst{name,description,supported,action,forced,standard}=signal;\nreturn{\n[number]:{\nname,\nnumber,\ndescription,\nsupported,\naction,\nforced,\nstandard\n}\n}\n};\n\n\n\nconst findSignalByNumber=(number,signals)=>{\nconst signal=signals.find(({name})=>constants.signals[name]===number);\n\nif(signal!==undefined){\nreturn signal\n}\n\nreturn signals.find((signalA)=>signalA.number===number)\n};\n\nexport const signalsByNumber=getSignalsByNumber();","import process from 'node:process';\nimport {signalsByName} from 'human-signals';\n\nconst getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {\n\tif (timedOut) {\n\t\treturn `timed out after ${timeout} milliseconds`;\n\t}\n\n\tif (isCanceled) {\n\t\treturn 'was canceled';\n\t}\n\n\tif (errorCode !== undefined) {\n\t\treturn `failed with ${errorCode}`;\n\t}\n\n\tif (signal !== undefined) {\n\t\treturn `was killed with ${signal} (${signalDescription})`;\n\t}\n\n\tif (exitCode !== undefined) {\n\t\treturn `failed with exit code ${exitCode}`;\n\t}\n\n\treturn 'failed';\n};\n\nexport const makeError = ({\n\tstdout,\n\tstderr,\n\tall,\n\terror,\n\tsignal,\n\texitCode,\n\tcommand,\n\tescapedCommand,\n\ttimedOut,\n\tisCanceled,\n\tkilled,\n\tparsed: {options: {timeout, cwd = process.cwd()}},\n}) => {\n\t// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.\n\t// We normalize them to `undefined`\n\texitCode = exitCode === null ? undefined : exitCode;\n\tsignal = signal === null ? undefined : signal;\n\tconst signalDescription = signal === undefined ? undefined : signalsByName[signal].description;\n\n\tconst errorCode = error && error.code;\n\n\tconst prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});\n\tconst execaMessage = `Command ${prefix}: ${command}`;\n\tconst isError = Object.prototype.toString.call(error) === '[object Error]';\n\tconst shortMessage = isError ? `${execaMessage}\\n${error.message}` : execaMessage;\n\tconst message = [shortMessage, stderr, stdout].filter(Boolean).join('\\n');\n\n\tif (isError) {\n\t\terror.originalMessage = error.message;\n\t\terror.message = message;\n\t} else {\n\t\terror = new Error(message);\n\t}\n\n\terror.shortMessage = shortMessage;\n\terror.command = command;\n\terror.escapedCommand = escapedCommand;\n\terror.exitCode = exitCode;\n\terror.signal = signal;\n\terror.signalDescription = signalDescription;\n\terror.stdout = stdout;\n\terror.stderr = stderr;\n\terror.cwd = cwd;\n\n\tif (all !== undefined) {\n\t\terror.all = all;\n\t}\n\n\tif ('bufferedData' in error) {\n\t\tdelete error.bufferedData;\n\t}\n\n\terror.failed = true;\n\terror.timedOut = Boolean(timedOut);\n\terror.isCanceled = isCanceled;\n\terror.killed = killed && !timedOut;\n\n\treturn error;\n};\n","const aliases = ['stdin', 'stdout', 'stderr'];\n\nconst hasAlias = options => aliases.some(alias => options[alias] !== undefined);\n\nexport const normalizeStdio = options => {\n\tif (!options) {\n\t\treturn;\n\t}\n\n\tconst {stdio} = options;\n\n\tif (stdio === undefined) {\n\t\treturn aliases.map(alias => options[alias]);\n\t}\n\n\tif (hasAlias(options)) {\n\t\tthrow new Error(`It's not possible to provide \\`stdio\\` in combination with one of ${aliases.map(alias => `\\`${alias}\\``).join(', ')}`);\n\t}\n\n\tif (typeof stdio === 'string') {\n\t\treturn stdio;\n\t}\n\n\tif (!Array.isArray(stdio)) {\n\t\tthrow new TypeError(`Expected \\`stdio\\` to be of type \\`string\\` or \\`Array\\`, got \\`${typeof stdio}\\``);\n\t}\n\n\tconst length = Math.max(stdio.length, aliases.length);\n\treturn Array.from({length}, (value, index) => stdio[index]);\n};\n\n// `ipc` is pushed unless it is already present\nexport const normalizeStdioNode = options => {\n\tconst stdio = normalizeStdio(options);\n\n\tif (stdio === 'ipc') {\n\t\treturn 'ipc';\n\t}\n\n\tif (stdio === undefined || typeof stdio === 'string') {\n\t\treturn [stdio, stdio, stdio, 'ipc'];\n\t}\n\n\tif (stdio.includes('ipc')) {\n\t\treturn stdio;\n\t}\n\n\treturn [...stdio, 'ipc'];\n};\n","/**\n * This is not the set of all possible signals.\n *\n * It IS, however, the set of all signals that trigger\n * an exit on either Linux or BSD systems. Linux is a\n * superset of the signal names supported on BSD, and\n * the unknown signals just fail to register, so we can\n * catch that easily enough.\n *\n * Windows signals are a different set, since there are\n * signals that terminate Windows processes, but don't\n * terminate (or don't even exist) on Posix systems.\n *\n * Don't bother with SIGKILL. It's uncatchable, which\n * means that we can't fire any callbacks anyway.\n *\n * If a user does happen to register a handler on a non-\n * fatal signal like SIGWINCH or something, and then\n * exit, it'll end up firing `process.emit('exit')`, so\n * the handler will be fired anyway.\n *\n * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised\n * artificially, inherently leave the process in a\n * state from which it is not safe to try and enter JS\n * listeners.\n */\nexport const signals = [];\nsignals.push('SIGHUP', 'SIGINT', 'SIGTERM');\nif (process.platform !== 'win32') {\n signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT'\n // should detect profiler and enable/disable accordingly.\n // see #21\n // 'SIGPROF'\n );\n}\nif (process.platform === 'linux') {\n signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT');\n}\n//# sourceMappingURL=signals.js.map","// Note: since nyc uses this module to output coverage, any lines\n// that are in the direct sync flow of nyc's outputCoverage are\n// ignored, since we can never get coverage for them.\n// grab a reference to node's real process object right away\nimport { signals } from './signals.js';\nexport { signals };\nconst processOk = (process) => !!process &&\n typeof process === 'object' &&\n typeof process.removeListener === 'function' &&\n typeof process.emit === 'function' &&\n typeof process.reallyExit === 'function' &&\n typeof process.listeners === 'function' &&\n typeof process.kill === 'function' &&\n typeof process.pid === 'number' &&\n typeof process.on === 'function';\nconst kExitEmitter = Symbol.for('signal-exit emitter');\nconst global = globalThis;\nconst ObjectDefineProperty = Object.defineProperty.bind(Object);\n// teeny special purpose ee\nclass Emitter {\n emitted = {\n afterExit: false,\n exit: false,\n };\n listeners = {\n afterExit: [],\n exit: [],\n };\n count = 0;\n id = Math.random();\n constructor() {\n if (global[kExitEmitter]) {\n return global[kExitEmitter];\n }\n ObjectDefineProperty(global, kExitEmitter, {\n value: this,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n }\n on(ev, fn) {\n this.listeners[ev].push(fn);\n }\n removeListener(ev, fn) {\n const list = this.listeners[ev];\n const i = list.indexOf(fn);\n /* c8 ignore start */\n if (i === -1) {\n return;\n }\n /* c8 ignore stop */\n if (i === 0 && list.length === 1) {\n list.length = 0;\n }\n else {\n list.splice(i, 1);\n }\n }\n emit(ev, code, signal) {\n if (this.emitted[ev]) {\n return false;\n }\n this.emitted[ev] = true;\n let ret = false;\n for (const fn of this.listeners[ev]) {\n ret = fn(code, signal) === true || ret;\n }\n if (ev === 'exit') {\n ret = this.emit('afterExit', code, signal) || ret;\n }\n return ret;\n }\n}\nclass SignalExitBase {\n}\nconst signalExitWrap = (handler) => {\n return {\n onExit(cb, opts) {\n return handler.onExit(cb, opts);\n },\n load() {\n return handler.load();\n },\n unload() {\n return handler.unload();\n },\n };\n};\nclass SignalExitFallback extends SignalExitBase {\n onExit() {\n return () => { };\n }\n load() { }\n unload() { }\n}\nclass SignalExit extends SignalExitBase {\n // \"SIGHUP\" throws an `ENOSYS` error on Windows,\n // so use a supported signal instead\n /* c8 ignore start */\n #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP';\n /* c8 ignore stop */\n #emitter = new Emitter();\n #process;\n #originalProcessEmit;\n #originalProcessReallyExit;\n #sigListeners = {};\n #loaded = false;\n constructor(process) {\n super();\n this.#process = process;\n // { <signal>: <listener fn>, ... }\n this.#sigListeners = {};\n for (const sig of signals) {\n this.#sigListeners[sig] = () => {\n // If there are no other listeners, an exit is coming!\n // Simplest way: remove us and then re-send the signal.\n // We know that this will kill the process, so we can\n // safely emit now.\n const listeners = this.#process.listeners(sig);\n let { count } = this.#emitter;\n // This is a workaround for the fact that signal-exit v3 and signal\n // exit v4 are not aware of each other, and each will attempt to let\n // the other handle it, so neither of them do. To correct this, we\n // detect if we're the only handler *except* for previous versions\n // of signal-exit, and increment by the count of listeners it has\n // created.\n /* c8 ignore start */\n const p = process;\n if (typeof p.__signal_exit_emitter__ === 'object' &&\n typeof p.__signal_exit_emitter__.count === 'number') {\n count += p.__signal_exit_emitter__.count;\n }\n /* c8 ignore stop */\n if (listeners.length === count) {\n this.unload();\n const ret = this.#emitter.emit('exit', null, sig);\n /* c8 ignore start */\n const s = sig === 'SIGHUP' ? this.#hupSig : sig;\n if (!ret)\n process.kill(process.pid, s);\n /* c8 ignore stop */\n }\n };\n }\n this.#originalProcessReallyExit = process.reallyExit;\n this.#originalProcessEmit = process.emit;\n }\n onExit(cb, opts) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return () => { };\n }\n /* c8 ignore stop */\n if (this.#loaded === false) {\n this.load();\n }\n const ev = opts?.alwaysLast ? 'afterExit' : 'exit';\n this.#emitter.on(ev, cb);\n return () => {\n this.#emitter.removeListener(ev, cb);\n if (this.#emitter.listeners['exit'].length === 0 &&\n this.#emitter.listeners['afterExit'].length === 0) {\n this.unload();\n }\n };\n }\n load() {\n if (this.#loaded) {\n return;\n }\n this.#loaded = true;\n // This is the number of onSignalExit's that are in play.\n // It's important so that we can count the correct number of\n // listeners on signals, and don't wait for the other one to\n // handle it instead of us.\n this.#emitter.count += 1;\n for (const sig of signals) {\n try {\n const fn = this.#sigListeners[sig];\n if (fn)\n this.#process.on(sig, fn);\n }\n catch (_) { }\n }\n this.#process.emit = (ev, ...a) => {\n return this.#processEmit(ev, ...a);\n };\n this.#process.reallyExit = (code) => {\n return this.#processReallyExit(code);\n };\n }\n unload() {\n if (!this.#loaded) {\n return;\n }\n this.#loaded = false;\n signals.forEach(sig => {\n const listener = this.#sigListeners[sig];\n /* c8 ignore start */\n if (!listener) {\n throw new Error('Listener not defined for signal: ' + sig);\n }\n /* c8 ignore stop */\n try {\n this.#process.removeListener(sig, listener);\n /* c8 ignore start */\n }\n catch (_) { }\n /* c8 ignore stop */\n });\n this.#process.emit = this.#originalProcessEmit;\n this.#process.reallyExit = this.#originalProcessReallyExit;\n this.#emitter.count -= 1;\n }\n #processReallyExit(code) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return 0;\n }\n this.#process.exitCode = code || 0;\n /* c8 ignore stop */\n this.#emitter.emit('exit', this.#process.exitCode, null);\n return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);\n }\n #processEmit(ev, ...args) {\n const og = this.#originalProcessEmit;\n if (ev === 'exit' && processOk(this.#process)) {\n if (typeof args[0] === 'number') {\n this.#process.exitCode = args[0];\n /* c8 ignore start */\n }\n /* c8 ignore start */\n const ret = og.call(this.#process, ev, ...args);\n /* c8 ignore start */\n this.#emitter.emit('exit', this.#process.exitCode, null);\n /* c8 ignore stop */\n return ret;\n }\n else {\n return og.call(this.#process, ev, ...args);\n }\n }\n}\nconst process = globalThis.process;\n// wrap so that we call the method on the actual handler, without\n// exporting it directly.\nexport const { \n/**\n * Called when the process is exiting, whether via signal, explicit\n * exit, or running out of stuff to do.\n *\n * If the global process object is not suitable for instrumentation,\n * then this will be a no-op.\n *\n * Returns a function that may be used to unload signal-exit.\n */\nonExit, \n/**\n * Load the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\nload, \n/**\n * Unload the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\nunload, } = signalExitWrap(processOk(process) ? new SignalExit(process) : new SignalExitFallback());\n//# sourceMappingURL=index.js.map","import os from 'node:os';\nimport {onExit} from 'signal-exit';\n\nconst DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;\n\n// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior\nexport const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {\n\tconst killResult = kill(signal);\n\tsetKillTimeout(kill, signal, options, killResult);\n\treturn killResult;\n};\n\nconst setKillTimeout = (kill, signal, options, killResult) => {\n\tif (!shouldForceKill(signal, options, killResult)) {\n\t\treturn;\n\t}\n\n\tconst timeout = getForceKillAfterTimeout(options);\n\tconst t = setTimeout(() => {\n\t\tkill('SIGKILL');\n\t}, timeout);\n\n\t// Guarded because there's no `.unref()` when `execa` is used in the renderer\n\t// process in Electron. This cannot be tested since we don't run tests in\n\t// Electron.\n\t// istanbul ignore else\n\tif (t.unref) {\n\t\tt.unref();\n\t}\n};\n\nconst shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult;\n\nconst isSigterm = signal => signal === os.constants.signals.SIGTERM\n\t\t|| (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');\n\nconst getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {\n\tif (forceKillAfterTimeout === true) {\n\t\treturn DEFAULT_FORCE_KILL_TIMEOUT;\n\t}\n\n\tif (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {\n\t\tthrow new TypeError(`Expected the \\`forceKillAfterTimeout\\` option to be a non-negative integer, got \\`${forceKillAfterTimeout}\\` (${typeof forceKillAfterTimeout})`);\n\t}\n\n\treturn forceKillAfterTimeout;\n};\n\n// `childProcess.cancel()`\nexport const spawnedCancel = (spawned, context) => {\n\tconst killResult = spawned.kill();\n\n\tif (killResult) {\n\t\tcontext.isCanceled = true;\n\t}\n};\n\nconst timeoutKill = (spawned, signal, reject) => {\n\tspawned.kill(signal);\n\treject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));\n};\n\n// `timeout` option handling\nexport const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {\n\tif (timeout === 0 || timeout === undefined) {\n\t\treturn spawnedPromise;\n\t}\n\n\tlet timeoutId;\n\tconst timeoutPromise = new Promise((resolve, reject) => {\n\t\ttimeoutId = setTimeout(() => {\n\t\t\ttimeoutKill(spawned, killSignal, reject);\n\t\t}, timeout);\n\t});\n\n\tconst safeSpawnedPromise = spawnedPromise.finally(() => {\n\t\tclearTimeout(timeoutId);\n\t});\n\n\treturn Promise.race([timeoutPromise, safeSpawnedPromise]);\n};\n\nexport const validateTimeout = ({timeout}) => {\n\tif (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {\n\t\tthrow new TypeError(`Expected the \\`timeout\\` option to be a non-negative integer, got \\`${timeout}\\` (${typeof timeout})`);\n\t}\n};\n\n// `cleanup` option handling\nexport const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {\n\tif (!cleanup || detached) {\n\t\treturn timedPromise;\n\t}\n\n\tconst removeExitHandler = onExit(() => {\n\t\tspawned.kill();\n\t});\n\n\treturn timedPromise.finally(() => {\n\t\tremoveExitHandler();\n\t});\n};\n","export function isStream(stream) {\n\treturn stream !== null\n\t\t&& typeof stream === 'object'\n\t\t&& typeof stream.pipe === 'function';\n}\n\nexport function isWritableStream(stream) {\n\treturn isStream(stream)\n\t\t&& stream.writable !== false\n\t\t&& typeof stream._write === 'function'\n\t\t&& typeof stream._writableState === 'object';\n}\n\nexport function isReadableStream(stream) {\n\treturn isStream(stream)\n\t\t&& stream.readable !== false\n\t\t&& typeof stream._read === 'function'\n\t\t&& typeof stream._readableState === 'object';\n}\n\nexport function isDuplexStream(stream) {\n\treturn isWritableStream(stream)\n\t\t&& isReadableStream(stream);\n}\n\nexport function isTransformStream(stream) {\n\treturn isDuplexStream(stream)\n\t\t&& typeof stream._transform === 'function';\n}\n","import {createWriteStream} from 'node:fs';\nimport {ChildProcess} from 'node:child_process';\nimport {isWritableStream} from 'is-stream';\n\nconst isExecaChildProcess = target => target instanceof ChildProcess && typeof target.then === 'function';\n\nconst pipeToTarget = (spawned, streamName, target) => {\n\tif (typeof target === 'string') {\n\t\tspawned[streamName].pipe(createWriteStream(target));\n\t\treturn spawned;\n\t}\n\n\tif (isWritableStream(target)) {\n\t\tspawned[streamName].pipe(target);\n\t\treturn spawned;\n\t}\n\n\tif (!isExecaChildProcess(target)) {\n\t\tthrow new TypeError('The second argument must be a string, a stream or an Execa child process.');\n\t}\n\n\tif (!isWritableStream(target.stdin)) {\n\t\tthrow new TypeError('The target child process\\'s stdin must be available.');\n\t}\n\n\tspawned[streamName].pipe(target.stdin);\n\treturn target;\n};\n\nexport const addPipeMethods = spawned => {\n\tif (spawned.stdout !== null) {\n\t\tspawned.pipeStdout = pipeToTarget.bind(undefined, spawned, 'stdout');\n\t}\n\n\tif (spawned.stderr !== null) {\n\t\tspawned.pipeStderr = pipeToTarget.bind(undefined, spawned, 'stderr');\n\t}\n\n\tif (spawned.all !== undefined) {\n\t\tspawned.pipeAll = pipeToTarget.bind(undefined, spawned, 'all');\n\t}\n};\n","export const getStreamContents = async (stream, {init, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, finalize}, {maxBuffer = Number.POSITIVE_INFINITY} = {}) => {\n\tif (!isAsyncIterable(stream)) {\n\t\tthrow new Error('The first argument must be a Readable, a ReadableStream, or an async iterable.');\n\t}\n\n\tconst state = init();\n\tstate.length = 0;\n\n\ttry {\n\t\tfor await (const chunk of stream) {\n\t\t\tconst chunkType = getChunkType(chunk);\n\t\t\tconst convertedChunk = convertChunk[chunkType](chunk, state);\n\t\t\tappendChunk({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer});\n\t\t}\n\n\t\tappendFinalChunk({state, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer});\n\t\treturn finalize(state);\n\t} catch (error) {\n\t\terror.bufferedData = finalize(state);\n\t\tthrow error;\n\t}\n};\n\nconst appendFinalChunk = ({state, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer}) => {\n\tconst convertedChunk = getFinalChunk(state);\n\tif (convertedChunk !== undefined) {\n\t\tappendChunk({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer});\n\t}\n};\n\nconst appendChunk = ({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}) => {\n\tconst chunkSize = getSize(convertedChunk);\n\tconst newLength = state.length + chunkSize;\n\n\tif (newLength <= maxBuffer) {\n\t\taddNewChunk(convertedChunk, state, addChunk, newLength);\n\t\treturn;\n\t}\n\n\tconst truncatedChunk = truncateChunk(convertedChunk, maxBuffer - state.length);\n\n\tif (truncatedChunk !== undefined) {\n\t\taddNewChunk(truncatedChunk, state, addChunk, maxBuffer);\n\t}\n\n\tthrow new MaxBufferError();\n};\n\nconst addNewChunk = (convertedChunk, state, addChunk, newLength) => {\n\tstate.contents = addChunk(convertedChunk, state, newLength);\n\tstate.length = newLength;\n};\n\nconst isAsyncIterable = stream => typeof stream === 'object' && stream !== null && typeof stream[Symbol.asyncIterator] === 'function';\n\nconst getChunkType = chunk => {\n\tconst typeOfChunk = typeof chunk;\n\n\tif (typeOfChunk === 'string') {\n\t\treturn 'string';\n\t}\n\n\tif (typeOfChunk !== 'object' || chunk === null) {\n\t\treturn 'others';\n\t}\n\n\t// eslint-disable-next-line n/prefer-global/buffer\n\tif (globalThis.Buffer?.isBuffer(chunk)) {\n\t\treturn 'buffer';\n\t}\n\n\tconst prototypeName = objectToString.call(chunk);\n\n\tif (prototypeName === '[object ArrayBuffer]') {\n\t\treturn 'arrayBuffer';\n\t}\n\n\tif (prototypeName === '[object DataView]') {\n\t\treturn 'dataView';\n\t}\n\n\tif (\n\t\tNumber.isInteger(chunk.byteLength)\n\t\t&& Number.isInteger(chunk.byteOffset)\n\t\t&& objectToString.call(chunk.buffer) === '[object ArrayBuffer]'\n\t) {\n\t\treturn 'typedArray';\n\t}\n\n\treturn 'others';\n};\n\nconst {toString: objectToString} = Object.prototype;\n\nexport class MaxBufferError extends Error {\n\tname = 'MaxBufferError';\n\n\tconstructor() {\n\t\tsuper('maxBuffer exceeded');\n\t}\n}\n","export const identity = value => value;\n\nexport const noop = () => undefined;\n\nexport const getContentsProp = ({contents}) => contents;\n\nexport const throwObjectStream = chunk => {\n\tthrow new Error(`Streams in object mode are not supported: ${String(chunk)}`);\n};\n\nexport const getLengthProp = convertedChunk => convertedChunk.length;\n","import {getStreamContents} from './contents.js';\nimport {noop, throwObjectStream, getLengthProp} from './utils.js';\n\nexport async function getStreamAsArrayBuffer(stream, options) {\n\treturn getStreamContents(stream, arrayBufferMethods, options);\n}\n\nconst initArrayBuffer = () => ({contents: new ArrayBuffer(0)});\n\nconst useTextEncoder = chunk => textEncoder.encode(chunk);\nconst textEncoder = new TextEncoder();\n\nconst useUint8Array = chunk => new Uint8Array(chunk);\n\nconst useUint8ArrayWithOffset = chunk => new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n\nconst truncateArrayBufferChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize);\n\n// `contents` is an increasingly growing `Uint8Array`.\nconst addArrayBufferChunk = (convertedChunk, {contents, length: previousLength}, length) => {\n\tconst newContents = hasArrayBufferResize() ? resizeArrayBuffer(contents, length) : resizeArrayBufferSlow(contents, length);\n\tnew Uint8Array(newContents).set(convertedChunk, previousLength);\n\treturn newContents;\n};\n\n// Without `ArrayBuffer.resize()`, `contents` size is always a power of 2.\n// This means its last bytes are zeroes (not stream data), which need to be\n// trimmed at the end with `ArrayBuffer.slice()`.\nconst resizeArrayBufferSlow = (contents, length) => {\n\tif (length <= contents.byteLength) {\n\t\treturn contents;\n\t}\n\n\tconst arrayBuffer = new ArrayBuffer(getNewContentsLength(length));\n\tnew Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0);\n\treturn arrayBuffer;\n};\n\n// With `ArrayBuffer.resize()`, `contents` size matches exactly the size of\n// the stream data. It does not include extraneous zeroes to trim at the end.\n// The underlying `ArrayBuffer` does allocate a number of bytes that is a power\n// of 2, but those bytes are only visible after calling `ArrayBuffer.resize()`.\nconst resizeArrayBuffer = (contents, length) => {\n\tif (length <= contents.maxByteLength) {\n\t\tcontents.resize(length);\n\t\treturn contents;\n\t}\n\n\tconst arrayBuffer = new ArrayBuffer(length, {maxByteLength: getNewContentsLength(length)});\n\tnew Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0);\n\treturn arrayBuffer;\n};\n\n// Retrieve the closest `length` that is both >= and a power of 2\nconst getNewContentsLength = length => SCALE_FACTOR ** Math.ceil(Math.log(length) / Math.log(SCALE_FACTOR));\n\nconst SCALE_FACTOR = 2;\n\nconst finalizeArrayBuffer = ({contents, length}) => hasArrayBufferResize() ? contents : contents.slice(0, length);\n\n// `ArrayBuffer.slice()` is slow. When `ArrayBuffer.resize()` is available\n// (Node >=20.0.0, Safari >=16.4 and Chrome), we can use it instead.\n// eslint-disable-next-line no-warning-comments\n// TODO: remove after dropping support for Node 20.\n// eslint-disable-next-line no-warning-comments\n// TODO: use `ArrayBuffer.transferToFixedLength()` instead once it is available\nconst hasArrayBufferResize = () => 'resize' in ArrayBuffer.prototype;\n\nconst arrayBufferMethods = {\n\tinit: initArrayBuffer,\n\tconvertChunk: {\n\t\tstring: useTextEncoder,\n\t\tbuffer: useUint8Array,\n\t\tarrayBuffer: useUint8Array,\n\t\tdataView: useUint8ArrayWithOffset,\n\t\ttypedArray: useUint8ArrayWithOffset,\n\t\tothers: throwObjectStream,\n\t},\n\tgetSize: getLengthProp,\n\ttruncateChunk: truncateArrayBufferChunk,\n\taddChunk: addArrayBufferChunk,\n\tgetFinalChunk: noop,\n\tfinalize: finalizeArrayBuffer,\n};\n","import {getStreamAsArrayBuffer} from './array-buffer.js';\n\nexport async function getStreamAsBuffer(stream, options) {\n\tif (!('Buffer' in globalThis)) {\n\t\tthrow new Error('getStreamAsBuffer() is only supported in Node.js');\n\t}\n\n\ttry {\n\t\treturn arrayBufferToNodeBuffer(await getStreamAsArrayBuffer(stream, options));\n\t} catch (error) {\n\t\tif (error.bufferedData !== undefined) {\n\t\t\terror.bufferedData = arrayBufferToNodeBuffer(error.bufferedData);\n\t\t}\n\n\t\tthrow error;\n\t}\n}\n\n// eslint-disable-next-line n/prefer-global/buffer\nconst arrayBufferToNodeBuffer = arrayBuffer => globalThis.Buffer.from(arrayBuffer);\n","import {getStreamContents} from './contents.js';\nimport {identity, getContentsProp, throwObjectStream, getLengthProp} from './utils.js';\n\nexport async function getStreamAsString(stream, options) {\n\treturn getStreamContents(stream, stringMethods, options);\n}\n\nconst initString = () => ({contents: '', textDecoder: new TextDecoder()});\n\nconst useTextDecoder = (chunk, {textDecoder}) => textDecoder.decode(chunk, {stream: true});\n\nconst addStringChunk = (convertedChunk, {contents}) => contents + convertedChunk;\n\nconst truncateStringChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize);\n\nconst getFinalStringChunk = ({textDecoder}) => {\n\tconst finalChunk = textDecoder.decode();\n\treturn finalChunk === '' ? undefined : finalChunk;\n};\n\nconst stringMethods = {\n\tinit: initString,\n\tconvertChunk: {\n\t\tstring: identity,\n\t\tbuffer: useTextDecoder,\n\t\tarrayBuffer: useTextDecoder,\n\t\tdataView: useTextDecoder,\n\t\ttypedArray: useTextDecoder,\n\t\tothers: throwObjectStream,\n\t},\n\tgetSize: getLengthProp,\n\ttruncateChunk: truncateStringChunk,\n\taddChunk: addStringChunk,\n\tgetFinalChunk: getFinalStringChunk,\n\tfinalize: getContentsProp,\n};\n","'use strict';\n\nconst { PassThrough } = require('stream');\n\nmodule.exports = function (/*streams...*/) {\n var sources = []\n var output = new PassThrough({objectMode: true})\n\n output.setMaxListeners(0)\n\n output.add = add\n output.isEmpty = isEmpty\n\n output.on('unpipe', remove)\n\n Array.prototype.slice.call(arguments).forEach(add)\n\n return output\n\n function add (source) {\n if (Array.isArray(source)) {\n source.forEach(add)\n return this\n }\n\n sources.push(source);\n source.once('end', remove.bind(null, source))\n source.once('error', output.emit.bind(output, 'error'))\n source.pipe(output, {end: false})\n return this\n }\n\n function isEmpty () {\n return sources.length == 0;\n }\n\n function remove (source) {\n sources = sources.filter(function (it) { return it !== source })\n if (!sources.length && output.readable) { output.end() }\n }\n}\n","import {createReadStream, readFileSync} from 'node:fs';\nimport {setTimeout} from 'node:timers/promises';\nimport {isStream} from 'is-stream';\nimport getStream, {getStreamAsBuffer} from 'get-stream';\nimport mergeStream from 'merge-stream';\n\nconst validateInputOptions = input => {\n\tif (input !== undefined) {\n\t\tthrow new TypeError('The `input` and `inputFile` options cannot be both set.');\n\t}\n};\n\nconst getInputSync = ({input, inputFile}) => {\n\tif (typeof inputFile !== 'string') {\n\t\treturn input;\n\t}\n\n\tvalidateInputOptions(input);\n\treturn readFileSync(inputFile);\n};\n\n// `input` and `inputFile` option in sync mode\nexport const handleInputSync = options => {\n\tconst input = getInputSync(options);\n\n\tif (isStream(input)) {\n\t\tthrow new TypeError('The `input` option cannot be a stream in sync mode');\n\t}\n\n\treturn input;\n};\n\nconst getInput = ({input, inputFile}) => {\n\tif (typeof inputFile !== 'string') {\n\t\treturn input;\n\t}\n\n\tvalidateInputOptions(input);\n\treturn createReadStream(inputFile);\n};\n\n// `input` and `inputFile` option in async mode\nexport const handleInput = (spawned, options) => {\n\tconst input = getInput(options);\n\n\tif (input === undefined) {\n\t\treturn;\n\t}\n\n\tif (isStream(input)) {\n\t\tinput.pipe(spawned.stdin);\n\t} else {\n\t\tspawned.stdin.end(input);\n\t}\n};\n\n// `all` interleaves `stdout` and `stderr`\nexport const makeAllStream = (spawned, {all}) => {\n\tif (!all || (!spawned.stdout && !spawned.stderr)) {\n\t\treturn;\n\t}\n\n\tconst mixed = mergeStream();\n\n\tif (spawned.stdout) {\n\t\tmixed.add(spawned.stdout);\n\t}\n\n\tif (spawned.stderr) {\n\t\tmixed.add(spawned.stderr);\n\t}\n\n\treturn mixed;\n};\n\n// On failure, `result.stdout|stderr|all` should contain the currently buffered stream\nconst getBufferedData = async (stream, streamPromise) => {\n\t// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve\n\tif (!stream || streamPromise === undefined) {\n\t\treturn;\n\t}\n\n\t// Wait for the `all` stream to receive the last chunk before destroying the stream\n\tawait setTimeout(0);\n\n\tstream.destroy();\n\n\ttry {\n\t\treturn await streamPromise;\n\t} catch (error) {\n\t\treturn error.bufferedData;\n\t}\n};\n\nconst getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {\n\tif (!stream || !buffer) {\n\t\treturn;\n\t}\n\n\t// eslint-disable-next-line unicorn/text-encoding-identifier-case\n\tif (encoding === 'utf8' || encoding === 'utf-8') {\n\t\treturn getStream(stream, {maxBuffer});\n\t}\n\n\tif (encoding === null || encoding === 'buffer') {\n\t\treturn getStreamAsBuffer(stream, {maxBuffer});\n\t}\n\n\treturn applyEncoding(stream, maxBuffer, encoding);\n};\n\nconst applyEncoding = async (stream, maxBuffer, encoding) => {\n\tconst buffer = await getStreamAsBuffer(stream, {maxBuffer});\n\treturn buffer.toString(encoding);\n};\n\n// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)\nexport const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {\n\tconst stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});\n\tconst stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});\n\tconst allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});\n\n\ttry {\n\t\treturn await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);\n\t} catch (error) {\n\t\treturn Promise.all([\n\t\t\t{error, signal: error.signal, timedOut: error.timedOut},\n\t\t\tgetBufferedData(stdout, stdoutPromise),\n\t\t\tgetBufferedData(stderr, stderrPromise),\n\t\t\tgetBufferedData(all, allPromise),\n\t\t]);\n\t}\n};\n","// eslint-disable-next-line unicorn/prefer-top-level-await\nconst nativePromisePrototype = (async () => {})().constructor.prototype;\n\nconst descriptors = ['then', 'catch', 'finally'].map(property => [\n\tproperty,\n\tReflect.getOwnPropertyDescriptor(nativePromisePrototype, property),\n]);\n\n// The return value is a mixin of `childProcess` and `Promise`\nexport const mergePromise = (spawned, promise) => {\n\tfor (const [property, descriptor] of descriptors) {\n\t\t// Starting the main `promise` is deferred to avoid consuming streams\n\t\tconst value = typeof promise === 'function'\n\t\t\t? (...args) => Reflect.apply(descriptor.value, promise(), args)\n\t\t\t: descriptor.value.bind(promise);\n\n\t\tReflect.defineProperty(spawned, property, {...descriptor, value});\n\t}\n};\n\n// Use promises instead of `child_process` events\nexport const getSpawnedPromise = spawned => new Promise((resolve, reject) => {\n\tspawned.on('exit', (exitCode, signal) => {\n\t\tresolve({exitCode, signal});\n\t});\n\n\tspawned.on('error', error => {\n\t\treject(error);\n\t});\n\n\tif (spawned.stdin) {\n\t\tspawned.stdin.on('error', error => {\n\t\t\treject(error);\n\t\t});\n\t}\n});\n","import {Buffer} from 'node:buffer';\nimport {ChildProcess} from 'node:child_process';\n\nconst normalizeArgs = (file, args = []) => {\n\tif (!Array.isArray(args)) {\n\t\treturn [file];\n\t}\n\n\treturn [file, ...args];\n};\n\nconst NO_ESCAPE_REGEXP = /^[\\w.-]+$/;\n\nconst escapeArg = arg => {\n\tif (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) {\n\t\treturn arg;\n\t}\n\n\treturn `\"${arg.replaceAll('\"', '\\\\\"')}\"`;\n};\n\nexport const joinCommand = (file, args) => normalizeArgs(file, args).join(' ');\n\nexport const getEscapedCommand = (file, args) => normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');\n\nconst SPACES_REGEXP = / +/g;\n\n// Handle `execaCommand()`\nexport const parseCommand = command => {\n\tconst tokens = [];\n\tfor (const token of command.trim().split(SPACES_REGEXP)) {\n\t\t// Allow spaces to be escaped by a backslash if not meant as a delimiter\n\t\tconst previousToken = tokens.at(-1);\n\t\tif (previousToken && previousToken.endsWith('\\\\')) {\n\t\t\t// Merge previous token with current one\n\t\t\ttokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;\n\t\t} else {\n\t\t\ttokens.push(token);\n\t\t}\n\t}\n\n\treturn tokens;\n};\n\nconst parseExpression = expression => {\n\tconst typeOfExpression = typeof expression;\n\n\tif (typeOfExpression === 'string') {\n\t\treturn expression;\n\t}\n\n\tif (typeOfExpression === 'number') {\n\t\treturn String(expression);\n\t}\n\n\tif (\n\t\ttypeOfExpression === 'object'\n\t\t&& expression !== null\n\t\t&& !(expression instanceof ChildProcess)\n\t\t&& 'stdout' in expression\n\t) {\n\t\tconst typeOfStdout = typeof expression.stdout;\n\n\t\tif (typeOfStdout === 'string') {\n\t\t\treturn expression.stdout;\n\t\t}\n\n\t\tif (Buffer.isBuffer(expression.stdout)) {\n\t\t\treturn expression.stdout.toString();\n\t\t}\n\n\t\tthrow new TypeError(`Unexpected \"${typeOfStdout}\" stdout in template expression`);\n\t}\n\n\tthrow new TypeError(`Unexpected \"${typeOfExpression}\" in template expression`);\n};\n\nconst concatTokens = (tokens, nextTokens, isNew) => isNew || tokens.length === 0 || nextTokens.length === 0\n\t? [...tokens, ...nextTokens]\n\t: [\n\t\t...tokens.slice(0, -1),\n\t\t`${tokens.at(-1)}${nextTokens[0]}`,\n\t\t...nextTokens.slice(1),\n\t];\n\nconst parseTemplate = ({templates, expressions, tokens, index, template}) => {\n\tconst templateString = template ?? templates.raw[index];\n\tconst templateTokens = templateString.split(SPACES_REGEXP).filter(Boolean);\n\tconst newTokens = concatTokens(\n\t\ttokens,\n\t\ttemplateTokens,\n\t\ttemplateString.startsWith(' '),\n\t);\n\n\tif (index === expressions.length) {\n\t\treturn newTokens;\n\t}\n\n\tconst expression = expressions[index];\n\tconst expressionTokens = Array.isArray(expression)\n\t\t? expression.map(expression => parseExpression(expression))\n\t\t: [parseExpression(expression)];\n\treturn concatTokens(\n\t\tnewTokens,\n\t\texpressionTokens,\n\t\ttemplateString.endsWith(' '),\n\t);\n};\n\nexport const parseTemplates = (templates, expressions) => {\n\tlet tokens = [];\n\n\tfor (const [index, template] of templates.entries()) {\n\t\ttokens = parseTemplate({templates, expressions, tokens, index, template});\n\t}\n\n\treturn tokens;\n};\n\n","import {debuglog} from 'node:util';\nimport process from 'node:process';\n\nexport const verboseDefault = debuglog('execa').enabled;\n\nconst padField = (field, padding) => String(field).padStart(padding, '0');\n\nconst getTimestamp = () => {\n\tconst date = new Date();\n\treturn `${padField(date.getHours(), 2)}:${padField(date.getMinutes(), 2)}:${padField(date.getSeconds(), 2)}.${padField(date.getMilliseconds(), 3)}`;\n};\n\nexport const logCommand = (escapedCommand, {verbose}) => {\n\tif (!verbose) {\n\t\treturn;\n\t}\n\n\tprocess.stderr.write(`[${getTimestamp()}] ${escapedCommand}\\n`);\n};\n","import {Buffer} from 'node:buffer';\nimport path from 'node:path';\nimport childProcess from 'node:child_process';\nimport process from 'node:process';\nimport crossSpawn from 'cross-spawn';\nimport stripFinalNewline from 'strip-final-newline';\nimport {npmRunPathEnv} from 'npm-run-path';\nimport onetime from 'onetime';\nimport {makeError} from './lib/error.js';\nimport {normalizeStdio, normalizeStdioNode} from './lib/stdio.js';\nimport {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';\nimport {addPipeMethods} from './lib/pipe.js';\nimport {handleInput, getSpawnedResult, makeAllStream, handleInputSync} from './lib/stream.js';\nimport {mergePromise, getSpawnedPromise} from './lib/promise.js';\nimport {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';\nimport {logCommand, verboseDefault} from './lib/verbose.js';\n\nconst DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;\n\nconst getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {\n\tconst env = extendEnv ? {...process.env, ...envOption} : envOption;\n\n\tif (preferLocal) {\n\t\treturn npmRunPathEnv({env, cwd: localDir, execPath});\n\t}\n\n\treturn env;\n};\n\nconst handleArguments = (file, args, options = {}) => {\n\tconst parsed = crossSpawn._parse(file, args, options);\n\tfile = parsed.command;\n\targs = parsed.args;\n\toptions = parsed.options;\n\n\toptions = {\n\t\tmaxBuffer: DEFAULT_MAX_BUFFER,\n\t\tbuffer: true,\n\t\tstripFinalNewline: true,\n\t\textendEnv: true,\n\t\tpreferLocal: false,\n\t\tlocalDir: options.cwd || process.cwd(),\n\t\texecPath: process.execPath,\n\t\tencoding: 'utf8',\n\t\treject: true,\n\t\tcleanup: true,\n\t\tall: false,\n\t\twindowsHide: true,\n\t\tverbose: verboseDefault,\n\t\t...options,\n\t};\n\n\toptions.env = getEnv(options);\n\n\toptions.stdio = normalizeStdio(options);\n\n\tif (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {\n\t\t// #116\n\t\targs.unshift('/q');\n\t}\n\n\treturn {file, args, options, parsed};\n};\n\nconst handleOutput = (options, value, error) => {\n\tif (typeof value !== 'string' && !Buffer.isBuffer(value)) {\n\t\t// When `execaSync()` errors, we normalize it to '' to mimic `execa()`\n\t\treturn error === undefined ? undefined : '';\n\t}\n\n\tif (options.stripFinalNewline) {\n\t\treturn stripFinalNewline(value);\n\t}\n\n\treturn value;\n};\n\nexport function execa(file, args, options) {\n\tconst parsed = handleArguments(file, args, options);\n\tconst command = joinCommand(file, args);\n\tconst escapedCommand = getEscapedCommand(file, args);\n\tlogCommand(escapedCommand, parsed.options);\n\n\tvalidateTimeout(parsed.options);\n\n\tlet spawned;\n\ttry {\n\t\tspawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);\n\t} catch (error) {\n\t\t// Ensure the returned error is always both a promise and a child process\n\t\tconst dummySpawned = new childProcess.ChildProcess();\n\t\tconst errorPromise = Promise.reject(makeError({\n\t\t\terror,\n\t\t\tstdout: '',\n\t\t\tstderr: '',\n\t\t\tall: '',\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\tparsed,\n\t\t\ttimedOut: false,\n\t\t\tisCanceled: false,\n\t\t\tkilled: false,\n\t\t}));\n\t\tmergePromise(dummySpawned, errorPromise);\n\t\treturn dummySpawned;\n\t}\n\n\tconst spawnedPromise = getSpawnedPromise(spawned);\n\tconst timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);\n\tconst processDone = setExitHandler(spawned, parsed.options, timedPromise);\n\n\tconst context = {isCanceled: false};\n\n\tspawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));\n\tspawned.cancel = spawnedCancel.bind(null, spawned, context);\n\n\tconst handlePromise = async () => {\n\t\tconst [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);\n\t\tconst stdout = handleOutput(parsed.options, stdoutResult);\n\t\tconst stderr = handleOutput(parsed.options, stderrResult);\n\t\tconst all = handleOutput(parsed.options, allResult);\n\n\t\tif (error || exitCode !== 0 || signal !== null) {\n\t\t\tconst returnedError = makeError({\n\t\t\t\terror,\n\t\t\t\texitCode,\n\t\t\t\tsignal,\n\t\t\t\tstdout,\n\t\t\t\tstderr,\n\t\t\t\tall,\n\t\t\t\tcommand,\n\t\t\t\tescapedCommand,\n\t\t\t\tparsed,\n\t\t\t\ttimedOut,\n\t\t\t\tisCanceled: context.isCanceled || (parsed.options.signal ? parsed.options.signal.aborted : false),\n\t\t\t\tkilled: spawned.killed,\n\t\t\t});\n\n\t\t\tif (!parsed.options.reject) {\n\t\t\t\treturn returnedError;\n\t\t\t}\n\n\t\t\tthrow returnedError;\n\t\t}\n\n\t\treturn {\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\texitCode: 0,\n\t\t\tstdout,\n\t\t\tstderr,\n\t\t\tall,\n\t\t\tfailed: false,\n\t\t\ttimedOut: false,\n\t\t\tisCanceled: false,\n\t\t\tkilled: false,\n\t\t};\n\t};\n\n\tconst handlePromiseOnce = onetime(handlePromise);\n\n\thandleInput(spawned, parsed.options);\n\n\tspawned.all = makeAllStream(spawned, parsed.options);\n\n\taddPipeMethods(spawned);\n\tmergePromise(spawned, handlePromiseOnce);\n\treturn spawned;\n}\n\nexport function execaSync(file, args, options) {\n\tconst parsed = handleArguments(file, args, options);\n\tconst command = joinCommand(file, args);\n\tconst escapedCommand = getEscapedCommand(file, args);\n\tlogCommand(escapedCommand, parsed.options);\n\n\tconst input = handleInputSync(parsed.options);\n\n\tlet result;\n\ttry {\n\t\tresult = childProcess.spawnSync(parsed.file, parsed.args, {...parsed.options, input});\n\t} catch (error) {\n\t\tthrow makeError({\n\t\t\terror,\n\t\t\tstdout: '',\n\t\t\tstderr: '',\n\t\t\tall: '',\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\tparsed,\n\t\t\ttimedOut: false,\n\t\t\tisCanceled: false,\n\t\t\tkilled: false,\n\t\t});\n\t}\n\n\tconst stdout = handleOutput(parsed.options, result.stdout, result.error);\n\tconst stderr = handleOutput(parsed.options, result.stderr, result.error);\n\n\tif (result.error || result.status !== 0 || result.signal !== null) {\n\t\tconst error = makeError({\n\t\t\tstdout,\n\t\t\tstderr,\n\t\t\terror: result.error,\n\t\t\tsignal: result.signal,\n\t\t\texitCode: result.status,\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\tparsed,\n\t\t\ttimedOut: result.error && result.error.code === 'ETIMEDOUT',\n\t\t\tisCanceled: false,\n\t\t\tkilled: result.signal !== null,\n\t\t});\n\n\t\tif (!parsed.options.reject) {\n\t\t\treturn error;\n\t\t}\n\n\t\tthrow error;\n\t}\n\n\treturn {\n\t\tcommand,\n\t\tescapedCommand,\n\t\texitCode: 0,\n\t\tstdout,\n\t\tstderr,\n\t\tfailed: false,\n\t\ttimedOut: false,\n\t\tisCanceled: false,\n\t\tkilled: false,\n\t};\n}\n\nconst normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined\n\t? {stdin: 'inherit'}\n\t: {};\n\nconst normalizeScriptOptions = (options = {}) => ({\n\tpreferLocal: true,\n\t...normalizeScriptStdin(options),\n\t...options,\n});\n\nfunction create$(options) {\n\tfunction $(templatesOrOptions, ...expressions) {\n\t\tif (!Array.isArray(templatesOrOptions)) {\n\t\t\treturn create$({...options, ...templatesOrOptions});\n\t\t}\n\n\t\tconst [file, ...args] = parseTemplates(templatesOrOptions, expressions);\n\t\treturn execa(file, args, normalizeScriptOptions(options));\n\t}\n\n\t$.sync = (templates, ...expressions) => {\n\t\tif (!Array.isArray(templates)) {\n\t\t\tthrow new TypeError('Please use $(options).sync`command` instead of $.sync(options)`command`.');\n\t\t}\n\n\t\tconst [file, ...args] = parseTemplates(templates, expressions);\n\t\treturn execaSync(file, args, normalizeScriptOptions(options));\n\t};\n\n\treturn $;\n}\n\nexport const $ = create$();\n\nexport function execaCommand(command, options) {\n\tconst [file, ...args] = parseCommand(command);\n\treturn execa(file, args, options);\n}\n\nexport function execaCommandSync(command, options) {\n\tconst [file, ...args] = parseCommand(command);\n\treturn execaSync(file, args, options);\n}\n\nexport function execaNode(scriptPath, args, options = {}) {\n\tif (args && !Array.isArray(args) && typeof args === 'object') {\n\t\toptions = args;\n\t\targs = [];\n\t}\n\n\tconst stdio = normalizeStdioNode(options);\n\tconst defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect'));\n\n\tconst {\n\t\tnodePath = process.execPath,\n\t\tnodeOptions = defaultExecArgv,\n\t} = options;\n\n\treturn execa(\n\t\tnodePath,\n\t\t[\n\t\t\t...nodeOptions,\n\t\t\tscriptPath,\n\t\t\t...(Array.isArray(args) ? args : []),\n\t\t],\n\t\t{\n\t\t\t...options,\n\t\t\tstdin: undefined,\n\t\t\tstdout: undefined,\n\t\t\tstderr: undefined,\n\t\t\tstdio,\n\t\t\tshell: false,\n\t\t},\n\t);\n}\n","export default function stripFinalNewline(input) {\n\tconst LF = typeof input === 'string' ? '\\n' : '\\n'.charCodeAt();\n\tconst CR = typeof input === 'string' ? '\\r' : '\\r'.charCodeAt();\n\n\tif (input[input.length - 1] === LF) {\n\t\tinput = input.slice(0, -1);\n\t}\n\n\tif (input[input.length - 1] === CR) {\n\t\tinput = input.slice(0, -1);\n\t}\n\n\treturn input;\n}\n","import { intro, outro, isCancel, cancel, text, confirm, spinner } from '@clack/prompts';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { execa } from 'execa';\n\nimport { MINIMUM_VERSIONS, semverComply } from '../../utils/semver';\nimport { readTSConfigFile } from '@gql.tada/internal';\n\nconst s = spinner();\n\nconst TADA_VERSION = '^1.4.3';\nconst LSP_VERSION = '^1.8.0';\n\nexport async function run(target: string) {\n intro(`GQL.Tada`);\n\n const schemaLocation = await question(\n 'Where can we get your schema? Point us at an introspection JSON-file, a GraphQL schema file or an endpoint',\n async (value: string) => {\n try {\n const url = new URL(value);\n s.start('Validating the URL.');\n try {\n const response = await fetch(url.toString());\n if (!response.ok) {\n s.stop('Validated the URL.');\n const urlFailureIsOkay = await confirm({\n message: `Got ${\n response.status\n } from ${url.toString()}, continue anyway? You can add headers later.`,\n });\n return !!urlFailureIsOkay;\n }\n } catch (e) {\n s.stop('Validated the URL.');\n const urlFailureIsOkay = await confirm({\n message: `Got ${\n (e as Error).message\n } from ${url.toString()}, continue anyway? You can add headers later.`,\n });\n return !!urlFailureIsOkay;\n }\n s.stop('Validated the URL.');\n return true;\n } catch (e) {}\n const isFile = value.endsWith('.json') || value.endsWith('.graphql');\n if (!isFile) {\n return false;\n }\n\n const filePath = path.resolve(target, value);\n const fileExists = !!(await fs.readFile(filePath));\n if (!fileExists) {\n // eslint-disable-next-line no-console\n console.log(`\\nCould not find \"${filePath}\"`);\n }\n\n return fileExists;\n },\n true\n );\n\n let tadaLocation = await question(\n 'What directory do you want us to write the tadaOutputFile to?',\n async (value: string) => {\n const dir = path.resolve(target, value);\n const directoryExists = !!(await fs.stat(dir));\n if (!directoryExists) {\n // eslint-disable-next-line no-console\n console.log(`\\nCould not find \"${dir}\"`);\n }\n\n return directoryExists;\n },\n true\n );\n\n if (isCancel(tadaLocation)) {\n cancel('Operation cancelled.');\n process.exit(0);\n }\n\n tadaLocation = path.resolve(tadaLocation, 'graphql-env.d.ts');\n\n const shouldInstallDependencies = await confirm({\n message: 'Do you want us to install the dependencies?',\n });\n\n if (isCancel(shouldInstallDependencies)) {\n cancel('Operation cancelled.');\n process.exit(0);\n }\n\n let supportsEmbeddedLsp = false;\n let packageJson: {\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n };\n\n try {\n const packageJsonPath = path.resolve(target, 'package.json');\n const packageJsonContents = await fs.readFile(packageJsonPath, 'utf-8');\n packageJson = JSON.parse(packageJsonContents);\n const deps = Object.entries({\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n });\n\n const typeScriptVersion = deps.find((x) => x[0] === 'typescript');\n if (typeScriptVersion && typeof typeScriptVersion[1] === 'string') {\n supportsEmbeddedLsp = semverComply(\n typeScriptVersion[1],\n MINIMUM_VERSIONS.typescript_embed_lsp\n );\n }\n } catch (e) {}\n\n if (shouldInstallDependencies) {\n s.start('Installing packages.');\n await installPackages(getPkgManager(), target, !supportsEmbeddedLsp);\n s.stop('Installed packages.');\n } else {\n s.start('Writing to package.json.');\n try {\n const packageJsonPath = path.resolve(target, 'package.json');\n const packageJsonContents = await fs.readFile(packageJsonPath, 'utf-8');\n packageJson = JSON.parse(packageJsonContents);\n\n if (!packageJson.dependencies) packageJson.dependencies = {};\n if (!packageJson.dependencies['gql.tada']) {\n packageJson.dependencies['gql.tada'] = TADA_VERSION;\n }\n\n if (!supportsEmbeddedLsp) {\n if (!packageJson.devDependencies) packageJson.devDependencies = {};\n if (!packageJson.devDependencies['@0no-co/graphqlsp']) {\n packageJson.devDependencies['@0no-co/graphqlsp'] = LSP_VERSION;\n }\n }\n\n await fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2));\n s.stop('Written to package.json.');\n } catch (e) {\n s.stop(\n 'Failed to write to package.json, you can try adding \"gql.tada\" and \"@0no-co/graphqlsp\" yourself.'\n );\n }\n }\n\n s.start('Writing to tsconfig.json.');\n try {\n const tsConfigPath = path.resolve(target, 'tsconfig.json');\n const tsConfig = await readTSConfigFile(tsConfigPath);\n // TODO: do we need to ensure that include contains the tadaOutputLocation?\n const isFile = schemaLocation.endsWith('.json') || schemaLocation.endsWith('.graphql');\n tsConfig.compilerOptions = {\n ...tsConfig.compilerOptions,\n plugins: [\n {\n name: supportsEmbeddedLsp ? 'gql.tada/ts-plugin' : '@0no-co/graphqlsp',\n schema: isFile ? path.relative(target, schemaLocation) : schemaLocation,\n tadaOutputLocation: path.relative(target, tadaLocation),\n } as any,\n ],\n };\n await fs.writeFile(tsConfigPath, JSON.stringify(tsConfig, null, 2));\n } catch (e) {}\n s.stop('Written to tsconfig.json.');\n\n outro(`Off to the races!`);\n}\n\ntype PackageManager = 'yarn' | 'pnpm' | 'npm';\nasync function installPackages(\n packageManager: PackageManager,\n target: string,\n shouldInstallGraphQLSP\n) {\n if (shouldInstallGraphQLSP) {\n await execa(\n packageManager,\n [\n // `yarn add` will fail if nothing is provided\n packageManager === 'yarn' ? 'add' : 'install',\n '-D',\n '@0no-co/graphqlsp',\n ],\n {\n stdio: 'ignore',\n cwd: target,\n }\n );\n }\n\n await execa(packageManager, [packageManager === 'yarn' ? 'add' : 'install', 'gql.tada'], {\n stdio: 'ignore',\n cwd: target,\n });\n}\n\nfunction getPkgManager(): PackageManager {\n const userAgent = process.env.npm_config_user_agent || '';\n if (userAgent.startsWith('yarn')) return 'yarn';\n if (userAgent.startsWith('pnpm')) return 'pnpm';\n return 'npm';\n}\n\nconst question = async (\n msg: string,\n validate: (value: string) => Promise<boolean>,\n repeat?: boolean\n): Promise<string> => {\n let value: string | symbol = '';\n if (repeat) {\n // while there is no value or the value is not a cancel symbol and the value is not a string or the value is a string but the validation fails\n let done = false;\n while (!done) {\n value = await text({\n message: msg,\n });\n if (isCancel(value)) {\n done = true;\n cancel('Operation cancelled.');\n process.exit(0);\n } else if (await validate(value)) {\n done = true;\n }\n }\n } else {\n value = await text({\n message: msg,\n });\n if (isCancel(value)) {\n cancel('Operation cancelled.');\n process.exit(0);\n }\n }\n\n return value as string;\n};\n","import * as path from 'node:path';\nimport { Command, Option } from 'clipanion';\nimport { run } from './runner';\n\nexport class InitCommand extends Command {\n static paths = [['init']];\n\n input = Option.String({ name: 'dir' });\n\n async execute() {\n const target = path.resolve(process.cwd(), this.input);\n await run(target);\n }\n}\n","import { Cli } from 'clipanion';\nimport * as api from './api';\n\nimport { CheckCommand } from './commands/check/index';\nimport { DoctorCommand } from './commands/doctor/index';\nimport { GenerateOutputCommand } from './commands/generate-output/index';\nimport { GeneratePersisted } from './commands/generate-persisted/index';\nimport { GenerateSchema } from './commands/generate-schema/index';\nimport { InitCommand } from './commands/init/index';\nimport { TurboCommand } from './commands/turbo/index';\n\nasync function _main() {\n const cli = new Cli({\n binaryVersion: process.env.npm_package_version || '0.0.0',\n binaryLabel: 'gql.tada CLI',\n binaryName: 'gql.tada',\n });\n\n cli.register(CheckCommand);\n cli.register(DoctorCommand);\n cli.register(GenerateOutputCommand);\n cli.register(GeneratePersisted);\n cli.register(GenerateSchema);\n cli.register(InitCommand);\n cli.register(TurboCommand);\n\n await cli.runExit(process.argv.slice(2));\n}\n\ntype MainFn = typeof _main & typeof api;\nconst main = Object.assign(_main, api) as MainFn;\n\nexport * from './api';\nexport default main;\n"],"names":["SpecialToken","NodeType","HELP_COMMAND_INDEX","HELP_REGEX","OPTION_REGEX","BATCH_REGEX","BINDING_REGEX","IS_DEBUG","process","env","DEBUG_CLI","UsageError","Error","constructor","message","super","this","clipanion","type","name","UnknownSyntaxError","input","candidates","length","every","candidate","reason","map","usage","join","whileRunning","index","padStart","AmbiguousSyntaxError","usages","filter","token","EndOfInput","EndOfPartialInput","json","JSON","stringify","match","richLine","Array","fill","t","richFormat","header","str","MAX_LINE_LENGTH","slice","bold","error","code","textFormat","formatMarkdownish","text","format","paragraphs","dedent","lines","split","nonEmptyLines","line","indent","reduce","minLength","Math","min","trimStart","Number","MAX_VALUE","trimRight","replace","$0","$1","paragraph","bulletMatch","RegExp","repeat","$2","isOptionSymbol","Symbol","makeCommandOption","spec","rerouteArguments","a","b","isArray","undefined","cleanValidationError","mergeName","path","toLowerCase","formatError","errors","applyValidator","value","validator","coercions","coercion","v","orig","bind","op","Command","help","Usage","catch","validateAndExecute","cascade","schema","isDict","isUnknown","applyCascade","Promise","resolve","then","exitCode","execute","isOption","Default","debug","console","log","basicHelpState","candidateUsage","requiredOptions","errorMessage","ignoreOptions","positionals","options","remainder","selectedIndex","tokens","makeStateMachine","stateMachine","nodes","CustomNode","push","dynamics","shortcuts","statics","injectNode","machine","node","runMachineInternal","partial","branches","InitialNode","state","debugMachine","prefix","StartOfInput","segment","isEOI","segmentIndex","nextBranches","nodeDef","ErrorNode","assert","hasExactMatch","Object","prototype","hasOwnProperty","call","transitions","to","reducer","reducers","hasMatches","keys","startsWith","test","tests","trimSmallerBranches","branch","runMachine","endToken","selectBestState","states","terminalStates","requiredOptionsSetStates","names","some","find","opt","maxPathSize","bestPathBranches","getPositionalCount","extra","statesWithPositionalCount","positionalCount","maxPositionalCount","fixedStates","aggregateHelpStates","notHelps","helps","findCommonPrefix","concat","firstPath","secondPath","rest","from","i","isTerminalNode","SuccessNode","cloneTransition","offset","cloneNode","output","transition","entries","registerDynamic","registerShortcut","registerStatic","store","callback","args","always","isOptionLike","isNotOptionLike","isBatchOption","has","isBoundOption","optionParsing","nameSet","includes","allowBinding","isNegatedOption","isHelp","isUnsupportedOption","isInvalidOption","setCandidateState","candidateState","setSelectedIndex","pushBatch","get","option","pushBound","pushPath","pushPositional","pushExtra","pushExtraNoLimits","NoLimits","pushTrue","pushFalse","pushUndefined","pushStringValue","_a","lastOption","setStringValue","inhibateOptions","useHelp","command","String","setError","setOptionArityError","CommandBuilder","cliIndex","cliOpts","allOptionNames","Map","arity","leading","trailing","proxy","paths","addPath","setArity","assign","addPositional","required","addRest","addProxy","addOption","description","hidden","isInteger","preferredName","longestName","set","setContext","context","detailed","inlineOptions","segments","binaryName","detailedOptionList","definition","compile","firstNode","positionalArgument","lastPathNode","optionPathNode","registerOptions","nextPathNode","helpNode","lastLeadingNode","nextLeadingNode","lastExtraNode","extraShortcutNode","extraNode","nextExtraNode","lastTrailingNode","nextTrailingNode","lastNode","nextNode","CliBuilder","builders","opts","build","cbs","commands","getBuilderByIndex","n","cb","builder","machines","contexts","makeAnyOfMachine","inputs","heads","head","simplifyMachine","visited","Set","add","values","shift","toDef","_loop","_loop2","_transition","otherTest","HelpCommand","stdout","write","cli","commandClass","errorCommandSymbol","Cli","binaryLabel","binaryNameOpt","binaryVersion","enableCapture","enableColors","registrations","commandClasses","resolvedCommandClasses","register","specs","key","contextArg","userContext","defaultContext","record","transformer","run","_b","colored","colorDepth","definitions","subContext","activate","getCaptureActivator","noopCaptureActivator","runExit","getUsageByRegistration","category","details","examples","label","data","isDocumented","isDefault","result","commandsByCategories","categoryCommands","getUsageByIndex","categoryNames","sort","localeCompare","caseFirst","hasLabel","hasVersion","categoryName","trim","doc","toUpperCase","maxDefinitionLength","max","padEnd","example","meta","stack","klass","stdin","stderr","fn","Boolean","descriptor","initialValueBase","optsBase","initialValue","optNames","builer","currentValue","StringOption","tolerateBoolean","usedName","StringPositional","positional","splice","TadaErrorCode","TadaError","isTadaError","parseInt","hasColor","_setColor","color","CSI","EraseLine","Mode","PrivateMode","Style","escapeCSI","cmd","out","SetPrivateMode","SetMode","UnsetPrivateMode","UnsetMode","ansiRegex","stripAnsi","CLIError","exit","toString","argIndex","arg","compose","outputs","reset","Reset","NoInvert","outputs$","pipe","fromAsyncIterable","async","convertError","concatMap","fromValue","x","share","output$","merge","never","takeUntil","takeLast","endsWith","scan","prev","clear","charCodeAt","PrevLine","DeleteLines","Backward","ToColumn","Chars","HeavyBox","Icons","dotSpinner","circleSpinner","isGithubCI","GITHUB_ACTIONS","toCommandValue","escapeData","escapeProperty","githubAnnotation","kind","properties","propsOut","initTTY","params","isTTY","TERM","CI","disableTTY","pipeTo","hasColorArg","argv","hasColorEnv","NO_COLOR","inputSource","fromReadStream","stream","make","observer","onKeypress","event","ctrl","cleanup","next","setRawMode","complete","removeListener","unref","emitKeypressEvents","setEncoding","resume","addListener","onStart","_start","ShowCursor","onEnd","_end","ResetPrivateMode","cancelSource","isInteractive","start","onPush","toPromise","mode","modes","normalModes","privateModes","Insert","AutomaticNewline","modeOff","Newline","Underline","NoUnderline","Bold","Normal","hint","BrightBlack","BottomLeft","BrightBlue","Info","Blue","Red","Invert","Warning","externalError","title","experimentMessage","Yellow","directoryExists","stat","fs","file","isDirectory","isSymbolicLink","realpath","writeOutput","target","contents","reject","targetDirectory","dirname","mkdir","recursive","isFile","writeFile","tempTarget","rename","unlink","now","Date","utimes","_error","touchFile","summary","showHint","BrightGreen","Tick","tty","configResult","pluginConfig","loadConfig","tsconfig","parseConfig","rootPath","logger","schemaRef","loadRef","load","configPath","projectPath","current","destination","cwd","tadaOutputLocation","outputIntrospectionFile","minifyIntrospection","introspection","fileType","forceTSFormat","shouldPreprocess","disablePreprocessing","schemaName","multi","GenerateOutputCommand","static","Option","generateOutput","CWD","INDENT","warningFile","filePath","relativePath","relative","documentSummary","documentCount","warningSummary","warningCount","Cross","infoSummary","BrightYellow","warningGithub","col","runningPersisted","ofFiles","progress","interval","Magenta","Foreground","Ellipsis","runPersisted","import","generator","disableNormalization","documents","warnings","totalFileCount","fileCount","signal","buffer","warning","Tab","tadaPersistedLocation","failOnWarn","item","hashKey","document","schemaConfig","schemas","GeneratePersisted","generatePersisted","simpleKeyRegExp","getPrintable","computeKey","_c","p","pushError","makeCoercionFn","previous","isLiteral","expected","makeValidator","isString","delimiter","originalValue","valid","T","isTuple","lengthValidator","hasExactLength","isRecord","keySpec","isArrayValidator","fromEntries","sub","isOneOf","exclusive","matches","errorBuffer","subErrors","subCoercions","makeTrait","matchesRegExp","regExp","followups","resolvedFollowups","subCoercion","reverts","revert","KeyRelationship","origin","headers","url","loader","extname","printSchema","isHeaderEntries","parseHeaders","entry","indexOf","trimEnd","GenerateSchema","generateSchema","runningTurbo","PREAMBLE_IGNORE","runTurbo","destinations","tadaTurboLocation","hintMessage","turboOutputPath","graphqlSources","sources","cache","argumentKey","documentType","createCacheContents","turboDestination","imports","isFilePath","addedImports","source","importInfo","turboPath","sourceDir","absolutePath","specifier","importClause","TurboCommand","generateTurbo","diagnosticFile","diagnosticMessage","severity","BrightRed","diagnosticMessageGithub","endLine","endColumn","runningDiagnostics","isMinSeverity","minSeverity","runDiagnostics","warn","info","messages","problemsSummary","CheckCommand","Intl","Collator","numeric","compare","MINIMUM_VERSIONS","semverComply","version","semiver","bool","spanToFilePosition","span","fileName","lineAndChar","getLineAndCharacterOfPosition","character","notImplemented","methodName","defaultCompilerOptions","ts","getDefaultCompilerOptions","jsx","JsxEmit","React","strict","esModuleInterop","module","ModuleKind","ESNext","suppressOutputPathCheck","skipLibCheck","skipDefaultLibCheck","moduleResolution","ModuleResolutionKind","NodeJs","createVirtualCompilerHost","sys","compilerOptions","sourceFiles","compilerHost","getCanonicalFileName","getDefaultLibFileName","getDirectories","getNewLine","newLine","getSourceFile","sourceFile","save","createSourceFile","readFile","useCaseSensitiveFileNames","updateFile","alreadyExists","createVirtualLanguageServiceHost","rootFiles","customTransformers","fileNames","fileVersions","projectVersion","languageServiceHost","getProjectVersion","getCompilationSettings","getCustomTransformers","getScriptFileNames","getScriptSnapshot","ScriptSnapshot","fromString","getScriptVersion","defineProperty","binarySearch_1","binarySearch","offsets","low","high","mid","floor","midValue","track_1","getStack","track","resetOffsetStack","offsetStack","setTracking","tracking","stackOffset","stacks","Proxy","prop","receiver","pop","unshift","reverse","Reflect","items","last","first","deleteCount","_stackStart","operateIndex","stackStart","originalLength","_deleteCount","compareFn","lastIndexOf","types","__createBinding","create","o","m","k","k2","desc","getOwnPropertyDescriptor","__esModule","writable","configurable","enumerable","__exportStar","exports","replaceRange","replaceSourceRange","getLength","require$$0","require$$1","require$$2","s","pattern","replacers","startOffset","endOffset","replacer","replaceAll","allMatch","matchAll","lengthDiff","newLength","newSegments","segmentStart","segmentEnd","inserts","trimSegmentEnd","newSegment","trimSegmentStart","combineStrings","toOffsets","startIndex","endIndex","endSegment","startSegmentStart","endSegmentStart","endSegmentEnd","searchValue","translateOffset_1","translateOffset","fromOffsets","lengths","fromOffset","sourceMap","SourceMap","mappings","getSourceOffset","generatedOffset","mapped","findMatching","getGeneratedOffset","sourceOffset","getSourceOffsets","getGeneratedOffsets","fromRange","toRange","memo","getMemoBasedOnRange","end","skip","mapping","sourceCodeOffsetsMemo","createMemo","generatedCodeOffsetsMemo","offsetsSet","buildMappings_1","buildMappings","chunks","sourceOffsets","generatedOffsets","buildStacks_1","buildStacks","range","require$$3","require$$4","SourceMappedFile","sourceFileId","generatedFileId","getSourceSpan","sourceStart","sourceEnd","maybeBind","that","buildLanguageService","virtualMap","languageService","createLanguageService","getProgram","mapFileFn","fileFn","fileId","mappedFile","mapFileTextSpanFn","textSpanFn","mapFileTextRangeFn","pos","mapFilePositionFn","positionFn","position","mapFileStartEndFn","program","serviceProgram","projectRoot","isSourceFileFromExternalLibrary","getModeForResolutionAtIndex","getSourceFiles","mapSourceFileFn","getSyntacticDiagnostics","getSemanticDiagnostics","getDeclarationDiagnostics","isSourceFileDefaultLibrary","getModeForUsageLocation","buildProgram","getReferencesAtPosition","findReferences","getDefinitionAtPosition","getDefinitionAndBoundSpan","getTypeDefinitionAtPosition","getImplementationAtPosition","getCompletionsAtPosition","getCompletionEntryDetails","getCompletionEntrySymbol","getQuickInfoAtPosition","getBreakpointStatementAtPosition","getSignatureHelpItems","getRenameInfo","getSmartSelectionRange","getDocumentHighlights","prepareCallHierarchy","provideCallHierarchyIncomingCalls","provideCallHierarchyOutgoingCalls","getBraceMatchingAtPosition","getIndentationAtPosition","getFormattingEditsAfterKeystroke","getDocCommentTemplateAtPosition","isValidBraceCompletionAtPosition","getJsxClosingTagAtPosition","getLinkedEditingRangeAtPosition","getSpanOfEnclosingComment","getSyntacticClassifications","getSemanticClassifications","getEncodedSyntacticClassifications","getEncodedSemanticClassifications","provideInlayHints","getNameOrDottedNameSpan","getFormattingEditsForRange","getCodeFixesAtPosition","getFileReferences","getNavigationBarItems","getNavigationTree","getOutliningSpans","getTodoComments","getFormattingEditsForDocument","getEditsForRefactor","getEmitOutput","getSuggestionDiagnostics","getSupportedCodeFixes","toggleLineComment","toggleMultilineComment","commentSelection","uncommentSelection","buildPluginInfo","config","getLanguageService","system","rootNames","project","getProjectName","projectService","serverHost","setImmediate","clearImmediate","_svelte","_vue","transformExtensions","transform","SVELTE_SUPPORT","transformSvelte","VUE_SUPPORT","check","checkVue","transformVue","UNKNOWN_EXTERNAL_FILE","programFactory","vfsMap","createFSBackedSystem","files","_projectRoot","tsLibDirectory","root","nodeSys","tsLib","require","directory","createDirectory","fileExists","tsLibName","getCurrentDirectory","getExecutingFilePath","readDirectory","libs","resolvePath","resolveDefaultLibsPath","resolveConfig","getDefaultLibFilePath","NodeNext","Node16","Bundler","host","factory","projectDirectories","directories","rootName","scriptKind","sourceText","getText","ScriptTarget","ScriptKind","TSX","createExternalFiles","exts","seen","External","addSourceFile","addMappedFile","delete","sourceMappedFile","addVirtualFiles","virtualFileId","virtualCode","snapshot","resolveModuleName","importSpecifier","fromPath","toPath","resolved","resolvedModule","targetFilePath","resolvedFileName","fromDir","toDir","absoluteImportPath","relativeImportPath","bumpStackTraceLimit","stackTraceLimit","init","typescript","service","serviceHost","pluginInfo","getLanguageServiceHost","createProgram","getSourceMappedFile","getSourcePosition","buildContainer","createRequire","request","parseResult","parseConfigFileTextToJson","messageText","parseJsonConfigFileContent","FileType","File","Directory","configFileRe","findGraphQLConfig","dir","readdir","configFile","workspaceRoot","targetPath","packageJsonPath","parse","workspaces","findWorkspaceRoot","graphql","loadPnpmWorkspaceCatalogs","startPath","currentPath","workspaceFile","access","findPnpmWorkspaceroot","content","currentSection","currentCatalog","trimmed","packages","catalog","catalogs","colonIndex","parseYaml","loadBunWorkspaceCatalogs","packageJsonFile","packageJson","findBunWorkspaceRoot","loadWorkspaceCatalogs","pnpmCatalogs","bunCatalogs","resolveCatalogVersion","catalogRef","catalogName","getVersionFromCatalog","packageName","getPackageVersion","devVersion","devDependencies","resolvedVersion","depVersion","dependencies","hasPackageSupport","__dirname","hasSvelteSupport","hasVueSupport","jsonParse","parseJsonText","convertToObject","isVSCodeInstalled","HOME","vscodeFolder","loadSuggestedExtensionsList","recommendations","loadExtensionsList","identifier","id","emptyLine","Vertical","completedTask","isLast","VerticalRight","Green","TickSwoosh","failedTask","CrossSwoosh","warningTask","runningTask","delay","ms","setTimeout","Messages","TopLeft","TITLE","DESCRIPTION","CHECK_TS_VERSION","versions","typeScriptVersion","pkg","catalogVersion","CHECK_DEPENDENCIES","supportsEmbeddedLsp","gqlspVersion","gqlTadaVersion","CHECK_TSCONFIG","runExternalFilesChecks","externalFiles","CHECK_EXTERNAL_FILES","extensions","runVSCodeChecks","suggestedExtensions","vscode","CHECK_VSCODE","hasEndedTask","userExtensions","hasProblemExtension","graphqlConfig","basename","CHECK_SCHEMA","success","Space","DoctorCommand","cursor","y","move","ret","up","count","down","forward","backward","nextLine","prevLine","left","hide","show","restore","scroll","erase","screen","lineEnd","lineStart","src","beep","isColorSupported","dim","italic","underline","inverse","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","bgBlack","bgRed","bgGreen","bgYellow","bgBlue","bgMagenta","bgCyan","bgWhite","picocolors_browserModule","createColors","q","onlyFirst","u","_","h","platform","WT_SESSION","TERMINUS_SUBLIME","ConEmuTask","TERM_PROGRAM","TERMINAL_EMULATOR","r","H","I","S","K","d","E","e","te","V","validate","placeholder","defaultValue","render","valueWithCursor","prompt","se","active","inactive","N","ue","core","global","TESTING_WINDOWS","windows","isexe","sync","checkStat","statSync","checkPathExt","pathext","pathExt","PATHEXT","substr","er","checkMode","mod","uid","gid","myUid","getuid","myGid","getgid","g","isexe_1","ignoreErrors","TypeError","is","isWindows","OSTYPE","COLON","getNotFoundError","getPathInfo","colon","pathEnv","PATH","pathExtExe","which","found","step","all","ppRaw","pathPart","pCmd","subStep","ii","ext","res","which_1","whichSync","j","cur","ex","nothrow","pathKey","environment","pathKeyModule","default","getPathKey","resolveCommandAttempt","parsed","withoutPathExt","hasCustomCwd","shouldSwitchCwd","chdir","disabled","err","resolveCommand_1","resolveCommand","metaCharsRegExp","_escape","escapeCommand","argument","escapeArgument","doubleEscapeMetaChars","shebangRegex","shebangCommand","string","binary","escape","readShebang","Buffer","alloc","fd","openSync","readSync","closeSync","isWin","isExecutableRegExp","isCmdShimRegExp","parseNonShell","commandFile","detectShebang","shebang","needsShell","forceShell","needsDoubleEscapeMetaChars","normalize","shellCommand","comspec","windowsVerbatimArguments","notFoundError","original","syscall","errno","spawnargs","verifyENOENT","status","enoent","hookChildProcess","cp","originalEmit","emit","arg1","apply","arguments","verifyENOENTSync","shell","spawn","spawned","crossSpawnModule","spawnSync","_parse","_enoent","applyPreferLocal","cwdPath","applyExecPath","execPath","execPathString","URL","fileURLToPath","npmRunPathEnv","pathName","npmRunPath","pathOption","preferLocal","addExecPath","cwdString","copyProperty","property","ignoreNonConfigurable","toDescriptor","fromDescriptor","canCopyProperty","wrappedToString","withName","fromBody","toStringDescriptor","Function","toStringName","mimicFunction","ownKeys","changePrototype","fromPrototype","getPrototypeOf","setPrototypeOf","changeToString","newToString","calledFunctions","WeakMap","onetime","function_","returnValue","callCount","functionName","displayName","arguments_","throw","getRealtimeSignal","number","SIGRTMIN","action","standard","SIGRTMAX","SIGNALS","forced","getSignals","realtimeSignals","normalizeSignal","defaultNumber","signals","constantSignal","constants","supported","getSignalByName","signalsByName","getSignalsByName","getSignalByNumber","findSignalByNumber","signalA","getSignalsByNumber","signalsA","makeError","escapedCommand","timedOut","isCanceled","killed","timeout","signalDescription","getErrorPrefix","errorCode","execaMessage","isError","shortMessage","originalMessage","bufferedData","failed","aliases","normalizeStdio","stdio","alias","hasAlias","processOk","reallyExit","listeners","kill","pid","on","kExitEmitter","for","globalThis","ObjectDefineProperty","Emitter","emitted","afterExit","random","ev","list","SignalExitBase","onExit","handler","SignalExit","hupSig","emitter","originalProcessEmit","originalProcessReallyExit","sigListeners","loaded","_this","sig","__signal_exit_emitter__","unload","alwaysLast","processEmit","processReallyExit","forEach","listener","og","SignalExitFallback","spawnedKill","killResult","setKillTimeout","shouldForceKill","getForceKillAfterTimeout","forceKillAfterTimeout","isSigterm","os","SIGTERM","isFinite","spawnedCancel","setupTimeout","killSignal","spawnedPromise","timeoutId","timeoutPromise","timeoutKill","safeSpawnedPromise","finally","clearTimeout","race","validateTimeout","setExitHandler","detached","timedPromise","removeExitHandler","isStream","isWritableStream","_write","_writableState","pipeToTarget","streamName","createWriteStream","ChildProcess","isExecaChildProcess","addPipeMethods","pipeStdout","pipeStderr","pipeAll","getStreamContents","convertChunk","getSize","truncateChunk","addChunk","getFinalChunk","finalize","maxBuffer","POSITIVE_INFINITY","isAsyncIterable","chunk","convertedChunk","getChunkType","appendChunk","appendFinalChunk","chunkSize","addNewChunk","truncatedChunk","MaxBufferError","asyncIterator","typeOfChunk","isBuffer","prototypeName","objectToString","byteLength","byteOffset","throwObjectStream","getLengthProp","textEncoder","TextEncoder","useUint8Array","Uint8Array","useUint8ArrayWithOffset","resizeArrayBufferSlow","arrayBuffer","ArrayBuffer","getNewContentsLength","resizeArrayBuffer","maxByteLength","resize","SCALE_FACTOR","ceil","hasArrayBufferResize","arrayBufferMethods","initArrayBuffer","encode","dataView","typedArray","others","truncateArrayBufferChunk","addArrayBufferChunk","previousLength","newContents","noop","finalizeArrayBuffer","getStreamAsBuffer","arrayBufferToNodeBuffer","getStreamAsArrayBuffer","useTextDecoder","textDecoder","decode","stringMethods","initString","TextDecoder","truncateStringChunk","addStringChunk","getFinalStringChunk","finalChunk","getContentsProp","PassThrough","objectMode","setMaxListeners","isEmpty","remove","once","it","readable","getInput","inputFile","validateInputOptions","createReadStream","handleInput","makeAllStream","mixed","mergeStream","getBufferedData","streamPromise","destroy","getStreamPromise","encoding","getStreamAsString","getStream","applyEncoding","getSpawnedResult","processDone","stdoutPromise","stderrPromise","allPromise","nativePromisePrototype","descriptors","mergePromise","promise","getSpawnedPromise","normalizeArgs","NO_ESCAPE_REGEXP","joinCommand","getEscapedCommand","escapeArg","verboseDefault","debuglog","enabled","padField","field","padding","logCommand","verbose","date","getHours","getMinutes","getSeconds","getMilliseconds","getTimestamp","handleArguments","crossSpawn","stripFinalNewline","extendEnv","localDir","windowsHide","getEnv","envOption","handleOutput","LF","CR","execa","childProcess","dummySpawned","errorPromise","cancel","handlePromiseOnce","stdoutResult","stderrResult","allResult","returnedError","aborted","de","c","clearInterval","A","$","l","F","setInterval","O","P","stop","spinner","oe","intro","schemaLocation","question","response","fetch","ok","confirm","tadaLocation","isCancel","shouldInstallDependencies","packageJsonContents","installPackages","packageManager","shouldInstallGraphQLSP","getPkgManager","userAgent","npm_config_user_agent","tsConfigPath","tsConfig","readTSConfigFile","plugins","$e","outro","msg","done","InitCommand","main","_main","npm_package_version","api"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAIA;;CACJ,SAAWA;EACPA,EAA2B,eAAI;EAC/BA,EAAyB,aAAI;EAC7BA,EAAgC,oBAAI;AACvC,CAJD,CAIGA,OAAiBA,KAAe,CAAE;;AACrC,IAAIC;;CACJ,SAAWA;EACPA,EAASA,EAAsB,cAAI,KAAK;EACxCA,EAASA,EAAsB,cAAI,KAAK;EACxCA,EAASA,EAAoB,YAAI,KAAK;EACtCA,EAASA,EAAqB,aAAI,KAAK;AAC1C,CALD,CAKGA,OAAaA,KAAW,CAAE;;AAC7B,IAAMC,MAAsB;;AAC5B,IAAMC,KAAa;;AACnB,IAAMC,KAAe;;AACrB,IAAMC,KAAc;;AACpB,IAAMC,KAAgB;;AACtB,IAAMC,KAAqC,QAA1BC,QAAQC,IAAIC;;ACX7B,MAAMC,mBAAmBC;EACrBC,WAAAA,CAAYC;IACRC,MAAMD;IACNE,KAAKC,YAAY;MAAEC,MAAM;;IACzBF,KAAKG,OAAO;AAChB;;;AAEJ,MAAMC,2BAA2BR;EAC7BC,WAAAA,CAAYQ,GAAOC;IACfP;IACAC,KAAKK,QAAQA;IACbL,KAAKM,aAAaA;IAClBN,KAAKC,Y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Y,SAASuX;QAEPnY,EAAI6B,QAAQxW,QAAQme,KAAKxb,MAAM;AACvC,IAGkC+rD;;","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,25,29,36,40,41,42,43,44,45,46,47,48,49,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105]}Выполнить команду
Для локальной разработки. Не используйте в интернете!