@gunshi/plugin-completion 0.27.0-alpha.8 → 0.27.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +407 -4
  2. package/lib/index.d.ts +44 -13
  3. package/lib/index.js +261 -975
  4. package/package.json +16 -8
package/README.md CHANGED
@@ -1,14 +1,417 @@
1
- # `@gunshi/plugin-completion`
1
+ # @gunshi/plugin-completion
2
2
 
3
- > completion plugin for gunshi
3
+ [![Version][npm-version-src]][npm-version-href]
4
+ [![InstallSize][install-size-src]][install-size-src]
5
+ [![JSR][jsr-src]][jsr-href]
6
+
7
+ > shell completion plugin for gunshi.
8
+
9
+ This plugin provides tab completion functionality for your CLI applications, allowing users to auto-complete commands, options, and arguments in their shell. It generates shell-specific completion scripts and handles runtime completion suggestions.
10
+
11
+ This completion plugin is powered by [`@bomb.sh/tab`](https://github.com/bombshell-dev/tab)
4
12
 
5
13
  <!-- eslint-disable markdown/no-missing-label-refs -->
6
14
 
7
- > ![WARNING]
8
- > This package is still work in progress
15
+ > [!WARNING]
16
+ > This package support Node.js runtime only. Deno and Bun support are coming soon.
9
17
 
10
18
  <!-- eslint-enable markdown/no-missing-label-refs -->
11
19
 
20
+ ## đŸ’ŋ Installation
21
+
22
+ ```sh
23
+ # npm
24
+ npm install --save @gunshi/plugin-completion
25
+
26
+ # pnpm
27
+ pnpm add @gunshi/plugin-completion
28
+
29
+ # yarn
30
+ yarn add @gunshi/plugin-completion
31
+
32
+ # deno
33
+ deno add jsr:@gunshi/plugin-completion
34
+
35
+ # bun
36
+ bun add @gunshi/plugin-completion
37
+ ```
38
+
39
+ ## 🚀 Usage
40
+
41
+ ```ts
42
+ import { cli } from 'gunshi'
43
+ import completion from '@gunshi/plugin-completion'
44
+
45
+ const command = {
46
+ name: 'deploy',
47
+ args: {
48
+ environment: {
49
+ type: 'string',
50
+ short: 'e',
51
+ description: 'Target environment'
52
+ },
53
+ config: {
54
+ type: 'string',
55
+ short: 'c',
56
+ description: 'Config file path'
57
+ }
58
+ },
59
+ run: ctx => {
60
+ console.log(`Deploying to ${ctx.values.environment}`)
61
+ }
62
+ }
63
+
64
+ await cli(process.argv.slice(2), command, {
65
+ name: 'my-cli',
66
+ version: '1.0.0',
67
+ plugins: [
68
+ completion({
69
+ config: {
70
+ entry: {
71
+ args: {
72
+ config: {
73
+ handler: () => [
74
+ { value: 'prod.json', description: 'Production config' },
75
+ { value: 'dev.json', description: 'Development config' },
76
+ { value: 'test.json', description: 'Test config' }
77
+ ]
78
+ }
79
+ }
80
+ }
81
+ }
82
+ })
83
+ ]
84
+ })
85
+ ```
86
+
87
+ ## ✨ Features
88
+
89
+ ### Automatic Complete Command
90
+
91
+ The plugin automatically adds a `complete` subcommand to your CLI:
92
+
93
+ ```sh
94
+ # Generate shell completion script
95
+ my-cli complete bash > ~/.my-cli-completion.bash
96
+ source ~/.my-cli-completion.bash
97
+
98
+ # Now tab completion works!
99
+ my-cli dep<TAB> # Completes to: my-cli deploy
100
+ my-cli deploy --env<TAB> # Completes to: my-cli deploy --environment
101
+ ```
102
+
103
+ ### Shell Support
104
+
105
+ The `complete` command accepts the following shell types:
106
+
107
+ - `bash` - Bash shell completion
108
+ - `zsh` - Zsh shell completion
109
+ - `fish` - Fish shell completion
110
+ - `powershell` - PowerShell completion
111
+
112
+ <!-- eslint-disable markdown/no-missing-label-refs -->
113
+
114
+ > [!NOTE]
115
+ > Supported shells comply with [`@bomb.sh/tab`](https://github.com/bombshell-dev/tab)
116
+
117
+ <!-- eslint-enable markdown/no-missing-label-refs -->
118
+
119
+ ## Shell Completion Setup
120
+
121
+ This section provides detailed instructions for setting up shell completions in different shells. The setup is a one-time process that enables tab completion for your CLI.
122
+
123
+ ### Prerequisites
124
+
125
+ Shell completion requires Node.js runtime. Ensure your CLI is running with Node.js (not Deno or Bun).
126
+
127
+ <!-- eslint-disable markdown/no-missing-label-refs -->
128
+
129
+ > [!WARNING]
130
+ > This package support Node.js runtime only. Deno and Bun support are coming soon.
131
+
132
+ <!-- eslint-enable markdown/no-missing-label-refs -->
133
+
134
+ ### Setup by Shell
135
+
136
+ #### Bash
137
+
138
+ Bash users have multiple options for installing completion scripts. Choose the approach that best fits your system:
139
+
140
+ **Option 1: User-specific completion directory (Recommended)**
141
+
142
+ ```sh
143
+ # Create the completion directory if it doesn't exist
144
+ mkdir -p ~/.local/share/bash-completion/completions
145
+
146
+ # Generate and install the completion script
147
+ your-cli complete bash > ~/.local/share/bash-completion/completions/your-cli
148
+
149
+ # Reload your shell configuration
150
+ source ~/.bashrc
151
+ ```
152
+
153
+ **Option 2: Alternative user directory**
154
+
155
+ ```sh
156
+ # Create the completion directory if it doesn't exist
157
+ mkdir -p ~/.bash_completion.d
158
+
159
+ # Generate and install the completion script
160
+ your-cli complete bash > ~/.bash_completion.d/your-cli
161
+
162
+ # Add this line to your ~/.bashrc (only needed once)
163
+ echo 'for f in ~/.bash_completion.d/*; do source "$f"; done' >> ~/.bashrc
164
+
165
+ # Reload your shell configuration
166
+ source ~/.bashrc
167
+ ```
168
+
169
+ #### Zsh
170
+
171
+ Zsh requires adding the completion directory to your `fpath`:
172
+
173
+ ```sh
174
+ # Create the completion directory if it doesn't exist
175
+ mkdir -p ~/.zsh/completions
176
+
177
+ # Add the completion directory to fpath in ~/.zshrc (only needed once)
178
+ echo 'fpath=(~/.zsh/completions $fpath)' >> ~/.zshrc
179
+ echo 'autoload -U compinit && compinit' >> ~/.zshrc
180
+
181
+ # Generate and install the completion script (note the underscore prefix)
182
+ your-cli complete zsh > ~/.zsh/completions/_your-cli
183
+
184
+ # Reload your shell configuration
185
+ source ~/.zshrc
186
+ # OR restart the shell
187
+ exec zsh
188
+ ```
189
+
190
+ <!-- eslint-disable markdown/no-missing-label-refs -->
191
+
192
+ > [!NOTE]
193
+ > Zsh completion files must start with an underscore (`_`) followed by the command name.
194
+
195
+ <!-- eslint-enable markdown/no-missing-label-refs -->
196
+
197
+ #### Fish
198
+
199
+ Fish shell has the simplest setup process:
200
+
201
+ ```sh
202
+ # Create the completion directory if it doesn't exist
203
+ mkdir -p ~/.config/fish/completions
204
+
205
+ # Generate and install the completion script
206
+ your-cli complete fish > ~/.config/fish/completions/your-cli.fish
207
+
208
+ # Completions are loaded automatically - no reload needed
209
+ # Optionally, restart the shell for immediate effect
210
+ exec fish
211
+ ```
212
+
213
+ #### PowerShell
214
+
215
+ PowerShell requires adding the completion script to your profile:
216
+
217
+ ```powershell
218
+ # Create the profile directory if it doesn't exist
219
+ New-Item -ItemType Directory -Force -Path (Split-Path $PROFILE)
220
+
221
+ # Generate the completion script and test it
222
+ your-cli complete powershell | Out-String | Invoke-Expression
223
+
224
+ # To make it permanent, add it to your PowerShell profile
225
+ your-cli complete powershell >> $PROFILE
226
+
227
+ # Reload your profile
228
+ . $PROFILE
229
+ # OR restart PowerShell
230
+ ```
231
+
232
+ ### Troubleshooting
233
+
234
+ If completions don't work after setup:
235
+
236
+ 1. **Check script generation**: Ensure `your-cli complete <shell>` outputs a valid script
237
+ 2. **Verify file location**: Confirm the completion script is in the correct directory
238
+ 3. **Reload shell**: Try opening a new terminal session
239
+ 4. **Check permissions**: Ensure the completion file is readable (`chmod +r <file>`)
240
+ 5. **Debug mode**: Some shells offer debug options:
241
+ - Bash: `set -x` before sourcing
242
+ - Zsh: `setopt xtrace` before sourcing
243
+ - Fish: `fish --debug=complete`
244
+ - Powershell: `Set-PSDebug -Trace 1`
245
+
246
+ ### System-wide Installation
247
+
248
+ <!-- eslint-disable markdown/no-missing-label-refs -->
249
+
250
+ > [!WARNING]
251
+ > System-wide installation requires root/administrator permissions and is not recommended for most users. User-specific installation is preferred as it doesn't require elevated privileges and is easier to manage.
252
+
253
+ <!-- eslint-enable markdown/no-missing-label-refs -->
254
+
255
+ If you need system-wide completions:
256
+
257
+ - **Bash**: `/etc/bash_completion.d/` or `/usr/share/bash-completion/completions/`
258
+ - **Zsh**: `/usr/share/zsh/site-functions/` or `/usr/local/share/zsh/site-functions/`
259
+ - **Fish**: `/usr/share/fish/vendor_completions.d/`
260
+ - **PowerShell**: for Moduele, `/usr/local/share/powershell/Modules/`, for system profiles, `$PSHOME\Profile.ps1`
261
+
262
+ ### Updating Completions
263
+
264
+ When your CLI updates with new commands or options:
265
+
266
+ 1. Regenerate the completion script: `your-cli complete <shell> > <path-to-completion-file>`
267
+ 2. Reload your shell or start a new session
268
+
269
+ ### Uninstalling Completions
270
+
271
+ To remove completion support:
272
+
273
+ 1. Delete the completion script file
274
+ 2. Remove any lines added to your shell configuration files (`.bashrc`, `.zshrc`, etc.)
275
+ 3. Reload your shell or start a new session
276
+
277
+ ### Custom Completion Handlers
278
+
279
+ You can provide custom completion handlers for specific arguments:
280
+
281
+ ```ts
282
+ completion({
283
+ config: {
284
+ entry: {
285
+ args: {
286
+ environment: {
287
+ handler: ({ locale }) => [
288
+ { value: 'production', description: 'Production environment' },
289
+ { value: 'staging', description: 'Staging environment' },
290
+ { value: 'development', description: 'Development environment' }
291
+ ]
292
+ }
293
+ }
294
+ },
295
+ subCommands: {
296
+ deploy: {
297
+ args: {
298
+ region: {
299
+ handler: ({ previousArgs }) => {
300
+ // Dynamic completions based on previous arguments
301
+ const env = previousArgs.find(arg => arg.startsWith('--environment='))
302
+ if (env?.includes('production')) {
303
+ return [
304
+ { value: 'us-east-1', description: 'US East (N. Virginia)' },
305
+ { value: 'eu-west-1', description: 'EU (Ireland)' }
306
+ ]
307
+ }
308
+ return [{ value: 'local', description: 'Local development' }]
309
+ }
310
+ }
311
+ }
312
+ }
313
+ }
314
+ }
315
+ })
316
+ ```
317
+
318
+ ### Internationalization Support
319
+
320
+ When used with `@gunshi/plugin-i18n`, completion descriptions are automatically localized:
321
+
322
+ ```ts
323
+ import completion from '@gunshi/plugin-completion'
324
+ import i18n from '@gunshi/plugin-i18n'
325
+
326
+ await cli(args, command, {
327
+ plugins: [
328
+ i18n({ locale: 'ja-JP' }),
329
+ completion() // Descriptions will be shown in Japanese
330
+ ]
331
+ })
332
+ ```
333
+
334
+ ## âš™ī¸ Plugin Options
335
+
336
+ ### `config`
337
+
338
+ - Type: `{ entry?: CompletionConfig, subCommands?: Record<string, CompletionConfig> }`
339
+ - Default: `{}`
340
+ - Description: Configuration for completion handlers
341
+
342
+ #### CompletionConfig
343
+
344
+ ```ts
345
+ interface CompletionConfig {
346
+ handler?: CompletionHandler // Handler for command-level completions
347
+ args?: Record<
348
+ string,
349
+ {
350
+ // Handlers for specific arguments
351
+ handler: CompletionHandler
352
+ }
353
+ >
354
+ }
355
+ ```
356
+
357
+ #### CompletionHandler
358
+
359
+ ```ts
360
+ type CompletionHandler = (params: {
361
+ locale?: Intl.Locale // Current locale (if i18n is enabled)
362
+ }) => CompletionItem[]
363
+
364
+ interface CompletionItem {
365
+ value: string // The completion value
366
+ description?: string // Optional description
367
+ }
368
+ ```
369
+
370
+ ## 🔗 Plugin Dependencies
371
+
372
+ The completion plugin has an optional dependency on the i18n plugin:
373
+
374
+ - **Plugin ID**: `g:i18n` (optional)
375
+ - **Purpose**: Provides localized descriptions for completions
376
+ - **Effect**: When the i18n plugin is present, all command and argument descriptions are automatically translated to the current locale
377
+
378
+ ## 🧩 Context Extensions
379
+
380
+ When using the completion plugin, your command context is extended via `ctx.extensions['g:completion']`.
381
+
382
+ <!-- eslint-disable markdown/no-missing-label-refs -->
383
+
384
+ > [!IMPORTANT]
385
+ > This plugin extension is namespaced in `CommandContext.extensions` using this plugin ID `g:completion` by the gunshi plugin system.
386
+
387
+ <!-- eslint-enable markdown/no-missing-label-refs -->
388
+
389
+ Currently, the completion plugin does not provide any context extensions for use within commands. The plugin ID can be imported for type-safe access:
390
+
391
+ ```ts
392
+ import completion, { pluginId } from '@gunshi/plugin-completion'
393
+ ```
394
+
395
+ ## 📚 API References
396
+
397
+ See the [API References](./docs/index.md)
398
+
399
+ ## 💖 Credits
400
+
401
+ This project uses and depends on:
402
+
403
+ - [`@bomb.sh/tab`](https://github.com/bombshell-dev/tab), created by [Bombshell](https://github.com/bombshell-dev) - Shell completion library
404
+
405
+ Thank you!
406
+
12
407
  ## ÂŠī¸ License
13
408
 
14
409
  [MIT](http://opensource.org/licenses/MIT)
410
+
411
+ <!-- Badges -->
412
+
413
+ [npm-version-src]: https://img.shields.io/npm/v/@gunshi/plugin-completion?style=flat
414
+ [npm-version-href]: https://npmjs.com/package/@gunshi/plugin-completion@alpha
415
+ [jsr-src]: https://jsr.io/badges/@gunshi/plugin-completion
416
+ [jsr-href]: https://jsr.io/@gunshi/plugin-completion
417
+ [install-size-src]: https://pkg-size.dev/badge/install/30875
package/lib/index.d.ts CHANGED
@@ -1,5 +1,10 @@
1
- import { PluginWithExtension } from "@gunshi/plugin";
2
- import { Handler } from "@bombsh/tab";
1
+ /*! license ISC
2
+ * @author Bombshell team and Bombshell contributors
3
+ * Bombshell related codes are forked from @bombsh/tab
4
+ */
5
+
6
+ import { Completion } from "@bomb.sh/tab";
7
+ import { PluginWithoutExtension } from "@gunshi/plugin";
3
8
 
4
9
  //#region ../shared/src/constants.d.ts
5
10
  /**
@@ -20,9 +25,6 @@ declare const BUILT_IN_KEY_SEPARATOR = ":";
20
25
  * Generate a namespaced key.
21
26
  */
22
27
  type GenerateNamespacedKey<Key extends string, Prefixed extends string = typeof BUILT_IN_PREFIX> = `${Prefixed}${typeof BUILT_IN_KEY_SEPARATOR}${Key}`;
23
- /**
24
- * Command i18n built-in arguments keys.
25
- */
26
28
  //#endregion
27
29
  //#region src/types.d.ts
28
30
  /**
@@ -33,40 +35,69 @@ declare const pluginId: GenerateNamespacedKey<'completion', typeof PLUGIN_PREFIX
33
35
  * Type representing the unique identifier for the completion plugin.
34
36
  */
35
37
  type PluginId = typeof pluginId;
38
+ /**
39
+ * Parameters for {@linkcode CompletionHandler | the completion handler}.
40
+ */
41
+ interface CompletionParams {
42
+ /**
43
+ * The locale to use for i18n.
44
+ */
45
+ locale?: Intl.Locale;
46
+ }
47
+ /**
48
+ * The handler for completion.
49
+ *
50
+ * @param params - The {@linkcode CompletionParams | parameters} for the completion handler.
51
+ * @returns An array of {@linkcode Completion | completions}.
52
+ */
53
+ type CompletionHandler = (params: CompletionParams) => Completion[];
36
54
  /**
37
55
  * Extended command context which provides utilities via completion plugin.
38
56
  * These utilities are available via `CommandContext.extensions['g:completion']`.
39
57
  */
40
- interface CompletionCommandContext {}
58
+ interface CompletionExtension {}
41
59
  /**
42
60
  * Completion configuration, which structure is similar `bombsh/tab`'s `CompletionConfig`.
43
61
  */
44
62
  interface CompletionConfig {
45
- handler?: Handler;
63
+ /**
64
+ * The {@linkcode CompletionHandler | handler} for the completion.
65
+ */
66
+ handler?: CompletionHandler;
67
+ /**
68
+ * The command arguments for the completion.
69
+ */
46
70
  args?: Record<string, {
47
- handler: Handler;
71
+ handler: CompletionHandler;
48
72
  }>;
49
73
  }
50
74
  /**
51
75
  * Completion plugin options.
52
76
  */
53
77
  interface CompletionOptions {
78
+ /**
79
+ * The completion configuration
80
+ */
54
81
  config?: {
55
82
  /**
56
- * The entry point completion configuration.
83
+ * The entry point {@linkcode CompletionConfig | completion configuration}.
57
84
  */
58
85
  entry?: CompletionConfig;
59
86
  /**
60
- * The handlers for subcommands.
87
+ * The handlers for sub-commands.
61
88
  */
62
89
  subCommands?: Record<string, CompletionConfig>;
63
90
  };
64
91
  }
65
92
  //#endregion
66
93
  //#region src/index.d.ts
94
+
67
95
  /**
68
- * completion plugin for gunshi
96
+ * completion plugin
97
+ *
98
+ * @param options - A {@linkcode CompletionOptions | Completion options}
99
+ * @returns A defined plugin as completion
69
100
  */
70
- declare function completion(options?: CompletionOptions): PluginWithExtension<CompletionCommandContext>;
101
+ declare function completion(options?: CompletionOptions): PluginWithoutExtension;
71
102
  //#endregion
72
- export { CompletionCommandContext, CompletionConfig, CompletionOptions, PluginId, completion as default, pluginId };
103
+ export { CompletionConfig, CompletionExtension, CompletionHandler, CompletionOptions, CompletionParams, PluginId, completion as default, pluginId };