keychains 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +40 -0
  2. package/package.json +27 -0
package/dist/index.js ADDED
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ #!/usr/bin/env node
3
+ var Be=Object.create;var L=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Ye=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var D=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var v=(o,e)=>()=>(o&&(e=o(o=0)),e);var $=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),H=(o,e)=>{for(var t in e)L(o,t,{get:e[t],enumerable:!0})},Xe=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Je(e))!ze.call(o,n)&&n!==t&&L(o,n,{get:()=>e[n],enumerable:!(i=Ge(e,n))||i.enumerable});return o};var Qe=(o,e,t)=>(t=o!=null?Be(Ye(o)):{},Xe(e||!o||!o.__esModule?L(t,"default",{value:o,enumerable:!0}):t,o));var V=$(G=>{var N=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},B=class extends N{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};G.CommanderError=N;G.InvalidArgumentError=B});var q=$(Y=>{var{InvalidArgumentError:Ze}=V(),J=class{constructor(e,t){switch(this.description=t||"",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.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new Ze(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function et(o){let e=o.name()+(o.variadic===!0?"...":"");return o.required?"<"+e+">":"["+e+"]"}Y.Argument=J;Y.humanReadableArgName=et});var Q=$(X=>{var{humanReadableArgName:tt}=q(),z=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 t=e.commands.filter(n=>!n._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((n,s)=>n.name().localeCompare(s.name())),t}compareOptions(e,t){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),s=i.long&&e._findOption(i.long);!n&&!s?t.push(i):i.long&&!s?t.push(e.createOption(i.long,i.description)):i.short&&!n&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);t.push(...n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(i=>tt(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),n=t.helpWidth??80;function s(u,m){return t.formatItem(u,i,m,t)}let r=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],l=t.commandDescription(e);l.length>0&&(r=r.concat([t.boxWrap(t.styleCommandDescription(l),n),""]));let a=t.visibleArguments(e).map(u=>s(t.styleArgumentTerm(t.argumentTerm(u)),t.styleArgumentDescription(t.argumentDescription(u))));a.length>0&&(r=r.concat([t.styleTitle("Arguments:"),...a,""]));let c=t.visibleOptions(e).map(u=>s(t.styleOptionTerm(t.optionTerm(u)),t.styleOptionDescription(t.optionDescription(u))));if(c.length>0&&(r=r.concat([t.styleTitle("Options:"),...c,""])),t.showGlobalOptions){let u=t.visibleGlobalOptions(e).map(m=>s(t.styleOptionTerm(t.optionTerm(m)),t.styleOptionDescription(t.optionDescription(m))));u.length>0&&(r=r.concat([t.styleTitle("Global Options:"),...u,""]))}let h=t.visibleCommands(e).map(u=>s(t.styleSubcommandTerm(t.subcommandTerm(u)),t.styleSubcommandDescription(t.subcommandDescription(u))));return h.length>0&&(r=r.concat([t.styleTitle("Commands:"),...h,""])),r.join(`
4
+ `)}displayWidth(e){return pe(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).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(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).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,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,i,n){let r=" ".repeat(2);if(!i)return r+e;let l=e.padEnd(t+e.length-n.displayWidth(e)),a=2,h=(this.helpWidth??80)-t-a-2,u;return h<this.minWidthToWrap||n.preformatted(i)?u=i:u=n.boxWrap(i,h).replace(/\n/g,`
5
+ `+" ".repeat(t+a)),r+l+" ".repeat(a)+u.replace(/\n/g,`
6
+ ${r}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,s=[];return i.forEach(r=>{let l=r.match(n);if(l===null){s.push("");return}let a=[l.shift()],c=this.displayWidth(a[0]);l.forEach(h=>{let u=this.displayWidth(h);if(c+u<=t){a.push(h),c+=u;return}s.push(a.join(""));let m=h.trimStart();a=[m],c=this.displayWidth(m)}),s.push(a.join(""))}),s.join(`
7
+ `)}};function pe(o){let e=/\x1b\[\d*(;\d*)*m/g;return o.replace(e,"")}X.Help=z;X.stripColor=pe});var ie=$(te=>{var{InvalidArgumentError:it}=V(),Z=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=nt(e);this.short=i.shortFlag,this.long=i.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}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),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}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new it(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?fe(this.name().replace(/^no-/,"")):fe(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ee=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,s=n!==void 0?n:!1;return t.negate===(s===e)}};function fe(o){return o.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function nt(o){let e,t,i=/^-[^-]$/,n=/^--[^-]/,s=o.split(/[ |,]+/).concat("guard");if(i.test(s[0])&&(e=s.shift()),n.test(s[0])&&(t=s.shift()),!e&&i.test(s[0])&&(e=s.shift()),!e&&n.test(s[0])&&(e=t,t=s.shift()),s[0].startsWith("-")){let r=s[0],l=`option creation failed due to '${r}' in option flags '${o}'`;throw/^-[^-][^-]/.test(r)?new Error(`${l}
8
+ - a short flag is a single dash and a single character
9
+ - either use a single dash and a single character (for a short flag)
10
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(r)?new Error(`${l}
11
+ - too many short flags`):n.test(r)?new Error(`${l}
12
+ - too many long flags`):new Error(`${l}
13
+ - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${o}'.`);return{shortFlag:e,longFlag:t}}te.Option=Z;te.DualOptions=ee});var _e=$(ge=>{function st(o,e){if(Math.abs(o.length-e.length)>3)return Math.max(o.length,e.length);let t=[];for(let i=0;i<=o.length;i++)t[i]=[i];for(let i=0;i<=e.length;i++)t[0][i]=i;for(let i=1;i<=e.length;i++)for(let n=1;n<=o.length;n++){let s=1;o[n-1]===e[i-1]?s=0:s=1,t[n][i]=Math.min(t[n-1][i]+1,t[n][i-1]+1,t[n-1][i-1]+s),n>1&&i>1&&o[n-1]===e[i-2]&&o[n-2]===e[i-1]&&(t[n][i]=Math.min(t[n][i],t[n-2][i-2]+1))}return t[o.length][e.length]}function rt(o,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=o.startsWith("--");t&&(o=o.slice(2),e=e.map(r=>r.slice(2)));let i=[],n=3,s=.4;return e.forEach(r=>{if(r.length<=1)return;let l=st(o,r),a=Math.max(o.length,r.length);(a-l)/a>s&&(l<n?(n=l,i=[r]):l===n&&i.push(r))}),i.sort((r,l)=>r.localeCompare(l)),t&&(i=i.map(r=>`--${r}`)),i.length>1?`
14
+ (Did you mean one of ${i.join(", ")}?)`:i.length===1?`
15
+ (Did you mean ${i[0]}?)`:""}ge.suggestSimilar=rt});var Oe=$(ae=>{var ot=D("node:events").EventEmitter,ne=D("node:child_process"),w=D("node:path"),U=D("node:fs"),d=D("node:process"),{Argument:at,humanReadableArgName:lt}=q(),{CommanderError:se}=V(),{Help:ct,stripColor:ht}=Q(),{Option:ye,DualOptions:ut}=ie(),{suggestSimilar:Ce}=_e(),re=class o extends ot{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:t=>d.stdout.write(t),writeErr:t=>d.stderr.write(t),outputError:(t,i)=>i(t),getOutHelpWidth:()=>d.stdout.isTTY?d.stdout.columns:void 0,getErrHelpWidth:()=>d.stderr.isTTY?d.stderr.columns:void 0,getOutHasColors:()=>oe()??(d.stdout.isTTY&&d.stdout.hasColors?.()),getErrHasColors:()=>oe()??(d.stderr.isTTY&&d.stderr.hasColors?.()),stripColor:t=>ht(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}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 t=this;t;t=t.parent)e.push(t);return e}command(e,t,i){let n=t,s=i;typeof n=="object"&&n!==null&&(s=n,n=null),s=s||{};let[,r,l]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(r);return n&&(a.description(n),a._executableHandler=!0),s.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(s.noHelp||s.hidden),a._executableFile=s.executableFile||null,l&&a.arguments(l),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),n?this:a}createCommand(e){return new o(e)}createHelp(){return Object.assign(new ct,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(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,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
16
+ - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new at(e,t)}argument(e,t,i,n){let s=this.createArgument(e,t);return typeof i=="function"?s.default(n).argParser(i):s.default(i),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.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,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,i,n]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",r=this.createCommand(i);return r.helpOption(!1),n&&r.arguments(n),s&&r.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=r,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=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,t){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
17
+ Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,i){this._exitCallback&&this._exitCallback(new se(e,t,i)),d.exit(e)}action(e){let t=i=>{let n=this.registeredArguments.length,s=i.slice(0,n);return this._storeOptionsAsProperties?s[n]=this:s[n]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new ye(e,t)}_callParseArg(e,t,i,n){try{return e.parseArg(t,i)}catch(s){if(s.code==="commander.invalidArgument"){let r=`${n} ${s.message}`;this.error(r,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let i=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 '${i}'
18
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=n=>[n.name()].concat(n.aliases()),i=t(e).find(n=>this._findCommand(n));if(i){let n=t(this._findCommand(i)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let n=(s,r,l)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let a=this.getOptionValue(i);s!==null&&e.parseArg?s=this._callParseArg(e,s,a,r):s!==null&&e.variadic&&(s=e._concatValue(s,a)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(i,s,l)};return this.on("option:"+t,s=>{let r=`error: option '${e.flags}' argument '${s}' is invalid.`;n(s,r,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let r=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;n(s,r,"env")}),this}_optionEx(e,t,i,n,s){if(typeof t=="object"&&t instanceof ye)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(t,i);if(r.makeOptionMandatory(!!e.mandatory),typeof n=="function")r.default(s).argParser(n);else if(n instanceof RegExp){let l=n;n=(a,c)=>{let h=l.exec(a);return h?h[0]:c},r.default(s).argParser(n)}else r.default(n);return this.addOption(r)}option(e,t,i,n){return this._optionEx({},e,t,i,n)}requiredOption(e,t,i,n){return this._optionEx({mandatory:!0},e,t,i,n)}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,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,i){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(t=i.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){d.versions?.electron&&(t.from="electron");let n=d.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=d.argv),this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":d.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(e,t){this._prepareForParse();let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){this._prepareForParse();let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),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.
19
+ - 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,t,i){if(U.existsSync(e))return;let n=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${e}' does not exist
20
+ - if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
21
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
22
+ - ${n}`;throw new Error(s)}_executeSubCommand(e,t){t=t.slice();let i=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function s(h,u){let m=w.resolve(h,u);if(U.existsSync(m))return m;if(n.includes(w.extname(u)))return;let f=n.find(x=>U.existsSync(`${m}${x}`));if(f)return`${m}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let h;try{h=U.realpathSync(this._scriptPath)}catch{h=this._scriptPath}l=w.resolve(w.dirname(h),l)}if(l){let h=s(l,r);if(!h&&!e._executableFile&&this._scriptPath){let u=w.basename(this._scriptPath,w.extname(this._scriptPath));u!==this._name&&(h=s(l,`${u}-${e._name}`))}r=h||r}i=n.includes(w.extname(r));let a;d.platform!=="win32"?i?(t.unshift(r),t=we(d.execArgv).concat(t),a=ne.spawn(d.argv[0],t,{stdio:"inherit"})):a=ne.spawn(r,t,{stdio:"inherit"}):(this._checkForMissingExecutable(r,l,e._name),t.unshift(r),t=we(d.execArgv).concat(t),a=ne.spawn(d.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{d.on(u,()=>{a.killed===!1&&a.exitCode===null&&a.kill(u)})});let c=this._exitCallback;a.on("close",h=>{h=h??1,c?c(new se(h,"commander.executeSubCommandAsync","(close)")):d.exit(h)}),a.on("error",h=>{if(h.code==="ENOENT")this._checkForMissingExecutable(r,l,e._name);else if(h.code==="EACCES")throw new Error(`'${r}' not executable`);if(!c)d.exit(1);else{let u=new se(1,"commander.executeSubCommandAsync","(error)");u.nestedError=h,c(u)}}),this.runningCommand=a}_dispatchSubcommand(e,t,i){let n=this._findCommand(e);n||this.help({error:!0}),n._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,n,"preSubcommand"),s=this._chainOrCall(s,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(i));else return n._parseCommand(t,i)}),s}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==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=(i,n,s)=>{let r=n;if(n!==null&&i.parseArg){let l=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;r=this._callParseArg(i,n,s,l)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,n)=>{let s=i.defaultValue;i.variadic?n<this.args.length?(s=this.args.slice(n),i.parseArg&&(s=s.reduce((r,l)=>e(i,l,r),i.defaultValue))):s===void 0&&(s=[]):n<this.args.length&&(s=this.args[n],i.parseArg&&(s=e(i,s,i.defaultValue))),t[n]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let i=e,n=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(r=>{n.push({hookedCommand:s,callback:r})})}),t==="postAction"&&n.reverse(),n.forEach(s=>{i=this._chainOrCall(i,()=>s.callback(s.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let n=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(s=>{n=this._chainOrCall(n,()=>s(this,t))}),n}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let r;return r=this._chainOrCallHooks(r,"preAction"),r=this._chainOrCall(r,()=>this._actionHandler(this.processedArgs)),this.parent&&(r=this._chainOrCall(r,()=>{this.parent.emit(s,e,t)})),r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent&&this.parent.listenerCount(s))n(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(i=>{let n=i.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let n=e.find(s=>i.conflictsWith.includes(s.attributeName()));n&&this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],n=t,s=e.slice();function r(a){return a.length>1&&a[0]==="-"}let l=null;for(;s.length;){let a=s.shift();if(a==="--"){n===i&&n.push(a),n.push(...s);break}if(l&&!r(a)){this.emit(`option:${l.name()}`,a);continue}if(l=null,r(a)){let c=this._findOption(a);if(c){if(c.required){let h=s.shift();h===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,h)}else if(c.optional){let h=null;s.length>0&&!r(s[0])&&(h=s.shift()),this.emit(`option:${c.name()}`,h)}else this.emit(`option:${c.name()}`);l=c.variadic?c:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let c=this._findOption(`-${a[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,a.slice(2)):(this.emit(`option:${c.name()}`),s.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let c=a.indexOf("="),h=this._findOption(a.slice(0,c));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,a.slice(c+1));continue}}if(r(a)&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(a)){t.push(a),s.length>0&&i.push(...s);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){i.push(a),s.length>0&&i.push(...s);break}}if(this._passThroughOptions){n.push(a),s.length>0&&n.push(...s);break}n.push(a)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let n=this.options[i].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
23
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
24
+ `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
25
+ `),this.outputHelp({error:!0}));let i=t||{},n=i.exitCode||1,s=i.code||"commander.error";this._exit(n,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in d.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,d.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new ut(this.options),t=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!t(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let i=r=>{let l=r.attributeName(),a=this.getOptionValue(l),c=this.options.find(u=>u.negate&&l===u.attributeName()),h=this.options.find(u=>!u.negate&&l===u.attributeName());return c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg)?c:h||r},n=r=>{let l=i(r),a=l.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},s=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{let r=s.createHelp().visibleOptions(s).filter(l=>l.long).map(l=>l.long);n=n.concat(r),s=s.parent}while(s&&!s._enablePositionalOptions);t=Ce(e,n)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(s=>{n.push(s.name()),s.alias()&&n.push(s.alias())}),t=Ce(e,n)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let n=this.createOption(t,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
26
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(i=>lt(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=w.basename(e,w.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),i=this._getOutputContext(e);t.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=t.formatHelp(this,t);return i.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let t=!!e.error,i,n,s;return t?(i=l=>this._outputConfiguration.writeErr(l),n=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(i=l=>this._outputConfiguration.writeOut(l),n=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:t,write:l=>(n||(l=this._outputConfiguration.stripColor(l)),i(l)),hasColors:n,helpWidth:s}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getOutputContext(e),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(r=>r.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation({error:i.error});if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(r=>r.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number(d.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
27
+ Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,s=>{let r;typeof t=="function"?r=t({error:s.error,command:s.command}):r=t,r&&s.write(`${r}
28
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function we(o){return o.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",n="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?n=s[3]:i=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],i=s[3],n=s[4]),t&&n!=="0"?`${t}=${i}:${parseInt(n)+1}`:e})}function oe(){if(d.env.NO_COLOR||d.env.FORCE_COLOR==="0"||d.env.FORCE_COLOR==="false")return!1;if(d.env.FORCE_COLOR||d.env.CLICOLOR_FORCE!==void 0)return!0}ae.Command=re;ae.useColor=oe});var xe=$(_=>{var{Argument:be}=q(),{Command:le}=Oe(),{CommanderError:dt,InvalidArgumentError:Ae}=V(),{Help:mt}=Q(),{Option:$e}=ie();_.program=new le;_.createCommand=o=>new le(o);_.createOption=(o,e)=>new $e(o,e);_.createArgument=(o,e)=>new be(o,e);_.Command=le;_.Option=$e;_.Argument=be;_.Help=mt;_.CommanderError=dt;_.InvalidArgumentError=Ae;_.InvalidOptionArgumentError=Ae});var Te={};H(Te,{getCredentialsPath:()=>ce,getKeychainsDir:()=>K,getServerUrl:()=>g,loadCredentials:()=>y,saveCredentials:()=>R});import{readFileSync as pt,writeFileSync as ft,mkdirSync as gt,existsSync as Ee}from"fs";import{join as Se}from"path";import{homedir as _t}from"os";function ce(o){return o?.credentialsPath??yt}function g(o){return o?.serverUrl??process.env.KEYCHAINS_SERVER_URL??Ct}function y(o){let e=ce(o);if(!Ee(e))return null;try{let t=pt(e,"utf-8");return JSON.parse(t)}catch{return null}}function R(o,e){let t=ce(e),i=t.substring(0,t.lastIndexOf("/"));Ee(i)||gt(i,{recursive:!0,mode:448}),ft(t,JSON.stringify(o,null,2),{mode:384})}function K(){return Pe}var Pe,yt,Ct,k=v(()=>{"use strict";Pe=Se(_t(),".keychains"),yt=Se(Pe,"credentials.json"),Ct="https://keychains.dev"});var p,I=v(()=>{"use strict";p=class extends Error{constructor(t,i,n,s){super(t);this.code=i;this.statusCode=n;this.approvalUrl=s;this.name="KeychainsError"}}});var ue={};H(ue,{authenticate:()=>O,register:()=>Ot,rotateKeys:()=>bt});import{execSync as E}from"child_process";import{readFileSync as De,existsSync as W,mkdirSync as wt}from"fs";import{join as M}from"path";async function Ot(o,e){let t=g(e),i=K();W(i)||wt(i,{recursive:!0,mode:448});let n=M(i,"id_ed25519"),s=M(i,"id_ed25519.pub");W(n)||E(`ssh-keygen -t ed25519 -f "${n}" -N "" -C "keychains-machine"`,{stdio:"pipe"});let r=De(s,"utf-8").trim(),l=he(),a=await fetch(`${t}/api/machine/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({publicKey:r,machineName:o,fingerprint:l})});if(!a.ok){let u=await a.json().catch(()=>({error:"unknown"}));throw new p(`Registration failed: ${u.error_description||u.error}`,"registration_failed",a.status)}let{machineId:c}=await a.json(),h={machineId:c,publicKeyPath:s,privateKeyPath:n,serverUrl:t};return R(h,e),h}async function O(o){let e=y(o);if(!e)throw new p("No machine credentials found. Run register() first.","not_registered");let t=e.serverUrl,i=he(),n=await fetch(`${t}/api/machine/challenge`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:e.machineId,fingerprint:i})});if(!n.ok){let c=await n.json().catch(()=>({error:"unknown"}));throw new p(`Challenge failed: ${c.error_description||c.error}`,"challenge_failed",n.status)}let{nonce:s}=await n.json(),r=At(s,e.privateKeyPath),l=await fetch(`${t}/api/machine/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:e.machineId,signature:r,fingerprint:i})});if(!l.ok){let c=await l.json().catch(()=>({error:"unknown"}));throw new p(`Verification failed: ${c.error_description||c.error}`,"verification_failed",l.status)}let a=await l.json();if(a.status==="pending")throw new p("Machine is verified but not yet linked to a user. Visit the auth URL to link.","pending_link");return{token:a.token,userId:a.userId,expiresAt:a.expiresAt}}async function bt(o){let e=y(o);if(!e)throw new p("No machine credentials found.","not_registered");let t=K(),i=M(t,"id_ed25519"),n=M(t,"id_ed25519.pub"),s=`.bak.${Date.now()}`;W(i)&&E(`mv "${i}" "${i}${s}"`,{stdio:"pipe"}),W(n)&&E(`mv "${n}" "${n}${s}"`,{stdio:"pipe"}),E(`ssh-keygen -t ed25519 -f "${i}" -N "" -C "keychains-machine-rotated"`,{stdio:"pipe"});let r=De(n,"utf-8").trim(),l=await fetch(`${e.serverUrl}/api/machine/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({publicKey:r,machineName:`rotated-${e.machineId}`,fingerprint:he()})});if(!l.ok){let h=await l.json().catch(()=>({error:"unknown"}));throw new p(`Key rotation failed: ${h.error_description||h.error}`,"rotation_failed",l.status)}let{machineId:a}=await l.json(),c={machineId:a,publicKeyPath:n,privateKeyPath:i,serverUrl:e.serverUrl};return R(c,o),c}function At(o,e){return E(`echo -n "${o}" | openssl pkeyutl -sign -inkey "${e}" | openssl base64 -A`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function he(){try{let o=E("hostname",{encoding:"utf-8"}).trim(),e=process.platform,t=process.arch;return`${o}:${e}:${t}`}catch{return"unknown"}}var F=v(()=>{"use strict";k();I()});var j={};H(j,{checkScopes:()=>xt,createPermissionRequest:()=>$t,listPermissions:()=>kt,mintPermissionToken:()=>de,revokePermission:()=>vt});async function $t(o,e){let{token:t}=await O(e);if(!y(e))throw new p("Not registered","not_registered");let n=g(e),s=await fetch(`${n}/api/permissions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(o)});if(!s.ok){let a=await s.json().catch(()=>({error:"unknown"}));throw new p(`Failed to create permission: ${a.error_description||a.error}`,"permission_create_failed",s.status)}let r=await s.json(),l=`${n}/add-permissions?permissionId=${r.id}`;return{permission:r,approvalUrl:l}}async function de(o,e,t){let{token:i}=await O(t),n=g(t),s=await fetch(`${n}/api/permissions/${o}/token`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({ttlSeconds:e})});if(!s.ok){let r=await s.json().catch(()=>({error:"unknown"}));throw new p(`Failed to mint token: ${r.error_description||r.error}`,"token_mint_failed",s.status)}return await s.json()}async function xt(o,e,t){let{token:i}=await O(t),n=g(t),s=await fetch(`${n}/api/permissions/${o}`,{headers:{Authorization:`Bearer ${i}`}});if(!s.ok)throw new p("Failed to fetch permission","fetch_failed",s.status);let r=await s.json(),l=new Set(r.approvedScopes),a=e.filter(h=>!l.has(h)),c={allowed:a.length===0,missing:a};return a.length>0&&r.mode==="wildcard"&&(c.approvalUrl=`${n}/add-permissions?permissionId=${o}&scopes=${encodeURIComponent(a.join(" "))}`),c}async function vt(o,e){let{token:t}=await O(e),i=g(e),n=await fetch(`${i}/api/permissions/${o}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}});if(!n.ok){let s=await n.json().catch(()=>({error:"unknown"}));throw new p(`Failed to revoke: ${s.error_description||s.error}`,"revoke_failed",n.status)}}async function kt(o){let{token:e}=await O(o),t=g(o),i=await fetch(`${t}/api/permissions`,{headers:{Authorization:`Bearer ${e}`}});if(!i.ok)throw new p("Failed to list permissions","list_failed",i.status);return(await i.json()).permissions}var S=v(()=>{"use strict";k();F();I()});var je={};H(je,{createDelegate:()=>Et,mintDelegateToken:()=>St});async function Et(o,e={},t){let{execSync:i}=await import("child_process"),{readFileSync:n,mkdtempSync:s,rmSync:r}=await import("fs"),{join:l}=await import("path"),{tmpdir:a}=await import("os"),{token:c}=await O(t),h=g(t),u=s(l(a(),"keychains-delegate-")),m=l(u,"delegate_key");try{i(`ssh-keygen -t ed25519 -f "${m}" -N "" -C "keychains-delegate"`,{stdio:"pipe"});let f=n(`${m}.pub`,"utf-8").trim(),x=n(m,"utf-8"),b=await fetch(`${h}/api/permissions/${o}/delegate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({publicKey:f,...e})});if(!b.ok){let A=await b.json().catch(()=>({error:"unknown"}));throw new p(`Failed to create delegate: ${A.error_description||A.error}`,"delegate_create_failed",b.status)}return{delegate:await b.json(),privateKey:x}}finally{r(u,{recursive:!0,force:!0})}}async function St(o,e,t,i){let{execSync:n}=await import("child_process"),{writeFileSync:s,mkdtempSync:r,rmSync:l}=await import("fs"),{join:a}=await import("path"),{tmpdir:c}=await import("os"),u=y(i)?.serverUrl??g(i),m=await fetch(`${u}/api/delegates/${o}/challenge`,{method:"POST"});if(!m.ok){let T=await m.json().catch(()=>({error:"unknown"}));throw new p(`Delegate challenge failed: ${T.error_description||T.error}`,"delegate_challenge_failed",m.status)}let{nonce:f}=await m.json(),x=r(a(c(),"keychains-sig-")),b=a(x,"delegate_key");try{s(b,e,{mode:384});let T=n(`echo -n "${f}" | openssl pkeyutl -sign -inkey "${b}" | openssl base64 -A`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),A=await fetch(`${u}/api/delegates/${o}/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({signature:T,ttlSeconds:t})});if(!A.ok){let me=await A.json().catch(()=>({error:"unknown"}));throw new p(`Delegate token mint failed: ${me.error_description||me.error}`,"delegate_token_failed",A.status)}return await A.json()}finally{l(x,{recursive:!0,force:!0})}}var Ne=v(()=>{"use strict";k();F();I()});var Ke={};H(Ke,{proxyFetch:()=>Pt});async function Pt(o,e={},t){let{token:i,permissionRequestId:n,...s}=e,l=y(t)?.serverUrl??g(t),a=i;if(!a){if(!n)throw new p("Either token or permissionRequestId must be provided","missing_token");a=await Re(n,t)}let c=new URL(o),h=`${l}/${c.hostname}${c.pathname}${c.search}`,u=new Headers(s.headers);u.set("X-Proxy-Authorization",`Bearer ${a}`);let m=await fetch(h,{...s,headers:u});if(m.status===403)try{let f=await m.json();throw new p(f.error==="scope_refused"?`Scopes refused: ${f.refused_scopes?.join(", ")}`:`Insufficient scopes: ${f.missing_scopes?.join(", ")}`,f.error||"insufficient_scope",403,f.approval_url)}catch(f){throw f instanceof p?f:new p("Permission denied","permission_denied",403)}if(m.status===401&&n){P=null;let f=await Re(n,t);return u.set("X-Proxy-Authorization",`Bearer ${f}`),fetch(h,{...s,headers:u})}return m}async function Re(o,e){if(P&&P.requestId===o&&P.expiresAt>Date.now()+3e4)return P.token;let t=await de(o,void 0,e);return P={token:t.token,expiresAt:Date.now()+t.expiresIn*1e3,requestId:o},t.token}var P,We=v(()=>{"use strict";k();S();I();P=null});var ve=Qe(xe(),1),{program:qt,createCommand:Ut,createArgument:Rt,createOption:Kt,CommanderError:Wt,InvalidArgumentError:Mt,InvalidOptionArgumentError:Lt,Command:ke,Argument:Bt,Option:Gt,Help:Jt}=ve.default;function He(o){o.command("register").description("Register this machine with Keychains.dev").requiredOption("--name <name>","Machine name").option("--server <url>","Server URL","https://keychains.dev").action(async e=>{let{register:t}=await Promise.resolve().then(()=>(F(),ue));try{console.log(`Registering machine "${e.name}"...`);let i=await t(e.name,{serverUrl:e.server});console.log(`
29
+ Machine registered successfully!`),console.log(` Machine ID: ${i.machineId}`),console.log(` Keys stored at: ${i.privateKeyPath}`),console.log(`
30
+ Next: Link this machine to your account by visiting the auth URL.`)}catch(i){console.error(`Registration failed: ${i instanceof Error?i.message:i}`),process.exit(1)}})}function Ve(o){o.command("create-permission").description("Create a new permission request").requiredOption("--name <name>","Permission name").option("--scopes <scopes>",'Comma-separated scopes (e.g. "gmail::readonly,github::repo")').option("--wildcard","Create a wildcard permission (scopes added dynamically)").option("--allow-delegation","Allow creating delegates from this permission").option("--description <desc>","Description of what this permission is for").option("--ttl <seconds>","TTL in seconds","7776000").action(async e=>{let{createPermissionRequest:t}=await Promise.resolve().then(()=>(S(),j));try{let i=e.scopes?e.scopes.split(",").map(s=>s.trim()):void 0;!e.wildcard&&(!i||i.length===0)&&(console.error("Error: --scopes is required for scoped mode. Use --wildcard for dynamic scopes."),process.exit(1)),console.log(`Creating ${e.wildcard?"wildcard":"scoped"} permission "${e.name}"...`);let n=await t({name:e.name,requestedScopes:i,wildcard:e.wildcard,allowDelegation:e.allowDelegation,description:e.description,ttlSeconds:parseInt(e.ttl,10)});console.log(`
31
+ Permission request created!`),console.log(` ID: ${n.permission.id}`),console.log(` Mode: ${n.permission.mode}`),console.log(` Status: ${n.permission.status}`),console.log(`
32
+ Share this URL with your user to approve:`),console.log(` ${n.approvalUrl}`)}catch(i){console.error(`Failed: ${i instanceof Error?i.message:i}`),process.exit(1)}})}function Ie(o){o.command("list-permissions").description("List all permission requests for this machine").action(async()=>{let{listPermissions:e}=await Promise.resolve().then(()=>(S(),j));try{let t=await e();if(t.length===0){console.log("No permission requests found.");return}console.log(`Found ${t.length} permission(s):
33
+ `);for(let i of t){let n=i.mode==="wildcard"?"[wildcard]":"[scoped]",s=`(${i.status})`;console.log(` ${i.name} ${n} ${s}`),console.log(` ID: ${i.id}`),console.log(` Scopes: ${i.approvedScopes.length>0?i.approvedScopes.join(", "):"(none)"}`),console.log(` Created: ${new Date(i.createdAt).toLocaleString()}`),i.lastUsedAt&&console.log(` Last used: ${new Date(i.lastUsedAt).toLocaleString()}`),console.log()}}catch(t){console.error(`Failed: ${t instanceof Error?t.message:t}`),process.exit(1)}})}function Fe(o){o.command("revoke <id>").description("Revoke a permission request or delegate").action(async e=>{let{revokePermission:t}=await Promise.resolve().then(()=>(S(),j));try{console.log(`Revoking ${e}...`),await t(e),console.log("Revoked successfully.")}catch(i){console.error(`Failed: ${i instanceof Error?i.message:i}`),process.exit(1)}})}function qe(o){o.command("delegate <permissionId>").description("Create a delegate identity from a permission request").option("--scopes <scopes>","Comma-separated scopes for the delegate").option("--wildcard","Create a wildcard delegate").option("--ttl <seconds>","TTL in seconds","86400").option("--allow-delegation","Allow the delegate to create sub-delegates").action(async(e,t)=>{let{createDelegate:i}=await Promise.resolve().then(()=>(Ne(),je));try{let n=t.scopes?t.scopes.split(",").map(r=>r.trim()):void 0;!t.wildcard&&(!n||n.length===0)&&(console.error("Error: --scopes is required for scoped delegates. Use --wildcard for dynamic scopes."),process.exit(1)),console.log(`Creating delegate for permission ${e}...`);let s=await i(e,{mode:t.wildcard?"wildcard":"scoped",scopes:n,ttlSeconds:parseInt(t.ttl,10),allowDelegation:t.allowDelegation});console.log(`
34
+ Delegate created!`),console.log(` Delegate ID: ${s.delegate.delegateId}`),console.log(` Mode: ${s.delegate.mode}`),console.log(` Expires: ${new Date(s.delegate.expiresAt).toLocaleString()}`),console.log(`
35
+ Ship these to the remote system:`),console.log(` KEYCHAINS_DELEGATE_ID=${s.delegate.delegateId}`),console.log(" KEYCHAINS_DELEGATE_KEY=<private key below>"),console.log(`
36
+ --- BEGIN DELEGATE PRIVATE KEY ---`),console.log(s.privateKey),console.log("--- END DELEGATE PRIVATE KEY ---")}catch(n){console.error(`Failed: ${n instanceof Error?n.message:n}`),process.exit(1)}})}function Ue(o){o.command("rotate-keys").description("Rotate the SSH keypair for this machine").action(async()=>{let{rotateKeys:e}=await Promise.resolve().then(()=>(F(),ue));try{console.log("Rotating SSH keys...");let t=await e();console.log(`
37
+ Keys rotated successfully!`),console.log(` New Machine ID: ${t.machineId}`),console.log(` Keys stored at: ${t.privateKeyPath}`),console.log(`
38
+ Note: You'll need to re-link this machine to your account.`)}catch(t){console.error(`Failed: ${t instanceof Error?t.message:t}`),process.exit(1)}})}function Me(o){o.command("curl <url>").description("Make a proxied API call (like curl, but through Keychains)").requiredOption("--permission <id>","Permission request ID to use").option("-X, --method <method>","HTTP method","GET").option("-H, --header <header...>","Request headers (key: value)").option("-d, --data <data>","Request body").action(async(e,t)=>{let{proxyFetch:i}=await Promise.resolve().then(()=>(We(),Ke));try{let n={};if(t.header)for(let l of t.header){let a=l.indexOf(":");a>0&&(n[l.slice(0,a).trim()]=l.slice(a+1).trim())}let s=await i(e,{permissionRequestId:t.permission,method:t.method,headers:n,body:t.data||void 0});console.log(`HTTP ${s.status} ${s.statusText}`),s.headers.forEach((l,a)=>{console.log(`${a}: ${l}`)}),console.log();let r=await s.text();try{let l=JSON.parse(r);console.log(JSON.stringify(l,null,2))}catch{console.log(r)}}catch(n){if(n&&typeof n=="object"&&"approvalUrl"in n){let s=n;console.error(`Permission required: ${s.message}`),console.error(`Approve at: ${s.approvalUrl}`)}else console.error(`Failed: ${n instanceof Error?n.message:n}`);process.exit(1)}})}function Le(o){o.command("status").description("Show current machine status and permissions").action(async()=>{let{loadCredentials:e}=await Promise.resolve().then(()=>(k(),Te)),{listPermissions:t}=await Promise.resolve().then(()=>(S(),j)),i=e();if(!i){console.log('Not registered. Run `keychains register --name "my-machine"` first.');return}console.log("Machine Status:"),console.log(` Machine ID: ${i.machineId}`),console.log(` Server: ${i.serverUrl}`),console.log(` Keys: ${i.privateKeyPath}`),console.log();try{let n=await t();console.log(`Permissions: ${n.length} total`);let s=n.filter(a=>a.status==="active"),r=n.filter(a=>a.status==="pending"),l=n.filter(a=>a.mode==="wildcard");if(console.log(` Active: ${s.length}`),console.log(` Pending: ${r.length}`),console.log(` Wildcard: ${l.length}`),s.length>0){console.log(`
39
+ Active permissions:`);for(let a of s)console.log(` - ${a.name} (${a.mode}) \u2014 ${a.approvedScopes.length} scopes`)}}catch(n){console.log(`
40
+ Could not fetch permissions: ${n instanceof Error?n.message:"Authentication required"}`),console.log("Link this machine to your account first.")}})}var C=new ke;C.name("keychains").description("Keychains.dev CLI \u2014 Secure credential delegation for AI agents").version("0.1.0");He(C);Ve(C);Ie(C);Fe(C);qe(C);Ue(C);Me(C);Le(C);C.parse();
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "keychains",
3
+ "version": "0.0.1",
4
+ "description": "CLI for Keychains.dev — register machines, manage permissions, and make proxied API calls",
5
+ "type": "module",
6
+ "bin": {
7
+ "keychains": "dist/index.js"
8
+ },
9
+ "main": "dist/index.js",
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "scripts": {
14
+ "clean": "rm -rf dist",
15
+ "build": "npm run clean && node build.mjs",
16
+ "prepublishOnly": "npm run build",
17
+ "dev": "tsc --watch"
18
+ },
19
+ "dependencies": {
20
+ "commander": "^13.0.0"
21
+ },
22
+ "devDependencies": {
23
+ "esbuild": "^0.25.0",
24
+ "typescript": "^5"
25
+ },
26
+ "packageManager": "pnpm@10.29.2+sha512.bef43fa759d91fd2da4b319a5a0d13ef7a45bb985a3d7342058470f9d2051a3ba8674e629672654686ef9443ad13a82da2beb9eeb3e0221c87b8154fff9d74b8"
27
+ }