politty 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +297 -28
  2. package/dist/arg-registry-ClI2WGgH.d.cts +89 -0
  3. package/dist/arg-registry-ClI2WGgH.d.cts.map +1 -0
  4. package/dist/arg-registry-D4NsqcNZ.d.ts +89 -0
  5. package/dist/arg-registry-D4NsqcNZ.d.ts.map +1 -0
  6. package/dist/augment.cjs +0 -0
  7. package/dist/augment.d.cts +17 -0
  8. package/dist/augment.d.cts.map +1 -0
  9. package/dist/augment.d.ts +17 -0
  10. package/dist/augment.d.ts.map +1 -0
  11. package/dist/augment.js +1 -0
  12. package/dist/command-Bgd-yIwv.cjs +25 -0
  13. package/dist/command-Bgd-yIwv.cjs.map +1 -0
  14. package/dist/command-CvKyk4ag.js +20 -0
  15. package/dist/command-CvKyk4ag.js.map +1 -0
  16. package/dist/completion/index.cjs +595 -0
  17. package/dist/completion/index.cjs.map +1 -0
  18. package/dist/completion/index.d.cts +153 -0
  19. package/dist/completion/index.d.cts.map +1 -0
  20. package/dist/completion/index.d.ts +153 -0
  21. package/dist/completion/index.d.ts.map +1 -0
  22. package/dist/completion/index.js +588 -0
  23. package/dist/completion/index.js.map +1 -0
  24. package/dist/docs/index.cjs +1239 -0
  25. package/dist/docs/index.cjs.map +1 -0
  26. package/dist/docs/index.d.cts +500 -0
  27. package/dist/docs/index.d.cts.map +1 -0
  28. package/dist/docs/index.d.ts +500 -0
  29. package/dist/docs/index.d.ts.map +1 -0
  30. package/dist/docs/index.js +1182 -0
  31. package/dist/docs/index.js.map +1 -0
  32. package/dist/index.cjs +29 -0
  33. package/dist/index.d.cts +478 -0
  34. package/dist/index.d.cts.map +1 -0
  35. package/dist/index.d.ts +478 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +5 -0
  38. package/dist/runner-BZuYiRhi.cjs +1492 -0
  39. package/dist/runner-BZuYiRhi.cjs.map +1 -0
  40. package/dist/runner-D2BXiWtg.cjs +4 -0
  41. package/dist/runner-DceWXOwD.js +1372 -0
  42. package/dist/runner-DceWXOwD.js.map +1 -0
  43. package/dist/runner-KCql2UKz.js +4 -0
  44. package/dist/schema-extractor-B9D3Rf22.cjs +354 -0
  45. package/dist/schema-extractor-B9D3Rf22.cjs.map +1 -0
  46. package/dist/schema-extractor-D-Eo7I77.d.cts +303 -0
  47. package/dist/schema-extractor-D-Eo7I77.d.cts.map +1 -0
  48. package/dist/schema-extractor-Dk5Z0Iei.js +324 -0
  49. package/dist/schema-extractor-Dk5Z0Iei.js.map +1 -0
  50. package/dist/schema-extractor-kkajLb9E.d.ts +303 -0
  51. package/dist/schema-extractor-kkajLb9E.d.ts.map +1 -0
  52. package/dist/subcommand-router-BiSvDXHg.js +153 -0
  53. package/dist/subcommand-router-BiSvDXHg.js.map +1 -0
  54. package/dist/subcommand-router-Vf-0w9P4.cjs +189 -0
  55. package/dist/subcommand-router-Vf-0w9P4.cjs.map +1 -0
  56. package/package.json +108 -6
