shared-context-ai 0.1.3 → 0.1.5

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 +30 -30
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,33 +1,33 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Hi=Object.create;var ge=Object.defineProperty;var Fi=Object.getOwnPropertyDescriptor;var Di=Object.getOwnPropertyNames;var Ni=Object.getPrototypeOf,Li=Object.prototype.hasOwnProperty;var O=(n,e)=>()=>(n&&(e=n(n=0)),e);var W=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),_e=(n,e)=>{for(var t in e)ge(n,t,{get:e[t],enumerable:!0})},Mi=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Di(e))!Li.call(n,r)&&r!==t&&ge(n,r,{get:()=>e[r],enumerable:!(i=Fi(e,r))||i.enumerable});return n};var y=(n,e,t)=>(t=n!=null?Hi(Ni(n)):{},Mi(e||!n||!n.__esModule?ge(t,"default",{value:n,enumerable:!0}):t,n));var K=W(we=>{"use strict";var ee=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}},xe=class extends ee{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};we.CommanderError=ee;we.InvalidArgumentError=xe});var te=W(Ce=>{"use strict";var{InvalidArgumentError:ji}=K(),ye=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 ji(`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 Ri(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}Ce.Argument=ye;Ce.humanReadableArgName=Ri});var Se=W(Oe=>{"use strict";var{humanReadableArgName:Vi}=te(),Ae=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(r=>!r._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((r,s)=>r.name().localeCompare(s.name())),t}compareOptions(e,t){let i=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(r=>!r.hidden),i=e._getHelpOption();if(i&&!i.hidden){let r=i.short&&e._findOption(i.short),s=i.long&&e._findOption(i.long);!r&&!s?t.push(i):i.long&&!s?t.push(e.createOption(i.long,i.description)):i.short&&!r&&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 r=i.options.filter(s=>!s.hidden);t.push(...r)}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=>Vi(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,r)=>Math.max(i,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(r)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,r)=>Math.max(i,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(r)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let r=e.parent;r;r=r.parent)i=r.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),r=t.helpWidth??80;function s(p,m){return t.formatItem(p,i,m,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(o=o.concat([t.boxWrap(t.styleCommandDescription(a),r),""]));let l=t.visibleArguments(e).map(p=>s(t.styleArgumentTerm(t.argumentTerm(p)),t.styleArgumentDescription(t.argumentDescription(p))));l.length>0&&(o=o.concat([t.styleTitle("Arguments:"),...l,""]));let c=t.visibleOptions(e).map(p=>s(t.styleOptionTerm(t.optionTerm(p)),t.styleOptionDescription(t.optionDescription(p))));if(c.length>0&&(o=o.concat([t.styleTitle("Options:"),...c,""])),t.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(m=>s(t.styleOptionTerm(t.optionTerm(m)),t.styleOptionDescription(t.optionDescription(m))));p.length>0&&(o=o.concat([t.styleTitle("Global Options:"),...p,""]))}let d=t.visibleCommands(e).map(p=>s(t.styleSubcommandTerm(t.subcommandTerm(p)),t.styleSubcommandDescription(t.subcommandDescription(p))));return d.length>0&&(o=o.concat([t.styleTitle("Commands:"),...d,""])),o.join(`
3
- `)}displayWidth(e){return pt(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,r){let o=" ".repeat(2);if(!i)return o+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),l=2,d=(this.helpWidth??80)-t-l-2,p;return d<this.minWidthToWrap||r.preformatted(i)?p=i:p=r.boxWrap(i,d).replace(/\n/g,`
4
- `+" ".repeat(t+l)),o+a+" ".repeat(l)+p.replace(/\n/g,`
5
- ${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,s=[];return i.forEach(o=>{let a=o.match(r);if(a===null){s.push("");return}let l=[a.shift()],c=this.displayWidth(l[0]);a.forEach(d=>{let p=this.displayWidth(d);if(c+p<=t){l.push(d),c+=p;return}s.push(l.join(""));let m=d.trimStart();l=[m],c=this.displayWidth(m)}),s.push(l.join(""))}),s.join(`
6
- `)}};function pt(n){let e=/\x1b\[\d*(;\d*)*m/g;return n.replace(e,"")}Oe.Help=Ae;Oe.stripColor=pt});var ve=W(ke=>{"use strict";var{InvalidArgumentError:Wi}=K(),be=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=Ui(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 Wi(`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?mt(this.name().replace(/^no-/,"")):mt(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 r=this.negativeOptions.get(i).presetArg,s=r!==void 0?r:!1;return t.negate===(s===e)}};function mt(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ui(n){let e,t,i=/^-[^-]$/,r=/^--[^-]/,s=n.split(/[ |,]+/).concat("guard");if(i.test(s[0])&&(e=s.shift()),r.test(s[0])&&(t=s.shift()),!e&&i.test(s[0])&&(e=s.shift()),!e&&r.test(s[0])&&(e=t,t=s.shift()),s[0].startsWith("-")){let o=s[0],a=`option creation failed due to '${o}' in option flags '${n}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
2
+ "use strict";var Hi=Object.create;var _e=Object.defineProperty;var Fi=Object.getOwnPropertyDescriptor;var Di=Object.getOwnPropertyNames;var Ni=Object.getPrototypeOf,Li=Object.prototype.hasOwnProperty;var O=(n,e)=>()=>(n&&(e=n(n=0)),e);var B=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),we=(n,e)=>{for(var t in e)_e(n,t,{get:e[t],enumerable:!0})},Mi=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Di(e))!Li.call(n,r)&&r!==t&&_e(n,r,{get:()=>e[r],enumerable:!(i=Fi(e,r))||i.enumerable});return n};var C=(n,e,t)=>(t=n!=null?Hi(Ni(n)):{},Mi(e||!n||!n.__esModule?_e(t,"default",{value:n,enumerable:!0}):t,n));var X=B(ye=>{"use strict";var ie=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}},xe=class extends ie{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ye.CommanderError=ie;ye.InvalidArgumentError=xe});var re=B(Ae=>{"use strict";var{InvalidArgumentError:Ri}=X(),Ce=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 Ri(`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 Vi(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}Ae.Argument=Ce;Ae.humanReadableArgName=Vi});var Se=B(be=>{"use strict";var{humanReadableArgName:ji}=re(),Oe=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(r=>!r._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((r,s)=>r.name().localeCompare(s.name())),t}compareOptions(e,t){let i=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(r=>!r.hidden),i=e._getHelpOption();if(i&&!i.hidden){let r=i.short&&e._findOption(i.short),s=i.long&&e._findOption(i.long);!r&&!s?t.push(i):i.long&&!s?t.push(e.createOption(i.long,i.description)):i.short&&!r&&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 r=i.options.filter(s=>!s.hidden);t.push(...r)}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=>ji(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,r)=>Math.max(i,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(r)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,r)=>Math.max(i,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(r)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let r=e.parent;r;r=r.parent)i=r.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),r=t.helpWidth??80;function s(p,_){return t.formatItem(p,i,_,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],l=t.commandDescription(e);l.length>0&&(o=o.concat([t.boxWrap(t.styleCommandDescription(l),r),""]));let a=t.visibleArguments(e).map(p=>s(t.styleArgumentTerm(t.argumentTerm(p)),t.styleArgumentDescription(t.argumentDescription(p))));a.length>0&&(o=o.concat([t.styleTitle("Arguments:"),...a,""]));let c=t.visibleOptions(e).map(p=>s(t.styleOptionTerm(t.optionTerm(p)),t.styleOptionDescription(t.optionDescription(p))));if(c.length>0&&(o=o.concat([t.styleTitle("Options:"),...c,""])),t.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(_=>s(t.styleOptionTerm(t.optionTerm(_)),t.styleOptionDescription(t.optionDescription(_))));p.length>0&&(o=o.concat([t.styleTitle("Global Options:"),...p,""]))}let h=t.visibleCommands(e).map(p=>s(t.styleSubcommandTerm(t.subcommandTerm(p)),t.styleSubcommandDescription(t.subcommandDescription(p))));return h.length>0&&(o=o.concat([t.styleTitle("Commands:"),...h,""])),o.join(`
3
+ `)}displayWidth(e){return mt(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,r){let o=" ".repeat(2);if(!i)return o+e;let l=e.padEnd(t+e.length-r.displayWidth(e)),a=2,h=(this.helpWidth??80)-t-a-2,p;return h<this.minWidthToWrap||r.preformatted(i)?p=i:p=r.boxWrap(i,h).replace(/\n/g,`
4
+ `+" ".repeat(t+a)),o+l+" ".repeat(a)+p.replace(/\n/g,`
5
+ ${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,s=[];return i.forEach(o=>{let l=o.match(r);if(l===null){s.push("");return}let a=[l.shift()],c=this.displayWidth(a[0]);l.forEach(h=>{let p=this.displayWidth(h);if(c+p<=t){a.push(h),c+=p;return}s.push(a.join(""));let _=h.trimStart();a=[_],c=this.displayWidth(_)}),s.push(a.join(""))}),s.join(`
6
+ `)}};function mt(n){let e=/\x1b\[\d*(;\d*)*m/g;return n.replace(e,"")}be.Help=Oe;be.stripColor=mt});var Te=B(ve=>{"use strict";var{InvalidArgumentError:Wi}=X(),Ee=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=Ui(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 Wi(`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?ft(this.name().replace(/^no-/,"")):ft(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ke=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 r=this.negativeOptions.get(i).presetArg,s=r!==void 0?r:!1;return t.negate===(s===e)}};function ft(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ui(n){let e,t,i=/^-[^-]$/,r=/^--[^-]/,s=n.split(/[ |,]+/).concat("guard");if(i.test(s[0])&&(e=s.shift()),r.test(s[0])&&(t=s.shift()),!e&&i.test(s[0])&&(e=s.shift()),!e&&r.test(s[0])&&(e=t,t=s.shift()),s[0].startsWith("-")){let o=s[0],l=`option creation failed due to '${o}' in option flags '${n}'`;throw/^-[^-][^-]/.test(o)?new Error(`${l}
7
7
  - a short flag is a single dash and a single character
8
8
  - either use a single dash and a single character (for a short flag)
9
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(o)?new Error(`${a}
10
- - too many short flags`):r.test(o)?new Error(`${a}
11
- - too many long flags`):new Error(`${a}
12
- - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${n}'.`);return{shortFlag:e,longFlag:t}}ke.Option=be;ke.DualOptions=Ee});var gt=W(ft=>{"use strict";function Bi(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let i=0;i<=n.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 r=1;r<=n.length;r++){let s=1;n[r-1]===e[i-1]?s=0:s=1,t[r][i]=Math.min(t[r-1][i]+1,t[r][i-1]+1,t[r-1][i-1]+s),r>1&&i>1&&n[r-1]===e[i-2]&&n[r-2]===e[i-1]&&(t[r][i]=Math.min(t[r][i],t[r-2][i-2]+1))}return t[n.length][e.length]}function qi(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(o=>o.slice(2)));let i=[],r=3,s=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Bi(n,o),l=Math.max(n.length,o.length);(l-a)/l>s&&(a<r?(r=a,i=[o]):a===r&&i.push(o))}),i.sort((o,a)=>o.localeCompare(a)),t&&(i=i.map(o=>`--${o}`)),i.length>1?`
9
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(o)?new Error(`${l}
10
+ - too many short flags`):r.test(o)?new Error(`${l}
11
+ - too many long flags`):new Error(`${l}
12
+ - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${n}'.`);return{shortFlag:e,longFlag:t}}ve.Option=Ee;ve.DualOptions=ke});var _t=B(gt=>{"use strict";function Bi(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let i=0;i<=n.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 r=1;r<=n.length;r++){let s=1;n[r-1]===e[i-1]?s=0:s=1,t[r][i]=Math.min(t[r-1][i]+1,t[r][i-1]+1,t[r-1][i-1]+s),r>1&&i>1&&n[r-1]===e[i-2]&&n[r-2]===e[i-1]&&(t[r][i]=Math.min(t[r][i],t[r-2][i-2]+1))}return t[n.length][e.length]}function qi(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(o=>o.slice(2)));let i=[],r=3,s=.4;return e.forEach(o=>{if(o.length<=1)return;let l=Bi(n,o),a=Math.max(n.length,o.length);(a-l)/a>s&&(l<r?(r=l,i=[o]):l===r&&i.push(o))}),i.sort((o,l)=>o.localeCompare(l)),t&&(i=i.map(o=>`--${o}`)),i.length>1?`
13
13
  (Did you mean one of ${i.join(", ")}?)`:i.length===1?`
14
- (Did you mean ${i[0]}?)`:""}ft.suggestSimilar=qi});var yt=W(He=>{"use strict";var Gi=require("events").EventEmitter,Te=require("child_process"),I=require("path"),ie=require("fs"),f=require("process"),{Argument:Ji,humanReadableArgName:Yi}=te(),{CommanderError:$e}=K(),{Help:Ki,stripColor:zi}=Se(),{Option:_t,DualOptions:Xi}=ve(),{suggestSimilar:xt}=gt(),Ie=class n extends Gi{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=>f.stdout.write(t),writeErr:t=>f.stderr.write(t),outputError:(t,i)=>i(t),getOutHelpWidth:()=>f.stdout.isTTY?f.stdout.columns:void 0,getErrHelpWidth:()=>f.stderr.isTTY?f.stderr.columns:void 0,getOutHasColors:()=>Pe()??(f.stdout.isTTY&&f.stdout.hasColors?.()),getErrHasColors:()=>Pe()??(f.stderr.isTTY&&f.stderr.hasColors?.()),stripColor:t=>zi(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 r=t,s=i;typeof r=="object"&&r!==null&&(s=r,r=null),s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return r&&(l.description(r),l._executableHandler=!0),s.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(s.noHelp||s.hidden),l._executableFile=s.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),r?this:l}createCommand(e){return new n(e)}createHelp(){return Object.assign(new Ki,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
14
+ (Did you mean ${i[0]}?)`:""}gt.suggestSimilar=qi});var Ct=B(Fe=>{"use strict";var Gi=require("events").EventEmitter,$e=require("child_process"),H=require("path"),ne=require("fs"),m=require("process"),{Argument:Ji,humanReadableArgName:Yi}=re(),{CommanderError:Ie}=X(),{Help:Ki,stripColor:zi}=Se(),{Option:wt,DualOptions:Xi}=Te(),{suggestSimilar:xt}=_t(),Pe=class n extends Gi{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=>m.stdout.write(t),writeErr:t=>m.stderr.write(t),outputError:(t,i)=>i(t),getOutHelpWidth:()=>m.stdout.isTTY?m.stdout.columns:void 0,getErrHelpWidth:()=>m.stderr.isTTY?m.stderr.columns:void 0,getOutHasColors:()=>He()??(m.stdout.isTTY&&m.stdout.hasColors?.()),getErrHasColors:()=>He()??(m.stderr.isTTY&&m.stderr.hasColors?.()),stripColor:t=>zi(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 r=t,s=i;typeof r=="object"&&r!==null&&(s=r,r=null),s=s||{};let[,o,l]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return r&&(a.description(r),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),r?this:a}createCommand(e){return new n(e)}createHelp(){return Object.assign(new Ki,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
15
15
  - 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 Ji(e,t)}argument(e,t,i,r){let s=this.createArgument(e,t);return typeof i=="function"?s.default(r).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,r]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(i);return o.helpOption(!1),r&&o.arguments(r),s&&o.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=o,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}'.
16
- 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 $e(e,t,i)),f.exit(e)}action(e){let t=i=>{let r=this.registeredArguments.length,s=i.slice(0,r);return this._storeOptionsAsProperties?s[r]=this:s[r]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new _t(e,t)}_callParseArg(e,t,i,r){try{return e.parseArg(t,i)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${r} ${s.message}`;this.error(o,{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}'
17
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=r=>[r.name()].concat(r.aliases()),i=t(e).find(r=>this._findCommand(r));if(i){let r=t(this._findCommand(i)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${r}'`)}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 r=(s,o,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let l=this.getOptionValue(i);s!==null&&e.parseArg?s=this._callParseArg(e,s,l,o):s!==null&&e.variadic&&(s=e._concatValue(s,l)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(i,s,a)};return this.on("option:"+t,s=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;r(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;r(s,o,"env")}),this}_optionEx(e,t,i,r,s){if(typeof t=="object"&&t instanceof _t)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,i);if(o.makeOptionMandatory(!!e.mandatory),typeof r=="function")o.default(s).argParser(r);else if(r instanceof RegExp){let a=r;r=(l,c)=>{let d=a.exec(l);return d?d[0]:c},o.default(s).argParser(r)}else o.default(r);return this.addOption(o)}option(e,t,i,r){return this._optionEx({},e,t,i,r)}requiredOption(e,t,i,r){return this._optionEx({mandatory:!0},e,t,i,r)}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){f.versions?.electron&&(t.from="electron");let r=f.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=f.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":f.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.
18
- - 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(ie.existsSync(e))return;let r=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
16
+ 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 Ie(e,t,i)),m.exit(e)}action(e){let t=i=>{let r=this.registeredArguments.length,s=i.slice(0,r);return this._storeOptionsAsProperties?s[r]=this:s[r]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new wt(e,t)}_callParseArg(e,t,i,r){try{return e.parseArg(t,i)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${r} ${s.message}`;this.error(o,{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}'
17
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=r=>[r.name()].concat(r.aliases()),i=t(e).find(r=>this._findCommand(r));if(i){let r=t(this._findCommand(i)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${r}'`)}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 r=(s,o,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,o):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 o=`error: option '${e.flags}' argument '${s}' is invalid.`;r(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;r(s,o,"env")}),this}_optionEx(e,t,i,r,s){if(typeof t=="object"&&t instanceof wt)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,i);if(o.makeOptionMandatory(!!e.mandatory),typeof r=="function")o.default(s).argParser(r);else if(r instanceof RegExp){let l=r;r=(a,c)=>{let h=l.exec(a);return h?h[0]:c},o.default(s).argParser(r)}else o.default(r);return this.addOption(o)}option(e,t,i,r){return this._optionEx({},e,t,i,r)}requiredOption(e,t,i,r){return this._optionEx({mandatory:!0},e,t,i,r)}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){m.versions?.electron&&(t.from="electron");let r=m.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=m.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":m.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.
18
+ - 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(ne.existsSync(e))return;let r=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
19
19
  - if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
20
20
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
21
- - ${r}`;throw new Error(s)}_executeSubCommand(e,t){t=t.slice();let i=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function s(d,p){let m=I.resolve(d,p);if(ie.existsSync(m))return m;if(r.includes(I.extname(p)))return;let A=r.find(fe=>ie.existsSync(`${m}${fe}`));if(A)return`${m}${A}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=ie.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=I.resolve(I.dirname(d),a)}if(a){let d=s(a,o);if(!d&&!e._executableFile&&this._scriptPath){let p=I.basename(this._scriptPath,I.extname(this._scriptPath));p!==this._name&&(d=s(a,`${p}-${e._name}`))}o=d||o}i=r.includes(I.extname(o));let l;f.platform!=="win32"?i?(t.unshift(o),t=wt(f.execArgv).concat(t),l=Te.spawn(f.argv[0],t,{stdio:"inherit"})):l=Te.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=wt(f.execArgv).concat(t),l=Te.spawn(f.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{f.on(p,()=>{l.killed===!1&&l.exitCode===null&&l.kill(p)})});let c=this._exitCallback;l.on("close",d=>{d=d??1,c?c(new $e(d,"commander.executeSubCommandAsync","(close)")):f.exit(d)}),l.on("error",d=>{if(d.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)f.exit(1);else{let p=new $e(1,"commander.executeSubCommandAsync","(error)");p.nestedError=d,c(p)}}),this.runningCommand=l}_dispatchSubcommand(e,t,i){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,r,"preSubcommand"),s=this._chainOrCall(s,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(i));else return r._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,r,s)=>{let o=r;if(r!==null&&i.parseArg){let a=`error: command-argument value '${r}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,r,s,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,r)=>{let s=i.defaultValue;i.variadic?r<this.args.length?(s=this.args.slice(r),i.parseArg&&(s=s.reduce((o,a)=>e(i,a,o),i.defaultValue))):s===void 0&&(s=[]):r<this.args.length&&(s=this.args[r],i.parseArg&&(s=e(i,s,i.defaultValue))),t[r]=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,r=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(o=>{r.push({hookedCommand:s,callback:o})})}),t==="postAction"&&r.reverse(),r.forEach(s=>{i=this._chainOrCall(i,()=>s.callback(s.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let r=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(s=>{r=this._chainOrCall(r,()=>s(this,t))}),r}_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 r=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){r(),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,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(s))r(),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():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),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 r=i.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let r=e.find(s=>i.conflictsWith.includes(s.attributeName()));r&&this._conflictingOption(i,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],r=t,s=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;s.length;){let l=s.shift();if(l==="--"){r===i&&r.push(l),r.push(...s);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let c=this._findOption(l);if(c){if(c.required){let d=s.shift();d===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,d)}else if(c.optional){let d=null;s.length>0&&!o(s[0])&&(d=s.shift()),this.emit(`option:${c.name()}`,d)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),s.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),d=this._findOption(l.slice(0,c));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,l.slice(c+1));continue}}if(o(l)&&(r=i),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(l)){t.push(l),s.length>0&&i.push(...s);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){i.push(l),s.length>0&&i.push(...s);break}}if(this._passThroughOptions){r.push(l),s.length>0&&r.push(...s);break}r.push(l)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let r=this.options[i].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
21
+ - ${r}`;throw new Error(s)}_executeSubCommand(e,t){t=t.slice();let i=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function s(h,p){let _=H.resolve(h,p);if(ne.existsSync(_))return _;if(r.includes(H.extname(p)))return;let T=r.find(x=>ne.existsSync(`${_}${x}`));if(T)return`${_}${T}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let h;try{h=ne.realpathSync(this._scriptPath)}catch{h=this._scriptPath}l=H.resolve(H.dirname(h),l)}if(l){let h=s(l,o);if(!h&&!e._executableFile&&this._scriptPath){let p=H.basename(this._scriptPath,H.extname(this._scriptPath));p!==this._name&&(h=s(l,`${p}-${e._name}`))}o=h||o}i=r.includes(H.extname(o));let a;m.platform!=="win32"?i?(t.unshift(o),t=yt(m.execArgv).concat(t),a=$e.spawn(m.argv[0],t,{stdio:"inherit"})):a=$e.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,l,e._name),t.unshift(o),t=yt(m.execArgv).concat(t),a=$e.spawn(m.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{m.on(p,()=>{a.killed===!1&&a.exitCode===null&&a.kill(p)})});let c=this._exitCallback;a.on("close",h=>{h=h??1,c?c(new Ie(h,"commander.executeSubCommandAsync","(close)")):m.exit(h)}),a.on("error",h=>{if(h.code==="ENOENT")this._checkForMissingExecutable(o,l,e._name);else if(h.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)m.exit(1);else{let p=new Ie(1,"commander.executeSubCommandAsync","(error)");p.nestedError=h,c(p)}}),this.runningCommand=a}_dispatchSubcommand(e,t,i){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,r,"preSubcommand"),s=this._chainOrCall(s,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(i));else return r._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,r,s)=>{let o=r;if(r!==null&&i.parseArg){let l=`error: command-argument value '${r}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,r,s,l)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,r)=>{let s=i.defaultValue;i.variadic?r<this.args.length?(s=this.args.slice(r),i.parseArg&&(s=s.reduce((o,l)=>e(i,l,o),i.defaultValue))):s===void 0&&(s=[]):r<this.args.length&&(s=this.args[r],i.parseArg&&(s=e(i,s,i.defaultValue))),t[r]=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,r=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(o=>{r.push({hookedCommand:s,callback:o})})}),t==="postAction"&&r.reverse(),r.forEach(s=>{i=this._chainOrCall(i,()=>s.callback(s.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let r=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(s=>{r=this._chainOrCall(r,()=>s(this,t))}),r}_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 r=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){r(),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,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(s))r(),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():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),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 r=i.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let r=e.find(s=>i.conflictsWith.includes(s.attributeName()));r&&this._conflictingOption(i,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],r=t,s=e.slice();function o(a){return a.length>1&&a[0]==="-"}let l=null;for(;s.length;){let a=s.shift();if(a==="--"){r===i&&r.push(a),r.push(...s);break}if(l&&!o(a)){this.emit(`option:${l.name()}`,a);continue}if(l=null,o(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&&!o(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(o(a)&&(r=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){r.push(a),s.length>0&&r.push(...s);break}r.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 r=this.options[i].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
22
22
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
23
23
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
24
- `),this.outputHelp({error:!0}));let i=t||{},r=i.exitCode||1,s=i.code||"commander.error";this._exit(r,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in f.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()}`,f.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Xi(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(r=>!t(r)).forEach(r=>{this.setOptionValueWithSource(r,i.implied[r],"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=o=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find(p=>p.negate&&a===p.attributeName()),d=this.options.find(p=>!p.negate&&a===p.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:d||o},r=o=>{let a=i(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);r=r.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=xt(e,r)}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 r=[];this.createHelp().visibleCommands(this).forEach(s=>{r.push(s.name()),s.alias()&&r.push(s.alias())}),t=xt(e,r)}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 r=this.createOption(t,i);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
25
- `),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 r=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}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=>Yi(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=I.basename(e,I.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 r=t.formatHelp(this,t);return i.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,i,r,s;return t?(i=a=>this._outputConfiguration.writeErr(a),r=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),r=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(r||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:r,helpWidth:s}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getOutputContext(e),r={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);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",r),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",r))}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(f.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.
24
+ `),this.outputHelp({error:!0}));let i=t||{},r=i.exitCode||1,s=i.code||"commander.error";this._exit(r,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in m.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()}`,m.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Xi(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(r=>!t(r)).forEach(r=>{this.setOptionValueWithSource(r,i.implied[r],"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=o=>{let l=o.attributeName(),a=this.getOptionValue(l),c=this.options.find(p=>p.negate&&l===p.attributeName()),h=this.options.find(p=>!p.negate&&l===p.attributeName());return c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg)?c:h||o},r=o=>{let l=i(o),a=l.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},s=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(l=>l.long).map(l=>l.long);r=r.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=xt(e,r)}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 r=[];this.createHelp().visibleCommands(this).forEach(s=>{r.push(s.name()),s.alias()&&r.push(s.alias())}),t=xt(e,r)}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 r=this.createOption(t,i);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
25
+ `),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 r=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}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=>Yi(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=H.basename(e,H.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 r=t.formatHelp(this,t);return i.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,i,r,s;return t?(i=l=>this._outputConfiguration.writeErr(l),r=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(i=l=>this._outputConfiguration.writeOut(l),r=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:t,write:l=>(r||(l=this._outputConfiguration.stripColor(l)),i(l)),hasColors:r,helpWidth:s}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getOutputContext(e),r={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);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",r),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",r))}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(m.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.
26
26
  Expecting one of '${i.join("', '")}'`);let r=`${e}Help`;return this.on(r,s=>{let o;typeof t=="function"?o=t({error:s.error,command:s.command}):o=t,o&&s.write(`${o}
27
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function wt(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",r="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])?r=s[3]:i=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],i=s[3],r=s[4]),t&&r!=="0"?`${t}=${i}:${parseInt(r)+1}`:e})}function Pe(){if(f.env.NO_COLOR||f.env.FORCE_COLOR==="0"||f.env.FORCE_COLOR==="false")return!1;if(f.env.FORCE_COLOR||f.env.CLICOLOR_FORCE!==void 0)return!0}He.Command=Ie;He.useColor=Pe});var St=W(b=>{"use strict";var{Argument:Ct}=te(),{Command:Fe}=yt(),{CommanderError:Qi,InvalidArgumentError:At}=K(),{Help:Zi}=Se(),{Option:Ot}=ve();b.program=new Fe;b.createCommand=n=>new Fe(n);b.createOption=(n,e)=>new Ot(n,e);b.createArgument=(n,e)=>new Ct(n,e);b.Command=Fe;b.Option=Ot;b.Argument=Ct;b.Help=Zi;b.CommanderError=Qi;b.InvalidArgumentError=At;b.InvalidOptionArgumentError=At});var Ft={};_e(Ft,{addToManifest:()=>F,clearAuth:()=>je,getAuth:()=>$,getConfig:()=>H,getManifest:()=>P,removeFromManifest:()=>Ve,saveAuth:()=>Me,saveConfig:()=>Ht,saveManifest:()=>Re,updateConfig:()=>ir});function er(){(0,T.mkdirSync)(re,{recursive:!0})}function Ne(n,e){try{return(0,T.existsSync)(n)?JSON.parse((0,T.readFileSync)(n,"utf-8")):e}catch{return e}}function Le(n,e,t=!1){if(er(),(0,T.writeFileSync)(n,JSON.stringify(e,null,2)+`
28
- `,"utf-8"),t)try{(0,T.chmodSync)(n,384)}catch{}}function $(){return Ne(De,null)}function Me(n){Le(De,n,!0)}function je(){try{(0,T.writeFileSync)(De,"{}","utf-8")}catch{}}function H(){return Ne(It,tr)}function Ht(n){Le(It,n)}function ir(n){let e=H();Ht({...e,...n})}function P(){return Ne(Pt,rr)}function Re(n){Le(Pt,n)}function F(n){let e=P(),t=e.installations.findIndex(i=>i.resourceId===n.resourceId&&i.agent===n.agent);t>=0?e.installations[t]=n:e.installations.push(n),Re(e)}function Ve(n,e){let t=P();t.installations=t.installations.filter(i=>!(i.resourceId===n&&(!e||i.agent===e))),Re(t)}var T,z,$t,re,De,It,Pt,tr,rr,E=O(()=>{"use strict";T=require("fs"),z=require("path"),$t=require("os"),re=(0,z.join)((0,$t.homedir)(),".config","shared-context"),De=(0,z.join)(re,"auth.json"),It=(0,z.join)(re,"config.json"),Pt=(0,z.join)(re,"manifest.json");tr={apiBase:"https://sharedcontext.ai"};rr={installations:[]}});var Dt={};_e(Dt,{del:()=>We,get:()=>C,isAuthenticated:()=>w,patch:()=>or,post:()=>k});function nr(){return H().apiBase||"https://sharedcontext.ai"}function sr(){let n={"Content-Type":"application/json"},e=$();return e?.token&&(n.Authorization=`Bearer ${e.token}`),n}function w(){return!!$()?.token}async function ne(n,e,t){let i=`${nr()}${e}`;try{let r=await fetch(i,{method:n,headers:sr(),body:t?JSON.stringify(t):void 0}),s=r.headers.get("content-type")||"";if(!s.includes("application/json"))return r.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${s||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${r.status}`,message:r.statusText}};let o=await r.json();return r.ok?{ok:!0,data:o.data??o}:{ok:!1,error:{code:o?.error?.code||`HTTP_${r.status}`,message:o?.error?.message||o?.message||r.statusText}}}catch(r){return{ok:!1,error:{code:"NETWORK_ERROR",message:r instanceof Error?r.message:"Network request failed"}}}}function C(n){return ne("GET",n)}function k(n,e){return ne("POST",n,e)}function or(n,e){return ne("PATCH",n,e)}function We(n,e){return ne("DELETE",n,e)}var v=O(()=>{"use strict";E()});function lr(){try{return Ge.default.statSync("/.dockerenv"),!0}catch{return!1}}function cr(){try{return Ge.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Je(){return qe===void 0&&(qe=lr()||cr()),qe}var Ge,qe,jt=O(()=>{"use strict";Ge=y(require("fs"),1)});function B(){return Ye===void 0&&(Ye=ur()||Je()),Ye}var Rt,Ye,ur,Ke=O(()=>{"use strict";Rt=y(require("fs"),1);jt();ur=()=>{try{return Rt.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var ze,Wt,le,Vt,M,Xe=O(()=>{"use strict";ze=y(require("process"),1),Wt=y(require("os"),1),le=y(require("fs"),1);Ke();Vt=()=>{if(ze.default.platform!=="linux")return!1;if(Wt.default.release().toLowerCase().includes("microsoft"))return!B();try{if(le.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!B()}catch{}return le.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||le.default.existsSync("/run/WSL")?!B():!1},M=ze.default.env.__IS_WSL_TEST__?Vt:Vt()});var Qe,Q,dr,hr,Ze,Ut=O(()=>{"use strict";Qe=y(require("process"),1),Q=y(require("fs/promises"),1);Xe();Xe();dr=(()=>{let n="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await Q.default.access(t,Q.constants.F_OK),i=!0}catch{}if(!i)return n;let r=await Q.default.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(r);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):n}})(),hr=async()=>`${await dr()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Ze=async()=>M?hr():`${Qe.default.env.SYSTEMROOT||Qe.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function j(n,e,t){let i=r=>Object.defineProperty(n,e,{value:r,enumerable:!0,writable:!0});return Object.defineProperty(n,e,{configurable:!0,enumerable:!0,get(){let r=t();return i(r),r},set(r){i(r)}}),n}var Bt=O(()=>{"use strict"});async function et(){if(Gt.default.platform!=="darwin")throw new Error("macOS only");let{stdout:n}=await pr("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(n)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var qt,Gt,Jt,pr,Yt=O(()=>{"use strict";qt=require("util"),Gt=y(require("process"),1),Jt=require("child_process"),pr=(0,qt.promisify)(Jt.execFile)});async function Xt(n,{humanReadableOutput:e=!0,signal:t}={}){if(Kt.default.platform!=="darwin")throw new Error("macOS only");let i=e?[]:["-ss"],r={};t&&(r.signal=t);let{stdout:s}=await mr("osascript",["-e",n,i],r);return s.trim()}var Kt,zt,tt,mr,Qt=O(()=>{"use strict";Kt=y(require("process"),1),zt=require("util"),tt=require("child_process"),mr=(0,zt.promisify)(tt.execFile)});async function it(n){return Xt(`tell application "Finder" to set app_path to application file id "${n}" as string
29
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var Zt=O(()=>{"use strict";Qt()});async function nt(n=fr){let{stdout:e}=await n("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new rt(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:i}=t.groups,r=i.lastIndexOf("."),s=i.lastIndexOf("-"),o=r===-1?void 0:i.slice(0,r),a=s===-1?void 0:i.slice(0,s);return ce[i]??ce[o]??ce[a]??{name:i,id:i}}var ei,ti,fr,ce,xn,rt,ii=O(()=>{"use strict";ei=require("util"),ti=require("child_process"),fr=(0,ei.promisify)(ti.execFile),ce={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},xn=new Map(Object.entries(ce)),rt=class extends Error{}});async function st(){if(ue.default.platform==="darwin"){let n=await et();return{name:await it(n),id:n}}if(ue.default.platform==="linux"){let{stdout:n}=await gr("xdg-mime",["query","default","x-scheme-handler/http"]),e=n.trim();return{name:_r(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(ue.default.platform==="win32")return nt();throw new Error("Only macOS, Linux, and Windows are supported")}var ri,ue,ni,gr,_r,si=O(()=>{"use strict";ri=require("util"),ue=y(require("process"),1),ni=require("child_process");Yt();Zt();ii();gr=(0,ri.promisify)(ni.execFile),_r=n=>n.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var hi={};_e(hi,{apps:()=>R,default:()=>Ar,openApp:()=>Cr});async function wr(){let n=await Ze(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=lt.Buffer.from(e,"utf16le").toString("base64"),{stdout:i}=await xr(n,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),r=i.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[r]?{id:s[r]}:{}}function ci(n){if(typeof n=="string"||Array.isArray(n))return n;let{[ai]:e}=n;if(!e)throw new Error(`${ai} is not supported`);return e}function he({[J]:n},{wsl:e}){if(e&&M)return ci(e);if(!n)throw new Error(`${J} is not supported`);return ci(n)}var at,lt,ct,ui,di,ut,de,Or,xr,ot,oi,J,ai,li,Z,yr,Cr,R,Ar,pi=O(()=>{"use strict";at=y(require("process"),1),lt=require("buffer"),ct=y(require("path"),1),ui=require("url"),di=require("util"),ut=y(require("child_process"),1),de=y(require("fs/promises"),1);Ut();Bt();si();Ke();Or={},xr=(0,di.promisify)(ut.default.execFile),ot=ct.default.dirname((0,ui.fileURLToPath)(Or.url)),oi=ct.default.join(ot,"xdg-open"),{platform:J,arch:ai}=at.default;li=async(n,e)=>{let t;for(let i of n)try{return await e(i)}catch(r){t=r}throw t},Z=async n=>{if(n={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...n},Array.isArray(n.app))return li(n.app,a=>Z({...n,app:a}));let{name:e,arguments:t=[]}=n.app??{};if(t=[...t],Array.isArray(e))return li(e,a=>Z({...n,app:{name:a,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let a={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},l={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},c=M?await wr():await st();if(c.id in a){let d=a[c.id];return e==="browserPrivate"&&t.push(l[d]),Z({...n,app:{name:R[d],arguments:t}})}throw new Error(`${c.name} is not supported as a default browser`)}let i,r=[],s={};if(J==="darwin")i="open",n.wait&&r.push("--wait-apps"),n.background&&r.push("--background"),n.newInstance&&r.push("--new"),e&&r.push("-a",e);else if(J==="win32"||M&&!B()&&!e){i=await Ze(),r.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),M||(s.windowsVerbatimArguments=!0);let a=["Start"];n.wait&&a.push("-Wait"),e?(a.push(`"\`"${e}\`""`),n.target&&t.push(n.target)):n.target&&a.push(`"${n.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),a.push("-ArgumentList",t.join(","))),n.target=lt.Buffer.from(a.join(" "),"utf16le").toString("base64")}else{if(e)i=e;else{let a=!ot||ot==="/",l=!1;try{await de.default.access(oi,de.constants.X_OK),l=!0}catch{}i=at.default.versions.electron??(J==="android"||a||!l)?"xdg-open":oi}t.length>0&&r.push(...t),n.wait||(s.stdio="ignore",s.detached=!0)}J==="darwin"&&t.length>0&&r.push("--args",...t),n.target&&r.push(n.target);let o=ut.default.spawn(i,r,s);return n.wait?new Promise((a,l)=>{o.once("error",l),o.once("close",c=>{if(!n.allowNonzeroExitCode&&c>0){l(new Error(`Exited with code ${c}`));return}a(o)})}):(o.unref(),o)},yr=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a `target`");return Z({...e,target:n})},Cr=(n,e)=>{if(typeof n!="string"&&!Array.isArray(n))throw new TypeError("Expected a valid `name`");let{arguments:t=[]}=e??{};if(t!=null&&!Array.isArray(t))throw new TypeError("Expected `appArguments` as Array type");return Z({...e,app:{name:n,arguments:t}})};R={};j(R,"chrome",()=>he({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));j(R,"brave",()=>he({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));j(R,"firefox",()=>he({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));j(R,"edge",()=>he({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));j(R,"browser",()=>"browser");j(R,"browserPrivate",()=>"browserPrivate");Ar=yr});var bt=y(St(),1),{program:Lr,createCommand:Mr,createArgument:jr,createOption:Rr,CommanderError:Vr,InvalidArgumentError:Wr,InvalidOptionArgumentError:Ur,Command:Et,Argument:Br,Option:qr,Help:Gr}=bt.default;var kt=!1,vt=!1;function Tt(n,e){kt=n,vt=e}function h(){return kt?!0:vt?!1:!process.stdout.isTTY}function x(n,e){console.log(JSON.stringify({ok:!0,command:n,data:e}))}function _(n,e,t){console.log(JSON.stringify({ok:!1,command:n,errors:[{code:e,message:t}]}))}function u(n){console.log(n)}function g(n){console.error(n)}function U(n,e=2){if(n.length===0)return"";let t=[];for(let i of n)for(let r=0;r<i.length;r++)t[r]=Math.max(t[r]||0,i[r].length);return n.map(i=>i.map((r,s)=>s<i.length-1?r.padEnd(t[s]+e):r).join("")).join(`
30
- `)}var ae=require("fs"),oe=require("path");E();v();var Ue=require("fs"),X=require("path"),se=require("os"),q=[{id:"claude-code",label:"Claude Code",envVars:["CLAUDE_CODE"],dir:".claude",skillsSubdir:"skills",platform:"claude_code"},{id:"cursor",label:"Cursor",envVars:["CURSOR","CURSOR_TRACE_ID"],dir:".cursor",skillsSubdir:"skills",platform:"custom"},{id:"codex",label:"Codex",envVars:["CODEX","CODEX_CI"],dir:".codex",skillsSubdir:"skills",platform:"codex"},{id:"opencode",label:"OpenCode",envVars:["OPENCODE"],dir:".opencode",skillsSubdir:"skills",platform:"custom"},{id:"gemini-cli",label:"Gemini CLI",envVars:["GEMINI_CLI"],dir:".gemini",skillsSubdir:"skills",platform:"gemini"},{id:"antigravity",label:"Antigravity",envVars:["GEMINI_CLI_IDE_WORKSPACE_PATH","GEMINI_CLI_IDE_PID"],dir:".gemini/antigravity",skillsSubdir:"skills",platform:"gemini"}];function D(n){if(n){let i=q.find(s=>s.id===n);if(i)return i;let r=q.find(s=>s.dir===`.${n}`||s.dir===n);return r||null}for(let i of q)if(i.envVars.some(r=>process.env[r]))return i;let e=(0,se.homedir)(),t=[];for(let i of q)(0,Ue.existsSync)((0,X.join)(e,i.dir))&&t.push(i);return t.length===1?t[0]:null}function Be(){let n=[],e=(0,se.homedir)();for(let t of q)(t.envVars.some(i=>process.env[i])||(0,Ue.existsSync)((0,X.join)(e,t.dir)))&&n.push(t);return n}function N(){let n=Be();return n.length>1?`Multiple AI agents detected (${n.map(e=>e.label).join(", ")}). Use --agent to specify: ${n.map(e=>e.id).join(", ")}`:`No AI agent detected. Use --agent to specify one (${q.map(e=>e.id).join(", ")})`}function L(n,e){return e?(0,X.join)(process.cwd(),n.dir,n.skillsSubdir):(0,X.join)((0,se.homedir)(),n.dir,n.skillsSubdir)}var Nt=`---
27
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function yt(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",r="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])?r=s[3]:i=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],i=s[3],r=s[4]),t&&r!=="0"?`${t}=${i}:${parseInt(r)+1}`:e})}function He(){if(m.env.NO_COLOR||m.env.FORCE_COLOR==="0"||m.env.FORCE_COLOR==="false")return!1;if(m.env.FORCE_COLOR||m.env.CLICOLOR_FORCE!==void 0)return!0}Fe.Command=Pe;Fe.useColor=He});var St=B(S=>{"use strict";var{Argument:At}=re(),{Command:De}=Ct(),{CommanderError:Qi,InvalidArgumentError:Ot}=X(),{Help:Zi}=Se(),{Option:bt}=Te();S.program=new De;S.createCommand=n=>new De(n);S.createOption=(n,e)=>new bt(n,e);S.createArgument=(n,e)=>new At(n,e);S.Command=De;S.Option=bt;S.Argument=At;S.Help=Zi;S.CommanderError=Qi;S.InvalidArgumentError=Ot;S.InvalidOptionArgumentError=Ot});var Dt={};we(Dt,{addToManifest:()=>N,clearAuth:()=>Ve,getAuth:()=>P,getConfig:()=>D,getManifest:()=>F,removeFromManifest:()=>We,saveAuth:()=>Re,saveConfig:()=>Ft,saveManifest:()=>je,updateConfig:()=>ir});function er(){(0,$.mkdirSync)(se,{recursive:!0})}function Le(n,e){try{return(0,$.existsSync)(n)?JSON.parse((0,$.readFileSync)(n,"utf-8")):e}catch{return e}}function Me(n,e,t=!1){if(er(),(0,$.writeFileSync)(n,JSON.stringify(e,null,2)+`
28
+ `,"utf-8"),t)try{(0,$.chmodSync)(n,384)}catch{}}function P(){return Le(Ne,null)}function Re(n){Me(Ne,n,!0)}function Ve(){try{(0,$.writeFileSync)(Ne,"{}","utf-8")}catch{}}function D(){return Le(Pt,tr)}function Ft(n){Me(Pt,n)}function ir(n){let e=D();Ft({...e,...n})}function F(){return Le(Ht,rr)}function je(n){Me(Ht,n)}function N(n){let e=F(),t=e.installations.findIndex(i=>i.resourceId===n.resourceId&&i.agent===n.agent);t>=0?e.installations[t]=n:e.installations.push(n),je(e)}function We(n,e){let t=F();t.installations=t.installations.filter(i=>!(i.resourceId===n&&(!e||i.agent===e))),je(t)}var $,Q,It,se,Ne,Pt,Ht,tr,rr,E=O(()=>{"use strict";$=require("fs"),Q=require("path"),It=require("os"),se=(0,Q.join)((0,It.homedir)(),".config","shared-context"),Ne=(0,Q.join)(se,"auth.json"),Pt=(0,Q.join)(se,"config.json"),Ht=(0,Q.join)(se,"manifest.json");tr={apiBase:"https://sharedcontext.ai"};rr={installations:[]}});var Nt={};we(Nt,{del:()=>Ue,get:()=>A,isAuthenticated:()=>y,patch:()=>or,post:()=>k});function nr(){return D().apiBase||"https://sharedcontext.ai"}function sr(){let n={"Content-Type":"application/json"},e=P();return e?.token&&(n.Authorization=`Bearer ${e.token}`),n}function y(){return!!P()?.token}async function oe(n,e,t){let i=`${nr()}${e}`;try{let r=await fetch(i,{method:n,headers:sr(),body:t?JSON.stringify(t):void 0}),s=r.headers.get("content-type")||"";if(!s.includes("application/json"))return r.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${s||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${r.status}`,message:r.statusText}};let o=await r.json();return r.ok?{ok:!0,data:o.data??o}:{ok:!1,error:{code:o?.error?.code||`HTTP_${r.status}`,message:o?.error?.message||o?.message||r.statusText}}}catch(r){return{ok:!1,error:{code:"NETWORK_ERROR",message:r instanceof Error?r.message:"Network request failed"}}}}function A(n){return oe("GET",n)}function k(n,e){return oe("POST",n,e)}function or(n,e){return oe("PATCH",n,e)}function Ue(n,e){return oe("DELETE",n,e)}var v=O(()=>{"use strict";E()});function lr(){try{return Je.default.statSync("/.dockerenv"),!0}catch{return!1}}function cr(){try{return Je.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Ye(){return Ge===void 0&&(Ge=lr()||cr()),Ge}var Je,Ge,Vt=O(()=>{"use strict";Je=C(require("fs"),1)});function G(){return Ke===void 0&&(Ke=ur()||Ye()),Ke}var jt,Ke,ur,ze=O(()=>{"use strict";jt=C(require("fs"),1);Vt();ur=()=>{try{return jt.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var Xe,Ut,ue,Wt,V,Qe=O(()=>{"use strict";Xe=C(require("process"),1),Ut=C(require("os"),1),ue=C(require("fs"),1);ze();Wt=()=>{if(Xe.default.platform!=="linux")return!1;if(Ut.default.release().toLowerCase().includes("microsoft"))return!G();try{if(ue.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!G()}catch{}return ue.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||ue.default.existsSync("/run/WSL")?!G():!1},V=Xe.default.env.__IS_WSL_TEST__?Wt:Wt()});var Ze,ee,hr,dr,et,Bt=O(()=>{"use strict";Ze=C(require("process"),1),ee=C(require("fs/promises"),1);Qe();Qe();hr=(()=>{let n="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await ee.default.access(t,ee.constants.F_OK),i=!0}catch{}if(!i)return n;let r=await ee.default.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(r);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):n}})(),dr=async()=>`${await hr()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,et=async()=>V?dr():`${Ze.default.env.SYSTEMROOT||Ze.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function j(n,e,t){let i=r=>Object.defineProperty(n,e,{value:r,enumerable:!0,writable:!0});return Object.defineProperty(n,e,{configurable:!0,enumerable:!0,get(){let r=t();return i(r),r},set(r){i(r)}}),n}var qt=O(()=>{"use strict"});async function tt(){if(Jt.default.platform!=="darwin")throw new Error("macOS only");let{stdout:n}=await pr("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(n)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var Gt,Jt,Yt,pr,Kt=O(()=>{"use strict";Gt=require("util"),Jt=C(require("process"),1),Yt=require("child_process"),pr=(0,Gt.promisify)(Yt.execFile)});async function Qt(n,{humanReadableOutput:e=!0,signal:t}={}){if(zt.default.platform!=="darwin")throw new Error("macOS only");let i=e?[]:["-ss"],r={};t&&(r.signal=t);let{stdout:s}=await mr("osascript",["-e",n,i],r);return s.trim()}var zt,Xt,it,mr,Zt=O(()=>{"use strict";zt=C(require("process"),1),Xt=require("util"),it=require("child_process"),mr=(0,Xt.promisify)(it.execFile)});async function rt(n){return Qt(`tell application "Finder" to set app_path to application file id "${n}" as string
29
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var ei=O(()=>{"use strict";Zt()});async function st(n=fr){let{stdout:e}=await n("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new nt(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:i}=t.groups,r=i.lastIndexOf("."),s=i.lastIndexOf("-"),o=r===-1?void 0:i.slice(0,r),l=s===-1?void 0:i.slice(0,s);return he[i]??he[o]??he[l]??{name:i,id:i}}var ti,ii,fr,he,wn,nt,ri=O(()=>{"use strict";ti=require("util"),ii=require("child_process"),fr=(0,ti.promisify)(ii.execFile),he={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},wn=new Map(Object.entries(he)),nt=class extends Error{}});async function ot(){if(de.default.platform==="darwin"){let n=await tt();return{name:await rt(n),id:n}}if(de.default.platform==="linux"){let{stdout:n}=await gr("xdg-mime",["query","default","x-scheme-handler/http"]),e=n.trim();return{name:_r(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(de.default.platform==="win32")return st();throw new Error("Only macOS, Linux, and Windows are supported")}var ni,de,si,gr,_r,oi=O(()=>{"use strict";ni=require("util"),de=C(require("process"),1),si=require("child_process");Kt();ei();ri();gr=(0,ni.promisify)(si.execFile),_r=n=>n.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var pi={};we(pi,{apps:()=>W,default:()=>Ar,openApp:()=>Cr});async function xr(){let n=await et(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=ct.Buffer.from(e,"utf16le").toString("base64"),{stdout:i}=await wr(n,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),r=i.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[r]?{id:s[r]}:{}}function ui(n){if(typeof n=="string"||Array.isArray(n))return n;let{[li]:e}=n;if(!e)throw new Error(`${li} is not supported`);return e}function me({[K]:n},{wsl:e}){if(e&&V)return ui(e);if(!n)throw new Error(`${K} is not supported`);return ui(n)}var lt,ct,ut,hi,di,ht,pe,Or,wr,at,ai,K,li,ci,te,yr,Cr,W,Ar,mi=O(()=>{"use strict";lt=C(require("process"),1),ct=require("buffer"),ut=C(require("path"),1),hi=require("url"),di=require("util"),ht=C(require("child_process"),1),pe=C(require("fs/promises"),1);Bt();qt();oi();ze();Or={},wr=(0,di.promisify)(ht.default.execFile),at=ut.default.dirname((0,hi.fileURLToPath)(Or.url)),ai=ut.default.join(at,"xdg-open"),{platform:K,arch:li}=lt.default;ci=async(n,e)=>{let t;for(let i of n)try{return await e(i)}catch(r){t=r}throw t},te=async n=>{if(n={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...n},Array.isArray(n.app))return ci(n.app,l=>te({...n,app:l}));let{name:e,arguments:t=[]}=n.app??{};if(t=[...t],Array.isArray(e))return ci(e,l=>te({...n,app:{name:l,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let l={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},a={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},c=V?await xr():await ot();if(c.id in l){let h=l[c.id];return e==="browserPrivate"&&t.push(a[h]),te({...n,app:{name:W[h],arguments:t}})}throw new Error(`${c.name} is not supported as a default browser`)}let i,r=[],s={};if(K==="darwin")i="open",n.wait&&r.push("--wait-apps"),n.background&&r.push("--background"),n.newInstance&&r.push("--new"),e&&r.push("-a",e);else if(K==="win32"||V&&!G()&&!e){i=await et(),r.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),V||(s.windowsVerbatimArguments=!0);let l=["Start"];n.wait&&l.push("-Wait"),e?(l.push(`"\`"${e}\`""`),n.target&&t.push(n.target)):n.target&&l.push(`"${n.target}"`),t.length>0&&(t=t.map(a=>`"\`"${a}\`""`),l.push("-ArgumentList",t.join(","))),n.target=ct.Buffer.from(l.join(" "),"utf16le").toString("base64")}else{if(e)i=e;else{let l=!at||at==="/",a=!1;try{await pe.default.access(ai,pe.constants.X_OK),a=!0}catch{}i=lt.default.versions.electron??(K==="android"||l||!a)?"xdg-open":ai}t.length>0&&r.push(...t),n.wait||(s.stdio="ignore",s.detached=!0)}K==="darwin"&&t.length>0&&r.push("--args",...t),n.target&&r.push(n.target);let o=ht.default.spawn(i,r,s);return n.wait?new Promise((l,a)=>{o.once("error",a),o.once("close",c=>{if(!n.allowNonzeroExitCode&&c>0){a(new Error(`Exited with code ${c}`));return}l(o)})}):(o.unref(),o)},yr=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a `target`");return te({...e,target:n})},Cr=(n,e)=>{if(typeof n!="string"&&!Array.isArray(n))throw new TypeError("Expected a valid `name`");let{arguments:t=[]}=e??{};if(t!=null&&!Array.isArray(t))throw new TypeError("Expected `appArguments` as Array type");return te({...e,app:{name:n,arguments:t}})};W={};j(W,"chrome",()=>me({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));j(W,"brave",()=>me({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));j(W,"firefox",()=>me({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));j(W,"edge",()=>me({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));j(W,"browser",()=>"browser");j(W,"browserPrivate",()=>"browserPrivate");Ar=yr});var Et=C(St(),1),{program:Lr,createCommand:Mr,createArgument:Rr,createOption:Vr,CommanderError:jr,InvalidArgumentError:Wr,InvalidOptionArgumentError:Ur,Command:kt,Argument:Br,Option:qr,Help:Gr}=Et.default;var vt=!1,Tt=!1;function $t(n,e){vt=n,Tt=e}function d(){return vt?!0:Tt?!1:!process.stdout.isTTY}function w(n,e){console.log(JSON.stringify({ok:!0,command:n,data:e}))}function g(n,e,t){console.log(JSON.stringify({ok:!1,command:n,errors:[{code:e,message:t}]}))}function u(n){console.log(n)}function f(n){console.error(n)}function q(n,e=2){if(n.length===0)return"";let t=[];for(let i of n)for(let r=0;r<i.length;r++)t[r]=Math.max(t[r]||0,i[r].length);return n.map(i=>i.map((r,s)=>s<i.length-1?r.padEnd(t[s]+e):r).join("")).join(`
30
+ `)}var ce=require("fs"),le=require("path");E();v();var Be=require("fs"),Z=require("path"),ae=require("os"),J=[{id:"claude-code",label:"Claude Code",envVars:["CLAUDE_CODE"],dir:".claude",skillsSubdir:"skills",platform:"claude_code"},{id:"cursor",label:"Cursor",envVars:["CURSOR","CURSOR_TRACE_ID"],dir:".cursor",skillsSubdir:"skills",platform:"custom"},{id:"codex",label:"Codex",envVars:["CODEX","CODEX_CI"],dir:".codex",skillsSubdir:"skills",platform:"codex"},{id:"opencode",label:"OpenCode",envVars:["OPENCODE"],dir:".opencode",skillsSubdir:"skills",platform:"custom"},{id:"gemini-cli",label:"Gemini CLI",envVars:["GEMINI_CLI"],dir:".gemini",skillsSubdir:"skills",platform:"gemini"},{id:"antigravity",label:"Antigravity",envVars:["GEMINI_CLI_IDE_WORKSPACE_PATH","GEMINI_CLI_IDE_PID"],dir:".gemini/antigravity",skillsSubdir:"skills",platform:"gemini"}];function L(n){if(n){let i=J.find(s=>s.id===n);if(i)return i;let r=J.find(s=>s.dir===`.${n}`||s.dir===n);return r||null}for(let i of J)if(i.envVars.some(r=>process.env[r]))return i;let e=(0,ae.homedir)(),t=[];for(let i of J)(0,Be.existsSync)((0,Z.join)(e,i.dir))&&t.push(i);return t.length===1?t[0]:null}function qe(){let n=[],e=(0,ae.homedir)();for(let t of J)(t.envVars.some(i=>process.env[i])||(0,Be.existsSync)((0,Z.join)(e,t.dir)))&&n.push(t);return n}function M(){let n=qe();return n.length>1?`Multiple AI agents detected (${n.map(e=>e.label).join(", ")}). Use --agent to specify: ${n.map(e=>e.id).join(", ")}`:`No AI agent detected. Use --agent to specify one (${J.map(e=>e.id).join(", ")})`}function R(n,e){return e?(0,Z.join)(process.cwd(),n.dir,n.skillsSubdir):(0,Z.join)((0,ae.homedir)(),n.dir,n.skillsSubdir)}var Lt=`---
31
31
  title: Skill Manager
32
32
  description: Browse, install, and manage AI skills from the Shared Context library
33
33
  ---
@@ -149,13 +149,13 @@ npx shared-context-ai status # Auth status, detected agents, install
149
149
  \`\`\`
150
150
 
151
151
  **Error codes:** \`NOT_FOUND\`, \`AUTH_MISSING\`, \`NO_AGENTS\`, \`SKILL_NOT_FOUND\`, \`WRITE_FAILED\`, \`API_ERROR\`, \`UNEXPECTED\`
152
- `;var G="skill-manager",Lt="Skill Manager";function ar(n,e){let t=L(n,e),i=(0,oe.join)(t,G);return(0,ae.mkdirSync)(i,{recursive:!0}),(0,ae.writeFileSync)((0,oe.join)(i,"SKILL.md"),Nt,"utf-8"),(0,oe.join)(i,"SKILL.md")}function Mt(n){n.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").option("--agent <agent>","Agent to configure (claude-code, cursor, codex, opencode, gemini-cli, antigravity)").option("--project","Install to project directory instead of global").action(async e=>{if(e.code){let{post:s}=await Promise.resolve().then(()=>(v(),Dt)),{saveAuth:o}=await Promise.resolve().then(()=>(E(),Ft)),a=await s("/api/cli/auth",{code:e.code});a.ok||(h()?_("init",a.error.code,a.error.message):g(`Auth failed: ${a.error.message}`),process.exit(1)),o({token:a.data.token,email:a.data.user.email,orgId:a.data.org.id,orgSlug:a.data.org.slug,orgName:a.data.org.name,createdAt:new Date().toISOString()}),h()||u(`Authenticated as ${a.data.user.email}`)}else w()||(h()?(_("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(g("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let t=D(e.agent);if(!t){let s=N();h()?_("init","NO_AGENTS",s):g(s),process.exit(1)}let i=$();if(i?.token){let s=(await import("os")).hostname(),o=await k("/api/cli/register-agent",{platform:t.platform,name:`CLI (${s})`});!o.ok&&!h()&&g(`Warning: Could not register agent connection: ${o.error.message}`)}let r=ar(t,!!e.project);if(F({resourceId:"skill-manager",slug:G,installPath:`skills/${G}`,title:Lt,sha:"",scope:e.project?"project":"global",agent:t.id,installedAt:new Date().toISOString()}),i?.token)try{let s=`skills/shared-context/${G}`,o=await C(`/api/cli/resource/${s}`);if(o.ok&&o.data.resource){let a=o.data.resource;a.latestSha&&await k("/api/cli/install",{resourceId:a.id,agentPlatform:t.platform,installedSha:a.latestSha}),F({resourceId:a.id,slug:a.slug||G,installPath:`skills/shared-context/${a.slug||G}`,title:a.title||Lt,sha:a.latestSha||"",scope:e.project?"project":"global",agent:t.id,installedAt:new Date().toISOString()})}}catch{}h()?x("init",{agent:t.id,skillManagerPath:r,authenticated:w()}):(u(""),u(`Shared Context initialized for ${t.label}`),u(`Skill Manager installed to: ${r}`),u(""),u("Quick reference:"),u(' shared-context-ai search "query" Search for skills'),u(" shared-context-ai install <installPath> Install a skill"),u(" shared-context-ai list List installed skills"),u(" shared-context-ai check Check for updates"),u(" shared-context-ai preview <installPath> Preview before installing"))})}var mi=require("http"),fi=require("crypto");E();v();E();async function gi(n){let e=await k("/api/cli/auth",{code:n});return e.ok?(Me({token:e.data.token,email:e.data.user.email,orgId:e.data.org.id,orgSlug:e.data.org.slug,orgName:e.data.org.name,createdAt:new Date().toISOString()}),h()?x("login",{email:e.data.user.email,org:e.data.org.slug}):u(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(h()?_("login",e.error.code,e.error.message):g(`Login failed: ${e.error.message}`),!1)}async function Sr(){let n=(0,fi.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,mi.createServer)((i,r)=>{let s=new URL(i.url||"/","http://localhost"),o=s.searchParams.get("code"),a=s.searchParams.get("state");if(!o||a!==n){r.writeHead(400,{"Content-Type":"text/html"}),r.end("<h1>Authentication failed</h1><p>Invalid state. Please try again.</p>"),t.close(),e(!1);return}r.writeHead(200,{"Content-Type":"text/html"}),r.end("<h1>Authentication successful!</h1><p>You can close this tab and return to your terminal.</p>"),t.close(),gi(o).then(e)});t.listen(0,"127.0.0.1",async()=>{let i=t.address();if(!i||typeof i=="string"){t.close(),e(!1);return}let r=i.port,o=`${H().apiBase||"https://sharedcontext.ai"}/cli/login?port=${r}&state=${n}`;h()||(u("Opening browser for authentication..."),u(`If the browser doesn't open, visit: ${o}`));try{let a=(await Promise.resolve().then(()=>(pi(),hi))).default;await a(o)}catch{h()||u(`Could not open browser. Please visit:
153
- ${o}`)}setTimeout(()=>{t.close(),h()||g("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function _i(n){n.command("login").description("Authenticate with Shared Context").option("--code <code>","Use an auth code directly (skip browser)").action(async e=>{let t;e.code?t=await gi(e.code):t=await Sr(),process.exit(t?0:1)})}v();var br={skill:"skills",file:"files"};function xi(n){let e=br[n.resourceType]||n.resourceType+"s";return n.orgSlug?`${e}/${n.orgSlug}/${n.slug}`:`${e}/${n.slug}`}function wi(n){n.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, file)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let i=new URLSearchParams({q:e});t.type&&i.set("type",t.type),t.tag&&i.set("tag",t.tag),t.limit&&i.set("limit",t.limit);let r=w()?`/api/cli/search?${i}`:`/api/public/search?${i}`,s=await C(r);s.ok||(h()?_("search",s.error.code,s.error.message):u(`Search failed: ${s.error.message}`),process.exit(1));let o=s.data.results;if(h()){let l=o.map(c=>{let d=xi(c);return{installPath:d,installCommand:`npx shared-context-ai install ${d}`,title:c.title,description:c.description,resourceType:c.resourceType,installCount:c.installCount,topicTags:c.topicTags}});x("search",{results:l,count:l.length});return}if(o.length===0){let l=t.type?`${t.type}s`:"results";u(`No ${l} found.`);return}u(`Found ${o.length} result${o.length===1?"":"s"}:
154
- `);let a=o.map(l=>[xi(l),l.title,`\u2193${l.installCount}`]);u(U(a)),u(`
155
- Install a skill: npx shared-context-ai install <installPath>`)})}var pe=require("fs"),V=require("path");v();E();var Er={skill:"skills",file:"files"};function dt(n,e){let t=(0,V.resolve)(n);for(let i of e){let r=(0,V.resolve)((0,V.join)(n,i.path));if(!r.startsWith(t+"/")&&r!==t)throw new Error(`Invalid file path: ${i.path}`);(0,pe.mkdirSync)((0,V.dirname)(r),{recursive:!0}),(0,pe.writeFileSync)(r,i.content,"utf-8")}}function kr(n){let e=n.resource.slug||n.resource.id,t=Er[n.resource.resourceType]||n.resource.resourceType+"s";return n.resource.orgSlug?`${t}/${n.resource.orgSlug}/${e}`:`${t}/${e}`}function vr(n){let e=n.resource.slug||n.resource.id;return n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}function yi(n){n.command("install <path>").description("Install a skill (e.g., skills/acme/api-testing)").option("--project","Install to project directory instead of global").option("--agent <agent>","Override agent detection").action(async(e,t)=>{let i=D(t.agent);if(!i){let A=N();h()?_("install","NO_AGENTS",A):g(A),process.exit(1)}let r=w(),o=await C(`${r?"/api/cli/resource":"/api/public/resource"}/${e}`);o.ok||(h()?_("install",o.error.code,o.error.message):g(`Install failed: ${o.error.message}`),process.exit(1));let a=o.data,l=a.resource.slug||a.resource.id,c=kr(a),d=L(i,!!t.project),p=(0,V.join)(d,...vr(a));try{dt(p,a.files)}catch(A){h()?_("install","WRITE_FAILED",`Failed to write files: ${A}`):g(`Failed to write files: ${A}`),process.exit(1)}let m;if(r&&a.resource.latestSha){let A=await k("/api/cli/install",{resourceId:a.resource.id,agentPlatform:i.platform,installedSha:a.resource.latestSha});A.ok||(m=`Could not record install on server: ${A.error.message}`,h()||g(`Warning: ${m}`))}F({resourceId:a.resource.id,slug:l,installPath:c,title:a.resource.title,sha:a.resource.latestSha||"",scope:t.project?"project":"global",agent:i.id,installedAt:new Date().toISOString()}),h()?x("install",{installPath:c,title:a.resource.title,path:p,files:a.files.length,...m&&{warning:m}}):(u(`Installed "${a.resource.title}" to ${p}`),u(` ${a.files.length} file${a.files.length===1?"":"s"} written`),r||(u(""),u("Tip: Sign up at sharedcontext.ai to track installations and get updates.")))})}v();E();function Ci(n){let e=n.slug||n.resourceId;return n.orgSlug?`skills/${n.orgSlug}/${e}`:`skills/${e}`}function Ai(n){n.command("list").description("List installed skills").alias("ls").action(async()=>{if(w()){let e=await C("/api/cli/installed");e.ok||(h()?_("list",e.error.code,e.error.message):u(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(h()){let r=t.map(s=>({...s,installPath:Ci(s)}));x("list",{installations:r,count:r.length});return}if(t.length===0){u("No skills installed."),u("Use 'shared-context-ai search' to find skills to install.");return}u(`${t.length} skill${t.length===1?"":"s"} installed:
156
- `);let i=t.map(r=>[Ci(r),r.title,r.hasUpdate?"(update available)":"(current)"]);u(U(i))}else{let t=P().installations;if(h()){x("list",{installations:t,count:t.length});return}if(t.length===0){u("No skills installed locally.");return}u(`${t.length} skill${t.length===1?"":"s"} installed locally:
157
- `);let i=t.map(r=>[r.installPath||r.slug,r.title,`(${r.agent})`]);u(U(i)),u(`
158
- Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}v();function Oi(n){n.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let i=w()?"/api/cli/resource":"/api/public/resource",r=await C(`${i}/${e}/preview`);r.ok||(h()?_("preview",r.error.code,r.error.message):g(`Preview failed: ${r.error.message}`),process.exit(1)),h()?x("preview",r.data):u(r.data.content)})}v();function Si(n){n.command("check").description("Check for skill updates").action(async()=>{w()||(h()?_("check","AUTH_MISSING","Login required to check for updates."):g("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await C("/api/cli/updates");e.ok||(h()?_("check",e.error.code,e.error.message):g(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:i}=e.data;if(h()){x("check",{updates:t,count:i});return}if(i===0){u("All skills are up to date.");return}u(`${i} update${i===1?"":"s"} available:
159
- `);let r=t.map(s=>{let o=s.slug||s.resourceId;return[s.orgSlug?`skills/${s.orgSlug}/${o}`:`skills/${o}`,s.title,`${s.installedSha.slice(0,7)} \u2192 ${s.latestSha.slice(0,7)}`]});u(U(r)),u(`
160
- Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var Ei=require("path");v();E();function bi(n){let e=n.slug||n.resourceId;return n.orgSlug?`skills/${n.orgSlug}/${e}`:`skills/${e}`}function ki(n){n.command("update [path]").description("Update installed skills (all or by install path)").option("--project","Update in project directory").option("--agent <agent>","Override agent detection").action(async(e,t)=>{w()||(h()?_("update","AUTH_MISSING","Login required to update skills."):g("Login required to update skills. Run 'shared-context-ai login'."),process.exit(1));let i=D(t.agent);if(!i){let a=N();h()?_("update","NO_AGENTS",a):g(a),process.exit(1)}let r=await C("/api/cli/updates");r.ok||(h()?_("update",r.error.code,r.error.message):g(`Failed to check updates: ${r.error.message}`),process.exit(1));let s=r.data.updates;if(e&&(s=s.filter(a=>bi(a)===e||a.slug===e||a.resourceId===e),s.length===0)){h()?_("update","SKILL_NOT_FOUND",`No update available for "${e}".`):u(`No update available for "${e}".`);return}if(s.length===0){h()?x("update",{updated:[],count:0}):u("All skills are up to date.");return}let o=[];for(let a of s){let l=a.slug||a.resourceId,c=a.orgSlug?`skills/${a.orgSlug}/${l}`:`skills/${l}`,d=bi(a),p=await C(`/api/cli/resource/${c}`);if(!p.ok){h()||g(` Failed to fetch ${d}: ${p.error.message}`);continue}let m=p.data,A=L(i,!!t.project),fe=a.orgSlug?[a.orgSlug,l]:[l],Pi=(0,Ei.join)(A,...fe);dt(Pi,m.files),m.resource.latestSha&&await k("/api/cli/update",{resourceId:m.resource.id,installedSha:m.resource.latestSha}),F({resourceId:m.resource.id,slug:l,installPath:d,title:m.resource.title,sha:m.resource.latestSha||"",scope:t.project?"project":"global",agent:i.id,installedAt:new Date().toISOString()}),o.push({installPath:d,title:m.resource.title}),h()||u(` Updated ${d}`)}h()?x("update",{updated:o,count:o.length}):o.length>0&&u(`
161
- ${o.length} skill${o.length===1?"":"s"} updated.`)})}var Y=require("fs"),ht=require("path");v();E();function vi(n){n.command("uninstall <path>").description("Uninstall a skill by install path (e.g., skills/acme/api-testing)").option("--project","Uninstall from project directory").option("--agent <agent>","Override agent detection").action(async(e,t)=>{let i=D(t.agent);if(!i){let m=N();h()?_("uninstall","NO_AGENTS",m):g(m),process.exit(1)}let s=P().installations.find(m=>m.installPath===e||m.slug===e||m.resourceId===e),o=L(i,!!t.project),a=e.split("/"),c=["skills","files"].includes(a[0])?a.slice(1):a,d=(0,ht.join)(o,...c),p=(0,Y.existsSync)(d);if(p&&(0,Y.rmSync)(d,{recursive:!0,force:!0}),!p&&s?.slug){let m=(0,ht.join)(o,s.slug);(0,Y.existsSync)(m)&&(0,Y.rmSync)(m,{recursive:!0,force:!0})}if(w()&&s){let m=await k("/api/cli/uninstall",{resourceId:s.resourceId});!m.ok&&!h()&&g(`Warning: Could not record uninstall on server: ${m.error.message}`)}s&&Ve(s.resourceId,i.id),h()?x("uninstall",{path:e,removed:!0}):u(`Uninstalled "${e}"`)})}E();function Ti(n){n.command("status").description("Show CLI status: auth, agents, installed skill counts").action(async()=>{let e=$(),t=H(),i=P(),r=Be(),s={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:r.map(o=>o.id),installedCount:i.installations.length};if(h()){x("status",s);return}u("Shared Context CLI Status"),u("\u2500".repeat(30)),e?.token?u(` Auth: ${e.email} (${e.orgSlug})`):u(" Auth: Not logged in"),u(` API: ${t.apiBase}`),r.length>0?u(` Agents: ${r.map(o=>o.label).join(", ")}`):u(" Agents: None detected"),u(` Skills: ${i.installations.length} installed`)})}E();v();function $i(n){n.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=$();e.revoke&&w()&&await We("/api/cli/auth"),je(),h()?x("logout",{email:t?.email||null}):u("Logged out.")})}var Ii={AUTH_MISSING:"Run 'shared-context-ai login' to authenticate.",AUTH_EXPIRED:"Run 'shared-context-ai login' to re-authenticate.",SKILL_NOT_FOUND:"Check the skill slug and try again.",ALREADY_INSTALLED:"Use 'shared-context-ai update <slug>' to update instead.",NO_AGENTS:"No AI coding agents detected. Run 'shared-context-ai init --agent <name>' to set up manually.",API_ERROR:"The server returned an error. Try again later.",WRITE_FAILED:"Could not write files to disk. Check permissions."},me=class extends Error{constructor(t,i){super(i||Ii[t]);this.code=t;this.name="CliError"}get recovery(){return Ii[this.code]}};var S=new Et;S.name("shared-context-ai").description("CLI for Shared Context - search, install, and manage AI skills").version("0.1.0").option("--json","Output as JSON (default when piped)").option("--human","Output as human-readable text (default in TTY)").option("--agent <name>","Override agent detection").option("--project","Use project-local directory instead of global").hook("preAction",n=>{let e=n.opts();Tt(!!e.json,!!e.human)});Mt(S);_i(S);wi(S);yi(S);Ai(S);Oi(S);Si(S);ki(S);vi(S);Ti(S);$i(S);process.on("uncaughtException",n=>{n instanceof me?h()?_(process.argv[2]||"unknown",n.code,n.message):(g(`Error: ${n.message}`),g(n.recovery)):h()?_(process.argv[2]||"unknown","UNEXPECTED",n.message||"Unexpected error"):g(`Error: ${n.message||n}`),process.exit(1)});S.parse();
152
+ `;var Y="skill-manager",Mt="Skill Manager";function ar(n,e){let t=R(n,e),i=(0,le.join)(t,Y);return(0,ce.mkdirSync)(i,{recursive:!0}),(0,ce.writeFileSync)((0,le.join)(i,"SKILL.md"),Lt,"utf-8"),(0,le.join)(i,"SKILL.md")}function Rt(n){n.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").action(async(e,t)=>{let i={...e,...t.optsWithGlobals()};if(i.code){let{post:l}=await Promise.resolve().then(()=>(v(),Nt)),{saveAuth:a}=await Promise.resolve().then(()=>(E(),Dt)),c=await l("/api/cli/auth",{code:i.code});c.ok||(d()?g("init",c.error.code,c.error.message):f(`Auth failed: ${c.error.message}`),process.exit(1)),a({token:c.data.token,email:c.data.user.email,orgId:c.data.org.id,orgSlug:c.data.org.slug,orgName:c.data.org.name,createdAt:new Date().toISOString()}),d()||u(`Authenticated as ${c.data.user.email}`)}else y()||(d()?(g("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(f("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let r=L(i.agent);if(!r){let l=M();d()?g("init","NO_AGENTS",l):f(l),process.exit(1)}let s=P();if(s?.token){let l=(await import("os")).hostname(),a=await k("/api/cli/register-agent",{platform:r.platform,name:`CLI (${l})`});!a.ok&&!d()&&f(`Warning: Could not register agent connection: ${a.error.message}`)}let o=ar(r,!!i.project);if(N({resourceId:"skill-manager",slug:Y,installPath:`skills/${Y}`,title:Mt,sha:"",scope:i.project?"project":"global",agent:r.id,installedAt:new Date().toISOString()}),s?.token)try{let l=`skills/shared-context/${Y}`,a=await A(`/api/cli/resource/${l}`);if(a.ok&&a.data.resource){let c=a.data.resource;c.latestSha&&await k("/api/cli/install",{resourceId:c.id,agentPlatform:r.platform,installedSha:c.latestSha}),N({resourceId:c.id,slug:c.slug||Y,installPath:`skills/shared-context/${c.slug||Y}`,title:c.title||Mt,sha:c.latestSha||"",scope:i.project?"project":"global",agent:r.id,installedAt:new Date().toISOString()})}}catch{}d()?w("init",{agent:r.id,skillManagerPath:o,authenticated:y()}):(u(""),u(`Shared Context initialized for ${r.label}`),u(`Skill Manager installed to: ${o}`),u(""),u("Quick reference:"),u(' shared-context-ai search "query" Search for skills'),u(" shared-context-ai install <installPath> Install a skill"),u(" shared-context-ai list List installed skills"),u(" shared-context-ai check Check for updates"),u(" shared-context-ai preview <installPath> Preview before installing"))})}var fi=require("http"),gi=require("crypto");E();v();E();async function _i(n){let e=await k("/api/cli/auth",{code:n});return e.ok?(Re({token:e.data.token,email:e.data.user.email,orgId:e.data.org.id,orgSlug:e.data.org.slug,orgName:e.data.org.name,createdAt:new Date().toISOString()}),d()?w("login",{email:e.data.user.email,org:e.data.org.slug}):u(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(d()?g("login",e.error.code,e.error.message):f(`Login failed: ${e.error.message}`),!1)}async function br(){let n=(0,gi.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,fi.createServer)((i,r)=>{let s=new URL(i.url||"/","http://localhost"),o=s.searchParams.get("code"),l=s.searchParams.get("state");if(!o||l!==n){r.writeHead(400,{"Content-Type":"text/html"}),r.end("<h1>Authentication failed</h1><p>Invalid state. Please try again.</p>"),t.close(),e(!1);return}r.writeHead(200,{"Content-Type":"text/html"}),r.end("<h1>Authentication successful!</h1><p>You can close this tab and return to your terminal.</p>"),t.close(),_i(o).then(e)});t.listen(0,"127.0.0.1",async()=>{let i=t.address();if(!i||typeof i=="string"){t.close(),e(!1);return}let r=i.port,o=`${D().apiBase||"https://sharedcontext.ai"}/cli/login?port=${r}&state=${n}`;d()||(u("Opening browser for authentication..."),u(`If the browser doesn't open, visit: ${o}`));try{let l=(await Promise.resolve().then(()=>(mi(),pi))).default;await l(o)}catch{d()||u(`Could not open browser. Please visit:
153
+ ${o}`)}setTimeout(()=>{t.close(),d()||f("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function wi(n){n.command("login").description("Authenticate with Shared Context").option("--code <code>","Use an auth code directly (skip browser)").action(async e=>{let t;e.code?t=await _i(e.code):t=await br(),process.exit(t?0:1)})}v();var Sr={skill:"skills",file:"files"};function xi(n){let e=Sr[n.resourceType]||n.resourceType+"s";return n.storageType==="github"&&n.githubOwner?`${e}/external/${n.githubOwner}/${n.slug}`:n.orgSlug?`${e}/${n.orgSlug}/${n.slug}`:`${e}/${n.slug}`}function yi(n){n.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, file)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let i=new URLSearchParams({q:e});t.type&&i.set("type",t.type),t.tag&&i.set("tag",t.tag),t.limit&&i.set("limit",t.limit);let r=y()?`/api/cli/search?${i}`:`/api/public/search?${i}`,s=await A(r);s.ok||(d()?g("search",s.error.code,s.error.message):u(`Search failed: ${s.error.message}`),process.exit(1));let o=s.data.results;if(d()){let a=o.map(c=>{let h=xi(c);return{installPath:h,installCommand:`npx shared-context-ai install ${h}`,title:c.title,description:c.description,resourceType:c.resourceType,installCount:c.installCount,topicTags:c.topicTags}});w("search",{results:a,count:a.length});return}if(o.length===0){let a=t.type?`${t.type}s`:"results";u(`No ${a} found.`);return}u(`Found ${o.length} result${o.length===1?"":"s"}:
154
+ `);let l=o.map(a=>[xi(a),a.title,`\u2193${a.installCount}`]);u(q(l)),u(`
155
+ Install a skill: npx shared-context-ai install <installPath>`)})}var fe=require("fs"),U=require("path");v();E();var Er={skill:"skills",file:"files"};function dt(n,e){let t=(0,U.resolve)(n);for(let i of e){let r=(0,U.resolve)((0,U.join)(n,i.path));if(!r.startsWith(t+"/")&&r!==t)throw new Error(`Invalid file path: ${i.path}`);(0,fe.mkdirSync)((0,U.dirname)(r),{recursive:!0}),(0,fe.writeFileSync)(r,i.content,"utf-8")}}function kr(n){let e=n.resource.slug||n.resource.id,t=Er[n.resource.resourceType]||n.resource.resourceType+"s";return n.resource.storageType==="github"&&n.resource.githubOwner?`${t}/external/${n.resource.githubOwner}/${e}`:n.resource.orgSlug?`${t}/${n.resource.orgSlug}/${e}`:`${t}/${e}`}function vr(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}function Ci(n){n.command("install <path>").description("Install a skill (e.g., skills/acme/api-testing)").action(async(e,t,i)=>{let r=i.optsWithGlobals(),s=L(r.agent);if(!s){let I=M();d()?g("install","NO_AGENTS",I):f(I),process.exit(1)}let o=y(),a=await A(`${o?"/api/cli/resource":"/api/public/resource"}/${e}`);a.ok||(d()?g("install",a.error.code,a.error.message):f(`Install failed: ${a.error.message}`),process.exit(1));let c=a.data,h=c.resource.slug||c.resource.id,p=kr(c),_=R(s,!!r.project),T=(0,U.join)(_,...vr(c));try{dt(T,c.files)}catch(I){d()?g("install","WRITE_FAILED",`Failed to write files: ${I}`):f(`Failed to write files: ${I}`),process.exit(1)}let x;if(o&&c.resource.latestSha){let I=await k("/api/cli/install",{resourceId:c.resource.id,agentPlatform:s.platform,installedSha:c.resource.latestSha});I.ok||(x=`Could not record install on server: ${I.error.message}`,d()||f(`Warning: ${x}`))}N({resourceId:c.resource.id,slug:h,installPath:p,title:c.resource.title,sha:c.resource.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString()}),d()?w("install",{installPath:p,title:c.resource.title,path:T,files:c.files.length,...x&&{warning:x}}):(u(`Installed "${c.resource.title}" to ${T}`),u(` ${c.files.length} file${c.files.length===1?"":"s"} written`),o||(u(""),u("Tip: Sign up at sharedcontext.ai to track installations and get updates.")))})}v();E();function Ai(n){let e=n.slug||n.resourceId;return n.storageType==="github"&&n.githubOwner?`skills/external/${n.githubOwner}/${e}`:n.orgSlug?`skills/${n.orgSlug}/${e}`:`skills/${e}`}function Oi(n){n.command("list").description("List installed skills").alias("ls").action(async()=>{if(y()){let e=await A("/api/cli/installed");e.ok||(d()?g("list",e.error.code,e.error.message):u(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(d()){let r=t.map(s=>({...s,installPath:Ai(s)}));w("list",{installations:r,count:r.length});return}if(t.length===0){u("No skills installed."),u("Use 'shared-context-ai search' to find skills to install.");return}u(`${t.length} skill${t.length===1?"":"s"} installed:
156
+ `);let i=t.map(r=>[Ai(r),r.title,r.hasUpdate?"(update available)":"(current)"]);u(q(i))}else{let t=F().installations;if(d()){w("list",{installations:t,count:t.length});return}if(t.length===0){u("No skills installed locally.");return}u(`${t.length} skill${t.length===1?"":"s"} installed locally:
157
+ `);let i=t.map(r=>[r.installPath||r.slug,r.title,`(${r.agent})`]);u(q(i)),u(`
158
+ Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}v();function bi(n){n.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let i=y()?"/api/cli/resource":"/api/public/resource",r=await A(`${i}/${e}/preview`);r.ok||(d()?g("preview",r.error.code,r.error.message):f(`Preview failed: ${r.error.message}`),process.exit(1)),d()?w("preview",r.data):u(r.data.content)})}v();function Si(n){n.command("check").description("Check for skill updates").action(async()=>{y()||(d()?g("check","AUTH_MISSING","Login required to check for updates."):f("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await A("/api/cli/updates");e.ok||(d()?g("check",e.error.code,e.error.message):f(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:i}=e.data;if(d()){w("check",{updates:t,count:i});return}if(i===0){u("All skills are up to date.");return}u(`${i} update${i===1?"":"s"} available:
159
+ `);let r=t.map(s=>{let o=s.slug||s.resourceId;return[s.storageType==="github"&&s.githubOwner?`skills/external/${s.githubOwner}/${o}`:s.orgSlug?`skills/${s.orgSlug}/${o}`:`skills/${o}`,s.title,`${s.installedSha.slice(0,7)} \u2192 ${s.latestSha.slice(0,7)}`]});u(q(r)),u(`
160
+ Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var ki=require("path");v();E();function Ei(n){let e=n.slug||n.resourceId;return n.storageType==="github"&&n.githubOwner?`skills/external/${n.githubOwner}/${e}`:n.orgSlug?`skills/${n.orgSlug}/${e}`:`skills/${e}`}function vi(n){n.command("update [path]").description("Update installed skills (all or by install path)").action(async(e,t,i)=>{let r=i.optsWithGlobals();y()||(d()?g("update","AUTH_MISSING","Login required to update skills."):f("Login required to update skills. Run 'shared-context-ai login'."),process.exit(1));let s=L(r.agent);if(!s){let c=M();d()?g("update","NO_AGENTS",c):f(c),process.exit(1)}let o=await A("/api/cli/updates");o.ok||(d()?g("update",o.error.code,o.error.message):f(`Failed to check updates: ${o.error.message}`),process.exit(1));let l=o.data.updates;if(e&&(l=l.filter(c=>Ei(c)===e||c.slug===e||c.resourceId===e),l.length===0)){d()?g("update","SKILL_NOT_FOUND",`No update available for "${e}".`):u(`No update available for "${e}".`);return}if(l.length===0){d()?w("update",{updated:[],count:0}):u("All skills are up to date.");return}let a=[];for(let c of l){let h=Ei(c),p=await A(`/api/cli/resource/${h}`);if(!p.ok){d()||f(` Failed to fetch ${h}: ${p.error.message}`);continue}let _=p.data,T=R(s,!!r.project),x=h.split("/").slice(1),I=(0,ki.join)(T,...x);dt(I,_.files),_.resource.latestSha&&await k("/api/cli/update",{resourceId:_.resource.id,installedSha:_.resource.latestSha}),N({resourceId:_.resource.id,slug:resourceSlug,installPath:h,title:_.resource.title,sha:_.resource.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString()}),a.push({installPath:h,title:_.resource.title}),d()||u(` Updated ${h}`)}d()?w("update",{updated:a,count:a.length}):a.length>0&&u(`
161
+ ${a.length} skill${a.length===1?"":"s"} updated.`)})}var z=require("fs"),pt=require("path");v();E();function Ti(n){n.command("uninstall <path>").description("Uninstall a skill by install path (e.g., skills/acme/api-testing)").action(async(e,t,i)=>{let r=i.optsWithGlobals(),s=L(r.agent);if(!s){let x=M();d()?g("uninstall","NO_AGENTS",x):f(x),process.exit(1)}let l=F().installations.find(x=>x.installPath===e||x.slug===e||x.resourceId===e),a=R(s,!!r.project),c=e.split("/"),p=["skills","files"].includes(c[0])?c.slice(1):c,_=(0,pt.join)(a,...p),T=(0,z.existsSync)(_);if(T&&(0,z.rmSync)(_,{recursive:!0,force:!0}),!T&&l?.slug){let x=(0,pt.join)(a,l.slug);(0,z.existsSync)(x)&&(0,z.rmSync)(x,{recursive:!0,force:!0})}if(y()&&l){let x=await k("/api/cli/uninstall",{resourceId:l.resourceId});!x.ok&&!d()&&f(`Warning: Could not record uninstall on server: ${x.error.message}`)}l&&We(l.resourceId,s.id),d()?w("uninstall",{path:e,removed:!0}):u(`Uninstalled "${e}"`)})}E();function $i(n){n.command("status").description("Show CLI status: auth, agents, installed skill counts").action(async()=>{let e=P(),t=D(),i=F(),r=qe(),s={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:r.map(o=>o.id),installedCount:i.installations.length};if(d()){w("status",s);return}u("Shared Context CLI Status"),u("\u2500".repeat(30)),e?.token?u(` Auth: ${e.email} (${e.orgSlug})`):u(" Auth: Not logged in"),u(` API: ${t.apiBase}`),r.length>0?u(` Agents: ${r.map(o=>o.label).join(", ")}`):u(" Agents: None detected"),u(` Skills: ${i.installations.length} installed`)})}E();v();function Ii(n){n.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=P();e.revoke&&y()&&await Ue("/api/cli/auth"),Ve(),d()?w("logout",{email:t?.email||null}):u("Logged out.")})}var Pi={AUTH_MISSING:"Run 'shared-context-ai login' to authenticate.",AUTH_EXPIRED:"Run 'shared-context-ai login' to re-authenticate.",SKILL_NOT_FOUND:"Check the skill slug and try again.",ALREADY_INSTALLED:"Use 'shared-context-ai update <slug>' to update instead.",NO_AGENTS:"No AI coding agents detected. Run 'shared-context-ai init --agent <name>' to set up manually.",API_ERROR:"The server returned an error. Try again later.",WRITE_FAILED:"Could not write files to disk. Check permissions."},ge=class extends Error{constructor(t,i){super(i||Pi[t]);this.code=t;this.name="CliError"}get recovery(){return Pi[this.code]}};var b=new kt;b.name("shared-context-ai").description("CLI for Shared Context - search, install, and manage AI skills").version("0.1.0").option("--json","Output as JSON (default when piped)").option("--human","Output as human-readable text (default in TTY)").option("--agent <name>","Override agent detection").option("--project","Use project-local directory instead of global").hook("preAction",n=>{let e=n.opts();$t(!!e.json,!!e.human)});Rt(b);wi(b);yi(b);Ci(b);Oi(b);bi(b);Si(b);vi(b);Ti(b);$i(b);Ii(b);process.on("uncaughtException",n=>{n instanceof ge?d()?g(process.argv[2]||"unknown",n.code,n.message):(f(`Error: ${n.message}`),f(n.recovery)):d()?g(process.argv[2]||"unknown","UNEXPECTED",n.message||"Unexpected error"):f(`Error: ${n.message||n}`),process.exit(1)});b.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shared-context-ai",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "CLI for Shared Context - search, install, and manage AI skills",
5
5
  "bin": {
6
6
  "shared-context-ai": "dist/index.js"