shared-context-ai 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +99 -0
- package/package.json +29 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";var $i=Object.create;var ge=Object.defineProperty;var Ti=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 M=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),_e=(s,e)=>{for(var t in e)ge(s,t,{get:e[t],enumerable:!0})},Fi=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ii(e))!Hi.call(s,r)&&r!==t&&ge(s,r,{get:()=>e[r],enumerable:!(i=Ti(e,r))||i.enumerable});return s};var A=(s,e,t)=>(t=s!=null?$i(Pi(s)):{},Fi(e||!s||!s.__esModule?ge(t,"default",{value:s,enumerable:!0}):t,s));var W=M(we=>{"use strict";var Q=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}},Ce=class extends Q{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};we.CommanderError=Q;we.InvalidArgumentError=Ce});var Z=M(xe=>{"use strict";var{InvalidArgumentError:Ni}=W(),Ae=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 Ni(`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 ji(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}xe.Argument=Ae;xe.humanReadableArgName=ji});var be=M(Oe=>{"use strict";var{humanReadableArgName:Di}=Z(),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=>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(m,_){return t.formatItem(m,i,_,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],l=t.commandDescription(e);l.length>0&&(o=o.concat([t.boxWrap(t.styleCommandDescription(l),r),""]));let a=t.visibleArguments(e).map(m=>n(t.styleArgumentTerm(t.argumentTerm(m)),t.styleArgumentDescription(t.argumentDescription(m))));a.length>0&&(o=o.concat([t.styleTitle("Arguments:"),...a,""]));let c=t.visibleOptions(e).map(m=>n(t.styleOptionTerm(t.optionTerm(m)),t.styleOptionDescription(t.optionDescription(m))));if(c.length>0&&(o=o.concat([t.styleTitle("Options:"),...c,""])),t.showGlobalOptions){let m=t.visibleGlobalOptions(e).map(_=>n(t.styleOptionTerm(t.optionTerm(_)),t.styleOptionDescription(t.optionDescription(_))));m.length>0&&(o=o.concat([t.styleTitle("Global Options:"),...m,""]))}let p=t.visibleCommands(e).map(m=>n(t.styleSubcommandTerm(t.subcommandTerm(m)),t.styleSubcommandDescription(t.subcommandDescription(m))));return p.length>0&&(o=o.concat([t.styleTitle("Commands:"),...p,""])),o.join(`
|
|
3
|
+
`)}displayWidth(e){return mt(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,i,r){let o=" ".repeat(2);if(!i)return o+e;let l=e.padEnd(t+e.length-r.displayWidth(e)),a=2,p=(this.helpWidth??80)-t-a-2,m;return p<this.minWidthToWrap||r.preformatted(i)?m=i:m=r.boxWrap(i,p).replace(/\n/g,`
|
|
4
|
+
`+" ".repeat(t+a)),o+l+" ".repeat(a)+m.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 l=o.match(r);if(l===null){n.push("");return}let a=[l.shift()],c=this.displayWidth(a[0]);l.forEach(p=>{let m=this.displayWidth(p);if(c+m<=t){a.push(p),c+=m;return}n.push(a.join(""));let _=p.trimStart();a=[_],c=this.displayWidth(_)}),n.push(a.join(""))}),n.join(`
|
|
6
|
+
`)}};function mt(s){let e=/\x1b\[\d*(;\d*)*m/g;return s.replace(e,"")}Oe.Help=ye;Oe.stripColor=mt});var ve=M(ke=>{"use strict";var{InvalidArgumentError:Mi}=W(),Se=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=Vi(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}},Ee=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let r=this.negativeOptions.get(i).presetArg,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 Vi(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],l=`option creation failed due to '${o}' in option flags '${s}'`;throw/^-[^-][^-]/.test(o)?new Error(`${l}
|
|
7
|
+
- a short flag is a single dash and a single character
|
|
8
|
+
- either use a single dash and a single character (for a short flag)
|
|
9
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(o)?new Error(`${l}
|
|
10
|
+
- too many short flags`):r.test(o)?new Error(`${l}
|
|
11
|
+
- too many long flags`):new Error(`${l}
|
|
12
|
+
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${s}'.`);return{shortFlag:e,longFlag:t}}ke.Option=Se;ke.DualOptions=Ee});var gt=M(ft=>{"use strict";function Li(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 Ri(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 l=Li(s,o),a=Math.max(s.length,o.length);(a-l)/a>n&&(l<r?(r=l,i=[o]):l===r&&i.push(o))}),i.sort((o,l)=>o.localeCompare(l)),t&&(i=i.map(o=>`--${o}`)),i.length>1?`
|
|
13
|
+
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
14
|
+
(Did you mean ${i[0]}?)`:""}ft.suggestSimilar=Ri});var At=M(He=>{"use strict";var Wi=require("events").EventEmitter,$e=require("child_process"),I=require("path"),ee=require("fs"),h=require("process"),{Argument:Ui,humanReadableArgName:Bi}=Z(),{CommanderError:Te}=W(),{Help:qi,stripColor:Gi}=be(),{Option:_t,DualOptions:Ji}=ve(),{suggestSimilar:Ct}=gt(),Ie=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=>h.stdout.write(t),writeErr:t=>h.stderr.write(t),outputError:(t,i)=>i(t),getOutHelpWidth:()=>h.stdout.isTTY?h.stdout.columns:void 0,getErrHelpWidth:()=>h.stderr.isTTY?h.stderr.columns:void 0,getOutHasColors:()=>Pe()??(h.stdout.isTTY&&h.stdout.hasColors?.()),getErrHasColors:()=>Pe()??(h.stderr.isTTY&&h.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,l]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return r&&(a.description(r),a._executableHandler=!0),n.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(n.noHelp||n.hidden),a._executableFile=n.executableFile||null,l&&a.arguments(l),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),r?this:a}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
|
+
- 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
|
+
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)),h.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 _t(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,l)=>{n==null&&e.presetArg!==void 0&&(n=e.presetArg);let a=this.getOptionValue(i);n!==null&&e.parseArg?n=this._callParseArg(e,n,a,o):n!==null&&e.variadic&&(n=e._concatValue(n,a)),n==null&&(e.negate?n=!1:e.isBoolean()||e.optional?n=!0:n=""),this.setOptionValueWithSource(i,n,l)};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 _t)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,i);if(o.makeOptionMandatory(!!e.mandatory),typeof r=="function")o.default(n).argParser(r);else if(r instanceof RegExp){let l=r;r=(a,c)=>{let p=l.exec(a);return p?p[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){h.versions?.electron&&(t.from="electron");let r=h.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=h.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":h.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(e,t){this._prepareForParse();let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){this._prepareForParse();let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
18
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,i){if(ee.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
|
+
- if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
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(p,m){let _=I.resolve(p,m);if(ee.existsSync(_))return _;if(r.includes(I.extname(m)))return;let X=r.find(fe=>ee.existsSync(`${_}${fe}`));if(X)return`${_}${X}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let p;try{p=ee.realpathSync(this._scriptPath)}catch{p=this._scriptPath}l=I.resolve(I.dirname(p),l)}if(l){let p=n(l,o);if(!p&&!e._executableFile&&this._scriptPath){let m=I.basename(this._scriptPath,I.extname(this._scriptPath));m!==this._name&&(p=n(l,`${m}-${e._name}`))}o=p||o}i=r.includes(I.extname(o));let a;h.platform!=="win32"?i?(t.unshift(o),t=wt(h.execArgv).concat(t),a=$e.spawn(h.argv[0],t,{stdio:"inherit"})):a=$e.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,l,e._name),t.unshift(o),t=wt(h.execArgv).concat(t),a=$e.spawn(h.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(m=>{h.on(m,()=>{a.killed===!1&&a.exitCode===null&&a.kill(m)})});let c=this._exitCallback;a.on("close",p=>{p=p??1,c?c(new Te(p,"commander.executeSubCommandAsync","(close)")):h.exit(p)}),a.on("error",p=>{if(p.code==="ENOENT")this._checkForMissingExecutable(o,l,e._name);else if(p.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)h.exit(1);else{let m=new Te(1,"commander.executeSubCommandAsync","(error)");m.nestedError=p,c(m)}}),this.runningCommand=a}_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 l=`error: command-argument value '${r}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,r,n,l)}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,l)=>e(i,l,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(a){return a.length>1&&a[0]==="-"}let l=null;for(;n.length;){let a=n.shift();if(a==="--"){r===i&&r.push(a),r.push(...n);break}if(l&&!o(a)){this.emit(`option:${l.name()}`,a);continue}if(l=null,o(a)){let c=this._findOption(a);if(c){if(c.required){let p=n.shift();p===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,p)}else if(c.optional){let p=null;n.length>0&&!o(n[0])&&(p=n.shift()),this.emit(`option:${c.name()}`,p)}else this.emit(`option:${c.name()}`);l=c.variadic?c:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let c=this._findOption(`-${a[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,a.slice(2)):(this.emit(`option:${c.name()}`),n.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let c=a.indexOf("="),p=this._findOption(a.slice(0,c));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,a.slice(c+1));continue}}if(o(a)&&(r=i),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(a)){t.push(a),n.length>0&&i.push(...n);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),n.length>0&&t.push(...n);break}else if(this._defaultCommandName){i.push(a),n.length>0&&i.push(...n);break}}if(this._passThroughOptions){r.push(a),n.length>0&&r.push(...n);break}r.push(a)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let r=this.options[i].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
22
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
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 h.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()}`,h.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 l=o.attributeName(),a=this.getOptionValue(l),c=this.options.find(m=>m.negate&&l===m.attributeName()),p=this.options.find(m=>!m.negate&&l===m.attributeName());return c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg)?c:p||o},r=o=>{let l=i(o),a=l.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${l.envVar}'`:`option '${l.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(l=>l.long).map(l=>l.long);r=r.concat(o),n=n.parent}while(n&&!n._enablePositionalOptions);t=Ct(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=Ct(e,r)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let r=this.createOption(t,i);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
25
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let r=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(i=>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=I.basename(e,I.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),i=this._getOutputContext(e);t.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let r=t.formatHelp(this,t);return i.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,i,r,n;return t?(i=l=>this._outputConfiguration.writeErr(l),r=this._outputConfiguration.getErrHasColors(),n=this._outputConfiguration.getErrHelpWidth()):(i=l=>this._outputConfiguration.writeOut(l),r=this._outputConfiguration.getOutHasColors(),n=this._outputConfiguration.getOutHelpWidth()),{error:t,write:l=>(r||(l=this._outputConfiguration.stripColor(l)),i(l)),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(h.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
|
+
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 wt(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 Pe(){if(h.env.NO_COLOR||h.env.FORCE_COLOR==="0"||h.env.FORCE_COLOR==="false")return!1;if(h.env.FORCE_COLOR||h.env.CLICOLOR_FORCE!==void 0)return!0}He.Command=Ie;He.useColor=Pe});var bt=M(S=>{"use strict";var{Argument:xt}=Z(),{Command:Fe}=At(),{CommanderError:Ki,InvalidArgumentError:yt}=W(),{Help:zi}=be(),{Option:Ot}=ve();S.program=new Fe;S.createCommand=s=>new Fe(s);S.createOption=(s,e)=>new Ot(s,e);S.createArgument=(s,e)=>new xt(s,e);S.Command=Fe;S.Option=Ot;S.Argument=xt;S.Help=zi;S.CommanderError=Ki;S.InvalidArgumentError=yt;S.InvalidOptionArgumentError=yt});var Ft={};_e(Ft,{addToManifest:()=>B,clearAuth:()=>Ve,getAuth:()=>T,getConfig:()=>x,getManifest:()=>P,removeFromManifest:()=>We,saveAuth:()=>Me,saveConfig:()=>Ht,saveManifest:()=>Re,updateConfig:()=>Le});function Yi(){(0,v.mkdirSync)(te,{recursive:!0})}function je(s,e){try{return(0,v.existsSync)(s)?JSON.parse((0,v.readFileSync)(s,"utf-8")):e}catch{return e}}function De(s,e,t=!1){if(Yi(),(0,v.writeFileSync)(s,JSON.stringify(e,null,2)+`
|
|
28
|
+
`,"utf-8"),t)try{(0,v.chmodSync)(s,384)}catch{}}function T(){return je(Ne,null)}function Me(s){De(Ne,s,!0)}function Ve(){try{(0,v.writeFileSync)(Ne,"{}","utf-8")}catch{}}function x(){return je(It,Xi)}function Ht(s){De(It,s)}function Le(s){let e=x();Ht({...e,...s})}function P(){return je(Pt,Qi)}function Re(s){De(Pt,s)}function B(s){let e=P(),t=e.installations.findIndex(i=>i.resourceId===s.resourceId);t>=0?e.installations[t]=s:e.installations.push(s),Re(e)}function We(s){let e=P();e.installations=e.installations.filter(t=>t.resourceId!==s),Re(e)}var v,U,Tt,te,Ne,It,Pt,Xi,Qi,E=O(()=>{"use strict";v=require("fs"),U=require("path"),Tt=require("os"),te=(0,U.join)((0,Tt.homedir)(),".config","shared-context"),Ne=(0,U.join)(te,"auth.json"),It=(0,U.join)(te,"config.json"),Pt=(0,U.join)(te,"manifest.json");Xi={apiBase:"https://app.sharedcontext.ai"};Qi={installations:[]}});var Nt={};_e(Nt,{del:()=>Ue,get:()=>y,isAuthenticated:()=>w,patch:()=>tr,post:()=>$});function Zi(){return x().apiBase||"https://app.sharedcontext.ai"}function er(){let s={"Content-Type":"application/json"},e=T();return e?.token&&(s.Authorization=`Bearer ${e.token}`),s}function w(){return!!T()?.token}async function ie(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=await r.json();return r.ok?{ok:!0,data:n.data??n}:{ok:!1,error:{code:n?.error?.code||`HTTP_${r.status}`,message:n?.error?.message||n?.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 ie("GET",s)}function $(s,e){return ie("POST",s,e)}function tr(s,e){return ie("PATCH",s,e)}function Ue(s,e){return ie("DELETE",s,e)}var k=O(()=>{"use strict";E()});function rr(){try{return Ge.default.statSync("/.dockerenv"),!0}catch{return!1}}function nr(){try{return Ge.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Je(){return qe===void 0&&(qe=rr()||nr()),qe}var Ge,qe,Vt=O(()=>{"use strict";Ge=A(require("fs"),1)});function L(){return Ke===void 0&&(Ke=sr()||Je()),Ke}var Lt,Ke,sr,ze=O(()=>{"use strict";Lt=A(require("fs"),1);Vt();sr=()=>{try{return Lt.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var Ye,Wt,oe,Rt,N,Xe=O(()=>{"use strict";Ye=A(require("process"),1),Wt=A(require("os"),1),oe=A(require("fs"),1);ze();Rt=()=>{if(Ye.default.platform!=="linux")return!1;if(Wt.default.release().toLowerCase().includes("microsoft"))return!L();try{if(oe.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!L()}catch{}return oe.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||oe.default.existsSync("/run/WSL")?!L():!1},N=Ye.default.env.__IS_WSL_TEST__?Rt:Rt()});var Qe,J,or,ar,Ze,Ut=O(()=>{"use strict";Qe=A(require("process"),1),J=A(require("fs/promises"),1);Xe();Xe();or=(()=>{let s="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await J.default.access(t,J.constants.F_OK),i=!0}catch{}if(!i)return s;let r=await J.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`,Ze=async()=>N?ar():`${Qe.default.env.SYSTEMROOT||Qe.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function j(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 Bt=O(()=>{"use strict"});async function et(){if(Gt.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 qt,Gt,Jt,lr,Kt=O(()=>{"use strict";qt=require("util"),Gt=A(require("process"),1),Jt=require("child_process"),lr=(0,qt.promisify)(Jt.execFile)});async function Xt(s,{humanReadableOutput:e=!0,signal:t}={}){if(zt.default.platform!=="darwin")throw new Error("macOS only");let i=e?[]:["-ss"],r={};t&&(r.signal=t);let{stdout:n}=await cr("osascript",["-e",s,i],r);return n.trim()}var zt,Yt,tt,cr,Qt=O(()=>{"use strict";zt=A(require("process"),1),Yt=require("util"),tt=require("child_process"),cr=(0,Yt.promisify)(tt.execFile)});async function it(s){return Xt(`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 Zt=O(()=>{"use strict";Qt()});async function nt(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 rt(`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),l=n===-1?void 0:i.slice(0,n);return ae[i]??ae[o]??ae[l]??{name:i,id:i}}var ei,ti,ur,ae,dn,rt,ii=O(()=>{"use strict";ei=require("util"),ti=require("child_process"),ur=(0,ei.promisify)(ti.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"}},dn=new Map(Object.entries(ae)),rt=class extends Error{}});async function st(){if(le.default.platform==="darwin"){let s=await et();return{name:await it(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:pr(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(le.default.platform==="win32")return nt();throw new Error("Only macOS, Linux, and Windows are supported")}var ri,le,ni,dr,pr,si=O(()=>{"use strict";ri=require("util"),le=A(require("process"),1),ni=require("child_process");Kt();Zt();ii();dr=(0,ri.promisify)(ni.execFile),pr=s=>s.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var pi={};_e(pi,{apps:()=>D,default:()=>_r,openApp:()=>gr});async function hr(){let s=await Ze(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=lt.Buffer.from(e,"utf16le").toString("base64"),{stdout:i}=await mr(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 ci(s){if(typeof s=="string"||Array.isArray(s))return s;let{[ai]:e}=s;if(!e)throw new Error(`${ai} is not supported`);return e}function ue({[R]:s},{wsl:e}){if(e&&N)return ci(e);if(!s)throw new Error(`${R} is not supported`);return ci(s)}var at,lt,ct,ui,di,ut,ce,Cr,mr,ot,oi,R,ai,li,K,fr,gr,D,_r,mi=O(()=>{"use strict";at=A(require("process"),1),lt=require("buffer"),ct=A(require("path"),1),ui=require("url"),di=require("util"),ut=A(require("child_process"),1),ce=A(require("fs/promises"),1);Ut();Bt();si();ze();Cr={},mr=(0,di.promisify)(ut.default.execFile),ot=ct.default.dirname((0,ui.fileURLToPath)(Cr.url)),oi=ct.default.join(ot,"xdg-open"),{platform:R,arch:ai}=at.default;li=async(s,e)=>{let t;for(let i of s)try{return await e(i)}catch(r){t=r}throw t},K=async s=>{if(s={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...s},Array.isArray(s.app))return li(s.app,l=>K({...s,app:l}));let{name:e,arguments:t=[]}=s.app??{};if(t=[...t],Array.isArray(e))return li(e,l=>K({...s,app:{name:l,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let l={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},a={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},c=N?await hr():await st();if(c.id in l){let p=l[c.id];return e==="browserPrivate"&&t.push(a[p]),K({...s,app:{name:D[p],arguments:t}})}throw new Error(`${c.name} is not supported as a default browser`)}let i,r=[],n={};if(R==="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(R==="win32"||N&&!L()&&!e){i=await Ze(),r.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),N||(n.windowsVerbatimArguments=!0);let l=["Start"];s.wait&&l.push("-Wait"),e?(l.push(`"\`"${e}\`""`),s.target&&t.push(s.target)):s.target&&l.push(`"${s.target}"`),t.length>0&&(t=t.map(a=>`"\`"${a}\`""`),l.push("-ArgumentList",t.join(","))),s.target=lt.Buffer.from(l.join(" "),"utf16le").toString("base64")}else{if(e)i=e;else{let l=!ot||ot==="/",a=!1;try{await ce.default.access(oi,ce.constants.X_OK),a=!0}catch{}i=at.default.versions.electron??(R==="android"||l||!a)?"xdg-open":oi}t.length>0&&r.push(...t),s.wait||(n.stdio="ignore",n.detached=!0)}R==="darwin"&&t.length>0&&r.push("--args",...t),s.target&&r.push(s.target);let o=ut.default.spawn(i,r,n);return s.wait?new Promise((l,a)=>{o.once("error",a),o.once("close",c=>{if(!s.allowNonzeroExitCode&&c>0){a(new Error(`Exited with code ${c}`));return}l(o)})}):(o.unref(),o)},fr=(s,e)=>{if(typeof s!="string")throw new TypeError("Expected a `target`");return K({...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 K({...e,app:{name:s,arguments:t}})};D={};j(D,"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"]}}));j(D,"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"]}}));j(D,"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"}));j(D,"edge",()=>ue({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));j(D,"browser",()=>"browser");j(D,"browserPrivate",()=>"browserPrivate");_r=fr});var St=A(bt(),1),{program:$r,createCommand:Tr,createArgument:Ir,createOption:Pr,CommanderError:Hr,InvalidArgumentError:Fr,InvalidOptionArgumentError:Nr,Command:Et,Argument:jr,Option:Dr,Help:Mr}=St.default;var kt=!1,vt=!1;function $t(s,e){kt=s,vt=e}function d(){return kt?!0:vt?!1:!process.stdout.isTTY}function C(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 V(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"),ne=require("path");E();k();var Be=require("fs"),G=require("path"),re=require("os"),q=[{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 H(s){if(s){let t=q.find(r=>r.id===s);if(t)return t;let i=q.find(r=>r.dir===`.${s}`||r.dir===s);return i||null}for(let t of q)if(process.env[t.envVar])return t;let e=(0,re.homedir)();for(let t of q)if((0,Be.existsSync)((0,G.join)(e,t.dir)))return t;return null}function jt(){let s=[],e=(0,re.homedir)();for(let t of q)(process.env[t.envVar]||(0,Be.existsSync)((0,G.join)(e,t.dir)))&&s.push(t);return s}function F(s,e){return e?(0,G.join)(process.cwd(),s.dir,s.skillsSubdir):(0,G.join)((0,re.homedir)(),s.dir,s.skillsSubdir)}var Dt=`---
|
|
31
|
+
title: Shared Context
|
|
32
|
+
description: Search, install, and manage AI skills from sharedcontext.ai
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
# Shared Context CLI
|
|
36
|
+
|
|
37
|
+
Use \`npx shared-context-ai\` (or \`npx sc\`) to search and install skills from the Shared Context skill library.
|
|
38
|
+
|
|
39
|
+
## Workflow
|
|
40
|
+
|
|
41
|
+
1. **Search** for skills matching your task
|
|
42
|
+
2. **Preview** to check if a skill is relevant
|
|
43
|
+
3. **Install** the skill to make it available
|
|
44
|
+
|
|
45
|
+
## Commands
|
|
46
|
+
|
|
47
|
+
### Search for skills
|
|
48
|
+
\`\`\`bash
|
|
49
|
+
npx shared-context-ai search "api testing"
|
|
50
|
+
npx shared-context-ai search "code review" --type skill
|
|
51
|
+
\`\`\`
|
|
52
|
+
|
|
53
|
+
### Preview a skill before installing
|
|
54
|
+
\`\`\`bash
|
|
55
|
+
npx shared-context-ai preview skills/api-testing
|
|
56
|
+
\`\`\`
|
|
57
|
+
|
|
58
|
+
### Install a skill
|
|
59
|
+
\`\`\`bash
|
|
60
|
+
npx shared-context-ai install skills/api-testing
|
|
61
|
+
npx shared-context-ai install skills/acme/code-review # from specific org
|
|
62
|
+
\`\`\`
|
|
63
|
+
|
|
64
|
+
### List installed skills
|
|
65
|
+
\`\`\`bash
|
|
66
|
+
npx shared-context-ai list
|
|
67
|
+
\`\`\`
|
|
68
|
+
|
|
69
|
+
### Check for updates
|
|
70
|
+
\`\`\`bash
|
|
71
|
+
npx shared-context-ai check
|
|
72
|
+
\`\`\`
|
|
73
|
+
|
|
74
|
+
### Update skills
|
|
75
|
+
\`\`\`bash
|
|
76
|
+
npx shared-context-ai update # update all
|
|
77
|
+
npx shared-context-ai update api-testing # update one
|
|
78
|
+
\`\`\`
|
|
79
|
+
|
|
80
|
+
### Uninstall a skill
|
|
81
|
+
\`\`\`bash
|
|
82
|
+
npx shared-context-ai uninstall api-testing
|
|
83
|
+
\`\`\`
|
|
84
|
+
|
|
85
|
+
## Tips
|
|
86
|
+
|
|
87
|
+
- Use \`--json\` flag for machine-readable output
|
|
88
|
+
- Use \`--project\` to install skills to the current project instead of globally
|
|
89
|
+
- Skills are installed to your agent's skills directory (e.g., \`~/.claude/skills/\`)
|
|
90
|
+
- Run \`npx shared-context-ai status\` to see detected agents and auth status
|
|
91
|
+
`;function ir(s,e){let t=F(s,e),i=(0,ne.join)(t,"shared-context");return(0,se.mkdirSync)(i,{recursive:!0}),(0,se.writeFileSync)((0,ne.join)(i,"SKILL.md"),Dt,"utf-8"),(0,ne.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(()=>(k(),Nt)),{saveAuth:o}=await Promise.resolve().then(()=>(E(),Ft)),l=await n("/api/cli/auth",{code:e.code});l.ok||(d()?g("init",l.error.code,l.error.message):f(`Auth failed: ${l.error.message}`),process.exit(1)),o({token:l.data.token,email:l.data.user.email,orgId:l.data.org.id,orgSlug:l.data.org.slug,orgName:l.data.org.name,createdAt:new Date().toISOString()}),d()||u(`Authenticated as ${l.data.user.email}`)}else w()||(d()?(g("init","AUTH_MISSING","Not authenticated. Run 'sc login' first or pass --code."),process.exit(1)):(f("Not authenticated. Run 'sc login' first or pass --code <code>."),process.exit(1)));let t=H(e.agent);if(t||(d()?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)),T()?.token){let n=(await import("os")).hostname(),o=await $("/api/cli/register-agent",{platform:t.platform,name:`CLI (${n})`});!o.ok&&!d()&&f(`Warning: Could not register agent connection: ${o.error.message}`)}let r=ir(t,!!e.project);Le({detectedAgent:t.id}),d()?C("init",{agent:t.id,metaSkillPath:r,authenticated:w()}):(u(""),u(`Shared Context initialized for ${t.label}`),u(`Meta-skill installed to: ${r}`),u(""),u("Quick reference:"),u(' sc search "query" Search for skills'),u(" sc install skills/<slug> Install a skill"),u(" sc list List installed skills"),u(" sc check Check for updates"),u(" sc preview skills/<slug> Preview before installing"))})}var hi=require("http"),fi=require("crypto");E();k();E();async function gi(s){let e=await $("/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()}),d()?C("login",{email:e.data.user.email,org:e.data.org.slug}):u(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(d()?g("login",e.error.code,e.error.message):f(`Login failed: ${e.error.message}`),!1)}async function wr(){let s=(0,fi.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,hi.createServer)((i,r)=>{let n=new URL(i.url||"/","http://localhost"),o=n.searchParams.get("code"),l=n.searchParams.get("state");if(!o||l!==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(),gi(o).then(e)});t.listen(0,"127.0.0.1",async()=>{let i=t.address();if(!i||typeof i=="string"){t.close(),e(!1);return}let r=i.port,o=`${x().apiBase||"https://app.sharedcontext.ai"}/cli/login?port=${r}&state=${s}`;d()||(u("Opening browser for authentication..."),u(`If the browser doesn't open, visit: ${o}`));try{let l=(await Promise.resolve().then(()=>(mi(),pi))).default;await l(o)}catch{d()||u(`Could not open browser. Please visit:
|
|
92
|
+
${o}`)}setTimeout(()=>{t.close(),d()||f("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function _i(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 gi(e.code):t=await wr(),process.exit(t?0:1)})}k();function Ci(s){s.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, prompt)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let i=new URLSearchParams({q:e});t.type&&i.set("type",t.type),t.tag&&i.set("tag",t.tag),t.limit&&i.set("limit",t.limit);let r=w()?`/api/cli/search?${i}`:`/api/public/search?${i}`,n=await y(r);n.ok||(d()?g("search",n.error.code,n.error.message):u(`Search failed: ${n.error.message}`),process.exit(1));let o=n.data.results;if(d()){C("search",{results:o,count:o.length});return}if(o.length===0){u("No skills found.");return}u(`Found ${o.length} result${o.length===1?"":"s"}:
|
|
93
|
+
`);let l=o.map(a=>[a.orgSlug?`skills/${a.orgSlug}/${a.slug}`:`skills/${a.slug}`,a.title,`\u2605${a.starCount}`,`\u2193${a.installCount}`]);u(V(l))})}var de=require("fs"),z=require("path");k();E();function Ar(s,e){for(let t of e){let i=(0,z.join)(s,t.path);(0,de.mkdirSync)((0,z.dirname)(i),{recursive:!0}),(0,de.writeFileSync)(i,t.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=x(),r=H(t.agent||i.detectedAgent);r||(d()?g("install","NO_AGENTS","No AI agent detected. Run sc init first."):f("No AI agent detected. Run 'sc init' first."),process.exit(1));let n=w(),o=n?`/api/cli/resource/${e}`:`/api/public/resource/${e}`,l=await y(o);l.ok||(d()?g("install",l.error.code,l.error.message):f(`Install failed: ${l.error.message}`),process.exit(1));let a=l.data,c=a.resource.slug||a.resource.id,p=F(r,!!t.project),m=(0,z.join)(p,c);try{Ar(m,a.files)}catch(_){d()?g("install","WRITE_FAILED",`Failed to write files: ${_}`):f(`Failed to write files: ${_}`),process.exit(1)}if(n&&a.resource.latestSha){let _=await $("/api/cli/install",{resourceId:a.resource.id,agentPlatform:r.platform,installedSha:a.resource.latestSha});!_.ok&&!d()&&f(`Warning: Could not record install on server: ${_.error.message}`)}B({resourceId:a.resource.id,slug:c,title:a.resource.title,sha:a.resource.latestSha||"",scope:t.project?"project":"global",agent:r.id,installedAt:new Date().toISOString()}),d()?C("install",{slug:c,title:a.resource.title,path:m,files:a.files.length}):(u(`Installed "${a.resource.title}" to ${m}`),u(` ${a.files.length} file${a.files.length===1?"":"s"} written`),n||(u(""),u("Tip: Sign up at sharedcontext.ai to track installations and get updates.")))})}k();E();function Ai(s){s.command("list").description("List installed skills").alias("ls").action(async()=>{if(w()){let e=await y("/api/cli/installed");e.ok||(d()?g("list",e.error.code,e.error.message):u(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(d()){C("list",{installations:t,count:t.length});return}if(t.length===0){u("No skills installed."),u("Use 'sc search' to find skills to install.");return}u(`${t.length} skill${t.length===1?"":"s"} installed:
|
|
94
|
+
`);let i=t.map(r=>[r.slug||r.resourceId,r.title,r.hasUpdate?"(update available)":"(current)"]);u(V(i))}else{let t=P().installations;if(d()){C("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:
|
|
95
|
+
`);let i=t.map(r=>[r.slug,r.title,`(${r.agent})`]);u(V(i)),u(`
|
|
96
|
+
Tip: Run 'sc login' to sync with sharedcontext.ai and check for updates.`)}})}k();function xi(s){s.command("preview <path>").description("Preview a skill's content (e.g., skills/api-testing)").action(async e=>{let i=w()?`/api/cli/resource/${e}/preview`:`/api/public/resource/${e}/preview`,r=await y(i);r.ok||(d()?g("preview",r.error.code,r.error.message):f(`Preview failed: ${r.error.message}`),process.exit(1)),d()?C("preview",r.data):u(r.data.content)})}k();function yi(s){s.command("check").description("Check for skill updates").action(async()=>{w()||(d()?g("check","AUTH_MISSING","Login required to check for updates."):f("Login required to check for updates. Run 'sc login'."),process.exit(1));let e=await y("/api/cli/updates");e.ok||(d()?g("check",e.error.code,e.error.message):f(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:i}=e.data;if(d()){C("check",{updates:t,count:i});return}if(i===0){u("All skills are up to date.");return}u(`${i} update${i===1?"":"s"} available:
|
|
97
|
+
`);let r=t.map(n=>[n.slug||n.resourceId,n.title,`${n.installedSha.slice(0,7)} \u2192 ${n.latestSha.slice(0,7)}`]);u(V(r)),u(`
|
|
98
|
+
Run 'sc update' to update all, or 'sc update <slug>' to update one.`)})}var pe=require("fs"),Y=require("path");k();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)=>{w()||(d()?g("update","AUTH_MISSING","Login required to update skills."):f("Login required to update skills. Run 'sc login'."),process.exit(1));let i=x(),r=H(t.agent||i.detectedAgent);r||(d()?g("update","NO_AGENTS","No AI agent detected."):f("No AI agent detected. Run 'sc init' first."),process.exit(1));let n=await y("/api/cli/updates");n.ok||(d()?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(a=>a.slug===e||a.resourceId===e),o.length===0)){d()?g("update","SKILL_NOT_FOUND",`No update available for "${e}".`):u(`No update available for "${e}".`);return}if(o.length===0){d()?C("update",{updated:[],count:0}):u("All skills are up to date.");return}let l=[];for(let a of o){let c=a.slug||a.resourceId,p=`skills/${c}`,m=await y(`/api/cli/resource/${p}`);if(!m.ok){d()||f(` Failed to fetch ${c}: ${m.error.message}`);continue}let _=m.data,X=F(r,!!t.project),fe=(0,Y.join)(X,c);for(let dt of _.files){let pt=(0,Y.join)(fe,dt.path);(0,pe.mkdirSync)((0,Y.dirname)(pt),{recursive:!0}),(0,pe.writeFileSync)(pt,dt.content,"utf-8")}_.resource.latestSha&&await $("/api/cli/update",{resourceId:_.resource.id,installedSha:_.resource.latestSha}),B({resourceId:_.resource.id,slug:c,title:_.resource.title,sha:_.resource.latestSha||"",scope:t.project?"project":"global",agent:r.id,installedAt:new Date().toISOString()}),l.push({slug:c,title:_.resource.title}),d()||u(` Updated ${c}`)}d()?C("update",{updated:l,count:l.length}):l.length>0&&u(`
|
|
99
|
+
${l.length} skill${l.length===1?"":"s"} updated.`)})}var me=require("fs"),bi=require("path");k();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=x(),r=H(t.agent||i.detectedAgent);r||(d()?g("uninstall","NO_AGENTS","No AI agent detected."):f("No AI agent detected. Run 'sc init' first."),process.exit(1));let o=P().installations.find(c=>c.slug===e||c.resourceId===e),l=F(r,!!t.project),a=(0,bi.join)(l,e);if((0,me.existsSync)(a)&&(0,me.rmSync)(a,{recursive:!0,force:!0}),w()&&o){let c=await $("/api/cli/uninstall",{resourceId:o.resourceId});!c.ok&&!d()&&f(`Warning: Could not record uninstall on server: ${c.error.message}`)}o&&We(o.resourceId),d()?C("uninstall",{slug:e,removed:!0}):u(`Uninstalled "${e}"`)})}E();function Ei(s){s.command("status").description("Show CLI status: auth, agents, installed skill counts").action(async()=>{let e=T(),t=x(),i=P(),r=jt(),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(d()){C("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`)})}E();k();function ki(s){s.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=T();e.revoke&&w()&&await Ue("/api/cli/auth"),Ve(),d()?C("logout",{email:t?.email||null}):u("Logged out.")})}var vi={AUTH_MISSING:"Run 'sc login' to authenticate.",AUTH_EXPIRED:"Run 'sc login' to re-authenticate.",SKILL_NOT_FOUND:"Check the skill slug and try again.",ALREADY_INSTALLED:"Use 'sc update <slug>' to update instead.",NO_AGENTS:"No AI coding agents detected. Run 'sc 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."},he=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 Et;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();$t(!!e.json,!!e.human)});Mt(b);_i(b);Ci(b);wi(b);Ai(b);xi(b);yi(b);Oi(b);Si(b);Ei(b);ki(b);process.on("uncaughtException",s=>{s instanceof he?d()?g(process.argv[2]||"unknown",s.code,s.message):(f(`Error: ${s.message}`),f(s.recovery)):d()?g(process.argv[2]||"unknown","UNEXPECTED",s.message||"Unexpected error"):f(`Error: ${s.message||s}`),process.exit(1)});b.parse();
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "shared-context-ai",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "CLI for Shared Context - search, install, and manage AI skills",
|
|
5
|
+
"bin": {
|
|
6
|
+
"shared-context-ai": "dist/index.js",
|
|
7
|
+
"sc": "dist/index.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"build": "tsup",
|
|
14
|
+
"dev": "tsup --watch"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"ai",
|
|
18
|
+
"skills",
|
|
19
|
+
"cli",
|
|
20
|
+
"shared-context"
|
|
21
|
+
],
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"commander": "^13.1.0",
|
|
25
|
+
"open": "^10.1.0",
|
|
26
|
+
"tsup": "^8.4.0",
|
|
27
|
+
"typescript": "^5.8.0"
|
|
28
|
+
}
|
|
29
|
+
}
|