@@ -0,0 +1,595 @@
1
+ const require_schema_extractor = require('../schema-extractor-B9D3Rf22.cjs');
2
+ const require_command = require('../command-Bgd-yIwv.cjs');
3
+ const require_docs_index = require('../docs/index.cjs');
4
+ let zod = require("zod");
5
+
6
+ //#region src/completion/extractor.ts
7
+ /**
8
+ * Extract completion data from commands
9
+ */
10
+ /**
11
+ * Convert a resolved field to a completable option
12
+ */
13
+ function fieldToOption(field) {
14
+ return {
15
+ name: field.name,
16
+ cliName: field.cliName,
17
+ alias: field.alias,
18
+ description: field.description,
19
+ takesValue: field.type !== "boolean",
20
+ valueType: field.type,
21
+ required: field.required
22
+ };
23
+ }
24
+ /**
25
+ * Extract options from a command's args schema
26
+ */
27
+ function extractOptions(command) {
28
+ if (!command.args) return [];
29
+ return require_schema_extractor.extractFields(command.args).fields.filter((field) => !field.positional).map(fieldToOption);
30
+ }
31
+ /**
32
+ * Extract positional arguments from a command
33
+ */
34
+ function extractPositionals(command) {
35
+ if (!command.args) return [];
36
+ return require_schema_extractor.extractFields(command.args).fields.filter((field) => field.positional);
37
+ }
38
+ /**
39
+ * Extract a completable subcommand from a command
40
+ */
41
+ function extractSubcommand(name, command) {
42
+ const subcommands = [];
43
+ if (command.subCommands) for (const [subName, subCommand] of Object.entries(command.subCommands)) if (typeof subCommand === "function") subcommands.push({
44
+ name: subName,
45
+ description: "(lazy loaded)",
46
+ subcommands: [],
47
+ options: []
48
+ });
49
+ else subcommands.push(extractSubcommand(subName, subCommand));
50
+ return {
51
+ name,
52
+ description: command.description,
53
+ subcommands,
54
+ options: extractOptions(command)
55
+ };
56
+ }
57
+ /**
58
+ * Extract completion data from a command tree
59
+ */
60
+ function extractCompletionData(command, programName) {
61
+ const rootSubcommand = extractSubcommand(programName, command);
62
+ return {
63
+ command: rootSubcommand,
64
+ programName,
65
+ globalOptions: rootSubcommand.options
66
+ };
67
+ }
68
+
69
+ //#endregion
70
+ //#region src/completion/bash.ts
71
+ /**
72
+ * Generate option completions for bash
73
+ */
74
+ function generateOptionCompletions$1(options) {
75
+ const completions = [];
76
+ for (const opt of options) {
77
+ completions.push(`--${opt.cliName}`);
78
+ if (opt.alias) completions.push(`-${opt.alias}`);
79
+ }
80
+ return completions;
81
+ }
82
+ /**
83
+ * Generate subcommand completions for bash
84
+ */
85
+ function generateSubcommandCompletions$1(subcommands) {
86
+ return subcommands.map((sub) => sub.name);
87
+ }
88
+ /**
89
+ * Generate the bash completion script
90
+ */
91
+ function generateBashScript(command, programName, includeDescriptions) {
92
+ const allOptions = collectAllOptions(command);
93
+ const optionList = generateOptionCompletions$1(allOptions).join(" ");
94
+ const subcommandList = generateSubcommandCompletions$1(command.subcommands).join(" ");
95
+ const subcommandCases = buildSubcommandCases(command.subcommands, includeDescriptions);
96
+ return `# Bash completion for ${programName}
97
+ # Generated by politty
98
+
99
+ _${programName}_completions() {
100
+ local cur prev words cword
101
+ _init_completion || return
102
+
103
+ local commands="${subcommandList}"
104
+ local global_opts="${optionList}"
105
+
106
+ # Handle subcommand-specific completions
107
+ local cmd_index=1
108
+ local cmd=""
109
+
110
+ # Find the subcommand
111
+ for ((i=1; i < cword; i++)); do
112
+ case "\${words[i]}" in
113
+ -*)
114
+ # Skip options and their values
115
+ if [[ "\${words[i]}" == *=* ]]; then
116
+ continue
117
+ fi
118
+ # Check if next word is the option's value
119
+ local opt="\${words[i]}"
120
+ case "$opt" in
121
+ ${allOptions.filter((o) => o.takesValue).map((o) => `--${o.cliName}|-${o.alias || ""}`).join("|") || "--*"}
122
+ ((i++))
123
+ ;;
124
+ esac
125
+ ;;
126
+ *)
127
+ # Found a subcommand
128
+ cmd="\${words[i]}"
129
+ cmd_index=$i
130
+ break
131
+ ;;
132
+ esac
133
+ done
134
+
135
+ # Subcommand-specific completions
136
+ case "$cmd" in
137
+ ${subcommandCases}
138
+ *)
139
+ # Root level completions
140
+ if [[ "$cur" == -* ]]; then
141
+ COMPREPLY=($(compgen -W "$global_opts" -- "$cur"))
142
+ else
143
+ COMPREPLY=($(compgen -W "$commands" -- "$cur"))
144
+ fi
145
+ ;;
146
+ esac
147
+
148
+ return 0
149
+ }
150
+
151
+ # Register the completion function
152
+ complete -F _${programName}_completions ${programName}
153
+ `;
154
+ }
155
+ /**
156
+ * Build case statements for subcommand-specific completions
157
+ */
158
+ function buildSubcommandCases(subcommands, includeDescriptions) {
159
+ if (subcommands.length === 0) return "";
160
+ let cases = "";
161
+ for (const sub of subcommands) {
162
+ const completions = [generateOptionCompletions$1(sub.options).join(" "), generateSubcommandCompletions$1(sub.subcommands).join(" ")].filter(Boolean).join(" ");
163
+ cases += ` ${sub.name})\n`;
164
+ cases += ` COMPREPLY=($(compgen -W "${completions}" -- "$cur"))\n`;
165
+ cases += ` ;;\n`;
166
+ if (sub.subcommands.length > 0) {
167
+ const nestedCases = buildSubcommandCases(sub.subcommands, includeDescriptions);
168
+ if (nestedCases) cases += nestedCases;
169
+ }
170
+ }
171
+ return cases;
172
+ }
173
+ /**
174
+ * Collect all options from a command tree
175
+ */
176
+ function collectAllOptions(command) {
177
+ const options = [...command.options];
178
+ for (const sub of command.subcommands) options.push(...collectAllOptions(sub));
179
+ const seen = /* @__PURE__ */ new Set();
180
+ return options.filter((opt) => {
181
+ if (seen.has(opt.name)) return false;
182
+ seen.add(opt.name);
183
+ return true;
184
+ });
185
+ }
186
+ /**
187
+ * Generate bash completion script for a command
188
+ */
189
+ function generateBashCompletion(command, options) {
190
+ const data = extractCompletionData(command, options.programName);
191
+ const includeDescriptions = options.includeDescriptions ?? true;
192
+ return {
193
+ script: generateBashScript(data.command, options.programName, includeDescriptions),
194
+ shell: "bash",
195
+ installInstructions: `# To enable completions, add the following to your ~/.bashrc:
196
+
197
+ # Option 1: Source directly
198
+ eval "$(${options.programName} completion bash)"
199
+
200
+ # Option 2: Save to a file
201
+ ${options.programName} completion bash > ~/.local/share/bash-completion/completions/${options.programName}
202
+
203
+ # Then reload your shell or run:
204
+ source ~/.bashrc`
205
+ };
206
+ }
207
+
208
+ //#endregion
209
+ //#region src/completion/fish.ts
210
+ /**
211
+ * Escape a string for use in fish completion descriptions
212
+ */
213
+ function escapeForFish(str) {
214
+ return str.replace(/'/g, "\\'").replace(/"/g, "\\\"");
215
+ }
216
+ /**
217
+ * Generate completion entries for options
218
+ */
219
+ function generateOptionCompletions(options, programName, condition, includeDescriptions) {
220
+ const completions = [];
221
+ for (const opt of options) {
222
+ let cmd = `complete -c ${programName}`;
223
+ if (condition) cmd += ` -n '${condition}'`;
224
+ cmd += ` -l ${opt.cliName}`;
225
+ if (opt.alias) cmd += ` -s ${opt.alias}`;
226
+ if (opt.takesValue) cmd += " -r";
227
+ else cmd += " -f";
228
+ if (includeDescriptions && opt.description) cmd += ` -d '${escapeForFish(opt.description)}'`;
229
+ completions.push(cmd);
230
+ }
231
+ return completions;
232
+ }
233
+ /**
234
+ * Generate completion entries for subcommands
235
+ */
236
+ function generateSubcommandCompletions(subcommands, programName, condition, includeDescriptions) {
237
+ const completions = [];
238
+ for (const sub of subcommands) {
239
+ let cmd = `complete -c ${programName}`;
240
+ if (condition) cmd += ` -n '${condition}'`;
241
+ cmd += ` -f -a ${sub.name}`;
242
+ if (includeDescriptions && sub.description) cmd += ` -d '${escapeForFish(sub.description)}'`;
243
+ completions.push(cmd);
244
+ }
245
+ return completions;
246
+ }
247
+ /**
248
+ * Generate helper functions for fish
249
+ */
250
+ function generateHelperFunctions(programName) {
251
+ return `# Helper function to check if using subcommand
252
+ function __fish_use_subcommand_${programName}
253
+ set -l cmd (commandline -opc)
254
+ if test (count $cmd) -eq 1
255
+ return 0
256
+ end
257
+ return 1
258
+ end
259
+
260
+ # Helper function to check current subcommand
261
+ function __fish_${programName}_using_command
262
+ set -l cmd (commandline -opc)
263
+ if contains -- $argv[1] $cmd
264
+ return 0
265
+ end
266
+ return 1
267
+ end
268
+ `;
269
+ }
270
+ /**
271
+ * Recursively generate completions for a command and its subcommands
272
+ */
273
+ function generateCommandCompletions(command, programName, includeDescriptions, parentCommands = []) {
274
+ const completions = [];
275
+ const optionCondition = parentCommands.length === 0 ? "" : `__fish_${programName}_using_command ${parentCommands[parentCommands.length - 1]}`;
276
+ const subcommandCondition = parentCommands.length === 0 ? `__fish_use_subcommand_${programName}` : `__fish_${programName}_using_command ${parentCommands[parentCommands.length - 1]}`;
277
+ completions.push(...generateOptionCompletions(command.options, programName, optionCondition, includeDescriptions));
278
+ if (command.subcommands.length > 0) {
279
+ completions.push(...generateSubcommandCompletions(command.subcommands, programName, subcommandCondition, includeDescriptions));
280
+ for (const sub of command.subcommands) completions.push(...generateCommandCompletions(sub, programName, includeDescriptions, [...parentCommands, sub.name]));
281
+ }
282
+ return completions;
283
+ }
284
+ /**
285
+ * Generate the fish completion script
286
+ */
287
+ function generateFishScript(command, programName, includeDescriptions) {
288
+ const helpers = generateHelperFunctions(programName);
289
+ const completions = generateCommandCompletions(command, programName, includeDescriptions);
290
+ return `# Fish completion for ${programName}
291
+ # Generated by politty
292
+
293
+ ${helpers}
294
+
295
+ # Clear existing completions
296
+ complete -e -c ${programName}
297
+
298
+ # Built-in options
299
+ ${[`complete -c ${programName} -l help -s h -d 'Show help information'`, `complete -c ${programName} -l version -d 'Show version information'`].join("\n")}
300
+
301
+ # Command-specific completions
302
+ ${completions.join("\n")}
303
+ `;
304
+ }
305
+ /**
306
+ * Generate fish completion script for a command
307
+ */
308
+ function generateFishCompletion(command, options) {
309
+ const data = extractCompletionData(command, options.programName);
310
+ const includeDescriptions = options.includeDescriptions ?? true;
311
+ return {
312
+ script: generateFishScript(data.command, options.programName, includeDescriptions),
313
+ shell: "fish",
314
+ installInstructions: `# To enable completions, run one of the following:
315
+
316
+ # Option 1: Source directly
317
+ ${options.programName} completion fish | source
318
+
319
+ # Option 2: Save to the fish completions directory
320
+ ${options.programName} completion fish > ~/.config/fish/completions/${options.programName}.fish
321
+
322
+ # The completion will be available immediately in new shell sessions.
323
+ # To use in the current session, run:
324
+ source ~/.config/fish/completions/${options.programName}.fish`
325
+ };
326
+ }
327
+
328
+ //#endregion
329
+ //#region src/completion/zsh.ts
330
+ /**
331
+ * Escape a string for use in zsh completion descriptions
332
+ */
333
+ function escapeForZsh(str) {
334
+ return str.replace(/'/g, "''").replace(/\[/g, "\\[").replace(/\]/g, "\\]");
335
+ }
336
+ /**
337
+ * Generate option specs for zsh _arguments
338
+ */
339
+ function generateOptionSpecs(options, includeDescriptions) {
340
+ const specs = [];
341
+ for (const opt of options) {
342
+ const desc = includeDescriptions && opt.description ? escapeForZsh(opt.description) : "";
343
+ const valueSpec = opt.takesValue ? ":" : "";
344
+ if (desc) specs.push(`'--${opt.cliName}[${desc}]${valueSpec}'`);
345
+ else specs.push(`'--${opt.cliName}${valueSpec}'`);
346
+ if (opt.alias) if (desc) specs.push(`'-${opt.alias}[${desc}]${valueSpec}'`);
347
+ else specs.push(`'-${opt.alias}${valueSpec}'`);
348
+ }
349
+ return specs;
350
+ }
351
+ /**
352
+ * Generate subcommand descriptions for zsh
353
+ */
354
+ function generateSubcommandDescriptions(subcommands, includeDescriptions) {
355
+ if (subcommands.length === 0) return "";
356
+ return subcommands.map((sub) => {
357
+ const desc = includeDescriptions && sub.description ? escapeForZsh(sub.description) : sub.name;
358
+ return `'${sub.name}:${desc}'`;
359
+ }).join("\n ");
360
+ }
361
+ /**
362
+ * Generate a zsh function for a subcommand
363
+ */
364
+ function generateSubcommandFunction(command, programName, includeDescriptions, parentPath = []) {
365
+ const currentPath = [...parentPath, command.name];
366
+ const funcName = parentPath.length === 0 ? `_${programName}` : `_${programName}_${currentPath.slice(1).join("_")}`;
367
+ const optionSpecs = generateOptionSpecs(command.options, includeDescriptions);
368
+ const hasSubcommands = command.subcommands.length > 0;
369
+ let func = `${funcName}() {\n`;
370
+ func += ` local -a args\n`;
371
+ if (hasSubcommands) {
372
+ const subcommandDesc = generateSubcommandDescriptions(command.subcommands, includeDescriptions);
373
+ func += ` local -a subcommands\n`;
374
+ func += ` subcommands=(\n`;
375
+ func += ` ${subcommandDesc}\n`;
376
+ func += ` )\n\n`;
377
+ }
378
+ func += ` args=(\n`;
379
+ if (hasSubcommands) {
380
+ func += ` '1:command:->command'\n`;
381
+ func += ` '*::arg:->args'\n`;
382
+ }
383
+ for (const spec of optionSpecs) func += ` ${spec}\n`;
384
+ func += ` )\n\n`;
385
+ func += ` _arguments -s -S $args\n\n`;
386
+ if (hasSubcommands) {
387
+ func += ` case "$state" in\n`;
388
+ func += ` command)\n`;
389
+ func += ` _describe -t commands 'command' subcommands\n`;
390
+ func += ` ;;\n`;
391
+ func += ` args)\n`;
392
+ func += ` case $words[1] in\n`;
393
+ for (const sub of command.subcommands) {
394
+ const subFuncName = `_${programName}_${[...currentPath.slice(1), sub.name].join("_")}`;
395
+ func += ` ${sub.name})\n`;
396
+ func += ` ${subFuncName}\n`;
397
+ func += ` ;;\n`;
398
+ }
399
+ func += ` esac\n`;
400
+ func += ` ;;\n`;
401
+ func += ` esac\n`;
402
+ }
403
+ func += `}\n`;
404
+ return func;
405
+ }
406
+ /**
407
+ * Collect all subcommand functions recursively
408
+ */
409
+ function collectSubcommandFunctions(command, programName, includeDescriptions, parentPath = []) {
410
+ const functions = [];
411
+ functions.push(generateSubcommandFunction(command, programName, includeDescriptions, parentPath));
412
+ const currentPath = parentPath.length === 0 ? [command.name] : [...parentPath, command.name];
413
+ for (const sub of command.subcommands) functions.push(...collectSubcommandFunctions(sub, programName, includeDescriptions, currentPath));
414
+ return functions;
415
+ }
416
+ /**
417
+ * Generate the zsh completion script
418
+ */
419
+ function generateZshScript(command, programName, includeDescriptions) {
420
+ return `#compdef ${programName}
421
+
422
+ # Zsh completion for ${programName}
423
+ # Generated by politty
424
+
425
+ ${collectSubcommandFunctions(command, programName, includeDescriptions).join("\n")}
426
+
427
+ _${programName} "$@"
428
+ `;
429
+ }
430
+ /**
431
+ * Generate zsh completion script for a command
432
+ */
433
+ function generateZshCompletion(command, options) {
434
+ const data = extractCompletionData(command, options.programName);
435
+ const includeDescriptions = options.includeDescriptions ?? true;
436
+ return {
437
+ script: generateZshScript(data.command, options.programName, includeDescriptions),
438
+ shell: "zsh",
439
+ installInstructions: `# To enable completions, add the following to your ~/.zshrc:
440
+
441
+ # Option 1: Source directly (add before compinit)
442
+ eval "$(${options.programName} completion zsh)"
443
+
444
+ # Option 2: Save to a file in your fpath
445
+ ${options.programName} completion zsh > ~/.zsh/completions/_${options.programName}
446
+
447
+ # Make sure your fpath includes the completions directory:
448
+ # fpath=(~/.zsh/completions $fpath)
449
+ # autoload -Uz compinit && compinit
450
+
451
+ # Then reload your shell or run:
452
+ source ~/.zshrc`
453
+ };
454
+ }
455
+
456
+ //#endregion
457
+ //#region src/completion/index.ts
458
+ /**
459
+ * Shell completion generation module
460
+ *
461
+ * Provides utilities to generate shell completion scripts for bash, zsh, and fish.
462
+ *
463
+ * @example
464
+ * ```typescript
465
+ * import { generateCompletion, createCompletionCommand } from "politty/completion";
466
+ *
467
+ * // Generate completion script directly
468
+ * const result = generateCompletion(myCommand, {
469
+ * shell: "bash",
470
+ * programName: "mycli"
471
+ * });
472
+ * console.log(result.script);
473
+ *
474
+ * // Or add a completion subcommand to your CLI
475
+ * const mainCommand = defineCommand({
476
+ * name: "mycli",
477
+ * subCommands: {
478
+ * completion: createCompletionCommand(myCommand, "mycli")
479
+ * }
480
+ * });
481
+ * ```
482
+ */
483
+ /**
484
+ * Generate completion script for the specified shell
485
+ */
486
+ function generateCompletion(command, options) {
487
+ switch (options.shell) {
488
+ case "bash": return generateBashCompletion(command, options);
489
+ case "zsh": return generateZshCompletion(command, options);
490
+ case "fish": return generateFishCompletion(command, options);
491
+ default: throw new Error(`Unsupported shell: ${options.shell}`);
492
+ }
493
+ }
494
+ /**
495
+ * Get the list of supported shells
496
+ */
497
+ function getSupportedShells() {
498
+ return [
499
+ "bash",
500
+ "zsh",
501
+ "fish"
502
+ ];
503
+ }
504
+ /**
505
+ * Detect the current shell from environment
506
+ */
507
+ function detectShell() {
508
+ const shellName = (process.env.SHELL || "").split("/").pop()?.toLowerCase() || "";
509
+ if (shellName.includes("bash")) return "bash";
510
+ if (shellName.includes("zsh")) return "zsh";
511
+ if (shellName.includes("fish")) return "fish";
512
+ return null;
513
+ }
514
+ /**
515
+ * Schema for the completion command arguments
516
+ */
517
+ const completionArgsSchema = zod.z.object({
518
+ shell: require_schema_extractor.arg(zod.z.enum([
519
+ "bash",
520
+ "zsh",
521
+ "fish"
522
+ ]).optional().describe("Shell type (auto-detected if not specified)"), {
523
+ positional: true,
524
+ description: "Shell type (bash, zsh, or fish)",
525
+ placeholder: "SHELL"
526
+ }),
527
+ instructions: require_schema_extractor.arg(zod.z.boolean().default(false), {
528
+ alias: "i",
529
+ description: "Show installation instructions"
530
+ })
531
+ });
532
+ /**
533
+ * Create a completion subcommand for your CLI
534
+ *
535
+ * This creates a ready-to-use subcommand that generates completion scripts.
536
+ *
537
+ * @example
538
+ * ```typescript
539
+ * const mainCommand = defineCommand({
540
+ * name: "mycli",
541
+ * subCommands: {
542
+ * completion: createCompletionCommand(mainCommand, "mycli")
543
+ * }
544
+ * });
545
+ * ```
546
+ */
547
+ function createCompletionCommand(rootCommand, programName) {
548
+ return require_command.defineCommand({
549
+ name: "completion",
550
+ description: "Generate shell completion script",
551
+ args: completionArgsSchema,
552
+ run(args) {
553
+ const shellType = args.shell || detectShell();
554
+ if (!shellType) {
555
+ console.error("Could not detect shell type. Please specify one of: bash, zsh, fish");
556
+ process.exitCode = 1;
557
+ return;
558
+ }
559
+ const result = generateCompletion(rootCommand, {
560
+ shell: shellType,
561
+ programName,
562
+ includeDescriptions: true
563
+ });
564
+ if (args.instructions) console.log(result.installInstructions);
565
+ else console.log(result.script);
566
+ }
567
+ });
568
+ }
569
+ /**
570
+ * Helper to add completion command to an existing command's subCommands
571
+ *
572
+ * @example
573
+ * ```typescript
574
+ * const command = defineCommand({
575
+ * name: "mycli",
576
+ * subCommands: {
577
+ * ...withCompletionCommand(command, "mycli"),
578
+ * // other subcommands
579
+ * }
580
+ * });
581
+ * ```
582
+ */
583
+ function withCompletionCommand(rootCommand, programName) {
584
+ return { completion: createCompletionCommand(rootCommand, programName) };
585
+ }
586
+
587
+ //#endregion
588
+ exports.createCompletionCommand = createCompletionCommand;
589
+ exports.detectShell = detectShell;
590
+ exports.extractCompletionData = extractCompletionData;
591
+ exports.extractPositionals = extractPositionals;
592
+ exports.generateCompletion = generateCompletion;
593
+ exports.getSupportedShells = getSupportedShells;
594
+ exports.withCompletionCommand = withCompletionCommand;
595
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["extractFields","subcommands: CompletableSubcommand[]","generateOptionCompletions","completions: string[]","generateSubcommandCompletions","completions: string[]","specs: string[]","functions: string[]","z","arg","defineCommand"],"sources":["../../src/completion/extractor.ts","../../src/completion/bash.ts","../../src/completion/fish.ts","../../src/completion/zsh.ts","../../src/completion/index.ts"],"sourcesContent":["/**\n * Extract completion data from commands\n */\n\nimport { extractFields, type ResolvedFieldMeta } from \"../core/schema-extractor.js\";\nimport type { AnyCommand } from \"../types.js\";\nimport type { CompletableOption, CompletableSubcommand, CompletionData } from \"./types.js\";\n\n/**\n * Convert a resolved field to a completable option\n */\nfunction fieldToOption(field: ResolvedFieldMeta): CompletableOption {\n return {\n name: field.name,\n cliName: field.cliName,\n alias: field.alias,\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 };\n}\n\n/**\n * Extract options from a command's args schema\n */\nfunction extractOptions(command: AnyCommand): CompletableOption[] {\n if (!command.args) {\n return [];\n }\n\n const extracted = extractFields(command.args);\n return extracted.fields\n .filter((field) => !field.positional) // Only include flags/options, not positionals\n .map(fieldToOption);\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/**\n * Extract a completable subcommand from a command\n */\nfunction extractSubcommand(name: string, command: AnyCommand): 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 // Skip async subcommands as we can't inspect them statically\n if (typeof subCommand === \"function\") {\n // For async subcommands, add a placeholder\n subcommands.push({\n name: subName,\n description: \"(lazy loaded)\",\n subcommands: [],\n options: [],\n });\n } else {\n subcommands.push(extractSubcommand(subName, subCommand));\n }\n }\n }\n\n return {\n name,\n description: command.description,\n subcommands,\n options: extractOptions(command),\n };\n}\n\n/**\n * Extract completion data from a command tree\n */\nexport function extractCompletionData(command: AnyCommand, programName: string): CompletionData {\n const rootSubcommand = extractSubcommand(programName, command);\n\n return {\n command: rootSubcommand,\n programName,\n // Global options are the options defined on the root command\n globalOptions: rootSubcommand.options,\n };\n}\n","/**\n * Bash completion script generator\n */\n\nimport type { AnyCommand } from \"../types.js\";\nimport { extractCompletionData } from \"./extractor.js\";\nimport type {\n CompletableOption,\n CompletableSubcommand,\n CompletionOptions,\n CompletionResult,\n} from \"./types.js\";\n\n/**\n * Generate option completions for bash\n */\nfunction generateOptionCompletions(options: CompletableOption[]): string[] {\n const completions: string[] = [];\n\n for (const opt of options) {\n completions.push(`--${opt.cliName}`);\n if (opt.alias) {\n completions.push(`-${opt.alias}`);\n }\n }\n\n return completions;\n}\n\n/**\n * Generate subcommand completions for bash\n */\nfunction generateSubcommandCompletions(subcommands: CompletableSubcommand[]): string[] {\n return subcommands.map((sub) => sub.name);\n}\n\n/**\n * Generate the bash completion script\n */\nfunction generateBashScript(\n command: CompletableSubcommand,\n programName: string,\n includeDescriptions: boolean,\n): string {\n const allOptions = collectAllOptions(command);\n\n const optionList = generateOptionCompletions(allOptions).join(\" \");\n const subcommandList = generateSubcommandCompletions(command.subcommands).join(\" \");\n\n // Build subcommand-specific completions\n const subcommandCases = buildSubcommandCases(command.subcommands, includeDescriptions);\n\n return `# Bash completion for ${programName}\n# Generated by politty\n\n_${programName}_completions() {\n local cur prev words cword\n _init_completion || return\n\n local commands=\"${subcommandList}\"\n local global_opts=\"${optionList}\"\n\n # Handle subcommand-specific completions\n local cmd_index=1\n local cmd=\"\"\n\n # Find the subcommand\n for ((i=1; i < cword; i++)); do\n case \"\\${words[i]}\" in\n -*)\n # Skip options and their values\n if [[ \"\\${words[i]}\" == *=* ]]; then\n continue\n fi\n # Check if next word is the option's value\n local opt=\"\\${words[i]}\"\n case \"$opt\" in\n ${\n allOptions\n .filter((o) => o.takesValue)\n .map((o) => `--${o.cliName}|-${o.alias || \"\"}`)\n .join(\"|\") || \"--*\"\n }\n ((i++))\n ;;\n esac\n ;;\n *)\n # Found a subcommand\n cmd=\"\\${words[i]}\"\n cmd_index=$i\n break\n ;;\n esac\n done\n\n # Subcommand-specific completions\n case \"$cmd\" in\n${subcommandCases}\n *)\n # Root level completions\n if [[ \"$cur\" == -* ]]; then\n COMPREPLY=($(compgen -W \"$global_opts\" -- \"$cur\"))\n else\n COMPREPLY=($(compgen -W \"$commands\" -- \"$cur\"))\n fi\n ;;\n esac\n\n return 0\n}\n\n# Register the completion function\ncomplete -F _${programName}_completions ${programName}\n`;\n}\n\n/**\n * Build case statements for subcommand-specific completions\n */\nfunction buildSubcommandCases(\n subcommands: CompletableSubcommand[],\n includeDescriptions: boolean,\n): string {\n if (subcommands.length === 0) {\n return \"\";\n }\n\n let cases = \"\";\n\n for (const sub of subcommands) {\n const options = generateOptionCompletions(sub.options).join(\" \");\n const nestedSubcommands = generateSubcommandCompletions(sub.subcommands).join(\" \");\n const completions = [options, nestedSubcommands].filter(Boolean).join(\" \");\n\n cases += ` ${sub.name})\\n`;\n cases += ` COMPREPLY=($(compgen -W \"${completions}\" -- \"$cur\"))\\n`;\n cases += ` ;;\\n`;\n\n // Add nested subcommand cases if any\n if (sub.subcommands.length > 0) {\n const nestedCases = buildSubcommandCases(sub.subcommands, includeDescriptions);\n if (nestedCases) {\n cases += nestedCases;\n }\n }\n }\n\n return cases;\n}\n\n/**\n * Collect all options from a command tree\n */\nfunction collectAllOptions(command: CompletableSubcommand): CompletableOption[] {\n const options = [...command.options];\n\n for (const sub of command.subcommands) {\n options.push(...collectAllOptions(sub));\n }\n\n // Deduplicate by name\n const seen = new Set<string>();\n return options.filter((opt) => {\n if (seen.has(opt.name)) {\n return false;\n }\n seen.add(opt.name);\n return true;\n });\n}\n\n/**\n * Generate bash completion script for a command\n */\nexport function generateBashCompletion(\n command: AnyCommand,\n options: CompletionOptions,\n): CompletionResult {\n const data = extractCompletionData(command, options.programName);\n const includeDescriptions = options.includeDescriptions ?? true;\n\n const script = generateBashScript(data.command, options.programName, includeDescriptions);\n\n return {\n script,\n shell: \"bash\",\n installInstructions: `# To enable completions, add the following to your ~/.bashrc:\n\n# Option 1: Source directly\neval \"$(${options.programName} completion bash)\"\n\n# Option 2: Save to a file\n${options.programName} completion bash > ~/.local/share/bash-completion/completions/${options.programName}\n\n# Then reload your shell or run:\nsource ~/.bashrc`,\n };\n}\n","/**\n * Fish completion script generator\n */\n\nimport type { AnyCommand } from \"../types.js\";\nimport { extractCompletionData } from \"./extractor.js\";\nimport type {\n CompletableOption,\n CompletableSubcommand,\n CompletionOptions,\n CompletionResult,\n} from \"./types.js\";\n\n/**\n * Escape a string for use in fish completion descriptions\n */\nfunction escapeForFish(str: string): string {\n return str.replace(/'/g, \"\\\\'\").replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Generate completion entries for options\n */\nfunction generateOptionCompletions(\n options: CompletableOption[],\n programName: string,\n condition: string,\n includeDescriptions: boolean,\n): string[] {\n const completions: string[] = [];\n\n for (const opt of options) {\n let cmd = `complete -c ${programName}`;\n\n // Add condition if specified\n if (condition) {\n cmd += ` -n '${condition}'`;\n }\n\n // Add long option\n cmd += ` -l ${opt.cliName}`;\n\n // Add short option if exists\n if (opt.alias) {\n cmd += ` -s ${opt.alias}`;\n }\n\n // Add flag for options that take values\n if (opt.takesValue) {\n cmd += \" -r\"; // Require argument\n } else {\n cmd += \" -f\"; // No argument (flag)\n }\n\n // Add description\n if (includeDescriptions && opt.description) {\n cmd += ` -d '${escapeForFish(opt.description)}'`;\n }\n\n completions.push(cmd);\n }\n\n return completions;\n}\n\n/**\n * Generate completion entries for subcommands\n */\nfunction generateSubcommandCompletions(\n subcommands: CompletableSubcommand[],\n programName: string,\n condition: string,\n includeDescriptions: boolean,\n): string[] {\n const completions: string[] = [];\n\n for (const sub of subcommands) {\n let cmd = `complete -c ${programName}`;\n\n // Add condition\n if (condition) {\n cmd += ` -n '${condition}'`;\n }\n\n // Subcommands are exclusive (no prefix)\n cmd += ` -f -a ${sub.name}`;\n\n // Add description\n if (includeDescriptions && sub.description) {\n cmd += ` -d '${escapeForFish(sub.description)}'`;\n }\n\n completions.push(cmd);\n }\n\n return completions;\n}\n\n/**\n * Generate helper functions for fish\n */\nfunction generateHelperFunctions(programName: string): string {\n return `# Helper function to check if using subcommand\nfunction __fish_use_subcommand_${programName}\n set -l cmd (commandline -opc)\n if test (count $cmd) -eq 1\n return 0\n end\n return 1\nend\n\n# Helper function to check current subcommand\nfunction __fish_${programName}_using_command\n set -l cmd (commandline -opc)\n if contains -- $argv[1] $cmd\n return 0\n end\n return 1\nend\n`;\n}\n\n/**\n * Recursively generate completions for a command and its subcommands\n */\nfunction generateCommandCompletions(\n command: CompletableSubcommand,\n programName: string,\n includeDescriptions: boolean,\n parentCommands: string[] = [],\n): string[] {\n const completions: string[] = [];\n\n // Build condition for this level\n const optionCondition =\n parentCommands.length === 0\n ? \"\"\n : `__fish_${programName}_using_command ${parentCommands[parentCommands.length - 1]}`;\n\n const subcommandCondition =\n parentCommands.length === 0\n ? `__fish_use_subcommand_${programName}`\n : `__fish_${programName}_using_command ${parentCommands[parentCommands.length - 1]}`;\n\n // Add option completions\n completions.push(\n ...generateOptionCompletions(\n command.options,\n programName,\n optionCondition,\n includeDescriptions,\n ),\n );\n\n // Add subcommand completions\n if (command.subcommands.length > 0) {\n completions.push(\n ...generateSubcommandCompletions(\n command.subcommands,\n programName,\n subcommandCondition,\n includeDescriptions,\n ),\n );\n\n // Recursively add completions for subcommands\n for (const sub of command.subcommands) {\n completions.push(\n ...generateCommandCompletions(sub, programName, includeDescriptions, [\n ...parentCommands,\n sub.name,\n ]),\n );\n }\n }\n\n return completions;\n}\n\n/**\n * Generate the fish completion script\n */\nfunction generateFishScript(\n command: CompletableSubcommand,\n programName: string,\n includeDescriptions: boolean,\n): string {\n const helpers = generateHelperFunctions(programName);\n const completions = generateCommandCompletions(command, programName, includeDescriptions);\n\n // Add built-in options (help and version)\n const builtinCompletions = [\n `complete -c ${programName} -l help -s h -d 'Show help information'`,\n `complete -c ${programName} -l version -d 'Show version information'`,\n ];\n\n return `# Fish completion for ${programName}\n# Generated by politty\n\n${helpers}\n\n# Clear existing completions\ncomplete -e -c ${programName}\n\n# Built-in options\n${builtinCompletions.join(\"\\n\")}\n\n# Command-specific completions\n${completions.join(\"\\n\")}\n`;\n}\n\n/**\n * Generate fish completion script for a command\n */\nexport function generateFishCompletion(\n command: AnyCommand,\n options: CompletionOptions,\n): CompletionResult {\n const data = extractCompletionData(command, options.programName);\n const includeDescriptions = options.includeDescriptions ?? true;\n\n const script = generateFishScript(data.command, options.programName, includeDescriptions);\n\n return {\n script,\n shell: \"fish\",\n installInstructions: `# To enable completions, run one of the following:\n\n# Option 1: Source directly\n${options.programName} completion fish | source\n\n# Option 2: Save to the fish completions directory\n${options.programName} completion fish > ~/.config/fish/completions/${options.programName}.fish\n\n# The completion will be available immediately in new shell sessions.\n# To use in the current session, run:\nsource ~/.config/fish/completions/${options.programName}.fish`,\n };\n}\n","/**\n * Zsh completion script generator\n */\n\nimport type { AnyCommand } from \"../types.js\";\nimport { extractCompletionData } from \"./extractor.js\";\nimport type {\n CompletableOption,\n CompletableSubcommand,\n CompletionOptions,\n CompletionResult,\n} from \"./types.js\";\n\n/**\n * Escape a string for use in zsh completion descriptions\n */\nfunction escapeForZsh(str: string): string {\n return str.replace(/'/g, \"''\").replace(/\\[/g, \"\\\\[\").replace(/\\]/g, \"\\\\]\");\n}\n\n/**\n * Generate option specs for zsh _arguments\n */\nfunction generateOptionSpecs(options: CompletableOption[], includeDescriptions: boolean): string[] {\n const specs: string[] = [];\n\n for (const opt of options) {\n const desc = includeDescriptions && opt.description ? escapeForZsh(opt.description) : \"\";\n const valueSpec = opt.takesValue ? \":\" : \"\";\n\n // Long option\n if (desc) {\n specs.push(`'--${opt.cliName}[${desc}]${valueSpec}'`);\n } else {\n specs.push(`'--${opt.cliName}${valueSpec}'`);\n }\n\n // Short option (alias)\n if (opt.alias) {\n if (desc) {\n specs.push(`'-${opt.alias}[${desc}]${valueSpec}'`);\n } else {\n specs.push(`'-${opt.alias}${valueSpec}'`);\n }\n }\n }\n\n return specs;\n}\n\n/**\n * Generate subcommand descriptions for zsh\n */\nfunction generateSubcommandDescriptions(\n subcommands: CompletableSubcommand[],\n includeDescriptions: boolean,\n): string {\n if (subcommands.length === 0) {\n return \"\";\n }\n\n const lines = subcommands.map((sub) => {\n const desc = includeDescriptions && sub.description ? escapeForZsh(sub.description) : sub.name;\n return `'${sub.name}:${desc}'`;\n });\n\n return lines.join(\"\\n \");\n}\n\n/**\n * Generate a zsh function for a subcommand\n */\nfunction generateSubcommandFunction(\n command: CompletableSubcommand,\n programName: string,\n includeDescriptions: boolean,\n parentPath: string[] = [],\n): string {\n const currentPath = [...parentPath, command.name];\n const funcName =\n parentPath.length === 0\n ? `_${programName}`\n : `_${programName}_${currentPath.slice(1).join(\"_\")}`;\n\n const optionSpecs = generateOptionSpecs(command.options, includeDescriptions);\n const hasSubcommands = command.subcommands.length > 0;\n\n let func = `${funcName}() {\\n`;\n func += ` local -a args\\n`;\n\n if (hasSubcommands) {\n const subcommandDesc = generateSubcommandDescriptions(command.subcommands, includeDescriptions);\n func += ` local -a subcommands\\n`;\n func += ` subcommands=(\\n`;\n func += ` ${subcommandDesc}\\n`;\n func += ` )\\n\\n`;\n }\n\n func += ` args=(\\n`;\n\n if (hasSubcommands) {\n func += ` '1:command:->command'\\n`;\n func += ` '*::arg:->args'\\n`;\n }\n\n for (const spec of optionSpecs) {\n func += ` ${spec}\\n`;\n }\n\n func += ` )\\n\\n`;\n\n func += ` _arguments -s -S $args\\n\\n`;\n\n if (hasSubcommands) {\n func += ` case \"$state\" in\\n`;\n func += ` command)\\n`;\n func += ` _describe -t commands 'command' subcommands\\n`;\n func += ` ;;\\n`;\n func += ` args)\\n`;\n func += ` case $words[1] in\\n`;\n\n for (const sub of command.subcommands) {\n const subFuncName = `_${programName}_${[...currentPath.slice(1), sub.name].join(\"_\")}`;\n func += ` ${sub.name})\\n`;\n func += ` ${subFuncName}\\n`;\n func += ` ;;\\n`;\n }\n\n func += ` esac\\n`;\n func += ` ;;\\n`;\n func += ` esac\\n`;\n }\n\n func += `}\\n`;\n\n return func;\n}\n\n/**\n * Collect all subcommand functions recursively\n */\nfunction collectSubcommandFunctions(\n command: CompletableSubcommand,\n programName: string,\n includeDescriptions: boolean,\n parentPath: string[] = [],\n): string[] {\n const functions: string[] = [];\n\n // Generate function for this command\n functions.push(generateSubcommandFunction(command, programName, includeDescriptions, parentPath));\n\n // Generate functions for subcommands\n const currentPath = parentPath.length === 0 ? [command.name] : [...parentPath, command.name];\n\n for (const sub of command.subcommands) {\n functions.push(\n ...collectSubcommandFunctions(sub, programName, includeDescriptions, currentPath),\n );\n }\n\n return functions;\n}\n\n/**\n * Generate the zsh completion script\n */\nfunction generateZshScript(\n command: CompletableSubcommand,\n programName: string,\n includeDescriptions: boolean,\n): string {\n const functions = collectSubcommandFunctions(command, programName, includeDescriptions);\n\n return `#compdef ${programName}\n\n# Zsh completion for ${programName}\n# Generated by politty\n\n${functions.join(\"\\n\")}\n\n_${programName} \"$@\"\n`;\n}\n\n/**\n * Generate zsh completion script for a command\n */\nexport function generateZshCompletion(\n command: AnyCommand,\n options: CompletionOptions,\n): CompletionResult {\n const data = extractCompletionData(command, options.programName);\n const includeDescriptions = options.includeDescriptions ?? true;\n\n const script = generateZshScript(data.command, options.programName, includeDescriptions);\n\n return {\n script,\n shell: \"zsh\",\n installInstructions: `# To enable completions, add the following to your ~/.zshrc:\n\n# Option 1: Source directly (add before compinit)\neval \"$(${options.programName} completion zsh)\"\n\n# Option 2: Save to a file in your fpath\n${options.programName} completion zsh > ~/.zsh/completions/_${options.programName}\n\n# Make sure your fpath includes the completions directory:\n# fpath=(~/.zsh/completions $fpath)\n# autoload -Uz compinit && compinit\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 = defineCommand({\n * name: \"mycli\",\n * subCommands: {\n * completion: createCompletionCommand(myCommand, \"mycli\")\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, Command } from \"../types.js\";\nimport { generateBashCompletion } from \"./bash.js\";\nimport { generateFishCompletion } from \"./fish.js\";\nimport type { CompletionOptions, CompletionResult, ShellType } from \"./types.js\";\nimport { generateZshCompletion } from \"./zsh.js\";\n\n// Re-export types\n// Re-export extractor\nexport { extractCompletionData, extractPositionals } from \"./extractor.js\";\nexport type {\n CompletableOption,\n CompletableSubcommand,\n CompletionData,\n CompletionGenerator,\n CompletionOptions,\n CompletionResult,\n ShellType,\n} from \"./types.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\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});\n\ntype CompletionArgs = z.infer<typeof completionArgsSchema>;\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, \"mycli\")\n * }\n * });\n * ```\n */\nexport function createCompletionCommand(\n rootCommand: AnyCommand,\n programName: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Command<typeof completionArgsSchema, CompletionArgs, any> {\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 const result = generateCompletion(rootCommand, {\n shell: shellType,\n programName,\n includeDescriptions: true,\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 * Helper to add completion command to an existing command's subCommands\n *\n * @example\n * ```typescript\n * const command = defineCommand({\n * name: \"mycli\",\n * subCommands: {\n * ...withCompletionCommand(command, \"mycli\"),\n * // other subcommands\n * }\n * });\n * ```\n */\nexport function withCompletionCommand(\n rootCommand: AnyCommand,\n programName: string,\n): { completion: ReturnType<typeof createCompletionCommand> } {\n return {\n completion: createCompletionCommand(rootCommand, programName),\n };\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAS,cAAc,OAA6C;AAClE,QAAO;EACL,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,OAAO,MAAM;EACb,aAAa,MAAM;EAEnB,YAAY,MAAM,SAAS;EAC3B,WAAW,MAAM;EACjB,UAAU,MAAM;EACjB;;;;;AAMH,SAAS,eAAe,SAA0C;AAChE,KAAI,CAAC,QAAQ,KACX,QAAO,EAAE;AAIX,QADkBA,uCAAc,QAAQ,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