@gql.tada/cli-utils 1.6.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index-chunk.js","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/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/utils/error.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.0/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.2.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","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 * as fs from 'node:fs/promises';\n\n/** Checks whether a file exists on disk */\nexport const 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 } else 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 { 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 process.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 { 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 process.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 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 process.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 } 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\n const generator = runTurbo({\n rootPath: configResult.rootPath,\n configPath: configResult.configPath,\n pluginConfig,\n });\n\n const documents: TurboDocument[] = [];\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 {\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 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.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(\n '\"tadaTurboLocation\"'\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 }\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);\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 contents = createCacheContents(cache);\n await writeOutput(path.resolve(projectPath, tadaTurboLocation), 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(cache: Record<string, string>): string {\n let output = '';\n for (const key in cache) {\n if (output) output += '\\n';\n output += ` ${key}:\\n ${cache[key]};`;\n }\n return (\n PREAMBLE_IGNORE +\n \"import type { TadaDocumentNode, $tada } from 'gql.tada';\\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 { 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 process.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 { 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 process.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","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","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, addRootName?: boolean): this;\n addMappedFile(file: SourceFileParams | ts.SourceFile, params: MappedFileParams): this;\n\n addVirtualFiles(files: readonly ts.SourceFile[]): Promise<this>;\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, addRootName) {\n const sourceFile =\n 'fileName' in input ? input : factory.createSourceFile(input, ts.ScriptKind.TSX);\n host.updateFile(sourceFile);\n if (addRootName) 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 {\n fileId: virtualFileId,\n sourceText: virtualCode.snapshot,\n },\n /*addRootName*/ true\n )\n .addMappedFile(sourceFile, {\n mappings: virtualCode.mappings,\n fileId: virtualFileId,\n });\n }\n }\n return factory;\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","import { 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 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 if (meta.devDependencies?.[pkg]) {\n return meta.devDependencies[pkg];\n } else if (meta.dependencies?.[pkg]) {\n return meta.dependencies[pkg];\n }\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 if (meta.devDependencies?.[pkg]) {\n return meta.devDependencies[pkg];\n } else if (meta.dependencies?.[pkg]) {\n return meta.dependencies[pkg];\n }\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 if (meta.devDependencies?.[pkg]) {\n return meta.devDependencies[pkg];\n } else if (meta.dependencies?.[pkg]) {\n return meta.dependencies[pkg];\n }\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\nexport const hasSvelteSupport = async (meta: PackageJson): Promise<boolean> => {\n const pkg = '@gql.tada/svelte-support';\n const isInstalled = !!meta.devDependencies?.[pkg] || !!meta.devDependencies?.[pkg];\n if (isInstalled) {\n return true;\n }\n try {\n // NOTE: Resolved from current folder, since it's a child dependency\n return !!createRequire(__dirname)(`${pkg}/package.json`)?.version;\n } catch (_error) {\n return false;\n }\n};\n\nexport const hasVueSupport = async (meta: PackageJson): Promise<boolean> => {\n const pkg = '@gql.tada/vue-support';\n const isInstalled = !!meta.devDependencies?.[pkg] || !!meta.devDependencies?.[pkg];\n if (isInstalled) {\n return true;\n }\n try {\n // NOTE: Resolved from current folder, since it's a child dependency\n return !!createRequire(__dirname)(`${pkg}/package.json`)?.version;\n } catch (_error) {\n return false;\n }\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 { 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 process.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[\\uDDA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\\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\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DF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFE\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFD\\u200D(?:\\uD83C[\\uDF3E\\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\\uDD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\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 url from 'node:url';\nimport pathKey from 'path-key';\n\nexport function npmRunPath(options = {}) {\n\tconst {\n\t\tcwd = process.cwd(),\n\t\tpath: path_ = process.env[pathKey()],\n\t\texecPath = process.execPath,\n\t} = options;\n\n\tlet previous;\n\tconst execPathString = execPath instanceof URL ? url.fileURLToPath(execPath) : execPath;\n\tconst cwdString = cwd instanceof URL ? url.fileURLToPath(cwd) : cwd;\n\tlet cwdPath = path.resolve(cwdString);\n\tconst result = [];\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\t// Ensure the running `node` binary is used.\n\tresult.push(path.resolve(cwdString, execPathString, '..'));\n\n\treturn [...result, path_].join(path.delimiter);\n}\n\nexport function npmRunPathEnv({env = process.env, ...options} = {}) {\n\tenv = {...env};\n\n\tconst path = pathKey({env});\n\toptions.path = env[path];\n\tenv[path] = 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","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","writeOutput","target","contents","reject","file","fs","stat","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","dirname","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","require","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","tadaTurboLocation","hintMessage","cache","argumentKey","documentType","createCacheContents","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","source","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","TadaErrorCode","TadaError","isTadaError","_svelte","_vue","transformExtensions","transform","import","SVELTE_SUPPORT","transformSvelte","VUE_SUPPORT","check","checkVue","transformVue","UNKNOWN_EXTERNAL_FILE","programFactory","vfsMap","createFSBackedSystem","files","_projectRoot","tsLibDirectory","root","nodeSys","tsLib","realpath","directory","createDirectory","directoryExists","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","addRootName","addMappedFile","delete","sourceMappedFile","addVirtualFiles","virtualFileId","virtualCode","snapshot","bumpStackTraceLimit","stackTraceLimit","init","typescript","service","serviceHost","pluginInfo","getLanguageServiceHost","createProgram","getSourceMappedFile","getSourcePosition","buildContainer","createRequire","request","parseResult","parseConfigFileTextToJson","messageText","parseJsonConfigFileContent","FileType","File","Directory","isDirectory","configFileRe","findGraphQLConfig","targetPath","dir","readdir","configFile","workspaceRoot","packageJsonPath","parse","workspaces","findWorkspaceRoot","graphql","hasSvelteSupport","pkg","devDependencies","__dirname","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","packageJson","versions","typeScriptVersion","dependencies","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","erase","screen","lineEnd","lineStart","src","scroll","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","isSymbolicLink","checkPathExt","pathext","pathExt","PATHEXT","substr","er","checkMode","mod","uid","gid","myUid","getuid","myGid","getgid","parseInt","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","resolved","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","npmRunPathEnv","npmRunPath","path_","execPath","execPathString","URL","fileURLToPath","cwdString","cwdPath","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","sources","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","preferLocal","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,MAAiBA,IAAe,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,MAAaA,IAAW,CAAE;;AAC7B,IAAMC,KAAsB;;AAC5B,IAAMC,IAAa;;AACnB,IAAMC,IAAe;;AACrB,IAAMC,IAAc;;AACpB,IAAMC,IAAgB;;AACtB,IAAMC,IAAqC,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,YAAY;MAAEC,MAAM;;IACzBF,KAAKG,OAAO;IACZ,IAA+B,MAA3BH,KAAKM,WAAWC;MAChBP,KAAKF,UAAU;WAEd,IAAIE,KAAKM,WAAWE,OAAMC,KAAkC,SAArBA,EAAUC,UAAmBD,EAAUC,WAAWJ,EAAW,GAAGI,UAAS;MACjH,MAAOA,QAAEA,MAAYV,KAAKM;MAC1BN,KAAKF,UAAU,GAAGY,QAAaV,KAAKM,WAAWK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AM8kD,oBAAoBtkD;EAC/Bue,aAAe,EAAC,EAAC;EAEjB5jB,MAAQ6jB,SAAc;IAAE/jB,MAAM;;EAE9B,aAAMqG;IACJ,IAAMya,IAASpc,EAAKwB,QAAQ7G,QAAQ6jB,OAAOrjB,KAAKK;UAC1CkV,IAAI0L;AACZ;;;ACkBIgpC,IAAAA,KAAO9gD,OAAO4G,QAnBpB8K,eAAeqvC;EACb,IAAM/1C,IAAM,IAAIG,IAAI;IAClBG,eAAejV,QAAQC,IAAI0qD,uBAAuB;IAClD51C,aAAa;IACbvD,YAAY;;EAGdmD,EAAIY,SAAS8W;EACb1X,EAAIY,SAAS4yB;EACbxzB,EAAIY,SAASiP;EACb7P,EAAIY,SAAS8R;EACb1S,EAAIY,SAASkV;EACb9V,EAAIY,SAASi1C;EACb71C,EAAIY,SAAS6V;QAEPzW,EAAI6B,QAAQxW,QAAQ+d,KAAKpb,MAAM;AACvC,IAGkCioD;;;;;;;;;;;;","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,24,28,35,39,40,41,42,43,44,45,46,47,48,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]}
1
+ {"version":3,"file":"index-chunk.js","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 * as fs from 'node:fs/promises';\n\n/** Checks whether a file exists on disk */\nexport const 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 } else 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 } 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\n const generator = runTurbo({\n rootPath: configResult.rootPath,\n configPath: configResult.configPath,\n pluginConfig,\n });\n\n const documents: TurboDocument[] = [];\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 {\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 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.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(\n '\"tadaTurboLocation\"'\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 }\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);\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 contents = createCacheContents(cache);\n await writeOutput(path.resolve(projectPath, tadaTurboLocation), 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(cache: Record<string, string>): string {\n let output = '';\n for (const key in cache) {\n if (output) output += '\\n';\n output += ` ${key}:\\n ${cache[key]};`;\n }\n return (\n PREAMBLE_IGNORE +\n \"import type { TadaDocumentNode, $tada } from 'gql.tada';\\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, addRootName?: boolean): this;\n addMappedFile(file: SourceFileParams | ts.SourceFile, params: MappedFileParams): this;\n\n addVirtualFiles(files: readonly ts.SourceFile[]): Promise<this>;\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, addRootName) {\n const sourceFile =\n 'fileName' in input ? input : factory.createSourceFile(input, ts.ScriptKind.TSX);\n host.updateFile(sourceFile);\n if (addRootName) 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 {\n fileId: virtualFileId,\n sourceText: virtualCode.snapshot,\n },\n /*addRootName*/ true\n )\n .addMappedFile(sourceFile, {\n mappings: virtualCode.mappings,\n fileId: virtualFileId,\n });\n }\n }\n return factory;\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","import { 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 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 if (meta.devDependencies?.[pkg]) {\n return meta.devDependencies[pkg];\n } else if (meta.dependencies?.[pkg]) {\n return meta.dependencies[pkg];\n }\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 if (meta.devDependencies?.[pkg]) {\n return meta.devDependencies[pkg];\n } else if (meta.dependencies?.[pkg]) {\n return meta.dependencies[pkg];\n }\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 if (meta.devDependencies?.[pkg]) {\n return meta.devDependencies[pkg];\n } else if (meta.dependencies?.[pkg]) {\n return meta.dependencies[pkg];\n }\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\nexport const hasSvelteSupport = async (meta: PackageJson): Promise<boolean> => {\n const pkg = '@gql.tada/svelte-support';\n const isInstalled = !!meta.devDependencies?.[pkg] || !!meta.devDependencies?.[pkg];\n if (isInstalled) {\n return true;\n }\n try {\n // NOTE: Resolved from current folder, since it's a child dependency\n return !!createRequire(__dirname)(`${pkg}/package.json`)?.version;\n } catch (_error) {\n return false;\n }\n};\n\nexport const hasVueSupport = async (meta: PackageJson): Promise<boolean> => {\n const pkg = '@gql.tada/vue-support';\n const isInstalled = !!meta.devDependencies?.[pkg] || !!meta.devDependencies?.[pkg];\n if (isInstalled) {\n return true;\n }\n try {\n // NOTE: Resolved from current folder, since it's a child dependency\n return !!createRequire(__dirname)(`${pkg}/package.json`)?.version;\n } catch (_error) {\n return false;\n }\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\\u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\\uD83C\\uDFFD\\u200D(?:\\uD83C[\\uDF3E\\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\\u200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\\uD83D[\\uDC08\\uDC15\\uDC3B\\uDC42\\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","writeOutput","target","contents","reject","file","fs","stat","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","dirname","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","require","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","tadaTurboLocation","hintMessage","cache","argumentKey","documentType","createCacheContents","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","source","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","import","SVELTE_SUPPORT","transformSvelte","VUE_SUPPORT","check","checkVue","transformVue","UNKNOWN_EXTERNAL_FILE","programFactory","vfsMap","createFSBackedSystem","files","_projectRoot","tsLibDirectory","root","nodeSys","tsLib","realpath","directory","createDirectory","directoryExists","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","addRootName","addMappedFile","delete","sourceMappedFile","addVirtualFiles","virtualFileId","virtualCode","snapshot","bumpStackTraceLimit","stackTraceLimit","init","typescript","service","serviceHost","pluginInfo","getLanguageServiceHost","createProgram","getSourceMappedFile","getSourcePosition","buildContainer","createRequire","request","parseResult","parseConfigFileTextToJson","messageText","parseJsonConfigFileContent","FileType","File","Directory","isDirectory","configFileRe","findGraphQLConfig","dir","readdir","configFile","workspaceRoot","targetPath","packageJsonPath","parse","workspaces","findWorkspaceRoot","graphql","hasSvelteSupport","pkg","devDependencies","__dirname","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","packageJson","versions","typeScriptVersion","dependencies","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","isSymbolicLink","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","resolved","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","sources","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","_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;AC/BtC,IAAMO,oBAAkBA,CAACnyC,GAAMnE,OAAS;EACxCZ,MAAK,QAAQY,IAAM;EACnBu2C,QAAOC,KAASx2C;EAChBy2C,QAAO;EACPnnC,aAAY;EACZonC,UAAS;;;AAGT,IAAMF,KAAS;;AACR,IAAMG,KAAS;;ACbf,IAAMC,KAAQ,EACrB;EACAx3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aACA;EACAonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;EACTG,SAAO;GAEP;EACAz3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;EACTG,SAAO;GAEP;EACAz3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;EACTG,SAAO;GAEP;EACAz3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,MAAK;EACLm3C,QAAO;EACPE,QAAO;EACPnnC,aAAY;EACZonC,UAAS;GAET;EACAt3C,M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ikB,SAAc;IAAEnkB,MAAM;;EAE9B,aAAMqG;IACJ,IAAM6a,IAASxc,EAAKwB,QAAQ7G,QAAQikB,OAAOzjB,KAAKK;UAC1CkV,IAAI8L;AACZ;;;ACkBIgpC,IAAAA,KAAOlhD,OAAO4G,QAnBpBkL,eAAeqvC;EACb,IAAMn2C,IAAM,IAAIG,IAAI;IAClBG,eAAejV,QAAQC,IAAI8qD,uBAAuB;IAClDh2C,aAAa;IACbvD,YAAY;;EAGdmD,EAAIY,SAASkX;EACb9X,EAAIY,SAAS6yB;EACbzzB,EAAIY,SAASqP;EACbjQ,EAAIY,SAASkS;EACb9S,EAAIY,SAASsV;EACblW,EAAIY,SAASq1C;EACbj2C,EAAIY,SAASiW;QAEP7W,EAAI6B,QAAQxW,QAAQme,KAAKxb,MAAM;AACvC,IAGkCqoD;;;;;;;;;;;;","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]}