politty 0.5.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -0
- package/dist/{arg-registry-6E0WHOh_.d.ts → arg-registry-DDJpsUea.d.cts} +47 -23
- package/dist/arg-registry-DDJpsUea.d.cts.map +1 -0
- package/dist/{arg-registry--NRaNFJM.d.cts → arg-registry-DDJpsUea.d.ts} +47 -23
- package/dist/arg-registry-DDJpsUea.d.ts.map +1 -0
- package/dist/augment.d.cts +1 -1
- package/dist/augment.d.ts +1 -1
- package/dist/cli.cjs +54 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +55 -0
- package/dist/cli.js.map +1 -0
- package/dist/completion/index.cjs +6 -1
- package/dist/completion/index.d.cts +3 -3
- package/dist/completion/index.d.ts +3 -3
- package/dist/completion/index.js +2 -2
- package/dist/{completion-BFOAOg95.cjs → completion-CLHO3Xaz.cjs} +1812 -337
- package/dist/completion-CLHO3Xaz.cjs.map +1 -0
- package/dist/{completion-K5LGh1hO.js → completion-DHnVx9Zk.js} +1786 -340
- package/dist/completion-DHnVx9Zk.js.map +1 -0
- package/dist/docs/index.cjs +3 -3
- package/dist/docs/index.cjs.map +1 -1
- package/dist/docs/index.d.cts +1 -1
- package/dist/docs/index.d.cts.map +1 -1
- package/dist/docs/index.d.ts +1 -1
- package/dist/docs/index.d.ts.map +1 -1
- package/dist/docs/index.js +3 -3
- package/dist/docs/index.js.map +1 -1
- package/dist/{index-Cg8qstsT.d.cts → index-DKGn3lIl.d.ts} +119 -4
- package/dist/index-DKGn3lIl.d.ts.map +1 -0
- package/dist/{index-O3yn97Ed.d.ts → index-WyViqW59.d.cts} +119 -4
- package/dist/index-WyViqW59.d.cts.map +1 -0
- package/dist/index.cjs +4 -3
- package/dist/index.d.cts +3 -3
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -4
- package/dist/{log-collector-Cu6MCtAx.js → log-collector-DK32-73m.js} +1 -1
- package/dist/{log-collector-Cu6MCtAx.js.map → log-collector-DK32-73m.js.map} +1 -1
- package/dist/{log-collector-Cd2_mv87.cjs → log-collector-DUqC427m.cjs} +1 -1
- package/dist/{log-collector-Cd2_mv87.cjs.map → log-collector-DUqC427m.cjs.map} +1 -1
- package/dist/prompt/clack/index.cjs +1 -2
- package/dist/prompt/clack/index.cjs.map +1 -1
- package/dist/prompt/clack/index.d.cts +1 -1
- package/dist/prompt/clack/index.d.ts +1 -1
- package/dist/prompt/clack/index.js +1 -1
- package/dist/prompt/index.cjs +1 -1
- package/dist/prompt/index.d.cts +1 -1
- package/dist/prompt/index.d.cts.map +1 -1
- package/dist/prompt/index.d.ts +1 -1
- package/dist/prompt/index.d.ts.map +1 -1
- package/dist/prompt/index.js +1 -1
- package/dist/prompt/inquirer/index.cjs +1 -2
- package/dist/prompt/inquirer/index.cjs.map +1 -1
- package/dist/prompt/inquirer/index.d.cts +1 -1
- package/dist/prompt/inquirer/index.d.ts +1 -1
- package/dist/prompt/inquirer/index.js +1 -1
- package/dist/{prompt-aXfSf27y.cjs → prompt-Bs9e-Em3.cjs} +1 -1
- package/dist/{prompt-aXfSf27y.cjs.map → prompt-Bs9e-Em3.cjs.map} +1 -1
- package/dist/{prompt-BKHqGrFw.js → prompt-Cc8Tfmdv.js} +1 -1
- package/dist/{prompt-BKHqGrFw.js.map → prompt-Cc8Tfmdv.js.map} +1 -1
- package/dist/{runner-BmSEiD9A.js → runner-D43SkHt5.js} +121 -20
- package/dist/runner-D43SkHt5.js.map +1 -0
- package/dist/{runner-CRZ_7Y9i.cjs → runner-DvFvokV6.cjs} +121 -20
- package/dist/runner-DvFvokV6.cjs.map +1 -0
- package/dist/{schema-extractor-SLPgBNgZ.cjs → schema-extractor-BxSRwLrx.cjs} +1 -2
- package/dist/schema-extractor-BxSRwLrx.cjs.map +1 -0
- package/dist/{schema-extractor-C50R-1re.js → schema-extractor-Dqe7_kyQ.js} +1 -1
- package/dist/schema-extractor-Dqe7_kyQ.js.map +1 -0
- package/package.json +15 -12
- package/dist/arg-registry--NRaNFJM.d.cts.map +0 -1
- package/dist/arg-registry-6E0WHOh_.d.ts.map +0 -1
- package/dist/completion-BFOAOg95.cjs.map +0 -1
- package/dist/completion-K5LGh1hO.js.map +0 -1
- package/dist/index-Cg8qstsT.d.cts.map +0 -1
- package/dist/index-O3yn97Ed.d.ts.map +0 -1
- package/dist/runner-BmSEiD9A.js.map +0 -1
- package/dist/runner-CRZ_7Y9i.cjs.map +0 -1
- package/dist/schema-extractor-C50R-1re.js.map +0 -1
- package/dist/schema-extractor-SLPgBNgZ.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"completion-K5LGh1hO.js","names":["optionValueCases","positionalBlock","availableOptionLines","generateSubHandler","escapeDesc","optionValueCases","positionalBlock","availableOptionLines","generateSubHandler","shSingleQuote","installCompletion"],"sources":["../src/core/command.ts","../src/completion/shell-shared.ts","../src/completion/value-completion-resolver.ts","../src/completion/dynamic/context-parser.ts","../src/completion/dynamic/candidate-generator.ts","../src/completion/expand-resolver.ts","../src/completion/extractor.ts","../src/completion/header.ts","../src/completion/self-refresh.ts","../src/completion/bash.ts","../src/completion/dynamic/shell-formatter.ts","../src/completion/dynamic/complete-command.ts","../src/completion/fish.ts","../src/completion/loader.ts","../src/completion/install.ts","../src/completion/zsh.ts","../src/completion/index.ts"],"sourcesContent":["import type { z } from \"zod\";\nimport type {\n ArgsSchema,\n Command,\n Example,\n GlobalArgs,\n IsEmpty,\n NonRunnableCommand,\n RunnableCommand,\n SubCommandsRecord,\n} from \"../types.js\";\nimport type { WithCaseVariants } from \"./case-types.js\";\n\n/**\n * Infer args type from schema, defaults to empty object if undefined.\n * Wraps with WithCaseVariants so both camelCase and kebab-case access is typed.\n */\ntype InferArgs<TArgsSchema> = TArgsSchema extends z.ZodType\n ? WithCaseVariants<z.infer<TArgsSchema>>\n : Record<string, never>;\n\n/**\n * Merge local args with global args.\n * No-op when TGlobalArgs is empty (default GlobalArgs not extended).\n * Wraps TGlobalArgs with WithCaseVariants for dual-case access.\n */\nexport type MergedArgs<TLocalArgs, TGlobalArgs> =\n IsEmpty<TGlobalArgs> extends true ? TLocalArgs : TLocalArgs & WithCaseVariants<TGlobalArgs>;\n\n/**\n * Resolve merged args from schema and global args type\n */\ntype ResolvedArgs<TArgsSchema, TGlobalArgs> = MergedArgs<InferArgs<TArgsSchema>, TGlobalArgs>;\n\n/**\n * Config for defining a command\n * @template TArgsSchema - The Zod schema type for arguments\n * @template TResult - The return type of run function (void if no run)\n * @template TGlobalArgs - Global args type (from declaration merging or factory)\n */\ninterface DefineCommandConfig<TArgsSchema extends ArgsSchema | undefined, TResult, TGlobalArgs> {\n name: string;\n description?: string;\n aliases?: string[];\n args?: TArgsSchema;\n subCommands?: SubCommandsRecord;\n setup?: (context: { args: ResolvedArgs<TArgsSchema, TGlobalArgs> }) => void | Promise<void>;\n run?: (args: ResolvedArgs<TArgsSchema, TGlobalArgs>) => TResult;\n cleanup?: (context: {\n args: ResolvedArgs<TArgsSchema, TGlobalArgs>;\n error?: Error | undefined;\n }) => void | Promise<void>;\n notes?: string;\n examples?: Example[];\n}\n\n/**\n * Config with run function (runnable command)\n */\nexport interface RunnableConfig<\n TArgsSchema extends ArgsSchema | undefined,\n TResult,\n TGlobalArgs,\n> extends DefineCommandConfig<TArgsSchema, TResult, TGlobalArgs> {\n run: (args: ResolvedArgs<TArgsSchema, TGlobalArgs>) => TResult;\n}\n\n/**\n * Config without run function (non-runnable command)\n */\nexport interface NonRunnableConfig<\n TArgsSchema extends ArgsSchema | undefined,\n TGlobalArgs,\n> extends Omit<DefineCommandConfig<TArgsSchema, void, TGlobalArgs>, \"run\"> {\n run?: undefined;\n}\n\n/**\n * Define a CLI command with type-safe arguments\n *\n * @param config - Command configuration\n * @returns A defined command with preserved type information\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * import { arg, defineCommand } from \"politty\";\n *\n * const command = defineCommand({\n * name: \"greet\",\n * args: z.object({\n * name: arg(z.string(), { description: \"Name to greet\", positional: true }),\n * loud: arg(z.boolean().default(false), { alias: \"l\", description: \"Use uppercase\" }),\n * }),\n * run: (args) => {\n * const greeting = `Hello, ${args.name}!`;\n * console.log(args.loud ? greeting.toUpperCase() : greeting);\n * },\n * });\n *\n * // Type of command.argsSchema is preserved as z.ZodObject<...>\n * // Type of command.run is (args: { name: string; loud: boolean }) => void\n * ```\n *\n * @example\n * ```ts\n * // With discriminated union for subcommand-like behavior\n * const command = defineCommand({\n * name: \"resource\",\n * args: z.discriminatedUnion(\"action\", [\n * z.object({\n * action: z.literal(\"create\"),\n * name: arg(z.string(), { description: \"Resource name\" }),\n * }),\n * z.object({\n * action: z.literal(\"delete\"),\n * id: arg(z.coerce.number(), { description: \"Resource ID\" }),\n * }),\n * ]),\n * run: (args) => {\n * if (args.action === \"create\") {\n * console.log(`Creating ${args.name}`);\n * } else {\n * console.log(`Deleting ${args.id}`);\n * }\n * },\n * });\n * ```\n */\n// Overload 1: with run function - returns RunnableCommand with preserved schema type\nexport function defineCommand<\n TArgsSchema extends ArgsSchema | undefined = undefined,\n TResult = void,\n TGlobalArgs = GlobalArgs,\n>(\n config: RunnableConfig<TArgsSchema, TResult, TGlobalArgs>,\n): RunnableCommand<TArgsSchema, ResolvedArgs<TArgsSchema, TGlobalArgs>, TResult>;\n\n// Overload 2: without run function - returns NonRunnableCommand with preserved schema type\nexport function defineCommand<\n TArgsSchema extends ArgsSchema | undefined = undefined,\n TGlobalArgs = GlobalArgs,\n>(\n config: NonRunnableConfig<TArgsSchema, TGlobalArgs>,\n): NonRunnableCommand<TArgsSchema, ResolvedArgs<TArgsSchema, TGlobalArgs>>;\n\n// Implementation\nexport function defineCommand<\n TArgsSchema extends ArgsSchema | undefined = undefined,\n TResult = void,\n TGlobalArgs = GlobalArgs,\n>(\n config:\n | RunnableConfig<TArgsSchema, TResult, TGlobalArgs>\n | NonRunnableConfig<TArgsSchema, TGlobalArgs>,\n): Command<TArgsSchema, ResolvedArgs<TArgsSchema, TGlobalArgs>, TResult> {\n return {\n name: config.name,\n description: config.description,\n aliases: config.aliases,\n args: config.args as TArgsSchema,\n subCommands: config.subCommands,\n setup: config.setup,\n run: config.run,\n cleanup: config.cleanup,\n notes: config.notes,\n examples: config.examples,\n } as Command<TArgsSchema, ResolvedArgs<TArgsSchema, TGlobalArgs>, TResult>;\n}\n\n/**\n * Create a typed defineCommand factory with pre-bound global args type.\n * This is the recommended pattern for type-safe global options.\n *\n * @example\n * ```ts\n * // global-args.ts\n * type GlobalArgsType = { verbose: boolean; config?: string };\n * export const defineAppCommand = createDefineCommand<GlobalArgsType>();\n *\n * // commands/build.ts\n * export const buildCommand = defineAppCommand({\n * name: \"build\",\n * args: z.object({ output: arg(z.string().default(\"dist\")) }),\n * run: (args) => {\n * args.verbose; // typed via GlobalArgsType\n * args.output; // typed via local args\n * },\n * });\n * ```\n */\nexport function createDefineCommand<TGlobalArgs>(): {\n <TArgsSchema extends ArgsSchema | undefined = undefined, TResult = void>(\n config: RunnableConfig<TArgsSchema, TResult, TGlobalArgs>,\n ): RunnableCommand<TArgsSchema, ResolvedArgs<TArgsSchema, TGlobalArgs>, TResult>;\n <TArgsSchema extends ArgsSchema | undefined = undefined>(\n config: NonRunnableConfig<TArgsSchema, TGlobalArgs>,\n ): NonRunnableCommand<TArgsSchema, ResolvedArgs<TArgsSchema, TGlobalArgs>>;\n} {\n return defineCommand as ReturnType<typeof createDefineCommand<TGlobalArgs>>;\n}\n","/**\n * Helpers shared across the bash/zsh/fish completion generators.\n *\n * The three generators are necessarily distinct (each shell has its own\n * syntax) but they share a handful of building blocks: ANSI-C literal\n * encoding, the `--alias`/`-a` token shape, and the resolved-dep records\n * that drive expand lookups. Keeping these in one place avoids drift\n * when one generator gets a fix that the others should mirror.\n */\n\nimport { toCamelCase } from \"../core/schema-extractor.js\";\nimport type { CompletableOption, CompletablePositional, ValueCompletion } from \"./types.js\";\n\n/**\n * Resolved sibling dep used by an `expand` value completion. Paired with\n * a globality bit so the shell-side lookup reads from the matching\n * bucket: local deps from `_arg_values`, global deps from\n * `_global_arg_values`.\n */\nexport interface ResolvedExpandDep {\n readonly name: string;\n readonly isGlobal: boolean;\n}\n\n/**\n * Per-host metadata every shell's expand emission needs: which field, whether\n * the dedup-bucket reads from the global namespace, whether the host repeats\n * (`key=` dedup applies), and the resolved `dependsOn` slots. Bash and zsh\n * additionally carry a `funcSuffix` to name the hoisted table variable —\n * fish keys its lookup off `fieldName` alone, so the extension is opt-in\n * via {@link FuncSuffixedExpandLocation}.\n */\nexport interface BaseExpandLocation {\n fieldName: string;\n isArrayOption: boolean;\n isGlobal: boolean;\n resolvedDeps: readonly ResolvedExpandDep[];\n}\n\n/**\n * Bash and zsh both hoist their expand table as `__<fn>_expand_<funcSuffix>__<field>`\n * — bash uses per-entry scalars (bash 3.2 has no associative arrays), zsh uses\n * an associative-array subscript — so both need the surrounding handler's\n * function suffix on top of the shell-agnostic {@link BaseExpandLocation}.\n */\nexport interface FuncSuffixedExpandLocation extends BaseExpandLocation {\n funcSuffix: string;\n}\n\n/**\n * Build the shell-agnostic part of an expand location for an option. Wraps\n * `resolveExpandDepGlobality` so the three generators don't each repeat the\n * `(opt.valueCompletion, opt.isGlobal === true, options, positionals)`\n * incantation.\n */\nexport function optionExpandLocation(\n opt: CompletableOption,\n frameOptions: readonly CompletableOption[],\n framePositionals: readonly CompletablePositional[],\n): BaseExpandLocation {\n return {\n fieldName: opt.name,\n isArrayOption: opt.valueType === \"array\",\n isGlobal: opt.isGlobal === true,\n resolvedDeps: resolveExpandDepGlobality(\n opt.valueCompletion,\n opt.isGlobal === true,\n frameOptions,\n framePositionals,\n ),\n };\n}\n\n/**\n * Shell-agnostic expand location for a positional. Positionals are never\n * global (the runtime parser does not propagate positionals across frames)\n * and never array-dedup hosts (`key=value` semantics don't apply), so those\n * bits are hard-coded.\n */\nexport function positionalExpandLocation(\n pos: CompletablePositional,\n frameOptions: readonly CompletableOption[],\n framePositionals: readonly CompletablePositional[],\n): BaseExpandLocation {\n return {\n fieldName: pos.name,\n isArrayOption: false,\n isGlobal: false,\n resolvedDeps: resolveExpandDepGlobality(\n pos.valueCompletion,\n false,\n frameOptions,\n framePositionals,\n ),\n };\n}\n\n/**\n * Resolve each `dependsOn` entry to its globality at codegen time. A\n * global host's deps all live in the global namespace. A local host\n * may declare deps against a propagated global (its sibling index\n * includes globals); those individual deps must read from the global\n * bucket even when the host itself is local — the tracker only ever\n * writes the global value into \\`_global_arg_values_<name>\\`, so a\n * lookup against the local bucket would see the empty key.\n *\n * Local-precedence matches `buildSiblingIndex` in `expand-resolver.ts`:\n * a dep name that exists on a local field (option OR positional) at the\n * frame resolves to the local, even if a same-named global also exists.\n * Marking such a dep as global would route the lookup at the wrong\n * bucket and produce no candidates.\n */\nexport function resolveExpandDepGlobality(\n vc: ValueCompletion | undefined,\n hostIsGlobal: boolean,\n frameOptions: readonly CompletableOption[],\n framePositionals: readonly { name: string }[] = [],\n): readonly ResolvedExpandDep[] {\n if (vc?.type !== \"expand\") return [];\n const globalOptionNames = new Set<string>();\n const localFieldNames = new Set<string>();\n for (const o of frameOptions) {\n if (o.isGlobal === true) globalOptionNames.add(o.name);\n else localFieldNames.add(o.name);\n }\n for (const p of framePositionals) localFieldNames.add(p.name);\n return vc.dependsOn.map((name) => ({\n name,\n isGlobal: hostIsGlobal || (globalOptionNames.has(name) && !localFieldNames.has(name)),\n }));\n}\n\n/**\n * Encode a string as an ANSI-C shell literal (`$'…'`) with backslash\n * escapes. Used by bash and zsh to embed expand-table values so newlines,\n * the unit-separator key delimiter, and other control characters survive\n * verbatim.\n */\nexport function ansiC(s: string): string {\n let out = \"$'\";\n for (const ch of s) {\n const code = ch.codePointAt(0)!;\n if (ch === \"\\\\\") out += \"\\\\\\\\\";\n else if (ch === \"'\") out += \"\\\\'\";\n else if (ch === \"\\n\") out += \"\\\\n\";\n else if (ch === \"\\r\") out += \"\\\\r\";\n else if (ch === \"\\t\") out += \"\\\\t\";\n else if (code < 0x20 || code === 0x7f) out += `\\\\x${code.toString(16).padStart(2, \"0\")}`;\n else out += ch;\n }\n out += \"'\";\n return out;\n}\n\n/**\n * Render an alias as its CLI token form: single-char aliases become `-x`,\n * multi-char aliases become `--long`. Mirrors the parser's accepted shapes\n * and is the bare-token form (no quoting) used inside generated case\n * patterns.\n */\nexport function aliasToken(alias: string): string {\n return alias.length === 1 ? `-${alias}` : `--${alias}`;\n}\n\n/**\n * Append every alternate spelling runtime's aliasMap accepts for an alias:\n * `-a` / `--a` for single-char, `--to-be` / `--toBe` for hyphenated.\n * Shared between {@link collectOptionTokens} and {@link localShadowingTokens}.\n */\nfunction pushAliasTokens(tokens: string[], a: string): void {\n pushUnique(tokens, aliasToken(a));\n if (a.length === 1) pushUnique(tokens, `--${a}`);\n else if (a.includes(\"-\")) pushUnique(tokens, `--${toCamelCase(a)}`);\n}\n\nfunction pushUnique(tokens: string[], t: string): void {\n if (!tokens.includes(t)) tokens.push(t);\n}\n\n/**\n * Every CLI spelling the runtime's aliasMap routes to this option:\n * - `--cliName` (always),\n * - `-x` when `cliName` is one character,\n * - `--toCamelCase(cliName)` when `cliName` is hyphenated,\n * - and the analogous forms for each alias.\n *\n * The order is stable so shell-side case patterns stay diff-friendly.\n */\nexport function collectOptionTokens(\n cliName: string,\n aliases: readonly string[] | undefined,\n): string[] {\n const tokens = [`--${cliName}`];\n if (cliName.length === 1) tokens.push(`-${cliName}`);\n if (cliName.includes(\"-\")) tokens.push(`--${toCamelCase(cliName)}`);\n for (const a of aliases ?? []) pushAliasTokens(tokens, a);\n return tokens;\n}\n\n/**\n * Single-character tokens (`-x`) that global options at this frame own.\n * Shared between availability-guard and value-completion token filtering:\n * both paths must agree on which short forms `separateGlobalArgs` routes\n * to a global rather than a same-letter local.\n */\nexport function globalShortTokens(frameOptions: readonly CompletableOption[]): Set<string> {\n const out = new Set<string>();\n for (const o of frameOptions) {\n if (o.isGlobal !== true) continue;\n if (o.cliName.length === 1) out.add(`-${o.cliName}`);\n for (const a of o.alias ?? []) {\n if (a.length === 1) out.add(`-${a}`);\n }\n }\n return out;\n}\n\n/**\n * Build the quoted-token list bash/zsh/fish pass to `__<fn>_not_used` to\n * decide whether an option (and its negation form, if any) is still\n * available. Quoting style (`\"…\"`) is identical across all three shells,\n * so the helper lives here instead of being re-derived per generator.\n */\nexport function quotedAvailabilityTokens(\n cliName: string,\n aliases: readonly string[] | undefined,\n negation: string | undefined,\n options?: {\n isGlobal?: boolean;\n /**\n * Other options at the same frame. Used to drop short tokens that a\n * global owns from a LOCAL's availability guard — otherwise consuming\n * \\`-e\\` (routed to a global) would hide the local's still-available\n * \\`--e\\` suggestion.\n */\n frameOptions?: readonly CompletableOption[];\n },\n): string[] {\n // Mirror every spelling the runtime aliasMap accepts so the\n // used-option guard covers each form a value-completion case (or\n // tracker) might consume. Without this, the option-name suggestion\n // path still offers the canonical \\`--cliName\\` after the user\n // consumed it as \\`-x\\` / \\`--f\\` / \\`--toBe\\`.\n const tokens = new Set<string>(collectOptionTokens(cliName, aliases));\n if (negation) {\n tokens.add(`--${negation}`);\n if (negation.includes(\"-\")) tokens.add(`--${toCamelCase(negation)}`);\n }\n // Drop tokens runtime would NOT route to this option. For a LOCAL\n // option, a short token owned by a global at the same frame is\n // never consumed locally. For a GLOBAL option, every spelling a\n // local at the frame owns (long-form cliName, explicit aliases) is\n // routed to the local — guarding on it would falsely suppress the\n // global's canonical suggestion after the local was used.\n if (options?.frameOptions) {\n if (options.isGlobal === true) {\n for (const o of options.frameOptions) {\n if (o.isGlobal === true) continue;\n for (const t of localShadowingTokens(o.cliName, o.alias)) tokens.delete(t);\n }\n } else {\n const globalShort = globalShortTokens(options.frameOptions);\n if (globalShort.size > 0) {\n const localExplicitShort = new Set(\n (aliases ?? []).filter((a) => a.length === 1).map((a) => `-${a}`),\n );\n for (const g of globalShort) {\n if (!localExplicitShort.has(g)) tokens.delete(g);\n }\n }\n }\n }\n return [...tokens].map((t) => `\"${t}\"`);\n}\n\n/**\n * Tokens the runtime's `separateGlobalArgs` would consider locally\n * owned at the leaf: long-form cliName plus every EXPLICIT alias\n * spelling (in all forms the aliasMap accepts — `-a`/`--a` for short,\n * `--to-be`/`--toBe` for hyphenated). Excludes the auto-derived `-x`\n * for a 1-char cliName because that short form lives in the local\n * aliasMap only when an explicit alias declares it.\n */\nexport function localShadowingTokens(\n cliName: string,\n aliases: readonly string[] | undefined,\n): string[] {\n // Same shape as `collectOptionTokens` minus the auto-derived `-x`\n // short form for a bare 1-char cliName: that short form never\n // registers in the local aliasMap unless an EXPLICIT `alias: \"x\"`\n // declares it.\n const tokens = [`--${cliName}`];\n if (cliName.includes(\"-\")) tokens.push(`--${toCamelCase(cliName)}`);\n for (const a of aliases ?? []) pushAliasTokens(tokens, a);\n return tokens;\n}\n","/**\n * Shared value completion resolver\n *\n * Resolves value completion metadata from field information.\n * Used by both the static extractor and the dynamic context parser.\n */\n\nimport type { DynamicCompletionResolver } from \"../core/dynamic-completion-types.js\";\nimport type { ExpandCompletion } from \"../core/expand-completion-types.js\";\nimport type { ValueCompletion } from \"./types.js\";\n\n/**\n * Sentinel returned when a field uses `completion.custom.expand`. The static\n * extractor recognises this and replaces it with a fully resolved\n * `{ type: \"expand\", ... }` ValueCompletion after sibling args' static\n * values are known. Internal: never assigned onto `CompletableOption` /\n * `CompletablePositional` directly; callers stash it in a side map keyed by\n * field name and patch the resolved spec in afterwards.\n */\nexport interface PendingExpandValueCompletion {\n type: \"pending-expand\";\n spec: ExpandCompletion;\n}\n\n/**\n * Minimal field interface needed for resolving value completion.\n * Both ResolvedFieldMeta and inline context-parser types satisfy this.\n */\nexport interface ValueCompletionField {\n completion?:\n | ({\n type?: string;\n custom?: {\n choices?: string[];\n shellCommand?: string;\n resolve?: DynamicCompletionResolver;\n expand?: ExpandCompletion;\n };\n } & ({ extensions?: string[]; matcher?: never } | { matcher?: string[]; extensions?: never }))\n | undefined;\n enumValues?: string[] | undefined;\n /** Field name surfaced in error messages when custom variants are mixed. */\n name?: string;\n}\n\n/**\n * Resolve value completion from field metadata.\n *\n * Priority (within `custom`): `expand` > `resolve` > `choices` > `shellCommand`.\n * Specifying more than one of these on the same field throws so the\n * misconfiguration surfaces at command-definition time rather than at\n * completion time. The `expand` variant returns a sentinel — the extractor\n * resolves it against sibling fields and replaces the sentinel with a\n * `{ type: \"expand\", table, dependsOn }` entry.\n *\n * Outside `custom`: explicit `type` (file/directory/none) > auto-detected\n * enum values from the schema.\n */\nexport function resolveValueCompletion(\n field: ValueCompletionField,\n): ValueCompletion | PendingExpandValueCompletion | undefined {\n const meta = field.completion;\n\n if (meta?.custom) {\n const c = meta.custom;\n const definedKeys: string[] = [];\n if (c.expand) definedKeys.push(\"expand\");\n if (c.resolve) definedKeys.push(\"resolve\");\n if (c.choices && c.choices.length > 0) definedKeys.push(\"choices\");\n if (c.shellCommand) definedKeys.push(\"shellCommand\");\n\n if (definedKeys.length > 1) {\n throw new Error(\n `Field \"${field.name ?? \"<unknown>\"}\": completion.custom may only specify one of choices, shellCommand, resolve, expand (got ${definedKeys.join(\", \")}).`,\n );\n }\n\n if (c.expand) {\n return { type: \"pending-expand\", spec: c.expand };\n }\n if (c.resolve) {\n return { type: \"dynamic\", resolve: c.resolve };\n }\n if (c.choices && c.choices.length > 0) {\n return { type: \"choices\", choices: c.choices };\n }\n if (c.shellCommand) {\n return { type: \"command\", shellCommand: c.shellCommand };\n }\n }\n\n // Priority 2: Explicit completion type\n if (meta?.type) {\n if (meta.type === \"file\") {\n if (meta.matcher) return { type: \"file\", matcher: meta.matcher };\n if (meta.extensions) return { type: \"file\", extensions: meta.extensions };\n return { type: \"file\" };\n }\n if (meta.type === \"directory\") {\n return { type: \"directory\" };\n }\n if (meta.type === \"none\") {\n return { type: \"none\" };\n }\n }\n\n // Priority 3: Auto-detect from enum schema\n if (field.enumValues && field.enumValues.length > 0) {\n return { type: \"choices\", choices: field.enumValues };\n }\n\n return undefined;\n}\n","/**\n * Parse completion context from partial command line\n */\n\nimport { extractFields, getAllAliases, toCamelCase } from \"../../core/schema-extractor.js\";\nimport { resolveSubCommandAlias } from \"../../executor/subcommand-router.js\";\nimport { resolveSubCommandMeta } from \"../../lazy.js\";\nimport type { AnyCommand, ArgsSchema } from \"../../types.js\";\nimport { collectOptionTokens } from \"../shell-shared.js\";\nimport type { CompletableOption, CompletablePositional, ValueCompletion } from \"../types.js\";\nimport {\n resolveValueCompletion,\n type PendingExpandValueCompletion,\n} from \"../value-completion-resolver.js\";\n\n/**\n * The dynamic completion path runs `__complete` at TAB time and never sees\n * \"expand\" fields (those are handled inline by the static shell script).\n * Strip the transient pending sentinel here so the rest of the runtime path\n * can stay strict about handling only resolved `ValueCompletion` values.\n */\nfunction stripPendingExpand(\n vc: ValueCompletion | PendingExpandValueCompletion | undefined,\n): ValueCompletion | undefined {\n return vc?.type === \"pending-expand\" ? undefined : vc;\n}\n\n/**\n * Completion type indicates what kind of completion is expected\n */\nexport type CompletionType =\n | \"subcommand\" // Completing a subcommand name\n | \"option-name\" // Completing an option name (--xxx, -x)\n | \"option-value\" // Completing an option's value\n | \"positional\"; // Completing a positional argument\n\n/**\n * Context for completion at current cursor position\n */\nexport interface CompletionContext {\n /** Subcommand path from root (e.g., [\"plugin\", \"add\"]) */\n subcommandPath: string[];\n /** The resolved command at current path */\n currentCommand: AnyCommand;\n /** Current word being typed (may be partial) */\n currentWord: string;\n /** Previous word (useful for option value detection) */\n previousWord: string;\n /** What type of completion is expected */\n completionType: CompletionType;\n /** Target option when completing option value */\n targetOption?: CompletableOption | undefined;\n /** Positional index when completing positional argument */\n positionalIndex?: number | undefined;\n /** Available options for current command */\n options: CompletableOption[];\n /** Available subcommands */\n subcommands: string[];\n /** Available positionals */\n positionals: CompletablePositional[];\n /** Options already used (to avoid duplicates) */\n usedOptions: Set<string>;\n /** Number of positional arguments already provided */\n providedPositionalCount: number;\n /**\n * Best-effort parsed values for the CURRENT command, keyed by camelCase\n * field name. Includes positionals (single value or string[] for variadic\n * positionals) and options (string for scalars, string[] for array\n * options). Zod validation is NOT applied — values are raw strings.\n */\n parsedArgs: Record<string, unknown>;\n /**\n * Values already supplied for the option/positional currently being\n * completed (for de-duplicating array options and oneof exclusivity in\n * dynamic resolvers).\n */\n previousValues: string[];\n}\n\n/**\n * Extract options from a command\n */\nfunction extractOptions(command: AnyCommand): CompletableOption[] {\n if (!command.args) {\n return [];\n }\n return extractOptionsFromSchema(command.args);\n}\n\nfunction extractOptionsFromSchema(schema: ArgsSchema): CompletableOption[] {\n const extracted = extractFields(schema);\n return extracted.fields\n .filter((field) => !field.positional)\n .map((field) => {\n // Merge hiddenAlias into the matcher-visible alias list. The runtime\n // parser accepts hidden aliases via `getAllAliases`, so the dynamic\n // completion parser must too — otherwise typing an accepted hidden\n // alias (`--legacy value`) leaves the sibling value unparsed and\n // unrecognised as the target being completed.\n const aliases = getAllAliases(field);\n return {\n name: field.name,\n cliName: field.cliName,\n alias: aliases.length > 0 ? aliases : undefined,\n negation: field.negationDisplay,\n negationDescription: field.negationDescription,\n description: field.description,\n takesValue: field.type !== \"boolean\",\n valueType: field.type,\n required: field.required,\n // Mirror runtime: default `--no-<cliName>` is accepted unless the\n // user opted out via `negation: false` or a custom-string negation.\n defaultNegationAccepted:\n field.type === \"boolean\" && (field.negation === undefined || field.negation === true),\n valueCompletion: stripPendingExpand(resolveValueCompletion(field)),\n };\n });\n}\n\n/**\n * Build the CLI tokens an option is recognised by (`--cliName`,\n * `--long-alias`, `-x`). Wraps `collectOptionTokens` so collision\n * detection sees every spelling the runtime aliasMap accepts — including\n * the camelCase form of hyphenated names, without which a parent-frame\n * local that intercepts `--toBe` for a global `to-be` would silently\n * skip the migration loop.\n */\nfunction optionTokenSet(opt: CompletableOption): Set<string> {\n return new Set(collectOptionTokens(opt.cliName, opt.alias));\n}\n\n/**\n * Find a global option whose CLI tokens overlap with `local`'s tokens.\n * Used at subcommand descent to migrate values the runtime's\n * `scanForSubcommand` would have routed to a global field even though\n * the completion parser stored them under a different-named local.\n */\nfunction findGlobalByTokenCollision(\n globals: readonly CompletableOption[],\n local: CompletableOption,\n): CompletableOption | undefined {\n const localTokens = optionTokenSet(local);\n for (const g of globals) {\n for (const t of optionTokenSet(g)) {\n if (localTokens.has(t)) return g;\n }\n }\n return undefined;\n}\n\n/**\n * Mirror runtime `scanForSubcommand`: walk a pre-subcommand token slice\n * with the global schema only, populating `globalParsedArgs` with the\n * values the runtime would have routed there before the next subcommand\n * boundary. Runs at every subcommand descent — the runtime invokes\n * `scanForSubcommand` recursively at each frame in `parseArgs`, so the\n * pre-sub global pass applies per descent, not just from root.\n *\n * Returns the set of global option names captured during this pre-scan.\n * Used at descent to skip the local→global token migration for entries\n * whose true value is already known here — a value-taking global\n * aliased the same as a parent-local boolean (e.g. global `--profile`\n * /`-p` and local boolean `alias: \"p\"`) would otherwise have `true`\n * written over the genuine `\"prod\"`.\n */\nfunction parsePreSubGlobals(\n tokens: readonly string[],\n globalOptions: readonly CompletableOption[],\n globalParsedArgs: Record<string, unknown>,\n): Set<string> {\n const captured = new Set<string>();\n if (globalOptions.length === 0) return captured;\n // Mirror runtime per-frame array semantics: the first time this\n // slice writes an array global, the value REPLACES any prior entry\n // (matching `rawGlobalArgs`'s shallow merge); subsequent writes in\n // the same slice append.\n const arrayWrittenInThisSlice = new Set<string>();\n const writeGlobal = (opt: CompletableOption, value: string): void => {\n writeOptionValue(globalParsedArgs, opt, value, arrayWrittenInThisSlice);\n captured.add(opt.name);\n };\n let i = 0;\n while (i < tokens.length) {\n const word = tokens[i]!;\n if (word === \"--\") break;\n if (!word.startsWith(\"-\")) break;\n // Combined short flags (`-fg`) freeze runtime scanForSubcommand —\n // mirror that, otherwise pre-pass over-consumes tokens the runtime\n // would have left for the leaf parser.\n if (!word.startsWith(\"--\") && word.length > 2) {\n const eqIdx = word.indexOf(\"=\");\n const withoutDash = eqIdx >= 0 ? word.slice(1, eqIdx) : word.slice(1);\n if (withoutDash.length > 1) break;\n }\n const parsed = parseOption(word);\n // Reuse `findOption` so the explicit > implicit-negation precedence\n // stays in lockstep with the leaf scanner. Passing only the globals\n // list keeps local-precedence rules dormant — there are no locals to\n // shadow against during the pre-sub scan.\n const opt = findOption(globalOptions, parsed);\n if (!opt) break;\n if (opt.takesValue) {\n if (hasInlineValue(word)) {\n const eqIdx = word.indexOf(\"=\");\n writeGlobal(opt, word.slice(eqIdx + 1));\n i++;\n } else if (i + 1 < tokens.length) {\n const next = tokens[i + 1]!;\n if (next.startsWith(\"-\")) {\n i++;\n continue;\n }\n writeGlobal(opt, next);\n i += 2;\n } else {\n break;\n }\n } else {\n globalParsedArgs[opt.name] = !isNegationOf(opt, parsed);\n captured.add(opt.name);\n i++;\n }\n }\n return captured;\n}\n\n/**\n * Reshape a value pulled from local storage so it matches the global's\n * declared shape before landing in `globalParsedArgs`. Without this,\n * migrating a local scalar into an array global would expose the\n * resolver to `parsedArgs.tags === \"foo\"` instead of `[\"foo\"]` — a\n * state the runtime parser never produces.\n */\nfunction adaptValueForGlobal(value: unknown, global: CompletableOption): unknown {\n if (global.valueType === \"array\") {\n if (Array.isArray(value)) return value;\n return [value];\n }\n // Runtime's argv parser uses last-wins for scalars, so picking the\n // final element matches what `parseArgv` would have produced when\n // multiple matching tokens reach the global scalar.\n if (Array.isArray(value)) return value.at(-1);\n return value;\n}\n\n/**\n * Append globals to local, preserving local-shadowing by list ORDER rather\n * than by exclusion. Keeping a global in the merged list — even when a\n * local declares the same `cliName` — lets a global's non-colliding tokens\n * (e.g. a `-e` alias the local does not redeclare) still resolve to the\n * global. `findOption` walks the list and returns the first match, so a\n * token the local actually owns still wins.\n */\nfunction mergeGlobalOptions(\n local: CompletableOption[],\n globals: CompletableOption[],\n): CompletableOption[] {\n if (globals.length === 0) return local;\n return [...local, ...globals];\n}\n\n/**\n * Clamp a positional index against `positionals` so a value past the last\n * declared positional resolves to the trailing variadic slot (if any).\n * Returns `undefined` only when `positionals` is empty — callers can then\n * skip the variadic/previousValues path entirely.\n */\nexport function clampToVariadic(\n positionalIndex: number,\n positionals: readonly CompletablePositional[],\n): number | undefined {\n const lastIdx = positionals.length - 1;\n if (lastIdx < 0) return undefined;\n return positionalIndex > lastIdx ? lastIdx : positionalIndex;\n}\n\n/**\n * Extract positionals from a command\n */\nfunction extractPositionalsForContext(command: AnyCommand): CompletablePositional[] {\n if (!command.args) {\n return [];\n }\n\n const extracted = extractFields(command.args);\n return extracted.fields\n .filter((field) => field.positional)\n .map((field, index) => ({\n name: field.name,\n cliName: field.cliName,\n position: index,\n description: field.description,\n required: field.required,\n variadic: field.type === \"array\",\n valueCompletion: stripPendingExpand(resolveValueCompletion(field)),\n }));\n}\n\n/**\n * Get subcommand names from a command (including aliases)\n */\nfunction getSubcommandNames(command: AnyCommand): string[] {\n if (!command.subCommands) {\n return [];\n }\n const names: string[] = [];\n for (const [name, subCmd] of Object.entries(command.subCommands)) {\n // Filter out internal subcommands (e.g., __complete)\n if (name.startsWith(\"__\")) continue;\n names.push(name);\n const meta = resolveSubCommandMeta(subCmd);\n if (meta?.aliases) {\n names.push(...meta.aliases);\n }\n }\n return names;\n}\n\n/**\n * Resolve subcommand by name (including alias lookup)\n */\nfunction resolveSubcommand(command: AnyCommand, name: string): AnyCommand | null {\n if (!command.subCommands) {\n return null;\n }\n\n // Direct lookup\n const sub = command.subCommands[name];\n if (sub) {\n return resolveSubCommandMeta(sub);\n }\n\n // Alias lookup\n const canonical = resolveSubCommandAlias(command, name);\n if (canonical) {\n return resolveSubCommandMeta(command.subCommands[canonical]!);\n }\n\n return null;\n}\n\n/**\n * Check if a word is an option (starts with - or --)\n */\nfunction isOption(word: string): boolean {\n return word.startsWith(\"-\");\n}\n\ninterface ParsedOption {\n name: string;\n /** True when the user typed the long form (`--foo`), false for short (`-x`). */\n isLong: boolean;\n}\n\n/**\n * Parse option name from word, retaining the form the user typed so the\n * lookup can keep short-form (`-x`) and long-form (`--x`) matches in\n * separate token spaces — runtime negation, cliName, and multi-char\n * aliases only ever appear as long form.\n */\nfunction parseOption(word: string): ParsedOption {\n if (word.startsWith(\"--\")) {\n const withoutPrefix = word.slice(2);\n const eqIndex = withoutPrefix.indexOf(\"=\");\n return { name: eqIndex >= 0 ? withoutPrefix.slice(0, eqIndex) : withoutPrefix, isLong: true };\n }\n if (word.startsWith(\"-\")) {\n return { name: word.slice(1, 2), isLong: false };\n }\n return { name: word, isLong: true };\n}\n\n/**\n * Check if option has inline value (e.g., \"--foo=bar\")\n */\nfunction hasInlineValue(word: string): boolean {\n return word.includes(\"=\");\n}\n\n/**\n * For boolean options, the runtime parser accepts the implicit\n * `--no-<cliName>` (and camelCase `--noCliName`) form unless the user\n * opted out via `negation: false` or supplied a custom-string negation\n * (which suppresses the default form). Aliases participate too: a\n * boolean with `alias: \"c\"` accepts `--no-c` / `--noC` because the\n * runtime resolves the post-`no-` segment through `aliasMap`. Implicit\n * negation is LONG-FORM only — `-no-c` is never an accepted negation —\n * so callers must say so via `isLong` to prevent a short option from\n * being read as a negation.\n */\nfunction isImplicitBooleanNegation(opt: CompletableOption, name: string, isLong: boolean): boolean {\n if (!isLong) return false;\n if (opt.valueType !== \"boolean\") return false;\n if (opt.defaultNegationAccepted === false) return false;\n const candidates = [opt.cliName, ...(opt.alias ?? [])];\n for (const c of candidates) {\n const hyphenated = `no-${c}`;\n if (name === hyphenated) return true;\n if (name === toCamelCase(hyphenated)) return true;\n }\n return false;\n}\n\n/** True when `source` is hyphenated and its camelCase form equals `name`. */\nfunction matchesCamelCase(source: string | undefined, name: string): boolean {\n return source !== undefined && source.includes(\"-\") && toCamelCase(source) === name;\n}\n\n/**\n * Write `value` into `target[opt.name]` following the runtime's per-frame\n * array semantics: the first write in a frame REPLACES any inherited value\n * (mirroring the runtime's shallow merge of inherited globals), subsequent\n * writes in the same frame APPEND. Scalars overwrite unconditionally.\n * `arraysSeenInFrame` is the frame-scoped seen-set the caller maintains.\n */\nfunction writeOptionValue(\n target: Record<string, unknown>,\n opt: CompletableOption,\n value: string,\n arraysSeenInFrame: Set<string>,\n): void {\n if (opt.valueType !== \"array\") {\n target[opt.name] = value;\n return;\n }\n if (arraysSeenInFrame.has(opt.name)) {\n const existing = target[opt.name];\n target[opt.name] = Array.isArray(existing) ? [...existing, value] : [value];\n } else {\n target[opt.name] = [value];\n arraysSeenInFrame.add(opt.name);\n }\n}\n\n/**\n * True when the typed token is the boolean option's negation form — either\n * the explicit `negation` name (or its camelCase variant) or the implicit\n * `--no-<name>` form. Long-form only; short tokens are never negations.\n */\nfunction isNegationOf(opt: CompletableOption, parsed: ParsedOption): boolean {\n if (!parsed.isLong) return false;\n if (\n opt.negation !== undefined &&\n (opt.negation === parsed.name || matchesCamelCase(opt.negation, parsed.name))\n ) {\n return true;\n }\n return isImplicitBooleanNegation(opt, parsed.name, parsed.isLong);\n}\n\n/**\n * Match by cliName, alias, camelCase variants, or an explicit negation\n * name. `isLong` separates the short (`-x`) and long (`--xxx`) token\n * spaces: cliNames and explicit negations are only valid as long form,\n * and aliases match their own length class (a 1-char alias only matches\n * short form because its token is `-x`).\n */\nfunction matchesExplicit(opt: CompletableOption, name: string, isLong: boolean): boolean {\n // A single-character cliName / alias is reachable from BOTH `--x`\n // and `-x` at runtime — short form falls through `aliasMap` to the\n // canonical name, and long form lands in the same map. Multi-char\n // names are only invokable as long form.\n if (opt.cliName === name && (isLong || opt.cliName.length === 1)) return true;\n if (opt.alias) {\n for (const a of opt.alias) {\n if (a === name && (isLong || a.length === 1)) return true;\n }\n }\n // Custom negation names always belong to the long-form token space —\n // runtime only matches them via the `--<negation>` route.\n if (isLong && opt.negation === name) return true;\n if (!isLong || name.length <= 1) return false;\n if (matchesCamelCase(opt.cliName, name)) return true;\n if (opt.alias?.some((a) => matchesCamelCase(a, name))) return true;\n return matchesCamelCase(opt.negation, name);\n}\n\n/**\n * Find option by name or alias. Tried in two passes so that a real field\n * literally named `noFoo` always wins over `--no-foo` being interpreted as\n * the implicit negation of a sibling `foo` field — the runtime parser\n * resolves the explicit field first as well.\n *\n * Short-form precedence mirrors runtime's `separateGlobalArgs`: when a\n * global owns the `-x` alias and the local does NOT explicitly declare\n * `alias: \"x\"`, the global wins (a bare local `cliName: \"x\"` does not\n * register `x` in the local aliasMap). Long form keeps the local-first\n * order via the unshadowed merged list.\n */\nfunction findOption(\n options: readonly CompletableOption[],\n parsed: ParsedOption,\n): CompletableOption | undefined {\n if (!parsed.isLong) {\n const localWithExplicitAlias = options.find(\n (opt) => opt.isGlobal !== true && opt.alias?.includes(parsed.name) === true,\n );\n if (localWithExplicitAlias) return localWithExplicitAlias;\n const global = options.find(\n (opt) => opt.isGlobal === true && matchesExplicit(opt, parsed.name, parsed.isLong),\n );\n if (global) return global;\n }\n const explicit = options.find((opt) => matchesExplicit(opt, parsed.name, parsed.isLong));\n if (explicit) return explicit;\n return options.find((opt) => isImplicitBooleanNegation(opt, parsed.name, parsed.isLong));\n}\n\n/**\n * Parse completion context from command line arguments\n *\n * @param argv - Arguments after the program name (e.g., [\"build\", \"--fo\"])\n * @param rootCommand - The root command\n * @param globalArgsSchema - Optional global args. When provided, options\n * derived from this schema are merged into every command level so dynamic\n * resolvers attached to global options can be reached from any subcommand.\n * @returns Completion context\n */\nexport function parseCompletionContext(\n argv: string[],\n rootCommand: AnyCommand,\n globalArgsSchema?: ArgsSchema,\n): CompletionContext {\n // Initialize with root command\n let currentCommand = rootCommand;\n const subcommandPath: string[] = [];\n\n // Tag every global-schema option with `isGlobal: true` so the\n // value-routing logic in `recordOptionValue` / `recordBooleanFlag` can\n // tell a global match apart from a same-shaped local match purely\n // through the option object, without re-scanning the global schema.\n const globalOptions: CompletableOption[] = globalArgsSchema\n ? extractOptionsFromSchema(globalArgsSchema).map((o) => ({ ...o, isGlobal: true }))\n : [];\n\n // Track used options and positional count\n const usedOptions = new Set<string>();\n let positionalCount = 0;\n\n // Best-effort parsed values for the CURRENT command. Reset when traversing\n // into a subcommand so dynamic resolvers only see siblings on the same\n // command frame. Global option values live in a separate map so they\n // survive subcommand descent — runtime accumulates globals across the\n // command path, and resolvers attached to global options expect them\n // visible regardless of where the option was supplied.\n let parsedArgs: Record<string, unknown> = {};\n let positionalValues: string[] = [];\n const globalParsedArgs: Record<string, unknown> = {};\n\n // Track every global name captured by the per-descent pre-sub scan.\n // At each descent the runtime's `scanForSubcommand` routes pre-sub\n // tokens to globals even when a parent-local schema shadows the same\n // alias; the migration logic below skips any name in this set so a\n // local parse (`-p` boolean) doesn't clobber the genuine global value\n // (`-p prod` → `profile = \"prod\"`).\n const globalsCapturedByPreSubScan = new Set<string>();\n // Start-of-frame index in `argv`. The slice `[frameStartIdx, i)` at\n // each descent is the pre-sub token range for that frame and gets\n // re-scanned against the global schema.\n let frameStartIdx = 0;\n\n // Names of array options written in the current command frame. Used to\n // mirror the runtime's per-frame array semantics: the first `--arr v`\n // in a frame *replaces* any value inherited from the parent frame (the\n // runtime's shallow merge of `rawGlobalArgs`), while subsequent\n // `--arr v` in the same frame *append*. Cleared on every subcommand\n // descent below.\n let arraysSetInCurrentFrame = new Set<string>();\n\n /**\n * Mark the option's cliName plus every alias and (if present) negation\n * form as consumed. The negation shares the field's \"used\" slot so\n * typing either form filters both from subsequent suggestions.\n */\n const markUsed = (opt: CompletableOption): void => {\n usedOptions.add(opt.cliName);\n for (const a of opt.alias ?? []) usedOptions.add(a);\n if (opt.negation) usedOptions.add(opt.negation);\n };\n\n const recordOptionValue = (opt: CompletableOption, value: string): void => {\n const target = opt.isGlobal === true ? globalParsedArgs : parsedArgs;\n writeOptionValue(target, opt, value, arraysSetInCurrentFrame);\n };\n\n /**\n * Record a boolean flag the user typed. The positive form sets `true`;\n * the negation form (`--no-foo` or a custom `negationDisplay`) sets\n * `false`. Dynamic resolvers depend on these values to switch candidates\n * based on flag state, so the absence of a writer here used to hide\n * boolean siblings entirely.\n */\n const recordBooleanFlag = (opt: CompletableOption, parsed: ParsedOption): void => {\n const target = opt.isGlobal === true ? globalParsedArgs : parsedArgs;\n target[opt.name] = !isNegationOf(opt, parsed);\n };\n\n // Process arguments to resolve subcommands and track state\n let i = 0;\n let options = mergeGlobalOptions(extractOptions(currentCommand), globalOptions);\n let afterDoubleDash = false;\n\n // Traverse subcommands\n while (i < argv.length - 1) {\n const word = argv[i]!;\n\n // \"--\" marks the end of option parsing\n if (!afterDoubleDash && word === \"--\") {\n afterDoubleDash = true;\n i++;\n continue;\n }\n\n // Combined short boolean flags such as `-ab` ⇒ `-a -b`. The runtime\n // parser unpacks these; the completion parser must do the same so a\n // resolver sees both flags as set. Only attempted when every char in\n // the group resolves to a value-less option, otherwise the word is\n // ambiguous (`-cVALUE` syntax) and we fall through to the single-\n // char path below.\n if (\n !afterDoubleDash &&\n word.startsWith(\"-\") &&\n !word.startsWith(\"--\") &&\n word.length > 2 &&\n !word.includes(\"=\")\n ) {\n const chars: string[] = Array.from(word.slice(1));\n // Runtime's global separation (`scanForSubcommand` /\n // `separateGlobalArgs`) does NOT decompose combined short flags\n // — only the leaf-level local parser does. Mirror that here by\n // matching each char against LOCAL options only and recording\n // every resolved boolean. A char that doesn't resolve locally\n // (or that maps to a value-taking option) is a no-op, just like\n // the runtime's `setOption` on an unknown short. Always consume\n // the whole combined word so the single-option branch below\n // does not misread `-ab` as `-a`.\n const localOptions = options.filter((o) => o.isGlobal !== true);\n for (const c of chars) {\n const o = findOption(localOptions, { name: c, isLong: false });\n if (!o || o.takesValue) continue;\n markUsed(o);\n recordBooleanFlag(o, { name: c, isLong: false });\n }\n i++;\n continue;\n }\n\n // Skip options and their values (before \"--\")\n if (!afterDoubleDash && isOption(word)) {\n const parsed = parseOption(word);\n const opt = findOption(options, parsed);\n\n if (opt) {\n markUsed(opt);\n\n if (opt.takesValue) {\n if (hasInlineValue(word)) {\n const eqIdx = word.indexOf(\"=\");\n recordOptionValue(opt, word.slice(eqIdx + 1));\n } else if (i + 1 < argv.length - 1) {\n const next = argv[i + 1]!;\n // Mirror the runtime parser (`parseArgv`): a token starting\n // with `-` is treated as the next option, not as this\n // option's value. Otherwise `--config --flag --field <TAB>`\n // records `config === \"--flag\"` and leaves `flag` unset,\n // so the resolver sees a state the runtime never produces.\n if (!isOption(next)) {\n recordOptionValue(opt, next);\n i++;\n }\n }\n } else {\n recordBooleanFlag(opt, parsed);\n }\n }\n i++;\n continue;\n }\n\n // Check if this is a subcommand (before \"--\")\n const subcommand = afterDoubleDash ? null : resolveSubcommand(currentCommand, word);\n if (subcommand) {\n subcommandPath.push(word);\n // Capture the parent's local options BEFORE switching frames so\n // the migration loop below can resolve token collisions against\n // them; once `currentCommand` flips to the child we lose access\n // to the parent's schema.\n const parentLocalOptions = extractOptions(currentCommand);\n // Pre-scan this frame's pre-sub slice with the global schema.\n // Runtime's `scanForSubcommand` runs at every frame in the\n // recursive `parseArgs` descent, routing pre-sub tokens to\n // globals — applies to nested parents too, not just root.\n const preSubSlice = argv.slice(frameStartIdx, i);\n for (const name of parsePreSubGlobals(preSubSlice, globalOptions, globalParsedArgs)) {\n globalsCapturedByPreSubScan.add(name);\n }\n currentCommand = subcommand;\n options = mergeGlobalOptions(extractOptions(currentCommand), globalOptions);\n // Migrate values the parent frame recorded locally that the\n // runtime would have routed to a global instead. Runtime's\n // `scanForSubcommand` only knows the global schema and harvests\n // any flag matching a global token as global when it precedes a\n // descent, so two shapes of collision both need to migrate:\n // - Same-name shadow: parent declares a local with the SAME\n // field name as a global → write-time used the (unshadowed)\n // local store; we migrate by field name here.\n // - Token collision: parent's local shares a CLI token (alias,\n // camelCase variant) with a global option of a DIFFERENT\n // name → write-time still stored under the local's name, but\n // the runtime would have surfaced the value as\n // `globalArgs[globalOpt.name]`. Migrate to the global's name.\n for (const key of Object.keys(parsedArgs)) {\n const localOpt = parentLocalOptions.find((o) => o.name === key);\n const sameNameGlobal = globalOptions.find((g) => g.name === key);\n const tokenCollidingGlobal =\n sameNameGlobal ??\n (localOpt ? findGlobalByTokenCollision(globalOptions, localOpt) : undefined);\n if (!tokenCollidingGlobal) continue;\n // Skip migration when this descent's (or an earlier descent's)\n // pre-sub global scan already populated the authoritative value;\n // overwriting with the arity-adapted local would clobber it.\n if (globalsCapturedByPreSubScan.has(tokenCollidingGlobal.name)) continue;\n globalParsedArgs[tokenCollidingGlobal.name] = adaptValueForGlobal(\n parsedArgs[key],\n tokenCollidingGlobal,\n );\n }\n usedOptions.clear(); // Reset for new subcommand\n positionalCount = 0;\n parsedArgs = {};\n positionalValues = [];\n // Mirror the runner's per-frame array semantics: keep the parent\n // frame's value as the inherited starting point (shallow merge\n // preserves it when the child doesn't redeclare). The \"first set\n // in this frame replaces\" rule is enforced by clearing the\n // per-frame seen-set instead of deleting the accumulator outright.\n arraysSetInCurrentFrame = new Set<string>();\n frameStartIdx = i + 1;\n i++;\n continue;\n }\n\n // Otherwise it's a positional argument\n positionalValues.push(word);\n positionalCount++;\n i++;\n }\n\n // Get current and previous word\n const currentWord: string = argv[argv.length - 1] ?? \"\";\n const previousWord: string = argv[argv.length - 2] ?? \"\";\n\n // Extract data for current command\n const positionals = extractPositionalsForContext(currentCommand);\n const subcommands = getSubcommandNames(currentCommand);\n\n // Map collected positional values to their field names so resolvers can\n // reference them like options. The trailing variadic positional (if any)\n // absorbs every value beyond `positionals.length - 1`.\n for (let p = 0; p < positionals.length; p++) {\n const pos = positionals[p]!;\n if (pos.variadic) {\n parsedArgs[pos.name] = positionalValues.slice(p);\n break;\n }\n if (p < positionalValues.length) {\n parsedArgs[pos.name] = positionalValues[p];\n }\n }\n\n // Determine completion type\n let completionType: CompletionType;\n let targetOption: CompletableOption | undefined;\n let positionalIndex: number | undefined;\n\n // Case 1: Previous word is an option that takes a value\n if (!afterDoubleDash && previousWord && isOption(previousWord) && !hasInlineValue(previousWord)) {\n const opt = findOption(options, parseOption(previousWord));\n if (opt && opt.takesValue) {\n completionType = \"option-value\";\n targetOption = opt;\n } else if (currentWord.startsWith(\"-\")) {\n // Previous word is boolean flag, current word starts with - → option name\n completionType = \"option-name\";\n } else {\n completionType = determineDefaultCompletionType(\n currentWord,\n subcommands,\n positionals,\n positionalCount,\n );\n if (completionType === \"positional\") {\n positionalIndex = positionalCount;\n }\n }\n }\n // Case 2: Current word is an option with inline value (--foo= or -f=).\n // Runtime accepts both shapes; the generated bash script's pre-scan\n // already splits the short form for earlier words, and now the\n // option-value classifier matches it for the current word too.\n else if (!afterDoubleDash && currentWord.startsWith(\"-\") && hasInlineValue(currentWord)) {\n const opt = findOption(options, parseOption(currentWord));\n if (opt && opt.takesValue) {\n completionType = \"option-value\";\n targetOption = opt;\n } else {\n completionType = \"option-name\";\n }\n }\n // Case 3: Current word starts with - (completing option name)\n else if (!afterDoubleDash && currentWord.startsWith(\"-\")) {\n completionType = \"option-name\";\n }\n // Case 4: Determine based on available subcommands and positionals\n else {\n completionType = determineDefaultCompletionType(\n currentWord,\n subcommands,\n positionals,\n positionalCount,\n afterDoubleDash,\n );\n if (completionType === \"positional\") {\n positionalIndex = positionalCount;\n }\n }\n\n // Compute previousValues for the target of completion. Useful for resolvers\n // that need to de-dup repeated array options or enforce oneof exclusivity.\n let previousValues: string[] = [];\n if (targetOption) {\n if (targetOption.valueType === \"array\") {\n const store = targetOption.isGlobal === true ? globalParsedArgs : parsedArgs;\n const stored = store[targetOption.name];\n previousValues = Array.isArray(stored)\n ? stored.filter((v): v is string => typeof v === \"string\")\n : [];\n }\n } else if (completionType === \"positional\" && positionalIndex !== undefined) {\n const clampedIdx = clampToVariadic(positionalIndex, positionals);\n if (clampedIdx !== undefined && positionals[clampedIdx]?.variadic) {\n previousValues = positionalValues.slice(clampedIdx);\n }\n }\n\n // Expose globals alongside locals; local args win on name collision.\n const mergedParsedArgs: Record<string, unknown> = { ...globalParsedArgs, ...parsedArgs };\n\n return {\n subcommandPath,\n currentCommand,\n currentWord,\n previousWord,\n completionType,\n targetOption,\n positionalIndex,\n options,\n subcommands,\n positionals,\n usedOptions,\n providedPositionalCount: positionalCount,\n parsedArgs: mergedParsedArgs,\n previousValues,\n };\n}\n\n/**\n * Determine default completion type when not completing an option\n */\nfunction determineDefaultCompletionType(\n currentWord: string,\n subcommands: string[],\n positionals: CompletablePositional[],\n positionalCount: number,\n afterDoubleDash?: boolean,\n): CompletionType {\n // After --, everything is positional — never suggest subcommands or options\n if (afterDoubleDash) {\n return \"positional\";\n }\n\n // If there are subcommands and current word might match one, suggest subcommands\n if (subcommands.length > 0) {\n // Check if any subcommand starts with current word\n const matchingSubcommands = subcommands.filter((s) => s.startsWith(currentWord));\n if (matchingSubcommands.length > 0 || currentWord === \"\") {\n return \"subcommand\";\n }\n }\n\n // If there are positionals to complete\n if (positionalCount < positionals.length) {\n return \"positional\";\n }\n\n // If the last positional is variadic (array), continue with positional\n if (positionals.length > 0 && positionals[positionals.length - 1]!.variadic) {\n return \"positional\";\n }\n\n // Default to subcommand (will show options too)\n return \"subcommand\";\n}\n","/**\n * Generate completion candidates based on context\n */\n\nimport { execSync } from \"node:child_process\";\nimport type { DynamicCompletionContext } from \"../../core/dynamic-completion-types.js\";\nimport { resolveSubCommandAlias } from \"../../executor/subcommand-router.js\";\nimport { resolveSubCommandMeta } from \"../../lazy.js\";\nimport type { CompletablePositional, ShellType, ValueCompletion } from \"../types.js\";\nimport { clampToVariadic, type CompletionContext } from \"./context-parser.js\";\n\n/**\n * Completion directive flags (bitwise)\n */\nexport const CompletionDirective = {\n /** Default completion behavior */\n Default: 0,\n /** Don't add space after completion */\n NoSpace: 1,\n /** Don't offer file completion (even if no other completions) */\n NoFileCompletion: 2,\n /** Filter completions using current word as prefix */\n FilterPrefix: 4,\n /** Keep the order of completions */\n KeepOrder: 8,\n /** Trigger file completion */\n FileCompletion: 16,\n /** Trigger directory completion */\n DirectoryCompletion: 32,\n /** Error occurred during completion */\n Error: 64,\n} as const;\n\n/**\n * A completion candidate\n */\nexport interface CompletionCandidate {\n /** The completion value */\n value: string;\n /** Optional description */\n description?: string | undefined;\n /** Type hint for display purposes */\n type?: \"option\" | \"subcommand\" | \"value\" | \"file\" | \"directory\";\n}\n\n/**\n * Result of candidate generation\n */\nexport interface CandidateResult {\n /** Completion candidates */\n candidates: CompletionCandidate[];\n /** Directive flags for shell behavior */\n directive: number;\n /** File extensions for shell-native filtering (e.g., [\"json\", \"yaml\"]) */\n fileExtensions?: string[] | undefined;\n /** Glob patterns for shell-native file matching (e.g., [\".env.*\"]) */\n fileMatchers?: string[] | undefined;\n}\n\n/**\n * Options for candidate generation.\n */\nexport interface GenerateCandidatesOptions {\n /**\n * Target shell. Forwarded to dynamic resolvers so they can vary output\n * (e.g. include descriptions only for shells that render them).\n */\n shell: ShellType;\n}\n\n/**\n * Detect an inline `--opt=` prefix on an option-value `currentWord`.\n * Mirrors what the shell scripts already strip via `_inline_prefix`, so\n * resolvers see only the value portion (e.g. `foo` for `--field=foo`).\n * Positional words are excluded: `cli -- --foo=bar` is a legitimate\n * positional value, not an inline option assignment.\n */\nexport function detectInlineOptionPrefix(currentWord: string): string | undefined {\n if (!currentWord.startsWith(\"-\")) return undefined;\n const eqIdx = currentWord.indexOf(\"=\");\n if (eqIdx <= 0) return undefined;\n return currentWord.slice(0, eqIdx + 1);\n}\n\n/**\n * Generate completion candidates based on context.\n *\n * Async because dynamic resolvers may return promises. Sync completion\n * sources (choices/file/directory/command/none, subcommand, option name)\n * still resolve synchronously and the await is a no-op for them.\n *\n * Inline option-value prefixes (`--field=foo`) on the option-value path\n * are stripped here so resolvers and post-processing always see the\n * value portion regardless of whether the caller pre-normalized.\n */\nexport async function generateCandidates(\n context: CompletionContext,\n options: GenerateCandidatesOptions,\n): Promise<CandidateResult> {\n switch (context.completionType) {\n case \"subcommand\":\n return generateSubcommandCandidates(context);\n case \"option-name\":\n return generateOptionNameCandidates(context);\n case \"option-value\": {\n const opt = context.targetOption;\n const inlinePrefix = opt ? detectInlineOptionPrefix(context.currentWord) : undefined;\n const effectiveContext = inlinePrefix\n ? { ...context, currentWord: context.currentWord.slice(inlinePrefix.length) }\n : context;\n return generateValueCandidates(effectiveContext, options, opt?.name, opt?.valueCompletion);\n }\n case \"positional\": {\n const positional = resolvePositionalTarget(context);\n return generateValueCandidates(\n context,\n options,\n positional?.name,\n positional?.valueCompletion,\n positional?.description,\n );\n }\n }\n}\n\n/**\n * Pick the positional whose `valueCompletion` should drive the current\n * cursor. Clamps to the trailing variadic positional so a value beyond\n * the schema's positional count still resolves to the variadic slot —\n * but only when that slot IS variadic; otherwise a non-variadic last\n * positional must not greedily absorb the extra value.\n */\nfunction resolvePositionalTarget(context: CompletionContext): CompletablePositional | undefined {\n const requestedIdx = context.positionalIndex ?? 0;\n const clampedIdx = clampToVariadic(requestedIdx, context.positionals);\n if (clampedIdx === undefined) return undefined;\n const candidate = context.positionals[clampedIdx];\n if (!candidate) return undefined;\n return clampedIdx === requestedIdx || candidate.variadic ? candidate : undefined;\n}\n\n/**\n * Execute a shell command and return results as candidates\n */\nfunction executeShellCommand(command: string): CompletionCandidate[] {\n try {\n const output = execSync(command, { encoding: \"utf-8\", timeout: 5000 });\n return output\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => ({ value: line, type: \"value\" as const }));\n } catch {\n return [];\n }\n}\n\n/**\n * Two-stage `key=value` post-processing. Returns the transformed candidate\n * list plus whether it contains a bare `key=` entry so the caller can flip\n * NoSpace and let the user keep typing past the first TAB.\n *\n * Key stage (`=` not yet typed): collapse every `key=value` candidate to a\n * unique `key=` entry so the first TAB picks the key.\n *\n * Value stage (`=` typed): drop only the bare `<key>=` candidate that\n * echoes the prefix the user already typed. A blanket `endsWith(\"=\")`\n * filter would also remove legitimate values such as base64 `key=YWJj=` or\n * value-only `YWJj=` (padding), so match the candidate string exactly\n * against the typed key prefix.\n */\nfunction applyKeyValuePostProcessing(\n candidates: readonly CompletionCandidate[],\n currentWord: string,\n): { candidates: CompletionCandidate[]; hasEqSuffix: boolean } {\n const keyStage = !currentWord.includes(\"=\");\n const processed = keyStage\n ? collapseToKeys(candidates)\n : dropBareKeyEcho(candidates, currentWord);\n // Flip NoSpace only at key stage where a candidate ending with `=`\n // really is a bare-key marker. At value stage a candidate like\n // `YWJj=` is a concrete value, so NoSpace would incorrectly suppress\n // the trailing space after a regular value selection.\n return {\n candidates: processed,\n hasEqSuffix: keyStage && processed.some((c) => c.value.endsWith(\"=\")),\n };\n}\n\nfunction collapseToKeys(candidates: readonly CompletionCandidate[]): CompletionCandidate[] {\n const seen = new Set<string>();\n const out: CompletionCandidate[] = [];\n for (const c of candidates) {\n const eqIdx = c.value.indexOf(\"=\");\n if (eqIdx <= 0) {\n out.push(c);\n continue;\n }\n const keyPart = c.value.slice(0, eqIdx + 1);\n if (seen.has(keyPart)) continue;\n seen.add(keyPart);\n out.push({ ...c, value: keyPart });\n }\n return out;\n}\n\nfunction dropBareKeyEcho(\n candidates: readonly CompletionCandidate[],\n currentWord: string,\n): CompletionCandidate[] {\n const keyPrefix = currentWord.slice(0, currentWord.indexOf(\"=\") + 1);\n return candidates.filter((c) => c.value !== keyPrefix);\n}\n\n/**\n * Resolve value completion, executing shell commands and file lookups in JS\n */\nasync function resolveValueCandidates(\n vc: ValueCompletion,\n ctx: DynamicCompletionContext,\n description?: string,\n): Promise<CandidateResult> {\n const candidates: CompletionCandidate[] = [];\n let directive: number = CompletionDirective.FilterPrefix;\n let fileExtensions: string[] | undefined;\n let fileMatchers: string[] | undefined;\n\n switch (vc.type) {\n case \"choices\":\n if (vc.choices) {\n for (const choice of vc.choices) {\n candidates.push({\n value: choice,\n description,\n type: \"value\",\n });\n }\n }\n directive |= CompletionDirective.NoFileCompletion;\n break;\n\n case \"file\":\n if (vc.matcher && vc.matcher.length > 0) {\n // Delegate to shell with glob matcher metadata\n fileMatchers = vc.matcher.filter((m) => m.trim().length > 0);\n if (fileMatchers.length === 0) {\n fileMatchers = undefined;\n directive |= CompletionDirective.FileCompletion;\n }\n } else if (vc.extensions && vc.extensions.length > 0) {\n // Delegate to shell with extension filter metadata\n fileExtensions = Array.from(\n new Set(\n vc.extensions\n .map((ext) => ext.trim().replace(/^\\./, \"\"))\n .filter((ext) => ext.length > 0),\n ),\n );\n if (fileExtensions.length === 0) {\n // All extensions were invalid → treat as unfiltered file completion\n fileExtensions = undefined;\n directive |= CompletionDirective.FileCompletion;\n }\n } else {\n // No extensions or matchers: let shell handle native file completion\n directive |= CompletionDirective.FileCompletion;\n }\n break;\n\n case \"directory\":\n directive |= CompletionDirective.DirectoryCompletion;\n break;\n\n case \"command\":\n // Execute shell command in JS and add results as candidates\n if (vc.shellCommand) {\n candidates.push(...executeShellCommand(vc.shellCommand));\n }\n directive |= CompletionDirective.NoFileCompletion;\n break;\n\n case \"none\":\n directive |= CompletionDirective.NoFileCompletion;\n break;\n\n case \"dynamic\": {\n try {\n const result = await vc.resolve(ctx);\n for (const c of result.candidates) {\n const normalized = typeof c === \"string\" ? { value: c } : c;\n candidates.push({ ...normalized, type: \"value\" });\n }\n directive =\n result.directive ??\n CompletionDirective.FilterPrefix | CompletionDirective.NoFileCompletion;\n } catch {\n // Resolver failures must not break the user's shell. Surface an\n // empty candidate set with the Error directive so callers that care\n // can detect a faulted resolver.\n directive = CompletionDirective.NoFileCompletion | CompletionDirective.Error;\n }\n break;\n }\n\n case \"expand\":\n // `expand` candidates are inlined into the static shell script at\n // generation time, so the dynamic path never delegates to us for an\n // expand field. This case is reachable only if a caller invokes\n // `__complete` for an expand field directly (e.g. from tests). Return\n // no candidates with `NoFileCompletion` to mirror the choices/none\n // shapes.\n directive |= CompletionDirective.NoFileCompletion;\n break;\n }\n\n // Two-stage key=value: collapse to keys before `=` is typed, and flip\n // NoSpace whenever a candidate ends with `=` so the user can keep\n // typing the value after the first TAB. Apply only to `dynamic` and\n // `expand` sources — `choices`/`shellCommand` values containing `=`\n // are concrete (e.g. `foo=bar` literal choice) and must reach the\n // shell unchanged, matching what the static script paths emit.\n if (vc.type === \"dynamic\" || vc.type === \"expand\") {\n const processed = applyKeyValuePostProcessing(candidates, ctx.currentWord);\n if (processed.hasEqSuffix) {\n directive |= CompletionDirective.NoSpace;\n }\n return {\n candidates: processed.candidates,\n directive,\n fileExtensions,\n fileMatchers,\n };\n }\n\n return { candidates, directive, fileExtensions, fileMatchers };\n}\n\n/**\n * Generate subcommand candidates\n */\nfunction generateSubcommandCandidates(context: CompletionContext): CandidateResult {\n const candidates: CompletionCandidate[] = [];\n\n // Add subcommands (context.subcommands already includes aliases)\n for (const name of context.subcommands) {\n // Direct lookup first, fall back to alias resolution.\n const subs = context.currentCommand.subCommands;\n const direct = subs?.[name];\n const aliasCanonical = direct\n ? undefined\n : resolveSubCommandAlias(context.currentCommand, name);\n const resolved = direct ?? (aliasCanonical ? subs?.[aliasCanonical] : undefined);\n const description = resolved ? resolveSubCommandMeta(resolved)?.description : undefined;\n\n candidates.push({\n value: name,\n description,\n type: \"subcommand\",\n });\n }\n\n // Add options when no subcommands exist, or when typing an option prefix\n if (candidates.length === 0 || context.currentWord.startsWith(\"-\")) {\n const optionResult = generateOptionNameCandidates(context);\n candidates.push(...optionResult.candidates);\n }\n\n return { candidates, directive: CompletionDirective.FilterPrefix };\n}\n\n/**\n * Generate option name candidates\n */\nfunction generateOptionNameCandidates(context: CompletionContext): CandidateResult {\n const candidates: CompletionCandidate[] = [];\n\n // Filter out already used options\n const availableOptions = context.options.filter((opt) => {\n // Array options can be specified multiple times, so keep them available.\n if (opt.valueType === \"array\") {\n return true;\n }\n\n if (context.usedOptions.has(opt.cliName)) return false;\n if (opt.alias && opt.alias.some((a) => context.usedOptions.has(a))) return false;\n // The negation form shares the field's \"used\" slot: if either the positive\n // flag or its negation has already been typed, suppress both.\n if (opt.negation && context.usedOptions.has(opt.negation)) return false;\n return true;\n });\n\n for (const opt of availableOptions) {\n candidates.push({\n value: `--${opt.cliName}`,\n description: opt.description,\n type: \"option\",\n });\n if (opt.negation) {\n candidates.push({\n value: `--${opt.negation}`,\n description: opt.negationDescription ?? opt.description,\n type: \"option\",\n });\n }\n }\n\n // Add help option if not already used\n if (!context.usedOptions.has(\"help\")) {\n candidates.push({\n value: \"--help\",\n description: \"Show help information\",\n type: \"option\",\n });\n }\n\n return { candidates, directive: CompletionDirective.FilterPrefix };\n}\n\n/**\n * Build the resolver-invocation slice of CompletionContext.\n * `currentWord` reaches resolvers normalized by `generateCandidates` —\n * the option-value path strips any inline `--field=` prefix first, so\n * resolvers and the key=value post-processing only ever see the value\n * portion. The target field is dropped from `parsedArgs` so resolvers\n * can treat it as \"other args\": for repeatable options and variadic\n * positionals the parser already stages already-typed values under the\n * same key, and exposing them under both `parsedArgs` and `previousValues`\n * would let a resolver mistake the in-flight field for a fully-supplied\n * sibling.\n */\nfunction resolverContext(\n context: CompletionContext,\n options: GenerateCandidatesOptions,\n targetFieldName: string | undefined,\n): DynamicCompletionContext {\n return {\n currentWord: context.currentWord,\n shell: options.shell,\n parsedArgs: parsedArgsWithoutTarget(context.parsedArgs, targetFieldName),\n previousValues: context.previousValues,\n subcommandPath: context.subcommandPath,\n };\n}\n\nfunction parsedArgsWithoutTarget(\n parsedArgs: Record<string, unknown>,\n key: string | undefined,\n): Record<string, unknown> {\n if (key === undefined || !(key in parsedArgs)) return parsedArgs;\n const next = { ...parsedArgs };\n delete next[key];\n return next;\n}\n\n/**\n * Generate value candidates for either an option or a positional. Both paths\n * resolve the same way once their target field is identified. `description`\n * is propagated to choices candidates (positional path supplies it; option\n * path does not, mirroring the prior split implementations).\n */\nasync function generateValueCandidates(\n context: CompletionContext,\n options: GenerateCandidatesOptions,\n targetFieldName: string | undefined,\n vc: ValueCompletion | undefined,\n description?: string,\n): Promise<CandidateResult> {\n if (!vc) {\n return { candidates: [], directive: CompletionDirective.FilterPrefix };\n }\n return resolveValueCandidates(\n vc,\n resolverContext(context, options, targetFieldName),\n description,\n );\n}\n","/**\n * Resolve `completion.custom.expand` specs at script-generation time.\n *\n * The user-facing API records `dependsOn` (sibling arg names) plus an\n * `enumerate(deps)` callback. This module:\n * 1. Validates `dependsOn` against the sibling args (must exist, must have\n * static `choices` or an enum schema, no chaining).\n * 2. Walks the cartesian product of those static value lists.\n * 3. Calls `enumerate` for each combination and normalises the candidates.\n * 4. Stores the resolved table on the field's `valueCompletion`.\n *\n * Runs once per shell-script generation. Errors throw with the offending\n * field name so misconfiguration surfaces before the script is written.\n */\n\nimport type { ExpandCompletion, ResolvedExpandCandidate } from \"../core/expand-completion-types.js\";\nimport type {\n CompletableOption,\n CompletableSubcommand,\n ExpandTableEntry,\n ValueCompletion,\n} from \"./types.js\";\n\n/** Information about a single field that needs its expand spec resolved. */\nexport interface PendingExpandTarget {\n /** Sibling-lookup key (camelCase field name). */\n name: string;\n /** Human-readable label (e.g. `--field` or `<endpoint>`) used in errors. */\n describe: string;\n /** Setter that writes the resolved `ValueCompletion` onto the field. */\n set: (vc: ValueCompletion) => void;\n /** The unresolved spec from the user. */\n spec: ExpandCompletion;\n}\n\n/**\n * Resolve every pending `expand` spec on a subcommand. The static extractor\n * collects pending targets while building options/positionals (it sees the\n * sentinel via `resolveValueCompletion`) and passes them here once siblings\n * are known.\n */\nexport function resolveExpandTargets(\n sub: CompletableSubcommand,\n targets: readonly PendingExpandTarget[],\n globalOptions: readonly CompletableOption[] = [],\n): void {\n if (targets.length === 0) return;\n const siblingIndex = buildSiblingIndex(sub, globalOptions);\n for (const target of targets) {\n target.set(resolveOne(target, siblingIndex));\n }\n}\n\n/**\n * Build a name → static-values map for siblings, using each field's already\n * resolved `valueCompletion`. Only `choices`-typed completions count;\n * referencing anything else from `dependsOn` is reported as a clean error\n * in {@link resolveOne}. Global options with static choices are merged in\n * so a local expand can declare `dependsOn: [\"env\"]` against a global\n * \\`env\\` field — runtime propagates the global value to every frame, so\n * the resolved table must cover those combinations too.\n */\nfunction buildSiblingIndex(\n sub: CompletableSubcommand,\n globalOptions: readonly CompletableOption[],\n): Map<string, readonly string[]> {\n const index = new Map<string, readonly string[]>();\n // Names a local field claims — even when the local has no static\n // choices. Without this, a local arg shadowing a same-named global\n // arg would silently bind the dep to the global's choices while the\n // generated tracker still reads from the local value bucket. Reserving\n // the name here forces `resolveOne` to throw, surfacing the schema\n // mismatch instead of producing wrong candidates.\n const claimedByLocal = new Set<string>();\n for (const field of [...sub.options, ...sub.positionals]) claimedByLocal.add(field.name);\n const visit = (\n fields: readonly { name: string; valueCompletion?: ValueCompletion | undefined }[],\n fromGlobal: boolean,\n ): void => {\n for (const field of fields) {\n if (index.has(field.name)) continue;\n if (fromGlobal && claimedByLocal.has(field.name)) continue;\n const vc = field.valueCompletion;\n if (vc?.type === \"choices\" && vc.choices && vc.choices.length > 0) {\n index.set(field.name, vc.choices);\n }\n }\n };\n visit([...sub.options, ...sub.positionals], false);\n visit(globalOptions, true);\n return index;\n}\n\nfunction resolveOne(\n target: PendingExpandTarget,\n siblings: Map<string, readonly string[]>,\n): ValueCompletion {\n const { spec } = target;\n const deps = spec.dependsOn;\n\n if (deps.length === 0) {\n throw new Error(\n `Field \"${target.describe}\": completion.custom.expand.dependsOn must list at least one sibling arg.`,\n );\n }\n\n const valueLists: string[][] = [];\n for (const dep of deps) {\n if (dep === target.name) {\n throw new Error(\n `Field \"${target.describe}\": completion.custom.expand.dependsOn cannot reference the field itself (\"${dep}\").`,\n );\n }\n const values = siblings.get(dep);\n if (!values) {\n throw new Error(\n `Field \"${target.describe}\": completion.custom.expand.dependsOn references \"${dep}\", which is not a sibling arg with a static \\`choices\\`/enum schema on the same command. Chaining expand specs is not supported.`,\n );\n }\n valueLists.push([...values]);\n }\n\n const table: ExpandTableEntry[] = [];\n for (const combo of cartesian(valueLists)) {\n const depsRecord: Record<string, string> = {};\n deps.forEach((name, idx) => {\n depsRecord[name] = combo[idx]!;\n });\n\n let raw: ReturnType<typeof spec.enumerate>;\n try {\n raw = spec.enumerate(depsRecord);\n } catch (err) {\n const cause = err instanceof Error ? err.message : String(err);\n throw new Error(\n `Field \"${target.describe}\": completion.custom.expand.enumerate threw for deps=${JSON.stringify(depsRecord)}: ${cause}`,\n );\n }\n\n const candidates = normaliseCandidates(raw);\n if (candidates.length === 0) continue;\n table.push({ key: combo, candidates });\n }\n\n return {\n type: \"expand\",\n dependsOn: deps,\n table,\n };\n}\n\nfunction normaliseCandidates(\n raw: ReadonlyArray<string | { value: string; description?: string }>,\n): ResolvedExpandCandidate[] {\n const out: ResolvedExpandCandidate[] = [];\n const seen = new Set<string>();\n for (const item of raw) {\n const value = typeof item === \"string\" ? item : item.value;\n if (seen.has(value)) continue;\n seen.add(value);\n const entry: ResolvedExpandCandidate = { value };\n // Guarded so `exactOptionalPropertyTypes` doesn't reject `undefined`.\n if (typeof item !== \"string\" && item.description !== undefined) {\n entry.description = item.description;\n }\n out.push(entry);\n }\n return out;\n}\n\nfunction* cartesian(lists: readonly string[][]): Generator<string[]> {\n if (lists.length === 0) {\n yield [];\n return;\n }\n const indices = Array.from<number>({ length: lists.length }).fill(0);\n while (true) {\n yield indices.map((i, dim) => lists[dim]![i]!);\n let dim = lists.length - 1;\n while (dim >= 0) {\n indices[dim]!++;\n if (indices[dim]! < lists[dim]!.length) break;\n indices[dim] = 0;\n dim--;\n }\n if (dim < 0) return;\n }\n}\n","/**\n * Extract completion data from commands\n */\n\nimport { extractFields, type ResolvedFieldMeta } from \"../core/schema-extractor.js\";\nimport { resolveSubCommandMeta } from \"../lazy.js\";\nimport type { AnyCommand, ArgsSchema } from \"../types.js\";\nimport { resolveExpandTargets, type PendingExpandTarget } from \"./expand-resolver.js\";\nimport { collectOptionTokens, globalShortTokens, localShadowingTokens } from \"./shell-shared.js\";\nimport type {\n CompletableOption,\n CompletablePositional,\n CompletableSubcommand,\n CompletionData,\n ValueCompletion,\n} from \"./types.js\";\nimport { resolveValueCompletion } from \"./value-completion-resolver.js\";\n\n/**\n * Resolve and assign value completion to a field. Pending expand sentinels\n * are stashed in `pending`; the eventual `resolveExpandTargets` pass replaces\n * the sentinel with a fully-resolved `{ type: \"expand\", ... }` via `set`.\n */\nfunction assignValueCompletion(\n field: ResolvedFieldMeta,\n pending: PendingExpandTarget[],\n describe: string,\n set: (vc: ValueCompletion) => void,\n): void {\n const raw = resolveValueCompletion(field);\n if (raw?.type === \"pending-expand\") {\n pending.push({ name: field.name, describe, set, spec: raw.spec });\n return;\n }\n if (raw !== undefined) set(raw);\n}\n\n/**\n * Sanitize a name for use as a shell function/variable identifier.\n * Replaces any character that is not alphanumeric or underscore with underscore.\n *\n * Note: This is not injective -- distinct names may produce the same output\n * (e.g., \"foo-bar\" and \"foo_bar\" both become \"foo_bar\"). When used for nested\n * path encoding (`path.map(sanitize).join(\"_\")`), cross-level collisions are\n * theoretically possible (e.g., \"foo-bar:baz\" vs \"foo:bar-baz\") but extremely\n * unlikely in real CLI designs. If collision-safety is needed, sanitize must be\n * replaced with an injective encoding.\n */\nexport function sanitize(name: string): string {\n return name.replace(/[^a-zA-Z0-9_]/g, \"_\");\n}\n\n/**\n * Build the override env-var name shells inspect to pick a different\n * binary (`<NAME>_BIN`). Shell parameter names cannot begin with a\n * digit, so prepend an underscore when the upper-cased function name\n * starts with one — e.g. `2fa` ⇒ `_2FA_BIN`.\n */\nexport function binEnvVarName(fn: string): string {\n const upper = fn.toUpperCase();\n return /^[A-Z_]/.test(upper) ? `${upper}_BIN` : `_${upper}_BIN`;\n}\n\n/**\n * Hoisted expand-table variable name for a (funcSuffix, fieldName) at frame\n * scope. Bash uses indirect expansion `${!var}` on per-entry scalars, zsh\n * uses associative-array subscripts on this same base — the identifier\n * shape is identical, so both generators share this helper.\n */\nexport function expandTableVarName(fn: string, funcSuffix: string, fieldName: string): string {\n return `__${fn}_expand_${funcSuffix}__${sanitize(fieldName)}`;\n}\n\n/**\n * Body of the `__<fn>_invoke_complete` wrapper that bash and zsh emit when\n * any field uses an in-process JS resolver. Bytes are identical between the\n * two shells — both use `local`, `shift`, and the `<NAME>_BIN`-override\n * lookup — so the helper lives here. Fish has a different `function`\n * syntax (no `local`, `set -l` instead) and emits its own version inline.\n */\nexport function dynamicInvokeCompleteLines(fn: string, programName: string): string[] {\n return [\n `__${fn}_invoke_complete() {`,\n ` local _shell=\"$1\"; shift`,\n ` \"\\${${binEnvVarName(fn)}:-${programName}}\" __complete --shell \"$_shell\" -- \"$@\" 2>/dev/null`,\n `}`,\n ];\n}\n\n/**\n * Filter subcommands to only visible (non-internal) ones.\n * Internal subcommands start with \"__\" and are hidden from completion/help.\n */\nexport function getVisibleSubs(subs: CompletableSubcommand[]): CompletableSubcommand[] {\n return subs.filter((s) => !s.name.startsWith(\"__\"));\n}\n\n/**\n * Get all completable subcommand names including aliases.\n * Returns an array of { name, description } for all visible subcommands\n * and their aliases.\n */\nexport function getSubNamesWithAliases(\n subs: CompletableSubcommand[],\n): Array<{ name: string; description?: string | undefined }> {\n const result: Array<{ name: string; description?: string | undefined }> = [];\n for (const sub of getVisibleSubs(subs)) {\n result.push({ name: sub.name, description: sub.description });\n if (sub.aliases) {\n for (const alias of sub.aliases) {\n result.push({ name: alias, description: sub.description });\n }\n }\n }\n return result;\n}\n\n/**\n * Convert a resolved field to a completable option. Pending expand specs\n * are stashed in `pending` and patched onto the returned object after\n * sibling choices are known.\n */\nfunction fieldToOption(\n field: ResolvedFieldMeta,\n pending: PendingExpandTarget[],\n): CompletableOption {\n // Runtime accepts the implicit `--no-<cliName>` form only when `negation`\n // is undefined or `true`. A custom-string or explicit `false` disables\n // the default form.\n const defaultNegationAccepted =\n field.type === \"boolean\" && (field.negation === undefined || field.negation === true);\n\n const opt: CompletableOption = {\n name: field.name,\n cliName: field.cliName,\n alias: field.alias,\n negation: field.negationDisplay,\n negationDescription: field.negationDescription,\n description: field.description,\n // Booleans are flags that don't require a value\n takesValue: field.type !== \"boolean\",\n valueType: field.type,\n required: field.required,\n defaultNegationAccepted,\n };\n assignValueCompletion(field, pending, `--${field.cliName}`, (next) => {\n opt.valueCompletion = next;\n });\n return opt;\n}\n\n/**\n * Extract positional arguments from a command\n */\nexport function extractPositionals(command: AnyCommand): ResolvedFieldMeta[] {\n if (!command.args) {\n return [];\n }\n\n const extracted = extractFields(command.args);\n return extracted.fields.filter((field) => field.positional);\n}\n\n/** Convert pre-extracted fields to options. */\nfunction fieldsToOptions(\n fields: readonly ResolvedFieldMeta[],\n pending: PendingExpandTarget[],\n): CompletableOption[] {\n return fields.filter((field) => !field.positional).map((field) => fieldToOption(field, pending));\n}\n\n/** Convert pre-extracted fields to positionals. */\nfunction fieldsToPositionals(\n fields: readonly ResolvedFieldMeta[],\n pending: PendingExpandTarget[],\n): CompletablePositional[] {\n return fields\n .filter((field) => field.positional)\n .map((field, index): CompletablePositional => {\n const pos: CompletablePositional = {\n name: field.name,\n cliName: field.cliName,\n position: index,\n description: field.description,\n required: field.required,\n variadic: field.type === \"array\",\n };\n assignValueCompletion(field, pending, `<${field.cliName}>`, (next) => {\n pos.valueCompletion = next;\n });\n return pos;\n });\n}\n\n/**\n * Extract a completable subcommand from a command\n */\nfunction extractSubcommand(\n name: string,\n command: AnyCommand,\n globalOptions: readonly CompletableOption[] = [],\n): CompletableSubcommand {\n const subcommands: CompletableSubcommand[] = [];\n\n // Extract subcommands recursively (only sync subcommands for now)\n if (command.subCommands) {\n for (const [subName, subCommand] of Object.entries(command.subCommands)) {\n const resolved = resolveSubCommandMeta(subCommand);\n if (resolved) {\n subcommands.push(extractSubcommand(subName, resolved, globalOptions));\n } else {\n // Legacy async subcommands: placeholder only\n subcommands.push({\n name: subName,\n description: \"(lazy loaded)\",\n subcommands: [],\n options: [],\n positionals: [],\n });\n }\n }\n }\n\n const pending: PendingExpandTarget[] = [];\n // Extract once and partition: `extractFields` walks the Zod schema (a\n // non-trivial reflection pass for nested unions/wraps), so the prior\n // two-call shape paid that cost twice per command frame.\n const fields = command.args ? extractFields(command.args).fields : [];\n const node: CompletableSubcommand = {\n name,\n description: command.description,\n aliases: command.aliases,\n subcommands,\n options: fieldsToOptions(fields, pending),\n positionals: fieldsToPositionals(fields, pending),\n };\n // Resolve every `pending-expand` collected above against this\n // subcommand's siblings (and the global schema, which runtime\n // propagates to every frame). Throws if `dependsOn` references a\n // non-static sibling or `enumerate` raises.\n resolveExpandTargets(node, pending, globalOptions);\n return node;\n}\n\n/** Join parent and child with a separator, omitting separator when parent is empty. */\nfunction joinPrefix(parent: string, child: string, sep: string): string {\n return parent ? `${parent}${sep}${child}` : child;\n}\n\n/**\n * Expand each parent pathStr by joining every child name (canonical plus\n * aliases) with `:`. Used to keep alias-expanded path variants in lockstep\n * across walkers that need to reach the same node from any path the\n * runtime scanner can produce.\n */\nfunction expandChildPathStrs(pathStrs: readonly string[], child: CompletableSubcommand): string[] {\n const childNames = [child.name, ...(child.aliases ?? [])];\n return pathStrs.flatMap((p) => childNames.map((n) => joinPrefix(p, n, \":\")));\n}\n\n/**\n * A single (parentPath, tokens) row for a value-taking option, emitted by\n * {@link walkOptTakesValueRows} as the shell-agnostic intermediate form.\n * Bash/zsh format it as `parentPath:token) return 0 ;;`; fish quotes each\n * `\"parentPath:token\"` in a `case` head. Multiple tokens share a row when\n * the runtime accepts more than one spelling for the option.\n */\nexport interface OptTakesValueRow {\n readonly parentPath: string;\n readonly tokens: readonly string[];\n}\n\n/**\n * Walk the subcommand tree and yield a row per value-taking option, with\n * the path-aware token set the runtime would actually route here. Used by\n * all three shell generators — bash/zsh format these as `|`-joined case\n * patterns, fish wraps each pattern in a quoted glob.\n *\n * At ANCESTOR frames (those with further subcommand children) the runtime's\n * `scanForSubcommand` consults globals only — local-precedence does NOT\n * apply, so a global value option keeps every alias even when a local at\n * the frame claims the same short token. At LEAF frames, the leaf parser's\n * `separateGlobalArgs` applies local-precedence so `effectiveOptionTokens`\n * is the correct filter.\n */\nexport function walkOptTakesValueRows(\n sub: CompletableSubcommand,\n parentPath: string,\n): OptTakesValueRow[] {\n const rows: OptTakesValueRow[] = [];\n const isAncestor = getVisibleSubs(sub.subcommands).length > 0;\n for (const opt of sub.options) {\n if (!opt.takesValue) continue;\n const tokens =\n isAncestor && opt.isGlobal === true\n ? collectOptionTokens(opt.cliName, opt.alias)\n : effectiveOptionTokens(opt, sub.options);\n if (tokens.length === 0) continue;\n rows.push({ parentPath, tokens });\n }\n for (const child of getVisibleSubs(sub.subcommands)) {\n // Recurse once per name variant the runtime scanner can route to this\n // child (canonical + every alias). All variants share the same handler\n // body, so the only thing that changes between iterations is the path\n // prefix passed to the recursive call.\n for (const name of [child.name, ...(child.aliases ?? [])]) {\n rows.push(...walkOptTakesValueRows(child, joinPrefix(parentPath, name, \":\")));\n }\n }\n return rows;\n}\n\n/**\n * Collect opt-takes-value case entries for a subcommand tree.\n * Used by bash and zsh generators (identical case syntax: `path:--opt) return 0 ;;`).\n * parentPath is a colon-delimited path (e.g., \"\" for root, \"workspace:user\" for nested).\n */\nexport function optTakesValueEntries(sub: CompletableSubcommand, parentPath: string): string[] {\n return walkOptTakesValueRows(sub, parentPath).map((row) => {\n const patterns = row.tokens.map((t) => `${row.parentPath}:${t}`);\n return ` ${patterns.join(\"|\")}) return 0 ;;`;\n });\n}\n\n/**\n * Route entry for subcommand dispatch.\n * - pathStr: colon-delimited path (e.g., \"config:user:get\")\n * - funcSuffix: sanitized function suffix (e.g., \"config_user_get\")\n * - lookupPattern: \"parentPath:childName\" for is_subcmd matching (e.g., \"config:user:get\", or \":config\" for root-level)\n */\nexport interface RouteEntry {\n pathStr: string;\n funcSuffix: string;\n lookupPattern: string;\n}\n\n/**\n * Recursively collect all subcommand route entries.\n * Returns entries used by all shell generators for both dispatch routing\n * and subcommand lookup (is_subcmd) tables.\n * Aliases are mapped to the same handler as the canonical name.\n */\nexport function collectRouteEntries(\n sub: CompletableSubcommand,\n parentPath = \"\",\n parentFunc = \"\",\n): RouteEntry[] {\n const entries: RouteEntry[] = [];\n for (const child of getVisibleSubs(sub.subcommands)) {\n // Canonical and aliases all share one handler (`funcSuffix` is built\n // off the canonical name); only the path component changes, so iterate\n // every name variant and emit the entry plus descendant routes for\n // each.\n const funcSuffix = joinPrefix(parentFunc, sanitize(child.name), \"_\");\n for (const name of [child.name, ...(child.aliases ?? [])]) {\n const pathStr = joinPrefix(parentPath, name, \":\");\n entries.push(...collectRouteEntries(child, pathStr, funcSuffix));\n entries.push({\n pathStr,\n funcSuffix,\n lookupPattern: `${parentPath}:${name}`,\n });\n }\n }\n return entries;\n}\n\n/**\n * Generate is_subcmd case/switch body lines (bash/zsh case syntax).\n * Returns lines for the case statement body only (caller wraps in function).\n */\nexport function isSubcmdCaseLines(routeEntries: RouteEntry[]): string[] {\n return routeEntries.map((r) => ` ${r.lookupPattern}) return 0 ;;`);\n}\n\n/**\n * Subcommand-dispatch case body lines for bash/zsh: each route forwards\n * `$_subcmd` to its handler function. Identical emission between shells.\n */\nexport function subDispatchCaseLines(routeEntries: RouteEntry[], fn: string): string[] {\n return routeEntries.map((r) => ` ${r.pathStr}) __${fn}_complete_${r.funcSuffix} ;;`);\n}\n\n/**\n * Per-shell `_arg_values` write expression. zsh uses an associative-array\n * subscript; bash uses prefix-scalar variables so the generated script\n * runs on bash 3.2 (macOS default `/bin/bash`), which lacks associative\n * arrays. The `isGlobal` flag picks the bucket (`_global_arg_values_*`\n * survives subcommand descent; `_arg_values_*` does not).\n */\nfunction trackedFieldAssign(\n t: Pick<TrackedFieldRef, \"fieldName\" | \"isGlobal\">,\n shell: \"bash\" | \"zsh\",\n): string {\n const prefix = t.isGlobal ? `_global_arg_values` : `_arg_values`;\n return shell === \"bash\"\n ? `${prefix}_${sanitize(t.fieldName)}=\"$3\"`\n : `${prefix}[${t.fieldName}]=\"$3\"`;\n}\n\n/**\n * Case-statement body lines for `__track_opt` — capture option values into\n * the per-frame state. See {@link trackedFieldAssign} for the per-shell\n * assignment shape.\n */\nexport function trackOptCaseLines(\n trackedFields: readonly TrackedFieldRef[],\n shell: \"bash\" | \"zsh\",\n): string[] {\n const lines: string[] = [];\n for (const t of trackedFields) {\n if (t.isPositional || !t.optionTokens || t.optionTokens.length === 0) continue;\n const joined = t.pathStrs.flatMap((p) => t.optionTokens!.map((n) => `${p}:${n}`)).join(\"|\");\n lines.push(` ${joined}) ${trackedFieldAssign(t, shell)} ;;`);\n }\n return lines;\n}\n\n/**\n * Case-statement body lines for `__track_pos` — capture positional values\n * by `(subcmd, positional-index)`. See {@link trackedFieldAssign} for the\n * per-shell assignment shape.\n */\nexport function trackPosCaseLines(\n trackedFields: readonly TrackedFieldRef[],\n shell: \"bash\" | \"zsh\",\n): string[] {\n const lines: string[] = [];\n for (const t of trackedFields) {\n if (!t.isPositional) continue;\n const joined = t.pathStrs.map((p) => `${p}:${t.position}`).join(\"|\");\n lines.push(` ${joined}) ${trackedFieldAssign(t, shell)} ;;`);\n }\n return lines;\n}\n\n/**\n * Case-statement body lines for `__track_array_expand` — record each `key=`\n * slot the user has typed so the candidate loop can skip already-consumed\n * entries. The first write to a global array in a frame replaces the\n * inherited bucket (mirroring the runtime's per-frame array merge);\n * subsequent writes append. zsh uses associative arrays; bash uses\n * prefix-scalar variables (see {@link trackOptCaseLines}).\n */\nexport function trackArrayExpandCaseLines(\n arrayExpandSpecs: readonly ExpandSpecLocation[],\n shell: \"bash\" | \"zsh\",\n): string[] {\n const lines: string[] = [];\n for (const spec of arrayExpandSpecs) {\n if (spec.optionTokens.length === 0) continue;\n const joined = spec.pathStrs\n .flatMap((p) => spec.optionTokens.map((tok) => `${p}:${tok}`))\n .join(\"|\");\n const bucket = sanitize(spec.fieldName);\n const bucketPrefix = spec.isGlobal ? `_global_used_field_keys` : `_used_field_keys`;\n // Bash 3.2 has no associative arrays; both shells happen to share\n // the +=/=\" $_k \" append/replace syntax, so only the variable shape\n // differs.\n const bucketRef = shell === \"bash\" ? `${bucketPrefix}_${bucket}` : `${bucketPrefix}[${bucket}]`;\n const seenRef = shell === \"bash\" ? `_global_arr_seen_${bucket}` : `_global_arr_seen[${bucket}]`;\n const assignFirst = `${bucketRef}=\" $_k \"`;\n const assignAppend = `${bucketRef}+=\" $_k \"`;\n const seenSet = `${seenRef}=1`;\n lines.push(` ${joined})`);\n lines.push(` if [[ \"$3\" == *=* ]]; then`);\n lines.push(` local _k=\"\\${3%%=*}\"`);\n if (spec.isGlobal) {\n lines.push(` if [[ -n \"$_k\" ]]; then`);\n lines.push(` if [[ -z \"\\${${seenRef}:-}\" ]]; then`);\n lines.push(` ${assignFirst}`);\n lines.push(` ${seenSet}`);\n lines.push(` else`);\n lines.push(` ${assignAppend}`);\n lines.push(` fi`);\n lines.push(` fi`);\n } else {\n lines.push(` [[ -n \"$_k\" ]] && ${assignAppend}`);\n }\n lines.push(` fi`);\n lines.push(` ;;`);\n }\n return lines;\n}\n\n/**\n * Location of a resolved expand-completion spec inside the command tree.\n * Emitted by {@link collectExpandSpecs}; shell generators use it to name\n * the hoisted table variable and to scope the tracker entries.\n */\nexport interface ExpandSpecLocation {\n /** Subcommand path from root (e.g., [\"api\"]). Empty array = root. */\n readonly path: readonly string[];\n /**\n * Colon-delimited canonical subcommand path used for case-statement matching\n * (e.g., \"\" for root, \"api\" for one level, \"workspace:user\" for nested).\n * For shell-side `case $_subcmd` emissions that must match the path the\n * user actually typed (including alias names), iterate over {@link pathStrs}\n * instead — they enumerate the canonical path plus every alias-expanded\n * variant.\n */\n readonly pathStr: string;\n /**\n * Canonical path plus all alias-expanded variants. The first element is\n * {@link pathStr}. Shell scanners need every variant when emitting tracker\n * `case` patterns: `$_subcmd` reflects the path-as-typed, so an alias\n * route like `a:GetApplication` must match alongside `api:GetApplication`.\n */\n readonly pathStrs: readonly string[];\n /**\n * Ancestor subcommand paths (canonical + alias variants) above this\n * spec's host frame. Used to emit global dep trackers at every\n * \"before subcommand boundary\" position: the runtime scanner collects\n * matching global tokens at every frame on the way down regardless of\n * the local schema, so a global dep value typed at any ancestor must\n * still feed this spec's lookup. Empty when the spec lives at the\n * root.\n */\n readonly intermediatePathStrs: readonly string[];\n /**\n * Function suffix used in `__<fn>_<funcSuffix>` naming (e.g., \"api\",\n * \"workspace_user\"; \"root\" for the root command).\n */\n readonly funcSuffix: string;\n /** Field name (camelCase) of the option/positional that has the expand spec. */\n readonly fieldName: string;\n /**\n * True when the host field comes from `globalArgsSchema`. Shell\n * generators store the array-dedup bucket in a global state so the\n * already-consumed keys survive subcommand descent — matching how the\n * runtime parser keeps global option values visible across frames.\n */\n readonly isGlobal: boolean;\n /** Whether the field is a positional argument. */\n readonly isPositional: boolean;\n /**\n * True when the host field is a repeatable array option. Shell generators\n * use this to enable runtime deduplication: as the user repeats the option\n * (e.g. `-f workspaceId=foo -f <TAB>`), already-used `key=` candidates are\n * filtered out. Always false for positionals (where repetition is variadic\n * and `key=value` semantics don't apply).\n */\n readonly isArrayOption: boolean;\n /**\n * Option tokens (`--cliName`, `-a`, `--long-alias`) used by the shell\n * scanner to recognise this option's values and update the dedup bucket.\n * Empty when `isArrayOption` is false.\n */\n readonly optionTokens: readonly string[];\n /** The resolved expand spec on this field. */\n readonly vc: Extract<ValueCompletion, { type: \"expand\" }>;\n}\n\n/**\n * Compute the option token set the runtime would actually route to\n * `opt` at the given frame. Globals shadow LOCAL short tokens of the\n * same letter (runtime's `separateGlobalArgs` harvests `-x` for the\n * global unless the local explicitly declares `alias: \"x\"`), so a\n * local cliName `x` with no alias must NOT emit `-x` in its\n * tracker / value-completion / takes-value cases when a global at the\n * frame owns that token. Long forms are unaffected — precedence is\n * scoped to short aliases.\n */\nexport function effectiveOptionTokens(\n opt: CompletableOption,\n frameOptions: readonly CompletableOption[],\n): string[] {\n const all = collectOptionTokens(opt.cliName, opt.alias);\n if (opt.isGlobal === true) {\n // Tokens any local at the frame owns are routed by\n // `separateGlobalArgs` to the local, never to the global. Pull the\n // full owned spelling set via `localShadowingTokens` so a local\n // `alias: \"e\"` (which owns both `-e` and `--e`) excludes both forms\n // from the global's value-completion case, not just one.\n const localClaimed = new Set<string>();\n for (const o of frameOptions) {\n if (o.isGlobal === true) continue;\n for (const t of localShadowingTokens(o.cliName, o.alias)) localClaimed.add(t);\n }\n return all.filter((t) => !localClaimed.has(t));\n }\n const globalShort = globalShortTokens(frameOptions);\n if (globalShort.size === 0) return all;\n return all.filter((t) => {\n if (!t.startsWith(\"-\") || t.startsWith(\"--\")) return true;\n if (!globalShort.has(t)) return true;\n // Keep if the local explicitly declares the matching short alias.\n return opt.alias?.includes(t.slice(1)) === true;\n });\n}\n\n/**\n * Walk the subcommand tree and return every resolved expand spec along\n * with where it lives. The order is deterministic (DFS, root → leaves;\n * options before positionals within a node).\n */\nexport function collectExpandSpecs(root: CompletableSubcommand): ExpandSpecLocation[] {\n const out: ExpandSpecLocation[] = [];\n walk(root, [], [\"\"], [], \"root\", out);\n return out;\n}\n\nfunction walk(\n node: CompletableSubcommand,\n path: string[],\n pathStrs: readonly string[],\n intermediatePathStrs: readonly string[],\n funcSuffix: string,\n out: ExpandSpecLocation[],\n): void {\n const pathStr = pathStrs[0]!;\n for (const opt of node.options) {\n const vc = opt.valueCompletion;\n if (vc?.type === \"expand\") {\n const isArrayOption = opt.valueType === \"array\";\n out.push({\n path,\n pathStr,\n pathStrs,\n intermediatePathStrs,\n funcSuffix,\n fieldName: opt.name,\n isGlobal: opt.isGlobal === true,\n isPositional: false,\n isArrayOption,\n optionTokens: isArrayOption ? effectiveOptionTokens(opt, node.options) : [],\n vc,\n });\n }\n }\n for (const pos of node.positionals) {\n const vc = pos.valueCompletion;\n if (vc?.type === \"expand\") {\n out.push({\n path,\n pathStr,\n pathStrs,\n intermediatePathStrs,\n funcSuffix,\n fieldName: pos.name,\n isGlobal: false,\n isPositional: true,\n isArrayOption: false,\n optionTokens: [],\n vc,\n });\n }\n }\n for (const child of getVisibleSubs(node.subcommands)) {\n const childPath = [...path, child.name];\n const childPathStrs = expandChildPathStrs(pathStrs, child);\n // Pass the current frame's pathStrs (canonical + alias variants)\n // down as ancestor pathStrs for descendants. The descendant spec\n // uses these to emit global-dep tracker cases at every \"before\n // subcommand boundary\" position the runtime scanner can reach.\n const childIntermediates = [...intermediatePathStrs, ...pathStrs];\n const childFunc =\n funcSuffix === \"root\" ? sanitize(child.name) : `${funcSuffix}_${sanitize(child.name)}`;\n walk(child, childPath, childPathStrs, childIntermediates, childFunc, out);\n }\n}\n\n/**\n * Per-path information about a sibling field that an expand spec depends\n * on. Shell generators use this to populate `_arg_values` during the main\n * scan loop.\n */\nexport interface TrackedFieldRef {\n /** camelCase field name; used as the `_arg_values` map key. */\n readonly fieldName: string;\n /**\n * True when the underlying option is a global (propagated from\n * `globalArgsSchema`). Shell generators route global trackers into a\n * separate bucket that is not cleared on subcommand descent — matching\n * the runtime parser's behaviour of keeping globals visible from any\n * frame.\n */\n readonly isGlobal: boolean;\n /** Canonical subcommand path where this field lives. */\n readonly pathStr: string;\n /**\n * Canonical path plus all alias-expanded variants. The first element is\n * {@link pathStr}. Shell tracker emitters iterate over every variant so\n * `$_subcmd` matches whether the user typed the canonical or an alias.\n */\n readonly pathStrs: readonly string[];\n /** True if positional, false if option. */\n readonly isPositional: boolean;\n /** 0-based positional index (positional only). */\n readonly position?: number;\n /**\n * CLI tokens this option is recognised by (`--cliName`, `--long-alias`,\n * `-x`). Option only; empty for positionals. Emit-ready: shell tracker\n * generators concatenate these with the per-path prefix to produce case\n * patterns. Use {@link aliasToken} via {@link collectOptionTokens} so\n * single-char aliases keep their `-` prefix.\n */\n readonly optionTokens?: readonly string[];\n}\n\n/**\n * For every expand spec, find each `dependsOn` sibling field at the same\n * path and return enough metadata for the shell generator to emit tracker\n * cases. Fields that cannot be resolved are silently skipped — the static\n * extractor already validated `dependsOn` upstream in\n * `resolveExpandTargets`, so unresolved siblings here would indicate a\n * programming error and would simply yield no tracker entries.\n */\nexport function collectTrackedFields(\n root: CompletableSubcommand,\n specs: readonly ExpandSpecLocation[],\n globalOptions: readonly CompletableOption[] = [],\n): TrackedFieldRef[] {\n const nodeByPath = indexNodesByPath(root);\n // Aggregate per (fieldName, isGlobal, isPositional, position) — multiple\n // specs may share the same dep (e.g. the same global dep referenced from\n // root, parent, and parent:child specs). Unioning their pathStrs into a\n // single case branch keeps the generated `__track_opt` body free of\n // duplicate patterns while preserving every frame the runtime scanner can\n // reach.\n interface Bucket {\n ref: Omit<TrackedFieldRef, \"pathStr\" | \"pathStrs\">;\n pathStrs: string[];\n seen: Set<string>;\n }\n const buckets = new Map<string, Bucket>();\n const addPath = (key: string, ref: Bucket[\"ref\"], paths: readonly string[]): void => {\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = { ref, pathStrs: [], seen: new Set() };\n buckets.set(key, bucket);\n }\n for (const p of paths) {\n if (bucket.seen.has(p)) continue;\n bucket.seen.add(p);\n bucket.pathStrs.push(p);\n }\n };\n\n /**\n * Group spec frames by the per-leaf surviving-token set for a global option.\n * The runtime scanner at a LEAF frame drops global tokens that a local\n * option already claims (via `localShadowingTokens`); at ANCESTOR frames it\n * sees only globals so every token survives. Grouping by token-set keeps the\n * generated tracker case body minimal — one branch per unique frame group.\n */\n const groupGlobalFramesByTokenSet = (\n optTokens: readonly string[],\n leafPaths: readonly string[],\n ancestorPaths: readonly string[],\n ): Map<string, { tokens: readonly string[]; paths: string[] }> => {\n const groups = new Map<string, { tokens: readonly string[]; paths: string[] }>();\n const recordLeaf = (path: string, tokens: readonly string[]): void => {\n if (tokens.length === 0) return;\n const tokenKey = tokens.join(\" \");\n let group = groups.get(tokenKey);\n if (!group) {\n group = { tokens, paths: [] };\n groups.set(tokenKey, group);\n }\n group.paths.push(path);\n };\n for (const p of leafPaths) {\n const n = nodeByPath.get(p);\n if (!n) continue;\n // Use only the tokens the runtime's `separateGlobalArgs` would treat\n // as locally-owned at this leaf: the long-form cliName and every\n // EXPLICIT alias. A bare 1-char cliName does NOT register in the\n // local aliasMap unless an explicit `alias: \"x\"` is declared.\n const claimed = new Set<string>();\n for (const o of n.options) {\n if (o.isGlobal === true) continue;\n for (const t of localShadowingTokens(o.cliName, o.alias)) claimed.add(t);\n }\n recordLeaf(\n p,\n optTokens.filter((t) => !claimed.has(t)),\n );\n }\n // Intermediate frames always carry every global token: the runtime\n // scanner at those frames does not consult any local schema, so the\n // value always lands in `_global_arg_values` there.\n for (const p of ancestorPaths) recordLeaf(p, optTokens);\n return groups;\n };\n\n const addGlobalDepTracker = (\n dep: string,\n opt: CompletableOption,\n spec: ExpandSpecLocation,\n ): void => {\n const allTokens = collectOptionTokens(opt.cliName, opt.alias);\n const groups = groupGlobalFramesByTokenSet(allTokens, spec.pathStrs, spec.intermediatePathStrs);\n for (const [tokenKey, group] of groups) {\n addPath(\n `g::${dep}::${tokenKey}`,\n {\n fieldName: dep,\n isGlobal: true,\n isPositional: false,\n optionTokens: group.tokens,\n },\n group.paths,\n );\n }\n };\n\n for (const spec of specs) {\n const node = nodeByPath.get(spec.pathStr);\n if (!node) continue;\n for (const dep of spec.vc.dependsOn) {\n // Global expand specs are resolved against the global siblings list\n // alone (see `resolveExpandTargets` in `extractCompletionData`), so\n // their dep tracker must reference the global option metadata even\n // when a subcommand later defines a local field with the same\n // name. Looking the dep up on `node.options` would silently rebind\n // the tracker to the local shadow.\n if (spec.isGlobal) {\n const globalOpt = globalOptions.find((o) => o.name === dep);\n if (!globalOpt) continue;\n addGlobalDepTracker(dep, globalOpt, spec);\n continue;\n }\n const posIndex = node.positionals.findIndex((p) => p.name === dep);\n if (posIndex >= 0) {\n const key = `lp::${spec.pathStr}::${dep}`;\n addPath(\n key,\n {\n fieldName: dep,\n isGlobal: false,\n isPositional: true,\n position: posIndex,\n },\n spec.pathStrs,\n );\n continue;\n }\n const opt = node.options.find((o) => o.name === dep);\n if (!opt) continue;\n if (opt.isGlobal === true) {\n // Local expand depending on a propagated global tracks at the host\n // frame AND every ancestor the scanner crosses. The leaf frame may\n // have a local option whose emitted token shadows one of the\n // global's aliases — but that shadow does NOT apply at ancestor\n // frames, where the runtime scanner sees only globals.\n addGlobalDepTracker(dep, opt, spec);\n continue;\n }\n // A local dep tracker stays bound to the host frame: locals don't\n // propagate across subcommand boundaries the way globals do.\n addPath(\n `lo::${spec.pathStr}::${dep}`,\n {\n fieldName: dep,\n isGlobal: false,\n isPositional: false,\n optionTokens: effectiveOptionTokens(opt, node.options),\n },\n spec.pathStrs,\n );\n }\n }\n const out: TrackedFieldRef[] = [];\n for (const bucket of buckets.values()) {\n if (bucket.pathStrs.length === 0) continue;\n out.push({\n ...bucket.ref,\n pathStr: bucket.pathStrs[0]!,\n pathStrs: bucket.pathStrs,\n });\n }\n return out;\n}\n\nfunction indexNodesByPath(root: CompletableSubcommand): Map<string, CompletableSubcommand> {\n const map = new Map<string, CompletableSubcommand>();\n // Walk with all alias-expanded path variants so the same node is\n // reachable by every path the runtime scanner can produce (`d:Get`\n // alongside `deploy:Get`). Without alias paths in the index, callers\n // that look a node up by `$_subcmd` would miss the aliased frames.\n const recurse = (node: CompletableSubcommand, pathStrs: readonly string[]): void => {\n for (const p of pathStrs) map.set(p, node);\n for (const child of getVisibleSubs(node.subcommands)) {\n recurse(child, expandChildPathStrs(pathStrs, child));\n }\n };\n recurse(root, [\"\"]);\n return map;\n}\n\n/**\n * Walk a CompletableSubcommand tree and return true when any option or\n * positional uses an in-process dynamic resolver. Used by shell generators\n * to decide whether to emit `__<fn>_invoke_complete` delegate helpers.\n */\nexport function hasDynamicCompletion(sub: CompletableSubcommand): boolean {\n for (const opt of sub.options) {\n if (opt.valueCompletion?.type === \"dynamic\") return true;\n }\n for (const pos of sub.positionals) {\n if (pos.valueCompletion?.type === \"dynamic\") return true;\n }\n for (const child of sub.subcommands) {\n if (hasDynamicCompletion(child)) return true;\n }\n return false;\n}\n\n/**\n * Recursively merge global options into a subcommand and all its descendants.\n * Avoids duplicates by checking existing option names.\n */\nfunction propagateGlobalOptions(\n sub: CompletableSubcommand,\n globalOptions: CompletableOption[],\n): void {\n const existingNames = new Set(sub.options.map((o) => o.name));\n const newOpts = globalOptions.filter((o) => !existingNames.has(o.name));\n sub.options = [...sub.options, ...newOpts];\n for (const child of sub.subcommands) {\n propagateGlobalOptions(child, globalOptions);\n }\n}\n\n/**\n * Extract completion data from a command tree\n *\n * @param command - The root command\n * @param programName - Program name for completion scripts\n * @param globalArgsSchema - Optional global args schema. When provided, global options\n * are derived from this schema instead of the root command's options.\n */\nexport function extractCompletionData(\n command: AnyCommand,\n programName: string,\n globalArgsSchema?: ArgsSchema,\n): CompletionData {\n // Derive globals FIRST so they're available when subcommand expand\n // specs resolve. A local expand that declares `dependsOn: [\"env\"]`\n // against a global \\`env\\` field would otherwise fail with a \"not a\n // sibling\" error at codegen time — runtime propagates the global to\n // every frame, so the resolved table needs to cover those keys too.\n let globalOptions: CompletableOption[] = [];\n if (globalArgsSchema) {\n const globalPending: PendingExpandTarget[] = [];\n globalOptions = fieldsToOptions(extractFields(globalArgsSchema).fields, globalPending).map(\n (opt) => {\n opt.isGlobal = true;\n return opt;\n },\n );\n // Resolve `expand` specs on global options against the globals themselves\n // (globals can depend on other globals but not on subcommand-local args).\n resolveExpandTargets(\n {\n name: programName,\n subcommands: [],\n options: globalOptions,\n positionals: [],\n },\n globalPending,\n );\n }\n\n const rootSubcommand = extractSubcommand(programName, command, globalOptions);\n\n if (globalArgsSchema) {\n // Merge global options into all subcommands recursively so shell\n // generators include them at every level.\n propagateGlobalOptions(rootSubcommand, globalOptions);\n } else {\n // Default: global options are the options defined on the root command\n globalOptions = rootSubcommand.options;\n }\n\n return {\n command: rootSubcommand,\n programName,\n globalOptions,\n };\n}\n","/**\n * Static-script header utilities.\n *\n * Every completion script generated by politty starts with a small\n * machine-readable header. The rc loader and the runMain background\n * refresh path use the `# politty-bin-sig:` line to detect when the\n * cached script is stale relative to the binary on disk.\n */\n\nimport { statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ShellType } from \"./types.js\";\n\n/** Schema version of the header itself. Bump when the header layout changes. */\nexport const COMPLETION_VERSION = 1;\n\n/**\n * Read the binary's mtime in whole seconds (matches POSIX `stat -c %Y` /\n * BSD `stat -f %m`). Returns `\"0\"` on failure so the header is always\n * well-formed.\n */\nexport function computeBinSig(binPath: string): string {\n try {\n return Math.floor(statSync(binPath).mtimeMs / 1000).toString();\n } catch {\n return \"0\";\n }\n}\n\n/**\n * Walk `$PATH` looking for an executable named `programName`. Returns\n * the first match's full path, or `null` when not found. We mirror the\n * shell's `command -v <prog>` here so the sig embedded in the header\n * (computed by Node) lines up with what the rc loader stat-checks at\n * runtime — including pnpm/npm bin shims that wrap the real entrypoint.\n * Without this alignment, shimmed installs would never match the\n * embedded sig and the cache would regenerate on every shell startup.\n */\nfunction findOnPath(programName: string): string | null {\n // eslint-disable-next-line no-control-regex -- intentional null-byte rejection to block path injection in `programName`\n if (!programName || /[/\\\\\\0]/.test(programName)) return null;\n const path = process.env.PATH ?? \"\";\n for (const dir of path.split(\":\")) {\n if (!dir) continue;\n const candidate = join(dir, programName);\n try {\n if (statSync(candidate).isFile()) return candidate;\n } catch {\n // skip\n }\n }\n return null;\n}\n\n/**\n * Resolve the binary path used for sig computation and stat checks.\n *\n * Order: explicit override → `$PATH` lookup of `programName` → `process.argv[1]`.\n * The `$PATH` lookup keeps Node-side and shell-side stats pointed at the\n * same shim file when the CLI is invoked through a package-manager bin shim.\n */\nexport function resolveBinPath(programName: string, override?: string | undefined): string {\n if (override) return override;\n return findOnPath(programName) ?? process.argv[1] ?? \"\";\n}\n\nexport interface HeaderOptions {\n programName: string;\n shell: ShellType;\n binPath?: string | undefined;\n programVersion?: string | undefined;\n}\n\n/**\n * Build the header lines (no trailing blank line). Returned without a\n * leading `#!` so each generator can prepend its own shebang/compdef\n * marker.\n */\nexport function buildHeaderLines(opts: HeaderOptions): string[] {\n const sig = computeBinSig(resolveBinPath(opts.programName, opts.binPath));\n const lines = [\n `# politty-completion-version: ${COMPLETION_VERSION}`,\n `# politty-bin-sig: ${sig}`,\n `# program: ${opts.programName}`,\n ];\n if (opts.programVersion) {\n lines.push(`# program-version: ${opts.programVersion}`);\n }\n lines.push(`# shell: ${opts.shell}`);\n return lines;\n}\n","/**\n * Self-refresh guards embedded in generated bash/zsh scripts.\n *\n * These guards make the default `completion <shell>` output safe to\n * save as a static completion file: when the CLI binary changes, the\n * script asks the hidden refresh subcommand to rewrite the sourced\n * file in place, then sources the fresh file and stops executing the\n * stale body.\n */\n\nimport { sanitize } from \"./extractor.js\";\nimport { computeBinSig, resolveBinPath } from \"./header.js\";\n\ninterface SelfRefreshOptions {\n programName: string;\n binPath?: string | undefined;\n}\n\nfunction statSigExpr(): string {\n return `$(stat -L -c '%Y' \"$_bin\" 2>/dev/null || stat -L -f '%m' \"$_bin\" 2>/dev/null)`;\n}\n\nexport function generateBashSelfRefresh(opts: SelfRefreshOptions): string[] {\n const { programName, binPath } = opts;\n const fn = sanitize(programName);\n const sig = computeBinSig(resolveBinPath(programName, binPath));\n const refreshFn = `__${fn}_self_refresh`;\n\n return [\n `${refreshFn}() {`,\n ` local _self _bin _sig`,\n ` _self=\\${BASH_SOURCE[0]:-}`,\n ` [[ -n \"$_self\" && -f \"$_self\" ]] || return 1`,\n ` head -n 8 \"$_self\" 2>/dev/null | grep -qF \"# politty-completion-version:\" || return 1`,\n ` head -n 8 \"$_self\" 2>/dev/null | grep -qF \"# program: ${programName}\" || return 1`,\n ` head -n 8 \"$_self\" 2>/dev/null | grep -qF \"# shell: bash\" || return 1`,\n ` _bin=$(type -P ${programName} 2>/dev/null)`,\n ` [[ -n \"$_bin\" ]] || return 1`,\n ` _sig=${statSigExpr()} || return 1`,\n ` [[ \"$_sig\" != \"${sig}\" ]] || return 1`,\n ` \"$_bin\" __refresh-completion bash \"$_self\" 2>/dev/null || return 1`,\n ` head -n 8 \"$_self\" 2>/dev/null | grep -qF \"# politty-bin-sig: $_sig\" || return 1`,\n ` source \"$_self\" 2>/dev/null || return 1`,\n ` return 0`,\n `}`,\n `if ${refreshFn}; then`,\n ` unset -f ${refreshFn}`,\n ` return 0 2>/dev/null || true`,\n `else`,\n ` unset -f ${refreshFn}`,\n `fi`,\n ``,\n ];\n}\n\nexport function generateZshSelfRefresh(opts: SelfRefreshOptions): string[] {\n const { programName, binPath } = opts;\n const fn = sanitize(programName);\n const completionFn = `_${programName}`;\n const sig = computeBinSig(resolveBinPath(programName, binPath));\n const refreshFn = `__${fn}_self_refresh`;\n\n return [\n `${refreshFn}() {`,\n ` emulate -L zsh`,\n ` setopt local_options no_aliases`,\n ` local _self _bin _sig`,\n ` _self=\"\\${(%):-%x}\"`,\n ` [[ -n \"$_self\" && -f \"$_self\" ]] || return 1`,\n ` head -n 8 \"$_self\" 2>/dev/null | grep -qF \"# politty-completion-version:\" || return 1`,\n ` head -n 8 \"$_self\" 2>/dev/null | grep -qF \"# program: ${programName}\" || return 1`,\n ` head -n 8 \"$_self\" 2>/dev/null | grep -qF \"# shell: zsh\" || return 1`,\n ` _bin=$(whence -p ${programName} 2>/dev/null)`,\n ` [[ -n \"$_bin\" ]] || return 1`,\n ` _sig=${statSigExpr()} || return 1`,\n ` [[ \"$_sig\" != \"${sig}\" ]] || return 1`,\n ` \"$_bin\" __refresh-completion zsh \"$_self\" 2>/dev/null || return 1`,\n ` head -n 8 \"$_self\" 2>/dev/null | grep -qF \"# politty-bin-sig: $_sig\" || return 1`,\n ` source \"$_self\" 2>/dev/null || return 1`,\n ` ${completionFn} \"$@\"`,\n ` return 0`,\n `}`,\n `if ${refreshFn} \"$@\"; then`,\n ` unfunction ${refreshFn} 2>/dev/null`,\n ` return 0 2>/dev/null || true`,\n `else`,\n ` unfunction ${refreshFn} 2>/dev/null`,\n `fi`,\n ``,\n ];\n}\n","/**\n * Bash completion script generator (static)\n *\n * Generates a self-contained bash completion script that embeds all\n * completion metadata. No Node.js process is spawned on TAB.\n */\n\nimport type { AnyCommand } from \"../types.js\";\nimport { CompletionDirective } from \"./dynamic/candidate-generator.js\";\nimport {\n collectExpandSpecs,\n collectRouteEntries,\n collectTrackedFields,\n dynamicInvokeCompleteLines,\n effectiveOptionTokens,\n expandTableVarName,\n extractCompletionData,\n getSubNamesWithAliases,\n getVisibleSubs,\n hasDynamicCompletion,\n isSubcmdCaseLines,\n optTakesValueEntries,\n sanitize,\n subDispatchCaseLines,\n trackArrayExpandCaseLines,\n trackOptCaseLines,\n trackPosCaseLines,\n} from \"./extractor.js\";\nimport { buildHeaderLines } from \"./header.js\";\nimport { generateBashSelfRefresh } from \"./self-refresh.js\";\nimport {\n ansiC,\n optionExpandLocation,\n positionalExpandLocation,\n quotedAvailabilityTokens,\n type FuncSuffixedExpandLocation,\n} from \"./shell-shared.js\";\nimport type {\n CompletableOption,\n CompletablePositional,\n CompletableSubcommand,\n CompletionOptions,\n CompletionResult,\n ValueCompletion,\n} from \"./types.js\";\n\n/** Escape a string for use inside bash double-quotes */\nfunction escapeBashDQ(s: string): string {\n return s.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"').replace(/\\$/g, \"\\\\$\").replace(/`/g, \"\\\\`\");\n}\n\n/**\n * Hex-encode the UTF-8 byte representation of `s` so the resulting\n * string is safe as a suffix of a bash identifier. Each non-alnum byte\n * becomes `_HH` (exactly 2 hex digits, always upper-case). `_` is also\n * encoded (as `_5F`) to keep the join separator between encoded dep\n * values unambiguous — without that, `(v1=\"-\", v2=\"\")` and\n * `(v1=\"_2D\", v2=\"\")` would both render `_2D_`.\n *\n * Per-byte fixed-width encoding avoids the variable-length codepoint\n * collision where `-A` (codepoint 0x2D + literal `A`) and `˚` (codepoint\n * 0x02DA) would both produce `_2DA` under the previous scheme. Mirrors\n * the runtime `__<fn>_enc` helper emitted alongside expand tables; the\n * helper forces `LC_ALL=C` so its `${var:i:1}` iterates over the same\n * UTF-8 bytes this encoder emits.\n */\nfunction bashEncodeKey(s: string): string {\n let out = \"\";\n const bytes = new TextEncoder().encode(s);\n for (const byte of bytes) {\n if (\n (byte >= 0x30 && byte <= 0x39) ||\n (byte >= 0x41 && byte <= 0x5a) ||\n (byte >= 0x61 && byte <= 0x7a)\n ) {\n out += String.fromCharCode(byte);\n } else {\n out += `_${byte.toString(16).toUpperCase().padStart(2, \"0\")}`;\n }\n }\n return out;\n}\n\n/**\n * Generate bash value completion code for a ValueCompletion spec.\n * `location` is required when `vc.type === \"expand\"` (otherwise unused).\n */\nfunction bashValueLines(\n vc: ValueCompletion | undefined,\n inline: boolean,\n fn: string,\n location?: FuncSuffixedExpandLocation,\n): string[] {\n if (!vc) return [];\n\n switch (vc.type) {\n case \"expand\": {\n if (!location) {\n throw new Error(\"bashValueLines: expand variant requires a location\");\n }\n // The expand table is hoisted as per-entry scalar variables (one\n // per key combination). Build the encoded runtime suffix from the\n // dependsOn values via `__<fn>_enc`, then read the candidate list\n // through indirect expansion and filter against `$_cur`.\n const varName = expandTableVarName(fn, location.funcSuffix, location.fieldName);\n // Per-dep lookups read from the matching prefix-scalar bucket:\n // globals from `_global_arg_values_<dep>` (preserved across\n // subcommand descent), locals from `_arg_values_<dep>` (cleared on\n // descent). Mixing the two would let a global value silently\n // substitute for a missing local dep of the same name.\n const encLines: string[] = [`local _enc_key='' _enc_v`];\n location.resolvedDeps.forEach((d, i) => {\n const safe = sanitize(d.name);\n const varRef = d.isGlobal ? `_global_arg_values_${safe}` : `_arg_values_${safe}`;\n encLines.push(`_enc_v=\"\\${${varRef}:-}\"`);\n encLines.push(\n i === 0 ? `_enc_key=\"$(__${fn}_enc \"$_enc_v\")\"` : `_enc_key+=\"_$(__${fn}_enc \"$_enc_v\")\"`,\n );\n });\n const inlineExpr = inline ? `\"\\${_inline_prefix}\\${_c}\"` : `\"$_c\"`;\n // The array dedup bucket for a global expand host lives in\n // _global_used_field_keys_<bucket> so already-consumed keys survive\n // descent. Bash 3.2 prefix-scalar shape — see the table emission\n // above for the matching writer side.\n const bucketRef = location.isGlobal\n ? `\\${_global_used_field_keys_${sanitize(location.fieldName)}:-}`\n : `\\${_used_field_keys_${sanitize(location.fieldName)}:-}`;\n // The dedup + key-collapse loop body. When `_cur` has no `=` yet,\n // `key=value` candidates collapse to a unique `key=` so the first\n // TAB picks the key. Array-host dedup against already-typed keys\n // runs before the collapse so a used key is skipped at both\n // stages.\n const arrayDedupLines = location.isArrayOption\n ? [` if [[ -n \"$_ck\" && \" ${bucketRef} \" == *\" $_ck \"* ]]; then continue; fi`]\n : [];\n return [\n // Suppress bash's `-o default` filename fallback. bash 4+ honors\n // this `compopt`; bash 3.2 silently fails the call, so the\n // no-entry branch below ALSO seeds COMPREPLY with an empty\n // sentinel to keep the `complete -o default` registration from\n // falling back to filenames when no candidates are produced.\n `compopt +o default 2>/dev/null`,\n ...encLines,\n `local _varname=${varName}__\\${_enc_key}`,\n `local _raw=\"\\${!_varname:-}\"`,\n `if [[ -n \"$_raw\" ]]; then`,\n ` local -a _vals=()`,\n ` local _line`,\n ` while IFS= read -r _line; do _vals+=(\"$_line\"); done <<< \"$_raw\"`,\n ` local _c _ck _seen_keys=\" \" _had_key=0`,\n ` for _c in \"\\${_vals[@]}\"; do`,\n ` [[ -z \"$_c\" ]] && continue`,\n ` if [[ \"$_c\" == *=* ]]; then`,\n ` _ck=\"\\${_c%%=*}\"`,\n ...arrayDedupLines,\n ` if [[ \"$_cur\" != *=* ]]; then`,\n ` [[ \"$_seen_keys\" == *\" $_ck \"* ]] && continue`,\n ` _seen_keys+=\"$_ck \"`,\n ` _c=\"\\${_ck}=\"`,\n ` _had_key=1`,\n // Value stage: drop bare `key=` candidates so the value picker is\n // not cluttered by the key entry the user already typed.\n ` elif [[ \"$_c\" != *=?* ]]; then`,\n ` continue`,\n ` fi`,\n ` fi`,\n ` [[ \"$_c\" == \"$_cur\"* ]] && COMPREPLY+=(${inlineExpr})`,\n ` done`,\n // Only the `key=` candidates need `nospace` so the user can keep\n // typing the value after TAB. Scalar candidates and the value\n // stage of `key=value` should accept with the usual trailing\n // space, matching the dynamic resolver's NoSpace-gated path.\n ` if (( _had_key )); then compopt -o nospace 2>/dev/null; fi`,\n `fi`,\n // bash 3.2 ignores the earlier `compopt +o default`, so an\n // entry-empty lookup OR a filtered-out match list both need\n // the empty sentinel — set it whenever the loop above left\n // COMPREPLY untouched.\n `if (( \\${#COMPREPLY[@]} == 0 )); then COMPREPLY=( \"\" ); fi`,\n ];\n }\n case \"dynamic\": {\n // Delegate to `<program> __complete --shell bash`; the politty bash\n // formatter already prepends the inline prefix to each candidate, so\n // the consumer just drops sentinel lines.\n return [\n `local _dyn_out`,\n `_dyn_out=$(__${fn}_invoke_complete bash \"\\${_words[@]}\")`,\n `__${fn}_apply_dynamic_output \"$_dyn_out\"`,\n ];\n }\n case \"choices\": {\n const items = vc.choices!.map((c) => `\"${escapeBashDQ(c)}\"`).join(\" \");\n // `$_inline_prefix` is empty in non-inline mode, so the same loop\n // handles both: a set prefix gets prepended, an empty one is a no-op.\n // `compopt -o nospace` is inline-only — it suppresses the trailing\n // space after `--opt=value` so the user can keep typing.\n const lines = [\n `local -a _choices=(${items})`,\n `COMPREPLY=()`,\n `local _c; for _c in \"\\${_choices[@]}\"; do [[ \"$_c\" == \"$_cur\"* ]] && COMPREPLY+=(\"\\${_inline_prefix}\\${_c}\"); done`,\n ];\n if (inline) lines.push(`compopt -o nospace`);\n lines.push(`compopt +o default 2>/dev/null`);\n return lines;\n }\n case \"file\": {\n if (vc.matcher?.length) {\n const checks = vc.matcher.map((p) => `[[ \"\\${_f##*/}\" == ${p} ]]`).join(\" || \");\n return bashFileFilter(checks);\n }\n if (vc.extensions?.length) {\n const checks = vc.extensions.map((ext) => `[[ \"$_f\" == *\".${ext}\" ]]`).join(\" || \");\n return bashFileFilter(checks);\n }\n // `compgen -P` prepends the inline prefix when set; an empty prefix\n // is a no-op, so the same emission works for both modes.\n return [`COMPREPLY=($(compgen -P \"$_inline_prefix\" -f -- \"$_cur\"))`, `compopt -o filenames`];\n }\n case \"directory\":\n return [`COMPREPLY=($(compgen -P \"$_inline_prefix\" -d -- \"$_cur\"))`, `compopt -o filenames`];\n case \"command\":\n return [`COMPREPLY=($(compgen -P \"$_inline_prefix\" -W \"$(${vc.shellCommand!})\" -- \"$_cur\"))`];\n case \"none\":\n return [`compopt +o default 2>/dev/null`];\n }\n}\n\n/**\n * Snippet that unsets every shell variable matching `<prefix>*`. Bash 3.2\n * has no associative arrays, so the trackers use one variable per field;\n * the per-invocation reset clears them by enumerating with `compgen -v\n * <prefix>` and feeding the names to `unset`. `2>/dev/null` is paired both\n * sides so an empty enumeration result (no variables yet) doesn't print\n * the `unset:` usage line.\n */\nfunction unsetPrefixed(prefix: string): string {\n return `unset $(compgen -v ${prefix} 2>/dev/null) 2>/dev/null`;\n}\n\nfunction bashFileFilter(checks: string): string[] {\n // `$_inline_prefix` is empty in non-inline mode, so the same template\n // works for both: a set prefix gets prepended, an empty one is a no-op.\n return [\n `local -a _all_entries=($(compgen -f -- \"$_cur\"))`,\n `for _f in \"\\${_all_entries[@]}\"; do`,\n ` if [[ -d \"$_f\" ]]; then`,\n ` COMPREPLY+=(\"\\${_inline_prefix}$_f\")`,\n ` elif ${checks}; then`,\n ` COMPREPLY+=(\"\\${_inline_prefix}$_f\")`,\n ` fi`,\n `done`,\n `compopt -o filenames`,\n `compopt +o default 2>/dev/null`,\n ];\n}\n\n/** Collect value-taking option patterns for case matching */\nfunction optionValueCases(\n options: CompletableOption[],\n positionals: readonly CompletablePositional[],\n inline: boolean,\n fn: string,\n funcSuffix: string,\n): string[] {\n const lines: string[] = [];\n for (const opt of options) {\n if (!opt.takesValue || !opt.valueCompletion) continue;\n const valLines = bashValueLines(opt.valueCompletion, inline, fn, {\n funcSuffix,\n ...optionExpandLocation(opt, options, positionals),\n });\n if (valLines.length === 0) continue;\n\n const patterns = effectiveOptionTokens(opt, options);\n // An option whose every emitted spelling is shadowed by siblings at\n // this frame has nothing to pattern-match on. Emitting an empty\n // `)` branch would break the surrounding case.\n if (patterns.length === 0) continue;\n\n lines.push(` ${patterns.join(\"|\")})`);\n for (const vl of valLines) {\n lines.push(` ${vl}`);\n }\n lines.push(` return ;;`);\n }\n return lines;\n}\n\n/** Generate positional completion block */\nfunction positionalBlock(\n positionals: CompletablePositional[],\n fn: string,\n funcSuffix: string,\n options: readonly CompletableOption[] = [],\n): string[] {\n if (positionals.length === 0) return [];\n const lines: string[] = [];\n lines.push(` case \"$_pos_count\" in`);\n\n for (const pos of positionals) {\n if (pos.variadic) {\n // Variadic: use * to match any position from this index onward\n lines.push(` ${pos.position}|*)`);\n } else {\n lines.push(` ${pos.position})`);\n }\n for (const vl of bashValueLines(pos.valueCompletion, false, fn, {\n funcSuffix,\n ...positionalExpandLocation(pos, options, positionals),\n })) {\n lines.push(` ${vl}`);\n }\n lines.push(` ;;`);\n }\n\n lines.push(` esac`);\n return lines;\n}\n\n/** Generate prev/inline value completion blocks for options */\nfunction valueCompletionBlocks(\n options: CompletableOption[],\n positionals: readonly CompletablePositional[],\n fn: string,\n funcSuffix: string,\n): string[] {\n if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];\n\n const lines: string[] = [];\n const prevCases = optionValueCases(options, positionals, false, fn, funcSuffix);\n if (prevCases.length > 0) {\n lines.push(` if [[ -z \"$_inline_prefix\" ]]; then`);\n lines.push(` case \"$_prev\" in`);\n lines.push(...prevCases);\n lines.push(` esac`);\n lines.push(` fi`);\n }\n const inlineCases = optionValueCases(options, positionals, true, fn, funcSuffix);\n if (inlineCases.length > 0) {\n lines.push(` if [[ -n \"$_inline_prefix\" ]]; then`);\n lines.push(` case \"\\${_inline_prefix%=}\" in`);\n lines.push(...inlineCases);\n lines.push(` esac`);\n lines.push(` fi`);\n }\n return lines;\n}\n\n/** Generate available-options list lines */\nfunction availableOptionLines(options: CompletableOption[], fn: string): string[] {\n const lines: string[] = [];\n for (const opt of options) {\n if (opt.valueType === \"array\") {\n // Array options can be specified multiple times — always keep available\n lines.push(` _avail+=(--${opt.cliName})`);\n continue;\n }\n const patterns = quotedAvailabilityTokens(opt.cliName, opt.alias, opt.negation, {\n isGlobal: opt.isGlobal === true,\n frameOptions: options,\n });\n const guard = `__${fn}_not_used ${patterns.join(\" \")}`;\n const emitNames = opt.negation ? [opt.cliName, opt.negation] : [opt.cliName];\n for (const name of emitNames) {\n // Skip the suggestion when `--name`'s long form was filtered out\n // of the routing-aware token set. For a global whose canonical\n // long form is claimed by a local at this frame, suggesting\n // `--name` would direct the user toward an option the runtime\n // routes elsewhere.\n if (!patterns.includes(`\"--${name}\"`)) continue;\n lines.push(` ${guard} && _avail+=(--${name})`);\n }\n }\n lines.push(` __${fn}_not_used \"--help\" && _avail+=(--help)`);\n return lines;\n}\n\n/**\n * Generate a per-subcommand completion function.\n * Recursively generates functions for nested subcommands.\n */\nfunction generateSubHandler(sub: CompletableSubcommand, fn: string, path: string[]): string[] {\n const fullPath = [...path, sub.name];\n const funcSuffix = fullPath.map(sanitize).join(\"_\");\n const funcName = `__${fn}_complete_${funcSuffix}`;\n const visibleSubs = getVisibleSubs(sub.subcommands);\n\n const lines: string[] = [];\n\n // Recursively generate handlers for child subcommands\n for (const child of visibleSubs) {\n lines.push(...generateSubHandler(child, fn, fullPath));\n }\n\n lines.push(`${funcName}() {`);\n\n // 1. Option value completion (prev is value-taking option)\n lines.push(...valueCompletionBlocks(sub.options, sub.positionals, fn, funcSuffix));\n\n // Fallback: value-taking option without explicit completion → default file completion\n const fullPathStr = fullPath.join(\":\");\n lines.push(\n ` if [[ -z \"$_inline_prefix\" ]] && __${fn}_opt_takes_value \"${fullPathStr}\" \"$_prev\"; then return; fi`,\n );\n lines.push(\n ` if [[ -n \"$_inline_prefix\" ]] && __${fn}_opt_takes_value \"${fullPathStr}\" \"\\${_inline_prefix%=}\"; then return; fi`,\n );\n\n // 2. After -- separator\n if (sub.positionals.length > 0) {\n lines.push(` if (( _after_dd )); then`);\n lines.push(\n ...positionalBlock(sub.positionals, fn, funcSuffix, sub.options).map((l) => ` ${l}`),\n );\n lines.push(` return`);\n lines.push(` fi`);\n } else {\n lines.push(` if (( _after_dd )); then return; fi`);\n }\n\n // 3. Option name completion\n lines.push(` if [[ \"$_cur\" == -* ]]; then`);\n lines.push(` local -a _avail=()`);\n lines.push(...availableOptionLines(sub.options, fn));\n lines.push(` COMPREPLY=($(compgen -W \"\\${_avail[*]}\" -- \"$_cur\"))`);\n lines.push(` compopt +o default 2>/dev/null`);\n lines.push(` return`);\n lines.push(` fi`);\n\n // 4. Subcommand or positional completion\n if (visibleSubs.length > 0) {\n const subNames = getSubNamesWithAliases(sub.subcommands)\n .map((s) => s.name)\n .join(\" \");\n lines.push(` COMPREPLY=($(compgen -W \"${subNames}\" -- \"$_cur\"))`);\n lines.push(` compopt +o default 2>/dev/null`);\n } else if (sub.positionals.length > 0) {\n lines.push(...positionalBlock(sub.positionals, fn, funcSuffix, sub.options));\n }\n\n lines.push(`}`);\n lines.push(``);\n return lines;\n}\n\nexport function generateBashCompletion(\n command: AnyCommand,\n options: CompletionOptions,\n): CompletionResult {\n const { programName } = options;\n const data = extractCompletionData(command, programName, options.globalArgsSchema);\n const fn = sanitize(programName);\n const root = data.command;\n const visibleSubs = getVisibleSubs(root.subcommands);\n const expandSpecs = collectExpandSpecs(root);\n const trackedFields = collectTrackedFields(root, expandSpecs, data.globalOptions);\n\n const lines: string[] = [];\n lines.push(\n ...buildHeaderLines({\n programName,\n shell: \"bash\",\n binPath: options.binPath,\n programVersion: options.programVersion,\n }),\n );\n lines.push(`# Generated by politty`);\n lines.push(``);\n lines.push(...generateBashSelfRefresh({ programName, binPath: options.binPath }));\n\n const hasExpand = expandSpecs.length > 0;\n const arrayExpandSpecs = expandSpecs.filter((s) => s.isArrayOption);\n const hasArrayExpand = arrayExpandSpecs.length > 0;\n\n // Expand-completion hoisted tables. Bash 3.2 (macOS default\n // `/bin/bash`) has no associative arrays, so each table entry becomes a\n // top-level scalar `<base>__<encKey>=<candidates>`. The runtime helper\n // `__<fn>_enc` (emitted once below when `hasExpand`) builds the same\n // encoded suffix from the user's runtime dep values; lookups read via\n // indirect expansion `${!_varname:-}`.\n if (hasExpand) {\n lines.push(`__${fn}_enc() {`);\n // Force C locale so `${_s:_i:1}` extracts ONE BYTE per iteration and\n // `'$_c` resolves to that byte. Without this, a multi-byte UTF-8 dep\n // value is iterated as one char and `'$_c` is implementation-defined\n // — the runtime suffix then disagrees with `bashEncodeKey`'s\n // byte-wise encoding and the lookup misses.\n lines.push(` local LC_ALL=C`);\n lines.push(` local _s=$1 _r='' _c _i`);\n lines.push(` for (( _i=0; _i<\\${#_s}; _i++ )); do`);\n lines.push(` _c=\\${_s:_i:1}`);\n lines.push(` case \"$_c\" in`);\n lines.push(` [a-zA-Z0-9]) _r+=\"$_c\" ;;`);\n lines.push(` *) printf -v _r '%s_%02X' \"$_r\" \"'$_c\" ;;`);\n lines.push(` esac`);\n lines.push(` done`);\n lines.push(` printf '%s' \"$_r\"`);\n lines.push(`}`);\n lines.push(``);\n }\n for (const spec of expandSpecs) {\n const varName = expandTableVarName(fn, spec.funcSuffix, spec.fieldName);\n for (const entry of spec.vc.table) {\n const encKey = entry.key.map(bashEncodeKey).join(\"_\");\n const value = entry.candidates.map((c) => c.value).join(\"\\n\");\n lines.push(`${varName}__${encKey}=${ansiC(value)}`);\n }\n lines.push(``);\n }\n\n // Dynamic completion delegate helpers (only when any value spec uses\n // an in-process JS resolver). The static script invokes\n // `<program> __complete --shell bash` and parses the candidate stream.\n if (hasDynamicCompletion(root)) {\n lines.push(...dynamicInvokeCompleteLines(fn, programName));\n lines.push(``);\n lines.push(`__${fn}_apply_dynamic_output() {`);\n lines.push(` local _raw=\"$1\"`);\n lines.push(` COMPREPLY=()`);\n lines.push(` local _directive=0`);\n lines.push(` local -a _lines=()`);\n lines.push(` local _line`);\n lines.push(` while IFS= read -r _line; do _lines+=(\"$_line\"); done <<< \"$_raw\"`);\n // Only the trailing line is the directive sentinel; intermediate lines\n // beginning with `:` are legitimate candidate values.\n lines.push(` local _last=$((\\${#_lines[@]} - 1))`);\n lines.push(` if (( _last >= 0 )) && [[ \"\\${_lines[$_last]}\" =~ ^:[0-9]+$ ]]; then`);\n lines.push(` _directive=\"\\${_lines[$_last]#:}\"`);\n lines.push(` unset '_lines[_last]'`);\n lines.push(` fi`);\n lines.push(` for _line in \"\\${_lines[@]}\"; do`);\n // Skip only blanks. The `@ext:`/`@matcher:` sentinels are produced by\n // the static shellCommand pipeline, not by dynamic resolvers — filtering\n // them here would silently drop resolver candidates that happen to\n // start with those literal strings.\n lines.push(` [[ -z \"$_line\" ]] && continue`);\n lines.push(` COMPREPLY+=(\"$_line\")`);\n lines.push(` done`);\n // Apply resolver-supplied directive bits. DirectoryCompletion takes\n // precedence over FileCompletion when both are set; NoSpace stacks.\n // bash's `-o default` / `-o dirnames` fall back to filename\n // completion only when COMPREPLY is empty, but their candidates use\n // the *original* word — which still carries the `--opt=` prefix we\n // stripped into `_inline_prefix`. Always expand filesystem matches\n // manually against `$_cur` (prepending `_ip` when an inline prefix\n // is in play) instead of relying on bash's builtin fallback, since\n // `compopt -o dirnames` is unavailable on bash 3.2 (macOS) and would\n // otherwise let the top-level `-o default` registration leak files.\n lines.push(` local _ip=\"\\${_inline_prefix:-}\"`);\n lines.push(` if (( _directive & ${CompletionDirective.DirectoryCompletion} )); then`);\n lines.push(` compopt +o default 2>/dev/null`);\n // `-o filenames` tells bash to treat candidates as paths so spaces\n // and other shell metacharacters are escaped on insertion. Match\n // what the static directory-completion branch sets.\n lines.push(` compopt -o filenames 2>/dev/null`);\n lines.push(` local _d`);\n lines.push(\n ` while IFS= read -r _d; do COMPREPLY+=(\"\\${_ip}\\${_d}\"); done < <(compgen -d -- \"$_cur\")`,\n );\n // On bash 3.2 `compopt +o default` is a no-op, so when no candidates\n // and no directory matches were produced the top-level\n // `complete -o default` fallback would leak file completions into a\n // dir-only directive. Seed an empty sentinel to suppress it.\n lines.push(` if (( \\${#COMPREPLY[@]} == 0 )); then COMPREPLY=( \"\" ); fi`);\n lines.push(` elif (( _directive & ${CompletionDirective.FileCompletion} )); then`);\n lines.push(` if (( \\${#COMPREPLY[@]} > 0 )) || [[ -n \"$_ip\" ]]; then`);\n // Same filenames treatment as the directory branch — `compgen -f`\n // returns raw paths, so the candidate insertion must escape spaces.\n lines.push(` compopt -o filenames 2>/dev/null`);\n lines.push(` local _f`);\n lines.push(\n ` while IFS= read -r _f; do COMPREPLY+=(\"\\${_ip}\\${_f}\"); done < <(compgen -f -- \"$_cur\")`,\n );\n lines.push(` else`);\n lines.push(` compopt -o default 2>/dev/null`);\n lines.push(` fi`);\n lines.push(` else`);\n // Neither FileCompletion nor DirectoryCompletion is requested. Only\n // suppress the `complete -o default` filename fallback when the\n // resolver explicitly opted out via `NoFileCompletion` — `Default`\n // (directive 0) leaves the documented file fallback intact. bash 4+\n // honours `compopt +o default`; bash 3.2 lacks compopt, so a literal\n // empty sentinel keeps the registration from falling through.\n lines.push(` if (( _directive & ${CompletionDirective.NoFileCompletion} )); then`);\n lines.push(` compopt +o default 2>/dev/null`);\n lines.push(` if (( \\${#COMPREPLY[@]} == 0 )); then COMPREPLY=( \"\" ); fi`);\n lines.push(` fi`);\n lines.push(` fi`);\n lines.push(` if (( _directive & ${CompletionDirective.NoSpace} )); then`);\n lines.push(` compopt -o nospace 2>/dev/null`);\n lines.push(` fi`);\n lines.push(`}`);\n lines.push(``);\n }\n\n // Helper: check if option is already used\n lines.push(`__${fn}_not_used() {`);\n lines.push(` for _u in \"\\${_used_opts[@]}\"; do`);\n lines.push(` for _chk in \"$@\"; do`);\n lines.push(` [[ \"$_u\" == \"$_chk\" ]] && return 1`);\n lines.push(` done`);\n lines.push(` done`);\n lines.push(` return 0`);\n lines.push(`}`);\n lines.push(``);\n\n // Helper: check if option takes a value\n lines.push(`__${fn}_opt_takes_value() {`);\n lines.push(` case \"$1:$2\" in`);\n lines.push(...optTakesValueEntries(root, \"\"));\n lines.push(` esac`);\n lines.push(` return 1`);\n lines.push(`}`);\n lines.push(``);\n\n if (hasExpand) {\n // Trackers populate `_arg_values` during the main scan loop so the\n // per-spec lookup can dispatch on sibling arg values. `_track_opt`\n // runs for every option-value pair; `_track_pos` runs once per\n // positional.\n lines.push(`__${fn}_track_opt() {`);\n lines.push(` case \"$1:$2\" in`);\n lines.push(...trackOptCaseLines(trackedFields, \"bash\"));\n lines.push(` esac`);\n lines.push(`}`);\n lines.push(``);\n lines.push(`__${fn}_track_pos() {`);\n lines.push(` case \"$1:$2\" in`);\n lines.push(...trackPosCaseLines(trackedFields, \"bash\"));\n lines.push(` esac`);\n lines.push(`}`);\n lines.push(``);\n }\n\n if (hasArrayExpand) {\n // Track which `key=` slots a repeatable array option has already\n // consumed. Separate function (and bucket) from `__track_opt` so an\n // option that is simultaneously a dependsOn target and an array\n // expand host doesn't collide on the same case pattern. The bucket\n // is space-padded on both ends so membership checks via\n // `*\" $_ck \"*` work for the first and last entries.\n lines.push(`__${fn}_track_array_expand() {`);\n lines.push(` case \"$1:$2\" in`);\n lines.push(...trackArrayExpandCaseLines(arrayExpandSpecs, \"bash\"));\n lines.push(` esac`);\n lines.push(`}`);\n lines.push(``);\n }\n\n // Collect all nested subcommand routes (used for both is_subcmd and dispatch)\n const routeEntries = collectRouteEntries(root);\n\n // Helper: check if a word is a known subcommand at the current path level\n if (routeEntries.length > 0) {\n lines.push(`__${fn}_is_subcmd() {`);\n lines.push(` case \"$1:$2\" in`);\n lines.push(...isSubcmdCaseLines(routeEntries));\n lines.push(` esac`);\n lines.push(` return 1`);\n lines.push(`}`);\n lines.push(``);\n }\n\n // Per-subcommand completion functions\n for (const sub of visibleSubs) {\n lines.push(...generateSubHandler(sub, fn, []));\n }\n\n // Root handler\n lines.push(`__${fn}_complete_root() {`);\n lines.push(...valueCompletionBlocks(root.options, root.positionals, fn, \"root\"));\n // Fallback: value-taking option without explicit completion → default file completion\n lines.push(\n ` if [[ -z \"$_inline_prefix\" ]] && __${fn}_opt_takes_value \"\" \"$_prev\"; then return; fi`,\n );\n lines.push(\n ` if [[ -n \"$_inline_prefix\" ]] && __${fn}_opt_takes_value \"\" \"\\${_inline_prefix%=}\"; then return; fi`,\n );\n if (root.positionals.length > 0) {\n lines.push(` if (( _after_dd )); then`);\n lines.push(\n ...positionalBlock(root.positionals, fn, \"root\", root.options).map((l) => ` ${l}`),\n );\n lines.push(` return`);\n lines.push(` fi`);\n } else {\n lines.push(` if (( _after_dd )); then return; fi`);\n }\n lines.push(` if [[ \"$_cur\" == -* ]]; then`);\n lines.push(` local -a _avail=()`);\n lines.push(...availableOptionLines(root.options, fn));\n lines.push(` COMPREPLY=($(compgen -W \"\\${_avail[*]}\" -- \"$_cur\"))`);\n lines.push(` compopt +o default 2>/dev/null`);\n if (visibleSubs.length > 0) {\n lines.push(` else`);\n const subNames = getSubNamesWithAliases(root.subcommands)\n .map((s) => s.name)\n .join(\" \");\n lines.push(` COMPREPLY=($(compgen -W \"${subNames}\" -- \"$_cur\"))`);\n lines.push(` compopt +o default 2>/dev/null`);\n } else if (root.positionals.length > 0) {\n lines.push(` else`);\n lines.push(\n ...positionalBlock(root.positionals, fn, \"root\", root.options).map((l) => ` ${l}`),\n );\n }\n lines.push(` fi`);\n lines.push(`}`);\n lines.push(``);\n\n // Main completion function -- subcommand dispatch routing\n const subRouting = subDispatchCaseLines(routeEntries, fn).join(\"\\n\");\n\n lines.push(`_${fn}_completions() {`);\n lines.push(` COMPREPLY=()`);\n lines.push(``);\n lines.push(` # Rejoin words split by '=' in COMP_WORDBREAKS`);\n lines.push(` local -a _words=()`);\n lines.push(` local _i=1`);\n lines.push(` while (( _i <= COMP_CWORD )); do`);\n lines.push(` if [[ \"\\${COMP_WORDS[_i]}\" == \"=\" && \\${#_words[@]} -gt 0 ]]; then`);\n lines.push(` _words[\\${#_words[@]}-1]+=\"=\\${COMP_WORDS[_i+1]:-}\"`);\n lines.push(` (( _i += 2 ))`);\n lines.push(` else`);\n lines.push(` _words+=(\"\\${COMP_WORDS[_i]}\")`);\n lines.push(` (( _i++ ))`);\n lines.push(` fi`);\n lines.push(` done`);\n lines.push(``);\n lines.push(` local _cur=\"\"`);\n lines.push(` (( \\${#_words[@]} > 0 )) && _cur=\"\\${_words[\\${#_words[@]}-1]}\"`);\n // _inline_prefix is computed AFTER the pre-scan loop below so we can\n // suppress the split when the cursor word follows a `--`. Otherwise\n // `cmd -- -D=foo<TAB>` would strip `-D=` as if it were an inline\n // option-value prefix and feed `foo` through positional completion\n // with `-D=` re-prepended, yielding garbage candidates.\n lines.push(` local _inline_prefix=\"\"`);\n lines.push(``);\n lines.push(` local _prev=\"\"`);\n lines.push(` (( \\${#_words[@]} > 1 )) && _prev=\"\\${_words[\\${#_words[@]}-2]}\"`);\n lines.push(``);\n lines.push(` local _subcmd=\"\" _after_dd=0 _pos_count=0 _skip_next=0`);\n lines.push(` local -a _used_opts=()`);\n if (hasExpand) {\n // Bash 3.2 has no associative arrays — trackers write per-field\n // scalars (`_arg_values_<field>`, `_global_arg_values_<field>`).\n // Wipe any leftovers from a previous invocation so completion state\n // is fresh on every TAB. Globals survive subcommand descent within\n // the same invocation (re-populated below by the scan loop) but must\n // not bleed across invocations.\n lines.push(` ${unsetPrefixed(\"_arg_values_\")}`);\n lines.push(` ${unsetPrefixed(\"_global_arg_values_\")}`);\n }\n if (hasArrayExpand) {\n lines.push(` ${unsetPrefixed(\"_used_field_keys_\")}`);\n lines.push(` ${unsetPrefixed(\"_global_used_field_keys_\")}`);\n // Per-frame seen-set: marks which global array buckets have been\n // written in the current frame so the first write replaces the\n // inherited entries. Cleared on every subcommand descent below.\n lines.push(` ${unsetPrefixed(\"_global_arr_seen_\")}`);\n }\n lines.push(``);\n lines.push(` local _j=0`);\n lines.push(` while (( _j < \\${#_words[@]} - 1 )); do`);\n lines.push(` local _w=\"\\${_words[_j]}\"`);\n lines.push(` if (( _skip_next )); then _skip_next=0; (( _j++ )); continue; fi`);\n lines.push(` if [[ \"$_w\" == \"--\" ]]; then _after_dd=1; (( _j++ )); continue; fi`);\n // After `--`, all remaining words are positionals. Track them so an\n // expand spec that depends on a positional still sees the value.\n const afterDdTrack = hasExpand ? `__${fn}_track_pos \"$_subcmd\" \"$_pos_count\" \"$_w\"; ` : \"\";\n lines.push(\n ` if (( _after_dd )); then ${afterDdTrack}(( _pos_count++ )); (( _j++ )); continue; fi`,\n );\n // Match both `--opt=value` and `-o=value`: the parser accepts the\n // short inline form too, so the scanner must split it before tracking\n // the dep value, otherwise `-e=prod` slips past the tracker.\n lines.push(` if [[ \"$_w\" == -*=* ]]; then`);\n lines.push(` _used_opts+=(\"\\${_w%%=*}\")`);\n if (hasExpand) {\n lines.push(` __${fn}_track_opt \"$_subcmd\" \"\\${_w%%=*}\" \"\\${_w#*=}\"`);\n if (hasArrayExpand) {\n lines.push(` __${fn}_track_array_expand \"$_subcmd\" \"\\${_w%%=*}\" \"\\${_w#*=}\"`);\n }\n }\n lines.push(` (( _j++ )); continue`);\n lines.push(` fi`);\n lines.push(` if [[ \"$_w\" == -* ]]; then`);\n lines.push(` _used_opts+=(\"$_w\")`);\n // Mirror the runtime parser: a token starting with `-` is the next\n // option, not this option's value, so don't skip/track it. Otherwise\n // `--config --env prod --field <TAB>` treats `--env` as `--config`'s\n // value and the expand dep is lost.\n lines.push(` if __${fn}_opt_takes_value \"$_subcmd\" \"$_w\"; then`);\n lines.push(` local _next=\"\\${_words[_j+1]:-}\"`);\n lines.push(` if [[ -n \"$_next\" && \"$_next\" != -* ]]; then _skip_next=1; fi`);\n if (hasExpand) {\n lines.push(` if (( _skip_next )); then`);\n lines.push(` __${fn}_track_opt \"$_subcmd\" \"$_w\" \"$_next\"`);\n if (hasArrayExpand) {\n // Skip array-expand dedup tracking when the next token is the word\n // being completed. Otherwise typing `-f pageDirection=<TAB>` marks\n // the partial cursor value as already used and filters out the\n // candidates the user is trying to select.\n lines.push(` if (( _j + 2 < \\${#_words[@]} )); then`);\n lines.push(` __${fn}_track_array_expand \"$_subcmd\" \"$_w\" \"$_next\"`);\n lines.push(` fi`);\n }\n lines.push(` fi`);\n }\n lines.push(` fi`);\n lines.push(` (( _j++ )); continue`);\n lines.push(` fi`);\n // Clear sibling-tracker state when descending into a subcommand:\n // `dependsOn` is scoped to siblings on the same command frame, so\n // letting a parent's `--env` bleed into a child with its own `--env`\n // would feed the wrong value into the child's expand lookup.\n // Prefix-scalar equivalent of the bash 4 `_arg_values=()` reset: drop\n // every per-field scalar written by the trackers so far. compgen -v\n // takes a prefix and prints matching variable names; bash 3.2+.\n const clearState = hasArrayExpand\n ? `; ${unsetPrefixed(\"_arg_values_\")}; ${unsetPrefixed(\"_used_field_keys_\")}; ${unsetPrefixed(\"_global_arr_seen_\")}`\n : hasExpand\n ? `; ${unsetPrefixed(\"_arg_values_\")}`\n : \"\";\n const posTrack = hasExpand ? `__${fn}_track_pos \"$_subcmd\" \"$_pos_count\" \"$_w\"; ` : \"\";\n if (routeEntries.length > 0) {\n lines.push(\n ` if __${fn}_is_subcmd \"$_subcmd\" \"$_w\"; then _subcmd=\"\\${_subcmd:+\\${_subcmd}:}$_w\"; _used_opts=(); _pos_count=0${clearState}; else ${posTrack}(( _pos_count++ )); fi`,\n );\n } else {\n if (hasExpand) {\n lines.push(` __${fn}_track_pos \"$_subcmd\" \"$_pos_count\" \"$_w\"`);\n }\n lines.push(` (( _pos_count++ ))`);\n }\n lines.push(` (( _j++ ))`);\n lines.push(` done`);\n lines.push(``);\n // Strip `--opt=value` / `-o=value` inline prefixes from the cursor\n // ONLY when the cursor is not a positional after `--`. Doing this\n // after the scan means `_after_dd` is reliable; \\`cmd -- -D=foo\\`\n // keeps \\`_cur=\"-D=foo\"\\` so positional completion sees the whole\n // token instead of garbage.\n lines.push(` if (( ! _after_dd )) && [[ \"$_cur\" == -*=* ]]; then`);\n lines.push(` _inline_prefix=\"\\${_cur%%=*}=\"`);\n lines.push(` _cur=\"\\${_cur#*=}\"`);\n lines.push(` fi`);\n lines.push(``);\n lines.push(` case \"$_subcmd\" in`);\n lines.push(subRouting);\n lines.push(` *) __${fn}_complete_root ;;`);\n lines.push(` esac`);\n lines.push(`}`);\n lines.push(``);\n lines.push(`complete -o default -F _${fn}_completions ${programName}`);\n lines.push(``);\n\n return {\n script: lines.join(\"\\n\"),\n shell: \"bash\",\n installInstructions: `# To enable auto-refreshing bash completions, add this to your ~/.bashrc:\neval \"$(${programName} completion bash)\"\n\n# For faster shell startup, save the script instead:\nmkdir -p ~/.local/share/bash-completion/completions\n${programName} completion bash > ~/.local/share/bash-completion/completions/${programName}\n\n# Then reload your shell or run:\nsource ~/.bashrc`,\n };\n}\n","/**\n * Shell-specific output formatter for completion candidates\n *\n * Formats completion candidates into shell-native output so that\n * shell scripts can consume them with minimal parsing logic.\n */\n\nimport type { ShellType } from \"../types.js\";\nimport { CompletionDirective, type CandidateResult } from \"./candidate-generator.js\";\n\n/**\n * Options for shell-specific formatting\n */\nexport interface ShellFormatOptions {\n /** Target shell type */\n shell: ShellType;\n /** Current word being completed (used for prefix filtering) */\n currentWord: string;\n /** For bash: the prefix before '=' in --opt=value completions */\n inlinePrefix?: string | undefined;\n}\n\n/**\n * Format completion candidates for the specified shell\n *\n * @returns Shell-ready output string (lines separated by newline, last line is :directive)\n */\nexport function formatForShell(result: CandidateResult, options: ShellFormatOptions): string {\n switch (options.shell) {\n case \"bash\":\n return formatForBash(result, options);\n case \"zsh\":\n return formatForZsh(result, options);\n case \"fish\":\n return formatForFish(result, options);\n }\n}\n\n/**\n * Append extension metadata and directive to output lines\n */\nfunction appendMetadata(lines: string[], result: CandidateResult): void {\n if (result.fileExtensions && result.fileExtensions.length > 0) {\n lines.push(`@ext:${result.fileExtensions.join(\",\")}`);\n }\n if (result.fileMatchers && result.fileMatchers.length > 0) {\n lines.push(`@matcher:${result.fileMatchers.join(\",\")}`);\n }\n lines.push(`:${result.directive}`);\n}\n\n/**\n * Format for bash\n *\n * - Pre-filters candidates by currentWord prefix (replaces compgen -W)\n * - Handles --opt=value inline values by prepending prefix\n * - Outputs plain values only (no descriptions - bash COMPREPLY doesn't support them)\n * - Last line: :directive\n */\nfunction formatForBash(result: CandidateResult, options: ShellFormatOptions): string {\n const filtered =\n (result.directive & CompletionDirective.FilterPrefix) !== 0 && options.currentWord\n ? result.candidates.filter((c) => c.value.startsWith(options.currentWord))\n : result.candidates;\n\n const lines: string[] = filtered.map((c) =>\n options.inlinePrefix ? `${options.inlinePrefix}${c.value}` : c.value,\n );\n\n appendMetadata(lines, result);\n return lines.join(\"\\n\");\n}\n\n/**\n * Format for zsh\n *\n * - Outputs value:description pairs for _describe\n * - Colons in values/descriptions are escaped with backslash\n * - Last line: :directive\n */\nfunction formatForZsh(result: CandidateResult, _options: ShellFormatOptions): string {\n const lines: string[] = result.candidates.map((c) => {\n const escapedValue = c.value.replace(/:/g, \"\\\\:\");\n if (c.description) {\n const escapedDesc = c.description.replace(/:/g, \"\\\\:\");\n return `${escapedValue}:${escapedDesc}`;\n }\n return escapedValue;\n });\n\n appendMetadata(lines, result);\n return lines.join(\"\\n\");\n}\n\n/**\n * Format for fish\n *\n * - Outputs value\\tdescription pairs\n * - Last line: :directive\n */\nfunction formatForFish(result: CandidateResult, _options: ShellFormatOptions): string {\n const lines: string[] = result.candidates.map((c) => {\n if (c.description) {\n return `${c.value}\\t${c.description}`;\n }\n return c.value;\n });\n\n appendMetadata(lines, result);\n return lines.join(\"\\n\");\n}\n","/**\n * Dynamic completion command implementation\n *\n * This creates a hidden `__complete` command that outputs completion candidates\n * for shell scripts to consume. Usage:\n *\n * mycli __complete --shell bash -- build --fo\n * mycli __complete --shell zsh -- plugin add\n *\n * Output format depends on the target shell:\n * bash: plain values (pre-filtered by prefix), last line :directive\n * zsh: value:description pairs, last line :directive\n * fish: value\\tdescription pairs, last line :directive\n */\n\nimport { z } from \"zod\";\nimport { arg } from \"../../core/arg-registry.js\";\nimport { defineCommand } from \"../../core/command.js\";\nimport type { AnyCommand, ArgsSchema, Command } from \"../../types.js\";\nimport { detectInlineOptionPrefix, generateCandidates } from \"./candidate-generator.js\";\nimport { parseCompletionContext } from \"./context-parser.js\";\nimport { formatForShell } from \"./shell-formatter.js\";\n\n/**\n * Schema for the __complete command\n */\nconst completeArgsSchema = z.object({\n shell: arg(z.enum([\"bash\", \"zsh\", \"fish\"]), {\n description: \"Target shell for output formatting\",\n }),\n // The arguments to complete are passed after --\n args: arg(z.array(z.string()).default([]), {\n positional: true,\n description: \"Arguments to complete\",\n variadic: true,\n }),\n});\n\ntype CompleteArgs = z.infer<typeof completeArgsSchema>;\n\n/**\n * Create the dynamic completion command\n *\n * @param rootCommand - The root command to generate completions for\n * @param programName - The program name (optional, defaults to rootCommand.name)\n * @param globalArgsSchema - Global args schema. Forwarded to\n * `parseCompletionContext` so resolvers attached to global options remain\n * reachable at every subcommand level.\n * @returns A command that outputs completion candidates\n */\nexport function createDynamicCompleteCommand(\n rootCommand: AnyCommand,\n _programName?: string,\n globalArgsSchema?: ArgsSchema,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Command<typeof completeArgsSchema, CompleteArgs, any> {\n return defineCommand({\n name: \"__complete\",\n // No description - this is a hidden command\n args: completeArgsSchema,\n async run(args) {\n const context = parseCompletionContext(args.args, rootCommand, globalArgsSchema);\n\n // Detect the inline `--opt=` prefix so the formatter can re-attach\n // it to bash candidates. `generateCandidates` performs the same\n // strip internally so resolvers see only the value portion;\n // positionals (e.g. `cli -- --foo=<TAB>`) keep the prefix as part\n // of the value and bypass this detection.\n const inlinePrefix =\n context.completionType === \"option-value\" && context.targetOption\n ? detectInlineOptionPrefix(context.currentWord)\n : undefined;\n const effectiveWord = inlinePrefix\n ? context.currentWord.slice(inlinePrefix.length)\n : context.currentWord;\n\n const result = await generateCandidates(context, { shell: args.shell });\n\n const output = formatForShell(result, {\n shell: args.shell,\n currentWord: effectiveWord,\n inlinePrefix,\n });\n\n console.log(output);\n },\n });\n}\n\n/**\n * Check if a command tree contains the __complete command\n */\nexport function hasCompleteCommand(command: AnyCommand): boolean {\n return Boolean(command.subCommands?.[\"__complete\"]);\n}\n","/**\n * Fish completion script generator (static)\n *\n * Generates a self-contained fish completion script that embeds all\n * completion metadata. No Node.js process is spawned on TAB.\n */\n\nimport type { AnyCommand } from \"../types.js\";\nimport { CompletionDirective } from \"./dynamic/candidate-generator.js\";\nimport {\n binEnvVarName,\n collectExpandSpecs,\n collectRouteEntries,\n collectTrackedFields,\n effectiveOptionTokens,\n extractCompletionData,\n getSubNamesWithAliases,\n getVisibleSubs,\n hasDynamicCompletion,\n sanitize,\n walkOptTakesValueRows,\n} from \"./extractor.js\";\nimport { buildHeaderLines, computeBinSig, resolveBinPath } from \"./header.js\";\nimport {\n optionExpandLocation,\n positionalExpandLocation,\n quotedAvailabilityTokens,\n type BaseExpandLocation,\n type ResolvedExpandDep,\n} from \"./shell-shared.js\";\nimport type {\n CompletableOption,\n CompletablePositional,\n CompletableSubcommand,\n CompletionOptions,\n CompletionResult,\n ValueCompletion,\n} from \"./types.js\";\n\n/** Escape shell-special characters for fish double-quoted strings */\nfunction escapeDesc(s: string): string {\n return s.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"').replace(/\\$/g, \"\\\\$\");\n}\n\n/**\n * Escape a fish `switch` case pattern. Fish's `case` interprets its\n * arguments as globs even when double-quoted, so glob metacharacters\n * (`*`, `?`, `[`, `]`) must be backslash-escaped to keep the comparison\n * literal — otherwise a key like `prod*` would also match a runtime\n * value of `production`. Quote/dollar/backslash are escaped first so the\n * resulting string remains valid inside a double-quoted literal.\n */\nfunction fishCaseEscape(s: string): string {\n return s\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\$/g, \"\\\\$\")\n .replace(/\\*/g, \"\\\\*\")\n .replace(/\\?/g, \"\\\\?\")\n .replace(/\\[/g, \"\\\\[\")\n .replace(/]/g, \"\\\\]\");\n}\n\n/**\n * Generate fish value completion lines for a ValueCompletion spec.\n * Each line outputs candidates via echo (tab-separated value\\tdescription).\n *\n * `location` is required for the expand variant (carries fieldName +\n * isArrayOption); other variants ignore it.\n */\nfunction fishValueLines(\n vc: ValueCompletion | undefined,\n fn: string,\n location?: BaseExpandLocation,\n): string[] {\n if (!vc) return [];\n switch (vc.type) {\n case \"expand\": {\n if (!location) {\n throw new Error(\"fishValueLines: expand variant requires a location\");\n }\n // Fish has no associative arrays, so emit an inline switch over the\n // dependsOn values. For multi-dimensional dependsOn the values are\n // concatenated with the unit-separator so they collide cleanly with\n // the table keys we encode here. Candidates carry `value\\tdescription`\n // when a description is set, matching fish's preferred format. Each\n // dep reads from its matching bucket — local deps from\n // `_arg_values_<d>`, global deps from `_global_arg_values_<d>` —\n // so a local dep is never accidentally satisfied by a same-named\n // global value supplied at a parent frame.\n // Fish variable names accept only alnum + underscore; sanitize the\n // field name so a hyphenated schema key (e.g. `env-name`) still\n // produces a valid `$_arg_values_env_name`.\n const depExpr = (d: ResolvedExpandDep): string => {\n const safe = sanitize(d.name);\n return d.isGlobal ? `$_global_arg_values_${safe}` : `$_arg_values_${safe}`;\n };\n const depKey = location.resolvedDeps.map((d) => `\"${depExpr(d)}\"`).join(`\\\\x1f`);\n const bucket = sanitize(location.fieldName);\n // Array dedup bucket lookup mirrors host scope: globals read the\n // _global bucket; locals read the local bucket.\n const bucketList = location.isGlobal\n ? `$_global_used_field_keys_${bucket}`\n : `$_used_field_keys_${bucket}`;\n const out: string[] = [`switch ${depKey}`];\n for (const entry of vc.table) {\n // Mirror `depKey`'s layout: each segment is its own double-quoted\n // string with an UNQUOTED `\\x1f` joining them. Fish does not honor\n // `\\x` escapes inside double quotes, so `case \"k1\\x1fk2\"` would\n // wait for a literal `\\x1f` sequence and never match the switch\n // expression (which carries the actual 0x1f byte).\n const casePattern = entry.key.map((k) => `\"${fishCaseEscape(k)}\"`).join(`\\\\x1f`);\n out.push(` case ${casePattern}`);\n\n // Two-stage `key=value`: when the user has not typed `=` yet,\n // emit each unique key as `key=` so the first TAB picks the\n // key. After `=` is typed the full `key=value` candidates are\n // emitted so the second TAB picks the value. The branch is\n // selected at runtime via `$_cur` so the user sees only what\n // is relevant for their current input.\n const keyOnlyLines: string[] = [];\n const fullLines: string[] = [];\n const seenKeys = new Set<string>();\n\n // `printf` instead of `echo` — `expand` candidates accept arbitrary\n // strings, and a value matching one of fish's `echo` flags (`-n`,\n // `-e`, `-s`, `-E`) would be swallowed as an option and disappear\n // from the completion list.\n const printfLine = (value: string, description?: string): string =>\n description\n ? `printf '%s\\\\t%s\\\\n' \"${escapeDesc(value)}\" \"${escapeDesc(description)}\"`\n : `printf '%s\\\\n' \"${escapeDesc(value)}\"`;\n // Wrap a single echo line in the array-host dedup guard when the\n // host is repeatable AND the candidate carries a key prefix. For\n // candidates without `=` the dedup is a no-op so the line is\n // emitted bare.\n const wrapWithDedup = (echoLine: string, keyPart: string): string[] =>\n location.isArrayOption && keyPart.length > 0\n ? [\n ` if not contains -- \"${escapeDesc(keyPart)}\" ${bucketList}`,\n ` ${echoLine}`,\n ` end`,\n ]\n : [` ${echoLine}`];\n\n for (const c of entry.candidates) {\n const eqIdx = c.value.indexOf(\"=\");\n const keyPart = eqIdx > 0 ? c.value.slice(0, eqIdx) : \"\";\n const echoLine = printfLine(c.value, c.description);\n // A candidate that ends with `=` is a bare key (no value yet).\n // Skip it in the value-stage branch so the picker doesn't\n // surface the key the user already typed.\n const isBareKey = keyPart.length > 0 && c.value.length === eqIdx + 1;\n\n if (!isBareKey) {\n fullLines.push(...wrapWithDedup(echoLine, keyPart));\n }\n\n if (keyPart.length === 0) {\n // Candidate without `=` — same in both branches.\n keyOnlyLines.push(` ${echoLine}`);\n } else if (!seenKeys.has(keyPart)) {\n seenKeys.add(keyPart);\n // Reuse the original description on the collapsed key form.\n keyOnlyLines.push(...wrapWithDedup(printfLine(`${keyPart}=`, c.description), keyPart));\n }\n }\n\n // Split into two runtime branches whenever the two stages differ.\n // They are identical only when every candidate has no `=` (no key\n // collapse and no bare-key drop); in that case a single branch\n // suffices.\n const branchesDiffer =\n fullLines.length !== keyOnlyLines.length ||\n fullLines.some((l, i) => l !== keyOnlyLines[i]);\n if (branchesDiffer) {\n out.push(` if string match -q '*=*' -- \"$_cur\"`);\n out.push(...fullLines);\n out.push(` else`);\n out.push(...keyOnlyLines);\n out.push(` end`);\n } else {\n out.push(...fullLines);\n }\n }\n out.push(`end`);\n return out;\n }\n case \"dynamic\": {\n // Delegate to `<program> __complete --shell fish` and pipe each line\n // through the apply helper, which interprets the trailing\n // `:<directive>` so resolver-supplied file/directory completion still\n // reaches the shell. `$_cur` is passed so file/dir directives respect\n // the partial path the user has typed.\n return [`__${fn}_invoke_complete fish $_args | __${fn}_apply_dynamic_output \"$_cur\"`];\n }\n case \"choices\":\n return vc.choices!.map((c) => `echo \"${escapeDesc(c)}\"`);\n case \"file\": {\n if (vc.matcher?.length) {\n return fishMatcherLines(vc.matcher);\n }\n if (vc.extensions?.length) {\n return fishExtensionLines(vc.extensions);\n }\n return [`__fish_complete_path \"$_cur\"`];\n }\n case \"directory\":\n return [`__fish_complete_directories \"$_cur\"`];\n case \"command\":\n return [`for _v in (${vc.shellCommand!})`, ` echo \"$_v\"`, `end`];\n case \"none\":\n return [];\n }\n}\n\n/** Generate fish matcher-filtered file completion */\nfunction fishMatcherLines(patterns: string[]): string[] {\n return [\n `__fish_complete_directories \"$_cur\"`,\n // Extract directory prefix from $_cur for correct subdirectory matching\n `set -l _dir \"\"`,\n `if string match -q '*/*' \"$_cur\"`,\n ` set _dir (string replace -r '[^/]*$' '' \"$_cur\")`,\n `end`,\n ...patterns.flatMap((p) => [\n `for _f in \"$_dir\"${p}`,\n ` test -f \"$_f\"; and string match -q \"$_cur*\" \"$_f\"; and echo \"$_f\"`,\n `end`,\n ]),\n ];\n}\n\n/** Generate fish extension-filtered file completion */\nfunction fishExtensionLines(extensions: string[]): string[] {\n const lines: string[] = [];\n lines.push(`__fish_complete_directories \"$_cur\"`);\n for (const ext of extensions) {\n lines.push(`for _f in \"$_cur\"*.${ext}`);\n lines.push(` test -f \"$_f\"; and echo \"$_f\"`);\n lines.push(`end`);\n }\n return lines;\n}\n\n/** Generate option-value switch cases for fish */\nfunction optionValueCases(\n options: CompletableOption[],\n positionals: readonly CompletablePositional[],\n fn: string,\n): string[] {\n const lines: string[] = [];\n for (const opt of options) {\n if (!opt.takesValue || !opt.valueCompletion) continue;\n const valLines = fishValueLines(\n opt.valueCompletion,\n fn,\n optionExpandLocation(opt, options, positionals),\n );\n if (valLines.length === 0) continue;\n\n // Mirror the bash/zsh tracker emission: use every CLI token the\n // runtime's aliasMap accepts so a value-completion trigger fires\n // for every valid spelling of this option (1-char cliName as `-x`,\n // 1-char alias long form `--f`, camelCase of hyphenated names).\n const tokens = effectiveOptionTokens(opt, options);\n // No surviving spelling means no condition; an empty `if`\n // generates invalid fish syntax.\n if (tokens.length === 0) continue;\n const cond = tokens.map((t) => `test \"$_prev\" = \"${t}\"`).join(\"; or \");\n\n lines.push(` if ${cond}`);\n for (const vl of valLines) {\n lines.push(` ${vl}`);\n }\n lines.push(` return`);\n lines.push(` end`);\n }\n return lines;\n}\n\n/** Generate positional completion block for fish */\nfunction positionalBlock(\n positionals: CompletablePositional[],\n fn: string,\n options: readonly CompletableOption[] = [],\n): string[] {\n if (positionals.length === 0) return [];\n const lines: string[] = [];\n for (const pos of positionals) {\n const valLines = fishValueLines(\n pos.valueCompletion,\n fn,\n positionalExpandLocation(pos, options, positionals),\n );\n if (valLines.length === 0) continue;\n\n if (pos.variadic) {\n lines.push(` if test $_pos_count -ge ${pos.position}`);\n } else {\n lines.push(` if test $_pos_count -eq ${pos.position}`);\n }\n for (const vl of valLines) {\n lines.push(` ${vl}`);\n }\n lines.push(` return`);\n lines.push(` end`);\n }\n return lines;\n}\n\n/** Generate available-option echo lines for fish */\nfunction availableOptionLines(options: CompletableOption[], fn: string): string[] {\n const lines: string[] = [];\n for (const opt of options) {\n const desc = escapeDesc(opt.description ?? \"\");\n if (opt.valueType === \"array\") {\n lines.push(` echo \"--${opt.cliName}\\t${desc}\"`);\n continue;\n }\n const checks = quotedAvailabilityTokens(opt.cliName, opt.alias, opt.negation, {\n isGlobal: opt.isGlobal === true,\n frameOptions: options,\n });\n const guard = `__${fn}_not_used ${checks.join(\" \")}`;\n const negDesc = opt.negationDescription ? escapeDesc(opt.negationDescription) : desc;\n const entries: Array<{ name: string; desc: string }> = [{ name: opt.cliName, desc }];\n if (opt.negation) entries.push({ name: opt.negation, desc: negDesc });\n for (const e of entries) {\n // Skip the suggestion when `--name`'s long form was filtered out\n // of the routing-aware token set — emitting it would point the\n // user at an option the runtime routes elsewhere.\n if (!checks.includes(`\"--${e.name}\"`)) continue;\n lines.push(` ${guard}; and echo \"--${e.name}\\t${e.desc}\"`);\n }\n }\n lines.push(` __${fn}_not_used \"--help\"; and echo \"--help\\tShow help\"`);\n return lines;\n}\n\n/**\n * Generate a per-subcommand completion function for fish.\n * Recursively generates functions for nested subcommands.\n */\nfunction generateSubHandler(sub: CompletableSubcommand, fn: string, path: string[]): string[] {\n const fullPath = [...path, sub.name];\n const funcName = `__${fn}_complete_${fullPath.map(sanitize).join(\"_\")}`;\n const visibleSubs = getVisibleSubs(sub.subcommands);\n\n const lines: string[] = [];\n\n // Recursively generate handlers for child subcommands\n for (const child of visibleSubs) {\n lines.push(...generateSubHandler(child, fn, fullPath));\n }\n\n lines.push(`function ${funcName} --no-scope-shadowing`);\n\n // 1. Option value completion\n lines.push(...optionValueCases(sub.options, sub.positionals, fn));\n // Fallback: value-taking option without explicit completion → default file completion\n const fullPathStr = fullPath.join(\":\");\n lines.push(` if __${fn}_opt_takes_value \"${fullPathStr}\" \"$_prev\"; return; end`);\n\n // 2. After -- separator\n if (sub.positionals.length > 0) {\n lines.push(` if test $_after_dd -eq 1`);\n lines.push(...positionalBlock(sub.positionals, fn, sub.options).map((l) => ` ${l}`));\n lines.push(` return`);\n lines.push(` end`);\n } else {\n lines.push(` if test $_after_dd -eq 1; return; end`);\n }\n\n // 3. Option name completion\n lines.push(` if string match -q -- '-*' \"$_cur\"`);\n lines.push(...availableOptionLines(sub.options, fn));\n lines.push(` return`);\n lines.push(` end`);\n\n // 4. Subcommand or positional completion (includes aliases)\n if (visibleSubs.length > 0) {\n for (const s of getSubNamesWithAliases(sub.subcommands)) {\n const desc = escapeDesc(s.description ?? \"\");\n lines.push(` echo \"${s.name}\\t${desc}\"`);\n }\n } else if (sub.positionals.length > 0) {\n lines.push(...positionalBlock(sub.positionals, fn, sub.options));\n }\n\n lines.push(`end`);\n lines.push(``);\n return lines;\n}\n\n/** Generate opt-takes-value entries for fish switch cases */\nfunction optTakesValueCases(sub: CompletableSubcommand, parentPath: string): string[] {\n const lines: string[] = [];\n for (const row of walkOptTakesValueRows(sub, parentPath)) {\n const patterns = row.tokens.map((t) => `\"${row.parentPath}:${t}\"`);\n lines.push(` case ${patterns.join(\" \")}`);\n lines.push(` return 0`);\n }\n return lines;\n}\n\nexport function generateFishCompletion(\n command: AnyCommand,\n options: CompletionOptions,\n): CompletionResult {\n const { programName } = options;\n const data = extractCompletionData(command, programName, options.globalArgsSchema);\n const fn = sanitize(programName);\n const root = data.command;\n const visibleSubs = getVisibleSubs(root.subcommands);\n const expandSpecs = collectExpandSpecs(root);\n const trackedFields = collectTrackedFields(root, expandSpecs, data.globalOptions);\n const hasExpand = expandSpecs.length > 0;\n const arrayExpandSpecs = expandSpecs.filter((s) => s.isArrayOption);\n const hasArrayExpand = arrayExpandSpecs.length > 0;\n\n const lines: string[] = [];\n lines.push(\n ...buildHeaderLines({\n programName,\n shell: \"fish\",\n binPath: options.binPath,\n programVersion: options.programVersion,\n }),\n );\n lines.push(`# Generated by politty`);\n lines.push(``);\n\n // Self-rewriting autoload header. Fish autoloads completion files\n // from `$__fish_config_dir/completions/<prog>.fish` lazily, so the\n // refresh check has to live in the file itself. When the binary's\n // mtime no longer matches the embedded sig, we regenerate the file\n // in place via the hidden __refresh-completion subcommand, then\n // `source` the rewritten file so the *current* session picks up the\n // new definitions, and `return` from this script so the rest of the\n // *old* file (stale helper functions and `complete` registrations)\n // doesn't run on top of the freshly sourced new definitions.\n // Failures are silent — a stale completion is preferable to a\n // shell-startup error.\n //\n // We invoke __refresh-completion (internal) instead of\n // `<bin> completion fish`: the foreground completion command runs\n // user setup/cleanup/prompt and validates required globalArgs, which\n // can fail or block when triggered from autoload.\n const sig = computeBinSig(resolveBinPath(programName, options.binPath));\n const refreshFn = `__${fn}_refresh_completion`;\n lines.push(`function ${refreshFn} --no-scope-shadowing`);\n lines.push(` set -l _bin (command -v ${programName})`);\n lines.push(` test -z \"$_bin\"; and return 1`);\n // `-L` follows symlinks so the shell-side mtime matches Node's\n // `fs.statSync`, mirroring the bash/zsh loader. Probe order matches\n // the bash/zsh loader: GNU (`-c`) first because `-f` is filesystem\n // mode there and would otherwise dump filesystem info into `_sig`.\n lines.push(\n ` set -l _sig (stat -L -c '%Y' \"$_bin\" 2>/dev/null; or stat -L -f '%m' \"$_bin\" 2>/dev/null)`,\n );\n lines.push(` test \"$_sig\" = \"${sig}\"; and return 1`);\n lines.push(` set -l _target (status current-filename)`);\n lines.push(` test -n \"$_target\"; and test -f \"$_target\"; or return 1`);\n lines.push(` \"$_bin\" __refresh-completion fish \"$_target\" 2>/dev/null`);\n lines.push(` and source \"$_target\" 2>/dev/null`);\n lines.push(` and return 0`);\n lines.push(` return 1`);\n lines.push(`end`);\n lines.push(`${refreshFn}`);\n lines.push(`set -l _politty_refreshed $status`);\n lines.push(`functions -e ${refreshFn}`);\n // `return` from a sourced fish script aborts the rest of the source\n // call, so the stale `complete -c` lines below do not execute when\n // the fresh script has already been sourced.\n lines.push(`test $_politty_refreshed -eq 0; and return`);\n lines.push(``);\n\n // Dynamic completion delegate helpers (only when any value spec uses\n // an in-process JS resolver).\n if (hasDynamicCompletion(root)) {\n lines.push(`function __${fn}_invoke_complete`);\n lines.push(` set -l _shell $argv[1]`);\n lines.push(` set -l _argv $argv[2..]`);\n lines.push(` set -l _bin ${programName}`);\n lines.push(` if set -q ${binEnvVarName(fn)}`);\n lines.push(` set _bin $${binEnvVarName(fn)}`);\n lines.push(` end`);\n lines.push(` $_bin __complete --shell $_shell -- $_argv 2>/dev/null`);\n lines.push(`end`);\n lines.push(``);\n lines.push(`function __${fn}_apply_dynamic_output`);\n lines.push(` set -l _cur $argv[1]`);\n lines.push(` set -l _directive 0`);\n // Boolean flag (not a counter): the `Default` (directive 0) fallback\n // below only branches on \"any candidate emitted yet?\", so a single\n // 0/1 flip avoids a `math` invocation per resolver candidate.\n lines.push(` set -l _emitted 0`);\n // Buffer one line so we can detect the trailing `:<digits>` directive\n // sentinel without misinterpreting candidate values that legitimately\n // start with `:` in intermediate positions.\n lines.push(` set -l _prev \"\"`);\n lines.push(` set -l _has_prev 0`);\n // Skip only blanks. The `@ext:`/`@matcher:` sentinels are produced by\n // the static shellCommand pipeline, not by dynamic resolvers — filtering\n // them here would silently drop resolver candidates that happen to\n // start with those literal strings.\n lines.push(` while read -l _l`);\n lines.push(` if test $_has_prev -eq 1`);\n lines.push(` if test -n \"$_prev\"`);\n // `printf` rather than `echo` — a resolver candidate that happens to\n // match a fish `echo` flag (`-n`, `-e`, `-s`, `-E`) would otherwise\n // be swallowed as an option instead of being emitted as a candidate.\n lines.push(` printf '%s\\\\n' \"$_prev\"`);\n lines.push(` set _emitted 1`);\n lines.push(` end`);\n lines.push(` end`);\n lines.push(` set _prev $_l`);\n lines.push(` set _has_prev 1`);\n lines.push(` end`);\n lines.push(` if test $_has_prev -eq 1`);\n lines.push(` if string match -qr '^:[0-9]+$' -- $_prev`);\n lines.push(` set _directive (string sub -s 2 -- $_prev)`);\n lines.push(` else`);\n lines.push(` if test -n \"$_prev\"`);\n lines.push(` printf '%s\\\\n' \"$_prev\"`);\n lines.push(` set _emitted 1`);\n lines.push(` end`);\n lines.push(` end`);\n lines.push(` end`);\n // Apply resolver-supplied directive bits. fish lacks compopt; emit\n // path/dir candidates inline (filtered by the partially-typed token)\n // so completion still includes them. fish's `math` does not accept\n // the `&` operator (it errors with \"Logical operations are not\n // supported\"), so use the `bitand()` function form instead.\n lines.push(\n ` if test (math \"bitand($_directive, ${CompletionDirective.DirectoryCompletion})\") -ne 0`,\n );\n lines.push(` __fish_complete_directories \"$_cur\"`);\n lines.push(\n ` else if test (math \"bitand($_directive, ${CompletionDirective.FileCompletion})\") -ne 0`,\n );\n lines.push(` __fish_complete_path \"$_cur\"`);\n // Default directive (0) with no resolver candidates: fall back to\n // filename completion, mirroring the bash/zsh apply helpers. fish's\n // `-f` registration suppresses the automatic file fallback, so the\n // helper has to call `__fish_complete_path` itself.\n lines.push(\n ` else if test $_emitted -eq 0; and test (math \"bitand($_directive, ${CompletionDirective.NoFileCompletion})\") -eq 0`,\n );\n lines.push(` __fish_complete_path \"$_cur\"`);\n lines.push(` end`);\n lines.push(`end`);\n lines.push(``);\n }\n\n // Helper: check if option is already used\n lines.push(`function __${fn}_not_used --no-scope-shadowing`);\n lines.push(` for _chk in $argv`);\n lines.push(` if contains -- \"$_chk\" $_used_opts`);\n lines.push(` return 1`);\n lines.push(` end`);\n lines.push(` end`);\n lines.push(` return 0`);\n lines.push(`end`);\n lines.push(``);\n\n // Helper: check if option takes a value\n lines.push(`function __${fn}_opt_takes_value`);\n lines.push(` switch \"$argv[1]:$argv[2]\"`);\n lines.push(...optTakesValueCases(root, \"\"));\n lines.push(` end`);\n lines.push(` return 1`);\n lines.push(`end`);\n lines.push(``);\n\n if (hasExpand) {\n // Trackers populate `_arg_values_<field>` global scalars during the\n // main scan loop. Each expand spec looks up the value via the same\n // variable to pick a case branch. `sanitize` keeps the variable\n // names valid (alnum + underscore) even for hyphenated schema keys.\n const trackerVar = (t: { fieldName: string; isGlobal: boolean }): string =>\n `${t.isGlobal ? \"_global_arg_values_\" : \"_arg_values_\"}${sanitize(t.fieldName)}`;\n lines.push(`function __${fn}_track_opt --no-scope-shadowing`);\n lines.push(` switch \"$argv[1]:$argv[2]\"`);\n for (const t of trackedFields) {\n if (t.isPositional || !t.optionTokens || t.optionTokens.length === 0) continue;\n const cases = t.pathStrs.flatMap((p) => t.optionTokens!.map((n) => `\"${p}:${n}\"`)).join(\" \");\n lines.push(` case ${cases}`);\n lines.push(` set -g ${trackerVar(t)} \"$argv[3]\"`);\n }\n lines.push(` end`);\n lines.push(`end`);\n lines.push(``);\n lines.push(`function __${fn}_track_pos --no-scope-shadowing`);\n lines.push(` switch \"$argv[1]:$argv[2]\"`);\n for (const t of trackedFields) {\n if (!t.isPositional) continue;\n const cases = t.pathStrs.map((p) => `\"${p}:${t.position}\"`).join(\" \");\n lines.push(` case ${cases}`);\n lines.push(` set -g ${trackerVar(t)} \"$argv[3]\"`);\n }\n lines.push(` end`);\n lines.push(`end`);\n lines.push(``);\n }\n\n if (hasArrayExpand) {\n // Track which `key=` slots a repeatable array option has already\n // consumed. Stored in a per-field global list (one variable per\n // expand-host fieldName) so multiple coexisting array expand options\n // don't share a bucket. Kept separate from `__track_opt` to avoid\n // case-pattern collisions if an option is both a dependsOn target\n // and an array expand host.\n lines.push(`function __${fn}_track_array_expand --no-scope-shadowing`);\n lines.push(` switch \"$argv[1]:$argv[2]\"`);\n for (const spec of arrayExpandSpecs) {\n if (spec.optionTokens.length === 0) continue;\n const cases = spec.pathStrs\n .flatMap((p) => spec.optionTokens.map((tok) => `\"${p}:${tok}\"`))\n .join(\" \");\n const bucket = sanitize(spec.fieldName);\n const bucketVar = spec.isGlobal ? `_global_used_field_keys_` : `_used_field_keys_`;\n lines.push(` case ${cases}`);\n lines.push(` if string match -q '*=*' -- \"$argv[3]\"`);\n lines.push(` set -l _k (string replace -r '=.*' '' -- \"$argv[3]\")`);\n lines.push(` if test -n \"$_k\"`);\n if (spec.isGlobal) {\n // Mirror runtime per-frame replace semantics for global arrays.\n lines.push(` if not set -q _global_arr_seen_${bucket}`);\n lines.push(` set -g ${bucketVar}${bucket} \"$_k\"`);\n lines.push(` set -g _global_arr_seen_${bucket} 1`);\n lines.push(` else if not contains -- \"$_k\" $${bucketVar}${bucket}`);\n lines.push(` set -ga ${bucketVar}${bucket} \"$_k\"`);\n lines.push(` end`);\n } else {\n lines.push(` if not contains -- \"$_k\" $${bucketVar}${bucket}`);\n lines.push(` set -ga ${bucketVar}${bucket} \"$_k\"`);\n lines.push(` end`);\n }\n lines.push(` end`);\n lines.push(` end`);\n }\n lines.push(` end`);\n lines.push(`end`);\n lines.push(``);\n }\n\n // Collect all nested subcommand routes (used for both is_subcmd and dispatch)\n const routeEntries = collectRouteEntries(root);\n\n // Helper: check if a word is a known subcommand at the current path level\n if (routeEntries.length > 0) {\n lines.push(`function __${fn}_is_subcmd`);\n lines.push(` switch \"$argv[1]:$argv[2]\"`);\n for (const r of routeEntries) {\n lines.push(` case \"${r.lookupPattern}\"`);\n lines.push(` return 0`);\n }\n lines.push(` end`);\n lines.push(` return 1`);\n lines.push(`end`);\n lines.push(``);\n }\n\n // Per-subcommand completion functions\n for (const sub of visibleSubs) {\n lines.push(...generateSubHandler(sub, fn, []));\n }\n\n // Root handler\n // NOTE: Inline --opt=value completion is not yet supported in fish; only\n // separate-word value completion (--opt <value>) is handled. Bash supports\n // inline via _inline_prefix parsing.\n lines.push(`function __${fn}_complete_root --no-scope-shadowing`);\n lines.push(...optionValueCases(root.options, root.positionals, fn));\n // Fallback: value-taking option without explicit completion → default file completion\n lines.push(` if __${fn}_opt_takes_value \"\" \"$_prev\"; return; end`);\n if (root.positionals.length > 0) {\n lines.push(` if test $_after_dd -eq 1`);\n lines.push(...positionalBlock(root.positionals, fn, root.options).map((l) => ` ${l}`));\n lines.push(` return`);\n lines.push(` end`);\n } else {\n lines.push(` if test $_after_dd -eq 1; return; end`);\n }\n lines.push(` if string match -q -- '-*' \"$_cur\"`);\n lines.push(...availableOptionLines(root.options, fn));\n if (visibleSubs.length > 0) {\n lines.push(` else`);\n for (const s of getSubNamesWithAliases(root.subcommands)) {\n const desc = escapeDesc(s.description ?? \"\");\n lines.push(` echo \"${s.name}\\t${desc}\"`);\n }\n } else if (root.positionals.length > 0) {\n lines.push(` else`);\n lines.push(...positionalBlock(root.positionals, fn, root.options));\n }\n lines.push(` end`);\n lines.push(`end`);\n lines.push(``);\n\n // Main completion function\n lines.push(`function __fish_${fn}_complete`);\n lines.push(` set -l _args (commandline -opc)`);\n lines.push(` set -e _args[1]`);\n lines.push(``);\n lines.push(` set -l _ct (commandline -ct)`);\n lines.push(` if test (count $_ct) -eq 0`);\n lines.push(` set -a _args \"\"`);\n lines.push(` else`);\n lines.push(` set -a _args $_ct`);\n lines.push(` end`);\n lines.push(``);\n lines.push(` set -l _cur \"\"`);\n lines.push(` if test (count $_args) -gt 0`);\n lines.push(` set _cur \"$_args[-1]\"`);\n lines.push(` end`);\n lines.push(``);\n lines.push(` set -l _prev \"\"`);\n lines.push(` if test (count $_args) -gt 1`);\n lines.push(` set _prev \"$_args[-2]\"`);\n lines.push(` end`);\n lines.push(``);\n lines.push(\n ` set -l _subcmd \"\" ; set -l _after_dd 0 ; set -l _pos_count 0 ; set -l _skip_next 0`,\n );\n lines.push(` set -l _used_opts`);\n lines.push(``);\n if (hasExpand) {\n // Clear any sibling values left over from previous completions so a\n // partial command doesn't pick up stale values from the global scope.\n // Both local and global buckets are cleared because the previous\n // completion run may have populated either side.\n for (const t of trackedFields) {\n lines.push(` set -e _arg_values_${sanitize(t.fieldName)}`);\n lines.push(` set -e _global_arg_values_${sanitize(t.fieldName)}`);\n }\n }\n if (hasArrayExpand) {\n for (const spec of arrayExpandSpecs) {\n lines.push(` set -e _used_field_keys_${sanitize(spec.fieldName)}`);\n lines.push(` set -e _global_used_field_keys_${sanitize(spec.fieldName)}`);\n // Per-frame seen flag for global array hosts.\n lines.push(` set -e _global_arr_seen_${sanitize(spec.fieldName)}`);\n }\n }\n lines.push(` set -l _j 1`);\n lines.push(` set -l _limit (math (count $_args) - 1)`);\n lines.push(` while test $_j -le $_limit`);\n lines.push(` set -l _w \"$_args[$_j]\"`);\n lines.push(\n ` if test $_skip_next -eq 1; set _skip_next 0; set _j (math $_j + 1); continue; end`,\n );\n lines.push(` if test \"$_w\" = \"--\"; set _after_dd 1; set _j (math $_j + 1); continue; end`);\n // After `--`, all remaining words are positionals. Track them so an\n // expand spec that depends on a positional still sees the value.\n const afterDdTrack = hasExpand ? `__${fn}_track_pos \"$_subcmd\" \"$_pos_count\" \"$_w\"; ` : \"\";\n lines.push(\n ` if test $_after_dd -eq 1; ${afterDdTrack}set _pos_count (math $_pos_count + 1); set _j (math $_j + 1); continue; end`,\n );\n // Match both `--opt=value` and `-o=value`: the parser accepts the\n // short inline form too, so the scanner must split it before tracking\n // the dep value, otherwise `-e=prod` slips past the tracker.\n lines.push(` if string match -q -- '-*=*' \"$_w\"`);\n lines.push(` set -l _opt (string replace -r '=.*' '' -- \"$_w\")`);\n lines.push(` set -a _used_opts \"$_opt\"`);\n if (hasExpand) {\n lines.push(` set -l _val (string replace -r '^[^=]*=' '' -- \"$_w\")`);\n lines.push(` __${fn}_track_opt \"$_subcmd\" \"$_opt\" \"$_val\"`);\n if (hasArrayExpand) {\n lines.push(` __${fn}_track_array_expand \"$_subcmd\" \"$_opt\" \"$_val\"`);\n }\n }\n lines.push(` set _j (math $_j + 1); continue`);\n lines.push(` end`);\n lines.push(` if string match -q -- '-*' \"$_w\"`);\n lines.push(` set -a _used_opts \"$_w\"`);\n lines.push(` if __${fn}_opt_takes_value \"$_subcmd\" \"$_w\"`);\n lines.push(` set -l _next \"\"`);\n lines.push(` set -l _next_idx (math $_j + 1)`);\n lines.push(` if test $_next_idx -le (count $_args)`);\n lines.push(` set _next \"$_args[$_next_idx]\"`);\n lines.push(` end`);\n // Mirror the runtime parser: a token starting with `-` is the next\n // option, not this option's value. Skip/track only when the next\n // token looks like a value.\n lines.push(` if test -n \"$_next\"; and not string match -q -- '-*' \"$_next\"`);\n lines.push(` set _skip_next 1`);\n if (hasExpand) {\n lines.push(` __${fn}_track_opt \"$_subcmd\" \"$_w\" \"$_next\"`);\n if (hasArrayExpand) {\n lines.push(` if test $_j -lt $_limit`);\n lines.push(` __${fn}_track_array_expand \"$_subcmd\" \"$_w\" \"$_next\"`);\n lines.push(` end`);\n }\n }\n lines.push(` end`);\n lines.push(` end`);\n lines.push(` set _j (math $_j + 1); continue`);\n lines.push(` end`);\n if (routeEntries.length > 0) {\n lines.push(` if __${fn}_is_subcmd \"$_subcmd\" \"$_w\"`);\n lines.push(\n ` test -n \"$_subcmd\"; and set _subcmd \"$_subcmd:$_w\"; or set _subcmd \"$_w\"`,\n );\n lines.push(` set _used_opts; set _pos_count 0`);\n if (hasExpand) {\n // Clear sibling-tracker state when descending into a subcommand:\n // `dependsOn` is scoped to siblings on the same command frame, so\n // letting a parent's `--env` bleed into a child with its own `--env`\n // would feed the wrong value into the child's expand lookup.\n for (const t of trackedFields) {\n lines.push(` set -e _arg_values_${sanitize(t.fieldName)}`);\n }\n if (hasArrayExpand) {\n for (const spec of arrayExpandSpecs) {\n lines.push(` set -e _used_field_keys_${sanitize(spec.fieldName)}`);\n // Per-frame seen flag also clears so global hosts pick up the\n // \"first write replaces inherited array\" semantics in the new\n // frame.\n lines.push(` set -e _global_arr_seen_${sanitize(spec.fieldName)}`);\n }\n }\n }\n lines.push(` else`);\n if (hasExpand) {\n lines.push(` __${fn}_track_pos \"$_subcmd\" \"$_pos_count\" \"$_w\"`);\n }\n lines.push(` set _pos_count (math $_pos_count + 1)`);\n lines.push(` end`);\n } else {\n if (hasExpand) {\n lines.push(` __${fn}_track_pos \"$_subcmd\" \"$_pos_count\" \"$_w\"`);\n }\n lines.push(` set _pos_count (math $_pos_count + 1)`);\n }\n lines.push(` set _j (math $_j + 1)`);\n lines.push(` end`);\n lines.push(``);\n\n // Route to subcommand handler (all nested paths)\n lines.push(` switch \"$_subcmd\"`);\n for (const r of routeEntries) {\n lines.push(` case \"${r.pathStr}\"; __${fn}_complete_${r.funcSuffix}`);\n }\n lines.push(` case '*'; __${fn}_complete_root`);\n lines.push(` end`);\n lines.push(`end`);\n lines.push(``);\n\n // Register completion\n lines.push(`# Clear existing completions`);\n lines.push(`complete -e -c ${programName}`);\n lines.push(``);\n lines.push(`# Register completion`);\n lines.push(`complete -c ${programName} -f -a '(__fish_${fn}_complete)'`);\n lines.push(``);\n\n return {\n script: lines.join(\"\\n\"),\n shell: \"fish\",\n installInstructions: `# To enable auto-refreshing fish completions, run:\n${programName} completion fish --install`,\n };\n}\n","/**\n * Rc-loader generators (bash / zsh).\n *\n * These produce the small snippet a user adds once to `~/.bashrc` or\n * `~/.zshrc`. The snippet:\n *\n * 1. Looks up the binary on $PATH.\n * 2. Reads its mtime.\n * 3. If the on-disk completion cache is missing or its\n * `# politty-bin-sig:` header differs, regenerates the cache by\n * spawning the binary once.\n * 4. Sources the cache.\n *\n * All failure modes are silent no-ops so a broken / missing CLI never\n * blocks shell startup.\n */\n\nimport { sanitize } from \"./extractor.js\";\nimport type { ShellType } from \"./types.js\";\n\nexport interface LoaderOptions {\n programName: string;\n shell: ShellType;\n /**\n * Optional hardcoded cache directory. When omitted, the loader\n * derives `${XDG_CACHE_HOME:-$HOME/.cache}/<programName>` at runtime,\n * which is what most users want.\n */\n cacheDir?: string;\n}\n\n/**\n * Single-quote escape: `'` -> `'\\''`. Inside single quotes the shell\n * performs no expansion at all, so `$`, backticks, and `$(...)` are\n * inert. Used for hardcoded paths because callers may sources them\n * from env / config — we must not let metachars in the path execute as\n * commands when the rc snippet is sourced.\n */\nfunction shSingleQuote(s: string): string {\n return `'${s.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nfunction bashCachePathExpr(\n programName: string,\n cacheDir: string | undefined,\n shell: \"bash\" | \"zsh\",\n): string {\n if (cacheDir) {\n return shSingleQuote(`${cacheDir}/completion.${shell}`);\n }\n return `\"\\${XDG_CACHE_HOME:-$HOME/.cache}/${programName}/completion.${shell}\"`;\n}\n\nfunction generateBashLoader(opts: LoaderOptions): string {\n const fn = sanitize(opts.programName);\n const cache = bashCachePathExpr(opts.programName, opts.cacheDir, \"bash\");\n // `type -P` is path-only — it skips aliases, functions, and builtins.\n // `command -v` would surface the alias text or function name when the\n // user has shadowed the CLI in their rc, and the subsequent `stat`\n // would fail, leaving completions unsourced for that shell.\n //\n // `-L` follows symlinks so the shell-side mtime matches Node's\n // `fs.statSync`, which also follows symlinks. Without `-L`, BSD `stat`\n // (macOS) reports the symlink's own mtime, so package-manager bin\n // shims (npm/pnpm/etc.) would never match the embedded sig and the\n // cache would regenerate on every shell startup.\n //\n // Try GNU (`-c '%Y'`) before BSD (`-f '%m'`): GNU treats `-f` as\n // file-system mode, so `stat -L -f '%m' file` would emit filesystem\n // info on stdout *and* exit non-zero, causing the `||` fallback to\n // append a second line and break the header comparison.\n return `__${fn}_load_completion() {\n local _bin _cache _sig _hdr\n _bin=$(type -P ${opts.programName} 2>/dev/null)\n [[ -n \"$_bin\" ]] || return 0\n _cache=${cache}\n _sig=$(stat -L -c '%Y' \"$_bin\" 2>/dev/null || stat -L -f '%m' \"$_bin\" 2>/dev/null) || return 0\n _hdr=\"# politty-bin-sig: $_sig\"\n if [[ ! -f \"$_cache\" ]] || ! head -5 \"$_cache\" 2>/dev/null | grep -qF \"$_hdr\"; then\n # Use the hidden __refresh-completion subcommand instead of\n # \\`$_bin completion bash\\`: the foreground completion command\n # is subject to user setup/cleanup/prompt and required\n # globalArgs validation, which can silently fail or block when\n # invoked from rc; runMain bypasses those for __-prefixed\n # internal subcommands.\n \"$_bin\" __refresh-completion bash 2>/dev/null\n fi\n # If regen failed but a stale cache survived from a previous run,\n # source it anyway — a stale completion is preferable to no\n # completion at all.\n [[ -f \"$_cache\" ]] || return 0\n # shellcheck disable=SC1090\n source \"$_cache\"\n}\n__${fn}_load_completion\nunset -f __${fn}_load_completion\n`;\n}\n\nfunction generateZshLoader(opts: LoaderOptions): string {\n const fn = sanitize(opts.programName);\n const cache = bashCachePathExpr(opts.programName, opts.cacheDir, \"zsh\");\n // `whence -p` is the zsh equivalent of bash's `type -P` — path-only,\n // ignoring aliases / functions / builtins. See bash loader for the\n // rationale and for `-L` / stat probe-order.\n return `__${fn}_load_completion() {\n emulate -L zsh\n setopt local_options no_aliases\n local _bin _cache _sig _hdr\n _bin=$(whence -p ${opts.programName} 2>/dev/null)\n [[ -n \"$_bin\" ]] || return 0\n _cache=${cache}\n _sig=$(stat -L -c '%Y' \"$_bin\" 2>/dev/null || stat -L -f '%m' \"$_bin\" 2>/dev/null) || return 0\n _hdr=\"# politty-bin-sig: $_sig\"\n if [[ ! -f \"$_cache\" ]] || ! head -5 \"$_cache\" 2>/dev/null | grep -qF \"$_hdr\"; then\n # See bash loader for why we use __refresh-completion instead\n # of \\`$_bin completion zsh\\`.\n \"$_bin\" __refresh-completion zsh 2>/dev/null\n fi\n # See bash loader: keep stale completion over no completion.\n [[ -f \"$_cache\" ]] || return 0\n source \"$_cache\"\n}\n__${fn}_load_completion\nunfunction __${fn}_load_completion\n`;\n}\n\n/**\n * Build the rc-loader snippet for bash or zsh. Fish doesn't have an\n * rc-loader; instead, `<program> completion fish --install` writes a\n * self-rewriting autoload file.\n */\nexport function generateLoader(opts: LoaderOptions): string {\n switch (opts.shell) {\n case \"bash\":\n return generateBashLoader(opts);\n case \"zsh\":\n return generateZshLoader(opts);\n case \"fish\":\n throw new Error(\n \"fish does not use an rc loader. Run `<program> completion fish --install` to write the self-refreshing autoload file instead.\",\n );\n }\n}\n\n/**\n * Default cache file path (used by `completion <bash|zsh> --install`\n * and the `__refresh-completion` subcommand). For fish, the install\n * path is `$__fish_config_dir/completions/<program>.fish` and is\n * computed inside `installPath()` instead.\n */\nexport function defaultCacheDir(programName: string): string {\n const xdg = process.env.XDG_CACHE_HOME ?? `${process.env.HOME ?? \"\"}/.cache`;\n return `${xdg}/${programName}`;\n}\n","/**\n * On-disk install + refresh helpers.\n *\n * `install` writes the generated script to its canonical cache /\n * autoload path. `refresh` is the body of the `__refresh-completion`\n * hidden subcommand and the runMain background hook — it regenerates\n * the cache only when the binary's mtime no longer matches the\n * embedded `# politty-bin-sig:` header.\n *\n * All file I/O is best-effort: failures fall through silently. A stale\n * (or missing) cache is preferable to crashing the user's shell.\n */\n\nimport { spawn } from \"node:child_process\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n realpathSync,\n renameSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type { AnyCommand, ArgsSchema } from \"../types.js\";\nimport { resolveBinPath } from \"./header.js\";\nimport { generateCompletion } from \"./index.js\";\nimport { defaultCacheDir } from \"./loader.js\";\nimport type { ShellType } from \"./types.js\";\n\nexport interface InstallContext {\n rootCommand: AnyCommand;\n programName: string;\n programVersion?: string | undefined;\n cacheDir?: string | undefined;\n binPath?: string | undefined;\n globalArgsSchema?: ArgsSchema | undefined;\n targetPath?: string | undefined;\n}\n\n/**\n * Resolve where a script for the given shell should live on disk.\n *\n * - bash/zsh: `<cacheDir>/completion.<shell>` — sourced by the rc loader.\n * - fish: `$__fish_config_dir/completions/<program>.fish` — autoloaded\n * by fish on TAB. We approximate `$__fish_config_dir` from\n * `$XDG_CONFIG_HOME` / `$HOME`.\n */\nexport function installPath(programName: string, shell: ShellType, cacheDir?: string): string {\n if (shell === \"fish\") {\n const cfg = process.env.XDG_CONFIG_HOME ?? `${process.env.HOME ?? \"\"}/.config`;\n return join(cfg, \"fish\", \"completions\", `${programName}.fish`);\n }\n const dir = cacheDir ?? defaultCacheDir(programName);\n return join(dir, `completion.${shell}`);\n}\n\n/** Atomic write: tmp file in the same dir, then rename. */\nfunction writeAtomic(path: string, content: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp.${process.pid}`;\n writeFileSync(tmp, content);\n renameSync(tmp, path);\n}\n\nfunction generateScript(ctx: InstallContext, shell: ShellType): string {\n return generateCompletion(ctx.rootCommand, {\n shell,\n programName: ctx.programName,\n includeDescriptions: true,\n ...(ctx.programVersion !== undefined && { programVersion: ctx.programVersion }),\n ...(ctx.binPath !== undefined && { binPath: ctx.binPath }),\n ...(ctx.cacheDir !== undefined && { cacheDir: ctx.cacheDir }),\n ...(ctx.globalArgsSchema !== undefined && { globalArgsSchema: ctx.globalArgsSchema }),\n }).script;\n}\n\n/** Write the script for `shell` to its install path. Returns the path. */\nexport function install(ctx: InstallContext, shell: ShellType): string {\n const target = installPath(ctx.programName, shell, ctx.cacheDir);\n writeAtomic(target, generateScript(ctx, shell));\n return target;\n}\n\n/**\n * Read the first ~5 lines of an existing cache file and return its\n * embedded bin-sig. Returns `null` when the file is missing, unreadable,\n * or doesn't have a sig header.\n */\nfunction readCachedSig(path: string): string | null {\n try {\n if (!existsSync(path)) return null;\n const head = readFileSync(path, \"utf8\").split(\"\\n\", 6).join(\"\\n\");\n const m = head.match(/^# politty-bin-sig: (\\S+)/m);\n return m ? m[1]! : null;\n } catch {\n return null;\n }\n}\n\nfunction isManagedTarget(path: string, programName: string, shell: ShellType): boolean {\n try {\n if (!existsSync(path)) return false;\n const head = readFileSync(path, \"utf8\").split(\"\\n\", 8).join(\"\\n\");\n return (\n /^# politty-completion-version: \\S+/m.test(head) &&\n head.includes(`# program: ${programName}`) &&\n head.includes(`# shell: ${shell}`)\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Rewrite the cache only when stale. Used by:\n * - `<program> __refresh-completion <shell>` (the hidden subcommand\n * spawned both by the rc loader and by the runMain background hook)\n *\n * Caller is responsible for gating: the runMain hook (`maybeSpawnRefresh`)\n * checks `hasManagedCache` before spawning so we don't silently create\n * a fish autoload the user never opted into. The rc loader / fish\n * autoload only run after the user has installed completion in the\n * first place, so they're allowed to refresh unconditionally.\n *\n * Must never throw — a stale completion is fine, a crash isn't.\n */\nexport function refreshIfStale(ctx: InstallContext, shell: ShellType): void {\n try {\n const target = ctx.targetPath\n ? realpathSync(ctx.targetPath)\n : installPath(ctx.programName, shell, ctx.cacheDir);\n if (ctx.targetPath && !isManagedTarget(target, ctx.programName, shell)) return;\n const binPath = resolveBinPath(ctx.programName, ctx.binPath);\n if (!binPath) return;\n let currentSig: string;\n try {\n currentSig = Math.floor(statSync(binPath).mtimeMs / 1000).toString();\n } catch {\n return;\n }\n if (readCachedSig(target) === currentSig) return;\n writeAtomic(target, generateScript(ctx, shell));\n } catch {\n // Best-effort.\n }\n}\n\n/**\n * Returns true when a politty-managed cache file already exists on disk\n * for the given shell — i.e. the user has installed completion via\n * `<program> completion <shell> --install` or the rc loader has already\n * sourced one. Used by the runMain background hook to avoid spawning\n * the refresher (and thereby silently creating files) on plain CLI runs\n * the user never opted into.\n */\nexport function hasManagedCache(\n ctx: { programName: string; cacheDir?: string | undefined },\n shell: ShellType,\n): boolean {\n const target = installPath(ctx.programName, shell, ctx.cacheDir);\n return readCachedSig(target) !== null;\n}\n\n/**\n * Spawn a detached child process that runs `<program> __refresh-completion <shell>`.\n * The child is fully decoupled (`stdio: \"ignore\"` + `unref()`), so it\n * outlives the parent without holding any handles.\n *\n * Caller is expected to gate this on the right conditions (interactive\n * shell, not running inside `__complete` itself, etc.).\n *\n * Returns `void` and never throws — even spawn failures are absorbed.\n */\nexport function spawnBackgroundRefresh(programArgv0: string, shell: ShellType): void {\n try {\n const child = spawn(process.execPath, [programArgv0, \"__refresh-completion\", shell], {\n detached: true,\n stdio: \"ignore\",\n // Inherit the env so XDG_CACHE_HOME / HOME / etc. flow through.\n });\n child.unref();\n } catch {\n // Best-effort.\n }\n}\n","/**\n * Zsh completion script generator (static)\n *\n * Generates a self-contained zsh completion script that embeds all\n * completion metadata. No Node.js process is spawned on TAB.\n */\n\nimport type { AnyCommand } from \"../types.js\";\nimport { CompletionDirective } from \"./dynamic/candidate-generator.js\";\nimport {\n collectExpandSpecs,\n collectRouteEntries,\n collectTrackedFields,\n dynamicInvokeCompleteLines,\n effectiveOptionTokens,\n expandTableVarName,\n extractCompletionData,\n getSubNamesWithAliases,\n getVisibleSubs,\n hasDynamicCompletion,\n isSubcmdCaseLines,\n optTakesValueEntries,\n sanitize,\n subDispatchCaseLines,\n trackArrayExpandCaseLines,\n trackOptCaseLines,\n trackPosCaseLines,\n} from \"./extractor.js\";\nimport { buildHeaderLines } from \"./header.js\";\nimport { generateZshSelfRefresh } from \"./self-refresh.js\";\nimport {\n ansiC,\n optionExpandLocation,\n positionalExpandLocation,\n quotedAvailabilityTokens,\n type FuncSuffixedExpandLocation,\n} from \"./shell-shared.js\";\nimport type {\n CompletableOption,\n CompletablePositional,\n CompletableSubcommand,\n CompletionOptions,\n CompletionResult,\n ValueCompletion,\n} from \"./types.js\";\n\nfunction escapeDesc(s: string): string {\n return s\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\$/g, \"\\\\$\")\n .replace(/`/g, \"\\\\`\")\n .replace(/:/g, \"\\\\:\");\n}\n\n/**\n * Escape a candidate value for use inside a `_describe` spec. `_describe`\n * splits each spec on the first unescaped `:` to separate value from\n * description, so any literal `:` in the value (URLs, namespaced ids) must\n * be backslash-escaped — and the escape itself must double up so the final\n * string interprets `\\:` as a single literal.\n */\nfunction escapeDescribeValue(s: string): string {\n return s.replace(/\\\\/g, \"\\\\\\\\\").replace(/:/g, \"\\\\:\");\n}\n\n/** Escape a string for use inside zsh double-quotes. */\nfunction escapeZshDQ(s: string): string {\n return s.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"').replace(/\\$/g, \"\\\\$\").replace(/`/g, \"\\\\`\");\n}\n\n/**\n * Generate zsh value completion lines for a ValueCompletion spec.\n * Uses `_vals` array (must be declared in the calling function scope).\n * `location` is required when `vc.type === \"expand\"`.\n */\nfunction zshValueLines(\n vc: ValueCompletion | undefined,\n fn: string,\n location?: FuncSuffixedExpandLocation,\n): string[] {\n if (!vc) return [];\n switch (vc.type) {\n case \"expand\": {\n if (!location) {\n throw new Error(\"zshValueLines: expand variant requires a location\");\n }\n const varName = expandTableVarName(fn, location.funcSuffix, location.fieldName);\n // Per-dep lookups read from the matching bucket: globals from\n // `_global_arg_values` (preserved across subcommand descent) and\n // locals from `_arg_values` (cleared on descent).\n const depKey = location.resolvedDeps\n .map((d) =>\n d.isGlobal ? `\"\\${_global_arg_values[${d.name}]:-}\"` : `\"\\${_arg_values[${d.name}]:-}\"`,\n )\n .join(`$'\\\\x1f'`);\n // _vals is split on newlines so each candidate can carry a `:desc`\n // suffix understood by `_describe`. Empty entries (from\n // unrecognised keys) are silently dropped by zsh's _describe.\n // Two-stage `key=value`: when the user has not typed `=` yet,\n // collapse every `key=value` candidate to a unique `key=` so the\n // first TAB picks the key. The second TAB (after `key=`) keeps the\n // full `key=value` candidates so the user picks the value. Array-host\n // dedup against already-typed keys runs before the collapse so a\n // used key stays hidden at both stages.\n const bucket = sanitize(location.fieldName);\n const bucketRef = location.isGlobal\n ? `\\${_global_used_field_keys[${bucket}]:-}`\n : `\\${_used_field_keys[${bucket}]:-}`;\n const arrayDedupLines = location.isArrayOption\n ? [` if [[ -n \"$_ck\" && \" ${bucketRef} \" == *\" $_ck \"* ]]; then continue; fi`]\n : [];\n return [\n `local _key=${depKey}`,\n `local _raw=\"\\${${varName}[$_key]:-}\"`,\n `if [[ -n \"$_raw\" ]]; then`,\n ` local -a _candidates=(\"\\${(@f)_raw}\")`,\n ` _vals=()`,\n ` local _c _ck _cke _vp _seen_keys=\" \" _desc _has_eq=0 _tmp`,\n ` for _c in \"\\${_candidates[@]}\"; do`,\n // Replace escaped `\\:` with a sentinel byte (0x01, never present\n // in real candidate text) so the value/description split at the\n // first UNESCAPED `:` survives values that contain literal `:`\n // (e.g. `ns:key=value`).\n ` _tmp=\"\\${_c//\\\\\\\\:/$'\\\\x01'}\"`,\n // Inspect only the VALUE portion when deciding key=value. A\n // candidate like `{value: \"region\", description: \"format a=b\"}`\n // surfaces as `region:format a=b`, and a naive `$_c == *=*`\n // would route it through the key=value branch on the\n // description alone.\n ` _vp=\"\\${_tmp%%:*}\"`,\n ` if [[ \"$_vp\" == *=* ]]; then`,\n // Two forms of the key: the ESCAPED `_cke` keeps `\\:` intact for\n // rebuilding `_c` so `_describe`'s value:description split sees\n // the right boundary; the UNESCAPED `_ck` (`\\:` → `:`) is what\n // the tracker recorded into `_used_field_keys` and what the\n // dedup checks need to match.\n ` _cke=\"\\${_c%%=*}\"`,\n ` _ck=\"\\${_cke//\\\\\\\\:/:}\"`,\n ...arrayDedupLines,\n ` if [[ \"\\${words[CURRENT]}\" != *=* ]]; then`,\n ` [[ \"$_seen_keys\" == *\" $_ck \"* ]] && continue`,\n ` _seen_keys+=\"$_ck \"`,\n ` if [[ \"$_tmp\" == *:* ]]; then`,\n // Extract desc from after the first UNESCAPED `:` (via `_tmp`),\n // then restore the sentinel to `\\:` so a literal colon inside\n // the description survives intact.\n ` _desc=\"\\${\\${_tmp#*:}//$'\\\\x01'/\\\\\\\\:}\"`,\n ` _c=\"\\${_cke}=:$_desc\"`,\n ` else`,\n ` _c=\"\\${_cke}=\"`,\n ` fi`,\n // Key-stage candidates always end with `=`, so `_describe` needs\n // `-S ''` to skip the trailing space and let the user type the\n // value after TAB. Mark the flag here instead of inferring it\n // from \\`_tmp\\` — `enumerate` may return only `key=value`\n // candidates, which fold to `key=` only in `_c`.\n ` _has_eq=1`,\n ` else`,\n // Value stage: drop bare `key=` candidates so they do not clutter\n // the value picker. `_vp` is the value-portion of `_tmp` (already\n // computed above) — split at the first UNESCAPED `:`.\n ` [[ \"$_vp\" == *=?* ]] || continue`,\n ` fi`,\n ` fi`,\n ` _vals+=(\"$_c\")`,\n ` done`,\n ` if (( _has_eq )); then`,\n ` __${fn}_cdescribe 'completions' _vals -S ''`,\n ` else`,\n ` __${fn}_cdescribe 'completions' _vals`,\n ` fi`,\n `fi`,\n ];\n }\n case \"dynamic\": {\n // Delegate to `<program> __complete --shell zsh` and let the apply\n // helper interpret the trailing `:<directive>` line so resolver-supplied\n // file/directory completion still reaches the shell. Slice `words` to\n // `CURRENT` (1-based, inclusive) so the resolver does not observe\n // tokens typed past the cursor — `parseCompletionContext` treats the\n // last argv element as the word being completed.\n return [\n `__${fn}_apply_dynamic_output \"$(__${fn}_invoke_complete zsh \"\\${(@)words[2,CURRENT]}\")\"`,\n ];\n }\n case \"choices\": {\n const items = vc.choices!.map((c) => `\"${escapeDesc(c)}\"`).join(\" \");\n return [`_vals=(${items})`, `__${fn}_cdescribe 'completions' _vals`];\n }\n case \"file\": {\n if (vc.matcher?.length) {\n return vc.matcher.map((p) => `_files -g \"${p}\"`);\n }\n if (vc.extensions?.length) {\n return vc.extensions.map((ext) => `_files -g \"*.${ext}\"`);\n }\n return [`_files`];\n }\n case \"directory\":\n return [`_files -/`];\n case \"command\":\n return [`_vals=(\"\\${(@f)$(${vc.shellCommand!})}\")`, `__${fn}_cdescribe 'completions' _vals`];\n case \"none\":\n return [];\n }\n}\n\n/** Generate option-value case branches */\nfunction optionValueCases(\n options: CompletableOption[],\n positionals: readonly CompletablePositional[],\n fn: string,\n funcSuffix: string,\n): string[] {\n const lines: string[] = [];\n for (const opt of options) {\n if (!opt.takesValue || !opt.valueCompletion) continue;\n const valLines = zshValueLines(opt.valueCompletion, fn, {\n funcSuffix,\n ...optionExpandLocation(opt, options, positionals),\n });\n if (valLines.length === 0) continue;\n\n const patterns = effectiveOptionTokens(opt, options);\n // An option whose every emitted spelling is shadowed by siblings at\n // this frame has nothing to pattern-match on. Emitting an empty\n // `)` branch would break the surrounding case.\n if (patterns.length === 0) continue;\n\n lines.push(` ${patterns.join(\"|\")})`);\n for (const vl of valLines) {\n lines.push(` ${vl}`);\n }\n lines.push(` return 0 ;;`);\n }\n return lines;\n}\n\n/** Generate positional completion block */\nfunction positionalBlock(\n positionals: CompletablePositional[],\n fn: string,\n funcSuffix: string,\n options: readonly CompletableOption[] = [],\n): string[] {\n if (positionals.length === 0) return [];\n const lines: string[] = [];\n lines.push(` case \"$_pos_count\" in`);\n for (const pos of positionals) {\n if (pos.variadic) {\n lines.push(` ${pos.position}|*)`);\n } else {\n lines.push(` ${pos.position})`);\n }\n const valLines = zshValueLines(pos.valueCompletion, fn, {\n funcSuffix,\n ...positionalExpandLocation(pos, options, positionals),\n });\n for (const vl of valLines) {\n lines.push(` ${vl}`);\n }\n lines.push(` ;;`);\n }\n lines.push(` esac`);\n return lines;\n}\n\n/** Generate prev-word value completion case block */\nfunction valueCompletionBlock(\n options: CompletableOption[],\n positionals: readonly CompletablePositional[],\n fn: string,\n funcSuffix: string,\n): string[] {\n if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];\n\n const prevCases = optionValueCases(options, positionals, fn, funcSuffix);\n if (prevCases.length === 0) return [];\n\n return [` case \"\\${words[CURRENT-1]}\" in`, ...prevCases, ` esac`];\n}\n\n/** Generate available-options list lines */\nfunction availableOptionLines(options: CompletableOption[], fn: string): string[] {\n const lines: string[] = [];\n for (const opt of options) {\n const desc = opt.description ? `:${escapeDesc(opt.description)}` : \"\";\n if (opt.valueType === \"array\") {\n lines.push(` _opts+=(\"--${opt.cliName}${desc}\")`);\n continue;\n }\n const patterns = quotedAvailabilityTokens(opt.cliName, opt.alias, opt.negation, {\n isGlobal: opt.isGlobal === true,\n frameOptions: options,\n });\n const guard = `__${fn}_not_used ${patterns.join(\" \")}`;\n const negDesc = opt.negationDescription ? `:${escapeDesc(opt.negationDescription)}` : desc;\n const entries: Array<{ name: string; desc: string }> = [{ name: opt.cliName, desc }];\n if (opt.negation) entries.push({ name: opt.negation, desc: negDesc });\n for (const e of entries) {\n // Skip the suggestion when `--name`'s long form was filtered out\n // of the routing-aware token set — emitting it would point the\n // user at an option the runtime routes elsewhere.\n if (!patterns.includes(`\"--${e.name}\"`)) continue;\n lines.push(` ${guard} && _opts+=(\"--${e.name}${e.desc}\")`);\n }\n }\n lines.push(` __${fn}_not_used \"--help\" && _opts+=(\"--help:Show help\")`);\n return lines;\n}\n\n/**\n * Generate a per-subcommand completion function.\n * Recursively generates functions for nested subcommands.\n */\nfunction generateSubHandler(sub: CompletableSubcommand, fn: string, path: string[]): string[] {\n const fullPath = [...path, sub.name];\n const funcSuffix = fullPath.map(sanitize).join(\"_\");\n const funcName = `__${fn}_complete_${funcSuffix}`;\n const visibleSubs = getVisibleSubs(sub.subcommands);\n\n const lines: string[] = [];\n\n // Recursively generate handlers for child subcommands\n for (const child of visibleSubs) {\n lines.push(...generateSubHandler(child, fn, fullPath));\n }\n\n lines.push(`${funcName}() {`);\n lines.push(` local -a _vals=()`);\n\n // 1. Option value completion (prev word is value-taking option)\n lines.push(...valueCompletionBlock(sub.options, sub.positionals, fn, funcSuffix));\n // Fallback: value-taking option without explicit completion → default file completion\n const fullPathStr = fullPath.join(\":\");\n lines.push(\n ` if __${fn}_opt_takes_value \"${fullPathStr}\" \"\\${words[CURRENT-1]}\"; then return 0; fi`,\n );\n\n // 2. After -- separator\n if (sub.positionals.length > 0) {\n lines.push(` if (( _after_dd )); then`);\n lines.push(\n ...positionalBlock(sub.positionals, fn, funcSuffix, sub.options).map((l) => ` ${l}`),\n );\n lines.push(` return 0`);\n lines.push(` fi`);\n } else {\n lines.push(` if (( _after_dd )); then return 0; fi`);\n }\n\n // 3. Option name completion\n lines.push(` if [[ \"\\${words[CURRENT]}\" == -* ]]; then`);\n lines.push(` local -a _opts=()`);\n lines.push(...availableOptionLines(sub.options, fn));\n lines.push(` __${fn}_cdescribe 'options' _opts`);\n lines.push(` return 0`);\n lines.push(` fi`);\n\n // 4. Subcommand or positional completion (includes aliases)\n if (visibleSubs.length > 0) {\n const subItems = getSubNamesWithAliases(sub.subcommands)\n .map((s) => {\n const desc = s.description ? `:${escapeDesc(s.description)}` : \"\";\n return `\"${s.name}${desc}\"`;\n })\n .join(\" \");\n lines.push(` local -a _subs=(${subItems})`);\n lines.push(` __${fn}_cdescribe 'subcommands' _subs`);\n } else if (sub.positionals.length > 0) {\n lines.push(...positionalBlock(sub.positionals, fn, funcSuffix, sub.options));\n }\n\n lines.push(`}`);\n lines.push(``);\n return lines;\n}\n\nexport function generateZshCompletion(\n command: AnyCommand,\n options: CompletionOptions,\n): CompletionResult {\n const { programName } = options;\n const data = extractCompletionData(command, programName, options.globalArgsSchema);\n const fn = sanitize(programName);\n const completionFn = `_${programName}`;\n const autoloadCheck = `\"\\${funcstack[1]:-}\" == \"${escapeZshDQ(completionFn)}\"`;\n const root = data.command;\n const visibleSubs = getVisibleSubs(root.subcommands);\n const expandSpecs = collectExpandSpecs(root);\n const trackedFields = collectTrackedFields(root, expandSpecs, data.globalOptions);\n const hasExpand = expandSpecs.length > 0;\n const arrayExpandSpecs = expandSpecs.filter((s) => s.isArrayOption);\n const hasArrayExpand = arrayExpandSpecs.length > 0;\n\n const lines: string[] = [];\n lines.push(`#compdef ${programName}`);\n lines.push(``);\n lines.push(\n ...buildHeaderLines({\n programName,\n shell: \"zsh\",\n binPath: options.binPath,\n programVersion: options.programVersion,\n }),\n );\n lines.push(`# Generated by politty`);\n lines.push(``);\n lines.push(...generateZshSelfRefresh({ programName, binPath: options.binPath }));\n\n // Expand-completion hoisted tables. One global associative array per\n // expand spec, populated via the array-literal form (which is the only\n // place where zsh evaluates `$'…'` for keys — subscripts treat the\n // quoted form as the literal string). Keys are `dependsOn` values\n // joined by U+001F; values are newline-separated `value:description`\n // entries consumed by `_describe`.\n for (const spec of expandSpecs) {\n const varName = expandTableVarName(fn, spec.funcSuffix, spec.fieldName);\n if (spec.vc.table.length === 0) {\n lines.push(`typeset -gA ${varName}=()`);\n } else {\n lines.push(`typeset -gA ${varName}=(`);\n for (const entry of spec.vc.table) {\n const key = entry.key.join(\"\\x1f\");\n const value = entry.candidates\n .map((c) => {\n const escapedValue = escapeDescribeValue(c.value);\n // The whole `value:description` line is wrapped in `ansiC(...)`,\n // which handles shell-level escaping. `_describe` consumes only\n // the first unescaped `:` to split value/description, so the\n // description tail does not need any additional escaping —\n // applying the double-quoted-string escaper here would leak\n // backslashes for `$`, `\"`, `` ` ``, and `:` into the rendered\n // completion UI (e.g. `cost $5` becoming `cost \\$5`).\n return c.description ? `${escapedValue}:${c.description}` : escapedValue;\n })\n .join(\"\\n\");\n lines.push(` ${ansiC(key)} ${ansiC(value)}`);\n }\n lines.push(`)`);\n }\n lines.push(``);\n }\n\n // Dynamic completion delegate helpers (only when any value spec uses\n // an in-process JS resolver).\n if (hasDynamicCompletion(root)) {\n lines.push(...dynamicInvokeCompleteLines(fn, programName));\n lines.push(``);\n lines.push(`__${fn}_apply_dynamic_output() {`);\n lines.push(` local _raw=\"$1\"`);\n lines.push(` local _directive=0`);\n lines.push(` local -a _vals _lines`);\n lines.push(` _lines=(\"\\${(@f)_raw}\")`);\n // Only the trailing line is the directive sentinel; intermediate lines\n // starting with `:` are legitimate candidate values.\n lines.push(` local _last=$#_lines`);\n lines.push(` if (( _last >= 1 )) && [[ \"\\${_lines[$_last]}\" == :<-> ]]; then`);\n lines.push(` _directive=\"\\${_lines[$_last]#:}\"`);\n lines.push(` _lines[$_last]=()`);\n lines.push(` fi`);\n lines.push(` local _l`);\n lines.push(` for _l in \"\\${_lines[@]}\"; do`);\n // Skip only blanks. The `@ext:`/`@matcher:` sentinels are produced by\n // the static shellCommand pipeline, not by dynamic resolvers — filtering\n // them here would silently drop resolver candidates that happen to\n // start with those literal strings.\n lines.push(` [[ -z \"$_l\" ]] && continue`);\n lines.push(` _vals+=(\"$_l\")`);\n lines.push(` done`);\n // Emit resolver candidates first, then layer on filesystem completion\n // when the resolver requested it. `_files` adds to the candidate list\n // rather than replacing it, so a resolver returning both names and\n // `FileCompletion` shows both — matching the bash/fish behaviour. When\n // the resolver flags NoSpace (e.g. `key=` candidates that the user\n // should keep typing past), forward `-S ''` to compadd so zsh does\n // not append the default trailing space.\n lines.push(` if (( \\${#_vals[@]} > 0 )); then`);\n lines.push(` if (( _directive & ${CompletionDirective.NoSpace} )); then`);\n lines.push(` __${fn}_cdescribe 'completions' _vals -S ''`);\n lines.push(` else`);\n lines.push(` __${fn}_cdescribe 'completions' _vals`);\n lines.push(` fi`);\n lines.push(` fi`);\n lines.push(` if (( _directive & ${CompletionDirective.DirectoryCompletion} )); then`);\n lines.push(` _files -/`);\n lines.push(` elif (( _directive & ${CompletionDirective.FileCompletion} )); then`);\n lines.push(` _files`);\n // Default directive (0) with no resolver candidates: fall back to\n // the documented filename completion, matching the bash apply\n // helper. Without this, an empty `Default` result silently leaves\n // the caller's `return 0` to suppress any file fallback.\n lines.push(\n ` elif (( \\${#_vals[@]} == 0 )) && ! (( _directive & ${CompletionDirective.NoFileCompletion} )); then`,\n );\n lines.push(` _files`);\n lines.push(` fi`);\n lines.push(`}`);\n lines.push(``);\n }\n\n // Helper: check if option is already used\n lines.push(`__${fn}_not_used() {`);\n lines.push(` local _u _chk`);\n lines.push(` for _u in \"\\${_used_opts[@]}\"; do`);\n lines.push(` for _chk in \"$@\"; do`);\n lines.push(` [[ \"$_u\" == \"$_chk\" ]] && return 1`);\n lines.push(` done`);\n lines.push(` done`);\n lines.push(` return 0`);\n lines.push(`}`);\n lines.push(``);\n\n // Helper: _describe with compadd fallback\n // _describe may fail to add matches when prefix starts with - (zsh tag\n // system limitation). When that happens we still want any trailing\n // compadd-pass-through options (e.g. `-S ''` for NoSpace) to reach\n // compadd so two-stage `key=` candidates keep their suffix behaviour.\n lines.push(`__${fn}_cdescribe() {`);\n lines.push(` _describe \"$@\" 2>/dev/null && return 0`);\n lines.push(` shift`);\n lines.push(` local _cd_arr=\"$1\"`);\n lines.push(` shift`);\n lines.push(` local -a _cd_vals=(\"\\${(@)\\${(P)_cd_arr}%%:*}\")`);\n lines.push(` compadd \"$@\" -a _cd_vals 2>/dev/null`);\n lines.push(` return 0`);\n lines.push(`}`);\n lines.push(``);\n\n // Helper: check if option takes a value\n lines.push(`__${fn}_opt_takes_value() {`);\n lines.push(` case \"$1:$2\" in`);\n lines.push(...optTakesValueEntries(root, \"\"));\n lines.push(` esac`);\n lines.push(` return 1`);\n lines.push(`}`);\n lines.push(``);\n\n if (hasExpand) {\n // Trackers populate `_arg_values` during the main scan loop so the\n // per-spec lookup can dispatch on sibling arg values.\n lines.push(`__${fn}_track_opt() {`);\n lines.push(` case \"$1:$2\" in`);\n lines.push(...trackOptCaseLines(trackedFields, \"zsh\"));\n lines.push(` esac`);\n lines.push(`}`);\n lines.push(``);\n lines.push(`__${fn}_track_pos() {`);\n lines.push(` case \"$1:$2\" in`);\n lines.push(...trackPosCaseLines(trackedFields, \"zsh\"));\n lines.push(` esac`);\n lines.push(`}`);\n lines.push(``);\n }\n\n if (hasArrayExpand) {\n // Separate function from `__track_opt` so an option that is\n // simultaneously a dependsOn target and an array expand host does\n // not collide on the same case pattern.\n lines.push(`__${fn}_track_array_expand() {`);\n lines.push(` case \"$1:$2\" in`);\n lines.push(...trackArrayExpandCaseLines(arrayExpandSpecs, \"zsh\"));\n lines.push(` esac`);\n lines.push(`}`);\n lines.push(``);\n }\n\n // Collect all nested subcommand routes (used for both is_subcmd and dispatch)\n const routeEntries = collectRouteEntries(root);\n\n // Helper: check if a word is a known subcommand at the current path level\n if (routeEntries.length > 0) {\n lines.push(`__${fn}_is_subcmd() {`);\n lines.push(` case \"$1:$2\" in`);\n lines.push(...isSubcmdCaseLines(routeEntries));\n lines.push(` esac`);\n lines.push(` return 1`);\n lines.push(`}`);\n lines.push(``);\n }\n\n // Per-subcommand completion functions\n for (const sub of visibleSubs) {\n lines.push(...generateSubHandler(sub, fn, []));\n }\n\n // Root handler\n // NOTE: Inline --opt=value completion is not yet supported in zsh; only\n // separate-word value completion (--opt <value>) is handled. Bash supports\n // inline via _inline_prefix parsing.\n lines.push(`__${fn}_complete_root() {`);\n lines.push(` local -a _vals=()`);\n lines.push(...valueCompletionBlock(root.options, root.positionals, fn, \"root\"));\n // Fallback: value-taking option without explicit completion → default file completion\n lines.push(` if __${fn}_opt_takes_value \"\" \"\\${words[CURRENT-1]}\"; then return 0; fi`);\n if (root.positionals.length > 0) {\n lines.push(` if (( _after_dd )); then`);\n lines.push(\n ...positionalBlock(root.positionals, fn, \"root\", root.options).map((l) => ` ${l}`),\n );\n lines.push(` return 0`);\n lines.push(` fi`);\n } else {\n lines.push(` if (( _after_dd )); then return 0; fi`);\n }\n lines.push(` if [[ \"\\${words[CURRENT]}\" == -* ]]; then`);\n lines.push(` local -a _opts=()`);\n lines.push(...availableOptionLines(root.options, fn));\n lines.push(` __${fn}_cdescribe 'options' _opts`);\n if (visibleSubs.length > 0) {\n lines.push(` else`);\n const subItems = getSubNamesWithAliases(root.subcommands)\n .map((s) => {\n const desc = s.description ? `:${escapeDesc(s.description)}` : \"\";\n return `\"${s.name}${desc}\"`;\n })\n .join(\" \");\n lines.push(` local -a _subs=(${subItems})`);\n lines.push(` __${fn}_cdescribe 'subcommands' _subs`);\n } else if (root.positionals.length > 0) {\n lines.push(` else`);\n lines.push(\n ...positionalBlock(root.positionals, fn, \"root\", root.options).map((l) => ` ${l}`),\n );\n }\n lines.push(` fi`);\n lines.push(`}`);\n lines.push(``);\n\n // Main completion function -- subcommand dispatch routing\n const subRouting = subDispatchCaseLines(routeEntries, fn).join(\"\\n\");\n\n lines.push(`${completionFn}() {`);\n lines.push(` (( CURRENT )) || CURRENT=\\${#words}`);\n lines.push(``);\n lines.push(` local _subcmd=\"\" _after_dd=0 _pos_count=0 _skip_next=0`);\n lines.push(` local -a _used_opts=()`);\n if (hasExpand) {\n lines.push(` local -A _arg_values=()`);\n // Globals survive subcommand descent so values supplied before the\n // subcommand (e.g. `cli --env prod sub --field <TAB>`) remain visible.\n lines.push(` local -A _global_arg_values=()`);\n }\n if (hasArrayExpand) {\n lines.push(` local -A _used_field_keys=()`);\n lines.push(` local -A _global_used_field_keys=()`);\n lines.push(` local -A _global_arr_seen=()`);\n }\n lines.push(``);\n lines.push(` local _j=2`);\n lines.push(` while (( _j < CURRENT )); do`);\n lines.push(` local _w=\"\\${words[_j]}\"`);\n lines.push(` if (( _skip_next )); then _skip_next=0; (( _j++ )); continue; fi`);\n lines.push(` if [[ \"$_w\" == \"--\" ]]; then _after_dd=1; (( _j++ )); continue; fi`);\n // After `--`, all remaining words are positionals. Track them so an\n // expand spec that depends on a positional still sees the value.\n const afterDdTrack = hasExpand ? `__${fn}_track_pos \"$_subcmd\" \"$_pos_count\" \"$_w\"; ` : \"\";\n lines.push(\n ` if (( _after_dd )); then ${afterDdTrack}(( _pos_count++ )); (( _j++ )); continue; fi`,\n );\n // Match both `--opt=value` and `-o=value`: the parser accepts the\n // short inline form too, so the scanner must split it before tracking\n // the dep value, otherwise `-e=prod` slips past the tracker.\n lines.push(` if [[ \"$_w\" == -*=* ]]; then`);\n lines.push(` _used_opts+=(\"\\${_w%%=*}\")`);\n if (hasExpand) {\n lines.push(` __${fn}_track_opt \"$_subcmd\" \"\\${_w%%=*}\" \"\\${_w#*=}\"`);\n if (hasArrayExpand) {\n lines.push(` __${fn}_track_array_expand \"$_subcmd\" \"\\${_w%%=*}\" \"\\${_w#*=}\"`);\n }\n }\n lines.push(` (( _j++ )); continue`);\n lines.push(` fi`);\n lines.push(` if [[ \"$_w\" == -* ]]; then`);\n lines.push(` _used_opts+=(\"$_w\")`);\n // Mirror the runtime parser: a token starting with `-` is the next\n // option, not this option's value. Skip/track only when the next\n // token looks like a value.\n lines.push(` if __${fn}_opt_takes_value \"$_subcmd\" \"$_w\"; then`);\n lines.push(` local _next=\"\\${words[_j+1]:-}\"`);\n lines.push(` if [[ -n \"$_next\" && \"$_next\" != -* ]]; then _skip_next=1; fi`);\n if (hasExpand) {\n lines.push(` if (( _skip_next )); then`);\n lines.push(` __${fn}_track_opt \"$_subcmd\" \"$_w\" \"$_next\"`);\n if (hasArrayExpand) {\n lines.push(` if (( _j + 1 < CURRENT )); then`);\n lines.push(` __${fn}_track_array_expand \"$_subcmd\" \"$_w\" \"$_next\"`);\n lines.push(` fi`);\n }\n lines.push(` fi`);\n }\n lines.push(` fi`);\n lines.push(` (( _j++ )); continue`);\n lines.push(` fi`);\n // Clear sibling-tracker state when descending into a subcommand:\n // `dependsOn` is scoped to siblings on the same command frame, so\n // letting a parent's `--env` bleed into a child with its own `--env`\n // would feed the wrong value into the child's expand lookup.\n const clearState = hasArrayExpand\n ? `; _arg_values=(); _used_field_keys=(); _global_arr_seen=()`\n : hasExpand\n ? `; _arg_values=()`\n : \"\";\n const posTrack = hasExpand ? `__${fn}_track_pos \"$_subcmd\" \"$_pos_count\" \"$_w\"; ` : \"\";\n if (routeEntries.length > 0) {\n lines.push(\n ` if __${fn}_is_subcmd \"$_subcmd\" \"$_w\"; then _subcmd=\"\\${_subcmd:+\\${_subcmd}:}$_w\"; _used_opts=(); _pos_count=0${clearState}; else ${posTrack}(( _pos_count++ )); fi`,\n );\n } else {\n if (hasExpand) {\n lines.push(` __${fn}_track_pos \"$_subcmd\" \"$_pos_count\" \"$_w\"`);\n }\n lines.push(` (( _pos_count++ ))`);\n }\n lines.push(` (( _j++ ))`);\n lines.push(` done`);\n lines.push(``);\n lines.push(` case \"$_subcmd\" in`);\n lines.push(subRouting);\n lines.push(` *) __${fn}_complete_root ;;`);\n lines.push(` esac`);\n lines.push(`}`);\n lines.push(``);\n lines.push(\n `zstyle ':completion:*:*:${programName}:*' file-patterns '%p:globbed-files *(-/):directories'`,\n );\n lines.push(``);\n lines.push(`if [[ ${autoloadCheck} ]]; then`);\n lines.push(` ${completionFn} \"$@\"`);\n lines.push(`else`);\n lines.push(` compdef ${completionFn} ${programName}`);\n lines.push(`fi`);\n lines.push(``);\n\n return {\n script: lines.join(\"\\n\"),\n shell: \"zsh\",\n installInstructions: `# To enable auto-refreshing zsh completions, add this to your ~/.zshrc after compinit:\neval \"$(${programName} completion zsh)\"\n\n# For faster shell startup, save the script in your fpath:\nmkdir -p ~/.zsh/completions\n${programName} completion zsh > ~/.zsh/completions/_${programName}\n\n# Make sure your ~/.zshrc includes the fpath line before compinit:\nfpath=(~/.zsh/completions $fpath)\nautoload -Uz compinit && compinit\n\n# If ~/.zshrc already calls compinit, add only the fpath line before\n# the existing compinit call.\n\n# Then reload your shell or run:\nsource ~/.zshrc`,\n };\n}\n","/**\n * Shell completion generation module\n *\n * Provides utilities to generate shell completion scripts for bash, zsh, and fish.\n *\n * @example\n * ```typescript\n * import { generateCompletion, createCompletionCommand } from \"politty/completion\";\n *\n * // Generate completion script directly\n * const result = generateCompletion(myCommand, {\n * shell: \"bash\",\n * programName: \"mycli\"\n * });\n * console.log(result.script);\n *\n * // Or add a completion subcommand to your CLI\n * const mainCommand = withCompletionCommand(\n * defineCommand({\n * name: \"mycli\",\n * subCommands: { ... },\n * }),\n * );\n * ```\n */\n\nimport { z } from \"zod\";\nimport { arg } from \"../core/arg-registry.js\";\nimport { defineCommand } from \"../core/command.js\";\nimport type { AnyCommand, ArgsSchema, Command } from \"../types.js\";\nimport { generateBashCompletion } from \"./bash.js\";\nimport { createDynamicCompleteCommand } from \"./dynamic/index.js\";\nimport { generateFishCompletion } from \"./fish.js\";\nimport {\n hasManagedCache,\n install as installCompletion,\n refreshIfStale,\n spawnBackgroundRefresh,\n} from \"./install.js\";\nimport { generateLoader } from \"./loader.js\";\nimport type { CompletionOptions, CompletionResult, ShellType } from \"./types.js\";\nimport { generateZshCompletion } from \"./zsh.js\";\n\n// Re-export dynamic completion types (in-process resolver)\nexport type {\n CompletionDirectiveMask,\n DynamicCompletionCandidate,\n DynamicCompletionContext,\n DynamicCompletionResolver,\n DynamicCompletionResult,\n} from \"../core/dynamic-completion-types.js\";\nexport {\n CompletionDirective,\n createDynamicCompleteCommand,\n formatForShell,\n generateCandidates,\n hasCompleteCommand,\n parseCompletionContext,\n type CandidateResult,\n type CompletionCandidate,\n type CompletionContext,\n type CompletionType,\n type ShellFormatOptions,\n} from \"./dynamic/index.js\";\n// Re-export extractor\nexport { extractCompletionData, extractPositionals } from \"./extractor.js\";\n// Re-export types\nexport type {\n CompletableOption,\n CompletableSubcommand,\n CompletionData,\n CompletionGenerator,\n CompletionOptions,\n CompletionResult,\n ShellType,\n} from \"./types.js\";\n// Re-export value completion resolver\nexport { resolveValueCompletion, type ValueCompletionField } from \"./value-completion-resolver.js\";\n\n/**\n * Generate completion script for the specified shell\n */\nexport function generateCompletion(\n command: AnyCommand,\n options: CompletionOptions,\n): CompletionResult {\n switch (options.shell) {\n case \"bash\":\n return generateBashCompletion(command, options);\n case \"zsh\":\n return generateZshCompletion(command, options);\n case \"fish\":\n return generateFishCompletion(command, options);\n default:\n throw new Error(`Unsupported shell: ${options.shell}`);\n }\n}\n\n/**\n * Get the list of supported shells\n */\nexport function getSupportedShells(): ShellType[] {\n return [\"bash\", \"zsh\", \"fish\"];\n}\n\nfunction shSingleQuote(s: string): string {\n return `'${s.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nfunction printZshFpathSetup(programName: string, target: string): void {\n console.error(\"\");\n console.error(\"Configure zsh fpath with:\");\n console.error(\"\");\n console.error(\" mkdir -p ~/.zsh/completions\");\n console.error(` ln -sf ${shSingleQuote(target)} ~/.zsh/completions/_${programName}`);\n console.error(\"\");\n console.error(\"Add only this block to your ~/.zshrc before compinit:\");\n console.error(\"\");\n console.error(\" fpath=(~/.zsh/completions $fpath)\");\n console.error(\" autoload -Uz compinit && compinit\");\n}\n\n/**\n * Detect the current shell from environment\n */\nexport function detectShell(): ShellType | null {\n const shell = process.env.SHELL || \"\";\n const shellName = shell.split(\"/\").pop()?.toLowerCase() || \"\";\n\n if (shellName.includes(\"bash\")) {\n return \"bash\";\n }\n if (shellName.includes(\"zsh\")) {\n return \"zsh\";\n }\n if (shellName.includes(\"fish\")) {\n return \"fish\";\n }\n\n return null;\n}\n\n/**\n * Schema for the completion command arguments\n */\nconst completionArgsSchema = z.object({\n shell: arg(\n z\n .enum([\"bash\", \"zsh\", \"fish\"])\n .optional()\n .describe(\"Shell type (auto-detected if not specified)\"),\n {\n positional: true,\n description: \"Shell type (bash, zsh, or fish)\",\n placeholder: \"SHELL\",\n },\n ),\n instructions: arg(z.boolean().default(false), {\n alias: \"i\",\n description: \"Show installation instructions\",\n }),\n loader: arg(z.boolean().default(false), {\n description:\n \"Print just the rc loader snippet (bash/zsh). Add it to ~/.bashrc or ~/.zshrc; it auto-regenerates the cache when the binary changes.\",\n }),\n install: arg(z.boolean().default(false), {\n description:\n \"Write the completion script to its on-disk cache (bash/zsh) or autoload location (fish) instead of printing it.\",\n }),\n});\n\ntype CompletionArgs = z.infer<typeof completionArgsSchema>;\n\nconst refreshArgsSchema = z.object({\n shell: arg(z.enum([\"bash\", \"zsh\", \"fish\"]), {\n positional: true,\n description: \"Shell to refresh\",\n placeholder: \"SHELL\",\n }),\n target: arg(z.string().optional(), {\n positional: true,\n description: \"Existing politty-generated completion file to refresh\",\n placeholder: \"TARGET\",\n }),\n});\n\ntype RefreshArgs = z.infer<typeof refreshArgsSchema>;\n\n/**\n * Create a completion subcommand for your CLI\n *\n * This creates a ready-to-use subcommand that generates completion scripts.\n *\n * @example\n * ```typescript\n * const mainCommand = defineCommand({\n * name: \"mycli\",\n * subCommands: {\n * completion: createCompletionCommand(mainCommand)\n * }\n * });\n * ```\n */\nexport function createCompletionCommand(\n rootCommand: AnyCommand,\n programName?: string,\n globalArgsSchema?: ArgsSchema,\n extra: { cacheDir?: string; programVersion?: string } = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Command<typeof completionArgsSchema, CompletionArgs, any> {\n const resolvedProgramName = programName ?? rootCommand.name;\n const { cacheDir, programVersion } = extra;\n\n // Build the option fragments once. Under exactOptionalPropertyTypes\n // we can't pass `undefined` values directly, so we omit absent keys.\n const refreshExtra: {\n cacheDir?: string;\n programVersion?: string;\n globalArgsSchema?: ArgsSchema;\n } = {\n ...(cacheDir !== undefined && { cacheDir }),\n ...(programVersion !== undefined && { programVersion }),\n ...(globalArgsSchema !== undefined && { globalArgsSchema }),\n };\n const installCtxBase: Omit<Parameters<typeof installCompletion>[0], \"rootCommand\"> = {\n programName: resolvedProgramName,\n ...refreshExtra,\n };\n const loaderOptsBase = {\n programName: resolvedProgramName,\n ...(cacheDir !== undefined && { cacheDir }),\n };\n\n if (!rootCommand.subCommands?.__complete) {\n rootCommand.subCommands = {\n ...rootCommand.subCommands,\n __complete: createDynamicCompleteCommand(rootCommand, resolvedProgramName, globalArgsSchema),\n };\n }\n // Register `__refresh-completion` here too so callers using\n // `createCompletionCommand` directly (rather than\n // `withCompletionCommand`) still expose the subcommand the generated\n // rc loaders / fish autoload expect to invoke after the binary's\n // mtime changes. Without it, the loaders would call an unknown\n // subcommand with stderr swallowed and silently keep sourcing the\n // stale cache.\n if (!rootCommand.subCommands?.[\"__refresh-completion\"]) {\n rootCommand.subCommands = {\n ...rootCommand.subCommands,\n \"__refresh-completion\": createRefreshCompletionCommand(\n rootCommand,\n resolvedProgramName,\n refreshExtra,\n ),\n };\n }\n\n return defineCommand({\n name: \"completion\",\n description: \"Generate shell completion script\",\n args: completionArgsSchema,\n run(args) {\n // Detect shell if not specified\n const shellType = args.shell || detectShell();\n\n if (!shellType) {\n console.error(\"Could not detect shell type. Please specify one of: bash, zsh, fish\");\n process.exitCode = 1;\n return;\n }\n\n if (args.install) {\n let target: string;\n try {\n target = installCompletion({ rootCommand, ...installCtxBase }, shellType);\n } catch (e) {\n throw new Error(`install failed: ${e instanceof Error ? e.message : String(e)}`);\n }\n console.error(`installed: ${target}`);\n if (shellType === \"bash\") {\n console.error(\"\");\n console.error(`Add to your ~/.${shellType}rc:`);\n console.error(\"\");\n console.error(\n generateLoader({ ...loaderOptsBase, shell: shellType })\n .trim()\n .replace(/^/gm, \" \"),\n );\n } else if (shellType === \"zsh\") {\n printZshFpathSetup(resolvedProgramName, target);\n }\n return;\n }\n\n if (args.loader) {\n if (shellType === \"fish\") {\n throw new Error(\n \"fish does not use an rc loader. Run `<program> completion fish --install` to write the self-refreshing autoload file instead.\",\n );\n }\n process.stdout.write(generateLoader({ ...loaderOptsBase, shell: shellType }));\n return;\n }\n\n const result = generateCompletion(rootCommand, {\n shell: shellType,\n programName: resolvedProgramName,\n includeDescriptions: true,\n ...(globalArgsSchema !== undefined && { globalArgsSchema }),\n ...(programVersion !== undefined && { programVersion }),\n ...(cacheDir !== undefined && { cacheDir }),\n });\n\n if (args.instructions) {\n console.log(result.installInstructions);\n } else {\n console.log(result.script);\n }\n },\n });\n}\n\n/**\n * Hidden subcommand that the runMain background hook spawns. It does\n * the same stat-compare + atomic rewrite as the rc loader, but in a\n * detached child process so it's invisible to the user.\n */\nexport function createRefreshCompletionCommand(\n rootCommand: AnyCommand,\n programName: string,\n extra: { cacheDir?: string; programVersion?: string; globalArgsSchema?: ArgsSchema } = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Command<typeof refreshArgsSchema, RefreshArgs, any> {\n return defineCommand({\n name: \"__refresh-completion\",\n description: \"(internal) Refresh the on-disk completion cache if stale.\",\n args: refreshArgsSchema,\n run(args) {\n refreshIfStale(\n {\n rootCommand,\n programName,\n ...extra,\n ...(args.target !== undefined && { targetPath: args.target }),\n },\n args.shell,\n );\n },\n });\n}\n\n/**\n * Options for withCompletionCommand\n */\nexport interface WithCompletionOptions {\n /** Override the program name (defaults to command.name) */\n programName?: string;\n /** Global args schema for deriving global options in completion */\n globalArgsSchema?: ArgsSchema;\n /**\n * Hardcode the cache directory used by the rc loader and the\n * background refresh. When omitted, the loader derives\n * `${XDG_CACHE_HOME:-$HOME/.cache}/<programName>` at runtime, which\n * is the right answer for almost every CLI.\n */\n cacheDir?: string;\n /** Program version embedded in the script header. */\n programVersion?: string;\n}\n\n/**\n * Wrap a command with a completion subcommand\n *\n * This avoids circular references that occur when a command references itself\n * in its subCommands (e.g., for completion generation).\n *\n * @param command - The command to wrap\n * @param options - Options including programName\n * @returns A new command with the completion subcommand added\n *\n * @example\n * ```typescript\n * const mainCommand = withCompletionCommand(\n * defineCommand({\n * name: \"mycli\",\n * subCommands: { ... },\n * }),\n * );\n * ```\n */\nexport function withCompletionCommand<T extends AnyCommand>(\n command: T,\n options?: string | WithCompletionOptions,\n): T {\n // Support both string (programName) and options object for backwards compatibility\n const opts: WithCompletionOptions =\n typeof options === \"string\" ? { programName: options } : (options ?? {});\n\n const { programName, globalArgsSchema, cacheDir, programVersion } = opts;\n const resolvedProgramName = programName ?? command.name;\n const extra: { cacheDir?: string; programVersion?: string; globalArgsSchema?: ArgsSchema } = {\n ...(cacheDir !== undefined && { cacheDir }),\n ...(programVersion !== undefined && { programVersion }),\n ...(globalArgsSchema !== undefined && { globalArgsSchema }),\n };\n\n const wrappedCommand = {\n ...command,\n } as T;\n\n wrappedCommand.subCommands = {\n ...command.subCommands,\n completion: createCompletionCommand(wrappedCommand, programName, globalArgsSchema, extra),\n __complete: createDynamicCompleteCommand(wrappedCommand, programName, globalArgsSchema),\n \"__refresh-completion\": createRefreshCompletionCommand(\n wrappedCommand,\n resolvedProgramName,\n extra,\n ),\n };\n\n wrappedCommand.runMainHook = (argv) => {\n maybeSpawnRefresh(argv, {\n programName: resolvedProgramName,\n ...(cacheDir !== undefined && { cacheDir }),\n });\n };\n\n return wrappedCommand;\n}\n\n/**\n * Background-refresh trigger fired from `runMain` via `runMainHook`.\n *\n * Skipped when:\n * - the user is invoking `__complete` / `__refresh-completion` /\n * `completion` themselves (avoids loops and double work)\n * - $SHELL doesn't resolve to a known shell\n * - the user opted out via $POLITTY_NO_COMPLETION_REFRESH\n * - process.argv[1] is missing (shouldn't happen for normal CLIs)\n * - no politty-managed cache exists yet — i.e. the user hasn't\n * installed completion. Without this gate the detached child would\n * create a fish autoload (or any cache file) on every CLI run,\n * even though the user never opted in via `--install` or the rc loader.\n */\nfunction maybeSpawnRefresh(\n argv: readonly string[],\n ctx: { programName: string; cacheDir?: string | undefined },\n): void {\n if (process.env.POLITTY_NO_COMPLETION_REFRESH) return;\n\n const firstPositional = argv.find((a) => !a.startsWith(\"-\"));\n if (\n firstPositional === \"__complete\" ||\n firstPositional === \"__refresh-completion\" ||\n firstPositional === \"completion\"\n ) {\n return;\n }\n\n const shell = detectShell();\n if (!shell) return;\n const argv0 = process.argv[1];\n if (!argv0) return;\n if (!hasManagedCache(ctx, shell)) return;\n\n spawnBackgroundRefresh(argv0, shell);\n}\n"],"mappings":";;;;;;;AAmJA,SAAgB,cAKd,QAGuE;CACvE,OAAO;EACL,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,SAAS,OAAO;EAChB,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,OAAO,OAAO;EACd,KAAK,OAAO;EACZ,SAAS,OAAO;EAChB,OAAO,OAAO;EACd,UAAU,OAAO;CACnB;AACF;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,sBAOd;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;ACjJA,SAAgB,qBACd,KACA,cACA,kBACoB;CACpB,OAAO;EACL,WAAW,IAAI;EACf,eAAe,IAAI,cAAc;EACjC,UAAU,IAAI,aAAa;EAC3B,cAAc,0BACZ,IAAI,iBACJ,IAAI,aAAa,MACjB,cACA,gBACF;CACF;AACF;;;;;;;AAQA,SAAgB,yBACd,KACA,cACA,kBACoB;CACpB,OAAO;EACL,WAAW,IAAI;EACf,eAAe;EACf,UAAU;EACV,cAAc,0BACZ,IAAI,iBACJ,OACA,cACA,gBACF;CACF;AACF;;;;;;;;;;;;;;;;AAiBA,SAAgB,0BACd,IACA,cACA,cACA,mBAAgD,CAAC,GACnB;CAC9B,IAAI,IAAI,SAAS,UA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