botparty 0.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +103 -0
  2. package/dist/index.js +159 -0
  3. package/package.json +43 -0
package/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # botparty
2
+
3
+ CLI for [BotParty](https://botparty.club) — federated bot identity, authentication, and payments.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g botparty
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```bash
14
+ # Just run it — no setup needed
15
+ botparty curl https://api.example.com/data
16
+ ```
17
+
18
+ That's it. On first run, BotParty automatically:
19
+
20
+ 1. Generates an Ed25519 keypair
21
+ 2. Registers a namespace like `brave-fox-a3f2`
22
+ 3. Signs a JWT and sends the authenticated request
23
+
24
+ ### How it works
25
+
26
+ ```
27
+ botparty curl <url>
28
+
29
+ ├── Not registered? → auto-register namespace + keypair
30
+ ├── Key going stale? → auto-rotate
31
+ ├── Sign JWT → send request with Authorization: Bearer <jwt>
32
+
33
+ └── Error? → typed output with action URLs
34
+ ├── 423: "Namespace locked — unlock at: https://..."
35
+ ├── 402: "Payment required — top up at: https://..."
36
+ └── 403: "Missing scopes" or "Link a human account at: https://..."
37
+ ```
38
+
39
+ ---
40
+
41
+ ## Commands
42
+
43
+ ### Identity
44
+
45
+ ```bash
46
+ botparty init [namespace] # Register (auto-generates name if omitted)
47
+ botparty init my-bot --ttl 30 # Custom namespace, 30min key rotation
48
+ botparty whoami # Show current identity
49
+ botparty info [namespace] # Show namespace info from server
50
+ botparty link # Generate URL for a human to claim ownership
51
+ botparty reset # Clear local state
52
+ botparty destroy --yes # Destroy namespace (irreversible)
53
+ ```
54
+
55
+ ### Authenticated Requests
56
+
57
+ ```bash
58
+ botparty curl https://api.example.com/data
59
+ botparty curl https://api.example.com -X POST -d '{"key":"val"}'
60
+ botparty curl https://api.example.com -H "X-Custom: value"
61
+ botparty token # Print a signed JWT to stdout
62
+ ```
63
+
64
+ ### Key Management
65
+
66
+ ```bash
67
+ botparty keys list # List all keys
68
+ botparty keys rotate # Rotate current key
69
+ botparty keys rotate <keyId> # Rotate a specific key
70
+ botparty keys add \ # Add a delegated key
71
+ --public-key "..." \
72
+ --scopes "mongo://prod/*:read" \
73
+ --ttl 60
74
+ botparty keys delete <keyId> --yes
75
+ botparty keys invalidate <keyId> --yes # Panic button — locks namespace
76
+ ```
77
+
78
+ ---
79
+
80
+ ## Global Options
81
+
82
+ | Flag | Env Variable | Default | Description |
83
+ |------|-------------|---------|-------------|
84
+ | `--server <url>` | `BOTPARTY_SERVER_URL` | `https://id.botparty.club` | BotParty server URL |
85
+ | `--state-dir <path>` | `BOTPARTY_STATE_DIR` | `~/.botparty` | Local state directory |
86
+ | `--json` | — | — | Machine-readable JSON output |
87
+
88
+ ---
89
+
90
+ ## Local Storage
91
+
92
+ All state is stored in `~/.botparty/`:
93
+
94
+ | File | Contents |
95
+ |------|----------|
96
+ | `identity.json` | Namespace, key ID, algorithm, rotation info |
97
+ | `private.pem` | Ed25519 private key (mode 0600) |
98
+
99
+ ---
100
+
101
+ ## License
102
+
103
+ MIT
package/dist/index.js ADDED
@@ -0,0 +1,159 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from "module";
3
+ const require = __createRequire(import.meta.url);
4
+ var er=Object.create;var Ze=Object.defineProperty;var tr=Object.getOwnPropertyDescriptor;var rr=Object.getOwnPropertyNames;var nr=Object.getPrototypeOf,ir=Object.prototype.hasOwnProperty;var z=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var H=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var sr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of rr(e))!ir.call(t,i)&&i!==r&&Ze(t,i,{get:()=>e[i],enumerable:!(n=tr(e,i))||n.enumerable});return t};var or=(t,e,r)=>(r=t!=null?er(nr(t)):{},sr(e||!t||!t.__esModule?Ze(r,"default",{value:t,enumerable:!0}):r,t));var ee=H(Pe=>{var ae=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},Te=class extends ae{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Pe.CommanderError=ae;Pe.InvalidArgumentError=Te});var ce=H(xe=>{var{InvalidArgumentError:bn}=ee(),Re=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:(r.push(e),r)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new bn(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function En(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}xe.Argument=Re;xe.humanReadableArgName=En});var He=H(De=>{var{humanReadableArgName:An}=ce(),Ie=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let r=e.commands.filter(i=>!i._hidden),n=e._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((i,s)=>i.name().localeCompare(s.name())),r}compareOptions(e,r){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(i=>!i.hidden),n=e._getHelpOption();if(n&&!n.hidden){let i=n.short&&e._findOption(n.short),s=n.long&&e._findOption(n.long);!i&&!s?r.push(n):n.long&&!s?r.push(e.createOption(n.long,n.description)):n.short&&!i&&r.push(e.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let i=n.options.filter(s=>!s.hidden);r.push(...i)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>An(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(i)))),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleOptionTerm(r.optionTerm(i)))),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,i)=>Math.max(n,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(i)))),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let i=e.parent;i;i=i.parent)n=i.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,r,n){return r.length===0?[]:[n.styleTitle(e),...r,""]}groupItems(e,r,n){let i=new Map;return e.forEach(s=>{let o=n(s);i.has(o)||i.set(o,[])}),r.forEach(s=>{let o=n(s);i.has(o)||i.set(o,[]),i.get(o).push(s)}),i}formatHelp(e,r){let n=r.padWidth(e,r),i=r.helpWidth??80;function s(d,h){return r.formatItem(d,n,h,r)}let o=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(e))}`,""],a=r.commandDescription(e);a.length>0&&(o=o.concat([r.boxWrap(r.styleCommandDescription(a),i),""]));let c=r.visibleArguments(e).map(d=>s(r.styleArgumentTerm(r.argumentTerm(d)),r.styleArgumentDescription(r.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",c,r)),this.groupItems(e.options,r.visibleOptions(e),d=>d.helpGroupHeading??"Options:").forEach((d,h)=>{let y=d.map(O=>s(r.styleOptionTerm(r.optionTerm(O)),r.styleOptionDescription(r.optionDescription(O))));o=o.concat(this.formatItemList(h,y,r))}),r.showGlobalOptions){let d=r.visibleGlobalOptions(e).map(h=>s(r.styleOptionTerm(r.optionTerm(h)),r.styleOptionDescription(r.optionDescription(h))));o=o.concat(this.formatItemList("Global Options:",d,r))}return this.groupItems(e.commands,r.visibleCommands(e),d=>d.helpGroup()||"Commands:").forEach((d,h)=>{let y=d.map(O=>s(r.styleSubcommandTerm(r.subcommandTerm(O)),r.styleSubcommandDescription(r.subcommandDescription(O))));o=o.concat(this.formatItemList(h,y,r))}),o.join(`
5
+ `)}displayWidth(e){return Ot(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r==="[command]"?this.styleSubcommandText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleCommandText(r)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleSubcommandText(r)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,r,n,i){let o=" ".repeat(2);if(!n)return o+e;let a=e.padEnd(r+e.length-i.displayWidth(e)),c=2,l=(this.helpWidth??80)-r-c-2,d;return l<this.minWidthToWrap||i.preformatted(n)?d=n:d=i.boxWrap(n,l).replace(/\n/g,`
6
+ `+" ".repeat(r+c)),o+a+" ".repeat(c)+d.replace(/\n/g,`
7
+ ${o}`)}boxWrap(e,r){if(r<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,s=[];return n.forEach(o=>{let a=o.match(i);if(a===null){s.push("");return}let c=[a.shift()],u=this.displayWidth(c[0]);a.forEach(l=>{let d=this.displayWidth(l);if(u+d<=r){c.push(l),u+=d;return}s.push(c.join(""));let h=l.trimStart();c=[h],u=this.displayWidth(h)}),s.push(c.join(""))}),s.join(`
8
+ `)}};function Ot(t){let e=/\x1b\[\d*(;\d*)*m/g;return t.replace(e,"")}De.Help=Ie;De.stripColor=Ot});var Ke=H(Ne=>{var{InvalidArgumentError:_n}=ee(),Ue=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Sn(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:(r.push(e),r)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new _n(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Tt(this.name().replace(/^no-/,"")):Tt(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Le=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let i=this.negativeOptions.get(n).presetArg,s=i!==void 0?i:!1;return r.negate===(s===e)}};function Tt(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Sn(t){let e,r,n=/^-[^-]$/,i=/^--[^-]/,s=t.split(/[ |,]+/).concat("guard");if(n.test(s[0])&&(e=s.shift()),i.test(s[0])&&(r=s.shift()),!e&&n.test(s[0])&&(e=s.shift()),!e&&i.test(s[0])&&(e=r,r=s.shift()),s[0].startsWith("-")){let o=s[0],a=`option creation failed due to '${o}' in option flags '${t}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
9
+ - a short flag is a single dash and a single character
10
+ - either use a single dash and a single character (for a short flag)
11
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(o)?new Error(`${a}
12
+ - too many short flags`):i.test(o)?new Error(`${a}
13
+ - too many long flags`):new Error(`${a}
14
+ - unrecognised flag format`)}if(e===void 0&&r===void 0)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:r}}Ne.Option=Ue;Ne.DualOptions=Le});var Rt=H(Pt=>{function vn(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=t.length;i++){let s=1;t[i-1]===e[n-1]?s=0:s=1,r[i][n]=Math.min(r[i-1][n]+1,r[i][n-1]+1,r[i-1][n-1]+s),i>1&&n>1&&t[i-1]===e[n-2]&&t[i-2]===e[n-1]&&(r[i][n]=Math.min(r[i][n],r[i-2][n-2]+1))}return r[t.length][e.length]}function kn(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let n=[],i=3,s=.4;return e.forEach(o=>{if(o.length<=1)return;let a=vn(t,o),c=Math.max(t.length,o.length);(c-a)/c>s&&(a<i?(i=a,n=[o]):a===i&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),r&&(n=n.map(o=>`--${o}`)),n.length>1?`
15
+ (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
16
+ (Did you mean ${n[0]}?)`:""}Pt.suggestSimilar=kn});var Ht=H(Fe=>{var Cn=z("node:events").EventEmitter,We=z("node:child_process"),x=z("node:path"),le=z("node:fs"),p=z("node:process"),{Argument:$n,humanReadableArgName:On}=ce(),{CommanderError:je}=ee(),{Help:Tn,stripColor:Pn}=He(),{Option:xt,DualOptions:Rn}=Ke(),{suggestSimilar:It}=Rt(),Me=class t extends Cn{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:r=>p.stdout.write(r),writeErr:r=>p.stderr.write(r),outputError:(r,n)=>n(r),getOutHelpWidth:()=>p.stdout.isTTY?p.stdout.columns:void 0,getErrHelpWidth:()=>p.stderr.isTTY?p.stderr.columns:void 0,getOutHasColors:()=>Ve()??(p.stdout.isTTY&&p.stdout.hasColors?.()),getErrHasColors:()=>Ve()??(p.stderr.isTTY&&p.stderr.hasColors?.()),stripColor:r=>Pn(r)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let i=r,s=n;typeof i=="object"&&i!==null&&(s=i,i=null),s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return i&&(c.description(i),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),i?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Tn,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
17
+ - specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new $n(e,r)}argument(e,r,n,i){let s=this.createArgument(e,r);return typeof n=="function"?s.default(i).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r?.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let n=e??"help [command]",[,i,s]=n.match(/([^ ]+) *(.*)/),o=r??"display help for command",a=this.createCommand(i);return a.helpOption(!1),s&&a.arguments(s),o&&a.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||r)&&this._initCommandGroup(a),this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
18
+ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new je(e,r,n)),p.exit(e)}action(e){let r=n=>{let i=this.registeredArguments.length,s=n.slice(0,i);return this._storeOptionsAsProperties?s[i]=this:s[i]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=r,this}createOption(e,r){return new xt(e,r)}_callParseArg(e,r,n,i){try{return e.parseArg(r,n)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${i} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
19
+ - already used by option '${r.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let r=i=>[i.name()].concat(i.aliases()),n=r(e).find(i=>this._findCommand(i));if(n){let i=r(this._findCommand(n)).join("|"),s=r(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${i}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(s,o,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,o):s!==null&&e.variadic&&(s=e._collectValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,a)};return this.on("option:"+r,s=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;i(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;i(s,o,"env")}),this}_optionEx(e,r,n,i,s){if(typeof r=="object"&&r instanceof xt)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(r,n);if(o.makeOptionMandatory(!!e.mandatory),typeof i=="function")o.default(s).argParser(i);else if(i instanceof RegExp){let a=i;i=(c,u)=>{let l=a.exec(c);return l?l[0]:u},o.default(s).argParser(i)}else o.default(i);return this.addOption(o)}option(e,r,n,i){return this._optionEx({},e,r,n,i)}requiredOption(e,r,n,i){return this._optionEx({mandatory:!0},e,r,n,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){p.versions?.electron&&(r.from="electron");let i=p.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(r.from="eval")}e===void 0&&(e=p.argv),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":p.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){this._prepareForParse();let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){this._prepareForParse();let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
20
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,r,n){if(le.existsSync(e))return;let i=r?`searched for local subcommand relative to directory '${r}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${e}' does not exist
21
+ - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
22
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
23
+ - ${i}`;throw new Error(s)}_executeSubCommand(e,r){r=r.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function s(l,d){let h=x.resolve(l,d);if(le.existsSync(h))return h;if(i.includes(x.extname(d)))return;let y=i.find(O=>le.existsSync(`${h}${O}`));if(y)return`${h}${y}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let l;try{l=le.realpathSync(this._scriptPath)}catch{l=this._scriptPath}a=x.resolve(x.dirname(l),a)}if(a){let l=s(a,o);if(!l&&!e._executableFile&&this._scriptPath){let d=x.basename(this._scriptPath,x.extname(this._scriptPath));d!==this._name&&(l=s(a,`${d}-${e._name}`))}o=l||o}n=i.includes(x.extname(o));let c;p.platform!=="win32"?n?(r.unshift(o),r=Dt(p.execArgv).concat(r),c=We.spawn(p.argv[0],r,{stdio:"inherit"})):c=We.spawn(o,r,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),r.unshift(o),r=Dt(p.execArgv).concat(r),c=We.spawn(p.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{p.on(d,()=>{c.killed===!1&&c.exitCode===null&&c.kill(d)})});let u=this._exitCallback;c.on("close",l=>{l=l??1,u?u(new je(l,"commander.executeSubCommandAsync","(close)")):p.exit(l)}),c.on("error",l=>{if(l.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(l.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)p.exit(1);else{let d=new je(1,"commander.executeSubCommandAsync","(error)");d.nestedError=l,u(d)}}),this.runningCommand=c}_dispatchSubcommand(e,r,n){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,i,"preSubcommand"),s=this._chainOrCall(s,()=>{if(i._executableHandler)this._executeSubCommand(i,r.concat(n));else return i._parseCommand(r,n)}),s}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,i,s)=>{let o=i;if(i!==null&&n.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,i,s,a)}return o};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,i)=>{let s=n.defaultValue;n.variadic?i<this.args.length?(s=this.args.slice(i),n.parseArg&&(s=s.reduce((o,a)=>e(n,a,o),n.defaultValue))):s===void 0&&(s=[]):i<this.args.length&&(s=this.args[i],n.parseArg&&(s=e(n,s,n.defaultValue))),r[i]=s}),this.processedArgs=r}_chainOrCall(e,r){return e?.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,i=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[r]!==void 0).forEach(s=>{s._lifeCycleHooks[r].forEach(o=>{i.push({hookedCommand:s,callback:o})})}),r==="postAction"&&i.reverse(),i.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let i=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{i=this._chainOrCall(i,()=>s(this,r))}),i}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(s,e,r)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent?.listenerCount(s))i(),this._processArguments(),this.parent.emit(s,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let i=n.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let i=e.find(s=>n.conflictsWith.includes(s.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],i=r;function s(l){return l.length>1&&l[0]==="-"}let o=l=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(l)?!this._getCommandAndAncestors().some(d=>d.options.map(h=>h.short).some(h=>/^-\d$/.test(h))):!1,a=null,c=null,u=0;for(;u<e.length||c;){let l=c??e[u++];if(c=null,l==="--"){i===n&&i.push(l),i.push(...e.slice(u));break}if(a&&(!s(l)||o(l))){this.emit(`option:${a.name()}`,l);continue}if(a=null,s(l)){let d=this._findOption(l);if(d){if(d.required){let h=e[u++];h===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,h)}else if(d.optional){let h=null;u<e.length&&(!s(e[u])||o(e[u]))&&(h=e[u++]),this.emit(`option:${d.name()}`,h)}else this.emit(`option:${d.name()}`);a=d.variadic?d:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let d=this._findOption(`-${l[1]}`);if(d){d.required||d.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${d.name()}`,l.slice(2)):(this.emit(`option:${d.name()}`),c=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let d=l.indexOf("="),h=this._findOption(l.slice(0,d));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,l.slice(d+1));continue}}if(i===r&&s(l)&&!(this.commands.length===0&&o(l))&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(l)){r.push(l),n.push(...e.slice(u));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){r.push(l,...e.slice(u));break}else if(this._defaultCommandName){n.push(l,...e.slice(u));break}}if(this._passThroughOptions){i.push(l,...e.slice(u));break}i.push(l)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let i=this.options[n].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
24
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
25
+ `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
26
+ `),this.outputHelp({error:!0}));let n=r||{},i=n.exitCode||1,s=n.code||"commander.error";this._exit(i,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in p.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,p.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Rn(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(i=>!r(i)).forEach(i=>{this.setOptionValueWithSource(i,n.implied[i],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=o=>{let a=o.attributeName(),c=this.getOptionValue(a),u=this.options.find(d=>d.negate&&a===d.attributeName()),l=this.options.find(d=>!d.negate&&a===d.attributeName());return u&&(u.presetArg===void 0&&c===!1||u.presetArg!==void 0&&c===u.presetArg)?u:l||o},i=o=>{let a=n(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${i(e)} cannot be used with ${i(r)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);i=i.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);r=It(e,i)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(s=>{i.push(s.name()),s.alias()&&i.push(s.alias())}),r=It(e,i)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let i=this.createOption(r,n);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
27
+ `),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>On(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=x.basename(e,x.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp(),n=this._getOutputContext(e);r.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let i=r.formatHelp(this,r);return n.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let r=!!e.error,n,i,s;return r?(n=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:r,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:i,helpWidth:s}}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getOutputContext(e),i={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let s=this.helpInformation({error:n.error});if(r&&(s=r(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",i))}helpOption(e,r){return typeof e=="boolean"?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??"-h, --help",r??"display help for command"),(e||r)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let r=Number(p.exitCode??0);r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
28
+ Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,s=>{let o;typeof r=="function"?o=r({error:s.error,command:s.command}):o=r,o&&s.write(`${o}
29
+ `)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(i=>r.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Dt(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",i="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?r=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=s[1],/^\d+$/.test(s[3])?i=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=s[1],n=s[3],i=s[4]),r&&i!=="0"?`${r}=${n}:${parseInt(i)+1}`:e})}function Ve(){if(p.env.NO_COLOR||p.env.FORCE_COLOR==="0"||p.env.FORCE_COLOR==="false")return!1;if(p.env.FORCE_COLOR||p.env.CLICOLOR_FORCE!==void 0)return!0}Fe.Command=Me;Fe.useColor=Ve});var Kt=H($=>{var{Argument:Ut}=ce(),{Command:qe}=Ht(),{CommanderError:xn,InvalidArgumentError:Lt}=ee(),{Help:In}=He(),{Option:Nt}=Ke();$.program=new qe;$.createCommand=t=>new qe(t);$.createOption=(t,e)=>new Nt(t,e);$.createArgument=(t,e)=>new Ut(t,e);$.Command=qe;$.Option=Nt;$.Argument=Ut;$.Help=In;$.CommanderError=xn;$.InvalidArgumentError=Lt;$.InvalidOptionArgumentError=Lt});import{readFileSync as Et,writeFileSync as At,mkdirSync as zr,existsSync as ie,unlinkSync as Xr}from"node:fs";import{join as M}from"node:path";import{homedir as Qr}from"node:os";import{randomBytes as _t}from"node:crypto";var ot=new TextEncoder,et=new TextDecoder,vi=2**32;function ar(...t){let e=t.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function pe(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}function at(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,r=[];for(let n=0;n<t.length;n+=e)r.push(String.fromCharCode.apply(null,t.subarray(n,n+e)));return btoa(r.join(""))}function ct(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function cr(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:et.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=et.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return ct(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function fe(t){let e=t;return typeof e=="string"&&(e=ot.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):at(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var I=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),N=(t,e)=>t.name===e;function lr(t){return parseInt(t.name.slice(4),10)}function me(t,e){if(lr(t.hash)!==e)throw I(`SHA-${e}`,"algorithm.hash")}function ur(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function dr(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function hr(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!N(t.algorithm,"HMAC"))throw I("HMAC");me(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!N(t.algorithm,"RSASSA-PKCS1-v1_5"))throw I("RSASSA-PKCS1-v1_5");me(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!N(t.algorithm,"RSA-PSS"))throw I("RSA-PSS");me(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!N(t.algorithm,"Ed25519"))throw I("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!N(t.algorithm,e))throw I(e);break}case"ES256":case"ES384":case"ES512":{if(!N(t.algorithm,"ECDSA"))throw I("ECDSA");let n=ur(e);if(t.algorithm.namedCurve!==n)throw I(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}dr(t,r)}function lt(t,e,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var ut=(t,...e)=>lt("Key must be ",t,...e),dt=(t,e,...r)=>lt(`Key for the ${t} algorithm must be `,e,...r),_e=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,e){super(t,e),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},C=class extends _e{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},X=class extends _e{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},pr=class extends _e{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},Se=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},ve=t=>t?.[Symbol.toStringTag]==="KeyObject",ht=t=>Se(t)||ve(t),ki=Symbol();function tt(t,e){if(t)throw new TypeError(`${e} can only be called once`)}var fr=t=>typeof t=="object"&&t!==null;function pt(t){if(!fr(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function mr(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let s of i){if(r.has(s))return!1;r.add(s)}}return!0}var ke=t=>pt(t)&&typeof t.kty=="string",gr=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),yr=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,wr=t=>t.kty==="oct"&&typeof t.k=="string";function br(t,e){if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function Er(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new C(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Ar(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(ut(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return hr(e,t,r),e}async function _r(t,e,r){let n=await Ar(t,e,"sign");br(t,n);let i=await crypto.subtle.sign(Er(t,n.algorithm),n,r);return new Uint8Array(i)}var re='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function Sr(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new C(re)}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new C(re)}break}case"EC":{switch(t.alg){case"ES256":case"ES384":case"ES512":e={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[t.alg]},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new C(re)}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new C(re)}break}default:throw new C('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function vr(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=Sr(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}var K="given KeyObject instance cannot be used for this algorithm",j,rt=async(t,e,r,n=!1)=>{j||=new WeakMap;let i=j.get(t);if(i?.[r])return i[r];let s=await vr({...e,alg:r});return n&&Object.freeze(t),i?i[r]=s:j.set(t,{[r]:s}),s},kr=(t,e)=>{j||=new WeakMap;let r=j.get(t);if(r?.[e])return r[e];let n=t.type==="public",i=!!n,s;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(K)}s=t.toCryptoKey(t.asymmetricKeyType,i,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(K);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError(K);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let o;switch(e){case"RSA-OAEP":o="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":o="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":o="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":o="SHA-512";break;default:throw new TypeError(K)}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},i,n?["encrypt"]:["decrypt"]);s=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},i,[n?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){let o=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!o)throw new TypeError(K);let a={ES256:"P-256",ES384:"P-384",ES512:"P-521"};a[e]&&o===a[e]&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:o},i,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(s=t.toCryptoKey({name:"ECDH",namedCurve:o},i,n?[]:["deriveBits"]))}if(!s)throw new TypeError(K);return r?r[e]=s:j.set(t,{[e]:s}),s};async function Cr(t,e){if(t instanceof Uint8Array||Se(t))return t;if(ve(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return kr(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return rt(t,r,e)}if(ke(t))return t.k?cr(t.k):rt(t,t,e,!0);throw new Error("unreachable")}var $r=(t,e)=>{let r=(t.match(/.{1,64}/g)||[]).join(`
30
+ `);return`-----BEGIN ${e}-----
31
+ ${r}
32
+ -----END ${e}-----`},ft=async(t,e,r)=>{if(ve(r)){if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return r.export({format:"pem",type:e})}if(!Se(r))throw new TypeError(ut(r,"CryptoKey","KeyObject"));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==t)throw new TypeError(`key is not a ${t} key`);return $r(at(new Uint8Array(await crypto.subtle.exportKey(e,r))),`${t.toUpperCase()} KEY`)},Or=t=>ft("public","spki",t),Tr=t=>ft("private","pkcs8",t),ge=(t,e)=>{if(t.byteLength!==e.length)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},Pr=t=>({data:t,pos:0}),Q=t=>{let e=t.data[t.pos++];if(e&128){let r=e&127,n=0;for(let i=0;i<r;i++)n=n<<8|t.data[t.pos++];return n}return e},Z=(t,e,r)=>{if(t.data[t.pos++]!==e)throw new Error(r)},mt=(t,e)=>{let r=t.data.subarray(t.pos,t.pos+e);return t.pos+=e,r},Rr=t=>{Z(t,6,"Expected algorithm OID");let e=Q(t);return mt(t,e)};function xr(t){Z(t,48,"Invalid PKCS#8 structure"),Q(t),Z(t,2,"Expected version field");let e=Q(t);t.pos+=e,Z(t,48,"Expected algorithm identifier");let r=Q(t);return{algIdStart:t.pos,algIdLength:r}}var Ir=t=>{let e=Rr(t);if(ge(e,[43,101,110]))return"X25519";if(!ge(e,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");Z(t,6,"Expected curve OID");let r=Q(t),n=mt(t,r);for(let{name:i,oid:s}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(ge(n,s))return i;throw new Error("Unsupported named curve")},Dr=async(t,e,r,n)=>{let i,s,o=t==="spki",a=()=>o?["verify"]:["sign"],c=()=>o?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},s=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":i={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},s=c();break;case"ES256":case"ES384":case"ES512":{i={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},s=a();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{let u=n.getNamedCurve(e);i=u==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:u}}catch{throw new C("Invalid or unsupported key format")}s=o?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":i={name:"Ed25519"},s=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":i={name:r},s=a();break;default:throw new C('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(t,e,i,n?.extractable??!!o,s)},Hr=(t,e)=>ct(t.replace(e,"")),Ur=(t,e,r)=>{let n=Hr(t,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),i=r;return e?.startsWith?.("ECDH-ES")&&(i||={},i.getNamedCurve=s=>{let o=Pr(s);return xr(o),Ir(o)}),Dr("pkcs8",n,e,i)};async function gt(t,e,r){if(typeof t!="string"||t.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Ur(t,e,r)}async function Lr(t){return Or(t)}async function Nr(t){return Tr(t)}function Kr(t,e,r,n,i){if(i.crit!==void 0&&n?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(o=>typeof o!="string"||o.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let o of n.crit){if(!s.has(o))throw new C(`Extension Header Parameter "${o}" is not recognized`);if(i[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(s.get(o)&&n[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}var W=t=>t?.[Symbol.toStringTag],Ee=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&t.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Wr=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(ke(e)){if(wr(e)&&Ee(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ht(e))throw new TypeError(dt(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${W(e)} instances for symmetric algorithms must be of type "secret"`)}},jr=(t,e,r)=>{if(ke(e))switch(r){case"decrypt":case"sign":if(gr(e)&&Ee(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(yr(e)&&Ee(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ht(e))throw new TypeError(dt(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${W(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${W(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${W(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${W(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${W(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Mr(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Wr(t,e,r);break;default:jr(t,e,r)}}var U=t=>Math.floor(t.getTime()/1e3),yt=60,wt=yt*60,Ce=wt*24,Vr=Ce*7,Fr=Ce*365.25,qr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function ye(t){let e=qr.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(r*yt);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(r*wt);break;case"day":case"days":case"d":i=Math.round(r*Ce);break;case"week":case"weeks":case"w":i=Math.round(r*Vr);break;default:i=Math.round(r*Fr);break}return e[1]==="-"||e[4]==="ago"?-i:i}function L(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var Gr=class{#e;constructor(t){if(!pt(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return ot.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(t){this.#e.iss=t}get sub(){return this.#e.sub}set sub(t){this.#e.sub=t}get aud(){return this.#e.aud}set aud(t){this.#e.aud=t}set jti(t){this.#e.jti=t}set nbf(t){typeof t=="number"?this.#e.nbf=L("setNotBefore",t):t instanceof Date?this.#e.nbf=L("setNotBefore",U(t)):this.#e.nbf=U(new Date)+ye(t)}set exp(t){typeof t=="number"?this.#e.exp=L("setExpirationTime",t):t instanceof Date?this.#e.exp=L("setExpirationTime",U(t)):this.#e.exp=U(new Date)+ye(t)}set iat(t){t===void 0?this.#e.iat=U(new Date):t instanceof Date?this.#e.iat=L("setIssuedAt",U(t)):typeof t=="string"?this.#e.iat=L("setIssuedAt",U(new Date)+ye(t)):this.#e.iat=L("setIssuedAt",t)}},bt=class{#e;#t;#r;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=t}setProtectedHeader(t){return tt(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return tt(this.#r,"setUnprotectedHeader"),this.#r=t,this}async sign(t,e){if(!this.#t&&!this.#r)throw new X("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!mr(this.#t,this.#r))throw new X("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this.#t,...this.#r},n=Kr(X,new Map([["b64",!0]]),e?.crit,this.#t,r),i=!0;if(n.has("b64")&&(i=this.#t.b64,typeof i!="boolean"))throw new X('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=r;if(typeof s!="string"||!s)throw new X('JWS "alg" (Algorithm) Header Parameter missing or invalid');Mr(s,t,"sign");let o,a;i?(o=fe(this.#e),a=pe(o)):(a=this.#e,o="");let c,u;this.#t?(c=fe(JSON.stringify(this.#t)),u=pe(c)):(c="",u=new Uint8Array);let l=ar(u,pe("."),a),d=await Cr(t,s),h=await _r(s,d,l),y={signature:fe(h),payload:o};return this.#r&&(y.header=this.#r),this.#t&&(y.protected=c),y}},Br=class{#e;constructor(t){this.#e=new bt(t)}setProtectedHeader(t){return this.#e.setProtectedHeader(t),this}async sign(t,e){let r=await this.#e.sign(t,e);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}},Jr=class{#e;#t;constructor(t={}){this.#t=new Gr(t)}setIssuer(t){return this.#t.iss=t,this}setSubject(t){return this.#t.sub=t,this}setAudience(t){return this.#t.aud=t,this}setJti(t){return this.#t.jti=t,this}setNotBefore(t){return this.#t.nbf=t,this}setExpirationTime(t){return this.#t.exp=t,this}setIssuedAt(t){return this.#t.iat=t,this}setProtectedHeader(t){return this.#e=t,this}async sign(t,e){let r=new Br(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new pr("JWTs MUST NOT use unencoded payload");return r.sign(t,e)}};function we(t){let e=t?.modulusLength??2048;if(typeof e!="number"||e<2048)throw new C("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Yr(t,e){let r,n;switch(t){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${t.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:we(e)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:we(e)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(t.slice(-3),10)||1}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:we(e)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":case"EdDSA":{n=["sign","verify"],r={name:"Ed25519"};break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{n=["sign","verify"],r={name:t};break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveBits"];let i=e?.crv??"P-256";switch(i){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:i};break}case"X25519":r={name:"X25519"};break;default:throw new C("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519")}break}default:throw new C('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(r,e?.extractable??!1,n)}var Zr="https://id.botparty.club",en="EdDSA",tn=15,rn=6e4,nn="5m",sn=3,on=["brave","calm","cosmic","eager","fair","gentle","happy","keen","lively","noble","proud","quick","rare","sharp","swift","true","vivid","warm","wild","bold","cool","fast","grand","just","kind","lean","mild","neat","pale","rich","safe","tall","vast","wise","bright","dark","fierce","quiet","free","glad"],an=["lion","hawk","wolf","bear","fox","deer","owl","crane","whale","tiger","eagle","shark","raven","puma","lynx","orca","swan","viper","bison","cobra","finch","gecko","heron","ibex","jay","kite","lark","moth","newt","otter","perch","quail","robin","seal","toad","wren","yak","zebra","ant","bee"],A=class extends Error{code;statusCode;actionUrl;details;constructor(t){super(t.message),this.name="BotPartyError",this.code=t.code,this.statusCode=t.statusCode,this.actionUrl=t.actionUrl,this.details=t.details}},$e=class extends A{constructor(t){super({code:"NAMESPACE_LOCKED",message:t.message,statusCode:423,actionUrl:t.actionUrl,details:{lockedAt:t.lockedAt,reason:t.reason}}),this.name="NamespaceLockedError"}},se=class extends A{amount;service;constructor(t){super({code:"PAYMENT_REQUIRED",message:t.message,statusCode:402,actionUrl:t.actionUrl}),this.name="PaymentRequiredError",this.amount=t.amount,this.service=t.service}},oe=class extends A{missingScopes;constructor(t){super({code:"INSUFFICIENT_PERMISSION",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="InsufficientPermissionError",this.missingScopes=t.missingScopes}},Oe=class extends A{constructor(t){super({code:"LINK_REQUIRED",message:t.message,statusCode:403,actionUrl:t.actionUrl}),this.name="LinkRequiredError"}};function nt(t){let e=_t(4);return t[e.readUInt32BE(0)%t.length]}function cn(){return`${nt(on)}-${nt(an)}`}function ln(){let t=cn(),e=_t(2).toString("hex");return`${t}-${e}`}function un(){return M(Qr(),".botparty")}function St(t){ie(t)||zr(t,{recursive:!0,mode:448})}function dn(t){let e=M(t,"identity.json");if(!ie(e))return null;try{return JSON.parse(Et(e,"utf-8"))}catch{return null}}function vt(t,e){St(t);let r=M(t,"identity.json");At(r,JSON.stringify(e,null,2),{mode:384})}function hn(t){let e=M(t,"private.pem");if(!ie(e))return null;try{return Et(e,"utf-8")}catch{return null}}function kt(t,e){St(t);let r=M(t,"private.pem");At(r,e,{mode:384})}function it(t){for(let e of["identity.json","private.pem"]){let r=M(t,e);ie(r)&&Xr(r)}}async function Ct(t){let e={extractable:!0};t==="EdDSA"&&(e.crv="Ed25519");let{privateKey:r,publicKey:n}=await Yr(t,e),i=await Nr(r),s=await Lr(n);return{privateKey:r,publicKey:n,privatePem:i,publicPem:s}}async function pn(t,e,r){let n=await gt(e,r);return(await new bt(new TextEncoder().encode(t)).setProtectedHeader({alg:r}).sign(n)).signature}async function Ae(t,e,r,n,i){let s=n,o=await gt(r,s);return new Jr({...i}).setProtectedHeader({alg:s,kid:e}).setIssuer(t).setSubject(t).setIssuedAt().setExpirationTime(nn).sign(o)}async function R(t,e,r={}){let{token:n,...i}=r,s=new Headers(i.headers);return s.set("Content-Type","application/json"),n&&s.set("Authorization",`Bearer ${n}`),fetch(`${t}${e}`,{...i,headers:s})}async function be(t){try{return await t.clone().json()}catch{return null}}function ne(t){let e=t.error,r,n,i,s={};if(typeof e=="object"&&e!==null){let o=e;r=o.code||"UNKNOWN",n=o.message||t.message||"Request failed",i=o.actionUrl||t.actionUrl,s=o}else r=(typeof e=="string"?e:t.code)||"UNKNOWN",n=t.message||(typeof e=="string"?e:"Request failed"),i=t.actionUrl,s=t;return{code:r,message:n,actionUrl:i,extra:s}}var fn=class{constructor(t,e){this.client=t,this.keyId=e}get id(){return this.keyId}async info(){return this.client.keys.get(this.keyId)}async update(t){return this.client.keys.update(this.keyId,t)}async delete(){return this.client.keys.delete(this.keyId)}async rotate(){return this.client.keys.rotate(this.keyId)}async invalidate(t){return this.client.keys.invalidate(this.keyId,t)}},mn=class{constructor(t){this.client=t}async list(){let t=await this.client.generateToken(),e=await R(this.client.serverUrl,"/api/v1/namespaces/keys",{token:t});if(!e.ok)throw await this.client._apiError(e);return(await e.json()).data}async get(t){let e=(await this.list()).find(r=>r.id===t);if(!e)throw new A({code:"KEY_NOT_FOUND",message:`Key ${t} not found`,statusCode:404});return e}async add(t){let e=await this.client.generateToken(),r=await R(this.client.serverUrl,"/api/v1/namespaces/keys",{method:"POST",token:e,body:JSON.stringify(t)});if(!r.ok)throw await this.client._apiError(r);return r.json()}async update(t,e){let r=await this.client.generateToken(),n=await R(this.client.serverUrl,`/api/v1/namespaces/keys/${t}`,{method:"PATCH",token:r,body:JSON.stringify(e)});if(!n.ok)throw await this.client._apiError(n);return n.json()}async delete(t){let e=await this.client.generateToken(),r=await R(this.client.serverUrl,`/api/v1/namespaces/keys/${t}`,{method:"DELETE",token:e});if(!r.ok&&r.status!==204)throw await this.client._apiError(r)}async rotate(t){let e=this.client.getIdentity();if(!e)throw new Error("Not registered");let r=this.client.getPrivateKey();if(!r)throw new Error("Private key not found");let n=t||e.keyId;if(n!==e.keyId)throw new A({code:"CANNOT_ROTATE_OTHER_KEY",message:"Can only rotate the current machine key from this client. Use the server API directly for other keys.",statusCode:400});let i=await Ct(e.algorithm),s=await Ae(e.namespace,e.keyId,r,e.algorithm),o=await R(e.serverUrl,`/api/v1/namespaces/keys/${n}/rotate`,{method:"POST",token:s,body:JSON.stringify({newPublicKey:i.publicPem})});if(!o.ok)throw await this.client._apiError(o);let a=await o.json();return kt(this.client.stateDir,i.privatePem),vt(this.client.stateDir,{...e,rotatedAt:a.rotatedAt}),a}async rotateCurrent(){return this.rotate()}async invalidate(t,e){let r=await this.client.generateToken(),n=await R(this.client.serverUrl,`/api/v1/namespaces/keys/${t}/invalidate`,{method:"POST",token:r,body:JSON.stringify({reason:e})});if(!n.ok)throw await this.client._apiError(n)}},$t=class{serverUrl;stateDir;keys;algorithm;rotationTTL;constructor(t={}){this.serverUrl=(t.serverUrl||st("BOTPARTY_SERVER_URL")||Zr).replace(/\/$/,""),this.stateDir=t.stateDir||st("BOTPARTY_STATE_DIR")||un(),this.algorithm=t.algorithm||en,this.rotationTTL=t.rotationTTL||tn,this.keys=new mn(this)}getIdentity(){return dn(this.stateDir)}getPrivateKey(){return hn(this.stateDir)}isRegistered(){return this.getIdentity()!==null&&this.getPrivateKey()!==null}async register(t,e){let r=t,n=0;for(;n<sn;){r||(r=ln());let i=e||r,s=await Ct(this.algorithm),o=await R(this.serverUrl,"/api/v1/namespaces/register",{method:"POST",body:JSON.stringify({namespace:r,publicKey:s.publicPem,rotationTTL:this.rotationTTL})}),a=await o.json();if(a.status==="already_registered")throw new A({code:"ALREADY_REGISTERED",message:`Namespace "${r}" is already registered`,statusCode:409});if(o.status===409&&!t){r=void 0,n++;continue}if(!o.ok)throw new A({code:a.error||"REGISTRATION_FAILED",message:a.message||a.error||"Registration failed",statusCode:o.status});let c=a.challenge,u=await pn(c,s.privatePem,this.algorithm),l=await R(this.serverUrl,"/api/v1/namespaces/register/verify",{method:"POST",body:JSON.stringify({namespace:r,challenge:c,signature:u})});if(!l.ok)throw await this._apiError(l);let d=await l.json();return kt(this.stateDir,s.privatePem),vt(this.stateDir,{serverUrl:this.serverUrl,namespace:r,keyId:d.keyId,algorithm:this.algorithm,rotatedAt:d.rotatedAt,rotationTTL:d.rotationTTL,label:i}),d}throw new A({code:"REGISTRATION_FAILED",message:"Failed to find available namespace after retries",statusCode:409})}async ensureRegistered(){let t=this.getIdentity();if(t&&this.getPrivateKey())return t;await this.register();let e=this.getIdentity();if(!e)throw new Error("Registration succeeded but identity could not be read");return e}async ensureFreshKey(){let t=this.getIdentity();if(!t)throw new Error("Not registered");let e=new Date(t.rotatedAt).getTime()+t.rotationTTL*6e4;Date.now()>=e-rn&&await this.keys.rotateCurrent()}async generateToken(t){await this.ensureRegistered(),await this.ensureFreshKey();let e=this.getIdentity(),r=this.getPrivateKey();return Ae(e.namespace,e.keyId,r,e.algorithm,t)}async fetch(t,e={}){let r=await this.generateToken(),n=new Headers(e.headers);n.set("X-Proxy-Authorization",`Bearer ${r}`);let i=await fetch(t,{...e,headers:n});if(i.status===401){let s=await be(i);if(s){let{code:o}=ne(s);if(o==="KEY_STALE"){await this.keys.rotateCurrent();let a=await this.generateToken(),c=new Headers(e.headers);c.set("X-Proxy-Authorization",`Bearer ${a}`),i=await fetch(t,{...e,headers:c})}}}if([401,402,403,423].includes(i.status)){let s=await be(i);if(s){let{code:o}=ne(s);yn(o)&&wn(i.status,s,this.getIdentity(),this.serverUrl)}}return i}async info(t){let e=t||this.getIdentity()?.namespace;if(!e)throw new Error("Not registered and no namespace provided");let r=await R(this.serverUrl,`/api/v1/namespaces/${e}/info`);if(!r.ok)throw await this._apiError(r);return r.json()}async destroy(){let t=await this.generateToken(),e=await R(this.serverUrl,"/api/v1/namespaces",{method:"DELETE",token:t});if(!e.ok&&e.status!==204)throw await this._apiError(e);it(this.stateDir)}async link(){let t=this.getIdentity();if(!t)throw new Error("Not registered");let e=this.getPrivateKey();if(!e)throw new Error("Private key not found");let r=await Ae(t.namespace,t.keyId,e,t.algorithm,{act:"link"});return{url:`${t.serverUrl}/namespaces/${t.namespace}/link?jwt=${r}`}}whoami(){let t=this.getIdentity();if(!t)return null;let e=new Date(new Date(t.rotatedAt).getTime()+t.rotationTTL*6e4).toISOString();return{namespace:t.namespace,keyId:t.keyId,algorithm:t.algorithm,rotationTTL:t.rotationTTL,rotatedAt:t.rotatedAt,staleAt:e,label:t.label,serverUrl:t.serverUrl}}key(t){return new fn(this,t)}reset(){it(this.stateDir)}async _apiError(t){let e=await be(t);if(!e)return new A({code:"UNKNOWN",message:`Request failed with status ${t.status}`,statusCode:t.status});let{code:r,message:n,actionUrl:i}=ne(e);return new A({code:r,message:n,statusCode:t.status,actionUrl:i})}},gn=new Set(["NAMESPACE_LOCKED","LOCKUP_TRIGGERED","PAYMENT_REQUIRED","LINK_REQUIRED","INSUFFICIENT_SCOPE","PERMISSION_DENIED","KEY_STALE","KEY_EXPIRED"]);function yn(t){return gn.has(t)}function wn(t,e,r,n){let{code:i,message:s,actionUrl:o,extra:a}=ne(e),c=r?.namespace||"",u=r?.serverUrl||n;throw i==="NAMESPACE_LOCKED"||i==="LOCKUP_TRIGGERED"||t===423?new $e({message:s||"Namespace is locked",actionUrl:o||`${u}/namespaces/${c}/unlock`,lockedAt:a.lockedAt,reason:a.reason}):i==="PAYMENT_REQUIRED"||t===402?new se({message:s,actionUrl:o,amount:a.amount||e.amount,service:a.service||e.service}):i==="LINK_REQUIRED"?new Oe({message:s,actionUrl:o||`${u}/namespaces/${c}/link`}):i==="INSUFFICIENT_SCOPE"||i==="PERMISSION_DENIED"||t===403?new oe({message:s,actionUrl:o,missingScopes:a.missingScopes||a.missing_scopes}):new A({code:i,message:s,statusCode:t,actionUrl:o})}function st(t){if(typeof process<"u"&&process.env)return process.env[t]}import{writeFileSync as Mt}from"fs";import{readFileSync as ue}from"fs";import{basename as Dn}from"path";var Wt=or(Kt(),1),{program:es,createCommand:ts,createArgument:rs,createOption:ns,CommanderError:is,InvalidArgumentError:ss,InvalidOptionArgumentError:os,Command:jt,Argument:as,Option:cs,Help:ls}=Wt.default;var Hn="\x1B[1m",Un="\x1B[2m",Ln="\x1B[31m",Nn="\x1B[32m",Kn="\x1B[33m",Wn="\x1B[36m",F="\x1B[0m";function jn(t){return`${Hn}${t}${F}`}function Ge(t){return`${Un}${t}${F}`}function Vt(t){return`${Ln}${t}${F}`}function Be(t){return`${Kn}${t}${F}`}function Ft(t){return`${Wn}${t}${F}`}function Mn(t){return`${Nn}${t}${F}`}function qt(t){return(t||process.env.KEYCHAINS_PROXY_URL||process.env.BOTPARTY_PROXY_URL||"https://keychains.dev").replace(/\/$/,"")}var V=class extends Error{approvalUrl;constructor(e,r){super(e),this.approvalUrl=r}};function Vn(t,e){try{let r=new URL(t),n=new URL(e);return r.hostname===n.hostname&&r.port===n.port&&r.protocol===n.protocol?t:`${e}/${r.hostname}${r.pathname}${r.search}`}catch{return`${e}/${t}`}}async function Gt(t,e,r,n){let i=await r.generateToken(),s=Vn(t,n),o=new Headers(e.headers);o.set("X-Proxy-Authorization",`Bearer ${i}`);let a=await fetch(s,{method:e.method,headers:o,body:e.body});if(a.status===401)try{let u=await a.clone().json();if(u.code==="KEY_STALE"||u.error==="KEY_STALE"){await r.keys.rotateCurrent();let l=await r.generateToken(),d=new Headers(e.headers);d.set("X-Proxy-Authorization",`Bearer ${l}`),a=await fetch(s,{method:e.method,headers:d,body:e.body})}}catch{}if(a.status===403){let c=a.clone();try{let u=await c.json(),l=u.approval_url||u.authorizationUrl;if(l){let d=typeof u.message=="string"?u.message:u.missing_scopes?`Insufficient scopes: ${u.missing_scopes.join(", ")}`:"Missing required credentials";throw new V(d,l)}}catch(u){if(u instanceof V)throw u}}return a}function Je(t,e,r,n){let i=(Date.now()-n)/1e3,s=e.headers.get("content-type")||"",o={http_code:e.status,http_connect:0,http_version:"1.1",response_code:e.status,content_type:s,size_download:r,size_header:0,size_request:0,size_upload:0,speed_download:i>0?Math.round(r/i):0,speed_upload:0,time_appconnect:i,time_connect:i,time_namelookup:0,time_pretransfer:i,time_redirect:0,time_starttransfer:i,time_total:i,url_effective:"",num_connects:1,num_redirects:0,redirect_url:"",ssl_verify_result:0,stdout:"-",stderr:"-",exitcode:0,errormsg:"",method:"",scheme:"",filename_effective:"",onerror:"",urlnum:0},a=t;return a=a.replace(/\\n/g,`
33
+ `),a=a.replace(/\\r/g,"\r"),a=a.replace(/\\t/g," "),a=a.replace(/\\\\/g,"\\"),a=a.replace(/%\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g,(c,u)=>u in o?String(o[u]):c),a}function Fn(t,e,r){let n=[],i;try{let s=new URL(e);i=s.pathname+s.search}catch{i=e}n.push(`> ${t} ${i} HTTP/1.1`);try{let s=new URL(e);n.push(`> Host: ${s.host}`)}catch{}for(let[s,o]of Object.entries(r))s.toLowerCase()!=="host"&&n.push(`> ${s}: ${o}`);return n.push(">"),n.join(`
34
+ `)}function qn(t,e,r){let n=[];return n.push(`< HTTP/1.1 ${t} ${e}`),r.forEach((i,s)=>{n.push(`< ${s}: ${i}`)}),n.push("<"),n.join(`
35
+ `)}function Bt(t,e,r){let n=[];return n.push(`HTTP/1.1 ${t} ${e}`),r.forEach((i,s)=>{n.push(`${s}: ${i}`)}),n.push(""),n.join(`
36
+ `)}function Gn(t,e,r){let n=[];return n.push(`HTTP/1.1 ${t} ${e}`),r.forEach((i,s)=>{n.push(`${s}: ${i}`)}),n.push(""),n.join(`
37
+ `)}function Bn(t){let e=[];if(t.data)for(let r of t.data)if(r.startsWith("@"))try{e.push(ue(r.slice(1),"utf-8"))}catch{e.push(r)}else e.push(r);if(t.dataRaw)for(let r of t.dataRaw)e.push(r);if(t.dataBinary)for(let r of t.dataBinary)if(r.startsWith("@"))try{e.push(ue(r.slice(1),"utf-8"))}catch{e.push(r)}else e.push(r);if(t.dataUrlencode)for(let r of t.dataUrlencode){let n=r.indexOf("=");if(n>0){let i=r.slice(0,n),s=r.slice(n+1);e.push(`${encodeURIComponent(i)}=${encodeURIComponent(s)}`)}else r.startsWith("=")?e.push(encodeURIComponent(r.slice(1))):e.push(encodeURIComponent(r))}if(t.dataAscii)for(let r of t.dataAscii)e.push(r);if(t.json)for(let r of t.json)e.push(r);if(e.length!==0)return e.join("&")}function Jn(t){return!!(t.data&&t.data.length>0||t.dataRaw&&t.dataRaw.length>0||t.dataBinary&&t.dataBinary.length>0||t.dataUrlencode&&t.dataUrlencode.length>0||t.dataAscii&&t.dataAscii.length>0||t.json&&t.json.length>0)}function Yt(t){return!!(t.form&&t.form.length>0||t.formString&&t.formString.length>0)}function Yn(t){return t.request?t.request.toUpperCase():t.head?"HEAD":Jn(t)&&!t.get||Yt(t)?"POST":t.uploadFile?"PUT":"GET"}async function Jt(t,e,r,n,i,s){let o=await t.text(),a=Buffer.byteLength(o,"utf-8");if(e.verbose){let u=Fn(r,n,i);process.stderr.write(u+`
38
+ `);let l=qn(t.status,t.statusText,t.headers);process.stderr.write(l+`
39
+ `)}if(e.dumpHeader){let u=Gn(t.status,t.statusText,t.headers);e.dumpHeader==="-"?process.stdout.write(u):Mt(e.dumpHeader,u)}e.fail&&t.status>=400&&(e.failWithBody||(e.silent||process.stderr.write(`curl: (22) The requested URL returned error: ${t.status} ${t.statusText}
40
+ `),e.writeOut&&process.stdout.write(Je(e.writeOut,t,a,s)),process.exit(22)));let c="";e.include&&(c+=Bt(t.status,t.statusText,t.headers)),e.head?!e.include&&!e.verbose&&(c+=Bt(t.status,t.statusText,t.headers)):c+=o,e.output?e.output==="-"?process.stdout.write(c):Mt(e.output,c):c&&process.stdout.write(c),e.failWithBody&&t.status>=400&&(e.silent||process.stderr.write(`curl: (22) The requested URL returned error: ${t.status} ${t.statusText}
41
+ `),e.writeOut&&process.stdout.write(Je(e.writeOut,t,a,s)),process.exit(22)),e.writeOut&&process.stdout.write(Je(e.writeOut,t,a,s))}async function zt(t,e){let r=new jt;r.exitOverride(),r.name("botparty curl").argument("[url]","URL to request").description("Make a proxied API call (like curl, but through BotParty + Keychains)").allowUnknownOption(!1).option("--proxy-url <url>","Keychains proxy base URL (default: $KEYCHAINS_PROXY_URL or https://keychains.dev)").option("--wait-on-authlink","If credentials are required, wait for user approval then retry automatically").option("--wait-timeout <seconds>","Max seconds to wait for approval when using --wait-on-authlink (default: no limit)").option("-X, --request <method>","Specify request method").option("-H, --header <header...>","Pass custom header(s) to server (repeatable)").option("-d, --data <data...>","HTTP POST data (repeatable)").option("--data-raw <data...>","HTTP POST data without @ file interpretation (repeatable)").option("--data-binary <data...>","HTTP POST binary data (repeatable)").option("--data-urlencode <data...>","HTTP POST data URL encoded (repeatable)").option("--data-ascii <data...>","HTTP POST ASCII data (repeatable)").option("--json <data...>","HTTP POST JSON data (sets Content-Type and Accept headers)").option("-F, --form <name=content...>","Specify multipart MIME data (repeatable)").option("--form-string <name=content...>","Specify multipart MIME data (no file interpretation)").option("-v, --verbose","Make the operation more talkative").option("-i, --include","Include response headers in output").option("-I, --head","Show document info only (HEAD request)").option("-s, --silent","Silent mode").option("-S, --show-error","Show error even when -s is used").option("-o, --output <file>","Write to file instead of stdout").option("-D, --dump-header <file>","Write response headers to file").option("-w, --write-out <format>","Display information after transfer").option("-f, --fail","Fail fast with no output on HTTP errors").option("--fail-with-body","Fail with output on HTTP errors").option("-L, --location","Follow redirects").option("--max-redirs <num>","Maximum number of redirects").option("--location-trusted","Follow redirects and send auth to other hosts").option("-A, --user-agent <name>","Send User-Agent to server").option("-e, --referer <URL>","Referrer URL").option("-b, --cookie <data...>","Send cookies from string/file (repeatable)").option("-c, --cookie-jar <filename>","Write cookies to filename after operation").option("-u, --user <user:password>","Server user and password").option("--compressed","Request compressed response").option("-r, --range <range>","Retrieve only this byte range").option("--connect-timeout <seconds>","Maximum time for connection").option("-m, --max-time <seconds>","Maximum time for the transfer").option("--retry <num>","Retry request if transient problems occur").option("--retry-delay <seconds>","Wait time between retries").option("--retry-max-time <seconds>","Retry only within this period").option("--retry-all-errors","Retry on all errors").option("--url <url>","URL to work with").option("-G, --get","Put the post data in the URL and use GET").option("-T, --upload-file <file>","Transfer local FILE to destination").option("-k, --insecure","Allow insecure server connections").option("--cacert <file>","CA certificate to verify peer against").option("--capath <dir>","CA directory to verify peer against").option("--cert <cert[:passwd]>","Client certificate file and password").option("--cert-type <type>","Certificate type (DER/PEM/ENG)").option("--key <key>","Private key file name").option("--key-type <type>","Private key file type (DER/PEM/ENG)").option("--pass <phrase>","Pass phrase for the private key").option("--ciphers <list>","SSL ciphers to use").option("-1, --tlsv1","Use TLSv1.0 or greater").option("--tlsv1.0","Use TLSv1.0 or greater").option("--tlsv1.1","Use TLSv1.1 or greater").option("--tlsv1.2","Use TLSv1.2 or greater").option("--tlsv1.3","Use TLSv1.3 or greater").option("--ssl","Try SSL/TLS").option("--ssl-reqd","Require SSL/TLS").option("--ssl-no-revoke","Disable cert revocation checks").option("--no-alpn","Disable the ALPN TLS extension").option("--no-npn","Disable the NPN TLS extension").option("--no-sessionid","Disable SSL session-ID reusing").option("-0, --http1.0","Use HTTP 1.0").option("--http1.1","Use HTTP 1.1").option("--http2","Use HTTP 2").option("--http2-prior-knowledge","Use HTTP 2 without HTTP/1.1 Upgrade").option("--http3","Use HTTP v3").option("-4, --ipv4","Resolve names to IPv4 addresses").option("-6, --ipv6","Resolve names to IPv6 addresses").option("-x, --proxy <[protocol://]host[:port]>","Use this proxy").option("-U, --proxy-user <user:password>","Proxy user and password").option("--noproxy <no-proxy-list>","List of hosts which do not use proxy").option("-n, --netrc","Must read .netrc for user name and password").option("--netrc-optional","Use either .netrc or URL").option("--netrc-file <filename>","Specify FILE for netrc").option("-K, --config <file>","Read config from a file").option("--create-dirs","Create necessary local directory hierarchy").option("--raw",'Do HTTP "raw"; no transfer decoding').option("--no-keepalive","Disable TCP keepalive on the connection").option("--keepalive-time <seconds>","Interval time for keepalive probes").option("-N, --no-buffer","Disable buffering of the output stream").option("-#, --progress-bar","Display transfer progress as a bar").option("--stderr <file>","Where to redirect stderr").option("--trace <file>","Write a debug trace to FILE").option("--trace-ascii <file>","Like --trace, but without hex output").option("--trace-time","Add time stamps to trace/verbose output").option("--path-as-is","Do not squash .. sequences in URL path").option("--tcp-fastopen","Use TCP Fast Open").option("--tcp-nodelay","Use the TCP_NODELAY option").option("-j, --junk-session-cookies","Ignore session cookies read from file").option("-O, --remote-name","Write output to a file named as the remote file").option("--remote-name-all","Use the remote file name for all URLs").option("-R, --remote-time","Set the remote file time on the local output").option("-J, --remote-header-name","Use the header-provided filename").option("-C, --continue-at <offset>","Resumed transfer offset").option("-g, --globoff","Disable URL sequences and ranges using {} and []").option("--limit-rate <speed>","Limit transfer speed to RATE").option("--max-filesize <bytes>","Maximum file size to download").option("--interface <name>","Use network INTERFACE (or address)").option("--local-port <num/range>","Force use of RANGE for local port numbers").option("--dns-servers <addresses>","DNS server addrs to use").option("--dns-interface <interface>","Interface to use for DNS requests").option("--dns-ipv4-addr <address>","IPv4 address to use for DNS requests").option("--dns-ipv6-addr <address>","IPv6 address to use for DNS requests").option("--expect100-timeout <seconds>","How long to wait for 100-continue").option("--happy-eyeballs-timeout-ms <milliseconds>","Time for IPv6 before trying IPv4").action(async(i,s)=>{let o;try{let a=e(),c=qt(s.proxyUrl),u=i||s.url;u||(process.stderr.write(`curl: no URL specified!
42
+ curl: try 'botparty curl --help' for more information
43
+ `),process.exit(2));let l={};if(s.header)for(let b of s.header){let T=b.indexOf(":");if(T>0){let k=b.slice(0,T).trim(),te=b.slice(T+1).trim();te===""?delete l[k]:l[k]=te}else b.endsWith(";")&&(l[b.slice(0,-1).trim()]="")}if(s.userAgent&&(l["User-Agent"]=s.userAgent),s.referer&&(l.Referer=s.referer),s.cookie&&(l.Cookie=s.cookie.join("; ")),s.user){let b=Buffer.from(s.user).toString("base64");l.Authorization=`Basic ${b}`}s.compressed&&(l["Accept-Encoding"]="gzip, deflate, br"),s.range&&(l.Range=`bytes=${s.range}`),s.json&&s.json.length>0&&(!l["Content-Type"]&&!l["content-type"]&&(l["Content-Type"]="application/json"),!l.Accept&&!l.accept&&(l.Accept="application/json"));let d=Yn(s),h=Bn(s),y=u;if(s.get&&h){let b=y.includes("?")?"&":"?";y=y+b+h,h=void 0}if(!h&&Yt(s)){let b=new FormData,T=(k,te)=>{let he=k.indexOf("=");if(he<=0)return;let Qe=k.slice(0,he),Y=k.slice(he+1);if(te&&Y.startsWith("@"))try{let Qt=ue(Y.slice(1)),Zt=new Blob([Qt]);b.append(Qe,Zt,Dn(Y.slice(1)))}catch{process.stderr.write(`curl: (26) Failed to open/read local data from file: ${Y.slice(1)}
44
+ `),process.exit(26)}else b.append(Qe,Y)};if(s.form)for(let k of s.form)T(k,!0);if(s.formString)for(let k of s.formString)T(k,!1);h=b}if(s.uploadFile&&!h)try{h=ue(s.uploadFile,"utf-8")}catch{process.stderr.write(`curl: (26) Failed to open/read local data from file: ${s.uploadFile}
45
+ `),process.exit(26)}h&&!l["Content-Type"]&&!l["content-type"]&&(s.json&&s.json.length>0?l["Content-Type"]="application/json":l["Content-Type"]="application/x-www-form-urlencoded"),o={url:y,method:d,headers:l,body:typeof h=="string"?h:void 0};let O=Date.now(),B=s.retry?parseInt(s.retry,10):0,Xe=s.retryDelay?parseInt(s.retryDelay,10)*1e3:1e3,de=null,J=null;for(let b=0;b<=B;b++)try{if(J=await Gt(o.url,{method:o.method,headers:o.headers,body:o.body},a,c),J.status>=500&&b<B){de=new Error(`HTTP ${J.status}`),await new Promise(T=>setTimeout(T,Xe));continue}break}catch(T){if(de=T,b<B){await new Promise(k=>setTimeout(k,Xe));continue}throw T}if(!J)throw de;await Jt(J,s,o.method,o.url,o.headers,O)}catch(a){if(s.silent&&!s.showError&&process.exit(1),a instanceof V&&a.approvalUrl){if(s.waitOnAuthlink){process.stderr.write(`
46
+ `),process.stderr.write(` ${Be("Authorization required:")} ${a.message}
47
+ `),process.stderr.write(` ${Ge("Auth URL:")} ${Ft(a.approvalUrl)}
48
+ `),process.stderr.write(` ${Ge("Open this link to authorize, then the request will retry.")}
49
+ `),process.stderr.write(`
50
+ ${Be("Waiting for user to approve...")}
51
+ `);try{let c=s.waitTimeout?parseInt(s.waitTimeout,10)*1e3:void 0,u=2e3,l=c?Date.now()+c:1/0,d=0,h=!1;for(;Date.now()<l;){await new Promise(y=>setTimeout(y,u)),d++,d%30===0&&process.stderr.write(`
52
+ `),process.stderr.write(Ge("."));try{let y=e(),O=qt(s.proxyUrl);if(o){let B=await Gt(o.url,{method:o.method,headers:o.headers,body:o.body},y,O);process.stderr.write(`
53
+
54
+ ${Mn("\u2713")} Authorization approved!
55
+
56
+ `),h=!0,await Jt(B,s,o.method,o.url,o.headers,Date.now());return}}catch(y){if(y instanceof V)continue;throw y}}h||(process.stderr.write(`
57
+
58
+ ${Vt("Timed out waiting for approval.")}
59
+
60
+ `),process.exit(1))}catch(c){process.stderr.write(`
61
+
62
+ `),process.stderr.write(` ${Vt(c instanceof Error?c.message:String(c))}
63
+
64
+ `),process.exit(1)}}process.stderr.write(`
65
+ `),process.stderr.write(` ${Be("Credentials required:")} ${a.message}
66
+ `),process.stderr.write(`
67
+ `),process.stderr.write(` ${jn("Authorize at:")}
68
+ `),process.stderr.write(` ${Ft(a.approvalUrl)}
69
+ `),process.stderr.write(`
70
+ `)}else process.stderr.write(`curl: (6) ${a instanceof Error?a.message:a}
71
+ `);process.exit(1)}});try{await r.parseAsync(t,{from:"user"})}catch(i){if(i&&typeof i=="object"&&"exitCode"in i){let s=i;process.exit(s.exitCode)}throw i}}var m=!1,zn="\x1B[1m",Xn="\x1B[2m",Qn="\x1B[31m",Zn="\x1B[32m",ei="\x1B[33m",ti="\x1B[36m",G="\x1B[0m";function g(t){return`${zn}${t}${G}`}function _(t){return`${Xn}${t}${G}`}function v(t){return`${Qn}${t}${G}`}function P(t){return`${Zn}${t}${G}`}function q(t){return`${ei}${t}${G}`}function f(t){return`${ti}${t}${G}`}function E(t){console.log(JSON.stringify({ok:!0,...t},null,2))}function w(t,e=1){m?console.log(JSON.stringify({ok:!1,error:{message:t}},null,2)):console.error(`${v("error")}: ${t}`),process.exit(e)}function ri(t){if(m){let e={ok:!1};t instanceof A?e.error={code:t.code,message:t.message,statusCode:t.statusCode,...t.actionUrl&&{actionUrl:t.actionUrl},...t instanceof se&&t.amount&&{amount:t.amount},...t instanceof oe&&t.missingScopes&&{missingScopes:t.missingScopes}}:t instanceof Error?e.error={message:t.message}:e.error={message:String(t)},console.log(JSON.stringify(e,null,2)),process.exit(1)}t instanceof $e&&(console.error(`
72
+ ${v("NAMESPACE LOCKED")}: ${t.message}`),t.actionUrl&&console.error(`
73
+ A human must unlock it at:
74
+ ${f(t.actionUrl)}`),process.exit(1)),t instanceof se&&(console.error(`
75
+ ${q("PAYMENT REQUIRED")}: ${t.message}`),t.amount&&console.error(` Amount: $${(t.amount/1e6).toFixed(6)}`),t.actionUrl&&console.error(`
76
+ Complete payment at:
77
+ ${f(t.actionUrl)}`),process.exit(1)),t instanceof oe&&(console.error(`
78
+ ${v("PERMISSION DENIED")}: ${t.message}`),t.missingScopes?.length&&console.error(` Missing scopes: ${t.missingScopes.join(", ")}`),t.actionUrl&&console.error(`
79
+ Grant access at:
80
+ ${f(t.actionUrl)}`),process.exit(1)),t instanceof Oe&&(console.error(`
81
+ ${q("LINK REQUIRED")}: ${t.message}`),t.actionUrl&&console.error(`
82
+ Link a human account at:
83
+ ${f(t.actionUrl)}`),process.exit(1)),t instanceof A&&(console.error(`
84
+ ${v(t.code)}: ${t.message}`),t.actionUrl&&console.error(`
85
+ ${f(t.actionUrl)}`),process.exit(1)),t instanceof Error&&(console.error(`
86
+ ${v("error")}: ${t.message}`),process.exit(1)),console.error(t),process.exit(1)}var ni=new Set(["header","H"]);function ii(t){let e=t.slice(2),r=[],n={},i="help",s="",o=0;e[0]&&!e[0].startsWith("-")&&(i=e[0],o=1,["keys","connections","conn"].includes(i)&&e[1]&&!e[1].startsWith("-")&&(s=e[1],o=2));function a(c,u){if(ni.has(c)&&typeof u=="string"){let l=n[c];Array.isArray(l)?l.push(u):typeof l=="string"?n[c]=[l,u]:n[c]=[u]}else n[c]=u}for(let c=o;c<e.length;c++){let u=e[c];if(u.startsWith("--")){let l=u.indexOf("=");l>-1?a(u.slice(2,l),u.slice(l+1)):c+1<e.length&&!e[c+1].startsWith("-")?(a(u.slice(2),e[c+1]),c++):a(u.slice(2),!0)}else u.startsWith("-")&&u.length===2?c+1<e.length&&!e[c+1].startsWith("-")?(a(u.slice(1),e[c+1]),c++):a(u.slice(1),!0):r.push(u)}return{command:i,subcommand:s,positional:r,flags:n}}function S(t){return new $t({serverUrl:typeof t.server=="string"?t.server:void 0,stateDir:typeof t["state-dir"]=="string"?t["state-dir"]:void 0})}function D(t){return new Date(t).toLocaleString()}function ze(t){let e=new Date(t).getTime()-Date.now();if(e<=0)return v("expired");let r=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return r>0?`${r}m ${n}s`:`${n}s`}async function si(t,e){let r=S(t);if(r.isRegistered()){let a=r.whoami();m?E({alreadyRegistered:!0,namespace:a.namespace,keyId:a.keyId,serverUrl:a.serverUrl}):(console.log(`Already registered as ${g(a.namespace)}`),console.log(` Key ID: ${a.keyId}`),console.log(` Server: ${_(a.serverUrl)}`),console.log(`
87
+ Use ${f("botparty reset")} to clear and re-register.`));return}let n=e[0]||(typeof t.namespace=="string"?t.namespace:void 0),i=typeof t.name=="string"?t.name:void 0,s=typeof t.ttl=="string"?parseInt(t.ttl,10):void 0;s&&(r.rotationTTL=s),m||console.log("Registering namespace...");let o=await r.register(n,i);m?E({namespace:o.namespace,keyId:o.keyId,role:o.role,rotationTTL:o.rotationTTL}):(console.log(`
88
+ ${P("Registered!")} ${g(o.namespace)}`),console.log(` Key ID: ${o.keyId}`),console.log(` Role: ${o.role}`),console.log(` Rotation TTL: ${o.rotationTTL} min`),console.log(`
89
+ Identity saved to ${_("~/.botparty/")}`))}async function oi(t){let r=S(t).whoami();r||w("Not registered. Run: botparty init"),m?E(r):(console.log(g("Identity")),console.log(` Namespace: ${f(r.namespace)}`),console.log(` Key ID: ${r.keyId}`),console.log(` Algorithm: ${r.algorithm}`),console.log(` Rotation TTL: ${r.rotationTTL} min`),console.log(` Last rotated: ${D(r.rotatedAt)}`),console.log(` Stale at: ${D(r.staleAt)} (${ze(r.staleAt)})`),r.label&&console.log(` Label: ${r.label}`),console.log(` Server: ${_(r.serverUrl)}`))}async function ai(t,e){let r=S(t),n=e[0]||r.getIdentity()?.namespace;n||w("Not registered and no namespace provided. Run: botparty init");let i=await r.info(n);m?E(i):(console.log(g("Namespace Info")),console.log(` Namespace: ${f(i.namespace)}`),console.log(` Status: ${i.status==="active"?P(i.status):v(i.status)}`),console.log(` Linked: ${i.linked?P("yes"):q("no")}`),console.log(` Active keys: ${i.activeKeys}`),console.log(` Created: ${D(i.createdAt)}`),i.lockedAt&&console.log(` Locked at: ${v(D(i.lockedAt))}`))}async function ci(t){let e=S(t);e.isRegistered()||w("Not registered. Run: botparty init");let{url:r}=await e.link();m?E({url:r}):(console.log(`Share this link with your human to claim ownership:
90
+ `),console.log(` ${f(r)}`),console.log(`
91
+ ${_("The link expires in 5 minutes.")}`))}async function li(t){let e=S(t);e.isRegistered()||w("Not registered.");let r=e.whoami();if(t.yes!==!0&&t.y!==!0){m&&w("--yes flag required to confirm destruction"),console.log(`${v("WARNING")}: This will permanently destroy namespace ${g(r.namespace)}.`),console.log(`All keys, links, and data will be deleted.
92
+ `),console.log(`Re-run with ${f("--yes")} to confirm.`);return}await e.destroy(),m?E({namespace:r.namespace,destroyed:!0}):console.log(`${P("Destroyed")} namespace ${g(r.namespace)}`)}async function ui(t){S(t).reset(),m?E({reset:!0}):(console.log(`${P("Local state cleared.")} The namespace still exists on the server.`),console.log(`Run ${f("botparty init")} to register a new namespace.`))}async function di(t){let r=await S(t).generateToken();m?E({token:r}):console.log(r)}async function hi(t){let e=process.argv.slice(2),r=e.findIndex(i=>i==="curl"||i==="fetch"),n=r>=0?e.slice(r+1):e.slice(1);await zt(n,()=>S(t))}async function pi(t){let e=S(t),r=await e.keys.list();if(m){E({keys:r});return}if(r.length===0){console.log("No keys found.");return}let n=e.getIdentity();for(let i of r){let s=n&&i.id===n.keyId,o=[];i.isRoot&&o.push(f("root")),s&&o.push(P("current"));let a=new Date(i.staleAt).getTime();Date.now()>a?o.push(v("stale")):o.push(`stale in ${ze(i.staleAt)}`),console.log(`${g(i.id)} ${o.join(" | ")}`),console.log(` Fingerprint: ${_(i.fingerprint)}`),console.log(` Algorithm: ${i.algorithm}`),console.log(` Role: ${i.role}`),i.label&&console.log(` Label: ${i.label}`),console.log(` Scopes: ${i.scopes.join(", ")}`),console.log(` Rotation TTL: ${i.rotationTTL} min`),console.log(` Last rotated: ${D(i.rotatedAt)}`),i.expiresAt&&console.log(` Expires at: ${D(i.expiresAt)}`),i.lastUsedAt&&console.log(` Last used: ${D(i.lastUsedAt)} from ${i.lastUsedIp}`),console.log("")}}async function fi(t){let e=typeof t.label=="string"?t.label:void 0,r=typeof t.scopes=="string"?t.scopes.split(","):void 0,n=typeof t.ttl=="string"?parseInt(t.ttl,10):void 0,i=typeof t.expires=="string"?t.expires:void 0,s=typeof t["public-key"]=="string"?t["public-key"]:void 0;s||w("--public-key is required (PEM-encoded public key)"),r?.length||w("--scopes is required (comma-separated)"),n||w("--ttl is required (rotation TTL in minutes)");let a=await S(t).keys.add({publicKey:s,label:e,scopes:r,rotationTTL:n,expiresAt:i});m?E(a):(console.log(`${P("Key added")}`),console.log(` ID: ${g(a.id)}`),console.log(` Fingerprint: ${a.fingerprint}`),console.log(` Scopes: ${a.scopes.join(", ")}`),console.log(` Rotation TTL: ${a.rotationTTL} min`))}async function mi(t,e){let r=e[0]||void 0,n=S(t);m||console.log("Rotating key...");let i=await n.keys.rotate(r);m?E(i):(console.log(`
93
+ ${P("Key rotated")}`),console.log(` ID: ${g(i.id)}`),console.log(` Fingerprint: ${i.fingerprint}`),console.log(` Stale at: ${D(i.staleAt)} (${ze(i.staleAt)})`))}async function gi(t,e){let r=e[0];r||w("Usage: botparty keys delete <keyId>");let n=S(t);if(t.yes!==!0&&t.y!==!0){m&&w("--yes flag required to confirm deletion"),console.log(`${q("WARNING")}: This will delete key ${g(r)} and all sub-keys.`),console.log(`Re-run with ${f("--yes")} to confirm.`);return}await n.keys.delete(r),m?E({keyId:r,deleted:!0}):console.log(`${P("Deleted")} key ${g(r)}`)}async function yi(t,e){let r=e[0];r||w("Usage: botparty keys invalidate <keyId>");let n=typeof t.reason=="string"?t.reason:void 0,i=S(t);if(t.yes!==!0&&t.y!==!0){m&&w("--yes flag required to confirm invalidation"),console.log(`${v("DANGER")}: This will invalidate key ${g(r)} and ${v("LOCK THE ENTIRE NAMESPACE")}.`),console.log(`All JWTs will be rejected until a human unlocks it.
94
+ `),console.log(`Re-run with ${f("--yes")} to confirm.`);return}await i.keys.invalidate(r,n),m?E({keyId:r,invalidated:!0,namespaceLocked:!0}):(console.log(`${v("Key invalidated")} \u2014 namespace is now ${v("LOCKED")}.`),console.log("A human must unlock it at the BotParty web UI."))}function Xt(t){return((typeof t["proxy-url"]=="string"?t["proxy-url"]:void 0)||process.env.KEYCHAINS_PROXY_URL||process.env.BOTPARTY_PROXY_URL||"https://keychains.dev").replace(/\/$/,"")}async function Ye(t,e,r,n){let i=await e.generateToken(),s=new Headers(n?.headers);return s.set("Authorization",`Bearer ${i}`),fetch(`${r}${t}`,{...n,headers:s})}async function wi(t){let e=S(t),r=Xt(t),n=new URLSearchParams;typeof t.provider=="string"&&n.set("provider",t.provider),typeof t.status=="string"&&n.set("status",t.status);let i=n.toString(),s=await Ye(`/api/botparty/connections${i?`?${i}`:""}`,e,r);if(!s.ok){let c=await s.json().catch(()=>({error:s.statusText}));w(c.error||`HTTP ${s.status}`)}let a=(await s.json()).connections;if(m){E({connections:a});return}if(a.length===0){console.log(_("No connections found."));return}console.log(`
95
+ ${g("Connections")} (${a.length})
96
+ `);for(let c of a){let u=c.status==="active"?P("active"):q(c.status),l=c.type==="api_key"?_("[api_key]"):_("[oauth]"),d=c.accountLabel&&c.accountLabel!=="default"?_(` (${c.accountLabel})`):"",h=c.accountIdentifier?_(` \u2014 ${c.accountIdentifier}`):"";console.log(` ${g(c.displayName||c.provider)} ${l} ${u}${d}${h}`),console.log(` ${_("id:")} ${c.id}`),c.keyNames?.length&&console.log(` ${_("keys:")} ${c.keyNames.join(", ")}`),c.scopes?.length&&console.log(` ${_("scopes:")} ${c.scopes.join(", ")}`)}console.log("")}function bi(t,e){let r=e.toLowerCase();if(t.id===e||t.provider.toLowerCase()===r||t.displayName?.toLowerCase()===r||t.domain?.toLowerCase()===r)return!0;let n=t.domain?.toLowerCase().replace(/\.(com|io|dev|org|net|ai|club)$/,"");return!!(n&&n===r)}async function Ei(t,e){let r=e[0];r||w("Usage: botparty connections delete <name|provider|id> [--yes]");let n=S(t),i=Xt(t),s=await Ye("/api/botparty/connections",n,i);if(!s.ok){let l=await s.json().catch(()=>({error:s.statusText}));w(l.error||`HTTP ${s.status}`)}let{connections:o}=await s.json(),a=o.filter(l=>bi(l,r));if(a.length===0&&w(`No connection found matching "${r}". Run: botparty connections list`),a.length>1){console.error(`${q("Multiple connections match")} "${r}":
97
+ `);for(let l of a){let d=l.accountLabel&&l.accountLabel!=="default"?_(` (${l.accountLabel})`):"";console.error(` ${g(l.displayName||l.provider)}${d} ${_(l.id)}`)}console.error(`
98
+ Specify the exact connection ID to delete.`),process.exit(1)}let c=a[0];t.yes!==!0&&t.y!==!0&&w(`This will permanently delete ${g(c.displayName||c.provider)} (${c.id}). Pass --yes to confirm.`);let u=await Ye(`/api/botparty/connections?id=${encodeURIComponent(c.id)}`,n,i,{method:"DELETE"});if(!u.ok){let l=await u.json().catch(()=>({error:u.statusText}));w(l.error||`HTTP ${u.status}`)}m?E({deleted:!0,connectionId:c.id,provider:c.provider}):console.log(`${P("Deleted")} ${g(c.displayName||c.provider)} (${c.id})`)}function Ai(){console.log(`
99
+ ${g("botparty")} \u2014 federated bot identity, authentication, and payments
100
+
101
+ ${g("USAGE")}
102
+ botparty <command> [options]
103
+
104
+ ${g("COMMANDS")}
105
+ ${f("init")} [namespace] Register a new namespace
106
+ --name <name> Human-readable label
107
+ --ttl <minutes> Key rotation TTL (default: 15)
108
+
109
+ ${f("whoami")} Show current identity
110
+ ${f("info")} [namespace] Show namespace info from server
111
+ ${f("link")} Generate a link URL for a human
112
+ ${f("token")} Generate a JWT token (stdout)
113
+ ${f("reset")} Clear local state
114
+
115
+ ${f("curl")} <url> Authenticated fetch
116
+ -X, --method <METHOD> HTTP method (default: GET)
117
+ -d, --data <body> Request body
118
+ -H, --header <header> Additional header
119
+
120
+ ${f("keys list")} List all keys
121
+ ${f("keys add")} Add a delegated key
122
+ --public-key <pem> PEM-encoded public key
123
+ --scopes <s1,s2> Comma-separated scopes
124
+ --ttl <minutes> Rotation TTL
125
+ --label <label> Human-readable label
126
+ --expires <iso> Hard expiry timestamp
127
+
128
+ ${f("keys rotate")} [keyId] Rotate a key (default: current)
129
+ ${f("keys delete")} <keyId> Delete a key (--yes to confirm)
130
+ ${f("keys invalidate")} <keyId> Panic button \u2014 locks namespace
131
+ --reason <text> Reason for invalidation
132
+
133
+ ${f("connections list")} List credential connections
134
+ --provider <domain> Filter by provider
135
+ --status <status> Filter by status
136
+ ${f("connections delete")} <name> Delete a connection by name, provider, or ID (--yes)
137
+
138
+ ${f("destroy")} Destroy namespace (--yes to confirm)
139
+
140
+ ${g("GLOBAL OPTIONS")}
141
+ --server <url> BotParty server URL
142
+ --state-dir <path> Local state directory (default: ~/.botparty)
143
+ --json Output machine-readable JSON
144
+
145
+ ${g("ENVIRONMENT")}
146
+ BOTPARTY_SERVER_URL Server URL override
147
+ BOTPARTY_STATE_DIR State directory override
148
+
149
+ ${g("EXAMPLES")}
150
+ botparty init # Auto-generate namespace
151
+ botparty init my-cool-bot --ttl 30 # Custom namespace
152
+ botparty curl https://api.example.com # Authenticated GET
153
+ botparty curl https://api.example.com -X POST -d '{"key":"val"}'
154
+ botparty keys list # Show all keys
155
+ botparty keys rotate # Rotate current key
156
+ botparty connections list # Show credential connections
157
+ botparty connections delete <id> --yes # Remove a connection
158
+ botparty link # Get link URL for human
159
+ `)}async function _i(){let{command:t,subcommand:e,positional:r,flags:n}=ii(process.argv);if(n.json===!0&&(m=!0),n.version===!0||n.v===!0&&t!=="curl"&&t!=="fetch"||t==="version"){m?E({version:"0.0.1"}):console.log("botparty 0.0.1");return}if((n.help===!0||n.h===!0||t==="help")&&t!=="curl"&&t!=="fetch"){Ai();return}try{switch(t){case"init":case"join":await si(n,r);break;case"whoami":await oi(n);break;case"info":await ai(n,r);break;case"link":await ci(n);break;case"destroy":await li(n);break;case"reset":await ui(n);break;case"token":await di(n);break;case"curl":case"fetch":await hi(n);break;case"keys":switch(e){case"list":case"ls":await pi(n);break;case"add":await fi(n);break;case"rotate":await mi(n,r);break;case"delete":case"rm":await gi(n,r);break;case"invalidate":case"panic":await yi(n,r);break;default:w(`Unknown keys subcommand: ${e||"(none)"}. Run: botparty keys list`)}break;case"connections":case"conn":switch(e){case"list":case"ls":case"":await wi(n);break;case"delete":case"rm":await Ei(n,r);break;default:w(`Unknown connections subcommand: ${e}. Run: botparty connections list`)}break;default:w(`Unknown command: ${t}. Run: botparty --help`)}}catch(i){ri(i)}}_i();
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "botparty",
3
+ "version": "0.0.26",
4
+ "description": "CLI for BotParty — federated bot identity, authentication, and payments",
5
+ "type": "module",
6
+ "bin": {
7
+ "botparty": "dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "README.md"
12
+ ],
13
+ "keywords": [
14
+ "botparty",
15
+ "cli",
16
+ "auth",
17
+ "jwt",
18
+ "identity",
19
+ "agents",
20
+ "bots"
21
+ ],
22
+ "author": "BotParty",
23
+ "license": "SEE LICENSE IN LICENSE",
24
+ "homepage": "https://botparty.club",
25
+ "scripts": {
26
+ "clean": "rm -rf dist",
27
+ "build": "npm run clean && node build.mjs",
28
+ "prepublishOnly": "npm run build",
29
+ "test": "bash test-e2e.sh",
30
+ "dev": "tsc --watch",
31
+ "deploy": "npm version patch && npm publish"
32
+ },
33
+ "dependencies": {
34
+ "@botparty/sdk": "file:../client-sdk",
35
+ "commander": "^14.0.3"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^22.0.0",
39
+ "esbuild": "^0.25.0",
40
+ "typescript": "^5"
41
+ },
42
+ "packageManager": "pnpm@10.32.0+sha512.9b2634bb3fed5601c33633f2d92593f506270a3963b8c51d2b2d6a828da615ce4e9deebef9614ccebbc13ac8d3c0f9c9ccceb583c69c8578436fa477dbb20d70"
43
+ }