@gunshi/plugin-completion 0.26.3 → 0.27.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,16 +1,1296 @@
1
- import { plugin } from "@gunshi/plugin";
1
+ /*! license ISC
2
+ * @author Bombshell team and Bombshell contributors
3
+ * Bombshell related codes are forked from @bombsh/tab
4
+ */
2
5
 
6
+ import { CLI_OPTIONS_DEFAULT, createCommandContext, plugin } from "@gunshi/plugin";
7
+
8
+ //#region ../../node_modules/.pnpm/args-tokens@0.22.0/node_modules/args-tokens/lib/utils-N7UlhLbz.js
9
+ /**
10
+ * Entry point of utils.
11
+ *
12
+ * Note that this entry point is used by gunshi to import utility functions.
13
+ *
14
+ * @module
15
+ */
16
+ /**
17
+ * @author kazuya kawaguchi (a.k.a. kazupon)
18
+ * @license MIT
19
+ */
20
+ function kebabnize(str) {
21
+ return str.replace(/[A-Z]/g, (match, offset) => (offset > 0 ? "-" : "") + match.toLowerCase());
22
+ }
23
+
24
+ //#endregion
25
+ //#region ../gunshi/src/utils.ts
26
+ function isLazyCommand(cmd) {
27
+ return typeof cmd === "function" && "commandName" in cmd && !!cmd.commandName;
28
+ }
29
+ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
30
+ let command;
31
+ if (isLazyCommand(cmd)) {
32
+ const baseCommand = {
33
+ name: cmd.commandName,
34
+ description: cmd.description,
35
+ args: cmd.args,
36
+ examples: cmd.examples,
37
+ internal: cmd.internal,
38
+ entry: cmd.entry
39
+ };
40
+ if ("resource" in cmd && cmd.resource) baseCommand.resource = cmd.resource;
41
+ command = Object.assign(create(), baseCommand);
42
+ if (needRunResolving) {
43
+ const loaded = await cmd();
44
+ if (typeof loaded === "function") command.run = loaded;
45
+ else if (typeof loaded === "object") {
46
+ if (loaded.run == null) throw new TypeError(`'run' is required in command: ${cmd.name || name}`);
47
+ command.run = loaded.run;
48
+ command.name = loaded.name;
49
+ command.description = loaded.description;
50
+ command.args = loaded.args;
51
+ command.examples = loaded.examples;
52
+ command.internal = loaded.internal;
53
+ command.entry = loaded.entry;
54
+ if ("resource" in loaded && loaded.resource) command.resource = loaded.resource;
55
+ } else throw new TypeError(`Cannot resolve command: ${cmd.name || name}`);
56
+ }
57
+ } else command = Object.assign(create(), cmd);
58
+ if (command.name == null && name) command.name = name;
59
+ return deepFreeze(command);
60
+ }
61
+ function create(obj = null) {
62
+ return Object.create(obj);
63
+ }
64
+ function deepFreeze(obj, ignores = []) {
65
+ if (obj === null || typeof obj !== "object") return obj;
66
+ for (const key of Object.keys(obj)) {
67
+ const value = obj[key];
68
+ if (ignores.includes(key)) continue;
69
+ if (typeof value === "object" && value !== null) deepFreeze(value, ignores);
70
+ }
71
+ return Object.freeze(obj);
72
+ }
73
+
74
+ //#endregion
75
+ //#region ../shared/src/constants.ts
76
+ /**
77
+ * @author kazuya kawaguchi (a.k.a. kazupon)
78
+ * @license MIT
79
+ */
80
+ const BUILT_IN_PREFIX = "_";
81
+ const PLUGIN_PREFIX = "g";
82
+ const ARG_PREFIX = "arg";
83
+ const BUILT_IN_KEY_SEPARATOR = ":";
84
+ const BUILD_IN_PREFIX_AND_KEY_SEPARATOR = `${BUILT_IN_PREFIX}${BUILT_IN_KEY_SEPARATOR}`;
85
+ const ARG_PREFIX_AND_KEY_SEPARATOR = `${ARG_PREFIX}${BUILT_IN_KEY_SEPARATOR}`;
86
+ const ARG_NEGATABLE_PREFIX = "no-";
87
+
88
+ //#endregion
89
+ //#region ../resources/locales/en-US.json
90
+ var COMMAND = "COMMAND";
91
+ var COMMANDS = "COMMANDS";
92
+ var SUBCOMMAND = "SUBCOMMAND";
93
+ var USAGE = "USAGE";
94
+ var ARGUMENTS = "ARGUMENTS";
95
+ var OPTIONS = "OPTIONS";
96
+ var EXAMPLES = "EXAMPLES";
97
+ var FORMORE = "For more info, run any command with the `--help` flag";
98
+ var NEGATABLE = "Negatable of";
99
+ var DEFAULT = "default";
100
+ var CHOICES = "choices";
101
+ var help = "Display this help message";
102
+ var version = "Display this version";
103
+ var en_US_default = {
104
+ COMMAND,
105
+ COMMANDS,
106
+ SUBCOMMAND,
107
+ USAGE,
108
+ ARGUMENTS,
109
+ OPTIONS,
110
+ EXAMPLES,
111
+ FORMORE,
112
+ NEGATABLE,
113
+ DEFAULT,
114
+ CHOICES,
115
+ help,
116
+ version
117
+ };
118
+
119
+ //#endregion
120
+ //#region ../shared/src/utils.ts
121
+ /**
122
+ * Resolve a namespaced key for argument resources.
123
+ * Argument keys are prefixed with "arg:".
124
+ * If the command name is provided, it will be prefixed with the command name (e.g. "cmd1:arg:foo").
125
+ * @param key The argument key to resolve.
126
+ * @param ctx The command context.
127
+ * @returns Prefixed argument key.
128
+ */
129
+ function resolveArgKey(key, ctx) {
130
+ return `${ctx?.name ? `${ctx.name}${BUILT_IN_KEY_SEPARATOR}` : ""}${ARG_PREFIX}${BUILT_IN_KEY_SEPARATOR}${key}`;
131
+ }
132
+ /**
133
+ * Resolve a namespaced key for non-built-in resources.
134
+ * Non-built-in keys are not prefixed with any special characters. If the command name is provided, it will be prefixed with the command name (e.g. "cmd1:foo").
135
+ * @param key The non-built-in key to resolve.
136
+ * @param ctx The command context.
137
+ * @returns Prefixed non-built-in key.
138
+ */
139
+ function resolveKey(key, ctx) {
140
+ return `${ctx?.name ? `${ctx.name}${BUILT_IN_KEY_SEPARATOR}` : ""}${key}`;
141
+ }
142
+ async function resolveExamples(ctx, examples) {
143
+ return typeof examples === "string" ? examples : typeof examples === "function" ? await examples(ctx) : "";
144
+ }
145
+ function namespacedId(id) {
146
+ return `${PLUGIN_PREFIX}${BUILT_IN_KEY_SEPARATOR}${id}`;
147
+ }
148
+ function makeShortLongOptionPair(schema, name, toKebab) {
149
+ const displayName = toKebab || schema.toKebab ? kebabnize(name) : name;
150
+ let key = `--${displayName}`;
151
+ if (schema.short) key = `-${schema.short}, ${key}`;
152
+ return key;
153
+ }
154
+
155
+ //#endregion
156
+ //#region ../shared/src/localization.ts
157
+ /**
158
+ * Create a localizable function for a command.
159
+ * This function will resolve the translation key based on the command context and the provided translation function.
160
+ * @param ctx Command context
161
+ * @param cmd Command
162
+ * @param translate Translation function
163
+ * @returns Localizable function
164
+ */
165
+ function localizable(ctx, cmd, translate) {
166
+ async function localize(key, values) {
167
+ if (translate) return translate(key, values);
168
+ if (key.startsWith(BUILD_IN_PREFIX_AND_KEY_SEPARATOR)) {
169
+ const resKey = key.slice(BUILD_IN_PREFIX_AND_KEY_SEPARATOR.length);
170
+ return en_US_default[resKey] || key;
171
+ }
172
+ const namaspacedArgKey = resolveKey(ARG_PREFIX_AND_KEY_SEPARATOR, ctx);
173
+ if (key.startsWith(namaspacedArgKey)) {
174
+ let argKey = key.slice(namaspacedArgKey.length);
175
+ let negatable = false;
176
+ if (argKey.startsWith(ARG_NEGATABLE_PREFIX)) {
177
+ argKey = argKey.slice(ARG_NEGATABLE_PREFIX.length);
178
+ negatable = true;
179
+ }
180
+ const schema = ctx.args[argKey];
181
+ if (!schema) return argKey;
182
+ return negatable && schema.type === "boolean" && schema.negatable ? `${en_US_default["NEGATABLE"]} ${makeShortLongOptionPair(schema, argKey, ctx.toKebab)}` : schema.description || "";
183
+ }
184
+ if (key === resolveKey("description", ctx)) return "";
185
+ else if (key === resolveKey("examples", ctx)) return await resolveExamples(ctx, cmd.examples);
186
+ else return key;
187
+ }
188
+ return localize;
189
+ }
190
+
191
+ //#endregion
192
+ //#region src/bombshell/bash.ts
193
+ function generate$3(name, exec) {
194
+ const nameForVar = name.replace(/[-:]/g, "_");
195
+ const ShellCompDirectiveError = ShellCompDirective.ShellCompDirectiveError;
196
+ const ShellCompDirectiveNoSpace = ShellCompDirective.ShellCompDirectiveNoSpace;
197
+ const ShellCompDirectiveNoFileComp = ShellCompDirective.ShellCompDirectiveNoFileComp;
198
+ const ShellCompDirectiveFilterFileExt = ShellCompDirective.ShellCompDirectiveFilterFileExt;
199
+ const ShellCompDirectiveFilterDirs = ShellCompDirective.ShellCompDirectiveFilterDirs;
200
+ const ShellCompDirectiveKeepOrder = ShellCompDirective.ShellCompDirectiveKeepOrder;
201
+ return `# bash completion for ${name}
202
+
203
+ # Define shell completion directives
204
+ readonly ShellCompDirectiveError=${ShellCompDirectiveError}
205
+ readonly ShellCompDirectiveNoSpace=${ShellCompDirectiveNoSpace}
206
+ readonly ShellCompDirectiveNoFileComp=${ShellCompDirectiveNoFileComp}
207
+ readonly ShellCompDirectiveFilterFileExt=${ShellCompDirectiveFilterFileExt}
208
+ readonly ShellCompDirectiveFilterDirs=${ShellCompDirectiveFilterDirs}
209
+ readonly ShellCompDirectiveKeepOrder=${ShellCompDirectiveKeepOrder}
210
+
211
+ # Function to debug completion
212
+ __${nameForVar}_debug() {
213
+ if [[ -n \${BASH_COMP_DEBUG_FILE:-} ]]; then
214
+ echo "$*" >> "\${BASH_COMP_DEBUG_FILE}"
215
+ fi
216
+ }
217
+
218
+ # Function to handle completions
219
+ __${nameForVar}_complete() {
220
+ local cur prev words cword
221
+ _get_comp_words_by_ref -n "=:" cur prev words cword
222
+
223
+ local requestComp out directive
224
+
225
+ # Build the command to get completions
226
+ requestComp="${exec} complete -- \${words[@]:1}"
227
+
228
+ # Add an empty parameter if the last parameter is complete
229
+ if [[ -z "$cur" ]]; then
230
+ requestComp="$requestComp ''"
231
+ fi
232
+
233
+ # Get completions from the program
234
+ out=$(eval "$requestComp" 2>/dev/null)
235
+
236
+ # Extract directive if present
237
+ directive=0
238
+ if [[ "$out" == *:* ]]; then
239
+ directive=\${out##*:}
240
+ out=\${out%:*}
241
+ fi
242
+
243
+ # Process completions based on directive
244
+ if [[ $((directive & $ShellCompDirectiveError)) -ne 0 ]]; then
245
+ # Error, no completion
246
+ return
247
+ fi
248
+
249
+ # Apply directives
250
+ if [[ $((directive & $ShellCompDirectiveNoSpace)) -ne 0 ]]; then
251
+ compopt -o nospace
252
+ fi
253
+ if [[ $((directive & $ShellCompDirectiveKeepOrder)) -ne 0 ]]; then
254
+ compopt -o nosort
255
+ fi
256
+ if [[ $((directive & $ShellCompDirectiveNoFileComp)) -ne 0 ]]; then
257
+ compopt +o default
258
+ fi
259
+
260
+ # Handle file extension filtering
261
+ if [[ $((directive & $ShellCompDirectiveFilterFileExt)) -ne 0 ]]; then
262
+ local filter=""
263
+ for ext in $out; do
264
+ filter="$filter|$ext"
265
+ done
266
+ filter="\\.($filter)"
267
+ compopt -o filenames
268
+ COMPREPLY=( $(compgen -f -X "!$filter" -- "$cur") )
269
+ return
270
+ fi
271
+
272
+ # Handle directory filtering
273
+ if [[ $((directive & $ShellCompDirectiveFilterDirs)) -ne 0 ]]; then
274
+ compopt -o dirnames
275
+ COMPREPLY=( $(compgen -d -- "$cur") )
276
+ return
277
+ fi
278
+
279
+ # Process completions
280
+ local IFS=$'\\n'
281
+ local tab=$(printf '\\t')
282
+
283
+ # Parse completions with descriptions
284
+ local completions=()
285
+ while read -r comp; do
286
+ if [[ "$comp" == *$tab* ]]; then
287
+ # Split completion and description
288
+ local value=\${comp%%$tab*}
289
+ local desc=\${comp#*$tab}
290
+ completions+=("$value")
291
+ else
292
+ completions+=("$comp")
293
+ fi
294
+ done <<< "$out"
295
+
296
+ # Return completions
297
+ COMPREPLY=( $(compgen -W "\${completions[*]}" -- "$cur") )
298
+ }
299
+
300
+ # Register completion function
301
+ complete -F __${nameForVar}_complete ${name}
302
+ `;
303
+ }
304
+
305
+ //#endregion
306
+ //#region src/bombshell/fish.ts
307
+ function generate$2(name, exec) {
308
+ const nameForVar = name.replace(/[-:]/g, "_");
309
+ const ShellCompDirectiveError = ShellCompDirective.ShellCompDirectiveError;
310
+ const ShellCompDirectiveNoSpace = ShellCompDirective.ShellCompDirectiveNoSpace;
311
+ const ShellCompDirectiveNoFileComp = ShellCompDirective.ShellCompDirectiveNoFileComp;
312
+ const ShellCompDirectiveFilterFileExt = ShellCompDirective.ShellCompDirectiveFilterFileExt;
313
+ const ShellCompDirectiveFilterDirs = ShellCompDirective.ShellCompDirectiveFilterDirs;
314
+ const ShellCompDirectiveKeepOrder = ShellCompDirective.ShellCompDirectiveKeepOrder;
315
+ return `# fish completion for ${name} -*- shell-script -*-
316
+
317
+ # Define shell completion directives
318
+ set -l ShellCompDirectiveError ${ShellCompDirectiveError}
319
+ set -l ShellCompDirectiveNoSpace ${ShellCompDirectiveNoSpace}
320
+ set -l ShellCompDirectiveNoFileComp ${ShellCompDirectiveNoFileComp}
321
+ set -l ShellCompDirectiveFilterFileExt ${ShellCompDirectiveFilterFileExt}
322
+ set -l ShellCompDirectiveFilterDirs ${ShellCompDirectiveFilterDirs}
323
+ set -l ShellCompDirectiveKeepOrder ${ShellCompDirectiveKeepOrder}
324
+
325
+ function __${nameForVar}_debug
326
+ set -l file "$BASH_COMP_DEBUG_FILE"
327
+ if test -n "$file"
328
+ echo "$argv" >> $file
329
+ end
330
+ end
331
+
332
+ function __${nameForVar}_perform_completion
333
+ __${nameForVar}_debug "Starting __${nameForVar}_perform_completion"
334
+
335
+ # Extract all args except the completion flag
336
+ set -l args (string match -v -- "--completion=" (commandline -opc))
337
+
338
+ # Extract the current token being completed
339
+ set -l current_token (commandline -ct)
340
+
341
+ # Check if current token starts with a dash
342
+ set -l flag_prefix ""
343
+ if string match -q -- "-*" $current_token
344
+ set flag_prefix "--flag="
345
+ end
346
+
347
+ __${nameForVar}_debug "Current token: $current_token"
348
+ __${nameForVar}_debug "All args: $args"
349
+
350
+ # Call the completion program and get the results
351
+ set -l requestComp "${exec} complete -- $args"
352
+ __${nameForVar}_debug "Calling $requestComp"
353
+ set -l results (eval $requestComp 2> /dev/null)
354
+
355
+ # Some programs may output extra empty lines after the directive.
356
+ # Let's ignore them or else it will break completion.
357
+ # Ref: https://github.com/spf13/cobra/issues/1279
358
+ for line in $results[-1..1]
359
+ if test (string sub -s 1 -l 1 -- $line) = ":"
360
+ # The directive
361
+ set -l directive (string sub -s 2 -- $line)
362
+ set -l directive_num (math $directive)
363
+ break
364
+ end
365
+ end
366
+
367
+ # No directive specified, use default
368
+ if not set -q directive_num
369
+ set directive_num 0
370
+ end
371
+
372
+ __${nameForVar}_debug "Directive: $directive_num"
373
+
374
+ # Process completions based on directive
375
+ if test $directive_num -eq $ShellCompDirectiveError
376
+ # Error code. No completion.
377
+ __${nameForVar}_debug "Received error directive: aborting."
378
+ return 1
379
+ end
380
+
381
+ # Filter out the directive (last line)
382
+ if test (count $results) -gt 0 -a (string sub -s 1 -l 1 -- $results[-1]) = ":"
383
+ set results $results[1..-2]
384
+ end
385
+
386
+ # No completions, let fish handle file completions unless forbidden
387
+ if test (count $results) -eq 0
388
+ if test $directive_num -ne $ShellCompDirectiveNoFileComp
389
+ __${nameForVar}_debug "No completions, performing file completion"
390
+ return 1
391
+ end
392
+ __${nameForVar}_debug "No completions, but file completion forbidden"
393
+ return 0
394
+ end
395
+
396
+ # Filter file extensions
397
+ if test $directive_num -eq $ShellCompDirectiveFilterFileExt
398
+ __${nameForVar}_debug "File extension filtering"
399
+ set -l file_extensions
400
+ for item in $results
401
+ if test -n "$item" -a (string sub -s 1 -l 1 -- $item) != "-"
402
+ set -a file_extensions "*$item"
403
+ end
404
+ end
405
+ __${nameForVar}_debug "File extensions: $file_extensions"
406
+
407
+ # Use the file extensions as completions
408
+ set -l completions
409
+ for ext in $file_extensions
410
+ # Get all files matching the extension
411
+ set -a completions (string replace -r '^.*/' '' -- $ext)
412
+ end
413
+
414
+ for item in $completions
415
+ echo -e "$item\t"
416
+ end
417
+ return 0
418
+ end
419
+
420
+ # Filter directories
421
+ if test $directive_num -eq $ShellCompDirectiveFilterDirs
422
+ __${nameForVar}_debug "Directory filtering"
423
+ set -l dirs
424
+ for item in $results
425
+ if test -d "$item"
426
+ set -a dirs "$item/"
427
+ end
428
+ end
429
+
430
+ for item in $dirs
431
+ echo -e "$item\t"
432
+ end
433
+ return 0
434
+ end
435
+
436
+ # Process remaining completions
437
+ for item in $results
438
+ if test -n "$item"
439
+ # Check if the item has a description
440
+ if string match -q "*\t*" -- "$item"
441
+ set -l completion_parts (string split \t -- "$item")
442
+ set -l comp $completion_parts[1]
443
+ set -l desc $completion_parts[2]
444
+
445
+ # Add the completion and description
446
+ echo -e "$comp\t$desc"
447
+ else
448
+ # Add just the completion
449
+ echo -e "$item\t"
450
+ end
451
+ end
452
+ end
453
+
454
+ # If directive contains NoSpace, tell fish not to add a space after completion
455
+ if test (math "$directive_num & $ShellCompDirectiveNoSpace") -ne 0
456
+ return 2
457
+ end
458
+
459
+ return 0
460
+ end
461
+
462
+ # Set up the completion for the ${name} command
463
+ complete -c ${name} -f -a "(eval __${nameForVar}_perform_completion)"
464
+ `;
465
+ }
466
+
467
+ //#endregion
468
+ //#region src/bombshell/powershell.ts
469
+ function generate$1(name, exec, _includeDesc = false) {
470
+ const nameForVar = name.replace(/[-:]/g, "_");
471
+ const ShellCompDirectiveError = ShellCompDirective.ShellCompDirectiveError;
472
+ const ShellCompDirectiveNoSpace = ShellCompDirective.ShellCompDirectiveNoSpace;
473
+ const ShellCompDirectiveNoFileComp = ShellCompDirective.ShellCompDirectiveNoFileComp;
474
+ const ShellCompDirectiveFilterFileExt = ShellCompDirective.ShellCompDirectiveFilterFileExt;
475
+ const ShellCompDirectiveFilterDirs = ShellCompDirective.ShellCompDirectiveFilterDirs;
476
+ const ShellCompDirectiveKeepOrder = ShellCompDirective.ShellCompDirectiveKeepOrder;
477
+ return `# powershell completion for ${name} -*- shell-script -*-
478
+
479
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
480
+ function __${name}_debug {
481
+ if ($env:BASH_COMP_DEBUG_FILE) {
482
+ "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"
483
+ }
484
+ }
485
+
486
+ filter __${name}_escapeStringWithSpecialChars {
487
+ $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|"|\\||<|>|&','\`$&'
488
+ }
489
+
490
+ [scriptblock]$__${nameForVar}CompleterBlock = {
491
+ param(
492
+ $WordToComplete,
493
+ $CommandAst,
494
+ $CursorPosition
495
+ )
496
+
497
+ # Get the current command line and convert into a string
498
+ $Command = $CommandAst.CommandElements
499
+ $Command = "$Command"
500
+
501
+ __${name}_debug ""
502
+ __${name}_debug "========= starting completion logic =========="
503
+ __${name}_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition"
504
+
505
+ # The user could have moved the cursor backwards on the command-line.
506
+ # We need to trigger completion from the $CursorPosition location, so we need
507
+ # to truncate the command-line ($Command) up to the $CursorPosition location.
508
+ # Make sure the $Command is longer then the $CursorPosition before we truncate.
509
+ # This happens because the $Command does not include the last space.
510
+ if ($Command.Length -gt $CursorPosition) {
511
+ $Command = $Command.Substring(0, $CursorPosition)
512
+ }
513
+ __${name}_debug "Truncated command: $Command"
514
+
515
+ $ShellCompDirectiveError=${ShellCompDirectiveError}
516
+ $ShellCompDirectiveNoSpace=${ShellCompDirectiveNoSpace}
517
+ $ShellCompDirectiveNoFileComp=${ShellCompDirectiveNoFileComp}
518
+ $ShellCompDirectiveFilterFileExt=${ShellCompDirectiveFilterFileExt}
519
+ $ShellCompDirectiveFilterDirs=${ShellCompDirectiveFilterDirs}
520
+ $ShellCompDirectiveKeepOrder=${ShellCompDirectiveKeepOrder}
521
+
522
+ # Prepare the command to request completions for the program.
523
+ # Split the command at the first space to separate the program and arguments.
524
+ $Program, $Arguments = $Command.Split(" ", 2)
525
+
526
+ $RequestComp = "& ${exec} complete -- $Arguments"
527
+ __${name}_debug "RequestComp: $RequestComp"
528
+
529
+ # we cannot use $WordToComplete because it
530
+ # has the wrong values if the cursor was moved
531
+ # so use the last argument
532
+ if ($WordToComplete -ne "" ) {
533
+ $WordToComplete = $Arguments.Split(" ")[-1]
534
+ }
535
+ __${name}_debug "New WordToComplete: $WordToComplete"
536
+
537
+
538
+ # Check for flag with equal sign
539
+ $IsEqualFlag = ($WordToComplete -Like "--*=*" )
540
+ if ( $IsEqualFlag ) {
541
+ __${name}_debug "Completing equal sign flag"
542
+ # Remove the flag part
543
+ $Flag, $WordToComplete = $WordToComplete.Split("=", 2)
544
+ }
545
+
546
+ if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) {
547
+ # If the last parameter is complete (there is a space following it)
548
+ # We add an extra empty parameter so we can indicate this to the go method.
549
+ __${name}_debug "Adding extra empty parameter"
550
+ # PowerShell 7.2+ changed the way how the arguments are passed to executables,
551
+ # so for pre-7.2 or when Legacy argument passing is enabled we need to use
552
+ if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or
553
+ ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or
554
+ (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and
555
+ $PSNativeCommandArgumentPassing -eq 'Legacy')) {
556
+ $RequestComp="$RequestComp" + ' \`"\`"'
557
+ } else {
558
+ $RequestComp = "$RequestComp" + ' ""'
559
+ }
560
+ }
561
+
562
+ __${name}_debug "Calling $RequestComp"
563
+ # First disable ActiveHelp which is not supported for Powershell
564
+ $env:ActiveHelp = 0
565
+
566
+ # call the command store the output in $out and redirect stderr and stdout to null
567
+ # $Out is an array contains each line per element
568
+ Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null
569
+
570
+ # get directive from last line
571
+ [int]$Directive = $Out[-1].TrimStart(':')
572
+ if ($Directive -eq "") {
573
+ # There is no directive specified
574
+ $Directive = 0
575
+ }
576
+ __${name}_debug "The completion directive is: $Directive"
577
+
578
+ # remove directive (last element) from out
579
+ $Out = $Out | Where-Object { $_ -ne $Out[-1] }
580
+ __${name}_debug "The completions are: $Out"
581
+
582
+ if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {
583
+ # Error code. No completion.
584
+ __${name}_debug "Received error from custom completion go code"
585
+ return
586
+ }
587
+
588
+ $Longest = 0
589
+ [Array]$Values = $Out | ForEach-Object {
590
+ # Split the output in name and description
591
+ $Name, $Description = $_.Split("\`t", 2)
592
+ __${name}_debug "Name: $Name Description: $Description"
593
+
594
+ # Look for the longest completion so that we can format things nicely
595
+ if ($Longest -lt $Name.Length) {
596
+ $Longest = $Name.Length
597
+ }
598
+
599
+ # Set the description to a one space string if there is none set.
600
+ # This is needed because the CompletionResult does not accept an empty string as argument
601
+ if (-Not $Description) {
602
+ $Description = " "
603
+ }
604
+ @{ Name = "$Name"; Description = "$Description" }
605
+ }
606
+
607
+
608
+ $Space = " "
609
+ if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {
610
+ # remove the space here
611
+ __${name}_debug "ShellCompDirectiveNoSpace is called"
612
+ $Space = ""
613
+ }
614
+
615
+ if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or
616
+ (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {
617
+ __${name}_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"
618
+
619
+ # return here to prevent the completion of the extensions
620
+ return
621
+ }
622
+
623
+ $Values = $Values | Where-Object {
624
+ # filter the result
625
+ $_.Name -like "$WordToComplete*"
626
+
627
+ # Join the flag back if we have an equal sign flag
628
+ if ( $IsEqualFlag ) {
629
+ __${name}_debug "Join the equal sign flag back to the completion value"
630
+ $_.Name = $Flag + "=" + $_.Name
631
+ }
632
+ }
633
+
634
+ # we sort the values in ascending order by name if keep order isn't passed
635
+ if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {
636
+ $Values = $Values | Sort-Object -Property Name
637
+ }
638
+
639
+ if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
640
+ __${name}_debug "ShellCompDirectiveNoFileComp is called"
641
+
642
+ if ($Values.Length -eq 0) {
643
+ # Just print an empty string here so the
644
+ # shell does not start to complete paths.
645
+ # We cannot use CompletionResult here because
646
+ # it does not accept an empty string as argument.
647
+ ""
648
+ return
649
+ }
650
+ }
651
+
652
+ # Get the current mode
653
+ $Mode = (Get-PSReadLineKeyHandler | Where-Object { $_.Key -eq "Tab" }).Function
654
+ __${name}_debug "Mode: $Mode"
655
+
656
+ $Values | ForEach-Object {
657
+
658
+ # store temporary because switch will overwrite $_
659
+ $comp = $_
660
+
661
+ # PowerShell supports three different completion modes
662
+ # - TabCompleteNext (default windows style - on each key press the next option is displayed)
663
+ # - Complete (works like bash)
664
+ # - MenuComplete (works like zsh)
665
+ # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>
666
+
667
+ # CompletionResult Arguments:
668
+ # 1) CompletionText text to be used as the auto completion result
669
+ # 2) ListItemText text to be displayed in the suggestion list
670
+ # 3) ResultType type of completion result
671
+ # 4) ToolTip text for the tooltip with details about the object
672
+
673
+ switch ($Mode) {
674
+
675
+ # bash like
676
+ "Complete" {
677
+
678
+ if ($Values.Length -eq 1) {
679
+ __${name}_debug "Only one completion left"
680
+
681
+ # insert space after value
682
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __${name}_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
683
+
684
+ } else {
685
+ # Add the proper number of spaces to align the descriptions
686
+ while($comp.Name.Length -lt $Longest) {
687
+ $comp.Name = $comp.Name + " "
688
+ }
689
+
690
+ # Check for empty description and only add parentheses if needed
691
+ if ($($comp.Description) -eq " " ) {
692
+ $Description = ""
693
+ } else {
694
+ $Description = " ($($comp.Description))"
695
+ }
696
+
697
+ [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
698
+ }
699
+ }
700
+
701
+ # zsh like
702
+ "MenuComplete" {
703
+ # insert space after value
704
+ # MenuComplete will automatically show the ToolTip of
705
+ # the highlighted value at the bottom of the suggestions.
706
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __${name}_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
707
+ }
708
+
709
+ # TabCompleteNext and in case we get something unknown
710
+ Default {
711
+ # Like MenuComplete but we don't want to add a space here because
712
+ # the user need to press space anyway to get the completion.
713
+ # Description will not be shown because that's not possible with TabCompleteNext
714
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __${name}_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
715
+ }
716
+ }
717
+
718
+ }
719
+ }
720
+
721
+ Register-ArgumentCompleter -CommandName '${name}' -ScriptBlock $__${nameForVar}CompleterBlock
722
+ `;
723
+ }
724
+
725
+ //#endregion
726
+ //#region src/bombshell/zsh.ts
727
+ function generate(name, exec) {
728
+ return `#compdef ${name}
729
+ compdef _${name} ${name}
730
+
731
+ # zsh completion for ${name} -*- shell-script -*-
732
+
733
+ __${name}_debug() {
734
+ local file="$BASH_COMP_DEBUG_FILE"
735
+ if [[ -n \${file} ]]; then
736
+ echo "$*" >> "\${file}"
737
+ fi
738
+ }
739
+
740
+ _${name}() {
741
+ local shellCompDirectiveError=${ShellCompDirective.ShellCompDirectiveError}
742
+ local shellCompDirectiveNoSpace=${ShellCompDirective.ShellCompDirectiveNoSpace}
743
+ local shellCompDirectiveNoFileComp=${ShellCompDirective.ShellCompDirectiveNoFileComp}
744
+ local shellCompDirectiveFilterFileExt=${ShellCompDirective.ShellCompDirectiveFilterFileExt}
745
+ local shellCompDirectiveFilterDirs=${ShellCompDirective.ShellCompDirectiveFilterDirs}
746
+ local shellCompDirectiveKeepOrder=${ShellCompDirective.ShellCompDirectiveKeepOrder}
747
+
748
+ local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder
749
+ local -a completions
750
+
751
+ __${name}_debug "\\n========= starting completion logic =========="
752
+ __${name}_debug "CURRENT: \${CURRENT}, words[*]: \${words[*]}"
753
+
754
+ # The user could have moved the cursor backwards on the command-line.
755
+ # We need to trigger completion from the $CURRENT location, so we need
756
+ # to truncate the command-line ($words) up to the $CURRENT location.
757
+ # (We cannot use $CURSOR as its value does not work when a command is an alias.)
758
+ words=( "\${=words[1,CURRENT]}" )
759
+ __${name}_debug "Truncated words[*]: \${words[*]},"
760
+
761
+ lastParam=\${words[-1]}
762
+ lastChar=\${lastParam[-1]}
763
+ __${name}_debug "lastParam: \${lastParam}, lastChar: \${lastChar}"
764
+
765
+ # For zsh, when completing a flag with an = (e.g., ${name} -n=<TAB>)
766
+ # completions must be prefixed with the flag
767
+ setopt local_options BASH_REMATCH
768
+ if [[ "\${lastParam}" =~ '-.*=' ]]; then
769
+ # We are dealing with a flag with an =
770
+ flagPrefix="-P \${BASH_REMATCH}"
771
+ fi
772
+
773
+ # Prepare the command to obtain completions, ensuring arguments are quoted for eval
774
+ local -a args_to_quote=("\${(@)words[2,-1]}")
775
+ if [ "\${lastChar}" = "" ]; then
776
+ # If the last parameter is complete (there is a space following it)
777
+ # We add an extra empty parameter so we can indicate this to the go completion code.
778
+ __${name}_debug "Adding extra empty parameter"
779
+ args_to_quote+=("")
780
+ fi
781
+
782
+ # Use Zsh's (q) flag to quote each argument safely for eval
783
+ local quoted_args=("\${(@q)args_to_quote}")
784
+
785
+ # Join the main command and the quoted arguments into a single string for eval
786
+ requestComp="${exec} complete -- \${quoted_args[*]}"
787
+
788
+ __${name}_debug "About to call: eval \${requestComp}"
789
+
790
+ # Use eval to handle any environment variables and such
791
+ out=$(eval \${requestComp} 2>/dev/null)
792
+ __${name}_debug "completion output: \${out}"
793
+
794
+ # Extract the directive integer following a : from the last line
795
+ local lastLine
796
+ while IFS='\n' read -r line; do
797
+ lastLine=\${line}
798
+ done < <(printf "%s\n" "\${out[@]}")
799
+ __${name}_debug "last line: \${lastLine}"
800
+
801
+ if [ "\${lastLine[1]}" = : ]; then
802
+ directive=\${lastLine[2,-1]}
803
+ # Remove the directive including the : and the newline
804
+ local suffix
805
+ (( suffix=\${#lastLine}+2))
806
+ out=\${out[1,-$suffix]}
807
+ else
808
+ # There is no directive specified. Leave $out as is.
809
+ __${name}_debug "No directive found. Setting to default"
810
+ directive=0
811
+ fi
812
+
813
+ __${name}_debug "directive: \${directive}"
814
+ __${name}_debug "completions: \${out}"
815
+ __${name}_debug "flagPrefix: \${flagPrefix}"
816
+
817
+ if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
818
+ __${name}_debug "Completion received error. Ignoring completions."
819
+ return
820
+ fi
821
+
822
+ local activeHelpMarker="%"
823
+ local endIndex=\${#activeHelpMarker}
824
+ local startIndex=$((\${#activeHelpMarker}+1))
825
+ local hasActiveHelp=0
826
+ while IFS='\n' read -r comp; do
827
+ # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)
828
+ if [ "\${comp[1,$endIndex]}" = "$activeHelpMarker" ];then
829
+ __${name}_debug "ActiveHelp found: $comp"
830
+ comp="\${comp[$startIndex,-1]}"
831
+ if [ -n "$comp" ]; then
832
+ compadd -x "\${comp}"
833
+ __${name}_debug "ActiveHelp will need delimiter"
834
+ hasActiveHelp=1
835
+ fi
836
+ continue
837
+ fi
838
+
839
+ if [ -n "$comp" ]; then
840
+ # If requested, completions are returned with a description.
841
+ # The description is preceded by a TAB character.
842
+ # For zsh's _describe, we need to use a : instead of a TAB.
843
+ # We first need to escape any : as part of the completion itself.
844
+ comp=\${comp//:/\\:}
845
+
846
+ local tab="$(printf '\\t')"
847
+ comp=\${comp//$tab/:}
848
+
849
+ __${name}_debug "Adding completion: \${comp}"
850
+ completions+=\${comp}
851
+ lastComp=$comp
852
+ fi
853
+ done < <(printf "%s\n" "\${out[@]}")
854
+
855
+ # Add a delimiter after the activeHelp statements, but only if:
856
+ # - there are completions following the activeHelp statements, or
857
+ # - file completion will be performed (so there will be choices after the activeHelp)
858
+ if [ $hasActiveHelp -eq 1 ]; then
859
+ if [ \${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then
860
+ __${name}_debug "Adding activeHelp delimiter"
861
+ compadd -x "--"
862
+ hasActiveHelp=0
863
+ fi
864
+ fi
865
+
866
+ if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
867
+ __${name}_debug "Activating nospace."
868
+ noSpace="-S ''"
869
+ fi
870
+
871
+ if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then
872
+ __${name}_debug "Activating keep order."
873
+ keepOrder="-V"
874
+ fi
875
+
876
+ if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
877
+ # File extension filtering
878
+ local filteringCmd
879
+ filteringCmd='_files'
880
+ for filter in \${completions[@]}; do
881
+ if [ \${filter[1]} != '*' ]; then
882
+ # zsh requires a glob pattern to do file filtering
883
+ filter="\\*.$filter"
884
+ fi
885
+ filteringCmd+=" -g $filter"
886
+ done
887
+ filteringCmd+=" \${flagPrefix}"
888
+
889
+ __${name}_debug "File filtering command: $filteringCmd"
890
+ _arguments '*:filename:'"$filteringCmd"
891
+ elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
892
+ # File completion for directories only
893
+ local subdir
894
+ subdir="\${completions[1]}"
895
+ if [ -n "$subdir" ]; then
896
+ __${name}_debug "Listing directories in $subdir"
897
+ pushd "\${subdir}" >/dev/null 2>&1
898
+ else
899
+ __${name}_debug "Listing directories in ."
900
+ fi
901
+
902
+ local result
903
+ _arguments '*:dirname:_files -/'" \${flagPrefix}"
904
+ result=$?
905
+ if [ -n "$subdir" ]; then
906
+ popd >/dev/null 2>&1
907
+ fi
908
+ return $result
909
+ else
910
+ __${name}_debug "Calling _describe"
911
+ if eval _describe $keepOrder "completions" completions -Q \${flagPrefix} \${noSpace}; then
912
+ __${name}_debug "_describe found some completions"
913
+
914
+ # Return the success of having called _describe
915
+ return 0
916
+ else
917
+ __${name}_debug "_describe did not find completions."
918
+ __${name}_debug "Checking if we should do file completion."
919
+ if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
920
+ __${name}_debug "deactivating file completion"
921
+
922
+ # We must return an error code here to let zsh know that there were no
923
+ # completions found by _describe; this is what will trigger other
924
+ # matching algorithms to attempt to find completions.
925
+ # For example zsh can match letters in the middle of words.
926
+ return 1
927
+ else
928
+ # Perform file completion
929
+ __${name}_debug "Activating file completion"
930
+
931
+ # We must return the result of this command, so it must be the
932
+ # last command, or else we must store its result to return it.
933
+ _arguments '*:filename:_files'" \${flagPrefix}"
934
+ fi
935
+ fi
936
+ fi
937
+ }
938
+
939
+ # don't run the completion function when being sourced or eval-ed
940
+ if [ "\${funcstack[1]}" = "_${name}" ]; then
941
+ _${name}
942
+ fi
943
+ `;
944
+ }
945
+
946
+ //#endregion
947
+ //#region src/bombshell/index.ts
948
+ const ShellCompDirective = {
949
+ ShellCompDirectiveError: Math.trunc(1),
950
+ ShellCompDirectiveNoSpace: 2,
951
+ ShellCompDirectiveNoFileComp: 4,
952
+ ShellCompDirectiveFilterFileExt: 8,
953
+ ShellCompDirectiveFilterDirs: 16,
954
+ ShellCompDirectiveKeepOrder: 32,
955
+ shellCompDirectiveMaxValue: 64,
956
+ ShellCompDirectiveDefault: 0
957
+ };
958
+ var Completion = class {
959
+ commands = new Map();
960
+ completions = [];
961
+ directive = ShellCompDirective.ShellCompDirectiveDefault;
962
+ addCommand(name, description, args, handler, parent) {
963
+ const key = parent ? `${parent} ${name}` : name;
964
+ this.commands.set(key, {
965
+ name: key,
966
+ description,
967
+ args,
968
+ handler,
969
+ options: new Map(),
970
+ parent: parent ? this.commands.get(parent) : void 0
971
+ });
972
+ return key;
973
+ }
974
+ addOption(command, option, description, handler, alias) {
975
+ const cmd = this.commands.get(command);
976
+ if (!cmd) throw new Error(`Command ${command} not found.`);
977
+ cmd.options.set(option, {
978
+ description,
979
+ handler,
980
+ alias
981
+ });
982
+ return option;
983
+ }
984
+ stripOptions(args) {
985
+ const parts = [];
986
+ let option = false;
987
+ for (const k of args) {
988
+ if (k.startsWith("-")) {
989
+ option = true;
990
+ continue;
991
+ }
992
+ if (option) {
993
+ option = false;
994
+ continue;
995
+ }
996
+ parts.push(k);
997
+ }
998
+ return parts;
999
+ }
1000
+ matchCommand(args) {
1001
+ args = this.stripOptions(args);
1002
+ const parts = [];
1003
+ let remaining = [];
1004
+ let matched = this.commands.get("");
1005
+ for (let i = 0; i < args.length; i++) {
1006
+ const k = args[i];
1007
+ parts.push(k);
1008
+ const potential = this.commands.get(parts.join(" "));
1009
+ if (potential) matched = potential;
1010
+ else {
1011
+ remaining = args.slice(i);
1012
+ break;
1013
+ }
1014
+ }
1015
+ return [matched, remaining];
1016
+ }
1017
+ async parse(args) {
1018
+ const endsWithSpace = args.at(-1) === "";
1019
+ if (endsWithSpace) args.pop();
1020
+ let toComplete = args.at(-1) || "";
1021
+ const previousArgs = args.slice(0, -1);
1022
+ if (endsWithSpace) {
1023
+ previousArgs.push(toComplete);
1024
+ toComplete = "";
1025
+ }
1026
+ const [matchedCommand] = this.matchCommand(previousArgs);
1027
+ const lastPrevArg = previousArgs.at(-1);
1028
+ if (this.shouldCompleteFlags(lastPrevArg, toComplete, endsWithSpace)) await this.handleFlagCompletion(matchedCommand, previousArgs, toComplete, endsWithSpace, lastPrevArg);
1029
+ else {
1030
+ if (this.shouldCompleteCommands(toComplete, endsWithSpace)) await this.handleCommandCompletion(previousArgs, toComplete);
1031
+ if (matchedCommand && matchedCommand.args.length > 0) await this.handlePositionalCompletion(matchedCommand, previousArgs, toComplete, endsWithSpace);
1032
+ }
1033
+ this.complete(toComplete);
1034
+ }
1035
+ complete(toComplete) {
1036
+ this.directive = ShellCompDirective.ShellCompDirectiveNoFileComp;
1037
+ const seen = new Set();
1038
+ for (const comp of this.completions.filter((comp$1) => {
1039
+ if (seen.has(comp$1.value)) return false;
1040
+ seen.add(comp$1.value);
1041
+ return true;
1042
+ }).filter((comp$1) => comp$1.value.startsWith(toComplete))) console.log(`${comp.value}\t${comp.description ?? ""}`);
1043
+ console.log(`:${this.directive}`);
1044
+ }
1045
+ shouldCompleteFlags(lastPrevArg, toComplete, _endsWithSpace) {
1046
+ return lastPrevArg?.startsWith("--") || lastPrevArg?.startsWith("-") || toComplete.startsWith("--") || toComplete.startsWith("-");
1047
+ }
1048
+ shouldCompleteCommands(toComplete, _endsWithSpace) {
1049
+ return !toComplete.startsWith("-");
1050
+ }
1051
+ async handleFlagCompletion(command, previousArgs, toComplete, endsWithSpace, lastPrevArg) {
1052
+ let flagName;
1053
+ let valueToComplete = toComplete;
1054
+ if (toComplete.includes("=")) {
1055
+ const parts = toComplete.split("=");
1056
+ flagName = parts[0];
1057
+ valueToComplete = parts[1] || "";
1058
+ } else if (lastPrevArg?.startsWith("-")) flagName = lastPrevArg;
1059
+ if (flagName) {
1060
+ let option = command.options.get(flagName);
1061
+ if (!option) {
1062
+ for (const [name, opt] of command.options) if (opt.alias && `-${opt.alias}` === flagName) {
1063
+ option = opt;
1064
+ flagName = name;
1065
+ break;
1066
+ }
1067
+ }
1068
+ if (option) {
1069
+ const suggestions = await option.handler(previousArgs, valueToComplete, endsWithSpace);
1070
+ if (toComplete.includes("=")) this.completions = suggestions.map((suggestion) => ({
1071
+ value: `${flagName}=${suggestion.value}`,
1072
+ description: suggestion.description
1073
+ }));
1074
+ else this.completions.push(...suggestions);
1075
+ }
1076
+ return;
1077
+ }
1078
+ if (toComplete.startsWith("-")) {
1079
+ const isShortFlag = toComplete.startsWith("-") && !toComplete.startsWith("--");
1080
+ for (const [name, option] of command.options) if (isShortFlag) {
1081
+ if (option.alias && `-${option.alias}`.startsWith(toComplete)) this.completions.push({
1082
+ value: `-${option.alias}`,
1083
+ description: option.description
1084
+ });
1085
+ } else if (name.startsWith(toComplete)) this.completions.push({
1086
+ value: name,
1087
+ description: option.description
1088
+ });
1089
+ }
1090
+ }
1091
+ async handleCommandCompletion(previousArgs, toComplete) {
1092
+ const commandParts = [...previousArgs].filter(Boolean);
1093
+ for (const [k, command] of this.commands) {
1094
+ if (k === "") continue;
1095
+ const parts = k.split(" ");
1096
+ let match = true;
1097
+ let i = 0;
1098
+ while (i < commandParts.length) {
1099
+ if (parts[i] !== commandParts[i]) {
1100
+ match = false;
1101
+ break;
1102
+ }
1103
+ i++;
1104
+ }
1105
+ if (match && parts[i]?.startsWith(toComplete)) this.completions.push({
1106
+ value: parts[i],
1107
+ description: command.description
1108
+ });
1109
+ }
1110
+ }
1111
+ async handlePositionalCompletion(command, previousArgs, toComplete, endsWithSpace) {
1112
+ const suggestions = await command.handler(previousArgs, toComplete, endsWithSpace);
1113
+ this.completions.push(...suggestions);
1114
+ }
1115
+ };
1116
+ function script(shell, name, x) {
1117
+ switch (shell) {
1118
+ case "zsh": {
1119
+ const script$1 = generate(name, x);
1120
+ console.log(script$1);
1121
+ break;
1122
+ }
1123
+ case "bash": {
1124
+ const script$1 = generate$3(name, x);
1125
+ console.log(script$1);
1126
+ break;
1127
+ }
1128
+ case "fish": {
1129
+ const script$1 = generate$2(name, x);
1130
+ console.log(script$1);
1131
+ break;
1132
+ }
1133
+ case "powershell": {
1134
+ const script$1 = generate$1(name, x);
1135
+ console.log(script$1);
1136
+ break;
1137
+ }
1138
+ default: throw new Error(`Unsupported shell: ${shell}`);
1139
+ }
1140
+ }
1141
+
1142
+ //#endregion
1143
+ //#region src/types.ts
1144
+ /**
1145
+ * The unique identifier for the completion plugin.
1146
+ */
1147
+ const pluginId = namespacedId("completion");
1148
+
1149
+ //#endregion
1150
+ //#region src/utils.ts
1151
+ async function createCommandContext$1(cmd, id, i18n) {
1152
+ const extensions = Object.create(null);
1153
+ if (i18n) extensions[id] = {
1154
+ key: Symbol(id),
1155
+ factory: () => i18n
1156
+ };
1157
+ return await createCommandContext({
1158
+ args: cmd.args || Object.create(null),
1159
+ values: Object.create(null),
1160
+ positionals: [],
1161
+ rest: [],
1162
+ argv: [],
1163
+ explicit: Object.create(null),
1164
+ tokens: [],
1165
+ omitted: false,
1166
+ callMode: cmd.entry ? "entry" : "subCommand",
1167
+ command: cmd,
1168
+ extensions,
1169
+ cliOptions: CLI_OPTIONS_DEFAULT
1170
+ });
1171
+ }
1172
+ function detectRuntime() {
1173
+ if (globalThis.process !== void 0 && globalThis.process.release?.name === "node") return "node";
1174
+ if (globalThis.Deno !== void 0) return "deno";
1175
+ if (globalThis.Bun !== void 0) return "bun";
1176
+ return "unknown";
1177
+ }
1178
+ function quoteIfNeeded(path) {
1179
+ return path.includes(" ") ? `'${path}'` : path;
1180
+ }
1181
+ function quoteExec() {
1182
+ const runtime = detectRuntime();
1183
+ switch (runtime) {
1184
+ case "node": {
1185
+ const execPath = globalThis.process.execPath;
1186
+ const processArgs = globalThis.process.argv.slice(1);
1187
+ const quotedExecPath = quoteIfNeeded(execPath);
1188
+ const quotedProcessArgs = processArgs.map(quoteIfNeeded);
1189
+ const quotedProcessExecArgs = globalThis.process.execArgv.map(quoteIfNeeded);
1190
+ return `${quotedExecPath} ${quotedProcessExecArgs.join(" ")} ${quotedProcessArgs[0]}`;
1191
+ }
1192
+ case "deno": throw new Error("deno not implemented yet, welcome contributions :)");
1193
+ case "bun": throw new Error("bun not implemented yet, welcome contributions :)");
1194
+ default: throw new Error("Unsupported your javascript runtime for completion script generation.");
1195
+ }
1196
+ }
1197
+
1198
+ //#endregion
3
1199
  //#region src/index.ts
