politty 0.4.0 → 0.4.2

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.
Files changed (67) hide show
  1. package/dist/{arg-registry-C3GP-5C9.d.ts → arg-registry-BNoIwnNr.d.cts} +15 -8
  2. package/dist/arg-registry-BNoIwnNr.d.cts.map +1 -0
  3. package/dist/{arg-registry-B4a4Fj7f.d.cts → arg-registry-BUUhZ7JR.d.ts} +15 -8
  4. package/dist/arg-registry-BUUhZ7JR.d.ts.map +1 -0
  5. package/dist/augment.d.cts +1 -1
  6. package/dist/augment.d.ts +1 -1
  7. package/dist/completion/index.cjs +20 -19
  8. package/dist/completion/index.cjs.map +1 -1
  9. package/dist/completion/index.d.cts +4 -4
  10. package/dist/completion/index.d.cts.map +1 -1
  11. package/dist/completion/index.d.ts +4 -4
  12. package/dist/completion/index.d.ts.map +1 -1
  13. package/dist/completion/index.js +3 -3
  14. package/dist/completion/index.js.map +1 -1
  15. package/dist/docs/index.cjs +6 -6
  16. package/dist/docs/index.cjs.map +1 -1
  17. package/dist/docs/index.d.cts +3 -3
  18. package/dist/docs/index.d.cts.map +1 -1
  19. package/dist/docs/index.d.ts +3 -3
  20. package/dist/docs/index.d.ts.map +1 -1
  21. package/dist/docs/index.js +3 -3
  22. package/dist/index.cjs +10 -8
  23. package/dist/index.d.cts +4 -4
  24. package/dist/index.d.cts.map +1 -1
  25. package/dist/index.d.ts +4 -4
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +4 -4
  28. package/dist/{schema-extractor-Cv7ipqLS.cjs → lazy-BEDnSR0m.cjs} +81 -2
  29. package/dist/lazy-BEDnSR0m.cjs.map +1 -0
  30. package/dist/{schema-extractor-CP3ar0Wi.js → lazy-BrEg8SgI.js} +63 -2
  31. package/dist/lazy-BrEg8SgI.js.map +1 -0
  32. package/dist/{runner-LJRI4haB.js → runner-B6W9A8P0.js} +5 -5
  33. package/dist/runner-B6W9A8P0.js.map +1 -0
  34. package/dist/{runner-9dLE13Dv.cjs → runner-CpyB8JiY.cjs} +10 -10
  35. package/dist/runner-CpyB8JiY.cjs.map +1 -0
  36. package/dist/{schema-extractor-DyfK21m_.d.cts → schema-extractor-DFaAZzaY.d.cts} +49 -4
  37. package/dist/schema-extractor-DFaAZzaY.d.cts.map +1 -0
  38. package/dist/{schema-extractor-CHiBRT39.d.ts → schema-extractor-n9288WJ6.d.ts} +49 -4
  39. package/dist/schema-extractor-n9288WJ6.d.ts.map +1 -0
  40. package/dist/{subcommand-router-DtCeT_O9.js → subcommand-router-CAzBsLSI.js} +4 -1
  41. package/dist/{subcommand-router-DtCeT_O9.js.map → subcommand-router-CAzBsLSI.js.map} +1 -1
  42. package/dist/{subcommand-router-4d1Xbp8B.cjs → subcommand-router-ZjNjFaUL.cjs} +3 -1
  43. package/dist/subcommand-router-ZjNjFaUL.cjs.map +1 -0
  44. package/dist/{extractor-DsJ6hYqQ.d.cts → value-completion-resolver-BQgHsX7b.d.cts} +73 -20
  45. package/dist/value-completion-resolver-BQgHsX7b.d.cts.map +1 -0
  46. package/dist/{extractor-CCi4rjSI.d.ts → value-completion-resolver-C9LTGr0O.d.ts} +73 -20
  47. package/dist/value-completion-resolver-C9LTGr0O.d.ts.map +1 -0
  48. package/dist/zsh-CASZWn0o.cjs +1586 -0
  49. package/dist/zsh-CASZWn0o.cjs.map +1 -0
  50. package/dist/zsh-hjvdI8uZ.js +1508 -0
  51. package/dist/zsh-hjvdI8uZ.js.map +1 -0
  52. package/package.json +7 -6
  53. package/dist/arg-registry-B4a4Fj7f.d.cts.map +0 -1
  54. package/dist/arg-registry-C3GP-5C9.d.ts.map +0 -1
  55. package/dist/extractor-CCi4rjSI.d.ts.map +0 -1
  56. package/dist/extractor-CqfDnGKd.cjs +0 -970
  57. package/dist/extractor-CqfDnGKd.cjs.map +0 -1
  58. package/dist/extractor-DsJ6hYqQ.d.cts.map +0 -1
  59. package/dist/extractor-JfoYSoMk.js +0 -898
  60. package/dist/extractor-JfoYSoMk.js.map +0 -1
  61. package/dist/runner-9dLE13Dv.cjs.map +0 -1
  62. package/dist/runner-LJRI4haB.js.map +0 -1
  63. package/dist/schema-extractor-CHiBRT39.d.ts.map +0 -1
  64. package/dist/schema-extractor-CP3ar0Wi.js.map +0 -1
  65. package/dist/schema-extractor-Cv7ipqLS.cjs.map +0 -1
  66. package/dist/schema-extractor-DyfK21m_.d.cts.map +0 -1
  67. package/dist/subcommand-router-4d1Xbp8B.cjs.map +0 -1
