bridge-agent 0.2.10 → 0.2.11

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 +31 -31
  2. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -1,46 +1,46 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var bs=Object.create;var at=Object.defineProperty;var Ss=Object.getOwnPropertyDescriptor;var ws=Object.getOwnPropertyNames;var Es=Object.getPrototypeOf,vs=Object.prototype.hasOwnProperty;var xs=(r,e)=>()=>(r&&(e=r(r=0)),e);var v=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ks=(r,e)=>{for(var t in e)at(r,t,{get:e[t],enumerable:!0})},Os=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ws(e))!vs.call(r,s)&&s!==t&&at(r,s,{get:()=>e[s],enumerable:!(n=Ss(e,s))||n.enumerable});return r};var y=(r,e,t)=>(t=r!=null?bs(Es(r)):{},Os(e||!r||!r.__esModule?at(t,"default",{value:r,enumerable:!0}):t,r));var me=v(lt=>{var Re=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}},ct=class extends Re{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};lt.CommanderError=Re;lt.InvalidArgumentError=ct});var Le=v(ut=>{var{InvalidArgumentError:Is}=me(),dt=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 Is(`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 As(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}ut.Argument=dt;ut.humanReadableArgName=As});var ft=v(cr=>{var{humanReadableArgName:Cs}=Le(),ht=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}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,i)=>s.name().localeCompare(i.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),i=n.long&&e._findOption(n.long);!s&&!i?t.push(n):n.long&&!i?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(i=>!i.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=>Cs(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,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,t.argumentTerm(s).length),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,i=2,o=2;function c(f,p){if(p){let _=`${f.padEnd(n+o)}${p}`;return t.wrap(_,s-i,n+o)}return f}function a(f){return f.join(`
2
+ "use strict";var xs=Object.create;var dt=Object.defineProperty;var ks=Object.getOwnPropertyDescriptor;var Os=Object.getOwnPropertyNames;var Cs=Object.getPrototypeOf,Is=Object.prototype.hasOwnProperty;var As=(r,e)=>()=>(r&&(e=r(r=0)),e);var v=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ps=(r,e)=>{for(var t in e)dt(r,t,{get:e[t],enumerable:!0})},Ts=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Os(e))!Is.call(r,s)&&s!==t&&dt(r,s,{get:()=>e[s],enumerable:!(n=ks(e,s))||n.enumerable});return r};var _=(r,e,t)=>(t=r!=null?xs(Cs(r)):{},Ts(e||!r||!r.__esModule?dt(t,"default",{value:r,enumerable:!0}):t,r));var me=v(ht=>{var Le=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}},ut=class extends Le{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ht.CommanderError=Le;ht.InvalidArgumentError=ut});var Me=v(pt=>{var{InvalidArgumentError:Ns}=me(),ft=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 Ns(`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 Ds(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}pt.Argument=ft;pt.humanReadableArgName=Ds});var mt=v(ur=>{var{humanReadableArgName:Rs}=Me(),gt=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}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,i)=>s.name().localeCompare(i.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),i=n.long&&e._findOption(n.long);!s&&!i?t.push(n):n.long&&!i?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(i=>!i.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=>Rs(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,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,t.argumentTerm(s).length),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,i=2,o=2;function c(f,p){if(p){let y=`${f.padEnd(n+o)}${p}`;return t.wrap(y,s-i,n+o)}return f}function a(f){return f.join(`
3
3
  `).replace(/^/gm," ".repeat(i))}let l=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(l=l.concat([t.wrap(d,s,0),""]));let u=t.visibleArguments(e).map(f=>c(t.argumentTerm(f),t.argumentDescription(f)));u.length>0&&(l=l.concat(["Arguments:",a(u),""]));let h=t.visibleOptions(e).map(f=>c(t.optionTerm(f),t.optionDescription(f)));if(h.length>0&&(l=l.concat(["Options:",a(h),""])),this.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(p=>c(t.optionTerm(p),t.optionDescription(p)));f.length>0&&(l=l.concat(["Global Options:",a(f),""]))}let g=t.visibleCommands(e).map(f=>c(t.subcommandTerm(f),t.subcommandDescription(f)));return g.length>0&&(l=l.concat(["Commands:",a(g),""])),l.join(`
4
4
  `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let c=t-n;if(c<s)return e;let a=e.slice(0,n),l=e.slice(n).replace(`\r
5
5
  `,`
6
6
  `),d=" ".repeat(n),h="\\s\u200B",g=new RegExp(`
7
- |.{1,${c-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),f=l.match(g)||[];return a+f.map((p,_)=>p===`
8
- `?"":(_>0?d:"")+p.trimEnd()).join(`
9
- `)}};cr.Help=ht});var _t=v(mt=>{var{InvalidArgumentError:Ts}=me(),pt=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=Ns(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 Ts(`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 Ps(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},gt=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,i=s!==void 0?s:!1;return t.negate===(i===e)}};function Ps(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ns(r){let e,t,n=r.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}mt.Option=pt;mt.DualOptions=gt});var dr=v(lr=>{function Ds(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 i=1;r[s-1]===e[n-1]?i=0:i=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+i),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 Rs(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(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let c=Ds(r,o),a=Math.max(r.length,o.length);(a-c)/a>i&&(c<s?(s=c,n=[o]):c===s&&n.push(o))}),n.sort((o,c)=>o.localeCompare(c)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
7
+ |.{1,${c-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),f=l.match(g)||[];return a+f.map((p,y)=>p===`
8
+ `?"":(y>0?d:"")+p.trimEnd()).join(`
9
+ `)}};ur.Help=gt});var wt=v(bt=>{var{InvalidArgumentError:Ls}=me(),_t=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=js(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 Ls(`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 Ms(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},yt=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,i=s!==void 0?s:!1;return t.negate===(i===e)}};function Ms(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function js(r){let e,t,n=r.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}bt.Option=_t;bt.DualOptions=yt});var fr=v(hr=>{function Bs(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 i=1;r[s-1]===e[n-1]?i=0:i=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+i),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 $s(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(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let c=Bs(r,o),a=Math.max(r.length,o.length);(a-c)/a>i&&(c<s?(s=c,n=[o]):c===s&&n.push(o))}),n.sort((o,c)=>o.localeCompare(c)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
10
10
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
11
- (Did you mean ${n[0]}?)`:""}lr.suggestSimilar=Rs});var gr=v(pr=>{var Ls=require("node:events").EventEmitter,yt=require("node:child_process"),B=require("node:path"),bt=require("node:fs"),x=require("node:process"),{Argument:Ms,humanReadableArgName:js}=Le(),{CommanderError:St}=me(),{Help:$s}=ft(),{Option:ur,DualOptions:Bs}=_t(),{suggestSimilar:hr}=dr(),wt=class r extends Ls{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,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._outputConfiguration={writeOut:t=>x.stdout.write(t),writeErr:t=>x.stderr.write(t),getOutHelpWidth:()=>x.stdout.isTTY?x.stdout.columns:void 0,getErrHelpWidth:()=>x.stderr.isTTY?x.stderr.columns:void 0,outputError:(t,n)=>n(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,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,c]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return s&&(a.description(s),a._executableHandler=!0),i.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(i.noHelp||i.hidden),a._executableFile=i.executableFile||null,c&&a.arguments(c),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),s?this:a}createCommand(e){return new r(e)}createHelp(){return Object.assign(new $s,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
12
- - 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 Ms(e,t)}argument(e,t,n,s){let i=this.createArgument(e,t);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),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(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
- 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 St(e,t,n)),x.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new ur(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_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}'
14
- - 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("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' 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 i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,c)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let a=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,a,o):i!==null&&e.variadic&&(i=e._concatValue(i,a)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,c)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,n,s,i){if(typeof t=="object"&&t instanceof ur)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let c=s;s=(a,l)=>{let d=c.exec(a);return d?d[0]:l},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}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){x.versions?.electron&&(t.from="electron");let s=x.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=x.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":x.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){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,u){let h=B.resolve(d,u);if(bt.existsSync(h))return h;if(s.includes(B.extname(u)))return;let g=s.find(f=>bt.existsSync(`${h}${f}`));if(g)return`${h}${g}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let d;try{d=bt.realpathSync(this._scriptPath)}catch{d=this._scriptPath}c=B.resolve(B.dirname(d),c)}if(c){let d=i(c,o);if(!d&&!e._executableFile&&this._scriptPath){let u=B.basename(this._scriptPath,B.extname(this._scriptPath));u!==this._name&&(d=i(c,`${u}-${e._name}`))}o=d||o}n=s.includes(B.extname(o));let a;x.platform!=="win32"?n?(t.unshift(o),t=fr(x.execArgv).concat(t),a=yt.spawn(x.argv[0],t,{stdio:"inherit"})):a=yt.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=fr(x.execArgv).concat(t),a=yt.spawn(x.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{x.on(u,()=>{a.killed===!1&&a.exitCode===null&&a.kill(u)})});let l=this._exitCallback;a.on("close",d=>{d=d??1,l?l(new St(d,"commander.executeSubCommandAsync","(close)")):x.exit(d)}),a.on("error",d=>{if(d.code==="ENOENT"){let u=c?`searched for local subcommand relative to directory '${c}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
11
+ (Did you mean ${n[0]}?)`:""}hr.suggestSimilar=$s});var yr=v(_r=>{var Us=require("node:events").EventEmitter,St=require("node:child_process"),$=require("node:path"),Et=require("node:fs"),x=require("node:process"),{Argument:Ws,humanReadableArgName:Fs}=Me(),{CommanderError:vt}=me(),{Help:Hs}=mt(),{Option:pr,DualOptions:qs}=wt(),{suggestSimilar:gr}=fr(),xt=class r extends Us{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,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._outputConfiguration={writeOut:t=>x.stdout.write(t),writeErr:t=>x.stderr.write(t),getOutHelpWidth:()=>x.stdout.isTTY?x.stdout.columns:void 0,getErrHelpWidth:()=>x.stderr.isTTY?x.stderr.columns:void 0,outputError:(t,n)=>n(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,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,c]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return s&&(a.description(s),a._executableHandler=!0),i.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(i.noHelp||i.hidden),a._executableFile=i.executableFile||null,c&&a.arguments(c),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),s?this:a}createCommand(e){return new r(e)}createHelp(){return Object.assign(new Hs,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
12
+ - 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 Ws(e,t)}argument(e,t,n,s){let i=this.createArgument(e,t);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),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(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
+ 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 vt(e,t,n)),x.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new pr(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_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}'
14
+ - 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("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' 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 i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,c)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let a=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,a,o):i!==null&&e.variadic&&(i=e._concatValue(i,a)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,c)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,n,s,i){if(typeof t=="object"&&t instanceof pr)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let c=s;s=(a,l)=>{let d=c.exec(a);return d?d[0]:l},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}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){x.versions?.electron&&(t.from="electron");let s=x.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=x.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":x.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){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,u){let h=$.resolve(d,u);if(Et.existsSync(h))return h;if(s.includes($.extname(u)))return;let g=s.find(f=>Et.existsSync(`${h}${f}`));if(g)return`${h}${g}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let d;try{d=Et.realpathSync(this._scriptPath)}catch{d=this._scriptPath}c=$.resolve($.dirname(d),c)}if(c){let d=i(c,o);if(!d&&!e._executableFile&&this._scriptPath){let u=$.basename(this._scriptPath,$.extname(this._scriptPath));u!==this._name&&(d=i(c,`${u}-${e._name}`))}o=d||o}n=s.includes($.extname(o));let a;x.platform!=="win32"?n?(t.unshift(o),t=mr(x.execArgv).concat(t),a=St.spawn(x.argv[0],t,{stdio:"inherit"})):a=St.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=mr(x.execArgv).concat(t),a=St.spawn(x.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{x.on(u,()=>{a.killed===!1&&a.exitCode===null&&a.kill(u)})});let l=this._exitCallback;a.on("close",d=>{d=d??1,l?l(new vt(d,"commander.executeSubCommandAsync","(close)")):x.exit(d)}),a.on("error",d=>{if(d.code==="ENOENT"){let u=c?`searched for local subcommand relative to directory '${c}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
15
15
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
16
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${u}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)x.exit(1);else{let u=new St(1,"commander.executeSubCommandAsync","(error)");u.nestedError=d,l(u)}}),this.runningCommand=a}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),i}_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,i)=>{let o=s;if(s!==null&&n.parseArg){let c=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,c)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,c)=>e(n,c,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),t[s]=i}),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(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(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])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,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(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,i=e.slice();function o(a){return a.length>1&&a[0]==="-"}let c=null;for(;i.length;){let a=i.shift();if(a==="--"){s===n&&s.push(a),s.push(...i);break}if(c&&!o(a)){this.emit(`option:${c.name()}`,a);continue}if(c=null,o(a)){let l=this._findOption(a);if(l){if(l.required){let d=i.shift();d===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,d)}else if(l.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${l.name()}`,d)}else this.emit(`option:${l.name()}`);c=l.variadic?l:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let l=this._findOption(`-${a[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,a.slice(2)):(this.emit(`option:${l.name()}`),i.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let l=a.indexOf("="),d=this._findOption(a.slice(0,l));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,a.slice(l+1));continue}}if(o(a)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(a)){t.push(a),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(a),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(a),i.length>0&&s.push(...i);break}s.push(a)}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}
17
+ - ${u}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)x.exit(1);else{let u=new vt(1,"commander.executeSubCommandAsync","(error)");u.nestedError=d,l(u)}}),this.runningCommand=a}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),i}_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,i)=>{let o=s;if(s!==null&&n.parseArg){let c=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,c)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,c)=>e(n,c,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),t[s]=i}),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(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(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])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,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(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,i=e.slice();function o(a){return a.length>1&&a[0]==="-"}let c=null;for(;i.length;){let a=i.shift();if(a==="--"){s===n&&s.push(a),s.push(...i);break}if(c&&!o(a)){this.emit(`option:${c.name()}`,a);continue}if(c=null,o(a)){let l=this._findOption(a);if(l){if(l.required){let d=i.shift();d===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,d)}else if(l.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${l.name()}`,d)}else this.emit(`option:${l.name()}`);c=l.variadic?l:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let l=this._findOption(`-${a[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,a.slice(2)):(this.emit(`option:${l.name()}`),i.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let l=a.indexOf("="),d=this._findOption(a.slice(0,l));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,a.slice(l+1));continue}}if(o(a)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(a)){t.push(a),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(a),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(a),i.length>0&&s.push(...i);break}s.push(a)}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}
18
18
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
19
19
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
20
- `),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in x.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()}`,x.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Bs(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=o=>{let c=o.attributeName(),a=this.getOptionValue(c),l=this.options.find(u=>u.negate&&c===u.attributeName()),d=this.options.find(u=>!u.negate&&c===u.attributeName());return l&&(l.presetArg===void 0&&a===!1||l.presetArg!==void 0&&a===l.presetArg)?l:d||o},s=o=>{let c=n(o),a=c.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${c.envVar}'`:`option '${c.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(c=>c.long).map(c=>c.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=hr(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",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=hr(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}
21
- `),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=>js(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=B.basename(e,B.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=x.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.
20
+ `),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in x.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()}`,x.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new qs(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=o=>{let c=o.attributeName(),a=this.getOptionValue(c),l=this.options.find(u=>u.negate&&c===u.attributeName()),d=this.options.find(u=>!u.negate&&c===u.attributeName());return l&&(l.presetArg===void 0&&a===!1||l.presetArg!==void 0&&a===l.presetArg)?l:d||o},s=o=>{let c=n(o),a=c.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${c.envVar}'`:`option '${c.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(c=>c.long).map(c=>c.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=gr(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",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=gr(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}
21
+ `),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=>Fs(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=$.basename(e,$.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=x.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.
22
22
  Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
23
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function fr(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}pr.Command=wt});var br=v(P=>{var{Argument:mr}=Le(),{Command:Et}=gr(),{CommanderError:Us,InvalidArgumentError:_r}=me(),{Help:Ws}=ft(),{Option:yr}=_t();P.program=new Et;P.createCommand=r=>new Et(r);P.createOption=(r,e)=>new yr(r,e);P.createArgument=(r,e)=>new mr(r,e);P.Command=Et;P.Option=yr;P.Argument=mr;P.Help=Ws;P.CommanderError=Us;P.InvalidArgumentError=_r;P.InvalidOptionArgumentError=_r});var Ir=v(O=>{"use strict";var vt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Fs=vt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.sync=r.isexe=void 0;var e=require("node:fs"),t=require("node:fs/promises"),n=async(c,a={})=>{let{ignoreErrors:l=!1}=a;try{return i(await(0,t.stat)(c),a)}catch(d){let u=d;if(l||u.code==="EACCES")return!1;throw u}};r.isexe=n;var s=(c,a={})=>{let{ignoreErrors:l=!1}=a;try{return i((0,e.statSync)(c),a)}catch(d){let u=d;if(l||u.code==="EACCES")return!1;throw u}};r.sync=s;var i=(c,a)=>c.isFile()&&o(c,a),o=(c,a)=>{let l=a.uid??process.getuid?.(),d=a.groups??process.getgroups?.()??[],u=a.gid??process.getgid?.()??d[0];if(l===void 0||u===void 0)throw new Error("cannot get uid or gid");let h=new Set([u,...d]),g=c.mode,f=c.uid,p=c.gid,_=parseInt("100",8),k=parseInt("010",8),E=parseInt("001",8),m=_|k;return!!(g&E||g&k&&h.has(p)||g&_&&f===l||g&m&&l===0)}}),qs=vt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.sync=r.isexe=void 0;var e=require("node:fs"),t=require("node:fs/promises"),n=require("node:path"),s=async(a,l={})=>{let{ignoreErrors:d=!1}=l;try{return c(await(0,t.stat)(a),a,l)}catch(u){let h=u;if(d||h.code==="EACCES")return!1;throw h}};r.isexe=s;var i=(a,l={})=>{let{ignoreErrors:d=!1}=l;try{return c((0,e.statSync)(a),a,l)}catch(u){let h=u;if(d||h.code==="EACCES")return!1;throw h}};r.sync=i;var o=(a,l)=>{let{pathExt:d=process.env.PATHEXT||""}=l,u=d.split(n.delimiter);if(u.indexOf("")!==-1)return!0;for(let h of u){let g=h.toLowerCase(),f=a.substring(a.length-g.length).toLowerCase();if(g&&f===g)return!0}return!1},c=(a,l,d)=>a.isFile()&&o(l,d)}),Vs=vt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0})}),Er=O&&O.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Hs=O&&O.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),vr=O&&O.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&Er(t,e,n[s]);return Hs(t,e),t}})(),Gs=O&&O.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Er(e,r,t)};Object.defineProperty(O,"__esModule",{value:!0});O.sync=O.isexe=O.posix=O.win32=void 0;var xr=vr(Fs());O.posix=xr;var kr=vr(qs());O.win32=kr;Gs(Vs(),O);var Ks=process.env._ISEXE_TEST_PLATFORM_||process.platform,Or=Ks==="win32"?kr:xr;O.isexe=Or.isexe;O.sync=Or.sync});var jr=v((Ra,Mr)=>{var{isexe:Ys,sync:zs}=Ir(),{join:Js,delimiter:Xs,sep:Ar,posix:Cr}=require("path"),Tr=process.platform==="win32",Pr=new RegExp(`[${Cr.sep}${Ar===Cr.sep?"":Ar}]`.replace(/(\\)/g,"\\$1")),Qs=new RegExp(`^\\.${Pr.source}`),Nr=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),Dr=(r,{path:e=process.env.PATH,pathExt:t=process.env.PATHEXT,delimiter:n=Xs})=>{let s=r.match(Pr)?[""]:[...Tr?[process.cwd()]:[],...(e||"").split(n)];if(Tr){let i=t||[".EXE",".CMD",".BAT",".COM"].join(n),o=i.split(n).flatMap(c=>[c,c.toLowerCase()]);return r.includes(".")&&o[0]!==""&&o.unshift(""),{pathEnv:s,pathExt:o,pathExtExe:i}}return{pathEnv:s,pathExt:[""]}},Rr=(r,e)=>{let t=/^".*"$/.test(r)?r.slice(1,-1):r;return(!t&&Qs.test(e)?e.slice(0,2):"")+Js(t,e)},Lr=async(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=Dr(r,e),i=[];for(let o of t){let c=Rr(o,r);for(let a of n){let l=c+a;if(await Ys(l,{pathExt:s,ignoreErrors:!0})){if(!e.all)return l;i.push(l)}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw Nr(r)},Zs=(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=Dr(r,e),i=[];for(let o of t){let c=Rr(o,r);for(let a of n){let l=c+a;if(zs(l,{pathExt:s,ignoreErrors:!0})){if(!e.all)return l;i.push(l)}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw Nr(r)};Mr.exports=Lr;Lr.sync=Zs});var U=v(($a,Vr)=>{"use strict";var Fr=["nodebuffer","arraybuffer","fragments"],qr=typeof Blob<"u";qr&&Fr.push("blob");Vr.exports={BINARY_TYPES:Fr,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:qr,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ye=v((Ba,Ue)=>{"use strict";var{EMPTY_BUFFER:ni}=U(),It=Buffer[Symbol.species];function si(r,e){if(r.length===0)return ni;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new It(t.buffer,t.byteOffset,n):t}function Hr(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function Gr(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function ii(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function At(r){if(At.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new It(r):ArrayBuffer.isView(r)?e=new It(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),At.readOnly=!1),e}Ue.exports={concat:si,mask:Hr,toArrayBuffer:ii,toBuffer:At,unmask:Gr};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Ue.exports.mask=function(e,t,n,s,i){i<48?Hr(e,t,n,s,i):r.mask(e,t,n,s,i)},Ue.exports.unmask=function(e,t){e.length<32?Gr(e,t):r.unmask(e,t)}}catch{}});var zr=v((Ua,Yr)=>{"use strict";var Kr=Symbol("kDone"),Ct=Symbol("kRun"),Tt=class{constructor(e){this[Kr]=()=>{this.pending--,this[Ct]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ct]()}[Ct](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Kr])}}};Yr.exports=Tt});var le=v((Wa,Zr)=>{"use strict";var be=require("zlib"),Jr=ye(),oi=zr(),{kStatusCode:Xr}=U(),ai=Buffer[Symbol.species],ci=Buffer.from([0,0,255,255]),Fe=Symbol("permessage-deflate"),W=Symbol("total-length"),ae=Symbol("callback"),H=Symbol("buffers"),ce=Symbol("error"),We,Pt=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!We){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;We=new oi(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ae];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){We.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){We.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?be.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=be.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Fe]=this,this._inflate[W]=0,this._inflate[H]=[],this._inflate.on("error",di),this._inflate.on("data",Qr)}this._inflate[ae]=n,this._inflate.write(e),t&&this._inflate.write(ci),this._inflate.flush(()=>{let i=this._inflate[ce];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=Jr.concat(this._inflate[H],this._inflate[W]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[W]=0,this._inflate[H]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?be.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=be.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[W]=0,this._deflate[H]=[],this._deflate.on("data",li)}this._deflate[ae]=n,this._deflate.write(e),this._deflate.flush(be.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Jr.concat(this._deflate[H],this._deflate[W]);t&&(i=new ai(i.buffer,i.byteOffset,i.length-4)),this._deflate[ae]=null,this._deflate[W]=0,this._deflate[H]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};Zr.exports=Pt;function li(r){this[H].push(r),this[W]+=r.length}function Qr(r){if(this[W]+=r.length,this[Fe]._maxPayload<1||this[W]<=this[Fe]._maxPayload){this[H].push(r);return}this[ce]=new RangeError("Max payload size exceeded"),this[ce].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ce][Xr]=1009,this.removeListener("data",Qr),this.reset()}function di(r){if(this[Fe]._inflate=null,this[ce]){this[ae](this[ce]);return}r[Xr]=1007,this[ae](r)}});var de=v((Fa,qe)=>{"use strict";var{isUtf8:en}=require("buffer"),{hasBlob:ui}=U(),hi=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function fi(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Nt(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function pi(r){return ui&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}qe.exports={isBlob:pi,isValidStatusCode:fi,isValidUTF8:Nt,tokenChars:hi};if(en)qe.exports.isValidUTF8=function(r){return r.length<24?Nt(r):en(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");qe.exports.isValidUTF8=function(e){return e.length<32?Nt(e):r(e)}}catch{}});var jt=v((qa,cn)=>{"use strict";var{Writable:gi}=require("stream"),tn=le(),{BINARY_TYPES:mi,EMPTY_BUFFER:rn,kStatusCode:_i,kWebSocket:yi}=U(),{concat:Dt,toArrayBuffer:bi,unmask:Si}=ye(),{isValidStatusCode:wi,isValidUTF8:nn}=de(),Ve=Buffer[Symbol.species],N=0,sn=1,on=2,an=3,Rt=4,Lt=5,He=6,Mt=class extends gi{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||mi[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[yi]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=N}_write(e,t,n){if(this._opcode===8&&this._state==N)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Ve(n.buffer,n.byteOffset+e,n.length-e),new Ve(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Ve(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case N:this.getInfo(e);break;case sn:this.getPayloadLength16(e);break;case on:this.getPayloadLength64(e);break;case an:this.getMask();break;case Rt:this.getData(e);break;case Lt:case He:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[tn.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=sn:this._payloadLength===127?this._state=on:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=an:this._state=Rt}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Rt}getData(e){let t=rn;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Si(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Lt,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[tn.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===N&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=N;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Dt(n,t):this._binaryType==="arraybuffer"?s=bi(Dt(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=N):(this._state=He,setImmediate(()=>{this.emit("message",s,!0),this._state=N,this.startLoop(e)}))}else{let s=Dt(n,t);if(!this._skipUTF8Validation&&!nn(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Lt||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=N):(this._state=He,setImmediate(()=>{this.emit("message",s,!1),this._state=N,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,rn),this.end();else{let n=e.readUInt16BE(0);if(!wi(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Ve(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!nn(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=N;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=N):(this._state=He,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=N,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[_i]=s,o}};cn.exports=Mt});var Ut=v((Ha,un)=>{"use strict";var{Duplex:Va}=require("stream"),{randomFillSync:Ei}=require("crypto"),ln=le(),{EMPTY_BUFFER:vi,kWebSocket:xi,NOOP:ki}=U(),{isBlob:ue,isValidStatusCode:Oi}=de(),{mask:dn,toBuffer:J}=ye(),D=Symbol("kByteLength"),Ii=Buffer.alloc(4),Ge=8*1024,X,he=Ge,L=0,Ai=1,Ci=2,$t=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=L,this.onerror=ki,this[xi]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||Ii,t.generateMask?t.generateMask(n):(he===Ge&&(X===void 0&&(X=Buffer.alloc(Ge)),Ei(X,0,Ge),he=0),n[0]=X[he++],n[1]=X[he++],n[2]=X[he++],n[3]=X[he++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof e=="string"?(!t.mask||o)&&t[D]!==void 0?c=t[D]:(e=Buffer.from(e),c=e.length):(c=e.length,s=t.mask&&t.readOnly&&!o);let a=c;c>=65536?(i+=8,a=127):c>125&&(i+=2,a=126);let l=Buffer.allocUnsafe(s?c+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=a,a===126?l.writeUInt16BE(c,2):a===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),t.mask?(l[1]|=128,l[i-4]=n[0],l[i-3]=n[1],l[i-2]=n[2],l[i-1]=n[3],o?[l,e]:s?(dn(e,n,l,i,c),[l]):(dn(e,n,e,0,c),[l,e])):[l,e]}close(e,t,n,s){let i;if(e===void 0)i=vi;else{if(typeof e!="number"||!Oi(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let o={[D]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==L?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ue(e)?(s=e.size,i=!1):(e=J(e),s=e.length,i=J.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[D]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ue(e)?this._state!==L?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==L?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ue(e)?(s=e.size,i=!1):(e=J(e),s=e.length,i=J.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[D]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ue(e)?this._state!==L?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==L?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[ln.extensionName],i=t.binary?2:1,o=t.compress,c,a;typeof e=="string"?(c=Buffer.byteLength(e),a=!1):ue(e)?(c=e.size,a=!1):(e=J(e),c=e.length,a=J.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=c>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[D]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:a,rsv1:o};ue(e)?this._state!==L?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==L?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[D],this._state=Ci,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Bt,this,c,s);return}this._bufferedBytes-=n[D];let o=J(i);t?this.dispatch(o,t,n,s):(this._state=L,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(Ti,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[ln.extensionName];this._bufferedBytes+=n[D],this._state=Ai,i.compress(e,n.fin,(o,c)=>{if(this._socket.destroyed){let a=new Error("The socket was closed while data was being compressed");Bt(this,a,s);return}this._bufferedBytes-=n[D],this._state=L,n.readOnly=!1,this.sendFrame(r.frame(c,n),s),this.dequeue()})}dequeue(){for(;this._state===L&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][D],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][D],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};un.exports=$t;function Bt(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function Ti(r,e,t){Bt(r,e,t),r.onerror(e)}});var Sn=v((Ga,bn)=>{"use strict";var{kForOnEventAttribute:Se,kListener:Wt}=U(),hn=Symbol("kCode"),fn=Symbol("kData"),pn=Symbol("kError"),gn=Symbol("kMessage"),mn=Symbol("kReason"),fe=Symbol("kTarget"),_n=Symbol("kType"),yn=Symbol("kWasClean"),F=class{constructor(e){this[fe]=null,this[_n]=e}get target(){return this[fe]}get type(){return this[_n]}};Object.defineProperty(F.prototype,"target",{enumerable:!0});Object.defineProperty(F.prototype,"type",{enumerable:!0});var Q=class extends F{constructor(e,t={}){super(e),this[hn]=t.code===void 0?0:t.code,this[mn]=t.reason===void 0?"":t.reason,this[yn]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[hn]}get reason(){return this[mn]}get wasClean(){return this[yn]}};Object.defineProperty(Q.prototype,"code",{enumerable:!0});Object.defineProperty(Q.prototype,"reason",{enumerable:!0});Object.defineProperty(Q.prototype,"wasClean",{enumerable:!0});var pe=class extends F{constructor(e,t={}){super(e),this[pn]=t.error===void 0?null:t.error,this[gn]=t.message===void 0?"":t.message}get error(){return this[pn]}get message(){return this[gn]}};Object.defineProperty(pe.prototype,"error",{enumerable:!0});Object.defineProperty(pe.prototype,"message",{enumerable:!0});var we=class extends F{constructor(e,t={}){super(e),this[fn]=t.data===void 0?null:t.data}get data(){return this[fn]}};Object.defineProperty(we.prototype,"data",{enumerable:!0});var Pi={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[Se]&&s[Wt]===e&&!s[Se])return;let n;if(r==="message")n=function(i,o){let c=new we("message",{data:o?i:i.toString()});c[fe]=this,Ke(e,this,c)};else if(r==="close")n=function(i,o){let c=new Q("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[fe]=this,Ke(e,this,c)};else if(r==="error")n=function(i){let o=new pe("error",{error:i,message:i.message});o[fe]=this,Ke(e,this,o)};else if(r==="open")n=function(){let i=new F("open");i[fe]=this,Ke(e,this,i)};else return;n[Se]=!!t[Se],n[Wt]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[Wt]===e&&!t[Se]){this.removeListener(r,t);break}}};bn.exports={CloseEvent:Q,ErrorEvent:pe,Event:F,EventTarget:Pi,MessageEvent:we};function Ke(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Ye=v((Ka,wn)=>{"use strict";var{tokenChars:Ee}=de();function j(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Ni(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,c,a=-1,l=-1,d=-1,u=0;for(;u<r.length;u++)if(l=r.charCodeAt(u),o===void 0)if(d===-1&&Ee[l]===1)a===-1&&(a=u);else if(u!==0&&(l===32||l===9))d===-1&&a!==-1&&(d=u);else if(l===59||l===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let g=r.slice(a,d);l===44?(j(e,g,t),t=Object.create(null)):o=g,a=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===void 0)if(d===-1&&Ee[l]===1)a===-1&&(a=u);else if(l===32||l===9)d===-1&&a!==-1&&(d=u);else if(l===59||l===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u),j(t,r.slice(a,d),!0),l===44&&(j(e,o,t),t=Object.create(null),o=void 0),a=d=-1}else if(l===61&&a!==-1&&d===-1)c=r.slice(a,u),a=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(Ee[l]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);a===-1?a=u:n||(n=!0),s=!1}else if(i)if(Ee[l]===1)a===-1&&(a=u);else if(l===34&&a!==-1)i=!1,d=u;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(l===34&&r.charCodeAt(u-1)===61)i=!0;else if(d===-1&&Ee[l]===1)a===-1&&(a=u);else if(a!==-1&&(l===32||l===9))d===-1&&(d=u);else if(l===59||l===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let g=r.slice(a,d);n&&(g=g.replace(/\\/g,""),n=!1),j(t,c,g),l===44&&(j(e,o,t),t=Object.create(null),o=void 0),c=void 0,a=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(a===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=u);let h=r.slice(a,d);return o===void 0?j(e,h,t):(c===void 0?j(t,h,!0):n?j(t,c,h.replace(/\\/g,"")):j(t,c,h),j(e,o,t)),e}function Di(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}wn.exports={format:Di,parse:Ni}});var Qe=v((Ja,Dn)=>{"use strict";var Ri=require("events"),Li=require("https"),Mi=require("http"),xn=require("net"),ji=require("tls"),{randomBytes:$i,createHash:Bi}=require("crypto"),{Duplex:Ya,Readable:za}=require("stream"),{URL:Ft}=require("url"),G=le(),Ui=jt(),Wi=Ut(),{isBlob:Fi}=de(),{BINARY_TYPES:En,CLOSE_TIMEOUT:qi,EMPTY_BUFFER:ze,GUID:Vi,kForOnEventAttribute:qt,kListener:Hi,kStatusCode:Gi,kWebSocket:A,NOOP:kn}=U(),{EventTarget:{addEventListener:Ki,removeEventListener:Yi}}=Sn(),{format:zi,parse:Ji}=Ye(),{toBuffer:Xi}=ye(),On=Symbol("kAborted"),Vt=[8,13],q=["CONNECTING","OPEN","CLOSING","CLOSED"],Qi=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,w=class r extends Ri{constructor(e,t,n){super(),this._binaryType=En[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ze,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),In(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){En.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new Ui({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new Wi(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[A]=this,i[A]=this,e[A]=this,s.on("conclude",to),s.on("drain",ro),s.on("error",no),s.on("message",so),s.on("ping",io),s.on("pong",oo),i.onerror=ao,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Tn),e.on("data",Xe),e.on("end",Pn),e.on("error",Nn),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[G.extensionName]&&this._extensions[G.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){C(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Cn(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ht(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||ze,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ht(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||ze,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ht(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[G.extensionName]||(s.compress=!1),this._sender.send(e||ze,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){C(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(w,"CONNECTING",{enumerable:!0,value:q.indexOf("CONNECTING")});Object.defineProperty(w.prototype,"CONNECTING",{enumerable:!0,value:q.indexOf("CONNECTING")});Object.defineProperty(w,"OPEN",{enumerable:!0,value:q.indexOf("OPEN")});Object.defineProperty(w.prototype,"OPEN",{enumerable:!0,value:q.indexOf("OPEN")});Object.defineProperty(w,"CLOSING",{enumerable:!0,value:q.indexOf("CLOSING")});Object.defineProperty(w.prototype,"CLOSING",{enumerable:!0,value:q.indexOf("CLOSING")});Object.defineProperty(w,"CLOSED",{enumerable:!0,value:q.indexOf("CLOSED")});Object.defineProperty(w.prototype,"CLOSED",{enumerable:!0,value:q.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(w.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(w.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[qt])return e[Hi];return null},set(e){for(let t of this.listeners(r))if(t[qt]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[qt]:!0})}})});w.prototype.addEventListener=Ki;w.prototype.removeEventListener=Yi;Dn.exports=w;function In(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:qi,protocolVersion:Vt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!Vt.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Vt.join(", ")})`);let i;if(e instanceof Ft)i=e;else try{i=new Ft(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",c=i.protocol==="ws+unix:",a;if(i.protocol!=="ws:"&&!o&&!c?a=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?a="The URL's pathname is empty":i.hash&&(a="The URL contains a fragment identifier"),a){let p=new SyntaxError(a);if(r._redirects===0)throw p;Je(r,p);return}let l=o?443:80,d=$i(16).toString("base64"),u=o?Li.request:Mi.request,h=new Set,g;if(s.createConnection=s.createConnection||(o?eo:Zi),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(g=new G({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=zi({[G.extensionName]:g.offer()})),t.length){for(let p of t){if(typeof p!="string"||!Qi.test(p)||h.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(p)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),c){let p=s.path.split(":");s.socketPath=p[0],s.path=p[1]}let f;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=o,r._originalHostOrSocketPath=c?s.socketPath:i.host;let p=n&&n.headers;if(n={...n,headers:{}},p)for(let[_,k]of Object.entries(p))n.headers[_.toLowerCase()]=k}else if(r.listenerCount("redirect")===0){let p=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!p||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,p||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),f=r._req=u(s),r._redirects&&r.emit("redirect",r.url,f)}else f=r._req=u(s);s.timeout&&f.on("timeout",()=>{C(r,f,"Opening handshake has timed out")}),f.on("error",p=>{f===null||f[On]||(f=r._req=null,Je(r,p))}),f.on("response",p=>{let _=p.headers.location,k=p.statusCode;if(_&&s.followRedirects&&k>=300&&k<400){if(++r._redirects>s.maxRedirects){C(r,f,"Maximum redirects exceeded");return}f.abort();let E;try{E=new Ft(_,e)}catch{let S=new SyntaxError(`Invalid URL: ${_}`);Je(r,S);return}In(r,E,t,n)}else r.emit("unexpected-response",f,p)||C(r,f,`Unexpected server response: ${p.statusCode}`)}),f.on("upgrade",(p,_,k)=>{if(r.emit("upgrade",p),r.readyState!==w.CONNECTING)return;f=r._req=null;let E=p.headers.upgrade;if(E===void 0||E.toLowerCase()!=="websocket"){C(r,_,"Invalid Upgrade header");return}let m=Bi("sha1").update(d+Vi).digest("base64");if(p.headers["sec-websocket-accept"]!==m){C(r,_,"Invalid Sec-WebSocket-Accept header");return}let S=p.headers["sec-websocket-protocol"],b;if(S!==void 0?h.size?h.has(S)||(b="Server sent an invalid subprotocol"):b="Server sent a subprotocol but none was requested":h.size&&(b="Server sent no subprotocol"),b){C(r,_,b);return}S&&(r._protocol=S);let R=p.headers["sec-websocket-extensions"];if(R!==void 0){if(!g){C(r,_,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let z;try{z=Ji(R)}catch{C(r,_,"Invalid Sec-WebSocket-Extensions header");return}let De=Object.keys(z);if(De.length!==1||De[0]!==G.extensionName){C(r,_,"Server indicated an extension that was not requested");return}try{g.accept(z[G.extensionName])}catch{C(r,_,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[G.extensionName]=g}r.setSocket(_,k,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(f,r):f.end()}function Je(r,e){r._readyState=w.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Zi(r){return r.path=r.socketPath,xn.connect(r)}function eo(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=xn.isIP(r.host)?"":r.host),ji.connect(r)}function C(r,e,t){r._readyState=w.CLOSING;let n=new Error(t);Error.captureStackTrace(n,C),e.setHeader?(e[On]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Je,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Ht(r,e,t){if(e){let n=Fi(e)?e.size:Xi(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${q[r.readyState]})`);process.nextTick(t,n)}}function to(r,e){let t=this[A];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[A]!==void 0&&(t._socket.removeListener("data",Xe),process.nextTick(An,t._socket),r===1005?t.close():t.close(r,e))}function ro(){let r=this[A];r.isPaused||r._socket.resume()}function no(r){let e=this[A];e._socket[A]!==void 0&&(e._socket.removeListener("data",Xe),process.nextTick(An,e._socket),e.close(r[Gi])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function vn(){this[A].emitClose()}function so(r,e){this[A].emit("message",r,e)}function io(r){let e=this[A];e._autoPong&&e.pong(r,!this._isServer,kn),e.emit("ping",r)}function oo(r){this[A].emit("pong",r)}function An(r){r.resume()}function ao(r){let e=this[A];e.readyState!==w.CLOSED&&(e.readyState===w.OPEN&&(e._readyState=w.CLOSING,Cn(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Cn(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function Tn(){let r=this[A];if(this.removeListener("close",Tn),this.removeListener("data",Xe),this.removeListener("end",Pn),r._readyState=w.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[A]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",vn),r._receiver.on("finish",vn))}function Xe(r){this[A]._receiver.write(r)||this.pause()}function Pn(){let r=this[A];r._readyState=w.CLOSING,r._receiver.end(),this.end()}function Nn(){let r=this[A];this.removeListener("error",Nn),this.on("error",kn),r&&(r._readyState=w.CLOSING,this.destroy())}});var jn=v((Qa,Mn)=>{"use strict";var Xa=Qe(),{Duplex:co}=require("stream");function Rn(r){r.emit("close")}function lo(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ln(r){this.removeListener("error",Ln),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function uo(r,e){let t=!0,n=new co({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let c=!o&&n._readableState.objectMode?i.toString():i;n.push(c)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(Rn,n);return}let o=!1;r.once("error",function(a){o=!0,i(a)}),r.once("close",function(){o||i(s),process.nextTick(Rn,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",lo),n.on("error",Ln),n}Mn.exports=uo});var Gt=v((Za,$n)=>{"use strict";var{tokenChars:ho}=de();function fo(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&ho[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let c=r.slice(t,n);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}$n.exports={parse:fo}});var Hn=v((tc,Vn)=>{"use strict";var po=require("events"),Ze=require("http"),{Duplex:ec}=require("stream"),{createHash:go}=require("crypto"),Bn=Ye(),Z=le(),mo=Gt(),_o=Qe(),{CLOSE_TIMEOUT:yo,GUID:bo,kWebSocket:So}=U(),wo=/^[+/0-9A-Za-z]{22}==$/,Un=0,Wn=1,qn=2,Kt=class extends po{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:yo,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:_o,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Ze.createServer((n,s)=>{let i=Ze.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Eo(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Un}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===qn){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ve,this);return}if(e&&this.once("close",e),this._state!==Wn)if(this._state=Wn,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ve,this):process.nextTick(ve,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{ve(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Fn);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ee(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ee(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!wo.test(i)){ee(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){ee(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){xe(t,400);return}let a=e.headers["sec-websocket-protocol"],l=new Set;if(a!==void 0)try{l=mo.parse(a)}catch{ee(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let h=new Z({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Bn.parse(d);g[Z.extensionName]&&(h.accept(g[Z.extensionName]),u[Z.extensionName]=h)}catch{ee(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(g,f,p,_)=>{if(!g)return xe(t,f||401,p,_);this.completeUpgrade(u,i,l,e,t,n,s)});return}if(!this.options.verifyClient(h))return xe(t,401)}this.completeUpgrade(u,i,l,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,c){if(!i.readable||!i.writable)return i.destroy();if(i[So])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Un)return xe(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${go("sha1").update(t+bo).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let u=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;u&&(l.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[Z.extensionName]){let u=e[Z.extensionName].params,h=Bn.format({[Z.extensionName]:[u]});l.push(`Sec-WebSocket-Extensions: ${h}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
23
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function mr(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}_r.Command=xt});var Er=v(T=>{var{Argument:br}=Me(),{Command:kt}=yr(),{CommanderError:Vs,InvalidArgumentError:wr}=me(),{Help:Gs}=mt(),{Option:Sr}=wt();T.program=new kt;T.createCommand=r=>new kt(r);T.createOption=(r,e)=>new Sr(r,e);T.createArgument=(r,e)=>new br(r,e);T.Command=kt;T.Option=Sr;T.Argument=br;T.Help=Gs;T.CommanderError=Vs;T.InvalidArgumentError=wr;T.InvalidOptionArgumentError=wr});var Pr=v(O=>{"use strict";var Ot=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ks=Ot(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.sync=r.isexe=void 0;var e=require("node:fs"),t=require("node:fs/promises"),n=async(c,a={})=>{let{ignoreErrors:l=!1}=a;try{return i(await(0,t.stat)(c),a)}catch(d){let u=d;if(l||u.code==="EACCES")return!1;throw u}};r.isexe=n;var s=(c,a={})=>{let{ignoreErrors:l=!1}=a;try{return i((0,e.statSync)(c),a)}catch(d){let u=d;if(l||u.code==="EACCES")return!1;throw u}};r.sync=s;var i=(c,a)=>c.isFile()&&o(c,a),o=(c,a)=>{let l=a.uid??process.getuid?.(),d=a.groups??process.getgroups?.()??[],u=a.gid??process.getgid?.()??d[0];if(l===void 0||u===void 0)throw new Error("cannot get uid or gid");let h=new Set([u,...d]),g=c.mode,f=c.uid,p=c.gid,y=parseInt("100",8),k=parseInt("010",8),E=parseInt("001",8),m=y|k;return!!(g&E||g&k&&h.has(p)||g&y&&f===l||g&m&&l===0)}}),Ys=Ot(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.sync=r.isexe=void 0;var e=require("node:fs"),t=require("node:fs/promises"),n=require("node:path"),s=async(a,l={})=>{let{ignoreErrors:d=!1}=l;try{return c(await(0,t.stat)(a),a,l)}catch(u){let h=u;if(d||h.code==="EACCES")return!1;throw h}};r.isexe=s;var i=(a,l={})=>{let{ignoreErrors:d=!1}=l;try{return c((0,e.statSync)(a),a,l)}catch(u){let h=u;if(d||h.code==="EACCES")return!1;throw h}};r.sync=i;var o=(a,l)=>{let{pathExt:d=process.env.PATHEXT||""}=l,u=d.split(n.delimiter);if(u.indexOf("")!==-1)return!0;for(let h of u){let g=h.toLowerCase(),f=a.substring(a.length-g.length).toLowerCase();if(g&&f===g)return!0}return!1},c=(a,l,d)=>a.isFile()&&o(l,d)}),zs=Ot(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0})}),kr=O&&O.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Js=O&&O.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Or=O&&O.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&kr(t,e,n[s]);return Js(t,e),t}})(),Xs=O&&O.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&kr(e,r,t)};Object.defineProperty(O,"__esModule",{value:!0});O.sync=O.isexe=O.posix=O.win32=void 0;var Cr=Or(Ks());O.posix=Cr;var Ir=Or(Ys());O.win32=Ir;Xs(zs(),O);var Qs=process.env._ISEXE_TEST_PLATFORM_||process.platform,Ar=Qs==="win32"?Ir:Cr;O.isexe=Ar.isexe;O.sync=Ar.sync});var Ur=v((Wa,$r)=>{var{isexe:Zs,sync:ei}=Pr(),{join:ti,delimiter:ri,sep:Tr,posix:Nr}=require("path"),Dr=process.platform==="win32",Rr=new RegExp(`[${Nr.sep}${Tr===Nr.sep?"":Tr}]`.replace(/(\\)/g,"\\$1")),ni=new RegExp(`^\\.${Rr.source}`),Lr=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),Mr=(r,{path:e=process.env.PATH,pathExt:t=process.env.PATHEXT,delimiter:n=ri})=>{let s=r.match(Rr)?[""]:[...Dr?[process.cwd()]:[],...(e||"").split(n)];if(Dr){let i=t||[".EXE",".CMD",".BAT",".COM"].join(n),o=i.split(n).flatMap(c=>[c,c.toLowerCase()]);return r.includes(".")&&o[0]!==""&&o.unshift(""),{pathEnv:s,pathExt:o,pathExtExe:i}}return{pathEnv:s,pathExt:[""]}},jr=(r,e)=>{let t=/^".*"$/.test(r)?r.slice(1,-1):r;return(!t&&ni.test(e)?e.slice(0,2):"")+ti(t,e)},Br=async(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=Mr(r,e),i=[];for(let o of t){let c=jr(o,r);for(let a of n){let l=c+a;if(await Zs(l,{pathExt:s,ignoreErrors:!0})){if(!e.all)return l;i.push(l)}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw Lr(r)},si=(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=Mr(r,e),i=[];for(let o of t){let c=jr(o,r);for(let a of n){let l=c+a;if(ei(l,{pathExt:s,ignoreErrors:!0})){if(!e.all)return l;i.push(l)}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw Lr(r)};$r.exports=Br;Br.sync=si});var U=v((Va,Kr)=>{"use strict";var Vr=["nodebuffer","arraybuffer","fragments"],Gr=typeof Blob<"u";Gr&&Vr.push("blob");Kr.exports={BINARY_TYPES:Vr,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Gr,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ye=v((Ga,We)=>{"use strict";var{EMPTY_BUFFER:ci}=U(),Pt=Buffer[Symbol.species];function li(r,e){if(r.length===0)return ci;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new Pt(t.buffer,t.byteOffset,n):t}function Yr(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function zr(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function di(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Tt(r){if(Tt.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Pt(r):ArrayBuffer.isView(r)?e=new Pt(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Tt.readOnly=!1),e}We.exports={concat:li,mask:Yr,toArrayBuffer:di,toBuffer:Tt,unmask:zr};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");We.exports.mask=function(e,t,n,s,i){i<48?Yr(e,t,n,s,i):r.mask(e,t,n,s,i)},We.exports.unmask=function(e,t){e.length<32?zr(e,t):r.unmask(e,t)}}catch{}});var Qr=v((Ka,Xr)=>{"use strict";var Jr=Symbol("kDone"),Nt=Symbol("kRun"),Dt=class{constructor(e){this[Jr]=()=>{this.pending--,this[Nt]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Nt]()}[Nt](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Jr])}}};Xr.exports=Dt});var le=v((Ya,rn)=>{"use strict";var be=require("zlib"),Zr=ye(),ui=Qr(),{kStatusCode:en}=U(),hi=Buffer[Symbol.species],fi=Buffer.from([0,0,255,255]),He=Symbol("permessage-deflate"),W=Symbol("total-length"),ae=Symbol("callback"),V=Symbol("buffers"),ce=Symbol("error"),Fe,Rt=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Fe){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Fe=new ui(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ae];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){Fe.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Fe.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?be.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=be.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[He]=this,this._inflate[W]=0,this._inflate[V]=[],this._inflate.on("error",gi),this._inflate.on("data",tn)}this._inflate[ae]=n,this._inflate.write(e),t&&this._inflate.write(fi),this._inflate.flush(()=>{let i=this._inflate[ce];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=Zr.concat(this._inflate[V],this._inflate[W]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[W]=0,this._inflate[V]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?be.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=be.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[W]=0,this._deflate[V]=[],this._deflate.on("data",pi)}this._deflate[ae]=n,this._deflate.write(e),this._deflate.flush(be.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Zr.concat(this._deflate[V],this._deflate[W]);t&&(i=new hi(i.buffer,i.byteOffset,i.length-4)),this._deflate[ae]=null,this._deflate[W]=0,this._deflate[V]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};rn.exports=Rt;function pi(r){this[V].push(r),this[W]+=r.length}function tn(r){if(this[W]+=r.length,this[He]._maxPayload<1||this[W]<=this[He]._maxPayload){this[V].push(r);return}this[ce]=new RangeError("Max payload size exceeded"),this[ce].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ce][en]=1009,this.removeListener("data",tn),this.reset()}function gi(r){if(this[He]._inflate=null,this[ce]){this[ae](this[ce]);return}r[en]=1007,this[ae](r)}});var de=v((za,qe)=>{"use strict";var{isUtf8:nn}=require("buffer"),{hasBlob:mi}=U(),_i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function yi(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Lt(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function bi(r){return mi&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}qe.exports={isBlob:bi,isValidStatusCode:yi,isValidUTF8:Lt,tokenChars:_i};if(nn)qe.exports.isValidUTF8=function(r){return r.length<24?Lt(r):nn(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");qe.exports.isValidUTF8=function(e){return e.length<32?Lt(e):r(e)}}catch{}});var Ut=v((Ja,un)=>{"use strict";var{Writable:wi}=require("stream"),sn=le(),{BINARY_TYPES:Si,EMPTY_BUFFER:on,kStatusCode:Ei,kWebSocket:vi}=U(),{concat:Mt,toArrayBuffer:xi,unmask:ki}=ye(),{isValidStatusCode:Oi,isValidUTF8:an}=de(),Ve=Buffer[Symbol.species],N=0,cn=1,ln=2,dn=3,jt=4,Bt=5,Ge=6,$t=class extends wi{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Si[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[vi]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=N}_write(e,t,n){if(this._opcode===8&&this._state==N)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Ve(n.buffer,n.byteOffset+e,n.length-e),new Ve(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Ve(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case N:this.getInfo(e);break;case cn:this.getPayloadLength16(e);break;case ln:this.getPayloadLength64(e);break;case dn:this.getMask();break;case jt:this.getData(e);break;case Bt:case Ge:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[sn.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=cn:this._payloadLength===127?this._state=ln:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=dn:this._state=jt}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=jt}getData(e){let t=on;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&ki(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Bt,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[sn.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===N&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=N;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Mt(n,t):this._binaryType==="arraybuffer"?s=xi(Mt(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=N):(this._state=Ge,setImmediate(()=>{this.emit("message",s,!0),this._state=N,this.startLoop(e)}))}else{let s=Mt(n,t);if(!this._skipUTF8Validation&&!an(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Bt||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=N):(this._state=Ge,setImmediate(()=>{this.emit("message",s,!1),this._state=N,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,on),this.end();else{let n=e.readUInt16BE(0);if(!Oi(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Ve(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!an(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=N;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=N):(this._state=Ge,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=N,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Ei]=s,o}};un.exports=$t});var Ht=v((Qa,pn)=>{"use strict";var{Duplex:Xa}=require("stream"),{randomFillSync:Ci}=require("crypto"),hn=le(),{EMPTY_BUFFER:Ii,kWebSocket:Ai,NOOP:Pi}=U(),{isBlob:ue,isValidStatusCode:Ti}=de(),{mask:fn,toBuffer:J}=ye(),D=Symbol("kByteLength"),Ni=Buffer.alloc(4),Ke=8*1024,X,he=Ke,L=0,Di=1,Ri=2,Wt=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=L,this.onerror=Pi,this[Ai]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||Ni,t.generateMask?t.generateMask(n):(he===Ke&&(X===void 0&&(X=Buffer.alloc(Ke)),Ci(X,0,Ke),he=0),n[0]=X[he++],n[1]=X[he++],n[2]=X[he++],n[3]=X[he++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof e=="string"?(!t.mask||o)&&t[D]!==void 0?c=t[D]:(e=Buffer.from(e),c=e.length):(c=e.length,s=t.mask&&t.readOnly&&!o);let a=c;c>=65536?(i+=8,a=127):c>125&&(i+=2,a=126);let l=Buffer.allocUnsafe(s?c+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=a,a===126?l.writeUInt16BE(c,2):a===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),t.mask?(l[1]|=128,l[i-4]=n[0],l[i-3]=n[1],l[i-2]=n[2],l[i-1]=n[3],o?[l,e]:s?(fn(e,n,l,i,c),[l]):(fn(e,n,e,0,c),[l,e])):[l,e]}close(e,t,n,s){let i;if(e===void 0)i=Ii;else{if(typeof e!="number"||!Ti(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let o={[D]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==L?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ue(e)?(s=e.size,i=!1):(e=J(e),s=e.length,i=J.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[D]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ue(e)?this._state!==L?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==L?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ue(e)?(s=e.size,i=!1):(e=J(e),s=e.length,i=J.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[D]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ue(e)?this._state!==L?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==L?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[hn.extensionName],i=t.binary?2:1,o=t.compress,c,a;typeof e=="string"?(c=Buffer.byteLength(e),a=!1):ue(e)?(c=e.size,a=!1):(e=J(e),c=e.length,a=J.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=c>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[D]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:a,rsv1:o};ue(e)?this._state!==L?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==L?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[D],this._state=Ri,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Ft,this,c,s);return}this._bufferedBytes-=n[D];let o=J(i);t?this.dispatch(o,t,n,s):(this._state=L,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(Li,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[hn.extensionName];this._bufferedBytes+=n[D],this._state=Di,i.compress(e,n.fin,(o,c)=>{if(this._socket.destroyed){let a=new Error("The socket was closed while data was being compressed");Ft(this,a,s);return}this._bufferedBytes-=n[D],this._state=L,n.readOnly=!1,this.sendFrame(r.frame(c,n),s),this.dequeue()})}dequeue(){for(;this._state===L&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][D],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][D],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};pn.exports=Wt;function Ft(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function Li(r,e,t){Ft(r,e,t),r.onerror(e)}});var vn=v((Za,En)=>{"use strict";var{kForOnEventAttribute:we,kListener:qt}=U(),gn=Symbol("kCode"),mn=Symbol("kData"),_n=Symbol("kError"),yn=Symbol("kMessage"),bn=Symbol("kReason"),fe=Symbol("kTarget"),wn=Symbol("kType"),Sn=Symbol("kWasClean"),F=class{constructor(e){this[fe]=null,this[wn]=e}get target(){return this[fe]}get type(){return this[wn]}};Object.defineProperty(F.prototype,"target",{enumerable:!0});Object.defineProperty(F.prototype,"type",{enumerable:!0});var Q=class extends F{constructor(e,t={}){super(e),this[gn]=t.code===void 0?0:t.code,this[bn]=t.reason===void 0?"":t.reason,this[Sn]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[gn]}get reason(){return this[bn]}get wasClean(){return this[Sn]}};Object.defineProperty(Q.prototype,"code",{enumerable:!0});Object.defineProperty(Q.prototype,"reason",{enumerable:!0});Object.defineProperty(Q.prototype,"wasClean",{enumerable:!0});var pe=class extends F{constructor(e,t={}){super(e),this[_n]=t.error===void 0?null:t.error,this[yn]=t.message===void 0?"":t.message}get error(){return this[_n]}get message(){return this[yn]}};Object.defineProperty(pe.prototype,"error",{enumerable:!0});Object.defineProperty(pe.prototype,"message",{enumerable:!0});var Se=class extends F{constructor(e,t={}){super(e),this[mn]=t.data===void 0?null:t.data}get data(){return this[mn]}};Object.defineProperty(Se.prototype,"data",{enumerable:!0});var Mi={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[we]&&s[qt]===e&&!s[we])return;let n;if(r==="message")n=function(i,o){let c=new Se("message",{data:o?i:i.toString()});c[fe]=this,Ye(e,this,c)};else if(r==="close")n=function(i,o){let c=new Q("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[fe]=this,Ye(e,this,c)};else if(r==="error")n=function(i){let o=new pe("error",{error:i,message:i.message});o[fe]=this,Ye(e,this,o)};else if(r==="open")n=function(){let i=new F("open");i[fe]=this,Ye(e,this,i)};else return;n[we]=!!t[we],n[qt]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[qt]===e&&!t[we]){this.removeListener(r,t);break}}};En.exports={CloseEvent:Q,ErrorEvent:pe,Event:F,EventTarget:Mi,MessageEvent:Se};function Ye(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var ze=v((ec,xn)=>{"use strict";var{tokenChars:Ee}=de();function j(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function ji(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,c,a=-1,l=-1,d=-1,u=0;for(;u<r.length;u++)if(l=r.charCodeAt(u),o===void 0)if(d===-1&&Ee[l]===1)a===-1&&(a=u);else if(u!==0&&(l===32||l===9))d===-1&&a!==-1&&(d=u);else if(l===59||l===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let g=r.slice(a,d);l===44?(j(e,g,t),t=Object.create(null)):o=g,a=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===void 0)if(d===-1&&Ee[l]===1)a===-1&&(a=u);else if(l===32||l===9)d===-1&&a!==-1&&(d=u);else if(l===59||l===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u),j(t,r.slice(a,d),!0),l===44&&(j(e,o,t),t=Object.create(null),o=void 0),a=d=-1}else if(l===61&&a!==-1&&d===-1)c=r.slice(a,u),a=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(Ee[l]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);a===-1?a=u:n||(n=!0),s=!1}else if(i)if(Ee[l]===1)a===-1&&(a=u);else if(l===34&&a!==-1)i=!1,d=u;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(l===34&&r.charCodeAt(u-1)===61)i=!0;else if(d===-1&&Ee[l]===1)a===-1&&(a=u);else if(a!==-1&&(l===32||l===9))d===-1&&(d=u);else if(l===59||l===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let g=r.slice(a,d);n&&(g=g.replace(/\\/g,""),n=!1),j(t,c,g),l===44&&(j(e,o,t),t=Object.create(null),o=void 0),c=void 0,a=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(a===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=u);let h=r.slice(a,d);return o===void 0?j(e,h,t):(c===void 0?j(t,h,!0):n?j(t,c,h.replace(/\\/g,"")):j(t,c,h),j(e,o,t)),e}function Bi(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}xn.exports={format:Bi,parse:ji}});var Ze=v((nc,Mn)=>{"use strict";var $i=require("events"),Ui=require("https"),Wi=require("http"),Cn=require("net"),Fi=require("tls"),{randomBytes:Hi,createHash:qi}=require("crypto"),{Duplex:tc,Readable:rc}=require("stream"),{URL:Vt}=require("url"),G=le(),Vi=Ut(),Gi=Ht(),{isBlob:Ki}=de(),{BINARY_TYPES:kn,CLOSE_TIMEOUT:Yi,EMPTY_BUFFER:Je,GUID:zi,kForOnEventAttribute:Gt,kListener:Ji,kStatusCode:Xi,kWebSocket:I,NOOP:In}=U(),{EventTarget:{addEventListener:Qi,removeEventListener:Zi}}=vn(),{format:eo,parse:to}=ze(),{toBuffer:ro}=ye(),An=Symbol("kAborted"),Kt=[8,13],H=["CONNECTING","OPEN","CLOSING","CLOSED"],no=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,S=class r extends $i{constructor(e,t,n){super(),this._binaryType=kn[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Je,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Pn(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){kn.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new Vi({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new Gi(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[I]=this,i[I]=this,e[I]=this,s.on("conclude",oo),s.on("drain",ao),s.on("error",co),s.on("message",lo),s.on("ping",uo),s.on("pong",ho),i.onerror=fo,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Dn),e.on("data",Qe),e.on("end",Rn),e.on("error",Ln),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[G.extensionName]&&this._extensions[G.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){A(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Nn(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Yt(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Je,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Yt(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Je,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Yt(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[G.extensionName]||(s.compress=!1),this._sender.send(e||Je,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){A(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(S,"CONNECTING",{enumerable:!0,value:H.indexOf("CONNECTING")});Object.defineProperty(S.prototype,"CONNECTING",{enumerable:!0,value:H.indexOf("CONNECTING")});Object.defineProperty(S,"OPEN",{enumerable:!0,value:H.indexOf("OPEN")});Object.defineProperty(S.prototype,"OPEN",{enumerable:!0,value:H.indexOf("OPEN")});Object.defineProperty(S,"CLOSING",{enumerable:!0,value:H.indexOf("CLOSING")});Object.defineProperty(S.prototype,"CLOSING",{enumerable:!0,value:H.indexOf("CLOSING")});Object.defineProperty(S,"CLOSED",{enumerable:!0,value:H.indexOf("CLOSED")});Object.defineProperty(S.prototype,"CLOSED",{enumerable:!0,value:H.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(S.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(S.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Gt])return e[Ji];return null},set(e){for(let t of this.listeners(r))if(t[Gt]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Gt]:!0})}})});S.prototype.addEventListener=Qi;S.prototype.removeEventListener=Zi;Mn.exports=S;function Pn(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Yi,protocolVersion:Kt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!Kt.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Kt.join(", ")})`);let i;if(e instanceof Vt)i=e;else try{i=new Vt(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",c=i.protocol==="ws+unix:",a;if(i.protocol!=="ws:"&&!o&&!c?a=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?a="The URL's pathname is empty":i.hash&&(a="The URL contains a fragment identifier"),a){let p=new SyntaxError(a);if(r._redirects===0)throw p;Xe(r,p);return}let l=o?443:80,d=Hi(16).toString("base64"),u=o?Ui.request:Wi.request,h=new Set,g;if(s.createConnection=s.createConnection||(o?io:so),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(g=new G({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=eo({[G.extensionName]:g.offer()})),t.length){for(let p of t){if(typeof p!="string"||!no.test(p)||h.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(p)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),c){let p=s.path.split(":");s.socketPath=p[0],s.path=p[1]}let f;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=o,r._originalHostOrSocketPath=c?s.socketPath:i.host;let p=n&&n.headers;if(n={...n,headers:{}},p)for(let[y,k]of Object.entries(p))n.headers[y.toLowerCase()]=k}else if(r.listenerCount("redirect")===0){let p=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!p||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,p||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),f=r._req=u(s),r._redirects&&r.emit("redirect",r.url,f)}else f=r._req=u(s);s.timeout&&f.on("timeout",()=>{A(r,f,"Opening handshake has timed out")}),f.on("error",p=>{f===null||f[An]||(f=r._req=null,Xe(r,p))}),f.on("response",p=>{let y=p.headers.location,k=p.statusCode;if(y&&s.followRedirects&&k>=300&&k<400){if(++r._redirects>s.maxRedirects){A(r,f,"Maximum redirects exceeded");return}f.abort();let E;try{E=new Vt(y,e)}catch{let w=new SyntaxError(`Invalid URL: ${y}`);Xe(r,w);return}Pn(r,E,t,n)}else r.emit("unexpected-response",f,p)||A(r,f,`Unexpected server response: ${p.statusCode}`)}),f.on("upgrade",(p,y,k)=>{if(r.emit("upgrade",p),r.readyState!==S.CONNECTING)return;f=r._req=null;let E=p.headers.upgrade;if(E===void 0||E.toLowerCase()!=="websocket"){A(r,y,"Invalid Upgrade header");return}let m=qi("sha1").update(d+zi).digest("base64");if(p.headers["sec-websocket-accept"]!==m){A(r,y,"Invalid Sec-WebSocket-Accept header");return}let w=p.headers["sec-websocket-protocol"],b;if(w!==void 0?h.size?h.has(w)||(b="Server sent an invalid subprotocol"):b="Server sent a subprotocol but none was requested":h.size&&(b="Server sent no subprotocol"),b){A(r,y,b);return}w&&(r._protocol=w);let R=p.headers["sec-websocket-extensions"];if(R!==void 0){if(!g){A(r,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let z;try{z=to(R)}catch{A(r,y,"Invalid Sec-WebSocket-Extensions header");return}let Re=Object.keys(z);if(Re.length!==1||Re[0]!==G.extensionName){A(r,y,"Server indicated an extension that was not requested");return}try{g.accept(z[G.extensionName])}catch{A(r,y,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[G.extensionName]=g}r.setSocket(y,k,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(f,r):f.end()}function Xe(r,e){r._readyState=S.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function so(r){return r.path=r.socketPath,Cn.connect(r)}function io(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Cn.isIP(r.host)?"":r.host),Fi.connect(r)}function A(r,e,t){r._readyState=S.CLOSING;let n=new Error(t);Error.captureStackTrace(n,A),e.setHeader?(e[An]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Xe,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Yt(r,e,t){if(e){let n=Ki(e)?e.size:ro(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${H[r.readyState]})`);process.nextTick(t,n)}}function oo(r,e){let t=this[I];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[I]!==void 0&&(t._socket.removeListener("data",Qe),process.nextTick(Tn,t._socket),r===1005?t.close():t.close(r,e))}function ao(){let r=this[I];r.isPaused||r._socket.resume()}function co(r){let e=this[I];e._socket[I]!==void 0&&(e._socket.removeListener("data",Qe),process.nextTick(Tn,e._socket),e.close(r[Xi])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function On(){this[I].emitClose()}function lo(r,e){this[I].emit("message",r,e)}function uo(r){let e=this[I];e._autoPong&&e.pong(r,!this._isServer,In),e.emit("ping",r)}function ho(r){this[I].emit("pong",r)}function Tn(r){r.resume()}function fo(r){let e=this[I];e.readyState!==S.CLOSED&&(e.readyState===S.OPEN&&(e._readyState=S.CLOSING,Nn(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Nn(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function Dn(){let r=this[I];if(this.removeListener("close",Dn),this.removeListener("data",Qe),this.removeListener("end",Rn),r._readyState=S.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[I]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",On),r._receiver.on("finish",On))}function Qe(r){this[I]._receiver.write(r)||this.pause()}function Rn(){let r=this[I];r._readyState=S.CLOSING,r._receiver.end(),this.end()}function Ln(){let r=this[I];this.removeListener("error",Ln),this.on("error",In),r&&(r._readyState=S.CLOSING,this.destroy())}});var Un=v((ic,$n)=>{"use strict";var sc=Ze(),{Duplex:po}=require("stream");function jn(r){r.emit("close")}function go(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Bn(r){this.removeListener("error",Bn),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function mo(r,e){let t=!0,n=new po({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let c=!o&&n._readableState.objectMode?i.toString():i;n.push(c)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(jn,n);return}let o=!1;r.once("error",function(a){o=!0,i(a)}),r.once("close",function(){o||i(s),process.nextTick(jn,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",go),n.on("error",Bn),n}$n.exports=mo});var zt=v((oc,Wn)=>{"use strict";var{tokenChars:_o}=de();function yo(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&_o[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let c=r.slice(t,n);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Wn.exports={parse:yo}});var Yn=v((cc,Kn)=>{"use strict";var bo=require("events"),et=require("http"),{Duplex:ac}=require("stream"),{createHash:wo}=require("crypto"),Fn=ze(),Z=le(),So=zt(),Eo=Ze(),{CLOSE_TIMEOUT:vo,GUID:xo,kWebSocket:ko}=U(),Oo=/^[+/0-9A-Za-z]{22}==$/,Hn=0,qn=1,Gn=2,Jt=class extends bo{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:vo,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Eo,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=et.createServer((n,s)=>{let i=et.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Co(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Hn}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Gn){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ve,this);return}if(e&&this.once("close",e),this._state!==qn)if(this._state=qn,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ve,this):process.nextTick(ve,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{ve(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Vn);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ee(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ee(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Oo.test(i)){ee(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){ee(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){xe(t,400);return}let a=e.headers["sec-websocket-protocol"],l=new Set;if(a!==void 0)try{l=So.parse(a)}catch{ee(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let h=new Z({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Fn.parse(d);g[Z.extensionName]&&(h.accept(g[Z.extensionName]),u[Z.extensionName]=h)}catch{ee(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(g,f,p,y)=>{if(!g)return xe(t,f||401,p,y);this.completeUpgrade(u,i,l,e,t,n,s)});return}if(!this.options.verifyClient(h))return xe(t,401)}this.completeUpgrade(u,i,l,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,c){if(!i.readable||!i.writable)return i.destroy();if(i[ko])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Hn)return xe(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${wo("sha1").update(t+xo).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let u=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;u&&(l.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[Z.extensionName]){let u=e[Z.extensionName].params,h=Fn.format({[Z.extensionName]:[u]});l.push(`Sec-WebSocket-Extensions: ${h}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
24
24
  `).join(`\r
25
- `)),i.removeListener("error",Fn),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ve,this)})),c(d,s)}};Vn.exports=Kt;function Eo(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function ve(r){r._state=qn,r.emit("close")}function Fn(){this.destroy()}function xe(r,e,t,n){t=t||Ze.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${Ze.STATUS_CODES[e]}\r
25
+ `)),i.removeListener("error",Vn),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ve,this)})),c(d,s)}};Kn.exports=Jt;function Co(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function ve(r){r._state=Gn,r.emit("close")}function Vn(){this.destroy()}function xe(r,e,t,n){t=t||et.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${et.STATUS_CODES[e]}\r
26
26
  `+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
27
27
  `)+`\r
28
28
  \r
29
- `+t)}function ee(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,ee),r.emit("wsClientError",o,t,e)}else xe(t,n,s,i)}});var Xn={};ks(Xn,{loadConfig:()=>zt,loadProjectSettings:()=>Xt,saveConfig:()=>Jt});function zt(){let r=V.default.existsSync(et)?et:Jn;V.default.existsSync(r)||(console.error("[bridge] Config not found. Run: bridge-agent auth"),process.exit(1));let e=V.default.readFileSync(r,"utf-8"),t;try{t=JSON.parse(e)}catch{console.error("[bridge] Invalid config file at",Jn),process.exit(1)}(!t||typeof t!="object")&&(console.error("[bridge] Config must be a JSON object. Run: bridge-agent auth"),process.exit(1));let n=t,s=typeof n.server=="string"?n.server:"",i=typeof n.token=="string"?n.token:"",o=typeof n.name=="string"?n.name:"bridge-agent";(!s||!i)&&(console.error("[bridge] Config missing server or token. Run: bridge-agent auth"),process.exit(1));let c={server:s,token:i,name:o};return n.agentPaths&&typeof n.agentPaths=="object"&&!Array.isArray(n.agentPaths)&&(c.agentPaths=Object.fromEntries(Object.entries(n.agentPaths).filter(([,a])=>typeof a=="string"))),c}function Jt(r){let e=ke.default.dirname(et);V.default.existsSync(e)||V.default.mkdirSync(e,{recursive:!0}),V.default.writeFileSync(et,JSON.stringify(r,null,2),{mode:384})}function Xt(r){let e=ke.default.join(r??process.cwd(),".jerico","settings.json");if(!V.default.existsSync(e))return{};try{let t=V.default.readFileSync(e,"utf-8"),n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return{};let s=n,i={};return typeof s.preferredAgent=="string"&&(i.preferredAgent=s.preferredAgent),s.hooks&&typeof s.hooks=="object"&&!Array.isArray(s.hooks)&&(i.hooks=Object.fromEntries(Object.entries(s.hooks).filter(([,o])=>typeof o=="string"))),s.env&&typeof s.env=="object"&&!Array.isArray(s.env)&&(i.env=Object.fromEntries(Object.entries(s.env).filter(([,o])=>typeof o=="string"))),s.agentPaths&&typeof s.agentPaths=="object"&&!Array.isArray(s.agentPaths)&&(i.agentPaths=Object.fromEntries(Object.entries(s.agentPaths).filter(([,o])=>typeof o=="string"))),i}catch{return console.warn("[bridge] Failed to parse .jerico/settings.json, ignoring"),{}}}var V,ke,Yt,et,Jn,tt=xs(()=>{"use strict";V=y(require("fs")),ke=y(require("path")),Yt=y(require("os")),et=ke.default.join(Yt.default.homedir(),".jerico","settings.json"),Jn=ke.default.join(Yt.default.homedir(),".bridge","config.json")});var Sr=y(br(),1),{program:Ea,createCommand:va,createArgument:xa,createOption:ka,CommanderError:Oa,InvalidArgumentError:Ia,InvalidOptionArgumentError:Aa,Command:wr,Argument:Ca,Option:Ta,Help:Pa}=Sr.default;var ds=require("node:http"),ne=require("node:child_process"),$=require("node:fs"),Y=require("node:os"),T=y(require("path"));var Wr=y(require("node-pty"));var kt=y(jr()),ie=y(require("fs")),_e=y(require("path")),Br=y(require("net")),Ur=require("child_process"),Me=r=>r+`
30
- `,je=r=>r.replace(/[\r\n]+$/,"")+"\r",oe=[{key:"sh",displayName:"Shell",binary:"sh",checkAuth:async()=>!0,formatInput:Me},{key:"claude",displayName:"Claude Code",binary:"claude",checkAuth:async()=>xt(".claude")||se("ANTHROPIC_API_KEY"),assignSessionId:!0,spawnArgs:["--dangerously-skip-permissions"],resumeArgs:r=>["--dangerously-skip-permissions","--resume",r],supportsMcpConfig:!0,formatInput:je,versionDirGlobs:[".local/share/claude/versions/*"]},{key:"codex",displayName:"Codex CLI",binary:"codex",checkAuth:async()=>se("OPENAI_API_KEY"),spawnArgs:["--full-auto"],supportsMcpConfig:!0,formatInput:je},{key:"qwen",displayName:"Qwen CLI",binary:"qwen",checkAuth:async()=>xt(".qwen"),assignSessionId:!0,spawnArgs:["--yolo"],resumeArgs:r=>["--resume",r,"--yolo"],supportsMcpConfig:!0,formatInput:je,versionDirGlobs:[".local/share/qwen/versions/*"]},{key:"gemini",displayName:"Gemini",binary:"gemini",checkAuth:async()=>se("GEMINI_API_KEY"),supportsMcpConfig:!0,formatInput:Me},{key:"ollama",displayName:"Ollama",binary:"ollama",checkAuth:async()=>ri(11434),formatInput:Me},{key:"aider",displayName:"Aider",binary:"aider",checkAuth:async()=>se("OPENAI_API_KEY")||se("ANTHROPIC_API_KEY"),supportsMcpConfig:!0,formatInput:Me},{key:"kimi",displayName:"Kimi Code",binary:"kimi",checkAuth:async()=>xt(".kimi")||se("KIMI_API_KEY"),assignSessionId:!0,spawnArgs:["--yolo"],resumeArgs:r=>["-r",r,"--yolo"],supportsMcpConfig:!0,formatInput:je,versionDirGlobs:[".local/share/uv/tools/kimi-cli/bin",".local/share/kimi/versions/*"]}];var $r=process.env.HOME??"/Users/unknown";function $e(r){try{let e=(0,Ur.spawnSync)(r,["--version"],{timeout:5e3});return e.status!==0?void 0:(e.stdout??e.stderr??Buffer.from("")).toString("utf8").split(`
31
- `)[0].trim()||void 0}catch{return}}function ei(r){if(!r.versionDirGlobs?.length)return[];let e=[],t=r.versionDirGlobs;for(let n of t){let s=_e.default.join($r,n.replace(/\/\*$/,""));if(n.endsWith("/*")){let i=[];try{i=ie.default.readdirSync(s)}catch{}i.sort((o,c)=>c.localeCompare(o));for(let o of i){let c=_e.default.join(s,o,r.binary);if(ie.default.existsSync(c)){let a=$e(c);e.push({path:c,version:a})}}}else{let i=_e.default.join($r,n);if(ie.default.existsSync(i)){let o=$e(i);e.push({path:i,version:o})}}}return e}async function ti(r,e={}){if(e[r.key]){let n=e[r.key],s=$e(n);if(s)return{path:n,version:s}}try{let n=await(0,kt.default)(r.binary);if(n&&ie.default.existsSync(n)){let s=$e(n);if(s!==void 0)return{path:n,version:s}}}catch{}let t=ei(r);for(let n of t)if(n.version!==void 0)return n;try{let n=await(0,kt.default)(r.binary);if(n)return{path:n}}catch{}throw new Error(`No working binary found for agent '${r.key}'`)}async function Ot(r={}){let e=[];for(let t of oe)try{let{path:n,version:s}=await ti(t,r),o=await t.checkAuth()?"ok":"missing";e.push({key:t.key,displayName:t.displayName,binaryPath:n,authStatus:o,version:s})}catch{}return console.log("[daemon] agent.detect.done",{found:e.map(t=>t.key),missing:oe.map(t=>t.key).filter(t=>!e.find(n=>n.key===t))}),e}function xt(r){return ie.default.existsSync(_e.default.join(process.env.HOME??"",r))}function se(r){return!!process.env[r]}async function ri(r){return new Promise(e=>{let t=Br.default.createConnection(r,"127.0.0.1");t.setTimeout(200),t.on("connect",()=>{t.destroy(),e(!0)}),t.on("error",()=>e(!1)),t.on("timeout",()=>{t.destroy(),e(!1)})})}var Be=class{handles=new Map;nextInstanceId=1;spawn(e,t,n,s,i,o,c,a,l){let d=this.handles.get(e);d&&(console.warn("[daemon] pty.spawn.replace_existing",{agentId:e,oldPid:d.pid,newAgentKey:t}),this.kill(e,!0));let u=Math.max(1,Math.min(500,i)),h=Math.max(1,Math.min(500,o)),g={...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"};l&&(g.BRIDGE_SERVER_URL=l.serverUrl,g.BRIDGE_TOKEN=l.token,g.BRIDGE_WORKSPACE_ID=l.workspaceId,g.BRIDGE_PROJECT_ID=l.projectId,l.projectEnv&&Object.assign(g,l.projectEnv));let f=process.env.BRIDGE_MCP_URL;f&&(g.BRIDGE_MCP_URL=f);let p;try{p=Wr.spawn(n,s,{name:"xterm-256color",cols:u,rows:h,cwd:l?.cwd,env:g})}catch(E){let m=E instanceof Error?E.message:String(E);return console.error("[daemon] pty.spawn.failed",{agentId:e,agentKey:t,error:m}),!1}let _=this.nextInstanceId++,k={agentId:e,agentKey:t,process:p,pid:p.pid,killed:!1,instanceId:_};return p.onData(E=>{let m=this.handles.get(e);!m||m.instanceId!==_||k.killed||c(Buffer.from(E).toString("base64"))}),p.onExit(({exitCode:E,signal:m})=>{let S=this.handles.get(e);!S||S.instanceId!==_||k.killed||k.killed||(this.handles.delete(e),console.log("[daemon] pty.exit",{agentId:e,exitCode:E,signal:m}),a(E??null,m?String(m):null))}),this.handles.set(e,k),console.log("[daemon] pty.spawn.success",{agentId:e,agentKey:t,args:s,cwd:l?.cwd}),!0}write(e,t,n){let s=this.handles.get(e);if(!s)return;let i=Buffer.from(t,"base64").toString(),o=oe.find(a=>a.key===s.agentKey),c=n==="orchestrator"&&o?.formatInput?o.formatInput(i):i;s.process.write(c)}kill(e,t=!1){let n=this.handles.get(e);if(!n)return;n.killed=!0,this.handles.delete(e);let s=n.pid;if(t){try{process.kill(-s,"SIGTERM")}catch{n.process.kill()}setTimeout(()=>{try{process.kill(-s,"SIGKILL")}catch{}},2e3)}else try{process.kill(-s,"SIGTERM")}catch{n.process.kill()}console.log("[daemon] pty.kill",{agentId:e,force:t})}resize(e,t,n){let s=this.handles.get(e);if(!s)return;let i=Math.max(1,Math.min(500,t)),o=Math.max(1,Math.min(500,n));s.process.resize(i,o)}killAll(){for(let e of this.handles.values())try{process.kill(-e.pid,"SIGTERM")}catch{e.process.kill()}this.handles.clear()}};var vo=y(jn(),1),xo=y(Ye(),1),ko=y(le(),1),Oo=y(jt(),1),Io=y(Ut(),1),Ao=y(Gt(),1),Gn=y(Qe(),1),Co=y(Hn(),1);var I=Gn.default;var re=y(require("fs")),M=y(require("path")),Te=y(require("os")),nr=require("node:child_process"),os=require("node:crypto");var Kn=r=>r;var Yn=r=>r,zn=r=>r;tt();var Oe=y(require("fs")),Qt=y(require("path")),Qn=y(require("os")),To=2e5;function Po(r){let e=Qt.default.join(Qn.default.homedir(),".claude","projects");if(Oe.default.existsSync(e))try{let t=Oe.default.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory());for(let n of t){let s=Qt.default.join(e,n.name,`${r}.jsonl`);if(Oe.default.existsSync(s))return s}}catch{}}function No(r){try{let t=Oe.default.readFileSync(r,"utf-8").trim().split(`
32
- `);for(let n=t.length-1;n>=0;n--){let s=t[n]?.trim();if(s)try{let i=JSON.parse(s),o=i.message?.usage??i.usage;if(!o||typeof o!="object")continue;let c=o,a=(c.input_tokens??0)+(c.cache_creation_input_tokens??0)+(c.cache_read_input_tokens??0);if(a===0)continue;return{usedPct:Math.min(100,Math.round(a/To*100)),usedTokens:a}}catch{continue}}}catch{}return null}function Zt(r,e,t){let n,s=-1,i=()=>{if(n||(n=Po(e)),!n)return;let a=No(n);a&&a.usedTokens!==s&&(s=a.usedTokens,t(r,a.usedPct,a.usedTokens))},o=setTimeout(i,2e3),c=setInterval(i,3e3);return()=>{clearTimeout(o),clearInterval(c)}}var K=y(require("fs")),Ie=y(require("path")),er=y(require("os")),Zn=300*60*1e3,es={free:10,pro:40,max_5x:200,max_20x:200};function Do(){let r=Ie.default.join(er.default.homedir(),".jerico","settings.json");try{if(!K.default.existsSync(r))return"pro";let t=JSON.parse(K.default.readFileSync(r,"utf-8")).claudeTier;if(typeof t=="string"&&t in es)return t}catch{}return"pro"}function Ro(){let r=Ie.default.join(er.default.homedir(),".claude","projects");if(!K.default.existsSync(r))return{prompts5h:0,resetAt:0};let t=Date.now()-Zn,n=1/0,s=0;try{let o=K.default.readdirSync(r,{withFileTypes:!0}).filter(c=>c.isDirectory());for(let c of o){let a=Ie.default.join(r,c.name),l;try{l=K.default.readdirSync(a).filter(d=>d.endsWith(".jsonl"))}catch{continue}for(let d of l){let u=Ie.default.join(a,d),h;try{if(K.default.statSync(u).size>20*1024*1024)continue;h=K.default.readFileSync(u,"utf-8")}catch{continue}for(let g of h.split(`
33
- `)){let f=g.trim();if(f)try{let p=JSON.parse(f);if(p.type!=="user"||p.message?.role!=="user"||p.userType!==void 0&&p.userType!=="external")continue;let k=p.timestamp;if(typeof k!="string")continue;let E=Date.parse(k);if(isNaN(E)||E<t)continue;s++,E<n&&(n=E)}catch{continue}}}}}catch{}let i=isFinite(n)?n+Zn:0;return{prompts5h:s,resetAt:i}}function ts(r){let e=()=>{let n=Do(),s=es[n]??40,{prompts5h:i,resetAt:o}=Ro();r({prompts5h:i,limit5h:s,resetAt:o,tier:n})};try{e()}catch(n){console.warn("[quota] initial poll failed",n)}let t=setInterval(()=>{try{e()}catch{}},6e4);return()=>clearInterval(t)}var ge=y(require("os")),rt=y(require("fs")),rr=require("node:child_process");function ns(){let r=0,e=0;for(let t of ge.default.cpus())r+=t.times.idle,e+=t.times.user+t.times.nice+t.times.sys+t.times.idle+(t.times.irq??0);return{idle:r,total:e}}var tr=ns();function Lo(){let r=ns(),e=r.idle-tr.idle,t=r.total-tr.total;return tr=r,t===0?0:Math.round((1-e/t)*100)}function Mo(){let r=ge.default.totalmem(),e=ge.default.freemem(),t=0;try{let n=(0,rr.spawnSync)("vm_stat",["-c","10"],{encoding:"utf-8",timeout:2e3,stdio:"pipe"});if(n.status===0&&n.stdout){let s=n.stdout.match(/page size of (\d+) bytes/),i=n.stdout.match(/Pages speculative:\s*(\d+)/),o=n.stdout.match(/Pages inactive:\s*(\d+)/);if(i&&o){let c=s?parseInt(s[1],10):4096;t=(parseInt(i[1],10)+parseInt(o[1],10))*c}}}catch{}return{totalMb:Math.round(r/1024/1024),usedMb:Math.round((r-e)/1024/1024),cachedMb:Math.round(t/1024/1024)}}function jo(){if(process.platform==="darwin")return Mo();let r=ge.default.totalmem(),e=ge.default.freemem();return{totalMb:Math.round(r/1024/1024),usedMb:Math.round((r-e)/1024/1024),cachedMb:0}}function $o(){try{let r=(0,rr.spawnSync)("pmset",["-g","batt"],{encoding:"utf-8",timeout:2e3,stdio:"pipe"});if(r.status!==0||!r.stdout)return;let e=r.stdout.match(/(\d+)%;\s*(charging|discharging|charged|finishing charge)/i);if(!e)return;let t=parseInt(e[1],10),n=/charging|charged|finishing/i.test(e[2]);return{percent:t,charging:n}}catch{return}}function Bo(){try{let r="/sys/class/power_supply",e=rt.default.readdirSync(r).filter(o=>/^BAT/i.test(o));if(e.length===0)return;let t=`${r}/${e[0]}`,n=parseInt(rt.default.readFileSync(`${t}/capacity`,"utf-8").trim(),10),s=rt.default.readFileSync(`${t}/status`,"utf-8").trim().toLowerCase();return{percent:n,charging:s==="charging"||s==="full"}}catch{return}}function rs(){let r=process.platform;if(r==="darwin")return $o();if(r==="linux")return Bo()}var Uo=1e4,Wo=3;function ss(r){let e=0,t=rs(),n=setInterval(()=>{e++,e%Wo===0&&(t=rs());let s=jo();r({cpu:Lo(),ramUsedMb:s.usedMb,ramTotalMb:s.totalMb,ramCachedMb:s.cachedMb,battery:t})},Uo);return()=>clearInterval(n)}var te=new Map,Fo=r=>r.replace(/[\r\n]+$/,"")+"\r",sr=null,qo=ts(r=>{sr=r}),Vo=3e4,Ho=5e3,Go=400;function Ko(r){return r.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"")}function Yo(r,e=Go){return r.length<=e?r:`${r.slice(0,e)}...`}function zo(r){return r.replace(/^wss?:/,e=>e==="wss:"?"https:":"http:").replace(/\/ws(\/.*)?$/,"")}function st(){let r=re.default.realpathSync(process.argv[1]??""),e=M.default.dirname(r);return[M.default.resolve(e,"../../mcp-server/dist/index.cjs"),M.default.resolve(e,"bridge-mcp.cjs"),M.default.resolve(process.cwd(),"node_modules/.bin/bridge-mcp")].find(n=>re.default.existsSync(n))??"bridge-mcp"}function Jo(r){try{let e=process.env.BRIDGE_MCP_URL,t=e?{mcpServers:{bridge:{type:"http",url:`${e}/mcp/${r.workspaceId}/${r.projectId}`,headers:{Authorization:`Bearer ${r.token}`,"x-panel-id":r.agentId??""}}}}:{mcpServers:{bridge:{command:st(),args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:r.projectId,BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}},n=M.default.join(Te.default.tmpdir(),`bridge-mcp-${r.agentId??r.projectId}.json`);return re.default.writeFileSync(n,JSON.stringify(t,null,2)+`
34
- `,"utf-8"),console.log("[daemon] mcp.config.written",{tmpPath:n,transport:e?"http":"stdio"}),["--mcp-config",n]}catch(e){return console.warn("[daemon] mcp.config.build.failed",{error:String(e)}),[]}}var Xo={bridge_get_project:"Project metadata: name, cwd, machineId",bridge_get_plan:"Read project spec/description",bridge_update_plan:"Update project spec/description",bridge_get_project_history:"Past run history and failure patterns",bridge_get_execution_status:"Run history with todo completion counts",bridge_get_todos:"List todos + session state for this project",bridge_add_todo:"Create a new todo (title, todoType, dependsOn)",bridge_update_todo:"Update a todo title or status",bridge_cancel_run:"Cancel active run (use before restarting a stale plan)",bridge_list_agents:"All agents: role, status, inRun flag",bridge_get_agent_status:"Single agent status check",bridge_spawn_worker:"Spawn a new worker agent (agentKey, role)",bridge_kill_agent:"Terminate a stuck or dead agent",bridge_get_agent_output:"Read terminal output of any agent",bridge_send_input:"Send text input to an agent PTY",bridge_get_my_task:"Get the task assigned to this agent",bridge_complete_task:"Signal task completion",bridge_fail_task:"Signal task failure with a specific reason",bridge_get_todo_context:"Read todo output/error for a specific todo",bridge_assign_task:"Assign a pending todo to a specific agent"};function Ae(...r){return`
29
+ `+t)}function ee(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,ee),r.emit("wsClientError",o,t,e)}else xe(t,n,s,i)}});var es={};Ps(es,{loadConfig:()=>Qt,loadProjectSettings:()=>er,saveConfig:()=>Zt});function Qt(){let r=q.default.existsSync(tt)?tt:Zn;q.default.existsSync(r)||(console.error("[bridge] Config not found. Run: bridge-agent auth"),process.exit(1));let e=q.default.readFileSync(r,"utf-8"),t;try{t=JSON.parse(e)}catch{console.error("[bridge] Invalid config file at",Zn),process.exit(1)}(!t||typeof t!="object")&&(console.error("[bridge] Config must be a JSON object. Run: bridge-agent auth"),process.exit(1));let n=t,s=typeof n.server=="string"?n.server:"",i=typeof n.token=="string"?n.token:"",o=typeof n.name=="string"?n.name:"bridge-agent";(!s||!i)&&(console.error("[bridge] Config missing server or token. Run: bridge-agent auth"),process.exit(1));let c={server:s,token:i,name:o};return n.agentPaths&&typeof n.agentPaths=="object"&&!Array.isArray(n.agentPaths)&&(c.agentPaths=Object.fromEntries(Object.entries(n.agentPaths).filter(([,a])=>typeof a=="string"))),c}function Zt(r){let e=ke.default.dirname(tt);q.default.existsSync(e)||q.default.mkdirSync(e,{recursive:!0}),q.default.writeFileSync(tt,JSON.stringify(r,null,2),{mode:384})}function er(r){let e=ke.default.join(r??process.cwd(),".jerico","settings.json");if(!q.default.existsSync(e))return{};try{let t=q.default.readFileSync(e,"utf-8"),n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return{};let s=n,i={};return typeof s.preferredAgent=="string"&&(i.preferredAgent=s.preferredAgent),s.hooks&&typeof s.hooks=="object"&&!Array.isArray(s.hooks)&&(i.hooks=Object.fromEntries(Object.entries(s.hooks).filter(([,o])=>typeof o=="string"))),s.env&&typeof s.env=="object"&&!Array.isArray(s.env)&&(i.env=Object.fromEntries(Object.entries(s.env).filter(([,o])=>typeof o=="string"))),s.agentPaths&&typeof s.agentPaths=="object"&&!Array.isArray(s.agentPaths)&&(i.agentPaths=Object.fromEntries(Object.entries(s.agentPaths).filter(([,o])=>typeof o=="string"))),i}catch{return console.warn("[bridge] Failed to parse .jerico/settings.json, ignoring"),{}}}var q,ke,Xt,tt,Zn,rt=As(()=>{"use strict";q=_(require("fs")),ke=_(require("path")),Xt=_(require("os")),tt=ke.default.join(Xt.default.homedir(),".jerico","settings.json"),Zn=ke.default.join(Xt.default.homedir(),".bridge","config.json")});var vr=_(Er(),1),{program:Aa,createCommand:Pa,createArgument:Ta,createOption:Na,CommanderError:Da,InvalidArgumentError:Ra,InvalidOptionArgumentError:La,Command:xr,Argument:Ma,Option:ja,Help:Ba}=vr.default;var gs=require("node:http"),ne=require("node:child_process"),B=require("node:fs"),Y=require("node:os"),P=_(require("path"));var qr=_(require("node-pty"));var It=_(Ur()),ie=_(require("fs")),_e=_(require("path")),Fr=_(require("net")),Hr=require("child_process"),je=r=>r+`
30
+ `,Be=r=>r.replace(/[\r\n]+$/,"")+"\r",oe=[{key:"sh",displayName:"Shell",binary:"sh",checkAuth:async()=>!0,formatInput:je},{key:"claude",displayName:"Claude Code",binary:"claude",checkAuth:async()=>Ct(".claude")||se("ANTHROPIC_API_KEY"),assignSessionId:!0,spawnArgs:["--dangerously-skip-permissions"],resumeArgs:r=>["--dangerously-skip-permissions","--resume",r],supportsMcpConfig:!0,formatInput:Be,versionDirGlobs:[".local/share/claude/versions/*"]},{key:"codex",displayName:"Codex CLI",binary:"codex",checkAuth:async()=>se("OPENAI_API_KEY"),spawnArgs:["--full-auto"],supportsMcpConfig:!0,formatInput:Be},{key:"qwen",displayName:"Qwen CLI",binary:"qwen",checkAuth:async()=>Ct(".qwen"),assignSessionId:!0,spawnArgs:["--yolo"],resumeArgs:r=>["--resume",r,"--yolo"],supportsMcpConfig:!0,formatInput:Be,versionDirGlobs:[".local/share/qwen/versions/*"]},{key:"gemini",displayName:"Gemini",binary:"gemini",checkAuth:async()=>se("GEMINI_API_KEY"),supportsMcpConfig:!0,formatInput:je},{key:"ollama",displayName:"Ollama",binary:"ollama",checkAuth:async()=>ai(11434),formatInput:je},{key:"aider",displayName:"Aider",binary:"aider",checkAuth:async()=>se("OPENAI_API_KEY")||se("ANTHROPIC_API_KEY"),supportsMcpConfig:!0,formatInput:je},{key:"kimi",displayName:"Kimi Code",binary:"kimi",checkAuth:async()=>Ct(".kimi")||se("KIMI_API_KEY"),assignSessionId:!0,spawnArgs:["--yolo"],resumeArgs:r=>["-r",r,"--yolo"],supportsMcpConfig:!0,formatInput:Be,versionDirGlobs:[".local/share/uv/tools/kimi-cli/bin",".local/share/kimi/versions/*"]}];var Wr=process.env.HOME??"/Users/unknown";function $e(r){try{let e=(0,Hr.spawnSync)(r,["--version"],{timeout:5e3});return e.status!==0?void 0:(e.stdout??e.stderr??Buffer.from("")).toString("utf8").split(`
31
+ `)[0].trim()||void 0}catch{return}}function ii(r){if(!r.versionDirGlobs?.length)return[];let e=[],t=r.versionDirGlobs;for(let n of t){let s=_e.default.join(Wr,n.replace(/\/\*$/,""));if(n.endsWith("/*")){let i=[];try{i=ie.default.readdirSync(s)}catch{}i.sort((o,c)=>c.localeCompare(o));for(let o of i){let c=_e.default.join(s,o,r.binary);if(ie.default.existsSync(c)){let a=$e(c);e.push({path:c,version:a})}}}else{let i=_e.default.join(Wr,n);if(ie.default.existsSync(i)){let o=$e(i);e.push({path:i,version:o})}}}return e}async function oi(r,e={}){if(e[r.key]){let n=e[r.key],s=$e(n);if(s)return{path:n,version:s}}try{let n=await(0,It.default)(r.binary);if(n&&ie.default.existsSync(n)){let s=$e(n);if(s!==void 0)return{path:n,version:s}}}catch{}let t=ii(r);for(let n of t)if(n.version!==void 0)return n;try{let n=await(0,It.default)(r.binary);if(n)return{path:n}}catch{}throw new Error(`No working binary found for agent '${r.key}'`)}async function At(r={}){let e=[];for(let t of oe)try{let{path:n,version:s}=await oi(t,r),o=await t.checkAuth()?"ok":"missing";e.push({key:t.key,displayName:t.displayName,binaryPath:n,authStatus:o,version:s})}catch{}return console.log("[daemon] agent.detect.done",{found:e.map(t=>t.key),missing:oe.map(t=>t.key).filter(t=>!e.find(n=>n.key===t))}),e}function Ct(r){return ie.default.existsSync(_e.default.join(process.env.HOME??"",r))}function se(r){return!!process.env[r]}async function ai(r){return new Promise(e=>{let t=Fr.default.createConnection(r,"127.0.0.1");t.setTimeout(200),t.on("connect",()=>{t.destroy(),e(!0)}),t.on("error",()=>e(!1)),t.on("timeout",()=>{t.destroy(),e(!1)})})}var Ue=class{handles=new Map;nextInstanceId=1;lastErrors=new Map;spawn(e,t,n,s,i,o,c,a,l){let d=this.handles.get(e);d&&(console.warn("[daemon] pty.spawn.replace_existing",{agentId:e,oldPid:d.pid,newAgentKey:t}),this.kill(e,!0));let u=Math.max(1,Math.min(500,i)),h=Math.max(1,Math.min(500,o)),g={...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"};l&&(g.BRIDGE_SERVER_URL=l.serverUrl,g.BRIDGE_TOKEN=l.token,g.BRIDGE_WORKSPACE_ID=l.workspaceId,g.BRIDGE_PROJECT_ID=l.projectId,l.projectEnv&&Object.assign(g,l.projectEnv));let f=process.env.BRIDGE_MCP_URL;f&&(g.BRIDGE_MCP_URL=f);let p;try{p=qr.spawn(n,s,{name:"xterm-256color",cols:u,rows:h,cwd:l?.cwd,env:g})}catch(E){let m=E instanceof Error?E.message:String(E);return this.lastErrors.set(e,m),console.error("[daemon] pty.spawn.failed",{agentId:e,agentKey:t,error:m}),!1}let y=this.nextInstanceId++,k={agentId:e,agentKey:t,process:p,pid:p.pid,killed:!1,instanceId:y};return p.onData(E=>{let m=this.handles.get(e);!m||m.instanceId!==y||k.killed||c(Buffer.from(E).toString("base64"))}),p.onExit(({exitCode:E,signal:m})=>{let w=this.handles.get(e);!w||w.instanceId!==y||k.killed||k.killed||(this.handles.delete(e),console.log("[daemon] pty.exit",{agentId:e,exitCode:E,signal:m}),a(E??null,m?String(m):null))}),this.lastErrors.delete(e),this.handles.set(e,k),console.log("[daemon] pty.spawn.success",{agentId:e,agentKey:t,args:s,cwd:l?.cwd}),!0}write(e,t,n){let s=this.handles.get(e);if(!s)return;let i=Buffer.from(t,"base64").toString(),o=oe.find(a=>a.key===s.agentKey),c=n==="orchestrator"&&o?.formatInput?o.formatInput(i):i;s.process.write(c)}kill(e,t=!1){let n=this.handles.get(e);if(!n)return;n.killed=!0,this.handles.delete(e);let s=n.pid;if(t){try{process.kill(-s,"SIGTERM")}catch{n.process.kill()}setTimeout(()=>{try{process.kill(-s,"SIGKILL")}catch{}},2e3)}else try{process.kill(-s,"SIGTERM")}catch{n.process.kill()}console.log("[daemon] pty.kill",{agentId:e,force:t})}resize(e,t,n){let s=this.handles.get(e);if(!s)return;let i=Math.max(1,Math.min(500,t)),o=Math.max(1,Math.min(500,n));s.process.resize(i,o)}getLastError(e){return this.lastErrors.get(e)}killAll(){for(let e of this.handles.values())try{process.kill(-e.pid,"SIGTERM")}catch{e.process.kill()}this.handles.clear()}};var Io=_(Un(),1),Ao=_(ze(),1),Po=_(le(),1),To=_(Ut(),1),No=_(Ht(),1),Do=_(zt(),1),zn=_(Ze(),1),Ro=_(Yn(),1);var C=zn.default;var re=_(require("fs")),M=_(require("path")),Te=_(require("os")),or=require("node:child_process"),us=require("node:crypto");var Jn=r=>r;var Xn=r=>r,Qn=r=>r;rt();var Oe=_(require("fs")),tr=_(require("path")),ts=_(require("os")),Lo=2e5;function Mo(r){let e=tr.default.join(ts.default.homedir(),".claude","projects");if(Oe.default.existsSync(e))try{let t=Oe.default.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory());for(let n of t){let s=tr.default.join(e,n.name,`${r}.jsonl`);if(Oe.default.existsSync(s))return s}}catch{}}function jo(r){try{let t=Oe.default.readFileSync(r,"utf-8").trim().split(`
32
+ `);for(let n=t.length-1;n>=0;n--){let s=t[n]?.trim();if(s)try{let i=JSON.parse(s),o=i.message?.usage??i.usage;if(!o||typeof o!="object")continue;let c=o,a=(c.input_tokens??0)+(c.cache_creation_input_tokens??0)+(c.cache_read_input_tokens??0);if(a===0)continue;return{usedPct:Math.min(100,Math.round(a/Lo*100)),usedTokens:a}}catch{continue}}}catch{}return null}function rr(r,e,t){let n,s=-1,i=()=>{if(n||(n=Mo(e)),!n)return;let a=jo(n);a&&a.usedTokens!==s&&(s=a.usedTokens,t(r,a.usedPct,a.usedTokens))},o=setTimeout(i,2e3),c=setInterval(i,3e3);return()=>{clearTimeout(o),clearInterval(c)}}var K=_(require("fs")),Ce=_(require("path")),nr=_(require("os")),rs=300*60*1e3,ns={free:10,pro:40,max_5x:200,max_20x:200};function Bo(){let r=Ce.default.join(nr.default.homedir(),".jerico","settings.json");try{if(!K.default.existsSync(r))return"pro";let t=JSON.parse(K.default.readFileSync(r,"utf-8")).claudeTier;if(typeof t=="string"&&t in ns)return t}catch{}return"pro"}function $o(){let r=Ce.default.join(nr.default.homedir(),".claude","projects");if(!K.default.existsSync(r))return{prompts5h:0,resetAt:0};let t=Date.now()-rs,n=1/0,s=0;try{let o=K.default.readdirSync(r,{withFileTypes:!0}).filter(c=>c.isDirectory());for(let c of o){let a=Ce.default.join(r,c.name),l;try{l=K.default.readdirSync(a).filter(d=>d.endsWith(".jsonl"))}catch{continue}for(let d of l){let u=Ce.default.join(a,d),h;try{if(K.default.statSync(u).size>20*1024*1024)continue;h=K.default.readFileSync(u,"utf-8")}catch{continue}for(let g of h.split(`
33
+ `)){let f=g.trim();if(f)try{let p=JSON.parse(f);if(p.type!=="user"||p.message?.role!=="user"||p.userType!==void 0&&p.userType!=="external")continue;let k=p.timestamp;if(typeof k!="string")continue;let E=Date.parse(k);if(isNaN(E)||E<t)continue;s++,E<n&&(n=E)}catch{continue}}}}}catch{}let i=isFinite(n)?n+rs:0;return{prompts5h:s,resetAt:i}}function ss(r){let e=()=>{let n=Bo(),s=ns[n]??40,{prompts5h:i,resetAt:o}=$o();r({prompts5h:i,limit5h:s,resetAt:o,tier:n})};try{e()}catch(n){console.warn("[quota] initial poll failed",n)}let t=setInterval(()=>{try{e()}catch{}},6e4);return()=>clearInterval(t)}var ge=_(require("os")),nt=_(require("fs")),ir=require("node:child_process");function os(){let r=0,e=0;for(let t of ge.default.cpus())r+=t.times.idle,e+=t.times.user+t.times.nice+t.times.sys+t.times.idle+(t.times.irq??0);return{idle:r,total:e}}var sr=os();function Uo(){let r=os(),e=r.idle-sr.idle,t=r.total-sr.total;return sr=r,t===0?0:Math.round((1-e/t)*100)}function Wo(){let r=ge.default.totalmem(),e=ge.default.freemem(),t=0;try{let n=(0,ir.spawnSync)("vm_stat",["-c","10"],{encoding:"utf-8",timeout:2e3,stdio:"pipe"});if(n.status===0&&n.stdout){let s=n.stdout.match(/page size of (\d+) bytes/),i=n.stdout.match(/Pages speculative:\s*(\d+)/),o=n.stdout.match(/Pages inactive:\s*(\d+)/);if(i&&o){let c=s?parseInt(s[1],10):4096;t=(parseInt(i[1],10)+parseInt(o[1],10))*c}}}catch{}return{totalMb:Math.round(r/1024/1024),usedMb:Math.round((r-e)/1024/1024),cachedMb:Math.round(t/1024/1024)}}function Fo(){if(process.platform==="darwin")return Wo();let r=ge.default.totalmem(),e=ge.default.freemem();return{totalMb:Math.round(r/1024/1024),usedMb:Math.round((r-e)/1024/1024),cachedMb:0}}function Ho(){try{let r=(0,ir.spawnSync)("pmset",["-g","batt"],{encoding:"utf-8",timeout:2e3,stdio:"pipe"});if(r.status!==0||!r.stdout)return;let e=r.stdout.match(/(\d+)%;\s*(charging|discharging|charged|finishing charge)/i);if(!e)return;let t=parseInt(e[1],10),n=/charging|charged|finishing/i.test(e[2]);return{percent:t,charging:n}}catch{return}}function qo(){try{let r="/sys/class/power_supply",e=nt.default.readdirSync(r).filter(o=>/^BAT/i.test(o));if(e.length===0)return;let t=`${r}/${e[0]}`,n=parseInt(nt.default.readFileSync(`${t}/capacity`,"utf-8").trim(),10),s=nt.default.readFileSync(`${t}/status`,"utf-8").trim().toLowerCase();return{percent:n,charging:s==="charging"||s==="full"}}catch{return}}function is(){let r=process.platform;if(r==="darwin")return Ho();if(r==="linux")return qo()}var Vo=1e4,Go=3;function as(r){let e=0,t=is(),n=setInterval(()=>{e++,e%Go===0&&(t=is());let s=Fo();r({cpu:Uo(),ramUsedMb:s.usedMb,ramTotalMb:s.totalMb,ramCachedMb:s.cachedMb,battery:t})},Vo);return()=>clearInterval(n)}var st=_(require("fs")),it=_(require("path")),cs=_(require("node-pty"));function Ko(){try{let r=require.resolve("node-pty"),e=it.default.resolve(it.default.dirname(r),"..");return it.default.join(e,"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper")}catch{return}}function ls(){let r=Ko();if(!r||!st.default.existsSync(r))return!0;try{st.default.accessSync(r,st.default.constants.X_OK)}catch{return!1}try{cs.spawn("/bin/sh",[],{name:"xterm-256color",cols:80,rows:24}).kill()}catch{return!1}return!0}var te=new Map,Ie=[];function Yo(r){let e=Date.now(),t=e-3e4;for(;Ie.length&&Ie[0].ts<t;)Ie.shift();return Ie.push({agentKey:r,ts:e}),new Set(Ie.map(s=>s.agentKey)).size>=2}var zo=r=>r.replace(/[\r\n]+$/,"")+"\r",ar=null,Jo=ss(r=>{ar=r}),Xo=3e4,Qo=5e3,Zo=400;function ea(r){return r.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"")}function ta(r,e=Zo){return r.length<=e?r:`${r.slice(0,e)}...`}function ra(r){return r.replace(/^wss?:/,e=>e==="wss:"?"https:":"http:").replace(/\/ws(\/.*)?$/,"")}function at(){let r=re.default.realpathSync(process.argv[1]??""),e=M.default.dirname(r);return[M.default.resolve(e,"../../mcp-server/dist/index.cjs"),M.default.resolve(e,"bridge-mcp.cjs"),M.default.resolve(process.cwd(),"node_modules/.bin/bridge-mcp")].find(n=>re.default.existsSync(n))??"bridge-mcp"}function na(r){try{let e=process.env.BRIDGE_MCP_URL,t=e?{mcpServers:{bridge:{type:"http",url:`${e}/mcp/${r.workspaceId}/${r.projectId}`,headers:{Authorization:`Bearer ${r.token}`,"x-panel-id":r.agentId??""}}}}:{mcpServers:{bridge:{command:at(),args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:r.projectId,BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}},n=M.default.join(Te.default.tmpdir(),`bridge-mcp-${r.agentId??r.projectId}.json`);return re.default.writeFileSync(n,JSON.stringify(t,null,2)+`
34
+ `,"utf-8"),console.log("[daemon] mcp.config.written",{tmpPath:n,transport:e?"http":"stdio"}),["--mcp-config",n]}catch(e){return console.warn("[daemon] mcp.config.build.failed",{error:String(e)}),[]}}var sa={bridge_get_project:"Project metadata: name, cwd, machineId",bridge_get_plan:"Read project spec/description",bridge_update_plan:"Update project spec/description",bridge_get_project_history:"Past run history and failure patterns",bridge_get_execution_status:"Run history with todo completion counts",bridge_get_todos:"List todos + session state for this project",bridge_add_todo:"Create a new todo (title, todoType, dependsOn)",bridge_update_todo:"Update a todo title or status",bridge_cancel_run:"Cancel active run (use before restarting a stale plan)",bridge_list_agents:"All agents: role, status, inRun flag",bridge_get_agent_status:"Single agent status check",bridge_spawn_worker:"Spawn a new worker agent (agentKey, role)",bridge_kill_agent:"Terminate a stuck or dead agent",bridge_get_agent_output:"Read terminal output of any agent",bridge_send_input:"Send text input to an agent PTY",bridge_get_my_task:"Get the task assigned to this agent",bridge_complete_task:"Signal task completion",bridge_fail_task:"Signal task failure with a specific reason",bridge_get_todo_context:"Read todo output/error for a specific todo",bridge_assign_task:"Assign a pending todo to a specific agent"};function Ae(...r){return`
35
35
 
36
- **Available MCP tools:** ${r.join(", ")}`}function Qo(...r){return`
36
+ **Available MCP tools:** ${r.join(", ")}`}function ia(...r){return`
37
37
 
38
38
  ## Tool reference (only call tools listed here)
39
39
 
40
40
  | Tool | Purpose |
41
41
  |------|---------|
42
- ${r.map(t=>`| \`${t}\` | ${Xo[t]} |`).join(`
43
- `)}`}var as={developer:`# Bridge Worker \u2014 Developer Role
42
+ ${r.map(t=>`| \`${t}\` | ${sa[t]} |`).join(`
43
+ `)}`}var hs={developer:`# Bridge Worker \u2014 Developer Role
44
44
 
45
45
  You are a **Developer** worker in a multi-agent orchestration system called Bridge.
46
46
 
@@ -340,10 +340,10 @@ Summarize: todos completed, failed, any blockers. List what workers did.
340
340
 
341
341
  ---
342
342
 
343
- ${Qo("bridge_get_project","bridge_get_plan","bridge_get_todos","bridge_add_todo","bridge_cancel_run","bridge_get_project_history","bridge_get_execution_status","bridge_list_agents","bridge_get_agent_status","bridge_spawn_worker","bridge_assign_task","bridge_get_todo_context","bridge_get_agent_output","bridge_kill_agent")}`};function Zo(r,e,t){if(!e)return[];let n=as[e];if(!n)return[];if(r==="claude")try{let s=M.default.join(Te.default.tmpdir(),`bridge-role-${t}.md`),i=n.replaceAll("{{PANEL_ID}}",t);return re.default.writeFileSync(s,i+`
344
- `,"utf-8"),console.log("[daemon] role.prompt.written",{agentId:t,role:e,tmpPath:s}),["--append-system-prompt-file",s]}catch(s){return console.warn("[daemon] role.prompt.write.failed",{agentId:t,role:e,error:String(s)}),[]}return r==="qwen"?["--append-system-prompt",n]:[]}function Ce(r){return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function ea(r){try{let e=process.env.BRIDGE_MCP_URL,t=e?{mcpServers:{bridge:{type:"http",url:`${e}/mcp/${r.workspaceId}/${r.projectId}`,headers:{Authorization:`Bearer ${r.token}`,"x-panel-id":r.agentId??""}}}}:{mcpServers:{bridge:{command:st(),args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:r.projectId,BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}},n=M.default.join(Te.default.tmpdir(),`bridge-mcp-kimi-${r.agentId??r.projectId}.json`);return re.default.writeFileSync(n,JSON.stringify(t,null,2)+`
345
- `,"utf-8"),console.log("[daemon] kimi.mcp.config.written",{tmpPath:n,transport:e?"http":"stdio"}),["--mcp-config-file",n]}catch(e){return console.warn("[daemon] kimi.mcp.config.build.failed",{error:String(e)}),[]}}function ta(r){try{let e=st(),t=`{BRIDGE_SERVER_URL=${Ce(r.serverUrl)},BRIDGE_TOKEN=${Ce(r.token)},BRIDGE_WORKSPACE_ID=${Ce(r.workspaceId)},BRIDGE_PROJECT_ID=${Ce(r.projectId)},HTTP_MODE="false"}`;return["-c",'mcp_servers.bridge.transport="stdio"',"-c",`mcp_servers.bridge.command=${Ce(e)}`,"-c","mcp_servers.bridge.args=[]","-c",`mcp_servers.bridge.env=${t}`]}catch(e){return console.warn("[daemon] codex.mcp.config.build.failed",{error:String(e)}),[]}}function ra(r){try{if(!r.cwd)return console.warn("[daemon] qwen.mcp.setup.skipped",{reason:"missing_cwd",projectId:r.projectId}),!1;let e=st(),t={cwd:r.cwd,encoding:"utf-8",timeout:5e3,stdio:"pipe"};(0,nr.spawnSync)("qwen",["mcp","remove","--scope","project","bridge"],t);let n=(0,nr.spawnSync)("qwen",["mcp","add","--scope","project","-t","stdio","-e",`BRIDGE_SERVER_URL=${r.serverUrl}`,"-e",`BRIDGE_TOKEN=${r.token}`,"-e",`BRIDGE_WORKSPACE_ID=${r.workspaceId}`,"-e",`BRIDGE_PROJECT_ID=${r.projectId}`,"-e",`BRIDGE_PANEL_ID=${r.agentId??""}`,"-e","HTTP_MODE=false","bridge",e],t);return n.status===0?(console.log("[daemon] qwen.mcp.setup.ok",{cwd:r.cwd,projectId:r.projectId}),!0):(console.warn("[daemon] qwen.mcp.setup.failed",{cwd:r.cwd,projectId:r.projectId,status:n.status,stderr:(n.stderr??"").toString().slice(0,300)}),!1)}catch(e){return console.warn("[daemon] qwen.mcp.setup.error",{error:String(e),projectId:r.projectId}),!1}}var nt=[],ir=!1,is=!1;function cs(){return ir}function ls(r){if(is)throw new Error("[daemon] startDaemonConnection called twice \u2014 only one connection manager allowed");is=!0;let e=zt(),t=(0,os.createHash)("sha256").update(e.token).digest("hex"),n=null,s=null,i=null,o=0;function c(){s&&(clearTimeout(s),s=null),n=new I(e.server,{headers:{Authorization:`Bearer ${e.token}`}});let l=n,d=null;l.on("open",()=>{ir=!0,console.log("[daemon] ws.connected",{server:e.server}),i=setInterval(()=>{l.readyState===I.OPEN&&l.ping()},Vo),l.send(JSON.stringify({type:"ready",version:"1.1",name:e.name})),Ot(e.agentPaths).then(u=>{nt=u,l.readyState===I.OPEN&&l.send(JSON.stringify({type:"agents",list:nt}))}),d=ss(u=>{l.readyState===I.OPEN&&l.send(JSON.stringify({type:"system_metrics",daemonId:t,...u}))})}),l.on("message",u=>{let h;try{h=JSON.parse(u.toString())}catch{console.warn("[daemon] Invalid JSON from server, ignoring");return}na(h,l,r,e)}),l.on("close",u=>{ir=!1,i&&(clearInterval(i),i=null),d?.(),d=null,u===1008?(o++,o>=2&&(console.error("[daemon] ws.auth_failed \u2014 token invalid or expired (2 consecutive rejections), stopping. Re-run: bridge-agent auth"),process.exit(1)),console.warn("[daemon] ws.auth_rejected \u2014 transient 1008, will retry once",{attempt:o})):o=0,!s&&(console.log("[daemon] ws.reconnecting",{attempt:1}),s=setTimeout(c,3e3))}),l.on("error",u=>{console.error("[daemon] ws.error",{message:u.message})})}function a(){i&&(clearInterval(i),i=null),qo();for(let l of te.values())l();r.killAll(),n?.close()}process.on("SIGINT",()=>{a(),process.exit(0)}),process.on("SIGTERM",()=>{a(),process.exit(0)}),process.on("SIGHUP",()=>{a(),process.exit(0)}),process.on("uncaughtException",l=>{console.error("[daemon] uncaughtException",{error:l.message}),r.killAll(),process.exit(1)}),c()}function na(r,e,t,n){switch(r.type){case"spawn":{console.log("[daemon] pty.spawn.start",{agentId:r.agentId,agentKey:r.agentKey,sessionId:r.sessionId,projectId:r.projectId,workspaceId:r.workspaceId,role:r.role});let s=nt.find(m=>m.key===r.agentKey);if(!s){e.readyState===I.OPEN&&e.send(JSON.stringify({type:"error",code:"AGENT_NOT_FOUND",message:`Agent '${r.agentKey}' is not installed on this machine`}));return}let i=oe.find(m=>m.key===r.agentKey),o=[];if(r.sessionId&&i?.resumeArgs)o=i.resumeArgs(r.sessionId),console.log("[daemon] pty.spawn.resume",{agentId:r.agentId,sessionId:r.sessionId}),r.agentKey==="claude"&&(te.get(r.agentId)?.(),te.set(r.agentId,Zt(r.agentId,r.sessionId,(m,S,b)=>{e.readyState===I.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:m,usedPct:S,usedTokens:b,...sr}))})));else if(i?.assignSessionId){let m=crypto.randomUUID(),S=r.agentKey==="kimi"?"--session":"--session-id";o=[...i.spawnArgs??[],S,m],e.readyState===I.OPEN&&(e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:m})),console.log("[daemon] session.assigned",{agentId:r.agentId,sessionId:m})),r.agentKey==="claude"&&(te.get(r.agentId)?.(),te.set(r.agentId,Zt(r.agentId,m,(b,R,z)=>{e.readyState===I.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:b,usedPct:R,usedTokens:z,...sr}))})))}else e.readyState===I.OPEN&&e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:crypto.randomUUID()}));let c,a=!1,l;if(r.projectId&&r.workspaceId){let m=zo(n.server),S=Xt(r.cwd);if(c={serverUrl:m,token:n.token,workspaceId:Yn(r.workspaceId),projectId:zn(r.projectId),agentId:r.agentId?Kn(r.agentId):void 0,cwd:r.cwd,projectEnv:S.env},r.agentKey==="claude"){let b=Jo(c);a=b.length>0,l=process.env.BRIDGE_MCP_URL?"http":"stdio",o=[...o,...b]}else if(r.agentKey==="codex"){let b=ta(c);a=b.length>0,l="stdio",o=[...o,...b]}else if(r.agentKey==="qwen")a=ra(c),l=a?"stdio":void 0;else if(r.agentKey==="kimi"){let b=ea(c);a=b.length>0,l=process.env.BRIDGE_MCP_URL?"http":"stdio",o=[...o,...b]}else a=!1,console.log("[daemon] mcp.config.skipped",{agentId:r.agentId,agentKey:r.agentKey,reason:"unsupported_agent_path"})}let d=Zo(r.agentKey,r.role,r.agentId);d.length>0&&(o=[...o,...d]);let u=Math.max(1,Math.min(500,r.cols)),h=Math.max(1,Math.min(500,r.rows)),g=Date.now(),f="",p=0,_=!1,k=!1;t.spawn(r.agentId,r.agentKey,s.binaryPath,o,u,h,m=>{p+=m.length;try{let S=Buffer.from(m,"base64").toString("utf-8");if(r.agentKey==="kimi"&&r.role&&!k&&Date.now()-g<3e4&&(/yolo agent/.test(S)||/●/.test(S)||/○/.test(S))){k=!0;let b=as[r.role];if(b){let R=b.replaceAll("{{PANEL_ID}}",r.agentId),z=Fo(R),De=Buffer.from(z).toString("base64");t.write(r.agentId,De,"orchestrator"),console.log("[daemon] kimi.role.injected",{agentId:r.agentId,role:r.role})}}}catch{}if(!f)try{let S=Buffer.from(m,"base64").toString("utf-8"),b=Ko(S).replace(/\x00/g,"").trim();if(b&&(f=Yo(b)),r.agentKey==="codex"&&!_&&Date.now()-g<2e4&&/included in your plan for free|let[’']s build together/i.test(b)&&/yes|no|\[y\/n\]|\(y\/n\)|y\/n/i.test(b)){_=!0;let R=Buffer.from("y").toString("base64");t.write(r.agentId,R,"orchestrator"),console.log("[daemon] codex.onboarding.auto_ack",{agentId:r.agentId})}}catch{}e.readyState===I.OPEN&&e.send(JSON.stringify({type:"output",agentId:r.agentId,data:m}))},(m,S)=>{let b=Date.now()-g,R=b<=Ho;console.log("[daemon] pty.spawn.result",{agentId:r.agentId,agentKey:r.agentKey,daemonId:r.daemonId,exitCode:m,signal:S,uptimeMs:b,earlyExit:R,outputBytes:p,firstOutputSnippet:f||void 0}),R&&e.readyState===I.OPEN&&e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Early exit: agent=${r.agentKey} code=${m??"null"} signal=${S??"null"} snippet="${f||"no output"}"`})),e.readyState===I.OPEN&&e.send(JSON.stringify({type:"exit",agentId:r.agentId,exitCode:m,signal:S}))},c)?e.readyState===I.OPEN&&e.send(JSON.stringify({type:"mcp_status",agentId:r.agentId,mcpConfigured:a,transport:a?l:void 0,projectId:c?.projectId})):e.readyState===I.OPEN&&e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Failed to spawn panel ${r.agentId}`}));break}case"input":t.write(r.agentId,r.data,r.source);break;case"kill":te.get(r.agentId)?.(),te.delete(r.agentId),t.kill(r.agentId,r.force);break;case"resize":t.resize(r.agentId,r.cols,r.rows);break;case"detect_agents":Ot(n.agentPaths).then(s=>{nt=s,e.readyState===I.OPEN&&e.send(JSON.stringify({type:"agents",list:s}))});break;case"dir_list":{let s=Te.default.homedir(),i=(r.path||"~").replace(/^~/,s),o=M.default.resolve(i);if(o!==s&&!o.startsWith(s+M.default.sep)){e.readyState===I.OPEN&&e.send(JSON.stringify({type:"error",code:"INVALID_MSG",message:"Path outside home directory"}));return}try{let c=re.default.readdirSync(o,{withFileTypes:!0}).filter(a=>a.isDirectory()&&!a.name.startsWith(".")).map(a=>({name:a.name,path:M.default.join(o,a.name)})).sort((a,l)=>a.name.localeCompare(l.name));e.readyState===I.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:o,entries:c}))}catch(c){e.readyState===I.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:o,entries:[],error:c instanceof Error?c.message:"Cannot read directory"}))}break}default:{let s=r}}}var us="com.jerico.bridge-agent.plist",hs=T.default.join((0,Y.homedir)(),"Library","LaunchAgents"),it=T.default.join(hs,us),or=T.default.join((0,Y.homedir)(),"bridge-daemon.log"),ar=T.default.join((0,Y.homedir)(),"bridge-daemon.err.log"),Pe=T.default.join((0,Y.homedir)(),".bridge","daemon.lock");function sa(){let r=[...process.env.npm_config_global_prefix?[T.default.join(process.env.npm_config_global_prefix,"lib","node_modules","bridge-agent","dist","index.js")]:[],...process.argv[1]?[process.argv[1]]:[],process.execPath];for(let e of r)try{return require("node:fs").realpathSync(e)}catch{}return process.execPath}function ia(){try{(0,$.mkdirSync)(T.default.dirname(Pe),{recursive:!0})}catch{}if((0,$.existsSync)(Pe))try{let{pid:r}=JSON.parse((0,$.readFileSync)(Pe,"utf8"));if(r&&process.kill(r,0))return console.warn("[bridge] daemon.already.running",{pid:r,lock:Pe}),!1}catch{}return(0,$.writeFileSync)(Pe,JSON.stringify({pid:process.pid,startedAt:Date.now()}),"utf8"),!0}function fs(){let r=["claude","codex","qwen","ollama","aider","python3","node","bun","sh"],e=new Set;e.add(T.default.join((0,Y.homedir)(),".nvm","versions","node",`v${process.versions.node}`,"bin")),e.add(T.default.join((0,Y.homedir)(),".local","bin")),e.add("/opt/homebrew/bin"),e.add("/usr/local/bin"),e.add("/usr/bin"),e.add("/bin");let t=process.env.PATH??"";for(let s of t.split(":"))s&&!s.startsWith("/dev")&&!s.startsWith("/tmp")&&e.add(s);for(let s of r)try{let i=(0,ne.execSync)(`which ${s} 2>/dev/null`,{stdio:"pipe"}).toString().trim();i&&i.startsWith("/")&&e.add(T.default.dirname(i))}catch{}let n=T.default.join((0,Y.homedir)(),".vscode","extensions");try{let s=(0,ne.execSync)(`ls "${n}" 2>/dev/null`,{stdio:"pipe"}).toString().split(`
346
- `);for(let i of s)if(i.startsWith("anthropic.claude-code-")){let o=T.default.join(n,i,"resources","native-binary");(0,$.existsSync)(o)&&e.add(o)}}catch{}return[...e].join(":")}function oa(r){try{(0,ne.execSync)(`mkdir -p "${hs}"`,{stdio:"pipe"})}catch{}let e=fs(),t=`<?xml version="1.0" encoding="UTF-8"?>
343
+ ${ia("bridge_get_project","bridge_get_plan","bridge_get_todos","bridge_add_todo","bridge_cancel_run","bridge_get_project_history","bridge_get_execution_status","bridge_list_agents","bridge_get_agent_status","bridge_spawn_worker","bridge_assign_task","bridge_get_todo_context","bridge_get_agent_output","bridge_kill_agent")}`};function oa(r,e,t){if(!e)return[];let n=hs[e];if(!n)return[];if(r==="claude")try{let s=M.default.join(Te.default.tmpdir(),`bridge-role-${t}.md`),i=n.replaceAll("{{PANEL_ID}}",t);return re.default.writeFileSync(s,i+`
344
+ `,"utf-8"),console.log("[daemon] role.prompt.written",{agentId:t,role:e,tmpPath:s}),["--append-system-prompt-file",s]}catch(s){return console.warn("[daemon] role.prompt.write.failed",{agentId:t,role:e,error:String(s)}),[]}return r==="qwen"?["--append-system-prompt",n]:[]}function Pe(r){return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function aa(r){try{let e=process.env.BRIDGE_MCP_URL,t=e?{mcpServers:{bridge:{type:"http",url:`${e}/mcp/${r.workspaceId}/${r.projectId}`,headers:{Authorization:`Bearer ${r.token}`,"x-panel-id":r.agentId??""}}}}:{mcpServers:{bridge:{command:at(),args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:r.projectId,BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}},n=M.default.join(Te.default.tmpdir(),`bridge-mcp-kimi-${r.agentId??r.projectId}.json`);return re.default.writeFileSync(n,JSON.stringify(t,null,2)+`
345
+ `,"utf-8"),console.log("[daemon] kimi.mcp.config.written",{tmpPath:n,transport:e?"http":"stdio"}),["--mcp-config-file",n]}catch(e){return console.warn("[daemon] kimi.mcp.config.build.failed",{error:String(e)}),[]}}function ca(r){try{let e=at(),t=`{BRIDGE_SERVER_URL=${Pe(r.serverUrl)},BRIDGE_TOKEN=${Pe(r.token)},BRIDGE_WORKSPACE_ID=${Pe(r.workspaceId)},BRIDGE_PROJECT_ID=${Pe(r.projectId)},HTTP_MODE="false"}`;return["-c",'mcp_servers.bridge.transport="stdio"',"-c",`mcp_servers.bridge.command=${Pe(e)}`,"-c","mcp_servers.bridge.args=[]","-c",`mcp_servers.bridge.env=${t}`]}catch(e){return console.warn("[daemon] codex.mcp.config.build.failed",{error:String(e)}),[]}}function la(r){try{if(!r.cwd)return console.warn("[daemon] qwen.mcp.setup.skipped",{reason:"missing_cwd",projectId:r.projectId}),!1;let e=at(),t={cwd:r.cwd,encoding:"utf-8",timeout:5e3,stdio:"pipe"};(0,or.spawnSync)("qwen",["mcp","remove","--scope","project","bridge"],t);let n=(0,or.spawnSync)("qwen",["mcp","add","--scope","project","-t","stdio","-e",`BRIDGE_SERVER_URL=${r.serverUrl}`,"-e",`BRIDGE_TOKEN=${r.token}`,"-e",`BRIDGE_WORKSPACE_ID=${r.workspaceId}`,"-e",`BRIDGE_PROJECT_ID=${r.projectId}`,"-e",`BRIDGE_PANEL_ID=${r.agentId??""}`,"-e","HTTP_MODE=false","bridge",e],t);return n.status===0?(console.log("[daemon] qwen.mcp.setup.ok",{cwd:r.cwd,projectId:r.projectId}),!0):(console.warn("[daemon] qwen.mcp.setup.failed",{cwd:r.cwd,projectId:r.projectId,status:n.status,stderr:(n.stderr??"").toString().slice(0,300)}),!1)}catch(e){return console.warn("[daemon] qwen.mcp.setup.error",{error:String(e),projectId:r.projectId}),!1}}var ot=[],cr=!1,ds=!1;function fs(){return cr}function ps(r){if(ds)throw new Error("[daemon] startDaemonConnection called twice \u2014 only one connection manager allowed");ds=!0;let e=Qt(),t=(0,us.createHash)("sha256").update(e.token).digest("hex"),n=null,s=null,i=null,o=0;function c(){s&&(clearTimeout(s),s=null),n=new C(e.server,{headers:{Authorization:`Bearer ${e.token}`}});let l=n,d=null;l.on("open",()=>{cr=!0,console.log("[daemon] ws.connected",{server:e.server}),i=setInterval(()=>{l.readyState===C.OPEN&&l.ping()},Xo);let u=!ls();l.send(JSON.stringify({type:"ready",version:"1.1",name:e.name,spawnHelperBroken:u})),At(e.agentPaths).then(h=>{ot=h,l.readyState===C.OPEN&&l.send(JSON.stringify({type:"agents",list:ot}))}),d=as(h=>{l.readyState===C.OPEN&&l.send(JSON.stringify({type:"system_metrics",daemonId:t,...h}))})}),l.on("message",u=>{let h;try{h=JSON.parse(u.toString())}catch{console.warn("[daemon] Invalid JSON from server, ignoring");return}da(h,l,r,e)}),l.on("close",u=>{cr=!1,i&&(clearInterval(i),i=null),d?.(),d=null,u===1008?(o++,o>=2&&(console.error("[daemon] ws.auth_failed \u2014 token invalid or expired (2 consecutive rejections), stopping. Re-run: bridge-agent auth"),process.exit(1)),console.warn("[daemon] ws.auth_rejected \u2014 transient 1008, will retry once",{attempt:o})):o=0,!s&&(console.log("[daemon] ws.reconnecting",{attempt:1}),s=setTimeout(c,3e3))}),l.on("error",u=>{console.error("[daemon] ws.error",{message:u.message})})}function a(){i&&(clearInterval(i),i=null),Jo();for(let l of te.values())l();r.killAll(),n?.close()}process.on("SIGINT",()=>{a(),process.exit(0)}),process.on("SIGTERM",()=>{a(),process.exit(0)}),process.on("SIGHUP",()=>{a(),process.exit(0)}),process.on("uncaughtException",l=>{console.error("[daemon] uncaughtException",{error:l.message}),r.killAll(),process.exit(1)}),c()}function da(r,e,t,n){switch(r.type){case"spawn":{console.log("[daemon] pty.spawn.start",{agentId:r.agentId,agentKey:r.agentKey,sessionId:r.sessionId,projectId:r.projectId,workspaceId:r.workspaceId,role:r.role});let s=ot.find(m=>m.key===r.agentKey);if(!s){e.readyState===C.OPEN&&e.send(JSON.stringify({type:"error",code:"AGENT_NOT_FOUND",message:`Agent '${r.agentKey}' is not installed on this machine`}));return}let i=oe.find(m=>m.key===r.agentKey),o=[];if(r.sessionId&&i?.resumeArgs)o=i.resumeArgs(r.sessionId),console.log("[daemon] pty.spawn.resume",{agentId:r.agentId,sessionId:r.sessionId}),r.agentKey==="claude"&&(te.get(r.agentId)?.(),te.set(r.agentId,rr(r.agentId,r.sessionId,(m,w,b)=>{e.readyState===C.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:m,usedPct:w,usedTokens:b,...ar}))})));else if(i?.assignSessionId){let m=crypto.randomUUID(),w=r.agentKey==="kimi"?"--session":"--session-id";o=[...i.spawnArgs??[],w,m],e.readyState===C.OPEN&&(e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:m})),console.log("[daemon] session.assigned",{agentId:r.agentId,sessionId:m})),r.agentKey==="claude"&&(te.get(r.agentId)?.(),te.set(r.agentId,rr(r.agentId,m,(b,R,z)=>{e.readyState===C.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:b,usedPct:R,usedTokens:z,...ar}))})))}else e.readyState===C.OPEN&&e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:crypto.randomUUID()}));let c,a=!1,l;if(r.projectId&&r.workspaceId){let m=ra(n.server),w=er(r.cwd);if(c={serverUrl:m,token:n.token,workspaceId:Xn(r.workspaceId),projectId:Qn(r.projectId),agentId:r.agentId?Jn(r.agentId):void 0,cwd:r.cwd,projectEnv:w.env},r.agentKey==="claude"){let b=na(c);a=b.length>0,l=process.env.BRIDGE_MCP_URL?"http":"stdio",o=[...o,...b]}else if(r.agentKey==="codex"){let b=ca(c);a=b.length>0,l="stdio",o=[...o,...b]}else if(r.agentKey==="qwen")a=la(c),l=a?"stdio":void 0;else if(r.agentKey==="kimi"){let b=aa(c);a=b.length>0,l=process.env.BRIDGE_MCP_URL?"http":"stdio",o=[...o,...b]}else a=!1,console.log("[daemon] mcp.config.skipped",{agentId:r.agentId,agentKey:r.agentKey,reason:"unsupported_agent_path"})}let d=oa(r.agentKey,r.role,r.agentId);d.length>0&&(o=[...o,...d]);let u=Math.max(1,Math.min(500,r.cols)),h=Math.max(1,Math.min(500,r.rows)),g=Date.now(),f="",p=0,y=!1,k=!1;if(t.spawn(r.agentId,r.agentKey,s.binaryPath,o,u,h,m=>{p+=m.length;try{let w=Buffer.from(m,"base64").toString("utf-8");if(r.agentKey==="kimi"&&r.role&&!k&&Date.now()-g<3e4&&(/yolo agent/.test(w)||/●/.test(w)||/○/.test(w))){k=!0;let b=hs[r.role];if(b){let R=b.replaceAll("{{PANEL_ID}}",r.agentId),z=zo(R),Re=Buffer.from(z).toString("base64");t.write(r.agentId,Re,"orchestrator"),console.log("[daemon] kimi.role.injected",{agentId:r.agentId,role:r.role})}}}catch{}if(!f)try{let w=Buffer.from(m,"base64").toString("utf-8"),b=ea(w).replace(/\x00/g,"").trim();if(b&&(f=ta(b)),r.agentKey==="codex"&&!y&&Date.now()-g<2e4&&/included in your plan for free|let[’']s build together/i.test(b)&&/yes|no|\[y\/n\]|\(y\/n\)|y\/n/i.test(b)){y=!0;let R=Buffer.from("y").toString("base64");t.write(r.agentId,R,"orchestrator"),console.log("[daemon] codex.onboarding.auto_ack",{agentId:r.agentId})}}catch{}e.readyState===C.OPEN&&e.send(JSON.stringify({type:"output",agentId:r.agentId,data:m}))},(m,w)=>{let b=Date.now()-g,R=b<=Qo;console.log("[daemon] pty.spawn.result",{agentId:r.agentId,agentKey:r.agentKey,daemonId:r.daemonId,exitCode:m,signal:w,uptimeMs:b,earlyExit:R,outputBytes:p,firstOutputSnippet:f||void 0}),R&&e.readyState===C.OPEN&&e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Early exit: agent=${r.agentKey} code=${m??"null"} signal=${w??"null"} snippet="${f||"no output"}"`})),e.readyState===C.OPEN&&e.send(JSON.stringify({type:"exit",agentId:r.agentId,exitCode:m,signal:w}))},c))e.readyState===C.OPEN&&e.send(JSON.stringify({type:"mcp_status",agentId:r.agentId,mcpConfigured:a,transport:a?l:void 0,projectId:c?.projectId}));else{let w=t.getLastError(r.agentId)?.includes("posix_spawnp failed")&&Yo(r.agentKey);e.readyState===C.OPEN&&(w?e.send(JSON.stringify({type:"error",code:"SPAWN_HELPER_BROKEN",message:"node-pty spawn-helper is not executable. Upgrade bridge-agent to v0.2.10+."})):e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Failed to spawn panel ${r.agentId}`})))}break}case"input":t.write(r.agentId,r.data,r.source);break;case"kill":te.get(r.agentId)?.(),te.delete(r.agentId),t.kill(r.agentId,r.force);break;case"resize":t.resize(r.agentId,r.cols,r.rows);break;case"detect_agents":At(n.agentPaths).then(s=>{ot=s,e.readyState===C.OPEN&&e.send(JSON.stringify({type:"agents",list:s}))});break;case"dir_list":{let s=Te.default.homedir(),i=(r.path||"~").replace(/^~/,s),o=M.default.resolve(i);if(o!==s&&!o.startsWith(s+M.default.sep)){e.readyState===C.OPEN&&e.send(JSON.stringify({type:"error",code:"INVALID_MSG",message:"Path outside home directory"}));return}try{let c=re.default.readdirSync(o,{withFileTypes:!0}).filter(a=>a.isDirectory()&&!a.name.startsWith(".")).map(a=>({name:a.name,path:M.default.join(o,a.name)})).sort((a,l)=>a.name.localeCompare(l.name));e.readyState===C.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:o,entries:c}))}catch(c){e.readyState===C.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:o,entries:[],error:c instanceof Error?c.message:"Cannot read directory"}))}break}default:{let s=r}}}var ms="com.jerico.bridge-agent.plist",_s=P.default.join((0,Y.homedir)(),"Library","LaunchAgents"),ct=P.default.join(_s,ms),lr=P.default.join((0,Y.homedir)(),"bridge-daemon.log"),dr=P.default.join((0,Y.homedir)(),"bridge-daemon.err.log"),Ne=P.default.join((0,Y.homedir)(),".bridge","daemon.lock");function ua(){let r=[...process.env.npm_config_global_prefix?[P.default.join(process.env.npm_config_global_prefix,"lib","node_modules","bridge-agent","dist","index.js")]:[],...process.argv[1]?[process.argv[1]]:[],process.execPath];for(let e of r)try{return require("node:fs").realpathSync(e)}catch{}return process.execPath}function ha(){try{(0,B.mkdirSync)(P.default.dirname(Ne),{recursive:!0})}catch{}if((0,B.existsSync)(Ne))try{let{pid:r}=JSON.parse((0,B.readFileSync)(Ne,"utf8"));if(r&&process.kill(r,0))return console.warn("[bridge] daemon.already.running",{pid:r,lock:Ne}),!1}catch{}return(0,B.writeFileSync)(Ne,JSON.stringify({pid:process.pid,startedAt:Date.now()}),"utf8"),!0}function ys(){let r=["claude","codex","qwen","ollama","aider","python3","node","bun","sh"],e=new Set;e.add(P.default.join((0,Y.homedir)(),".nvm","versions","node",`v${process.versions.node}`,"bin")),e.add(P.default.join((0,Y.homedir)(),".local","bin")),e.add("/opt/homebrew/bin"),e.add("/usr/local/bin"),e.add("/usr/bin"),e.add("/bin");let t=process.env.PATH??"";for(let s of t.split(":"))s&&!s.startsWith("/dev")&&!s.startsWith("/tmp")&&e.add(s);for(let s of r)try{let i=(0,ne.execSync)(`which ${s} 2>/dev/null`,{stdio:"pipe"}).toString().trim();i&&i.startsWith("/")&&e.add(P.default.dirname(i))}catch{}let n=P.default.join((0,Y.homedir)(),".vscode","extensions");try{let s=(0,ne.execSync)(`ls "${n}" 2>/dev/null`,{stdio:"pipe"}).toString().split(`
346
+ `);for(let i of s)if(i.startsWith("anthropic.claude-code-")){let o=P.default.join(n,i,"resources","native-binary");(0,B.existsSync)(o)&&e.add(o)}}catch{}return[...e].join(":")}function fa(r){try{(0,ne.execSync)(`mkdir -p "${_s}"`,{stdio:"pipe"})}catch{}let e=ys(),t=`<?xml version="1.0" encoding="UTF-8"?>
347
347
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
348
348
  <plist version="1.0">
349
349
  <dict>
@@ -359,9 +359,9 @@ ${Qo("bridge_get_project","bridge_get_plan","bridge_get_todos","bridge_add_todo"
359
359
  <key>KeepAlive</key>
360
360
  <true/>
361
361
  <key>StandardOutPath</key>
362
- <string>${or}</string>
362
+ <string>${lr}</string>
363
363
  <key>StandardErrorPath</key>
364
- <string>${ar}</string>
364
+ <string>${dr}</string>
365
365
  <key>EnvironmentVariables</key>
366
366
  <dict>
367
367
  <key>PATH</key>
@@ -371,6 +371,6 @@ ${Qo("bridge_get_project","bridge_get_plan","bridge_get_todos","bridge_add_todo"
371
371
  </dict>
372
372
  </dict>
373
373
  </plist>
374
- `;try{return(0,$.writeFileSync)(it,t,"utf-8"),!0}catch(n){return console.warn("[bridge] launchd.plist.write.failed",{error:String(n)}),!1}}function aa(){try{return(0,ne.execSync)(`launchctl kickstart -kp gui/$(id -u)/${us} 2>/dev/null; launchctl unload "${it}" 2>/dev/null; launchctl load "${it}"`,{stdio:"pipe"}),{ok:!0,permissionDenied:!1}}catch(r){let e=String(r);return{ok:!1,permissionDenied:e.includes("Permission denied")||e.includes("not allowed")||e.includes("bootstrap")}}}function ca(r){try{let e=(0,ne.spawn)(r,["start"],{detached:!0,stdio:"ignore",env:{...process.env,PATH:fs(),BRIDGE_DAEMON:"1"}});e.unref(),setTimeout(()=>{e.pid&&process.kill(e.pid,0)?(console.log("[bridge] daemon.pid",{pid:e.pid}),console.log("[bridge] background.ok",{log:or})):console.error("[bridge] background.failed \u2014 check: tail -f",{log:ar})},2e3)}catch(e){console.error("[bridge] background.spawn.failed",{error:String(e)})}}function la(){let r=parseInt(process.env.HEALTH_PORT??"3101",10),e=Date.now()+6e3,t=()=>{if(Date.now()>e){console.error("[bridge] health.verify.timeout \u2014 daemon may have crashed immediately");return}try{let s=require("node:http").get(`http://127.0.0.1:${r}/health`,i=>{i.statusCode===200?console.log("[bridge] health.verify.ok"):setTimeout(t,500)});s.on("error",()=>{setTimeout(t,500)}),s.setTimeout(1e3,()=>{s.destroy(),setTimeout(t,500)})}catch{setTimeout(t,500)}};setTimeout(t,1e3)}function da(){let r=new Be;ls(r);let e=parseInt(process.env.HEALTH_PORT??"3101",10),t=(0,ds.createServer)((n,s)=>{let i=cs(),o=JSON.stringify({status:"ok",connected:i,uptime:process.uptime()});s.writeHead(i?200:503,{"Content-Type":"application/json"}),s.end(o)});t.listen(e,"127.0.0.1",()=>{console.log(`[bridge] health. listening on 127.0.0.1:${e}`)}),t.on("error",n=>{console.error("[bridge] health.error",{error:n.message})})}function ps(){let r=process.env.BRIDGE_DAEMON==="1"||process.argv.includes("--daemon");if(console.log("[bridge] Starting bridge-agent daemon..."),r){da();return}ia()||(console.warn("[bridge] start.aborted.already.running"),process.exit(1));let e=sa(),t=oa(e),{ok:n,permissionDenied:s}=t?aa():{ok:!1,permissionDenied:!1};if(n){console.log("[bridge] launchd.ok \u2014 managed, auto-restart enabled"),console.log("[bridge] logs: tail -f",{out:or,err:ar}),la(),process.exit(0);return}s&&(console.warn("[bridge] launchd.permission.denied"),console.warn("[bridge] \u2192 Auto-start on login requires:"),console.warn(`[bridge] sudo launchctl bootstrap gui/$(id -u) "${it}"`),console.warn(`[bridge] Falling back to background process...
375
- `)),ca(e),process.exit(0)}var gs=y(require("https")),ms=y(require("http"));tt();function ua(r){return(r??"").trim()}async function _s(r,e=!1,t){console.log("[bridge] Starting auth flow..."),console.log(`[bridge] Server: ${r}`),console.log("[bridge] Open this URL to generate a daemon token:"),console.log(` ${r}/connect`);let n=ua(t);n&&console.log("[bridge] Using token from --token"),e&&(n?console.log("[bridge] --no-browser ignored because --token is provided."):(console.log("[bridge] --no-browser: exiting after printing URL."),process.exit(0)));let s=n;s||(console.log(),console.log("[bridge] After authenticating, paste your token here:"),s=await ha()),s||(console.error("[bridge] No token provided. Exiting."),process.exit(1)),await fa(r,s)||(console.error("[bridge] Token validation failed. Please try again."),process.exit(1));let c=r.replace(/^https?:\/\//,a=>a.startsWith("https")?"wss://":"ws://").replace(/\/?$/,"/ws/daemon");Jt({server:c,token:s,name:process.env.HOSTNAME??"My Machine"}),console.log("[bridge] Auth successful! Config saved to ~/.bridge/config.json"),console.log("[bridge] Run: bridge-agent start"),process.exit(0)}async function ha(){return new Promise(r=>{process.stdout.write("Token: ");let e="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",t=>{e+=t,e.includes(`
376
- `)&&(process.stdin.pause(),r(e.trim()))}),process.stdin.resume()})}async function fa(r,e){return new Promise(t=>{let n=new URL("/api/tokens/validate",r),s=n.protocol==="https:",i=s?gs.default:ms.default,o={hostname:n.hostname,port:n.port||(s?443:80),path:n.pathname,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}},c=i.request(o,a=>{t(a.statusCode===200)});c.on("error",()=>t(!1)),c.end()})}var Ne=new wr;Ne.name("bridge-agent").description("Bridge local agent \u2014 connects your AI tools to Jerico").version("0.2.10");Ne.command("start").description("Start the bridge-agent daemon").action(()=>{ps()});Ne.command("auth").description("Authenticate with Bridge server").requiredOption("-s, --server <url>","Server URL (e.g., https://your-server.com)").option("-t, --token <token>","Use token non-interactively").option("--no-browser","Print auth URL without opening browser or interactive prompt").action(r=>{_s(r.server,!r.browser,r.token)});Ne.command("status").description("Show connection status").action(async()=>{try{let{loadConfig:r}=await Promise.resolve().then(()=>(tt(),Xn)),e=r();console.log("[bridge] Config found"),console.log(" Server:",e.server),console.log(" Name:",e.name)}catch{console.log("[bridge] Not authenticated. Run: bridge-agent auth")}});Ne.parse();
374
+ `;try{return(0,B.writeFileSync)(ct,t,"utf-8"),!0}catch(n){return console.warn("[bridge] launchd.plist.write.failed",{error:String(n)}),!1}}function pa(){try{return(0,ne.execSync)(`launchctl kickstart -kp gui/$(id -u)/${ms} 2>/dev/null; launchctl unload "${ct}" 2>/dev/null; launchctl load "${ct}"`,{stdio:"pipe"}),{ok:!0,permissionDenied:!1}}catch(r){let e=String(r);return{ok:!1,permissionDenied:e.includes("Permission denied")||e.includes("not allowed")||e.includes("bootstrap")}}}function ga(r){try{let e=(0,ne.spawn)(r,["start"],{detached:!0,stdio:"ignore",env:{...process.env,PATH:ys(),BRIDGE_DAEMON:"1"}});e.unref(),setTimeout(()=>{e.pid&&process.kill(e.pid,0)?(console.log("[bridge] daemon.pid",{pid:e.pid}),console.log("[bridge] background.ok",{log:lr})):console.error("[bridge] background.failed \u2014 check: tail -f",{log:dr})},2e3)}catch(e){console.error("[bridge] background.spawn.failed",{error:String(e)})}}function ma(){let r=parseInt(process.env.HEALTH_PORT??"3101",10),e=Date.now()+6e3,t=()=>{if(Date.now()>e){console.error("[bridge] health.verify.timeout \u2014 daemon may have crashed immediately");return}try{let s=require("node:http").get(`http://127.0.0.1:${r}/health`,i=>{i.statusCode===200?console.log("[bridge] health.verify.ok"):setTimeout(t,500)});s.on("error",()=>{setTimeout(t,500)}),s.setTimeout(1e3,()=>{s.destroy(),setTimeout(t,500)})}catch{setTimeout(t,500)}};setTimeout(t,1e3)}function _a(){let r=new Ue;ps(r);let e=parseInt(process.env.HEALTH_PORT??"3101",10),t=(0,gs.createServer)((n,s)=>{let i=fs(),o=JSON.stringify({status:"ok",connected:i,uptime:process.uptime()});s.writeHead(i?200:503,{"Content-Type":"application/json"}),s.end(o)});t.listen(e,"127.0.0.1",()=>{console.log(`[bridge] health. listening on 127.0.0.1:${e}`)}),t.on("error",n=>{console.error("[bridge] health.error",{error:n.message})})}function bs(){let r=process.env.BRIDGE_DAEMON==="1"||process.argv.includes("--daemon");if(console.log("[bridge] Starting bridge-agent daemon..."),r){_a();return}ha()||(console.warn("[bridge] start.aborted.already.running"),process.exit(1));let e=ua(),t=fa(e),{ok:n,permissionDenied:s}=t?pa():{ok:!1,permissionDenied:!1};if(n){console.log("[bridge] launchd.ok \u2014 managed, auto-restart enabled"),console.log("[bridge] logs: tail -f",{out:lr,err:dr}),ma(),process.exit(0);return}s&&(console.warn("[bridge] launchd.permission.denied"),console.warn("[bridge] \u2192 Auto-start on login requires:"),console.warn(`[bridge] sudo launchctl bootstrap gui/$(id -u) "${ct}"`),console.warn(`[bridge] Falling back to background process...
375
+ `)),ga(e),process.exit(0)}var ws=_(require("https")),Ss=_(require("http"));rt();function ya(r){return(r??"").trim()}async function Es(r,e=!1,t){console.log("[bridge] Starting auth flow..."),console.log(`[bridge] Server: ${r}`),console.log("[bridge] Open this URL to generate a daemon token:"),console.log(` ${r}/connect`);let n=ya(t);n&&console.log("[bridge] Using token from --token"),e&&(n?console.log("[bridge] --no-browser ignored because --token is provided."):(console.log("[bridge] --no-browser: exiting after printing URL."),process.exit(0)));let s=n;s||(console.log(),console.log("[bridge] After authenticating, paste your token here:"),s=await ba()),s||(console.error("[bridge] No token provided. Exiting."),process.exit(1)),await wa(r,s)||(console.error("[bridge] Token validation failed. Please try again."),process.exit(1));let c=r.replace(/^https?:\/\//,a=>a.startsWith("https")?"wss://":"ws://").replace(/\/?$/,"/ws/daemon");Zt({server:c,token:s,name:process.env.HOSTNAME??"My Machine"}),console.log("[bridge] Auth successful! Config saved to ~/.bridge/config.json"),console.log("[bridge] Run: bridge-agent start"),process.exit(0)}async function ba(){return new Promise(r=>{process.stdout.write("Token: ");let e="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",t=>{e+=t,e.includes(`
376
+ `)&&(process.stdin.pause(),r(e.trim()))}),process.stdin.resume()})}async function wa(r,e){return new Promise(t=>{let n=new URL("/api/tokens/validate",r),s=n.protocol==="https:",i=s?ws.default:Ss.default,o={hostname:n.hostname,port:n.port||(s?443:80),path:n.pathname,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}},c=i.request(o,a=>{t(a.statusCode===200)});c.on("error",()=>t(!1)),c.end()})}var De=new xr;De.name("bridge-agent").description("Bridge local agent \u2014 connects your AI tools to Jerico").version("0.2.11");De.command("start").description("Start the bridge-agent daemon").action(()=>{bs()});De.command("auth").description("Authenticate with Bridge server").requiredOption("-s, --server <url>","Server URL (e.g., https://your-server.com)").option("-t, --token <token>","Use token non-interactively").option("--no-browser","Print auth URL without opening browser or interactive prompt").action(r=>{Es(r.server,!r.browser,r.token)});De.command("status").description("Show connection status").action(async()=>{try{let{loadConfig:r}=await Promise.resolve().then(()=>(rt(),es)),e=r();console.log("[bridge] Config found"),console.log(" Server:",e.server),console.log(" Name:",e.name)}catch{console.log("[bridge] Not authenticated. Run: bridge-agent auth")}});De.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bridge-agent",
3
- "version": "0.2.10",
3
+ "version": "0.2.11",
4
4
  "description": "Bridge local agent — connects your AI tools to Jerico",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -51,6 +51,7 @@
51
51
  "esbuild": "^0.27.4",
52
52
  "typescript": "^5.4.0",
53
53
  "which": "^4.0.0",
54
- "ws": "^8.17.0"
54
+ "ws": "^8.17.0",
55
+ "@jerico/shared": "workspace:*"
55
56
  }
56
57
  }