1200
+ const TERMINATOR = "--";
1201
+ const NOOP_HANDLER = () => {
1202
+ return [];
1203
+ };
1204
+ const i18nPluginId = namespacedId("i18n");
4
1205
  /**
5
1206
  * completion plugin for gunshi
6
1207
  */
7
- function completion() {
1208
+ function completion(options = {}) {
1209
+ const config = options.config || {};
1210
+ const completion$1 = new Completion();
8
1211
  return plugin({
9
- id: "g:completion",
1212
+ id: pluginId,
10
1213
  name: "completion",
11
- setup(_ctx) {}
1214
+ dependencies: [{
1215
+ id: i18nPluginId,
1216
+ optional: true
1217
+ }],
1218
+ async setup(ctx) {
1219
+ /**
1220
+ * add command for completion script generation
1221
+ */
1222
+ const completeName = "complete";
1223
+ ctx.addCommand(completeName, {
1224
+ name: completeName,
1225
+ description: "Generate shell completion script",
1226
+ rendering: { header: null },
1227
+ run: async (cmdCtx) => {
1228
+ if (!cmdCtx.env.name) throw new Error("your cli name is not defined.");
1229
+ let shell = cmdCtx._[1];
1230
+ if (shell === TERMINATOR) shell = void 0;
1231
+ if (shell === void 0) {
1232
+ const extra = cmdCtx._.slice(cmdCtx._.indexOf(TERMINATOR) + 1);
1233
+ await completion$1.parse(extra);
1234
+ } else script(shell, cmdCtx.env.name, quoteExec());
1235
+ }
1236
+ });
1237
+ },
1238
+ onExtension: async (ctx, cmd) => {
1239
+ const i18n = ctx.extensions?.[i18nPluginId];
1240
+ const subCommands = ctx.env.subCommands;
1241
+ const entry = [...subCommands].map(([_, cmd$1]) => cmd$1).find((cmd$1) => cmd$1.entry);
1242
+ if (!entry) throw new Error("entry command not found.");
1243
+ const entryCtx = await createCommandContext$1(entry, i18nPluginId, i18n);
1244
+ if (i18n) {
1245
+ const ret = await i18n.loadResource(i18n.locale, entryCtx, entry);
1246
+ if (!ret) console.warn(`Failed to load i18n resources for command: ${entry.name} (${i18n.locale})`);
1247
+ }
1248
+ const localizeDescription = localizable(entryCtx, cmd, i18n ? i18n.translate : void 0);
1249
+ const isPositional = hasPositional(await resolveLazyCommand(entry));
1250
+ const root = "";
1251
+ completion$1.addCommand(root, await localizeDescription(resolveKey("description", entryCtx)) || entry.description || "", isPositional ? [false] : [], NOOP_HANDLER);
1252
+ const args = entry.args || Object.create(null);
1253
+ for (const [key, schema] of Object.entries(args)) {
1254
+ if (schema.type === "positional") continue;
1255
+ completion$1.addOption(root, `--${key}`, await localizeDescription(resolveArgKey(key, entryCtx)) || schema.description || "", toBombshellCompletionHandler(config.entry?.args?.[key]?.handler || NOOP_HANDLER, i18n ? toLocale(i18n.locale) : void 0), schema.short);
1256
+ }
1257
+ await handleSubCommands(completion$1, subCommands, config.subCommands, i18nPluginId, i18n);
1258
+ }
1259
+ });
1260
+ }
1261
+ async function handleSubCommands(completion$1, subCommands, configs = {}, i18nPluginId$1, i18n) {
1262
+ for (const [name, cmd] of subCommands) {
1263
+ if (cmd.internal || cmd.entry || name === "complete") continue;
1264
+ const resolvedCmd = await resolveLazyCommand(cmd);
1265
+ const ctx = await createCommandContext$1(resolvedCmd, i18nPluginId$1, i18n);
1266
+ if (i18n) {
1267
+ const ret = await i18n.loadResource(i18n.locale, ctx, resolvedCmd);
1268
+ if (!ret) console.warn(`Failed to load i18n resources for command: ${name} (${i18n.locale})`);
1269
+ }
1270
+ const localizeDescription = localizable(ctx, resolvedCmd, i18n ? i18n.translate : void 0);
1271
+ const isPositional = hasPositional(resolvedCmd);
1272
+ const commandName = completion$1.addCommand(name, await localizeDescription(resolveKey("description", ctx)) || resolvedCmd.description || "", isPositional ? [false] : [], toBombshellCompletionHandler(configs?.[name]?.handler || NOOP_HANDLER, i18n ? toLocale(i18n.locale) : void 0));
1273
+ const args = resolvedCmd.args || Object.create(null);
1274
+ for (const [key, schema] of Object.entries(args)) {
1275
+ if (schema.type === "positional") continue;
1276
+ completion$1.addOption(commandName, `--${key}`, await localizeDescription(resolveArgKey(key, ctx)) || schema.description || "", toBombshellCompletionHandler(configs[commandName]?.args?.[key]?.handler || NOOP_HANDLER, i18n ? toLocale(i18n.locale) : void 0), schema.short);
1277
+ }
1278
+ }
1279
+ }
1280
+ function hasPositional(cmd) {
1281
+ return cmd.args && Object.values(cmd.args).some((arg) => arg.type === "positional");
1282
+ }
1283
+ function toLocale(locale) {
1284
+ return locale instanceof Intl.Locale ? locale : new Intl.Locale(locale);
1285
+ }
1286
+ function toBombshellCompletionHandler(handler, locale) {
1287
+ return (previousArgs, toComplete, endWithSpace) => handler({
1288
+ previousArgs,
1289
+ toComplete,
1290
+ endWithSpace,
1291
+ locale
12
1292
  });
13
1293
  }
14
1294
 
15
1295
  //#endregion
16
- export { completion as default };
1296
+ export { completion as default, pluginId };