@@ -0,0 +1,1586 @@
1
+ const require_subcommand_router = require('./subcommand-router-ZjNjFaUL.cjs');
2
+ const require_lazy = require('./lazy-BEDnSR0m.cjs');
3
+ let zod = require("zod");
4
+ let node_child_process = require("node:child_process");
5
+
6
+ //#region src/core/command.ts
7
+ function defineCommand(config) {
8
+ return {
9
+ name: config.name,
10
+ description: config.description,
11
+ args: config.args,
12
+ subCommands: config.subCommands,
13
+ setup: config.setup,
14
+ run: config.run,
15
+ cleanup: config.cleanup,
16
+ notes: config.notes,
17
+ examples: config.examples
18
+ };
19
+ }
20
+
21
+ //#endregion
22
+ //#region src/completion/value-completion-resolver.ts
23
+ /**
24
+ * Resolve value completion from field metadata
25
+ *
26
+ * Priority:
27
+ * 1. Explicit custom completion (choices or shellCommand)
28
+ * 2. Explicit completion type (file, directory, none)
29
+ * 3. Auto-detected enum values from schema
30
+ */
31
+ function resolveValueCompletion(field) {
32
+ const meta = field.completion;
33
+ if (meta?.custom) {
34
+ if (meta.custom.choices && meta.custom.choices.length > 0) return {
35
+ type: "choices",
36
+ choices: meta.custom.choices
37
+ };
38
+ if (meta.custom.shellCommand) return {
39
+ type: "command",
40
+ shellCommand: meta.custom.shellCommand
41
+ };
42
+ }
43
+ if (meta?.type) {
44
+ if (meta.type === "file") {
45
+ if (meta.matcher) return {
46
+ type: "file",
47
+ matcher: meta.matcher
48
+ };
49
+ if (meta.extensions) return {
50
+ type: "file",
51
+ extensions: meta.extensions
52
+ };
53
+ return { type: "file" };
54
+ }
55
+ if (meta.type === "directory") return { type: "directory" };
56
+ if (meta.type === "none") return { type: "none" };
57
+ }
58
+ if (field.enumValues && field.enumValues.length > 0) return {
59
+ type: "choices",
60
+ choices: field.enumValues
61
+ };
62
+ }
63
+
64
+ //#endregion
65
+ //#region src/completion/extractor.ts
66
+ /**
67
+ * Extract completion data from commands
68
+ */
69
+ /**
70
+ * Sanitize a name for use as a shell function/variable identifier.
71
+ * Replaces any character that is not alphanumeric or underscore with underscore.
72
+ */
73
+ function sanitize(name) {
74
+ return name.replace(/[^a-zA-Z0-9_]/g, "_");
75
+ }
76
+ /**
77
+ * Filter subcommands to only visible (non-internal) ones.
78
+ * Internal subcommands start with "__" and are hidden from completion/help.
79
+ */
80
+ function getVisibleSubs(subs) {
81
+ return subs.filter((s) => !s.name.startsWith("__"));
82
+ }
83
+ /**
84
+ * Convert a resolved field to a completable option
85
+ */
86
+ function fieldToOption(field) {
87
+ return {
88
+ name: field.name,
89
+ cliName: field.cliName,
90
+ alias: field.alias,
91
+ description: field.description,
92
+ takesValue: field.type !== "boolean",
93
+ valueType: field.type,
94
+ required: field.required,
95
+ valueCompletion: resolveValueCompletion(field)
96
+ };
97
+ }
98
+ /**
99
+ * Extract options from a command's args schema
100
+ */
101
+ function extractOptions$1(command) {
102
+ if (!command.args) return [];
103
+ return require_lazy.extractFields(command.args).fields.filter((field) => !field.positional).map(fieldToOption);
104
+ }
105
+ /**
106
+ * Extract positional arguments from a command
107
+ */
108
+ function extractPositionals(command) {
109
+ if (!command.args) return [];
110
+ return require_lazy.extractFields(command.args).fields.filter((field) => field.positional);
111
+ }
112
+ /**
113
+ * Extract completable positional arguments from a command
114
+ */
115
+ function extractCompletablePositionals(command) {
116
+ if (!command.args) return [];
117
+ return require_lazy.extractFields(command.args).fields.filter((field) => field.positional).map((field, index) => ({
118
+ name: field.name,
119
+ cliName: field.cliName,
120
+ position: index,
121
+ description: field.description,
122
+ required: field.required,
123
+ variadic: field.type === "array",
124
+ valueCompletion: resolveValueCompletion(field)
125
+ }));
126
+ }
127
+ /**
128
+ * Extract a completable subcommand from a command
129
+ */
130
+ function extractSubcommand(name, command) {
131
+ const subcommands = [];
132
+ if (command.subCommands) for (const [subName, subCommand] of Object.entries(command.subCommands)) {
133
+ const resolved = require_lazy.resolveSubCommandMeta(subCommand);
134
+ if (resolved) subcommands.push(extractSubcommand(subName, resolved));
135
+ else subcommands.push({
136
+ name: subName,
137
+ description: "(lazy loaded)",
138
+ subcommands: [],
139
+ options: [],
140
+ positionals: []
141
+ });
142
+ }
143
+ return {
144
+ name,
145
+ description: command.description,
146
+ subcommands,
147
+ options: extractOptions$1(command),
148
+ positionals: extractCompletablePositionals(command)
149
+ };
150
+ }
151
+ /**
152
+ * Collect opt-takes-value case entries for a subcommand tree.
153
+ * Used by bash and zsh generators (identical case syntax: `subcmd:--opt) return 0 ;;`).
154
+ */
155
+ function optTakesValueEntries(sub, subcmdName) {
156
+ const lines = [];
157
+ for (const opt of sub.options) if (opt.takesValue) {
158
+ const patterns = [`${subcmdName}:--${opt.cliName}`];
159
+ if (opt.alias) patterns.push(`${subcmdName}:-${opt.alias}`);
160
+ lines.push(` ${patterns.join("|")}) return 0 ;;`);
161
+ }
162
+ for (const child of getVisibleSubs(sub.subcommands)) lines.push(...optTakesValueEntries(child, child.name));
163
+ return lines;
164
+ }
165
+ /**
166
+ * Extract completion data from a command tree
167
+ */
168
+ function extractCompletionData(command, programName) {
169
+ const rootSubcommand = extractSubcommand(programName, command);
170
+ return {
171
+ command: rootSubcommand,
172
+ programName,
173
+ globalOptions: rootSubcommand.options
174
+ };
175
+ }
176
+
177
+ //#endregion
178
+ //#region src/completion/bash.ts
179
+ /** Escape a string for use inside bash double-quotes */
180
+ function escapeBashDQ(s) {
181
+ return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$").replace(/`/g, "\\`");
182
+ }
183
+ /**
184
+ * Generate bash value completion code for a ValueCompletion spec.
185
+ * Returns an array of bash lines.
186
+ */
187
+ function bashValueLines(vc, inline) {
188
+ if (!vc) return [];
189
+ switch (vc.type) {
190
+ case "choices": {
191
+ const items = vc.choices.map((c) => `"${escapeBashDQ(c)}"`).join(" ");
192
+ if (inline) return [
193
+ `local -a _choices=(${items})`,
194
+ `COMPREPLY=()`,
195
+ `local _c; for _c in "\${_choices[@]}"; do [[ "$_c" == "$_cur"* ]] && COMPREPLY+=("\${_inline_prefix}\${_c}"); done`,
196
+ `compopt -o nospace`,
197
+ `compopt +o default 2>/dev/null`
198
+ ];
199
+ return [
200
+ `local -a _choices=(${items})`,
201
+ `COMPREPLY=()`,
202
+ `local _c; for _c in "\${_choices[@]}"; do [[ "$_c" == "$_cur"* ]] && COMPREPLY+=("$_c"); done`,
203
+ `compopt +o default 2>/dev/null`
204
+ ];
205
+ }
206
+ case "file":
207
+ if (vc.matcher?.length) return bashFileFilter(vc.matcher.map((p) => `[[ "\${_f##*/}" == ${p} ]]`).join(" || "), inline);
208
+ if (vc.extensions?.length) return bashFileFilter(vc.extensions.map((ext) => `[[ "$_f" == *".${ext}" ]]`).join(" || "), inline);
209
+ if (inline) return [
210
+ `local -a _entries=($(compgen -f -- "$_cur"))`,
211
+ `COMPREPLY=("\${_entries[@]/#/$_inline_prefix}")`,
212
+ `compopt -o filenames`
213
+ ];
214
+ return [`COMPREPLY=($(compgen -f -- "$_cur"))`, `compopt -o filenames`];
215
+ case "directory":
216
+ if (inline) return [
217
+ `local -a _dirs=($(compgen -d -- "$_cur"))`,
218
+ `COMPREPLY=("\${_dirs[@]/#/$_inline_prefix}")`,
219
+ `compopt -o filenames`
220
+ ];
221
+ return [`COMPREPLY=($(compgen -d -- "$_cur"))`, `compopt -o filenames`];
222
+ case "command": {
223
+ const cmd = vc.shellCommand;
224
+ if (inline) return [`COMPREPLY=($(compgen -P "$_inline_prefix" -W "$(${cmd})" -- "$_cur"))`];
225
+ return [`COMPREPLY=($(compgen -W "$(${cmd})" -- "$_cur"))`];
226
+ }
227
+ case "none": return [`compopt +o default 2>/dev/null`];
228
+ }
229
+ }
230
+ function bashFileFilter(checks, inline) {
231
+ const prefix = inline ? `"\${_inline_prefix}$_f"` : `"$_f"`;
232
+ return [
233
+ `local -a _all_entries=($(compgen -f -- "$_cur"))`,
234
+ `for _f in "\${_all_entries[@]}"; do`,
235
+ ` if [[ -d "$_f" ]]; then`,
236
+ ` COMPREPLY+=(${prefix})`,
237
+ ` elif ${checks}; then`,
238
+ ` COMPREPLY+=(${prefix})`,
239
+ ` fi`,
240
+ `done`,
241
+ `compopt -o filenames`,
242
+ `compopt +o default 2>/dev/null`
243
+ ];
244
+ }
245
+ /** Collect value-taking option patterns for case matching */
246
+ function optionValueCases$2(options, inline) {
247
+ const lines = [];
248
+ for (const opt of options) {
249
+ if (!opt.takesValue || !opt.valueCompletion) continue;
250
+ const valLines = bashValueLines(opt.valueCompletion, inline);
251
+ if (valLines.length === 0) continue;
252
+ const patterns = [`--${opt.cliName}`];
253
+ if (opt.alias) patterns.push(`-${opt.alias}`);
254
+ const patternStr = patterns.join("|");
255
+ lines.push(` ${patternStr})`);
256
+ for (const vl of valLines) lines.push(` ${vl}`);
257
+ lines.push(` return ;;`);
258
+ }
259
+ return lines;
260
+ }
261
+ /** Generate positional completion block */
262
+ function positionalBlock$2(positionals) {
263
+ if (positionals.length === 0) return [];
264
+ const lines = [];
265
+ lines.push(` case "$_pos_count" in`);
266
+ for (const pos of positionals) {
267
+ if (pos.variadic) lines.push(` ${pos.position}|*)`);
268
+ else lines.push(` ${pos.position})`);
269
+ for (const vl of bashValueLines(pos.valueCompletion, false)) lines.push(` ${vl}`);
270
+ lines.push(` ;;`);
271
+ }
272
+ lines.push(` esac`);
273
+ return lines;
274
+ }
275
+ /** Generate prev/inline value completion blocks for options */
276
+ function valueCompletionBlocks(options) {
277
+ if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];
278
+ const lines = [];
279
+ const prevCases = optionValueCases$2(options, false);
280
+ if (prevCases.length > 0) {
281
+ lines.push(` if [[ -z "$_inline_prefix" ]]; then`);
282
+ lines.push(` case "$_prev" in`);
283
+ lines.push(...prevCases);
284
+ lines.push(` esac`);
285
+ lines.push(` fi`);
286
+ }
287
+ const inlineCases = optionValueCases$2(options, true);
288
+ if (inlineCases.length > 0) {
289
+ lines.push(` if [[ -n "$_inline_prefix" ]]; then`);
290
+ lines.push(` case "\${_inline_prefix%=}" in`);
291
+ lines.push(...inlineCases);
292
+ lines.push(` esac`);
293
+ lines.push(` fi`);
294
+ }
295
+ return lines;
296
+ }
297
+ /** Generate available-options list lines */
298
+ function availableOptionLines$2(options, fn) {
299
+ const lines = [];
300
+ for (const opt of options) if (opt.valueType === "array") lines.push(` _avail+=(--${opt.cliName})`);
301
+ else {
302
+ const patterns = [`"--${opt.cliName}"`];
303
+ if (opt.alias) patterns.push(`"-${opt.alias}"`);
304
+ lines.push(` __${fn}_not_used ${patterns.join(" ")} && _avail+=(--${opt.cliName})`);
305
+ }
306
+ lines.push(` __${fn}_not_used "--help" && _avail+=(--help)`);
307
+ return lines;
308
+ }
309
+ /**
310
+ * Generate a per-subcommand completion function.
311
+ * Recursively generates functions for nested subcommands.
312
+ */
313
+ function generateSubHandler$2(sub, fn, path) {
314
+ const fullPath = [...path, sub.name];
315
+ const funcName = `__${fn}_complete_${fullPath.map(sanitize).join("_")}`;
316
+ const visibleSubs = getVisibleSubs(sub.subcommands);
317
+ const lines = [];
318
+ for (const child of visibleSubs) lines.push(...generateSubHandler$2(child, fn, fullPath));
319
+ lines.push(`${funcName}() {`);
320
+ lines.push(...valueCompletionBlocks(sub.options));
321
+ lines.push(` if [[ -z "$_inline_prefix" ]] && __${fn}_opt_takes_value "${sub.name}" "$_prev"; then return; fi`);
322
+ lines.push(` if [[ -n "$_inline_prefix" ]] && __${fn}_opt_takes_value "${sub.name}" "\${_inline_prefix%=}"; then return; fi`);
323
+ if (sub.positionals.length > 0) {
324
+ lines.push(` if (( _after_dd )); then`);
325
+ lines.push(...positionalBlock$2(sub.positionals).map((l) => ` ${l}`));
326
+ lines.push(` return`);
327
+ lines.push(` fi`);
328
+ } else lines.push(` if (( _after_dd )); then return; fi`);
329
+ lines.push(` if [[ "$_cur" == -* ]]; then`);
330
+ lines.push(` local -a _avail=()`);
331
+ lines.push(...availableOptionLines$2(sub.options, fn));
332
+ lines.push(` COMPREPLY=($(compgen -W "\${_avail[*]}" -- "$_cur"))`);
333
+ lines.push(` compopt +o default 2>/dev/null`);
334
+ lines.push(` return`);
335
+ lines.push(` fi`);
336
+ if (visibleSubs.length > 0) {
337
+ const subNames = visibleSubs.map((s) => s.name).join(" ");
338
+ lines.push(` COMPREPLY=($(compgen -W "${subNames}" -- "$_cur"))`);
339
+ lines.push(` compopt +o default 2>/dev/null`);
340
+ } else if (sub.positionals.length > 0) lines.push(...positionalBlock$2(sub.positionals));
341
+ lines.push(`}`);
342
+ lines.push(``);
343
+ return lines;
344
+ }
345
+ function generateBashCompletion(command, options) {
346
+ const { programName } = options;
347
+ const data = extractCompletionData(command, programName);
348
+ const fn = sanitize(programName);
349
+ const root = data.command;
350
+ const visibleSubs = getVisibleSubs(root.subcommands);
351
+ const lines = [];
352
+ lines.push(`# Bash completion for ${programName}`);
353
+ lines.push(`# Generated by politty`);
354
+ lines.push(``);
355
+ lines.push(`__${fn}_not_used() {`);
356
+ lines.push(` for _u in "\${_used_opts[@]}"; do`);
357
+ lines.push(` for _chk in "$@"; do`);
358
+ lines.push(` [[ "$_u" == "$_chk" ]] && return 1`);
359
+ lines.push(` done`);
360
+ lines.push(` done`);
361
+ lines.push(` return 0`);
362
+ lines.push(`}`);
363
+ lines.push(``);
364
+ lines.push(`__${fn}_opt_takes_value() {`);
365
+ lines.push(` case "$1:$2" in`);
366
+ lines.push(...optTakesValueEntries(root, ""));
367
+ lines.push(` esac`);
368
+ lines.push(` return 1`);
369
+ lines.push(`}`);
370
+ lines.push(``);
371
+ for (const sub of visibleSubs) lines.push(...generateSubHandler$2(sub, fn, []));
372
+ lines.push(`__${fn}_complete_root() {`);
373
+ lines.push(...valueCompletionBlocks(root.options));
374
+ lines.push(` if [[ -z "$_inline_prefix" ]] && __${fn}_opt_takes_value "" "$_prev"; then return; fi`);
375
+ lines.push(` if [[ -n "$_inline_prefix" ]] && __${fn}_opt_takes_value "" "\${_inline_prefix%=}"; then return; fi`);
376
+ if (root.positionals.length > 0) {
377
+ lines.push(` if (( _after_dd )); then`);
378
+ lines.push(...positionalBlock$2(root.positionals).map((l) => ` ${l}`));
379
+ lines.push(` return`);
380
+ lines.push(` fi`);
381
+ } else lines.push(` if (( _after_dd )); then return; fi`);
382
+ lines.push(` if [[ "$_cur" == -* ]]; then`);
383
+ lines.push(` local -a _avail=()`);
384
+ lines.push(...availableOptionLines$2(root.options, fn));
385
+ lines.push(` COMPREPLY=($(compgen -W "\${_avail[*]}" -- "$_cur"))`);
386
+ lines.push(` compopt +o default 2>/dev/null`);
387
+ if (visibleSubs.length > 0) {
388
+ lines.push(` else`);
389
+ const subNames = visibleSubs.map((s) => s.name).join(" ");
390
+ lines.push(` COMPREPLY=($(compgen -W "${subNames}" -- "$_cur"))`);
391
+ lines.push(` compopt +o default 2>/dev/null`);
392
+ } else if (root.positionals.length > 0) {
393
+ lines.push(` else`);
394
+ lines.push(...positionalBlock$2(root.positionals).map((l) => ` ${l}`));
395
+ }
396
+ lines.push(` fi`);
397
+ lines.push(`}`);
398
+ lines.push(``);
399
+ const subRouting = visibleSubs.map((s) => ` ${s.name}) __${fn}_complete_${sanitize(s.name)} ;;`).join("\n");
400
+ lines.push(`_${fn}_completions() {`);
401
+ lines.push(` COMPREPLY=()`);
402
+ lines.push(``);
403
+ lines.push(` # Rejoin words split by '=' in COMP_WORDBREAKS`);
404
+ lines.push(` local -a _words=()`);
405
+ lines.push(` local _i=1`);
406
+ lines.push(` while (( _i <= COMP_CWORD )); do`);
407
+ lines.push(` if [[ "\${COMP_WORDS[_i]}" == "=" && \${#_words[@]} -gt 0 ]]; then`);
408
+ lines.push(` _words[\${#_words[@]}-1]+="=\${COMP_WORDS[_i+1]:-}"`);
409
+ lines.push(` (( _i += 2 ))`);
410
+ lines.push(` else`);
411
+ lines.push(` _words+=("\${COMP_WORDS[_i]}")`);
412
+ lines.push(` (( _i++ ))`);
413
+ lines.push(` fi`);
414
+ lines.push(` done`);
415
+ lines.push(``);
416
+ lines.push(` local _cur=""`);
417
+ lines.push(` (( \${#_words[@]} > 0 )) && _cur="\${_words[\${#_words[@]}-1]}"`);
418
+ lines.push(``);
419
+ lines.push(` local _inline_prefix=""`);
420
+ lines.push(` if [[ "$_cur" == --*=* ]]; then`);
421
+ lines.push(` _inline_prefix="\${_cur%%=*}="`);
422
+ lines.push(` _cur="\${_cur#*=}"`);
423
+ lines.push(` fi`);
424
+ lines.push(``);
425
+ lines.push(` local _prev=""`);
426
+ lines.push(` (( \${#_words[@]} > 1 )) && _prev="\${_words[\${#_words[@]}-2]}"`);
427
+ lines.push(``);
428
+ lines.push(` local _subcmd="" _after_dd=0 _pos_count=0 _skip_next=0`);
429
+ lines.push(` local -a _used_opts=()`);
430
+ lines.push(``);
431
+ lines.push(` local _j=0`);
432
+ lines.push(` while (( _j < \${#_words[@]} - 1 )); do`);
433
+ lines.push(` local _w="\${_words[_j]}"`);
434
+ lines.push(` if (( _skip_next )); then _skip_next=0; (( _j++ )); continue; fi`);
435
+ lines.push(` if [[ "$_w" == "--" ]]; then _after_dd=1; (( _j++ )); continue; fi`);
436
+ lines.push(` if (( _after_dd )); then (( _pos_count++ )); (( _j++ )); continue; fi`);
437
+ lines.push(` if [[ "$_w" == --*=* ]]; then _used_opts+=("\${_w%%=*}"); (( _j++ )); continue; fi`);
438
+ lines.push(` if [[ "$_w" == -* ]]; then`);
439
+ lines.push(` _used_opts+=("$_w")`);
440
+ lines.push(` __${fn}_opt_takes_value "$_subcmd" "$_w" && _skip_next=1`);
441
+ lines.push(` (( _j++ )); continue`);
442
+ lines.push(` fi`);
443
+ if (visibleSubs.length > 0) lines.push(` if [[ -z "$_subcmd" ]]; then _subcmd="$_w"; _used_opts=(); else (( _pos_count++ )); fi`);
444
+ else lines.push(` (( _pos_count++ ))`);
445
+ lines.push(` (( _j++ ))`);
446
+ lines.push(` done`);
447
+ lines.push(``);
448
+ lines.push(` case "$_subcmd" in`);
449
+ lines.push(subRouting);
450
+ lines.push(` *) __${fn}_complete_root ;;`);
451
+ lines.push(` esac`);
452
+ lines.push(`}`);
453
+ lines.push(``);
454
+ lines.push(`complete -o default -F _${fn}_completions ${programName}`);
455
+ lines.push(``);
456
+ return {
457
+ script: lines.join("\n"),
458
+ shell: "bash",
459
+ installInstructions: `# To enable completions, add the following to your ~/.bashrc:
460
+
461
+ # Option 1: Source directly
462
+ eval "$(${programName} completion bash)"
463
+
464
+ # Option 2: Save to a file
465
+ ${programName} completion bash > ~/.local/share/bash-completion/completions/${programName}
466
+
467
+ # Then reload your shell or run:
468
+ source ~/.bashrc`
469
+ };
470
+ }
471
+
472
+ //#endregion
473
+ //#region src/completion/dynamic/candidate-generator.ts
474
+ /**
475
+ * Generate completion candidates based on context
476
+ */
477
+ /**
478
+ * Completion directive flags (bitwise)
479
+ */
480
+ const CompletionDirective = {
481
+ Default: 0,
482
+ NoSpace: 1,
483
+ NoFileCompletion: 2,
484
+ FilterPrefix: 4,
485
+ KeepOrder: 8,
486
+ FileCompletion: 16,
487
+ DirectoryCompletion: 32,
488
+ Error: 64
489
+ };
490
+ /**
491
+ * Generate completion candidates based on context
492
+ */
493
+ function generateCandidates(context) {
494
+ const candidates = [];
495
+ let directive = CompletionDirective.Default;
496
+ switch (context.completionType) {
497
+ case "subcommand": return generateSubcommandCandidates(context);
498
+ case "option-name": return generateOptionNameCandidates(context);
499
+ case "option-value": return generateOptionValueCandidates(context);
500
+ case "positional": return generatePositionalCandidates(context);
501
+ default: return {
502
+ candidates,
503
+ directive
504
+ };
505
+ }
506
+ }
507
+ /**
508
+ * Execute a shell command and return results as candidates
509
+ */
510
+ function executeShellCommand(command) {
511
+ try {
512
+ return (0, node_child_process.execSync)(command, {
513
+ encoding: "utf-8",
514
+ timeout: 5e3
515
+ }).split("\n").map((line) => line.trim()).filter((line) => line.length > 0).map((line) => ({
516
+ value: line,
517
+ type: "value"
518
+ }));
519
+ } catch {
520
+ return [];
521
+ }
522
+ }
523
+ /**
524
+ * Resolve value completion, executing shell commands and file lookups in JS
525
+ */
526
+ function resolveValueCandidates(vc, candidates, _currentWord, description) {
527
+ let directive = CompletionDirective.FilterPrefix;
528
+ let fileExtensions;
529
+ let fileMatchers;
530
+ switch (vc.type) {
531
+ case "choices":
532
+ if (vc.choices) for (const choice of vc.choices) candidates.push({
533
+ value: choice,
534
+ description,
535
+ type: "value"
536
+ });
537
+ directive |= CompletionDirective.NoFileCompletion;
538
+ break;
539
+ case "file":
540
+ if (vc.matcher && vc.matcher.length > 0) {
541
+ fileMatchers = vc.matcher.filter((m) => m.trim().length > 0);
542
+ if (fileMatchers.length === 0) {
543
+ fileMatchers = void 0;
544
+ directive |= CompletionDirective.FileCompletion;
545
+ }
546
+ } else if (vc.extensions && vc.extensions.length > 0) {
547
+ fileExtensions = Array.from(new Set(vc.extensions.map((ext) => ext.trim().replace(/^\./, "")).filter((ext) => ext.length > 0)));
548
+ if (fileExtensions.length === 0) {
549
+ fileExtensions = void 0;
550
+ directive |= CompletionDirective.FileCompletion;
551
+ }
552
+ } else directive |= CompletionDirective.FileCompletion;
553
+ break;
554
+ case "directory":
555
+ directive |= CompletionDirective.DirectoryCompletion;
556
+ break;
557
+ case "command":
558
+ if (vc.shellCommand) candidates.push(...executeShellCommand(vc.shellCommand));
559
+ directive |= CompletionDirective.NoFileCompletion;
560
+ break;
561
+ case "none":
562
+ directive |= CompletionDirective.NoFileCompletion;
563
+ break;
564
+ }
565
+ return {
566
+ directive,
567
+ fileExtensions,
568
+ fileMatchers
569
+ };
570
+ }
571
+ /**
572
+ * Generate subcommand candidates
573
+ */
574
+ function generateSubcommandCandidates(context) {
575
+ const candidates = [];
576
+ let directive = CompletionDirective.FilterPrefix;
577
+ for (const name of context.subcommands) {
578
+ const sub = context.currentCommand.subCommands?.[name];
579
+ const description = sub ? require_lazy.resolveSubCommandMeta(sub)?.description : void 0;
580
+ candidates.push({
581
+ value: name,
582
+ description,
583
+ type: "subcommand"
584
+ });
585
+ }
586
+ if (candidates.length === 0 || context.currentWord.startsWith("-")) {
587
+ const optionResult = generateOptionNameCandidates(context);
588
+ candidates.push(...optionResult.candidates);
589
+ }
590
+ return {
591
+ candidates,
592
+ directive
593
+ };
594
+ }
595
+ /**
596
+ * Generate option name candidates
597
+ */
598
+ function generateOptionNameCandidates(context) {
599
+ const candidates = [];
600
+ const directive = CompletionDirective.FilterPrefix;
601
+ const availableOptions = context.options.filter((opt) => {
602
+ if (opt.valueType === "array") return true;
603
+ return !context.usedOptions.has(opt.cliName) && !context.usedOptions.has(opt.alias || "");
604
+ });
605
+ for (const opt of availableOptions) candidates.push({
606
+ value: `--${opt.cliName}`,
607
+ description: opt.description,
608
+ type: "option"
609
+ });
610
+ if (!context.usedOptions.has("help")) candidates.push({
611
+ value: "--help",
612
+ description: "Show help information",
613
+ type: "option"
614
+ });
615
+ return {
616
+ candidates,
617
+ directive
618
+ };
619
+ }
620
+ /**
621
+ * Generate option value candidates
622
+ */
623
+ function generateOptionValueCandidates(context) {
624
+ const candidates = [];
625
+ if (!context.targetOption) return {
626
+ candidates,
627
+ directive: CompletionDirective.FilterPrefix
628
+ };
629
+ const vc = context.targetOption.valueCompletion;
630
+ if (!vc) return {
631
+ candidates,
632
+ directive: CompletionDirective.FilterPrefix
633
+ };
634
+ return {
635
+ candidates,
636
+ ...resolveValueCandidates(vc, candidates, context.currentWord)
637
+ };
638
+ }
639
+ /**
640
+ * Generate positional argument candidates
641
+ */
642
+ function generatePositionalCandidates(context) {
643
+ const candidates = [];
644
+ const positionalIndex = context.positionalIndex ?? 0;
645
+ const positional = context.positionals[positionalIndex] ?? (context.positionals.at(-1)?.variadic ? context.positionals.at(-1) : void 0);
646
+ if (!positional) return {
647
+ candidates,
648
+ directive: CompletionDirective.FilterPrefix
649
+ };
650
+ const vc = positional.valueCompletion;
651
+ if (!vc) return {
652
+ candidates,
653
+ directive: CompletionDirective.FilterPrefix
654
+ };
655
+ return {
656
+ candidates,
657
+ ...resolveValueCandidates(vc, candidates, context.currentWord, positional.description)
658
+ };
659
+ }
660
+
661
+ //#endregion
662
+ //#region src/completion/dynamic/context-parser.ts
663
+ /**
664
+ * Parse completion context from partial command line
665
+ */
666
+ /**
667
+ * Extract options from a command
668
+ */
669
+ function extractOptions(command) {
670
+ if (!command.args) return [];
671
+ return require_lazy.extractFields(command.args).fields.filter((field) => !field.positional).map((field) => ({
672
+ name: field.name,
673
+ cliName: field.cliName,
674
+ alias: field.alias,
675
+ description: field.description,
676
+ takesValue: field.type !== "boolean",
677
+ valueType: field.type,
678
+ required: field.required,
679
+ valueCompletion: resolveValueCompletion(field)
680
+ }));
681
+ }
682
+ /**
683
+ * Extract positionals from a command
684
+ */
685
+ function extractPositionalsForContext(command) {
686
+ if (!command.args) return [];
687
+ return require_lazy.extractFields(command.args).fields.filter((field) => field.positional).map((field, index) => ({
688
+ name: field.name,
689
+ cliName: field.cliName,
690
+ position: index,
691
+ description: field.description,
692
+ required: field.required,
693
+ variadic: field.type === "array",
694
+ valueCompletion: resolveValueCompletion(field)
695
+ }));
696
+ }
697
+ /**
698
+ * Get subcommand names from a command
699
+ */
700
+ function getSubcommandNames(command) {
701
+ if (!command.subCommands) return [];
702
+ return Object.keys(command.subCommands).filter((name) => !name.startsWith("__"));
703
+ }
704
+ /**
705
+ * Resolve subcommand by name
706
+ */
707
+ function resolveSubcommand(command, name) {
708
+ if (!command.subCommands) return null;
709
+ const sub = command.subCommands[name];
710
+ if (!sub) return null;
711
+ return require_lazy.resolveSubCommandMeta(sub);
712
+ }
713
+ /**
714
+ * Check if a word is an option (starts with - or --)
715
+ */
716
+ function isOption(word) {
717
+ return word.startsWith("-");
718
+ }
719
+ /**
720
+ * Parse option name from word (e.g., "--foo=bar" -> "foo", "-v" -> "v")
721
+ */
722
+ function parseOptionName(word) {
723
+ if (word.startsWith("--")) {
724
+ const withoutPrefix = word.slice(2);
725
+ const eqIndex = withoutPrefix.indexOf("=");
726
+ return eqIndex >= 0 ? withoutPrefix.slice(0, eqIndex) : withoutPrefix;
727
+ }
728
+ if (word.startsWith("-")) return word.slice(1, 2);
729
+ return word;
730
+ }
731
+ /**
732
+ * Check if option has inline value (e.g., "--foo=bar")
733
+ */
734
+ function hasInlineValue(word) {
735
+ return word.includes("=");
736
+ }
737
+ /**
738
+ * Find option by name or alias
739
+ */
740
+ function findOption(options, nameOrAlias) {
741
+ return options.find((opt) => opt.cliName === nameOrAlias || opt.alias === nameOrAlias);
742
+ }
743
+ /**
744
+ * Parse completion context from command line arguments
745
+ *
746
+ * @param argv - Arguments after the program name (e.g., ["build", "--fo"])
747
+ * @param rootCommand - The root command
748
+ * @returns Completion context
749
+ */
750
+ function parseCompletionContext(argv, rootCommand) {
751
+ let currentCommand = rootCommand;
752
+ const subcommandPath = [];
753
+ const usedOptions = /* @__PURE__ */ new Set();
754
+ let positionalCount = 0;
755
+ let i = 0;
756
+ let options = extractOptions(currentCommand);
757
+ let afterDoubleDash = false;
758
+ while (i < argv.length - 1) {
759
+ const word = argv[i];
760
+ if (!afterDoubleDash && word === "--") {
761
+ afterDoubleDash = true;
762
+ i++;
763
+ continue;
764
+ }
765
+ if (!afterDoubleDash && isOption(word)) {
766
+ const optName = parseOptionName(word);
767
+ const opt = findOption(options, optName);
768
+ if (opt) {
769
+ usedOptions.add(opt.cliName);
770
+ if (opt.alias) usedOptions.add(opt.alias);
771
+ if (opt.takesValue && !hasInlineValue(word)) i++;
772
+ }
773
+ i++;
774
+ continue;
775
+ }
776
+ const subcommand = afterDoubleDash ? null : resolveSubcommand(currentCommand, word);
777
+ if (subcommand) {
778
+ subcommandPath.push(word);
779
+ currentCommand = subcommand;
780
+ options = extractOptions(currentCommand);
781
+ usedOptions.clear();
782
+ positionalCount = 0;
783
+ i++;
784
+ continue;
785
+ }
786
+ positionalCount++;
787
+ i++;
788
+ }
789
+ const currentWord = argv[argv.length - 1] ?? "";
790
+ const previousWord = argv[argv.length - 2] ?? "";
791
+ const positionals = extractPositionalsForContext(currentCommand);
792
+ const subcommands = getSubcommandNames(currentCommand);
793
+ let completionType;
794
+ let targetOption;
795
+ let positionalIndex;
796
+ if (!afterDoubleDash && previousWord && isOption(previousWord) && !hasInlineValue(previousWord)) {
797
+ const optName = parseOptionName(previousWord);
798
+ const opt = findOption(options, optName);
799
+ if (opt && opt.takesValue) {
800
+ completionType = "option-value";
801
+ targetOption = opt;
802
+ } else if (currentWord.startsWith("-")) completionType = "option-name";
803
+ else {
804
+ completionType = determineDefaultCompletionType(currentWord, subcommands, positionals, positionalCount);
805
+ if (completionType === "positional") positionalIndex = positionalCount;
806
+ }
807
+ } else if (!afterDoubleDash && currentWord.startsWith("--") && hasInlineValue(currentWord)) {
808
+ const optName = parseOptionName(currentWord);
809
+ const opt = findOption(options, optName);
810
+ if (opt && opt.takesValue) {
811
+ completionType = "option-value";
812
+ targetOption = opt;
813
+ } else completionType = "option-name";
814
+ } else if (!afterDoubleDash && currentWord.startsWith("-")) completionType = "option-name";
815
+ else {
816
+ completionType = determineDefaultCompletionType(currentWord, subcommands, positionals, positionalCount, afterDoubleDash);
817
+ if (completionType === "positional") positionalIndex = positionalCount;
818
+ }
819
+ return {
820
+ subcommandPath,
821
+ currentCommand,
822
+ currentWord,
823
+ previousWord,
824
+ completionType,
825
+ targetOption,
826
+ positionalIndex,
827
+ options,
828
+ subcommands,
829
+ positionals,
830
+ usedOptions,
831
+ providedPositionalCount: positionalCount
832
+ };
833
+ }
834
+ /**
835
+ * Determine default completion type when not completing an option
836
+ */
837
+ function determineDefaultCompletionType(currentWord, subcommands, positionals, positionalCount, afterDoubleDash) {
838
+ if (afterDoubleDash) return "positional";
839
+ if (subcommands.length > 0) {
840
+ if (subcommands.filter((s) => s.startsWith(currentWord)).length > 0 || currentWord === "") return "subcommand";
841
+ }
842
+ if (positionalCount < positionals.length) return "positional";
843
+ if (positionals.length > 0 && positionals[positionals.length - 1].variadic) return "positional";
844
+ return "subcommand";
845
+ }
846
+
847
+ //#endregion
848
+ //#region src/completion/dynamic/shell-formatter.ts
849
+ /**
850
+ * Format completion candidates for the specified shell
851
+ *
852
+ * @returns Shell-ready output string (lines separated by newline, last line is :directive)
853
+ */
854
+ function formatForShell(result, options) {
855
+ switch (options.shell) {
856
+ case "bash": return formatForBash(result, options);
857
+ case "zsh": return formatForZsh(result, options);
858
+ case "fish": return formatForFish(result, options);
859
+ }
860
+ }
861
+ /**
862
+ * Check if the FilterPrefix directive is set
863
+ */
864
+ function shouldFilterPrefix(directive) {
865
+ return (directive & CompletionDirective.FilterPrefix) !== 0;
866
+ }
867
+ /**
868
+ * Filter candidates by prefix
869
+ */
870
+ function filterByPrefix(candidates, prefix) {
871
+ if (!prefix) return candidates;
872
+ return candidates.filter((c) => c.value.startsWith(prefix));
873
+ }
874
+ /**
875
+ * Append extension metadata and directive to output lines
876
+ */
877
+ function appendMetadata(lines, result) {
878
+ if (result.fileExtensions && result.fileExtensions.length > 0) lines.push(`@ext:${result.fileExtensions.join(",")}`);
879
+ if (result.fileMatchers && result.fileMatchers.length > 0) lines.push(`@matcher:${result.fileMatchers.join(",")}`);
880
+ lines.push(`:${result.directive}`);
881
+ }
882
+ /**
883
+ * Format for bash
884
+ *
885
+ * - Pre-filters candidates by currentWord prefix (replaces compgen -W)
886
+ * - Handles --opt=value inline values by prepending prefix
887
+ * - Outputs plain values only (no descriptions - bash COMPREPLY doesn't support them)
888
+ * - Last line: :directive
889
+ */
890
+ function formatForBash(result, options) {
891
+ let { candidates } = result;
892
+ if (shouldFilterPrefix(result.directive)) candidates = filterByPrefix(candidates, options.currentWord);
893
+ const lines = candidates.map((c) => {
894
+ if (options.inlinePrefix) return `${options.inlinePrefix}${c.value}`;
895
+ return c.value;
896
+ });
897
+ appendMetadata(lines, result);
898
+ return lines.join("\n");
899
+ }
900
+ /**
901
+ * Format for zsh
902
+ *
903
+ * - Outputs value:description pairs for _describe
904
+ * - Colons in values/descriptions are escaped with backslash
905
+ * - Last line: :directive
906
+ */
907
+ function formatForZsh(result, _options) {
908
+ const lines = result.candidates.map((c) => {
909
+ const escapedValue = c.value.replace(/:/g, "\\:");
910
+ if (c.description) return `${escapedValue}:${c.description.replace(/:/g, "\\:")}`;
911
+ return escapedValue;
912
+ });
913
+ appendMetadata(lines, result);
914
+ return lines.join("\n");
915
+ }
916
+ /**
917
+ * Format for fish
918
+ *
919
+ * - Outputs value\tdescription pairs
920
+ * - Last line: :directive
921
+ */
922
+ function formatForFish(result, _options) {
923
+ const lines = result.candidates.map((c) => {
924
+ if (c.description) return `${c.value}\t${c.description}`;
925
+ return c.value;
926
+ });
927
+ appendMetadata(lines, result);
928
+ return lines.join("\n");
929
+ }
930
+
931
+ //#endregion
932
+ //#region src/completion/dynamic/complete-command.ts
933
+ /**
934
+ * Dynamic completion command implementation
935
+ *
936
+ * This creates a hidden `__complete` command that outputs completion candidates
937
+ * for shell scripts to consume. Usage:
938
+ *
939
+ * mycli __complete --shell bash -- build --fo
940
+ * mycli __complete --shell zsh -- plugin add
941
+ *
942
+ * Output format depends on the target shell:
943
+ * bash: plain values (pre-filtered by prefix), last line :directive
944
+ * zsh: value:description pairs, last line :directive
945
+ * fish: value\tdescription pairs, last line :directive
946
+ */
947
+ /**
948
+ * Detect inline option-value prefix (e.g., "--format=" from "--format=json")
949
+ */
950
+ function detectInlinePrefix(currentWord) {
951
+ if (currentWord.startsWith("--") && currentWord.includes("=")) return currentWord.slice(0, currentWord.indexOf("=") + 1);
952
+ }
953
+ /**
954
+ * Schema for the __complete command
955
+ */
956
+ const completeArgsSchema = zod.z.object({
957
+ shell: require_lazy.arg(zod.z.enum([
958
+ "bash",
959
+ "zsh",
960
+ "fish"
961
+ ]), { description: "Target shell for output formatting" }),
962
+ args: require_lazy.arg(zod.z.array(zod.z.string()).default([]), {
963
+ positional: true,
964
+ description: "Arguments to complete",
965
+ variadic: true
966
+ })
967
+ });
968
+ /**
969
+ * Create the dynamic completion command
970
+ *
971
+ * @param rootCommand - The root command to generate completions for
972
+ * @param programName - The program name (optional, defaults to rootCommand.name)
973
+ * @returns A command that outputs completion candidates
974
+ */
975
+ function createDynamicCompleteCommand(rootCommand, _programName) {
976
+ return defineCommand({
977
+ name: "__complete",
978
+ args: completeArgsSchema,
979
+ run(args) {
980
+ const context = parseCompletionContext(args.args, rootCommand);
981
+ const result = generateCandidates(context);
982
+ const inlinePrefix = detectInlinePrefix(context.currentWord);
983
+ const output = formatForShell(result, {
984
+ shell: args.shell,
985
+ currentWord: inlinePrefix ? context.currentWord.slice(inlinePrefix.length) : context.currentWord,
986
+ inlinePrefix
987
+ });
988
+ console.log(output);
989
+ }
990
+ });
991
+ }
992
+ /**
993
+ * Check if a command tree contains the __complete command
994
+ */
995
+ function hasCompleteCommand(command) {
996
+ return Boolean(command.subCommands?.["__complete"]);
997
+ }
998
+
999
+ //#endregion
1000
+ //#region src/completion/fish.ts
1001
+ /** Escape shell-special characters for fish double-quoted strings */
1002
+ function escapeDesc$1(s) {
1003
+ return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$");
1004
+ }
1005
+ /**
1006
+ * Generate fish value completion lines for a ValueCompletion spec.
1007
+ * Each line outputs candidates via echo (tab-separated value\tdescription).
1008
+ */
1009
+ function fishValueLines(vc) {
1010
+ if (!vc) return [];
1011
+ switch (vc.type) {
1012
+ case "choices": return vc.choices.map((c) => `echo "${escapeDesc$1(c)}"`);
1013
+ case "file":
1014
+ if (vc.matcher?.length) return fishMatcherLines(vc.matcher);
1015
+ if (vc.extensions?.length) return fishExtensionLines(vc.extensions);
1016
+ return [`__fish_complete_path "$_cur"`];
1017
+ case "directory": return [`__fish_complete_directories "$_cur"`];
1018
+ case "command": return [
1019
+ `for _v in (${vc.shellCommand})`,
1020
+ ` echo "$_v"`,
1021
+ `end`
1022
+ ];
1023
+ case "none": return [];
1024
+ }
1025
+ }
1026
+ /** Generate fish matcher-filtered file completion */
1027
+ function fishMatcherLines(patterns) {
1028
+ return [
1029
+ `__fish_complete_directories "$_cur"`,
1030
+ `set -l _dir ""`,
1031
+ `if string match -q '*/*' "$_cur"`,
1032
+ ` set _dir (string replace -r '[^/]*$' '' "$_cur")`,
1033
+ `end`,
1034
+ ...patterns.flatMap((p) => [
1035
+ `for _f in "$_dir"${p}`,
1036
+ ` test -f "$_f"; and string match -q "$_cur*" "$_f"; and echo "$_f"`,
1037
+ `end`
1038
+ ])
1039
+ ];
1040
+ }
1041
+ /** Generate fish extension-filtered file completion */
1042
+ function fishExtensionLines(extensions) {
1043
+ const lines = [];
1044
+ lines.push(`__fish_complete_directories "$_cur"`);
1045
+ for (const ext of extensions) {
1046
+ lines.push(`for _f in "$_cur"*.${ext}`);
1047
+ lines.push(` test -f "$_f"; and echo "$_f"`);
1048
+ lines.push(`end`);
1049
+ }
1050
+ return lines;
1051
+ }
1052
+ /** Generate option-value switch cases for fish */
1053
+ function optionValueCases$1(options) {
1054
+ const lines = [];
1055
+ for (const opt of options) {
1056
+ if (!opt.takesValue || !opt.valueCompletion) continue;
1057
+ const valLines = fishValueLines(opt.valueCompletion);
1058
+ if (valLines.length === 0) continue;
1059
+ const conditions = [`test "$_prev" = "--${opt.cliName}"`];
1060
+ if (opt.alias) conditions.push(`test "$_prev" = "-${opt.alias}"`);
1061
+ const cond = conditions.join("; or ");
1062
+ lines.push(` if ${cond}`);
1063
+ for (const vl of valLines) lines.push(` ${vl}`);
1064
+ lines.push(` return`);
1065
+ lines.push(` end`);
1066
+ }
1067
+ return lines;
1068
+ }
1069
+ /** Generate positional completion block for fish */
1070
+ function positionalBlock$1(positionals) {
1071
+ if (positionals.length === 0) return [];
1072
+ const lines = [];
1073
+ for (const pos of positionals) {
1074
+ const valLines = fishValueLines(pos.valueCompletion);
1075
+ if (valLines.length === 0) continue;
1076
+ if (pos.variadic) lines.push(` if test $_pos_count -ge ${pos.position}`);
1077
+ else lines.push(` if test $_pos_count -eq ${pos.position}`);
1078
+ for (const vl of valLines) lines.push(` ${vl}`);
1079
+ lines.push(` return`);
1080
+ lines.push(` end`);
1081
+ }
1082
+ return lines;
1083
+ }
1084
+ /** Generate available-option echo lines for fish */
1085
+ function availableOptionLines$1(options, fn) {
1086
+ const lines = [];
1087
+ for (const opt of options) {
1088
+ const desc = escapeDesc$1(opt.description ?? "");
1089
+ if (opt.valueType === "array") lines.push(` echo "--${opt.cliName}\t${desc}"`);
1090
+ else {
1091
+ const checks = [`"--${opt.cliName}"`];
1092
+ if (opt.alias) checks.push(`"-${opt.alias}"`);
1093
+ lines.push(` __${fn}_not_used ${checks.join(" ")}; and echo "--${opt.cliName}\t${desc}"`);
1094
+ }
1095
+ }
1096
+ lines.push(` __${fn}_not_used "--help"; and echo "--help\tShow help"`);
1097
+ return lines;
1098
+ }
1099
+ /** Generate value-option completion block if any value-taking options exist */
1100
+ function valueCompletionBlock$1(options) {
1101
+ if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];
1102
+ return optionValueCases$1(options);
1103
+ }
1104
+ /**
1105
+ * Generate a per-subcommand completion function for fish.
1106
+ * Recursively generates functions for nested subcommands.
1107
+ */
1108
+ function generateSubHandler$1(sub, fn, path) {
1109
+ const fullPath = [...path, sub.name];
1110
+ const funcName = `__${fn}_complete_${fullPath.map(sanitize).join("_")}`;
1111
+ const visibleSubs = getVisibleSubs(sub.subcommands);
1112
+ const lines = [];
1113
+ for (const child of visibleSubs) lines.push(...generateSubHandler$1(child, fn, fullPath));
1114
+ lines.push(`function ${funcName} --no-scope-shadowing`);
1115
+ lines.push(...valueCompletionBlock$1(sub.options));
1116
+ lines.push(` if __${fn}_opt_takes_value "${sub.name}" "$_prev"; return; end`);
1117
+ if (sub.positionals.length > 0) {
1118
+ lines.push(` if test $_after_dd -eq 1`);
1119
+ lines.push(...positionalBlock$1(sub.positionals).map((l) => ` ${l}`));
1120
+ lines.push(` return`);
1121
+ lines.push(` end`);
1122
+ } else lines.push(` if test $_after_dd -eq 1; return; end`);
1123
+ lines.push(` if string match -q -- '-*' "$_cur"`);
1124
+ lines.push(...availableOptionLines$1(sub.options, fn));
1125
+ lines.push(` return`);
1126
+ lines.push(` end`);
1127
+ if (visibleSubs.length > 0) for (const s of visibleSubs) {
1128
+ const desc = escapeDesc$1(s.description ?? "");
1129
+ lines.push(` echo "${s.name}\t${desc}"`);
1130
+ }
1131
+ else if (sub.positionals.length > 0) lines.push(...positionalBlock$1(sub.positionals));
1132
+ lines.push(`end`);
1133
+ lines.push(``);
1134
+ return lines;
1135
+ }
1136
+ /** Generate opt-takes-value entries for fish switch cases */
1137
+ function optTakesValueCases(sub, subcmdName) {
1138
+ const lines = [];
1139
+ for (const opt of sub.options) if (opt.takesValue) {
1140
+ const patterns = [`"${subcmdName}:--${opt.cliName}"`];
1141
+ if (opt.alias) patterns.push(`"${subcmdName}:-${opt.alias}"`);
1142
+ lines.push(` case ${patterns.join(" ")}`);
1143
+ lines.push(` return 0`);
1144
+ }
1145
+ for (const child of getVisibleSubs(sub.subcommands)) lines.push(...optTakesValueCases(child, child.name));
1146
+ return lines;
1147
+ }
1148
+ function generateFishCompletion(command, options) {
1149
+ const { programName } = options;
1150
+ const data = extractCompletionData(command, programName);
1151
+ const fn = sanitize(programName);
1152
+ const root = data.command;
1153
+ const visibleSubs = getVisibleSubs(root.subcommands);
1154
+ const lines = [];
1155
+ lines.push(`# Fish completion for ${programName}`);
1156
+ lines.push(`# Generated by politty`);
1157
+ lines.push(``);
1158
+ lines.push(`function __${fn}_not_used --no-scope-shadowing`);
1159
+ lines.push(` for _chk in $argv`);
1160
+ lines.push(` if contains -- "$_chk" $_used_opts`);
1161
+ lines.push(` return 1`);
1162
+ lines.push(` end`);
1163
+ lines.push(` end`);
1164
+ lines.push(` return 0`);
1165
+ lines.push(`end`);
1166
+ lines.push(``);
1167
+ lines.push(`function __${fn}_opt_takes_value`);
1168
+ lines.push(` switch "$argv[1]:$argv[2]"`);
1169
+ lines.push(...optTakesValueCases(root, ""));
1170
+ lines.push(` end`);
1171
+ lines.push(` return 1`);
1172
+ lines.push(`end`);
1173
+ lines.push(``);
1174
+ for (const sub of visibleSubs) lines.push(...generateSubHandler$1(sub, fn, []));
1175
+ lines.push(`function __${fn}_complete_root --no-scope-shadowing`);
1176
+ lines.push(...valueCompletionBlock$1(root.options));
1177
+ lines.push(` if __${fn}_opt_takes_value "" "$_prev"; return; end`);
1178
+ if (root.positionals.length > 0) {
1179
+ lines.push(` if test $_after_dd -eq 1`);
1180
+ lines.push(...positionalBlock$1(root.positionals).map((l) => ` ${l}`));
1181
+ lines.push(` return`);
1182
+ lines.push(` end`);
1183
+ } else lines.push(` if test $_after_dd -eq 1; return; end`);
1184
+ lines.push(` if string match -q -- '-*' "$_cur"`);
1185
+ lines.push(...availableOptionLines$1(root.options, fn));
1186
+ if (visibleSubs.length > 0) {
1187
+ lines.push(` else`);
1188
+ for (const s of visibleSubs) {
1189
+ const desc = escapeDesc$1(s.description ?? "");
1190
+ lines.push(` echo "${s.name}\t${desc}"`);
1191
+ }
1192
+ } else if (root.positionals.length > 0) {
1193
+ lines.push(` else`);
1194
+ lines.push(...positionalBlock$1(root.positionals));
1195
+ }
1196
+ lines.push(` end`);
1197
+ lines.push(`end`);
1198
+ lines.push(``);
1199
+ lines.push(`function __fish_${fn}_complete`);
1200
+ lines.push(` set -l _args (commandline -opc)`);
1201
+ lines.push(` set -e _args[1]`);
1202
+ lines.push(``);
1203
+ lines.push(` set -l _ct (commandline -ct)`);
1204
+ lines.push(` if test (count $_ct) -eq 0`);
1205
+ lines.push(` set -a _args ""`);
1206
+ lines.push(` else`);
1207
+ lines.push(` set -a _args $_ct`);
1208
+ lines.push(` end`);
1209
+ lines.push(``);
1210
+ lines.push(` set -l _cur ""`);
1211
+ lines.push(` if test (count $_args) -gt 0`);
1212
+ lines.push(` set _cur "$_args[-1]"`);
1213
+ lines.push(` end`);
1214
+ lines.push(``);
1215
+ lines.push(` set -l _prev ""`);
1216
+ lines.push(` if test (count $_args) -gt 1`);
1217
+ lines.push(` set _prev "$_args[-2]"`);
1218
+ lines.push(` end`);
1219
+ lines.push(``);
1220
+ lines.push(` set -l _subcmd "" ; set -l _after_dd 0 ; set -l _pos_count 0 ; set -l _skip_next 0`);
1221
+ lines.push(` set -l _used_opts`);
1222
+ lines.push(``);
1223
+ lines.push(` set -l _j 1`);
1224
+ lines.push(` set -l _limit (math (count $_args) - 1)`);
1225
+ lines.push(` while test $_j -le $_limit`);
1226
+ lines.push(` set -l _w "$_args[$_j]"`);
1227
+ lines.push(` if test $_skip_next -eq 1; set _skip_next 0; set _j (math $_j + 1); continue; end`);
1228
+ lines.push(` if test "$_w" = "--"; set _after_dd 1; set _j (math $_j + 1); continue; end`);
1229
+ lines.push(` if test $_after_dd -eq 1; set _pos_count (math $_pos_count + 1); set _j (math $_j + 1); continue; end`);
1230
+ lines.push(` if string match -q -- '--*=*' "$_w"; set -a _used_opts (string replace -r '=.*' '' -- "$_w"); set _j (math $_j + 1); continue; end`);
1231
+ lines.push(` if string match -q -- '-*' "$_w"`);
1232
+ lines.push(` set -a _used_opts "$_w"`);
1233
+ lines.push(` __${fn}_opt_takes_value "$_subcmd" "$_w"; and set _skip_next 1`);
1234
+ lines.push(` set _j (math $_j + 1); continue`);
1235
+ lines.push(` end`);
1236
+ if (visibleSubs.length > 0) lines.push(` if test -z "$_subcmd"; set _subcmd "$_w"; set _used_opts; else; set _pos_count (math $_pos_count + 1); end`);
1237
+ else lines.push(` set _pos_count (math $_pos_count + 1)`);
1238
+ lines.push(` set _j (math $_j + 1)`);
1239
+ lines.push(` end`);
1240
+ lines.push(``);
1241
+ lines.push(` switch "$_subcmd"`);
1242
+ for (const s of visibleSubs) lines.push(` case "${s.name}"; __${fn}_complete_${sanitize(s.name)}`);
1243
+ lines.push(` case '*'; __${fn}_complete_root`);
1244
+ lines.push(` end`);
1245
+ lines.push(`end`);
1246
+ lines.push(``);
1247
+ lines.push(`# Clear existing completions`);
1248
+ lines.push(`complete -e -c ${programName}`);
1249
+ lines.push(``);
1250
+ lines.push(`# Register completion`);
1251
+ lines.push(`complete -c ${programName} -f -a '(__fish_${fn}_complete)'`);
1252
+ lines.push(``);
1253
+ return {
1254
+ script: lines.join("\n"),
1255
+ shell: "fish",
1256
+ installInstructions: `# To enable completions, run one of the following:
1257
+
1258
+ # Option 1: Source directly
1259
+ ${programName} completion fish | source
1260
+
1261
+ # Option 2: Save to the fish completions directory
1262
+ ${programName} completion fish > ~/.config/fish/completions/${programName}.fish
1263
+
1264
+ # The completion will be available immediately in new shell sessions.
1265
+ # To use in the current session, run:
1266
+ source ~/.config/fish/completions/${programName}.fish`
1267
+ };
1268
+ }
1269
+
1270
+ //#endregion
1271
+ //#region src/completion/zsh.ts
1272
+ function escapeDesc(s) {
1273
+ return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$").replace(/`/g, "\\`").replace(/:/g, "\\:");
1274
+ }
1275
+ /**
1276
+ * Generate zsh value completion lines for a ValueCompletion spec.
1277
+ * Uses `_vals` array (must be declared in the calling function scope).
1278
+ */
1279
+ function zshValueLines(vc, fn) {
1280
+ if (!vc) return [];
1281
+ switch (vc.type) {
1282
+ case "choices": return [`_vals=(${vc.choices.map((c) => `"${escapeDesc(c)}"`).join(" ")})`, `__${fn}_cdescribe 'completions' _vals`];
1283
+ case "file":
1284
+ if (vc.matcher?.length) return vc.matcher.map((p) => `_files -g "${p}"`);
1285
+ if (vc.extensions?.length) return vc.extensions.map((ext) => `_files -g "*.${ext}"`);
1286
+ return [`_files`];
1287
+ case "directory": return [`_files -/`];
1288
+ case "command": return [`_vals=("\${(@f)$(${vc.shellCommand})}")`, `__${fn}_cdescribe 'completions' _vals`];
1289
+ case "none": return [];
1290
+ }
1291
+ }
1292
+ /** Generate option-value case branches */
1293
+ function optionValueCases(options, fn) {
1294
+ const lines = [];
1295
+ for (const opt of options) {
1296
+ if (!opt.takesValue || !opt.valueCompletion) continue;
1297
+ const valLines = zshValueLines(opt.valueCompletion, fn);
1298
+ if (valLines.length === 0) continue;
1299
+ const patterns = [`--${opt.cliName}`];
1300
+ if (opt.alias) patterns.push(`-${opt.alias}`);
1301
+ lines.push(` ${patterns.join("|")})`);
1302
+ for (const vl of valLines) lines.push(` ${vl}`);
1303
+ lines.push(` return 0 ;;`);
1304
+ }
1305
+ return lines;
1306
+ }
1307
+ /** Generate positional completion block */
1308
+ function positionalBlock(positionals, fn) {
1309
+ if (positionals.length === 0) return [];
1310
+ const lines = [];
1311
+ lines.push(` case "$_pos_count" in`);
1312
+ for (const pos of positionals) {
1313
+ if (pos.variadic) lines.push(` ${pos.position}|*)`);
1314
+ else lines.push(` ${pos.position})`);
1315
+ const valLines = zshValueLines(pos.valueCompletion, fn);
1316
+ for (const vl of valLines) lines.push(` ${vl}`);
1317
+ lines.push(` ;;`);
1318
+ }
1319
+ lines.push(` esac`);
1320
+ return lines;
1321
+ }
1322
+ /** Generate prev-word value completion case block */
1323
+ function valueCompletionBlock(options, fn) {
1324
+ if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];
1325
+ const prevCases = optionValueCases(options, fn);
1326
+ if (prevCases.length === 0) return [];
1327
+ return [
1328
+ ` case "\${words[CURRENT-1]}" in`,
1329
+ ...prevCases,
1330
+ ` esac`
1331
+ ];
1332
+ }
1333
+ /** Generate available-options list lines */
1334
+ function availableOptionLines(options, fn) {
1335
+ const lines = [];
1336
+ for (const opt of options) {
1337
+ const desc = opt.description ? `:${escapeDesc(opt.description)}` : "";
1338
+ if (opt.valueType === "array") lines.push(` _opts+=("--${opt.cliName}${desc}")`);
1339
+ else {
1340
+ const patterns = [`"--${opt.cliName}"`];
1341
+ if (opt.alias) patterns.push(`"-${opt.alias}"`);
1342
+ lines.push(` __${fn}_not_used ${patterns.join(" ")} && _opts+=("--${opt.cliName}${desc}")`);
1343
+ }
1344
+ }
1345
+ lines.push(` __${fn}_not_used "--help" && _opts+=("--help:Show help")`);
1346
+ return lines;
1347
+ }
1348
+ /**
1349
+ * Generate a per-subcommand completion function.
1350
+ * Recursively generates functions for nested subcommands.
1351
+ */
1352
+ function generateSubHandler(sub, fn, path) {
1353
+ const fullPath = [...path, sub.name];
1354
+ const funcName = `__${fn}_complete_${fullPath.map(sanitize).join("_")}`;
1355
+ const visibleSubs = getVisibleSubs(sub.subcommands);
1356
+ const lines = [];
1357
+ for (const child of visibleSubs) lines.push(...generateSubHandler(child, fn, fullPath));
1358
+ lines.push(`${funcName}() {`);
1359
+ lines.push(` local -a _vals=()`);
1360
+ lines.push(...valueCompletionBlock(sub.options, fn));
1361
+ lines.push(` if __${fn}_opt_takes_value "${sub.name}" "\${words[CURRENT-1]}"; then return 0; fi`);
1362
+ if (sub.positionals.length > 0) {
1363
+ lines.push(` if (( _after_dd )); then`);
1364
+ lines.push(...positionalBlock(sub.positionals, fn).map((l) => ` ${l}`));
1365
+ lines.push(` return 0`);
1366
+ lines.push(` fi`);
1367
+ } else lines.push(` if (( _after_dd )); then return 0; fi`);
1368
+ lines.push(` if [[ "\${words[CURRENT]}" == -* ]]; then`);
1369
+ lines.push(` local -a _opts=()`);
1370
+ lines.push(...availableOptionLines(sub.options, fn));
1371
+ lines.push(` __${fn}_cdescribe 'options' _opts`);
1372
+ lines.push(` return 0`);
1373
+ lines.push(` fi`);
1374
+ if (visibleSubs.length > 0) {
1375
+ const subItems = visibleSubs.map((s) => {
1376
+ const desc = s.description ? `:${escapeDesc(s.description)}` : "";
1377
+ return `"${s.name}${desc}"`;
1378
+ }).join(" ");
1379
+ lines.push(` local -a _subs=(${subItems})`);
1380
+ lines.push(` __${fn}_cdescribe 'subcommands' _subs`);
1381
+ } else if (sub.positionals.length > 0) lines.push(...positionalBlock(sub.positionals, fn));
1382
+ lines.push(`}`);
1383
+ lines.push(``);
1384
+ return lines;
1385
+ }
1386
+ function generateZshCompletion(command, options) {
1387
+ const { programName } = options;
1388
+ const data = extractCompletionData(command, programName);
1389
+ const fn = sanitize(programName);
1390
+ const root = data.command;
1391
+ const visibleSubs = getVisibleSubs(root.subcommands);
1392
+ const lines = [];
1393
+ lines.push(`#compdef ${programName}`);
1394
+ lines.push(``);
1395
+ lines.push(`# Zsh completion for ${programName}`);
1396
+ lines.push(`# Generated by politty`);
1397
+ lines.push(``);
1398
+ lines.push(`__${fn}_not_used() {`);
1399
+ lines.push(` local _u _chk`);
1400
+ lines.push(` for _u in "\${_used_opts[@]}"; do`);
1401
+ lines.push(` for _chk in "$@"; do`);
1402
+ lines.push(` [[ "$_u" == "$_chk" ]] && return 1`);
1403
+ lines.push(` done`);
1404
+ lines.push(` done`);
1405
+ lines.push(` return 0`);
1406
+ lines.push(`}`);
1407
+ lines.push(``);
1408
+ lines.push(`__${fn}_cdescribe() {`);
1409
+ lines.push(` _describe "$@" 2>/dev/null && return 0`);
1410
+ lines.push(` shift`);
1411
+ lines.push(` local -a _cd_vals=("\${(@)\${(P)1}%%:*}")`);
1412
+ lines.push(` compadd -a _cd_vals 2>/dev/null`);
1413
+ lines.push(` return 0`);
1414
+ lines.push(`}`);
1415
+ lines.push(``);
1416
+ lines.push(`__${fn}_opt_takes_value() {`);
1417
+ lines.push(` case "$1:$2" in`);
1418
+ lines.push(...optTakesValueEntries(root, ""));
1419
+ lines.push(` esac`);
1420
+ lines.push(` return 1`);
1421
+ lines.push(`}`);
1422
+ lines.push(``);
1423
+ for (const sub of visibleSubs) lines.push(...generateSubHandler(sub, fn, []));
1424
+ lines.push(`__${fn}_complete_root() {`);
1425
+ lines.push(` local -a _vals=()`);
1426
+ lines.push(...valueCompletionBlock(root.options, fn));
1427
+ lines.push(` if __${fn}_opt_takes_value "" "\${words[CURRENT-1]}"; then return 0; fi`);
1428
+ if (root.positionals.length > 0) {
1429
+ lines.push(` if (( _after_dd )); then`);
1430
+ lines.push(...positionalBlock(root.positionals, fn).map((l) => ` ${l}`));
1431
+ lines.push(` return 0`);
1432
+ lines.push(` fi`);
1433
+ } else lines.push(` if (( _after_dd )); then return 0; fi`);
1434
+ lines.push(` if [[ "\${words[CURRENT]}" == -* ]]; then`);
1435
+ lines.push(` local -a _opts=()`);
1436
+ lines.push(...availableOptionLines(root.options, fn));
1437
+ lines.push(` __${fn}_cdescribe 'options' _opts`);
1438
+ if (visibleSubs.length > 0) {
1439
+ lines.push(` else`);
1440
+ const subItems = visibleSubs.map((s) => {
1441
+ const desc = s.description ? `:${escapeDesc(s.description)}` : "";
1442
+ return `"${s.name}${desc}"`;
1443
+ }).join(" ");
1444
+ lines.push(` local -a _subs=(${subItems})`);
1445
+ lines.push(` __${fn}_cdescribe 'subcommands' _subs`);
1446
+ } else if (root.positionals.length > 0) {
1447
+ lines.push(` else`);
1448
+ lines.push(...positionalBlock(root.positionals, fn).map((l) => ` ${l}`));
1449
+ }
1450
+ lines.push(` fi`);
1451
+ lines.push(`}`);
1452
+ lines.push(``);
1453
+ const subRouting = visibleSubs.map((s) => ` ${s.name}) __${fn}_complete_${sanitize(s.name)} ;;`).join("\n");
1454
+ lines.push(`_${fn}() {`);
1455
+ lines.push(` (( CURRENT )) || CURRENT=\${#words}`);
1456
+ lines.push(``);
1457
+ lines.push(` local _subcmd="" _after_dd=0 _pos_count=0 _skip_next=0`);
1458
+ lines.push(` local -a _used_opts=()`);
1459
+ lines.push(``);
1460
+ lines.push(` local _j=2`);
1461
+ lines.push(` while (( _j < CURRENT )); do`);
1462
+ lines.push(` local _w="\${words[_j]}"`);
1463
+ lines.push(` if (( _skip_next )); then _skip_next=0; (( _j++ )); continue; fi`);
1464
+ lines.push(` if [[ "$_w" == "--" ]]; then _after_dd=1; (( _j++ )); continue; fi`);
1465
+ lines.push(` if (( _after_dd )); then (( _pos_count++ )); (( _j++ )); continue; fi`);
1466
+ lines.push(` if [[ "$_w" == --*=* ]]; then _used_opts+=("\${_w%%=*}"); (( _j++ )); continue; fi`);
1467
+ lines.push(` if [[ "$_w" == -* ]]; then`);
1468
+ lines.push(` _used_opts+=("$_w")`);
1469
+ lines.push(` __${fn}_opt_takes_value "$_subcmd" "$_w" && _skip_next=1`);
1470
+ lines.push(` (( _j++ )); continue`);
1471
+ lines.push(` fi`);
1472
+ if (visibleSubs.length > 0) lines.push(` if [[ -z "$_subcmd" ]]; then _subcmd="$_w"; _used_opts=(); else (( _pos_count++ )); fi`);
1473
+ else lines.push(` (( _pos_count++ ))`);
1474
+ lines.push(` (( _j++ ))`);
1475
+ lines.push(` done`);
1476
+ lines.push(``);
1477
+ lines.push(` case "$_subcmd" in`);
1478
+ lines.push(subRouting);
1479
+ lines.push(` *) __${fn}_complete_root ;;`);
1480
+ lines.push(` esac`);
1481
+ lines.push(`}`);
1482
+ lines.push(``);
1483
+ lines.push(`zstyle ':completion:*:*:${programName}:*' file-patterns '%p:globbed-files *(-/):directories'`);
1484
+ lines.push(``);
1485
+ lines.push(`compdef _${fn} ${programName}`);
1486
+ lines.push(``);
1487
+ return {
1488
+ script: lines.join("\n"),
1489
+ shell: "zsh",
1490
+ installInstructions: `# To enable completions, add the following to your ~/.zshrc:
1491
+
1492
+ # Option 1: Source directly (add before compinit)
1493
+ eval "$(${programName} completion zsh)"
1494
+
1495
+ # Option 2: Save to a file in your fpath
1496
+ ${programName} completion zsh > ~/.zsh/completions/_${programName}
1497
+
1498
+ # Make sure your fpath includes the completions directory:
1499
+ # fpath=(~/.zsh/completions $fpath)
1500
+ # autoload -Uz compinit && compinit
1501
+
1502
+ # Then reload your shell or run:
1503
+ source ~/.zshrc`
1504
+ };
1505
+ }
1506
+
1507
+ //#endregion
1508
+ Object.defineProperty(exports, 'CompletionDirective', {
1509
+ enumerable: true,
1510
+ get: function () {
1511
+ return CompletionDirective;
1512
+ }
1513
+ });
1514
+ Object.defineProperty(exports, 'createDynamicCompleteCommand', {
1515
+ enumerable: true,
1516
+ get: function () {
1517
+ return createDynamicCompleteCommand;
1518
+ }
1519
+ });
1520
+ Object.defineProperty(exports, 'defineCommand', {
1521
+ enumerable: true,
1522
+ get: function () {
1523
+ return defineCommand;
1524
+ }
1525
+ });
1526
+ Object.defineProperty(exports, 'extractCompletionData', {
1527
+ enumerable: true,
1528
+ get: function () {
1529
+ return extractCompletionData;
1530
+ }
1531
+ });
1532
+ Object.defineProperty(exports, 'extractPositionals', {
1533
+ enumerable: true,
1534
+ get: function () {
1535
+ return extractPositionals;
1536
+ }
1537
+ });
1538
+ Object.defineProperty(exports, 'formatForShell', {
1539
+ enumerable: true,
1540
+ get: function () {
1541
+ return formatForShell;
1542
+ }
1543
+ });
1544
+ Object.defineProperty(exports, 'generateBashCompletion', {
1545
+ enumerable: true,
1546
+ get: function () {
1547
+ return generateBashCompletion;
1548
+ }
1549
+ });
1550
+ Object.defineProperty(exports, 'generateCandidates', {
1551
+ enumerable: true,
1552
+ get: function () {
1553
+ return generateCandidates;
1554
+ }
1555
+ });
1556
+ Object.defineProperty(exports, 'generateFishCompletion', {
1557
+ enumerable: true,
1558
+ get: function () {
1559
+ return generateFishCompletion;
1560
+ }
1561
+ });
1562
+ Object.defineProperty(exports, 'generateZshCompletion', {
1563
+ enumerable: true,
1564
+ get: function () {
1565
+ return generateZshCompletion;
1566
+ }
1567
+ });
1568
+ Object.defineProperty(exports, 'hasCompleteCommand', {
1569
+ enumerable: true,
1570
+ get: function () {
1571
+ return hasCompleteCommand;
1572
+ }
1573
+ });
1574
+ Object.defineProperty(exports, 'parseCompletionContext', {
1575
+ enumerable: true,
1576
+ get: function () {
1577
+ return parseCompletionContext;
1578
+ }
1579
+ });
1580
+ Object.defineProperty(exports, 'resolveValueCompletion', {
1581
+ enumerable: true,
1582
+ get: function () {
1583
+ return resolveValueCompletion;
1584
+ }
1585
+ });
1586
+ //# sourceMappingURL=zsh-CASZWn0o.cjs.map