shared-context-ai 0.1.20 → 0.1.22

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 +69 -67
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,52 +1,52 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var ei=Object.create;var ir=Object.defineProperty;var ti=Object.getOwnPropertyDescriptor;var ri=Object.getOwnPropertyNames;var ni=Object.getPrototypeOf,si=Object.prototype.hasOwnProperty;var pe=(r,e)=>()=>(r&&(e=r(r=0)),e);var Z=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),dt=(r,e)=>{for(var t in e)ir(r,t,{get:e[t],enumerable:!0})},oi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ri(e))!si.call(r,s)&&s!==t&&ir(r,s,{get:()=>e[s],enumerable:!(n=ti(e,s))||n.enumerable});return r};var me=(r,e,t)=>(t=r!=null?ei(ni(r)):{},oi(e||!r||!r.__esModule?ir(t,"default",{value:r,enumerable:!0}):t,r));var pt=Z(cr=>{"use strict";var _t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},ar=class extends _t{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};cr.CommanderError=_t;cr.InvalidArgumentError=ar});var xt=Z(ur=>{"use strict";var{InvalidArgumentError:ii}=pt(),lr=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,n)=>{if(!this.argChoices.includes(t))throw new ii(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ai(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}ur.Argument=lr;ur.humanReadableArgName=ai});var pr=Z(dr=>{"use strict";var{humanReadableArgName:ci}=xt(),fr=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(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,o)=>s.name().localeCompare(o.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);!s&&!o?t.push(n):n.long&&!o?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);t.push(...s)}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(n=>ci(n)).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((n,s)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(s)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(s)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+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(n=>JSON.stringify(n)).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(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth??80;function o(S,x){return t.formatItem(S,n,x,t)}let l=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],c=t.commandDescription(e);c.length>0&&(l=l.concat([t.boxWrap(t.styleCommandDescription(c),s),""]));let u=t.visibleArguments(e).map(S=>o(t.styleArgumentTerm(t.argumentTerm(S)),t.styleArgumentDescription(t.argumentDescription(S))));u.length>0&&(l=l.concat([t.styleTitle("Arguments:"),...u,""]));let a=t.visibleOptions(e).map(S=>o(t.styleOptionTerm(t.optionTerm(S)),t.styleOptionDescription(t.optionDescription(S))));if(a.length>0&&(l=l.concat([t.styleTitle("Options:"),...a,""])),t.showGlobalOptions){let S=t.visibleGlobalOptions(e).map(x=>o(t.styleOptionTerm(t.optionTerm(x)),t.styleOptionDescription(t.optionDescription(x))));S.length>0&&(l=l.concat([t.styleTitle("Global Options:"),...S,""]))}let p=t.visibleCommands(e).map(S=>o(t.styleSubcommandTerm(t.subcommandTerm(S)),t.styleSubcommandDescription(t.subcommandDescription(S))));return p.length>0&&(l=l.concat([t.styleTitle("Commands:"),...p,""])),l.join(`
3
- `)}displayWidth(e){return An(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,n,s){let l=" ".repeat(2);if(!n)return l+e;let c=e.padEnd(t+e.length-s.displayWidth(e)),u=2,p=(this.helpWidth??80)-t-u-2,S;return p<this.minWidthToWrap||s.preformatted(n)?S=n:S=s.boxWrap(n,p).replace(/\n/g,`
2
+ "use strict";var ri=Object.create;var ur=Object.defineProperty;var ni=Object.getOwnPropertyDescriptor;var si=Object.getOwnPropertyNames;var oi=Object.getPrototypeOf,ii=Object.prototype.hasOwnProperty;var ge=(r,e)=>()=>(r&&(e=r(r=0)),e);var K=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),yt=(r,e)=>{for(var t in e)ur(r,t,{get:e[t],enumerable:!0})},ai=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of si(e))!ii.call(r,s)&&s!==t&&ur(r,s,{get:()=>e[s],enumerable:!(n=ni(e,s))||n.enumerable});return r};var ye=(r,e,t)=>(t=r!=null?ri(oi(r)):{},ai(e||!r||!r.__esModule?ur(t,"default",{value:r,enumerable:!0}):t,r));var St=K(dr=>{"use strict";var Ot=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},fr=class extends Ot{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};dr.CommanderError=Ot;dr.InvalidArgumentError=fr});var kt=K(mr=>{"use strict";var{InvalidArgumentError:ci}=St(),pr=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,n)=>{if(!this.argChoices.includes(t))throw new ci(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function li(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}mr.Argument=pr;mr.humanReadableArgName=li});var yr=K(gr=>{"use strict";var{humanReadableArgName:ui}=kt(),hr=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(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,o)=>s.name().localeCompare(o.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);!s&&!o?t.push(n):n.long&&!o?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);t.push(...s)}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(n=>ui(n)).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((n,s)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(s)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(s)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+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(n=>JSON.stringify(n)).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(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth??80;function o(S,I){return t.formatItem(S,n,I,t)}let l=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],c=t.commandDescription(e);c.length>0&&(l=l.concat([t.boxWrap(t.styleCommandDescription(c),s),""]));let u=t.visibleArguments(e).map(S=>o(t.styleArgumentTerm(t.argumentTerm(S)),t.styleArgumentDescription(t.argumentDescription(S))));u.length>0&&(l=l.concat([t.styleTitle("Arguments:"),...u,""]));let a=t.visibleOptions(e).map(S=>o(t.styleOptionTerm(t.optionTerm(S)),t.styleOptionDescription(t.optionDescription(S))));if(a.length>0&&(l=l.concat([t.styleTitle("Options:"),...a,""])),t.showGlobalOptions){let S=t.visibleGlobalOptions(e).map(I=>o(t.styleOptionTerm(t.optionTerm(I)),t.styleOptionDescription(t.optionDescription(I))));S.length>0&&(l=l.concat([t.styleTitle("Global Options:"),...S,""]))}let p=t.visibleCommands(e).map(S=>o(t.styleSubcommandTerm(t.subcommandTerm(S)),t.styleSubcommandDescription(t.subcommandDescription(S))));return p.length>0&&(l=l.concat([t.styleTitle("Commands:"),...p,""])),l.join(`
3
+ `)}displayWidth(e){return In(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,n,s){let l=" ".repeat(2);if(!n)return l+e;let c=e.padEnd(t+e.length-s.displayWidth(e)),u=2,p=(this.helpWidth??80)-t-u-2,S;return p<this.minWidthToWrap||s.preformatted(n)?S=n:S=s.boxWrap(n,p).replace(/\n/g,`
4
4
  `+" ".repeat(t+u)),l+c+" ".repeat(u)+S.replace(/\n/g,`
5
- ${l}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,o=[];return n.forEach(l=>{let c=l.match(s);if(c===null){o.push("");return}let u=[c.shift()],a=this.displayWidth(u[0]);c.forEach(p=>{let S=this.displayWidth(p);if(a+S<=t){u.push(p),a+=S;return}o.push(u.join(""));let x=p.trimStart();u=[x],a=this.displayWidth(x)}),o.push(u.join(""))}),o.join(`
6
- `)}};function An(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}dr.Help=fr;dr.stripColor=An});var yr=Z(gr=>{"use strict";var{InvalidArgumentError:li}=pt(),mr=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 n=ui(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}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,n)=>{if(!this.argChoices.includes(t))throw new li(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?bn(this.name().replace(/^no-/,"")):bn(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},hr=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,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,o=s!==void 0?s:!1;return t.negate===(o===e)}};function bn(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ui(r){let e,t,n=/^-[^-]$/,s=/^--[^-]/,o=r.split(/[ |,]+/).concat("guard");if(n.test(o[0])&&(e=o.shift()),s.test(o[0])&&(t=o.shift()),!e&&n.test(o[0])&&(e=o.shift()),!e&&s.test(o[0])&&(e=t,t=o.shift()),o[0].startsWith("-")){let l=o[0],c=`option creation failed due to '${l}' in option flags '${r}'`;throw/^-[^-][^-]/.test(l)?new Error(`${c}
5
+ ${l}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,o=[];return n.forEach(l=>{let c=l.match(s);if(c===null){o.push("");return}let u=[c.shift()],a=this.displayWidth(u[0]);c.forEach(p=>{let S=this.displayWidth(p);if(a+S<=t){u.push(p),a+=S;return}o.push(u.join(""));let I=p.trimStart();u=[I],a=this.displayWidth(I)}),o.push(u.join(""))}),o.join(`
6
+ `)}};function In(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}gr.Help=hr;gr.stripColor=In});var wr=K(Cr=>{"use strict";var{InvalidArgumentError:fi}=St(),Sr=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 n=di(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}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,n)=>{if(!this.argChoices.includes(t))throw new fi(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?xn(this.name().replace(/^no-/,"")):xn(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Er=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,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,o=s!==void 0?s:!1;return t.negate===(o===e)}};function xn(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function di(r){let e,t,n=/^-[^-]$/,s=/^--[^-]/,o=r.split(/[ |,]+/).concat("guard");if(n.test(o[0])&&(e=o.shift()),s.test(o[0])&&(t=o.shift()),!e&&n.test(o[0])&&(e=o.shift()),!e&&s.test(o[0])&&(e=t,t=o.shift()),o[0].startsWith("-")){let l=o[0],c=`option creation failed due to '${l}' in option flags '${r}'`;throw/^-[^-][^-]/.test(l)?new Error(`${c}
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')`):n.test(l)?new Error(`${c}
10
10
  - too many short flags`):s.test(l)?new Error(`${c}
11
11
  - too many long flags`):new Error(`${c}
12
- - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${r}'.`);return{shortFlag:e,longFlag:t}}gr.Option=mr;gr.DualOptions=hr});var xn=Z(_n=>{"use strict";function fi(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let o=1;r[s-1]===e[n-1]?o=0:o=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+o),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function di(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(l=>l.slice(2)));let n=[],s=3,o=.4;return e.forEach(l=>{if(l.length<=1)return;let c=fi(r,l),u=Math.max(r.length,l.length);(u-c)/u>o&&(c<s?(s=c,n=[l]):c===s&&n.push(l))}),n.sort((l,c)=>l.localeCompare(c)),t&&(n=n.map(l=>`--${l}`)),n.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 '${r}'.`);return{shortFlag:e,longFlag:t}}Cr.Option=Sr;Cr.DualOptions=Er});var kn=K(On=>{"use strict";function pi(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let o=1;r[s-1]===e[n-1]?o=0:o=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+o),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function mi(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(l=>l.slice(2)));let n=[],s=3,o=.4;return e.forEach(l=>{if(l.length<=1)return;let c=pi(r,l),u=Math.max(r.length,l.length);(u-c)/u>o&&(c<s?(s=c,n=[l]):c===s&&n.push(l))}),n.sort((l,c)=>l.localeCompare(c)),t&&(n=n.map(l=>`--${l}`)),n.length>1?`
13
13
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
14
- (Did you mean ${n[0]}?)`:""}_n.suggestSimilar=di});var vn=Z(Ar=>{"use strict";var pi=require("events").EventEmitter,Sr=require("child_process"),Re=require("path"),It=require("fs"),U=require("process"),{Argument:mi,humanReadableArgName:hi}=xt(),{CommanderError:Er}=pt(),{Help:gi,stripColor:yi}=pr(),{Option:In,DualOptions:Si}=yr(),{suggestSimilar:On}=xn(),Cr=class r extends pi{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=>U.stdout.write(t),writeErr:t=>U.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>U.stdout.isTTY?U.stdout.columns:void 0,getErrHelpWidth:()=>U.stderr.isTTY?U.stderr.columns:void 0,getOutHasColors:()=>wr()??(U.stdout.isTTY&&U.stdout.hasColors?.()),getErrHasColors:()=>wr()??(U.stderr.isTTY&&U.stderr.hasColors?.()),stripColor:t=>yi(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,n){let s=t,o=n;typeof s=="object"&&s!==null&&(o=s,s=null),o=o||{};let[,l,c]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(l);return s&&(u.description(s),u._executableHandler=!0),o.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(o.noHelp||o.hidden),u._executableFile=o.executableFile||null,c&&u.arguments(c),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),s?this:u}createCommand(e){return new r(e)}createHelp(){return Object.assign(new gi,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 mi(e,t)}argument(e,t,n,s){let o=this.createArgument(e,t);return typeof n=="function"?o.default(s).argParser(n):o.default(n),this.addArgument(o),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[,n,s]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",l=this.createCommand(n);return l.helpOption(!1),s&&l.arguments(s),o&&l.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=l,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 n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
16
- Expecting one of '${n.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,n){this._exitCallback&&this._exitCallback(new Er(e,t,n)),U.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,o=n.slice(0,s);return this._storeOptionsAsProperties?o[s]=this:o[s]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new In(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let l=`${s} ${o.message}`;this.error(l,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
17
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(o,l,c)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let u=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,u,l):o!==null&&e.variadic&&(o=e._concatValue(o,u)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,c)};return this.on("option:"+t,o=>{let l=`error: option '${e.flags}' argument '${o}' is invalid.`;s(o,l,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let l=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;s(o,l,"env")}),this}_optionEx(e,t,n,s,o){if(typeof t=="object"&&t instanceof In)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let l=this.createOption(t,n);if(l.makeOptionMandatory(!!e.mandatory),typeof s=="function")l.default(o).argParser(s);else if(s instanceof RegExp){let c=s;s=(u,a)=>{let p=c.exec(u);return p?p[0]:a},l.default(o).argParser(s)}else l.default(s);return this.addOption(l)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}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,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.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){U.versions?.electron&&(t.from="electron");let s=U.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=U.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":U.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
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,n){if(It.existsSync(e))return;let s=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${e}' does not exist
14
+ (Did you mean ${n[0]}?)`:""}On.suggestSimilar=mi});var Pn=K(xr=>{"use strict";var hi=require("events").EventEmitter,br=require("child_process"),Ne=require("path"),vt=require("fs"),H=require("process"),{Argument:gi,humanReadableArgName:yi}=kt(),{CommanderError:Ar}=St(),{Help:Si,stripColor:Ei}=yr(),{Option:vn,DualOptions:Ci}=wr(),{suggestSimilar:Tn}=kn(),_r=class r extends hi{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,n)=>n(t),getOutHelpWidth:()=>H.stdout.isTTY?H.stdout.columns:void 0,getErrHelpWidth:()=>H.stderr.isTTY?H.stderr.columns:void 0,getOutHasColors:()=>Ir()??(H.stdout.isTTY&&H.stdout.hasColors?.()),getErrHasColors:()=>Ir()??(H.stderr.isTTY&&H.stderr.hasColors?.()),stripColor:t=>Ei(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,n){let s=t,o=n;typeof s=="object"&&s!==null&&(o=s,s=null),o=o||{};let[,l,c]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(l);return s&&(u.description(s),u._executableHandler=!0),o.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(o.noHelp||o.hidden),u._executableFile=o.executableFile||null,c&&u.arguments(c),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),s?this:u}createCommand(e){return new r(e)}createHelp(){return Object.assign(new Si,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 gi(e,t)}argument(e,t,n,s){let o=this.createArgument(e,t);return typeof n=="function"?o.default(s).argParser(n):o.default(n),this.addArgument(o),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[,n,s]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",l=this.createCommand(n);return l.helpOption(!1),s&&l.arguments(s),o&&l.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=l,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 n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
16
+ Expecting one of '${n.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,n){this._exitCallback&&this._exitCallback(new Ar(e,t,n)),H.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,o=n.slice(0,s);return this._storeOptionsAsProperties?o[s]=this:o[s]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new vn(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let l=`${s} ${o.message}`;this.error(l,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
17
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(o,l,c)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let u=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,u,l):o!==null&&e.variadic&&(o=e._concatValue(o,u)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,c)};return this.on("option:"+t,o=>{let l=`error: option '${e.flags}' argument '${o}' is invalid.`;s(o,l,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let l=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;s(o,l,"env")}),this}_optionEx(e,t,n,s,o){if(typeof t=="object"&&t instanceof vn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let l=this.createOption(t,n);if(l.makeOptionMandatory(!!e.mandatory),typeof s=="function")l.default(o).argParser(s);else if(s instanceof RegExp){let c=s;s=(u,a)=>{let p=c.exec(u);return p?p[0]:a},l.default(o).argParser(s)}else l.default(s);return this.addOption(l)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}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,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.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 s=H.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=H.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":H.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
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,n){if(vt.existsSync(e))return;let s=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${e}' does not exist
19
19
  - if '${n}' 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
- - ${s}`;throw new Error(o)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function o(p,S){let x=Re.resolve(p,S);if(It.existsSync(x))return x;if(s.includes(Re.extname(S)))return;let d=s.find(m=>It.existsSync(`${x}${m}`));if(d)return`${x}${d}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let l=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let p;try{p=It.realpathSync(this._scriptPath)}catch{p=this._scriptPath}c=Re.resolve(Re.dirname(p),c)}if(c){let p=o(c,l);if(!p&&!e._executableFile&&this._scriptPath){let S=Re.basename(this._scriptPath,Re.extname(this._scriptPath));S!==this._name&&(p=o(c,`${S}-${e._name}`))}l=p||l}n=s.includes(Re.extname(l));let u;U.platform!=="win32"?n?(t.unshift(l),t=kn(U.execArgv).concat(t),u=Sr.spawn(U.argv[0],t,{stdio:"inherit"})):u=Sr.spawn(l,t,{stdio:"inherit"}):(this._checkForMissingExecutable(l,c,e._name),t.unshift(l),t=kn(U.execArgv).concat(t),u=Sr.spawn(U.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(S=>{U.on(S,()=>{u.killed===!1&&u.exitCode===null&&u.kill(S)})});let a=this._exitCallback;u.on("close",p=>{p=p??1,a?a(new Er(p,"commander.executeSubCommandAsync","(close)")):U.exit(p)}),u.on("error",p=>{if(p.code==="ENOENT")this._checkForMissingExecutable(l,c,e._name);else if(p.code==="EACCES")throw new Error(`'${l}' not executable`);if(!a)U.exit(1);else{let S=new Er(1,"commander.executeSubCommandAsync","(error)");S.nestedError=p,a(S)}}),this.runningCommand=u}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0}),s._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,s,"preSubcommand"),o=this._chainOrCall(o,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),o}_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=(n,s,o)=>{let l=s;if(s!==null&&n.parseArg){let c=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;l=this._callParseArg(n,s,o,c)}return l};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let o=n.defaultValue;n.variadic?s<this.args.length?(o=this.args.slice(s),n.parseArg&&(o=o.reduce((l,c)=>e(n,c,l),n.defaultValue))):o===void 0&&(o=[]):s<this.args.length&&(o=this.args[s],n.parseArg&&(o=e(n,o,n.defaultValue))),t[s]=o}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(l=>{s.push({hookedCommand:o,callback:l})})}),t==="postAction"&&s.reverse(),s.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{s=this._chainOrCall(s,()=>o(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.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(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let l;return l=this._chainOrCallHooks(l,"preAction"),l=this._chainOrCall(l,()=>this._actionHandler(this.processedArgs)),this.parent&&(l=this._chainOrCall(l,()=>{this.parent.emit(o,e,t)})),l=this._chainOrCallHooks(l,"postAction"),l}if(this.parent&&this.parent.listenerCount(o))s(),this._processArguments(),this.parent.emit(o,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():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),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(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(o=>n.conflictsWith.includes(o.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,o=e.slice();function l(u){return u.length>1&&u[0]==="-"}let c=null;for(;o.length;){let u=o.shift();if(u==="--"){s===n&&s.push(u),s.push(...o);break}if(c&&!l(u)){this.emit(`option:${c.name()}`,u);continue}if(c=null,l(u)){let a=this._findOption(u);if(a){if(a.required){let p=o.shift();p===void 0&&this.optionMissingArgument(a),this.emit(`option:${a.name()}`,p)}else if(a.optional){let p=null;o.length>0&&!l(o[0])&&(p=o.shift()),this.emit(`option:${a.name()}`,p)}else this.emit(`option:${a.name()}`);c=a.variadic?a:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let a=this._findOption(`-${u[1]}`);if(a){a.required||a.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${a.name()}`,u.slice(2)):(this.emit(`option:${a.name()}`),o.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let a=u.indexOf("="),p=this._findOption(u.slice(0,a));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,u.slice(a+1));continue}}if(l(u)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(u)){t.push(u),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(u),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){s.push(u),o.length>0&&s.push(...o);break}s.push(u)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}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
+ - ${s}`;throw new Error(o)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function o(p,S){let I=Ne.resolve(p,S);if(vt.existsSync(I))return I;if(s.includes(Ne.extname(S)))return;let d=s.find(m=>vt.existsSync(`${I}${m}`));if(d)return`${I}${d}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let l=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let p;try{p=vt.realpathSync(this._scriptPath)}catch{p=this._scriptPath}c=Ne.resolve(Ne.dirname(p),c)}if(c){let p=o(c,l);if(!p&&!e._executableFile&&this._scriptPath){let S=Ne.basename(this._scriptPath,Ne.extname(this._scriptPath));S!==this._name&&(p=o(c,`${S}-${e._name}`))}l=p||l}n=s.includes(Ne.extname(l));let u;H.platform!=="win32"?n?(t.unshift(l),t=Rn(H.execArgv).concat(t),u=br.spawn(H.argv[0],t,{stdio:"inherit"})):u=br.spawn(l,t,{stdio:"inherit"}):(this._checkForMissingExecutable(l,c,e._name),t.unshift(l),t=Rn(H.execArgv).concat(t),u=br.spawn(H.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(S=>{H.on(S,()=>{u.killed===!1&&u.exitCode===null&&u.kill(S)})});let a=this._exitCallback;u.on("close",p=>{p=p??1,a?a(new Ar(p,"commander.executeSubCommandAsync","(close)")):H.exit(p)}),u.on("error",p=>{if(p.code==="ENOENT")this._checkForMissingExecutable(l,c,e._name);else if(p.code==="EACCES")throw new Error(`'${l}' not executable`);if(!a)H.exit(1);else{let S=new Ar(1,"commander.executeSubCommandAsync","(error)");S.nestedError=p,a(S)}}),this.runningCommand=u}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0}),s._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,s,"preSubcommand"),o=this._chainOrCall(o,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),o}_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=(n,s,o)=>{let l=s;if(s!==null&&n.parseArg){let c=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;l=this._callParseArg(n,s,o,c)}return l};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let o=n.defaultValue;n.variadic?s<this.args.length?(o=this.args.slice(s),n.parseArg&&(o=o.reduce((l,c)=>e(n,c,l),n.defaultValue))):o===void 0&&(o=[]):s<this.args.length&&(o=this.args[s],n.parseArg&&(o=e(n,o,n.defaultValue))),t[s]=o}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(l=>{s.push({hookedCommand:o,callback:l})})}),t==="postAction"&&s.reverse(),s.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{s=this._chainOrCall(s,()=>o(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.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(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let l;return l=this._chainOrCallHooks(l,"preAction"),l=this._chainOrCall(l,()=>this._actionHandler(this.processedArgs)),this.parent&&(l=this._chainOrCall(l,()=>{this.parent.emit(o,e,t)})),l=this._chainOrCallHooks(l,"postAction"),l}if(this.parent&&this.parent.listenerCount(o))s(),this._processArguments(),this.parent.emit(o,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():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),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(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(o=>n.conflictsWith.includes(o.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,o=e.slice();function l(u){return u.length>1&&u[0]==="-"}let c=null;for(;o.length;){let u=o.shift();if(u==="--"){s===n&&s.push(u),s.push(...o);break}if(c&&!l(u)){this.emit(`option:${c.name()}`,u);continue}if(c=null,l(u)){let a=this._findOption(u);if(a){if(a.required){let p=o.shift();p===void 0&&this.optionMissingArgument(a),this.emit(`option:${a.name()}`,p)}else if(a.optional){let p=null;o.length>0&&!l(o[0])&&(p=o.shift()),this.emit(`option:${a.name()}`,p)}else this.emit(`option:${a.name()}`);c=a.variadic?a:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let a=this._findOption(`-${u[1]}`);if(a){a.required||a.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${a.name()}`,u.slice(2)):(this.emit(`option:${a.name()}`),o.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let a=u.indexOf("="),p=this._findOption(u.slice(0,a));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,u.slice(a+1));continue}}if(l(u)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(u)){t.push(u),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(u),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){s.push(u),o.length>0&&s.push(...o);break}s.push(u)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}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 n=t||{},s=n.exitCode||1,o=n.code||"commander.error";this._exit(s,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in U.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()}`,U.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Si(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"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 n=l=>{let c=l.attributeName(),u=this.getOptionValue(c),a=this.options.find(S=>S.negate&&c===S.attributeName()),p=this.options.find(S=>!S.negate&&c===S.attributeName());return a&&(a.presetArg===void 0&&u===!1||a.presetArg!==void 0&&u===a.presetArg)?a:p||l},s=l=>{let c=n(l),u=c.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${c.envVar}'`:`option '${c.flags}'`},o=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],o=this;do{let l=o.createHelp().visibleOptions(o).filter(c=>c.long).map(c=>c.long);s=s.concat(l),o=o.parent}while(o&&!o._enablePositionalOptions);t=On(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(o=>{s.push(o.name()),o.alias()&&s.push(o.alias())}),t=On(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.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 n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}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(n=>hi(n));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=Re.basename(e,Re.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let s=t.formatHelp(this,t);return n.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(e){e=e||{};let t=!!e.error,n,s,o;return t?(n=c=>this._outputConfiguration.writeErr(c),s=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=c=>this._outputConfiguration.writeOut(c),s=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:t,write:c=>(s||(c=this._outputConfiguration.stripColor(c)),n(c)),hasColors:s,helpWidth:o}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),s={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(l=>l.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let o=this.helpInformation({error:n.error});if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(l=>l.emit("afterAllHelp",s))}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(U.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
24
+ `),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,o=n.code||"commander.error";this._exit(s,o,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 Ci(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"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 n=l=>{let c=l.attributeName(),u=this.getOptionValue(c),a=this.options.find(S=>S.negate&&c===S.attributeName()),p=this.options.find(S=>!S.negate&&c===S.attributeName());return a&&(a.presetArg===void 0&&u===!1||a.presetArg!==void 0&&u===a.presetArg)?a:p||l},s=l=>{let c=n(l),u=c.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${c.envVar}'`:`option '${c.flags}'`},o=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],o=this;do{let l=o.createHelp().visibleOptions(o).filter(c=>c.long).map(c=>c.long);s=s.concat(l),o=o.parent}while(o&&!o._enablePositionalOptions);t=Tn(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(o=>{s.push(o.name()),o.alias()&&s.push(o.alias())}),t=Tn(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.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 n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}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(n=>yi(n));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=Ne.basename(e,Ne.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let s=t.formatHelp(this,t);return n.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(e){e=e||{};let t=!!e.error,n,s,o;return t?(n=c=>this._outputConfiguration.writeErr(c),s=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=c=>this._outputConfiguration.writeOut(c),s=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:t,write:c=>(s||(c=this._outputConfiguration.stripColor(c)),n(c)),hasColors:s,helpWidth:o}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),s={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(l=>l.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let o=this.helpInformation({error:n.error});if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(l=>l.emit("afterAllHelp",s))}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 n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
26
26
  Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,o=>{let l;typeof t=="function"?l=t({error:o.error,command:o.command}):l=t,l&&o.write(`${l}
27
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function kn(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?s=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],s=o[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}function wr(){if(U.env.NO_COLOR||U.env.FORCE_COLOR==="0"||U.env.FORCE_COLOR==="false")return!1;if(U.env.FORCE_COLOR||U.env.CLICOLOR_FORCE!==void 0)return!0}Ar.Command=Cr;Ar.useColor=wr});var Dn=Z(we=>{"use strict";var{Argument:Tn}=xt(),{Command:br}=vn(),{CommanderError:Ei,InvalidArgumentError:Rn}=pt(),{Help:Ci}=pr(),{Option:Pn}=yr();we.program=new br;we.createCommand=r=>new br(r);we.createOption=(r,e)=>new Pn(r,e);we.createArgument=(r,e)=>new Tn(r,e);we.Command=br;we.Option=Pn;we.Argument=Tn;we.Help=Ci;we.CommanderError=Ei;we.InvalidArgumentError=Rn;we.InvalidOptionArgumentError=Rn});function $n(r,e){Ln=r,Fn=e}function _(){return Ln?!0:Fn?!1:!process.stdout.isTTY}function F(r,e){console.log(JSON.stringify({ok:!0,command:r,data:e}))}function j(r,e,t){console.log(JSON.stringify({ok:!1,command:r,errors:[{code:e,message:t}]}))}function w(r){console.log(r)}function R(r){console.error(r)}function he(r,e=2){if(r.length===0)return"";let t=[];for(let n of r)for(let s=0;s<n.length;s++)t[s]=Math.max(t[s]||0,n[s].length);return r.map(n=>n.map((s,o)=>o<n.length-1?s.padEnd(t[o]+e):s).join("")).join(`
28
- `)}var Ln,Fn,te=pe(()=>{"use strict";Ln=!1,Fn=!1});var vt={};dt(vt,{addToManifest:()=>ue,clearAuth:()=>Or,clearLastSyncAt:()=>Ne,getAuth:()=>Ae,getConfig:()=>be,getManifest:()=>G,getSyncState:()=>Ii,removeFromManifest:()=>yt,saveAuth:()=>Ir,saveConfig:()=>Bn,saveManifest:()=>Ze,saveSyncState:()=>Oi,shouldSync:()=>vr,updateConfig:()=>Ot,updateManifestMeta:()=>kt});function mt(){let r=process.env.SC_PROFILE;return r?(0,ze.join)(Mn,"profiles",r):Mn}function xr(){return(0,ze.join)(mt(),"auth.json")}function Hn(){return(0,ze.join)(mt(),"config.json")}function _r(){return(0,ze.join)(mt(),"manifest.json")}function wi(){(0,Ee.mkdirSync)(mt(),{recursive:!0})}function ht(r,e){try{return(0,Ee.existsSync)(r)?JSON.parse((0,Ee.readFileSync)(r,"utf-8")):e}catch{return e}}function gt(r,e,t=!1){if(wi(),(0,Ee.writeFileSync)(r,JSON.stringify(e,null,2)+`
29
- `,"utf-8"),t)try{(0,Ee.chmodSync)(r,384)}catch{}}function Ae(){return ht(xr(),null)}function Ir(r){gt(xr(),r,!0)}function Or(){try{(0,Ee.writeFileSync)(xr(),"{}","utf-8")}catch{}}function be(){return ht(Hn(),Ai)}function Bn(r){gt(Hn(),r)}function Ot(r){let e=be();Bn({...e,...r})}function _i(r){if(r.version&&r.version>=2)return r;let e={version:2,installations:r.installations.map(s=>({...s,serverSynced:!1}))},t=kr(),n=ht(t,null);n?.lastSyncAt&&(e.lastSyncAt=n.lastSyncAt);try{(0,Ee.unlinkSync)(t)}catch{}return e}function G(){let r=ht(_r(),bi),e=_i(r);return(!r.version||r.version<2)&&gt(_r(),e),e}function Ze(r){gt(_r(),r)}function ue(r){let e=G(),t=e.installations.findIndex(n=>n.resourceId===r.resourceId&&n.agent===r.agent);t>=0?e.installations[t]=r:e.installations.push(r),Ze(e)}function yt(r,e){let t=G();t.installations=t.installations.filter(n=>!(n.resourceId===r&&(!e||n.agent===e))),Ze(t)}function Ne(){let r=G();delete r.lastSyncAt,Ze(r)}function kt(r){let e=G();r.lastSyncAt!==void 0&&(e.lastSyncAt=r.lastSyncAt),Ze(e)}function kr(){return(0,ze.join)(mt(),"last-sync.json")}function Ii(){return ht(kr(),null)}function Oi(r){gt(kr(),r)}function vr(){let r=parseInt(process.env.SC_SYNC_COOLDOWN||"",10),e=r>=0?r:xi,t=G();return t.lastSyncAt?Date.now()-new Date(t.lastSyncAt).getTime()>=e:!0}var Ee,ze,Un,Mn,Ai,bi,xi,fe=pe(()=>{"use strict";Ee=require("fs"),ze=require("path"),Un=require("os"),Mn=(0,ze.join)((0,Un.homedir)(),".config","shared-context");Ai={apiBase:"https://sharedcontext.ai"};bi={version:2,installations:[]};xi=720*60*1e3});var Gn={};dt(Gn,{del:()=>Tr,fetchRaw:()=>Rr,get:()=>z,isAuthenticated:()=>M,patch:()=>ki,post:()=>$});function Wn(){return be().apiBase||"https://sharedcontext.ai"}function Vn(){let r={"Content-Type":"application/json"},e=Ae();return e?.token&&(r.Authorization=`Bearer ${e.token}`),r}function M(){return!!Ae()?.token}async function Tt(r,e,t,n){let s=`${Wn()}${e}`;try{let o={method:r,headers:Vn(),body:t?JSON.stringify(t):void 0};n&&(o.signal=AbortSignal.timeout(n));let l=await fetch(s,o),c=l.headers.get("content-type")||"";if(!c.includes("application/json"))return l.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${c||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${l.status}`,message:l.statusText}};let u=await l.json();return l.ok?{ok:!0,data:u.data??u}:{ok:!1,error:{code:u?.error?.code||`HTTP_${l.status}`,message:u?.error?.message||u?.message||l.statusText}}}catch(o){return{ok:!1,error:{code:"NETWORK_ERROR",message:o instanceof Error?o.message:"Network request failed"}}}}function z(r){return Tt("GET",r)}function $(r,e,t){return Tt("POST",r,e,t)}function ki(r,e){return Tt("PATCH",r,e)}function Tr(r,e){return Tt("DELETE",r,e)}async function Rr(r){let e=`${Wn()}${r}`,t=await fetch(e,{headers:Vn()});if(!t.ok)throw new Error(`Download failed: ${t.status} ${t.statusText}`);return Buffer.from(await t.arrayBuffer())}var se=pe(()=>{"use strict";fe()});var Dr=Z((hc,qn)=>{"use strict";qn.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Rt=Z(Zn=>{"use strict";var zn={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function vi(r){return function(...e){return e.length&&(r=r.replace(/\{(\d)\}/g,(t,n)=>e[n]||"")),new Error("ADM-ZIP: "+r)}}for(let r of Object.keys(zn))Zn[r]=vi(zn[r])});var Qn=Z((yc,Yn)=>{"use strict";var Ti=require("fs"),ie=require("path"),Jn=Dr(),Ri=Rt(),Pi=typeof process=="object"&&process.platform==="win32",Kn=r=>typeof r=="object"&&r!==null,Xn=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Q(r){this.sep=ie.sep,this.fs=Ti,Kn(r)&&Kn(r.fs)&&typeof r.fs.statSync=="function"&&(this.fs=r.fs)}Yn.exports=Q;Q.prototype.makeDir=function(r){let e=this;function t(n){let s=n.split(e.sep)[0];n.split(e.sep).forEach(function(o){if(!(!o||o.substr(-1,1)===":")){s+=e.sep+o;var l;try{l=e.fs.statSync(s)}catch(c){if(c.message&&c.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw c}if(l&&l.isFile())throw Ri.FILE_IN_THE_WAY(`"${s}"`)}})}t(r)};Q.prototype.writeFileTo=function(r,e,t,n){let s=this;if(s.fs.existsSync(r)){if(!t)return!1;var o=s.fs.statSync(r);if(o.isDirectory())return!1}var l=ie.dirname(r);s.fs.existsSync(l)||s.makeDir(l);var c;try{c=s.fs.openSync(r,"w",438)}catch{s.fs.chmodSync(r,438),c=s.fs.openSync(r,"w",438)}if(c)try{s.fs.writeSync(c,e,0,e.length,0)}finally{s.fs.closeSync(c)}return s.fs.chmodSync(r,n||438),!0};Q.prototype.writeFileToAsync=function(r,e,t,n,s){typeof n=="function"&&(s=n,n=void 0);let o=this;o.fs.exists(r,function(l){if(l&&!t)return s(!1);o.fs.stat(r,function(c,u){if(l&&u.isDirectory())return s(!1);var a=ie.dirname(r);o.fs.exists(a,function(p){p||o.makeDir(a),o.fs.open(r,"w",438,function(S,x){S?o.fs.chmod(r,438,function(){o.fs.open(r,"w",438,function(d,m){o.fs.write(m,e,0,e.length,0,function(){o.fs.close(m,function(){o.fs.chmod(r,n||438,function(){s(!0)})})})})}):x?o.fs.write(x,e,0,e.length,0,function(){o.fs.close(x,function(){o.fs.chmod(r,n||438,function(){s(!0)})})}):o.fs.chmod(r,n||438,function(){s(!0)})})})})})};Q.prototype.findFiles=function(r){let e=this;function t(n,s,o){typeof s=="boolean"&&(o=s,s=void 0);let l=[];return e.fs.readdirSync(n).forEach(function(c){let u=ie.join(n,c),a=e.fs.statSync(u);(!s||s.test(u))&&l.push(ie.normalize(u)+(a.isDirectory()?e.sep:"")),a.isDirectory()&&o&&(l=l.concat(t(u,s,o)))}),l}return t(r,void 0,!0)};Q.prototype.findFilesAsync=function(r,e){let t=this,n=[];t.fs.readdir(r,function(s,o){if(s)return e(s);let l=o.length;if(!l)return e(null,n);o.forEach(function(c){c=ie.join(r,c),t.fs.stat(c,function(u,a){if(u)return e(u);a&&(n.push(ie.normalize(c)+(a.isDirectory()?t.sep:"")),a.isDirectory()?t.findFilesAsync(c,function(p,S){if(p)return e(p);n=n.concat(S),--l||e(null,n)}):--l||e(null,n))})})})};Q.prototype.getAttributes=function(){};Q.prototype.setAttributes=function(){};Q.crc32update=function(r,e){return Xn[(r^e)&255]^r>>>8};Q.crc32=function(r){typeof r=="string"&&(r=Buffer.from(r,"utf8"));let e=r.length,t=-1;for(let n=0;n<e;)t=Q.crc32update(t,r[n++]);return~t>>>0};Q.methodToString=function(r){switch(r){case Jn.STORED:return"STORED ("+r+")";case Jn.DEFLATED:return"DEFLATED ("+r+")";default:return"UNSUPPORTED ("+r+")"}};Q.canonical=function(r){if(!r)return"";let e=ie.posix.normalize("/"+r.split("\\").join("/"));return ie.join(".",e)};Q.zipnamefix=function(r){if(!r)return"";let e=ie.posix.normalize("/"+r.split("\\").join("/"));return ie.posix.join(".",e)};Q.findLast=function(r,e){if(!Array.isArray(r))throw new TypeError("arr is not array");let t=r.length>>>0;for(let n=t-1;n>=0;n--)if(e(r[n],n,r))return r[n]};Q.sanitize=function(r,e){r=ie.resolve(ie.normalize(r));for(var t=e.split("/"),n=0,s=t.length;n<s;n++){var o=ie.normalize(ie.join(r,t.slice(n,s).join(ie.sep)));if(o.indexOf(r)===0)return o}return ie.normalize(ie.join(r,ie.basename(e)))};Q.toBuffer=function(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?t(e):Buffer.alloc(0)};Q.readBigUInt64LE=function(r,e){let t=r.readUInt32LE(e);return r.readUInt32LE(e+4)*4294967296+t};Q.fromDOS2Date=function(r){return new Date((r>>25&127)+1980,Math.max((r>>21&15)-1,0),Math.max(r>>16&31,1),r>>11&31,r>>5&63,(r&31)<<1)};Q.fromDate2DOS=function(r){let e=0,t=0;return r.getFullYear()>1979&&(e=(r.getFullYear()-1980&127)<<9|r.getMonth()+1<<5|r.getDate(),t=r.getHours()<<11|r.getMinutes()<<5|r.getSeconds()>>1),e<<16|t};Q.isWin=Pi;Q.crcTable=Xn});var ts=Z((Sc,es)=>{"use strict";var Di=require("path");es.exports=function(r,{fs:e}){var t=r||"",n=o(),s=null;function o(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return t&&e.existsSync(t)?(s=e.statSync(t),n.directory=s.isDirectory(),n.mtime=s.mtime,n.atime=s.atime,n.executable=(73&s.mode)!==0,n.readonly=(128&s.mode)===0,n.hidden=Di.basename(t)[0]==="."):console.warn("Invalid path: "+t),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:t,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ns=Z((Ec,rs)=>{"use strict";rs.exports={efs:!0,encode:r=>Buffer.from(r,"utf8"),decode:r=>r.toString("utf8")}});var rt=Z((Cc,tt)=>{"use strict";tt.exports=Qn();tt.exports.Constants=Dr();tt.exports.Errors=Rt();tt.exports.FileAttr=ts();tt.exports.decoder=ns()});var os=Z((wc,ss)=>{"use strict";var $e=rt(),P=$e.Constants;ss.exports=function(){var r=20,e=10,t=0,n=0,s=0,o=0,l=0,c=0,u=0,a=0,p=0,S=0,x=0,d=0,m=0;r|=$e.isWin?2560:768,t|=P.FLG_EFS;let E={extraLen:0},f=i=>Math.max(0,i)>>>0,h=i=>Math.max(0,i)&65535,C=i=>Math.max(0,i)&255;return s=$e.fromDate2DOS(new Date),{get made(){return r},set made(i){r=i},get version(){return e},set version(i){e=i},get flags(){return t},set flags(i){t=i},get flags_efs(){return(t&P.FLG_EFS)>0},set flags_efs(i){i?t|=P.FLG_EFS:t&=~P.FLG_EFS},get flags_desc(){return(t&P.FLG_DESC)>0},set flags_desc(i){i?t|=P.FLG_DESC:t&=~P.FLG_DESC},get method(){return n},set method(i){switch(i){case P.STORED:this.version=10;case P.DEFLATED:default:this.version=20}n=i},get time(){return $e.fromDOS2Date(this.timeval)},set time(i){i=new Date(i),this.timeval=$e.fromDate2DOS(i)},get timeval(){return s},set timeval(i){s=f(i)},get timeHighByte(){return C(s>>>8)},get crc(){return o},set crc(i){o=f(i)},get compressedSize(){return l},set compressedSize(i){l=f(i)},get size(){return c},set size(i){c=f(i)},get fileNameLength(){return u},set fileNameLength(i){u=i},get extraLength(){return a},set extraLength(i){a=i},get extraLocalLength(){return E.extraLen},set extraLocalLength(i){E.extraLen=i},get commentLength(){return p},set commentLength(i){p=i},get diskNumStart(){return S},set diskNumStart(i){S=f(i)},get inAttr(){return x},set inAttr(i){x=f(i)},get attr(){return d},set attr(i){d=f(i)},get fileAttr(){return(d||0)>>16&4095},get offset(){return m},set offset(i){m=f(i)},get encrypted(){return(t&P.FLG_ENC)===P.FLG_ENC},get centralHeaderSize(){return P.CENHDR+u+a+p},get realDataOffset(){return m+P.LOCHDR+E.fnameLen+E.extraLen},get localHeader(){return E},loadLocalHeaderFromBinary:function(i){var y=i.slice(m,m+P.LOCHDR);if(y.readUInt32LE(0)!==P.LOCSIG)throw $e.Errors.INVALID_LOC();E.version=y.readUInt16LE(P.LOCVER),E.flags=y.readUInt16LE(P.LOCFLG),E.flags_desc=(E.flags&P.FLG_DESC)>0,E.method=y.readUInt16LE(P.LOCHOW),E.time=y.readUInt32LE(P.LOCTIM),E.crc=y.readUInt32LE(P.LOCCRC),E.compressedSize=y.readUInt32LE(P.LOCSIZ),E.size=y.readUInt32LE(P.LOCLEN),E.fnameLen=y.readUInt16LE(P.LOCNAM),E.extraLen=y.readUInt16LE(P.LOCEXT);let g=m+P.LOCHDR+E.fnameLen,A=g+E.extraLen;return i.slice(g,A)},loadFromBinary:function(i){if(i.length!==P.CENHDR||i.readUInt32LE(0)!==P.CENSIG)throw $e.Errors.INVALID_CEN();r=i.readUInt16LE(P.CENVEM),e=i.readUInt16LE(P.CENVER),t=i.readUInt16LE(P.CENFLG),n=i.readUInt16LE(P.CENHOW),s=i.readUInt32LE(P.CENTIM),o=i.readUInt32LE(P.CENCRC),l=i.readUInt32LE(P.CENSIZ),c=i.readUInt32LE(P.CENLEN),u=i.readUInt16LE(P.CENNAM),a=i.readUInt16LE(P.CENEXT),p=i.readUInt16LE(P.CENCOM),S=i.readUInt16LE(P.CENDSK),x=i.readUInt16LE(P.CENATT),d=i.readUInt32LE(P.CENATX),m=i.readUInt32LE(P.CENOFF)},localHeaderToBinary:function(){var i=Buffer.alloc(P.LOCHDR);return i.writeUInt32LE(P.LOCSIG,0),i.writeUInt16LE(e,P.LOCVER),i.writeUInt16LE(t,P.LOCFLG),i.writeUInt16LE(n,P.LOCHOW),i.writeUInt32LE(s,P.LOCTIM),i.writeUInt32LE(o,P.LOCCRC),i.writeUInt32LE(l,P.LOCSIZ),i.writeUInt32LE(c,P.LOCLEN),i.writeUInt16LE(u,P.LOCNAM),i.writeUInt16LE(E.extraLen,P.LOCEXT),i},centralHeaderToBinary:function(){var i=Buffer.alloc(P.CENHDR+u+a+p);return i.writeUInt32LE(P.CENSIG,0),i.writeUInt16LE(r,P.CENVEM),i.writeUInt16LE(e,P.CENVER),i.writeUInt16LE(t,P.CENFLG),i.writeUInt16LE(n,P.CENHOW),i.writeUInt32LE(s,P.CENTIM),i.writeUInt32LE(o,P.CENCRC),i.writeUInt32LE(l,P.CENSIZ),i.writeUInt32LE(c,P.CENLEN),i.writeUInt16LE(u,P.CENNAM),i.writeUInt16LE(a,P.CENEXT),i.writeUInt16LE(p,P.CENCOM),i.writeUInt16LE(S,P.CENDSK),i.writeUInt16LE(x,P.CENATT),i.writeUInt32LE(d,P.CENATX),i.writeUInt32LE(m,P.CENOFF),i},toJSON:function(){let i=function(y){return y+" bytes"};return{made:r,version:e,flags:t,method:$e.methodToString(n),time:this.time,crc:"0x"+o.toString(16).toUpperCase(),compressedSize:i(l),size:i(c),fileNameLength:i(u),extraLength:i(a),commentLength:i(p),diskNumStart:S,inAttr:x,attr:d,offset:m,centralHeaderSize:i(P.CENHDR+u+a+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var as=Z((Ac,is)=>{"use strict";var nt=rt(),J=nt.Constants;is.exports=function(){var r=0,e=0,t=0,n=0,s=0;return{get diskEntries(){return r},set diskEntries(o){r=e=o},get totalEntries(){return e},set totalEntries(o){e=r=o},get size(){return t},set size(o){t=o},get offset(){return n},set offset(o){n=o},get commentLength(){return s},set commentLength(o){s=o},get mainHeaderSize(){return J.ENDHDR+s},loadFromBinary:function(o){if((o.length!==J.ENDHDR||o.readUInt32LE(0)!==J.ENDSIG)&&(o.length<J.ZIP64HDR||o.readUInt32LE(0)!==J.ZIP64SIG))throw nt.Errors.INVALID_END();o.readUInt32LE(0)===J.ENDSIG?(r=o.readUInt16LE(J.ENDSUB),e=o.readUInt16LE(J.ENDTOT),t=o.readUInt32LE(J.ENDSIZ),n=o.readUInt32LE(J.ENDOFF),s=o.readUInt16LE(J.ENDCOM)):(r=nt.readBigUInt64LE(o,J.ZIP64SUB),e=nt.readBigUInt64LE(o,J.ZIP64TOT),t=nt.readBigUInt64LE(o,J.ZIP64SIZE),n=nt.readBigUInt64LE(o,J.ZIP64OFF),s=0)},toBinary:function(){var o=Buffer.alloc(J.ENDHDR+s);return o.writeUInt32LE(J.ENDSIG,0),o.writeUInt32LE(0,4),o.writeUInt16LE(r,J.ENDSUB),o.writeUInt16LE(e,J.ENDTOT),o.writeUInt32LE(t,J.ENDSIZ),o.writeUInt32LE(n,J.ENDOFF),o.writeUInt16LE(s,J.ENDCOM),o.fill(" ",J.ENDHDR),o},toJSON:function(){let o=function(l,c){let u=l.toString(16).toUpperCase();for(;u.length<c;)u="0"+u;return"0x"+u};return{diskEntries:r,totalEntries:e,size:t+" bytes",offset:o(n,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var jr=Z(Nr=>{"use strict";Nr.EntryHeader=os();Nr.MainHeader=as()});var ls=Z((_c,cs)=>{"use strict";cs.exports=function(r){var e=require("zlib"),t={chunkSize:(parseInt(r.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(r,t)},deflateAsync:function(n){var s=e.createDeflateRaw(t),o=[],l=0;s.on("data",function(c){o.push(c),l+=c.length}),s.on("end",function(){var c=Buffer.alloc(l),u=0;c.fill(0);for(var a=0;a<o.length;a++){var p=o[a];p.copy(c,u),u+=p.length}n&&n(c)}),s.end(r)}}}});var fs=Z((xc,us)=>{"use strict";var Ni=+(process.versions?process.versions.node:"").split(".")[0]||0;us.exports=function(r,e){var t=require("zlib");let n=Ni>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return t.inflateRawSync(r,n)},inflateAsync:function(s){var o=t.createInflateRaw(n),l=[],c=0;o.on("data",function(u){l.push(u),c+=u.length}),o.on("end",function(){var u=Buffer.alloc(c),a=0;u.fill(0);for(var p=0;p<l.length;p++){var S=l[p];S.copy(u,a),a+=S.length}s&&s(u)}),o.end(r)}}}});var gs=Z((Ic,hs)=>{"use strict";var{randomFillSync:ds}=require("crypto"),ji=Rt(),Li=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),ms=(r,e)=>Math.imul(r,e)>>>0,ps=(r,e)=>Li[(r^e)&255]^r>>>8,St=()=>typeof ds=="function"?ds(Buffer.alloc(12)):St.node();St.node=()=>{let r=Buffer.alloc(12),e=r.length;for(let t=0;t<e;t++)r[t]=Math.random()*256&255;return r};var Pt={genSalt:St};function Dt(r){let e=Buffer.isBuffer(r)?r:Buffer.from(r);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let t=0;t<e.length;t++)this.updateKeys(e[t])}Dt.prototype.updateKeys=function(r){let e=this.keys;return e[0]=ps(e[0],r),e[1]+=e[0]&255,e[1]=ms(e[1],134775813)+1,e[2]=ps(e[2],e[1]>>>24),r};Dt.prototype.next=function(){let r=(this.keys[2]|2)>>>0;return ms(r,r^1)>>8&255};function Fi(r){let e=new Dt(r);return function(t){let n=Buffer.alloc(t.length),s=0;for(let o of t)n[s++]=e.updateKeys(o^e.next());return n}}function $i(r){let e=new Dt(r);return function(t,n,s=0){n||(n=Buffer.alloc(t.length));for(let o of t){let l=e.next();n[s++]=o^l,e.updateKeys(o)}return n}}function Mi(r,e,t){if(!r||!Buffer.isBuffer(r)||r.length<12)return Buffer.alloc(0);let n=Fi(t),s=n(r.slice(0,12)),o=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==o)throw ji.WRONG_PASSWORD();return n(r.slice(12))}function Ui(r){Buffer.isBuffer(r)&&r.length>=12?Pt.genSalt=function(){return r.slice(0,12)}:r==="node"?Pt.genSalt=St.node:Pt.genSalt=St}function Hi(r,e,t,n=!1){r==null&&(r=Buffer.alloc(0)),Buffer.isBuffer(r)||(r=Buffer.from(r.toString()));let s=$i(t),o=Pt.genSalt();o[11]=e.crc>>>24&255,n&&(o[10]=e.crc>>>16&255);let l=Buffer.alloc(r.length+12);return s(o,l),s(r,l,12)}hs.exports={decrypt:Mi,encrypt:Hi,_salter:Ui}});var ys=Z(Nt=>{"use strict";Nt.Deflater=ls();Nt.Inflater=fs();Nt.ZipCrypto=gs()});var Fr=Z((kc,Ss)=>{"use strict";var H=rt(),Bi=jr(),ee=H.Constants,Lr=ys();Ss.exports=function(r,e){var t=new Bi.EntryHeader,n=Buffer.alloc(0),s=Buffer.alloc(0),o=!1,l=null,c=Buffer.alloc(0),u=Buffer.alloc(0),a=!0;let p=r,S=typeof p.decoder=="object"?p.decoder:H.decoder;a=S.hasOwnProperty("efs")?S.efs:!1;function x(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(u=t.loadLocalHeaderFromBinary(e),e.slice(t.realDataOffset,t.realDataOffset+t.compressedSize))}function d(i){if(!t.flags_desc&&!t.localHeader.flags_desc){if(H.crc32(i)!==t.localHeader.crc)return!1}else{let y={},g=t.realDataOffset+t.compressedSize;if(e.readUInt32LE(g)==ee.LOCSIG||e.readUInt32LE(g)==ee.CENSIG)throw H.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(g)==ee.EXTSIG)y.crc=e.readUInt32LE(g+ee.EXTCRC),y.compressedSize=e.readUInt32LE(g+ee.EXTSIZ),y.size=e.readUInt32LE(g+ee.EXTLEN);else if(e.readUInt16LE(g+12)===19280)y.crc=e.readUInt32LE(g+ee.EXTCRC-4),y.compressedSize=e.readUInt32LE(g+ee.EXTSIZ-4),y.size=e.readUInt32LE(g+ee.EXTLEN-4);else throw H.Errors.DESCRIPTOR_UNKNOWN();if(y.compressedSize!==t.compressedSize||y.size!==t.size||y.crc!==t.crc)throw H.Errors.DESCRIPTOR_FAULTY();if(H.crc32(i)!==y.crc)return!1}return!0}function m(i,y,g){if(typeof y>"u"&&typeof i=="string"&&(g=i,i=void 0),o)return i&&y&&y(Buffer.alloc(0),H.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var A=x();if(A.length===0)return i&&y&&y(A),A;if(t.encrypted){if(typeof g!="string"&&!Buffer.isBuffer(g))throw H.Errors.INVALID_PASS_PARAM();A=Lr.ZipCrypto.decrypt(A,t,g)}var b=Buffer.alloc(t.size);switch(t.method){case H.Constants.STORED:if(A.copy(b),d(b))return i&&y&&y(b),b;throw i&&y&&y(b,H.Errors.BAD_CRC()),H.Errors.BAD_CRC();case H.Constants.DEFLATED:var O=new Lr.Inflater(A,t.size);if(i)O.inflateAsync(function(k){k.copy(k,0),y&&(d(k)?y(k):y(k,H.Errors.BAD_CRC()))});else{if(O.inflate(b).copy(b,0),!d(b))throw H.Errors.BAD_CRC(`"${S.decode(n)}"`);return b}break;default:throw i&&y&&y(Buffer.alloc(0),H.Errors.UNKNOWN_METHOD()),H.Errors.UNKNOWN_METHOD()}}function E(i,y){if((!l||!l.length)&&Buffer.isBuffer(e))return i&&y&&y(x()),x();if(l.length&&!o){var g;switch(t.method){case H.Constants.STORED:return t.compressedSize=t.size,g=Buffer.alloc(l.length),l.copy(g),i&&y&&y(g),g;default:case H.Constants.DEFLATED:var A=new Lr.Deflater(l);if(i)A.deflateAsync(function(O){g=Buffer.alloc(O.length),t.compressedSize=O.length,O.copy(g),y&&y(g)});else{var b=A.deflate();return t.compressedSize=b.length,b}A=null;break}}else if(i&&y)y(Buffer.alloc(0));else return Buffer.alloc(0)}function f(i,y){return H.readBigUInt64LE(i,y)}function h(i){try{for(var y=0,g,A,b;y+4<i.length;)g=i.readUInt16LE(y),y+=2,A=i.readUInt16LE(y),y+=2,b=i.slice(y,y+A),y+=A,ee.ID_ZIP64===g&&C(b)}catch{throw H.Errors.EXTRA_FIELD_PARSE_ERROR()}}function C(i){var y,g,A,b;i.length>=ee.EF_ZIP64_SCOMP&&(y=f(i,ee.EF_ZIP64_SUNCOMP),t.size===ee.EF_ZIP64_OR_32&&(t.size=y)),i.length>=ee.EF_ZIP64_RHO&&(g=f(i,ee.EF_ZIP64_SCOMP),t.compressedSize===ee.EF_ZIP64_OR_32&&(t.compressedSize=g)),i.length>=ee.EF_ZIP64_DSN&&(A=f(i,ee.EF_ZIP64_RHO),t.offset===ee.EF_ZIP64_OR_32&&(t.offset=A)),i.length>=ee.EF_ZIP64_DSN+4&&(b=i.readUInt32LE(ee.EF_ZIP64_DSN),t.diskNumStart===ee.EF_ZIP64_OR_16&&(t.diskNumStart=b))}return{get entryName(){return S.decode(n)},get rawEntryName(){return n},set entryName(i){n=H.toBuffer(i,S.encode);var y=n[n.length-1];o=y===47||y===92,t.fileNameLength=n.length},get efs(){return typeof a=="function"?a(this.entryName):a},get extra(){return c},set extra(i){c=i,t.extraLength=i.length,h(i)},get comment(){return S.decode(s)},set comment(i){if(s=H.toBuffer(i,S.encode),t.commentLength=s.length,s.length>65535)throw H.Errors.COMMENT_TOO_LONG()},get name(){var i=S.decode(n);return o?i.substr(i.length-1).split("/").pop():i.split("/").pop()},get isDirectory(){return o},getCompressedData:function(){return E(!1,null)},getCompressedDataAsync:function(i){E(!0,i)},setData:function(i){l=H.toBuffer(i,H.decoder.encode),!o&&l.length?(t.size=l.length,t.method=H.Constants.DEFLATED,t.crc=H.crc32(i),t.changed=!0):t.method=H.Constants.STORED},getData:function(i){return t.changed?l:m(!1,null,i)},getDataAsync:function(i,y){t.changed?i(l):m(!0,i,y)},set attr(i){t.attr=i},get attr(){return t.attr},set header(i){t.loadFromBinary(i)},get header(){return t},packCentralHeader:function(){t.flags_efs=this.efs,t.extraLength=c.length;var i=t.centralHeaderToBinary(),y=H.Constants.CENHDR;return n.copy(i,y),y+=n.length,c.copy(i,y),y+=t.extraLength,s.copy(i,y),i},packLocalHeader:function(){let i=0;t.flags_efs=this.efs,t.extraLocalLength=u.length;let y=t.localHeaderToBinary(),g=Buffer.alloc(y.length+n.length+t.extraLocalLength);return y.copy(g,i),i+=y.length,n.copy(g,i),i+=n.length,u.copy(g,i),i+=u.length,g},toJSON:function(){let i=function(y){return"<"+(y&&y.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:t.toJSON(),compressedData:i(e),data:i(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ws=Z((vc,Cs)=>{"use strict";var Es=Fr(),Wi=jr(),de=rt();Cs.exports=function(r,e){var t=[],n={},s=Buffer.alloc(0),o=new Wi.MainHeader,l=!1,c=null;let u=new Set,a=e,{noSort:p,decoder:S}=a;r?m(a.readEntries):l=!0;function x(){let f=new Set;for(let h of Object.keys(n)){let C=h.split("/");if(C.pop(),!!C.length)for(let i=0;i<C.length;i++){let y=C.slice(0,i+1).join("/")+"/";f.add(y)}}for(let h of f)if(!(h in n)){let C=new Es(a);C.entryName=h,C.attr=16,C.temporary=!0,t.push(C),n[C.entryName]=C,u.add(C)}}function d(){if(l=!0,n={},o.diskEntries>(r.length-o.offset)/de.Constants.CENHDR)throw de.Errors.DISK_ENTRY_TOO_LARGE();t=new Array(o.diskEntries);for(var f=o.offset,h=0;h<t.length;h++){var C=f,i=new Es(a,r);i.header=r.slice(C,C+=de.Constants.CENHDR),i.entryName=r.slice(C,C+=i.header.fileNameLength),i.header.extraLength&&(i.extra=r.slice(C,C+=i.header.extraLength)),i.header.commentLength&&(i.comment=r.slice(C,C+i.header.commentLength)),f+=i.header.centralHeaderSize,t[h]=i,n[i.entryName]=i}u.clear(),x()}function m(f){var h=r.length-de.Constants.ENDHDR,C=Math.max(0,h-65535),i=C,y=r.length,g=-1,A=0;for(typeof a.trailingSpace=="boolean"&&a.trailingSpace&&(C=0),h;h>=i;h--)if(r[h]===80){if(r.readUInt32LE(h)===de.Constants.ENDSIG){g=h,A=h,y=h+de.Constants.ENDHDR,i=h-de.Constants.END64HDR;continue}if(r.readUInt32LE(h)===de.Constants.END64SIG){i=C;continue}if(r.readUInt32LE(h)===de.Constants.ZIP64SIG){g=h,y=h+de.readBigUInt64LE(r,h+de.Constants.ZIP64SIZE)+de.Constants.ZIP64LEAD;break}}if(g==-1)throw de.Errors.INVALID_FORMAT();o.loadFromBinary(r.slice(g,y)),o.commentLength&&(s=r.slice(A+de.Constants.ENDHDR)),f&&d()}function E(){t.length>1&&!p&&t.sort((f,h)=>f.entryName.toLowerCase().localeCompare(h.entryName.toLowerCase()))}return{get entries(){return l||d(),t.filter(f=>!u.has(f))},get comment(){return S.decode(s)},set comment(f){s=de.toBuffer(f,S.encode),o.commentLength=s.length},getEntryCount:function(){return l?t.length:o.diskEntries},forEach:function(f){this.entries.forEach(f)},getEntry:function(f){return l||d(),n[f]||null},setEntry:function(f){l||d(),t.push(f),n[f.entryName]=f,o.totalEntries=t.length},deleteFile:function(f,h=!0){l||d();let C=n[f];this.getEntryChildren(C,h).map(y=>y.entryName).forEach(this.deleteEntry)},deleteEntry:function(f){l||d();let h=n[f],C=t.indexOf(h);C>=0&&(t.splice(C,1),delete n[f],o.totalEntries=t.length)},getEntryChildren:function(f,h=!0){if(l||d(),typeof f=="object")if(f.isDirectory&&h){let C=[],i=f.entryName;for(let y of t)y.entryName.startsWith(i)&&C.push(y);return C}else return[f];return[]},getChildCount:function(f){if(f&&f.isDirectory){let h=this.getEntryChildren(f);return h.includes(f)?h.length-1:h.length}return 0},compressToBuffer:function(){l||d(),E();let f=[],h=[],C=0,i=0;o.size=0,o.offset=0;let y=0;for(let b of this.entries){let O=b.getCompressedData();b.header.offset=i;let k=b.packLocalHeader(),D=k.length+O.length;i+=D,f.push(k),f.push(O);let I=b.packCentralHeader();h.push(I),o.size+=I.length,C+=D+I.length,y++}C+=o.mainHeaderSize,o.offset=i,o.totalEntries=y,i=0;let g=Buffer.alloc(C);for(let b of f)b.copy(g,i),i+=b.length;for(let b of h)b.copy(g,i),i+=b.length;let A=o.toBinary();return s&&s.copy(A,de.Constants.ENDHDR),A.copy(g,i),r=g,l=!1,g},toAsyncBuffer:function(f,h,C,i){try{l||d(),E();let y=[],g=[],A=0,b=0,O=0;o.size=0,o.offset=0;let k=function(D){if(D.length>0){let I=D.shift(),T=I.entryName+I.extra.toString();C&&C(T),I.getCompressedDataAsync(function(v){i&&i(T),I.header.offset=b;let N=I.packLocalHeader(),L=N.length+v.length;b+=L,y.push(N),y.push(v);let q=I.packCentralHeader();g.push(q),o.size+=q.length,A+=L+q.length,O++,k(D)})}else{A+=o.mainHeaderSize,o.offset=b,o.totalEntries=O,b=0;let I=Buffer.alloc(A);y.forEach(function(v){v.copy(I,b),b+=v.length}),g.forEach(function(v){v.copy(I,b),b+=v.length});let T=o.toBinary();s&&s.copy(T,de.Constants.ENDHDR),T.copy(I,b),r=I,l=!1,f(I)}};k(Array.from(this.entries))}catch(y){h(y)}}}}});var _s=Z((Tc,bs)=>{"use strict";var X=rt(),K=require("path"),Vi=Fr(),Gi=ws(),Je=(...r)=>X.findLast(r,e=>typeof e=="boolean"),As=(...r)=>X.findLast(r,e=>typeof e=="string"),qi=(...r)=>X.findLast(r,e=>typeof e=="function"),zi={noSort:!1,readEntries:!1,method:X.Constants.NONE,fs:null};bs.exports=function(r,e){let t=null,n=Object.assign(Object.create(null),zi);r&&typeof r=="object"&&(r instanceof Uint8Array||(Object.assign(n,r),r=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(r)&&(t=r,n.method=X.Constants.BUFFER,r=void 0)),Object.assign(n,e);let s=new X(n);if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=X.decoder),r&&typeof r=="string")if(s.fs.existsSync(r))n.method=X.Constants.FILE,n.filename=r,t=s.fs.readFileSync(r);else throw X.Errors.INVALID_FILENAME();let o=new Gi(t,n),{canonical:l,sanitize:c,zipnamefix:u}=X;function a(d){if(d&&o){var m;if(typeof d=="string"&&(m=o.getEntry(K.posix.normalize(d))),typeof d=="object"&&typeof d.entryName<"u"&&typeof d.header<"u"&&(m=o.getEntry(d.entryName)),m)return m}return null}function p(d){let{join:m,normalize:E,sep:f}=K.posix;return m(K.isAbsolute(d)?"/":".",E(f+d.split("\\").join(f)+f))}function S(d){return d instanceof RegExp?(function(m){return function(E){return m.test(E)}})(d):typeof d!="function"?()=>!0:d}let x=(d,m)=>{let E=m.slice(-1);return E=E===s.sep?s.sep:"",K.relative(d,m)+E};return{readFile:function(d,m){var E=a(d);return E&&E.getData(m)||null},childCount:function(d){let m=a(d);if(m)return o.getChildCount(m)},readFileAsync:function(d,m){var E=a(d);E?E.getDataAsync(m):m(null,"getEntry failed for:"+d)},readAsText:function(d,m){var E=a(d);if(E){var f=E.getData();if(f&&f.length)return f.toString(m||"utf8")}return""},readAsTextAsync:function(d,m,E){var f=a(d);f?f.getDataAsync(function(h,C){if(C){m(h,C);return}h&&h.length?m(h.toString(E||"utf8")):m("")}):m("")},deleteFile:function(d,m=!0){var E=a(d);E&&o.deleteFile(E.entryName,m)},deleteEntry:function(d){var m=a(d);m&&o.deleteEntry(m.entryName)},addZipComment:function(d){o.comment=d},getZipComment:function(){return o.comment||""},addZipEntryComment:function(d,m){var E=a(d);E&&(E.comment=m)},getZipEntryComment:function(d){var m=a(d);return m&&m.comment||""},updateFile:function(d,m){var E=a(d);E&&E.setData(m)},addLocalFile:function(d,m,E,f){if(s.fs.existsSync(d)){m=m?p(m):"";let h=K.win32.basename(K.win32.normalize(d));m+=E||h;let C=s.fs.statSync(d),i=C.isFile()?s.fs.readFileSync(d):Buffer.alloc(0);C.isDirectory()&&(m+=s.sep),this.addFile(m,i,f,C)}else throw X.Errors.FILE_NOT_FOUND(d)},addLocalFileAsync:function(d,m){d=typeof d=="object"?d:{localPath:d};let E=K.resolve(d.localPath),{comment:f}=d,{zipPath:h,zipName:C}=d,i=this;s.fs.stat(E,function(y,g){if(y)return m(y,!1);h=h?p(h):"";let A=K.win32.basename(K.win32.normalize(E));if(h+=C||A,g.isFile())s.fs.readFile(E,function(b,O){return b?m(b,!1):(i.addFile(h,O,f,g),setImmediate(m,void 0,!0))});else if(g.isDirectory())return h+=s.sep,i.addFile(h,Buffer.alloc(0),f,g),setImmediate(m,void 0,!0)})},addLocalFolder:function(d,m,E){if(E=S(E),m=m?p(m):"",d=K.normalize(d),s.fs.existsSync(d)){let f=s.findFiles(d),h=this;if(f.length)for(let C of f){let i=K.join(m,x(d,C));E(i)&&h.addLocalFile(C,K.dirname(i))}}else throw X.Errors.FILE_NOT_FOUND(d)},addLocalFolderAsync:function(d,m,E,f){f=S(f),E=E?p(E):"",d=K.normalize(d);var h=this;s.fs.open(d,"r",function(C){if(C&&C.code==="ENOENT")m(void 0,X.Errors.FILE_NOT_FOUND(d));else if(C)m(void 0,C);else{var i=s.findFiles(d),y=-1,g=function(){if(y+=1,y<i.length){var A=i[y],b=x(d,A).split("\\").join("/");b=b.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),f(b)?s.fs.stat(A,function(O,k){O&&m(void 0,O),k.isFile()?s.fs.readFile(A,function(D,I){D?m(void 0,D):(h.addFile(E+b,I,"",k),g())}):(h.addFile(E+b+"/",Buffer.alloc(0),"",k),g())}):process.nextTick(()=>{g()})}else m(!0,void 0)};g()}})},addLocalFolderAsync2:function(d,m){let E=this;d=typeof d=="object"?d:{localPath:d},localPath=K.resolve(p(d.localPath));let{zipPath:f,filter:h,namefix:C}=d;h instanceof RegExp?h=(function(g){return function(A){return g.test(A)}})(h):typeof h!="function"&&(h=function(){return!0}),f=f?p(f):"",C=="latin1"&&(C=g=>g.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof C!="function"&&(C=g=>g);let i=g=>K.join(f,C(x(localPath,g))),y=g=>K.win32.basename(K.win32.normalize(C(g)));s.fs.open(localPath,"r",function(g){g&&g.code==="ENOENT"?m(void 0,X.Errors.FILE_NOT_FOUND(localPath)):g?m(void 0,g):s.findFilesAsync(localPath,function(A,b){if(A)return m(A);b=b.filter(O=>h(i(O))),b.length||m(void 0,!1),setImmediate(b.reverse().reduce(function(O,k){return function(D,I){if(D||I===!1)return setImmediate(O,D,!1);E.addLocalFileAsync({localPath:k,zipPath:K.dirname(i(k)),zipName:y(k)},O)}},m))})})},addLocalFolderPromise:function(d,m){return new Promise((E,f)=>{this.addLocalFolderAsync2(Object.assign({localPath:d},m),(h,C)=>{h&&f(h),C&&E(this)})})},addFile:function(d,m,E,f){d=u(d);let h=a(d),C=h!=null;C||(h=new Vi(n),h.entryName=d),h.comment=E||"";let i=typeof f=="object"&&f instanceof s.fs.Stats;i&&(h.header.time=f.mtime);var y=h.isDirectory?16:0;let g=h.isDirectory?16384:32768;return i?g|=4095&f.mode:typeof f=="number"?g|=4095&f:g|=h.isDirectory?493:420,y=(y|g<<16)>>>0,h.attr=y,h.setData(m),C||o.setEntry(h),h},getEntries:function(d){return o.password=d,o?o.entries:[]},getEntry:function(d){return a(d)},getEntryCount:function(){return o.getEntryCount()},forEach:function(d){return o.forEach(d)},extractEntryTo:function(d,m,E,f,h,C){f=Je(!1,f),h=Je(!1,h),E=Je(!0,E),C=As(h,C);var i=a(d);if(!i)throw X.Errors.NO_ENTRY();var y=l(i.entryName),g=c(m,C&&!i.isDirectory?C:E?y:K.basename(y));if(i.isDirectory){var A=o.getEntryChildren(i);return A.forEach(function(k){if(k.isDirectory)return;var D=k.getData();if(!D)throw X.Errors.CANT_EXTRACT_FILE();var I=l(k.entryName),T=c(m,E?I:K.basename(I));let v=h?k.header.fileAttr:void 0;s.writeFileTo(T,D,f,v)}),!0}var b=i.getData(o.password);if(!b)throw X.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(g)&&!f)throw X.Errors.CANT_OVERRIDE();let O=h?d.header.fileAttr:void 0;return s.writeFileTo(g,b,f,O),!0},test:function(d){if(!o)return!1;for(var m in o.entries)try{if(m.isDirectory)continue;var E=o.entries[m].getData(d);if(!E)return!1}catch{return!1}return!0},extractAllTo:function(d,m,E,f){if(E=Je(!1,E),f=As(E,f),m=Je(!1,m),!o)throw X.Errors.NO_ZIP();o.entries.forEach(function(h){var C=c(d,l(h.entryName));if(h.isDirectory){s.makeDir(C);return}var i=h.getData(f);if(!i)throw X.Errors.CANT_EXTRACT_FILE();let y=E?h.header.fileAttr:void 0;s.writeFileTo(C,i,m,y);try{s.fs.utimesSync(C,h.header.time,h.header.time)}catch{throw X.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(d,m,E,f){if(f=qi(m,E,f),E=Je(!1,E),m=Je(!1,m),!f)return new Promise((g,A)=>{this.extractAllToAsync(d,m,E,function(b){b?A(b):g(this)})});if(!o){f(X.Errors.NO_ZIP());return}d=K.resolve(d);let h=g=>c(d,K.normalize(l(g.entryName))),C=(g,A)=>new Error(g+': "'+A+'"'),i=[],y=[];o.entries.forEach(g=>{g.isDirectory?i.push(g):y.push(g)});for(let g of i){let A=h(g),b=E?g.header.fileAttr:void 0;try{s.makeDir(A),b&&s.fs.chmodSync(A,b),s.fs.utimesSync(A,g.header.time,g.header.time)}catch{f(C("Unable to create folder",A))}}y.reverse().reduce(function(g,A){return function(b){if(b)g(b);else{let O=K.normalize(l(A.entryName)),k=c(d,O);A.getDataAsync(function(D,I){if(I)g(I);else if(!D)g(X.Errors.CANT_EXTRACT_FILE());else{let T=E?A.header.fileAttr:void 0;s.writeFileToAsync(k,D,m,T,function(v){v||g(C("Unable to write file",k)),s.fs.utimes(k,A.header.time,A.header.time,function(N){N?g(C("Unable to set times",k)):g()})})}})}}},f)()},writeZip:function(d,m){if(arguments.length===1&&typeof d=="function"&&(m=d,d=""),!d&&n.filename&&(d=n.filename),!!d){var E=o.compressToBuffer();if(E){var f=s.writeFileTo(d,E,!0);typeof m=="function"&&m(f?null:new Error("failed"),"")}}},writeZipPromise:function(d,m){let{overwrite:E,perm:f}=Object.assign({overwrite:!0},m);return new Promise((h,C)=>{!d&&n.filename&&(d=n.filename),d||C("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(i=>{let y=g=>g?h(g):C("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(d,i,E,f,y)},C)})},toBufferPromise:function(){return new Promise((d,m)=>{o.toAsyncBuffer(d,m)})},toBuffer:function(d,m,E,f){return typeof d=="function"?(o.toAsyncBuffer(d,m,E,f),null):o.compressToBuffer()}}}});var Vs={};dt(Vs,{enableTelemetryHook:()=>Ws,registerConfig:()=>Vr});function Wr(){let r=process.env.SC_PROFILE;return r?(0,De.join)((0,lt.homedir)(),".config","shared-context","profiles",r):(0,De.join)((0,lt.homedir)(),".config","shared-context")}function Ws(){try{let r=(0,De.join)((0,lt.homedir)(),".claude","settings.json"),{readFileSync:e,writeFileSync:t}=require("fs"),n={};try{(0,He.existsSync)(r)&&(n=JSON.parse(e(r,"utf8")))}catch{}n.hooks||(n.hooks={});let s=n.hooks;if(s.PostToolUse||(s.PostToolUse=[]),s.PostToolUse.some(p=>p._sc===Bs))return;let l=(0,De.join)(Wr(),"manifest.json"),c="";try{let S=(JSON.parse(e(l,"utf8")).installations||[]).find(x=>x.slug==="telemetry"||x.installPath?.includes("hooks/telemetry"));S?.installPath&&(c=(0,De.join)((0,lt.homedir)(),".config","shared-context",S.installPath,"scripts","telemetry.js"))}catch{}if((!c||!(0,He.existsSync)(c))&&(c=(0,De.join)(Wr(),"hooks","telemetry","scripts","telemetry.js")),!(0,He.existsSync)(c))return;s.PostToolUse.push({hooks:[{type:"command",command:`node ${c}`}],_sc:Bs}),s.SessionStart||(s.SessionStart=[]);let u="platform/telemetry-push";s.SessionStart.some(p=>p._sc===u)||s.SessionStart.push({hooks:[{type:"command",command:"npx shared-context-ai telemetry push --quiet 2>/dev/null || true"}],_sc:u}),t(r,JSON.stringify(n,null,2)+`
30
- `,"utf8")}catch{}}function ha(){Ot({telemetry:!1});let r=(0,De.join)(Wr(),"usage.jsonl");try{(0,He.existsSync)(r)&&(0,He.unlinkSync)(r)}catch{}try{let e=(0,De.join)((0,lt.homedir)(),".claude","settings.json");if((0,He.existsSync)(e)){let{readFileSync:t,writeFileSync:n}=require("fs"),s=JSON.parse(t(e,"utf8"));if(s.hooks){let o=!1,l=new Set(["hooks/shared-context/telemetry","platform/telemetry-push"]);for(let[c,u]of Object.entries(s.hooks))if(Array.isArray(u)){let a=u.filter(p=>!l.has(p._sc));a.length!==u.length&&(s.hooks[c]=a,o=!0)}for(let[c,u]of Object.entries(s.hooks))Array.isArray(u)&&u.length===0&&delete s.hooks[c];o&&n(e,JSON.stringify(s,null,2)+`
31
- `,"utf8")}}}catch{}}function Vr(r){let e=r.command("config").description("Manage CLI configuration");e.command("set <key> <value>").description("Set a configuration value (e.g., telemetry on/off)").action((t,n)=>{if(t==="telemetry"){let s=n==="on"||n==="true"||n==="1",o=n==="off"||n==="false"||n==="0";if(!s&&!o){_()?j("config","INVALID_VALUE","Telemetry value must be on or off"):R("Usage: shared-context-ai config set telemetry on|off");return}o?(ha(),_()?F("config",{key:"telemetry",value:!1}):w("Telemetry disabled. Usage data and hooks removed.")):(Ot({telemetry:!0}),Ws(),_()?F("config",{key:"telemetry",value:!0}):w("Telemetry enabled. Usage data will be collected and uploaded."));return}_()?j("config","UNKNOWN_KEY",`Unknown config key: ${t}`):R(`Unknown config key: ${t}. Available: telemetry`)}),e.command("get [key]").description("Show configuration values").action(t=>{let n=be();if(t==="telemetry"){let s=n.telemetry??!1;_()?F("config",{key:"telemetry",value:s}):w(`telemetry: ${s?"on":"off"}`);return}if(t){_()?j("config","UNKNOWN_KEY",`Unknown config key: ${t}`):R(`Unknown config key: ${t}`);return}_()?F("config",{telemetry:n.telemetry??!1}):w(`telemetry: ${n.telemetry?"on":"off"}`)})}var He,De,lt,Bs,Gr=pe(()=>{"use strict";He=require("fs"),De=require("path"),lt=require("os");fe();te();Bs="hooks/shared-context/telemetry"});function Ca(){try{return zr.default.statSync("/.dockerenv"),!0}catch{return!1}}function wa(){try{return zr.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Zr(){return qr===void 0&&(qr=Ca()||wa()),qr}var zr,qr,Js=pe(()=>{"use strict";zr=me(require("fs"),1)});function Qe(){return Jr===void 0&&(Jr=Aa()||Zr()),Jr}var Ks,Jr,Aa,Kr=pe(()=>{"use strict";Ks=me(require("fs"),1);Js();Aa=()=>{try{return Ks.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var Xr,Ys,Kt,Xs,We,Yr=pe(()=>{"use strict";Xr=me(require("process"),1),Ys=me(require("os"),1),Kt=me(require("fs"),1);Kr();Xs=()=>{if(Xr.default.platform!=="linux")return!1;if(Ys.default.release().toLowerCase().includes("microsoft"))return!Qe();try{if(Kt.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!Qe()}catch{}return Kt.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||Kt.default.existsSync("/run/WSL")?!Qe():!1},We=Xr.default.env.__IS_WSL_TEST__?Xs:Xs()});var Qr,wt,ba,_a,en,Qs=pe(()=>{"use strict";Qr=me(require("process"),1),wt=me(require("fs/promises"),1);Yr();Yr();ba=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await wt.default.access(t,wt.constants.F_OK),n=!0}catch{}if(!n)return r;let s=await wt.default.readFile(t,{encoding:"utf8"}),o=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return o?(e=o.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),_a=async()=>`${await ba()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,en=async()=>We?_a():`${Qr.default.env.SYSTEMROOT||Qr.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Ve(r,e,t){let n=s=>Object.defineProperty(r,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let s=t();return n(s),s},set(s){n(s)}}),r}var eo=pe(()=>{"use strict"});async function tn(){if(ro.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await xa("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(r)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var to,ro,no,xa,so=pe(()=>{"use strict";to=require("util"),ro=me(require("process"),1),no=require("child_process"),xa=(0,to.promisify)(no.execFile)});async function ao(r,{humanReadableOutput:e=!0,signal:t}={}){if(oo.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:o}=await Ia("osascript",["-e",r,n],s);return o.trim()}var oo,io,rn,Ia,co=pe(()=>{"use strict";oo=me(require("process"),1),io=require("util"),rn=require("child_process"),Ia=(0,io.promisify)(rn.execFile)});async function nn(r){return ao(`tell application "Finder" to set app_path to application file id "${r}" as string
32
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var lo=pe(()=>{"use strict";co()});async function on(r=Oa){let{stdout:e}=await r("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 sn(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,s=n.lastIndexOf("."),o=n.lastIndexOf("-"),l=s===-1?void 0:n.slice(0,s),c=o===-1?void 0:n.slice(0,o);return Xt[n]??Xt[l]??Xt[c]??{name:n,id:n}}var uo,fo,Oa,Xt,Bl,sn,po=pe(()=>{"use strict";uo=require("util"),fo=require("child_process"),Oa=(0,uo.promisify)(fo.execFile),Xt={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"}},Bl=new Map(Object.entries(Xt)),sn=class extends Error{}});async function an(){if(Yt.default.platform==="darwin"){let r=await tn();return{name:await nn(r),id:r}}if(Yt.default.platform==="linux"){let{stdout:r}=await ka("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:va(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(Yt.default.platform==="win32")return on();throw new Error("Only macOS, Linux, and Windows are supported")}var mo,Yt,ho,ka,va,go=pe(()=>{"use strict";mo=require("util"),Yt=me(require("process"),1),ho=require("child_process");so();lo();po();ka=(0,mo.promisify)(ho.execFile),va=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var bo={};dt(bo,{apps:()=>Ge,default:()=>Na,openApp:()=>Da});async function Ra(){let r=await en(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=un.Buffer.from(e,"utf16le").toString("base64"),{stdout:n}=await Ta(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=n.trim(),o={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return o[s]?{id:o[s]}:{}}function Co(r){if(typeof r=="string"||Array.isArray(r))return r;let{[So]:e}=r;if(!e)throw new Error(`${So} is not supported`);return e}function er({[ut]:r},{wsl:e}){if(e&&We)return Co(e);if(!r)throw new Error(`${ut} is not supported`);return Co(r)}var ln,un,fn,wo,Ao,dn,Qt,ja,Ta,cn,yo,ut,So,Eo,At,Pa,Da,Ge,Na,_o=pe(()=>{"use strict";ln=me(require("process"),1),un=require("buffer"),fn=me(require("path"),1),wo=require("url"),Ao=require("util"),dn=me(require("child_process"),1),Qt=me(require("fs/promises"),1);Qs();eo();go();Kr();ja={},Ta=(0,Ao.promisify)(dn.default.execFile),cn=fn.default.dirname((0,wo.fileURLToPath)(ja.url)),yo=fn.default.join(cn,"xdg-open"),{platform:ut,arch:So}=ln.default;Eo=async(r,e)=>{let t;for(let n of r)try{return await e(n)}catch(s){t=s}throw t},At=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return Eo(r.app,c=>At({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return Eo(e,c=>At({...r,app:{name:c,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let c={"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"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},a=We?await Ra():await an();if(a.id in c){let p=c[a.id];return e==="browserPrivate"&&t.push(u[p]),At({...r,app:{name:Ge[p],arguments:t}})}throw new Error(`${a.name} is not supported as a default browser`)}let n,s=[],o={};if(ut==="darwin")n="open",r.wait&&s.push("--wait-apps"),r.background&&s.push("--background"),r.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(ut==="win32"||We&&!Qe()&&!e){n=await en(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),We||(o.windowsVerbatimArguments=!0);let c=["Start"];r.wait&&c.push("-Wait"),e?(c.push(`"\`"${e}\`""`),r.target&&t.push(r.target)):r.target&&c.push(`"${r.target}"`),t.length>0&&(t=t.map(u=>`"\`"${u}\`""`),c.push("-ArgumentList",t.join(","))),r.target=un.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let c=!cn||cn==="/",u=!1;try{await Qt.default.access(yo,Qt.constants.X_OK),u=!0}catch{}n=ln.default.versions.electron??(ut==="android"||c||!u)?"xdg-open":yo}t.length>0&&s.push(...t),r.wait||(o.stdio="ignore",o.detached=!0)}ut==="darwin"&&t.length>0&&s.push("--args",...t),r.target&&s.push(r.target);let l=dn.default.spawn(n,s,o);return r.wait?new Promise((c,u)=>{l.once("error",u),l.once("close",a=>{if(!r.allowNonzeroExitCode&&a>0){u(new Error(`Exited with code ${a}`));return}c(l)})}):(l.unref(),l)},Pa=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return At({...e,target:r})},Da=(r,e)=>{if(typeof r!="string"&&!Array.isArray(r))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 At({...e,app:{name:r,arguments:t}})};Ge={};Ve(Ge,"chrome",()=>er({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"]}}));Ve(Ge,"brave",()=>er({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"]}}));Ve(Ge,"firefox",()=>er({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Ve(Ge,"edge",()=>er({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Ve(Ge,"browser",()=>"browser");Ve(Ge,"browserPrivate",()=>"browserPrivate");Na=Pa});var zo={};dt(zo,{pushTelemetry:()=>qo,registerTelemetry:()=>mn});function Ua(){let r=process.env.SC_PROFILE;return r?(0,rr.join)((0,pn.homedir)(),".config","shared-context","profiles",r):(0,rr.join)((0,pn.homedir)(),".config","shared-context")}function Go(){return(0,rr.join)(Ua(),"usage.jsonl")}function Ha(){let r=Go();if(!(0,qe.existsSync)(r))return[];try{let e=(0,qe.readFileSync)(r,"utf8").trim().split(`
33
- `).filter(Boolean),t=[];for(let n of e)try{let s=JSON.parse(n);s.v&&s.ts&&s.event&&s.rid&&t.push(s)}catch{}return t}catch{return[]}}function Ba(r){let e=Go();if((0,qe.existsSync)(e))try{let t=(0,qe.readFileSync)(e,"utf8").trim().split(`
34
- `).filter(Boolean);if(t.length<=r)return;let n=t.slice(-r);(0,qe.writeFileSync)(e,n.join(`
27
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Rn(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?s=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],s=o[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}function Ir(){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}xr.Command=_r;xr.useColor=Ir});var $n=K(_e=>{"use strict";var{Argument:Dn}=kt(),{Command:Or}=Pn(),{CommanderError:wi,InvalidArgumentError:Nn}=St(),{Help:bi}=yr(),{Option:jn}=wr();_e.program=new Or;_e.createCommand=r=>new Or(r);_e.createOption=(r,e)=>new jn(r,e);_e.createArgument=(r,e)=>new Dn(r,e);_e.Command=Or;_e.Option=jn;_e.Argument=Dn;_e.Help=bi;_e.CommanderError=wi;_e.InvalidArgumentError=Nn;_e.InvalidOptionArgumentError=Nn});function Hn(r,e){Mn=r,Un=e}function A(){return Mn?!0:Un?!1:!process.stdout.isTTY}function F(r,e){console.log(JSON.stringify({ok:!0,command:r,data:e}))}function $(r,e,t){console.log(JSON.stringify({ok:!1,command:r,errors:[{code:e,message:t}]}))}function w(r){console.log(r)}function R(r){console.error(r)}function Se(r,e=2){if(r.length===0)return"";let t=[];for(let n of r)for(let s=0;s<n.length;s++)t[s]=Math.max(t[s]||0,n[s].length);return r.map(n=>n.map((s,o)=>o<n.length-1?s.padEnd(t[o]+e):s).join("")).join(`
28
+ `)}var Mn,Un,se=ge(()=>{"use strict";Mn=!1,Un=!1});var Pt={};yt(Pt,{addToManifest:()=>pe,clearAuth:()=>Rr,clearLastSyncAt:()=>Me,getAuth:()=>Ie,getConfig:()=>xe,getManifest:()=>z,getSyncState:()=>ki,removeFromManifest:()=>bt,saveAuth:()=>Tr,saveConfig:()=>qn,saveManifest:()=>Le,saveSyncState:()=>vi,shouldSync:()=>Dr,updateConfig:()=>Tt,updateManifestMeta:()=>Rt});function Et(){let r=process.env.SC_PROFILE;return r?(0,Xe.join)(Bn,"profiles",r):Bn}function vr(){return(0,Xe.join)(Et(),"auth.json")}function Vn(){return(0,Xe.join)(Et(),"config.json")}function kr(){return(0,Xe.join)(Et(),"manifest.json")}function Ai(){(0,we.mkdirSync)(Et(),{recursive:!0})}function Ct(r,e){try{return(0,we.existsSync)(r)?JSON.parse((0,we.readFileSync)(r,"utf-8")):e}catch{return e}}function wt(r,e,t=!1){if(Ai(),(0,we.writeFileSync)(r,JSON.stringify(e,null,2)+`
29
+ `,"utf-8"),t)try{(0,we.chmodSync)(r,384)}catch{}}function Ie(){return Ct(vr(),null)}function Tr(r){wt(vr(),r,!0)}function Rr(){try{(0,we.writeFileSync)(vr(),"{}","utf-8")}catch{}}function xe(){return Ct(Vn(),_i)}function qn(r){wt(Vn(),r)}function Tt(r){let e=xe();qn({...e,...r})}function xi(r){if(r.version&&r.version>=2)return r;let e={version:2,installations:r.installations.map(s=>({...s,serverSynced:!1}))},t=Pr(),n=Ct(t,null);n?.lastSyncAt&&(e.lastSyncAt=n.lastSyncAt);try{(0,we.unlinkSync)(t)}catch{}return e}function z(){let r=Ct(kr(),Ii),e=xi(r);return(!r.version||r.version<2)&&wt(kr(),e),e}function Le(r){wt(kr(),r)}function pe(r){let e=z(),t=e.installations.findIndex(n=>n.resourceId===r.resourceId&&n.agent===r.agent);t>=0?e.installations[t]=r:e.installations.push(r),Le(e)}function bt(r,e){let t=z();t.installations=t.installations.filter(n=>!(n.resourceId===r&&(!e||n.agent===e))),Le(t)}function Me(){let r=z();delete r.lastSyncAt,Le(r)}function Rt(r){let e=z();r.lastSyncAt!==void 0&&(e.lastSyncAt=r.lastSyncAt),Le(e)}function Pr(){return(0,Xe.join)(Et(),"last-sync.json")}function ki(){return Ct(Pr(),null)}function vi(r){wt(Pr(),r)}function Dr(){let r=parseInt(process.env.SC_SYNC_COOLDOWN||"",10),e=r>=0?r:Oi,t=z();return t.lastSyncAt?Date.now()-new Date(t.lastSyncAt).getTime()>=e:!0}var we,Xe,Wn,Bn,_i,Ii,Oi,me=ge(()=>{"use strict";we=require("fs"),Xe=require("path"),Wn=require("os"),Bn=(0,Xe.join)((0,Wn.homedir)(),".config","shared-context");_i={apiBase:"https://sharedcontext.ai"};Ii={version:2,installations:[]};Oi=720*60*1e3});var Zn={};yt(Zn,{del:()=>Nr,fetchRaw:()=>jr,get:()=>Z,isAuthenticated:()=>U,patch:()=>Ti,post:()=>L});function Gn(){return xe().apiBase||"https://sharedcontext.ai"}function zn(){let r={"Content-Type":"application/json"},e=Ie();return e?.token&&(r.Authorization=`Bearer ${e.token}`),r}function U(){return!!Ie()?.token}async function Dt(r,e,t,n){let s=`${Gn()}${e}`;try{let o={method:r,headers:zn(),body:t?JSON.stringify(t):void 0};n&&(o.signal=AbortSignal.timeout(n));let l=await fetch(s,o),c=l.headers.get("content-type")||"";if(!c.includes("application/json"))return l.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${c||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${l.status}`,message:l.statusText}};let u=await l.json();return l.ok?{ok:!0,data:u.data??u}:{ok:!1,error:{code:u?.error?.code||`HTTP_${l.status}`,message:u?.error?.message||u?.message||l.statusText}}}catch(o){return{ok:!1,error:{code:"NETWORK_ERROR",message:o instanceof Error?o.message:"Network request failed"}}}}function Z(r){return Dt("GET",r)}function L(r,e,t){return Dt("POST",r,e,t)}function Ti(r,e){return Dt("PATCH",r,e)}function Nr(r,e){return Dt("DELETE",r,e)}async function jr(r){let e=`${Gn()}${r}`,t=await fetch(e,{headers:zn()});if(!t.ok)throw new Error(`Download failed: ${t.status} ${t.statusText}`);return Buffer.from(await t.arrayBuffer())}var ie=ge(()=>{"use strict";me()});var Fr=K((Sc,Jn)=>{"use strict";Jn.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Nt=K(Xn=>{"use strict";var Kn={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function Ri(r){return function(...e){return e.length&&(r=r.replace(/\{(\d)\}/g,(t,n)=>e[n]||"")),new Error("ADM-ZIP: "+r)}}for(let r of Object.keys(Kn))Xn[r]=Ri(Kn[r])});var rs=K((Cc,ts)=>{"use strict";var Pi=require("fs"),ce=require("path"),Yn=Fr(),Di=Nt(),Ni=typeof process=="object"&&process.platform==="win32",Qn=r=>typeof r=="object"&&r!==null,es=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function ee(r){this.sep=ce.sep,this.fs=Pi,Qn(r)&&Qn(r.fs)&&typeof r.fs.statSync=="function"&&(this.fs=r.fs)}ts.exports=ee;ee.prototype.makeDir=function(r){let e=this;function t(n){let s=n.split(e.sep)[0];n.split(e.sep).forEach(function(o){if(!(!o||o.substr(-1,1)===":")){s+=e.sep+o;var l;try{l=e.fs.statSync(s)}catch(c){if(c.message&&c.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw c}if(l&&l.isFile())throw Di.FILE_IN_THE_WAY(`"${s}"`)}})}t(r)};ee.prototype.writeFileTo=function(r,e,t,n){let s=this;if(s.fs.existsSync(r)){if(!t)return!1;var o=s.fs.statSync(r);if(o.isDirectory())return!1}var l=ce.dirname(r);s.fs.existsSync(l)||s.makeDir(l);var c;try{c=s.fs.openSync(r,"w",438)}catch{s.fs.chmodSync(r,438),c=s.fs.openSync(r,"w",438)}if(c)try{s.fs.writeSync(c,e,0,e.length,0)}finally{s.fs.closeSync(c)}return s.fs.chmodSync(r,n||438),!0};ee.prototype.writeFileToAsync=function(r,e,t,n,s){typeof n=="function"&&(s=n,n=void 0);let o=this;o.fs.exists(r,function(l){if(l&&!t)return s(!1);o.fs.stat(r,function(c,u){if(l&&u.isDirectory())return s(!1);var a=ce.dirname(r);o.fs.exists(a,function(p){p||o.makeDir(a),o.fs.open(r,"w",438,function(S,I){S?o.fs.chmod(r,438,function(){o.fs.open(r,"w",438,function(d,m){o.fs.write(m,e,0,e.length,0,function(){o.fs.close(m,function(){o.fs.chmod(r,n||438,function(){s(!0)})})})})}):I?o.fs.write(I,e,0,e.length,0,function(){o.fs.close(I,function(){o.fs.chmod(r,n||438,function(){s(!0)})})}):o.fs.chmod(r,n||438,function(){s(!0)})})})})})};ee.prototype.findFiles=function(r){let e=this;function t(n,s,o){typeof s=="boolean"&&(o=s,s=void 0);let l=[];return e.fs.readdirSync(n).forEach(function(c){let u=ce.join(n,c),a=e.fs.statSync(u);(!s||s.test(u))&&l.push(ce.normalize(u)+(a.isDirectory()?e.sep:"")),a.isDirectory()&&o&&(l=l.concat(t(u,s,o)))}),l}return t(r,void 0,!0)};ee.prototype.findFilesAsync=function(r,e){let t=this,n=[];t.fs.readdir(r,function(s,o){if(s)return e(s);let l=o.length;if(!l)return e(null,n);o.forEach(function(c){c=ce.join(r,c),t.fs.stat(c,function(u,a){if(u)return e(u);a&&(n.push(ce.normalize(c)+(a.isDirectory()?t.sep:"")),a.isDirectory()?t.findFilesAsync(c,function(p,S){if(p)return e(p);n=n.concat(S),--l||e(null,n)}):--l||e(null,n))})})})};ee.prototype.getAttributes=function(){};ee.prototype.setAttributes=function(){};ee.crc32update=function(r,e){return es[(r^e)&255]^r>>>8};ee.crc32=function(r){typeof r=="string"&&(r=Buffer.from(r,"utf8"));let e=r.length,t=-1;for(let n=0;n<e;)t=ee.crc32update(t,r[n++]);return~t>>>0};ee.methodToString=function(r){switch(r){case Yn.STORED:return"STORED ("+r+")";case Yn.DEFLATED:return"DEFLATED ("+r+")";default:return"UNSUPPORTED ("+r+")"}};ee.canonical=function(r){if(!r)return"";let e=ce.posix.normalize("/"+r.split("\\").join("/"));return ce.join(".",e)};ee.zipnamefix=function(r){if(!r)return"";let e=ce.posix.normalize("/"+r.split("\\").join("/"));return ce.posix.join(".",e)};ee.findLast=function(r,e){if(!Array.isArray(r))throw new TypeError("arr is not array");let t=r.length>>>0;for(let n=t-1;n>=0;n--)if(e(r[n],n,r))return r[n]};ee.sanitize=function(r,e){r=ce.resolve(ce.normalize(r));for(var t=e.split("/"),n=0,s=t.length;n<s;n++){var o=ce.normalize(ce.join(r,t.slice(n,s).join(ce.sep)));if(o.indexOf(r)===0)return o}return ce.normalize(ce.join(r,ce.basename(e)))};ee.toBuffer=function(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?t(e):Buffer.alloc(0)};ee.readBigUInt64LE=function(r,e){let t=r.readUInt32LE(e);return r.readUInt32LE(e+4)*4294967296+t};ee.fromDOS2Date=function(r){return new Date((r>>25&127)+1980,Math.max((r>>21&15)-1,0),Math.max(r>>16&31,1),r>>11&31,r>>5&63,(r&31)<<1)};ee.fromDate2DOS=function(r){let e=0,t=0;return r.getFullYear()>1979&&(e=(r.getFullYear()-1980&127)<<9|r.getMonth()+1<<5|r.getDate(),t=r.getHours()<<11|r.getMinutes()<<5|r.getSeconds()>>1),e<<16|t};ee.isWin=Ni;ee.crcTable=es});var ss=K((wc,ns)=>{"use strict";var ji=require("path");ns.exports=function(r,{fs:e}){var t=r||"",n=o(),s=null;function o(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return t&&e.existsSync(t)?(s=e.statSync(t),n.directory=s.isDirectory(),n.mtime=s.mtime,n.atime=s.atime,n.executable=(73&s.mode)!==0,n.readonly=(128&s.mode)===0,n.hidden=ji.basename(t)[0]==="."):console.warn("Invalid path: "+t),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:t,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var is=K((bc,os)=>{"use strict";os.exports={efs:!0,encode:r=>Buffer.from(r,"utf8"),decode:r=>r.toString("utf8")}});var ct=K((Ac,at)=>{"use strict";at.exports=rs();at.exports.Constants=Fr();at.exports.Errors=Nt();at.exports.FileAttr=ss();at.exports.decoder=is()});var cs=K((_c,as)=>{"use strict";var We=ct(),P=We.Constants;as.exports=function(){var r=20,e=10,t=0,n=0,s=0,o=0,l=0,c=0,u=0,a=0,p=0,S=0,I=0,d=0,m=0;r|=We.isWin?2560:768,t|=P.FLG_EFS;let E={extraLen:0},f=i=>Math.max(0,i)>>>0,h=i=>Math.max(0,i)&65535,C=i=>Math.max(0,i)&255;return s=We.fromDate2DOS(new Date),{get made(){return r},set made(i){r=i},get version(){return e},set version(i){e=i},get flags(){return t},set flags(i){t=i},get flags_efs(){return(t&P.FLG_EFS)>0},set flags_efs(i){i?t|=P.FLG_EFS:t&=~P.FLG_EFS},get flags_desc(){return(t&P.FLG_DESC)>0},set flags_desc(i){i?t|=P.FLG_DESC:t&=~P.FLG_DESC},get method(){return n},set method(i){switch(i){case P.STORED:this.version=10;case P.DEFLATED:default:this.version=20}n=i},get time(){return We.fromDOS2Date(this.timeval)},set time(i){i=new Date(i),this.timeval=We.fromDate2DOS(i)},get timeval(){return s},set timeval(i){s=f(i)},get timeHighByte(){return C(s>>>8)},get crc(){return o},set crc(i){o=f(i)},get compressedSize(){return l},set compressedSize(i){l=f(i)},get size(){return c},set size(i){c=f(i)},get fileNameLength(){return u},set fileNameLength(i){u=i},get extraLength(){return a},set extraLength(i){a=i},get extraLocalLength(){return E.extraLen},set extraLocalLength(i){E.extraLen=i},get commentLength(){return p},set commentLength(i){p=i},get diskNumStart(){return S},set diskNumStart(i){S=f(i)},get inAttr(){return I},set inAttr(i){I=f(i)},get attr(){return d},set attr(i){d=f(i)},get fileAttr(){return(d||0)>>16&4095},get offset(){return m},set offset(i){m=f(i)},get encrypted(){return(t&P.FLG_ENC)===P.FLG_ENC},get centralHeaderSize(){return P.CENHDR+u+a+p},get realDataOffset(){return m+P.LOCHDR+E.fnameLen+E.extraLen},get localHeader(){return E},loadLocalHeaderFromBinary:function(i){var g=i.slice(m,m+P.LOCHDR);if(g.readUInt32LE(0)!==P.LOCSIG)throw We.Errors.INVALID_LOC();E.version=g.readUInt16LE(P.LOCVER),E.flags=g.readUInt16LE(P.LOCFLG),E.flags_desc=(E.flags&P.FLG_DESC)>0,E.method=g.readUInt16LE(P.LOCHOW),E.time=g.readUInt32LE(P.LOCTIM),E.crc=g.readUInt32LE(P.LOCCRC),E.compressedSize=g.readUInt32LE(P.LOCSIZ),E.size=g.readUInt32LE(P.LOCLEN),E.fnameLen=g.readUInt16LE(P.LOCNAM),E.extraLen=g.readUInt16LE(P.LOCEXT);let y=m+P.LOCHDR+E.fnameLen,b=y+E.extraLen;return i.slice(y,b)},loadFromBinary:function(i){if(i.length!==P.CENHDR||i.readUInt32LE(0)!==P.CENSIG)throw We.Errors.INVALID_CEN();r=i.readUInt16LE(P.CENVEM),e=i.readUInt16LE(P.CENVER),t=i.readUInt16LE(P.CENFLG),n=i.readUInt16LE(P.CENHOW),s=i.readUInt32LE(P.CENTIM),o=i.readUInt32LE(P.CENCRC),l=i.readUInt32LE(P.CENSIZ),c=i.readUInt32LE(P.CENLEN),u=i.readUInt16LE(P.CENNAM),a=i.readUInt16LE(P.CENEXT),p=i.readUInt16LE(P.CENCOM),S=i.readUInt16LE(P.CENDSK),I=i.readUInt16LE(P.CENATT),d=i.readUInt32LE(P.CENATX),m=i.readUInt32LE(P.CENOFF)},localHeaderToBinary:function(){var i=Buffer.alloc(P.LOCHDR);return i.writeUInt32LE(P.LOCSIG,0),i.writeUInt16LE(e,P.LOCVER),i.writeUInt16LE(t,P.LOCFLG),i.writeUInt16LE(n,P.LOCHOW),i.writeUInt32LE(s,P.LOCTIM),i.writeUInt32LE(o,P.LOCCRC),i.writeUInt32LE(l,P.LOCSIZ),i.writeUInt32LE(c,P.LOCLEN),i.writeUInt16LE(u,P.LOCNAM),i.writeUInt16LE(E.extraLen,P.LOCEXT),i},centralHeaderToBinary:function(){var i=Buffer.alloc(P.CENHDR+u+a+p);return i.writeUInt32LE(P.CENSIG,0),i.writeUInt16LE(r,P.CENVEM),i.writeUInt16LE(e,P.CENVER),i.writeUInt16LE(t,P.CENFLG),i.writeUInt16LE(n,P.CENHOW),i.writeUInt32LE(s,P.CENTIM),i.writeUInt32LE(o,P.CENCRC),i.writeUInt32LE(l,P.CENSIZ),i.writeUInt32LE(c,P.CENLEN),i.writeUInt16LE(u,P.CENNAM),i.writeUInt16LE(a,P.CENEXT),i.writeUInt16LE(p,P.CENCOM),i.writeUInt16LE(S,P.CENDSK),i.writeUInt16LE(I,P.CENATT),i.writeUInt32LE(d,P.CENATX),i.writeUInt32LE(m,P.CENOFF),i},toJSON:function(){let i=function(g){return g+" bytes"};return{made:r,version:e,flags:t,method:We.methodToString(n),time:this.time,crc:"0x"+o.toString(16).toUpperCase(),compressedSize:i(l),size:i(c),fileNameLength:i(u),extraLength:i(a),commentLength:i(p),diskNumStart:S,inAttr:I,attr:d,offset:m,centralHeaderSize:i(P.CENHDR+u+a+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var us=K((Ic,ls)=>{"use strict";var lt=ct(),X=lt.Constants;ls.exports=function(){var r=0,e=0,t=0,n=0,s=0;return{get diskEntries(){return r},set diskEntries(o){r=e=o},get totalEntries(){return e},set totalEntries(o){e=r=o},get size(){return t},set size(o){t=o},get offset(){return n},set offset(o){n=o},get commentLength(){return s},set commentLength(o){s=o},get mainHeaderSize(){return X.ENDHDR+s},loadFromBinary:function(o){if((o.length!==X.ENDHDR||o.readUInt32LE(0)!==X.ENDSIG)&&(o.length<X.ZIP64HDR||o.readUInt32LE(0)!==X.ZIP64SIG))throw lt.Errors.INVALID_END();o.readUInt32LE(0)===X.ENDSIG?(r=o.readUInt16LE(X.ENDSUB),e=o.readUInt16LE(X.ENDTOT),t=o.readUInt32LE(X.ENDSIZ),n=o.readUInt32LE(X.ENDOFF),s=o.readUInt16LE(X.ENDCOM)):(r=lt.readBigUInt64LE(o,X.ZIP64SUB),e=lt.readBigUInt64LE(o,X.ZIP64TOT),t=lt.readBigUInt64LE(o,X.ZIP64SIZE),n=lt.readBigUInt64LE(o,X.ZIP64OFF),s=0)},toBinary:function(){var o=Buffer.alloc(X.ENDHDR+s);return o.writeUInt32LE(X.ENDSIG,0),o.writeUInt32LE(0,4),o.writeUInt16LE(r,X.ENDSUB),o.writeUInt16LE(e,X.ENDTOT),o.writeUInt32LE(t,X.ENDSIZ),o.writeUInt32LE(n,X.ENDOFF),o.writeUInt16LE(s,X.ENDCOM),o.fill(" ",X.ENDHDR),o},toJSON:function(){let o=function(l,c){let u=l.toString(16).toUpperCase();for(;u.length<c;)u="0"+u;return"0x"+u};return{diskEntries:r,totalEntries:e,size:t+" bytes",offset:o(n,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Mr=K(Lr=>{"use strict";Lr.EntryHeader=cs();Lr.MainHeader=us()});var ds=K((Oc,fs)=>{"use strict";fs.exports=function(r){var e=require("zlib"),t={chunkSize:(parseInt(r.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(r,t)},deflateAsync:function(n){var s=e.createDeflateRaw(t),o=[],l=0;s.on("data",function(c){o.push(c),l+=c.length}),s.on("end",function(){var c=Buffer.alloc(l),u=0;c.fill(0);for(var a=0;a<o.length;a++){var p=o[a];p.copy(c,u),u+=p.length}n&&n(c)}),s.end(r)}}}});var ms=K((kc,ps)=>{"use strict";var $i=+(process.versions?process.versions.node:"").split(".")[0]||0;ps.exports=function(r,e){var t=require("zlib");let n=$i>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return t.inflateRawSync(r,n)},inflateAsync:function(s){var o=t.createInflateRaw(n),l=[],c=0;o.on("data",function(u){l.push(u),c+=u.length}),o.on("end",function(){var u=Buffer.alloc(c),a=0;u.fill(0);for(var p=0;p<l.length;p++){var S=l[p];S.copy(u,a),a+=S.length}s&&s(u)}),o.end(r)}}}});var Es=K((vc,Ss)=>{"use strict";var{randomFillSync:hs}=require("crypto"),Fi=Nt(),Li=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),ys=(r,e)=>Math.imul(r,e)>>>0,gs=(r,e)=>Li[(r^e)&255]^r>>>8,At=()=>typeof hs=="function"?hs(Buffer.alloc(12)):At.node();At.node=()=>{let r=Buffer.alloc(12),e=r.length;for(let t=0;t<e;t++)r[t]=Math.random()*256&255;return r};var jt={genSalt:At};function $t(r){let e=Buffer.isBuffer(r)?r:Buffer.from(r);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let t=0;t<e.length;t++)this.updateKeys(e[t])}$t.prototype.updateKeys=function(r){let e=this.keys;return e[0]=gs(e[0],r),e[1]+=e[0]&255,e[1]=ys(e[1],134775813)+1,e[2]=gs(e[2],e[1]>>>24),r};$t.prototype.next=function(){let r=(this.keys[2]|2)>>>0;return ys(r,r^1)>>8&255};function Mi(r){let e=new $t(r);return function(t){let n=Buffer.alloc(t.length),s=0;for(let o of t)n[s++]=e.updateKeys(o^e.next());return n}}function Ui(r){let e=new $t(r);return function(t,n,s=0){n||(n=Buffer.alloc(t.length));for(let o of t){let l=e.next();n[s++]=o^l,e.updateKeys(o)}return n}}function Hi(r,e,t){if(!r||!Buffer.isBuffer(r)||r.length<12)return Buffer.alloc(0);let n=Mi(t),s=n(r.slice(0,12)),o=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==o)throw Fi.WRONG_PASSWORD();return n(r.slice(12))}function Bi(r){Buffer.isBuffer(r)&&r.length>=12?jt.genSalt=function(){return r.slice(0,12)}:r==="node"?jt.genSalt=At.node:jt.genSalt=At}function Wi(r,e,t,n=!1){r==null&&(r=Buffer.alloc(0)),Buffer.isBuffer(r)||(r=Buffer.from(r.toString()));let s=Ui(t),o=jt.genSalt();o[11]=e.crc>>>24&255,n&&(o[10]=e.crc>>>16&255);let l=Buffer.alloc(r.length+12);return s(o,l),s(r,l,12)}Ss.exports={decrypt:Hi,encrypt:Wi,_salter:Bi}});var Cs=K(Ft=>{"use strict";Ft.Deflater=ds();Ft.Inflater=ms();Ft.ZipCrypto=Es()});var Hr=K((Rc,ws)=>{"use strict";var V=ct(),Vi=Mr(),te=V.Constants,Ur=Cs();ws.exports=function(r,e){var t=new Vi.EntryHeader,n=Buffer.alloc(0),s=Buffer.alloc(0),o=!1,l=null,c=Buffer.alloc(0),u=Buffer.alloc(0),a=!0;let p=r,S=typeof p.decoder=="object"?p.decoder:V.decoder;a=S.hasOwnProperty("efs")?S.efs:!1;function I(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(u=t.loadLocalHeaderFromBinary(e),e.slice(t.realDataOffset,t.realDataOffset+t.compressedSize))}function d(i){if(!t.flags_desc&&!t.localHeader.flags_desc){if(V.crc32(i)!==t.localHeader.crc)return!1}else{let g={},y=t.realDataOffset+t.compressedSize;if(e.readUInt32LE(y)==te.LOCSIG||e.readUInt32LE(y)==te.CENSIG)throw V.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(y)==te.EXTSIG)g.crc=e.readUInt32LE(y+te.EXTCRC),g.compressedSize=e.readUInt32LE(y+te.EXTSIZ),g.size=e.readUInt32LE(y+te.EXTLEN);else if(e.readUInt16LE(y+12)===19280)g.crc=e.readUInt32LE(y+te.EXTCRC-4),g.compressedSize=e.readUInt32LE(y+te.EXTSIZ-4),g.size=e.readUInt32LE(y+te.EXTLEN-4);else throw V.Errors.DESCRIPTOR_UNKNOWN();if(g.compressedSize!==t.compressedSize||g.size!==t.size||g.crc!==t.crc)throw V.Errors.DESCRIPTOR_FAULTY();if(V.crc32(i)!==g.crc)return!1}return!0}function m(i,g,y){if(typeof g>"u"&&typeof i=="string"&&(y=i,i=void 0),o)return i&&g&&g(Buffer.alloc(0),V.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var b=I();if(b.length===0)return i&&g&&g(b),b;if(t.encrypted){if(typeof y!="string"&&!Buffer.isBuffer(y))throw V.Errors.INVALID_PASS_PARAM();b=Ur.ZipCrypto.decrypt(b,t,y)}var _=Buffer.alloc(t.size);switch(t.method){case V.Constants.STORED:if(b.copy(_),d(_))return i&&g&&g(_),_;throw i&&g&&g(_,V.Errors.BAD_CRC()),V.Errors.BAD_CRC();case V.Constants.DEFLATED:var O=new Ur.Inflater(b,t.size);if(i)O.inflateAsync(function(k){k.copy(k,0),g&&(d(k)?g(k):g(k,V.Errors.BAD_CRC()))});else{if(O.inflate(_).copy(_,0),!d(_))throw V.Errors.BAD_CRC(`"${S.decode(n)}"`);return _}break;default:throw i&&g&&g(Buffer.alloc(0),V.Errors.UNKNOWN_METHOD()),V.Errors.UNKNOWN_METHOD()}}function E(i,g){if((!l||!l.length)&&Buffer.isBuffer(e))return i&&g&&g(I()),I();if(l.length&&!o){var y;switch(t.method){case V.Constants.STORED:return t.compressedSize=t.size,y=Buffer.alloc(l.length),l.copy(y),i&&g&&g(y),y;default:case V.Constants.DEFLATED:var b=new Ur.Deflater(l);if(i)b.deflateAsync(function(O){y=Buffer.alloc(O.length),t.compressedSize=O.length,O.copy(y),g&&g(y)});else{var _=b.deflate();return t.compressedSize=_.length,_}b=null;break}}else if(i&&g)g(Buffer.alloc(0));else return Buffer.alloc(0)}function f(i,g){return V.readBigUInt64LE(i,g)}function h(i){try{for(var g=0,y,b,_;g+4<i.length;)y=i.readUInt16LE(g),g+=2,b=i.readUInt16LE(g),g+=2,_=i.slice(g,g+b),g+=b,te.ID_ZIP64===y&&C(_)}catch{throw V.Errors.EXTRA_FIELD_PARSE_ERROR()}}function C(i){var g,y,b,_;i.length>=te.EF_ZIP64_SCOMP&&(g=f(i,te.EF_ZIP64_SUNCOMP),t.size===te.EF_ZIP64_OR_32&&(t.size=g)),i.length>=te.EF_ZIP64_RHO&&(y=f(i,te.EF_ZIP64_SCOMP),t.compressedSize===te.EF_ZIP64_OR_32&&(t.compressedSize=y)),i.length>=te.EF_ZIP64_DSN&&(b=f(i,te.EF_ZIP64_RHO),t.offset===te.EF_ZIP64_OR_32&&(t.offset=b)),i.length>=te.EF_ZIP64_DSN+4&&(_=i.readUInt32LE(te.EF_ZIP64_DSN),t.diskNumStart===te.EF_ZIP64_OR_16&&(t.diskNumStart=_))}return{get entryName(){return S.decode(n)},get rawEntryName(){return n},set entryName(i){n=V.toBuffer(i,S.encode);var g=n[n.length-1];o=g===47||g===92,t.fileNameLength=n.length},get efs(){return typeof a=="function"?a(this.entryName):a},get extra(){return c},set extra(i){c=i,t.extraLength=i.length,h(i)},get comment(){return S.decode(s)},set comment(i){if(s=V.toBuffer(i,S.encode),t.commentLength=s.length,s.length>65535)throw V.Errors.COMMENT_TOO_LONG()},get name(){var i=S.decode(n);return o?i.substr(i.length-1).split("/").pop():i.split("/").pop()},get isDirectory(){return o},getCompressedData:function(){return E(!1,null)},getCompressedDataAsync:function(i){E(!0,i)},setData:function(i){l=V.toBuffer(i,V.decoder.encode),!o&&l.length?(t.size=l.length,t.method=V.Constants.DEFLATED,t.crc=V.crc32(i),t.changed=!0):t.method=V.Constants.STORED},getData:function(i){return t.changed?l:m(!1,null,i)},getDataAsync:function(i,g){t.changed?i(l):m(!0,i,g)},set attr(i){t.attr=i},get attr(){return t.attr},set header(i){t.loadFromBinary(i)},get header(){return t},packCentralHeader:function(){t.flags_efs=this.efs,t.extraLength=c.length;var i=t.centralHeaderToBinary(),g=V.Constants.CENHDR;return n.copy(i,g),g+=n.length,c.copy(i,g),g+=t.extraLength,s.copy(i,g),i},packLocalHeader:function(){let i=0;t.flags_efs=this.efs,t.extraLocalLength=u.length;let g=t.localHeaderToBinary(),y=Buffer.alloc(g.length+n.length+t.extraLocalLength);return g.copy(y,i),i+=g.length,n.copy(y,i),i+=n.length,u.copy(y,i),i+=u.length,y},toJSON:function(){let i=function(g){return"<"+(g&&g.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:t.toJSON(),compressedData:i(e),data:i(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var _s=K((Pc,As)=>{"use strict";var bs=Hr(),qi=Mr(),he=ct();As.exports=function(r,e){var t=[],n={},s=Buffer.alloc(0),o=new qi.MainHeader,l=!1,c=null;let u=new Set,a=e,{noSort:p,decoder:S}=a;r?m(a.readEntries):l=!0;function I(){let f=new Set;for(let h of Object.keys(n)){let C=h.split("/");if(C.pop(),!!C.length)for(let i=0;i<C.length;i++){let g=C.slice(0,i+1).join("/")+"/";f.add(g)}}for(let h of f)if(!(h in n)){let C=new bs(a);C.entryName=h,C.attr=16,C.temporary=!0,t.push(C),n[C.entryName]=C,u.add(C)}}function d(){if(l=!0,n={},o.diskEntries>(r.length-o.offset)/he.Constants.CENHDR)throw he.Errors.DISK_ENTRY_TOO_LARGE();t=new Array(o.diskEntries);for(var f=o.offset,h=0;h<t.length;h++){var C=f,i=new bs(a,r);i.header=r.slice(C,C+=he.Constants.CENHDR),i.entryName=r.slice(C,C+=i.header.fileNameLength),i.header.extraLength&&(i.extra=r.slice(C,C+=i.header.extraLength)),i.header.commentLength&&(i.comment=r.slice(C,C+i.header.commentLength)),f+=i.header.centralHeaderSize,t[h]=i,n[i.entryName]=i}u.clear(),I()}function m(f){var h=r.length-he.Constants.ENDHDR,C=Math.max(0,h-65535),i=C,g=r.length,y=-1,b=0;for(typeof a.trailingSpace=="boolean"&&a.trailingSpace&&(C=0),h;h>=i;h--)if(r[h]===80){if(r.readUInt32LE(h)===he.Constants.ENDSIG){y=h,b=h,g=h+he.Constants.ENDHDR,i=h-he.Constants.END64HDR;continue}if(r.readUInt32LE(h)===he.Constants.END64SIG){i=C;continue}if(r.readUInt32LE(h)===he.Constants.ZIP64SIG){y=h,g=h+he.readBigUInt64LE(r,h+he.Constants.ZIP64SIZE)+he.Constants.ZIP64LEAD;break}}if(y==-1)throw he.Errors.INVALID_FORMAT();o.loadFromBinary(r.slice(y,g)),o.commentLength&&(s=r.slice(b+he.Constants.ENDHDR)),f&&d()}function E(){t.length>1&&!p&&t.sort((f,h)=>f.entryName.toLowerCase().localeCompare(h.entryName.toLowerCase()))}return{get entries(){return l||d(),t.filter(f=>!u.has(f))},get comment(){return S.decode(s)},set comment(f){s=he.toBuffer(f,S.encode),o.commentLength=s.length},getEntryCount:function(){return l?t.length:o.diskEntries},forEach:function(f){this.entries.forEach(f)},getEntry:function(f){return l||d(),n[f]||null},setEntry:function(f){l||d(),t.push(f),n[f.entryName]=f,o.totalEntries=t.length},deleteFile:function(f,h=!0){l||d();let C=n[f];this.getEntryChildren(C,h).map(g=>g.entryName).forEach(this.deleteEntry)},deleteEntry:function(f){l||d();let h=n[f],C=t.indexOf(h);C>=0&&(t.splice(C,1),delete n[f],o.totalEntries=t.length)},getEntryChildren:function(f,h=!0){if(l||d(),typeof f=="object")if(f.isDirectory&&h){let C=[],i=f.entryName;for(let g of t)g.entryName.startsWith(i)&&C.push(g);return C}else return[f];return[]},getChildCount:function(f){if(f&&f.isDirectory){let h=this.getEntryChildren(f);return h.includes(f)?h.length-1:h.length}return 0},compressToBuffer:function(){l||d(),E();let f=[],h=[],C=0,i=0;o.size=0,o.offset=0;let g=0;for(let _ of this.entries){let O=_.getCompressedData();_.header.offset=i;let k=_.packLocalHeader(),D=k.length+O.length;i+=D,f.push(k),f.push(O);let x=_.packCentralHeader();h.push(x),o.size+=x.length,C+=D+x.length,g++}C+=o.mainHeaderSize,o.offset=i,o.totalEntries=g,i=0;let y=Buffer.alloc(C);for(let _ of f)_.copy(y,i),i+=_.length;for(let _ of h)_.copy(y,i),i+=_.length;let b=o.toBinary();return s&&s.copy(b,he.Constants.ENDHDR),b.copy(y,i),r=y,l=!1,y},toAsyncBuffer:function(f,h,C,i){try{l||d(),E();let g=[],y=[],b=0,_=0,O=0;o.size=0,o.offset=0;let k=function(D){if(D.length>0){let x=D.shift(),T=x.entryName+x.extra.toString();C&&C(T),x.getCompressedDataAsync(function(v){i&&i(T),x.header.offset=_;let N=x.packLocalHeader(),j=N.length+v.length;_+=j,g.push(N),g.push(v);let M=x.packCentralHeader();y.push(M),o.size+=M.length,b+=j+M.length,O++,k(D)})}else{b+=o.mainHeaderSize,o.offset=_,o.totalEntries=O,_=0;let x=Buffer.alloc(b);g.forEach(function(v){v.copy(x,_),_+=v.length}),y.forEach(function(v){v.copy(x,_),_+=v.length});let T=o.toBinary();s&&s.copy(T,he.Constants.ENDHDR),T.copy(x,_),r=x,l=!1,f(x)}};k(Array.from(this.entries))}catch(g){h(g)}}}}});var Os=K((Dc,xs)=>{"use strict";var Q=ct(),Y=require("path"),Gi=Hr(),zi=_s(),Ye=(...r)=>Q.findLast(r,e=>typeof e=="boolean"),Is=(...r)=>Q.findLast(r,e=>typeof e=="string"),Zi=(...r)=>Q.findLast(r,e=>typeof e=="function"),Ji={noSort:!1,readEntries:!1,method:Q.Constants.NONE,fs:null};xs.exports=function(r,e){let t=null,n=Object.assign(Object.create(null),Ji);r&&typeof r=="object"&&(r instanceof Uint8Array||(Object.assign(n,r),r=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(r)&&(t=r,n.method=Q.Constants.BUFFER,r=void 0)),Object.assign(n,e);let s=new Q(n);if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=Q.decoder),r&&typeof r=="string")if(s.fs.existsSync(r))n.method=Q.Constants.FILE,n.filename=r,t=s.fs.readFileSync(r);else throw Q.Errors.INVALID_FILENAME();let o=new zi(t,n),{canonical:l,sanitize:c,zipnamefix:u}=Q;function a(d){if(d&&o){var m;if(typeof d=="string"&&(m=o.getEntry(Y.posix.normalize(d))),typeof d=="object"&&typeof d.entryName<"u"&&typeof d.header<"u"&&(m=o.getEntry(d.entryName)),m)return m}return null}function p(d){let{join:m,normalize:E,sep:f}=Y.posix;return m(Y.isAbsolute(d)?"/":".",E(f+d.split("\\").join(f)+f))}function S(d){return d instanceof RegExp?(function(m){return function(E){return m.test(E)}})(d):typeof d!="function"?()=>!0:d}let I=(d,m)=>{let E=m.slice(-1);return E=E===s.sep?s.sep:"",Y.relative(d,m)+E};return{readFile:function(d,m){var E=a(d);return E&&E.getData(m)||null},childCount:function(d){let m=a(d);if(m)return o.getChildCount(m)},readFileAsync:function(d,m){var E=a(d);E?E.getDataAsync(m):m(null,"getEntry failed for:"+d)},readAsText:function(d,m){var E=a(d);if(E){var f=E.getData();if(f&&f.length)return f.toString(m||"utf8")}return""},readAsTextAsync:function(d,m,E){var f=a(d);f?f.getDataAsync(function(h,C){if(C){m(h,C);return}h&&h.length?m(h.toString(E||"utf8")):m("")}):m("")},deleteFile:function(d,m=!0){var E=a(d);E&&o.deleteFile(E.entryName,m)},deleteEntry:function(d){var m=a(d);m&&o.deleteEntry(m.entryName)},addZipComment:function(d){o.comment=d},getZipComment:function(){return o.comment||""},addZipEntryComment:function(d,m){var E=a(d);E&&(E.comment=m)},getZipEntryComment:function(d){var m=a(d);return m&&m.comment||""},updateFile:function(d,m){var E=a(d);E&&E.setData(m)},addLocalFile:function(d,m,E,f){if(s.fs.existsSync(d)){m=m?p(m):"";let h=Y.win32.basename(Y.win32.normalize(d));m+=E||h;let C=s.fs.statSync(d),i=C.isFile()?s.fs.readFileSync(d):Buffer.alloc(0);C.isDirectory()&&(m+=s.sep),this.addFile(m,i,f,C)}else throw Q.Errors.FILE_NOT_FOUND(d)},addLocalFileAsync:function(d,m){d=typeof d=="object"?d:{localPath:d};let E=Y.resolve(d.localPath),{comment:f}=d,{zipPath:h,zipName:C}=d,i=this;s.fs.stat(E,function(g,y){if(g)return m(g,!1);h=h?p(h):"";let b=Y.win32.basename(Y.win32.normalize(E));if(h+=C||b,y.isFile())s.fs.readFile(E,function(_,O){return _?m(_,!1):(i.addFile(h,O,f,y),setImmediate(m,void 0,!0))});else if(y.isDirectory())return h+=s.sep,i.addFile(h,Buffer.alloc(0),f,y),setImmediate(m,void 0,!0)})},addLocalFolder:function(d,m,E){if(E=S(E),m=m?p(m):"",d=Y.normalize(d),s.fs.existsSync(d)){let f=s.findFiles(d),h=this;if(f.length)for(let C of f){let i=Y.join(m,I(d,C));E(i)&&h.addLocalFile(C,Y.dirname(i))}}else throw Q.Errors.FILE_NOT_FOUND(d)},addLocalFolderAsync:function(d,m,E,f){f=S(f),E=E?p(E):"",d=Y.normalize(d);var h=this;s.fs.open(d,"r",function(C){if(C&&C.code==="ENOENT")m(void 0,Q.Errors.FILE_NOT_FOUND(d));else if(C)m(void 0,C);else{var i=s.findFiles(d),g=-1,y=function(){if(g+=1,g<i.length){var b=i[g],_=I(d,b).split("\\").join("/");_=_.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),f(_)?s.fs.stat(b,function(O,k){O&&m(void 0,O),k.isFile()?s.fs.readFile(b,function(D,x){D?m(void 0,D):(h.addFile(E+_,x,"",k),y())}):(h.addFile(E+_+"/",Buffer.alloc(0),"",k),y())}):process.nextTick(()=>{y()})}else m(!0,void 0)};y()}})},addLocalFolderAsync2:function(d,m){let E=this;d=typeof d=="object"?d:{localPath:d},localPath=Y.resolve(p(d.localPath));let{zipPath:f,filter:h,namefix:C}=d;h instanceof RegExp?h=(function(y){return function(b){return y.test(b)}})(h):typeof h!="function"&&(h=function(){return!0}),f=f?p(f):"",C=="latin1"&&(C=y=>y.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof C!="function"&&(C=y=>y);let i=y=>Y.join(f,C(I(localPath,y))),g=y=>Y.win32.basename(Y.win32.normalize(C(y)));s.fs.open(localPath,"r",function(y){y&&y.code==="ENOENT"?m(void 0,Q.Errors.FILE_NOT_FOUND(localPath)):y?m(void 0,y):s.findFilesAsync(localPath,function(b,_){if(b)return m(b);_=_.filter(O=>h(i(O))),_.length||m(void 0,!1),setImmediate(_.reverse().reduce(function(O,k){return function(D,x){if(D||x===!1)return setImmediate(O,D,!1);E.addLocalFileAsync({localPath:k,zipPath:Y.dirname(i(k)),zipName:g(k)},O)}},m))})})},addLocalFolderPromise:function(d,m){return new Promise((E,f)=>{this.addLocalFolderAsync2(Object.assign({localPath:d},m),(h,C)=>{h&&f(h),C&&E(this)})})},addFile:function(d,m,E,f){d=u(d);let h=a(d),C=h!=null;C||(h=new Gi(n),h.entryName=d),h.comment=E||"";let i=typeof f=="object"&&f instanceof s.fs.Stats;i&&(h.header.time=f.mtime);var g=h.isDirectory?16:0;let y=h.isDirectory?16384:32768;return i?y|=4095&f.mode:typeof f=="number"?y|=4095&f:y|=h.isDirectory?493:420,g=(g|y<<16)>>>0,h.attr=g,h.setData(m),C||o.setEntry(h),h},getEntries:function(d){return o.password=d,o?o.entries:[]},getEntry:function(d){return a(d)},getEntryCount:function(){return o.getEntryCount()},forEach:function(d){return o.forEach(d)},extractEntryTo:function(d,m,E,f,h,C){f=Ye(!1,f),h=Ye(!1,h),E=Ye(!0,E),C=Is(h,C);var i=a(d);if(!i)throw Q.Errors.NO_ENTRY();var g=l(i.entryName),y=c(m,C&&!i.isDirectory?C:E?g:Y.basename(g));if(i.isDirectory){var b=o.getEntryChildren(i);return b.forEach(function(k){if(k.isDirectory)return;var D=k.getData();if(!D)throw Q.Errors.CANT_EXTRACT_FILE();var x=l(k.entryName),T=c(m,E?x:Y.basename(x));let v=h?k.header.fileAttr:void 0;s.writeFileTo(T,D,f,v)}),!0}var _=i.getData(o.password);if(!_)throw Q.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(y)&&!f)throw Q.Errors.CANT_OVERRIDE();let O=h?d.header.fileAttr:void 0;return s.writeFileTo(y,_,f,O),!0},test:function(d){if(!o)return!1;for(var m in o.entries)try{if(m.isDirectory)continue;var E=o.entries[m].getData(d);if(!E)return!1}catch{return!1}return!0},extractAllTo:function(d,m,E,f){if(E=Ye(!1,E),f=Is(E,f),m=Ye(!1,m),!o)throw Q.Errors.NO_ZIP();o.entries.forEach(function(h){var C=c(d,l(h.entryName));if(h.isDirectory){s.makeDir(C);return}var i=h.getData(f);if(!i)throw Q.Errors.CANT_EXTRACT_FILE();let g=E?h.header.fileAttr:void 0;s.writeFileTo(C,i,m,g);try{s.fs.utimesSync(C,h.header.time,h.header.time)}catch{throw Q.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(d,m,E,f){if(f=Zi(m,E,f),E=Ye(!1,E),m=Ye(!1,m),!f)return new Promise((y,b)=>{this.extractAllToAsync(d,m,E,function(_){_?b(_):y(this)})});if(!o){f(Q.Errors.NO_ZIP());return}d=Y.resolve(d);let h=y=>c(d,Y.normalize(l(y.entryName))),C=(y,b)=>new Error(y+': "'+b+'"'),i=[],g=[];o.entries.forEach(y=>{y.isDirectory?i.push(y):g.push(y)});for(let y of i){let b=h(y),_=E?y.header.fileAttr:void 0;try{s.makeDir(b),_&&s.fs.chmodSync(b,_),s.fs.utimesSync(b,y.header.time,y.header.time)}catch{f(C("Unable to create folder",b))}}g.reverse().reduce(function(y,b){return function(_){if(_)y(_);else{let O=Y.normalize(l(b.entryName)),k=c(d,O);b.getDataAsync(function(D,x){if(x)y(x);else if(!D)y(Q.Errors.CANT_EXTRACT_FILE());else{let T=E?b.header.fileAttr:void 0;s.writeFileToAsync(k,D,m,T,function(v){v||y(C("Unable to write file",k)),s.fs.utimes(k,b.header.time,b.header.time,function(N){N?y(C("Unable to set times",k)):y()})})}})}}},f)()},writeZip:function(d,m){if(arguments.length===1&&typeof d=="function"&&(m=d,d=""),!d&&n.filename&&(d=n.filename),!!d){var E=o.compressToBuffer();if(E){var f=s.writeFileTo(d,E,!0);typeof m=="function"&&m(f?null:new Error("failed"),"")}}},writeZipPromise:function(d,m){let{overwrite:E,perm:f}=Object.assign({overwrite:!0},m);return new Promise((h,C)=>{!d&&n.filename&&(d=n.filename),d||C("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(i=>{let g=y=>y?h(y):C("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(d,i,E,f,g)},C)})},toBufferPromise:function(){return new Promise((d,m)=>{o.toAsyncBuffer(d,m)})},toBuffer:function(d,m,E,f){return typeof d=="function"?(o.toAsyncBuffer(d,m,E,f),null):o.compressToBuffer()}}}});var Gs={};yt(Gs,{enableTelemetryHook:()=>qs,registerConfig:()=>Jr});function Zr(){let r=process.env.SC_PROFILE;return r?(0,Fe.join)((0,mt.homedir)(),".config","shared-context","profiles",r):(0,Fe.join)((0,mt.homedir)(),".config","shared-context")}function qs(){try{let r=(0,Fe.join)((0,mt.homedir)(),".claude","settings.json"),{readFileSync:e,writeFileSync:t}=require("fs"),n={};try{(0,qe.existsSync)(r)&&(n=JSON.parse(e(r,"utf8")))}catch{}n.hooks||(n.hooks={});let s=n.hooks;if(s.PostToolUse||(s.PostToolUse=[]),s.PostToolUse.some(p=>p._sc===Vs))return;let l=(0,Fe.join)(Zr(),"manifest.json"),c="";try{let S=(JSON.parse(e(l,"utf8")).installations||[]).find(I=>I.slug==="telemetry"||I.installPath?.includes("hooks/telemetry"));S?.installPath&&(c=(0,Fe.join)((0,mt.homedir)(),".config","shared-context",S.installPath,"scripts","telemetry.js"))}catch{}if((!c||!(0,qe.existsSync)(c))&&(c=(0,Fe.join)(Zr(),"hooks","telemetry","scripts","telemetry.js")),!(0,qe.existsSync)(c))return;s.PostToolUse.push({hooks:[{type:"command",command:`node ${c}`}],_sc:Vs}),s.SessionStart||(s.SessionStart=[]);let u="platform/telemetry-push";s.SessionStart.some(p=>p._sc===u)||s.SessionStart.push({hooks:[{type:"command",command:"npx shared-context-ai telemetry push --quiet 2>/dev/null || true"}],_sc:u}),t(r,JSON.stringify(n,null,2)+`
30
+ `,"utf8")}catch{}}function ya(){Tt({telemetry:!1});let r=(0,Fe.join)(Zr(),"usage.jsonl");try{(0,qe.existsSync)(r)&&(0,qe.unlinkSync)(r)}catch{}try{let e=(0,Fe.join)((0,mt.homedir)(),".claude","settings.json");if((0,qe.existsSync)(e)){let{readFileSync:t,writeFileSync:n}=require("fs"),s=JSON.parse(t(e,"utf8"));if(s.hooks){let o=!1,l=new Set(["hooks/shared-context/telemetry","platform/telemetry-push"]);for(let[c,u]of Object.entries(s.hooks))if(Array.isArray(u)){let a=u.filter(p=>!l.has(p._sc));a.length!==u.length&&(s.hooks[c]=a,o=!0)}for(let[c,u]of Object.entries(s.hooks))Array.isArray(u)&&u.length===0&&delete s.hooks[c];o&&n(e,JSON.stringify(s,null,2)+`
31
+ `,"utf8")}}}catch{}}function Jr(r){let e=r.command("config").description("Manage CLI configuration");e.command("set <key> <value>").description("Set a configuration value (e.g., telemetry on/off)").action((t,n)=>{if(t==="telemetry"){let s=n==="on"||n==="true"||n==="1",o=n==="off"||n==="false"||n==="0";if(!s&&!o){A()?$("config","INVALID_VALUE","Telemetry value must be on or off"):R("Usage: shared-context-ai config set telemetry on|off");return}o?(ya(),A()?F("config",{key:"telemetry",value:!1}):w("Telemetry disabled. Usage data and hooks removed.")):(Tt({telemetry:!0}),qs(),A()?F("config",{key:"telemetry",value:!0}):w("Telemetry enabled. Usage data will be collected and uploaded."));return}A()?$("config","UNKNOWN_KEY",`Unknown config key: ${t}`):R(`Unknown config key: ${t}. Available: telemetry`)}),e.command("get [key]").description("Show configuration values").action(t=>{let n=xe();if(t==="telemetry"){let s=n.telemetry??!1;A()?F("config",{key:"telemetry",value:s}):w(`telemetry: ${s?"on":"off"}`);return}if(t){A()?$("config","UNKNOWN_KEY",`Unknown config key: ${t}`):R(`Unknown config key: ${t}`);return}A()?F("config",{telemetry:n.telemetry??!1}):w(`telemetry: ${n.telemetry?"on":"off"}`)})}var qe,Fe,mt,Vs,Kr=ge(()=>{"use strict";qe=require("fs"),Fe=require("path"),mt=require("os");me();se();Vs="hooks/shared-context/telemetry"});function ba(){try{return Yr.default.statSync("/.dockerenv"),!0}catch{return!1}}function Aa(){try{return Yr.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Qr(){return Xr===void 0&&(Xr=ba()||Aa()),Xr}var Yr,Xr,Xs=ge(()=>{"use strict";Yr=ye(require("fs"),1)});function st(){return en===void 0&&(en=_a()||Qr()),en}var Ys,en,_a,tn=ge(()=>{"use strict";Ys=ye(require("fs"),1);Xs();_a=()=>{try{return Ys.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var rn,eo,Qt,Qs,ze,nn=ge(()=>{"use strict";rn=ye(require("process"),1),eo=ye(require("os"),1),Qt=ye(require("fs"),1);tn();Qs=()=>{if(rn.default.platform!=="linux")return!1;if(eo.default.release().toLowerCase().includes("microsoft"))return!st();try{if(Qt.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!st()}catch{}return Qt.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||Qt.default.existsSync("/run/WSL")?!st():!1},ze=rn.default.env.__IS_WSL_TEST__?Qs:Qs()});var sn,It,Ia,xa,on,to=ge(()=>{"use strict";sn=ye(require("process"),1),It=ye(require("fs/promises"),1);nn();nn();Ia=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await It.default.access(t,It.constants.F_OK),n=!0}catch{}if(!n)return r;let s=await It.default.readFile(t,{encoding:"utf8"}),o=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return o?(e=o.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),xa=async()=>`${await Ia()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,on=async()=>ze?xa():`${sn.default.env.SYSTEMROOT||sn.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Ze(r,e,t){let n=s=>Object.defineProperty(r,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let s=t();return n(s),s},set(s){n(s)}}),r}var ro=ge(()=>{"use strict"});async function an(){if(so.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Oa("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(r)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var no,so,oo,Oa,io=ge(()=>{"use strict";no=require("util"),so=ye(require("process"),1),oo=require("child_process"),Oa=(0,no.promisify)(oo.execFile)});async function lo(r,{humanReadableOutput:e=!0,signal:t}={}){if(ao.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:o}=await ka("osascript",["-e",r,n],s);return o.trim()}var ao,co,cn,ka,uo=ge(()=>{"use strict";ao=ye(require("process"),1),co=require("util"),cn=require("child_process"),ka=(0,co.promisify)(cn.execFile)});async function ln(r){return lo(`tell application "Finder" to set app_path to application file id "${r}" as string
32
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var fo=ge(()=>{"use strict";uo()});async function fn(r=va){let{stdout:e}=await r("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 un(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,s=n.lastIndexOf("."),o=n.lastIndexOf("-"),l=s===-1?void 0:n.slice(0,s),c=o===-1?void 0:n.slice(0,o);return er[n]??er[l]??er[c]??{name:n,id:n}}var po,mo,va,er,ql,un,ho=ge(()=>{"use strict";po=require("util"),mo=require("child_process"),va=(0,po.promisify)(mo.execFile),er={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"}},ql=new Map(Object.entries(er)),un=class extends Error{}});async function dn(){if(tr.default.platform==="darwin"){let r=await an();return{name:await ln(r),id:r}}if(tr.default.platform==="linux"){let{stdout:r}=await Ta("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Ra(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(tr.default.platform==="win32")return fn();throw new Error("Only macOS, Linux, and Windows are supported")}var go,tr,yo,Ta,Ra,So=ge(()=>{"use strict";go=require("util"),tr=ye(require("process"),1),yo=require("child_process");io();fo();ho();Ta=(0,go.promisify)(yo.execFile),Ra=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var Io={};yt(Io,{apps:()=>Je,default:()=>$a,openApp:()=>ja});async function Da(){let r=await on(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=hn.Buffer.from(e,"utf16le").toString("base64"),{stdout:n}=await Pa(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=n.trim(),o={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return o[s]?{id:o[s]}:{}}function bo(r){if(typeof r=="string"||Array.isArray(r))return r;let{[Co]:e}=r;if(!e)throw new Error(`${Co} is not supported`);return e}function nr({[ht]:r},{wsl:e}){if(e&&ze)return bo(e);if(!r)throw new Error(`${ht} is not supported`);return bo(r)}var mn,hn,gn,Ao,_o,yn,rr,Fa,Pa,pn,Eo,ht,Co,wo,xt,Na,ja,Je,$a,xo=ge(()=>{"use strict";mn=ye(require("process"),1),hn=require("buffer"),gn=ye(require("path"),1),Ao=require("url"),_o=require("util"),yn=ye(require("child_process"),1),rr=ye(require("fs/promises"),1);to();ro();So();tn();Fa={},Pa=(0,_o.promisify)(yn.default.execFile),pn=gn.default.dirname((0,Ao.fileURLToPath)(Fa.url)),Eo=gn.default.join(pn,"xdg-open"),{platform:ht,arch:Co}=mn.default;wo=async(r,e)=>{let t;for(let n of r)try{return await e(n)}catch(s){t=s}throw t},xt=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return wo(r.app,c=>xt({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return wo(e,c=>xt({...r,app:{name:c,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let c={"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"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},a=ze?await Da():await dn();if(a.id in c){let p=c[a.id];return e==="browserPrivate"&&t.push(u[p]),xt({...r,app:{name:Je[p],arguments:t}})}throw new Error(`${a.name} is not supported as a default browser`)}let n,s=[],o={};if(ht==="darwin")n="open",r.wait&&s.push("--wait-apps"),r.background&&s.push("--background"),r.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(ht==="win32"||ze&&!st()&&!e){n=await on(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),ze||(o.windowsVerbatimArguments=!0);let c=["Start"];r.wait&&c.push("-Wait"),e?(c.push(`"\`"${e}\`""`),r.target&&t.push(r.target)):r.target&&c.push(`"${r.target}"`),t.length>0&&(t=t.map(u=>`"\`"${u}\`""`),c.push("-ArgumentList",t.join(","))),r.target=hn.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let c=!pn||pn==="/",u=!1;try{await rr.default.access(Eo,rr.constants.X_OK),u=!0}catch{}n=mn.default.versions.electron??(ht==="android"||c||!u)?"xdg-open":Eo}t.length>0&&s.push(...t),r.wait||(o.stdio="ignore",o.detached=!0)}ht==="darwin"&&t.length>0&&s.push("--args",...t),r.target&&s.push(r.target);let l=yn.default.spawn(n,s,o);return r.wait?new Promise((c,u)=>{l.once("error",u),l.once("close",a=>{if(!r.allowNonzeroExitCode&&a>0){u(new Error(`Exited with code ${a}`));return}c(l)})}):(l.unref(),l)},Na=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return xt({...e,target:r})},ja=(r,e)=>{if(typeof r!="string"&&!Array.isArray(r))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 xt({...e,app:{name:r,arguments:t}})};Je={};Ze(Je,"chrome",()=>nr({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"]}}));Ze(Je,"brave",()=>nr({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"]}}));Ze(Je,"firefox",()=>nr({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Ze(Je,"edge",()=>nr({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Ze(Je,"browser",()=>"browser");Ze(Je,"browserPrivate",()=>"browserPrivate");$a=Na});var Jo={};yt(Jo,{pushTelemetry:()=>Zo,registerTelemetry:()=>En});function Ba(){let r=process.env.SC_PROFILE;return r?(0,ir.join)((0,Sn.homedir)(),".config","shared-context","profiles",r):(0,ir.join)((0,Sn.homedir)(),".config","shared-context")}function zo(){return(0,ir.join)(Ba(),"usage.jsonl")}function Wa(){let r=zo();if(!(0,Ke.existsSync)(r))return[];try{let e=(0,Ke.readFileSync)(r,"utf8").trim().split(`
33
+ `).filter(Boolean),t=[];for(let n of e)try{let s=JSON.parse(n);s.v&&s.ts&&s.event&&s.rid&&t.push(s)}catch{}return t}catch{return[]}}function Va(r){let e=zo();if((0,Ke.existsSync)(e))try{let t=(0,Ke.readFileSync)(e,"utf8").trim().split(`
34
+ `).filter(Boolean);if(t.length<=r)return;let n=t.slice(-r);(0,Ke.writeFileSync)(e,n.join(`
35
35
  `)+`
36
- `,"utf8")}catch{}}async function qo(r=!1){if(!be().telemetry)return{uploaded:0};if(!M())return{uploaded:0};let e=Ha();if(e.length===0)return{uploaded:0};let t=e.slice(0,$a),n=await $("/api/cli/telemetry",{events:t},1e4);if(n.ok){if(Ba(Ma),!r){let s=n.data?.accepted??0;_()?F("telemetry",{uploaded:s}):s>0&&w(`Uploaded ${s} usage event${s===1?"":"s"}`)}return{uploaded:n.data?.accepted??0}}return!r&&!_()&&R("Telemetry upload failed \u2014 will retry next session"),{uploaded:0}}function mn(r){r.command("telemetry").description("Manage usage telemetry").command("push").description("Upload local usage data to Shared Context").option("--quiet","Suppress output").action(async t=>{await qo(t.quiet)})}var qe,rr,pn,$a,Ma,hn=pe(()=>{"use strict";qe=require("fs"),rr=require("path"),pn=require("os");se();fe();te();$a=1e3,Ma=100});var Nn=me(Dn(),1),{program:tc,createCommand:rc,createArgument:nc,createOption:sc,CommanderError:oc,InvalidArgumentError:ic,InvalidOptionArgumentError:ac,Command:jn,Argument:cc,Option:lc,Help:uc}=Nn.default;te();var Jt=require("fs"),Ye=require("path"),qs=require("os");fe();se();te();var Pr=require("fs"),Ce=require("path"),je=require("os"),et=[{id:"claude-code",label:"Claude Code",envVars:["CLAUDE_CODE"],dir:".claude",skillsSubdir:"skills",platform:"claude_code"},{id:"cursor",label:"Cursor",envVars:["CURSOR","CURSOR_TRACE_ID"],dir:".cursor",skillsSubdir:"skills",platform:"custom"},{id:"codex",label:"Codex",envVars:["CODEX","CODEX_CI"],dir:".codex",skillsSubdir:"skills",platform:"codex"},{id:"opencode",label:"OpenCode",envVars:["OPENCODE"],dir:".opencode",skillsSubdir:"skills",platform:"custom"},{id:"gemini-cli",label:"Gemini CLI",envVars:["GEMINI_CLI"],dir:".gemini",skillsSubdir:"skills",platform:"gemini"},{id:"antigravity",label:"Antigravity",envVars:["GEMINI_CLI_IDE_WORKSPACE_PATH","GEMINI_CLI_IDE_PID"],dir:".gemini/antigravity",skillsSubdir:"skills",platform:"gemini"}];function ke(r){if(r){let n=et.find(o=>o.id===r);if(n)return n;let s=et.find(o=>o.dir===`.${r}`||o.dir===r);return s||null}for(let n of et)if(n.envVars.some(s=>process.env[s]))return n;let e=(0,je.homedir)(),t=[];for(let n of et)(0,Pr.existsSync)((0,Ce.join)(e,n.dir))&&t.push(n);return t.length===1?t[0]:null}function Le(){let r=[],e=(0,je.homedir)();for(let t of et)(t.envVars.some(n=>process.env[n])||(0,Pr.existsSync)((0,Ce.join)(e,t.dir)))&&r.push(t);return r}function Fe(){let r=Le();return r.length>1?`Multiple AI agents detected (${r.map(e=>e.label).join(", ")}). Use --agent to specify: ${r.map(e=>e.id).join(", ")}`:`No AI agent detected. Use --agent to specify one (${et.map(e=>e.id).join(", ")})`}function W(r,e){return e?(0,Ce.join)(process.cwd(),r.dir,r.skillsSubdir):(0,Ce.join)((0,je.homedir)(),r.dir,r.skillsSubdir)}function re(r,e){return e?(0,Ce.join)(process.cwd(),r.dir,"agents"):(0,Ce.join)((0,je.homedir)(),r.dir,"agents")}function oe(r,e){return e?(0,Ce.join)(process.cwd(),".mcp.json"):r.id==="claude-code"?(0,Ce.join)((0,je.homedir)(),".claude.json"):r.id==="cursor"?(0,Ce.join)((0,je.homedir)(),".cursor","mcp.json"):(0,Ce.join)(process.cwd(),".mcp.json")}function ye(r,e){return e?(0,Ce.join)(process.cwd(),r.dir,"settings.json"):(0,Ce.join)((0,je.homedir)(),r.dir,"settings.json")}var ce=require("fs"),Ke=require("path");var xe=require("fs"),_e=require("path"),Ds=require("child_process");se();var xs=require("child_process"),Is=require("fs"),Os=require("path"),ks=require("os"),vs=me(_s());se();function st(r){let t={"claude-code":"claude",cursor:"cursor","gemini-cli":"gemini"}[r];if(!t)return null;try{return(0,xs.execSync)(`which ${t}`,{stdio:"pipe"}),t}catch{return null}}async function jt(r,e){let t=await Rr(r),n=(0,Os.join)((0,ks.tmpdir)(),`sc-plugin-${e}-${Date.now()}`);return(0,Is.mkdirSync)(n,{recursive:!0}),new vs.default(t).extractAllTo(n,!0),n}function Lt(r){return{"claude-code":"claude","gemini-cli":"gemini",cursor:"cursor"}[r]||"claude"}fe();te();var Me=require("fs"),Ft=require("path"),Ts=".shared-context",Rs="project.json";function ve(){let r=(0,Ft.join)(process.cwd(),Ts,Rs);if(!(0,Me.existsSync)(r))return null;try{let e=JSON.parse((0,Me.readFileSync)(r,"utf-8"));return e.projectId&&e.projectName&&e.projectSlug?e:null}catch{return null}}function Et(r){let e=(0,Ft.join)(process.cwd(),Ts);(0,Me.mkdirSync)(e,{recursive:!0}),(0,Me.writeFileSync)((0,Ft.join)(e,Rs),JSON.stringify(r,null,2)+`
37
- `,"utf-8")}var Ns={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function V(r,e){let t=(0,_e.resolve)(r);for(let n of e){let s=(0,_e.resolve)((0,_e.join)(r,n.path));if(!s.startsWith(t+"/")&&s!==t)throw new Error(`Invalid file path: ${n.path}`);(0,xe.mkdirSync)((0,_e.dirname)(s),{recursive:!0}),(0,xe.writeFileSync)(s,n.content,"utf-8")}}function $r(r){let e=r.resource.slug||r.resource.id;return`${Ns[r.resource.resourceType]||r.resource.resourceType+"s"}/${e}`}function Ps(r,e,t,n){let s=(0,_e.join)(r,e);if(!(0,xe.existsSync)(s))return{slug:e,renamed:!1};if(!G().installations.find(u=>{let a=u.installPath.split("/");return a[a.length-1]===e&&u.resourceId!==t}))return{slug:e,renamed:!1};let c=n.resource.orgSlug||n.resource.githubOwner||n.resource.id.slice(0,8);return{slug:`${e}-${c}`,renamed:!0}}function $t(r,e,t){let n=t.files.find(a=>a.path.endsWith(".json")&&!a.path.includes("/"))||t.files.find(a=>a.path.endsWith(".json")&&a.path.includes("resources/"));if(!n)throw new Error("MCP package does not contain a config file");let s=JSON.parse(n.content),o=oe(r,e),l=t.resource.slug||t.resource.id,c={};if((0,xe.existsSync)(o))try{c=JSON.parse((0,xe.readFileSync)(o,"utf-8"))}catch{c={}}let u=typeof c.mcpServers=="object"&&c.mcpServers&&!Array.isArray(c.mcpServers)?c.mcpServers:{};s.mcpServers&&typeof s.mcpServers=="object"?Object.assign(u,s.mcpServers):u[l]=s,c.mcpServers=u,(0,xe.mkdirSync)((0,_e.dirname)(o),{recursive:!0}),(0,xe.writeFileSync)(o,JSON.stringify(c,null,2)+`
38
- `,"utf-8")}function Zi(r,e,t,n){let s=t.files.find(a=>a.path.endsWith(".json")&&!a.path.includes("/"));if(!s)throw new Error("Hook package does not contain a hook.json file");let o=JSON.parse(s.content),l=ye(r,e),c={},u=o.hooks&&typeof o.hooks=="object"&&!Array.isArray(o.hooks)?o.hooks:o;for(let[a,p]of Object.entries(u))if(!(a==="name"||a==="description")&&Array.isArray(p)){c[a]||(c[a]=[]);for(let S of p)c[a].push(S)}if(Object.keys(c).length===0)throw new Error("Hook package does not contain any hook event handlers");return Mr(l,c,n),l}function js(r){r.command("install <path>").description("Install a resource (e.g., skills/acme/api-testing)").action(async(e,t,n)=>{let s=n.optsWithGlobals(),o=ke(s.agent);if(!o){let i=Fe();_()?j("install","NO_AGENTS",i):R(i),process.exit(1)}let l=M(),u=await z(`${l?"/api/cli/resource":"/api/public/resource"}/${e}`);u.ok||(_()?j("install",u.error.code,u.error.message):R(`Install failed: ${u.error.message}`),process.exit(1));let a=u.data,p=a.resource.slug||a.resource.id,S=$r(a),x,d="decomposed",m;if(a.resource.resourceType==="agent"){let i=re(o,!!s.project),y=Ps(i,p,a.resource.id,a);y.renamed&&(p=y.slug,S=$r({...a,resource:{...a.resource,slug:p}}),_()||w(`Note: Renamed to "${p}" (collision with existing resource)`)),x=(0,_e.join)(i,p);try{V(x,a.files)}catch(g){_()?j("install","WRITE_FAILED",`Failed to write files: ${g}`):R(`Failed to write files: ${g}`),process.exit(1)}}else if(a.resource.resourceType==="mcp"){x="";try{$t(o,!!s.project,a)}catch(i){_()?j("install","WRITE_FAILED",`Failed to install MCP config: ${i}`):R(`Failed to install MCP config: ${i}`),process.exit(1)}}else if(a.resource.resourceType==="hook"){x="";try{Zi(o,!!s.project,a,S)}catch(i){_()?j("install","WRITE_FAILED",`Failed to install hook config: ${i}`):R(`Failed to install hook config: ${i}`),process.exit(1)}}else{let i=W(o,!!s.project);if(a.resource.resourceType!=="collection"){let y=Ps(i,p,a.resource.id,a);y.renamed&&(p=y.slug,S=$r({...a,resource:{...a.resource,slug:p}}),_()||w(`Note: Renamed to "${p}" (collision with existing resource)`))}x=(0,_e.join)(i,p);try{if(a.resource.resourceType==="collection"){let y=st(o.id);if(y)try{let g=a.resource.slug||a.resource.id,A=a.resource.orgSlug||"",b=Lt(o.id),O=l?`/api/cli/resource/collections/${A}/${g}?format=plugin&platform=${b}`:`/api/public/resource/collections/${A}/${g}?format=plugin&platform=${b}`,k=await jt(O,g);(0,Ds.execSync)(`${y} plugin install "${k}"`,{stdio:"pipe"}),x=k,d="plugin",m=k,_()||w(`Installed as native ${y} plugin`)}catch(g){_()||R(`Native plugin install failed, falling back to decomposed: ${g}`);let b=await Te(o).install(a,s.project?"project":"user",o);x=b.installDir;for(let O of b.warnings)_()||R(`Warning: ${O}`)}else{let A=await Te(o).install(a,s.project?"project":"user",o);if(x=A.installDir,!_())for(let b of A.warnings)R(`Warning: ${b}`)}}else V(x,a.files)}catch(y){_()?j("install","WRITE_FAILED",`Failed to write files: ${y}`):R(`Failed to write files: ${y}`),process.exit(1)}}let E;if(l&&a.resource.latestSha){let i=await $("/api/cli/install",{resourceId:a.resource.id,agentPlatform:o.platform,installedSha:a.resource.latestSha});i.ok||(E=`Could not record install on server: ${i.error.message}`,_()||R(`Warning: ${E}`))}let f=s.project?ve():null;f&&l&&await $(`/api/cli/projects/${f.projectId}/resources`,{resourceId:a.resource.id}).catch(()=>{});let h={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"},C=a.resource.resourceType==="collection";if(ue({resourceId:a.resource.id,slug:p,installPath:S,title:a.resource.title,sha:a.resource.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),latestSha:a.resource.latestSha||void 0,resourceType:a.resource.resourceType,serverSynced:!0,...C?{pluginFormat:h[o.id]||"directory",memberCount:a.memberResources?.length,installMode:d,pluginDir:m}:{},...f?{projectId:f.projectId}:{}}),a.memberResources&&a.resource.resourceType==="collection"){if(d==="decomposed")for(let i of a.memberResources){let y=i.slug||i.id,A=`${Ns[i.resourceType]||i.resourceType+"s"}/${y}`;ue({resourceId:i.id,slug:y,installPath:A,title:i.title,sha:i.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),collectionId:a.resource.id,resourceType:i.resourceType,serverSynced:!0})}for(let i of a.memberResources)l&&i.latestSha&&await $("/api/cli/install",{resourceId:i.id,agentPlatform:o.platform,installedSha:i.latestSha}).catch(()=>{})}if(Ne(),_())F("install",{installPath:S,title:a.resource.title,path:x||void 0,files:a.files.length,...a.resource.resourceType==="mcp"?{mcpConfigPath:oe(o,!!s.project)}:{},...a.resource.resourceType==="hook"?{settingsPath:ye(o,!!s.project)}:{},...a.memberResources?{memberResources:a.memberResources.map(i=>({title:i.title,resourceType:i.resourceType,slug:i.slug}))}:{},...E&&{warning:E}});else{if(a.resource.resourceType==="mcp"?w(`Installed MCP "${a.resource.title}" to ${oe(o,!!s.project)}`):a.resource.resourceType==="hook"?w(`Installed hook "${a.resource.title}" to ${ye(o,!!s.project)}`):a.memberResources&&a.memberResources.length>0?w(`Installed "${a.resource.title}" (${a.memberResources.length} resources)`):w(`Installed "${a.resource.title}" to ${x}`),a.resource.resourceType!=="mcp"&&a.resource.resourceType!=="hook"&&!(a.memberResources&&a.memberResources.length>0)&&w(` ${a.files.length} file${a.files.length===1?"":"s"} written`),a.memberResources&&a.memberResources.length>0){let i={};for(let g of a.memberResources){let A=g.resourceType||"other";i[A]||(i[A]=[]),i[A].push(g.title)}let y={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections",file:"Files"};w("");for(let[g,A]of Object.entries(i)){let b=y[g]||g;w(` ${b}: ${A.join(", ")}`)}}l||(w(""),w("Tip: Sign up at sharedcontext.ai to track installations and get updates."))}})}var Mt=class{buildFiles(e){let t=[],n=[],s=[],o={},l={};for(let c of e.files){let u=c.path.split("/"),a=u[0];if(a==="agents")s.push({path:c.path.slice(7),content:c.content});else if(a==="mcps"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(o,p.mcpServers);else if(c.path.includes("resources/")){let S=u.indexOf("resources"),x=S>0?u[S-1]:u[1];o[x]=p}}catch{t.push(`Failed to parse MCP config: ${c.path}`)}}else if(a==="hooks"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content),S=c.path.replace(/\/[^/]+$/,"");Ji(p,l,S)}catch{t.push(`Failed to parse hook config: ${c.path}`)}}else a==="skills"||a==="commands"||a==="files"?n.push({path:c.path.slice(a.length+1),content:c.content}):n.push(c)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:l,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=e.resource.slug||e.resource.id,c=W(n,o),u=Yi(e),a=(0,Ke.join)(c,...u),p=0;if(s.mainFiles.length>0){let S=s.mainFiles.filter(d=>!d.path.includes("/")),x=s.mainFiles.filter(d=>d.path.includes("/"));if(S.length>0){let d=S.find(m=>m.path==="README.md");d&&S.push({path:"SKILL.md",content:Xi(e,d.content)}),V(a,S),p+=S.length}x.length>0&&(V(c,x),p+=x.length)}if(s.agentFiles.length>0){let S=re(n,o);V(S,s.agentFiles),p+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Ki(oe(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Mr(ye(n,o),s.hookEntries),{installDir:a,filesWritten:p,warnings:s.warnings}}async uninstall(e,t,n,s){let o=[],c=W(n,t==="project"),u=(0,Ke.join)(c,e),a=!1;return(0,ce.existsSync)(u)&&((0,ce.rmSync)(u,{recursive:!0,force:!0}),a=!0),a||o.push(`Collection directory not found at ${u}`),{removed:a,warnings:o}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,Ke.join)(s,e)}};function Ji(r,e,t){if(!r||typeof r!="object")return;let n=r,s=n.hooks&&typeof n.hooks=="object"&&!Array.isArray(n.hooks)?n.hooks:n;for(let[o,l]of Object.entries(s))if(!(o==="name"||o==="description")&&Array.isArray(l)){e[o]||(e[o]=[]);for(let c of l){let u=t&&typeof c=="object"&&c!==null?{...c,_sc:t}:c;e[o].push(u)}}}function Mr(r,e,t){let n={};if((0,ce.existsSync)(r))try{n=JSON.parse((0,ce.readFileSync)(r,"utf-8"))}catch{n={}}let s=typeof n.hooks=="object"&&n.hooks&&!Array.isArray(n.hooks)?n.hooks:{};if(t)for(let[o,l]of Object.entries(s))Array.isArray(l)&&(s[o]=l.filter(c=>!c||typeof c!="object"||c._sc!==t),s[o].length===0&&delete s[o]);for(let[o,l]of Object.entries(e)){Array.isArray(s[o])||(s[o]=[]);for(let c of l){let u=t&&typeof c=="object"&&c!==null?{...c,_sc:t}:c,a=JSON.stringify(u);s[o].some(S=>JSON.stringify(S)===a)||s[o].push(u)}}n.hooks=s,(0,ce.mkdirSync)((0,Ke.dirname)(r),{recursive:!0}),(0,ce.writeFileSync)(r,JSON.stringify(n,null,2)+`
39
- `,"utf-8")}function Ur(r,e){if(!(0,ce.existsSync)(r))return!1;let t;try{t=JSON.parse((0,ce.readFileSync)(r,"utf-8"))}catch{return!1}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:null;if(!n)return!1;let s=!1;for(let[o,l]of Object.entries(n)){if(!Array.isArray(l))continue;let c=l.filter(u=>!u||typeof u!="object"||u._sc!==e);c.length!==l.length&&(s=!0,c.length===0?delete n[o]:n[o]=c)}return s&&(t.hooks=n,(0,ce.writeFileSync)(r,JSON.stringify(t,null,2)+`
40
- `,"utf-8")),s}function Ki(r,e){let t={};if((0,ce.existsSync)(r))try{t=JSON.parse((0,ce.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,ce.mkdirSync)((0,Ke.dirname)(r),{recursive:!0}),(0,ce.writeFileSync)(r,JSON.stringify(t,null,2)+`
41
- `,"utf-8")}function Xi(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
42
- `)}function Yi(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var Se=require("fs"),Xe=require("path");var Qi={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},Ut=class{buildFiles(e){let t=[],n=[],s=[],o={},l={};for(let c of e.files){let u=c.path.split("/"),a=u[0];if(a==="agents")s.push({path:c.path.slice(7),content:c.content});else if(a==="mcps"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(o,p.mcpServers);else if(c.path.includes("resources/")){let S=u.indexOf("resources"),x=S>0?u[S-1]:u[1];o[x]=p}}catch{t.push(`Failed to parse MCP config: ${c.path}`)}}else if(a==="hooks"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content);ea(p,l)}catch{t.push(`Failed to parse hook config: ${c.path}`)}}else a==="skills"||a==="commands"||a==="files"?n.push({path:c.path.slice(a.length+1),content:c.content}):n.push(c)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:l,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=e.resource.slug||e.resource.id,c=W(n,o),u=sa(e),a=(0,Xe.join)(c,...u),p=0;if(s.mainFiles.length>0){let S=s.mainFiles.filter(d=>!d.path.includes("/")),x=s.mainFiles.filter(d=>d.path.includes("/"));if(S.length>0){let d=S.find(m=>m.path==="README.md");d&&S.push({path:"SKILL.md",content:na(e,d.content)}),V(a,S),p+=S.length}x.length>0&&(V(c,x),p+=x.length)}if(s.agentFiles.length>0){let S=re(n,o);V(S,s.agentFiles),p+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&ra(oe(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&ta(ye(n,o),s.hookEntries),{installDir:a,filesWritten:p,warnings:s.warnings}}async uninstall(e,t,n){let s=[],l=W(n,t==="project"),c=(0,Xe.join)(l,e),u=!1;return(0,Se.existsSync)(c)&&((0,Se.rmSync)(c,{recursive:!0,force:!0}),u=!0),u||s.push(`Collection directory not found at ${c}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,Xe.join)(s,e)}};function ea(r,e){if(!r||typeof r!="object")return;let t=r,n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:t;for(let[s,o]of Object.entries(n)){if(s==="name"||s==="description"||!Array.isArray(o))continue;let l=Qi[s]||s;e[l]||(e[l]=[]);for(let c of o)e[l].push(c)}}function ta(r,e){let t={};if((0,Se.existsSync)(r))try{t=JSON.parse((0,Se.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:{};for(let[s,o]of Object.entries(e)){Array.isArray(n[s])||(n[s]=[]);for(let l of o){let c=JSON.stringify(l);n[s].some(a=>JSON.stringify(a)===c)||n[s].push(l)}}t.hooks=n,(0,Se.mkdirSync)((0,Xe.dirname)(r),{recursive:!0}),(0,Se.writeFileSync)(r,JSON.stringify(t,null,2)+`
43
- `,"utf-8")}function ra(r,e){let t={};if((0,Se.existsSync)(r))try{t=JSON.parse((0,Se.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,Se.mkdirSync)((0,Xe.dirname)(r),{recursive:!0}),(0,Se.writeFileSync)(r,JSON.stringify(t,null,2)+`
44
- `,"utf-8")}function na(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
45
- `)}function sa(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var le=require("fs"),Pe=require("path");var Ht=class{buildFiles(e){let t=[],n=[],s=[],o={},l=[],c=e.resource.slug||e.resource.id;for(let u of e.files){let a=u.path.split("/"),p=a[0];if(p==="agents")s.push({path:u.path.slice(7),content:u.content});else if(p==="mcps"){if(u.path.endsWith(".json"))try{let S=JSON.parse(u.content);if(S.mcpServers&&typeof S.mcpServers=="object")Object.assign(o,S.mcpServers);else if(u.path.includes("resources/")){let x=a.indexOf("resources"),d=x>0?a[x-1]:a[1];o[d]=S}}catch{t.push(`Failed to parse MCP config: ${u.path}`)}}else p==="hooks"?t.push(`Hooks are not supported by Cursor (skipped: ${u.path})`):p==="skills"||p==="commands"||p==="files"?n.push({path:u.path.slice(p.length+1),content:u.content}):n.push(u)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:{},customFiles:l,warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=W(n,o),c=aa(e),u=(0,Pe.join)(l,...c),a=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(x=>!x.path.includes("/")),S=s.mainFiles.filter(x=>x.path.includes("/"));if(p.length>0){let x=p.find(d=>d.path==="README.md");x&&p.push({path:"SKILL.md",content:ia(e,x.content)}),V(u,p),a+=p.length}S.length>0&&(V(l,S),a+=S.length)}if(s.agentFiles.length>0){let p=re(n,o);V(p,s.agentFiles),a+=s.agentFiles.length}for(let p of s.customFiles)(0,le.mkdirSync)((0,Pe.dirname)(p.absolutePath),{recursive:!0}),(0,le.writeFileSync)(p.absolutePath,p.content,"utf-8"),a++;return Object.keys(s.mcpEntries).length>0&&oa(oe(n,o),s.mcpEntries),{installDir:u,filesWritten:a,warnings:s.warnings}}async uninstall(e,t,n){let s=[],l=W(n,t==="project"),c=(0,Pe.join)(l,e),u=!1;(0,le.existsSync)(c)&&((0,le.rmSync)(c,{recursive:!0,force:!0}),u=!0);let a=(0,Pe.join)(homedir(),".cursor","rules");if((0,le.existsSync)(a))try{let p=(0,le.readdirSync)(a);for(let S of p)S.startsWith(`${e}-`)&&S.endsWith(".mdc")&&((0,le.unlinkSync)((0,Pe.join)(a,S)),u=!0)}catch{s.push("Could not clean up Cursor rules")}return u||s.push(`Collection not found for Cursor at ${c}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,Pe.join)(s,e)}};function oa(r,e){let t={};if((0,le.existsSync)(r))try{t=JSON.parse((0,le.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,le.mkdirSync)((0,Pe.dirname)(r),{recursive:!0}),(0,le.writeFileSync)(r,JSON.stringify(t,null,2)+`
46
- `,"utf-8")}function ia(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
47
- `)}function aa(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var Vt=require("fs"),Bt=require("path");var Wt=class{buildFiles(e){let t=[],n=[],s=[];for(let o of e.files){let c=o.path.split("/")[0];c==="agents"?s.push({path:o.path.slice(7),content:o.content}):c==="mcps"?t.push(`MCP servers are not yet supported by Codex adapter (skipped: ${o.path})`):c==="hooks"?t.push(`Hooks are not supported by Codex (skipped: ${o.path})`):c==="commands"?t.push(`Commands are not supported by Codex (skipped: ${o.path})`):c==="skills"||c==="files"?n.push({path:o.path.slice(c.length+1),content:o.content}):n.push(o)}return{mainFiles:n,agentFiles:s,mcpEntries:{},hookEntries:{},customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=W(n,o),c=la(e),u=(0,Bt.join)(l,...c),a=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(x=>!x.path.includes("/")),S=s.mainFiles.filter(x=>x.path.includes("/"));if(p.length>0){let x=p.find(d=>d.path==="README.md");x&&p.push({path:"SKILL.md",content:ca(e,x.content)}),V(u,p),a+=p.length}S.length>0&&(V(l,S),a+=S.length)}if(s.agentFiles.length>0){let p=re(n,o);V(p,s.agentFiles),a+=s.agentFiles.length}return{installDir:u,filesWritten:a,warnings:s.warnings}}async uninstall(e,t,n){let s=[],l=W(n,t==="project"),c=(0,Bt.join)(l,e),u=!1;return(0,Vt.existsSync)(c)&&((0,Vt.rmSync)(c,{recursive:!0,force:!0}),u=!0),u||s.push(`Collection directory not found at ${c}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,Bt.join)(s,e)}};function ca(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
48
- `)}function la(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var Ie=require("fs"),ot=require("path");var Gt=class{buildFiles(e){let t=[],n=[],s={};for(let o of e.files){let l=o.path.split("/"),c=l[0];if(c==="agents")n.push({path:o.path.slice(7),content:o.content});else if(c==="mcps"){if(o.path.endsWith(".json"))try{let u=JSON.parse(o.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(s,u.mcpServers);else if(o.path.includes("resources/")){let a=l.indexOf("resources"),p=a>0?l[a-1]:l[1];s[p]=u}}catch{}}else c==="skills"||c==="commands"||c==="hooks"||c==="files"?t.push({path:o.path.slice(c.length+1),content:o.content}):t.push(o)}return{mainFiles:t,agentFiles:n,mcpEntries:s,hookEntries:{},customFiles:[],warnings:[]}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=W(n,o),c=fa(e),u=(0,ot.join)(l,...c),a=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(x=>!x.path.includes("/")),S=s.mainFiles.filter(x=>x.path.includes("/"));p.length>0&&(V(u,p),a+=p.length),S.length>0&&(V(l,S),a+=S.length)}if(s.agentFiles.length>0){let p=re(n,o);V(p,s.agentFiles),a+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&ua(oe(n,o),s.mcpEntries),{installDir:u,filesWritten:a,warnings:s.warnings}}async uninstall(e,t,n){let o=W(n,t==="project"),l=(0,ot.join)(o,e),c=!1;return(0,Ie.existsSync)(l)&&((0,Ie.rmSync)(l,{recursive:!0,force:!0}),c=!0),{removed:c,warnings:[]}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,ot.join)(s,e)}};function ua(r,e){let t={};if((0,Ie.existsSync)(r))try{t=JSON.parse((0,Ie.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,Ie.mkdirSync)((0,ot.dirname)(r),{recursive:!0}),(0,Ie.writeFileSync)(r,JSON.stringify(t,null,2)+`
49
- `,"utf-8")}function fa(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}function Te(r){switch(r.id){case"claude-code":return new Mt;case"gemini-cli":case"antigravity":return new Ut;case"cursor":return new Ht;case"codex":return new Wt;default:return new Gt}}var Ls=`---
36
+ `,"utf8")}catch{}}async function Zo(r=!1){if(!xe().telemetry)return{uploaded:0};if(!U())return{uploaded:0};let e=Wa();if(e.length===0)return{uploaded:0};let t=e.slice(0,Ua),n=await L("/api/cli/telemetry",{events:t},1e4);if(n.ok){if(Va(Ha),!r){let s=n.data?.accepted??0;A()?F("telemetry",{uploaded:s}):s>0&&w(`Uploaded ${s} usage event${s===1?"":"s"}`)}return{uploaded:n.data?.accepted??0}}return!r&&!A()&&R("Telemetry upload failed \u2014 will retry next session"),{uploaded:0}}function En(r){r.command("telemetry").description("Manage usage telemetry").command("push").description("Upload local usage data to Shared Context").option("--quiet","Suppress output").action(async t=>{await Zo(t.quiet)})}var Ke,ir,Sn,Ua,Ha,Cn=ge(()=>{"use strict";Ke=require("fs"),ir=require("path"),Sn=require("os");ie();me();se();Ua=1e3,Ha=100});var Fn=ye($n(),1),{program:sc,createCommand:oc,createArgument:ic,createOption:ac,CommanderError:cc,InvalidArgumentError:lc,InvalidOptionArgumentError:uc,Command:Ln,Argument:fc,Option:dc,Help:pc}=Fn.default;se();var Yt=require("fs"),nt=require("path"),Zs=require("os");me();ie();se();var $r=require("fs"),be=require("path"),Ue=require("os"),it=[{id:"claude-code",label:"Claude Code",envVars:["CLAUDE_CODE"],dir:".claude",skillsSubdir:"skills",platform:"claude_code"},{id:"cursor",label:"Cursor",envVars:["CURSOR","CURSOR_TRACE_ID"],dir:".cursor",skillsSubdir:"skills",platform:"custom"},{id:"codex",label:"Codex",envVars:["CODEX","CODEX_CI"],dir:".codex",skillsSubdir:"skills",platform:"codex"},{id:"opencode",label:"OpenCode",envVars:["OPENCODE"],dir:".opencode",skillsSubdir:"skills",platform:"custom"},{id:"gemini-cli",label:"Gemini CLI",envVars:["GEMINI_CLI"],dir:".gemini",skillsSubdir:"skills",platform:"gemini"},{id:"antigravity",label:"Antigravity",envVars:["GEMINI_CLI_IDE_WORKSPACE_PATH","GEMINI_CLI_IDE_PID"],dir:".gemini/antigravity",skillsSubdir:"skills",platform:"gemini"}];function Pe(r){if(r){let n=it.find(o=>o.id===r);if(n)return n;let s=it.find(o=>o.dir===`.${r}`||o.dir===r);return s||null}for(let n of it)if(n.envVars.some(s=>process.env[s]))return n;let e=(0,Ue.homedir)(),t=[];for(let n of it)(0,$r.existsSync)((0,be.join)(e,n.dir))&&t.push(n);return t.length===1?t[0]:null}function He(){let r=[],e=(0,Ue.homedir)();for(let t of it)(t.envVars.some(n=>process.env[n])||(0,$r.existsSync)((0,be.join)(e,t.dir)))&&r.push(t);return r}function Be(){let r=He();return r.length>1?`Multiple AI agents detected (${r.map(e=>e.label).join(", ")}). Use --agent to specify: ${r.map(e=>e.id).join(", ")}`:`No AI agent detected. Use --agent to specify one (${it.map(e=>e.id).join(", ")})`}function q(r,e){return e?(0,be.join)(process.cwd(),r.dir,r.skillsSubdir):(0,be.join)((0,Ue.homedir)(),r.dir,r.skillsSubdir)}function re(r,e){return e?(0,be.join)(process.cwd(),r.dir,"agents"):(0,be.join)((0,Ue.homedir)(),r.dir,"agents")}function ae(r,e){return e?(0,be.join)(process.cwd(),".mcp.json"):r.id==="claude-code"?(0,be.join)((0,Ue.homedir)(),".claude.json"):r.id==="cursor"?(0,be.join)((0,Ue.homedir)(),".cursor","mcp.json"):(0,be.join)(process.cwd(),".mcp.json")}function Ee(r,e){return e?(0,be.join)(process.cwd(),r.dir,"settings.json"):(0,be.join)((0,Ue.homedir)(),r.dir,"settings.json")}var fe=require("fs"),et=require("path");var Te=require("fs"),ve=require("path"),$s=require("child_process");ie();var ks=require("child_process"),vs=require("fs"),Ts=require("path"),Rs=require("os"),Ps=ye(Os());ie();function ut(r){let t={"claude-code":"claude",cursor:"cursor","gemini-cli":"gemini"}[r];if(!t)return null;try{return(0,ks.execSync)(`which ${t}`,{stdio:"pipe"}),t}catch{return null}}async function Lt(r,e){let t=await jr(r),n=(0,Ts.join)((0,Rs.tmpdir)(),`sc-plugin-${e}-${Date.now()}`);return(0,vs.mkdirSync)(n,{recursive:!0}),new Ps.default(t).extractAllTo(n,!0),n}function Mt(r){return{"claude-code":"claude","gemini-cli":"gemini",cursor:"cursor"}[r]||"claude"}me();se();var Ve=require("fs"),Ut=require("path"),Ds=".shared-context",Ns="project.json";function ke(){let r=(0,Ut.join)(process.cwd(),Ds,Ns);if(!(0,Ve.existsSync)(r))return null;try{let e=JSON.parse((0,Ve.readFileSync)(r,"utf-8"));return e.projectId&&e.projectName&&e.projectSlug?e:null}catch{return null}}function Qe(r){let e=(0,Ut.join)(process.cwd(),Ds);(0,Ve.mkdirSync)(e,{recursive:!0}),(0,Ve.writeFileSync)((0,Ut.join)(e,Ns),JSON.stringify(r,null,2)+`
37
+ `,"utf-8")}var Fs={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function G(r,e){let t=(0,ve.resolve)(r);for(let n of e){let s=(0,ve.resolve)((0,ve.join)(r,n.path));if(!s.startsWith(t+"/")&&s!==t)throw new Error(`Invalid file path: ${n.path}`);(0,Te.mkdirSync)((0,ve.dirname)(s),{recursive:!0}),(0,Te.writeFileSync)(s,n.content,"utf-8")}}function Br(r){let e=r.resource.slug||r.resource.id;return`${Fs[r.resource.resourceType]||r.resource.resourceType+"s"}/${e}`}function js(r,e,t,n){let s=(0,ve.join)(r,e);if(!(0,Te.existsSync)(s))return{slug:e,renamed:!1};if(!z().installations.find(u=>{let a=u.installPath.split("/");return a[a.length-1]===e&&u.resourceId!==t}))return{slug:e,renamed:!1};let c=n.resource.orgSlug||n.resource.githubOwner||n.resource.id.slice(0,8);return{slug:`${e}-${c}`,renamed:!0}}function Ht(r,e,t){let n=t.files.find(a=>a.path.endsWith(".json")&&!a.path.includes("/"))||t.files.find(a=>a.path.endsWith(".json")&&a.path.includes("resources/"));if(!n)throw new Error("MCP package does not contain a config file");let s=JSON.parse(n.content),o=ae(r,e),l=t.resource.slug||t.resource.id,c={};if((0,Te.existsSync)(o))try{c=JSON.parse((0,Te.readFileSync)(o,"utf-8"))}catch{c={}}let u=typeof c.mcpServers=="object"&&c.mcpServers&&!Array.isArray(c.mcpServers)?c.mcpServers:{};s.mcpServers&&typeof s.mcpServers=="object"?Object.assign(u,s.mcpServers):u[l]=s,c.mcpServers=u,(0,Te.mkdirSync)((0,ve.dirname)(o),{recursive:!0}),(0,Te.writeFileSync)(o,JSON.stringify(c,null,2)+`
38
+ `,"utf-8")}function Ki(r,e,t,n){let s=t.files.find(a=>a.path.endsWith(".json")&&!a.path.includes("/"));if(!s)throw new Error("Hook package does not contain a hook.json file");let o=JSON.parse(s.content),l=Ee(r,e),c={},u=o.hooks&&typeof o.hooks=="object"&&!Array.isArray(o.hooks)?o.hooks:o;for(let[a,p]of Object.entries(u))if(!(a==="name"||a==="description")&&Array.isArray(p)){c[a]||(c[a]=[]);for(let S of p)c[a].push(S)}if(Object.keys(c).length===0)throw new Error("Hook package does not contain any hook event handlers");return Wr(l,c,n),l}function Ls(r){r.command("install <path>").description("Install a resource (e.g., skills/acme/api-testing)").action(async(e,t,n)=>{let s=n.optsWithGlobals(),o=Pe(s.agent);if(!o){let i=Be();A()?$("install","NO_AGENTS",i):R(i),process.exit(1)}let l=U(),u=await Z(`${l?"/api/cli/resource":"/api/public/resource"}/${e}`);u.ok||(A()?$("install",u.error.code,u.error.message):R(`Install failed: ${u.error.message}`),process.exit(1));let a=u.data,p=a.resource.slug||a.resource.id,S=Br(a),I,d="decomposed",m;if(a.resource.resourceType==="agent"){let i=re(o,!!s.project),g=js(i,p,a.resource.id,a);g.renamed&&(p=g.slug,S=Br({...a,resource:{...a.resource,slug:p}}),A()||w(`Note: Renamed to "${p}" (collision with existing resource)`)),I=(0,ve.join)(i,p);try{G(I,a.files)}catch(y){A()?$("install","WRITE_FAILED",`Failed to write files: ${y}`):R(`Failed to write files: ${y}`),process.exit(1)}}else if(a.resource.resourceType==="mcp"){I="";try{Ht(o,!!s.project,a)}catch(i){A()?$("install","WRITE_FAILED",`Failed to install MCP config: ${i}`):R(`Failed to install MCP config: ${i}`),process.exit(1)}}else if(a.resource.resourceType==="hook"){I="";try{Ki(o,!!s.project,a,S)}catch(i){A()?$("install","WRITE_FAILED",`Failed to install hook config: ${i}`):R(`Failed to install hook config: ${i}`),process.exit(1)}}else{let i=q(o,!!s.project);if(a.resource.resourceType!=="collection"){let g=js(i,p,a.resource.id,a);g.renamed&&(p=g.slug,S=Br({...a,resource:{...a.resource,slug:p}}),A()||w(`Note: Renamed to "${p}" (collision with existing resource)`))}I=(0,ve.join)(i,p);try{if(a.resource.resourceType==="collection"){let g=ut(o.id);if(g)try{let y=a.resource.slug||a.resource.id,b=a.resource.orgSlug||"",_=Mt(o.id),O=l?`/api/cli/resource/collections/${b}/${y}?format=plugin&platform=${_}`:`/api/public/resource/collections/${b}/${y}?format=plugin&platform=${_}`,k=await Lt(O,y);(0,$s.execSync)(`${g} plugin install "${k}"`,{stdio:"pipe"}),I=k,d="plugin",m=k,A()||w(`Installed as native ${g} plugin`)}catch(y){A()||R(`Native plugin install failed, falling back to decomposed: ${y}`);let _=await De(o).install(a,s.project?"project":"user",o);I=_.installDir;for(let O of _.warnings)A()||R(`Warning: ${O}`)}else{let b=await De(o).install(a,s.project?"project":"user",o);if(I=b.installDir,!A())for(let _ of b.warnings)R(`Warning: ${_}`)}}else G(I,a.files)}catch(g){A()?$("install","WRITE_FAILED",`Failed to write files: ${g}`):R(`Failed to write files: ${g}`),process.exit(1)}}let E;if(l&&a.resource.latestSha){let i=await L("/api/cli/install",{resourceId:a.resource.id,agentPlatform:o.platform,installedSha:a.resource.latestSha});i.ok||(E=`Could not record install on server: ${i.error.message}`,A()||R(`Warning: ${E}`))}let f=s.project?ke():null;f&&l&&await L(`/api/cli/projects/${f.projectId}/resources`,{resourceId:a.resource.id}).catch(()=>{});let h={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"},C=a.resource.resourceType==="collection";if(pe({resourceId:a.resource.id,slug:p,installPath:S,title:a.resource.title,sha:a.resource.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),latestSha:a.resource.latestSha||void 0,resourceType:a.resource.resourceType,serverSynced:!0,...C?{pluginFormat:h[o.id]||"directory",memberCount:a.memberResources?.length,installMode:d,pluginDir:m}:{},...f?{projectId:f.projectId}:{}}),a.memberResources&&a.resource.resourceType==="collection"){if(d==="decomposed")for(let i of a.memberResources){let g=i.slug||i.id,b=`${Fs[i.resourceType]||i.resourceType+"s"}/${g}`;pe({resourceId:i.id,slug:g,installPath:b,title:i.title,sha:i.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),collectionId:a.resource.id,resourceType:i.resourceType,serverSynced:!0})}for(let i of a.memberResources)l&&i.latestSha&&await L("/api/cli/install",{resourceId:i.id,agentPlatform:o.platform,installedSha:i.latestSha}).catch(()=>{})}if(Me(),A())F("install",{installPath:S,title:a.resource.title,path:I||void 0,files:a.files.length,...a.resource.resourceType==="mcp"?{mcpConfigPath:ae(o,!!s.project)}:{},...a.resource.resourceType==="hook"?{settingsPath:Ee(o,!!s.project)}:{},...a.memberResources?{memberResources:a.memberResources.map(i=>({title:i.title,resourceType:i.resourceType,slug:i.slug}))}:{},...E&&{warning:E}});else{if(a.resource.resourceType==="mcp"?w(`Installed MCP "${a.resource.title}" to ${ae(o,!!s.project)}`):a.resource.resourceType==="hook"?w(`Installed hook "${a.resource.title}" to ${Ee(o,!!s.project)}`):a.memberResources&&a.memberResources.length>0?w(`Installed "${a.resource.title}" (${a.memberResources.length} resources)`):w(`Installed "${a.resource.title}" to ${I}`),a.resource.resourceType!=="mcp"&&a.resource.resourceType!=="hook"&&!(a.memberResources&&a.memberResources.length>0)&&w(` ${a.files.length} file${a.files.length===1?"":"s"} written`),a.memberResources&&a.memberResources.length>0){let i={};for(let y of a.memberResources){let b=y.resourceType||"other";i[b]||(i[b]=[]),i[b].push(y.title)}let g={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections",file:"Files"};w("");for(let[y,b]of Object.entries(i)){let _=g[y]||y;w(` ${_}: ${b.join(", ")}`)}}l||(w(""),w("Tip: Sign up at sharedcontext.ai to track installations and get updates."))}})}var Bt=class{buildFiles(e){let t=[],n=[],s=[],o={},l={};for(let c of e.files){let u=c.path.split("/"),a=u[0];if(a==="agents")s.push({path:c.path.slice(7),content:c.content});else if(a==="mcps"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(o,p.mcpServers);else if(c.path.includes("resources/")){let S=u.indexOf("resources"),I=S>0?u[S-1]:u[1];o[I]=p}}catch{t.push(`Failed to parse MCP config: ${c.path}`)}}else if(a==="hooks"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content),S=c.path.replace(/\/[^/]+$/,"");Xi(p,l,S)}catch{t.push(`Failed to parse hook config: ${c.path}`)}}else a==="skills"||a==="commands"||a==="files"?n.push({path:c.path.slice(a.length+1),content:c.content}):n.push(c)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:l,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=e.resource.slug||e.resource.id,c=q(n,o),u=ea(e),a=(0,et.join)(c,...u),p=0;if(s.mainFiles.length>0){let S=s.mainFiles.filter(d=>!d.path.includes("/")),I=s.mainFiles.filter(d=>d.path.includes("/"));if(S.length>0){let d=S.find(m=>m.path==="README.md");d&&S.push({path:"SKILL.md",content:Qi(e,d.content)}),G(a,S),p+=S.length}I.length>0&&(G(c,I),p+=I.length)}if(s.agentFiles.length>0){let S=re(n,o);G(S,s.agentFiles),p+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Yi(ae(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Wr(Ee(n,o),s.hookEntries),{installDir:a,filesWritten:p,warnings:s.warnings}}async uninstall(e,t,n,s){let o=[],c=q(n,t==="project"),u=(0,et.join)(c,e),a=!1;return(0,fe.existsSync)(u)&&((0,fe.rmSync)(u,{recursive:!0,force:!0}),a=!0),a||o.push(`Collection directory not found at ${u}`),{removed:a,warnings:o}}describeLocation(e,t,n){let s=q(n,t==="project");return(0,et.join)(s,e)}};function Xi(r,e,t){if(!r||typeof r!="object")return;let n=r,s=n.hooks&&typeof n.hooks=="object"&&!Array.isArray(n.hooks)?n.hooks:n;for(let[o,l]of Object.entries(s))if(!(o==="name"||o==="description")&&Array.isArray(l)){e[o]||(e[o]=[]);for(let c of l){let u=t&&typeof c=="object"&&c!==null?{...c,_sc:t}:c;e[o].push(u)}}}function Wr(r,e,t){let n={};if((0,fe.existsSync)(r))try{n=JSON.parse((0,fe.readFileSync)(r,"utf-8"))}catch{n={}}let s=typeof n.hooks=="object"&&n.hooks&&!Array.isArray(n.hooks)?n.hooks:{};if(t)for(let[o,l]of Object.entries(s))Array.isArray(l)&&(s[o]=l.filter(c=>!c||typeof c!="object"||c._sc!==t),s[o].length===0&&delete s[o]);for(let[o,l]of Object.entries(e)){Array.isArray(s[o])||(s[o]=[]);for(let c of l){let u=t&&typeof c=="object"&&c!==null?{...c,_sc:t}:c,a=JSON.stringify(u);s[o].some(S=>JSON.stringify(S)===a)||s[o].push(u)}}n.hooks=s,(0,fe.mkdirSync)((0,et.dirname)(r),{recursive:!0}),(0,fe.writeFileSync)(r,JSON.stringify(n,null,2)+`
39
+ `,"utf-8")}function Vr(r,e){if(!(0,fe.existsSync)(r))return!1;let t;try{t=JSON.parse((0,fe.readFileSync)(r,"utf-8"))}catch{return!1}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:null;if(!n)return!1;let s=!1;for(let[o,l]of Object.entries(n)){if(!Array.isArray(l))continue;let c=l.filter(u=>!u||typeof u!="object"||u._sc!==e);c.length!==l.length&&(s=!0,c.length===0?delete n[o]:n[o]=c)}return s&&(t.hooks=n,(0,fe.writeFileSync)(r,JSON.stringify(t,null,2)+`
40
+ `,"utf-8")),s}function Yi(r,e){let t={};if((0,fe.existsSync)(r))try{t=JSON.parse((0,fe.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,fe.mkdirSync)((0,et.dirname)(r),{recursive:!0}),(0,fe.writeFileSync)(r,JSON.stringify(t,null,2)+`
41
+ `,"utf-8")}function Qi(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
42
+ `)}function ea(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var Ce=require("fs"),tt=require("path");var ta={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},Wt=class{buildFiles(e){let t=[],n=[],s=[],o={},l={};for(let c of e.files){let u=c.path.split("/"),a=u[0];if(a==="agents")s.push({path:c.path.slice(7),content:c.content});else if(a==="mcps"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(o,p.mcpServers);else if(c.path.includes("resources/")){let S=u.indexOf("resources"),I=S>0?u[S-1]:u[1];o[I]=p}}catch{t.push(`Failed to parse MCP config: ${c.path}`)}}else if(a==="hooks"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content);ra(p,l)}catch{t.push(`Failed to parse hook config: ${c.path}`)}}else a==="skills"||a==="commands"||a==="files"?n.push({path:c.path.slice(a.length+1),content:c.content}):n.push(c)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:l,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=e.resource.slug||e.resource.id,c=q(n,o),u=ia(e),a=(0,tt.join)(c,...u),p=0;if(s.mainFiles.length>0){let S=s.mainFiles.filter(d=>!d.path.includes("/")),I=s.mainFiles.filter(d=>d.path.includes("/"));if(S.length>0){let d=S.find(m=>m.path==="README.md");d&&S.push({path:"SKILL.md",content:oa(e,d.content)}),G(a,S),p+=S.length}I.length>0&&(G(c,I),p+=I.length)}if(s.agentFiles.length>0){let S=re(n,o);G(S,s.agentFiles),p+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&sa(ae(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&na(Ee(n,o),s.hookEntries),{installDir:a,filesWritten:p,warnings:s.warnings}}async uninstall(e,t,n){let s=[],l=q(n,t==="project"),c=(0,tt.join)(l,e),u=!1;return(0,Ce.existsSync)(c)&&((0,Ce.rmSync)(c,{recursive:!0,force:!0}),u=!0),u||s.push(`Collection directory not found at ${c}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=q(n,t==="project");return(0,tt.join)(s,e)}};function ra(r,e){if(!r||typeof r!="object")return;let t=r,n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:t;for(let[s,o]of Object.entries(n)){if(s==="name"||s==="description"||!Array.isArray(o))continue;let l=ta[s]||s;e[l]||(e[l]=[]);for(let c of o)e[l].push(c)}}function na(r,e){let t={};if((0,Ce.existsSync)(r))try{t=JSON.parse((0,Ce.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:{};for(let[s,o]of Object.entries(e)){Array.isArray(n[s])||(n[s]=[]);for(let l of o){let c=JSON.stringify(l);n[s].some(a=>JSON.stringify(a)===c)||n[s].push(l)}}t.hooks=n,(0,Ce.mkdirSync)((0,tt.dirname)(r),{recursive:!0}),(0,Ce.writeFileSync)(r,JSON.stringify(t,null,2)+`
43
+ `,"utf-8")}function sa(r,e){let t={};if((0,Ce.existsSync)(r))try{t=JSON.parse((0,Ce.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,Ce.mkdirSync)((0,tt.dirname)(r),{recursive:!0}),(0,Ce.writeFileSync)(r,JSON.stringify(t,null,2)+`
44
+ `,"utf-8")}function oa(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
45
+ `)}function ia(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var de=require("fs"),je=require("path");var Vt=class{buildFiles(e){let t=[],n=[],s=[],o={},l=[],c=e.resource.slug||e.resource.id;for(let u of e.files){let a=u.path.split("/"),p=a[0];if(p==="agents")s.push({path:u.path.slice(7),content:u.content});else if(p==="mcps"){if(u.path.endsWith(".json"))try{let S=JSON.parse(u.content);if(S.mcpServers&&typeof S.mcpServers=="object")Object.assign(o,S.mcpServers);else if(u.path.includes("resources/")){let I=a.indexOf("resources"),d=I>0?a[I-1]:a[1];o[d]=S}}catch{t.push(`Failed to parse MCP config: ${u.path}`)}}else p==="hooks"?t.push(`Hooks are not supported by Cursor (skipped: ${u.path})`):p==="skills"||p==="commands"||p==="files"?n.push({path:u.path.slice(p.length+1),content:u.content}):n.push(u)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:{},customFiles:l,warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=q(n,o),c=la(e),u=(0,je.join)(l,...c),a=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(I=>!I.path.includes("/")),S=s.mainFiles.filter(I=>I.path.includes("/"));if(p.length>0){let I=p.find(d=>d.path==="README.md");I&&p.push({path:"SKILL.md",content:ca(e,I.content)}),G(u,p),a+=p.length}S.length>0&&(G(l,S),a+=S.length)}if(s.agentFiles.length>0){let p=re(n,o);G(p,s.agentFiles),a+=s.agentFiles.length}for(let p of s.customFiles)(0,de.mkdirSync)((0,je.dirname)(p.absolutePath),{recursive:!0}),(0,de.writeFileSync)(p.absolutePath,p.content,"utf-8"),a++;return Object.keys(s.mcpEntries).length>0&&aa(ae(n,o),s.mcpEntries),{installDir:u,filesWritten:a,warnings:s.warnings}}async uninstall(e,t,n){let s=[],l=q(n,t==="project"),c=(0,je.join)(l,e),u=!1;(0,de.existsSync)(c)&&((0,de.rmSync)(c,{recursive:!0,force:!0}),u=!0);let a=(0,je.join)(homedir(),".cursor","rules");if((0,de.existsSync)(a))try{let p=(0,de.readdirSync)(a);for(let S of p)S.startsWith(`${e}-`)&&S.endsWith(".mdc")&&((0,de.unlinkSync)((0,je.join)(a,S)),u=!0)}catch{s.push("Could not clean up Cursor rules")}return u||s.push(`Collection not found for Cursor at ${c}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=q(n,t==="project");return(0,je.join)(s,e)}};function aa(r,e){let t={};if((0,de.existsSync)(r))try{t=JSON.parse((0,de.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,de.mkdirSync)((0,je.dirname)(r),{recursive:!0}),(0,de.writeFileSync)(r,JSON.stringify(t,null,2)+`
46
+ `,"utf-8")}function ca(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
47
+ `)}function la(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var zt=require("fs"),qt=require("path");var Gt=class{buildFiles(e){let t=[],n=[],s=[];for(let o of e.files){let c=o.path.split("/")[0];c==="agents"?s.push({path:o.path.slice(7),content:o.content}):c==="mcps"?t.push(`MCP servers are not yet supported by Codex adapter (skipped: ${o.path})`):c==="hooks"?t.push(`Hooks are not supported by Codex (skipped: ${o.path})`):c==="commands"?t.push(`Commands are not supported by Codex (skipped: ${o.path})`):c==="skills"||c==="files"?n.push({path:o.path.slice(c.length+1),content:o.content}):n.push(o)}return{mainFiles:n,agentFiles:s,mcpEntries:{},hookEntries:{},customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=q(n,o),c=fa(e),u=(0,qt.join)(l,...c),a=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(I=>!I.path.includes("/")),S=s.mainFiles.filter(I=>I.path.includes("/"));if(p.length>0){let I=p.find(d=>d.path==="README.md");I&&p.push({path:"SKILL.md",content:ua(e,I.content)}),G(u,p),a+=p.length}S.length>0&&(G(l,S),a+=S.length)}if(s.agentFiles.length>0){let p=re(n,o);G(p,s.agentFiles),a+=s.agentFiles.length}return{installDir:u,filesWritten:a,warnings:s.warnings}}async uninstall(e,t,n){let s=[],l=q(n,t==="project"),c=(0,qt.join)(l,e),u=!1;return(0,zt.existsSync)(c)&&((0,zt.rmSync)(c,{recursive:!0,force:!0}),u=!0),u||s.push(`Collection directory not found at ${c}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=q(n,t==="project");return(0,qt.join)(s,e)}};function ua(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
48
+ `)}function fa(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var Re=require("fs"),ft=require("path");var Zt=class{buildFiles(e){let t=[],n=[],s={};for(let o of e.files){let l=o.path.split("/"),c=l[0];if(c==="agents")n.push({path:o.path.slice(7),content:o.content});else if(c==="mcps"){if(o.path.endsWith(".json"))try{let u=JSON.parse(o.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(s,u.mcpServers);else if(o.path.includes("resources/")){let a=l.indexOf("resources"),p=a>0?l[a-1]:l[1];s[p]=u}}catch{}}else c==="skills"||c==="commands"||c==="hooks"||c==="files"?t.push({path:o.path.slice(c.length+1),content:o.content}):t.push(o)}return{mainFiles:t,agentFiles:n,mcpEntries:s,hookEntries:{},customFiles:[],warnings:[]}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=q(n,o),c=pa(e),u=(0,ft.join)(l,...c),a=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(I=>!I.path.includes("/")),S=s.mainFiles.filter(I=>I.path.includes("/"));p.length>0&&(G(u,p),a+=p.length),S.length>0&&(G(l,S),a+=S.length)}if(s.agentFiles.length>0){let p=re(n,o);G(p,s.agentFiles),a+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&da(ae(n,o),s.mcpEntries),{installDir:u,filesWritten:a,warnings:s.warnings}}async uninstall(e,t,n){let o=q(n,t==="project"),l=(0,ft.join)(o,e),c=!1;return(0,Re.existsSync)(l)&&((0,Re.rmSync)(l,{recursive:!0,force:!0}),c=!0),{removed:c,warnings:[]}}describeLocation(e,t,n){let s=q(n,t==="project");return(0,ft.join)(s,e)}};function da(r,e){let t={};if((0,Re.existsSync)(r))try{t=JSON.parse((0,Re.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,Re.mkdirSync)((0,ft.dirname)(r),{recursive:!0}),(0,Re.writeFileSync)(r,JSON.stringify(t,null,2)+`
49
+ `,"utf-8")}function pa(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}function De(r){switch(r.id){case"claude-code":return new Bt;case"gemini-cli":case"antigravity":return new Wt;case"cursor":return new Vt;case"codex":return new Gt;default:return new Zt}}var Ms=`---
50
50
  name: Context Manager
51
51
  description: "Your AI chief of staff \u2014 distills expert knowledge into resources, finds off-the-shelf solutions, and manages your working context"
52
52
  tools:
@@ -135,40 +135,42 @@ When building custom resources, follow these patterns:
135
135
  - **Specificity over comprehensiveness** \u2014 Only include instructions that meaningfully change Claude's output
136
136
  - **Filesystem as memory** \u2014 Design persistent storage so resources accumulate knowledge over time
137
137
  - **Search before building** \u2014 Check the Shared Context library before creating from scratch
138
- `;var B=require("fs"),Y=require("path"),Hs=require("crypto");var qt=".context-collection",zt="manifest.json";function Fs(r,e){return{version:1,name:r.name||"Untitled Plugin",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}function da(r,e){return{version:1,name:r.name||"Untitled Extension",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}function pa(r,e){return{version:1,name:r.name||"Untitled Plugin",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}var Hr=[{path:`${qt}/${zt}`,converter:()=>{throw new Error("Use parseCollectionManifest for native format")},formatLabel:"Shared Context"},{path:".claude-plugin/plugin.json",converter:Fs,formatLabel:"Claude Plugin"},{path:".claude/plugin.json",converter:Fs,formatLabel:"Claude Plugin"},{path:"gemini-extension.json",converter:da,formatLabel:"Gemini Extension"},{path:".cursor-plugin/plugin.json",converter:pa,formatLabel:"Cursor Plugin"}];var $s=[{folder:"skills",mainFile:"SKILL.md",resourceType:"skill",canHaveChildren:!0},{folder:"commands",mainFile:null,resourceType:"skill",canHaveChildren:!0},{folder:"hooks",mainFile:"hook.json",resourceType:"hook",canHaveChildren:!1},{folder:"agents",mainFile:null,resourceType:"agent",canHaveChildren:!0},{folder:"mcps",mainFile:"mcp.json",resourceType:"mcp",canHaveChildren:!0},{folder:"collections",mainFile:"README.md",resourceType:"collection",canHaveChildren:!1}],Ms=`${qt}/${zt}`;function at(r){let e={name:"",description:"",body:r};if(!r.startsWith(`---
138
+ `;var B=require("fs"),J=require("path"),Ws=require("crypto");var Jt=".context-collection",Kt="manifest.json";function Us(r,e){return{version:1,name:r.name||"Untitled Plugin",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}function ma(r,e){return{version:1,name:r.name||"Untitled Extension",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}function ha(r,e){return{version:1,name:r.name||"Untitled Plugin",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}var qr=[{path:`${Jt}/${Kt}`,converter:()=>{throw new Error("Use parseCollectionManifest for native format")},formatLabel:"Shared Context"},{path:".claude-plugin/plugin.json",converter:Us,formatLabel:"Claude Plugin"},{path:".claude/plugin.json",converter:Us,formatLabel:"Claude Plugin"},{path:"gemini-extension.json",converter:ma,formatLabel:"Gemini Extension"},{path:".cursor-plugin/plugin.json",converter:ha,formatLabel:"Cursor Plugin"}];var Hs=[{folder:"skills",mainFile:"SKILL.md",resourceType:"skill",canHaveChildren:!0},{folder:"commands",mainFile:null,resourceType:"skill",canHaveChildren:!0},{folder:"hooks",mainFile:"hook.json",resourceType:"hook",canHaveChildren:!1},{folder:"agents",mainFile:null,resourceType:"agent",canHaveChildren:!0},{folder:"mcps",mainFile:"mcp.json",resourceType:"mcp",canHaveChildren:!0},{folder:"collections",mainFile:"README.md",resourceType:"collection",canHaveChildren:!1}],Bs=`${Jt}/${Kt}`;function rt(r){let e={name:"",description:"",body:r};if(!r.startsWith(`---
139
139
  `)&&!r.startsWith(`---\r
140
140
  `))return e;let t=r.indexOf(`
141
141
  ---`,3);if(t===-1)return e;let n=r.slice(4,t),s=r.slice(t+4);e.body=s.replace(/^\r?\n/,"").replace(/^\r?\n/,"");let o={},l={},c=new Set(["requires","tools"]),u={},a=n.split(`
142
- `),p=null,S=!1;for(let x=0;x<a.length;x++){let d=a[x];if(p&&/^\s+-\s/.test(d)){let h=d.replace(/^\s+-\s/,"").trim();if(h){let C=it(h);S?u[p].push(C):l[p].push(C)}continue}p=null,S=!1;let m=d.indexOf(":");if(m===-1)continue;let E=d.slice(0,m).trim(),f=d.slice(m+1).trim();if(!f&&E&&x+1<a.length&&/^\s+-\s/.test(a[x+1])){p=E,c.has(E)?(S=!0,u[E]=[]):(S=!1,l[E]=[]);continue}E==="name"||E==="title"?e.name=it(f):E==="description"?e.description=it(f):E==="skill_class"?e.skillClass=it(f):E==="service"?e.service=it(f):E&&f&&(o[E]=it(f))}return u.requires?.length&&(e.requires=u.requires),u.tools?.length&&(e.tools=u.tools),Object.keys(o).length&&(e.fields=o),Object.keys(l).length&&(e.arrayFields=l),e}function it(r){let e=r.trim();if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")){let t=e.slice(1,-1);return e.startsWith('"')?t.replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t.replace(/''/g,"'")}return e}function ma(r){let{body:e}=at(r);return e.replace(/\r\n/g,`
143
- `).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function Ue(r){let e=ma(r);return`sha256:${(0,Hs.createHash)("sha256").update(e,"utf8").digest("hex")}`}function Oe(r){return r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Ct(r){try{return(0,B.statSync)(r).isDirectory()}catch{return!1}}function Us(r){try{return(0,B.readdirSync)(r).filter(e=>!e.startsWith(".")&&Ct((0,Y.join)(r,e)))}catch{return[]}}function Br(r){try{return(0,B.readdirSync)(r).filter(e=>!e.startsWith(".")&&!Ct((0,Y.join)(r,e)))}catch{return[]}}function ct(r,e){let t=[],n=[],s,o;function l(d,m){let E=[],f=[];for(let h of $s){let C=(0,Y.join)(d,h.folder);if(!(0,B.existsSync)(C)||!Ct(C))continue;let i=m?`${m}/${h.folder}`:h.folder;if(h.folder==="files"){for(let y of Br(C)){if(!y.endsWith(".md"))continue;let g=(0,Y.join)(C,y),A=(0,B.readFileSync)(g,"utf-8"),b=at(A),O=b.name||(0,Y.basename)(y,".md"),k=`${i}/${(0,Y.basename)(y,".md")}`;E.push({importPath:k,resourceType:"file",title:O,description:b.description||null,body:b.body,bodyHash:Ue(A),metadata:{}})}continue}if(h.mainFile===null)for(let y of Br(C)){if(!y.endsWith(".md"))continue;let g=(0,Y.basename)(y,".md"),A=`${i}/${g}`;if(Ct((0,Y.join)(C,g)))continue;let b=(0,B.readFileSync)((0,Y.join)(C,y),"utf-8"),O=at(b),k=O.name||Oe(g),D={};O.skillClass&&(D.skillClass=O.skillClass),O.service&&(D.service=O.service),O.requires?.length&&(D.requires=O.requires),O.tools?.length&&(D.tools=O.tools),O.fields&&Object.keys(O.fields).length&&(D.fields=O.fields),h.folder==="commands"&&(D.fields||(D.fields={}),D.fields["user-invocable"]="true"),E.push({importPath:A,resourceType:h.resourceType,title:k,description:O.description||null,body:O.body,bodyHash:Ue(b),metadata:D})}for(let y of Us(C)){let g=h.mainFile||`${y}.md`,A=(0,Y.join)(C,y,g);if(!(0,B.existsSync)(A))continue;let b=(0,B.readFileSync)(A,"utf-8"),O=`${i}/${y}`,k,D,I,T={},v=null;if(h.resourceType==="hook"||h.resourceType==="mcp"){try{let N=JSON.parse(b);k=N.name||Oe(y),D=N.description||null}catch{k=Oe(y),D=null}I=b}else if(h.resourceType==="collection"){let N=(0,Y.join)(C,y,qt,zt);if((0,B.existsSync)(N))try{let L=JSON.parse((0,B.readFileSync)(N,"utf-8"));k=L.name||Oe(y),D=L.description||null,I=b,L.resources&&Array.isArray(L.resources)&&f.push({collectionImportPath:O,memberImportPaths:L.resources.map(q=>{let ge=q.split("/");return ge.length>=3?`${ge[0]}/${ge[ge.length-1]}`:q})})}catch{k=Oe(y),D=null,I=b}else v=at(b),k=v.name||Oe(y),D=v.description||null,I=v.body,v.arrayFields?.resources&&f.push({collectionImportPath:O,memberImportPaths:v.arrayFields.resources.map(L=>{let q=L.split("/");return q.length>=3?`${q[0]}/${q[q.length-1]}`:L})})}else v=at(b),k=v.name||Oe(y),D=v.description||null,I=v.body,v.skillClass&&(T.skillClass=v.skillClass),v.service&&(T.service=v.service),v.requires?.length&&(T.requires=v.requires),v.tools?.length&&(T.tools=v.tools),v.fields&&Object.keys(v.fields).length&&(T.fields=v.fields);h.folder==="commands"&&(T.fields||(T.fields={}),T.fields["user-invocable"]="true"),E.push({importPath:O,resourceType:h.resourceType,title:k,description:D,body:I,bodyHash:Ue(b),metadata:T})}}return{resources:E,memberships:f}}let c=l(r,"");t.push(...c.resources),n.push(...c.memberships);let u=new Set;e?.mcpConfigPath&&u.add(e.mcpConfigPath);let a=(0,Y.join)(r,".mcp.json");(0,B.existsSync)(a)&&u.add(a);for(let d of u)if((0,B.existsSync)(d))try{let m=JSON.parse((0,B.readFileSync)(d,"utf-8"));if(m.mcpServers&&typeof m.mcpServers=="object")for(let[E,f]of Object.entries(m.mcpServers)){let h=`mcps/${E}`;if(t.some(y=>y.importPath===h))continue;let C=Oe(E),i=JSON.stringify({name:C,description:`MCP server: ${E}`,mcpServers:{[E]:f}},null,2);t.push({importPath:h,resourceType:"mcp",title:C,description:`MCP server: ${E}`,body:i,bodyHash:Ue(i),metadata:{}})}}catch{}if(e?.settingsPath&&(0,B.existsSync)(e.settingsPath))try{let d=JSON.parse((0,B.readFileSync)(e.settingsPath,"utf-8"));if(d.hooks&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)){let m={};for(let[E,f]of Object.entries(d.hooks))if(Array.isArray(f))for(let h of f){if(!h||typeof h!="object")continue;let C=h,i=C._sc;if(!i)continue;m[i]||(m[i]={}),m[i][E]||(m[i][E]=[]);let{_sc:y,...g}=C;m[i][E].push(g)}for(let[E,f]of Object.entries(m)){let h=E;if(t.some(g=>g.importPath===h))continue;let C=E.split("/").pop()||E,i=Oe(C),y=JSON.stringify({name:i,description:`Hook: ${i}`,hooks:f},null,2);t.push({importPath:h,resourceType:"hook",title:i,description:`Hook: ${i}`,body:y,bodyHash:Ue(y),metadata:{}})}}}catch{}for(let d of Hr){if(d.path===Ms)continue;let m=(0,Y.join)(r,d.path);if((0,B.existsSync)(m)){try{let E=JSON.parse((0,B.readFileSync)(m,"utf-8"));if(s=s||E.name||void 0,o=d.formatLabel,!t.some(f=>f.resourceType==="collection")){let f=t.filter(g=>g.resourceType!=="collection").map(g=>({resourceRef:g.importPath})),h=d.converter(E,f),C=(0,Y.join)(r,"README.md"),i=(0,B.existsSync)(C)?(0,B.readFileSync)(C,"utf-8"):"",y="collections/_root";t.push({importPath:y,resourceType:"collection",title:Oe(h.name),description:h.description||null,body:i,bodyHash:Ue(i),metadata:{},manifestMetadata:{...h.author?{author:h.author}:{},...h.homepage?{homepage:h.homepage}:{},...h.license?{license:h.license}:{}}}),h.resources.length>0&&n.push({collectionImportPath:y,memberImportPaths:h.resources})}}catch{}break}}{let f=function(h,C,i){if(!(i>4))for(let y of Us(h)){if(E.has(y))continue;let g=(0,Y.join)(h,y),A=C?`${C}/${y}`:y;for(let b of Hr){if(b.path===Ms)continue;let O=(0,Y.join)(g,b.path);if((0,B.existsSync)(O)){if(d.has(A))break;d.add(A);try{let k=JSON.parse((0,B.readFileSync)(O,"utf-8")),D=l(g,A);if(D.resources.length===0)break;t.push(...D.resources),n.push(...D.memberships);let I=D.resources.filter(q=>q.resourceType!=="collection").map(q=>({resourceRef:q.importPath})),T=b.converter(k,I),v=(0,Y.join)(g,"README.md"),N=(0,B.existsSync)(v)?(0,B.readFileSync)(v,"utf-8"):"",L=`${A}/_collection`;t.push({importPath:L,resourceType:"collection",title:Oe(T.name),description:T.description||null,body:N,bodyHash:Ue(N),metadata:{},manifestMetadata:{...T.author?{author:T.author}:{},...T.homepage?{homepage:T.homepage}:{},...T.license?{license:T.license}:{}}}),n.push({collectionImportPath:L,memberImportPaths:D.resources.map(q=>q.importPath)}),s||(s=k.name||void 0),o||(o=b.formatLabel)}catch{}break}}f(g,A,i+1)}};var x=f;let d=new Set,m=new Set($s.map(h=>h.folder)),E=new Set([...m,"worktrees","plugins","node_modules","todos"]);f(r,"",0)}let p=(0,Y.join)(r,"files");if((0,B.existsSync)(p)&&Ct(p)&&!t.some(d=>d.resourceType==="file"))for(let d of Br(p)){if(!d.endsWith(".md"))continue;let m=(0,Y.join)(p,d),E=(0,B.readFileSync)(m,"utf-8"),f=at(E),h=f.name||(0,Y.basename)(d,".md"),C=`files/${(0,Y.basename)(d,".md")}`;t.some(i=>i.importPath===C)||t.push({importPath:C,resourceType:"file",title:h,description:f.description||null,body:f.body,bodyHash:Ue(E),metadata:{}})}return{resources:[...t.filter(d=>d.resourceType!=="collection"),...t.filter(d=>d.resourceType==="collection")],collectionMemberships:n,pluginName:s,formatLabel:o}}var zs=require("readline");function ga(){if(process.platform==="darwin")try{let{execSync:r}=require("child_process"),e=r("scutil --get ComputerName",{encoding:"utf-8"}).trim();if(e)return e}catch{}return require("os").hostname()}var Be="context-manager",Gs="Context Manager",Zt="collections/shared-context/context-manager";function ya(r,e){let t=re(r,e),n=(0,Ye.join)(t,Be);return(0,Jt.mkdirSync)(n,{recursive:!0}),(0,Jt.writeFileSync)((0,Ye.join)(n,`${Be}.md`),Ls,"utf-8"),(0,Ye.join)(n,`${Be}.md`)}var Sa={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Ea(r){return G().installations.some(t=>t.installPath===Zt&&t.agent===r)}function Zs(r){r.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").option("--link-project <id>","Link to a Shared Context project by ID").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()};if(n.code){let{post:f}=await Promise.resolve().then(()=>(se(),Gn)),{saveAuth:h}=await Promise.resolve().then(()=>(fe(),vt)),C=await f("/api/cli/auth",{code:n.code});C.ok?(h({token:C.data.token,email:C.data.user.email,orgId:C.data.org.id,orgSlug:C.data.org.slug,orgName:C.data.org.name,createdAt:new Date().toISOString()}),_()||w(`Authenticated as ${C.data.user.email}`)):M()?_()||w("Auth code already used, continuing with saved credentials."):(_()?j("init",C.error.code,C.error.message):R(`Auth failed: ${C.error.message}`),process.exit(1))}else M()||(_()?(j("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(R("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let s;if(n.agent){let f=ke(n.agent);if(!f){let h=`Unknown agent: ${n.agent}. Available: ${Le().map(C=>C.id).join(", ")||"none detected"}`;_()?j("init","NO_AGENTS",h):R(h),process.exit(1)}s=[f]}else if(s=Le(),s.length===0){let f=Fe();_()?j("init","NO_AGENTS",f):R(f),process.exit(1)}let o=Ae(),l=ga(),c;if(n.linkProject){if(!o?.token){let O="Authentication required for project linking. Run init with --code first.";_()?j("init","AUTH_REQUIRED",O):R(O),process.exit(1)}let f=s[0],h=await $("/api/cli/register-agent",{platform:f.platform,name:`CLI (${l})`});h.ok&&(c=h.data.connectionId);let C=await $(`/api/cli/projects/${n.linkProject}/join`,{localPath:process.cwd()});C.ok||(_()?j("init",C.error.code,C.error.message):R(`Failed to join project: ${C.error.message}`),process.exit(1));let{project:i,resources:y,members:g}=C.data;Et({projectId:i.id,projectName:i.name,projectSlug:i.slug});let A=Te(f),b=[];for(let O of y)try{let k=O.installPath,D=await z(`/api/cli/resource/${k}`);if(!D.ok)continue;let I=D.data;await A.install(I,"project",f),ue({resourceId:O.id,slug:O.slug||O.id,installPath:k,title:O.title,sha:O.latestSha||"",scope:"project",agent:f.id,installedAt:new Date().toISOString(),projectId:i.id}),O.latestSha&&await $("/api/cli/install",{resourceId:O.id,agentPlatform:f.platform,installedSha:O.latestSha}).catch(()=>{}),b.push({title:O.title,resourceType:O.resourceType})}catch{}if(await $(`/api/cli/projects/${i.id}/sync`,{localPath:process.cwd()}).catch(()=>{}),kt({lastSyncAt:new Date().toISOString()}),_())F("init",{project:{id:i.id,name:i.name,slug:i.slug},agent:f.id,resourcesInstalled:b.length,memberCount:g.length});else{if(w(""),w(`Joined project: ${i.name}`),i.description&&w(`"${i.description}"`),w(""),b.length>0){w(`Installed ${b.length} resource${b.length===1?"":"s"}:`);let O={};for(let D of b)O[D.resourceType]||(O[D.resourceType]=[]),O[D.resourceType].push(D.title);let k={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};for(let[D,I]of Object.entries(O))w(` ${k[D]||D}: ${I.join(", ")}`)}else w("No resources to install (project is empty)");g.length>0&&(w(""),w(`Team (${g.length}): ${g.map(O=>O.name).join(", ")}`)),w(""),w("Quick reference:"),w(" shared-context-ai status View project sync status"),w(" shared-context-ai sync Check for resource updates")}return}let u=!1,a=(0,Ye.basename)(process.cwd());if(o?.token&&!ve()&&a&&a!=="/")try{let f=await $("/api/cli/projects",{name:a});if(f.ok){let{id:h,name:C,slug:i}=f.data;Et({projectId:h,projectName:C,projectSlug:i}),u=!0,_()||w(`Created project: ${C}`)}}catch{}let p=[],S={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};for(let f of s){let h=!1,C=!1,i=[],y=[];if(o?.token){let g=await $("/api/cli/register-agent",{platform:f.platform,name:`CLI (${l})`});if(g.ok){if(!c){c=g.data.connectionId;let{saveAuth:A}=await Promise.resolve().then(()=>(fe(),vt));A({...o,connectionId:c})}}else _()||R(`Warning: Could not register ${f.label} connection: ${g.error.message}`)}if(o?.token&&Ea(f.id))C=!0,h=!0;else if(o?.token)try{let g=await z(`/api/cli/resource/${Zt}`);if(g.ok){let A=g.data,O=await Te(f).install(A,n.project?"project":"user",f);if(ue({resourceId:A.resource.id,slug:A.resource.slug||"context-manager",installPath:Zt,title:A.resource.title,sha:A.resource.latestSha||"",scope:n.project?"project":"global",agent:f.id,installedAt:new Date().toISOString(),pluginFormat:S[f.id]||"directory",memberCount:A.memberResources?.length}),A.resource.latestSha&&await $("/api/cli/install",{resourceId:A.resource.id,agentPlatform:f.platform,installedSha:A.resource.latestSha}).catch(()=>{}),A.memberResources)for(let k of A.memberResources){let D=k.slug||k.id,I=Sa[k.resourceType]||k.resourceType+"s",T=k.orgSlug||A.resource.orgSlug,v=T?`${I}/${T}/${D}`:`${I}/${D}`;ue({resourceId:k.id,slug:D,installPath:v,title:k.title,sha:k.latestSha||"",scope:n.project?"project":"global",agent:f.id,installedAt:new Date().toISOString(),collectionId:A.resource.id}),i.push({title:k.title,resourceType:k.resourceType}),k.latestSha&&await $("/api/cli/install",{resourceId:k.id,agentPlatform:f.platform,installedSha:k.latestSha}).catch(()=>{})}if(h=!0,!_()&&O.warnings.length>0)for(let k of O.warnings)R(`Warning: ${k}`)}}catch{}if(!h&&(ya(f,!!n.project),ue({resourceId:"context-manager",slug:Be,installPath:`agents/${Be}`,title:Gs,sha:"",scope:n.project?"project":"global",agent:f.id,installedAt:new Date().toISOString()}),o?.token))try{let g=`agents/shared-context/${Be}`,A=await z(`/api/cli/resource/${g}`);if(A.ok&&A.data.resource){let b=A.data.resource;b.latestSha&&await $("/api/cli/install",{resourceId:b.id,agentPlatform:f.platform,installedSha:b.latestSha}),ue({resourceId:b.id,slug:b.slug||Be,installPath:`agents/shared-context/${b.slug||Be}`,title:b.title||Gs,sha:b.latestSha||"",scope:n.project?"project":"global",agent:f.id,installedAt:new Date().toISOString()})}}catch{}if(o?.token)try{let g=(0,Ye.join)((0,qs.homedir)(),f.dir),A=ct(g,{settingsPath:ye(f,!!n.project),mcpConfigPath:oe(f,!!n.project)}),b=G(),O=new Set(b.installations.map(T=>T.installPath)),k=new Map;for(let T of b.installations){let v=T.installPath.split("/"),N=v[0],L=v[v.length-1];k.has(N)||k.set(N,new Set),k.get(N).add(L)}let D=new Set(["context-manager",".claude-plugin"]),I=A.resources.filter(T=>{if(O.has(T.importPath))return!1;let v=T.importPath.split("/"),N=v[0],L=v[v.length-1];return!((N==="mcps"||N==="hooks")&&k.get(N)?.has(L)||T.importPath.startsWith(".")||D.has(L))});if(I.length>0){let T={dryRun:!1,onConflict:"auto",visibility:"org",resources:I,collectionMemberships:A.collectionMemberships},v=await $("/api/cli/import",T,12e4);v.ok&&(y=[...v.data.created,...v.data.updated,...v.data.installed].map(L=>({resourceType:L.resourceType||L.importPath.split("/")[0]?.replace(/s$/,"")||"unknown",slug:L.slug||L.importPath.split("/").pop()||"",title:L.importPath.split("/").pop()||""})))}}catch{}p.push({agent:f,collectionInstalled:h,installedMembers:i,importedResources:y,skippedEssentials:C})}if(kt({lastSyncAt:new Date().toISOString()}),p.some(f=>!f.skippedEssentials)&&!_()&&process.stdin.isTTY){let{getConfig:f,updateConfig:h}=await Promise.resolve().then(()=>(fe(),vt));if(f().telemetry===void 0)try{if(await new Promise(y=>{let g=(0,zs.createInterface)({input:process.stdin,output:process.stdout});g.question(`
142
+ `),p=null,S=!1;for(let I=0;I<a.length;I++){let d=a[I];if(p&&/^\s+-\s/.test(d)){let h=d.replace(/^\s+-\s/,"").trim();if(h){let C=dt(h);S?u[p].push(C):l[p].push(C)}continue}p=null,S=!1;let m=d.indexOf(":");if(m===-1)continue;let E=d.slice(0,m).trim(),f=d.slice(m+1).trim();if(!f&&E&&I+1<a.length&&/^\s+-\s/.test(a[I+1])){p=E,c.has(E)?(S=!0,u[E]=[]):(S=!1,l[E]=[]);continue}E==="name"||E==="title"?e.name=dt(f):E==="description"?e.description=dt(f):E==="skill_class"?e.skillClass=dt(f):E==="service"?e.service=dt(f):E&&f&&(o[E]=dt(f))}return u.requires?.length&&(e.requires=u.requires),u.tools?.length&&(e.tools=u.tools),Object.keys(o).length&&(e.fields=o),Object.keys(l).length&&(e.arrayFields=l),e}function dt(r){let e=r.trim();if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")){let t=e.slice(1,-1);return e.startsWith('"')?t.replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t.replace(/''/g,"'")}return e}function ga(r){let{body:e}=rt(r);return e.replace(/\r\n/g,`
143
+ `).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function $e(r){let e=ga(r);return`sha256:${(0,Ws.createHash)("sha256").update(e,"utf8").digest("hex")}`}function Oe(r){return r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function _t(r){try{return(0,B.statSync)(r).isDirectory()}catch{return!1}}function Gr(r){try{return(0,B.readdirSync)(r).filter(e=>!e.startsWith(".")&&_t((0,J.join)(r,e)))}catch{return[]}}function zr(r){try{return(0,B.readdirSync)(r).filter(e=>!e.startsWith(".")&&!_t((0,J.join)(r,e)))}catch{return[]}}function pt(r,e){let t=[],n=[],s,o;function l(d,m){let E=[],f=[];for(let h of Hs){let C=(0,J.join)(d,h.folder);if(!(0,B.existsSync)(C)||!_t(C))continue;let i=m?`${m}/${h.folder}`:h.folder;if(h.folder==="files"){for(let g of zr(C)){if(!g.endsWith(".md"))continue;let y=(0,J.join)(C,g),b=(0,B.readFileSync)(y,"utf-8"),_=rt(b),O=_.name||(0,J.basename)(g,".md"),k=`${i}/${(0,J.basename)(g,".md")}`;E.push({importPath:k,resourceType:"file",title:O,description:_.description||null,body:_.body,bodyHash:$e(b),metadata:{}})}continue}if(h.mainFile===null)for(let g of zr(C)){if(!g.endsWith(".md"))continue;let y=(0,J.basename)(g,".md"),b=`${i}/${y}`;if(_t((0,J.join)(C,y)))continue;let _=(0,B.readFileSync)((0,J.join)(C,g),"utf-8"),O=rt(_),k=O.name||Oe(y),D={};O.skillClass&&(D.skillClass=O.skillClass),O.service&&(D.service=O.service),O.requires?.length&&(D.requires=O.requires),O.tools?.length&&(D.tools=O.tools),O.fields&&Object.keys(O.fields).length&&(D.fields=O.fields),h.folder==="commands"&&(D.fields||(D.fields={}),D.fields["user-invocable"]="true"),E.push({importPath:b,resourceType:h.resourceType,title:k,description:O.description||null,body:O.body,bodyHash:$e(_),metadata:D})}for(let g of Gr(C)){let y=h.mainFile||`${g}.md`,b=(0,J.join)(C,g,y);if(!(0,B.existsSync)(b)){if(h.mainFile===null)for(let N of Gr((0,J.join)(C,g))){let j=`${N}.md`,M=(0,J.join)(C,g,N,j);if(!(0,B.existsSync)(M))continue;let ne=(0,B.readFileSync)(M,"utf-8"),W=rt(ne),Ae=W.name||Oe(N),ue={};W.skillClass&&(ue.skillClass=W.skillClass),W.service&&(ue.service=W.service),W.requires?.length&&(ue.requires=W.requires),W.tools?.length&&(ue.tools=W.tools),W.fields&&Object.keys(W.fields).length&&(ue.fields=W.fields),E.push({importPath:`${i}/${N}`,resourceType:h.resourceType,title:Ae,description:W.description||null,body:W.body,bodyHash:$e(ne),metadata:ue})}continue}let _=(0,B.readFileSync)(b,"utf-8"),O=`${i}/${g}`,k,D,x,T={},v=null;if(h.resourceType==="hook"||h.resourceType==="mcp"){try{let N=JSON.parse(_);k=N.name||Oe(g),D=N.description||null}catch{k=Oe(g),D=null}x=_}else if(h.resourceType==="collection"){let N=(0,J.join)(C,g,Jt,Kt);if((0,B.existsSync)(N))try{let j=JSON.parse((0,B.readFileSync)(N,"utf-8"));k=j.name||Oe(g),D=j.description||null,x=_,j.resources&&Array.isArray(j.resources)&&f.push({collectionImportPath:O,memberImportPaths:j.resources.map(M=>{let ne=M.split("/");return ne.length>=3?`${ne[0]}/${ne[ne.length-1]}`:M})})}catch{k=Oe(g),D=null,x=_}else v=rt(_),k=v.name||Oe(g),D=v.description||null,x=v.body,v.arrayFields?.resources&&f.push({collectionImportPath:O,memberImportPaths:v.arrayFields.resources.map(j=>{let M=j.split("/");return M.length>=3?`${M[0]}/${M[M.length-1]}`:j})})}else v=rt(_),k=v.name||Oe(g),D=v.description||null,x=v.body,v.skillClass&&(T.skillClass=v.skillClass),v.service&&(T.service=v.service),v.requires?.length&&(T.requires=v.requires),v.tools?.length&&(T.tools=v.tools),v.fields&&Object.keys(v.fields).length&&(T.fields=v.fields);h.folder==="commands"&&(T.fields||(T.fields={}),T.fields["user-invocable"]="true"),E.push({importPath:O,resourceType:h.resourceType,title:k,description:D,body:x,bodyHash:$e(_),metadata:T})}}return{resources:E,memberships:f}}let c=l(r,"");t.push(...c.resources),n.push(...c.memberships);let u=new Set;e?.mcpConfigPath&&u.add(e.mcpConfigPath);let a=(0,J.join)(r,".mcp.json");(0,B.existsSync)(a)&&u.add(a);for(let d of u)if((0,B.existsSync)(d))try{let m=JSON.parse((0,B.readFileSync)(d,"utf-8"));if(m.mcpServers&&typeof m.mcpServers=="object")for(let[E,f]of Object.entries(m.mcpServers)){let h=`mcps/${E}`;if(t.some(g=>g.importPath===h))continue;let C=Oe(E),i=JSON.stringify({name:C,description:`MCP server: ${E}`,mcpServers:{[E]:f}},null,2);t.push({importPath:h,resourceType:"mcp",title:C,description:`MCP server: ${E}`,body:i,bodyHash:$e(i),metadata:{}})}}catch{}if(e?.settingsPath&&(0,B.existsSync)(e.settingsPath))try{let d=JSON.parse((0,B.readFileSync)(e.settingsPath,"utf-8"));if(d.hooks&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)){let m={};for(let[E,f]of Object.entries(d.hooks))if(Array.isArray(f))for(let h of f){if(!h||typeof h!="object")continue;let C=h,i=C._sc;if(!i)continue;m[i]||(m[i]={}),m[i][E]||(m[i][E]=[]);let{_sc:g,...y}=C;m[i][E].push(y)}for(let[E,f]of Object.entries(m)){let h=E;if(t.some(y=>y.importPath===h))continue;let C=E.split("/").pop()||E,i=Oe(C),g=JSON.stringify({name:i,description:`Hook: ${i}`,hooks:f},null,2);t.push({importPath:h,resourceType:"hook",title:i,description:`Hook: ${i}`,body:g,bodyHash:$e(g),metadata:{}})}}}catch{}for(let d of qr){if(d.path===Bs)continue;let m=(0,J.join)(r,d.path);if((0,B.existsSync)(m)){try{let E=JSON.parse((0,B.readFileSync)(m,"utf-8"));if(s=s||E.name||void 0,o=d.formatLabel,!t.some(f=>f.resourceType==="collection")){let f=t.filter(y=>y.resourceType!=="collection").map(y=>({resourceRef:y.importPath})),h=d.converter(E,f),C=(0,J.join)(r,"README.md"),i=(0,B.existsSync)(C)?(0,B.readFileSync)(C,"utf-8"):"",g="collections/_root";t.push({importPath:g,resourceType:"collection",title:Oe(h.name),description:h.description||null,body:i,bodyHash:$e(i),metadata:{},manifestMetadata:{...h.author?{author:h.author}:{},...h.homepage?{homepage:h.homepage}:{},...h.license?{license:h.license}:{}}}),h.resources.length>0&&n.push({collectionImportPath:g,memberImportPaths:h.resources})}}catch{}break}}{let f=function(h,C,i){if(!(i>4))for(let g of Gr(h)){if(E.has(g))continue;let y=(0,J.join)(h,g),b=C?`${C}/${g}`:g;for(let _ of qr){if(_.path===Bs)continue;let O=(0,J.join)(y,_.path);if((0,B.existsSync)(O)){if(d.has(b))break;d.add(b);try{let k=JSON.parse((0,B.readFileSync)(O,"utf-8")),D=l(y,b);if(D.resources.length===0)break;t.push(...D.resources),n.push(...D.memberships);let x=D.resources.filter(M=>M.resourceType!=="collection").map(M=>({resourceRef:M.importPath})),T=_.converter(k,x),v=(0,J.join)(y,"README.md"),N=(0,B.existsSync)(v)?(0,B.readFileSync)(v,"utf-8"):"",j=`${b}/_collection`;t.push({importPath:j,resourceType:"collection",title:Oe(T.name),description:T.description||null,body:N,bodyHash:$e(N),metadata:{},manifestMetadata:{...T.author?{author:T.author}:{},...T.homepage?{homepage:T.homepage}:{},...T.license?{license:T.license}:{}}}),n.push({collectionImportPath:j,memberImportPaths:D.resources.map(M=>M.importPath)}),s||(s=k.name||void 0),o||(o=_.formatLabel)}catch{}break}}f(y,b,i+1)}};var I=f;let d=new Set,m=new Set(Hs.map(h=>h.folder)),E=new Set([...m,"worktrees","plugins","node_modules","todos"]);f(r,"",0)}let p=(0,J.join)(r,"files");if((0,B.existsSync)(p)&&_t(p)&&!t.some(d=>d.resourceType==="file"))for(let d of zr(p)){if(!d.endsWith(".md"))continue;let m=(0,J.join)(p,d),E=(0,B.readFileSync)(m,"utf-8"),f=rt(E),h=f.name||(0,J.basename)(d,".md"),C=`files/${(0,J.basename)(d,".md")}`;t.some(i=>i.importPath===C)||t.push({importPath:C,resourceType:"file",title:h,description:f.description||null,body:f.body,bodyHash:$e(E),metadata:{}})}return{resources:[...t.filter(d=>d.resourceType!=="collection"),...t.filter(d=>d.resourceType==="collection")],collectionMemberships:n,pluginName:s,formatLabel:o}}var Js=require("readline");function Sa(){if(process.platform==="darwin")try{let{execSync:r}=require("child_process"),e=r("scutil --get ComputerName",{encoding:"utf-8"}).trim();if(e)return e}catch{}return require("os").hostname()}var Ge="context-manager",zs="Context Manager",Xt="collections/shared-context/context-manager";function Ea(r,e){let t=re(r,e),n=(0,nt.join)(t,Ge);return(0,Yt.mkdirSync)(n,{recursive:!0}),(0,Yt.writeFileSync)((0,nt.join)(n,`${Ge}.md`),Ms,"utf-8"),(0,nt.join)(n,`${Ge}.md`)}var Ca={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function wa(r){return z().installations.some(t=>t.installPath===Xt&&t.agent===r)}function Ks(r){r.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").option("--link-project <id>","Link to a Shared Context project by ID").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()};if(n.code){let{post:f}=await Promise.resolve().then(()=>(ie(),Zn)),{saveAuth:h}=await Promise.resolve().then(()=>(me(),Pt)),C=await f("/api/cli/auth",{code:n.code});C.ok?(h({token:C.data.token,email:C.data.user.email,orgId:C.data.org.id,orgSlug:C.data.org.slug,orgName:C.data.org.name,createdAt:new Date().toISOString()}),A()||w(`Authenticated as ${C.data.user.email}`)):U()?A()||w("Auth code already used, continuing with saved credentials."):(A()?$("init",C.error.code,C.error.message):R(`Auth failed: ${C.error.message}`),process.exit(1))}else U()||(A()?($("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(R("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let s;if(n.agent){let f=Pe(n.agent);if(!f){let h=`Unknown agent: ${n.agent}. Available: ${He().map(C=>C.id).join(", ")||"none detected"}`;A()?$("init","NO_AGENTS",h):R(h),process.exit(1)}s=[f]}else if(s=He(),s.length===0){let f=Be();A()?$("init","NO_AGENTS",f):R(f),process.exit(1)}let o=Ie(),l=Sa(),c;if(n.linkProject){if(!o?.token){let O="Authentication required for project linking. Run init with --code first.";A()?$("init","AUTH_REQUIRED",O):R(O),process.exit(1)}let f=s[0],h=await L("/api/cli/register-agent",{platform:f.platform,name:`CLI (${l})`});h.ok&&(c=h.data.connectionId);let C=await L(`/api/cli/projects/${n.linkProject}/join`,{localPath:process.cwd()});C.ok||(A()?$("init",C.error.code,C.error.message):R(`Failed to join project: ${C.error.message}`),process.exit(1));let{project:i,resources:g,members:y}=C.data;Qe({projectId:i.id,projectName:i.name,projectSlug:i.slug});let b=De(f),_=[];for(let O of g)try{let k=O.installPath,D=await Z(`/api/cli/resource/${k}`);if(!D.ok)continue;let x=D.data;await b.install(x,"project",f),pe({resourceId:O.id,slug:O.slug||O.id,installPath:k,title:O.title,sha:O.latestSha||"",scope:"project",agent:f.id,installedAt:new Date().toISOString(),projectId:i.id}),O.latestSha&&await L("/api/cli/install",{resourceId:O.id,agentPlatform:f.platform,installedSha:O.latestSha}).catch(()=>{}),_.push({title:O.title,resourceType:O.resourceType})}catch{}if(await L(`/api/cli/projects/${i.id}/sync`,{localPath:process.cwd()}).catch(()=>{}),Rt({lastSyncAt:new Date().toISOString()}),A())F("init",{project:{id:i.id,name:i.name,slug:i.slug},agent:f.id,resourcesInstalled:_.length,memberCount:y.length});else{if(w(""),w(`Joined project: ${i.name}`),i.description&&w(`"${i.description}"`),w(""),_.length>0){w(`Installed ${_.length} resource${_.length===1?"":"s"}:`);let O={};for(let D of _)O[D.resourceType]||(O[D.resourceType]=[]),O[D.resourceType].push(D.title);let k={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};for(let[D,x]of Object.entries(O))w(` ${k[D]||D}: ${x.join(", ")}`)}else w("No resources to install (project is empty)");y.length>0&&(w(""),w(`Team (${y.length}): ${y.map(O=>O.name).join(", ")}`)),w(""),w("Quick reference:"),w(" shared-context-ai status View project sync status"),w(" shared-context-ai sync Check for resource updates")}return}let u=!1,a=(0,nt.basename)(process.cwd());if(o?.token&&!ke()&&a&&a!=="/")try{let f=await L("/api/cli/projects",{name:a});if(f.ok){let{id:h,name:C,slug:i}=f.data;Qe({projectId:h,projectName:C,projectSlug:i}),u=!0,A()||w(`Created project: ${C}`)}}catch{}let p=[],S={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};for(let f of s){let h=!1,C=!1,i=[],g=[];if(o?.token){let y=await L("/api/cli/register-agent",{platform:f.platform,name:`CLI (${l})`});if(y.ok){if(!c){c=y.data.connectionId;let{saveAuth:b}=await Promise.resolve().then(()=>(me(),Pt));b({...o,connectionId:c})}}else A()||R(`Warning: Could not register ${f.label} connection: ${y.error.message}`)}if(o?.token&&wa(f.id))C=!0,h=!0;else if(o?.token)try{let y=await Z(`/api/cli/resource/${Xt}`);if(y.ok){let b=y.data,O=await De(f).install(b,n.project?"project":"user",f);if(pe({resourceId:b.resource.id,slug:b.resource.slug||"context-manager",installPath:Xt,title:b.resource.title,sha:b.resource.latestSha||"",scope:n.project?"project":"global",agent:f.id,installedAt:new Date().toISOString(),pluginFormat:S[f.id]||"directory",memberCount:b.memberResources?.length}),b.resource.latestSha&&await L("/api/cli/install",{resourceId:b.resource.id,agentPlatform:f.platform,installedSha:b.resource.latestSha}).catch(()=>{}),b.memberResources)for(let k of b.memberResources){let D=k.slug||k.id,x=Ca[k.resourceType]||k.resourceType+"s",T=k.orgSlug||b.resource.orgSlug,v=T?`${x}/${T}/${D}`:`${x}/${D}`;pe({resourceId:k.id,slug:D,installPath:v,title:k.title,sha:k.latestSha||"",scope:n.project?"project":"global",agent:f.id,installedAt:new Date().toISOString(),collectionId:b.resource.id}),i.push({title:k.title,resourceType:k.resourceType}),k.latestSha&&await L("/api/cli/install",{resourceId:k.id,agentPlatform:f.platform,installedSha:k.latestSha}).catch(()=>{})}if(h=!0,!A()&&O.warnings.length>0)for(let k of O.warnings)R(`Warning: ${k}`)}}catch{}if(!h&&(Ea(f,!!n.project),pe({resourceId:"context-manager",slug:Ge,installPath:`agents/${Ge}`,title:zs,sha:"",scope:n.project?"project":"global",agent:f.id,installedAt:new Date().toISOString()}),o?.token))try{let y=`agents/shared-context/${Ge}`,b=await Z(`/api/cli/resource/${y}`);if(b.ok&&b.data.resource){let _=b.data.resource;_.latestSha&&await L("/api/cli/install",{resourceId:_.id,agentPlatform:f.platform,installedSha:_.latestSha}),pe({resourceId:_.id,slug:_.slug||Ge,installPath:`agents/shared-context/${_.slug||Ge}`,title:_.title||zs,sha:_.latestSha||"",scope:n.project?"project":"global",agent:f.id,installedAt:new Date().toISOString()})}}catch{}if(o?.token)try{let y=(0,nt.join)((0,Zs.homedir)(),f.dir),b=pt(y,{settingsPath:Ee(f,!!n.project),mcpConfigPath:ae(f,!!n.project)}),_=z(),O=new Set(_.installations.map(T=>T.installPath)),k=new Map;for(let T of _.installations){let v=T.installPath.split("/"),N=v[0],j=v[v.length-1];k.has(N)||k.set(N,new Set),k.get(N).add(j)}let D=new Set(["context-manager",".claude-plugin"]),x=b.resources.filter(T=>{if(O.has(T.importPath))return!1;let v=T.importPath.split("/"),N=v[0],j=v[v.length-1];return!((N==="mcps"||N==="hooks")&&k.get(N)?.has(j)||T.importPath.startsWith(".")||D.has(j))});if(x.length>0){let T={dryRun:!1,onConflict:"auto",visibility:"org",resources:x,collectionMemberships:b.collectionMemberships},v=await L("/api/cli/import",T,12e4);v.ok&&(g=[...v.data.created,...v.data.updated,...v.data.installed].map(j=>({resourceType:j.resourceType||j.importPath.split("/")[0]?.replace(/s$/,"")||"unknown",slug:j.slug||j.importPath.split("/").pop()||"",title:j.importPath.split("/").pop()||""})))}}catch{}p.push({agent:f,collectionInstalled:h,installedMembers:i,importedResources:g,skippedEssentials:C})}if(Rt({lastSyncAt:new Date().toISOString()}),p.some(f=>!f.skippedEssentials)&&!A()&&process.stdin.isTTY){let{getConfig:f,updateConfig:h}=await Promise.resolve().then(()=>(me(),Pt));if(f().telemetry===void 0)try{if(await new Promise(g=>{let y=(0,Js.createInterface)({input:process.stdin,output:process.stdout});y.question(`
144
144
  Help improve Shared Context skills? We collect anonymous usage data
145
145
  (which skills you use, never conversation content). Change anytime with
146
- \`shared-context-ai config set telemetry off\`. [y/N] `,A=>{g.close(),y(A.trim().toLowerCase()==="y"||A.trim().toLowerCase()==="yes")})})){h({telemetry:!0});let{enableTelemetryHook:y}=await Promise.resolve().then(()=>(Gr(),Vs));y(),w("Telemetry enabled.")}else h({telemetry:!1}),w("Telemetry disabled.")}catch{}}if(c){let f=p.reduce((h,C)=>h+C.importedResources.length,0);$("/api/cli/sync-report",{connectionId:c,lastSyncResult:{updatesAvailable:0,importedCount:f}}).catch(()=>{})}let d=p.every(f=>f.skippedEssentials),m=p.some(f=>!f.skippedEssentials),E=p.some(f=>f.importedResources.length>0);if(_()){let f=h=>({agent:h.agent.id,collection:h.collectionInstalled?Zt:void 0,contextManagerOnly:!h.collectionInstalled,skipped:h.skippedEssentials,...h.collectionInstalled&&!h.skippedEssentials?{membersInstalled:h.installedMembers.map(C=>({title:C.title,resourceType:C.resourceType}))}:{},...h.importedResources.length>0?{importedResources:h.importedResources.map(C=>({resourceType:C.resourceType,slug:C.slug,title:C.title}))}:{}});F("init",{...f(p[0]),agents:p.map(f),...u?{projectCreated:!0}:{},authenticated:M()})}else{for(let f of p)if(!f.skippedEssentials){if(w(""),f.collectionInstalled){w(`Context Manager installed for ${f.agent.label} (${f.installedMembers.length} resources)`);let h={};for(let i of f.installedMembers)h[i.resourceType]||(h[i.resourceType]=[]),h[i.resourceType].push(i.title);let C={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};w("");for(let[i,y]of Object.entries(h)){let g=C[i]||i;w(` ${g}: ${y.join(", ")}`)}}else w(`Context Manager installed for ${f.agent.label} (offline)`),w("Context Manager agent written locally");if(f.importedResources.length>0){w(""),w(`Imported ${f.importedResources.length} existing resource${f.importedResources.length===1?"":"s"}:`);for(let h of f.importedResources)w(` ${h.resourceType.padEnd(12)} ${h.slug.padEnd(24)} ${h.title}`)}}d&&!u&&!E&&(w(""),w("Already initialized. Nothing to do.")),(m||u||E)&&(w(""),w("Quick reference:"),w(' shared-context-ai search "query" Search for resources'),w(" shared-context-ai install <installPath> Install a resource"),w(" shared-context-ai list List installed resources"),w(" shared-context-ai sync Check updates & discover resources"),w(" shared-context-ai preview <installPath> Preview before installing"))}})}var xo=require("http"),Io=require("crypto");fe();se();fe();te();async function Oo(r){let e=await $("/api/cli/auth",{code:r});return e.ok?(Ir({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()}),_()?F("login",{email:e.data.user.email,org:e.data.org.slug}):w(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(_()?j("login",e.error.code,e.error.message):R(`Login failed: ${e.error.message}`),!1)}async function La(){let r=(0,Io.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,xo.createServer)((n,s)=>{let o=new URL(n.url||"/","http://localhost"),l=o.searchParams.get("code"),c=o.searchParams.get("state");if(!l||c!==r){s.writeHead(400,{"Content-Type":"text/html"}),s.end("<h1>Authentication failed</h1><p>Invalid state. Please try again.</p>"),t.close(),e(!1);return}s.writeHead(200,{"Content-Type":"text/html"}),s.end("<h1>Authentication successful!</h1><p>You can close this tab and return to your terminal.</p>"),t.close(),Oo(l).then(e)});t.listen(0,"127.0.0.1",async()=>{let n=t.address();if(!n||typeof n=="string"){t.close(),e(!1);return}let s=n.port,l=`${be().apiBase||"https://sharedcontext.ai"}/cli/login?port=${s}&state=${r}`;_()||(w("Opening browser for authentication..."),w(`If the browser doesn't open, visit: ${l}`));try{let c=(await Promise.resolve().then(()=>(_o(),bo))).default;await c(l)}catch{_()||w(`Could not open browser. Please visit:
147
- ${l}`)}setTimeout(()=>{t.close(),_()||R("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function ko(r){r.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 Oo(e.code):t=await La(),process.exit(t?0:1)})}se();te();var Fa={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function vo(r){let e=Fa[r.resourceType]||r.resourceType+"s";return r.storageType==="github"&&r.githubOwner?`${e}/external/${r.githubOwner}/${r.slug}`:r.orgSlug?`${e}/${r.orgSlug}/${r.slug}`:`${e}/${r.slug}`}function To(r){r.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, command, hook, collection, agent, mcp, file)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let n=new URLSearchParams({q:e});t.type&&n.set("type",t.type),t.tag&&n.set("tag",t.tag),t.limit&&n.set("limit",t.limit);let s=M()?`/api/cli/search?${n}`:`/api/public/search?${n}`,o=await z(s);o.ok||(_()?j("search",o.error.code,o.error.message):w(`Search failed: ${o.error.message}`),process.exit(1));let l=o.data.results;if(_()){let u=l.map(a=>{let p=vo(a);return{installPath:p,installCommand:`npx shared-context-ai install ${p}`,title:a.title,description:a.description,resourceType:a.resourceType,installCount:a.installCount,topicTags:a.topicTags}});F("search",{results:u,count:u.length});return}if(l.length===0){let u=t.type?`${t.type}s`:"results";w(`No ${u} found.`);return}w(`Found ${l.length} result${l.length===1?"":"s"}:
148
- `);let c=l.map(u=>[vo(u),u.title,`\u2193${u.installCount}`]);w(he(c)),w(`
149
- Install a skill: npx shared-context-ai install <installPath>`)})}se();fe();te();function Ro(r){let e=r.slug||r.resourceId;return r.storageType==="github"&&r.githubOwner?`skills/external/${r.githubOwner}/${e}`:r.orgSlug?`skills/${r.orgSlug}/${e}`:`skills/${e}`}function Po(r){r.command("list").description("List installed skills").alias("ls").action(async()=>{if(M()){let e=await z("/api/cli/installed");e.ok||(_()?j("list",e.error.code,e.error.message):w(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(_()){let s=t.map(o=>({...o,installPath:Ro(o)}));F("list",{installations:s,count:s.length});return}if(t.length===0){w("No skills installed."),w("Use 'shared-context-ai search' to find skills to install.");return}w(`${t.length} skill${t.length===1?"":"s"} installed:
150
- `);let n=t.map(s=>[Ro(s),s.title,s.hasUpdate?"(update available)":"(current)"]);w(he(n))}else{let t=G().installations;if(_()){F("list",{installations:t,count:t.length});return}if(t.length===0){w("No skills installed locally.");return}w(`${t.length} skill${t.length===1?"":"s"} installed locally:
151
- `);let n=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);w(he(n)),w(`
152
- Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}se();te();function Do(r){r.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let n=M()?"/api/cli/resource":"/api/public/resource",s=await z(`${n}/${e}/preview`);s.ok||(_()?j("preview",s.error.code,s.error.message):R(`Preview failed: ${s.error.message}`),process.exit(1)),_()?F("preview",s.data):w(s.data.content)})}se();te();function No(r){r.command("check").description("Check for skill updates").action(async()=>{M()||(_()?j("check","AUTH_MISSING","Login required to check for updates."):R("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await z("/api/cli/updates");e.ok||(_()?j("check",e.error.code,e.error.message):R(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:n}=e.data;if(_()){F("check",{updates:t,count:n});return}if(n===0){w("All skills are up to date.");return}w(`${n} update${n===1?"":"s"} available:
153
- `);let s=t.map(o=>{let l=o.slug||o.resourceId;return[o.storageType==="github"&&o.githubOwner?`skills/external/${o.githubOwner}/${l}`:o.orgSlug?`skills/${o.orgSlug}/${l}`:`skills/${l}`,o.title,`${o.installedSha.slice(0,7)} \u2192 ${o.latestSha.slice(0,7)}`]});w(he(s)),w(`
154
- Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var bt=require("path"),Lo=require("child_process");se();fe();te();var Fo={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function jo(r){let e=r.slug||r.resourceId;return`${Fo[r.resourceType]||r.resourceType+"s"}/${e}`}function $o(r){r.command("update [path]").description("Update installed resources (all or by install path)").action(async(e,t,n)=>{let s=n.optsWithGlobals();M()||(_()?j("update","AUTH_MISSING","Login required to update resources."):R("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let o=ke(s.agent);if(!o){let a=Fe();_()?j("update","NO_AGENTS",a):R(a),process.exit(1)}let l=await z("/api/cli/updates");l.ok||(_()?j("update",l.error.code,l.error.message):R(`Failed to check updates: ${l.error.message}`),process.exit(1));let c=l.data.updates;if(e&&(c=c.filter(a=>jo(a)===e||a.slug===e||a.resourceId===e),c.length===0)){_()?j("update","SKILL_NOT_FOUND",`No update available for "${e}".`):w(`No update available for "${e}".`);return}if(c.length===0){_()?F("update",{updated:[],count:0}):w("All resources are up to date.");return}let u=[];for(let a of c){let p=jo(a),x=G().installations.find(f=>f.resourceId===a.resourceId&&f.agent===o.id);if(x?.installMode==="plugin"&&a.resourceType==="collection"){try{let f=a.orgSlug||"",h=a.slug||a.resourceId,C=Lt(o.id),i=`/api/cli/resource/collections/${f}/${h}?format=plugin&platform=${C}`,y=await jt(i,h),g=st(o.id);g&&(0,Lo.execSync)(`${g} plugin install "${y}"`,{stdio:"pipe"}),a.latestSha&&await $("/api/cli/update",{resourceId:a.resourceId,installedSha:a.latestSha}),ue({...x,sha:a.latestSha,installedAt:new Date().toISOString()}),u.push({installPath:p,title:a.title}),_()||w(` Updated plugin: ${p}`)}catch(f){_()||R(` Plugin update failed for ${p}: ${f}`)}continue}let d=await z(`/api/cli/resource/${p}`);if(!d.ok){_()||R(` Failed to fetch ${p}: ${d.error.message}`);continue}let m=d.data,E=p.split("/").slice(1);if(m.resource.resourceType==="agent"){let f=re(o,!!s.project),h=(0,bt.join)(f,...E);V(h,m.files)}else if(m.resource.resourceType==="mcp")$t(o,!!s.project,m);else{let f=W(o,!!s.project),h=(0,bt.join)(f,...E);V(h,m.files)}if(m.resource.latestSha&&await $("/api/cli/update",{resourceId:m.resource.id,installedSha:m.resource.latestSha}),ue({...x||{},resourceId:m.resource.id,slug:m.resource.slug||m.resource.id,installPath:p,title:m.resource.title,sha:m.resource.latestSha||"",scope:x?.scope||(s.project?"project":"global"),agent:o.id,installedAt:new Date().toISOString(),latestSha:m.resource.latestSha||void 0,resourceType:m.resource.resourceType,serverSynced:!0}),u.push({installPath:p,title:m.resource.title}),_()||w(` Updated ${p}`),m.resource.resourceType==="collection"&&m.memberResources&&x?.installMode!=="plugin"){let f=G(),h=new Set(f.installations.map(C=>C.resourceId));for(let C of m.memberResources){if(h.has(C.id))continue;let i=C.slug||C.id,g=`${Fo[C.resourceType]||C.resourceType+"s"}/${i}`,A=await z(`/api/cli/resource/${g}`);if(!A.ok){_()||R(` Failed to fetch new member ${g}: ${A.error.message}`);continue}let b=A.data,O=g.split("/").slice(1);if(b.resource.resourceType==="agent"){let k=re(o,!!s.project);V((0,bt.join)(k,...O),b.files)}else if(b.resource.resourceType==="mcp")$t(o,!!s.project,b);else{let k=W(o,!!s.project);V((0,bt.join)(k,...O),b.files)}C.latestSha&&await $("/api/cli/install",{resourceId:C.id,agentPlatform:o.platform,installedSha:C.latestSha}).catch(()=>{}),ue({resourceId:C.id,slug:i,installPath:g,title:C.title,sha:C.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),collectionId:m.resource.id,resourceType:C.resourceType,serverSynced:!0}),_()||w(` + New member: ${g}`)}}}u.length>0&&Ne(),_()?F("update",{updated:u,count:u.length}):u.length>0&&w(`
155
- ${u.length} resource${u.length===1?"":"s"} updated.`)})}var ne=require("fs"),ft=require("path"),Mo=require("child_process");se();fe();te();function Uo(r){r.command("uninstall [path]").description("Uninstall a resource by install path (e.g., skills/acme/api-testing)").action(async(e,t,n)=>{if(!e){let m=G().installations;if(m.length===0&&(_()?j("uninstall","NOTHING_INSTALLED","No resources installed."):w("No resources installed."),process.exit(0)),_())F("uninstall",{installations:m.map(E=>({path:E.installPath||E.slug,title:E.title,agent:E.agent}))});else{w(`Installed resources:
156
- `);let E=m.map(f=>[f.installPath||f.slug,f.title||"",`(${f.agent})`]);w(he(E)),w(`
157
- Usage: shared-context-ai uninstall <path>`)}return}let s=n.optsWithGlobals(),o=ke(s.agent);if(!o){let d=Fe();_()?j("uninstall","NO_AGENTS",d):R(d),process.exit(1)}let c=G().installations.find(d=>d.installPath===e||d.slug===e||d.resourceId===e),u=e.split("/"),p=["skills","files","commands","hooks","collections","agents","mcps"].includes(u[0])?u[0]:null,S=p?u.slice(1):u,x=!1;if(p==="collections")if(c?.installMode==="plugin"){let d=st(o.id);if(d)try{(0,Mo.execSync)(`${d} plugin uninstall "${c.slug}"`,{stdio:"pipe"}),_()||w(`Uninstalled native ${d} plugin: ${c.slug}`)}catch(m){_()||R(`Native uninstall failed: ${m}. Removing tracking only.`)}yt(c.resourceId,o.id),M()&&await $("/api/cli/uninstall",{resourceId:c.resourceId,agentPlatform:o.platform}).catch(()=>{}),Ne(),_()?F("uninstall",{path:e,removed:!0}):w(`Uninstalled "${e}"`);return}else{let d=Te(o),m=S[S.length-1],E=s.project?"project":"user",f=await d.uninstall(m,E,o,c?.resourceId);if(x=f.removed,!_())for(let h of f.warnings)R(`Warning: ${h}`);if(c){let C=G().installations.filter(i=>i.collectionId===c.resourceId&&i.agent===o.id);for(let i of C){let y=i.installPath.split("/"),g=y[0],A=y.slice(1);if(g==="agents"){let b=re(o,!!s.project),O=(0,ft.join)(b,...A);(0,ne.existsSync)(O)&&(0,ne.rmSync)(O,{recursive:!0,force:!0})}else if(g==="mcps"){let b=A[A.length-1],O=oe(o,!!s.project);if((0,ne.existsSync)(O))try{let k=JSON.parse((0,ne.readFileSync)(O,"utf-8"));if(typeof k.mcpServers=="object"&&k.mcpServers&&!Array.isArray(k.mcpServers)){let D=k.mcpServers;b in D&&(delete D[b],k.mcpServers=D,(0,ne.writeFileSync)(O,JSON.stringify(k,null,2)+`
158
- `,"utf-8"))}}catch{}}else if(g==="hooks")Ur(ye(o,!!s.project),i.installPath);else{let b=W(o,!!s.project),O=(0,ft.join)(b,...A);(0,ne.existsSync)(O)&&(0,ne.rmSync)(O,{recursive:!0,force:!0})}yt(i.resourceId,o.id)}}}else if(p==="agents"){let d=re(o,!!s.project),m=(0,ft.join)(d,...S);x=(0,ne.existsSync)(m),x&&(0,ne.rmSync)(m,{recursive:!0,force:!0})}else if(p==="mcps"){let d=S[S.length-1],m=oe(o,!!s.project);if((0,ne.existsSync)(m))try{let E=JSON.parse((0,ne.readFileSync)(m,"utf-8"));if(typeof E.mcpServers=="object"&&E.mcpServers&&!Array.isArray(E.mcpServers)){let f=E.mcpServers;d in f&&(delete f[d],E.mcpServers=f,(0,ne.writeFileSync)(m,JSON.stringify(E,null,2)+`
159
- `,"utf-8"),x=!0)}}catch{}}else if(p==="hooks"){let d=ye(o,!!s.project);x=Ur(d,e),!x&&!_()&&R(`Note: No tagged hook entries found in ${d} \u2014 may need manual removal if installed before v0.1.10`)}else{let d=W(o,!!s.project),m=(0,ft.join)(d,...S);if(x=(0,ne.existsSync)(m),x&&(0,ne.rmSync)(m,{recursive:!0,force:!0}),!x&&c?.slug){let E=(0,ft.join)(d,c.slug);(0,ne.existsSync)(E)&&(0,ne.rmSync)(E,{recursive:!0,force:!0})}}if(M()&&c){let d=await $("/api/cli/uninstall",{resourceId:c.resourceId});!d.ok&&!_()&&R(`Warning: Could not record uninstall on server: ${d.error.message}`)}c&&yt(c.resourceId,o.id),Ne(),_()?F("uninstall",{path:e,removed:!0}):w(`Uninstalled "${e}"`)})}fe();se();te();function Ho(r){r.command("status").description("Show CLI status: auth, agents, installed resources, project sync state").action(async()=>{let e=Ae(),t=be(),n=G(),s=Le(),o=ve(),l=n.installations.filter(S=>!S.projectId),c=n.installations.filter(S=>S.projectId),u=new Map;for(let S of c){let x=S.projectId;u.has(x)||u.set(x,[]),u.get(x).push(S)}let a=[];if(M()&&u.size>0)for(let[S,x]of u){let d=await z(`/api/cli/projects/${S}/resources`).catch(()=>null),m=d&&d.ok?d.data.resources.length:x.length,E=o?.projectId===S?o.projectName:`Project ${S.slice(0,8)}`;a.push({projectId:S,projectName:E,localCount:x.length,serverCount:m,synced:x.length>=m})}let p={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:s.map(S=>S.id),installedCount:n.installations.length,globalCount:l.length,projects:a};if(_()){F("status",p);return}if(w("Shared Context CLI Status"),w("\u2500".repeat(40)),e?.token?w(` Auth: ${e.email} (${e.orgSlug})`):w(" Auth: Not logged in"),w(` API: ${t.apiBase}`),s.length>0?w(` Agents: ${s.map(S=>S.label).join(", ")}`):w(" Agents: None detected"),w(` Global: ${l.length} resource${l.length===1?"":"s"} installed`),a.length>0){w(""),w("Projects:");for(let S of a){let x=S.synced?"\u2713 synced":`\u26A0 ${S.serverCount-S.localCount} new`;w(` ${S.projectName}: ${S.localCount}/${S.serverCount} resources (${x})`)}}else o&&(w(""),w(` Project: ${o.projectName} (linked)`))})}fe();se();te();function Bo(r){r.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=Ae();e.revoke&&M()&&await Tr("/api/cli/auth"),Or(),_()?F("logout",{email:t?.email||null}):w("Logged out.")})}var tr=require("fs"),Wo=require("path");se();te();function Vo(r){r.command("import [path]").description("Import resources from a local directory or GitHub URL").option("--github <url>","Import a single resource from a GitHub URL").option("--resource-type <type>","Resource type (skill|command|hook|agent|mcp) \u2014 for GitHub import disambiguation").option("--visibility <level>","Visibility for created resources","org").option("--dry-run","Preview what would happen without making changes",!1).option("--no-recursive","Do not recursively scan subdirectories").option("--tags <tags>","Comma-separated topic tags").option("--on-conflict <strategy>","Conflict resolution strategy (auto|skip|update|clone|error)","auto").action(async(e,t,n)=>{let s=n.optsWithGlobals(),o=t.github;if(o&&e&&(_()?j("import","INVALID_ARGS","Cannot use --github with a local path"):R("Error: Cannot use --github with a local path. Use one or the other."),process.exit(1)),!o&&!e&&(_()?j("import","INVALID_ARGS","Provide a local path or --github <url>"):R("Error: Provide a local path or --github <url>"),process.exit(1)),M()||(_()?j("import","AUTH_MISSING","Authentication required for import"):R("Error: Authentication required. Run 'shared-context-ai login' first."),process.exit(1)),o){t.onConflict&&t.onConflict!=="auto"&&(_()?j("import","INVALID_ARGS","--on-conflict is not supported with --github"):R("Error: --on-conflict is not supported with --github"),process.exit(1)),t.dryRun&&(_()?j("import","INVALID_ARGS","--dry-run is not supported with --github"):R("Error: --dry-run is not supported with --github"),process.exit(1));let m={url:o};t.resourceType&&(m.resourceType=t.resourceType),_()||w(`
160
- Importing from GitHub: ${o}`);let E=await $("/api/cli/github-import",m);E.ok||(_()?j("import",E.error.code,E.error.message):R(`
161
- Import failed: ${E.error.message}`),process.exit(1));let f=E.data;if(_()){F("import",f);return}w(""),w(` Source: ${f.source.owner}/${f.source.repo}`),w(` Type: ${f.resourceType}`),w(` Title: ${f.title}`),f.slug&&w(` Slug: ${f.slug}`),w(` URL: ${f.url}`),w(""),w("Import complete: 1 created");return}let l=(0,Wo.resolve)(e);(!(0,tr.existsSync)(l)||!(0,tr.statSync)(l).isDirectory())&&(_()?j("import","INVALID_PATH",`Not a directory: ${l}`):R(`Error: Not a directory: ${l}`),process.exit(1));let c=ct(l);if(c.resources.length===0){_()?F("import",{resources:[],message:"No resources found"}):w("No resources found in the specified directory.");return}if(!_()){let m=new Map;for(let f of c.resources)m.set(f.resourceType,(m.get(f.resourceType)||0)+1);let E=[...m.entries()].map(([f,h])=>`${h} ${f}${h===1?"":"s"}`).join(", ");w(`
162
- Discovered ${c.resources.length} resources in ${e}:`),w(` ${E}`),c.formatLabel&&c.pluginName?w(` ${c.formatLabel}: ${c.pluginName}`):c.pluginName&&w(` Plugin: ${c.pluginName}`)}let u=t.tags?t.tags.split(",").map(m=>m.trim()).filter(Boolean):void 0,a={dryRun:!!t.dryRun,onConflict:t.onConflict||"auto",visibility:t.visibility||"org",topicTags:u,resources:c.resources,collectionMemberships:c.collectionMemberships.length>0?c.collectionMemberships:void 0};!_()&&!t.dryRun?w(`
163
- Executing import...`):_()||w(`
164
- Dry run \u2014 previewing changes...`);let p=await $("/api/cli/import",a,12e4);p.ok||(_()?j("import",p.error.code,p.error.message):R(`
165
- Import failed: ${p.error.message}`),process.exit(1));let S=p.data;if(_()){F("import",S);return}let x=[...S.created.map(m=>({...m,action:"created"})),...S.updated.map(m=>({...m,action:"updated"})),...S.installed.map(m=>({...m,action:"installed"})),...S.cloned.map(m=>({...m,action:"cloned"})),...S.skipped.map(m=>({...m,action:"skipped"})),...S.errors.map(m=>({...m,action:"error"}))];if(x.length>0){w("");let m=x.length,E=x.map((f,h)=>{let C=`[${String(h+1).padStart(String(m).length)}/${m}]`,i=(f.resourceType||"").padEnd(10),y=(f.importPath.split("/").pop()||"").padEnd(24),g="";switch(f.action){case"created":g=`\u2713 created${f.slug?` (slug: ${f.slug})`:""}`;break;case"updated":g="\u2713 updated";break;case"installed":{let A=f.versionsBehind;g=`\u2713 installed${A?` (${A} versions behind)`:""}`;break}case"cloned":g=`\u2713 cloned${f.slug?` (slug: ${f.slug})`:""}`;break;case"skipped":g=`\u2713 skipped (${f.reason||"up to date"})`;break;case"error":g=`\u2717 error: ${f.error||"unknown"}`;break}return` ${C} ${i} ${y} ${g}`});for(let f of E)w(f)}if(S.collections.length>0)for(let m of S.collections){let E=m.importPath.split("/").pop()||m.importPath;w(` collection ${E.padEnd(20)} \u2713 ${m.membersLinked} members linked${m.membersFailed>0?`, ${m.membersFailed} failed`:""}`)}w("");let d=[S.created.length>0?`${S.created.length} created`:null,S.installed.length>0?`${S.installed.length} installed`:null,S.cloned.length>0?`${S.cloned.length} cloned`:null,S.updated.length>0?`${S.updated.length} updated`:null,S.skipped.length>0?`${S.skipped.length} skipped`:null,S.errors.length>0?`${S.errors.length} errors`:null].filter(Boolean);t.dryRun?w(`Dry run complete: ${d.join(", ")}`):w(`Import complete: ${d.join(", ")}`),S.errors.length>0&&process.exit(1)})}var Sn=require("path"),Zo=require("os");se();fe();te();var Wa={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Va(r){let e=r.slug||r.resourceId;return`${Wa[r.resourceType]||r.resourceType+"s"}/${e}`}function Jo(r){r.command("sync").description("Synchronize resource state \u2014 check for updates and discover untracked resources").option("--quiet","Minimal output (one-line summary)").option("--force","Bypass throttle and sync now").option("--no-import","Skip auto-importing untracked resources").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()};if(!n.force&&!vr()){let I=G(),T=I.installations.filter(L=>L.latestSha&&L.sha&&L.latestSha!==L.sha),v=I.lastSyncAt?Math.floor((Date.now()-new Date(I.lastSyncAt).getTime())/6e4):void 0,N={updatesAvailable:T.length,untrackedResources:0,driftRepairs:0,updates:T.map(L=>({installPath:L.installPath,title:L.title,sha:L.sha,latestSha:L.latestSha})),untracked:[],summary:gn(T.length,0)+(v!==void 0?` (cached ${v}m ago, run --force to refresh)`:""),throttled:!0,cacheAge:v};yn(N,!!n.quiet);return}M()||(_()?j("sync","AUTH_MISSING","Login required to sync."):R("Login required. Run 'shared-context-ai login'."),process.exit(1));let s=ke(n.agent),o=await z("/api/cli/installed");if(!o.ok){let T=G().installations.filter(N=>N.latestSha&&N.sha&&N.latestSha!==N.sha);!_()&&!n.quiet&&R(`Warning: Could not reach server (${o.error.message}). Showing cached state.`);let v={updatesAvailable:T.length,untrackedResources:0,driftRepairs:0,updates:T.map(N=>({installPath:N.installPath,title:N.title,sha:N.sha,latestSha:N.latestSha})),untracked:[],summary:gn(T.length,0)+" (offline)",throttled:!1};yn(v,!!n.quiet);return}let l=o.data.installations,c=new Map(l.map(I=>[I.resourceId,I])),u=G(),a=0;for(let I of u.installations){let T=c.get(I.resourceId);if(T)I.latestSha=T.latestSha||void 0,I.resourceType=I.resourceType||T.resourceType,I.serverSynced=!0,T.installedSha&&I.sha&&T.installedSha!==I.sha&&(!_()&&!n.quiet&&w(` Drift repaired: ${I.installPath} (local=${I.sha.slice(0,7)} \u2192 server=${T.installedSha.slice(0,7)})`),I.sha=T.installedSha,a++),c.delete(I.resourceId);else if(I.serverSynced!==!1){let v=await $("/api/cli/install",{resourceId:I.resourceId,agentPlatform:s?.platform||"claude_code",installedSha:I.sha});v.ok?I.serverSynced=!0:(v.error.code==="NOT_FOUND"||v.error.code==="RESOURCE_NOT_FOUND")&&(I.serverSynced=!1,I.resourceId="",a++)}}u.installations=u.installations.filter(I=>I.resourceId!=="");let p=Array.from(c.values());if(p.length>0&&!_()&&!n.quiet){w(`
166
- ${p.length} resource${p.length===1?"":"s"} installed elsewhere (web/other machine):`);for(let I of p.slice(0,5))w(` ${Va(I)} \u2014 ${I.title}`);p.length>5&&w(` ...and ${p.length-5} more`)}let S=s?[s]:Le();S.length===0&&!_()&&!n.quiet&&R("No AI agents detected \u2014 resource discovery skipped. Use --agent to specify one.");let x=[],d=[],m=new Set;for(let I of S){let T=n.project?(0,Sn.join)(process.cwd(),I.dir):(0,Sn.join)((0,Zo.homedir)(),I.dir),v=ct(T,{settingsPath:ye(I,!!n.project),mcpConfigPath:oe(I,!!n.project)});for(let N of v.resources)m.has(N.importPath)||(m.add(N.importPath),x.push(N));for(let N of v.collectionMemberships)m.has(`cm:${N.collectionImportPath}`)||(m.add(`cm:${N.collectionImportPath}`),d.push(N))}let E={resources:x,collectionMemberships:d},f=new Set(u.installations.map(I=>I.installPath)),h=new Map;for(let I of u.installations){let T=I.installPath.split("/"),v=T[0],N=T[T.length-1];h.has(v)||h.set(v,new Set),h.get(v).add(N)}let C=new Set(["context-manager",".claude-plugin"]),i=E.resources.filter(I=>{if(f.has(I.importPath))return!1;let T=I.importPath.split("/"),v=T[0],N=T[T.length-1];return!((v==="mcps"||v==="hooks")&&h.get(v)?.has(N)||I.importPath.startsWith(".")||C.has(N)||I.importPath.startsWith("plugins/"))});for(let I of i)I.description&&I.description.length>1e3&&(I.description=I.description.slice(0,997)+"...");let y=i.length;if(n.import!==!1&&i.length>0){let I={dryRun:!1,onConflict:"auto",visibility:"org",resources:i,collectionMemberships:E.collectionMemberships},T=await $("/api/cli/import",I,12e4);if(T.ok){let v=[...T.data.created,...T.data.updated,...T.data.installed];for(let N of v){if(!N.id)continue;let L=s?.id||S[0]?.id;L&&ue({resourceId:N.id,slug:N.slug||N.importPath.split("/").pop()||N.id,installPath:N.importPath,title:N.importPath.split("/").pop()||N.id,sha:N.commitSha||"",scope:n.project?"project":"global",agent:L,installedAt:new Date().toISOString(),resourceType:N.resourceType,serverSynced:!0})}if(!_()&&!n.quiet){if(v.length>0){w(`
167
- Imported ${v.length} resource${v.length===1?"":"s"}:`);let N=v.map(L=>[` ${(L.resourceType||"").padEnd(12)}`,(L.slug||L.importPath.split("/").pop()||"").padEnd(24),L.importPath]);w(he(N))}T.data.errors.length>0&&R(`
168
- ${T.data.errors.length} import error(s)`)}i.length=0}else _()||R(`Import failed: ${T.error.message}`)}let g=ve(),A=0;if(g){let I=await z(`/api/cli/projects/${g.projectId}/resources`);if(!I.ok)!_()&&!n.quiet&&(R(`Warning: Project "${g.projectName}" not found on server (may have been deleted).`),R(" Remove .shared-context/project.json to unlink this directory."));else{let T=I.data.resources,v=u.installations.filter(q=>q.projectId===g.projectId),N=new Set(v.map(q=>q.resourceId)),L=T.filter(q=>!N.has(q.id));if(L.length>0)if(!s)!_()&&!n.quiet&&R(`
169
- Project "${g.projectName}" has ${L.length} new resource${L.length===1?"":"s"} \u2014 use --agent to install them.`);else{let q=Te(s);for(let ge of L){let Cn=ge.installPath;try{let wn=await z(`/api/cli/resource/${Cn}`);if(!wn.ok)continue;await q.install(wn.data,"project",s),ue({resourceId:ge.id,slug:ge.slug||ge.id,installPath:Cn,title:ge.title,sha:ge.latestSha||"",scope:"project",agent:s.id,installedAt:new Date().toISOString(),projectId:g.projectId,resourceType:ge.resourceType,serverSynced:!0}),ge.latestSha&&await $("/api/cli/install",{resourceId:ge.id,agentPlatform:s.platform,installedSha:ge.latestSha}).catch(()=>{}),A++}catch{}}!_()&&!n.quiet&&A>0&&w(`
170
- Project "${g.projectName}": installed ${A} new resource${A===1?"":"s"}`)}await $(`/api/cli/projects/${g.projectId}/sync`,{localPath:process.cwd()}).catch(()=>{})}}let b=y-i.length;if(n.force){let I=u.lastSyncAt;u.lastSyncAt=I||new Date().toISOString()}else u.lastSyncAt=new Date().toISOString();Ze(u);let O=u.installations.filter(I=>I.latestSha&&I.sha&&I.latestSha!==I.sha),k=Ae();k?.connectionId&&$("/api/cli/sync-report",{connectionId:k.connectionId,lastSyncResult:{updatesAvailable:O.length,importedCount:b}}).catch(()=>{});try{let{pushTelemetry:I}=await Promise.resolve().then(()=>(hn(),zo));await I(!0)}catch{}let D={updatesAvailable:O.length,untrackedResources:i.length,driftRepairs:a,updates:O.map(I=>({installPath:I.installPath,title:I.title,sha:I.sha,latestSha:I.latestSha})),untracked:i.map(I=>({importPath:I.importPath,resourceType:I.resourceType,title:I.title})),summary:gn(O.length,i.length,a),throttled:!1};yn(D,!!n.quiet)})}function gn(r,e,t=0){let n=[];return r>0&&n.push(`${r} update${r===1?"":"s"} available`),e>0&&n.push(`${e} untracked resource${e===1?"":"s"}`),t>0&&n.push(`${t} drift repair${t===1?"":"s"}`),n.length===0?"Everything is up to date.":n.join(", ")}function yn(r,e){if(_()){F("sync",r);return}if(e){let t=r.summary;r.updatesAvailable>0&&(t+=" \u2014 run 'shared-context-ai update'"),r.untrackedResources>0&&(t+=` \u2014 ${r.untrackedResources} untracked`),w(t);return}if(w(""),r.updates.length>0){w(`${r.updates.length} update${r.updates.length===1?"":"s"} available:
171
- `);let t=r.updates.map(n=>[` ${n.installPath}`,n.title,`${n.sha.slice(0,7)} \u2192 ${n.latestSha.slice(0,7)}`]);w(he(t)),w("")}if(r.untracked.length>0){w(`${r.untracked.length} untracked resource${r.untracked.length===1?"":"s"}:
172
- `);let t=r.untracked.map(n=>[` ${n.resourceType.padEnd(12)}`,n.importPath.padEnd(30),n.title]);w(he(t)),w("")}r.updatesAvailable===0&&r.untrackedResources===0?w("Everything is up to date."):(r.updatesAvailable>0&&w("Run 'shared-context-ai update' to update installed resources."),r.untrackedResources>0&&w("Run 'shared-context-ai sync --force' to re-sync and import untracked resources.")),w("")}var Ko=require("path");se();se();te();function Xo(r){r.command("project").description("Manage projects").command("create").description("Create a project for the current folder").argument("[name]","Project name (defaults to folder name)").action(async t=>{if(!M()){let a="Not authenticated. Run 'shared-context-ai login' first.";_()?j("project create","AUTH_MISSING",a):R(a),process.exit(1)}let n=ve();if(n){_()?F("project create",{alreadyExists:!0,project:{id:n.projectId,name:n.projectName,slug:n.projectSlug}}):w(`Project already linked: ${n.projectName}`);return}let s=t?.trim()||(0,Ko.basename)(process.cwd());if(!s||s==="/"){let a='Could not determine project name. Provide one: shared-context-ai project create "My Project"';_()?j("project create","INVALID_NAME",a):R(a),process.exit(1)}let o=await $("/api/cli/projects",{name:s});o.ok||(_()?j("project create",o.error.code,o.error.message):R(`Failed to create project: ${o.error.message}`),process.exit(1));let{id:l,name:c,slug:u}=o.data;Et({projectId:l,projectName:c,projectSlug:u}),_()?F("project create",{id:l,name:c,slug:u}):(w(`Created project: ${c}`),w(""),w("Quick reference:"),w(" shared-context-ai install <installPath> Add a resource to this project"),w(" shared-context-ai sync Check for resource updates"),w(" shared-context-ai status View project sync status"))})}hn();var sr=require("fs"),nr=require("path"),En=require("os");te();function Ga(){let r=process.env.SC_PROFILE;return r?(0,nr.join)((0,En.homedir)(),".config","shared-context","profiles",r):(0,nr.join)((0,En.homedir)(),".config","shared-context")}function qa(){let r=(0,nr.join)(Ga(),"usage.jsonl");if(!(0,sr.existsSync)(r))return[];try{let e=(0,sr.readFileSync)(r,"utf8").trim().split(`
173
- `).filter(Boolean),t=[];for(let n of e)try{let s=JSON.parse(n);s.v&&s.ts&&s.event&&s.rid&&t.push(s)}catch{}return t}catch{return[]}}function Yo(r){r.command("stats").description("Show local usage statistics").option("--days <n>","Number of days to show","7").action(e=>{let t=parseInt(e.days,10)||7,n=new Date;n.setDate(n.getDate()-t);let o=qa().filter(u=>new Date(u.ts)>=n);if(o.length===0){_()?F("stats",{days:t,events:0,skills:[],agents:[]}):w("No usage data yet");return}let l=new Map,c=new Map;for(let u of o)if(u.event==="skill_invoked"){let a=l.get(u.slug)||{count:0,ok:0};a.count++,u.ok&&a.ok++,l.set(u.slug,a)}else if(u.event==="agent_invoked"){let a=c.get(u.slug)||{count:0,ok:0,totalMs:0,totalTokens:0};a.count++,u.ok&&a.ok++,u.dur_ms&&(a.totalMs+=u.dur_ms),u.tokens&&(a.totalTokens+=u.tokens),c.set(u.slug,a)}if(_()){F("stats",{days:t,events:o.length,skills:[...l.entries()].map(([u,a])=>({slug:u,...a})),agents:[...c.entries()].map(([u,a])=>({slug:u,...a,avgMs:a.count>0?Math.round(a.totalMs/a.count):0,avgTokens:a.count>0?Math.round(a.totalTokens/a.count):0}))});return}if(w(`Usage over the last ${t} day${t===1?"":"s"} (${o.length} event${o.length===1?"":"s"})
174
- `),l.size>0){w("Skills:");let u=[...l.entries()].sort((a,p)=>p[1].count-a[1].count).map(([a,p])=>[` ${a}`,`${p.count} use${p.count===1?"":"s"}`,`${Math.round(p.ok/p.count*100)}% ok`]);w(he(u))}if(c.size>0){l.size>0&&w(""),w("Agents:");let u=[...c.entries()].sort((a,p)=>p[1].count-a[1].count).map(([a,p])=>{let S=p.count>0?Math.round(p.totalMs/p.count):0;return[` ${a}`,`${p.count} use${p.count===1?"":"s"}`,`${Math.round(p.ok/p.count*100)}% ok`,S>0?`avg ${(S/1e3).toFixed(1)}s`:""]});w(he(u))}})}Gr();var Qo={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."},or=class extends Error{constructor(t,n){super(n||Qo[t]);this.code=t;this.name="CliError"}code;get recovery(){return Qo[this.code]}};te();var ae=new jn;ae.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",r=>{let e=r.opts();$n(!!e.json,!!e.human)});Zs(ae);ko(ae);To(ae);js(ae);Po(ae);Do(ae);No(ae);$o(ae);Uo(ae);Ho(ae);Bo(ae);Vo(ae);Jo(ae);Xo(ae);mn(ae);Yo(ae);Vr(ae);process.on("uncaughtException",r=>{r instanceof or?_()?j(process.argv[2]||"unknown",r.code,r.message):(R(`Error: ${r.message}`),R(r.recovery)):_()?j(process.argv[2]||"unknown","UNEXPECTED",r.message||"Unexpected error"):R(`Error: ${r.message||r}`),process.exit(1)});ae.parse();
146
+ \`shared-context-ai config set telemetry off\`. [y/N] `,b=>{y.close(),g(b.trim().toLowerCase()==="y"||b.trim().toLowerCase()==="yes")})})){h({telemetry:!0});let{enableTelemetryHook:g}=await Promise.resolve().then(()=>(Kr(),Gs));g(),w("Telemetry enabled.")}else h({telemetry:!1}),w("Telemetry disabled.")}catch{}}if(c){let f=p.reduce((h,C)=>h+C.importedResources.length,0);L("/api/cli/sync-report",{connectionId:c,lastSyncResult:{updatesAvailable:0,importedCount:f}}).catch(()=>{})}let d=p.every(f=>f.skippedEssentials),m=p.some(f=>!f.skippedEssentials),E=p.some(f=>f.importedResources.length>0);if(A()){let f=h=>({agent:h.agent.id,collection:h.collectionInstalled?Xt:void 0,contextManagerOnly:!h.collectionInstalled,skipped:h.skippedEssentials,...h.collectionInstalled&&!h.skippedEssentials?{membersInstalled:h.installedMembers.map(C=>({title:C.title,resourceType:C.resourceType}))}:{},...h.importedResources.length>0?{importedResources:h.importedResources.map(C=>({resourceType:C.resourceType,slug:C.slug,title:C.title}))}:{}});F("init",{...f(p[0]),agents:p.map(f),...u?{projectCreated:!0}:{},authenticated:U()})}else{for(let f of p)if(!f.skippedEssentials){if(w(""),f.collectionInstalled){w(`Context Manager installed for ${f.agent.label} (${f.installedMembers.length} resources)`);let h={};for(let i of f.installedMembers)h[i.resourceType]||(h[i.resourceType]=[]),h[i.resourceType].push(i.title);let C={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};w("");for(let[i,g]of Object.entries(h)){let y=C[i]||i;w(` ${y}: ${g.join(", ")}`)}}else w(`Context Manager installed for ${f.agent.label} (offline)`),w("Context Manager agent written locally");if(f.importedResources.length>0){w(""),w(`Imported ${f.importedResources.length} existing resource${f.importedResources.length===1?"":"s"}:`);for(let h of f.importedResources)w(` ${h.resourceType.padEnd(12)} ${h.slug.padEnd(24)} ${h.title}`)}}d&&!u&&!E&&(w(""),w("Already initialized. Nothing to do.")),(m||u||E)&&(w(""),w("Quick reference:"),w(' shared-context-ai search "query" Search for resources'),w(" shared-context-ai install <installPath> Install a resource"),w(" shared-context-ai list List installed resources"),w(" shared-context-ai sync Check updates & discover resources"),w(" shared-context-ai preview <installPath> Preview before installing"))}})}var Oo=require("http"),ko=require("crypto");me();ie();me();se();async function vo(r){let e=await L("/api/cli/auth",{code:r});return e.ok?(Tr({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()}),A()?F("login",{email:e.data.user.email,org:e.data.org.slug}):w(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(A()?$("login",e.error.code,e.error.message):R(`Login failed: ${e.error.message}`),!1)}async function La(){let r=(0,ko.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,Oo.createServer)((n,s)=>{let o=new URL(n.url||"/","http://localhost"),l=o.searchParams.get("code"),c=o.searchParams.get("state");if(!l||c!==r){s.writeHead(400,{"Content-Type":"text/html"}),s.end("<h1>Authentication failed</h1><p>Invalid state. Please try again.</p>"),t.close(),e(!1);return}s.writeHead(200,{"Content-Type":"text/html"}),s.end("<h1>Authentication successful!</h1><p>You can close this tab and return to your terminal.</p>"),t.close(),vo(l).then(e)});t.listen(0,"127.0.0.1",async()=>{let n=t.address();if(!n||typeof n=="string"){t.close(),e(!1);return}let s=n.port,l=`${xe().apiBase||"https://sharedcontext.ai"}/cli/login?port=${s}&state=${r}`;A()||(w("Opening browser for authentication..."),w(`If the browser doesn't open, visit: ${l}`));try{let c=(await Promise.resolve().then(()=>(xo(),Io))).default;await c(l)}catch{A()||w(`Could not open browser. Please visit:
147
+ ${l}`)}setTimeout(()=>{t.close(),A()||R("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function To(r){r.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 vo(e.code):t=await La(),process.exit(t?0:1)})}ie();se();var Ma={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Ro(r){let e=Ma[r.resourceType]||r.resourceType+"s";return r.storageType==="github"&&r.githubOwner?`${e}/external/${r.githubOwner}/${r.slug}`:r.orgSlug?`${e}/${r.orgSlug}/${r.slug}`:`${e}/${r.slug}`}function Po(r){r.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, command, hook, collection, agent, mcp, file)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let n=new URLSearchParams({q:e});t.type&&n.set("type",t.type),t.tag&&n.set("tag",t.tag),t.limit&&n.set("limit",t.limit);let s=U()?`/api/cli/search?${n}`:`/api/public/search?${n}`,o=await Z(s);o.ok||(A()?$("search",o.error.code,o.error.message):w(`Search failed: ${o.error.message}`),process.exit(1));let l=o.data.results;if(A()){let u=l.map(a=>{let p=Ro(a);return{installPath:p,installCommand:`npx shared-context-ai install ${p}`,title:a.title,description:a.description,resourceType:a.resourceType,installCount:a.installCount,topicTags:a.topicTags}});F("search",{results:u,count:u.length});return}if(l.length===0){let u=t.type?`${t.type}s`:"results";w(`No ${u} found.`);return}w(`Found ${l.length} result${l.length===1?"":"s"}:
148
+ `);let c=l.map(u=>[Ro(u),u.title,`\u2193${u.installCount}`]);w(Se(c)),w(`
149
+ Install a skill: npx shared-context-ai install <installPath>`)})}ie();me();se();function Do(r){let e=r.slug||r.resourceId;return r.storageType==="github"&&r.githubOwner?`skills/external/${r.githubOwner}/${e}`:r.orgSlug?`skills/${r.orgSlug}/${e}`:`skills/${e}`}function No(r){r.command("list").description("List installed skills").alias("ls").action(async()=>{if(U()){let e=await Z("/api/cli/installed");e.ok||(A()?$("list",e.error.code,e.error.message):w(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(A()){let s=t.map(o=>({...o,installPath:Do(o)}));F("list",{installations:s,count:s.length});return}if(t.length===0){w("No skills installed."),w("Use 'shared-context-ai search' to find skills to install.");return}w(`${t.length} skill${t.length===1?"":"s"} installed:
150
+ `);let n=t.map(s=>[Do(s),s.title,s.hasUpdate?"(update available)":"(current)"]);w(Se(n))}else{let t=z().installations;if(A()){F("list",{installations:t,count:t.length});return}if(t.length===0){w("No skills installed locally.");return}w(`${t.length} skill${t.length===1?"":"s"} installed locally:
151
+ `);let n=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);w(Se(n)),w(`
152
+ Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}ie();se();function jo(r){r.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let n=U()?"/api/cli/resource":"/api/public/resource",s=await Z(`${n}/${e}/preview`);s.ok||(A()?$("preview",s.error.code,s.error.message):R(`Preview failed: ${s.error.message}`),process.exit(1)),A()?F("preview",s.data):w(s.data.content)})}ie();se();function $o(r){r.command("check").description("Check for skill updates").action(async()=>{U()||(A()?$("check","AUTH_MISSING","Login required to check for updates."):R("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await Z("/api/cli/updates");e.ok||(A()?$("check",e.error.code,e.error.message):R(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:n}=e.data;if(A()){F("check",{updates:t,count:n});return}if(n===0){w("All skills are up to date.");return}w(`${n} update${n===1?"":"s"} available:
153
+ `);let s=t.map(o=>{let l=o.slug||o.resourceId;return[o.storageType==="github"&&o.githubOwner?`skills/external/${o.githubOwner}/${l}`:o.orgSlug?`skills/${o.orgSlug}/${l}`:`skills/${l}`,o.title,`${o.installedSha.slice(0,7)} \u2192 ${o.latestSha.slice(0,7)}`]});w(Se(s)),w(`
154
+ Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var ot=require("path"),sr=require("fs"),Lo=require("child_process");ie();me();se();var Mo={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Fo(r){let e=r.slug||r.resourceId;return`${Mo[r.resourceType]||r.resourceType+"s"}/${e}`}function Uo(r){r.command("update [path]").description("Update installed resources (all or by install path)").action(async(e,t,n)=>{let s=n.optsWithGlobals();U()||(A()?$("update","AUTH_MISSING","Login required to update resources."):R("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let o=Pe(s.agent);if(!o){let a=Be();A()?$("update","NO_AGENTS",a):R(a),process.exit(1)}let l=await Z("/api/cli/updates");l.ok||(A()?$("update",l.error.code,l.error.message):R(`Failed to check updates: ${l.error.message}`),process.exit(1));let c=l.data.updates;if(e&&(c=c.filter(a=>Fo(a)===e||a.slug===e||a.resourceId===e),c.length===0)){A()?$("update","SKILL_NOT_FOUND",`No update available for "${e}".`):w(`No update available for "${e}".`);return}if(c.length===0){A()?F("update",{updated:[],count:0}):w("All resources are up to date.");return}let u=[];for(let a of c){let p=Fo(a),I=z().installations.find(h=>h.resourceId===a.resourceId&&h.agent===o.id);if(I?.installMode==="plugin"&&a.resourceType==="collection"){try{let h=a.orgSlug||"",C=a.slug||a.resourceId,i=Mt(o.id),g=`/api/cli/resource/collections/${h}/${C}?format=plugin&platform=${i}`,y=await Lt(g,C),b=ut(o.id);b&&(0,Lo.execSync)(`${b} plugin install "${y}"`,{stdio:"pipe"}),a.latestSha&&await L("/api/cli/update",{resourceId:a.resourceId,installedSha:a.latestSha}),pe({...I,sha:a.latestSha,installedAt:new Date().toISOString()}),u.push({installPath:p,title:a.title}),A()||w(` Updated plugin: ${p}`)}catch(h){A()||R(` Plugin update failed for ${p}: ${h}`)}continue}let d=await Z(`/api/cli/resource/${p}`);if(!d.ok){A()||R(` Failed to fetch ${p}: ${d.error.message}`);continue}let m=d.data,E=p.split("/").slice(1);if(m.resource.resourceType==="agent"){let h=re(o,!!s.project),C=(0,ot.join)(h,...E);G(C,m.files)}else if(m.resource.resourceType==="mcp")Ht(o,!!s.project,m);else{let h=q(o,!!s.project),C=(0,ot.join)(h,...E);G(C,m.files)}if(I&&I.installPath&&I.installPath!==p){let h=I.installPath.split("/").slice(1),C;m.resource.resourceType==="agent"?C=(0,ot.join)(re(o,!!s.project),...h):m.resource.resourceType!=="mcp"&&(C=(0,ot.join)(q(o,!!s.project),...h)),C&&(0,sr.existsSync)(C)&&((0,sr.rmSync)(C,{recursive:!0}),A()||w(` Removed old path: ${I.installPath}`))}let f=a.latestSha||m.resource.latestSha;if(f&&await L("/api/cli/update",{resourceId:a.resourceId,installedSha:f}),pe({...I||{},resourceId:a.resourceId,slug:a.slug||a.resourceId,installPath:p,title:m.resource.title,sha:f||"",scope:I?.scope||(s.project?"project":"global"),agent:o.id,installedAt:new Date().toISOString(),latestSha:f||void 0,resourceType:a.resourceType||m.resource.resourceType,serverSynced:!0}),u.push({installPath:p,title:m.resource.title}),A()||w(` Updated ${p}`),m.resource.resourceType==="collection"&&m.memberResources&&I?.installMode!=="plugin"){let h=z(),C=new Set(h.installations.map(i=>i.resourceId));for(let i of m.memberResources){if(C.has(i.id))continue;let g=i.slug||i.id,b=`${Mo[i.resourceType]||i.resourceType+"s"}/${g}`,_=await Z(`/api/cli/resource/${b}`);if(!_.ok){A()||R(` Failed to fetch new member ${b}: ${_.error.message}`);continue}let O=_.data,k=b.split("/").slice(1);if(O.resource.resourceType==="agent"){let D=re(o,!!s.project);G((0,ot.join)(D,...k),O.files)}else if(O.resource.resourceType==="mcp")Ht(o,!!s.project,O);else{let D=q(o,!!s.project);G((0,ot.join)(D,...k),O.files)}i.latestSha&&await L("/api/cli/install",{resourceId:i.id,agentPlatform:o.platform,installedSha:i.latestSha}).catch(()=>{}),pe({resourceId:i.id,slug:g,installPath:b,title:i.title,sha:i.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),collectionId:m.resource.id,resourceType:i.resourceType,serverSynced:!0}),A()||w(` + New member: ${b}`)}}}u.length>0&&Me(),A()?F("update",{updated:u,count:u.length}):u.length>0&&w(`
155
+ ${u.length} resource${u.length===1?"":"s"} updated.`)})}var oe=require("fs"),gt=require("path"),Ho=require("child_process");ie();me();se();function Bo(r){r.command("uninstall [path]").description("Uninstall a resource by install path (e.g., skills/acme/api-testing)").action(async(e,t,n)=>{if(!e){let m=z().installations;if(m.length===0&&(A()?$("uninstall","NOTHING_INSTALLED","No resources installed."):w("No resources installed."),process.exit(0)),A())F("uninstall",{installations:m.map(E=>({path:E.installPath||E.slug,title:E.title,agent:E.agent}))});else{w(`Installed resources:
156
+ `);let E=m.map(f=>[f.installPath||f.slug,f.title||"",`(${f.agent})`]);w(Se(E)),w(`
157
+ Usage: shared-context-ai uninstall <path>`)}return}let s=n.optsWithGlobals(),o=Pe(s.agent);if(!o){let d=Be();A()?$("uninstall","NO_AGENTS",d):R(d),process.exit(1)}let c=z().installations.find(d=>d.installPath===e||d.slug===e||d.resourceId===e),u=e.split("/"),p=["skills","files","commands","hooks","collections","agents","mcps"].includes(u[0])?u[0]:null,S=p?u.slice(1):u,I=!1;if(p==="collections")if(c?.installMode==="plugin"){let d=ut(o.id);if(d)try{(0,Ho.execSync)(`${d} plugin uninstall "${c.slug}"`,{stdio:"pipe"}),A()||w(`Uninstalled native ${d} plugin: ${c.slug}`)}catch(m){A()||R(`Native uninstall failed: ${m}. Removing tracking only.`)}bt(c.resourceId,o.id),U()&&await L("/api/cli/uninstall",{resourceId:c.resourceId,agentPlatform:o.platform}).catch(()=>{}),Me(),A()?F("uninstall",{path:e,removed:!0}):w(`Uninstalled "${e}"`);return}else{let d=De(o),m=S[S.length-1],E=s.project?"project":"user",f=await d.uninstall(m,E,o,c?.resourceId);if(I=f.removed,!A())for(let h of f.warnings)R(`Warning: ${h}`);if(c){let C=z().installations.filter(i=>i.collectionId===c.resourceId&&i.agent===o.id);for(let i of C){let g=i.installPath.split("/"),y=g[0],b=g.slice(1);if(y==="agents"){let _=re(o,!!s.project),O=(0,gt.join)(_,...b);(0,oe.existsSync)(O)&&(0,oe.rmSync)(O,{recursive:!0,force:!0})}else if(y==="mcps"){let _=b[b.length-1],O=ae(o,!!s.project);if((0,oe.existsSync)(O))try{let k=JSON.parse((0,oe.readFileSync)(O,"utf-8"));if(typeof k.mcpServers=="object"&&k.mcpServers&&!Array.isArray(k.mcpServers)){let D=k.mcpServers;_ in D&&(delete D[_],k.mcpServers=D,(0,oe.writeFileSync)(O,JSON.stringify(k,null,2)+`
158
+ `,"utf-8"))}}catch{}}else if(y==="hooks")Vr(Ee(o,!!s.project),i.installPath);else{let _=q(o,!!s.project),O=(0,gt.join)(_,...b);(0,oe.existsSync)(O)&&(0,oe.rmSync)(O,{recursive:!0,force:!0})}bt(i.resourceId,o.id)}}}else if(p==="agents"){let d=re(o,!!s.project),m=(0,gt.join)(d,...S);I=(0,oe.existsSync)(m),I&&(0,oe.rmSync)(m,{recursive:!0,force:!0})}else if(p==="mcps"){let d=S[S.length-1],m=ae(o,!!s.project);if((0,oe.existsSync)(m))try{let E=JSON.parse((0,oe.readFileSync)(m,"utf-8"));if(typeof E.mcpServers=="object"&&E.mcpServers&&!Array.isArray(E.mcpServers)){let f=E.mcpServers;d in f&&(delete f[d],E.mcpServers=f,(0,oe.writeFileSync)(m,JSON.stringify(E,null,2)+`
159
+ `,"utf-8"),I=!0)}}catch{}}else if(p==="hooks"){let d=Ee(o,!!s.project);I=Vr(d,e),!I&&!A()&&R(`Note: No tagged hook entries found in ${d} \u2014 may need manual removal if installed before v0.1.10`)}else{let d=q(o,!!s.project),m=(0,gt.join)(d,...S);if(I=(0,oe.existsSync)(m),I&&(0,oe.rmSync)(m,{recursive:!0,force:!0}),!I&&c?.slug){let E=(0,gt.join)(d,c.slug);(0,oe.existsSync)(E)&&(0,oe.rmSync)(E,{recursive:!0,force:!0})}}if(U()&&c){let d=await L("/api/cli/uninstall",{resourceId:c.resourceId});!d.ok&&!A()&&R(`Warning: Could not record uninstall on server: ${d.error.message}`)}c&&bt(c.resourceId,o.id),Me(),A()?F("uninstall",{path:e,removed:!0}):w(`Uninstalled "${e}"`)})}me();ie();se();function Wo(r){r.command("status").description("Show CLI status: auth, agents, installed resources, project sync state").action(async()=>{let e=Ie(),t=xe(),n=z(),s=He(),o=ke(),l=n.installations.filter(S=>!S.projectId),c=n.installations.filter(S=>S.projectId),u=new Map;for(let S of c){let I=S.projectId;u.has(I)||u.set(I,[]),u.get(I).push(S)}let a=[];if(U()&&u.size>0)for(let[S,I]of u){let d=await Z(`/api/cli/projects/${S}/resources`).catch(()=>null),m=d&&d.ok?d.data.resources.length:I.length,E=o?.projectId===S?o.projectName:`Project ${S.slice(0,8)}`;a.push({projectId:S,projectName:E,localCount:I.length,serverCount:m,synced:I.length>=m})}let p={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:s.map(S=>S.id),installedCount:n.installations.length,globalCount:l.length,projects:a};if(A()){F("status",p);return}if(w("Shared Context CLI Status"),w("\u2500".repeat(40)),e?.token?w(` Auth: ${e.email} (${e.orgSlug})`):w(" Auth: Not logged in"),w(` API: ${t.apiBase}`),s.length>0?w(` Agents: ${s.map(S=>S.label).join(", ")}`):w(" Agents: None detected"),w(` Global: ${l.length} resource${l.length===1?"":"s"} installed`),a.length>0){w(""),w("Projects:");for(let S of a){let I=S.synced?"\u2713 synced":`\u26A0 ${S.serverCount-S.localCount} new`;w(` ${S.projectName}: ${S.localCount}/${S.serverCount} resources (${I})`)}}else o&&(w(""),w(` Project: ${o.projectName} (linked)`))})}me();ie();se();function Vo(r){r.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=Ie();e.revoke&&U()&&await Nr("/api/cli/auth"),Rr(),A()?F("logout",{email:t?.email||null}):w("Logged out.")})}var or=require("fs"),qo=require("path");ie();se();function Go(r){r.command("import [path]").description("Import resources from a local directory or GitHub URL").option("--github <url>","Import a single resource from a GitHub URL").option("--resource-type <type>","Resource type (skill|command|hook|agent|mcp) \u2014 for GitHub import disambiguation").option("--visibility <level>","Visibility for created resources","org").option("--dry-run","Preview what would happen without making changes",!1).option("--no-recursive","Do not recursively scan subdirectories").option("--tags <tags>","Comma-separated topic tags").option("--on-conflict <strategy>","Conflict resolution strategy (auto|skip|update|clone|error)","auto").action(async(e,t,n)=>{let s=n.optsWithGlobals(),o=t.github;if(o&&e&&(A()?$("import","INVALID_ARGS","Cannot use --github with a local path"):R("Error: Cannot use --github with a local path. Use one or the other."),process.exit(1)),!o&&!e&&(A()?$("import","INVALID_ARGS","Provide a local path or --github <url>"):R("Error: Provide a local path or --github <url>"),process.exit(1)),U()||(A()?$("import","AUTH_MISSING","Authentication required for import"):R("Error: Authentication required. Run 'shared-context-ai login' first."),process.exit(1)),o){t.onConflict&&t.onConflict!=="auto"&&(A()?$("import","INVALID_ARGS","--on-conflict is not supported with --github"):R("Error: --on-conflict is not supported with --github"),process.exit(1)),t.dryRun&&(A()?$("import","INVALID_ARGS","--dry-run is not supported with --github"):R("Error: --dry-run is not supported with --github"),process.exit(1));let m={url:o};t.resourceType&&(m.resourceType=t.resourceType),A()||w(`
160
+ Importing from GitHub: ${o}`);let E=await L("/api/cli/github-import",m);E.ok||(A()?$("import",E.error.code,E.error.message):R(`
161
+ Import failed: ${E.error.message}`),process.exit(1));let f=E.data;if(A()){F("import",f);return}w(""),w(` Source: ${f.source.owner}/${f.source.repo}`),w(` Type: ${f.resourceType}`),w(` Title: ${f.title}`),f.slug&&w(` Slug: ${f.slug}`),w(` URL: ${f.url}`),w(""),w("Import complete: 1 created");return}let l=(0,qo.resolve)(e);(!(0,or.existsSync)(l)||!(0,or.statSync)(l).isDirectory())&&(A()?$("import","INVALID_PATH",`Not a directory: ${l}`):R(`Error: Not a directory: ${l}`),process.exit(1));let c=pt(l);if(c.resources.length===0){A()?F("import",{resources:[],message:"No resources found"}):w("No resources found in the specified directory.");return}if(!A()){let m=new Map;for(let f of c.resources)m.set(f.resourceType,(m.get(f.resourceType)||0)+1);let E=[...m.entries()].map(([f,h])=>`${h} ${f}${h===1?"":"s"}`).join(", ");w(`
162
+ Discovered ${c.resources.length} resources in ${e}:`),w(` ${E}`),c.formatLabel&&c.pluginName?w(` ${c.formatLabel}: ${c.pluginName}`):c.pluginName&&w(` Plugin: ${c.pluginName}`)}let u=t.tags?t.tags.split(",").map(m=>m.trim()).filter(Boolean):void 0,a={dryRun:!!t.dryRun,onConflict:t.onConflict||"auto",visibility:t.visibility||"org",topicTags:u,resources:c.resources,collectionMemberships:c.collectionMemberships.length>0?c.collectionMemberships:void 0};!A()&&!t.dryRun?w(`
163
+ Executing import...`):A()||w(`
164
+ Dry run \u2014 previewing changes...`);let p=await L("/api/cli/import",a,12e4);p.ok||(A()?$("import",p.error.code,p.error.message):R(`
165
+ Import failed: ${p.error.message}`),process.exit(1));let S=p.data;if(A()){F("import",S);return}let I=[...S.created.map(m=>({...m,action:"created"})),...S.updated.map(m=>({...m,action:"updated"})),...S.installed.map(m=>({...m,action:"installed"})),...S.cloned.map(m=>({...m,action:"cloned"})),...S.skipped.map(m=>({...m,action:"skipped"})),...S.errors.map(m=>({...m,action:"error"}))];if(I.length>0){w("");let m=I.length,E=I.map((f,h)=>{let C=`[${String(h+1).padStart(String(m).length)}/${m}]`,i=(f.resourceType||"").padEnd(10),g=(f.importPath.split("/").pop()||"").padEnd(24),y="";switch(f.action){case"created":y=`\u2713 created${f.slug?` (slug: ${f.slug})`:""}`;break;case"updated":y="\u2713 updated";break;case"installed":{let b=f.versionsBehind;y=`\u2713 installed${b?` (${b} versions behind)`:""}`;break}case"cloned":y=`\u2713 cloned${f.slug?` (slug: ${f.slug})`:""}`;break;case"skipped":y=`\u2713 skipped (${f.reason||"up to date"})`;break;case"error":y=`\u2717 error: ${f.error||"unknown"}`;break}return` ${C} ${i} ${g} ${y}`});for(let f of E)w(f)}if(S.collections.length>0)for(let m of S.collections){let E=m.importPath.split("/").pop()||m.importPath;w(` collection ${E.padEnd(20)} \u2713 ${m.membersLinked} members linked${m.membersFailed>0?`, ${m.membersFailed} failed`:""}`)}w("");let d=[S.created.length>0?`${S.created.length} created`:null,S.installed.length>0?`${S.installed.length} installed`:null,S.cloned.length>0?`${S.cloned.length} cloned`:null,S.updated.length>0?`${S.updated.length} updated`:null,S.skipped.length>0?`${S.skipped.length} skipped`:null,S.errors.length>0?`${S.errors.length} errors`:null].filter(Boolean);t.dryRun?w(`Dry run complete: ${d.join(", ")}`):w(`Import complete: ${d.join(", ")}`),S.errors.length>0&&process.exit(1)})}var An=require("path"),Ko=require("os");ie();me();se();var qa={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Ga(r){let e=r.slug||r.resourceId;return`${qa[r.resourceType]||r.resourceType+"s"}/${e}`}function Xo(r){r.command("sync").description("Synchronize resource state \u2014 check for updates and discover untracked resources").option("--quiet","Minimal output (one-line summary)").option("--force","Bypass throttle and sync now").option("--no-import","Skip auto-importing untracked resources").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()};if(!n.force&&!Dr()){let x=z(),T=x.installations.filter(j=>j.latestSha&&j.sha&&j.latestSha!==j.sha),v=x.lastSyncAt?Math.floor((Date.now()-new Date(x.lastSyncAt).getTime())/6e4):void 0,N={updatesAvailable:T.length,untrackedResources:0,driftRepairs:0,updates:T.map(j=>({installPath:j.installPath,title:j.title,sha:j.sha,latestSha:j.latestSha})),untracked:[],summary:wn(T.length,0)+(v!==void 0?` (cached ${v}m ago, run --force to refresh)`:""),throttled:!0,cacheAge:v};bn(N,!!n.quiet);return}U()||(A()?$("sync","AUTH_MISSING","Login required to sync."):R("Login required. Run 'shared-context-ai login'."),process.exit(1));let s=Pe(n.agent),o=await Z("/api/cli/installed");if(!o.ok){let T=z().installations.filter(N=>N.latestSha&&N.sha&&N.latestSha!==N.sha);!A()&&!n.quiet&&R(`Warning: Could not reach server (${o.error.message}). Showing cached state.`);let v={updatesAvailable:T.length,untrackedResources:0,driftRepairs:0,updates:T.map(N=>({installPath:N.installPath,title:N.title,sha:N.sha,latestSha:N.latestSha})),untracked:[],summary:wn(T.length,0)+" (offline)",throttled:!1};bn(v,!!n.quiet);return}let l=o.data.installations,c=new Map(l.map(x=>[x.resourceId,x])),u=z(),a=0;for(let x of u.installations){let T=c.get(x.resourceId);if(T)x.latestSha=T.latestSha||void 0,x.resourceType=x.resourceType||T.resourceType,x.serverSynced=!0,T.installedSha&&x.sha&&T.installedSha!==x.sha&&(!A()&&!n.quiet&&w(` Drift repaired: ${x.installPath} (local=${x.sha.slice(0,7)} \u2192 server=${T.installedSha.slice(0,7)})`),x.sha=T.installedSha,a++),c.delete(x.resourceId);else if(x.serverSynced!==!1){let v=await L("/api/cli/install",{resourceId:x.resourceId,agentPlatform:s?.platform||"claude_code",installedSha:x.sha});v.ok?x.serverSynced=!0:(v.error.code==="NOT_FOUND"||v.error.code==="RESOURCE_NOT_FOUND")&&(x.serverSynced=!1,x.resourceId="",a++)}}u.installations=u.installations.filter(x=>x.resourceId!=="");let p=Array.from(c.values());if(p.length>0&&!A()&&!n.quiet){w(`
166
+ ${p.length} resource${p.length===1?"":"s"} installed elsewhere (web/other machine):`);for(let x of p.slice(0,5))w(` ${Ga(x)} \u2014 ${x.title}`);p.length>5&&w(` ...and ${p.length-5} more`)}Le(u);let S=s?[s]:He();S.length===0&&!A()&&!n.quiet&&R("No AI agents detected \u2014 resource discovery skipped. Use --agent to specify one.");let I=[],d=[],m=new Set;for(let x of S){let T=n.project?(0,An.join)(process.cwd(),x.dir):(0,An.join)((0,Ko.homedir)(),x.dir),v=pt(T,{settingsPath:Ee(x,!!n.project),mcpConfigPath:ae(x,!!n.project)});for(let N of v.resources)m.has(N.importPath)||(m.add(N.importPath),I.push(N));for(let N of v.collectionMemberships)m.has(`cm:${N.collectionImportPath}`)||(m.add(`cm:${N.collectionImportPath}`),d.push(N))}let E={resources:I,collectionMemberships:d},f=new Set(u.installations.map(x=>x.installPath)),h=new Map;for(let x of u.installations){let T=x.installPath.split("/"),v=T[0],N=T[T.length-1];h.has(v)||h.set(v,new Set),h.get(v).add(N)}let C=new Set([".claude-plugin"]),i=E.resources.filter(x=>{if(f.has(x.importPath))return!1;let T=x.importPath.split("/"),v=T[0],N=T[T.length-1];return!((v==="mcps"||v==="hooks")&&h.get(v)?.has(N)||x.importPath.startsWith(".")||C.has(N)||x.importPath.startsWith("plugins/"))});for(let x of i)x.description&&x.description.length>1e3&&(x.description=x.description.slice(0,997)+"...");let g=i.length;if(n.import!==!1&&i.length>0){let x={dryRun:!1,onConflict:"auto",visibility:"org",resources:i,collectionMemberships:E.collectionMemberships},T=await L("/api/cli/import",x,12e4);if(T.ok){let v=[...T.data.created,...T.data.updated,...T.data.installed],N=ke();for(let j of v){if(!j.id)continue;let M=s?.id||S[0]?.id;M&&(pe({resourceId:j.id,slug:j.slug||j.importPath.split("/").pop()||j.id,installPath:j.importPath,title:j.importPath.split("/").pop()||j.id,sha:j.commitSha||"",scope:n.project?"project":"global",agent:M,installedAt:new Date().toISOString(),resourceType:j.resourceType,serverSynced:!0,...N&&n.project?{projectId:N.projectId}:{}}),N&&n.project&&await L(`/api/cli/projects/${N.projectId}/resources`,{resourceId:j.id}).catch(()=>{}))}if(N&&n.project){let j=[...v,...T.data.skipped],M=0;for(let ne of j){let W=ne.id||ne.existingId;if(!W)continue;let Ae=await L(`/api/cli/projects/${N.projectId}/resources`,{resourceId:W});Ae.ok&&Ae.data.added&&M++}M>0&&!A()&&!n.quiet&&w(`
167
+ Project "${N.projectName}": registered ${M} resource${M===1?"":"s"}`)}if(!A()&&!n.quiet){if(v.length>0){w(`
168
+ Imported ${v.length} resource${v.length===1?"":"s"}:`);let j=v.map(M=>[` ${(M.resourceType||"").padEnd(12)}`,(M.slug||M.importPath.split("/").pop()||"").padEnd(24),M.importPath]);w(Se(j))}T.data.errors.length>0&&R(`
169
+ ${T.data.errors.length} import error(s)`)}i.length=0}else A()||R(`Import failed: ${T.error.message}`)}let y=ke(),b=0;if(y){let x=await Z(`/api/cli/projects/${y.projectId}/resources`);if(!x.ok)!A()&&!n.quiet&&(R(`Warning: Project "${y.projectName}" not found on server (may have been deleted).`),R(" Remove .shared-context/project.json to unlink this directory."));else{let T=x.data.project;T&&(T.name!==y.projectName||T.slug!==y.projectSlug)&&Qe({projectId:y.projectId,projectName:T.name,projectSlug:T.slug});let v=x.data.resources,N=u.installations.filter(ne=>ne.projectId===y.projectId),j=new Set(N.map(ne=>ne.resourceId)),M=v.filter(ne=>!j.has(ne.id));if(M.length>0)if(!s)!A()&&!n.quiet&&R(`
170
+ Project "${y.projectName}" has ${M.length} new resource${M.length===1?"":"s"} \u2014 use --agent to install them.`);else{let ne=De(s);for(let W of M){let Ae=W.installPath;try{let ue=await Z(`/api/cli/resource/${Ae}`);if(!ue.ok)continue;await ne.install(ue.data,"project",s),pe({resourceId:W.id,slug:W.slug||W.id,installPath:Ae,title:W.title,sha:W.latestSha||"",scope:"project",agent:s.id,installedAt:new Date().toISOString(),projectId:y.projectId,resourceType:W.resourceType,serverSynced:!0}),W.latestSha&&await L("/api/cli/install",{resourceId:W.id,agentPlatform:s.platform,installedSha:W.latestSha}).catch(()=>{}),b++}catch{}}!A()&&!n.quiet&&b>0&&w(`
171
+ Project "${y.projectName}": installed ${b} new resource${b===1?"":"s"}`)}if(n.project){let ne=new Set(v.map(ue=>ue.id)),W=new Set(E.resources.map(ue=>ue.importPath)),Ae=0;for(let ue of u.installations){if(ne.has(ue.resourceId)||!W.has(ue.installPath))continue;(await L(`/api/cli/projects/${y.projectId}/resources`,{resourceId:ue.resourceId})).ok&&(ue.projectId=y.projectId,Ae++)}Ae>0&&!A()&&!n.quiet&&w(`
172
+ Project "${y.projectName}": registered ${Ae} existing resource${Ae===1?"":"s"}`)}await L(`/api/cli/projects/${y.projectId}/sync`,{localPath:process.cwd()}).catch(()=>{})}}let _=g-i.length;if(n.force){let x=u.lastSyncAt;u.lastSyncAt=x||new Date().toISOString()}else u.lastSyncAt=new Date().toISOString();Le(u);let O=u.installations.filter(x=>x.latestSha&&x.sha&&x.latestSha!==x.sha),k=Ie();k?.connectionId&&L("/api/cli/sync-report",{connectionId:k.connectionId,lastSyncResult:{updatesAvailable:O.length,importedCount:_}}).catch(()=>{});try{let{pushTelemetry:x}=await Promise.resolve().then(()=>(Cn(),Jo));await x(!0)}catch{}let D={updatesAvailable:O.length,untrackedResources:i.length,driftRepairs:a,updates:O.map(x=>({installPath:x.installPath,title:x.title,sha:x.sha,latestSha:x.latestSha})),untracked:i.map(x=>({importPath:x.importPath,resourceType:x.resourceType,title:x.title})),summary:wn(O.length,i.length,a),throttled:!1};bn(D,!!n.quiet)})}function wn(r,e,t=0){let n=[];return r>0&&n.push(`${r} update${r===1?"":"s"} available`),e>0&&n.push(`${e} untracked resource${e===1?"":"s"}`),t>0&&n.push(`${t} drift repair${t===1?"":"s"}`),n.length===0?"Everything is up to date.":n.join(", ")}function bn(r,e){if(A()){F("sync",r);return}if(e){let t=r.summary;r.updatesAvailable>0&&(t+=" \u2014 run 'shared-context-ai update'"),r.untrackedResources>0&&(t+=` \u2014 ${r.untrackedResources} untracked`),w(t);return}if(w(""),r.updates.length>0){w(`${r.updates.length} update${r.updates.length===1?"":"s"} available:
173
+ `);let t=r.updates.map(n=>[` ${n.installPath}`,n.title,`${n.sha.slice(0,7)} \u2192 ${n.latestSha.slice(0,7)}`]);w(Se(t)),w("")}if(r.untracked.length>0){w(`${r.untracked.length} untracked resource${r.untracked.length===1?"":"s"}:
174
+ `);let t=r.untracked.map(n=>[` ${n.resourceType.padEnd(12)}`,n.importPath.padEnd(30),n.title]);w(Se(t)),w("")}r.updatesAvailable===0&&r.untrackedResources===0?w("Everything is up to date."):(r.updatesAvailable>0&&w("Run 'shared-context-ai update' to update installed resources."),r.untrackedResources>0&&w("Run 'shared-context-ai sync --force' to re-sync and import untracked resources.")),w("")}var Yo=require("path");ie();ie();se();function Qo(r){r.command("project").description("Manage projects").command("create").description("Create a project for the current folder").argument("[name]","Project name (defaults to folder name)").action(async t=>{if(!U()){let a="Not authenticated. Run 'shared-context-ai login' first.";A()?$("project create","AUTH_MISSING",a):R(a),process.exit(1)}let n=ke();if(n){A()?F("project create",{alreadyExists:!0,project:{id:n.projectId,name:n.projectName,slug:n.projectSlug}}):w(`Project already linked: ${n.projectName}`);return}let s=t?.trim()||(0,Yo.basename)(process.cwd());if(!s||s==="/"){let a='Could not determine project name. Provide one: shared-context-ai project create "My Project"';A()?$("project create","INVALID_NAME",a):R(a),process.exit(1)}let o=await L("/api/cli/projects",{name:s});o.ok||(A()?$("project create",o.error.code,o.error.message):R(`Failed to create project: ${o.error.message}`),process.exit(1));let{id:l,name:c,slug:u}=o.data;Qe({projectId:l,projectName:c,projectSlug:u}),A()?F("project create",{id:l,name:c,slug:u}):(w(`Created project: ${c}`),w(""),w("Quick reference:"),w(" shared-context-ai install <installPath> Add a resource to this project"),w(" shared-context-ai sync Check for resource updates"),w(" shared-context-ai status View project sync status"))})}Cn();var cr=require("fs"),ar=require("path"),_n=require("os");se();function za(){let r=process.env.SC_PROFILE;return r?(0,ar.join)((0,_n.homedir)(),".config","shared-context","profiles",r):(0,ar.join)((0,_n.homedir)(),".config","shared-context")}function Za(){let r=(0,ar.join)(za(),"usage.jsonl");if(!(0,cr.existsSync)(r))return[];try{let e=(0,cr.readFileSync)(r,"utf8").trim().split(`
175
+ `).filter(Boolean),t=[];for(let n of e)try{let s=JSON.parse(n);s.v&&s.ts&&s.event&&s.rid&&t.push(s)}catch{}return t}catch{return[]}}function ei(r){r.command("stats").description("Show local usage statistics").option("--days <n>","Number of days to show","7").action(e=>{let t=parseInt(e.days,10)||7,n=new Date;n.setDate(n.getDate()-t);let o=Za().filter(u=>new Date(u.ts)>=n);if(o.length===0){A()?F("stats",{days:t,events:0,skills:[],agents:[]}):w("No usage data yet");return}let l=new Map,c=new Map;for(let u of o)if(u.event==="skill_invoked"){let a=l.get(u.slug)||{count:0,ok:0};a.count++,u.ok&&a.ok++,l.set(u.slug,a)}else if(u.event==="agent_invoked"){let a=c.get(u.slug)||{count:0,ok:0,totalMs:0,totalTokens:0};a.count++,u.ok&&a.ok++,u.dur_ms&&(a.totalMs+=u.dur_ms),u.tokens&&(a.totalTokens+=u.tokens),c.set(u.slug,a)}if(A()){F("stats",{days:t,events:o.length,skills:[...l.entries()].map(([u,a])=>({slug:u,...a})),agents:[...c.entries()].map(([u,a])=>({slug:u,...a,avgMs:a.count>0?Math.round(a.totalMs/a.count):0,avgTokens:a.count>0?Math.round(a.totalTokens/a.count):0}))});return}if(w(`Usage over the last ${t} day${t===1?"":"s"} (${o.length} event${o.length===1?"":"s"})
176
+ `),l.size>0){w("Skills:");let u=[...l.entries()].sort((a,p)=>p[1].count-a[1].count).map(([a,p])=>[` ${a}`,`${p.count} use${p.count===1?"":"s"}`,`${Math.round(p.ok/p.count*100)}% ok`]);w(Se(u))}if(c.size>0){l.size>0&&w(""),w("Agents:");let u=[...c.entries()].sort((a,p)=>p[1].count-a[1].count).map(([a,p])=>{let S=p.count>0?Math.round(p.totalMs/p.count):0;return[` ${a}`,`${p.count} use${p.count===1?"":"s"}`,`${Math.round(p.ok/p.count*100)}% ok`,S>0?`avg ${(S/1e3).toFixed(1)}s`:""]});w(Se(u))}})}Kr();var ti={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."},lr=class extends Error{constructor(t,n){super(n||ti[t]);this.code=t;this.name="CliError"}code;get recovery(){return ti[this.code]}};se();var le=new Ln;le.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",r=>{let e=r.opts();Hn(!!e.json,!!e.human)});Ks(le);To(le);Po(le);Ls(le);No(le);jo(le);$o(le);Uo(le);Bo(le);Wo(le);Vo(le);Go(le);Xo(le);Qo(le);En(le);ei(le);Jr(le);process.on("uncaughtException",r=>{r instanceof lr?A()?$(process.argv[2]||"unknown",r.code,r.message):(R(`Error: ${r.message}`),R(r.recovery)):A()?$(process.argv[2]||"unknown","UNEXPECTED",r.message||"Unexpected error"):R(`Error: ${r.message||r}`),process.exit(1)});le.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shared-context-ai",
3
- "version": "0.1.20",
3
+ "version": "0.1.22",
4
4
  "description": "CLI for Shared Context - search, install, and manage AI skills",
5
5
  "bin": {
6
6
  "shared-context-ai": "dist/index.js"