{"version":3,"file":"index-chunk.mjs","sources":["../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/constants.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/errors.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/format.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/utils.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/Command.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/core.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/HelpCommand.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/Cli.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/platform/browser.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Boolean.mjs","../../../../node_modules/.pnpm/clipanion@4.0.0-rc.3_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/String.mjs","../../src/utils/error.ts","../../src/term/csi.ts","../../src/term/write.ts","../../src/term/symbols.ts","../../src/term/github.ts","../../src/term/tty.ts","../../src/commands/shared/logger.ts","../../src/commands/shared/projects.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/scan/module-graph.ts","../../src/commands/scan/fragment-graph.ts","../../src/commands/scan/context.ts","../../src/commands/scan/rules/field-usage.ts","../../src/commands/scan/rules/index.ts","../../src/commands/scan/rules/input-usage.ts","../../src/commands/scan/rules/deprecated-usage.ts","../../src/commands/scan/rules/orphan-fragments.ts","../../src/commands/scan/rules/cross-feature-fragments.ts","../../src/commands/scan/rules/operation-complexity.ts","../../src/commands/scan/rules/fetch-depth.ts","../../src/commands/scan/rules/directive-usage.ts","../../src/commands/scan/output/overview.ts","../../src/commands/scan/schema-util.ts","../../src/commands/scan/output/json.ts","../../src/commands/scan/output/graph.ts","../../src/commands/scan/output/terminal.ts","../../src/commands/scan/logger.ts","../../src/commands/scan/runner.ts","../../src/commands/scan/analyze.ts","../../src/commands/scan/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","../../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  make,\n  onPush,\n  onEnd,\n  subscribe,\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\nfunction commit(source: Source<string | CLIError>): Source<string | CLIError> {\n  return make((observer) => {\n    let last: string | CLIError | undefined;\n    const subscription = pipe(\n      source,\n      onPush((value) => {\n        last = value;\n        observer.next(value);\n      }),\n      onEnd(() => {\n        if (typeof last === 'string' && !last.endsWith('\\n')) observer.next('');\n        observer.complete();\n      }),\n      subscribe(() => {})\n    );\n    return subscription.unsubscribe;\n  });\n}\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        commit(output$),\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  silent?: 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, onTerminate: () => void): 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) return onTerminate();\n          break;\n        case 'escape':\n          return cleanup();\n      }\n      observer.next({ ...event, data });\n    }\n\n    function cleanup() {\n      try {\n        if (stream.isTTY) stream.setRawMode(false);\n        stream.removeListener('keypress', onKeypress);\n        if (typeof stream.unref === 'function') {\n          stream.unref();\n        }\n      } catch {\n        // noop\n      } finally {\n        observer.complete();\n      }\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 _restore() {\n    if (process.stdin.isTTY) process.stdin.setRawMode(false);\n    output.write(\n      cmd(CSI.Reset) + cmd(CSI.ResetPrivateMode) + cmd(CSI.SetPrivateMode, PrivateMode.ShowCursor)\n    );\n  }\n\n  function _terminate(code: number) {\n    _restore();\n    process.exit(code);\n  }\n\n  function _signal(signal: NodeJS.Signals) {\n    _terminate(signal === 'SIGINT' ? 130 : 143);\n  }\n\n  function _start() {\n    _setColor((isTTY && hasColorEnv) || hasColorArg);\n    if (isTTY) {\n      output.write(cmd(CSI.UnsetPrivateMode, PrivateMode.ShowCursor));\n      process.on('SIGINT', _signal);\n      process.on('SIGTERM', _signal);\n    }\n  }\n\n  function _end() {\n    if (isTTY) {\n      process.removeListener('SIGINT', _signal);\n      process.removeListener('SIGTERM', _signal);\n      output.write(\n        cmd(CSI.Reset) + cmd(CSI.ResetPrivateMode) + cmd(CSI.SetPrivateMode, PrivateMode.ShowCursor)\n      );\n    }\n  }\n\n  const inputSource = pipe(\n    fromReadStream(process.stdin, () => _terminate(130)),\n    onStart(_start),\n    onEnd(_end),\n    share\n  );\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    if (!params.silent) output.write(text(...input));\n  }\n\n  function start(outputs: AsyncIterable<ComposeInput>): Promise<string | CLIError> {\n    const write = (input: string | CLIError) => {\n      if (!params.silent) output.write('' + input);\n    };\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 projectHeader(label: string) {\n  return t.text([\n    '\\n',\n    t.cmd(t.CSI.Style, t.Style.Magenta),\n    `${t.SmallTriangle.Right} `,\n    t.cmd(t.CSI.Style, t.Style.Foreground),\n    bold(label),\n    '\\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\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 * as path from 'node:path';\nimport type { GraphQLSPConfig, LoadConfigResult } from '@gql.tada/internal';\nimport { loadConfigs, parseConfig, validateUniqueOutputLocations } from '@gql.tada/internal';\n\nexport interface ProjectContext {\n  configResult: LoadConfigResult;\n  pluginConfig: GraphQLSPConfig;\n  /** Directory of the project's own tsconfig.json file. */\n  projectPath: string;\n  /** Display name for per-project output. */\n  label: string;\n}\n\n/** Loads all projects with a plugin config, including referenced projects. */\nexport const loadProjects = async (tsconfig: string | undefined): Promise<ProjectContext[]> => {\n  const configResults = await loadConfigs(tsconfig);\n  const projects = configResults.map((configResult): ProjectContext => {\n    const projectPath = path.dirname(configResult.tsconfigPath);\n    return {\n      configResult,\n      pluginConfig: parseConfig(configResult.pluginConfig, configResult.rootPath),\n      projectPath,\n      label: path.relative(process.cwd(), configResult.tsconfigPath) || configResult.tsconfigPath,\n    };\n  });\n  validateUniqueOutputLocations(\n    projects.map((project) => ({\n      projectPath: project.projectPath,\n      config: project.pluginConfig,\n      label: project.label,\n    }))\n  );\n  return projects;\n};\n","import type { WriteStream } from 'node:tty';\nimport type { PathLike } from 'node:fs';\nimport { dirname } from 'node:path';\nimport * as fs from 'node:fs/promises';\n\n/** Checks whether a directory exists on disk */\nconst directoryExists = async (file: PathLike): Promise<boolean> => {\n  try {\n    const stat = await fs.stat(file);\n    if (stat.isDirectory()) {\n      return true;\n    } else if (stat.isSymbolicLink()) {\n      return directoryExists(await fs.realpath(file));\n    } else {\n      return false;\n    }\n  } catch {\n    return false;\n  }\n};\n\n/** Checks whether a file exists on disk */\nconst fileExists = (file: PathLike): Promise<boolean> =>\n  fs\n    .stat(file)\n    .then((stat) => stat.isFile())\n    .catch(() => false);\n\nconst touchFile = async (file: PathLike): Promise<void> => {\n  try {\n    const now = new Date();\n    await fs.utimes(file, now, now);\n  } catch (_error) {}\n};\n\nexport type WriteTarget = PathLike | WriteStream;\n\n/** Reads the current contents of a file target, or `undefined` for streams or missing files. */\nexport const readOutput = async (target: WriteTarget): Promise<string | undefined> => {\n  if (target && typeof target === 'object' && 'writable' in target) return undefined;\n  try {\n    return await fs.readFile(target, 'utf8');\n  } catch {\n    return undefined;\n  }\n};\n\n/** Writes a file to a swapfile then moves it into place to prevent excess change events. */\nexport const writeOutput = async (target: WriteTarget, contents: string): Promise<void> => {\n  if (target && typeof target === 'object' && 'writable' in target) {\n    // If we get a WritableStream (e.g. stdout), we write to that\n    // but we listen for errors and wait for it to flush fully\n    return await new Promise((resolve, reject) => {\n      target.write(contents, (error) => {\n        if (error) {\n          reject(error);\n        } else {\n          resolve();\n        }\n      });\n    });\n  }\n\n  const targetDirectory = dirname(typeof target !== 'string' ? await fs.realpath(target) : target);\n  if (!(await directoryExists(targetDirectory))) {\n    await fs.mkdir(targetDirectory, { recursive: true });\n  }\n\n  if (!(await fileExists(target))) {\n    // If the file doesn't exist, we can write directly, and not\n    // try-catch so the error falls through\n    await fs.writeFile(target, contents);\n  } else {\n    // If the file exists, we write to a swap-file, then rename (i.e. move)\n    // the file into place. No try-catch around `writeFile` for proper\n    // directory/permission errors\n    const tempTarget = target + '.tmp';\n    await fs.writeFile(tempTarget, contents);\n    try {\n      await fs.rename(tempTarget, target);\n    } catch (error) {\n      await fs.unlink(tempTarget);\n      throw error;\n    } finally {\n      // When we move the file into place, we also update its access and\n      // modification time manually, in case the rename doesn't trigger\n      // a change event\n      await touchFile(target);\n    }\n  }\n};\n","import * as t from '../../term';\n\nimport { hint, code } from '../shared/logger';\nexport * from '../shared/logger';\n\nexport function summary(showHint?: boolean) {\n  let out = t.text([\n    t.cmd(t.CSI.Style, t.Style.BrightGreen),\n    `${t.Icons.Tick} Introspection output was generated successfully\\n`,\n  ]);\n  if (showHint) {\n    out += hint(\n      `The pipe output was generated in the ${code('.d.ts')} format.\\n` +\n        `For the ${code('.ts')} format, pass the ${code('--force-ts-format')} argument.\\n`\n    );\n  }\n  return out;\n}\n","import * as path from 'node:path';\n\nimport {\n  loadRef,\n  minifyIntrospection,\n  outputIntrospectionFile,\n  extractIntrospectionHeader,\n} from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput, readOutput } 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  /** Whether to disable terminal output when using the programmatic API.\n   * @defaultValue `false` */\n  silent?: boolean;\n}\n\nexport async function* run(tty: TTY, opts: OutputOptions): AsyncIterable<ComposeInput> {\n  let projects: ProjectContext[];\n  try {\n    projects = await loadProjects(opts.tsconfig);\n  } catch (error) {\n    throw logger.externalError('Failed to load configuration.', error);\n  }\n\n  if (projects.length > 1 && (opts.output || tty.pipeTo)) {\n    throw logger.errorMessage(\n      'Output path was specified, while multiple projects are configured.\\n' +\n        logger.hint(\n          `You can only output all projects to their ${logger.code(\n            '\"tadaOutputLocation\"'\n          )} options\\n` +\n            `when multiple projects are set up through ${logger.code('\"references\"')}.`\n        )\n    );\n  }\n\n  // Projects may share an output file; its contents come only from the schema,\n  // so generate each distinct file once rather than once per referencing project.\n  const generated = new Set<string>();\n  for (const project of projects) {\n    const destinations = outputDestinations(project);\n    if (destinations.length && destinations.every((destination) => generated.has(destination))) {\n      continue;\n    }\n    for (const destination of destinations) generated.add(destination);\n    if (projects.length > 1) yield logger.projectHeader(project.label);\n    yield* runProject(tty, opts, project);\n  }\n}\n\nfunction outputDestinations(project: ProjectContext): string[] {\n  const { pluginConfig, projectPath } = project;\n  const locations =\n    'schemas' in pluginConfig\n      ? pluginConfig.schemas.map((schema) => schema.tadaOutputLocation)\n      : [pluginConfig.tadaOutputLocation];\n  return locations\n    .filter((location): location is string => !!location)\n    .map((location) => path.resolve(projectPath, location));\n}\n\n/** Generates the introspection output for a single project. */\nasync function* runProject(\n  tty: TTY,\n  opts: OutputOptions,\n  project: ProjectContext\n): AsyncIterable<ComposeInput> {\n  const { pluginConfig, projectPath } = project;\n\n  let schemaRef = loadRef(pluginConfig);\n  try {\n    schemaRef = await schemaRef.load({ rootPath: projectPath });\n  } catch (error) {\n    throw logger.externalError('Failed to load schema(s).', error);\n  }\n\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 = path.resolve(projectPath, 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    const existing = await readOutput(destination);\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        preamble: existing ? extractIntrospectionHeader(existing) || undefined : undefined,\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      const destination = path.resolve(projectPath, schema.tadaOutputLocation);\n      const existing = await readOutput(destination);\n      let contents: string;\n      try {\n        contents = outputIntrospectionFile(minifyIntrospection(schema.introspection), {\n          fileType: schema.tadaOutputLocation,\n          shouldPreprocess: !opts.disablePreprocessing,\n          preamble: existing ? extractIntrospectionHeader(existing) || undefined : undefined,\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(destination, 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, silent: opts.silent });\n  const result = await tty.start(run(tty, opts));\n  if (result instanceof Error) {\n    throw result;\n  }\n}\n","import { pipe, interval, map, concat, fromValue } 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  const frame = (state: number) =>\n    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  return concat([\n    fromValue(frame(0)),\n    pipe(\n      interval(150),\n      map((state) => frame(state + 1))\n    ),\n  ]);\n}\n","import * as path from 'node:path';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, 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  let projects: ProjectContext[];\n  try {\n    projects = await loadProjects(opts.tsconfig);\n  } catch (error) {\n    throw logger.externalError('Failed to load configuration.', error);\n  }\n\n  if (projects.length > 1 && (opts.output || tty.pipeTo)) {\n    throw logger.errorMessage(\n      'Output path was specified, while multiple projects are configured.\\n' +\n        logger.hint(\n          `You can only output all projects to their ${logger.code(\n            '\"tadaPersistedLocation\"'\n          )} options\\n` +\n            `when multiple projects are set up through ${logger.code('\"references\"')}.`\n        )\n    );\n  }\n\n  let totalWarnings = 0;\n  let failedProjects = false;\n  for (const project of projects) {\n    if (projects.length > 1) yield logger.projectHeader(project.label);\n    const result = yield* runProject(tty, opts, project, projects.length > 1);\n    totalWarnings += result.warnings;\n    failedProjects = failedProjects || result.failed;\n  }\n\n  if (failedProjects) {\n    throw logger.warningSummary(totalWarnings);\n  }\n}\n\ninterface ProjectResult {\n  warnings: number;\n  failed: boolean;\n}\n\n/** Generates the persisted manifest for a single project. */\nasync function* runProject(\n  tty: TTY,\n  opts: PersistedOptions,\n  project: ProjectContext,\n  deferWarnings: boolean\n): AsyncGenerator<ComposeInput, ProjectResult> {\n  const { runPersisted } = await import('./thread');\n\n  const { pluginConfig, projectPath } = project;\n\n  if (tty.isInteractive) yield logger.runningPersisted();\n\n  const generator = runPersisted({\n    disableNormalization: !!opts.disableNormalization,\n    rootPath: project.configResult.rootPath,\n    tsconfigPath: project.configResult.tsconfigPath,\n    configPath: project.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  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(projectPath, pluginConfig.tadaPersistedLocation);\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      if (!deferWarnings) throw logger.warningSummary(warnings);\n      return { warnings, failed: true };\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      if (!deferWarnings) throw logger.warningSummary(warnings);\n      return { warnings, failed: true };\n    } else {\n      yield logger.infoSummary(warnings, documentCount);\n    }\n  }\n\n  return { warnings, failed: false };\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 { load } from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, 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  /** Whether to disable terminal output when using the programmatic API.\n   * @defaultValue `false` */\n  silent?: boolean;\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 projects: ProjectContext[];\n    try {\n      projects = await loadProjects(opts.tsconfig);\n    } catch (error) {\n      throw logger.externalError('Failed to load configuration.', error);\n    }\n\n    if (projects.length > 1) {\n      throw logger.errorMessage(\n        `Output path cannot be automatically determined when multiple projects are configured,\\n` +\n          `because multiple projects are set up through ${logger.code('\"references\"')}.` +\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    }\n\n    const { pluginConfig, projectPath } = projects[0];\n    if (\n      'schema' in pluginConfig &&\n      typeof pluginConfig.schema === 'string' &&\n      path.extname(pluginConfig.schema) === '.graphql'\n    ) {\n      destination = path.resolve(projectPath, 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, silent: opts.silent });\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, concat, fromValue } 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 reusedLabel = (count: number | undefined) => (count ? `, ${count} reused` : '');\n\nconst documentSummary = (\n  documentCount: number | Record<string, number>,\n  cachedCount?: number | Record<string, number>\n) => {\n  let out = '';\n  if (typeof documentCount === 'number') {\n    const cachedLabel = reusedLabel(typeof cachedCount === 'number' ? cachedCount : undefined);\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${cachedLabel})\\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      const cachedLabel = reusedLabel(\n        cachedCount && typeof cachedCount !== 'number' ? cachedCount[schemaName] : undefined\n      );\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${cachedLabel}\\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(\n  warningCount: number,\n  documentCount: number | Record<string, number>,\n  cachedCount?: number | Record<string, number>\n) {\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, cachedCount);\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  const frame = (state: number) =>\n    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  return concat([\n    fromValue(frame(0)),\n    pipe(\n      interval(150),\n      map((state) => frame(state + 1))\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';\n\nimport { extractIntrospectionHeader } from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput, readOutput } from '../shared';\nimport type { TurboDocument, GraphQLSourceFile, TurboPath } from './types';\nimport * as logger from './logger';\n\nconst PREAMBLE_IGNORE = ['/* eslint-disable */', '/* prettier-ignore */'].join('\\n') + '\\n';\n\nexport interface TurboOptions {\n  /** Whether to fail instead of just logging a warning. */\n  failOnWarn: boolean;\n  /** The `tsconfig.json` to use for configurations and the TypeScript program.\n   * @defaultValue A `tsconfig.json` in the current or any parent directory. */\n  tsconfig: string | undefined;\n  /** The filename to write the cache file to.\n   * @defaultValue The `tadaTurboLocation` configuration option */\n  output: string | undefined;\n}\n\nexport async function* run(tty: TTY, opts: TurboOptions): AsyncIterable<ComposeInput> {\n  let projects: ProjectContext[];\n  try {\n    projects = await loadProjects(opts.tsconfig);\n  } catch (error) {\n    throw logger.externalError('Failed to load configuration.', error);\n  }\n\n  if (projects.length > 1 && (opts.output || tty.pipeTo)) {\n    throw logger.errorMessage(\n      'Output path was specified, while multiple projects are configured.\\n' +\n        logger.hint(\n          `You can only output all projects to their ${logger.code(\n            '\"tadaTurboLocation\"'\n          )} options\\n` +\n            `when multiple projects are set up through ${logger.code('\"references\"')}.`\n        )\n    );\n  }\n\n  let totalWarnings = 0;\n  let failedProjects = false;\n  for (const project of projects) {\n    if (projects.length > 1) yield logger.projectHeader(project.label);\n    const result = yield* runProject(tty, opts, project, projects.length > 1);\n    totalWarnings += result.warnings;\n    failedProjects = failedProjects || result.failed;\n  }\n\n  if (failedProjects) {\n    throw logger.warningSummary(totalWarnings);\n  }\n}\n\ninterface ProjectResult {\n  warnings: number;\n  failed: boolean;\n}\n\n/** Runs the turbo cache generation for a single project. */\nasync function* runProject(\n  tty: TTY,\n  opts: TurboOptions,\n  project: ProjectContext,\n  deferWarnings: boolean\n): AsyncGenerator<ComposeInput, ProjectResult> {\n  const { runTurbo } = await import('./thread');\n\n  const { pluginConfig, projectPath } = project;\n\n  let destination: WriteTarget;\n  const destinations: TurboPath[] = [];\n  if ('schema' in pluginConfig) {\n    if (!opts.output && tty.pipeTo) {\n      destination = tty.pipeTo;\n    } else if (opts.output) {\n      destination = path.resolve(process.cwd(), opts.output);\n    } else if (pluginConfig.tadaTurboLocation) {\n      destination = path.resolve(projectPath, pluginConfig.tadaTurboLocation);\n    } else if (pluginConfig.tadaOutputLocation) {\n      destination = path.resolve(\n        projectPath,\n        pluginConfig.tadaOutputLocation,\n        '..',\n        'graphql-cache.d.ts'\n      );\n      yield logger.hintMessage(\n        'No output location was specified.\\n' +\n          `The turbo cache will by default be saved as ${logger.code('\"graphql-cache.d.ts\"')}.\\n` +\n          logger.hint(\n            `To change this, add a ${logger.code('\"tadaTurboLocation\"')} in your configuration,\\n` +\n              `pass an ${logger.code('--output')} argument to this command,\\n` +\n              'or pipe this command to an output file.'\n          )\n      );\n    } else {\n      throw logger.errorMessage(\n        'No output path was specified to write the output file to.\\n' +\n          logger.hint(\n            `You have to either set ${logger.code('\"tadaTurboLocation\"')} in your configuration,\\n` +\n              `pass an ${logger.code('--output')} argument to this command,\\n` +\n              'or pipe this command to an output file.'\n          )\n      );\n    }\n  } else if ('schemas' in pluginConfig) {\n    for (const schemaConfig of pluginConfig.schemas) {\n      if (schemaConfig.tadaTurboLocation)\n        destinations.push({\n          path: path.resolve(projectPath, schemaConfig.tadaTurboLocation),\n          schemaName: schemaConfig.name,\n        });\n    }\n  }\n\n  const generator = runTurbo({\n    rootPath: project.configResult.rootPath,\n    tsconfigPath: project.configResult.tsconfigPath,\n    configPath: project.configResult.configPath,\n    pluginConfig,\n    turboOutputPath: typeof destination! === 'string' ? destination : destinations,\n  });\n\n  const documents: TurboDocument[] = [];\n  let graphqlSources: GraphQLSourceFile[] = [];\n  let warnings = 0;\n  let totalFileCount = 0;\n  let fileCount = 0;\n  let cachedDocumentCount = 0;\n\n  try {\n    if (tty.isInteractive) yield logger.runningTurbo();\n\n    for await (const signal of generator) {\n      if (signal.kind === 'EXTERNAL_WARNING') {\n        yield logger.experimentMessage(\n          `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n        );\n      } else if (signal.kind === 'FILE_COUNT') {\n        totalFileCount = signal.fileCount;\n      } else if (signal.kind === 'GRAPHQL_SOURCES') {\n        graphqlSources = signal.sources;\n      } else {\n        fileCount++;\n        documents.push(...signal.documents);\n        cachedDocumentCount += signal.documents.filter((document) => document.isCached).length;\n        warnings += signal.warnings.length;\n        if (signal.warnings.length) {\n          let buffer = logger.warningFile(signal.filePath);\n          for (const warning of signal.warnings) {\n            buffer += logger.warningMessage(warning);\n            logger.warningGithub(warning);\n          }\n          yield buffer + '\\n';\n        }\n      }\n\n      if (tty.isInteractive) yield logger.runningTurbo(fileCount, totalFileCount);\n    }\n  } catch (error) {\n    throw logger.externalError('Could not build cache', error);\n  }\n\n  if ('schema' in pluginConfig) {\n    if (warnings && opts.failOnWarn) {\n      if (!deferWarnings) throw logger.warningSummary(warnings);\n      return { warnings, failed: true };\n    }\n\n    try {\n      const existing = await readOutput(destination!);\n      const contents = createCacheContents(documents, graphqlSources, destination!, existing);\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, cachedDocumentCount);\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    const cachedCount: 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        cachedCount[name] = 0;\n        const cache: TurboDocument[] = [];\n        for (const item of documents) {\n          if (item.schemaName === name) {\n            cache.push(item);\n            documentCount[name]++;\n            if (item.isCached) cachedCount[name]++;\n          }\n        }\n        const destination = path.resolve(projectPath, tadaTurboLocation);\n        const existing = await readOutput(destination);\n        const contents = createCacheContents(cache, graphqlSources, destination, existing);\n        await writeOutput(destination, contents);\n      } catch (error) {\n        throw logger.externalError(\n          `Something went wrong while writing the '${name}' schema's type cache file.`,\n          error\n        );\n      }\n    }\n\n    if (warnings && opts.failOnWarn) {\n      if (!deferWarnings) throw logger.warningSummary(warnings);\n      return { warnings, failed: true };\n    } else {\n      yield logger.infoSummary(warnings, documentCount, cachedCount);\n    }\n  }\n\n  return { warnings, failed: false };\n}\n\nfunction createCacheContents(\n  cache: TurboDocument[],\n  graphqlSources: GraphQLSourceFile[],\n  turboDestination: WriteTarget,\n  existing?: string\n): string {\n  const preamble = (existing && extractIntrospectionHeader(existing)) || PREAMBLE_IGNORE;\n  const documentsByKey = new Map<string, TurboDocument>();\n  for (const document of cache) documentsByKey.set(document.argumentKey, document);\n\n  let output = '';\n  for (const document of documentsByKey.values()) {\n    if (output) output += '\\n';\n    if (document.documentHash) output += `    /** @gql.tada/hash ${document.documentHash} */\\n`;\n    output += `    ${document.argumentKey}:\\n      ${document.documentType};`;\n  }\n\n  let imports = \"import type { TadaDocumentNode, $tada } from 'gql.tada';\\n\";\n\n  const isFilePath =\n    typeof turboDestination === 'string' ||\n    (turboDestination &&\n      typeof turboDestination === 'object' &&\n      'toString' in turboDestination &&\n      !('writable' in turboDestination));\n\n  const addedImports = new Set<string>();\n  for (const source of graphqlSources) {\n    for (const importInfo of source.imports) {\n      if (isFilePath) {\n        const turboPath = turboDestination.toString();\n        const sourceDir = path.dirname(source.absolutePath);\n        const absoluteImportPath = path.resolve(sourceDir, importInfo.specifier);\n        const absoluteTurboPath = path.resolve(turboPath);\n\n        if (absoluteImportPath === absoluteTurboPath || addedImports.has(importInfo.specifier))\n          continue;\n\n        addedImports.add(importInfo.specifier);\n      }\n\n      imports += importInfo.importClause + '\\n';\n    }\n  }\n\n  return (\n    preamble +\n    imports +\n    '\\n' +\n    \"declare module 'gql.tada' {\\n\" +\n    ' interface setupCache {\\n' +\n    output +\n    '\\n  }' +\n    '\\n}\\n'\n  );\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { TurboOptions } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class TurboCommand extends Command {\n  static paths = [['generate', 'turbo'], ['turbo']];\n\n  tsconfig = Option.String('--tsconfig,-c', {\n    description: 'Specify the `tsconfig.json` read for configuration.',\n  });\n\n  failOnWarn = Option.Boolean('--fail-on-warn,-w', false, {\n    description: 'Triggers an error and a non-zero exit code if any warnings have been reported',\n  });\n\n  output = Option.String('--output,-o', {\n    description:\n      'Specifies where to output the file to.\\tDefault: The `tadaTurboLocation` configuration option',\n  });\n\n  async execute() {\n    // TODO: Add verbose/log/list/debug/trace option that outputs discovered documents (by name) per file\n    const tty = initTTY();\n    const result = await tty.start(\n      run(tty, {\n        failOnWarn: this.failOnWarn,\n        output: this.output,\n        tsconfig: this.tsconfig,\n      })\n    );\n    return exitCode() || (typeof result === 'object' ? result.exit : 0);\n  }\n}\n\n/** Generates a cache typings file for all GraphQL document types ahead of time.\n *\n * @remarks\n * The `generateTurbo()` function generates a cache for all GraphQL document types ahead of time.\n * This cache speeds up type evaluation and is especially useful when it's checked into the\n * repository after making changes to GraphQL documents, which speeds up all further type\n * checks and evaluation.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#generateturbo}\n */\nexport async function generateTurbo(opts: TurboOptions) {\n  const tty = initTTY({ disableTTY: true });\n  const result = await tty.start(run(tty, opts));\n  if (result instanceof Error) {\n    throw result;\n  }\n}\n","import * as path from 'node:path';\n\nexport interface ModuleReach {\n  /** The module itself plus every module that transitively depends on it. */\n  modules: string[];\n  /** Distinct areas covered by {@link modules}. */\n  areas: string[];\n  /** Entry points among {@link modules}. */\n  entryPoints: string[];\n}\n\n/**\n * The project's static module dependency graph (file → its project imports).\n *\n * A self-contained, reusable structure: all reachability/area analytics live\n * here and are memoised internally, so the {@link ScanContext} exposes it as a\n * single primitive and rules can do graph analysis without the context growing.\n */\nexport class ModuleGraph {\n  private readonly _edges: Map<string, readonly string[]>;\n  private readonly _cwd: string;\n  private _reverse: Map<string, Set<string>> | undefined;\n  private _entryPoints: Set<string> | undefined;\n  private _distance: Map<string, number> | undefined;\n  private readonly _dependents = new Map<string, Set<string>>();\n\n  constructor(edges: Map<string, string[]>, cwd: string = process.cwd()) {\n    this._edges = edges;\n    this._cwd = cwd;\n  }\n\n  /** All import edges (module → the project modules it imports). */\n  importMap(): ReadonlyMap<string, readonly string[]> {\n    return this._edges;\n  }\n\n  /** The \"area\" a module belongs to: its directory, relative to the cwd. */\n  areaOf(modulePath: string): string {\n    const rel = path.relative(this._cwd, modulePath);\n    const dir = path.dirname(!rel.startsWith('..') ? rel : modulePath);\n    return dir === '.' ? '(root)' : dir;\n  }\n\n  /** Modules that nothing else imports — the roots of the graph. */\n  entryPoints(): Set<string> {\n    if (this._entryPoints) return this._entryPoints;\n    const nodes = new Set<string>();\n    const targets = new Set<string>();\n    for (const [from, tos] of this._edges) {\n      nodes.add(from);\n      for (const to of tos) {\n        nodes.add(to);\n        targets.add(to);\n      }\n    }\n    return (this._entryPoints = new Set([...nodes].filter((node) => !targets.has(node))));\n  }\n\n  /** Modules that transitively import the given module (its reverse closure). */\n  dependents(modulePath: string): Set<string> {\n    const cached = this._dependents.get(modulePath);\n    if (cached) return cached;\n\n    const reverse = this._reverseGraph();\n    const result = new Set<string>();\n    const stack = [...(reverse.get(modulePath) || [])];\n    let node: string | undefined;\n    while ((node = stack.pop())) {\n      if (result.has(node)) continue;\n      result.add(node);\n      stack.push(...(reverse.get(node) || []));\n    }\n\n    this._dependents.set(modulePath, result);\n    return result;\n  }\n\n  /** Shortest distance from any entry point to the module (entry points are 0). */\n  distanceFromEntry(modulePath: string): number | undefined {\n    if (!this._distance) {\n      const distance = new Map<string, number>();\n      let frontier = [...this.entryPoints()];\n      let depth = 0;\n      while (frontier.length) {\n        const next: string[] = [];\n        for (const node of frontier) {\n          if (distance.has(node)) continue;\n          distance.set(node, depth);\n          for (const to of this._edges.get(node) || []) {\n            if (!distance.has(to)) next.push(to);\n          }\n        }\n        frontier = next;\n        depth++;\n      }\n      this._distance = distance;\n    }\n    return this._distance.get(modulePath);\n  }\n\n  /** The blast radius of a module: itself plus everything that depends on it. */\n  reach(modulePath: string): ModuleReach {\n    const entryPoints = this.entryPoints();\n    const modules = new Set<string>([modulePath, ...this.dependents(modulePath)]);\n    const areas = new Set<string>();\n    const reachedEntries = new Set<string>();\n    for (const module of modules) {\n      areas.add(this.areaOf(module));\n      if (entryPoints.has(module)) reachedEntries.add(module);\n    }\n    return { modules: [...modules], areas: [...areas].sort(), entryPoints: [...reachedEntries] };\n  }\n\n  private _reverseGraph(): Map<string, Set<string>> {\n    if (this._reverse) return this._reverse;\n    const reverse = new Map<string, Set<string>>();\n    for (const [from, tos] of this._edges) {\n      for (const to of tos) {\n        let importers = reverse.get(to);\n        if (!importers) reverse.set(to, (importers = new Set()));\n        importers.add(from);\n      }\n    }\n    return (this._reverse = reverse);\n  }\n}\n","import type { SchemaName } from './types';\n\nexport interface FragmentGraphDefinition {\n  id: string;\n  kind: 'operation' | 'fragment';\n  schemaName: SchemaName;\n  /** The fragment's name (present for fragment definitions). */\n  name?: string;\n  /** Names of fragments spread directly by this definition. */\n  fragmentSpreads: readonly string[];\n}\n\nconst key = (schemaName: SchemaName, name: string): string => `${schemaName ?? ''}\\0${name}`;\n\n/**\n * The fragment spread graph: resolution by name and reachability between\n * definitions.\n *\n * A self-contained, reusable structure (the GraphQL-side analogue of\n * {@link ModuleGraph}). Reachability is memoised internally, so the\n * {@link ScanContext} exposes it as a single primitive and rules can do\n * fragment-graph analysis without the context growing per rule.\n */\nexport class FragmentGraph {\n  private readonly _byId = new Map<string, FragmentGraphDefinition>();\n  private readonly _idByName = new Map<string, string>();\n  private readonly _operationIds: string[] = [];\n  private readonly _reachable = new Map<string, Set<string>>();\n  private _operationsReaching: Map<string, Set<string>> | undefined;\n\n  constructor(definitions: readonly FragmentGraphDefinition[]) {\n    for (const definition of definitions) {\n      this._byId.set(definition.id, definition);\n      if (definition.kind === 'operation') {\n        this._operationIds.push(definition.id);\n      } else if (definition.name != null) {\n        this._idByName.set(key(definition.schemaName, definition.name), definition.id);\n      }\n    }\n  }\n\n  /** Resolves a fragment name to its id within a schema. */\n  resolve(schemaName: SchemaName, name: string): string | undefined {\n    return this._idByName.get(key(schemaName, name));\n  }\n\n  /** Ids of fragments reachable from a definition via (nested) spreads. */\n  reachableFragments(definitionId: string): Set<string> {\n    const cached = this._reachable.get(definitionId);\n    if (cached) return cached;\n\n    const result = new Set<string>();\n    const start = this._byId.get(definitionId);\n    if (start) {\n      const stack = [...start.fragmentSpreads];\n      let name: string | undefined;\n      while ((name = stack.pop())) {\n        const id = this.resolve(start.schemaName, name);\n        if (!id || result.has(id)) continue;\n        result.add(id);\n        const fragment = this._byId.get(id);\n        if (fragment) stack.push(...fragment.fragmentSpreads);\n      }\n    }\n\n    this._reachable.set(definitionId, result);\n    return result;\n  }\n\n  /** Operation ids that reach a fragment directly or transitively. */\n  operationsReaching(fragmentId: string): Set<string> {\n    if (!this._operationsReaching) {\n      const map = new Map<string, Set<string>>();\n      for (const operationId of this._operationIds) {\n        for (const reachableId of this.reachableFragments(operationId)) {\n          let set = map.get(reachableId);\n          if (!set) map.set(reachableId, (set = new Set()));\n          set.add(operationId);\n        }\n      }\n      this._operationsReaching = map;\n    }\n    return this._operationsReaching.get(fragmentId) || new Set();\n  }\n}\n","import * as crypto from 'node:crypto';\nimport * as path from 'node:path';\nimport { parse, print, visit, Kind } from 'graphql';\nimport type {\n  GraphQLSchema,\n  GraphQLCompositeType,\n  GraphQLField,\n  GraphQLOutputType,\n  GraphQLInputType,\n  GraphQLEnumValue,\n  TypeInfo,\n  ASTNode,\n  ASTVisitor,\n  DefinitionNode,\n  OperationDefinitionNode,\n  FragmentDefinitionNode,\n} from 'graphql';\n\nimport type {\n  SchemaName,\n  RawScanDocument,\n  ScanWarning,\n  ModuleInfo,\n  OperationInfo,\n  FragmentInfo,\n  DefinitionRecord,\n} from './types';\nimport { ModuleGraph } from './module-graph';\nimport { FragmentGraph } from './fragment-graph';\nimport type { FragmentGraphDefinition } from './fragment-graph';\n\nconst CWD = process.cwd();\n\nexport interface ScanContextParams {\n  documents: RawScanDocument[];\n  schemas: Map<SchemaName, GraphQLSchema>;\n  imports: Map<string, string[]>;\n  warnings: ScanWarning[];\n}\n\nconst hashOf = (input: string): string =>\n  crypto.createHash('sha256').update(input).digest('hex').slice(0, 16);\n\n/** Collects the names of fragments spread anywhere within a definition. */\nfunction collectFragmentSpreads(node: DefinitionNode): string[] {\n  const names = new Set<string>();\n  visit(node, {\n    FragmentSpread(spread) {\n      names.add(spread.name.value);\n    },\n  });\n  return [...names];\n}\n\n/**\n * Shared state passed to every scan rule, modelled on graphql-js's\n * `ValidationContext`.\n *\n * It exposes only *primitives*: the loaded schemas, the corpus of discovered\n * definitions (identities + AST nodes), fragment resolution, structural\n * reachability helpers, and TypeInfo-backed accessors for the current\n * traversal position. It never holds derived insight data — rules build that\n * themselves.\n */\nexport class ScanContext {\n  private readonly _schemas: Map<SchemaName, GraphQLSchema>;\n  private readonly _warnings: ScanWarning[];\n  private readonly _operations: OperationInfo[] = [];\n  private readonly _fragments: FragmentInfo[] = [];\n  private readonly _definitions: DefinitionRecord[] = [];\n  private readonly _recordByNode = new Map<ASTNode, DefinitionRecord>();\n  private readonly _recordById = new Map<string, DefinitionRecord>();\n  private readonly _modules: ModuleInfo[];\n\n  private _typeInfo: TypeInfo | null = null;\n  private _currentDefinition: DefinitionRecord | null = null;\n\n  // Static module dependency graph (every scanned file → its project imports).\n  private readonly _importGraph: Map<string, string[]>;\n  private _moduleGraph: ModuleGraph | undefined;\n  private _fragmentGraph: FragmentGraph | undefined;\n\n  constructor(params: ScanContextParams) {\n    this._schemas = params.schemas;\n    this._warnings = [...params.warnings];\n    this._importGraph = params.imports;\n    this._buildCorpus(params.documents);\n    this._modules = this._buildModules(params.imports);\n  }\n\n  /* -- Corpus accessors (base facts) -- */\n\n  get operations(): readonly OperationInfo[] {\n    return this._operations;\n  }\n\n  get fragments(): readonly FragmentInfo[] {\n    return this._fragments;\n  }\n\n  get modules(): readonly ModuleInfo[] {\n    return this._modules;\n  }\n\n  get warnings(): readonly ScanWarning[] {\n    return this._warnings;\n  }\n\n  getSchemas(): Map<SchemaName, GraphQLSchema> {\n    return this._schemas;\n  }\n\n  /** Definition AST nodes for a single schema, for per-schema traversal. */\n  definitionNodesForSchema(schemaName: SchemaName): DefinitionNode[] {\n    const nodes: DefinitionNode[] = [];\n    for (const record of this._definitions) {\n      if (record.schemaName === schemaName) nodes.push(record.node);\n    }\n    return nodes;\n  }\n\n  /* -- Traversal primitives (set by the driver) -- */\n\n  /** @internal Used by the driver to bind the active schema's TypeInfo. */\n  setTypeInfo(typeInfo: TypeInfo): void {\n    this._typeInfo = typeInfo;\n  }\n\n  /** A visitor the driver runs first so rules can read the current definition. */\n  trackingVisitor(): ASTVisitor {\n    return {\n      OperationDefinition: {\n        enter: (node) => void (this._currentDefinition = this._recordByNode.get(node) || null),\n        leave: () => void (this._currentDefinition = null),\n      },\n      FragmentDefinition: {\n        enter: (node) => void (this._currentDefinition = this._recordByNode.get(node) || null),\n        leave: () => void (this._currentDefinition = null),\n      },\n    };\n  }\n\n  getCurrentDefinition(): DefinitionRecord | null {\n    return this._currentDefinition;\n  }\n\n  getParentType(): GraphQLCompositeType | null | undefined {\n    return this._typeInfo?.getParentType();\n  }\n\n  /** The current output type at this traversal position — the third TypeInfo\n   * accessor alongside {@link getParentType} and {@link getFieldDef}. Unused\n   * today, but kept as a generic primitive for rules that inspect return types\n   * (e.g. list/non-null wrapping) without the context having to grow. */\n  getType(): GraphQLOutputType | null | undefined {\n    return this._typeInfo?.getType();\n  }\n\n  getFieldDef(): GraphQLField<unknown, unknown> | null | undefined {\n    return this._typeInfo?.getFieldDef();\n  }\n\n  /** The input type expected at this position (argument / input-field / list value). */\n  getInputType(): GraphQLInputType | null | undefined {\n    return this._typeInfo?.getInputType();\n  }\n\n  /** The enclosing input-object type when inside an input object literal. */\n  getParentInputType(): GraphQLInputType | null | undefined {\n    return this._typeInfo?.getParentInputType();\n  }\n\n  /** The enum value definition at the current position, if any. */\n  getEnumValue(): GraphQLEnumValue | null | undefined {\n    return this._typeInfo?.getEnumValue();\n  }\n\n  /* -- Generic primitives for graph-level rules -- */\n\n  /** The project's static module dependency graph, as a reusable structure.\n   * All reachability/area analysis lives on it, so graph rules need no bespoke\n   * context methods. */\n  getModuleGraph(): ModuleGraph {\n    return (this._moduleGraph ??= new ModuleGraph(this._importGraph, CWD));\n  }\n\n  /** The fragment spread graph (resolution + reachability), as a reusable\n   * structure. Built from the corpus, so fragment-graph rules need no bespoke\n   * context methods. */\n  getFragmentGraph(): FragmentGraph {\n    if (!this._fragmentGraph) {\n      const definitions: FragmentGraphDefinition[] = [];\n      for (const op of this._operations) {\n        definitions.push({\n          id: op.id,\n          kind: 'operation',\n          schemaName: op.schemaName,\n          fragmentSpreads: op.fragmentSpreads,\n        });\n      }\n      for (const fragment of this._fragments) {\n        definitions.push({\n          id: fragment.id,\n          kind: 'fragment',\n          schemaName: fragment.schemaName,\n          name: fragment.name,\n          fragmentSpreads: fragment.fragmentSpreads,\n        });\n      }\n      this._fragmentGraph = new FragmentGraph(definitions);\n    }\n    return this._fragmentGraph;\n  }\n\n  /* -- Construction -- */\n\n  private _addWarning(message: string, doc: RawScanDocument): void {\n    this._warnings.push({ message, file: doc.filePath, line: doc.line, col: doc.col });\n  }\n\n  private _uniqueId(base: string): string {\n    if (!this._recordById.has(base)) return base;\n    let n = 2;\n    while (this._recordById.has(`${base}#${n}`)) n++;\n    return `${base}#${n}`;\n  }\n\n  private _register(record: DefinitionRecord): void {\n    this._definitions.push(record);\n    this._recordByNode.set(record.node, record);\n    this._recordById.set(record.id, record);\n    // Keep the AST node and discriminant internal; expose only clean identities.\n    if (record.defKind === 'operation') {\n      const { node: _node, defKind: _defKind, ...info } = record;\n      this._operations.push(info);\n    } else {\n      const { node: _node, defKind: _defKind, ...info } = record;\n      this._fragments.push(info);\n    }\n  }\n\n  private _buildCorpus(documents: RawScanDocument[]): void {\n    let anonCount = 0;\n    for (const doc of documents) {\n      if (!this._schemas.has(doc.schemaName)) {\n        this._addWarning(\n          `No schema was loaded for ${doc.schemaName ? `'${doc.schemaName}'` : 'the default schema'}.`,\n          doc\n        );\n        continue;\n      }\n\n      let definitions: readonly DefinitionNode[];\n      try {\n        definitions = parse(doc.document, { noLocation: true }).definitions;\n      } catch (error) {\n        this._addWarning(\n          `The document could not be parsed. Run \\`check\\` to see validation errors.\\n` +\n            `${error instanceof Error ? error.message : error}`,\n          doc\n        );\n        continue;\n      }\n\n      const loc = { file: doc.filePath, line: doc.line, col: doc.col };\n      for (const definition of definitions) {\n        if (definition.kind === Kind.OPERATION_DEFINITION) {\n          const op = definition as OperationDefinitionNode;\n          const name = op.name ? op.name.value : null;\n          const id = this._uniqueId(\n            `${doc.schemaName ?? ''}:operation:${name ?? `anonymous-${++anonCount}`}`\n          );\n          this._register({\n            defKind: 'operation',\n            node: op,\n            id,\n            name,\n            kind: op.operation,\n            schemaName: doc.schemaName,\n            module: doc.filePath,\n            loc,\n            variables: (op.variableDefinitions || []).map((v) => ({\n              name: v.variable.name.value,\n              type: print(v.type),\n              defaultValue: v.defaultValue ? print(v.defaultValue) : undefined,\n            })),\n            fragmentSpreads: collectFragmentSpreads(op),\n            hash: hashOf(print(op)),\n          });\n        } else if (definition.kind === Kind.FRAGMENT_DEFINITION) {\n          const fragment = definition as FragmentDefinitionNode;\n          const id = this._uniqueId(`${doc.schemaName ?? ''}:fragment:${fragment.name.value}`);\n          this._register({\n            defKind: 'fragment',\n            node: fragment,\n            id,\n            name: fragment.name.value,\n            typeCondition: fragment.typeCondition.name.value,\n            schemaName: doc.schemaName,\n            module: doc.filePath,\n            loc,\n            fragmentSpreads: collectFragmentSpreads(fragment),\n            hash: hashOf(print(fragment)),\n          });\n        }\n      }\n    }\n  }\n\n  private _buildModules(imports: Map<string, string[]>): ModuleInfo[] {\n    const byPath = new Map<string, ModuleInfo>();\n    const ensure = (modulePath: string): ModuleInfo => {\n      let info = byPath.get(modulePath);\n      if (!info) {\n        info = {\n          path: modulePath,\n          relativePath: path.relative(CWD, modulePath) || modulePath,\n          operations: [],\n          fragments: [],\n          imports: [],\n        };\n        byPath.set(modulePath, info);\n      }\n      return info;\n    };\n\n    for (const op of this._operations) ensure(op.module).operations.push(op.id);\n    for (const fragment of this._fragments) ensure(fragment.module).fragments.push(fragment.id);\n\n    for (const info of byPath.values()) {\n      const resolved = imports.get(info.path);\n      if (resolved) {\n        for (const target of resolved) {\n          if (target !== info.path && byPath.has(target)) info.imports.push(target);\n        }\n      }\n    }\n\n    return [...byPath.values()].sort((a, b) => a.relativePath.localeCompare(b.relativePath));\n  }\n}\n","import type { ScanRule, RuleDatapoint } from '../types';\n\nexport interface FieldUsageData {\n  typeName: string;\n  fieldName: string;\n  fieldType: string;\n  deprecated: boolean;\n  deprecationReason?: string | undefined;\n  count: number;\n  directUsages: { defId: string; module: string }[];\n  /** Operation ids that reach this field directly or transitively. */\n  operations: string[];\n  /** Blast radius: how much of the codebase transitively depends on this field. */\n  reach: { modules: number; areas: string[]; entryPoints: number };\n}\n\ninterface Accumulated {\n  typeName: string;\n  fieldName: string;\n  fieldType: string;\n  deprecationReason?: string;\n  directUsages: { defId: string; module: string }[];\n}\n\n/** Indexes every field that is actually selected: which operations/fragments\n * select each schema coordinate, the operations that reach it, and its blast\n * radius. Fields the schema declares but no document selects are absent (derive\n * them from the schema if needed; the overview carries aggregate coverage). */\nexport const fieldUsage: ScanRule<FieldUsageData> = {\n  name: 'field-usage',\n  description: 'Used fields, keyed by schema coordinate, with their reach.',\n  create(context) {\n    const byCoordinate = new Map<string, Accumulated>();\n    let seen = new Set<string>();\n    const resetSeen = () => void (seen = new Set());\n\n    return {\n      visitor: {\n        OperationDefinition: { enter: resetSeen },\n        FragmentDefinition: { enter: resetSeen },\n        Field: {\n          enter() {\n            const parentType = context.getParentType();\n            const fieldDef = context.getFieldDef();\n            const definition = context.getCurrentDefinition();\n            if (!parentType || !fieldDef || !definition) return;\n            // Skip reserved introspection meta-fields (__typename, __schema, __type).\n            if (fieldDef.name.startsWith('__')) return;\n\n            const coordinate = `${parentType.name}.${fieldDef.name}`;\n            if (seen.has(coordinate)) return;\n            seen.add(coordinate);\n\n            let entry = byCoordinate.get(coordinate);\n            if (!entry) {\n              entry = {\n                typeName: parentType.name,\n                fieldName: fieldDef.name,\n                fieldType: String(fieldDef.type),\n                deprecationReason: fieldDef.deprecationReason ?? undefined,\n                directUsages: [],\n              };\n              byCoordinate.set(coordinate, entry);\n            }\n            entry.directUsages.push({ defId: definition.id, module: definition.module });\n          },\n        },\n      },\n\n      collect() {\n        const operationIds = new Set(context.operations.map((op) => op.id));\n        const moduleById = new Map(context.operations.map((op) => [op.id, op.module] as const));\n        const graph = context.getModuleGraph();\n        const fragments = context.getFragmentGraph();\n        const hasEntryPoints = graph.entryPoints().size > 0;\n\n        const datapoints: RuleDatapoint<FieldUsageData>[] = [];\n        for (const [coordinate, entry] of byCoordinate) {\n          const operations = new Set<string>();\n          for (const usage of entry.directUsages) {\n            if (operationIds.has(usage.defId)) operations.add(usage.defId);\n            else for (const id of fragments.operationsReaching(usage.defId)) operations.add(id);\n          }\n\n          // Blast radius: every module that selects the field, plus the modules\n          // of the operations that reach it, expanded by who depends on them.\n          const sourceModules = new Set<string>(entry.directUsages.map((u) => u.module));\n          for (const id of operations) {\n            const module = moduleById.get(id);\n            if (module) sourceModules.add(module);\n          }\n          const reachModules = new Set<string>();\n          const reachAreas = new Set<string>();\n          const reachEntries = new Set<string>();\n          for (const module of sourceModules) {\n            const reach = graph.reach(module);\n            for (const m of reach.modules) reachModules.add(m);\n            for (const a of reach.areas) reachAreas.add(a);\n            for (const e of reach.entryPoints) reachEntries.add(e);\n          }\n\n          datapoints.push({\n            ref: { kind: 'field', coordinate },\n            message: `${coordinate} selected ${entry.directUsages.length} time(s)`,\n            weight: hasEntryPoints ? reachEntries.size : reachModules.size,\n            data: {\n              typeName: entry.typeName,\n              fieldName: entry.fieldName,\n              fieldType: entry.fieldType,\n              deprecated: entry.deprecationReason != null,\n              deprecationReason: entry.deprecationReason,\n              count: entry.directUsages.length,\n              directUsages: entry.directUsages,\n              operations: [...operations],\n              reach: {\n                modules: reachModules.size,\n                areas: [...reachAreas].sort(),\n                entryPoints: reachEntries.size,\n              },\n            },\n          });\n        }\n\n        // Rank by selection count, then reach, then coordinate for stable ties —\n        // so the terminal's top-N shows the most-used fields first.\n        const coordinateOf = (d: FieldUsageData) => `${d.typeName}.${d.fieldName}`;\n        return datapoints.sort(\n          (a, b) =>\n            b.data.count - a.data.count ||\n            (b.weight ?? 0) - (a.weight ?? 0) ||\n            coordinateOf(a.data).localeCompare(coordinateOf(b.data))\n        );\n      },\n    };\n  },\n};\n","import type { ScanRule } from '../types';\n\nimport { fieldUsage } from './field-usage';\nimport { inputUsage } from './input-usage';\nimport { deprecatedUsage } from './deprecated-usage';\nimport { orphanFragments } from './orphan-fragments';\nimport { crossFeatureFragments } from './cross-feature-fragments';\nimport { operationComplexity } from './operation-complexity';\nimport { fetchDepth } from './fetch-depth';\nimport { directiveUsage } from './directive-usage';\n\nexport type { FieldUsageData } from './field-usage';\n\n/** The rules run out of the box. Each is a `(context) => { visitor, collect }`\n * factory that owns its state — adding an insight means writing one rule file\n * and registering it here. */\nexport const DEFAULT_RULES: ScanRule[] = [\n  // The per-field usage index (reverse lookup + blast radius).\n  fieldUsage,\n  // Input-side usage: enum values and input-object fields.\n  inputUsage,\n  // Schema evolution & safety\n  deprecatedUsage,\n  // Code navigation & refactoring\n  orphanFragments,\n  crossFeatureFragments,\n  // Performance & DX\n  operationComplexity,\n  // Code-structure (dependency graph)\n  fetchDepth,\n  // Conventions\n  directiveUsage,\n];\n","import { getNamedType } from 'graphql';\n\nimport type { ScanRule, RuleDatapoint } from '../types';\n\nexport interface InputUsageData {\n  kind: 'enum-value' | 'input-field';\n  count: number;\n}\n\n/** Usage counts for the input side of the schema: which enum values are passed\n * and which input-object fields are set, keyed by coordinate (`Enum.VALUE` /\n * `Input.field`). Answers \"which enum values / input fields do we actually\n * use\", which neither field usage nor coverage captures. */\nexport const inputUsage: ScanRule<InputUsageData> = {\n  name: 'input-usage',\n  description: 'Usage counts for enum values and input-object fields.',\n  create(context) {\n    const counts = new Map<string, { kind: InputUsageData['kind']; count: number }>();\n    const bump = (coordinate: string, kind: InputUsageData['kind']) => {\n      const entry = counts.get(coordinate);\n      if (entry) entry.count++;\n      else counts.set(coordinate, { kind, count: 1 });\n    };\n\n    return {\n      visitor: {\n        EnumValue: {\n          enter(node) {\n            const inputType = context.getInputType();\n            if (inputType) bump(`${getNamedType(inputType).name}.${node.value}`, 'enum-value');\n          },\n        },\n        ObjectField: {\n          enter(node) {\n            const parentInput = context.getParentInputType();\n            if (parentInput)\n              bump(`${getNamedType(parentInput).name}.${node.name.value}`, 'input-field');\n          },\n        },\n      },\n\n      collect() {\n        const datapoints: RuleDatapoint<InputUsageData>[] = [...counts.entries()]\n          .sort((a, b) => b[1].count - a[1].count || a[0].localeCompare(b[0]))\n          .map(([coordinate, { kind, count }]) => ({\n            ref: { kind: 'field', coordinate },\n            message: `${coordinate} (${kind}) used ${count} time(s)`,\n            weight: count,\n            data: { kind, count },\n          }));\n        return datapoints;\n      },\n    };\n  },\n};\n","import type { ScanRule } from '../types';\n\nexport interface DeprecatedUsageData {\n  reason?: string | undefined;\n  count: number;\n  operations: string[];\n}\n\ninterface Accumulated {\n  reason?: string | undefined;\n  defIds: Set<string>;\n}\n\n/** Deprecated schema fields that are still selected, ranked by how many\n * operations reach them — the migration's remaining blast radius. */\nexport const deprecatedUsage: ScanRule<DeprecatedUsageData> = {\n  name: 'deprecated-usage',\n  description: 'Deprecated schema fields that are still in use.',\n  create(context) {\n    const byCoordinate = new Map<string, Accumulated>();\n\n    return {\n      visitor: {\n        Field: {\n          enter() {\n            const parentType = context.getParentType();\n            const fieldDef = context.getFieldDef();\n            const definition = context.getCurrentDefinition();\n            if (!parentType || !fieldDef || !definition) return;\n            if (fieldDef.deprecationReason == null) return;\n\n            const coordinate = `${parentType.name}.${fieldDef.name}`;\n            let entry = byCoordinate.get(coordinate);\n            if (!entry) {\n              byCoordinate.set(\n                coordinate,\n                (entry = { reason: fieldDef.deprecationReason ?? undefined, defIds: new Set() })\n              );\n            }\n            entry.defIds.add(definition.id);\n          },\n        },\n      },\n\n      collect() {\n        const operationIds = new Set(context.operations.map((op) => op.id));\n        const fragments = context.getFragmentGraph();\n        return [...byCoordinate.entries()]\n          .map(([coordinate, entry]) => {\n            const operations = new Set<string>();\n            for (const defId of entry.defIds) {\n              if (operationIds.has(defId)) operations.add(defId);\n              else for (const id of fragments.operationsReaching(defId)) operations.add(id);\n            }\n            return { coordinate, reason: entry.reason, operations: [...operations] };\n          })\n          .sort((a, b) => b.operations.length - a.operations.length)\n          .map(({ coordinate, reason, operations }) => ({\n            ref: { kind: 'field', coordinate },\n            message: `${coordinate} is deprecated but used by ${operations.length} operation(s)`,\n            weight: operations.length,\n            data: { reason, count: operations.length, operations },\n          }));\n      },\n    };\n  },\n};\n","import type { ScanRule } from '../types';\n\nexport interface OrphanFragmentData {\n  typeCondition: string;\n  module: string;\n}\n\n/** Fragments that are defined but never spread by any operation or fragment. */\nexport const orphanFragments: ScanRule<OrphanFragmentData> = {\n  name: 'orphan-fragments',\n  description: 'Fragments that are defined but never used.',\n  create(context) {\n    const spreadIds = new Set<string>();\n    const fragments = context.getFragmentGraph();\n\n    return {\n      visitor: {\n        FragmentSpread: {\n          enter(node) {\n            const definition = context.getCurrentDefinition();\n            if (!definition) return;\n            const id = fragments.resolve(definition.schemaName, node.name.value);\n            if (id) spreadIds.add(id);\n          },\n        },\n      },\n\n      collect() {\n        return context.fragments\n          .filter((fragment) => !spreadIds.has(fragment.id))\n          .map((fragment) => ({\n            ref: { kind: 'fragment', id: fragment.id },\n            message: `Fragment '${fragment.name}' is never spread`,\n            data: { typeCondition: fragment.typeCondition, module: fragment.module },\n          }));\n      },\n    };\n  },\n};\n","import type { ScanRule, RuleDatapoint } from '../types';\n\nexport interface CrossFeatureData {\n  definingArea: string;\n  consumerAreas: string[];\n  spreadCount: number;\n}\n\n/** Fragments consumed across area boundaries — a quantified signal of coupling\n * between features. The weight is the number of distinct consuming areas. */\nexport const crossFeatureFragments: ScanRule<CrossFeatureData> = {\n  name: 'cross-feature-fragments',\n  description: 'Fragments spread across multiple areas of the codebase.',\n  create(context) {\n    // fragment id -> areas of the definitions that spread it\n    const consumerAreas = new Map<string, Set<string>>();\n    const spreadCount = new Map<string, number>();\n\n    const graph = context.getModuleGraph();\n    const fragments = context.getFragmentGraph();\n\n    return {\n      visitor: {\n        FragmentSpread: {\n          enter(node) {\n            const definition = context.getCurrentDefinition();\n            if (!definition) return;\n            const id = fragments.resolve(definition.schemaName, node.name.value);\n            if (!id) return;\n            let areas = consumerAreas.get(id);\n            if (!areas) consumerAreas.set(id, (areas = new Set()));\n            areas.add(graph.areaOf(definition.module));\n            spreadCount.set(id, (spreadCount.get(id) || 0) + 1);\n          },\n        },\n      },\n\n      collect() {\n        const byId = new Map(context.fragments.map((fragment) => [fragment.id, fragment]));\n        const datapoints: RuleDatapoint<CrossFeatureData>[] = [];\n        for (const [id, areas] of consumerAreas) {\n          const fragment = byId.get(id);\n          if (!fragment) continue;\n          const definingArea = graph.areaOf(fragment.module);\n          // Areas other than where the fragment itself lives.\n          const externalAreas = [...areas].filter((area) => area !== definingArea).sort();\n          if (!externalAreas.length) continue;\n\n          datapoints.push({\n            ref: { kind: 'fragment' as const, id },\n            message: `Fragment '${fragment.name}' (${definingArea}) is consumed by ${externalAreas.length} other area(s)`,\n            weight: externalAreas.length,\n            data: {\n              definingArea,\n              consumerAreas: [...areas].sort(),\n              spreadCount: spreadCount.get(id) || 0,\n            },\n          });\n        }\n        return datapoints.sort((a, b) => (b.weight || 0) - (a.weight || 0));\n      },\n    };\n  },\n};\n","import { isListType, getNullableType } from 'graphql';\n\nimport type { ScanRule, RuleDatapoint } from '../types';\n\n/** Extra weight per list field — list selections drive response size / N+1 risk. */\nconst LIST_WEIGHT = 3;\n\nexport interface ComplexityData {\n  /** Selection depth, expanded through fragment spreads. */\n  depth: number;\n  /** Number of distinct fields selected, expanded through fragment spreads. */\n  fieldCount: number;\n  /** How many of those distinct fields return a list. */\n  listFields: number;\n  /** The distinct schema coordinates selected (the operation's footprint). */\n  fields: string[];\n  /** Combined cost score. */\n  score: number;\n}\n\n/** Per-definition metrics gathered during traversal (own selections only). */\ninterface DefMetrics {\n  schemaName: string | null;\n  ownDepth: number;\n  /** Distinct coordinates selected directly in this definition. */\n  fields: Set<string>;\n  /** Subset of {@link fields} whose field returns a list. */\n  listFields: Set<string>;\n  /** Fragment spreads with the selection-set depth they occur at. */\n  spreads: { name: string; depth: number }[];\n}\n\n/** Operations ranked by cost, expanded through fragment spreads (an operation\n * that delegates to a big fragment is correctly counted as large). Reports the\n * operation's full field footprint, its transitive depth, and how many of its\n * fields return lists (weighted more heavily as a proxy for response size /\n * N+1 risk). */\nexport const operationComplexity: ScanRule<ComplexityData> = {\n  name: 'operation-complexity',\n  description: 'Operations ranked by transitive footprint, depth, and list fan-out.',\n  create(context) {\n    const byDef = new Map<string, DefMetrics>();\n    let current: DefMetrics | null = null;\n    let depth = 0;\n\n    const startDefinition = () => {\n      const definition = context.getCurrentDefinition();\n      if (!definition) {\n        current = null;\n        return;\n      }\n      current = {\n        schemaName: definition.schemaName,\n        ownDepth: 0,\n        fields: new Set(),\n        listFields: new Set(),\n        spreads: [],\n      };\n      byDef.set(definition.id, current);\n      depth = 0;\n    };\n\n    return {\n      visitor: {\n        OperationDefinition: { enter: startDefinition, leave: () => void (current = null) },\n        FragmentDefinition: { enter: startDefinition, leave: () => void (current = null) },\n        SelectionSet: {\n          enter() {\n            if (current && ++depth > current.ownDepth) current.ownDepth = depth;\n          },\n          leave() {\n            if (current) depth--;\n          },\n        },\n        Field: {\n          enter() {\n            const parentType = context.getParentType();\n            const fieldDef = context.getFieldDef();\n            if (!current || !parentType || !fieldDef || fieldDef.name.startsWith('__')) return;\n            const coordinate = `${parentType.name}.${fieldDef.name}`;\n            current.fields.add(coordinate);\n            if (isListType(getNullableType(fieldDef.type))) current.listFields.add(coordinate);\n          },\n        },\n        FragmentSpread: {\n          enter(node) {\n            if (current) current.spreads.push({ name: node.name.value, depth });\n          },\n        },\n      },\n\n      collect() {\n        const fragments = context.getFragmentGraph();\n\n        // Transitive selection depth, expanding spreads (memoised, cycle-guarded).\n        const depthMemo = new Map<string, number>();\n        const effectiveDepth = (defId: string, visiting: Set<string>): number => {\n          const cached = depthMemo.get(defId);\n          if (cached != null) return cached;\n          const metrics = byDef.get(defId);\n          if (!metrics) return 0;\n          let result = metrics.ownDepth;\n          for (const spread of metrics.spreads) {\n            const fragmentId = fragments.resolve(metrics.schemaName, spread.name);\n            if (!fragmentId || visiting.has(fragmentId)) continue;\n            visiting.add(fragmentId);\n            result = Math.max(result, spread.depth - 1 + effectiveDepth(fragmentId, visiting));\n            visiting.delete(fragmentId);\n          }\n          depthMemo.set(defId, result);\n          return result;\n        };\n\n        const datapoints: RuleDatapoint<ComplexityData>[] = context.operations.map((op) => {\n          const fields = new Set<string>(byDef.get(op.id)?.fields);\n          const listFields = new Set<string>(byDef.get(op.id)?.listFields);\n          for (const fragmentId of fragments.reachableFragments(op.id)) {\n            const metrics = byDef.get(fragmentId);\n            if (!metrics) continue;\n            for (const coordinate of metrics.fields) fields.add(coordinate);\n            for (const coordinate of metrics.listFields) listFields.add(coordinate);\n          }\n          const operationDepth = effectiveDepth(op.id, new Set());\n          const score =\n            fields.size + operationDepth * operationDepth + listFields.size * LIST_WEIGHT;\n\n          return {\n            ref: { kind: 'operation', id: op.id },\n            message: `${op.name || '(anonymous)'}: depth ${operationDepth}, ${fields.size} fields (${listFields.size} list)`,\n            weight: score,\n            data: {\n              depth: operationDepth,\n              fieldCount: fields.size,\n              listFields: listFields.size,\n              fields: [...fields].sort(),\n              score,\n            },\n          };\n        });\n\n        return datapoints.sort((a, b) => b.data.score - a.data.score);\n      },\n    };\n  },\n};\n","import type { ScanRule } from '../types';\n\nexport interface FetchDepthData {\n  /** Shortest import-distance from an entry point to the defining module. */\n  depth: number | null;\n  area: string;\n  module: string;\n}\n\n/** Where each query sits in the module graph: how far its defining module is\n * from an entry point. As a distribution this describes data-fetching placement\n * (hoisted to route boundaries vs. scattered deep in the tree, i.e. waterfalls).\n *\n * Restricted to queries: mutations and subscriptions are naturally triggered\n * deep in the tree (event handlers, forms), so their depth carries no signal. */\nexport const fetchDepth: ScanRule<FetchDepthData> = {\n  name: 'fetch-depth',\n  description: 'Distance from an entry point to where each query is defined.',\n  create(context) {\n    // Reads the static module graph in collect(); no traversal state needed.\n    return {\n      visitor: {},\n      collect() {\n        const graph = context.getModuleGraph();\n        return context.operations\n          .filter((op) => op.kind === 'query')\n          .map((op) => {\n            const depth = graph.distanceFromEntry(op.module);\n            return { op, depth: depth ?? null };\n          })\n          .sort((a, b) => (b.depth ?? -1) - (a.depth ?? -1))\n          .map(({ op, depth }) => ({\n            ref: { kind: 'operation' as const, id: op.id },\n            message: `${op.name || '(anonymous)'} is ${\n              depth == null\n                ? 'unreachable from any entry point'\n                : `${depth} hop(s) from an entry point`\n            }`,\n            weight: depth ?? undefined,\n            data: { depth, area: graph.areaOf(op.module), module: op.module },\n          }));\n      },\n    };\n  },\n};\n","import type { ScanRule } from '../types';\n\nexport interface DirectiveUsageData {\n  count: number;\n}\n\n/** How often each directive is applied across all documents (e.g. `@skip`,\n * `@include`, `@defer`, `@_unmask`, custom client directives). Useful for\n * gauging adoption of directive-based features. */\nexport const directiveUsage: ScanRule<DirectiveUsageData> = {\n  name: 'directive-usage',\n  description: 'Application count per directive across documents.',\n  create() {\n    const counts = new Map<string, number>();\n    return {\n      visitor: {\n        Directive: {\n          enter(node) {\n            counts.set(node.name.value, (counts.get(node.name.value) || 0) + 1);\n          },\n        },\n      },\n      collect() {\n        return [...counts.entries()]\n          .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n          .map(([name, count]) => ({\n            ref: { kind: 'directive', name },\n            message: `@${name} applied ${count} time(s)`,\n            weight: count,\n            data: { count },\n          }));\n      },\n    };\n  },\n};\n","import type { ScanContext } from '../context';\nimport type { RuleResults } from '../types';\nimport { allSchemaFields } from '../schema-util';\n\nexport interface ScanOverview {\n  operations: number;\n  fragments: number;\n  modules: number;\n  operationsByKind: { query: number; mutation: number; subscription: number };\n  coverage: { usedFields: number; totalFields: number; percent: number };\n}\n\n/** Project-level totals, derived from the corpus, the schema, and the\n * field-usage rule. Shared so the JSON `overview` and the terminal header show\n * the same numbers. */\nexport function buildOverview(context: ScanContext, rules: RuleResults): ScanOverview {\n  const operationsByKind = { query: 0, mutation: 0, subscription: 0 };\n  for (const op of context.operations) operationsByKind[op.kind]++;\n\n  // field-usage emits one datapoint per used schema field.\n  const usedFields = (rules['field-usage'] || []).length;\n  const totalFields = allSchemaFields(context.getSchemas()).length;\n  const percent = totalFields ? Math.round((usedFields / totalFields) * 100) : 100;\n\n  return {\n    operations: context.operations.length,\n    fragments: context.fragments.length,\n    modules: context.modules.length,\n    operationsByKind,\n    coverage: { usedFields, totalFields, percent },\n  };\n}\n","import { isObjectType, isInterfaceType } from 'graphql';\nimport type { GraphQLSchema } from 'graphql';\n\nimport type { SchemaName } from './types';\n\nexport interface SchemaFieldInfo {\n  coordinate: string;\n  typeName: string;\n  fieldName: string;\n  fieldType: string;\n  deprecationReason?: string | undefined;\n}\n\n/** Enumerates every object/interface field across the schemas, deduped by\n * coordinate. A pure helper rules use to reconcile usage against the schema. */\nexport function allSchemaFields(schemas: Map<SchemaName, GraphQLSchema>): SchemaFieldInfo[] {\n  const seen = new Map<string, SchemaFieldInfo>();\n  for (const schema of schemas.values()) {\n    for (const type of Object.values(schema.getTypeMap())) {\n      if (type.name.startsWith('__')) continue;\n      if (!isObjectType(type) && !isInterfaceType(type)) continue;\n      for (const field of Object.values(type.getFields())) {\n        const coordinate = `${type.name}.${field.name}`;\n        if (!seen.has(coordinate)) {\n          seen.set(coordinate, {\n            coordinate,\n            typeName: type.name,\n            fieldName: field.name,\n            fieldType: String(field.type),\n            deprecationReason: field.deprecationReason ?? undefined,\n          });\n        }\n      }\n    }\n  }\n  return [...seen.values()];\n}\n","import type { ScanContext } from '../context';\nimport type { RuleResults, OperationInfo, FragmentInfo } from '../types';\nimport { buildOverview, type ScanOverview } from './overview';\n\nexport interface ScanJsonOutput {\n  version: number;\n  /** Project-level totals (same numbers the terminal header shows). */\n  overview: ScanOverview;\n  /** Discovered operations, with identity (kind, module, loc, variables, hash). */\n  operations: OperationInfo[];\n  /** Discovered fragments, with identity (type condition, module, loc, hash). */\n  fragments: FragmentInfo[];\n  /** Each rule's datapoints, keyed by rule name. */\n  rules: RuleResults;\n}\n\n/** Serialises the analysis result — overview, operation/fragment identities, and\n * the rule datapoints the terminal report renders — to the stable JSON\n * substrate. The relationship graph is emitted separately via `--graph`. */\nexport function renderJson(context: ScanContext, rules: RuleResults): string {\n  const output: ScanJsonOutput = {\n    version: 1,\n    overview: buildOverview(context, rules),\n    operations: [...context.operations],\n    fragments: [...context.fragments],\n    rules,\n  };\n  return JSON.stringify(output, null, 2) + '\\n';\n}\n","import * as path from 'node:path';\n\nimport type { ScanContext } from '../context';\nimport type { RuleResults, ScanGraph, ScanGraphNode, ScanGraphEdge, SchemaName } from '../types';\nimport type { FieldUsageData } from '../rules';\n\nconst CWD = process.cwd();\nconst relative = (modulePath: string): string => path.relative(CWD, modulePath) || modulePath;\n\nconst moduleNodeId = (modulePath: string): string => `module:${modulePath}`;\nconst fieldNodeId = (coordinate: string): string => `field:${coordinate}`;\nconst typeNodeId = (typeName: string): string => `type:${typeName}`;\nconst fragmentKey = (schemaName: SchemaName, name: string): string =>\n  `${schemaName ?? ''}\\0${name}`;\n\n/** Serialises the pure relationship graph (emitted via `--graph`). */\nexport function renderGraph(context: ScanContext, rules: RuleResults): string {\n  return JSON.stringify(buildGraph(context, rules), null, 2) + '\\n';\n}\n\n/** Composes the module ↔ document ↔ fragment ↔ schema relationship graph from\n * the corpus (identities, spreads, imports) and the field-usage rule (the\n * field selections). A derived view assembled at output time. */\nexport function buildGraph(context: ScanContext, rules: RuleResults): ScanGraph {\n  const nodes = new Map<string, ScanGraphNode>();\n  const edges: ScanGraphEdge[] = [];\n  const addNode = (node: ScanGraphNode): void => {\n    if (!nodes.has(node.id)) nodes.set(node.id, node);\n  };\n\n  const fragmentIdByName = new Map<string, string>();\n  for (const fragment of context.fragments) {\n    fragmentIdByName.set(fragmentKey(fragment.schemaName, fragment.name), fragment.id);\n  }\n\n  const moduleNode = (modulePath: string): void => {\n    addNode({ id: moduleNodeId(modulePath), kind: 'module', label: relative(modulePath) });\n  };\n\n  // The full project import graph (not just GraphQL-bearing modules), so the\n  // emitted `imports` edges match what reachability/fetch-depth actually use.\n  for (const [from, tos] of context.getModuleGraph().importMap()) {\n    moduleNode(from);\n    for (const target of tos) {\n      moduleNode(target);\n      edges.push({ from: moduleNodeId(from), to: moduleNodeId(target), kind: 'imports' });\n    }\n  }\n\n  // Schema field/type nodes + `selects` edges come from the field-usage rule\n  // (which only indexes used fields, so the graph is bounded to what's used).\n  for (const datapoint of rules['field-usage'] || []) {\n    if (datapoint.ref.kind !== 'field') continue;\n    const coordinate = datapoint.ref.coordinate;\n    const usage = datapoint.data as FieldUsageData;\n    addNode({ id: fieldNodeId(coordinate), kind: 'schemaField', label: coordinate });\n    addNode({ id: typeNodeId(usage.typeName), kind: 'schemaType', label: usage.typeName });\n    edges.push({ from: fieldNodeId(coordinate), to: typeNodeId(usage.typeName), kind: 'onType' });\n    for (const site of usage.directUsages) {\n      edges.push({ from: site.defId, to: fieldNodeId(coordinate), kind: 'selects' });\n    }\n  }\n\n  const addDefinition = (\n    id: string,\n    kind: 'operation' | 'fragment',\n    label: string,\n    module: string,\n    spreads: readonly string[],\n    schemaName: SchemaName\n  ): void => {\n    addNode({ id, kind, label });\n    moduleNode(module); // ensure the defining module is a node even if it has no imports\n    edges.push({ from: moduleNodeId(module), to: id, kind: 'defines' });\n    for (const spreadName of spreads) {\n      const target = fragmentIdByName.get(fragmentKey(schemaName, spreadName));\n      if (target) edges.push({ from: id, to: target, kind: 'spreads' });\n    }\n  };\n\n  for (const op of context.operations) {\n    addDefinition(\n      op.id,\n      'operation',\n      op.name || '(anonymous)',\n      op.module,\n      op.fragmentSpreads,\n      op.schemaName\n    );\n  }\n  for (const fragment of context.fragments) {\n    addDefinition(\n      fragment.id,\n      'fragment',\n      fragment.name,\n      fragment.module,\n      fragment.fragmentSpreads,\n      fragment.schemaName\n    );\n  }\n\n  return { nodes: [...nodes.values()], edges };\n}\n","import * as path from 'node:path';\nimport * as t from '../../../term';\n\nimport type { ScanContext } from '../context';\nimport type { RuleResults, DatapointRef } from '../types';\nimport { DEFAULT_RULES } from '../rules';\nimport { buildOverview } from './overview';\n\nconst CWD = process.cwd();\n/** Maximum datapoints shown per rule in the terminal report. */\nconst MAX_PER_RULE = 8;\n/** Below this many columns left for the message, the locator is dropped first. */\nconst MIN_MESSAGE_WIDTH = 24;\n\nconst RULE_DESCRIPTIONS = new Map(DEFAULT_RULES.map((rule) => [rule.name, rule.description]));\n\nconst truncate = (text: string, max: number): string =>\n  text.length <= max\n    ? text\n    : max > 1\n      ? text.slice(0, max - 1) + t.Chars.Ellipsis\n      : t.Chars.Ellipsis;\n\nconst relative = (filePath: string): string => {\n  const rel = path.relative(CWD, filePath);\n  return !rel.startsWith('..') ? rel : filePath;\n};\n\n/** Resolves a datapoint's `ref` to a short `file:line` locator, where one exists. */\nfunction locator(ref: DatapointRef, context: ScanContext): string | undefined {\n  switch (ref.kind) {\n    case 'operation': {\n      const op = context.operations.find((item) => item.id === ref.id);\n      return op ? `${relative(op.loc.file)}:${op.loc.line}` : undefined;\n    }\n    case 'fragment': {\n      const fragment = context.fragments.find((item) => item.id === ref.id);\n      return fragment ? `${relative(fragment.loc.file)}:${fragment.loc.line}` : undefined;\n    }\n    default:\n      return undefined;\n  }\n}\n\nfunction coverageLine(context: ScanContext, rules: RuleResults): string {\n  const { usedFields, totalFields, percent } = buildOverview(context, rules).coverage;\n  return t.text([\n    t.cmd(t.CSI.Style, t.Style.Foreground),\n    'Schema coverage: ',\n    t.cmd(t.CSI.Style, t.Style.BrightBlue),\n    `${percent}% `,\n    t.cmd(t.CSI.Style, t.Style.BrightBlack),\n    `(${usedFields}/${totalFields} fields used)\\n`,\n  ]);\n}\n\n/** Renders the default human-facing report: coverage plus the top datapoints of\n * each rule that produced findings. `width` (terminal columns) bounds each item\n * line so it doesn't wrap; omit it for unbounded output. */\nexport function renderTerminalReport(\n  context: ScanContext,\n  rules: RuleResults,\n  width?: number\n): string {\n  let out = '\\n' + coverageLine(context, rules);\n\n  for (const [name, datapoints] of Object.entries(rules)) {\n    if (!datapoints.length) continue;\n\n    out += t.text([\n      '\\n',\n      t.cmd(t.CSI.Style, t.Style.Magenta),\n      `${t.SmallTriangle.Right} `,\n      t.cmd(t.CSI.Style, t.Style.Foreground),\n      name,\n      t.cmd(t.CSI.Style, t.Style.BrightBlack),\n      ` (${datapoints.length})\\n`,\n    ]);\n\n    const description = RULE_DESCRIPTIONS.get(name);\n    if (description) {\n      const text = width ? truncate(description, Math.max(width - 2, 1)) : description;\n      out += t.text([t.cmd(t.CSI.Style, t.Style.BrightBlack), `  ${text}\\n`]);\n    }\n\n    const shown = datapoints.slice(0, MAX_PER_RULE);\n    const truncated = datapoints.length > shown.length;\n    // \"  \" + connector + \" \"\n    const prefixWidth = 4;\n    shown.forEach((datapoint, index) => {\n      const isLast = !truncated && index === shown.length - 1;\n      const weightText = datapoint.weight != null ? `~${datapoint.weight}` : '';\n      let message = datapoint.message;\n      let locText = locator(datapoint.ref, context);\n\n      if (width) {\n        const weightWidth = weightText ? weightText.length + 2 : 0;\n        let locWidth = locText ? locText.length + 2 : 0;\n        let budget = width - prefixWidth - weightWidth - locWidth;\n        // Too cramped for the message — drop the (long) locator before the message.\n        if (locText && budget < MIN_MESSAGE_WIDTH) {\n          budget += locWidth;\n          locText = undefined;\n          locWidth = 0;\n        }\n        message = truncate(message, Math.max(budget, 1));\n      }\n\n      out += t.text([\n        t.cmd(t.CSI.Style, t.Style.BrightBlack),\n        `  ${isLast ? t.Box.BottomLeft : t.Box.VerticalRight} `,\n        t.cmd(t.CSI.Style, t.Style.Foreground),\n        message,\n        ...(weightText ? [t.cmd(t.CSI.Style, t.Style.BrightBlue), `  ${weightText}`] : []),\n        ...(locText ? [t.cmd(t.CSI.Style, t.Style.BrightBlack), `  ${locText}`] : []),\n        '\\n',\n      ]);\n    });\n\n    if (truncated) {\n      out += t.text([\n        t.cmd(t.CSI.Style, t.Style.BrightBlack),\n        `  ${t.Box.BottomLeft} ${t.Chars.Ellipsis} and ${datapoints.length - shown.length} more\\n`,\n      ]);\n    }\n  }\n\n  return out;\n}\n","import { pipe, interval, map, concat, fromValue } from 'wonka';\n\nimport * as path from 'node:path';\nimport * as t from '../../term';\n\nimport type { ScanWarning } 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: ScanWarning) {\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\nexport function warningGithub(message: ScanWarning): void {\n  t.githubAnnotation('warning', message.message, {\n    file: message.file,\n    line: message.line,\n    col: message.col,\n  });\n}\n\nexport function runningScan(file?: number, ofFiles?: number) {\n  const progress = file ? (ofFiles ? `(${file}/${ofFiles})` : `(${file})`) : '';\n  const frame = (state: number) =>\n    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  return concat([\n    fromValue(frame(0)),\n    pipe(\n      interval(150),\n      map((state) => frame(state + 1))\n    ),\n  ]);\n}\n\nexport function summary(args: {\n  warnings: number;\n  operations: number;\n  fragments: number;\n  modules: number;\n}) {\n  let out = '\\n';\n  if (args.warnings) {\n    out += t.text([\n      t.cmd(t.CSI.Style, t.Style.BrightYellow),\n      t.Icons.Warning,\n      ` ${args.warnings} warnings\\n`,\n    ]);\n  }\n  out += t.text([\n    t.cmd(t.CSI.Style, t.Style.BrightGreen),\n    `${t.Icons.Tick} Scan completed `,\n    t.cmd(t.CSI.Style, t.Style.BrightBlack),\n    `(${args.operations} operations, ${args.fragments} fragments across ${args.modules} modules)\\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 wroteOutput(label: string, filePath: string) {\n  const relativePath = path.relative(CWD, filePath);\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    `Wrote ${label} to `,\n    t.cmd(t.CSI.Style, t.Style.Blue),\n    `${!relativePath.startsWith('..') ? relativePath : filePath}\\n`,\n  ]);\n}\n","import * as path from 'node:path';\nimport type { GraphQLSchema } from 'graphql';\nimport { loadRef } from '@gql.tada/internal';\n\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext, WriteTarget } from '../shared';\nimport { loadProjects, writeOutput } from '../shared';\n\nimport type { SchemaName, RawScanDocument, ScanWarning } from './types';\nimport { analyze } from './analyze';\nimport { renderJson } from './output/json';\nimport { renderGraph } from './output/graph';\nimport { renderTerminalReport } from './output/terminal';\nimport * as logger from './logger';\n\nexport type ScanFormat = 'json';\n\nexport interface ScanOptions {\n  /** The `tsconfig.json` to use for configurations and the TypeScript program. */\n  tsconfig: string | undefined;\n  /** When `json`, write the JSON report; otherwise show the terminal report. */\n  format: ScanFormat | undefined;\n  /** When set, output the pure relationship graph (implies machine output). */\n  graph: boolean;\n  /** Where to write machine output to. Defaults to standard output. */\n  output: string | undefined;\n  /** Whether to fail with a non-zero exit code if any warnings are reported. */\n  failOnWarn: boolean;\n}\n\nasync function loadSchemas(project: ProjectContext): Promise<Map<SchemaName, GraphQLSchema>> {\n  const ref = await loadRef(project.pluginConfig).load({ rootPath: project.projectPath });\n  const schemas = new Map<SchemaName, GraphQLSchema>();\n  if (ref.current) schemas.set(null, ref.current.schema);\n  for (const name in ref.multi) {\n    const result = ref.multi[name];\n    if (result) schemas.set(name, result.schema);\n  }\n  return schemas;\n}\n\nexport async function* run(tty: TTY, opts: ScanOptions): AsyncIterable<ComposeInput> {\n  if (opts.format && opts.format !== 'json') {\n    throw logger.errorMessage(\n      `Unknown ${logger.code('--format')} '${opts.format}'.\\n` +\n        logger.hint(`The only supported format is ${logger.code('json')}.`)\n    );\n  }\n\n  let projects: ProjectContext[];\n  try {\n    projects = await loadProjects(opts.tsconfig);\n  } catch (error) {\n    throw logger.externalError('Failed to load configuration.', error);\n  }\n\n  // Machine output goes to a single destination, so it can't span projects.\n  if (projects.length > 1 && (opts.format || opts.graph)) {\n    throw logger.errorMessage(\n      'Machine output can only target a single project.\\n' +\n        logger.hint(`Run scan per-project with an explicit ${logger.code('--tsconfig')}.`)\n    );\n  }\n\n  let totalWarnings = 0;\n  for (const project of projects) {\n    if (projects.length > 1) yield logger.projectHeader(project.label);\n    totalWarnings += yield* runProject(tty, opts, project);\n  }\n\n  if (opts.failOnWarn && totalWarnings) {\n    throw logger.warningSummary(totalWarnings);\n  }\n}\n\nasync function* runProject(\n  tty: TTY,\n  opts: ScanOptions,\n  project: ProjectContext\n): AsyncGenerator<ComposeInput, number> {\n  const { runScan } = await import('./thread');\n\n  // `--graph` implies machine output (the pure relationship graph).\n  const machine = !!opts.format || opts.graph;\n  // When machine output shares the (single) stdout stream, human chatter would\n  // corrupt it — so suppress progress/warnings/summary in that case.\n  const quiet = machine && !opts.output && !tty.pipeTo;\n\n  let schemas: Map<SchemaName, GraphQLSchema>;\n  try {\n    schemas = await loadSchemas(project);\n  } catch (error) {\n    throw logger.externalError('Failed to load schema.', error);\n  }\n\n  const generator = runScan({\n    rootPath: project.configResult.rootPath,\n    tsconfigPath: project.configResult.tsconfigPath,\n    configPath: project.configResult.configPath,\n    pluginConfig: project.pluginConfig,\n  });\n\n  const documents: RawScanDocument[] = [];\n  const imports = new Map<string, string[]>();\n  const warnings: ScanWarning[] = [];\n  let totalFileCount = 0;\n  let fileCount = 0;\n\n  try {\n    if (tty.isInteractive && !quiet) yield logger.runningScan();\n\n    for await (const signal of generator) {\n      if (signal.kind === 'EXTERNAL_WARNING') {\n        if (!quiet) {\n          yield logger.experimentMessage(\n            `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n          );\n        }\n      } else if (signal.kind === 'FILE_COUNT') {\n        totalFileCount = signal.fileCount;\n      } else {\n        fileCount++;\n        documents.push(...signal.documents);\n        if (signal.imports.length) imports.set(signal.filePath, signal.imports);\n        if (signal.warnings.length) {\n          warnings.push(...signal.warnings);\n          if (!quiet) {\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\n      if (tty.isInteractive && !quiet) yield logger.runningScan(fileCount, totalFileCount);\n    }\n  } catch (error) {\n    throw logger.externalError('Could not scan files', error);\n  }\n\n  // Both outputs render from the same analysis result (the rule datapoints, plus\n  // the context's identities for resolving locators).\n  const { context, rules } = analyze({ documents, schemas, imports, warnings });\n\n  if (machine) {\n    const label = opts.graph ? 'graph' : 'JSON report';\n    const render = opts.graph ? renderGraph : renderJson;\n    // Default to stdout; `--output` writes a file instead.\n    const destination: WriteTarget = opts.output\n      ? path.resolve(process.cwd(), opts.output)\n      : (tty.pipeTo ?? process.stdout);\n    try {\n      await writeOutput(destination, render(context, rules));\n    } catch (error) {\n      throw logger.externalError(`Something went wrong while writing the ${label}`, error);\n    }\n    if (!quiet && typeof destination === 'string') {\n      yield logger.wroteOutput(label, destination);\n    }\n  } else {\n    // Bound item lines to the terminal width so they don't wrap; unbounded when\n    // not writing to an interactive terminal.\n    const width = tty.isInteractive ? tty.output.columns || 80 : undefined;\n    yield renderTerminalReport(context, rules, width);\n  }\n\n  if (!quiet) {\n    yield logger.summary({\n      warnings: context.warnings.length,\n      operations: context.operations.length,\n      fragments: context.fragments.length,\n      modules: context.modules.length,\n    });\n  }\n\n  return context.warnings.length;\n}\n","import { visit, visitInParallel, visitWithTypeInfo, TypeInfo, Kind } from 'graphql';\nimport type { DocumentNode } from 'graphql';\n\nimport { ScanContext } from './context';\nimport type { ScanContextParams } from './context';\nimport { DEFAULT_RULES } from './rules';\nimport type { ScanRule, RuleResults } from './types';\n\nexport interface ScanAnalysis {\n  context: ScanContext;\n  rules: RuleResults;\n}\n\n/**\n * Runs the analysis: builds the context (corpus + primitives), then walks every\n * definition once per schema with all rule visitors merged in parallel —\n * mirroring graphql-js `validate`. Each rule accumulates its own state during\n * the traversal and converts it to datapoints in `collect()`.\n */\nexport function analyze(\n  params: ScanContextParams,\n  rules: ScanRule[] = DEFAULT_RULES\n): ScanAnalysis {\n  const context = new ScanContext(params);\n  const instances = rules.map((rule) => ({ name: rule.name, instance: rule.create(context) }));\n\n  for (const [schemaName, schema] of context.getSchemas()) {\n    const definitions = context.definitionNodesForSchema(schemaName);\n    if (!definitions.length) continue;\n\n    const typeInfo = new TypeInfo(schema);\n    context.setTypeInfo(typeInfo);\n\n    // A fresh `visitInParallel` per schema (its skip-state is per-call), but the\n    // same rule instances, so their accumulated state carries across schemas.\n    const visitor = visitInParallel([\n      context.trackingVisitor(),\n      ...instances.map(({ instance }) => instance.visitor),\n    ]);\n\n    const document: DocumentNode = { kind: Kind.DOCUMENT, definitions };\n    visit(document, visitWithTypeInfo(typeInfo, visitor));\n  }\n\n  const results: RuleResults = {};\n  for (const { name, instance } of instances) results[name] = instance.collect();\n  return { context, rules: results };\n}\n","import { Command, Option } from 'clipanion';\n\nimport type { ScanOptions, ScanFormat } from './runner';\nimport { exitCode } from '../../utils/error';\nimport { initTTY } from '../../term';\nimport { run } from './runner';\n\nexport class ScanCommand extends Command {\n  static paths = [['scan']];\n\n  tsconfig = Option.String('--tsconfig,-c', {\n    description: 'Specify the `tsconfig.json` read for configuration.',\n  });\n\n  format = Option.String('--format,-f', {\n    description: 'Emit the machine-readable `json` report.\\tDefault: a terminal report',\n  });\n\n  graph = Option.Boolean('--graph', false, {\n    description: 'Emit only the relationship graph as JSON (implies machine output).',\n  });\n\n  output = Option.String('--output,-o', {\n    description: 'Write machine output to this file.\\tDefault: standard output',\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  async execute() {\n    const tty = initTTY();\n    const result = await tty.start(\n      run(tty, {\n        tsconfig: this.tsconfig,\n        format: this.format as ScanFormat | undefined,\n        graph: this.graph,\n        output: this.output,\n        failOnWarn: this.failOnWarn,\n      })\n    );\n    return exitCode() || (typeof result === 'object' ? result.exit : 0);\n  }\n}\n\n/** Scans a project for all GraphQL documents and fragments, keys them to the\n * schema, and emits a JSON report (when piped or given `--output`) or a\n * human-readable terminal report.\n *\n * @see {@link https://gql-tada.0no.co/reference/gql-tada-cli#scan}\n */\nexport async function scan(opts: ScanOptions) {\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, concat, fromValue } 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  const frame = (state: number) =>\n    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  return concat([\n    fromValue(frame(0)),\n    pipe(\n      interval(150),\n      map((state) => frame(state + 1))\n    ),\n  ]);\n}\n","import * as logger from './logger';\nimport type { TTY, ComposeInput } from '../../term';\nimport type { ProjectContext } from '../shared';\nimport { loadProjects } from '../shared';\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 projects: ProjectContext[];\n  try {\n    projects = await loadProjects(opts.tsconfig);\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  let warnedAboutExternalFiles = false;\n\n  for (const project of projects) {\n    if (projects.length > 1) yield logger.projectHeader(project.label);\n\n    const generator = runDiagnostics({\n      rootPath: project.configResult.rootPath,\n      tsconfigPath: project.configResult.tsconfigPath,\n      configPath: project.configResult.configPath,\n      pluginConfig: project.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          if (!warnedAboutExternalFiles) {\n            warnedAboutExternalFiles = true;\n            yield logger.experimentMessage(\n              `${logger.code('.vue')} and ${logger.code('.svelte')} file support is experimental.`\n            );\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\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): T;\nfunction maybeBind(that: object, fn: undefined): undefined;\nfunction maybeBind<T extends Function>(that: object, fn: T | undefined): T | undefined {\n  return fn ? (fn.bind(that) as T) : undefined;\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  documentRegistry?: ts.DocumentRegistry;\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      documentRegistry: params.documentRegistry,\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  documentRegistry?: ts.DocumentRegistry;\n}): ts.LanguageService => {\n  const { virtualMap } = params;\n  const languageService = ts.createLanguageService(\n    params.languageServiceHost,\n    params.documentRegistry\n  );\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  tsconfigPath?: 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 wasOriginallyNodeNext: boolean;\n  readonly projectDirectories: readonly string[];\n  readonly rootFileNames: readonly string[];\n\n  createSourceFile(params: SourceFileParams, scriptKind?: ts.ScriptKind): ts.SourceFile;\n  createExternalFiles(exts?: readonly VirtualExtension[]): readonly ts.SourceFile[];\n\n  addSourceFile(file: SourceFileParams | ts.SourceFile): this;\n  addMappedFile(file: SourceFileParams | ts.SourceFile, params: MappedFileParams): this;\n\n  addVirtualFiles(files: readonly ts.SourceFile[]): Promise<this>;\n\n  resolveModulePath(importSpecifier: string, fromPath: string): string | undefined;\n  resolveModuleName(importSpecifier: string, fromPath: string, toPath: string): string;\n\n  build(): ProgramContainer;\n}\n\n/** Bumps the Error stack traces to a length of 25 for better debugging. */\nconst bumpStackTraceLimit = () => {\n  if ('stackTraceLimit' in Error && Error.stackTraceLimit < 25) {\n    Error.stackTraceLimit = 25;\n  }\n};\n\nexport const programFactory = (params: ProgramFactoryParams): ProgramFactory => {\n  const vfsMap = new Map<string, string>();\n  const virtualMap: VirtualMap = new Map();\n\n  const system = createFSBackedSystem(vfsMap, params.rootPath, ts, resolveDefaultLibsPath(params));\n  const config = resolveConfig(params);\n\n  const rootNames = new Set(config.fileNames);\n  const options: ts.CompilerOptions = {\n    ...ts.getDefaultCompilerOptions(),\n    getDefaultLibFilePath: ts.getDefaultLibFilePath(config.options),\n    noCheck: true,\n    ...config.options,\n  };\n\n  let orignallyNodeNext = false;\n  // NOTE: Using \"NodeNext\" instead of \"Bundler\" is almost always a mistake\n  // this should be revisited in the next major version.\n  if (\n    'Bundler' in ts.ModuleResolutionKind &&\n    (options.moduleResolution === ts.ModuleResolutionKind.NodeNext ||\n      options.moduleResolution === ts.ModuleResolutionKind.Node16)\n  ) {\n    orignallyNodeNext = true;\n    options.moduleResolution = ts.ModuleResolutionKind.Bundler;\n  }\n\n  const host = createVirtualCompilerHost(system, options, ts);\n  const documentRegistry = ts.createDocumentRegistry();\n\n  const factory: ProgramFactory = {\n    get projectPath() {\n      return params.rootPath;\n    },\n\n    get wasOriginallyNodeNext() {\n      return orignallyNodeNext;\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    get rootFileNames() {\n      return [...rootNames];\n    },\n\n    createSourceFile(params, scriptKind) {\n      return ts.createSourceFile(\n        params.fileId,\n        typeof params.sourceText === 'object'\n          ? params.sourceText.getText(0, params.sourceText.getLength())\n          : params.sourceText,\n        options.target || ts.ScriptTarget.ESNext,\n        /*setParentNodes*/ true,\n        scriptKind || (params.scriptKind != null ? params.scriptKind : ts.ScriptKind.TSX)\n      );\n    },\n\n    createExternalFiles(exts: readonly VirtualExtension[] = transformExtensions) {\n      const files: ts.SourceFile[] = [];\n      const seen = new Set(rootNames);\n      const directories = new Set([params.rootPath]);\n      for (const rootName of rootNames) directories.add(path.dirname(rootName));\n      for (const directory of directories) {\n        for (const fileId of system.readDirectory(directory, exts, ['**/node_modules'])) {\n          if (!seen.has(fileId)) {\n            seen.add(fileId);\n            const contents = system.readFile(fileId, 'utf8');\n            if (contents) {\n              files.push(\n                factory.createSourceFile(\n                  {\n                    fileId,\n                    sourceText: contents,\n                  },\n                  ts.ScriptKind.External\n                )\n              );\n            }\n          }\n        }\n      }\n      return files;\n    },\n\n    addSourceFile(input) {\n      const sourceFile =\n        'fileName' in input ? input : factory.createSourceFile(input, ts.ScriptKind.TSX);\n      host.updateFile(sourceFile);\n      rootNames.add(sourceFile.fileName);\n      return factory;\n    },\n\n    addMappedFile(input, params) {\n      const sourceFile =\n        'fileName' in input ? input : factory.createSourceFile(input, ts.ScriptKind.External);\n      if (params.mappings.length) rootNames.delete(sourceFile.fileName);\n      const sourceMappedFile = new SourceMappedFile(params.mappings, {\n        sourceFile,\n        sourceFileId: sourceFile.fileName,\n        generatedFileId: params.fileId,\n      });\n      virtualMap.set(sourceMappedFile.sourceFileId, sourceMappedFile);\n      virtualMap.set(sourceMappedFile.generatedFileId, sourceMappedFile);\n      return factory;\n    },\n\n    async addVirtualFiles(sourceFiles) {\n      for (const sourceFile of sourceFiles) {\n        const virtualFileId = `${sourceFile.fileName}.ts`;\n        const virtualCode = await transform(sourceFile);\n        if (virtualCode) {\n          factory\n            .addSourceFile({\n              fileId: virtualFileId,\n              sourceText: virtualCode.snapshot,\n            })\n            .addMappedFile(sourceFile, {\n              mappings: virtualCode.mappings,\n              fileId: virtualFileId,\n            });\n        }\n      }\n      return factory;\n    },\n\n    resolveModulePath(importSpecifier: string, fromPath: string): string | undefined {\n      const resolved = ts.resolveModuleName(importSpecifier, fromPath, options, host.compilerHost);\n\n      return resolved.resolvedModule?.resolvedFileName;\n    },\n\n    resolveModuleName(importSpecifier: string, fromPath: string, toPath: string): string {\n      // For absolute imports (including path-mapped ones), keep them as-is\n      // TypeScript's module resolution will handle them correctly\n      if (!importSpecifier.startsWith('.')) {\n        return importSpecifier;\n      }\n\n      // For relative imports, we need to adjust the path using the virtual compiler host\n      // First, resolve the import from the original location to get the actual file\n      const resolvedFileName = factory.resolveModulePath(importSpecifier, fromPath);\n\n      if (resolvedFileName) {\n        // Now create a relative path from the new location (toPath) to the target\n        const fromDir = path.dirname(toPath);\n        let relativePath = path.relative(fromDir, resolvedFileName);\n\n        // Ensure it starts with ./ or ../\n        if (!relativePath.startsWith('.')) {\n          relativePath = './' + relativePath;\n        }\n\n        // Convert Windows backslashes to forward slashes for imports\n        return relativePath.replace(/\\\\/g, '/');\n      }\n\n      // Fallback to simple path resolution if TypeScript resolution fails\n      const fromDir = path.dirname(fromPath);\n      const toDir = path.dirname(toPath);\n\n      const absoluteImportPath = path.resolve(fromDir, importSpecifier);\n      let relativeImportPath = path.relative(toDir, absoluteImportPath);\n\n      // Ensure it starts with ./ if it's a relative path\n      if (!relativeImportPath.startsWith('.')) {\n        relativeImportPath = './' + relativeImportPath;\n      }\n\n      // Convert Windows backslashes to forward slashes for imports\n      return relativeImportPath.replace(/\\\\/g, '/');\n    },\n\n    build() {\n      bumpStackTraceLimit();\n\n      // NOTE: This is necessary for `@0no-co/graphqlsp/api` to use the right instance\n      // of the typescript library\n      init({ typescript: ts });\n\n      return buildContainer({\n        virtualMap,\n        projectRoot: params.rootPath,\n        compilerHost: host.compilerHost,\n        rootNames: [...rootNames],\n        options,\n        system,\n        documentRegistry,\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): ts.ParsedCommandLine => {\n  const configPath = params.tsconfigPath || params.configPath;\n  const text = ts.sys.readFile(configPath, 'utf8') || '{}';\n  const parseResult = ts.parseConfigFileTextToJson(configPath, text);\n  if (parseResult.error != null) throw new Error(parseResult.error.messageText.toString());\n  const projectRoot = path.dirname(configPath);\n  return ts.parseJsonConfigFileContent(\n    parseResult.config,\n    ts.sys,\n    projectRoot,\n    ts.getDefaultCompilerOptions(),\n    configPath\n  );\n};\n","import * as fs from 'node:fs/promises';\n\nexport const enum FileType {\n  File,\n  Directory,\n}\n\nexport const stat = async (file: string, type = FileType.File): Promise<boolean> =>\n  await fs\n    .stat(file)\n    .then((stat) => {\n      switch (type) {\n        case FileType.File:\n          return stat.isFile();\n        case FileType.Directory:\n          return stat.isDirectory();\n      }\n    })\n    .catch(() => false);\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport { stat, FileType } from './fs';\nimport { findWorkspaceRoot } from './workspaceRoot';\n\nconst configFileRe = /^(?:graphql\\.config|\\.graphqlrc)\\.(?:cjs|[jt]s|json|toml|ya?ml)$/i;\n\n/** Loads list of suggested in-repo VSCode extensions */\nexport const findGraphQLConfig = async (targetPath?: string): Promise<string | null> => {\n  let target = targetPath || process.cwd();\n  const rootPath = path.resolve(target, '/');\n  while (target !== rootPath) {\n    let dir: readonly string[] = [];\n    try {\n      dir = await fs.readdir(target);\n    } catch (_error) {}\n    const configFile = dir.find((item) => configFileRe.test(item));\n    if (configFile) return configFile;\n    if (await stat(path.resolve(target, '.git'), FileType.Directory)) {\n      break;\n    } else if (await stat(path.resolve(target, '.vscode'), FileType.Directory)) {\n      break;\n    }\n    target = path.resolve(target, '..');\n  }\n\n  const workspaceRoot = await findWorkspaceRoot(targetPath);\n  if (workspaceRoot) {\n    const packageJsonPath = path.resolve(workspaceRoot, 'package.json');\n    if (await stat(packageJsonPath)) {\n      try {\n        const meta = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));\n        if (\n          meta &&\n          typeof meta === 'object' &&\n          'graphql' in meta &&\n          meta.graphql &&\n          typeof meta.graphql === 'object'\n        ) {\n          return packageJsonPath;\n        }\n      } catch (_error) {}\n    }\n  }\n\n  return null;\n};\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { stat, FileType } from './fs';\n\nexport const findWorkspaceRoot = async (targetPath?: string): Promise<string | null> => {\n  let target = targetPath || process.cwd();\n  const rootPath = path.resolve(target, '/');\n  while (target !== rootPath) {\n    if (await stat(path.resolve(target, '.git'), FileType.Directory)) {\n      return target;\n    } else if (await stat(path.resolve(target, '.vscode'), FileType.Directory)) {\n      return target;\n    } else if (await stat(path.resolve(target, 'pnpm-workspace.yml'))) {\n      return target;\n    }\n    const packageJsonPath = path.resolve(target, 'package.json');\n    if (await stat(packageJsonPath)) {\n      try {\n        const meta = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));\n        if (meta && typeof meta === 'object' && Array.isArray(meta.workspaces)) {\n          return target;\n        }\n      } catch (_error) {}\n    }\n    target = path.resolve(target, '..');\n  }\n  return null;\n};\n","/**\n * Version resolution utilities with support for workspace catalogs.\n *\n * Supports catalog-based dependency management for:\n * - pnpm (pnpm-workspace.yaml format)\n * - bun (package.json workspaces format)\n *\n * Catalog references follow the format:\n * - \"catalog:\" for default catalog\n * - \"catalog:name\" for named catalogs\n */\n\nimport { createRequire } from 'node:module';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nexport interface PackageJson {\n  name?: string;\n  dependencies?: Record<string, string>;\n  devDependencies?: Record<string, string>;\n}\n\nexport interface WorkspaceConfig {\n  packages?: string[];\n  catalog?: Record<string, string>;\n  catalogs?: Record<string, Record<string, string>>;\n}\n\nexport interface PnpmWorkspaceConfig extends WorkspaceConfig {\n  // Inherits from WorkspaceConfig - supports pnpm-workspace.yaml format\n}\n\nexport interface BunWorkspaceConfig extends WorkspaceConfig {\n  // Inherits from WorkspaceConfig - supports package.json workspaces format\n}\n\nconst parseYaml = (content: string): PnpmWorkspaceConfig => {\n  const lines = content.split('\\n');\n  const result: PnpmWorkspaceConfig = {};\n  let currentSection: string | null = null;\n  let currentCatalog: string | null = null;\n\n  for (const line of lines) {\n    const trimmed = line.trim();\n    if (!trimmed || trimmed.startsWith('#')) continue;\n\n    if (trimmed.endsWith(':') && !trimmed.includes(' ')) {\n      const key = trimmed.slice(0, -1).replace(/['\"]/g, '');\n      if (key === 'packages') {\n        currentSection = 'packages';\n        result.packages = [];\n      } else if (key === 'catalog') {\n        currentSection = 'catalog';\n        result.catalog = {};\n      } else if (key === 'catalogs') {\n        currentSection = 'catalogs';\n        result.catalogs = {};\n      } else if (currentSection === 'catalogs') {\n        currentCatalog = key;\n        result.catalogs![key] = {};\n      }\n    } else if (trimmed.startsWith('- ')) {\n      if (currentSection === 'packages') {\n        result.packages!.push(trimmed.slice(2).replace(/['\"]/g, ''));\n      }\n    } else if (trimmed.includes(':')) {\n      const colonIndex = trimmed.indexOf(':');\n      const key = trimmed.slice(0, colonIndex).trim().replace(/['\"]/g, '');\n      const value = trimmed\n        .slice(colonIndex + 1)\n        .trim()\n        .replace(/['\"]/g, '');\n\n      if (currentSection === 'catalog') {\n        result.catalog![key] = value;\n      } else if (currentSection === 'catalogs' && currentCatalog) {\n        result.catalogs![currentCatalog][key] = value;\n      }\n    }\n  }\n\n  return result;\n};\n\nconst findPnpmWorkspaceroot = async (startPath: string = process.cwd()): Promise<string | null> => {\n  let currentPath = startPath;\n  const root = path.parse(currentPath).root;\n\n  while (currentPath !== root) {\n    const workspaceFile = path.join(currentPath, 'pnpm-workspace.yaml');\n    try {\n      await fs.access(workspaceFile);\n      return currentPath;\n    } catch {\n      // File doesn't exist, continue searching\n    }\n    currentPath = path.dirname(currentPath);\n  }\n\n  return null;\n};\n\nconst findBunWorkspaceRoot = async (startPath: string = process.cwd()): Promise<string | null> => {\n  let currentPath = startPath;\n  const root = path.parse(currentPath).root;\n\n  while (currentPath !== root) {\n    const packageJsonFile = path.join(currentPath, 'package.json');\n    try {\n      await fs.access(packageJsonFile);\n      const content = await fs.readFile(packageJsonFile, 'utf-8');\n      const packageJson: PackageJson & { workspaces?: any } = JSON.parse(content);\n\n      // Check if this package.json has workspaces with catalog/catalogs\n      // Bun stores catalogs in workspaces.catalog and workspaces.catalogs\n      if (\n        packageJson.workspaces &&\n        (packageJson.workspaces.catalog || packageJson.workspaces.catalogs)\n      ) {\n        return currentPath;\n      }\n    } catch {\n      // File doesn't exist or can't be parsed, continue searching\n    }\n    currentPath = path.dirname(currentPath);\n  }\n\n  return null;\n};\n\nconst loadPnpmWorkspaceCatalogs = async (): Promise<PnpmWorkspaceConfig | null> => {\n  const workspaceRoot = await findPnpmWorkspaceroot();\n  if (!workspaceRoot) return null;\n\n  try {\n    const workspaceFile = path.join(workspaceRoot, 'pnpm-workspace.yaml');\n    const content = await fs.readFile(workspaceFile, 'utf-8');\n    return parseYaml(content);\n  } catch {\n    return null;\n  }\n};\n\nconst loadBunWorkspaceCatalogs = async (): Promise<BunWorkspaceConfig | null> => {\n  const workspaceRoot = await findBunWorkspaceRoot();\n  if (!workspaceRoot) return null;\n\n  try {\n    const packageJsonFile = path.join(workspaceRoot, 'package.json');\n    const content = await fs.readFile(packageJsonFile, 'utf-8');\n    const packageJson: PackageJson & { workspaces?: any } = JSON.parse(content);\n\n    if (!packageJson.workspaces) return null;\n\n    const result: BunWorkspaceConfig = {};\n\n    if (packageJson.workspaces.packages) {\n      result.packages = packageJson.workspaces.packages;\n    }\n\n    if (packageJson.workspaces.catalog) {\n      result.catalog = packageJson.workspaces.catalog;\n    }\n\n    if (packageJson.workspaces.catalogs) {\n      result.catalogs = packageJson.workspaces.catalogs;\n    }\n\n    return result;\n  } catch {\n    return null;\n  }\n};\n\nconst loadWorkspaceCatalogs = async (): Promise<WorkspaceConfig | null> => {\n  const pnpmCatalogs = await loadPnpmWorkspaceCatalogs();\n  if (pnpmCatalogs) return pnpmCatalogs;\n\n  const bunCatalogs = await loadBunWorkspaceCatalogs();\n  if (bunCatalogs) return bunCatalogs;\n\n  return null;\n};\n\nconst resolveCatalogVersion = (catalogRef: string): string | null => {\n  if (!catalogRef.startsWith('catalog:')) return null;\n\n  const catalogName = catalogRef.slice(8); // Remove 'catalog:' prefix\n\n  if (!catalogName || catalogName === 'default') {\n    return null; // Will be resolved by package name lookup\n  }\n\n  return catalogName;\n};\n\nconst getVersionFromCatalog = (\n  packageName: string,\n  catalogName: string | null,\n  catalogs: WorkspaceConfig\n): string | null => {\n  if (catalogName) {\n    // Named catalog\n    return catalogs.catalogs?.[catalogName]?.[packageName] || null;\n  } else {\n    // Default catalog\n    return catalogs.catalog?.[packageName] || null;\n  }\n};\n\nconst getPackageVersion = async (\n  packageName: string,\n  meta: PackageJson\n): Promise<string | null> => {\n  const devVersion = meta.devDependencies?.[packageName];\n  if (devVersion) {\n    if (devVersion.startsWith('catalog:')) {\n      const catalogs = await loadWorkspaceCatalogs();\n      if (catalogs) {\n        const catalogName = resolveCatalogVersion(devVersion);\n        const resolvedVersion = getVersionFromCatalog(packageName, catalogName, catalogs);\n        if (resolvedVersion) return resolvedVersion;\n      }\n    } else {\n      return devVersion;\n    }\n  }\n\n  const depVersion = meta.dependencies?.[packageName];\n  if (depVersion) {\n    if (depVersion.startsWith('catalog:')) {\n      const catalogs = await loadWorkspaceCatalogs();\n      if (catalogs) {\n        const catalogName = resolveCatalogVersion(depVersion);\n        const resolvedVersion = getVersionFromCatalog(packageName, catalogName, catalogs);\n        if (resolvedVersion) return resolvedVersion;\n      }\n    } else {\n      return depVersion;\n    }\n  }\n\n  return null;\n};\n\nexport const readPackageJson = async (): Promise<PackageJson> => {\n  const packageJsonPath = path.resolve(process.cwd(), 'package.json');\n  const file = path.resolve(packageJsonPath);\n  return JSON.parse(await fs.readFile(file, 'utf-8'));\n};\n\nexport const getTypeScriptVersion = async (meta: PackageJson): Promise<string | null> => {\n  const pkg = 'typescript';\n\n  // Try to get version with catalog support\n  const catalogVersion = await getPackageVersion(pkg, meta);\n  if (catalogVersion) return catalogVersion;\n\n  // Fallback to direct resolution\n  try {\n    return (await import(pkg)).version || null;\n  } catch (_error) {\n    return null;\n  }\n};\n\nexport const getGraphQLSPVersion = async (meta: PackageJson): Promise<string | null> => {\n  const pkg = '@0no-co/graphqlsp';\n\n  // Try to get version with catalog support\n  const catalogVersion = await getPackageVersion(pkg, meta);\n  if (catalogVersion) return catalogVersion;\n\n  // Fallback to direct resolution\n  try {\n    // NOTE: Resolved from current folder, since it's a child dependency\n    return createRequire(__dirname)(`${pkg}/package.json`)?.version || null;\n  } catch (_error) {\n    return null;\n  }\n};\n\nexport const getGqlTadaVersion = async (meta: PackageJson): Promise<string | null> => {\n  const pkg = 'gql.tada';\n\n  // Try to get version with catalog support\n  const catalogVersion = await getPackageVersion(pkg, meta);\n  if (catalogVersion) return catalogVersion;\n\n  // Fallback to direct resolution\n  try {\n    // NOTE: Resolved from working directory, since it's a parent dependency\n    return createRequire(process.cwd())(`${pkg}/package.json`)?.version || null;\n  } catch (_error) {\n    return null;\n  }\n};\n\nconst hasPackageSupport = async (packageName: string, meta: PackageJson): Promise<boolean> => {\n  // Check if package is listed in dependencies with catalog support\n  const catalogVersion = await getPackageVersion(packageName, meta);\n  if (catalogVersion) return true;\n\n  // Fallback to direct resolution\n  try {\n    // NOTE: Resolved from current folder, since it's a child dependency\n    return !!createRequire(__dirname)(`${packageName}/package.json`)?.version;\n  } catch (_error) {\n    return false;\n  }\n};\n\nexport const hasSvelteSupport = async (meta: PackageJson): Promise<boolean> => {\n  return hasPackageSupport('@gql.tada/svelte-support', meta);\n};\n\nexport const hasVueSupport = async (meta: PackageJson): Promise<boolean> => {\n  return hasPackageSupport('@gql.tada/vue-support', meta);\n};\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport ts from 'typescript';\nimport { stat, FileType } from './fs';\n\nconst jsonParse = async (fileName: string): Promise<unknown> => {\n  const contents = await fs.readFile(fileName, 'utf8');\n  const sourceFile = ts.parseJsonText(fileName, contents);\n  return ts.convertToObject(sourceFile, []);\n};\n\nexport const isVSCodeInstalled = async (): Promise<boolean> => {\n  if (!process.env.HOME) return false;\n  const vscodeFolder = path.resolve(process.env.HOME, '.vscode');\n  return !!(await stat(vscodeFolder, FileType.Directory));\n};\n\n/** Loads list of suggested in-repo VSCode extensions */\nexport const loadSuggestedExtensionsList = async (\n  targetPath?: string\n): Promise<readonly string[]> => {\n  let target = targetPath || process.cwd();\n  const rootPath = path.resolve(target, '/');\n  while (target !== rootPath) {\n    if (await stat(path.resolve(target, '.git'), FileType.Directory)) {\n      break;\n    } else if (await stat(path.resolve(target, '.vscode'), FileType.Directory)) {\n      break;\n    }\n    target = path.resolve(target, '..');\n  }\n  const configFile = path.resolve(target, '.vscode', 'extensions.json');\n  if (!(await stat(configFile))) return [];\n  let json: unknown;\n  try {\n    json = await jsonParse(configFile);\n  } catch (_error) {\n    return [];\n  }\n  if (json && typeof json === 'object' && 'recommendations' in json) {\n    return Array.isArray(json.recommendations)\n      ? json.recommendations\n          .filter((x): x is string => x && typeof x === 'string')\n          .map((x) => `${x}`.toLowerCase())\n      : [];\n  } else {\n    return [];\n  }\n};\n\n/** Loads list of installed VSCode extensions */\nexport const loadExtensionsList = async (): Promise<readonly string[]> => {\n  if (!process.env.HOME) return [];\n  const vscodeFolder = path.resolve(process.env.HOME, '.vscode');\n  const configFile = path.resolve(vscodeFolder, 'extensions', 'extensions.json');\n  if (!(await stat(configFile))) return [];\n  let json: unknown;\n  try {\n    json = await jsonParse(configFile);\n  } catch (_error) {\n    return [];\n  }\n  return (Array.isArray(json) ? json : [])\n    .map((entry) => {\n      if (!entry || typeof entry !== 'object' || !('identifier' in entry)) return null;\n      if (!entry.identifier || typeof entry.identifier !== 'object' || !('id' in entry.identifier))\n        return null;\n      return entry.identifier.id && typeof entry.identifier.id === 'string'\n        ? `${entry.identifier.id}`.toLowerCase()\n        : null;\n    })\n    .filter((x): x is string => !!x);\n};\n","import { pipe, interval, map, concat, fromValue } 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  const frame = (state: number) =>\n    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  return concat([\n    fromValue(frame(0)),\n    pipe(\n      interval(150),\n      map((state) => frame(state + 1))\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 { LoadConfigResult } from '@gql.tada/internal';\nimport {\n  loadRef,\n  loadConfigs,\n  parseConfig,\n  validateUniqueOutputLocations,\n} from '@gql.tada/internal';\n\nimport type { ComposeInput } from '../../term';\nimport type { ProjectContext } from '../shared';\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 configResults: LoadConfigResult[];\n  try {\n    configResults = await loadConfigs();\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  const projects: ProjectContext[] = [];\n  for (const configResult of configResults) {\n    const label =\n      path.relative(process.cwd(), configResult.tsconfigPath) || configResult.tsconfigPath;\n    try {\n      projects.push({\n        configResult,\n        pluginConfig: parseConfig(configResult.pluginConfig, configResult.rootPath),\n        projectPath: path.dirname(configResult.tsconfigPath),\n        label,\n      });\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        )} in ${logger.code(label)} seems to be invalid.`,\n        error\n      );\n    }\n  }\n\n  try {\n    validateUniqueOutputLocations(\n      projects.map((project) => ({\n        projectPath: project.projectPath,\n        config: project.pluginConfig,\n        label: project.label,\n      }))\n    );\n  } catch (error) {\n    yield logger.failedTask(Messages.CHECK_TSCONFIG);\n    throw logger.externalError('The output locations of your configured projects overlap.', error);\n  }\n\n  yield logger.completedTask(Messages.CHECK_TSCONFIG);\n  if (projects.length > 1) {\n    yield logger.hintMessage(\n      `Found ${projects.length} ${logger.code('gql.tada')} projects through ${logger.code(\n        '\"references\"'\n      )} in your ${logger.code('tsconfig.json')} files.\\n`\n    );\n  }\n\n  yield* runExternalFilesChecks(projects, packageJson);\n\n  yield* runVSCodeChecks();\n\n  yield logger.runningTask(Messages.CHECK_SCHEMA);\n  await delay();\n\n  for (const project of projects) {\n    try {\n      await loadRef(project.pluginConfig).load({ rootPath: project.projectPath });\n    } catch (error) {\n      yield logger.failedTask(Messages.CHECK_SCHEMA);\n      throw logger.externalError(\n        projects.length > 1\n          ? `Failed to load schema for project ${logger.code(project.label)}.`\n          : 'Failed to load schema.',\n        error\n      );\n    }\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  projects: readonly ProjectContext[],\n  packageJson: versions.PackageJson\n): AsyncIterable<ComposeInput> {\n  const externalFiles: ts.SourceFile[] = [];\n  for (const project of projects) {\n    try {\n      const factory = programFactory({\n        rootPath: project.configResult.rootPath,\n        configPath: project.configResult.tsconfigPath,\n      });\n      externalFiles.push(...factory.createExternalFiles());\n    } catch (_error) {\n      // NOTE: If a project fails to load, we currently just ignore this check and move on\n    }\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","import * as path from 'node:path';\nimport { Command, Option } from 'clipanion';\n\nexport class InitCommand extends Command {\n  static paths = [['init']];\n\n  input = Option.String({ name: 'dir' });\n\n  async execute() {\n    const { run } = await import('./runner');\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 { ScanCommand } from './commands/scan/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(ScanCommand);\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","commit","source","make","observer","last","subscription","pipe","onPush","next","onEnd","endsWith","complete","subscribe","unsubscribe","compose","outputs","reset","Reset","NoInvert","outputs$","fromAsyncIterable","async","convertError","concatMap","fromValue","x","share","output$","merge","never","takeUntil","scan","prev","clear","charCodeAt","PrevLine","DeleteLines","Backward","ToColumn","takeLast","Chars","Box","HeavyBox","SmallTriangle","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","_terminate","_restore","setRawMode","ResetPrivateMode","ShowCursor","_signal","signal","inputSource","fromReadStream","stream","onTerminate","onKeypress","event","ctrl","cleanup","removeListener","unref","emitKeypressEvents","setEncoding","resume","addListener","onStart","_start","on","_end","cancelSource","isInteractive","silent","start","toPromise","mode","modes","normalModes","privateModes","Insert","AutomaticNewline","modeOff","Newline","Underline","NoUnderline","Bold","Normal","hint","BrightBlack","BottomLeft","BrightBlue","Info","Blue","projectHeader","Magenta","Right","Foreground","Red","Invert","Warning","externalError","title","experimentMessage","Yellow","loadProjects","projects","loadConfigs","tsconfig","configResult","projectPath","dirname","tsconfigPath","pluginConfig","parseConfig","rootPath","relative","cwd","validateUniqueOutputLocations","project","config","directoryExists","stat","fs","file","isDirectory","isSymbolicLink","realpath","readOutput","target","readFile","writeOutput","contents","reject","targetDirectory","mkdir","recursive","isFile","writeFile","tempTarget","rename","unlink","now","Date","utimes","_error","touchFile","summary","showHint","BrightGreen","Tick","tty","logger","generated","destinations","outputDestinations","destination","runProject","schemas","tadaOutputLocation","location","schemaRef","loadRef","load","current","existing","outputIntrospectionFile","minifyIntrospection","introspection","fileType","forceTSFormat","shouldPreprocess","disablePreprocessing","preamble","extractIntrospectionHeader","schemaName","multi","GenerateOutputCommand","static","Option","generateOutput","CWD","INDENT","warningFile","filePath","relativePath","documentSummary","documentCount","warningSummary","warningCount","Cross","infoSummary","BrightYellow","warningGithub","col","runningPersisted","ofFiles","progress","frame","Ellipsis","interval","totalWarnings","failedProjects","warnings","failed","deferWarnings","runPersisted","import","generator","disableNormalization","configPath","documents","totalFileCount","fileCount","buffer","warning","Tab","tadaPersistedLocation","failOnWarn","item","hashKey","document","schemaConfig","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","reusedLabel","count","cachedCount","cachedLabel","runningTurbo","PREAMBLE_IGNORE","runTurbo","tadaTurboLocation","hintMessage","turboOutputPath","graphqlSources","cachedDocumentCount","sources","isCached","createCacheContents","cache","turboDestination","documentsByKey","argumentKey","documentHash","documentType","imports","isFilePath","addedImports","importInfo","turboPath","sourceDir","absolutePath","specifier","importClause","TurboCommand","generateTurbo","ModuleGraph","_dependents","edges","_edges","_cwd","importMap","areaOf","modulePath","rel","dir","entryPoints","_entryPoints","targets","tos","dependents","cached","reverse","_reverseGraph","pop","distanceFromEntry","_distance","distance","frontier","depth","reach","modules","areas","reachedEntries","module","_reverse","importers","FragmentGraph","_byId","_idByName","_operationIds","_reachable","id","reachableFragments","definitionId","fragmentSpreads","fragment","operationsReaching","fragmentId","_operationsReaching","operationId","reachableId","hashOf","crypto","createHash","update","digest","collectFragmentSpreads","visit","FragmentSpread","spread","ScanContext","_operations","_fragments","_definitions","_recordByNode","_recordById","_typeInfo","_currentDefinition","_schemas","_warnings","_importGraph","_buildCorpus","_modules","_buildModules","operations","fragments","getSchemas","definitionNodesForSchema","setTypeInfo","typeInfo","trackingVisitor","OperationDefinition","enter","leave","FragmentDefinition","getCurrentDefinition","getParentType","getType","getFieldDef","getInputType","getParentInputType","getEnumValue","getModuleGraph","_moduleGraph","getFragmentGraph","_fragmentGraph","_addWarning","_uniqueId","base","_register","defKind","_node","_defKind","info","anonCount","parse","noLocation","loc","Kind","OPERATION_DEFINITION","operation","variables","variableDefinitions","variable","print","defaultValue","hash","FRAGMENT_DEFINITION","typeCondition","byPath","ensure","resolved","fieldUsage","create","byCoordinate","seen","resetSeen","visitor","Field","parentType","fieldDef","coordinate","typeName","fieldName","fieldType","deprecationReason","directUsages","defId","collect","operationIds","moduleById","graph","hasEntryPoints","size","datapoints","sourceModules","u","reachModules","reachAreas","reachEntries","m","e","ref","weight","deprecated","coordinateOf","d","DEFAULT_RULES","counts","bump","EnumValue","inputType","getNamedType","ObjectField","parentInput","defIds","spreadIds","consumerAreas","spreadCount","byId","definingArea","externalAreas","area","byDef","startDefinition","ownDepth","fields","listFields","spreads","SelectionSet","isListType","getNullableType","depthMemo","effectiveDepth","visiting","metrics","delete","operationDepth","score","fieldCount","Directive","buildOverview","rules","operationsByKind","query","mutation","usedFields","totalFields","allSchemaFields","getTypeMap","isObjectType","isInterfaceType","field","getFields","percent","round","coverage","renderJson","version","overview","moduleNodeId","fieldNodeId","typeNodeId","fragmentKey","renderGraph","buildGraph","addNode","fragmentIdByName","moduleNode","datapoint","site","addDefinition","spreadName","MAX_PER_RULE","MIN_MESSAGE_WIDTH","RULE_DESCRIPTIONS","rule","truncate","renderTerminalReport","width","coverageLine","shown","truncated","forEach","isLast","weightText","locText","locator","locWidth","budget","VerticalRight","runningScan","runScan","quiet","loadSchemas","analyze","instances","instance","TypeInfo","visitInParallel","DOCUMENT","visitWithTypeInfo","results","render","wroteOutput","columns","ScanCommand","diagnosticFile","diagnosticMessage","severity","BrightRed","diagnosticMessageGithub","endLine","endColumn","runningDiagnostics","isMinSeverity","minSeverity","runDiagnostics","warn","warnedAboutExternalFiles","messages","problemsSummary","CheckCommand","Intl","Collator","numeric","compare","MINIMUM_VERSIONS","typescript_embed_lsp","typescript","tada","lsp","semverComply","semiver","bool","spanToFilePosition","span","fileName","lineAndChar","getLineAndCharacterOfPosition","character","notImplemented","methodName","defaultCompilerOptions","ts","getDefaultCompilerOptions","jsx","JsxEmit","React","strict","esModuleInterop","ModuleKind","ESNext","suppressOutputPathCheck","skipLibCheck","skipDefaultLibCheck","moduleResolution","ModuleResolutionKind","NodeJs","createVirtualCompilerHost","sys","compilerOptions","sourceFiles","compilerHost","getCanonicalFileName","getDefaultLibFileName","getDirectories","getNewLine","newLine","getSourceFile","sourceFile","save","createSourceFile","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","unshift","Reflect","items","first","deleteCount","_stackStart","operateIndex","stackStart","originalLength","_deleteCount","compareFn","lastIndexOf","types","__createBinding","o","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","documentRegistry","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","getLanguageService","system","rootNames","getProjectName","projectService","serverHost","setImmediate","clearImmediate","_svelte","_vue","transformExtensions","transform","SVELTE_SUPPORT","transformSvelte","VUE_SUPPORT","check","checkVue","transformVue","UNKNOWN_EXTERNAL_FILE","programFactory","vfsMap","createFSBackedSystem","files","_projectRoot","tsLibDirectory","root","nodeSys","tsLib","require","directory","createDirectory","fileExists","tsLibName","getCurrentDirectory","getExecutingFilePath","readDirectory","libs","resolvePath","resolveDefaultLibsPath","resolveConfig","getDefaultLibFilePath","noCheck","orignallyNodeNext","NodeNext","Node16","Bundler","host","createDocumentRegistry","factory","wasOriginallyNodeNext","projectDirectories","directories","rootName","rootFileNames","scriptKind","sourceText","getText","ScriptTarget","ScriptKind","TSX","createExternalFiles","exts","External","addSourceFile","addMappedFile","sourceMappedFile","addVirtualFiles","virtualFileId","virtualCode","snapshot","resolveModulePath","importSpecifier","fromPath","resolveModuleName","resolvedModule","resolvedFileName","toPath","fromDir","toDir","absoluteImportPath","relativeImportPath","bumpStackTraceLimit","stackTraceLimit","init","service","serviceHost","pluginInfo","getLanguageServiceHost","createProgram","getSourceMappedFile","getSourcePosition","buildContainer","createRequire","request","parseResult","parseConfigFileTextToJson","messageText","parseJsonConfigFileContent","FileType","File","Directory","configFileRe","findGraphQLConfig","readdir","configFile","workspaceRoot","targetPath","packageJsonPath","workspaces","findWorkspaceRoot","graphql","loadPnpmWorkspaceCatalogs","startPath","currentPath","workspaceFile","access","findPnpmWorkspaceroot","content","currentSection","currentCatalog","trimmed","packages","catalog","catalogs","colonIndex","parseYaml","loadBunWorkspaceCatalogs","packageJsonFile","packageJson","findBunWorkspaceRoot","loadWorkspaceCatalogs","pnpmCatalogs","bunCatalogs","resolveCatalogVersion","catalogRef","catalogName","getVersionFromCatalog","packageName","getPackageVersion","devVersion","devDependencies","resolvedVersion","depVersion","dependencies","hasPackageSupport","__dirname","hasSvelteSupport","hasVueSupport","jsonParse","parseJsonText","convertToObject","isVSCodeInstalled","HOME","vscodeFolder","loadSuggestedExtensionsList","recommendations","loadExtensionsList","identifier","emptyLine","Vertical","completedTask","Green","TickSwoosh","failedTask","CrossSwoosh","warningTask","runningTask","delay","ms","setTimeout","Messages","TopLeft","TITLE","DESCRIPTION","CHECK_TS_VERSION","versions","typeScriptVersion","pkg","catalogVersion","CHECK_DEPENDENCIES","supportsEmbeddedLsp","gqlspVersion","gqlTadaVersion","CHECK_TSCONFIG","configResults","runExternalFilesChecks","externalFiles","CHECK_EXTERNAL_FILES","extensions","runVSCodeChecks","suggestedExtensions","vscode","CHECK_VSCODE","hasEndedTask","userExtensions","hasProblemExtension","graphqlConfig","basename","CHECK_SCHEMA","success","Space","DoctorCommand","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;;AAC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