zod-args-parser 1.0.9 → 1.0.11
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/LICENSE +21 -21
- package/lib/commonjs/autocomplete.js +40 -3
- package/lib/commonjs/autocomplete.js.map +1 -1
- package/lib/commonjs/help.js +1 -1
- package/lib/commonjs/help.js.map +1 -1
- package/lib/commonjs/index.js +1 -1
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/parser.js +1 -1
- package/lib/commonjs/parser.js.map +1 -1
- package/lib/commonjs/utils.js +1 -1
- package/lib/commonjs/utils.js.map +1 -1
- package/lib/module/autocomplete.js +40 -3
- package/lib/module/autocomplete.js.map +1 -1
- package/lib/module/help.js +1 -1
- package/lib/module/help.js.map +1 -1
- package/lib/module/index.js +1 -1
- package/lib/module/index.js.map +1 -1
- package/lib/module/parser.js +1 -1
- package/lib/module/parser.js.map +1 -1
- package/lib/module/utils.js +1 -1
- package/lib/module/utils.js.map +1 -1
- package/lib/typescript/autocomplete.d.ts +9 -0
- package/lib/typescript/autocomplete.d.ts.map +1 -1
- package/lib/typescript/index.d.ts +1 -1
- package/lib/typescript/index.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/autocomplete.ts +64 -1
- package/src/index.ts +88 -84
- package/src/types.ts +333 -333
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2024 Ahmed Alabsi
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Ahmed Alabsi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.generateBashAutocompleteScript=generateBashAutocompleteScript;exports.generatePowerShellAutocompleteScript=generatePowerShellAutocompleteScript;var _utils=require("./utils.js");function generateBashAutocompleteScript(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.generateBashAutocompleteScript=generateBashAutocompleteScript;exports.generatePowerShellAutocompleteScript=generatePowerShellAutocompleteScript;exports.generateZshAutocompleteScript=generateZshAutocompleteScript;var _utils=require("./utils.js");function generateBashAutocompleteScript(...params){const[cli,...subcommands]=params;const mappedCommands=subcommands.reduce((acc,subcommand)=>{acc[subcommand.name]={options:subcommand.options?.map(option=>(0,_utils.transformOptionToArg)(option.name))??[],aliases:subcommand.aliases??[]};return acc;},{});let switchCase="";for(const[key,{options,aliases}]of Object.entries(mappedCommands)){switchCase+=` ${key}${aliases.length?"|":""}${aliases.join("|")})\n`;switchCase+=` opts="${options.join(" ")}"\n`;switchCase+=" ;;\n";}if(cli.options?.length){switchCase+=` "-"*)\n`;switchCase+=` opts="${cli.options.map(option=>(0,_utils.transformOptionToArg)(option.name)).join(" ")}"\n`;switchCase+=" ;;\n";}return`_${cli.cliName}_autocomplete() {
|
|
2
2
|
local cur prev commands opts subcommand used_opts filtered_opts
|
|
3
3
|
|
|
4
4
|
cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
@@ -37,7 +37,7 @@ ${switchCase}
|
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
complete -F _${cli.cliName}_autocomplete ${cli.cliName}
|
|
40
|
-
`;}function generatePowerShellAutocompleteScript(
|
|
40
|
+
`;}function generatePowerShellAutocompleteScript(...params){const[cli,...subcommands]=params;const mappedCommands=subcommands.reduce((acc,subcommand)=>{acc[subcommand.name]={options:subcommand.options?.map(option=>(0,_utils.transformOptionToArg)(option.name))??[],aliases:subcommand.aliases??[]};return acc;},{});const subcommandsStr=Object.keys(mappedCommands).map(key=>`'${key}'`).join(", ");const cliOptionsStr=cli.options?.map(option=>`'${(0,_utils.transformOptionToArg)(option.name)}'`).join(", ")||"";let switchCase="switch ($subcommand) {\n";for(const[key,{options,aliases}]of Object.entries(mappedCommands)){const optionsStr=options.map(option=>`'${option}'`).join(", ");switchCase+=` '${key}' { @(${optionsStr}) }\n`;aliases.forEach(a=>switchCase+=` '${a}' { @(${optionsStr}) }\n`);}switchCase+=` default { @(${cliOptionsStr}) }\n }`;let functionInfo="";if(cli.description){functionInfo=`<#\n.DESCRIPTION\n${cli.description}\n${cli.example?`\n.EXAMPLE\n${cli.example}`:""}\n#>`;}return`${functionInfo}
|
|
41
41
|
function ${cli.cliName} {
|
|
42
42
|
param(
|
|
43
43
|
[Parameter(Position = 0, Mandatory = $false)]
|
|
@@ -65,4 +65,41 @@ Register-ArgumentCompleter -CommandName '${cli.cliName}' -ParameterName 'argumen
|
|
|
65
65
|
$subcommand = $commandAst.CommandElements[1].Value
|
|
66
66
|
$arguments = ${switchCase}
|
|
67
67
|
$arguments | Where-Object { $_ -like "$wordToComplete*" }
|
|
68
|
-
}`;}
|
|
68
|
+
}`;}function generateZshAutocompleteScript(...params){const[cli,...subcommands]=params;const genArguments=options=>{return options?.map(option=>`'${(0,_utils.transformOptionToArg)(option.name)}[${option.description??""}]'`).join(" \\\n ");};const genSubCommand=subcommand=>{const options=subcommand.options;if(!options||options.length===0)return"";return`${subcommand.name})
|
|
69
|
+
_arguments \\
|
|
70
|
+
${genArguments(options)} \\
|
|
71
|
+
'1: :_files' \\
|
|
72
|
+
&& ret=0
|
|
73
|
+
;;`;};return`
|
|
74
|
+
_${cli.cliName}_autocomplete() {
|
|
75
|
+
local ret=1
|
|
76
|
+
|
|
77
|
+
_arguments -C \\
|
|
78
|
+
'1: :_${cli.cliName}_commands' \\
|
|
79
|
+
'*:: :->subcmds' \\
|
|
80
|
+
&& ret=0
|
|
81
|
+
|
|
82
|
+
case $state in
|
|
83
|
+
subcmds)
|
|
84
|
+
case "$words[1]" in
|
|
85
|
+
${subcommands.map(genSubCommand).filter(Boolean).join("\n ")}
|
|
86
|
+
*)
|
|
87
|
+
_message "No options available for this command"
|
|
88
|
+
;;
|
|
89
|
+
esac
|
|
90
|
+
;;
|
|
91
|
+
esac
|
|
92
|
+
|
|
93
|
+
return $ret
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
_${cli.cliName}_commands() {
|
|
97
|
+
local -a commands=(
|
|
98
|
+
${subcommands.map(subcommand=>`"${subcommand.name}:${subcommand.description??""}"`).join("\n ")}
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
_describe -t subcommands 'subcommand' commands
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
compdef _${cli.cliName}_autocomplete ${cli.cliName}
|
|
105
|
+
`;}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_utils","require","generateBashAutocompleteScript","_len","arguments","length","params","Array","_key","cli","subcommands","mappedCommands","reduce","acc","subcommand","name","options","map","option","transformOptionToArg","aliases","switchCase","key","Object","entries","join","cliName","keys","generatePowerShellAutocompleteScript","_len2","_key2","subcommandsStr","cliOptionsStr","optionsStr","forEach","a","functionInfo","description","example"],"sourceRoot":"../../src","sources":["autocomplete.ts"],"sourcesContent":["import { transformOptionToArg } from \"./utils.js\";\n\nimport type { Cli, Subcommand } from \"./types.js\";\n\n/**\n * - Generate bash autocomplete script for your CLI\n * - The generated script should be added to your `.bash_profile` or `.bashrc` file:\n *\n * - Run: `nano $HOME/.bash_profile` or `nano $HOME/.bashrc`\n * - Add the following line: `source <generated script path>`\n * - Save and reopen bash to take effect\n */\nexport function generateBashAutocompleteScript(...params: [Cli, ...Subcommand[]]): string {\n const [cli, ...subcommands] = params;\n\n type MappedCommands = Record<string, { options: string[]; aliases: string[] }>;\n\n const mappedCommands = subcommands.reduce((acc: MappedCommands, subcommand) => {\n acc[subcommand.name] = {\n options: subcommand.options?.map(option => transformOptionToArg(option.name)) ?? [],\n aliases: subcommand.aliases ?? [],\n };\n return acc;\n }, {});\n\n let switchCase = \"\";\n for (const [key, { options, aliases }] of Object.entries(mappedCommands)) {\n switchCase += ` ${key}${aliases.length ? \"|\" : \"\"}${aliases.join(\"|\")})\\n`;\n switchCase += ` opts=\"${options.join(\" \")}\"\\n`;\n switchCase += \" ;;\\n\";\n }\n\n if (cli.options?.length) {\n switchCase += ` \"-\"*)\\n`;\n switchCase += ` opts=\"${cli.options.map(option => transformOptionToArg(option.name)).join(\" \")}\"\\n`;\n switchCase += \" ;;\\n\";\n }\n\n return `_${cli.cliName}_autocomplete() {\n local cur prev commands opts subcommand used_opts filtered_opts\n\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"\n subcommand=\"\\${COMP_WORDS[1]}\"\n\n commands=\"${Object.keys(mappedCommands).join(\" \")}\"\n\n case \"$subcommand\" in\n${switchCase}\n esac\n\n used_opts=\"\"\n if [[ \" \\${commands[@]} \" =~ \" $subcommand \" ]]; then\n for word in \"\\${COMP_WORDS[@]:2}\"; do\n if [[ \"$word\" =~ ^- ]]; then\n used_opts+=\" $word\"\n fi\n done\n fi\n\n if [[ -n \"$opts\" ]]; then\n filtered_opts=\"\"\n for opt in $opts; do\n if [[ ! \" $used_opts \" =~ \" $opt \" ]]; then\n filtered_opts+=\"$opt \"\n fi\n done\n COMPREPLY=( $(compgen -W \"$filtered_opts\" -- \"$cur\") )\n return\n fi\n\n if [[ \"\\${COMP_CWORD}\" -eq 1 ]]; then\n COMPREPLY=( $(compgen -W \"$commands\" -- \"$cur\") )\n fi\n}\n\ncomplete -F _${cli.cliName}_autocomplete ${cli.cliName}\n`;\n}\n\n/**\n * - Generates a PowerShell autocomplete script for your CLI.\n * - The script assumes that your CLI is available as a `.ps1` file in the environment variable. For example:\n * `cliName.ps1`.\n * - This should return a path to your script: `(Get-Command <cliName>.ps1).Source`\n * - The generated script should be added to your `profile.ps1` file:\n *\n * - Run: `notepad $profile`\n * - Add the following line: `. \"<generated script path>\"`\n * - Save and reopen powershell to take effect\n */\nexport function generatePowerShellAutocompleteScript(...params: [Cli, ...Subcommand[]]): string {\n const [cli, ...subcommands] = params;\n\n type MappedCommands = Record<string, { options: string[]; aliases: string[] }>;\n\n const mappedCommands = subcommands.reduce((acc: MappedCommands, subcommand) => {\n acc[subcommand.name] = {\n options: subcommand.options?.map(option => transformOptionToArg(option.name)) ?? [],\n aliases: subcommand.aliases ?? [],\n };\n return acc;\n }, {});\n\n const subcommandsStr = Object.keys(mappedCommands)\n .map(key => `'${key}'`)\n .join(\", \");\n const cliOptionsStr = cli.options?.map(option => `'${transformOptionToArg(option.name)}'`).join(\", \") || \"\";\n\n let switchCase = \"switch ($subcommand) {\\n\";\n for (const [key, { options, aliases }] of Object.entries(mappedCommands)) {\n const optionsStr = options.map(option => `'${option}'`).join(\", \");\n switchCase += ` '${key}' { @(${optionsStr}) }\\n`;\n aliases.forEach(a => (switchCase += ` '${a}' { @(${optionsStr}) }\\n`));\n }\n switchCase += ` default { @(${cliOptionsStr}) }\\n }`;\n\n let functionInfo = \"\";\n if (cli.description) {\n functionInfo = `<#\\n.DESCRIPTION\\n${cli.description}\\n${cli.example ? `\\n.EXAMPLE\\n${cli.example}` : \"\"}\\n#>`;\n }\n\n return `${functionInfo}\nfunction ${cli.cliName} {\n param(\n [Parameter(Position = 0, Mandatory = $false)]\n [string]$subcommand,\n [Parameter(Position = 1, ValueFromRemainingArguments = $true)]\n [string[]]$arguments\n )\n $scriptPath = (Get-Command '${cli.cliName}.ps1').Source\n if ($scriptPath) {\n $argumentList = @($subcommand) + ($arguments | Where-Object { $_ -notin '--', '--%' }) | Where-Object { $_ -ne '' }\n & $scriptPath @argumentList\n return\n }\n Write-Error \"Could not find '${cli.cliName}.ps1' script\"\n}\n\nRegister-ArgumentCompleter -CommandName '${cli.cliName}' -ParameterName 'subcommand' -ScriptBlock {\n param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)\n $subcommands = @(${subcommandsStr}${subcommandsStr && cliOptionsStr ? \", \" : \"\"}${cliOptionsStr})\n $subcommands | Where-Object { $_ -like \"$wordToComplete*\" }\n}\n\nRegister-ArgumentCompleter -CommandName '${cli.cliName}' -ParameterName 'arguments' -ScriptBlock {\n param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)\n $subcommand = $commandAst.CommandElements[1].Value\n $arguments = ${switchCase}\n $arguments | Where-Object { $_ -like \"$wordToComplete*\" }\n}`;\n}\n"],"mappings":"8NAAA,IAAAA,MAAA,CAAAC,OAAA,eAYO,QAAS,CAAAC,8BAA8BA,CAAA,CAA4C,SAAAC,IAAA,CAAAC,SAAA,CAAAC,MAAA,CAAxCC,MAAM,KAAAC,KAAA,CAAAJ,IAAA,EAAAK,IAAA,GAAAA,IAAA,CAAAL,IAAA,CAAAK,IAAA,IAANF,MAAM,CAAAE,IAAA,EAAAJ,SAAA,CAAAI,IAAA,GACtD,KAAM,CAACC,GAAG,CAAE,GAAGC,WAAW,CAAC,CAAGJ,MAAM,CAIpC,KAAM,CAAAK,cAAc,CAAGD,WAAW,CAACE,MAAM,CAAC,CAACC,GAAmB,CAAEC,UAAU,GAAK,CAC7ED,GAAG,CAACC,UAAU,CAACC,IAAI,CAAC,CAAG,CACrBC,OAAO,CAAEF,UAAU,CAACE,OAAO,EAAEC,GAAG,CAACC,MAAM,EAAI,GAAAC,2BAAoB,EAACD,MAAM,CAACH,IAAI,CAAC,CAAC,EAAI,EAAE,CACnFK,OAAO,CAAEN,UAAU,CAACM,OAAO,EAAI,EACjC,CAAC,CACD,MAAO,CAAAP,GAAG,CACZ,CAAC,CAAE,CAAC,CAAC,CAAC,CAEN,GAAI,CAAAQ,UAAU,CAAG,EAAE,CACnB,IAAK,KAAM,CAACC,G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CAAC,SAASF,UAAU,OAAQ,CAAC,CAC/E,CACAZ,UAAU,EAAI,uBAAuBW,aAAa,YAAY,CAE9D,GAAI,CAAAI,YAAY,CAAG,EAAE,CACrB,GAAI3B,GAAG,CAAC4B,WAAW,CAAE,CACnBD,YAAY,CAAG,qBAAqB3B,GAAG,CAAC4B,WAAW,KAAK5B,GAAG,CAAC6B,OAAO,CAAG,eAAe7B,GAAG,CAAC6B,OAAO,EAAE,CAAG,EAAE,MAAM,CAC/G,CAEA,MAAO,GAAGF,YAAY;AACxB,WAAW3B,GAAG,CAACiB,OAAO;AACtB;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkCjB,GAAG,CAACiB,OAAO;AAC7C;AACA;AACA;AACA;AACA;AACA,mCAAmCjB,GAAG,CAACiB,OAAO;AAC9C;AACA;AACA,2CAA2CjB,GAAG,CAACiB,OAAO;AACtD;AACA,uBAAuBK,cAAc,GAAGA,cAAc,EAAIC,aAAa,CAAG,IAAI,CAAG,EAAE,GAAGA,aAAa;AACnG;AACA;AACA;AACA,2CAA2CvB,GAAG,CAACiB,OAAO;AACtD;AACA;AACA,mBAAmBL,UAAU;AAC7B;AACA,EAAE,CACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["_utils","require","generateBashAutocompleteScript","params","cli","subcommands","mappedCommands","reduce","acc","subcommand","name","options","map","option","transformOptionToArg","aliases","switchCase","key","Object","entries","length","join","cliName","keys","generatePowerShellAutocompleteScript","subcommandsStr","cliOptionsStr","optionsStr","forEach","a","functionInfo","description","example","generateZshAutocompleteScript","genArguments","genSubCommand","filter","Boolean"],"sourceRoot":"../../src","sources":["autocomplete.ts"],"sourcesContent":["import { transformOptionToArg } from \"./utils.js\";\n\nimport type { Cli, Option, Subcommand } from \"./types.js\";\n\n/**\n * - Generate bash autocomplete script for your CLI\n * - The generated script should be added to your `.bash_profile` or `.bashrc` file:\n *\n * - Run: `nano $HOME/.bash_profile` or `nano $HOME/.bashrc`\n * - Add the following line: `source <generated script path>`\n * - Save and reopen bash to take effect\n */\nexport function generateBashAutocompleteScript(...params: [Cli, ...Subcommand[]]): string {\n const [cli, ...subcommands] = params;\n\n type MappedCommands = Record<string, { options: string[]; aliases: string[] }>;\n\n const mappedCommands = subcommands.reduce((acc: MappedCommands, subcommand) => {\n acc[subcommand.name] = {\n options: subcommand.options?.map(option => transformOptionToArg(option.name)) ?? [],\n aliases: subcommand.aliases ?? [],\n };\n return acc;\n }, {});\n\n let switchCase = \"\";\n for (const [key, { options, aliases }] of Object.entries(mappedCommands)) {\n switchCase += ` ${key}${aliases.length ? \"|\" : \"\"}${aliases.join(\"|\")})\\n`;\n switchCase += ` opts=\"${options.join(\" \")}\"\\n`;\n switchCase += \" ;;\\n\";\n }\n\n if (cli.options?.length) {\n switchCase += ` \"-\"*)\\n`;\n switchCase += ` opts=\"${cli.options.map(option => transformOptionToArg(option.name)).join(\" \")}\"\\n`;\n switchCase += \" ;;\\n\";\n }\n\n return `_${cli.cliName}_autocomplete() {\n local cur prev commands opts subcommand used_opts filtered_opts\n\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"\n subcommand=\"\\${COMP_WORDS[1]}\"\n\n commands=\"${Object.keys(mappedCommands).join(\" \")}\"\n\n case \"$subcommand\" in\n${switchCase}\n esac\n\n used_opts=\"\"\n if [[ \" \\${commands[@]} \" =~ \" $subcommand \" ]]; then\n for word in \"\\${COMP_WORDS[@]:2}\"; do\n if [[ \"$word\" =~ ^- ]]; then\n used_opts+=\" $word\"\n fi\n done\n fi\n\n if [[ -n \"$opts\" ]]; then\n filtered_opts=\"\"\n for opt in $opts; do\n if [[ ! \" $used_opts \" =~ \" $opt \" ]]; then\n filtered_opts+=\"$opt \"\n fi\n done\n COMPREPLY=( $(compgen -W \"$filtered_opts\" -- \"$cur\") )\n return\n fi\n\n if [[ \"\\${COMP_CWORD}\" -eq 1 ]]; then\n COMPREPLY=( $(compgen -W \"$commands\" -- \"$cur\") )\n fi\n}\n\ncomplete -F _${cli.cliName}_autocomplete ${cli.cliName}\n`;\n}\n\n/**\n * - Generates a PowerShell autocomplete script for your CLI.\n * - The script assumes that your CLI is available as a `.ps1` file in the environment variable. For example:\n * `cliName.ps1`.\n * - This should return a path to your script: `(Get-Command <cliName>.ps1).Source`\n * - The generated script should be added to your `profile.ps1` file:\n *\n * - Run: `notepad $profile`\n * - Add the following line: `. \"<generated script path>\"`\n * - Save and reopen powershell to take effect\n */\nexport function generatePowerShellAutocompleteScript(...params: [Cli, ...Subcommand[]]): string {\n const [cli, ...subcommands] = params;\n\n type MappedCommands = Record<string, { options: string[]; aliases: string[] }>;\n\n const mappedCommands = subcommands.reduce((acc: MappedCommands, subcommand) => {\n acc[subcommand.name] = {\n options: subcommand.options?.map(option => transformOptionToArg(option.name)) ?? [],\n aliases: subcommand.aliases ?? [],\n };\n return acc;\n }, {});\n\n const subcommandsStr = Object.keys(mappedCommands)\n .map(key => `'${key}'`)\n .join(\", \");\n const cliOptionsStr = cli.options?.map(option => `'${transformOptionToArg(option.name)}'`).join(\", \") || \"\";\n\n let switchCase = \"switch ($subcommand) {\\n\";\n for (const [key, { options, aliases }] of Object.entries(mappedCommands)) {\n const optionsStr = options.map(option => `'${option}'`).join(\", \");\n switchCase += ` '${key}' { @(${optionsStr}) }\\n`;\n aliases.forEach(a => (switchCase += ` '${a}' { @(${optionsStr}) }\\n`));\n }\n switchCase += ` default { @(${cliOptionsStr}) }\\n }`;\n\n let functionInfo = \"\";\n if (cli.description) {\n functionInfo = `<#\\n.DESCRIPTION\\n${cli.description}\\n${cli.example ? `\\n.EXAMPLE\\n${cli.example}` : \"\"}\\n#>`;\n }\n\n return `${functionInfo}\nfunction ${cli.cliName} {\n param(\n [Parameter(Position = 0, Mandatory = $false)]\n [string]$subcommand,\n [Parameter(Position = 1, ValueFromRemainingArguments = $true)]\n [string[]]$arguments\n )\n $scriptPath = (Get-Command '${cli.cliName}.ps1').Source\n if ($scriptPath) {\n $argumentList = @($subcommand) + ($arguments | Where-Object { $_ -notin '--', '--%' }) | Where-Object { $_ -ne '' }\n & $scriptPath @argumentList\n return\n }\n Write-Error \"Could not find '${cli.cliName}.ps1' script\"\n}\n\nRegister-ArgumentCompleter -CommandName '${cli.cliName}' -ParameterName 'subcommand' -ScriptBlock {\n param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)\n $subcommands = @(${subcommandsStr}${subcommandsStr && cliOptionsStr ? \", \" : \"\"}${cliOptionsStr})\n $subcommands | Where-Object { $_ -like \"$wordToComplete*\" }\n}\n\nRegister-ArgumentCompleter -CommandName '${cli.cliName}' -ParameterName 'arguments' -ScriptBlock {\n param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)\n $subcommand = $commandAst.CommandElements[1].Value\n $arguments = ${switchCase}\n $arguments | Where-Object { $_ -like \"$wordToComplete*\" }\n}`;\n}\n\n/**\n * - Generates a ZSH autocomplete script for your CLI.\n * - The generated script should be added to your `~/.zshrc` or `~/.zsh_profile` file:\n *\n * - Run: `nano $HOME/.zshrc` or `nano $HOME/.zsh_profile`\n * - Add the following line: `source <generated script path>`\n * - Save and reopen zsh to take effect\n */\nexport function generateZshAutocompleteScript(...params: [Cli, ...Subcommand[]]): string {\n const [cli, ...subcommands] = params;\n\n const genArguments = (options: Option[]) => {\n return options\n ?.map(option => `'${transformOptionToArg(option.name)}[${option.description ?? \"\"}]'`)\n .join(\" \\\\\\n \");\n };\n\n const genSubCommand = (subcommand: Subcommand) => {\n const options = subcommand.options;\n if (!options || options.length === 0) return \"\";\n return `${subcommand.name})\n _arguments \\\\\n ${genArguments(options)} \\\\\n '1: :_files' \\\\\n && ret=0\n ;;`;\n };\n\n return `\n_${cli.cliName}_autocomplete() {\n local ret=1\n\n _arguments -C \\\\\n '1: :_${cli.cliName}_commands' \\\\\n '*:: :->subcmds' \\\\\n && ret=0\n\n case $state in\n subcmds)\n case \"$words[1]\" in\n ${subcommands.map(genSubCommand).filter(Boolean).join(\"\\n \")}\n *)\n _message \"No options available for this command\"\n ;;\n esac\n ;;\n esac\n\n return $ret\n}\n \n_${cli.cliName}_commands() {\n local -a commands=(\n ${subcommands.map(subcommand => `\"${subcommand.name}:${subcommand.description ?? \"\"}\"`).join(\"\\n \")}\n )\n\n _describe -t subcommands 'subcommand' commands\n}\n\ncompdef _${cli.cliName}_autocomplete ${cli.cliName}\n`;\n}\n"],"mappings":"kSAAA,IAAAA,MAAA,CAAAC,OAAA,eAYO,QAAS,CAAAC,8BAA8BA,CAAC,GAAGC,MAA8B,CAAU,CACxF,KAAM,CAACC,GAAG,CAAE,GAAGC,WAAW,CAAC,CAAGF,MAAM,CAIpC,KAAM,CAAAG,cAAc,CAAGD,WAAW,CAACE,MAAM,CAAC,CAACC,GAAmB,CAAEC,UAAU,GAAK,CAC7ED,GAAG,CAACC,UAAU,CAACC,IAAI,CAAC,CAAG,CACrBC,OAAO,CAAEF,UAAU,CAACE,OAAO,EAAEC,GAAG,CAACC,MAAM,EAAI,GAAAC,2BAAoB,EAACD,MAAM,CAACH,IAAI,CAAC,CAAC,EAAI,EAAE,CACnFK,OAAO,CAAEN,UAAU,CAACM,OAAO,EAAI,EACjC,CAAC,CACD,MAAO,CAAAP,GAAG,CACZ,CAAC,CAAE,CAAC,CAAC,CAAC,CAEN,GAAI,CAAAQ,UAAU,CAAG,EAAE,CACnB,IAAK,KAAM,CAACC,GAAG,CAAE,CAAEN,OAAO,CAAEI,OAAQ,CAAC,CAAC,EAAI,CAAAG,MAAM,CAACC,OAAO,CAACb,cAAc,CAAC,CAAE,CACxEU,UAAU,EAAI,OAAOC,GAAG,GAAGF,OAAO,CAACK,MAAM,CAAG,GAAG,CAAG,EAAE,GAAGL,OAAO,CAACM,IAAI,CAAC,GAAG,CAAC,KAAK,CAC7EL,UAAU,EAAI,eAAeL,OAAO,CAACU,IAAI,CAAC,GAAG,CAAC,KAAK,CACnDL,UAAU,EAAI,YAAY,CAC5B,CAEA,GAAIZ,GAAG,CAACO,O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AAI,IAAID,UAAU,CAACsB,WAAW,EAAI,EAAE,GAAG,CAAC,CAACV,IAAI,CAAC,QAAQ,CAAC;AAC1G;AACA;AACA;AACA;AACA;AACA,WAAWjB,GAAG,CAACkB,OAAO,iBAAiBlB,GAAG,CAACkB,OAAO;AAClD,CAAC,CACD","ignoreList":[]}
|
package/lib/commonjs/help.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.help=void 0;var _chalk=_interopRequireDefault(require("chalk"));var _utils=require("./utils.js");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}const colors={title:_chalk.default.bold.blue,description:_chalk.default.white,default:_chalk.default.dim.italic,optional:_chalk.default.dim.italic,exampleTitle:_chalk.default.yellow,example:_chalk.default.dim,command:_chalk.default.yellow,option:_chalk.default.cyan,argument:_chalk.default.green,placeholder:_chalk.default.hex("#FF9800"),punctuation:_chalk.default.white.dim};function printCliHelp(params
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.help=void 0;var _chalk=_interopRequireDefault(require("chalk"));var _utils=require("./utils.js");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}const colors={title:_chalk.default.bold.blue,description:_chalk.default.white,default:_chalk.default.dim.italic,optional:_chalk.default.dim.italic,exampleTitle:_chalk.default.yellow,example:_chalk.default.dim,command:_chalk.default.yellow,option:_chalk.default.cyan,argument:_chalk.default.green,placeholder:_chalk.default.hex("#FF9800"),punctuation:_chalk.default.white.dim};function printCliHelp(params,printOptions={}){printOptions.colors??=true;const noColors=new Proxy(colors,{get:()=>{return(...str)=>str.join(" ");}});const c=printOptions.colors?colors:noColors;if(printOptions.customColors){Object.assign(c,printOptions.customColors);}const isFirstParamCli="cliName"in params[0];const cliOptions=isFirstParamCli?params.shift():{};const subcommands=params;const printTitle=title=>{(0,_utils.print)(c.title(` ${title.toUpperCase()} `));};const cliName=cliOptions.cliName??"";const usage=cliOptions.usage??(0,_utils.concat)(c.punctuation("$"),cliName,subcommands.length?c.command("[command]"):"",cliOptions.options?.length?c.option("[options]"):"",cliOptions.arguments?.length||cliOptions.allowPositional?c.argument("<arguments>"):"");printTitle("Usage");(0,_utils.println)();(0,_utils.println)((0,_utils.indent)(2),usage,(0,_utils.ln)(1));if(cliOptions.description){printTitle("Description");(0,_utils.println)();(0,_utils.println)((0,_utils.indent)(2),c.description(cliOptions.description),(0,_utils.ln)(1));}let longest=0;const[optionsToPrint,longestOptionIndent]=prepareOptionsToPrint(cliOptions.options);if(longestOptionIndent>longest)longest=longestOptionIndent;const[commandsToPrint,longestSubcommandIndent]=prepareCommandsToPrint(subcommands);if(longestSubcommandIndent>longest)longest=longestSubcommandIndent;const[argsToPrint,longestArgIndent]=prepareArgumentsToPrint(cliOptions.arguments);if(longestArgIndent>longest)longest=longestArgIndent;printPreparedOptions(optionsToPrint,c,longest);printPreparedCommands(commandsToPrint,c,longest);printPreparedArguments(argsToPrint,c,longest);if(cliOptions.example){printTitle("Example");(0,_utils.println)();const normalizeExample=cliOptions.example.replace(/\n/g,"\n"+(0,_utils.indent)(3));(0,_utils.println)((0,_utils.indent)(2),c.example(normalizeExample),(0,_utils.ln)(1));}}function printSubcommandHelp(subcommand,printOptions={},cliName=""){printOptions.colors??=true;const noColors=new Proxy(colors,{get:()=>{return(...str)=>str.join(" ");}});const c=printOptions.colors?colors:noColors;if(printOptions.customColors){Object.assign(c,printOptions.customColors);}const printTitle=title=>{(0,_utils.print)(c.title(` ${title.toUpperCase()} `));};const usage=subcommand.usage??(0,_utils.concat)(c.punctuation("$"),cliName,c.command(subcommand.name),subcommand.options?.length?c.option("[options]"):"",subcommand.arguments?.length||subcommand.allowPositional?c.argument("<arguments>"):"");printTitle("Usage");(0,_utils.println)();(0,_utils.println)((0,_utils.indent)(2),usage,(0,_utils.ln)(1));if(subcommand.description){printTitle("Description");(0,_utils.println)();const normalizeDesc=subcommand.description.replace(/\n/g,"\n"+(0,_utils.indent)(3));(0,_utils.println)((0,_utils.indent)(2),c.description(normalizeDesc),(0,_utils.ln)(1));}let longest=0;const[optionsToPrint,longestOptionIndent]=prepareOptionsToPrint(subcommand.options);if(longestOptionIndent>longest)longest=longestOptionIndent;const[argsToPrint,longestArgIndent]=prepareArgumentsToPrint(subcommand.arguments);if(longestArgIndent>longest)longest=longestArgIndent;printPreparedOptions(optionsToPrint,c,longest);printPreparedArguments(argsToPrint,c,longest);if(subcommand.example){printTitle("Example");(0,_utils.println)();const normalizeExample=subcommand.example.replace(/\n/g,"\n"+(0,_utils.indent)(3));(0,_utils.println)((0,_utils.indent)(2),c.example(normalizeExample),(0,_utils.ln)(1));}}function prepareOptionsToPrint(options){if(!options||!options.length)return[[],0];const optionsToPrint=[];let longest=0;for(const option of options){const nameWithAliases=option.aliases?[...option.aliases,option.name]:[option.name];const names=Array.from(new Set(nameWithAliases.map(name=>(0,_utils.transformOptionToArg)(name)))).join(", ");const defaultValue=(0,_utils.getDefaultValueFromSchema)(option.type);const placeholder=option.placeholder??" ";optionsToPrint.push({names,placeholder,description:option.description??option.type.description??"",default:typeof defaultValue!=="undefined"?`(default: ${JSON.stringify(defaultValue)})`:"",optional:option.type.isOptional()?"[optional]":"",example:option.example??""});const optLength=names.length+placeholder.length;if(optLength>longest)longest=optLength;}return[optionsToPrint,longest];}function prepareCommandsToPrint(subcommands){if(!subcommands||!subcommands.length)return[[],0];const commandsToPrint=[];let longest=0;for(const subcommand of subcommands){const{name,aliases,description}=subcommand;const names=Array.from(new Set([...(aliases??[]),name])).join(", ");const placeholder=subcommand.placeholder??(subcommand.options?"[options]":subcommand.allowPositional?"<args>":" ");commandsToPrint.push({names,placeholder,description:description??""});const cmdLength=names.length+placeholder.length;if(cmdLength>longest)longest=cmdLength;}return[commandsToPrint,longest];}function prepareArgumentsToPrint(args){if(!args||!args.length)return[[],0];const argsToPrint=[];let longest=0;for(const arg of args){const defaultValue=(0,_utils.getDefaultValueFromSchema)(arg.type);argsToPrint.push({names:arg.name,description:arg.description??"",default:typeof defaultValue!=="undefined"?`(default: ${JSON.stringify(defaultValue)})`:"",optional:arg.type.isOptional()?"[optional]":"",example:arg.example??""});const cmdLength=arg.name.length;if(cmdLength>longest)longest=cmdLength;}return[argsToPrint,longest];}function printPreparedOptions(optionsToPrint,c,longest){if(!optionsToPrint.length)return;(0,_utils.print)(c.title(" OPTIONS "));(0,_utils.println)();for(const{names,placeholder,description,example,optional,default:def}of optionsToPrint){const optLength=names.length+(placeholder?.length??0);const spacing=longest+1-optLength;const normalizeDesc=description.replace(/\n/g,"\n"+(0,_utils.indent)(longest+7)+c.punctuation("└"));const coloredNames=names.split(/(,)/).map(name=>name===","?c.punctuation(name):c.option(name)).join("");(0,_utils.println)((0,_utils.indent)(2),coloredNames,c.placeholder(placeholder),(0,_utils.indent)(spacing),c.description(normalizeDesc),def?c.default(def):c.optional(optional));if(example){const normalizeExample=example.replace(/\n/g,"\n"+(0,_utils.indent)(longest+17));(0,_utils.println)((0,_utils.indent)(longest+6),c.punctuation("└")+c.exampleTitle("Example:"),c.example(normalizeExample));}}(0,_utils.println)();}function printPreparedCommands(commandsToPrint,c,longest){if(!commandsToPrint.length)return;(0,_utils.print)(c.title(" COMMANDS "));(0,_utils.println)();for(const{names,placeholder,description}of commandsToPrint){const optLength=names.length+(placeholder?.length??0);const spacing=longest+1-optLength;const normalizeDesc=description.replace(/\n/g,"\n"+(0,_utils.indent)(longest+7)+c.punctuation("└"));const coloredNames=names.split(/(,)/).map(name=>name===","?c.punctuation(name):c.command(name)).join("");(0,_utils.println)((0,_utils.indent)(2),coloredNames,c.placeholder(placeholder),(0,_utils.indent)(spacing),c.description(normalizeDesc));}(0,_utils.println)();}function printPreparedArguments(argsToPrint,c,longest){if(!argsToPrint.length)return;(0,_utils.print)(c.title(" ARGUMENTS "));(0,_utils.println)();for(const{names,description,example,optional,default:def}of argsToPrint){const spacing=longest+2-names.length;const normalizeDesc=description.replace(/\n/g,"\n"+(0,_utils.indent)(longest+6)+c.punctuation("└"));(0,_utils.println)((0,_utils.indent)(2),c.argument(names),(0,_utils.indent)(spacing),c.description(normalizeDesc),def?c.default(def):c.optional(optional));if(example){const normalizeExample=example.replace(/\n/g,"\n"+(0,_utils.indent)(longest+16));(0,_utils.println)((0,_utils.indent)(longest+5),c.punctuation("└")+c.exampleTitle("Example:"),c.example(normalizeExample));}}(0,_utils.println)();}const help=exports.help={printCliHelp,printSubcommandHelp};
|
package/lib/commonjs/help.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_chalk","_interopRequireDefault","require","_utils","e","__esModule","default","colors","title","chalk","bold","blue","description","white","dim","italic","optional","exampleTitle","yellow","example","command","option","cyan","argument","green","placeholder","hex","punctuation","printCliHelp","params","printOptions","arguments","length","undefined","noColors","Proxy","get","_len","str","Array","_key","join","c","customColors","Object","assign","isFirstParamCli","cliOptions","shift","subcommands","printTitle","print","toUpperCase","cliName","usage","concat","options","allowPositional","println","indent","ln","longest","optionsToPrint","longestOptionIndent","prepareOptionsToPrint","commandsToPrint","longestSubcommandIndent","prepareCommandsToPrint","argsToPrint","longestArgIndent","prepareArgumentsToPrint","printPreparedOptions","printPreparedCommands","printPreparedArguments","normalizeExample","replace","printSubcommandHelp","subcommand","_len2","_key2","name","normalizeDesc","nameWithAliases","aliases","names","from","Set","map","transformOptionToArg","defaultValue","getDefaultValueFromSchema","type","push","JSON","stringify","isOptional","optLength","cmdLength","args","arg","def","spacing","coloredNames","split","help","exports"],"sourceRoot":"../../src","sources":["help.ts"],"sourcesContent":["import chalk from \"chalk\";\nimport { concat, getDefaultValueFromSchema, indent, ln, print, println, transformOptionToArg } from \"./utils.js\";\n\nimport type { Argument, Cli, Option, PrintHelpOpt, Subcommand } from \"./types.js\";\n\nconst colors: NonNullable<Required<PrintHelpOpt[\"customColors\"]>> = {\n title: chalk.bold.blue,\n description: chalk.white,\n default: chalk.dim.italic,\n optional: chalk.dim.italic,\n exampleTitle: chalk.yellow,\n example: chalk.dim,\n command: chalk.yellow,\n option: chalk.cyan,\n argument: chalk.green,\n placeholder: chalk.hex(\"#FF9800\"),\n punctuation: chalk.white.dim,\n};\n\ntype PreparedToPrint = {\n names: string;\n description: string;\n placeholder?: string;\n example?: string;\n default?: string;\n optional?: string;\n};\n\nfunction printCliHelp(params: [Cli, ...Subcommand[]], printOptions: PrintHelpOpt = {}) {\n printOptions.colors ??= true;\n\n const noColors = new Proxy(colors, {\n get: () => {\n return (...str: string[]) => str.join(\" \");\n },\n });\n\n const c = printOptions.colors ? colors : noColors;\n\n if (printOptions.customColors) {\n Object.assign(c, printOptions.customColors);\n }\n\n const isFirstParamCli = \"cliName\" in params[0];\n const cliOptions = (isFirstParamCli ? params.shift() : {}) as Cli;\n const subcommands = params as Subcommand[];\n\n /** Print a styled title */\n const printTitle = (title: string) => {\n print(c.title(` ${title.toUpperCase()} `));\n };\n\n // Print CLI usage\n const cliName = cliOptions.cliName ?? \"\";\n const usage =\n cliOptions.usage ??\n concat(\n c.punctuation(\"$\"),\n cliName,\n subcommands.length ? c.command(\"[command]\") : \"\",\n cliOptions.options?.length ? c.option(\"[options]\") : \"\",\n cliOptions.arguments?.length || cliOptions.allowPositional ? c.argument(\"<arguments>\") : \"\",\n );\n printTitle(\"Usage\");\n println();\n println(indent(2), usage, ln(1));\n\n // Print CLI description\n if (cliOptions.description) {\n printTitle(\"Description\");\n println();\n println(indent(2), c.description(cliOptions.description), ln(1));\n }\n\n let longest = 0;\n\n // Prepare CLI options\n const [optionsToPrint, longestOptionIndent] = prepareOptionsToPrint(cliOptions.options);\n if (longestOptionIndent > longest) longest = longestOptionIndent;\n\n // Prepare CLI commands\n const [commandsToPrint, longestSubcommandIndent] = prepareCommandsToPrint(subcommands);\n if (longestSubcommandIndent > longest) longest = longestSubcommandIndent;\n\n // Prepare CLI arguments\n const [argsToPrint, longestArgIndent] = prepareArgumentsToPrint(cliOptions.arguments);\n if (longestArgIndent > longest) longest = longestArgIndent;\n\n // Print CLI options\n printPreparedOptions(optionsToPrint, c, longest);\n\n // Print CLI commands\n printPreparedCommands(commandsToPrint, c, longest);\n\n // Print CLI arguments\n printPreparedArguments(argsToPrint, c, longest);\n\n // Print CLI example\n if (cliOptions.example) {\n printTitle(\"Example\");\n println();\n const normalizeExample = cliOptions.example.replace(/\\n/g, \"\\n\" + indent(3));\n println(indent(2), c.example(normalizeExample), ln(1));\n }\n}\n\nfunction printSubcommandHelp(subcommand: Subcommand, printOptions: PrintHelpOpt = {}, cliName = \"\") {\n printOptions.colors ??= true;\n\n const noColors = new Proxy(colors, {\n get: () => {\n return (...str: string[]) => str.join(\" \");\n },\n });\n\n const c = printOptions.colors ? colors : noColors;\n\n if (printOptions.customColors) {\n Object.assign(c, printOptions.customColors);\n }\n\n /** Print a styled title */\n const printTitle = (title: string) => {\n print(c.title(` ${title.toUpperCase()} `));\n };\n\n // Print command usage\n const usage =\n subcommand.usage ??\n concat(\n c.punctuation(\"$\"),\n cliName,\n c.command(subcommand.name),\n subcommand.options?.length ? c.option(\"[options]\") : \"\",\n subcommand.arguments?.length || subcommand.allowPositional ? c.argument(\"<arguments>\") : \"\",\n );\n printTitle(\"Usage\");\n println();\n println(indent(2), usage, ln(1));\n\n // Print command description\n if (subcommand.description) {\n printTitle(\"Description\");\n println();\n const normalizeDesc = subcommand.description.replace(/\\n/g, \"\\n\" + indent(3));\n println(indent(2), c.description(normalizeDesc), ln(1));\n }\n\n let longest = 0;\n\n // Prepare command options\n const [optionsToPrint, longestOptionIndent] = prepareOptionsToPrint(subcommand.options);\n if (longestOptionIndent > longest) longest = longestOptionIndent;\n\n // Prepare command arguments\n const [argsToPrint, longestArgIndent] = prepareArgumentsToPrint(subcommand.arguments);\n if (longestArgIndent > longest) longest = longestArgIndent;\n\n // Print command options\n printPreparedOptions(optionsToPrint, c, longest);\n\n // Print command arguments\n printPreparedArguments(argsToPrint, c, longest);\n\n // Print command example\n if (subcommand.example) {\n printTitle(\"Example\");\n println();\n const normalizeExample = subcommand.example.replace(/\\n/g, \"\\n\" + indent(3));\n println(indent(2), c.example(normalizeExample), ln(1));\n }\n}\n\n// * Prepare\nfunction prepareOptionsToPrint(options: Option[] | undefined): [PreparedToPrint[], number] {\n if (!options || !options.length) return [[], 0];\n\n const optionsToPrint: PreparedToPrint[] = [];\n let longest = 0;\n\n for (const option of options) {\n const nameWithAliases = option.aliases ? [...option.aliases, option.name] : [option.name];\n const names = Array.from(new Set(nameWithAliases.map(name => transformOptionToArg(name)))).join(\", \");\n\n const defaultValue = getDefaultValueFromSchema(option.type);\n\n const placeholder = option.placeholder ?? \" \";\n optionsToPrint.push({\n names,\n placeholder,\n description: option.description ?? option.type.description ?? \"\",\n default: typeof defaultValue !== \"undefined\" ? `(default: ${JSON.stringify(defaultValue)})` : \"\",\n optional: option.type.isOptional() ? \"[optional]\" : \"\",\n example: option.example ?? \"\",\n });\n\n const optLength = names.length + placeholder.length;\n\n if (optLength > longest) longest = optLength;\n }\n\n return [optionsToPrint, longest];\n}\n\nfunction prepareCommandsToPrint(subcommands: Subcommand[] | undefined): [PreparedToPrint[], number] {\n if (!subcommands || !subcommands.length) return [[], 0];\n\n const commandsToPrint: PreparedToPrint[] = [];\n let longest = 0;\n\n for (const subcommand of subcommands) {\n const { name, aliases, description } = subcommand;\n const names = Array.from(new Set([...(aliases ?? []), name])).join(\", \");\n\n const placeholder =\n subcommand.placeholder ?? (subcommand.options ? \"[options]\" : subcommand.allowPositional ? \"<args>\" : \" \");\n\n commandsToPrint.push({ names, placeholder, description: description ?? \"\" });\n\n const cmdLength = names.length + placeholder.length;\n if (cmdLength > longest) longest = cmdLength;\n }\n\n return [commandsToPrint, longest];\n}\n\nfunction prepareArgumentsToPrint(args: Argument[] | undefined): [PreparedToPrint[], number] {\n if (!args || !args.length) return [[], 0];\n\n const argsToPrint: PreparedToPrint[] = [];\n let longest = 0;\n\n for (const arg of args) {\n const defaultValue = getDefaultValueFromSchema(arg.type);\n\n argsToPrint.push({\n names: arg.name,\n description: arg.description ?? \"\",\n default: typeof defaultValue !== \"undefined\" ? `(default: ${JSON.stringify(defaultValue)})` : \"\",\n optional: arg.type.isOptional() ? \"[optional]\" : \"\",\n example: arg.example ?? \"\",\n });\n\n const cmdLength = arg.name.length;\n if (cmdLength > longest) longest = cmdLength;\n }\n\n return [argsToPrint, longest];\n}\n\n// * Print\nfunction printPreparedOptions(optionsToPrint: PreparedToPrint[], c: typeof colors, longest: number) {\n if (!optionsToPrint.length) return;\n\n print(c.title(\" OPTIONS \"));\n\n println();\n\n for (const { names, placeholder, description, example, optional, default: def } of optionsToPrint) {\n const optLength = names.length + (placeholder?.length ?? 0);\n const spacing = longest + 1 - optLength;\n const normalizeDesc = description.replace(/\\n/g, \"\\n\" + indent(longest + 7) + c.punctuation(\"└\"));\n\n const coloredNames = names\n .split(/(,)/)\n .map(name => (name === \",\" ? c.punctuation(name) : c.option(name)))\n .join(\"\");\n\n println(\n indent(2),\n coloredNames,\n c.placeholder(placeholder),\n indent(spacing),\n c.description(normalizeDesc),\n def ? c.default(def) : c.optional(optional),\n );\n\n if (example) {\n const normalizeExample = example.replace(/\\n/g, \"\\n\" + indent(longest + 17));\n println(indent(longest + 6), c.punctuation(\"└\") + c.exampleTitle(\"Example:\"), c.example(normalizeExample));\n }\n }\n\n println();\n}\n\nfunction printPreparedCommands(commandsToPrint: PreparedToPrint[], c: typeof colors, longest: number) {\n if (!commandsToPrint.length) return;\n\n print(c.title(\" COMMANDS \"));\n\n println();\n\n for (const { names, placeholder, description } of commandsToPrint) {\n const optLength = names.length + (placeholder?.length ?? 0);\n const spacing = longest + 1 - optLength;\n const normalizeDesc = description.replace(/\\n/g, \"\\n\" + indent(longest + 7) + c.punctuation(\"└\"));\n\n const coloredNames = names\n .split(/(,)/)\n .map(name => (name === \",\" ? c.punctuation(name) : c.command(name)))\n .join(\"\");\n\n println(indent(2), coloredNames, c.placeholder(placeholder), indent(spacing), c.description(normalizeDesc));\n }\n\n println();\n}\n\nfunction printPreparedArguments(argsToPrint: PreparedToPrint[], c: typeof colors, longest: number) {\n if (!argsToPrint.length) return;\n\n print(c.title(\" ARGUMENTS \"));\n\n println();\n\n for (const { names, description, example, optional, default: def } of argsToPrint) {\n const spacing = longest + 2 - names.length;\n const normalizeDesc = description.replace(/\\n/g, \"\\n\" + indent(longest + 6) + c.punctuation(\"└\"));\n\n println(\n indent(2),\n c.argument(names),\n indent(spacing),\n c.description(normalizeDesc),\n def ? c.default(def) : c.optional(optional),\n );\n\n if (example) {\n const normalizeExample = example.replace(/\\n/g, \"\\n\" + indent(longest + 16));\n println(indent(longest + 5), c.punctuation(\"└\") + c.exampleTitle(\"Example:\"), c.example(normalizeExample));\n }\n }\n\n println();\n}\n\nexport const help = {\n printCliHelp,\n printSubcommandHelp,\n};\n"],"mappings":"0FAAA,IAAAA,MAAA,CAAAC,sBAAA,CAAAC,OAAA,WACA,IAAAC,MAAA,CAAAD,OAAA,eAAiH,SAAAD,uBAAAG,CAAA,SAAAA,CAAA,EAAAA,CAAA,CAAAC,UAAA,CAAAD,CAAA,EAAAE,OAAA,CAAAF,CAAA,GAIjH,KAAM,CAAAG,MAA2D,CAAG,CAClEC,KAAK,CAAEC,cAAK,CAACC,IAAI,CAACC,IAAI,CACtBC,WAAW,CAAEH,cAAK,CAACI,KAAK,CACxBP,OAAO,CAAEG,cAAK,CAACK,GAAG,CAACC,MAAM,CACzBC,QAAQ,CAAEP,cAAK,CAACK,GAAG,CAACC,MAAM,CAC1BE,YAAY,CAAER,cAAK,CAACS,MAAM,CAC1BC,OAAO,CAAEV,cAAK,CAACK,GAAG,CAClBM,OAAO,CAAEX,cAAK,CAACS,MAAM,CACrBG,MAAM,CAAEZ,cAAK,CAACa,IAAI,CAClBC,QAAQ,CAAEd,cAAK,CAACe,KAAK,CACrBC,WAAW,CAAEhB,cAAK,CAACiB,GAAG,CAAC,SAAS,CAAC,CACjCC,WAAW,CAAElB,cAAK,CAACI,KAAK,CAACC,GAC3B,CAAC,CAWD,QAAS,CAAAc,YAAYA,CAACC,MAA8B,CAAmC,IAAjC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CAAEnB,CAAC,CAACf,WAAW,CAAC,GAAG,CAAC,CAAGe,CAAC,CAACzB,YAAY,CAAC,UAAU,CAAC,CAAEyB,CAAC,CAACvB,OAAO,CAACuD,gBAAgB,CAAC,CAAC,CAC5G,CACF,CAEA,GAAAhB,cAAO,EAAC,CAAC,CACX,CAEO,KAAM,CAAA8C,IAAI,CAAAC,OAAA,CAAAD,IAAA,CAAG,CAClB5E,YAAY,CACZgD,mBACF,CAAC","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["_chalk","_interopRequireDefault","require","_utils","e","__esModule","default","colors","title","chalk","bold","blue","description","white","dim","italic","optional","exampleTitle","yellow","example","command","option","cyan","argument","green","placeholder","hex","punctuation","printCliHelp","params","printOptions","noColors","Proxy","get","str","join","c","customColors","Object","assign","isFirstParamCli","cliOptions","shift","subcommands","printTitle","print","toUpperCase","cliName","usage","concat","length","options","arguments","allowPositional","println","indent","ln","longest","optionsToPrint","longestOptionIndent","prepareOptionsToPrint","commandsToPrint","longestSubcommandIndent","prepareCommandsToPrint","argsToPrint","longestArgIndent","prepareArgumentsToPrint","printPreparedOptions","printPreparedCommands","printPreparedArguments","normalizeExample","replace","printSubcommandHelp","subcommand","name","normalizeDesc","nameWithAliases","aliases","names","Array","from","Set","map","transformOptionToArg","defaultValue","getDefaultValueFromSchema","type","push","JSON","stringify","isOptional","optLength","cmdLength","args","arg","def","spacing","coloredNames","split","help","exports"],"sourceRoot":"../../src","sources":["help.ts"],"sourcesContent":["import chalk from \"chalk\";\nimport { concat, getDefaultValueFromSchema, indent, ln, print, println, transformOptionToArg } from \"./utils.js\";\n\nimport type { Argument, Cli, Option, PrintHelpOpt, Subcommand } from \"./types.js\";\n\nconst colors: NonNullable<Required<PrintHelpOpt[\"customColors\"]>> = {\n title: chalk.bold.blue,\n description: chalk.white,\n default: chalk.dim.italic,\n optional: chalk.dim.italic,\n exampleTitle: chalk.yellow,\n example: chalk.dim,\n command: chalk.yellow,\n option: chalk.cyan,\n argument: chalk.green,\n placeholder: chalk.hex(\"#FF9800\"),\n punctuation: chalk.white.dim,\n};\n\ntype PreparedToPrint = {\n names: string;\n description: string;\n placeholder?: string;\n example?: string;\n default?: string;\n optional?: string;\n};\n\nfunction printCliHelp(params: [Cli, ...Subcommand[]], printOptions: PrintHelpOpt = {}) {\n printOptions.colors ??= true;\n\n const noColors = new Proxy(colors, {\n get: () => {\n return (...str: string[]) => str.join(\" \");\n },\n });\n\n const c = printOptions.colors ? colors : noColors;\n\n if (printOptions.customColors) {\n Object.assign(c, printOptions.customColors);\n }\n\n const isFirstParamCli = \"cliName\" in params[0];\n const cliOptions = (isFirstParamCli ? params.shift() : {}) as Cli;\n const subcommands = params as Subcommand[];\n\n /** Print a styled title */\n const printTitle = (title: string) => {\n print(c.title(` ${title.toUpperCase()} `));\n };\n\n // Print CLI usage\n const cliName = cliOptions.cliName ?? \"\";\n const usage =\n cliOptions.usage ??\n concat(\n c.punctuation(\"$\"),\n cliName,\n subcommands.length ? c.command(\"[command]\") : \"\",\n cliOptions.options?.length ? c.option(\"[options]\") : \"\",\n cliOptions.arguments?.length || cliOptions.allowPositional ? c.argument(\"<arguments>\") : \"\",\n );\n printTitle(\"Usage\");\n println();\n println(indent(2), usage, ln(1));\n\n // Print CLI description\n if (cliOptions.description) {\n printTitle(\"Description\");\n println();\n println(indent(2), c.description(cliOptions.description), ln(1));\n }\n\n let longest = 0;\n\n // Prepare CLI options\n const [optionsToPrint, longestOptionIndent] = prepareOptionsToPrint(cliOptions.options);\n if (longestOptionIndent > longest) longest = longestOptionIndent;\n\n // Prepare CLI commands\n const [commandsToPrint, longestSubcommandIndent] = prepareCommandsToPrint(subcommands);\n if (longestSubcommandIndent > longest) longest = longestSubcommandIndent;\n\n // Prepare CLI arguments\n const [argsToPrint, longestArgIndent] = prepareArgumentsToPrint(cliOptions.arguments);\n if (longestArgIndent > longest) longest = longestArgIndent;\n\n // Print CLI options\n printPreparedOptions(optionsToPrint, c, longest);\n\n // Print CLI commands\n printPreparedCommands(commandsToPrint, c, longest);\n\n // Print CLI arguments\n printPreparedArguments(argsToPrint, c, longest);\n\n // Print CLI example\n if (cliOptions.example) {\n printTitle(\"Example\");\n println();\n const normalizeExample = cliOptions.example.replace(/\\n/g, \"\\n\" + indent(3));\n println(indent(2), c.example(normalizeExample), ln(1));\n }\n}\n\nfunction printSubcommandHelp(subcommand: Subcommand, printOptions: PrintHelpOpt = {}, cliName = \"\") {\n printOptions.colors ??= true;\n\n const noColors = new Proxy(colors, {\n get: () => {\n return (...str: string[]) => str.join(\" \");\n },\n });\n\n const c = printOptions.colors ? colors : noColors;\n\n if (printOptions.customColors) {\n Object.assign(c, printOptions.customColors);\n }\n\n /** Print a styled title */\n const printTitle = (title: string) => {\n print(c.title(` ${title.toUpperCase()} `));\n };\n\n // Print command usage\n const usage =\n subcommand.usage ??\n concat(\n c.punctuation(\"$\"),\n cliName,\n c.command(subcommand.name),\n subcommand.options?.length ? c.option(\"[options]\") : \"\",\n subcommand.arguments?.length || subcommand.allowPositional ? c.argument(\"<arguments>\") : \"\",\n );\n printTitle(\"Usage\");\n println();\n println(indent(2), usage, ln(1));\n\n // Print command description\n if (subcommand.description) {\n printTitle(\"Description\");\n println();\n const normalizeDesc = subcommand.description.replace(/\\n/g, \"\\n\" + indent(3));\n println(indent(2), c.description(normalizeDesc), ln(1));\n }\n\n let longest = 0;\n\n // Prepare command options\n const [optionsToPrint, longestOptionIndent] = prepareOptionsToPrint(subcommand.options);\n if (longestOptionIndent > longest) longest = longestOptionIndent;\n\n // Prepare command arguments\n const [argsToPrint, longestArgIndent] = prepareArgumentsToPrint(subcommand.arguments);\n if (longestArgIndent > longest) longest = longestArgIndent;\n\n // Print command options\n printPreparedOptions(optionsToPrint, c, longest);\n\n // Print command arguments\n printPreparedArguments(argsToPrint, c, longest);\n\n // Print command example\n if (subcommand.example) {\n printTitle(\"Example\");\n println();\n const normalizeExample = subcommand.example.replace(/\\n/g, \"\\n\" + indent(3));\n println(indent(2), c.example(normalizeExample), ln(1));\n }\n}\n\n// * Prepare\nfunction prepareOptionsToPrint(options: Option[] | undefined): [PreparedToPrint[], number] {\n if (!options || !options.length) return [[], 0];\n\n const optionsToPrint: PreparedToPrint[] = [];\n let longest = 0;\n\n for (const option of options) {\n const nameWithAliases = option.aliases ? [...option.aliases, option.name] : [option.name];\n const names = Array.from(new Set(nameWithAliases.map(name => transformOptionToArg(name)))).join(\", \");\n\n const defaultValue = getDefaultValueFromSchema(option.type);\n\n const placeholder = option.placeholder ?? \" \";\n optionsToPrint.push({\n names,\n placeholder,\n description: option.description ?? option.type.description ?? \"\",\n default: typeof defaultValue !== \"undefined\" ? `(default: ${JSON.stringify(defaultValue)})` : \"\",\n optional: option.type.isOptional() ? \"[optional]\" : \"\",\n example: option.example ?? \"\",\n });\n\n const optLength = names.length + placeholder.length;\n\n if (optLength > longest) longest = optLength;\n }\n\n return [optionsToPrint, longest];\n}\n\nfunction prepareCommandsToPrint(subcommands: Subcommand[] | undefined): [PreparedToPrint[], number] {\n if (!subcommands || !subcommands.length) return [[], 0];\n\n const commandsToPrint: PreparedToPrint[] = [];\n let longest = 0;\n\n for (const subcommand of subcommands) {\n const { name, aliases, description } = subcommand;\n const names = Array.from(new Set([...(aliases ?? []), name])).join(\", \");\n\n const placeholder =\n subcommand.placeholder ?? (subcommand.options ? \"[options]\" : subcommand.allowPositional ? \"<args>\" : \" \");\n\n commandsToPrint.push({ names, placeholder, description: description ?? \"\" });\n\n const cmdLength = names.length + placeholder.length;\n if (cmdLength > longest) longest = cmdLength;\n }\n\n return [commandsToPrint, longest];\n}\n\nfunction prepareArgumentsToPrint(args: Argument[] | undefined): [PreparedToPrint[], number] {\n if (!args || !args.length) return [[], 0];\n\n const argsToPrint: PreparedToPrint[] = [];\n let longest = 0;\n\n for (const arg of args) {\n const defaultValue = getDefaultValueFromSchema(arg.type);\n\n argsToPrint.push({\n names: arg.name,\n description: arg.description ?? \"\",\n default: typeof defaultValue !== \"undefined\" ? `(default: ${JSON.stringify(defaultValue)})` : \"\",\n optional: arg.type.isOptional() ? \"[optional]\" : \"\",\n example: arg.example ?? \"\",\n });\n\n const cmdLength = arg.name.length;\n if (cmdLength > longest) longest = cmdLength;\n }\n\n return [argsToPrint, longest];\n}\n\n// * Print\nfunction printPreparedOptions(optionsToPrint: PreparedToPrint[], c: typeof colors, longest: number) {\n if (!optionsToPrint.length) return;\n\n print(c.title(\" OPTIONS \"));\n\n println();\n\n for (const { names, placeholder, description, example, optional, default: def } of optionsToPrint) {\n const optLength = names.length + (placeholder?.length ?? 0);\n const spacing = longest + 1 - optLength;\n const normalizeDesc = description.replace(/\\n/g, \"\\n\" + indent(longest + 7) + c.punctuation(\"└\"));\n\n const coloredNames = names\n .split(/(,)/)\n .map(name => (name === \",\" ? c.punctuation(name) : c.option(name)))\n .join(\"\");\n\n println(\n indent(2),\n coloredNames,\n c.placeholder(placeholder),\n indent(spacing),\n c.description(normalizeDesc),\n def ? c.default(def) : c.optional(optional),\n );\n\n if (example) {\n const normalizeExample = example.replace(/\\n/g, \"\\n\" + indent(longest + 17));\n println(indent(longest + 6), c.punctuation(\"└\") + c.exampleTitle(\"Example:\"), c.example(normalizeExample));\n }\n }\n\n println();\n}\n\nfunction printPreparedCommands(commandsToPrint: PreparedToPrint[], c: typeof colors, longest: number) {\n if (!commandsToPrint.length) return;\n\n print(c.title(\" COMMANDS \"));\n\n println();\n\n for (const { names, placeholder, description } of commandsToPrint) {\n const optLength = names.length + (placeholder?.length ?? 0);\n const spacing = longest + 1 - optLength;\n const normalizeDesc = description.replace(/\\n/g, \"\\n\" + indent(longest + 7) + c.punctuation(\"└\"));\n\n const coloredNames = names\n .split(/(,)/)\n .map(name => (name === \",\" ? c.punctuation(name) : c.command(name)))\n .join(\"\");\n\n println(indent(2), coloredNames, c.placeholder(placeholder), indent(spacing), c.description(normalizeDesc));\n }\n\n println();\n}\n\nfunction printPreparedArguments(argsToPrint: PreparedToPrint[], c: typeof colors, longest: number) {\n if (!argsToPrint.length) return;\n\n print(c.title(\" ARGUMENTS \"));\n\n println();\n\n for (const { names, description, example, optional, default: def } of argsToPrint) {\n const spacing = longest + 2 - names.length;\n const normalizeDesc = description.replace(/\\n/g, \"\\n\" + indent(longest + 6) + c.punctuation(\"└\"));\n\n println(\n indent(2),\n c.argument(names),\n indent(spacing),\n c.description(normalizeDesc),\n def ? c.default(def) : c.optional(optional),\n );\n\n if (example) {\n const normalizeExample = example.replace(/\\n/g, \"\\n\" + indent(longest + 16));\n println(indent(longest + 5), c.punctuation(\"└\") + c.exampleTitle(\"Example:\"), c.example(normalizeExample));\n }\n }\n\n println();\n}\n\nexport const help = {\n printCliHelp,\n printSubcommandHelp,\n};\n"],"mappings":"0FAAA,IAAAA,MAAA,CAAAC,sBAAA,CAAAC,OAAA,WACA,IAAAC,MAAA,CAAAD,OAAA,eAAiH,SAAAD,uBAAAG,CAAA,SAAAA,CAAA,EAAAA,CAAA,CAAAC,UAAA,CAAAD,CAAA,EAAAE,OAAA,CAAAF,CAAA,GAIjH,KAAM,CAAAG,MAA2D,CAAG,CAClEC,KAAK,CAAEC,cAAK,CAACC,IAAI,CAACC,IAAI,CACtBC,WAAW,CAAEH,cAAK,CAACI,KAAK,CACxBP,OAAO,CAAEG,cAAK,CAACK,GAAG,CAACC,MAAM,CACzBC,QAAQ,CAAEP,cAAK,CAACK,GAAG,CAACC,MAAM,CAC1BE,YAAY,CAAER,cAAK,CAACS,MAAM,CAC1BC,OAAO,CAAEV,cAAK,CAACK,GAAG,CAClBM,OAAO,CAAEX,cAAK,CAACS,MAAM,CACrBG,MAAM,CAAEZ,cAAK,CAACa,IAAI,CAClBC,QAAQ,CAAEd,cAAK,CAACe,KAAK,CACrBC,WAAW,CAAEhB,cAAK,CAACiB,GAAG,CAAC,SAAS,CAAC,CACjCC,WAAW,CAAElB,cAAK,CAACI,KAAK,CAACC,GAC3B,CAAC,CAWD,QAAS,CAAAc,YAAYA,CAACC,MAA8B,CAAEC,YAA0B,CAAG,CAAC,CAAC,CAAE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AW,CAAC,GAAG,CAAC,CAAC,CAEjG,GAAA2B,cAAO,EACL,GAAAC,aAAM,EAAC,CAAC,CAAC,CACTnB,CAAC,CAACb,QAAQ,CAACuD,KAAK,CAAC,CACjB,GAAAvB,aAAM,EAACyC,OAAO,CAAC,CACf5D,CAAC,CAACxB,WAAW,CAAC+D,aAAa,CAAC,CAC5BoB,GAAG,CAAG3D,CAAC,CAAC9B,OAAO,CAACyF,GAAG,CAAC,CAAG3D,CAAC,CAACpB,QAAQ,CAACA,QAAQ,CAC5C,CAAC,CAED,GAAIG,OAAO,CAAE,CACX,KAAM,CAAAmD,gBAAgB,CAAGnD,OAAO,CAACoD,OAAO,CAAC,KAAK,CAAE,IAAI,CAAG,GAAAhB,aAAM,EAACE,OAAO,CAAG,EAAE,CAAC,CAAC,CAC5E,GAAAH,cAAO,EAAC,GAAAC,aAAM,EAACE,OAAO,CAAG,CAAC,CAAC,CAAErB,CAAC,CAACT,WAAW,CAAC,GAAG,CAAC,CAAGS,CAAC,CAACnB,YAAY,CAAC,UAAU,CAAC,CAAEmB,CAAC,CAACjB,OAAO,CAACmD,gBAAgB,CAAC,CAAC,CAC5G,CACF,CAEA,GAAAhB,cAAO,EAAC,CAAC,CACX,CAEO,KAAM,CAAA6C,IAAI,CAAAC,OAAA,CAAAD,IAAA,CAAG,CAClBvE,YAAY,CACZ4C,mBACF,CAAC","ignoreList":[]}
|
package/lib/commonjs/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createArguments=createArguments;exports.createCli=createCli;exports.createOptions=createOptions;exports.createSubcommand=createSubcommand;Object.defineProperty(exports,"generateBashAutocompleteScript",{enumerable:true,get:function(){return _autocomplete.generateBashAutocompleteScript;}});Object.defineProperty(exports,"generatePowerShellAutocompleteScript",{enumerable:true,get:function(){return _autocomplete.generatePowerShellAutocompleteScript;}});Object.defineProperty(exports,"parse",{enumerable:true,get:function(){return _parser.parse;}});exports.printSubcommandHelp=exports.printCliHelp=void 0;Object.defineProperty(exports,"safeParse",{enumerable:true,get:function(){return _parser.safeParse;}});var _help=require("./help.js");var _parser=require("./parser.js");var _autocomplete=require("./autocomplete.js");function createCli(input){const setAction=action=>{input.action=action;};return Object.assign(input,{setAction});}function createSubcommand(input){const setAction=action=>{input.action=action;};return Object.assign(input,{setAction});}function createOptions(options){return options;}function createArguments(args){return args;}const{printCliHelp,printSubcommandHelp}=_help.help;exports.printSubcommandHelp=printSubcommandHelp;exports.printCliHelp=printCliHelp;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createArguments=createArguments;exports.createCli=createCli;exports.createOptions=createOptions;exports.createSubcommand=createSubcommand;Object.defineProperty(exports,"generateBashAutocompleteScript",{enumerable:true,get:function(){return _autocomplete.generateBashAutocompleteScript;}});Object.defineProperty(exports,"generatePowerShellAutocompleteScript",{enumerable:true,get:function(){return _autocomplete.generatePowerShellAutocompleteScript;}});Object.defineProperty(exports,"generateZshAutocompleteScript",{enumerable:true,get:function(){return _autocomplete.generateZshAutocompleteScript;}});Object.defineProperty(exports,"parse",{enumerable:true,get:function(){return _parser.parse;}});exports.printSubcommandHelp=exports.printCliHelp=void 0;Object.defineProperty(exports,"safeParse",{enumerable:true,get:function(){return _parser.safeParse;}});var _help=require("./help.js");var _parser=require("./parser.js");var _autocomplete=require("./autocomplete.js");function createCli(input){const setAction=action=>{input.action=action;};return Object.assign(input,{setAction});}function createSubcommand(input){const setAction=action=>{input.action=action;};return Object.assign(input,{setAction});}function createOptions(options){return options;}function createArguments(args){return args;}const{printCliHelp,printSubcommandHelp}=_help.help;exports.printSubcommandHelp=printSubcommandHelp;exports.printCliHelp=printCliHelp;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_help","require","_parser","_autocomplete","createCli","input","setAction","action","Object","assign","createSubcommand","createOptions","options","createArguments","args","printCliHelp","printSubcommandHelp","help","exports"],"sourceRoot":"../../src","sources":["index.ts"],"sourcesContent":["import { help } from \"./help.js\";\
|
|
1
|
+
{"version":3,"names":["_help","require","_parser","_autocomplete","createCli","input","setAction","action","Object","assign","createSubcommand","createOptions","options","createArguments","args","printCliHelp","printSubcommandHelp","help","exports"],"sourceRoot":"../../src","sources":["index.ts"],"sourcesContent":["import { help } from \"./help.js\";\n\nimport type {\n ActionFn,\n Argument,\n CheckDuplicatedOptions,\n Cli,\n Option,\n Prettify,\n Subcommand,\n UnSafeParseResult,\n} from \"./types.js\";\n\n/**\n * - Insures that there is no extra keys in `obj` compared to `shape`\n * - Also checks objects in arrays useful for the keys `options` and `arguments`\n */\ntype Exact<Obj extends object, Shape extends object> = {\n [K in keyof Obj]: K extends keyof Shape\n ? Obj[K] extends infer ObjArr extends object[]\n ? Required<Shape>[K] extends infer ShapeArr extends object[]\n ? ExactObjArr<ObjArr, ShapeArr[number]>\n : Obj[K]\n : Obj[K]\n : never;\n};\n\n/** - Insures that there is no extra keys in `obj` compared to `shape` */\ntype ExactKeys<T extends object, U extends object> = { [K in keyof T]: K extends keyof U ? T[K] : never };\n\n/** - Insures that there is no extra keys in the objects in an array compared to `shape` */\ntype ExactObjArr<ObjArr extends object[], ShapeObj extends object> = {\n [K in keyof ObjArr]: ExactKeys<ObjArr[K], ShapeObj>;\n};\n\n/**\n * - Insures that there are no duplicated options\n * - Disallow extra keys\n */\ntype CliInput<T extends Cli> = CheckDuplicatedOptions<T> extends T ? Exact<T, Cli> : CheckDuplicatedOptions<T>;\n\nexport function createCli<const T extends Cli>(input: CliInput<T>) {\n const setAction = (action: (res: UnSafeParseResult<[T]>) => void) => {\n input.action = action;\n };\n\n return Object.assign(input, { setAction }) as Prettify<CliInput<T> & ActionFn<T>>;\n}\n\n/**\n * - Insures that there are no duplicated options\n * - Disallow extra keys\n */\ntype SubcommandInput<T extends Subcommand> =\n CheckDuplicatedOptions<T> extends T ? Exact<T, Subcommand> : CheckDuplicatedOptions<T>;\n\nexport function createSubcommand<const T extends Subcommand>(input: SubcommandInput<T>) {\n const setAction = (action: (res: UnSafeParseResult<[T]>) => void) => {\n input.action = action;\n };\n\n return Object.assign(input, { setAction }) as Prettify<SubcommandInput<T> & ActionFn<T>>;\n}\n\n/** - Insures that there are no duplicated options */\ntype CheckOptionsInput<T extends Option[]> =\n CheckDuplicatedOptions<{ options: T }> extends infer Err extends string ? Err : T;\n\nexport function createOptions<const T extends [Option, ...Option[]]>(options: CheckOptionsInput<T>) {\n return options;\n}\n\nexport function createArguments<const T extends [Argument, ...Argument[]]>(args: T) {\n return args;\n}\n\nconst { printCliHelp, printSubcommandHelp } = help;\nexport { printCliHelp, printSubcommandHelp };\n\nexport { parse, safeParse } from \"./parser.js\";\n\nexport {\n generateBashAutocompleteScript,\n generateZshAutocompleteScript,\n generatePowerShellAutocompleteScript,\n} from \"./autocomplete.js\";\n\nexport type * from \"./types.js\";\n"],"mappings":"q6BAAA,IAAAA,KAAA,CAAAC,OAAA,cA+EA,IAAAC,OAAA,CAAAD,OAAA,gBAEA,IAAAE,aAAA,CAAAF,OAAA,sBAxCO,QAAS,CAAAG,SAASA,CAAsBC,KAAkB,CAAE,CACjE,KAAM,CAAAC,SAAS,CAAIC,MAA6C,EAAK,CACnEF,KAAK,CAACE,MAAM,CAAGA,MAAM,CACvB,CAAC,CAED,MAAO,CAAAC,MAAM,CAACC,MAAM,CAACJ,KAAK,CAAE,CAAEC,SAAU,CAAC,CAAC,CAC5C,CASO,QAAS,CAAAI,gBAAgBA,CAA6BL,KAAyB,CAAE,CACtF,KAAM,CAAAC,SAAS,CAAIC,MAA6C,EAAK,CACnEF,KAAK,CAACE,MAAM,CAAGA,MAAM,CACvB,CAAC,CAED,MAAO,CAAAC,MAAM,CAACC,MAAM,CAACJ,KAAK,CAAE,CAAEC,SAAU,CAAC,CAAC,CAC5C,CAMO,QAAS,CAAAK,aAAaA,CAAwCC,OAA6B,CAAE,CAClG,MAAO,CAAAA,OAAO,CAChB,CAEO,QAAS,CAAAC,eAAeA,CAA4CC,IAAO,CAAE,CAClF,MAAO,CAAAA,IAAI,CACb,CAEA,KAAM,CAAEC,YAAY,CAAEC,mBAAoB,CAAC,CAAGC,UAAI,CAACC,OAAA,CAAAF,mBAAA,CAAAA,mBAAA,CAAAE,OAAA,CAAAH,YAAA,CAAAA,YAAA","ignoreList":[]}
|
package/lib/commonjs/parser.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.parse=parse;exports.safeParse=safeParse;var _help=require("./help.js");var _utils=require("./utils.js");function parse(argsv
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.parse=parse;exports.safeParse=safeParse;var _help=require("./help.js");var _utils=require("./utils.js");function parse(argsv,...params){const cliOptions="cliName"in params[0]?params[0]:{};const subcommandArr=params;const allSubcommands=new Set(subcommandArr.flatMap(c=>[c.name,...(c.aliases||[])]));argsv=(0,_utils.decoupleFlags)(argsv);const results={subcommand:undefined,printCliHelp(opt){_help.help.printCliHelp(params,opt);},printSubcommandHelp(subcommandStr,opt){const subcommand=subcommandArr.find(c=>{if(c.name===subcommandStr)return true;if(!subcommandStr)return false;if(!c.aliases?.length)return false;return c.aliases.includes(subcommandStr);});if(!subcommand)return console.error(`Cannot print help for subcommand "${subcommandStr}" as it does not exist`);_help.help.printSubcommandHelp(subcommand,opt,cliOptions.cliName);}};const GetSubcommandProps=(cmd=results.subcommand)=>{return subcommandArr.find(c=>{if(c.name===cmd)return true;if(!cmd)return false;if(!c.aliases?.length)return false;return c.aliases.includes(cmd);});};const addRawArg=(optionName,rawArg)=>{if(!results._info)results._info={};if(!results._info[optionName])results._info[optionName]=Object.create({});results._info[optionName].rawArg=rawArg;};const addRawValue=(optionName,rawValue)=>{if(!results._info)results._info={};if(!results._info[optionName])results._info[optionName]=Object.create({});results._info[optionName].rawValue=rawValue;};const addSource=(optionName,source)=>{if(!results._info)results._info={};if(!results._info[optionName])results._info[optionName]=Object.create({});results._info[optionName].source=source;};const fillOption=(optionName,value)=>{if(!results._info)results._info={};if(!results._info[optionName])results._info[optionName]=Object.create({});Object.assign(results._info[optionName],value);};for(let i=0;i<argsv.length;i++){const arg=argsv[i];if(i===0){results.subcommand=allSubcommands.has(arg)?arg:undefined;const subcommandProps=GetSubcommandProps();if(subcommandProps?.allowPositional)results.positional=[];if(subcommandProps?.arguments?.length)results.arguments=[];if(results.subcommand)continue;}const argAndValue=arg.split("=").filter(Boolean);const argWithEquals=arg.includes("=");const argument=argAndValue[0];const argValue=argAndValue[1];if((0,_utils.isOptionArg)(argument)){if((0,_utils.isFlagArg)(argument)&&argWithEquals){throw new Error(`Flag arguments cannot be assigned using "=": "${arg}"`);}const subcommandProps=GetSubcommandProps();if(!subcommandProps)throw new Error(`Unknown subcommand: "${results.subcommand}"`);if(!subcommandProps.options){const msg=!results.subcommand?"options are not allowed here":`subcommand "${results.subcommand}" does not allow options`;throw new Error(`Error: ${msg}: "${argument}"`);}const optionName=(0,_utils.transformArg)(argument);const isNegative=argument.startsWith("--no-");const option=subcommandProps.options.find(o=>{if(o.name===optionName)return true;if(isNegative&&(0,_utils.noName)(o.name)===optionName)return true;if(!o.aliases)return false;if(o.aliases.includes(optionName))return true;if(isNegative&&o.aliases.map(_utils.noName).includes(optionName))return true;return false;});if(!option){throw new Error(`Unknown option: "${argument}"`);}if(option.name in results){throw new Error(`Duplicated option: "${argument}"`);}const isTypeBoolean=(0,_utils.isBooleanSchema)(option.type);const nextArg=argsv[i+1];let optionValue=argWithEquals?argValue:nextArg;if(isTypeBoolean){if(argWithEquals){const parsedBoolean=(0,_utils.stringToBoolean)(argValue);optionValue=isNegative?!parsedBoolean:parsedBoolean;}else{optionValue=!isNegative;}}if(typeof optionValue==="undefined"){throw new Error(`Expected a value for "${argument}" but got nothing`);}if(!argWithEquals&&(0,_utils.isOptionArg)(optionValue)){throw new Error(`Expected a value for "${argument}" but got an argument "${nextArg}"`);}const res=option.type.safeParse(optionValue);if(!res.success){throw new Error(`Invalid value "${optionValue}" for "${argument}": ${res.error.errors[0].message}`);}results[option.name]=res.data;addRawArg(option.name,argument);const rawVal=argWithEquals?argValue:isTypeBoolean?"":nextArg;addRawValue(option.name,rawVal);fillOption(option.name,option);if(!argWithEquals&&!isTypeBoolean)i++;continue;}const subcommandProps=GetSubcommandProps();if(subcommandProps?.arguments?.length){if(!results.arguments)results.arguments=[];const currentArgCount=results.arguments.length;if(currentArgCount<subcommandProps.arguments.length){const argType=subcommandProps.arguments[currentArgCount].type;let argValue=arg;const isTypeBoolean=(0,_utils.isBooleanSchema)(argType);if(isTypeBoolean)argValue=(0,_utils.stringToBoolean)(argValue);const res=argType.safeParse(argValue);if(!res.success){throw new Error(`The ${(0,_utils.getOrdinalPlacement)(currentArgCount)} argument "${arg}" is invalid: ${res.error.errors[0].message}`);}results.arguments.push(res.data);continue;}}if(subcommandProps?.allowPositional){if(!results.positional)results.positional=[];results.positional.push(arg);continue;}const msg=!results.subcommand?"here":`for subcommand "${results.subcommand}"`;throw new Error(`Unexpected argument "${arg}": positional arguments are not allowed ${msg}`);}const subcommandProps=GetSubcommandProps();if(subcommandProps?.options?.length){for(const option of subcommandProps.options){if(option.name in results){addSource(option.name,"cli");fillOption(option.name,option);continue;}if(option.type.isOptional()){const hasDefault=typeof option.type._def.defaultValue==="function";if(!hasDefault)continue;results[option.name]=option.type._def.defaultValue();addSource(option.name,"default");fillOption(option.name,option);continue;}throw new Error(`Missing required option: ${(0,_utils.transformOptionToArg)(option.name)}`);}}if(subcommandProps?.arguments?.length){const currentArgCount=results.arguments?.length??0;const subcommandArgCount=subcommandProps.arguments.length;if(currentArgCount<subcommandArgCount){for(let i=currentArgCount;i<subcommandArgCount;i++){const argumentType=subcommandProps.arguments[i].type;const hasDefault=typeof argumentType._def.defaultValue==="function";if(hasDefault&&results.arguments){results.arguments.push(argumentType._def.defaultValue());continue;}if(argumentType.isOptional())continue;throw new Error(`the ${(0,_utils.getOrdinalPlacement)(i)} argument is required: "${subcommandProps.arguments[i].name}"`);}}}if(subcommandProps?.action){subcommandProps.action(results);}return results;}function safeParse(argsv,...params){const cliOptions="cliName"in params[0]?params[0]:{};const subcommandArr=params;const printCliHelp=opt=>_help.help.printCliHelp(params,opt);const printSubcommandHelp=(subcommandStr,opt)=>{const subcommand=subcommandArr.find(c=>c.name===subcommandStr);if(!subcommand)return console.error(`Cannot print help for subcommand "${subcommandStr}" as it does not exist`);_help.help.printSubcommandHelp(subcommand,opt,cliOptions.cliName);};try{const data=parse(argsv,...params);delete data.printCliHelp;delete data.printSubcommandHelp;return{success:true,data:data,printCliHelp,printSubcommandHelp};}catch(e){return{success:false,error:e,printCliHelp,printSubcommandHelp};}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_help","require","_utils","parse","argsv","_len","arguments","length","params","Array","_key","cliOptions","subcommandArr","allSubcommands","Set","flatMap","c","name","aliases","decoupleFlags","results","subcommand","undefined","printCliHelp","opt","help","printSubcommandHelp","subcommandStr","find","includes","console","error","cliName","GetSubcommandProps","cmd","addRawArg","optionName","rawArg","_info","Object","create","addRawValue","rawValue","addSource","source","fillOption","value","assign","i","arg","has","subcommandProps","allowPositional","positional","argAndValue","split","filter","Boolean","argWithEquals","argument","argValue","isOptionArg","isFlagArg","Error","options","msg","transformArg","isNegative","startsWith","option","o","noName","map","isTypeBoolean","isBooleanSchema","type","nextArg","optionValue","parsedBoolean","stringToBoolean","res","safeParse","success","errors","message","data","rawVal","currentArgCount","argType","getOrdinalPlacement","push","isOptional","hasDefault","_def","defaultValue","transformOptionToArg","subcommandArgCount","argumentType","action","_len2","_key2","e"],"sourceRoot":"../../src","sources":["parser.ts"],"sourcesContent":["import { help } from \"./help.js\";\nimport {\n decoupleFlags,\n getOrdinalPlacement,\n isBooleanSchema,\n isFlagArg,\n isOptionArg,\n noName,\n stringToBoolean,\n transformArg,\n transformOptionToArg,\n} from \"./utils.js\";\n\nimport type {\n Cli,\n NoSubcommand,\n Option,\n PrintHelpOpt,\n PrintMethods,\n SafeParseResult,\n Subcommand,\n UnSafeParseResult,\n} from \"./types.js\";\n\nexport function parse<T extends Subcommand[], U extends Cli>(\n argsv: string[],\n ...params: [U, ...T]\n): UnSafeParseResult<[...T, NoSubcommand & U]> {\n const cliOptions = (\"cliName\" in params[0] ? params[0] : {}) as U;\n const subcommandArr = params as unknown as T;\n const allSubcommands = new Set<string>(subcommandArr.flatMap(c => [c.name, ...(c.aliases || [])]));\n\n // decouple flags E.g. `-rf` -> `-r, -f`\n argsv = decoupleFlags(argsv);\n\n type ResultObj = Record<string, unknown> & {\n subcommand: string | undefined;\n positional?: string[];\n arguments?: unknown[];\n _info?: Record<string, { rawArg?: string; rawValue?: string; source: \"cli\" | \"default\" }>;\n printCliHelp: (options?: PrintHelpOpt) => void;\n printSubcommandHelp: (subcommand: any, options?: PrintHelpOpt) => void;\n };\n\n const results: ResultObj = {\n subcommand: undefined,\n printCliHelp(opt) {\n help.printCliHelp(params, opt);\n },\n printSubcommandHelp(subcommandStr, opt) {\n const subcommand = subcommandArr.find(c => {\n if (c.name === subcommandStr) return true;\n if (!subcommandStr) return false;\n if (!c.aliases?.length) return false;\n return c.aliases.includes(subcommandStr);\n });\n if (!subcommand) return console.error(`Cannot print help for subcommand \"${subcommandStr}\" as it does not exist`);\n help.printSubcommandHelp(subcommand, opt, cliOptions.cliName);\n },\n };\n\n /** - Get current subcommand props */\n const GetSubcommandProps = (cmd = results.subcommand) => {\n return subcommandArr.find(c => {\n if (c.name === cmd) return true;\n if (!cmd) return false;\n if (!c.aliases?.length) return false;\n return c.aliases.includes(cmd);\n });\n };\n\n const addRawArg = (optionName: string, rawArg: string) => {\n if (!results._info) results._info = {};\n if (!results._info[optionName]) results._info[optionName] = Object.create({});\n results._info[optionName].rawArg = rawArg;\n };\n\n const addRawValue = (optionName: string, rawValue: string) => {\n if (!results._info) results._info = {};\n if (!results._info[optionName]) results._info[optionName] = Object.create({});\n results._info[optionName].rawValue = rawValue;\n };\n\n const addSource = (optionName: string, source: \"cli\" | \"default\") => {\n if (!results._info) results._info = {};\n if (!results._info[optionName]) results._info[optionName] = Object.create({});\n results._info[optionName].source = source;\n };\n\n const fillOption = (optionName: string, value: Option) => {\n if (!results._info) results._info = {};\n if (!results._info[optionName]) results._info[optionName] = Object.create({});\n Object.assign(results._info[optionName], value);\n };\n\n for (let i = 0; i < argsv.length; i++) {\n const arg = argsv[i];\n\n // * subcommand\n if (i === 0) {\n results.subcommand = allSubcommands.has(arg) ? arg : undefined;\n\n // add positional and arguments array\n const subcommandProps = GetSubcommandProps();\n if (subcommandProps?.allowPositional) results.positional = [];\n if (subcommandProps?.arguments?.length) results.arguments = [];\n\n if (results.subcommand) continue;\n }\n\n // * option\n const argAndValue = arg.split(\"=\").filter(Boolean);\n const argWithEquals = arg.includes(\"=\");\n const argument = argAndValue[0];\n const argValue: string | undefined = argAndValue[1];\n\n if (isOptionArg(argument)) {\n if (isFlagArg(argument) && argWithEquals) {\n throw new Error(`Flag arguments cannot be assigned using \"=\": \"${arg}\"`);\n }\n\n const subcommandProps = GetSubcommandProps();\n if (!subcommandProps) throw new Error(`Unknown subcommand: \"${results.subcommand}\"`);\n\n if (!subcommandProps.options) {\n const msg = !results.subcommand\n ? \"options are not allowed here\"\n : `subcommand \"${results.subcommand}\" does not allow options`;\n throw new Error(`Error: ${msg}: \"${argument}\"`);\n }\n\n const optionName = transformArg(argument);\n const isNegative = argument.startsWith(\"--no-\");\n\n const option = subcommandProps.options.find(o => {\n if (o.name === optionName) return true;\n if (isNegative && noName(o.name) === optionName) return true;\n\n if (!o.aliases) return false;\n if (o.aliases.includes(optionName)) return true;\n if (isNegative && o.aliases.map(noName).includes(optionName)) return true;\n\n return false;\n });\n\n if (!option) {\n throw new Error(`Unknown option: \"${argument}\"`);\n }\n\n if (option.name in results) {\n throw new Error(`Duplicated option: \"${argument}\"`);\n }\n\n const isTypeBoolean = isBooleanSchema(option.type);\n const nextArg = argsv[i + 1];\n\n let optionValue: string | boolean = argWithEquals ? argValue : nextArg;\n\n if (isTypeBoolean) {\n if (argWithEquals) {\n const parsedBoolean = stringToBoolean(argValue);\n optionValue = isNegative ? !parsedBoolean : parsedBoolean;\n } else {\n optionValue = !isNegative;\n }\n }\n\n if (typeof optionValue === \"undefined\") {\n throw new Error(`Expected a value for \"${argument}\" but got nothing`);\n }\n\n if (!argWithEquals && isOptionArg(optionValue)) {\n throw new Error(`Expected a value for \"${argument}\" but got an argument \"${nextArg}\"`);\n }\n\n const res = option.type.safeParse(optionValue);\n if (!res.success) {\n throw new Error(`Invalid value \"${optionValue}\" for \"${argument}\": ${res.error.errors[0].message}`);\n }\n\n results[option.name] = res.data;\n addRawArg(option.name, argument);\n const rawVal = argWithEquals ? argValue : isTypeBoolean ? \"\" : nextArg;\n addRawValue(option.name, rawVal);\n fillOption(option.name, option);\n\n if (!argWithEquals && !isTypeBoolean) i++;\n continue;\n }\n\n const subcommandProps = GetSubcommandProps();\n\n // * arguments\n if (subcommandProps?.arguments?.length) {\n if (!results.arguments) results.arguments = [];\n\n const currentArgCount = results.arguments.length;\n\n if (currentArgCount < subcommandProps.arguments.length) {\n const argType = subcommandProps.arguments[currentArgCount].type;\n\n let argValue: string | boolean = arg;\n const isTypeBoolean = isBooleanSchema(argType);\n if (isTypeBoolean) argValue = stringToBoolean(argValue);\n\n const res = argType.safeParse(argValue);\n if (!res.success) {\n throw new Error(\n `The ${getOrdinalPlacement(currentArgCount)} argument \"${arg}\" is invalid: ${res.error.errors[0].message}`,\n );\n }\n\n results.arguments.push(res.data);\n continue;\n }\n }\n\n // * positional\n if (subcommandProps?.allowPositional) {\n if (!results.positional) results.positional = [];\n results.positional.push(arg);\n continue;\n }\n\n const msg = !results.subcommand ? \"here\" : `for subcommand \"${results.subcommand}\"`;\n throw new Error(`Unexpected argument \"${arg}\": positional arguments are not allowed ${msg}`);\n }\n\n // check for missing options - set defaults - add _source\n const subcommandProps = GetSubcommandProps();\n if (subcommandProps?.options?.length) {\n for (const option of subcommandProps.options) {\n if (option.name in results) {\n addSource(option.name, \"cli\");\n fillOption(option.name, option);\n continue;\n }\n\n if (option.type.isOptional()) {\n const hasDefault = typeof option.type._def.defaultValue === \"function\";\n if (!hasDefault) continue;\n results[option.name] = option.type._def.defaultValue();\n addSource(option.name, \"default\");\n fillOption(option.name, option);\n continue;\n }\n\n throw new Error(`Missing required option: ${transformOptionToArg(option.name)}`);\n }\n }\n\n // check for arguments - set defaults\n if (subcommandProps?.arguments?.length) {\n const currentArgCount = results.arguments?.length ?? 0;\n const subcommandArgCount = subcommandProps.arguments.length;\n\n // missing arguments\n if (currentArgCount < subcommandArgCount) {\n for (let i = currentArgCount; i < subcommandArgCount; i++) {\n const argumentType = subcommandProps.arguments[i].type;\n const hasDefault = typeof argumentType._def.defaultValue === \"function\";\n if (hasDefault && results.arguments) {\n results.arguments.push(argumentType._def.defaultValue());\n continue;\n }\n\n if (argumentType.isOptional()) continue;\n\n throw new Error(`the ${getOrdinalPlacement(i)} argument is required: \"${subcommandProps.arguments[i].name}\"`);\n }\n }\n }\n\n if (subcommandProps?.action) {\n subcommandProps.action(results);\n }\n\n return results as UnSafeParseResult<[...T, NoSubcommand & U]>;\n}\n\nexport function safeParse<T extends Subcommand[], U extends Cli>(\n argsv: string[],\n ...params: [U, ...T]\n): SafeParseResult<[...T, NoSubcommand & U]> {\n const cliOptions = (\"cliName\" in params[0] ? params[0] : {}) as U;\n const subcommandArr = params as Subcommand[];\n\n type PrintTypes = PrintMethods<T[number][\"name\"]>;\n type PrintCli = PrintTypes[\"printCliHelp\"];\n type PrintSubcommand = PrintTypes[\"printSubcommandHelp\"];\n\n const printCliHelp: PrintCli = opt => help.printCliHelp(params, opt);\n const printSubcommandHelp: PrintSubcommand = (subcommandStr, opt) => {\n const subcommand = subcommandArr.find(c => c.name === subcommandStr);\n if (!subcommand) return console.error(`Cannot print help for subcommand \"${subcommandStr}\" as it does not exist`);\n help.printSubcommandHelp(subcommand, opt, cliOptions.cliName);\n };\n\n try {\n const data = parse(argsv, ...params);\n // @ts-expect-error The operand of a 'delete' operator must be optional.\n delete data.printCliHelp;\n // @ts-expect-errorThe operand of a 'delete' operator must be optional.\n delete data.printSubcommandHelp;\n\n return {\n success: true,\n data: data as Omit<typeof data, \"printCliHelp\" | \"printSubcommandHelp\">,\n printCliHelp,\n printSubcommandHelp,\n } as SafeParseResult<[...T, NoSubcommand & U]>;\n } catch (e) {\n return {\n success: false,\n error: e as Error,\n printCliHelp,\n printSubcommandHelp,\n } as SafeParseResult<[...T, NoSubcommand & U]>;\n }\n}\n"],"mappings":"sHAAA,IAAAA,KAAA,CAAAC,OAAA,cACA,IAAAC,MAAA,CAAAD,OAAA,eAuBO,QAAS,CAAAE,KAAKA,CACnBC,KAAe,CAE8B,SAAAC,IAAA,CAAAC,SAAA,CAAAC,MAAA,CAD1CC,MAAM,KAAAC,KAAA,CAAAJ,IAAA,GAAAA,IAAA,MAAAK,IAAA,GAAAA,IAAA,CAAAL,IAAA,CAAAK,IAAA,IAANF,MAAM,CAAAE,IAAA,IAAAJ,SAAA,CAAAI,IAAA,GAET,KAAM,CAAAC,UAAU,CAAI,SAAS,EAAI,CAAAH,MAAM,CAAC,CAAC,CAAC,CAAGA,MAAM,CAAC,CAAC,CAAC,CAAG,CAAC,CAAO,CACjE,KAAM,CAAAI,aAAa,CAAGJ,MAAsB,CAC5C,KAAM,CAAAK,cAAc,CAAG,GAAI,CAAAC,GAAG,CAASF,aAAa,CAACG,OAAO,CAACC,CAAC,EAAI,CAACA,CAAC,CAACC,IAAI,CAAE,IAAID,CAAC,CAACE,OAAO,EAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAGlGd,KAAK,CAAG,GAAAe,oBAAa,EAACf,KAAK,CAAC,CAW5B,KAAM,CAAAgB,OAAkB,CAAG,CACzBC,UAAU,CAAEC,SAAS,CACrBC,YAAYA,CAACC,GAAG,CAAE,CAChBC,UAAI,CAACF,YAAY,CAACf,MAAM,CAAEgB,GAAG,CAAC,CAChC,CAAC,CACDE,mBAAmBA,CAACC,aAAa,CAAEH,GA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ACH,CACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["_help","require","_utils","parse","argsv","params","cliOptions","subcommandArr","allSubcommands","Set","flatMap","c","name","aliases","decoupleFlags","results","subcommand","undefined","printCliHelp","opt","help","printSubcommandHelp","subcommandStr","find","length","includes","console","error","cliName","GetSubcommandProps","cmd","addRawArg","optionName","rawArg","_info","Object","create","addRawValue","rawValue","addSource","source","fillOption","value","assign","i","arg","has","subcommandProps","allowPositional","positional","arguments","argAndValue","split","filter","Boolean","argWithEquals","argument","argValue","isOptionArg","isFlagArg","Error","options","msg","transformArg","isNegative","startsWith","option","o","noName","map","isTypeBoolean","isBooleanSchema","type","nextArg","optionValue","parsedBoolean","stringToBoolean","res","safeParse","success","errors","message","data","rawVal","currentArgCount","argType","getOrdinalPlacement","push","isOptional","hasDefault","_def","defaultValue","transformOptionToArg","subcommandArgCount","argumentType","action","e"],"sourceRoot":"../../src","sources":["parser.ts"],"sourcesContent":["import { help } from \"./help.js\";\nimport {\n decoupleFlags,\n getOrdinalPlacement,\n isBooleanSchema,\n isFlagArg,\n isOptionArg,\n noName,\n stringToBoolean,\n transformArg,\n transformOptionToArg,\n} from \"./utils.js\";\n\nimport type {\n Cli,\n NoSubcommand,\n Option,\n PrintHelpOpt,\n PrintMethods,\n SafeParseResult,\n Subcommand,\n UnSafeParseResult,\n} from \"./types.js\";\n\nexport function parse<T extends Subcommand[], U extends Cli>(\n argsv: string[],\n ...params: [U, ...T]\n): UnSafeParseResult<[...T, NoSubcommand & U]> {\n const cliOptions = (\"cliName\" in params[0] ? params[0] : {}) as U;\n const subcommandArr = params as unknown as T;\n const allSubcommands = new Set<string>(subcommandArr.flatMap(c => [c.name, ...(c.aliases || [])]));\n\n // decouple flags E.g. `-rf` -> `-r, -f`\n argsv = decoupleFlags(argsv);\n\n type ResultObj = Record<string, unknown> & {\n subcommand: string | undefined;\n positional?: string[];\n arguments?: unknown[];\n _info?: Record<string, { rawArg?: string; rawValue?: string; source: \"cli\" | \"default\" }>;\n printCliHelp: (options?: PrintHelpOpt) => void;\n printSubcommandHelp: (subcommand: any, options?: PrintHelpOpt) => void;\n };\n\n const results: ResultObj = {\n subcommand: undefined,\n printCliHelp(opt) {\n help.printCliHelp(params, opt);\n },\n printSubcommandHelp(subcommandStr, opt) {\n const subcommand = subcommandArr.find(c => {\n if (c.name === subcommandStr) return true;\n if (!subcommandStr) return false;\n if (!c.aliases?.length) return false;\n return c.aliases.includes(subcommandStr);\n });\n if (!subcommand) return console.error(`Cannot print help for subcommand \"${subcommandStr}\" as it does not exist`);\n help.printSubcommandHelp(subcommand, opt, cliOptions.cliName);\n },\n };\n\n /** - Get current subcommand props */\n const GetSubcommandProps = (cmd = results.subcommand) => {\n return subcommandArr.find(c => {\n if (c.name === cmd) return true;\n if (!cmd) return false;\n if (!c.aliases?.length) return false;\n return c.aliases.includes(cmd);\n });\n };\n\n const addRawArg = (optionName: string, rawArg: string) => {\n if (!results._info) results._info = {};\n if (!results._info[optionName]) results._info[optionName] = Object.create({});\n results._info[optionName].rawArg = rawArg;\n };\n\n const addRawValue = (optionName: string, rawValue: string) => {\n if (!results._info) results._info = {};\n if (!results._info[optionName]) results._info[optionName] = Object.create({});\n results._info[optionName].rawValue = rawValue;\n };\n\n const addSource = (optionName: string, source: \"cli\" | \"default\") => {\n if (!results._info) results._info = {};\n if (!results._info[optionName]) results._info[optionName] = Object.create({});\n results._info[optionName].source = source;\n };\n\n const fillOption = (optionName: string, value: Option) => {\n if (!results._info) results._info = {};\n if (!results._info[optionName]) results._info[optionName] = Object.create({});\n Object.assign(results._info[optionName], value);\n };\n\n for (let i = 0; i < argsv.length; i++) {\n const arg = argsv[i];\n\n // * subcommand\n if (i === 0) {\n results.subcommand = allSubcommands.has(arg) ? arg : undefined;\n\n // add positional and arguments array\n const subcommandProps = GetSubcommandProps();\n if (subcommandProps?.allowPositional) results.positional = [];\n if (subcommandProps?.arguments?.length) results.arguments = [];\n\n if (results.subcommand) continue;\n }\n\n // * option\n const argAndValue = arg.split(\"=\").filter(Boolean);\n const argWithEquals = arg.includes(\"=\");\n const argument = argAndValue[0];\n const argValue: string | undefined = argAndValue[1];\n\n if (isOptionArg(argument)) {\n if (isFlagArg(argument) && argWithEquals) {\n throw new Error(`Flag arguments cannot be assigned using \"=\": \"${arg}\"`);\n }\n\n const subcommandProps = GetSubcommandProps();\n if (!subcommandProps) throw new Error(`Unknown subcommand: \"${results.subcommand}\"`);\n\n if (!subcommandProps.options) {\n const msg = !results.subcommand\n ? \"options are not allowed here\"\n : `subcommand \"${results.subcommand}\" does not allow options`;\n throw new Error(`Error: ${msg}: \"${argument}\"`);\n }\n\n const optionName = transformArg(argument);\n const isNegative = argument.startsWith(\"--no-\");\n\n const option = subcommandProps.options.find(o => {\n if (o.name === optionName) return true;\n if (isNegative && noName(o.name) === optionName) return true;\n\n if (!o.aliases) return false;\n if (o.aliases.includes(optionName)) return true;\n if (isNegative && o.aliases.map(noName).includes(optionName)) return true;\n\n return false;\n });\n\n if (!option) {\n throw new Error(`Unknown option: \"${argument}\"`);\n }\n\n if (option.name in results) {\n throw new Error(`Duplicated option: \"${argument}\"`);\n }\n\n const isTypeBoolean = isBooleanSchema(option.type);\n const nextArg = argsv[i + 1];\n\n let optionValue: string | boolean = argWithEquals ? argValue : nextArg;\n\n if (isTypeBoolean) {\n if (argWithEquals) {\n const parsedBoolean = stringToBoolean(argValue);\n optionValue = isNegative ? !parsedBoolean : parsedBoolean;\n } else {\n optionValue = !isNegative;\n }\n }\n\n if (typeof optionValue === \"undefined\") {\n throw new Error(`Expected a value for \"${argument}\" but got nothing`);\n }\n\n if (!argWithEquals && isOptionArg(optionValue)) {\n throw new Error(`Expected a value for \"${argument}\" but got an argument \"${nextArg}\"`);\n }\n\n const res = option.type.safeParse(optionValue);\n if (!res.success) {\n throw new Error(`Invalid value \"${optionValue}\" for \"${argument}\": ${res.error.errors[0].message}`);\n }\n\n results[option.name] = res.data;\n addRawArg(option.name, argument);\n const rawVal = argWithEquals ? argValue : isTypeBoolean ? \"\" : nextArg;\n addRawValue(option.name, rawVal);\n fillOption(option.name, option);\n\n if (!argWithEquals && !isTypeBoolean) i++;\n continue;\n }\n\n const subcommandProps = GetSubcommandProps();\n\n // * arguments\n if (subcommandProps?.arguments?.length) {\n if (!results.arguments) results.arguments = [];\n\n const currentArgCount = results.arguments.length;\n\n if (currentArgCount < subcommandProps.arguments.length) {\n const argType = subcommandProps.arguments[currentArgCount].type;\n\n let argValue: string | boolean = arg;\n const isTypeBoolean = isBooleanSchema(argType);\n if (isTypeBoolean) argValue = stringToBoolean(argValue);\n\n const res = argType.safeParse(argValue);\n if (!res.success) {\n throw new Error(\n `The ${getOrdinalPlacement(currentArgCount)} argument \"${arg}\" is invalid: ${res.error.errors[0].message}`,\n );\n }\n\n results.arguments.push(res.data);\n continue;\n }\n }\n\n // * positional\n if (subcommandProps?.allowPositional) {\n if (!results.positional) results.positional = [];\n results.positional.push(arg);\n continue;\n }\n\n const msg = !results.subcommand ? \"here\" : `for subcommand \"${results.subcommand}\"`;\n throw new Error(`Unexpected argument \"${arg}\": positional arguments are not allowed ${msg}`);\n }\n\n // check for missing options - set defaults - add _source\n const subcommandProps = GetSubcommandProps();\n if (subcommandProps?.options?.length) {\n for (const option of subcommandProps.options) {\n if (option.name in results) {\n addSource(option.name, \"cli\");\n fillOption(option.name, option);\n continue;\n }\n\n if (option.type.isOptional()) {\n const hasDefault = typeof option.type._def.defaultValue === \"function\";\n if (!hasDefault) continue;\n results[option.name] = option.type._def.defaultValue();\n addSource(option.name, \"default\");\n fillOption(option.name, option);\n continue;\n }\n\n throw new Error(`Missing required option: ${transformOptionToArg(option.name)}`);\n }\n }\n\n // check for arguments - set defaults\n if (subcommandProps?.arguments?.length) {\n const currentArgCount = results.arguments?.length ?? 0;\n const subcommandArgCount = subcommandProps.arguments.length;\n\n // missing arguments\n if (currentArgCount < subcommandArgCount) {\n for (let i = currentArgCount; i < subcommandArgCount; i++) {\n const argumentType = subcommandProps.arguments[i].type;\n const hasDefault = typeof argumentType._def.defaultValue === \"function\";\n if (hasDefault && results.arguments) {\n results.arguments.push(argumentType._def.defaultValue());\n continue;\n }\n\n if (argumentType.isOptional()) continue;\n\n throw new Error(`the ${getOrdinalPlacement(i)} argument is required: \"${subcommandProps.arguments[i].name}\"`);\n }\n }\n }\n\n if (subcommandProps?.action) {\n subcommandProps.action(results);\n }\n\n return results as UnSafeParseResult<[...T, NoSubcommand & U]>;\n}\n\nexport function safeParse<T extends Subcommand[], U extends Cli>(\n argsv: string[],\n ...params: [U, ...T]\n): SafeParseResult<[...T, NoSubcommand & U]> {\n const cliOptions = (\"cliName\" in params[0] ? params[0] : {}) as U;\n const subcommandArr = params as Subcommand[];\n\n type PrintTypes = PrintMethods<T[number][\"name\"]>;\n type PrintCli = PrintTypes[\"printCliHelp\"];\n type PrintSubcommand = PrintTypes[\"printSubcommandHelp\"];\n\n const printCliHelp: PrintCli = opt => help.printCliHelp(params, opt);\n const printSubcommandHelp: PrintSubcommand = (subcommandStr, opt) => {\n const subcommand = subcommandArr.find(c => c.name === subcommandStr);\n if (!subcommand) return console.error(`Cannot print help for subcommand \"${subcommandStr}\" as it does not exist`);\n help.printSubcommandHelp(subcommand, opt, cliOptions.cliName);\n };\n\n try {\n const data = parse(argsv, ...params);\n // @ts-expect-error The operand of a 'delete' operator must be optional.\n delete data.printCliHelp;\n // @ts-expect-errorThe operand of a 'delete' operator must be optional.\n delete data.printSubcommandHelp;\n\n return {\n success: true,\n data: data as Omit<typeof data, \"printCliHelp\" | \"printSubcommandHelp\">,\n printCliHelp,\n printSubcommandHelp,\n } as SafeParseResult<[...T, NoSubcommand & U]>;\n } catch (e) {\n return {\n success: false,\n error: e as Error,\n printCliHelp,\n printSubcommandHelp,\n } as SafeParseResult<[...T, NoSubcommand & U]>;\n }\n}\n"],"mappings":"sHAAA,IAAAA,KAAA,CAAAC,OAAA,cACA,IAAAC,MAAA,CAAAD,OAAA,eAuBO,QAAS,CAAAE,KAAKA,CACnBC,KAAe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,KAAK,CAAE,GAAGC,MAAM,CAAC,CAEpC,MAAO,CAAA6E,IAAI,CAAChE,YAAY,CAExB,MAAO,CAAAgE,IAAI,CAAC7D,mBAAmB,CAE/B,MAAO,CACL0D,OAAO,CAAE,IAAI,CACbG,IAAI,CAAEA,IAAiE,CACvEhE,YAAY,CACZG,mBACF,CAAC,CACH,CAAE,MAAO2E,CAAC,CAAE,CACV,MAAO,CACLjB,OAAO,CAAE,KAAK,CACdpD,KAAK,CAAEqE,CAAU,CACjB9E,YAAY,CACZG,mBACF,CAAC,CACH,CACF","ignoreList":[]}
|
package/lib/commonjs/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.addIndentLn=addIndentLn;exports.concat=concat;exports.decoupleFlags=decoupleFlags;exports.getDefaultValueFromSchema=getDefaultValueFromSchema;exports.getOrdinalPlacement=getOrdinalPlacement;exports.indent=indent;exports.isBooleanSchema=isBooleanSchema;exports.isFlagArg=isFlagArg;exports.isLongArg=isLongArg;exports.isOptionArg=isOptionArg;exports.ln=ln;exports.noName=noName;exports.print=print;exports.println=println;exports.stringToBoolean=stringToBoolean;exports.transformArg=transformArg;exports.transformOptionToArg=transformOptionToArg;var _nodeAssert=_interopRequireDefault(require("node:assert"));var _zod=require("zod");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function transformArg(name){(0,_nodeAssert.default)(name.startsWith("-"),`[transformArg] Invalid arg name: ${name}`);name=name.startsWith("--")?name.substring(2):name.substring(1);return name.replace(/-([a-z])/g,g=>g[1].toUpperCase());}function transformOptionToArg(name){name=name.replace(/^[A-Z]/g,g=>g.toLowerCase());if(name.length===1)return`-${name}`;return`--${name.replace(/[A-Z]/g,g=>"-"+g.toLowerCase())}`;}function isFlagArg(name){return /^-[A-Z-a-z]$/.test(name);}function isLongArg(name){return /^--[A-Z-a-z-]+[A-Z-a-z]$/.test(name);}function isOptionArg(name){if(typeof name!=="string")return false;return isFlagArg(name)||isLongArg(name);}function noName(name){if(name.length===1)return name;return"no"+name.replace(/^[a-z]/,g=>g.toUpperCase());}function stringToBoolean(str){if(str.toLowerCase()==="true")return true;if(str.toLowerCase()==="false")return false;throw new Error(`[stringToBoolean] Invalid boolean value: "${str}"; Expected "true" or "false"`);}function getOrdinalPlacement(index){if(index<0)return"";const suffixes=["th","st","nd","rd"];const lastDigit=index%10;const lastTwoDigits=index%100;const suffix=lastDigit===1&&lastTwoDigits!==11?suffixes[1]:lastDigit===2&&lastTwoDigits!==12?suffixes[2]:lastDigit===3&&lastTwoDigits!==13?suffixes[3]:suffixes[0];return`${index+1}${suffix}`;}function isBooleanSchema(schema){let type=schema;while(type){if(type instanceof _zod.z.ZodBoolean){return true;}if(type instanceof _zod.z.ZodLiteral){return type.value===true||type.value===false;}type=type._def.innerType;}return false;}function getDefaultValueFromSchema(schema){let type=schema;while(type){if(type instanceof _zod.z.ZodDefault){const defaultValue=type._def.defaultValue();return defaultValue;}type=type._def.innerType;}return undefined;}function decoupleFlags(args){const flagsRe=/^-[a-z]{2,}$/i;const result=[];for(let i=0;i<args.length;i++){const arg=args[i];const isCoupled=flagsRe.test(arg);if(!isCoupled){result.push(arg);continue;}const decoupledArr=arg.substring(1).split("").map(c=>"-"+c);result.push(...decoupledArr);}return result;}function print(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.addIndentLn=addIndentLn;exports.concat=concat;exports.decoupleFlags=decoupleFlags;exports.getDefaultValueFromSchema=getDefaultValueFromSchema;exports.getOrdinalPlacement=getOrdinalPlacement;exports.indent=indent;exports.isBooleanSchema=isBooleanSchema;exports.isFlagArg=isFlagArg;exports.isLongArg=isLongArg;exports.isOptionArg=isOptionArg;exports.ln=ln;exports.noName=noName;exports.print=print;exports.println=println;exports.stringToBoolean=stringToBoolean;exports.transformArg=transformArg;exports.transformOptionToArg=transformOptionToArg;var _nodeAssert=_interopRequireDefault(require("node:assert"));var _zod=require("zod");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function transformArg(name){(0,_nodeAssert.default)(name.startsWith("-"),`[transformArg] Invalid arg name: ${name}`);name=name.startsWith("--")?name.substring(2):name.substring(1);return name.replace(/-([a-z])/g,g=>g[1].toUpperCase());}function transformOptionToArg(name){name=name.replace(/^[A-Z]/g,g=>g.toLowerCase());if(name.length===1)return`-${name}`;return`--${name.replace(/[A-Z]/g,g=>"-"+g.toLowerCase())}`;}function isFlagArg(name){return /^-[A-Z-a-z]$/.test(name);}function isLongArg(name){return /^--[A-Z-a-z-]+[A-Z-a-z]$/.test(name);}function isOptionArg(name){if(typeof name!=="string")return false;return isFlagArg(name)||isLongArg(name);}function noName(name){if(name.length===1)return name;return"no"+name.replace(/^[a-z]/,g=>g.toUpperCase());}function stringToBoolean(str){if(str.toLowerCase()==="true")return true;if(str.toLowerCase()==="false")return false;throw new Error(`[stringToBoolean] Invalid boolean value: "${str}"; Expected "true" or "false"`);}function getOrdinalPlacement(index){if(index<0)return"";const suffixes=["th","st","nd","rd"];const lastDigit=index%10;const lastTwoDigits=index%100;const suffix=lastDigit===1&&lastTwoDigits!==11?suffixes[1]:lastDigit===2&&lastTwoDigits!==12?suffixes[2]:lastDigit===3&&lastTwoDigits!==13?suffixes[3]:suffixes[0];return`${index+1}${suffix}`;}function isBooleanSchema(schema){let type=schema;while(type){if(type instanceof _zod.z.ZodBoolean){return true;}if(type instanceof _zod.z.ZodLiteral){return type.value===true||type.value===false;}type=type._def.innerType;}return false;}function getDefaultValueFromSchema(schema){let type=schema;while(type){if(type instanceof _zod.z.ZodDefault){const defaultValue=type._def.defaultValue();return defaultValue;}type=type._def.innerType;}return undefined;}function decoupleFlags(args){const flagsRe=/^-[a-z]{2,}$/i;const result=[];for(let i=0;i<args.length;i++){const arg=args[i];const isCoupled=flagsRe.test(arg);if(!isCoupled){result.push(arg);continue;}const decoupledArr=arg.substring(1).split("").map(c=>"-"+c);result.push(...decoupledArr);}return result;}function print(...messages){return process.stdout.write(messages.join(" "));}function println(...messages){messages=messages.filter(Boolean);return console.log(...messages);}function ln(count){return"\n".repeat(count);}function indent(count){return" ".repeat(count);}function addIndentLn(message,indent=""){return message.replace(/\n/g,`\n${indent}`);}function concat(...messages){messages=messages.filter(Boolean);return messages.join(" ");}
|