shared-context-ai 0.1.1 → 0.1.2

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 +87 -99
  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 Ti=Object.create;var fe=Object.defineProperty;var $i=Object.getOwnPropertyDescriptor;var Ii=Object.getOwnPropertyNames;var Pi=Object.getPrototypeOf,Hi=Object.prototype.hasOwnProperty;var O=(s,e)=>()=>(s&&(e=s(s=0)),e);var V=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),ge=(s,e)=>{for(var t in e)fe(s,t,{get:e[t],enumerable:!0})},Ni=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ii(e))!Hi.call(s,r)&&r!==t&&fe(s,r,{get:()=>e[r],enumerable:!(i=$i(e,r))||i.enumerable});return s};var x=(s,e,t)=>(t=s!=null?Ti(Pi(s)):{},Ni(e||!s||!s.__esModule?fe(t,"default",{value:s,enumerable:!0}):t,s));var q=V(we=>{"use strict";var X=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}},_e=class extends X{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};we.CommanderError=X;we.InvalidArgumentError=_e});var Q=V(xe=>{"use strict";var{InvalidArgumentError:Fi}=q(),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 Fi(`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 Li(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}xe.Argument=ye;xe.humanReadableArgName=Li});var Oe=V(Ce=>{"use strict";var{humanReadableArgName:Di}=Q(),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,n)=>r.name().localeCompare(n.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),n=i.long&&e._findOption(i.long);!r&&!n?t.push(i):i.long&&!n?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(n=>!n.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=>Di(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 n(p,_){return t.formatItem(p,i,_,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=>n(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=>n(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(_=>n(t.styleOptionTerm(t.optionTerm(_)),t.styleOptionDescription(t.optionDescription(_))));p.length>0&&(o=o.concat([t.styleTitle("Global Options:"),...p,""]))}let d=t.visibleCommands(e).map(p=>n(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 dt(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,`
2
+ "use strict";var Ti=Object.create;var fe=Object.defineProperty;var $i=Object.getOwnPropertyDescriptor;var Ii=Object.getOwnPropertyNames;var Pi=Object.getPrototypeOf,Hi=Object.prototype.hasOwnProperty;var O=(s,e)=>()=>(s&&(e=s(s=0)),e);var V=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),ge=(s,e)=>{for(var t in e)fe(s,t,{get:e[t],enumerable:!0})},Ni=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ii(e))!Hi.call(s,r)&&r!==t&&fe(s,r,{get:()=>e[r],enumerable:!(i=$i(e,r))||i.enumerable});return s};var A=(s,e,t)=>(t=s!=null?Ti(Pi(s)):{},Ni(e||!s||!s.__esModule?fe(t,"default",{value:s,enumerable:!0}):t,s));var q=V(we=>{"use strict";var X=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}},_e=class extends X{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};we.CommanderError=X;we.InvalidArgumentError=_e});var Q=V(Ae=>{"use strict";var{InvalidArgumentError:Fi}=q(),xe=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 Fi(`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 Li(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}Ae.Argument=xe;Ae.humanReadableArgName=Li});var Oe=V(Ce=>{"use strict";var{humanReadableArgName:Mi}=Q(),ye=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,n)=>r.name().localeCompare(n.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),n=i.long&&e._findOption(i.long);!r&&!n?t.push(i):i.long&&!n?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(n=>!n.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=>Mi(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 n(p,g){return t.formatItem(p,i,g,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=>n(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=>n(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(g=>n(t.styleOptionTerm(t.optionTerm(g)),t.styleOptionDescription(t.optionDescription(g))));p.length>0&&(o=o.concat([t.styleTitle("Global Options:"),...p,""]))}let u=t.visibleCommands(e).map(p=>n(t.styleSubcommandTerm(t.subcommandTerm(p)),t.styleSubcommandDescription(t.subcommandDescription(p))));return u.length>0&&(o=o.concat([t.styleTitle("Commands:"),...u,""])),o.join(`
3
+ `)}displayWidth(e){return dt(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,u=(this.helpWidth??80)-t-l-2,p;return u<this.minWidthToWrap||r.preformatted(i)?p=i:p=r.boxWrap(i,u).replace(/\n/g,`
4
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,n=[];return i.forEach(o=>{let a=o.match(r);if(a===null){n.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}n.push(l.join(""));let _=d.trimStart();l=[_],c=this.displayWidth(_)}),n.push(l.join(""))}),n.join(`
6
- `)}};function dt(s){let e=/\x1b\[\d*(;\d*)*m/g;return s.replace(e,"")}Ce.Help=Ae;Ce.stripColor=dt});var Ee=V(ke=>{"use strict";var{InvalidArgumentError:Mi}=q(),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=ji(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 Mi(`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?ht(this.name().replace(/^no-/,"")):ht(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Se=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,n=r!==void 0?r:!1;return t.negate===(n===e)}};function ht(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ji(s){let e,t,i=/^-[^-]$/,r=/^--[^-]/,n=s.split(/[ |,]+/).concat("guard");if(i.test(n[0])&&(e=n.shift()),r.test(n[0])&&(t=n.shift()),!e&&i.test(n[0])&&(e=n.shift()),!e&&r.test(n[0])&&(e=t,t=n.shift()),n[0].startsWith("-")){let o=n[0],a=`option creation failed due to '${o}' in option flags '${s}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
5
+ ${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,n=[];return i.forEach(o=>{let a=o.match(r);if(a===null){n.push("");return}let l=[a.shift()],c=this.displayWidth(l[0]);a.forEach(u=>{let p=this.displayWidth(u);if(c+p<=t){l.push(u),c+=p;return}n.push(l.join(""));let g=u.trimStart();l=[g],c=this.displayWidth(g)}),n.push(l.join(""))}),n.join(`
6
+ `)}};function dt(s){let e=/\x1b\[\d*(;\d*)*m/g;return s.replace(e,"")}Ce.Help=ye;Ce.stripColor=dt});var ke=V(Ee=>{"use strict";var{InvalidArgumentError:Di}=q(),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=ji(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 Di(`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?ht(this.name().replace(/^no-/,"")):ht(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Se=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,n=r!==void 0?r:!1;return t.negate===(n===e)}};function ht(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ji(s){let e,t,i=/^-[^-]$/,r=/^--[^-]/,n=s.split(/[ |,]+/).concat("guard");if(i.test(n[0])&&(e=n.shift()),r.test(n[0])&&(t=n.shift()),!e&&i.test(n[0])&&(e=n.shift()),!e&&r.test(n[0])&&(e=t,t=n.shift()),n[0].startsWith("-")){let o=n[0],a=`option creation failed due to '${o}' in option flags '${s}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
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
9
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(o)?new Error(`${a}
10
10
  - too many short flags`):r.test(o)?new Error(`${a}
11
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 '${s}'.`);return{shortFlag:e,longFlag:t}}ke.Option=be;ke.DualOptions=Se});var mt=V(pt=>{"use strict";function Ri(s,e){if(Math.abs(s.length-e.length)>3)return Math.max(s.length,e.length);let t=[];for(let i=0;i<=s.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<=s.length;r++){let n=1;s[r-1]===e[i-1]?n=0:n=1,t[r][i]=Math.min(t[r-1][i]+1,t[r][i-1]+1,t[r-1][i-1]+n),r>1&&i>1&&s[r-1]===e[i-2]&&s[r-2]===e[i-1]&&(t[r][i]=Math.min(t[r][i],t[r-2][i-2]+1))}return t[s.length][e.length]}function Vi(s,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=s.startsWith("--");t&&(s=s.slice(2),e=e.map(o=>o.slice(2)));let i=[],r=3,n=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Ri(s,o),l=Math.max(s.length,o.length);(l-a)/l>n&&(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?`
12
+ - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${s}'.`);return{shortFlag:e,longFlag:t}}Ee.Option=be;Ee.DualOptions=Se});var mt=V(pt=>{"use strict";function Ri(s,e){if(Math.abs(s.length-e.length)>3)return Math.max(s.length,e.length);let t=[];for(let i=0;i<=s.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<=s.length;r++){let n=1;s[r-1]===e[i-1]?n=0:n=1,t[r][i]=Math.min(t[r-1][i]+1,t[r][i-1]+1,t[r-1][i-1]+n),r>1&&i>1&&s[r-1]===e[i-2]&&s[r-2]===e[i-1]&&(t[r][i]=Math.min(t[r][i],t[r-2][i-2]+1))}return t[s.length][e.length]}function Vi(s,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=s.startsWith("--");t&&(s=s.slice(2),e=e.map(o=>o.slice(2)));let i=[],r=3,n=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Ri(s,o),l=Math.max(s.length,o.length);(l-a)/l>n&&(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?`
13
13
  (Did you mean one of ${i.join(", ")}?)`:i.length===1?`
14
- (Did you mean ${i[0]}?)`:""}pt.suggestSimilar=Vi});var wt=V(Pe=>{"use strict";var Wi=require("events").EventEmitter,ve=require("child_process"),P=require("path"),Z=require("fs"),m=require("process"),{Argument:Ui,humanReadableArgName:Bi}=Q(),{CommanderError:Te}=q(),{Help:qi,stripColor:Gi}=Oe(),{Option:ft,DualOptions:Ji}=Ee(),{suggestSimilar:gt}=mt(),$e=class s extends Wi{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:()=>Ie()??(m.stdout.isTTY&&m.stdout.hasColors?.()),getErrHasColors:()=>Ie()??(m.stderr.isTTY&&m.stderr.hasColors?.()),stripColor:t=>Gi(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,n=i;typeof r=="object"&&r!==null&&(n=r,r=null),n=n||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return r&&(l.description(r),l._executableHandler=!0),n.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(n.noHelp||n.hidden),l._executableFile=n.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),r?this:l}createCommand(e){return new s(e)}createHelp(){return Object.assign(new qi,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]}?)`:""}pt.suggestSimilar=Vi});var wt=V(Pe=>{"use strict";var Wi=require("events").EventEmitter,ve=require("child_process"),P=require("path"),Z=require("fs"),m=require("process"),{Argument:Ui,humanReadableArgName:Bi}=Q(),{CommanderError:Te}=q(),{Help:qi,stripColor:Gi}=Oe(),{Option:ft,DualOptions:Ji}=ke(),{suggestSimilar:gt}=mt(),$e=class s extends Wi{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:()=>Ie()??(m.stdout.isTTY&&m.stdout.hasColors?.()),getErrHasColors:()=>Ie()??(m.stderr.isTTY&&m.stderr.hasColors?.()),stripColor:t=>Gi(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,n=i;typeof r=="object"&&r!==null&&(n=r,r=null),n=n||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return r&&(l.description(r),l._executableHandler=!0),n.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(n.noHelp||n.hidden),l._executableFile=n.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),r?this:l}createCommand(e){return new s(e)}createHelp(){return Object.assign(new qi,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 Ui(e,t)}argument(e,t,i,r){let n=this.createArgument(e,t);return typeof i=="function"?n.default(r).argParser(i):n.default(i),this.addArgument(n),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(/([^ ]+) *(.*)/),n=t??"display help for command",o=this.createCommand(i);return o.helpOption(!1),r&&o.arguments(r),n&&o.description(n),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
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 Te(e,t,i)),m.exit(e)}action(e){let t=i=>{let r=this.registeredArguments.length,n=i.slice(0,r);return this._storeOptionsAsProperties?n[r]=this:n[r]=this.opts(),n.push(this),e.apply(this,n)};return this._actionHandler=t,this}createOption(e,t){return new ft(e,t)}_callParseArg(e,t,i,r){try{return e.parseArg(t,i)}catch(n){if(n.code==="commander.invalidArgument"){let o=`${r} ${n.message}`;this.error(o,{exitCode:n.exitCode,code:n.code})}throw n}}_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("|"),n=t(e).join("|");throw new Error(`cannot add command '${n}' 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 n=e.long.replace(/^--no-/,"--");this._findOption(n)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let r=(n,o,a)=>{n==null&&e.presetArg!==void 0&&(n=e.presetArg);let l=this.getOptionValue(i);n!==null&&e.parseArg?n=this._callParseArg(e,n,l,o):n!==null&&e.variadic&&(n=e._concatValue(n,l)),n==null&&(e.negate?n=!1:e.isBoolean()||e.optional?n=!0:n=""),this.setOptionValueWithSource(i,n,a)};return this.on("option:"+t,n=>{let o=`error: option '${e.flags}' argument '${n}' is invalid.`;r(n,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,n=>{let o=`error: option '${e.flags}' value '${n}' from env '${e.envVar}' is invalid.`;r(n,o,"env")}),this}_optionEx(e,t,i,r,n){if(typeof t=="object"&&t instanceof ft)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(n).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(n).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.
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("|"),n=t(e).join("|");throw new Error(`cannot add command '${n}' 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 n=e.long.replace(/^--no-/,"--");this._findOption(n)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let r=(n,o,a)=>{n==null&&e.presetArg!==void 0&&(n=e.presetArg);let l=this.getOptionValue(i);n!==null&&e.parseArg?n=this._callParseArg(e,n,l,o):n!==null&&e.variadic&&(n=e._concatValue(n,l)),n==null&&(e.negate?n=!1:e.isBoolean()||e.optional?n=!0:n=""),this.setOptionValueWithSource(i,n,a)};return this.on("option:"+t,n=>{let o=`error: option '${e.flags}' argument '${n}' is invalid.`;r(n,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,n=>{let o=`error: option '${e.flags}' value '${n}' from env '${e.envVar}' is invalid.`;r(n,o,"env")}),this}_optionEx(e,t,i,r,n){if(typeof t=="object"&&t instanceof ft)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(n).argParser(r);else if(r instanceof RegExp){let a=r;r=(l,c)=>{let u=a.exec(l);return u?u[0]:c},o.default(n).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
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(Z.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",n=`'${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(n)}_executeSubCommand(e,t){t=t.slice();let i=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function n(d,p){let _=P.resolve(d,p);if(Z.existsSync(_))return _;if(r.includes(P.extname(p)))return;let $=r.find(me=>Z.existsSync(`${_}${me}`));if($)return`${_}${$}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=Z.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=P.resolve(P.dirname(d),a)}if(a){let d=n(a,o);if(!d&&!e._executableFile&&this._scriptPath){let p=P.basename(this._scriptPath,P.extname(this._scriptPath));p!==this._name&&(d=n(a,`${p}-${e._name}`))}o=d||o}i=r.includes(P.extname(o));let l;m.platform!=="win32"?i?(t.unshift(o),t=_t(m.execArgv).concat(t),l=ve.spawn(m.argv[0],t,{stdio:"inherit"})):l=ve.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=_t(m.execArgv).concat(t),l=ve.spawn(m.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{m.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 Te(d,"commander.executeSubCommandAsync","(close)")):m.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)m.exit(1);else{let p=new Te(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 n;return n=this._chainOrCallSubCommandHook(n,r,"preSubcommand"),n=this._chainOrCall(n,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(i));else return r._parseCommand(t,i)}),n}_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,n)=>{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,n,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,r)=>{let n=i.defaultValue;i.variadic?r<this.args.length?(n=this.args.slice(r),i.parseArg&&(n=n.reduce((o,a)=>e(i,a,o),i.defaultValue))):n===void 0&&(n=[]):r<this.args.length&&(n=this.args[r],i.parseArg&&(n=e(i,n,i.defaultValue))),t[r]=n}),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(n=>n._lifeCycleHooks[t]!==void 0).forEach(n=>{n._lifeCycleHooks[t].forEach(o=>{r.push({hookedCommand:n,callback:o})})}),t==="postAction"&&r.reverse(),r.forEach(n=>{i=this._chainOrCall(i,()=>n.callback(n.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let r=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(n=>{r=this._chainOrCall(r,()=>n(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])},n=`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(n,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(n))r(),this._processArguments(),this.parent.emit(n,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(n=>i.conflictsWith.includes(n.attributeName()));r&&this._conflictingOption(i,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],r=t,n=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;n.length;){let l=n.shift();if(l==="--"){r===i&&r.push(l),r.push(...n);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=n.shift();d===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,d)}else if(c.optional){let d=null;n.length>0&&!o(n[0])&&(d=n.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()}`),n.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),n.length>0&&i.push(...n);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),n.length>0&&t.push(...n);break}else if(this._defaultCommandName){i.push(l),n.length>0&&i.push(...n);break}}if(this._passThroughOptions){r.push(l),n.length>0&&r.push(...n);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(n)}_executeSubCommand(e,t){t=t.slice();let i=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function n(u,p){let g=P.resolve(u,p);if(Z.existsSync(g))return g;if(r.includes(P.extname(p)))return;let $=r.find(me=>Z.existsSync(`${g}${me}`));if($)return`${g}${$}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Z.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=P.resolve(P.dirname(u),a)}if(a){let u=n(a,o);if(!u&&!e._executableFile&&this._scriptPath){let p=P.basename(this._scriptPath,P.extname(this._scriptPath));p!==this._name&&(u=n(a,`${p}-${e._name}`))}o=u||o}i=r.includes(P.extname(o));let l;m.platform!=="win32"?i?(t.unshift(o),t=_t(m.execArgv).concat(t),l=ve.spawn(m.argv[0],t,{stdio:"inherit"})):l=ve.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=_t(m.execArgv).concat(t),l=ve.spawn(m.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{m.on(p,()=>{l.killed===!1&&l.exitCode===null&&l.kill(p)})});let c=this._exitCallback;l.on("close",u=>{u=u??1,c?c(new Te(u,"commander.executeSubCommandAsync","(close)")):m.exit(u)}),l.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)m.exit(1);else{let p=new Te(1,"commander.executeSubCommandAsync","(error)");p.nestedError=u,c(p)}}),this.runningCommand=l}_dispatchSubcommand(e,t,i){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let n;return n=this._chainOrCallSubCommandHook(n,r,"preSubcommand"),n=this._chainOrCall(n,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(i));else return r._parseCommand(t,i)}),n}_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,n)=>{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,n,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,r)=>{let n=i.defaultValue;i.variadic?r<this.args.length?(n=this.args.slice(r),i.parseArg&&(n=n.reduce((o,a)=>e(i,a,o),i.defaultValue))):n===void 0&&(n=[]):r<this.args.length&&(n=this.args[r],i.parseArg&&(n=e(i,n,i.defaultValue))),t[r]=n}),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(n=>n._lifeCycleHooks[t]!==void 0).forEach(n=>{n._lifeCycleHooks[t].forEach(o=>{r.push({hookedCommand:n,callback:o})})}),t==="postAction"&&r.reverse(),r.forEach(n=>{i=this._chainOrCall(i,()=>n.callback(n.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let r=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(n=>{r=this._chainOrCall(r,()=>n(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])},n=`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(n,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(n))r(),this._processArguments(),this.parent.emit(n,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(n=>i.conflictsWith.includes(n.attributeName()));r&&this._conflictingOption(i,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],r=t,n=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;n.length;){let l=n.shift();if(l==="--"){r===i&&r.push(l),r.push(...n);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 u=n.shift();u===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;n.length>0&&!o(n[0])&&(u=n.shift()),this.emit(`option:${c.name()}`,u)}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()}`),n.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),u=this._findOption(l.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.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),n.length>0&&i.push(...n);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),n.length>0&&t.push(...n);break}else if(this._defaultCommandName){i.push(l),n.length>0&&i.push(...n);break}}if(this._passThroughOptions){r.push(l),n.length>0&&r.push(...n);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}
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,n=i.code||"commander.error";this._exit(r,n,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 Ji(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}'`},n=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(n,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],n=this;do{let o=n.createHelp().visibleOptions(n).filter(a=>a.long).map(a=>a.long);r=r.concat(o),n=n.parent}while(n&&!n._enablePositionalOptions);t=gt(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",n=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(n,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(n=>{r.push(n.name()),n.alias()&&r.push(n.alias())}),t=gt(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}
24
+ `),this.outputHelp({error:!0}));let i=t||{},r=i.exitCode||1,n=i.code||"commander.error";this._exit(r,n,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 Ji(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()),u=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:u||o},r=o=>{let a=i(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},n=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(n,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],n=this;do{let o=n.createHelp().visibleOptions(n).filter(a=>a.long).map(a=>a.long);r=r.concat(o),n=n.parent}while(n&&!n._enablePositionalOptions);t=gt(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",n=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(n,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(n=>{r.push(n.name()),n.alias()&&r.push(n.alias())}),t=gt(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
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=>Bi(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=P.basename(e,P.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,n;return t?(i=a=>this._outputConfiguration.writeErr(a),r=this._outputConfiguration.getErrHasColors(),n=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),r=this._outputConfiguration.getOutHasColors(),n=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(r||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:r,helpWidth:n}}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 n=this.helpInformation({error:i.error});if(t&&(n=t(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(n),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,n=>{let o;typeof t=="function"?o=t({error:n.error,command:n.command}):o=t,o&&n.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 _t(s){return s.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",r="9229",n;return(n=e.match(/^(--inspect(-brk)?)$/))!==null?t=n[1]:(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=n[1],/^\d+$/.test(n[3])?r=n[3]:i=n[3]):(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=n[1],i=n[3],r=n[4]),t&&r!=="0"?`${t}=${i}:${parseInt(r)+1}`:e})}function Ie(){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}Pe.Command=$e;Pe.useColor=Ie});var Ct=V(S=>{"use strict";var{Argument:yt}=Q(),{Command:He}=wt(),{CommanderError:Ki,InvalidArgumentError:xt}=q(),{Help:Yi}=Oe(),{Option:At}=Ee();S.program=new He;S.createCommand=s=>new He(s);S.createOption=(s,e)=>new At(s,e);S.createArgument=(s,e)=>new yt(s,e);S.Command=He;S.Option=At;S.Argument=yt;S.Help=Yi;S.CommanderError=Ki;S.InvalidArgumentError=xt;S.InvalidOptionArgumentError=xt});var Pt={};ge(Pt,{addToManifest:()=>N,clearAuth:()=>Me,getAuth:()=>I,getConfig:()=>C,getManifest:()=>H,removeFromManifest:()=>Ve,saveAuth:()=>De,saveConfig:()=>It,saveManifest:()=>Re,updateConfig:()=>je});function zi(){(0,T.mkdirSync)(ee,{recursive:!0})}function Fe(s,e){try{return(0,T.existsSync)(s)?JSON.parse((0,T.readFileSync)(s,"utf-8")):e}catch{return e}}function Le(s,e,t=!1){if(zi(),(0,T.writeFileSync)(s,JSON.stringify(e,null,2)+`
28
- `,"utf-8"),t)try{(0,T.chmodSync)(s,384)}catch{}}function I(){return Fe(Ne,null)}function De(s){Le(Ne,s,!0)}function Me(){try{(0,T.writeFileSync)(Ne,"{}","utf-8")}catch{}}function C(){return Fe(Tt,Xi)}function It(s){Le(Tt,s)}function je(s){let e=C();It({...e,...s})}function H(){return Fe($t,Qi)}function Re(s){Le($t,s)}function N(s){let e=H(),t=e.installations.findIndex(i=>i.resourceId===s.resourceId);t>=0?e.installations[t]=s:e.installations.push(s),Re(e)}function Ve(s){let e=H();e.installations=e.installations.filter(t=>t.resourceId!==s),Re(e)}var T,G,vt,ee,Ne,Tt,$t,Xi,Qi,k=O(()=>{"use strict";T=require("fs"),G=require("path"),vt=require("os"),ee=(0,G.join)((0,vt.homedir)(),".config","shared-context"),Ne=(0,G.join)(ee,"auth.json"),Tt=(0,G.join)(ee,"config.json"),$t=(0,G.join)(ee,"manifest.json");Xi={apiBase:"https://sharedcontext.ai"};Qi={installations:[]}});var Ht={};ge(Ht,{del:()=>We,get:()=>A,isAuthenticated:()=>y,patch:()=>tr,post:()=>E});function Zi(){return C().apiBase||"https://sharedcontext.ai"}function er(){let s={"Content-Type":"application/json"},e=I();return e?.token&&(s.Authorization=`Bearer ${e.token}`),s}function y(){return!!I()?.token}async function te(s,e,t){let i=`${Zi()}${e}`;try{let r=await fetch(i,{method:s,headers:er(),body:t?JSON.stringify(t):void 0}),n=r.headers.get("content-type")||"";if(!n.includes("application/json"))return r.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${n||"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(s){return te("GET",s)}function E(s,e){return te("POST",s,e)}function tr(s,e){return te("PATCH",s,e)}function We(s,e){return te("DELETE",s,e)}var v=O(()=>{"use strict";k()});function rr(){try{return qe.default.statSync("/.dockerenv"),!0}catch{return!1}}function nr(){try{return qe.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Ge(){return Be===void 0&&(Be=rr()||nr()),Be}var qe,Be,Mt=O(()=>{"use strict";qe=x(require("fs"),1)});function U(){return Je===void 0&&(Je=sr()||Ge()),Je}var jt,Je,sr,Ke=O(()=>{"use strict";jt=x(require("fs"),1);Mt();sr=()=>{try{return jt.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var Ye,Vt,oe,Rt,D,ze=O(()=>{"use strict";Ye=x(require("process"),1),Vt=x(require("os"),1),oe=x(require("fs"),1);Ke();Rt=()=>{if(Ye.default.platform!=="linux")return!1;if(Vt.default.release().toLowerCase().includes("microsoft"))return!U();try{if(oe.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!U()}catch{}return oe.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||oe.default.existsSync("/run/WSL")?!U():!1},D=Ye.default.env.__IS_WSL_TEST__?Rt:Rt()});var Xe,Y,or,ar,Qe,Wt=O(()=>{"use strict";Xe=x(require("process"),1),Y=x(require("fs/promises"),1);ze();ze();or=(()=>{let s="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await Y.default.access(t,Y.constants.F_OK),i=!0}catch{}if(!i)return s;let r=await Y.default.readFile(t,{encoding:"utf8"}),n=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(r);return n?(e=n.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):s}})(),ar=async()=>`${await or()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Qe=async()=>D?ar():`${Xe.default.env.SYSTEMROOT||Xe.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function M(s,e,t){let i=r=>Object.defineProperty(s,e,{value:r,enumerable:!0,writable:!0});return Object.defineProperty(s,e,{configurable:!0,enumerable:!0,get(){let r=t();return i(r),r},set(r){i(r)}}),s}var Ut=O(()=>{"use strict"});async function Ze(){if(qt.default.platform!=="darwin")throw new Error("macOS only");let{stdout:s}=await lr("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(s)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var Bt,qt,Gt,lr,Jt=O(()=>{"use strict";Bt=require("util"),qt=x(require("process"),1),Gt=require("child_process"),lr=(0,Bt.promisify)(Gt.execFile)});async function zt(s,{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:n}=await cr("osascript",["-e",s,i],r);return n.trim()}var Kt,Yt,et,cr,Xt=O(()=>{"use strict";Kt=x(require("process"),1),Yt=require("util"),et=require("child_process"),cr=(0,Yt.promisify)(et.execFile)});async function tt(s){return zt(`tell application "Finder" to set app_path to application file id "${s}" 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 Qt=O(()=>{"use strict";Xt()});async function rt(s=ur){let{stdout:e}=await s("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 it(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:i}=t.groups,r=i.lastIndexOf("."),n=i.lastIndexOf("-"),o=r===-1?void 0:i.slice(0,r),a=n===-1?void 0:i.slice(0,n);return ae[i]??ae[o]??ae[a]??{name:i,id:i}}var Zt,ei,ur,ae,cn,it,ti=O(()=>{"use strict";Zt=require("util"),ei=require("child_process"),ur=(0,Zt.promisify)(ei.execFile),ae={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"}},cn=new Map(Object.entries(ae)),it=class extends Error{}});async function nt(){if(le.default.platform==="darwin"){let s=await Ze();return{name:await tt(s),id:s}}if(le.default.platform==="linux"){let{stdout:s}=await dr("xdg-mime",["query","default","x-scheme-handler/http"]),e=s.trim();return{name:hr(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(le.default.platform==="win32")return rt();throw new Error("Only macOS, Linux, and Windows are supported")}var ii,le,ri,dr,hr,ni=O(()=>{"use strict";ii=require("util"),le=x(require("process"),1),ri=require("child_process");Jt();Qt();ti();dr=(0,ii.promisify)(ri.execFile),hr=s=>s.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var di={};ge(di,{apps:()=>j,default:()=>_r,openApp:()=>gr});async function mr(){let s=await Qe(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=at.Buffer.from(e,"utf16le").toString("base64"),{stdout:i}=await pr(s,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),r=i.trim(),n={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return n[r]?{id:n[r]}:{}}function li(s){if(typeof s=="string"||Array.isArray(s))return s;let{[oi]:e}=s;if(!e)throw new Error(`${oi} is not supported`);return e}function ue({[B]:s},{wsl:e}){if(e&&D)return li(e);if(!s)throw new Error(`${B} is not supported`);return li(s)}var ot,at,lt,ci,ui,ct,ce,wr,pr,st,si,B,oi,ai,z,fr,gr,j,_r,hi=O(()=>{"use strict";ot=x(require("process"),1),at=require("buffer"),lt=x(require("path"),1),ci=require("url"),ui=require("util"),ct=x(require("child_process"),1),ce=x(require("fs/promises"),1);Wt();Ut();ni();Ke();wr={},pr=(0,ui.promisify)(ct.default.execFile),st=lt.default.dirname((0,ci.fileURLToPath)(wr.url)),si=lt.default.join(st,"xdg-open"),{platform:B,arch:oi}=ot.default;ai=async(s,e)=>{let t;for(let i of s)try{return await e(i)}catch(r){t=r}throw t},z=async s=>{if(s={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...s},Array.isArray(s.app))return ai(s.app,a=>z({...s,app:a}));let{name:e,arguments:t=[]}=s.app??{};if(t=[...t],Array.isArray(e))return ai(e,a=>z({...s,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=D?await mr():await nt();if(c.id in a){let d=a[c.id];return e==="browserPrivate"&&t.push(l[d]),z({...s,app:{name:j[d],arguments:t}})}throw new Error(`${c.name} is not supported as a default browser`)}let i,r=[],n={};if(B==="darwin")i="open",s.wait&&r.push("--wait-apps"),s.background&&r.push("--background"),s.newInstance&&r.push("--new"),e&&r.push("-a",e);else if(B==="win32"||D&&!U()&&!e){i=await Qe(),r.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),D||(n.windowsVerbatimArguments=!0);let a=["Start"];s.wait&&a.push("-Wait"),e?(a.push(`"\`"${e}\`""`),s.target&&t.push(s.target)):s.target&&a.push(`"${s.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),a.push("-ArgumentList",t.join(","))),s.target=at.Buffer.from(a.join(" "),"utf16le").toString("base64")}else{if(e)i=e;else{let a=!st||st==="/",l=!1;try{await ce.default.access(si,ce.constants.X_OK),l=!0}catch{}i=ot.default.versions.electron??(B==="android"||a||!l)?"xdg-open":si}t.length>0&&r.push(...t),s.wait||(n.stdio="ignore",n.detached=!0)}B==="darwin"&&t.length>0&&r.push("--args",...t),s.target&&r.push(s.target);let o=ct.default.spawn(i,r,n);return s.wait?new Promise((a,l)=>{o.once("error",l),o.once("close",c=>{if(!s.allowNonzeroExitCode&&c>0){l(new Error(`Exited with code ${c}`));return}a(o)})}):(o.unref(),o)},fr=(s,e)=>{if(typeof s!="string")throw new TypeError("Expected a `target`");return z({...e,target:s})},gr=(s,e)=>{if(typeof s!="string"&&!Array.isArray(s))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:s,arguments:t}})};j={};M(j,"chrome",()=>ue({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"]}}));M(j,"brave",()=>ue({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"]}}));M(j,"firefox",()=>ue({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));M(j,"edge",()=>ue({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));M(j,"browser",()=>"browser");M(j,"browserPrivate",()=>"browserPrivate");_r=fr});var Ot=x(Ct(),1),{program:vr,createCommand:Tr,createArgument:$r,createOption:Ir,CommanderError:Pr,InvalidArgumentError:Hr,InvalidOptionArgumentError:Nr,Command:bt,Argument:Fr,Option:Lr,Help:Dr}=Ot.default;var St=!1,kt=!1;function Et(s,e){St=s,kt=e}function h(){return St?!0:kt?!1:!process.stdout.isTTY}function w(s,e){console.log(JSON.stringify({ok:!0,command:s,data:e}))}function g(s,e,t){console.log(JSON.stringify({ok:!1,command:s,errors:[{code:e,message:t}]}))}function u(s){console.log(s)}function f(s){console.error(s)}function W(s,e=2){if(s.length===0)return"";let t=[];for(let i of s)for(let r=0;r<i.length;r++)t[r]=Math.max(t[r]||0,i[r].length);return s.map(i=>i.map((r,n)=>n<i.length-1?r.padEnd(t[n]+e):r).join("")).join(`
30
- `)}var se=require("fs"),re=require("path");k();v();var Ue=require("fs"),K=require("path"),ie=require("os"),J=[{id:"claude-code",label:"Claude Code",envVar:"CLAUDE_CODE",dir:".claude",skillsSubdir:"skills",platform:"claude_code"},{id:"cursor",label:"Cursor",envVar:"CURSOR",dir:".cursor",skillsSubdir:"skills",platform:"custom"},{id:"codex",label:"Codex",envVar:"CODEX",dir:".codex",skillsSubdir:"skills",platform:"codex"},{id:"opencode",label:"OpenCode",envVar:"OPENCODE",dir:".opencode",skillsSubdir:"skills",platform:"custom"}];function F(s){if(s){let t=J.find(r=>r.id===s);if(t)return t;let i=J.find(r=>r.dir===`.${s}`||r.dir===s);return i||null}for(let t of J)if(process.env[t.envVar])return t;let e=(0,ie.homedir)();for(let t of J)if((0,Ue.existsSync)((0,K.join)(e,t.dir)))return t;return null}function Nt(){let s=[],e=(0,ie.homedir)();for(let t of J)(process.env[t.envVar]||(0,Ue.existsSync)((0,K.join)(e,t.dir)))&&s.push(t);return s}function L(s,e){return e?(0,K.join)(process.cwd(),s.dir,s.skillsSubdir):(0,K.join)((0,ie.homedir)(),s.dir,s.skillsSubdir)}var Ft=`---
27
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function _t(s){return s.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",r="9229",n;return(n=e.match(/^(--inspect(-brk)?)$/))!==null?t=n[1]:(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=n[1],/^\d+$/.test(n[3])?r=n[3]:i=n[3]):(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=n[1],i=n[3],r=n[4]),t&&r!=="0"?`${t}=${i}:${parseInt(r)+1}`:e})}function Ie(){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}Pe.Command=$e;Pe.useColor=Ie});var Ct=V(S=>{"use strict";var{Argument:xt}=Q(),{Command:He}=wt(),{CommanderError:Ki,InvalidArgumentError:At}=q(),{Help:Yi}=Oe(),{Option:yt}=ke();S.program=new He;S.createCommand=s=>new He(s);S.createOption=(s,e)=>new yt(s,e);S.createArgument=(s,e)=>new xt(s,e);S.Command=He;S.Option=yt;S.Argument=xt;S.Help=Yi;S.CommanderError=Ki;S.InvalidArgumentError=At;S.InvalidOptionArgumentError=At});var Pt={};ge(Pt,{addToManifest:()=>N,clearAuth:()=>De,getAuth:()=>I,getConfig:()=>C,getManifest:()=>H,removeFromManifest:()=>Ve,saveAuth:()=>Me,saveConfig:()=>It,saveManifest:()=>Re,updateConfig:()=>je});function zi(){(0,T.mkdirSync)(ee,{recursive:!0})}function Fe(s,e){try{return(0,T.existsSync)(s)?JSON.parse((0,T.readFileSync)(s,"utf-8")):e}catch{return e}}function Le(s,e,t=!1){if(zi(),(0,T.writeFileSync)(s,JSON.stringify(e,null,2)+`
28
+ `,"utf-8"),t)try{(0,T.chmodSync)(s,384)}catch{}}function I(){return Fe(Ne,null)}function Me(s){Le(Ne,s,!0)}function De(){try{(0,T.writeFileSync)(Ne,"{}","utf-8")}catch{}}function C(){return Fe(Tt,Xi)}function It(s){Le(Tt,s)}function je(s){let e=C();It({...e,...s})}function H(){return Fe($t,Qi)}function Re(s){Le($t,s)}function N(s){let e=H(),t=e.installations.findIndex(i=>i.resourceId===s.resourceId);t>=0?e.installations[t]=s:e.installations.push(s),Re(e)}function Ve(s){let e=H();e.installations=e.installations.filter(t=>t.resourceId!==s),Re(e)}var T,G,vt,ee,Ne,Tt,$t,Xi,Qi,E=O(()=>{"use strict";T=require("fs"),G=require("path"),vt=require("os"),ee=(0,G.join)((0,vt.homedir)(),".config","shared-context"),Ne=(0,G.join)(ee,"auth.json"),Tt=(0,G.join)(ee,"config.json"),$t=(0,G.join)(ee,"manifest.json");Xi={apiBase:"https://sharedcontext.ai"};Qi={installations:[]}});var Ht={};ge(Ht,{del:()=>We,get:()=>y,isAuthenticated:()=>x,patch:()=>tr,post:()=>k});function Zi(){return C().apiBase||"https://sharedcontext.ai"}function er(){let s={"Content-Type":"application/json"},e=I();return e?.token&&(s.Authorization=`Bearer ${e.token}`),s}function x(){return!!I()?.token}async function te(s,e,t){let i=`${Zi()}${e}`;try{let r=await fetch(i,{method:s,headers:er(),body:t?JSON.stringify(t):void 0}),n=r.headers.get("content-type")||"";if(!n.includes("application/json"))return r.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${n||"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 y(s){return te("GET",s)}function k(s,e){return te("POST",s,e)}function tr(s,e){return te("PATCH",s,e)}function We(s,e){return te("DELETE",s,e)}var v=O(()=>{"use strict";E()});function rr(){try{return qe.default.statSync("/.dockerenv"),!0}catch{return!1}}function nr(){try{return qe.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Ge(){return Be===void 0&&(Be=rr()||nr()),Be}var qe,Be,Dt=O(()=>{"use strict";qe=A(require("fs"),1)});function U(){return Je===void 0&&(Je=sr()||Ge()),Je}var jt,Je,sr,Ke=O(()=>{"use strict";jt=A(require("fs"),1);Dt();sr=()=>{try{return jt.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var Ye,Vt,oe,Rt,M,ze=O(()=>{"use strict";Ye=A(require("process"),1),Vt=A(require("os"),1),oe=A(require("fs"),1);Ke();Rt=()=>{if(Ye.default.platform!=="linux")return!1;if(Vt.default.release().toLowerCase().includes("microsoft"))return!U();try{if(oe.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!U()}catch{}return oe.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||oe.default.existsSync("/run/WSL")?!U():!1},M=Ye.default.env.__IS_WSL_TEST__?Rt:Rt()});var Xe,Y,or,ar,Qe,Wt=O(()=>{"use strict";Xe=A(require("process"),1),Y=A(require("fs/promises"),1);ze();ze();or=(()=>{let s="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await Y.default.access(t,Y.constants.F_OK),i=!0}catch{}if(!i)return s;let r=await Y.default.readFile(t,{encoding:"utf8"}),n=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(r);return n?(e=n.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):s}})(),ar=async()=>`${await or()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Qe=async()=>M?ar():`${Xe.default.env.SYSTEMROOT||Xe.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function D(s,e,t){let i=r=>Object.defineProperty(s,e,{value:r,enumerable:!0,writable:!0});return Object.defineProperty(s,e,{configurable:!0,enumerable:!0,get(){let r=t();return i(r),r},set(r){i(r)}}),s}var Ut=O(()=>{"use strict"});async function Ze(){if(qt.default.platform!=="darwin")throw new Error("macOS only");let{stdout:s}=await lr("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(s)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var Bt,qt,Gt,lr,Jt=O(()=>{"use strict";Bt=require("util"),qt=A(require("process"),1),Gt=require("child_process"),lr=(0,Bt.promisify)(Gt.execFile)});async function zt(s,{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:n}=await cr("osascript",["-e",s,i],r);return n.trim()}var Kt,Yt,et,cr,Xt=O(()=>{"use strict";Kt=A(require("process"),1),Yt=require("util"),et=require("child_process"),cr=(0,Yt.promisify)(et.execFile)});async function tt(s){return zt(`tell application "Finder" to set app_path to application file id "${s}" 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 Qt=O(()=>{"use strict";Xt()});async function rt(s=ur){let{stdout:e}=await s("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 it(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:i}=t.groups,r=i.lastIndexOf("."),n=i.lastIndexOf("-"),o=r===-1?void 0:i.slice(0,r),a=n===-1?void 0:i.slice(0,n);return ae[i]??ae[o]??ae[a]??{name:i,id:i}}var Zt,ei,ur,ae,cn,it,ti=O(()=>{"use strict";Zt=require("util"),ei=require("child_process"),ur=(0,Zt.promisify)(ei.execFile),ae={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"}},cn=new Map(Object.entries(ae)),it=class extends Error{}});async function nt(){if(le.default.platform==="darwin"){let s=await Ze();return{name:await tt(s),id:s}}if(le.default.platform==="linux"){let{stdout:s}=await dr("xdg-mime",["query","default","x-scheme-handler/http"]),e=s.trim();return{name:hr(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(le.default.platform==="win32")return rt();throw new Error("Only macOS, Linux, and Windows are supported")}var ii,le,ri,dr,hr,ni=O(()=>{"use strict";ii=require("util"),le=A(require("process"),1),ri=require("child_process");Jt();Qt();ti();dr=(0,ii.promisify)(ri.execFile),hr=s=>s.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var di={};ge(di,{apps:()=>j,default:()=>_r,openApp:()=>gr});async function mr(){let s=await Qe(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=at.Buffer.from(e,"utf16le").toString("base64"),{stdout:i}=await pr(s,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),r=i.trim(),n={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return n[r]?{id:n[r]}:{}}function li(s){if(typeof s=="string"||Array.isArray(s))return s;let{[oi]:e}=s;if(!e)throw new Error(`${oi} is not supported`);return e}function ue({[B]:s},{wsl:e}){if(e&&M)return li(e);if(!s)throw new Error(`${B} is not supported`);return li(s)}var ot,at,lt,ci,ui,ct,ce,wr,pr,st,si,B,oi,ai,z,fr,gr,j,_r,hi=O(()=>{"use strict";ot=A(require("process"),1),at=require("buffer"),lt=A(require("path"),1),ci=require("url"),ui=require("util"),ct=A(require("child_process"),1),ce=A(require("fs/promises"),1);Wt();Ut();ni();Ke();wr={},pr=(0,ui.promisify)(ct.default.execFile),st=lt.default.dirname((0,ci.fileURLToPath)(wr.url)),si=lt.default.join(st,"xdg-open"),{platform:B,arch:oi}=ot.default;ai=async(s,e)=>{let t;for(let i of s)try{return await e(i)}catch(r){t=r}throw t},z=async s=>{if(s={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...s},Array.isArray(s.app))return ai(s.app,a=>z({...s,app:a}));let{name:e,arguments:t=[]}=s.app??{};if(t=[...t],Array.isArray(e))return ai(e,a=>z({...s,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 mr():await nt();if(c.id in a){let u=a[c.id];return e==="browserPrivate"&&t.push(l[u]),z({...s,app:{name:j[u],arguments:t}})}throw new Error(`${c.name} is not supported as a default browser`)}let i,r=[],n={};if(B==="darwin")i="open",s.wait&&r.push("--wait-apps"),s.background&&r.push("--background"),s.newInstance&&r.push("--new"),e&&r.push("-a",e);else if(B==="win32"||M&&!U()&&!e){i=await Qe(),r.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),M||(n.windowsVerbatimArguments=!0);let a=["Start"];s.wait&&a.push("-Wait"),e?(a.push(`"\`"${e}\`""`),s.target&&t.push(s.target)):s.target&&a.push(`"${s.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),a.push("-ArgumentList",t.join(","))),s.target=at.Buffer.from(a.join(" "),"utf16le").toString("base64")}else{if(e)i=e;else{let a=!st||st==="/",l=!1;try{await ce.default.access(si,ce.constants.X_OK),l=!0}catch{}i=ot.default.versions.electron??(B==="android"||a||!l)?"xdg-open":si}t.length>0&&r.push(...t),s.wait||(n.stdio="ignore",n.detached=!0)}B==="darwin"&&t.length>0&&r.push("--args",...t),s.target&&r.push(s.target);let o=ct.default.spawn(i,r,n);return s.wait?new Promise((a,l)=>{o.once("error",l),o.once("close",c=>{if(!s.allowNonzeroExitCode&&c>0){l(new Error(`Exited with code ${c}`));return}a(o)})}):(o.unref(),o)},fr=(s,e)=>{if(typeof s!="string")throw new TypeError("Expected a `target`");return z({...e,target:s})},gr=(s,e)=>{if(typeof s!="string"&&!Array.isArray(s))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:s,arguments:t}})};j={};D(j,"chrome",()=>ue({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"]}}));D(j,"brave",()=>ue({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"]}}));D(j,"firefox",()=>ue({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));D(j,"edge",()=>ue({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));D(j,"browser",()=>"browser");D(j,"browserPrivate",()=>"browserPrivate");_r=fr});var Ot=A(Ct(),1),{program:vr,createCommand:Tr,createArgument:$r,createOption:Ir,CommanderError:Pr,InvalidArgumentError:Hr,InvalidOptionArgumentError:Nr,Command:bt,Argument:Fr,Option:Lr,Help:Mr}=Ot.default;var St=!1,Et=!1;function kt(s,e){St=s,Et=e}function h(){return St?!0:Et?!1:!process.stdout.isTTY}function w(s,e){console.log(JSON.stringify({ok:!0,command:s,data:e}))}function _(s,e,t){console.log(JSON.stringify({ok:!1,command:s,errors:[{code:e,message:t}]}))}function d(s){console.log(s)}function f(s){console.error(s)}function W(s,e=2){if(s.length===0)return"";let t=[];for(let i of s)for(let r=0;r<i.length;r++)t[r]=Math.max(t[r]||0,i[r].length);return s.map(i=>i.map((r,n)=>n<i.length-1?r.padEnd(t[n]+e):r).join("")).join(`
30
+ `)}var se=require("fs"),re=require("path");E();v();var Ue=require("fs"),K=require("path"),ie=require("os"),J=[{id:"claude-code",label:"Claude Code",envVar:"CLAUDE_CODE",dir:".claude",skillsSubdir:"skills",platform:"claude_code"},{id:"cursor",label:"Cursor",envVar:"CURSOR",dir:".cursor",skillsSubdir:"skills",platform:"custom"},{id:"codex",label:"Codex",envVar:"CODEX",dir:".codex",skillsSubdir:"skills",platform:"codex"},{id:"opencode",label:"OpenCode",envVar:"OPENCODE",dir:".opencode",skillsSubdir:"skills",platform:"custom"}];function F(s){if(s){let t=J.find(r=>r.id===s);if(t)return t;let i=J.find(r=>r.dir===`.${s}`||r.dir===s);return i||null}for(let t of J)if(process.env[t.envVar])return t;let e=(0,ie.homedir)();for(let t of J)if((0,Ue.existsSync)((0,K.join)(e,t.dir)))return t;return null}function Nt(){let s=[],e=(0,ie.homedir)();for(let t of J)(process.env[t.envVar]||(0,Ue.existsSync)((0,K.join)(e,t.dir)))&&s.push(t);return s}function L(s,e){return e?(0,K.join)(process.cwd(),s.dir,s.skillsSubdir):(0,K.join)((0,ie.homedir)(),s.dir,s.skillsSubdir)}var Ft=`---
31
31
  title: Skill Manager
32
32
  description: Browse, install, and manage AI skills from the Shared Context library
33
33
  ---
@@ -36,17 +36,31 @@ description: Browse, install, and manage AI skills from the Shared Context libra
36
36
 
37
37
  You have access to the Shared Context skill library \u2014 a curated collection of AI skills you can search, install, and manage via the CLI.
38
38
 
39
- ## When to Use This
39
+ ## IMPORTANT: Search Before Creating
40
40
 
41
- Proactively search for skills when:
41
+ **Before creating any new skill, ALWAYS search this library first.** A proven, community-tested skill is better than one improvised from scratch.
42
42
 
43
- - The user asks **how to do something** you don't have specific expertise in (testing, deployment, code review, etc.)
44
- - The user requests help in a **domain that would benefit from a structured workflow** (debugging, migration, documentation)
45
- - You need **project-specific conventions** (style guides, architecture patterns, team workflows)
46
- - The user asks about **tools, frameworks, or processes** where a community skill likely exists
47
- - You want to **do something well** rather than improvise \u2014 a skill gives you a proven approach
43
+ Search when:
48
44
 
49
- Do **not** search when you already have an installed skill that covers the task, or when the request is straightforward enough that a skill would add no value.
45
+ - The user asks for help in any domain (testing, deployment, debugging, code review, etc.)
46
+ - A structured workflow or best-practice approach would be valuable
47
+ - You want to **do something well** rather than improvise
48
+
49
+ Do **not** search when you already have an installed skill that covers the task, or when the request is trivially simple.
50
+
51
+ ## Quick Reference
52
+
53
+ | Action | Command |
54
+ |--------|---------|
55
+ | Search | \`npx shared-context-ai search "query"\` |
56
+ | Preview | \`npx shared-context-ai preview <installPath>\` |
57
+ | Install | \`npx shared-context-ai install <installPath>\` |
58
+ | List installed | \`npx shared-context-ai list\` |
59
+ | Check updates | \`npx shared-context-ai check\` |
60
+ | Update all | \`npx shared-context-ai update\` |
61
+ | Update one | \`npx shared-context-ai update <slug>\` |
62
+ | Uninstall | \`npx shared-context-ai uninstall <slug>\` |
63
+ | Status | \`npx shared-context-ai status\` |
50
64
 
51
65
  ## How to Search Effectively
52
66
 
@@ -54,99 +68,57 @@ Use specific, descriptive queries. If the first search returns no good matches,
54
68
 
55
69
  \`\`\`bash
56
70
  # Be specific
57
- shared-context-ai search "react component testing"
58
- shared-context-ai search "postgresql query optimization"
71
+ npx shared-context-ai search "react component testing"
72
+ npx shared-context-ai search "postgresql query optimization"
59
73
 
60
74
  # Try alternatives if needed
61
- shared-context-ai search "CI/CD pipeline" # no results?
62
- shared-context-ai search "deployment automation" # try broader terms
63
- shared-context-ai search "github actions" # try the specific tool
75
+ npx shared-context-ai search "CI/CD pipeline" # no results?
76
+ npx shared-context-ai search "deployment automation" # try broader terms
64
77
 
65
78
  # Filter by type or tag
66
- shared-context-ai search "code review" --type skill
67
- shared-context-ai search "deployment" --tag devops
68
- shared-context-ai search "react" --limit 5
79
+ npx shared-context-ai search "code review" --type skill
80
+ npx shared-context-ai search "deployment" --tag devops
69
81
  \`\`\`
70
82
 
71
- **Search flags:** \`--type <type>\` (skill or file), \`--tag <tag>\`, \`--limit <n>\` (default: 20)
83
+ **Flags:** \`--type <type>\` (skill or file), \`--tag <tag>\`, \`--limit <n>\` (default: 20)
84
+
85
+ **JSON output includes \`installPath\`** \u2014 use it directly with \`preview\` and \`install\` commands. No need to construct paths manually.
72
86
 
73
87
  ## How to Present Results
74
88
 
75
89
  After searching, **show the user what you found before installing**. Let them choose.
76
90
 
77
- 1. Run \`shared-context-ai search "query"\` and review the results
91
+ 1. Run \`npx shared-context-ai search "query"\` and review the results
78
92
  2. Pick the 1-3 most relevant matches
79
- 3. Tell the user what you found: the skill name, what it does, and install count (as a quality signal)
80
- 4. If a skill looks right, preview it with \`shared-context-ai preview skills/org/slug\` to confirm
81
- 5. Ask the user if they'd like to install it, or let them pick from options
93
+ 3. Tell the user: the skill name, what it does, and install count (as a quality signal)
94
+ 4. Preview with \`npx shared-context-ai preview <installPath>\` to confirm it fits
95
+ 5. Ask the user if they'd like to install it
82
96
 
83
97
  If no skills match, say so and proceed with your best approach. Don't search repeatedly for the same thing.
84
98
 
85
- ## Quick Reference
99
+ ## Install & Preview Paths
86
100
 
87
- | Action | Command |
88
- |--------|---------|
89
- | Search | \`shared-context-ai search "query"\` |
90
- | Preview | \`shared-context-ai preview skills/org-name/skill-slug\` |
91
- | Install | \`shared-context-ai install skills/org-name/skill-slug\` |
92
- | List installed | \`shared-context-ai list\` |
93
- | Check updates | \`shared-context-ai check\` |
94
- | Update all | \`shared-context-ai update\` |
95
- | Update one | \`shared-context-ai update skill-slug\` |
96
- | Uninstall | \`shared-context-ai uninstall skill-slug\` |
97
- | Status | \`shared-context-ai status\` |
98
-
99
- ## Commands
100
-
101
- ### Search
102
- \`\`\`bash
103
- shared-context-ai search "api testing"
104
- \`\`\`
105
- Returns a table with path, title, stars, and install count.
101
+ The \`installPath\` field from search results is the path to use with \`install\` and \`preview\`:
106
102
 
107
- ### Preview
108
103
  \`\`\`bash
109
- shared-context-ai preview skills/acme/api-testing
104
+ npx shared-context-ai preview skills/acme/api-testing
105
+ npx shared-context-ai install skills/acme/api-testing
110
106
  \`\`\`
111
- Shows full skill content before installing.
112
107
 
113
- ### Install
114
- \`\`\`bash
115
- shared-context-ai install skills/acme/api-testing
116
- \`\`\`
117
- **Flags:** \`--project\` (project-scoped), \`--agent <agent>\` (override detection)
108
+ **Flags:** \`--project\` (project-scoped install), \`--agent <agent>\` (override agent detection)
118
109
 
119
110
  Skills install to your agent's skills directory (e.g., \`~/.claude/skills/\`) and are immediately available.
120
111
 
121
- ### List
122
- \`\`\`bash
123
- shared-context-ai list
124
- \`\`\`
125
- Shows installed skills with update status.
126
-
127
- ### Check for updates
128
- \`\`\`bash
129
- shared-context-ai check
130
- \`\`\`
131
-
132
- ### Update
133
- \`\`\`bash
134
- shared-context-ai update # all
135
- shared-context-ai update api-testing # one skill by slug
136
- \`\`\`
137
- **Flags:** \`--project\`, \`--agent <agent>\`
138
-
139
- ### Uninstall
140
- \`\`\`bash
141
- shared-context-ai uninstall api-testing
142
- \`\`\`
143
- **Flags:** \`--project\`, \`--agent <agent>\`
112
+ ## Other Commands
144
113
 
145
- ### Status
146
114
  \`\`\`bash
147
- shared-context-ai status
115
+ npx shared-context-ai list # List installed skills with update status
116
+ npx shared-context-ai check # Check for available updates
117
+ npx shared-context-ai update # Update all installed skills
118
+ npx shared-context-ai update api-testing # Update one skill by slug
119
+ npx shared-context-ai uninstall api-testing
120
+ npx shared-context-ai status # Auth status, detected agents, install count
148
121
  \`\`\`
149
- Shows auth status, detected agents, and install count.
150
122
 
151
123
  ## Output Modes
152
124
 
@@ -154,17 +126,33 @@ Shows auth status, detected agents, and install count.
154
126
  - **JSON mode** (default when piped, or \`--json\`): Machine-readable envelope
155
127
 
156
128
  \`\`\`json
157
- { "ok": true, "command": "search", "data": { "results": [...], "count": 5 } }
158
- { "ok": false, "command": "install", "errors": [{ "code": "NOT_FOUND", "message": "Resource not found" }] }
129
+ {
130
+ "ok": true,
131
+ "command": "search",
132
+ "data": {
133
+ "results": [
134
+ {
135
+ "id": "abc123",
136
+ "slug": "api-testing",
137
+ "title": "API Testing Guide",
138
+ "resourceType": "skill",
139
+ "orgSlug": "acme",
140
+ "installCount": 42,
141
+ "installPath": "skills/acme/api-testing"
142
+ }
143
+ ],
144
+ "count": 1
145
+ }
146
+ }
159
147
  \`\`\`
160
148
 
161
149
  **Error codes:** \`NOT_FOUND\`, \`AUTH_MISSING\`, \`NO_AGENTS\`, \`SKILL_NOT_FOUND\`, \`WRITE_FAILED\`, \`API_ERROR\`, \`UNEXPECTED\`
162
- `;var ne="skill-manager",Lt="Skill Manager";function ir(s,e){let t=L(s,e),i=(0,re.join)(t,ne);return(0,se.mkdirSync)(i,{recursive:!0}),(0,se.writeFileSync)((0,re.join)(i,"SKILL.md"),Ft,"utf-8"),(0,re.join)(i,"SKILL.md")}function Dt(s){s.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)").option("--project","Install to project directory instead of global").action(async e=>{if(e.code){let{post:n}=await Promise.resolve().then(()=>(v(),Ht)),{saveAuth:o}=await Promise.resolve().then(()=>(k(),Pt)),a=await n("/api/cli/auth",{code:e.code});a.ok||(h()?g("init",a.error.code,a.error.message):f(`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 y()||(h()?(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 t=F(e.agent);t||(h()?g("init","NO_AGENTS","No AI coding agent detected."):f("No AI coding agent detected. Use --agent to specify one (claude-code, cursor, codex, opencode)."),process.exit(1));let i=I();if(i?.token){let n=(await import("os")).hostname(),o=await E("/api/cli/register-agent",{platform:t.platform,name:`CLI (${n})`});!o.ok&&!h()&&f(`Warning: Could not register agent connection: ${o.error.message}`)}let r=ir(t,!!e.project);if(N({resourceId:"skill-manager",slug:ne,title:Lt,sha:"",scope:e.project?"project":"global",agent:t.id,installedAt:new Date().toISOString()}),i?.token)try{let n=`skills/shared-context/${ne}`,o=await A(`/api/cli/resource/${n}`);if(o.ok&&o.data.resource){let a=o.data.resource;a.latestSha&&await E("/api/cli/install",{resourceId:a.id,agentPlatform:t.platform,installedSha:a.latestSha}),N({resourceId:a.id,slug:a.slug||ne,title:a.title||Lt,sha:a.latestSha||"",scope:e.project?"project":"global",agent:t.id,installedAt:new Date().toISOString()})}}catch{}je({detectedAgent:t.id}),h()?w("init",{agent:t.id,skillManagerPath:r,authenticated:y()}):(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 skills/<slug> Install a skill"),u(" shared-context-ai list List installed skills"),u(" shared-context-ai check Check for updates"),u(" shared-context-ai preview skills/<slug> Preview before installing"))})}var pi=require("http"),mi=require("crypto");k();v();k();async function fi(s){let e=await E("/api/cli/auth",{code:s});return e.ok?(De({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()?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):(h()?g("login",e.error.code,e.error.message):f(`Login failed: ${e.error.message}`),!1)}async function yr(){let s=(0,mi.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,pi.createServer)((i,r)=>{let n=new URL(i.url||"/","http://localhost"),o=n.searchParams.get("code"),a=n.searchParams.get("state");if(!o||a!==s){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(),fi(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=`${C().apiBase||"https://sharedcontext.ai"}/cli/login?port=${r}&state=${s}`;h()||(u("Opening browser for authentication..."),u(`If the browser doesn't open, visit: ${o}`));try{let a=(await Promise.resolve().then(()=>(hi(),di))).default;await a(o)}catch{h()||u(`Could not open browser. Please visit:
163
- ${o}`)}setTimeout(()=>{t.close(),h()||f("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function gi(s){s.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 fi(e.code):t=await yr(),process.exit(t?0:1)})}v();function _i(s){s.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}`,n=await A(r);n.ok||(h()?g("search",n.error.code,n.error.message):u(`Search failed: ${n.error.message}`),process.exit(1));let o=n.data.results;if(h()){w("search",{results:o,count:o.length});return}if(o.length===0){let c=t.type?`${t.type}s`:"results";u(`No ${c} found.`);return}let a={skill:"skills",file:"files"};u(`Found ${o.length} result${o.length===1?"":"s"}:
164
- `);let l=o.map(c=>{let d=a[c.resourceType]||c.resourceType+"s";return[c.orgSlug?`${d}/${c.orgSlug}/${c.slug}`:`${d}/${c.slug}`,c.title,`\u2193${c.installCount}`]});u(W(l))})}var de=require("fs"),R=require("path");v();k();function ut(s,e){let t=(0,R.resolve)(s);for(let i of e){let r=(0,R.resolve)((0,R.join)(s,i.path));if(!r.startsWith(t+"/")&&r!==t)throw new Error(`Invalid file path: ${i.path}`);(0,de.mkdirSync)((0,R.dirname)(r),{recursive:!0}),(0,de.writeFileSync)(r,i.content,"utf-8")}}function wi(s){s.command("install <path>").description("Install a skill (e.g., skills/api-testing or 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=C(),r=F(t.agent||i.detectedAgent);r||(h()?g("install","NO_AGENTS","No AI agent detected. Run shared-context-ai init first."):f("No AI agent detected. Run 'shared-context-ai init' first."),process.exit(1));let n=y(),o=n?`/api/cli/resource/${e}`:`/api/public/resource/${e}`,a=await A(o);a.ok||(h()?g("install",a.error.code,a.error.message):f(`Install failed: ${a.error.message}`),process.exit(1));let l=a.data,c=l.resource.slug||l.resource.id,d=L(r,!!t.project),p=(0,R.join)(d,c);try{ut(p,l.files)}catch($){h()?g("install","WRITE_FAILED",`Failed to write files: ${$}`):f(`Failed to write files: ${$}`),process.exit(1)}let _;if(n&&l.resource.latestSha){let $=await E("/api/cli/install",{resourceId:l.resource.id,agentPlatform:r.platform,installedSha:l.resource.latestSha});$.ok||(_=`Could not record install on server: ${$.error.message}`,h()||f(`Warning: ${_}`))}N({resourceId:l.resource.id,slug:c,title:l.resource.title,sha:l.resource.latestSha||"",scope:t.project?"project":"global",agent:r.id,installedAt:new Date().toISOString()}),h()?w("install",{slug:c,title:l.resource.title,path:p,files:l.files.length,..._&&{warning:_}}):(u(`Installed "${l.resource.title}" to ${p}`),u(` ${l.files.length} file${l.files.length===1?"":"s"} written`),n||(u(""),u("Tip: Sign up at sharedcontext.ai to track installations and get updates.")))})}v();k();function yi(s){s.command("list").description("List installed skills").alias("ls").action(async()=>{if(y()){let e=await A("/api/cli/installed");e.ok||(h()?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(h()){w("list",{installations:t,count:t.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:
165
- `);let i=t.map(r=>[r.slug||r.resourceId,r.title,r.hasUpdate?"(update available)":"(current)"]);u(W(i))}else{let t=H().installations;if(h()){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:
166
- `);let i=t.map(r=>[r.slug,r.title,`(${r.agent})`]);u(W(i)),u(`
167
- Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}v();function xi(s){s.command("preview <path>").description("Preview a skill's content (e.g., skills/api-testing)").action(async e=>{let i=y()?`/api/cli/resource/${e}/preview`:`/api/public/resource/${e}/preview`,r=await A(i);r.ok||(h()?g("preview",r.error.code,r.error.message):f(`Preview failed: ${r.error.message}`),process.exit(1)),h()?w("preview",r.data):u(r.data.content)})}v();function Ai(s){s.command("check").description("Check for skill updates").action(async()=>{y()||(h()?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||(h()?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(h()){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:
168
- `);let r=t.map(n=>[n.slug||n.resourceId,n.title,`${n.installedSha.slice(0,7)} \u2192 ${n.latestSha.slice(0,7)}`]);u(W(r)),u(`
169
- Run 'shared-context-ai update' to update all, or 'shared-context-ai update <slug>' to update one.`)})}var Ci=require("path");v();k();function Oi(s){s.command("update [slug]").description("Update installed skills (all or a specific one)").option("--project","Update in project directory").option("--agent <agent>","Override agent detection").action(async(e,t)=>{y()||(h()?g("update","AUTH_MISSING","Login required to update skills."):f("Login required to update skills. Run 'shared-context-ai login'."),process.exit(1));let i=C(),r=F(t.agent||i.detectedAgent);r||(h()?g("update","NO_AGENTS","No AI agent detected."):f("No AI agent detected. Run 'shared-context-ai init' first."),process.exit(1));let n=await A("/api/cli/updates");n.ok||(h()?g("update",n.error.code,n.error.message):f(`Failed to check updates: ${n.error.message}`),process.exit(1));let o=n.data.updates;if(e&&(o=o.filter(l=>l.slug===e||l.resourceId===e),o.length===0)){h()?g("update","SKILL_NOT_FOUND",`No update available for "${e}".`):u(`No update available for "${e}".`);return}if(o.length===0){h()?w("update",{updated:[],count:0}):u("All skills are up to date.");return}let a=[];for(let l of o){let c=l.slug||l.resourceId,d=l.orgSlug?`skills/${l.orgSlug}/${c}`:`skills/${c}`,p=await A(`/api/cli/resource/${d}`);if(!p.ok){h()||f(` Failed to fetch ${c}: ${p.error.message}`);continue}let _=p.data,$=L(r,!!t.project),me=(0,Ci.join)($,c);ut(me,_.files),_.resource.latestSha&&await E("/api/cli/update",{resourceId:_.resource.id,installedSha:_.resource.latestSha}),N({resourceId:_.resource.id,slug:c,title:_.resource.title,sha:_.resource.latestSha||"",scope:t.project?"project":"global",agent:r.id,installedAt:new Date().toISOString()}),a.push({slug:c,title:_.resource.title}),h()||u(` Updated ${c}`)}h()?w("update",{updated:a,count:a.length}):a.length>0&&u(`
170
- ${a.length} skill${a.length===1?"":"s"} updated.`)})}var he=require("fs"),bi=require("path");v();k();function Si(s){s.command("uninstall <slug>").description("Uninstall a skill").option("--project","Uninstall from project directory").option("--agent <agent>","Override agent detection").action(async(e,t)=>{let i=C(),r=F(t.agent||i.detectedAgent);r||(h()?g("uninstall","NO_AGENTS","No AI agent detected."):f("No AI agent detected. Run 'shared-context-ai init' first."),process.exit(1));let o=H().installations.find(c=>c.slug===e||c.resourceId===e),a=L(r,!!t.project),l=(0,bi.join)(a,e);if((0,he.existsSync)(l)&&(0,he.rmSync)(l,{recursive:!0,force:!0}),y()&&o){let c=await E("/api/cli/uninstall",{resourceId:o.resourceId});!c.ok&&!h()&&f(`Warning: Could not record uninstall on server: ${c.error.message}`)}o&&Ve(o.resourceId),h()?w("uninstall",{slug:e,removed:!0}):u(`Uninstalled "${e}"`)})}k();function ki(s){s.command("status").description("Show CLI status: auth, agents, installed skill counts").action(async()=>{let e=I(),t=C(),i=H(),r=Nt(),n={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:r.map(o=>o.id),configuredAgent:t.detectedAgent||null,installedCount:i.installations.length};if(h()){w("status",n);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"),t.detectedAgent&&u(` Active: ${t.detectedAgent}`),u(` Skills: ${i.installations.length} installed`)})}k();v();function Ei(s){s.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=I();e.revoke&&y()&&await We("/api/cli/auth"),Me(),h()?w("logout",{email:t?.email||null}):u("Logged out.")})}var vi={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."},pe=class extends Error{constructor(t,i){super(i||vi[t]);this.code=t;this.name="CliError"}get recovery(){return vi[this.code]}};var b=new bt;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",s=>{let e=s.opts();Et(!!e.json,!!e.human)});Dt(b);gi(b);_i(b);wi(b);yi(b);xi(b);Ai(b);Oi(b);Si(b);ki(b);Ei(b);process.on("uncaughtException",s=>{s instanceof pe?h()?g(process.argv[2]||"unknown",s.code,s.message):(f(`Error: ${s.message}`),f(s.recovery)):h()?g(process.argv[2]||"unknown","UNEXPECTED",s.message||"Unexpected error"):f(`Error: ${s.message||s}`),process.exit(1)});b.parse();
150
+ `;var ne="skill-manager",Lt="Skill Manager";function ir(s,e){let t=L(s,e),i=(0,re.join)(t,ne);return(0,se.mkdirSync)(i,{recursive:!0}),(0,se.writeFileSync)((0,re.join)(i,"SKILL.md"),Ft,"utf-8"),(0,re.join)(i,"SKILL.md")}function Mt(s){s.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)").option("--project","Install to project directory instead of global").action(async e=>{if(e.code){let{post:n}=await Promise.resolve().then(()=>(v(),Ht)),{saveAuth:o}=await Promise.resolve().then(()=>(E(),Pt)),a=await n("/api/cli/auth",{code:e.code});a.ok||(h()?_("init",a.error.code,a.error.message):f(`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()||d(`Authenticated as ${a.data.user.email}`)}else x()||(h()?(_("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 t=F(e.agent);t||(h()?_("init","NO_AGENTS","No AI coding agent detected."):f("No AI coding agent detected. Use --agent to specify one (claude-code, cursor, codex, opencode)."),process.exit(1));let i=I();if(i?.token){let n=(await import("os")).hostname(),o=await k("/api/cli/register-agent",{platform:t.platform,name:`CLI (${n})`});!o.ok&&!h()&&f(`Warning: Could not register agent connection: ${o.error.message}`)}let r=ir(t,!!e.project);if(N({resourceId:"skill-manager",slug:ne,title:Lt,sha:"",scope:e.project?"project":"global",agent:t.id,installedAt:new Date().toISOString()}),i?.token)try{let n=`skills/shared-context/${ne}`,o=await y(`/api/cli/resource/${n}`);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}),N({resourceId:a.id,slug:a.slug||ne,title:a.title||Lt,sha:a.latestSha||"",scope:e.project?"project":"global",agent:t.id,installedAt:new Date().toISOString()})}}catch{}je({detectedAgent:t.id}),h()?w("init",{agent:t.id,skillManagerPath:r,authenticated:x()}):(d(""),d(`Shared Context initialized for ${t.label}`),d(`Skill Manager installed to: ${r}`),d(""),d("Quick reference:"),d(' shared-context-ai search "query" Search for skills'),d(" shared-context-ai install skills/<slug> Install a skill"),d(" shared-context-ai list List installed skills"),d(" shared-context-ai check Check for updates"),d(" shared-context-ai preview skills/<slug> Preview before installing"))})}var pi=require("http"),mi=require("crypto");E();v();E();async function fi(s){let e=await k("/api/cli/auth",{code:s});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()?w("login",{email:e.data.user.email,org:e.data.org.slug}):d(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(h()?_("login",e.error.code,e.error.message):f(`Login failed: ${e.error.message}`),!1)}async function xr(){let s=(0,mi.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,pi.createServer)((i,r)=>{let n=new URL(i.url||"/","http://localhost"),o=n.searchParams.get("code"),a=n.searchParams.get("state");if(!o||a!==s){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(),fi(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=`${C().apiBase||"https://sharedcontext.ai"}/cli/login?port=${r}&state=${s}`;h()||(d("Opening browser for authentication..."),d(`If the browser doesn't open, visit: ${o}`));try{let a=(await Promise.resolve().then(()=>(hi(),di))).default;await a(o)}catch{h()||d(`Could not open browser. Please visit:
151
+ ${o}`)}setTimeout(()=>{t.close(),h()||f("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function gi(s){s.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 fi(e.code):t=await xr(),process.exit(t?0:1)})}v();function _i(s){s.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=x()?`/api/cli/search?${i}`:`/api/public/search?${i}`,n=await y(r);n.ok||(h()?_("search",n.error.code,n.error.message):d(`Search failed: ${n.error.message}`),process.exit(1));let o=n.data.results,a={skill:"skills",file:"files"};if(h()){let c=o.map(u=>{let p=a[u.resourceType]||u.resourceType+"s",g=u.orgSlug?`${p}/${u.orgSlug}/${u.slug}`:`${p}/${u.slug}`;return{...u,installPath:g}});w("search",{results:c,count:c.length});return}if(o.length===0){let c=t.type?`${t.type}s`:"results";d(`No ${c} found.`);return}d(`Found ${o.length} result${o.length===1?"":"s"}:
152
+ `);let l=o.map(c=>{let u=a[c.resourceType]||c.resourceType+"s";return[c.orgSlug?`${u}/${c.orgSlug}/${c.slug}`:`${u}/${c.slug}`,c.title,`\u2193${c.installCount}`]});d(W(l))})}var de=require("fs"),R=require("path");v();E();function ut(s,e){let t=(0,R.resolve)(s);for(let i of e){let r=(0,R.resolve)((0,R.join)(s,i.path));if(!r.startsWith(t+"/")&&r!==t)throw new Error(`Invalid file path: ${i.path}`);(0,de.mkdirSync)((0,R.dirname)(r),{recursive:!0}),(0,de.writeFileSync)(r,i.content,"utf-8")}}function wi(s){s.command("install <path>").description("Install a skill (e.g., skills/api-testing or 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=C(),r=F(t.agent||i.detectedAgent);r||(h()?_("install","NO_AGENTS","No AI agent detected. Run shared-context-ai init first."):f("No AI agent detected. Run 'shared-context-ai init' first."),process.exit(1));let n=x(),o=n?`/api/cli/resource/${e}`:`/api/public/resource/${e}`,a=await y(o);a.ok||(h()?_("install",a.error.code,a.error.message):f(`Install failed: ${a.error.message}`),process.exit(1));let l=a.data,c=l.resource.slug||l.resource.id,u=L(r,!!t.project),p=(0,R.join)(u,c);try{ut(p,l.files)}catch($){h()?_("install","WRITE_FAILED",`Failed to write files: ${$}`):f(`Failed to write files: ${$}`),process.exit(1)}let g;if(n&&l.resource.latestSha){let $=await k("/api/cli/install",{resourceId:l.resource.id,agentPlatform:r.platform,installedSha:l.resource.latestSha});$.ok||(g=`Could not record install on server: ${$.error.message}`,h()||f(`Warning: ${g}`))}N({resourceId:l.resource.id,slug:c,title:l.resource.title,sha:l.resource.latestSha||"",scope:t.project?"project":"global",agent:r.id,installedAt:new Date().toISOString()}),h()?w("install",{slug:c,title:l.resource.title,path:p,files:l.files.length,...g&&{warning:g}}):(d(`Installed "${l.resource.title}" to ${p}`),d(` ${l.files.length} file${l.files.length===1?"":"s"} written`),n||(d(""),d("Tip: Sign up at sharedcontext.ai to track installations and get updates.")))})}v();E();function xi(s){s.command("list").description("List installed skills").alias("ls").action(async()=>{if(x()){let e=await y("/api/cli/installed");e.ok||(h()?_("list",e.error.code,e.error.message):d(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(h()){w("list",{installations:t,count:t.length});return}if(t.length===0){d("No skills installed."),d("Use 'shared-context-ai search' to find skills to install.");return}d(`${t.length} skill${t.length===1?"":"s"} installed:
153
+ `);let i=t.map(r=>[r.slug||r.resourceId,r.title,r.hasUpdate?"(update available)":"(current)"]);d(W(i))}else{let t=H().installations;if(h()){w("list",{installations:t,count:t.length});return}if(t.length===0){d("No skills installed locally.");return}d(`${t.length} skill${t.length===1?"":"s"} installed locally:
154
+ `);let i=t.map(r=>[r.slug,r.title,`(${r.agent})`]);d(W(i)),d(`
155
+ Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}v();function Ai(s){s.command("preview <path>").description("Preview a skill's content (e.g., skills/api-testing)").action(async e=>{let i=x()?`/api/cli/resource/${e}/preview`:`/api/public/resource/${e}/preview`,r=await y(i);r.ok||(h()?_("preview",r.error.code,r.error.message):f(`Preview failed: ${r.error.message}`),process.exit(1)),h()?w("preview",r.data):d(r.data.content)})}v();function yi(s){s.command("check").description("Check for skill updates").action(async()=>{x()||(h()?_("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 y("/api/cli/updates");e.ok||(h()?_("check",e.error.code,e.error.message):f(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:i}=e.data;if(h()){w("check",{updates:t,count:i});return}if(i===0){d("All skills are up to date.");return}d(`${i} update${i===1?"":"s"} available:
156
+ `);let r=t.map(n=>[n.slug||n.resourceId,n.title,`${n.installedSha.slice(0,7)} \u2192 ${n.latestSha.slice(0,7)}`]);d(W(r)),d(`
157
+ Run 'shared-context-ai update' to update all, or 'shared-context-ai update <slug>' to update one.`)})}var Ci=require("path");v();E();function Oi(s){s.command("update [slug]").description("Update installed skills (all or a specific one)").option("--project","Update in project directory").option("--agent <agent>","Override agent detection").action(async(e,t)=>{x()||(h()?_("update","AUTH_MISSING","Login required to update skills."):f("Login required to update skills. Run 'shared-context-ai login'."),process.exit(1));let i=C(),r=F(t.agent||i.detectedAgent);r||(h()?_("update","NO_AGENTS","No AI agent detected."):f("No AI agent detected. Run 'shared-context-ai init' first."),process.exit(1));let n=await y("/api/cli/updates");n.ok||(h()?_("update",n.error.code,n.error.message):f(`Failed to check updates: ${n.error.message}`),process.exit(1));let o=n.data.updates;if(e&&(o=o.filter(l=>l.slug===e||l.resourceId===e),o.length===0)){h()?_("update","SKILL_NOT_FOUND",`No update available for "${e}".`):d(`No update available for "${e}".`);return}if(o.length===0){h()?w("update",{updated:[],count:0}):d("All skills are up to date.");return}let a=[];for(let l of o){let c=l.slug||l.resourceId,u=l.orgSlug?`skills/${l.orgSlug}/${c}`:`skills/${c}`,p=await y(`/api/cli/resource/${u}`);if(!p.ok){h()||f(` Failed to fetch ${c}: ${p.error.message}`);continue}let g=p.data,$=L(r,!!t.project),me=(0,Ci.join)($,c);ut(me,g.files),g.resource.latestSha&&await k("/api/cli/update",{resourceId:g.resource.id,installedSha:g.resource.latestSha}),N({resourceId:g.resource.id,slug:c,title:g.resource.title,sha:g.resource.latestSha||"",scope:t.project?"project":"global",agent:r.id,installedAt:new Date().toISOString()}),a.push({slug:c,title:g.resource.title}),h()||d(` Updated ${c}`)}h()?w("update",{updated:a,count:a.length}):a.length>0&&d(`
158
+ ${a.length} skill${a.length===1?"":"s"} updated.`)})}var he=require("fs"),bi=require("path");v();E();function Si(s){s.command("uninstall <slug>").description("Uninstall a skill").option("--project","Uninstall from project directory").option("--agent <agent>","Override agent detection").action(async(e,t)=>{let i=C(),r=F(t.agent||i.detectedAgent);r||(h()?_("uninstall","NO_AGENTS","No AI agent detected."):f("No AI agent detected. Run 'shared-context-ai init' first."),process.exit(1));let o=H().installations.find(c=>c.slug===e||c.resourceId===e),a=L(r,!!t.project),l=(0,bi.join)(a,e);if((0,he.existsSync)(l)&&(0,he.rmSync)(l,{recursive:!0,force:!0}),x()&&o){let c=await k("/api/cli/uninstall",{resourceId:o.resourceId});!c.ok&&!h()&&f(`Warning: Could not record uninstall on server: ${c.error.message}`)}o&&Ve(o.resourceId),h()?w("uninstall",{slug:e,removed:!0}):d(`Uninstalled "${e}"`)})}E();function Ei(s){s.command("status").description("Show CLI status: auth, agents, installed skill counts").action(async()=>{let e=I(),t=C(),i=H(),r=Nt(),n={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:r.map(o=>o.id),configuredAgent:t.detectedAgent||null,installedCount:i.installations.length};if(h()){w("status",n);return}d("Shared Context CLI Status"),d("\u2500".repeat(30)),e?.token?d(` Auth: ${e.email} (${e.orgSlug})`):d(" Auth: Not logged in"),d(` API: ${t.apiBase}`),r.length>0?d(` Agents: ${r.map(o=>o.label).join(", ")}`):d(" Agents: None detected"),t.detectedAgent&&d(` Active: ${t.detectedAgent}`),d(` Skills: ${i.installations.length} installed`)})}E();v();function ki(s){s.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=I();e.revoke&&x()&&await We("/api/cli/auth"),De(),h()?w("logout",{email:t?.email||null}):d("Logged out.")})}var vi={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."},pe=class extends Error{constructor(t,i){super(i||vi[t]);this.code=t;this.name="CliError"}get recovery(){return vi[this.code]}};var b=new bt;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",s=>{let e=s.opts();kt(!!e.json,!!e.human)});Mt(b);gi(b);_i(b);wi(b);xi(b);Ai(b);yi(b);Oi(b);Si(b);Ei(b);ki(b);process.on("uncaughtException",s=>{s instanceof pe?h()?_(process.argv[2]||"unknown",s.code,s.message):(f(`Error: ${s.message}`),f(s.recovery)):h()?_(process.argv[2]||"unknown","UNEXPECTED",s.message||"Unexpected error"):f(`Error: ${s.message||s}`),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.1",
3
+ "version": "0.1.2",
4
4
  "description": "CLI for Shared Context - search, install, and manage AI skills",
5
5
  "bin": {
6
6
  "shared-context-ai": "dist/index.js"