@segosolutions/auto-task 1.7.7 → 1.7.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -22,16 +22,16 @@ Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
22
22
  `),this.outputHelp({error:!0}));let i=t||{},a=i.exitCode||1,c=i.code||"commander.error";this._exit(a,c,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in ce.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()}`,ce.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new im(this.options),t=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(a=>!t(a)).forEach(a=>{this.setOptionValueWithSource(a,i.implied[a],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let i=u=>{let p=u.attributeName(),g=this.getOptionValue(p),m=this.options.find(w=>w.negate&&p===w.attributeName()),_=this.options.find(w=>!w.negate&&p===w.attributeName());return m&&(m.presetArg===void 0&&g===!1||m.presetArg!==void 0&&g===m.presetArg)?m:_||u},a=u=>{let p=i(u),g=p.attributeName();return this.getOptionValueSource(g)==="env"?`environment variable '${p.envVar}'`:`option '${p.flags}'`},c=`error: ${a(e)} cannot be used with ${a(t)}`;this.error(c,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let a=[],c=this;do{let u=c.createHelp().visibleOptions(c).filter(p=>p.long).map(p=>p.long);a=a.concat(u),c=c.parent}while(c&&!c._enablePositionalOptions);t=Oc(e,a)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",c=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(c,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let a=[];this.createHelp().visibleCommands(this).forEach(c=>{a.push(c.name()),c.alias()&&a.push(c.alias())}),t=Oc(e,a)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let a=this.createOption(t,i);return this._versionOptionName=a.attributeName(),this._registerOption(a),this.on("option:"+a.name(),()=>{this._outputConfiguration.writeOut(`${e}
23
23
  `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let a=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${a}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(i=>nm(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Ye.basename(e,Ye.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},i;return t.error?i=a=>this._outputConfiguration.writeErr(a):i=a=>this._outputConfiguration.writeOut(a),t.write=e.write||i,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(c=>c.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let a=this.helpInformation(i);if(t&&(a=t(a),typeof a!="string"&&!Buffer.isBuffer(a)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(a),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(c=>c.emit("afterAllHelp",i))}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=ce.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
24
24
  Expecting one of '${i.join("', '")}'`);let a=`${e}Help`;return this.on(a,c=>{let u;typeof t=="function"?u=t({error:c.error,command:c.command}):u=t,u&&c.write(`${u}
25
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(a=>t.is(a))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Tc(s){return s.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",a="9229",c;return(c=e.match(/^(--inspect(-brk)?)$/))!==null?t=c[1]:(c=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=c[1],/^\d+$/.test(c[3])?a=c[3]:i=c[3]):(c=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=c[1],i=c[3],a=c[4]),t&&a!=="0"?`${t}=${i}:${parseInt(a)+1}`:e})}Sc.Command=Lr});var Mc=$(Me=>{var{Argument:Rc}=Js(),{Command:Dr}=Ac(),{CommanderError:om,InvalidArgumentError:Pc}=hs(),{Help:am}=Sr(),{Option:Ic}=Ir();Me.program=new Dr;Me.createCommand=s=>new Dr(s);Me.createOption=(s,e)=>new Ic(s,e);Me.createArgument=(s,e)=>new Rc(s,e);Me.Command=Dr;Me.Option=Ic;Me.Argument=Rc;Me.Help=am;Me.CommanderError=om;Me.InvalidArgumentError=Pc;Me.InvalidOptionArgumentError=Pc});var Nc=$((oC,cm)=>{cm.exports={name:"dotenv",version:"17.2.3",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var Bc=$((aC,Qe)=>{var Ur=q("fs"),Ys=q("path"),lm=q("os"),um=q("crypto"),hm=Nc(),jr=hm.version,Lc=["\u{1F510} encrypt with Dotenvx: https://dotenvx.com","\u{1F510} prevent committing .env to code: https://dotenvx.com/precommit","\u{1F510} prevent building .env in docker: https://dotenvx.com/prebuild","\u{1F4E1} add observability to secrets: https://dotenvx.com/ops","\u{1F465} sync secrets across teammates & machines: https://dotenvx.com/ops","\u{1F5C2}\uFE0F backup and recover secrets: https://dotenvx.com/ops","\u2705 audit secrets and track compliance: https://dotenvx.com/ops","\u{1F504} add secrets lifecycle management: https://dotenvx.com/ops","\u{1F511} add access controls to secrets: https://dotenvx.com/ops","\u{1F6E0}\uFE0F run anywhere with `dotenvx run -- yourcommand`","\u2699\uFE0F specify custom .env file path with { path: '/custom/path/.env' }","\u2699\uFE0F enable debug logging with { debug: true }","\u2699\uFE0F override existing env vars with { override: true }","\u2699\uFE0F suppress all logs with { quiet: true }","\u2699\uFE0F write to custom object with { processEnv: myObject }","\u2699\uFE0F load multiple .env files with { path: ['.env.local', '.env'] }"];function dm(){return Lc[Math.floor(Math.random()*Lc.length)]}function xt(s){return typeof s=="string"?!["false","0","no","off",""].includes(s.toLowerCase()):!!s}function fm(){return process.stdout.isTTY}function pm(s){return fm()?`\x1B[2m${s}\x1B[0m`:s}var gm=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function mm(s){let e={},t=s.toString();t=t.replace(/\r\n?/mg,`
25
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(a=>t.is(a))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Tc(s){return s.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",a="9229",c;return(c=e.match(/^(--inspect(-brk)?)$/))!==null?t=c[1]:(c=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=c[1],/^\d+$/.test(c[3])?a=c[3]:i=c[3]):(c=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=c[1],i=c[3],a=c[4]),t&&a!=="0"?`${t}=${i}:${parseInt(a)+1}`:e})}Sc.Command=Lr});var Mc=$(Me=>{var{Argument:Rc}=Js(),{Command:Dr}=Ac(),{CommanderError:om,InvalidArgumentError:Pc}=hs(),{Help:am}=Sr(),{Option:Ic}=Ir();Me.program=new Dr;Me.createCommand=s=>new Dr(s);Me.createOption=(s,e)=>new Ic(s,e);Me.createArgument=(s,e)=>new Rc(s,e);Me.Command=Dr;Me.Option=Ic;Me.Argument=Rc;Me.Help=am;Me.CommanderError=om;Me.InvalidArgumentError=Pc;Me.InvalidOptionArgumentError=Pc});var Nc=$((uC,cm)=>{cm.exports={name:"dotenv",version:"17.2.3",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var Bc=$((hC,Qe)=>{var Ur=q("fs"),Ys=q("path"),lm=q("os"),um=q("crypto"),hm=Nc(),jr=hm.version,Lc=["\u{1F510} encrypt with Dotenvx: https://dotenvx.com","\u{1F510} prevent committing .env to code: https://dotenvx.com/precommit","\u{1F510} prevent building .env in docker: https://dotenvx.com/prebuild","\u{1F4E1} add observability to secrets: https://dotenvx.com/ops","\u{1F465} sync secrets across teammates & machines: https://dotenvx.com/ops","\u{1F5C2}\uFE0F backup and recover secrets: https://dotenvx.com/ops","\u2705 audit secrets and track compliance: https://dotenvx.com/ops","\u{1F504} add secrets lifecycle management: https://dotenvx.com/ops","\u{1F511} add access controls to secrets: https://dotenvx.com/ops","\u{1F6E0}\uFE0F run anywhere with `dotenvx run -- yourcommand`","\u2699\uFE0F specify custom .env file path with { path: '/custom/path/.env' }","\u2699\uFE0F enable debug logging with { debug: true }","\u2699\uFE0F override existing env vars with { override: true }","\u2699\uFE0F suppress all logs with { quiet: true }","\u2699\uFE0F write to custom object with { processEnv: myObject }","\u2699\uFE0F load multiple .env files with { path: ['.env.local', '.env'] }"];function dm(){return Lc[Math.floor(Math.random()*Lc.length)]}function xt(s){return typeof s=="string"?!["false","0","no","off",""].includes(s.toLowerCase()):!!s}function fm(){return process.stdout.isTTY}function pm(s){return fm()?`\x1B[2m${s}\x1B[0m`:s}var gm=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function mm(s){let e={},t=s.toString();t=t.replace(/\r\n?/mg,`
26
26
  `);let i;for(;(i=gm.exec(t))!=null;){let a=i[1],c=i[2]||"";c=c.trim();let u=c[0];c=c.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),u==='"'&&(c=c.replace(/\\n/g,`
27
- `),c=c.replace(/\\r/g,"\r")),e[a]=c}return e}function ym(s){s=s||{};let e=qc(s);s.path=e;let t=he.configDotenv(s);if(!t.parsed){let u=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw u.code="MISSING_DATA",u}let i=jc(s).split(","),a=i.length,c;for(let u=0;u<a;u++)try{let p=i[u].trim(),g=bm(t,p);c=he.decrypt(g.ciphertext,g.key);break}catch(p){if(u+1>=a)throw p}return he.parse(c)}function _m(s){console.error(`[dotenv@${jr}][WARN] ${s}`)}function fs(s){console.log(`[dotenv@${jr}][DEBUG] ${s}`)}function Uc(s){console.log(`[dotenv@${jr}] ${s}`)}function jc(s){return s&&s.DOTENV_KEY&&s.DOTENV_KEY.length>0?s.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function bm(s,e){let t;try{t=new URL(e)}catch(p){if(p.code==="ERR_INVALID_URL"){let g=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw g.code="INVALID_DOTENV_KEY",g}throw p}let i=t.password;if(!i){let p=new Error("INVALID_DOTENV_KEY: Missing key part");throw p.code="INVALID_DOTENV_KEY",p}let a=t.searchParams.get("environment");if(!a){let p=new Error("INVALID_DOTENV_KEY: Missing environment part");throw p.code="INVALID_DOTENV_KEY",p}let c=`DOTENV_VAULT_${a.toUpperCase()}`,u=s.parsed[c];if(!u){let p=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${c} in your .env.vault file.`);throw p.code="NOT_FOUND_DOTENV_ENVIRONMENT",p}return{ciphertext:u,key:i}}function qc(s){let e=null;if(s&&s.path&&s.path.length>0)if(Array.isArray(s.path))for(let t of s.path)Ur.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=s.path.endsWith(".vault")?s.path:`${s.path}.vault`;else e=Ys.resolve(process.cwd(),".env.vault");return Ur.existsSync(e)?e:null}function Dc(s){return s[0]==="~"?Ys.join(lm.homedir(),s.slice(1)):s}function vm(s){let e=xt(process.env.DOTENV_CONFIG_DEBUG||s&&s.debug),t=xt(process.env.DOTENV_CONFIG_QUIET||s&&s.quiet);(e||!t)&&Uc("Loading env from encrypted .env.vault");let i=he._parseVault(s),a=process.env;return s&&s.processEnv!=null&&(a=s.processEnv),he.populate(a,i,s),{parsed:i}}function wm(s){let e=Ys.resolve(process.cwd(),".env"),t="utf8",i=process.env;s&&s.processEnv!=null&&(i=s.processEnv);let a=xt(i.DOTENV_CONFIG_DEBUG||s&&s.debug),c=xt(i.DOTENV_CONFIG_QUIET||s&&s.quiet);s&&s.encoding?t=s.encoding:a&&fs("No encoding is specified. UTF-8 is used by default");let u=[e];if(s&&s.path)if(!Array.isArray(s.path))u=[Dc(s.path)];else{u=[];for(let _ of s.path)u.push(Dc(_))}let p,g={};for(let _ of u)try{let w=he.parse(Ur.readFileSync(_,{encoding:t}));he.populate(g,w,s)}catch(w){a&&fs(`Failed to load ${_} ${w.message}`),p=w}let m=he.populate(i,g,s);if(a=xt(i.DOTENV_CONFIG_DEBUG||a),c=xt(i.DOTENV_CONFIG_QUIET||c),a||!c){let _=Object.keys(m).length,w=[];for(let C of u)try{let T=Ys.relative(process.cwd(),C);w.push(T)}catch(T){a&&fs(`Failed to load ${C} ${T.message}`),p=T}Uc(`injecting env (${_}) from ${w.join(",")} ${pm(`-- tip: ${dm()}`)}`)}return p?{parsed:g,error:p}:{parsed:g}}function Cm(s){if(jc(s).length===0)return he.configDotenv(s);let e=qc(s);return e?he._configVault(s):(_m(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),he.configDotenv(s))}function Em(s,e){let t=Buffer.from(e.slice(-64),"hex"),i=Buffer.from(s,"base64"),a=i.subarray(0,12),c=i.subarray(-16);i=i.subarray(12,-16);try{let u=um.createDecipheriv("aes-256-gcm",t,a);return u.setAuthTag(c),`${u.update(i)}${u.final()}`}catch(u){let p=u instanceof RangeError,g=u.message==="Invalid key length",m=u.message==="Unsupported state or unable to authenticate data";if(p||g){let _=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw _.code="INVALID_DOTENV_KEY",_}else if(m){let _=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw _.code="DECRYPTION_FAILED",_}else throw u}}function km(s,e,t={}){let i=!!(t&&t.debug),a=!!(t&&t.override),c={};if(typeof e!="object"){let u=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw u.code="OBJECT_REQUIRED",u}for(let u of Object.keys(e))Object.prototype.hasOwnProperty.call(s,u)?(a===!0&&(s[u]=e[u],c[u]=e[u]),i&&fs(a===!0?`"${u}" is already defined and WAS overwritten`:`"${u}" is already defined and was NOT overwritten`)):(s[u]=e[u],c[u]=e[u]);return c}var he={configDotenv:wm,_configVault:vm,_parseVault:ym,config:Cm,decrypt:Em,parse:mm,populate:km};Qe.exports.configDotenv=he.configDotenv;Qe.exports._configVault=he._configVault;Qe.exports._parseVault=he._parseVault;Qe.exports.config=he.config;Qe.exports.decrypt=he.decrypt;Qe.exports.parse=he.parse;Qe.exports.populate=he.populate;Qe.exports=he});var Xe=$((wC,hl)=>{"use strict";var ll=["nodebuffer","arraybuffer","fragments"],ul=typeof Blob<"u";ul&&ll.push("blob");hl.exports={BINARY_TYPES:ll,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ul,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ps=$((CC,en)=>{"use strict";var{EMPTY_BUFFER:Wm}=Xe(),Gr=Buffer[Symbol.species];function Vm(s,e){if(s.length===0)return Wm;if(s.length===1)return s[0];let t=Buffer.allocUnsafe(e),i=0;for(let a=0;a<s.length;a++){let c=s[a];t.set(c,i),i+=c.length}return i<e?new Gr(t.buffer,t.byteOffset,i):t}function dl(s,e,t,i,a){for(let c=0;c<a;c++)t[i+c]=s[c]^e[c&3]}function fl(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}function zm(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}function Fr(s){if(Fr.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new Gr(s):ArrayBuffer.isView(s)?e=new Gr(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),Fr.readOnly=!1),e}en.exports={concat:Vm,mask:dl,toArrayBuffer:zm,toBuffer:Fr,unmask:fl};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=q("bufferutil");en.exports.mask=function(e,t,i,a,c){c<48?dl(e,t,i,a,c):s.mask(e,t,i,a,c)},en.exports.unmask=function(e,t){e.length<32?fl(e,t):s.unmask(e,t)}}catch{}});var ml=$((EC,gl)=>{"use strict";var pl=Symbol("kDone"),Wr=Symbol("kRun"),Vr=class{constructor(e){this[pl]=()=>{this.pending--,this[Wr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Wr]()}[Wr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[pl])}}};gl.exports=Vr});var ms=$((kC,vl)=>{"use strict";var gs=q("zlib"),yl=ps(),Km=ml(),{kStatusCode:_l}=Xe(),Jm=Buffer[Symbol.species],Ym=Buffer.from([0,0,255,255]),sn=Symbol("permessage-deflate"),Ze=Symbol("total-length"),Dt=Symbol("callback"),ut=Symbol("buffers"),Ut=Symbol("error"),tn,zr=class{constructor(e,t,i){if(this._maxPayload=i|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!tn){let a=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;tn=new Km(a)}}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[Dt];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,i=e.find(a=>!(t.serverNoContextTakeover===!1&&a.server_no_context_takeover||a.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>a.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!a.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(i.server_no_context_takeover=!0),t.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(i.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?i.client_max_window_bits=t.clientMaxWindowBits:(i.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}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(i=>{let a=t[i];if(a.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(a=a[0],i==="client_max_window_bits"){if(a!==!0){let c=+a;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${a}`);a=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${a}`)}else if(i==="server_max_window_bits"){let c=+a;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${a}`);a=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(a!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${a}`)}else throw new Error(`Unknown parameter "${i}"`);t[i]=a})}),e}decompress(e,t,i){tn.add(a=>{this._decompress(e,t,(c,u)=>{a(),i(c,u)})})}compress(e,t,i){tn.add(a=>{this._compress(e,t,(c,u)=>{a(),i(c,u)})})}_decompress(e,t,i){let a=this._isServer?"client":"server";if(!this._inflate){let c=`${a}_max_window_bits`,u=typeof this.params[c]!="number"?gs.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=gs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:u}),this._inflate[sn]=this,this._inflate[Ze]=0,this._inflate[ut]=[],this._inflate.on("error",Xm),this._inflate.on("data",bl)}this._inflate[Dt]=i,this._inflate.write(e),t&&this._inflate.write(Ym),this._inflate.flush(()=>{let c=this._inflate[Ut];if(c){this._inflate.close(),this._inflate=null,i(c);return}let u=yl.concat(this._inflate[ut],this._inflate[Ze]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ze]=0,this._inflate[ut]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,u)})}_compress(e,t,i){let a=this._isServer?"server":"client";if(!this._deflate){let c=`${a}_max_window_bits`,u=typeof this.params[c]!="number"?gs.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=gs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:u}),this._deflate[Ze]=0,this._deflate[ut]=[],this._deflate.on("data",Qm)}this._deflate[Dt]=i,this._deflate.write(e),this._deflate.flush(gs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=yl.concat(this._deflate[ut],this._deflate[Ze]);t&&(c=new Jm(c.buffer,c.byteOffset,c.length-4)),this._deflate[Dt]=null,this._deflate[Ze]=0,this._deflate[ut]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};vl.exports=zr;function Qm(s){this[ut].push(s),this[Ze]+=s.length}function bl(s){if(this[Ze]+=s.length,this[sn]._maxPayload<1||this[Ze]<=this[sn]._maxPayload){this[ut].push(s);return}this[Ut]=new RangeError("Max payload size exceeded"),this[Ut].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ut][_l]=1009,this.removeListener("data",bl),this.reset()}function Xm(s){if(this[sn]._inflate=null,this[Ut]){this[Dt](this[Ut]);return}s[_l]=1007,this[Dt](s)}});var jt=$((OC,nn)=>{"use strict";var{isUtf8:wl}=q("buffer"),{hasBlob:Zm}=Xe(),ey=[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 ty(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}function Kr(s){let e=s.length,t=0;for(;t<e;)if(!(s[t]&128))t++;else if((s[t]&224)===192){if(t+1===e||(s[t+1]&192)!==128||(s[t]&254)===192)return!1;t+=2}else if((s[t]&240)===224){if(t+2>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||s[t]===224&&(s[t+1]&224)===128||s[t]===237&&(s[t+1]&224)===160)return!1;t+=3}else if((s[t]&248)===240){if(t+3>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||(s[t+3]&192)!==128||s[t]===240&&(s[t+1]&240)===128||s[t]===244&&s[t+1]>143||s[t]>244)return!1;t+=4}else return!1;return!0}function sy(s){return Zm&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}nn.exports={isBlob:sy,isValidStatusCode:ty,isValidUTF8:Kr,tokenChars:ey};if(wl)nn.exports.isValidUTF8=function(s){return s.length<24?Kr(s):wl(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=q("utf-8-validate");nn.exports.isValidUTF8=function(e){return e.length<32?Kr(e):s(e)}}catch{}});var Zr=$((TC,Al)=>{"use strict";var{Writable:ny}=q("stream"),Cl=ms(),{BINARY_TYPES:ry,EMPTY_BUFFER:El,kStatusCode:iy,kWebSocket:oy}=Xe(),{concat:Jr,toArrayBuffer:ay,unmask:cy}=ps(),{isValidStatusCode:ly,isValidUTF8:kl}=jt(),rn=Buffer[Symbol.species],xe=0,Ol=1,Tl=2,Sl=3,Yr=4,Qr=5,on=6,Xr=class extends ny{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ry[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[oy]=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=xe}_write(e,t,i){if(this._opcode===8&&this._state==xe)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new rn(i.buffer,i.byteOffset+e,i.length-e),new rn(i.buffer,i.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let i=this._buffers[0],a=t.length-e;e>=i.length?t.set(this._buffers.shift(),a):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),a),this._buffers[0]=new rn(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case xe:this.getInfo(e);break;case Ol:this.getPayloadLength16(e);break;case Tl:this.getPayloadLength64(e);break;case Sl:this.getMask();break;case Yr:this.getData(e);break;case Qr:case on: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){let a=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(a);return}let i=(t[0]&64)===64;if(i&&!this._extensions[Cl.extensionName]){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(a);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(i){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(a);return}if(!this._fragmented){let a=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(a);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let a=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(a);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let a=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(a);return}if(i){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(a);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let a=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(a);return}}else{let a=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(a);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let a=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(a);return}}else if(this._masked){let a=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(a);return}this._payloadLength===126?this._state=Ol:this._payloadLength===127?this._state=Tl: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),i=t.readUInt32BE(0);if(i>Math.pow(2,21)-1){let a=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(a);return}this._payloadLength=i*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=Sl:this._state=Yr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Yr}getData(e){let t=El;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]&&cy(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Qr,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Cl.extensionName].decompress(e,this._fin,(a,c)=>{if(a)return t(a);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let u=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(u);return}this._fragments.push(c)}this.dataMessage(t),this._state===xe&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=xe;return}let t=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let a;this._binaryType==="nodebuffer"?a=Jr(i,t):this._binaryType==="arraybuffer"?a=ay(Jr(i,t)):this._binaryType==="blob"?a=new Blob(i):a=i,this._allowSynchronousEvents?(this.emit("message",a,!0),this._state=xe):(this._state=on,setImmediate(()=>{this.emit("message",a,!0),this._state=xe,this.startLoop(e)}))}else{let a=Jr(i,t);if(!this._skipUTF8Validation&&!kl(a)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Qr||this._allowSynchronousEvents?(this.emit("message",a,!1),this._state=xe):(this._state=on,setImmediate(()=>{this.emit("message",a,!1),this._state=xe,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,El),this.end();else{let i=e.readUInt16BE(0);if(!ly(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(c);return}let a=new rn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!kl(a)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(c);return}this._loop=!1,this.emit("conclude",i,a),this.end()}this._state=xe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=xe):(this._state=on,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=xe,this.startLoop(t)}))}createError(e,t,i,a,c){this._loop=!1,this._errored=!0;let u=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(u,this.createError),u.code=c,u[iy]=a,u}};Al.exports=Xr});var si=$((AC,Il)=>{"use strict";var{Duplex:SC}=q("stream"),{randomFillSync:uy}=q("crypto"),Rl=ms(),{EMPTY_BUFFER:hy,kWebSocket:dy,NOOP:fy}=Xe(),{isBlob:qt,isValidStatusCode:py}=jt(),{mask:Pl,toBuffer:_t}=ps(),Ne=Symbol("kByteLength"),gy=Buffer.alloc(4),an=8*1024,bt,Bt=an,$e=0,my=1,yy=2,ei=class s{constructor(e,t,i){this._extensions=t||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=$e,this.onerror=fy,this[dy]=void 0}static frame(e,t){let i,a=!1,c=2,u=!1;t.mask&&(i=t.maskBuffer||gy,t.generateMask?t.generateMask(i):(Bt===an&&(bt===void 0&&(bt=Buffer.alloc(an)),uy(bt,0,an),Bt=0),i[0]=bt[Bt++],i[1]=bt[Bt++],i[2]=bt[Bt++],i[3]=bt[Bt++]),u=(i[0]|i[1]|i[2]|i[3])===0,c=6);let p;typeof e=="string"?(!t.mask||u)&&t[Ne]!==void 0?p=t[Ne]:(e=Buffer.from(e),p=e.length):(p=e.length,a=t.mask&&t.readOnly&&!u);let g=p;p>=65536?(c+=8,g=127):p>125&&(c+=2,g=126);let m=Buffer.allocUnsafe(a?p+c:c);return m[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(m[0]|=64),m[1]=g,g===126?m.writeUInt16BE(p,2):g===127&&(m[2]=m[3]=0,m.writeUIntBE(p,4,6)),t.mask?(m[1]|=128,m[c-4]=i[0],m[c-3]=i[1],m[c-2]=i[2],m[c-1]=i[3],u?[m,e]:a?(Pl(e,i,m,c,p),[m]):(Pl(e,i,e,0,p),[m,e])):[m,e]}close(e,t,i,a){let c;if(e===void 0)c=hy;else{if(typeof e!="number"||!py(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)c=Buffer.allocUnsafe(2),c.writeUInt16BE(e,0);else{let p=Buffer.byteLength(t);if(p>123)throw new RangeError("The message must not be greater than 123 bytes");c=Buffer.allocUnsafe(2+p),c.writeUInt16BE(e,0),typeof t=="string"?c.write(t,2):c.set(t,2)}}let u={[Ne]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==$e?this.enqueue([this.dispatch,c,!1,u,a]):this.sendFrame(s.frame(c,u),a)}ping(e,t,i){let a,c;if(typeof e=="string"?(a=Buffer.byteLength(e),c=!1):qt(e)?(a=e.size,c=!1):(e=_t(e),a=e.length,c=_t.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let u={[Ne]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};qt(e)?this._state!==$e?this.enqueue([this.getBlobData,e,!1,u,i]):this.getBlobData(e,!1,u,i):this._state!==$e?this.enqueue([this.dispatch,e,!1,u,i]):this.sendFrame(s.frame(e,u),i)}pong(e,t,i){let a,c;if(typeof e=="string"?(a=Buffer.byteLength(e),c=!1):qt(e)?(a=e.size,c=!1):(e=_t(e),a=e.length,c=_t.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let u={[Ne]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};qt(e)?this._state!==$e?this.enqueue([this.getBlobData,e,!1,u,i]):this.getBlobData(e,!1,u,i):this._state!==$e?this.enqueue([this.dispatch,e,!1,u,i]):this.sendFrame(s.frame(e,u),i)}send(e,t,i){let a=this._extensions[Rl.extensionName],c=t.binary?2:1,u=t.compress,p,g;typeof e=="string"?(p=Buffer.byteLength(e),g=!1):qt(e)?(p=e.size,g=!1):(e=_t(e),p=e.length,g=_t.readOnly),this._firstFragment?(this._firstFragment=!1,u&&a&&a.params[a._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(u=p>=a._threshold),this._compress=u):(u=!1,c=0),t.fin&&(this._firstFragment=!0);let m={[Ne]:p,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:g,rsv1:u};qt(e)?this._state!==$e?this.enqueue([this.getBlobData,e,this._compress,m,i]):this.getBlobData(e,this._compress,m,i):this._state!==$e?this.enqueue([this.dispatch,e,this._compress,m,i]):this.dispatch(e,this._compress,m,i)}getBlobData(e,t,i,a){this._bufferedBytes+=i[Ne],this._state=yy,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let p=new Error("The socket was closed while the blob was being read");process.nextTick(ti,this,p,a);return}this._bufferedBytes-=i[Ne];let u=_t(c);t?this.dispatch(u,t,i,a):(this._state=$e,this.sendFrame(s.frame(u,i),a),this.dequeue())}).catch(c=>{process.nextTick(_y,this,c,a)})}dispatch(e,t,i,a){if(!t){this.sendFrame(s.frame(e,i),a);return}let c=this._extensions[Rl.extensionName];this._bufferedBytes+=i[Ne],this._state=my,c.compress(e,i.fin,(u,p)=>{if(this._socket.destroyed){let g=new Error("The socket was closed while data was being compressed");ti(this,g,a);return}this._bufferedBytes-=i[Ne],this._state=$e,i.readOnly=!1,this.sendFrame(s.frame(p,i),a),this.dequeue()})}dequeue(){for(;this._state===$e&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ne],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ne],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)}};Il.exports=ei;function ti(s,e,t){typeof t=="function"&&t(e);for(let i=0;i<s._queue.length;i++){let a=s._queue[i],c=a[a.length-1];typeof c=="function"&&c(e)}}function _y(s,e,t){ti(s,e,t),s.onerror(e)}});var Bl=$((RC,ql)=>{"use strict";var{kForOnEventAttribute:ys,kListener:ni}=Xe(),Ml=Symbol("kCode"),xl=Symbol("kData"),Nl=Symbol("kError"),Ll=Symbol("kMessage"),Dl=Symbol("kReason"),$t=Symbol("kTarget"),Ul=Symbol("kType"),jl=Symbol("kWasClean"),et=class{constructor(e){this[$t]=null,this[Ul]=e}get target(){return this[$t]}get type(){return this[Ul]}};Object.defineProperty(et.prototype,"target",{enumerable:!0});Object.defineProperty(et.prototype,"type",{enumerable:!0});var vt=class extends et{constructor(e,t={}){super(e),this[Ml]=t.code===void 0?0:t.code,this[Dl]=t.reason===void 0?"":t.reason,this[jl]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Ml]}get reason(){return this[Dl]}get wasClean(){return this[jl]}};Object.defineProperty(vt.prototype,"code",{enumerable:!0});Object.defineProperty(vt.prototype,"reason",{enumerable:!0});Object.defineProperty(vt.prototype,"wasClean",{enumerable:!0});var Ht=class extends et{constructor(e,t={}){super(e),this[Nl]=t.error===void 0?null:t.error,this[Ll]=t.message===void 0?"":t.message}get error(){return this[Nl]}get message(){return this[Ll]}};Object.defineProperty(Ht.prototype,"error",{enumerable:!0});Object.defineProperty(Ht.prototype,"message",{enumerable:!0});var _s=class extends et{constructor(e,t={}){super(e),this[xl]=t.data===void 0?null:t.data}get data(){return this[xl]}};Object.defineProperty(_s.prototype,"data",{enumerable:!0});var by={addEventListener(s,e,t={}){for(let a of this.listeners(s))if(!t[ys]&&a[ni]===e&&!a[ys])return;let i;if(s==="message")i=function(c,u){let p=new _s("message",{data:u?c:c.toString()});p[$t]=this,cn(e,this,p)};else if(s==="close")i=function(c,u){let p=new vt("close",{code:c,reason:u.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});p[$t]=this,cn(e,this,p)};else if(s==="error")i=function(c){let u=new Ht("error",{error:c,message:c.message});u[$t]=this,cn(e,this,u)};else if(s==="open")i=function(){let c=new et("open");c[$t]=this,cn(e,this,c)};else return;i[ys]=!!t[ys],i[ni]=e,t.once?this.once(s,i):this.on(s,i)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[ni]===e&&!t[ys]){this.removeListener(s,t);break}}};ql.exports={CloseEvent:vt,ErrorEvent:Ht,Event:et,EventTarget:by,MessageEvent:_s};function cn(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}});var ri=$((PC,$l)=>{"use strict";var{tokenChars:bs}=jt();function Fe(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}function vy(s){let e=Object.create(null),t=Object.create(null),i=!1,a=!1,c=!1,u,p,g=-1,m=-1,_=-1,w=0;for(;w<s.length;w++)if(m=s.charCodeAt(w),u===void 0)if(_===-1&&bs[m]===1)g===-1&&(g=w);else if(w!==0&&(m===32||m===9))_===-1&&g!==-1&&(_=w);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${w}`);_===-1&&(_=w);let T=s.slice(g,_);m===44?(Fe(e,T,t),t=Object.create(null)):u=T,g=_=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(p===void 0)if(_===-1&&bs[m]===1)g===-1&&(g=w);else if(m===32||m===9)_===-1&&g!==-1&&(_=w);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${w}`);_===-1&&(_=w),Fe(t,s.slice(g,_),!0),m===44&&(Fe(e,u,t),t=Object.create(null),u=void 0),g=_=-1}else if(m===61&&g!==-1&&_===-1)p=s.slice(g,w),g=_=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(a){if(bs[m]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1?g=w:i||(i=!0),a=!1}else if(c)if(bs[m]===1)g===-1&&(g=w);else if(m===34&&g!==-1)c=!1,_=w;else if(m===92)a=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(m===34&&s.charCodeAt(w-1)===61)c=!0;else if(_===-1&&bs[m]===1)g===-1&&(g=w);else if(g!==-1&&(m===32||m===9))_===-1&&(_=w);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${w}`);_===-1&&(_=w);let T=s.slice(g,_);i&&(T=T.replace(/\\/g,""),i=!1),Fe(t,p,T),m===44&&(Fe(e,u,t),t=Object.create(null),u=void 0),p=void 0,g=_=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(g===-1||c||m===32||m===9)throw new SyntaxError("Unexpected end of input");_===-1&&(_=w);let C=s.slice(g,_);return u===void 0?Fe(e,C,t):(p===void 0?Fe(t,C,!0):i?Fe(t,p,C.replace(/\\/g,"")):Fe(t,p,C),Fe(e,u,t)),e}function wy(s){return Object.keys(s).map(e=>{let t=s[e];return Array.isArray(t)||(t=[t]),t.map(i=>[e].concat(Object.keys(i).map(a=>{let c=i[a];return Array.isArray(c)||(c=[c]),c.map(u=>u===!0?a:`${a}=${u}`).join("; ")})).join("; ")).join(", ")}).join(", ")}$l.exports={format:wy,parse:vy}});var dn=$((xC,Zl)=>{"use strict";var Cy=q("events"),Ey=q("https"),ky=q("http"),Fl=q("net"),Oy=q("tls"),{randomBytes:Ty,createHash:Sy}=q("crypto"),{Duplex:IC,Readable:MC}=q("stream"),{URL:ii}=q("url"),ht=ms(),Ay=Zr(),Ry=si(),{isBlob:Py}=jt(),{BINARY_TYPES:Hl,CLOSE_TIMEOUT:Iy,EMPTY_BUFFER:ln,GUID:My,kForOnEventAttribute:oi,kListener:xy,kStatusCode:Ny,kWebSocket:pe,NOOP:Wl}=Xe(),{EventTarget:{addEventListener:Ly,removeEventListener:Dy}}=Bl(),{format:Uy,parse:jy}=ri(),{toBuffer:qy}=ps(),Vl=Symbol("kAborted"),ai=[8,13],tt=["CONNECTING","OPEN","CLOSING","CLOSED"],By=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ie=class s extends Cy{constructor(e,t,i){super(),this._binaryType=Hl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ln,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=s.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?(i=t,t=[]):t=[t]),zl(this,e,t,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Hl.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,i){let a=new Ay({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new Ry(e,this._extensions,i.generateMask);this._receiver=a,this._sender=c,this._socket=e,a[pe]=this,c[pe]=this,e[pe]=this,a.on("conclude",Gy),a.on("drain",Fy),a.on("error",Wy),a.on("message",Vy),a.on("ping",zy),a.on("pong",Ky),c.onerror=Jy,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Yl),e.on("data",hn),e.on("end",Ql),e.on("error",Xl),this._readyState=s.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ht.extensionName]&&this._extensions[ht.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Ae(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===s.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=s.CLOSING,this._sender.close(e,t,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Jl(this)}}pause(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,i){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ci(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||ln,t,i)}pong(e,t,i){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ci(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||ln,t,i)}resume(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,i){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(i=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ci(this,e,i);return}let a={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ht.extensionName]||(a.compress=!1),this._sender.send(e||ln,a,i)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Ae(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=s.CLOSING,this._socket.destroy())}}};Object.defineProperty(ie,"CONNECTING",{enumerable:!0,value:tt.indexOf("CONNECTING")});Object.defineProperty(ie.prototype,"CONNECTING",{enumerable:!0,value:tt.indexOf("CONNECTING")});Object.defineProperty(ie,"OPEN",{enumerable:!0,value:tt.indexOf("OPEN")});Object.defineProperty(ie.prototype,"OPEN",{enumerable:!0,value:tt.indexOf("OPEN")});Object.defineProperty(ie,"CLOSING",{enumerable:!0,value:tt.indexOf("CLOSING")});Object.defineProperty(ie.prototype,"CLOSING",{enumerable:!0,value:tt.indexOf("CLOSING")});Object.defineProperty(ie,"CLOSED",{enumerable:!0,value:tt.indexOf("CLOSED")});Object.defineProperty(ie.prototype,"CLOSED",{enumerable:!0,value:tt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(s=>{Object.defineProperty(ie.prototype,s,{enumerable:!0})});["open","error","close","message"].forEach(s=>{Object.defineProperty(ie.prototype,`on${s}`,{enumerable:!0,get(){for(let e of this.listeners(s))if(e[oi])return e[xy];return null},set(e){for(let t of this.listeners(s))if(t[oi]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[oi]:!0})}})});ie.prototype.addEventListener=Ly;ie.prototype.removeEventListener=Dy;Zl.exports=ie;function zl(s,e,t,i){let a={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Iy,protocolVersion:ai[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(s._autoPong=a.autoPong,s._closeTimeout=a.closeTimeout,!ai.includes(a.protocolVersion))throw new RangeError(`Unsupported protocol version: ${a.protocolVersion} (supported versions: ${ai.join(", ")})`);let c;if(e instanceof ii)c=e;else try{c=new ii(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),s._url=c.href;let u=c.protocol==="wss:",p=c.protocol==="ws+unix:",g;if(c.protocol!=="ws:"&&!u&&!p?g=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!c.pathname?g="The URL's pathname is empty":c.hash&&(g="The URL contains a fragment identifier"),g){let O=new SyntaxError(g);if(s._redirects===0)throw O;un(s,O);return}let m=u?443:80,_=Ty(16).toString("base64"),w=u?Ey.request:ky.request,C=new Set,T;if(a.createConnection=a.createConnection||(u?Hy:$y),a.defaultPort=a.defaultPort||m,a.port=c.port||m,a.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,a.headers={...a.headers,"Sec-WebSocket-Version":a.protocolVersion,"Sec-WebSocket-Key":_,Connection:"Upgrade",Upgrade:"websocket"},a.path=c.pathname+c.search,a.timeout=a.handshakeTimeout,a.perMessageDeflate&&(T=new ht(a.perMessageDeflate!==!0?a.perMessageDeflate:{},!1,a.maxPayload),a.headers["Sec-WebSocket-Extensions"]=Uy({[ht.extensionName]:T.offer()})),t.length){for(let O of t){if(typeof O!="string"||!By.test(O)||C.has(O))throw new SyntaxError("An invalid or duplicated subprotocol was specified");C.add(O)}a.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(a.origin&&(a.protocolVersion<13?a.headers["Sec-WebSocket-Origin"]=a.origin:a.headers.Origin=a.origin),(c.username||c.password)&&(a.auth=`${c.username}:${c.password}`),p){let O=a.path.split(":");a.socketPath=O[0],a.path=O[1]}let S;if(a.followRedirects){if(s._redirects===0){s._originalIpc=p,s._originalSecure=u,s._originalHostOrSocketPath=p?a.socketPath:c.host;let O=i&&i.headers;if(i={...i,headers:{}},O)for(let[k,N]of Object.entries(O))i.headers[k.toLowerCase()]=N}else if(s.listenerCount("redirect")===0){let O=p?s._originalIpc?a.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:c.host===s._originalHostOrSocketPath;(!O||s._originalSecure&&!u)&&(delete a.headers.authorization,delete a.headers.cookie,O||delete a.headers.host,a.auth=void 0)}a.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(a.auth).toString("base64")),S=s._req=w(a),s._redirects&&s.emit("redirect",s.url,S)}else S=s._req=w(a);a.timeout&&S.on("timeout",()=>{Ae(s,S,"Opening handshake has timed out")}),S.on("error",O=>{S===null||S[Vl]||(S=s._req=null,un(s,O))}),S.on("response",O=>{let k=O.headers.location,N=O.statusCode;if(k&&a.followRedirects&&N>=300&&N<400){if(++s._redirects>a.maxRedirects){Ae(s,S,"Maximum redirects exceeded");return}S.abort();let G;try{G=new ii(k,e)}catch{let X=new SyntaxError(`Invalid URL: ${k}`);un(s,X);return}zl(s,G,t,i)}else s.emit("unexpected-response",S,O)||Ae(s,S,`Unexpected server response: ${O.statusCode}`)}),S.on("upgrade",(O,k,N)=>{if(s.emit("upgrade",O),s.readyState!==ie.CONNECTING)return;S=s._req=null;let G=O.headers.upgrade;if(G===void 0||G.toLowerCase()!=="websocket"){Ae(s,k,"Invalid Upgrade header");return}let Y=Sy("sha1").update(_+My).digest("base64");if(O.headers["sec-websocket-accept"]!==Y){Ae(s,k,"Invalid Sec-WebSocket-Accept header");return}let X=O.headers["sec-websocket-protocol"],Q;if(X!==void 0?C.size?C.has(X)||(Q="Server sent an invalid subprotocol"):Q="Server sent a subprotocol but none was requested":C.size&&(Q="Server sent no subprotocol"),Q){Ae(s,k,Q);return}X&&(s._protocol=X);let Z=O.headers["sec-websocket-extensions"];if(Z!==void 0){if(!T){Ae(s,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let oe;try{oe=jy(Z)}catch{Ae(s,k,"Invalid Sec-WebSocket-Extensions header");return}let Re=Object.keys(oe);if(Re.length!==1||Re[0]!==ht.extensionName){Ae(s,k,"Server indicated an extension that was not requested");return}try{T.accept(oe[ht.extensionName])}catch{Ae(s,k,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[ht.extensionName]=T}s.setSocket(k,N,{allowSynchronousEvents:a.allowSynchronousEvents,generateMask:a.generateMask,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation})}),a.finishRequest?a.finishRequest(S,s):S.end()}function un(s,e){s._readyState=ie.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}function $y(s){return s.path=s.socketPath,Fl.connect(s)}function Hy(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=Fl.isIP(s.host)?"":s.host),Oy.connect(s)}function Ae(s,e,t){s._readyState=ie.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Ae),e.setHeader?(e[Vl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(un,s,i)):(e.destroy(i),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}function ci(s,e,t){if(e){let i=Py(e)?e.size:qy(e).length;s._socket?s._sender._bufferedBytes+=i:s._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${s.readyState} (${tt[s.readyState]})`);process.nextTick(t,i)}}function Gy(s,e){let t=this[pe];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[pe]!==void 0&&(t._socket.removeListener("data",hn),process.nextTick(Kl,t._socket),s===1005?t.close():t.close(s,e))}function Fy(){let s=this[pe];s.isPaused||s._socket.resume()}function Wy(s){let e=this[pe];e._socket[pe]!==void 0&&(e._socket.removeListener("data",hn),process.nextTick(Kl,e._socket),e.close(s[Ny])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}function Gl(){this[pe].emitClose()}function Vy(s,e){this[pe].emit("message",s,e)}function zy(s){let e=this[pe];e._autoPong&&e.pong(s,!this._isServer,Wl),e.emit("ping",s)}function Ky(s){this[pe].emit("pong",s)}function Kl(s){s.resume()}function Jy(s){let e=this[pe];e.readyState!==ie.CLOSED&&(e.readyState===ie.OPEN&&(e._readyState=ie.CLOSING,Jl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}function Jl(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}function Yl(){let s=this[pe];if(this.removeListener("close",Yl),this.removeListener("data",hn),this.removeListener("end",Ql),s._readyState=ie.CLOSING,!this._readableState.endEmitted&&!s._closeFrameReceived&&!s._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);s._receiver.write(e)}s._receiver.end(),this[pe]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",Gl),s._receiver.on("finish",Gl))}function hn(s){this[pe]._receiver.write(s)||this.pause()}function Ql(){let s=this[pe];s._readyState=ie.CLOSING,s._receiver.end(),this.end()}function Xl(){let s=this[pe];this.removeListener("error",Xl),this.on("error",Wl),s&&(s._readyState=ie.CLOSING,this.destroy())}});var nu=$((LC,su)=>{"use strict";var NC=dn(),{Duplex:Yy}=q("stream");function eu(s){s.emit("close")}function Qy(){!this.destroyed&&this._writableState.finished&&this.destroy()}function tu(s){this.removeListener("error",tu),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}function Xy(s,e){let t=!0,i=new Yy({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return s.on("message",function(c,u){let p=!u&&i._readableState.objectMode?c.toString():c;i.push(p)||s.pause()}),s.once("error",function(c){i.destroyed||(t=!1,i.destroy(c))}),s.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(a,c){if(s.readyState===s.CLOSED){c(a),process.nextTick(eu,i);return}let u=!1;s.once("error",function(g){u=!0,c(g)}),s.once("close",function(){u||c(a),process.nextTick(eu,i)}),t&&s.terminate()},i._final=function(a){if(s.readyState===s.CONNECTING){s.once("open",function(){i._final(a)});return}s._socket!==null&&(s._socket._writableState.finished?(a(),i._readableState.endEmitted&&i.destroy()):(s._socket.once("finish",function(){a()}),s.close()))},i._read=function(){s.isPaused&&s.resume()},i._write=function(a,c,u){if(s.readyState===s.CONNECTING){s.once("open",function(){i._write(a,c,u)});return}s.send(a,u)},i.on("end",Qy),i.on("error",tu),i}su.exports=Xy});var iu=$((DC,ru)=>{"use strict";var{tokenChars:Zy}=jt();function e_(s){let e=new Set,t=-1,i=-1,a=0;for(a;a<s.length;a++){let u=s.charCodeAt(a);if(i===-1&&Zy[u]===1)t===-1&&(t=a);else if(a!==0&&(u===32||u===9))i===-1&&t!==-1&&(i=a);else if(u===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let p=s.slice(t,i);if(e.has(p))throw new SyntaxError(`The "${p}" subprotocol is duplicated`);e.add(p),t=i=-1}else throw new SyntaxError(`Unexpected character at index ${a}`)}if(t===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=s.slice(t,a);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}ru.exports={parse:e_}});var du=$((jC,hu)=>{"use strict";var t_=q("events"),fn=q("http"),{Duplex:UC}=q("stream"),{createHash:s_}=q("crypto"),ou=ri(),wt=ms(),n_=iu(),r_=dn(),{CLOSE_TIMEOUT:i_,GUID:o_,kWebSocket:a_}=Xe(),c_=/^[+/0-9A-Za-z]{22}==$/,au=0,cu=1,uu=2,li=class extends t_{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:i_,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:r_,...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=fn.createServer((i,a)=>{let c=fn.STATUS_CODES[426];a.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),a.end(c)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=l_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(a,c,u)=>{this.handleUpgrade(a,c,u,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=au}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===uu){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(vs,this);return}if(e&&this.once("close",e),this._state!==cu)if(this._state=cu,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(vs,this):process.nextTick(vs,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{vs(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,i,a){t.on("error",lu);let c=e.headers["sec-websocket-key"],u=e.headers.upgrade,p=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ct(this,e,t,405,"Invalid HTTP method");return}if(u===void 0||u.toLowerCase()!=="websocket"){Ct(this,e,t,400,"Invalid Upgrade header");return}if(c===void 0||!c_.test(c)){Ct(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(p!==13&&p!==8){Ct(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ws(t,400);return}let g=e.headers["sec-websocket-protocol"],m=new Set;if(g!==void 0)try{m=n_.parse(g)}catch{Ct(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let _=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&_!==void 0){let C=new wt(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let T=ou.parse(_);T[wt.extensionName]&&(C.accept(T[wt.extensionName]),w[wt.extensionName]=C)}catch{Ct(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let C={origin:e.headers[`${p===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(C,(T,S,O,k)=>{if(!T)return ws(t,S||401,O,k);this.completeUpgrade(w,c,m,e,t,i,a)});return}if(!this.options.verifyClient(C))return ws(t,401)}this.completeUpgrade(w,c,m,e,t,i,a)}completeUpgrade(e,t,i,a,c,u,p){if(!c.readable||!c.writable)return c.destroy();if(c[a_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>au)return ws(c,503);let m=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${s_("sha1").update(t+o_).digest("base64")}`],_=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,a):i.values().next().value;w&&(m.push(`Sec-WebSocket-Protocol: ${w}`),_._protocol=w)}if(e[wt.extensionName]){let w=e[wt.extensionName].params,C=ou.format({[wt.extensionName]:[w]});m.push(`Sec-WebSocket-Extensions: ${C}`),_._extensions=e}this.emit("headers",m,a),c.write(m.concat(`\r
27
+ `),c=c.replace(/\\r/g,"\r")),e[a]=c}return e}function ym(s){s=s||{};let e=qc(s);s.path=e;let t=he.configDotenv(s);if(!t.parsed){let u=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw u.code="MISSING_DATA",u}let i=jc(s).split(","),a=i.length,c;for(let u=0;u<a;u++)try{let p=i[u].trim(),g=bm(t,p);c=he.decrypt(g.ciphertext,g.key);break}catch(p){if(u+1>=a)throw p}return he.parse(c)}function _m(s){console.error(`[dotenv@${jr}][WARN] ${s}`)}function fs(s){console.log(`[dotenv@${jr}][DEBUG] ${s}`)}function Uc(s){console.log(`[dotenv@${jr}] ${s}`)}function jc(s){return s&&s.DOTENV_KEY&&s.DOTENV_KEY.length>0?s.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function bm(s,e){let t;try{t=new URL(e)}catch(p){if(p.code==="ERR_INVALID_URL"){let g=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw g.code="INVALID_DOTENV_KEY",g}throw p}let i=t.password;if(!i){let p=new Error("INVALID_DOTENV_KEY: Missing key part");throw p.code="INVALID_DOTENV_KEY",p}let a=t.searchParams.get("environment");if(!a){let p=new Error("INVALID_DOTENV_KEY: Missing environment part");throw p.code="INVALID_DOTENV_KEY",p}let c=`DOTENV_VAULT_${a.toUpperCase()}`,u=s.parsed[c];if(!u){let p=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${c} in your .env.vault file.`);throw p.code="NOT_FOUND_DOTENV_ENVIRONMENT",p}return{ciphertext:u,key:i}}function qc(s){let e=null;if(s&&s.path&&s.path.length>0)if(Array.isArray(s.path))for(let t of s.path)Ur.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=s.path.endsWith(".vault")?s.path:`${s.path}.vault`;else e=Ys.resolve(process.cwd(),".env.vault");return Ur.existsSync(e)?e:null}function Dc(s){return s[0]==="~"?Ys.join(lm.homedir(),s.slice(1)):s}function vm(s){let e=xt(process.env.DOTENV_CONFIG_DEBUG||s&&s.debug),t=xt(process.env.DOTENV_CONFIG_QUIET||s&&s.quiet);(e||!t)&&Uc("Loading env from encrypted .env.vault");let i=he._parseVault(s),a=process.env;return s&&s.processEnv!=null&&(a=s.processEnv),he.populate(a,i,s),{parsed:i}}function wm(s){let e=Ys.resolve(process.cwd(),".env"),t="utf8",i=process.env;s&&s.processEnv!=null&&(i=s.processEnv);let a=xt(i.DOTENV_CONFIG_DEBUG||s&&s.debug),c=xt(i.DOTENV_CONFIG_QUIET||s&&s.quiet);s&&s.encoding?t=s.encoding:a&&fs("No encoding is specified. UTF-8 is used by default");let u=[e];if(s&&s.path)if(!Array.isArray(s.path))u=[Dc(s.path)];else{u=[];for(let _ of s.path)u.push(Dc(_))}let p,g={};for(let _ of u)try{let w=he.parse(Ur.readFileSync(_,{encoding:t}));he.populate(g,w,s)}catch(w){a&&fs(`Failed to load ${_} ${w.message}`),p=w}let m=he.populate(i,g,s);if(a=xt(i.DOTENV_CONFIG_DEBUG||a),c=xt(i.DOTENV_CONFIG_QUIET||c),a||!c){let _=Object.keys(m).length,w=[];for(let C of u)try{let T=Ys.relative(process.cwd(),C);w.push(T)}catch(T){a&&fs(`Failed to load ${C} ${T.message}`),p=T}Uc(`injecting env (${_}) from ${w.join(",")} ${pm(`-- tip: ${dm()}`)}`)}return p?{parsed:g,error:p}:{parsed:g}}function Cm(s){if(jc(s).length===0)return he.configDotenv(s);let e=qc(s);return e?he._configVault(s):(_m(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),he.configDotenv(s))}function Em(s,e){let t=Buffer.from(e.slice(-64),"hex"),i=Buffer.from(s,"base64"),a=i.subarray(0,12),c=i.subarray(-16);i=i.subarray(12,-16);try{let u=um.createDecipheriv("aes-256-gcm",t,a);return u.setAuthTag(c),`${u.update(i)}${u.final()}`}catch(u){let p=u instanceof RangeError,g=u.message==="Invalid key length",m=u.message==="Unsupported state or unable to authenticate data";if(p||g){let _=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw _.code="INVALID_DOTENV_KEY",_}else if(m){let _=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw _.code="DECRYPTION_FAILED",_}else throw u}}function km(s,e,t={}){let i=!!(t&&t.debug),a=!!(t&&t.override),c={};if(typeof e!="object"){let u=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw u.code="OBJECT_REQUIRED",u}for(let u of Object.keys(e))Object.prototype.hasOwnProperty.call(s,u)?(a===!0&&(s[u]=e[u],c[u]=e[u]),i&&fs(a===!0?`"${u}" is already defined and WAS overwritten`:`"${u}" is already defined and was NOT overwritten`)):(s[u]=e[u],c[u]=e[u]);return c}var he={configDotenv:wm,_configVault:vm,_parseVault:ym,config:Cm,decrypt:Em,parse:mm,populate:km};Qe.exports.configDotenv=he.configDotenv;Qe.exports._configVault=he._configVault;Qe.exports._parseVault=he._parseVault;Qe.exports.config=he.config;Qe.exports.decrypt=he.decrypt;Qe.exports.parse=he.parse;Qe.exports.populate=he.populate;Qe.exports=he});var Xe=$((OC,hl)=>{"use strict";var ll=["nodebuffer","arraybuffer","fragments"],ul=typeof Blob<"u";ul&&ll.push("blob");hl.exports={BINARY_TYPES:ll,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ul,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ps=$((TC,en)=>{"use strict";var{EMPTY_BUFFER:Wm}=Xe(),Gr=Buffer[Symbol.species];function Vm(s,e){if(s.length===0)return Wm;if(s.length===1)return s[0];let t=Buffer.allocUnsafe(e),i=0;for(let a=0;a<s.length;a++){let c=s[a];t.set(c,i),i+=c.length}return i<e?new Gr(t.buffer,t.byteOffset,i):t}function dl(s,e,t,i,a){for(let c=0;c<a;c++)t[i+c]=s[c]^e[c&3]}function fl(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}function zm(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}function Fr(s){if(Fr.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new Gr(s):ArrayBuffer.isView(s)?e=new Gr(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),Fr.readOnly=!1),e}en.exports={concat:Vm,mask:dl,toArrayBuffer:zm,toBuffer:Fr,unmask:fl};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=q("bufferutil");en.exports.mask=function(e,t,i,a,c){c<48?dl(e,t,i,a,c):s.mask(e,t,i,a,c)},en.exports.unmask=function(e,t){e.length<32?fl(e,t):s.unmask(e,t)}}catch{}});var ml=$((SC,gl)=>{"use strict";var pl=Symbol("kDone"),Wr=Symbol("kRun"),Vr=class{constructor(e){this[pl]=()=>{this.pending--,this[Wr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Wr]()}[Wr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[pl])}}};gl.exports=Vr});var ms=$((AC,vl)=>{"use strict";var gs=q("zlib"),yl=ps(),Km=ml(),{kStatusCode:_l}=Xe(),Jm=Buffer[Symbol.species],Ym=Buffer.from([0,0,255,255]),sn=Symbol("permessage-deflate"),Ze=Symbol("total-length"),Dt=Symbol("callback"),ut=Symbol("buffers"),Ut=Symbol("error"),tn,zr=class{constructor(e,t,i){if(this._maxPayload=i|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!tn){let a=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;tn=new Km(a)}}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[Dt];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,i=e.find(a=>!(t.serverNoContextTakeover===!1&&a.server_no_context_takeover||a.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>a.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!a.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(i.server_no_context_takeover=!0),t.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(i.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?i.client_max_window_bits=t.clientMaxWindowBits:(i.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}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(i=>{let a=t[i];if(a.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(a=a[0],i==="client_max_window_bits"){if(a!==!0){let c=+a;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${a}`);a=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${a}`)}else if(i==="server_max_window_bits"){let c=+a;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${a}`);a=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(a!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${a}`)}else throw new Error(`Unknown parameter "${i}"`);t[i]=a})}),e}decompress(e,t,i){tn.add(a=>{this._decompress(e,t,(c,u)=>{a(),i(c,u)})})}compress(e,t,i){tn.add(a=>{this._compress(e,t,(c,u)=>{a(),i(c,u)})})}_decompress(e,t,i){let a=this._isServer?"client":"server";if(!this._inflate){let c=`${a}_max_window_bits`,u=typeof this.params[c]!="number"?gs.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=gs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:u}),this._inflate[sn]=this,this._inflate[Ze]=0,this._inflate[ut]=[],this._inflate.on("error",Xm),this._inflate.on("data",bl)}this._inflate[Dt]=i,this._inflate.write(e),t&&this._inflate.write(Ym),this._inflate.flush(()=>{let c=this._inflate[Ut];if(c){this._inflate.close(),this._inflate=null,i(c);return}let u=yl.concat(this._inflate[ut],this._inflate[Ze]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ze]=0,this._inflate[ut]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,u)})}_compress(e,t,i){let a=this._isServer?"server":"client";if(!this._deflate){let c=`${a}_max_window_bits`,u=typeof this.params[c]!="number"?gs.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=gs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:u}),this._deflate[Ze]=0,this._deflate[ut]=[],this._deflate.on("data",Qm)}this._deflate[Dt]=i,this._deflate.write(e),this._deflate.flush(gs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=yl.concat(this._deflate[ut],this._deflate[Ze]);t&&(c=new Jm(c.buffer,c.byteOffset,c.length-4)),this._deflate[Dt]=null,this._deflate[Ze]=0,this._deflate[ut]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};vl.exports=zr;function Qm(s){this[ut].push(s),this[Ze]+=s.length}function bl(s){if(this[Ze]+=s.length,this[sn]._maxPayload<1||this[Ze]<=this[sn]._maxPayload){this[ut].push(s);return}this[Ut]=new RangeError("Max payload size exceeded"),this[Ut].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ut][_l]=1009,this.removeListener("data",bl),this.reset()}function Xm(s){if(this[sn]._inflate=null,this[Ut]){this[Dt](this[Ut]);return}s[_l]=1007,this[Dt](s)}});var jt=$((RC,nn)=>{"use strict";var{isUtf8:wl}=q("buffer"),{hasBlob:Zm}=Xe(),ey=[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 ty(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}function Kr(s){let e=s.length,t=0;for(;t<e;)if(!(s[t]&128))t++;else if((s[t]&224)===192){if(t+1===e||(s[t+1]&192)!==128||(s[t]&254)===192)return!1;t+=2}else if((s[t]&240)===224){if(t+2>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||s[t]===224&&(s[t+1]&224)===128||s[t]===237&&(s[t+1]&224)===160)return!1;t+=3}else if((s[t]&248)===240){if(t+3>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||(s[t+3]&192)!==128||s[t]===240&&(s[t+1]&240)===128||s[t]===244&&s[t+1]>143||s[t]>244)return!1;t+=4}else return!1;return!0}function sy(s){return Zm&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}nn.exports={isBlob:sy,isValidStatusCode:ty,isValidUTF8:Kr,tokenChars:ey};if(wl)nn.exports.isValidUTF8=function(s){return s.length<24?Kr(s):wl(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=q("utf-8-validate");nn.exports.isValidUTF8=function(e){return e.length<32?Kr(e):s(e)}}catch{}});var Zr=$((PC,Al)=>{"use strict";var{Writable:ny}=q("stream"),Cl=ms(),{BINARY_TYPES:ry,EMPTY_BUFFER:El,kStatusCode:iy,kWebSocket:oy}=Xe(),{concat:Jr,toArrayBuffer:ay,unmask:cy}=ps(),{isValidStatusCode:ly,isValidUTF8:kl}=jt(),rn=Buffer[Symbol.species],xe=0,Ol=1,Tl=2,Sl=3,Yr=4,Qr=5,on=6,Xr=class extends ny{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ry[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[oy]=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=xe}_write(e,t,i){if(this._opcode===8&&this._state==xe)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new rn(i.buffer,i.byteOffset+e,i.length-e),new rn(i.buffer,i.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let i=this._buffers[0],a=t.length-e;e>=i.length?t.set(this._buffers.shift(),a):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),a),this._buffers[0]=new rn(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case xe:this.getInfo(e);break;case Ol:this.getPayloadLength16(e);break;case Tl:this.getPayloadLength64(e);break;case Sl:this.getMask();break;case Yr:this.getData(e);break;case Qr:case on: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){let a=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(a);return}let i=(t[0]&64)===64;if(i&&!this._extensions[Cl.extensionName]){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(a);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(i){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(a);return}if(!this._fragmented){let a=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(a);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let a=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(a);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let a=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(a);return}if(i){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(a);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let a=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(a);return}}else{let a=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(a);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let a=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(a);return}}else if(this._masked){let a=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(a);return}this._payloadLength===126?this._state=Ol:this._payloadLength===127?this._state=Tl: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),i=t.readUInt32BE(0);if(i>Math.pow(2,21)-1){let a=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(a);return}this._payloadLength=i*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=Sl:this._state=Yr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Yr}getData(e){let t=El;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]&&cy(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Qr,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Cl.extensionName].decompress(e,this._fin,(a,c)=>{if(a)return t(a);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let u=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(u);return}this._fragments.push(c)}this.dataMessage(t),this._state===xe&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=xe;return}let t=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let a;this._binaryType==="nodebuffer"?a=Jr(i,t):this._binaryType==="arraybuffer"?a=ay(Jr(i,t)):this._binaryType==="blob"?a=new Blob(i):a=i,this._allowSynchronousEvents?(this.emit("message",a,!0),this._state=xe):(this._state=on,setImmediate(()=>{this.emit("message",a,!0),this._state=xe,this.startLoop(e)}))}else{let a=Jr(i,t);if(!this._skipUTF8Validation&&!kl(a)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Qr||this._allowSynchronousEvents?(this.emit("message",a,!1),this._state=xe):(this._state=on,setImmediate(()=>{this.emit("message",a,!1),this._state=xe,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,El),this.end();else{let i=e.readUInt16BE(0);if(!ly(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(c);return}let a=new rn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!kl(a)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(c);return}this._loop=!1,this.emit("conclude",i,a),this.end()}this._state=xe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=xe):(this._state=on,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=xe,this.startLoop(t)}))}createError(e,t,i,a,c){this._loop=!1,this._errored=!0;let u=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(u,this.createError),u.code=c,u[iy]=a,u}};Al.exports=Xr});var si=$((MC,Il)=>{"use strict";var{Duplex:IC}=q("stream"),{randomFillSync:uy}=q("crypto"),Rl=ms(),{EMPTY_BUFFER:hy,kWebSocket:dy,NOOP:fy}=Xe(),{isBlob:qt,isValidStatusCode:py}=jt(),{mask:Pl,toBuffer:_t}=ps(),Ne=Symbol("kByteLength"),gy=Buffer.alloc(4),an=8*1024,bt,Bt=an,$e=0,my=1,yy=2,ei=class s{constructor(e,t,i){this._extensions=t||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=$e,this.onerror=fy,this[dy]=void 0}static frame(e,t){let i,a=!1,c=2,u=!1;t.mask&&(i=t.maskBuffer||gy,t.generateMask?t.generateMask(i):(Bt===an&&(bt===void 0&&(bt=Buffer.alloc(an)),uy(bt,0,an),Bt=0),i[0]=bt[Bt++],i[1]=bt[Bt++],i[2]=bt[Bt++],i[3]=bt[Bt++]),u=(i[0]|i[1]|i[2]|i[3])===0,c=6);let p;typeof e=="string"?(!t.mask||u)&&t[Ne]!==void 0?p=t[Ne]:(e=Buffer.from(e),p=e.length):(p=e.length,a=t.mask&&t.readOnly&&!u);let g=p;p>=65536?(c+=8,g=127):p>125&&(c+=2,g=126);let m=Buffer.allocUnsafe(a?p+c:c);return m[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(m[0]|=64),m[1]=g,g===126?m.writeUInt16BE(p,2):g===127&&(m[2]=m[3]=0,m.writeUIntBE(p,4,6)),t.mask?(m[1]|=128,m[c-4]=i[0],m[c-3]=i[1],m[c-2]=i[2],m[c-1]=i[3],u?[m,e]:a?(Pl(e,i,m,c,p),[m]):(Pl(e,i,e,0,p),[m,e])):[m,e]}close(e,t,i,a){let c;if(e===void 0)c=hy;else{if(typeof e!="number"||!py(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)c=Buffer.allocUnsafe(2),c.writeUInt16BE(e,0);else{let p=Buffer.byteLength(t);if(p>123)throw new RangeError("The message must not be greater than 123 bytes");c=Buffer.allocUnsafe(2+p),c.writeUInt16BE(e,0),typeof t=="string"?c.write(t,2):c.set(t,2)}}let u={[Ne]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==$e?this.enqueue([this.dispatch,c,!1,u,a]):this.sendFrame(s.frame(c,u),a)}ping(e,t,i){let a,c;if(typeof e=="string"?(a=Buffer.byteLength(e),c=!1):qt(e)?(a=e.size,c=!1):(e=_t(e),a=e.length,c=_t.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let u={[Ne]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};qt(e)?this._state!==$e?this.enqueue([this.getBlobData,e,!1,u,i]):this.getBlobData(e,!1,u,i):this._state!==$e?this.enqueue([this.dispatch,e,!1,u,i]):this.sendFrame(s.frame(e,u),i)}pong(e,t,i){let a,c;if(typeof e=="string"?(a=Buffer.byteLength(e),c=!1):qt(e)?(a=e.size,c=!1):(e=_t(e),a=e.length,c=_t.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let u={[Ne]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};qt(e)?this._state!==$e?this.enqueue([this.getBlobData,e,!1,u,i]):this.getBlobData(e,!1,u,i):this._state!==$e?this.enqueue([this.dispatch,e,!1,u,i]):this.sendFrame(s.frame(e,u),i)}send(e,t,i){let a=this._extensions[Rl.extensionName],c=t.binary?2:1,u=t.compress,p,g;typeof e=="string"?(p=Buffer.byteLength(e),g=!1):qt(e)?(p=e.size,g=!1):(e=_t(e),p=e.length,g=_t.readOnly),this._firstFragment?(this._firstFragment=!1,u&&a&&a.params[a._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(u=p>=a._threshold),this._compress=u):(u=!1,c=0),t.fin&&(this._firstFragment=!0);let m={[Ne]:p,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:g,rsv1:u};qt(e)?this._state!==$e?this.enqueue([this.getBlobData,e,this._compress,m,i]):this.getBlobData(e,this._compress,m,i):this._state!==$e?this.enqueue([this.dispatch,e,this._compress,m,i]):this.dispatch(e,this._compress,m,i)}getBlobData(e,t,i,a){this._bufferedBytes+=i[Ne],this._state=yy,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let p=new Error("The socket was closed while the blob was being read");process.nextTick(ti,this,p,a);return}this._bufferedBytes-=i[Ne];let u=_t(c);t?this.dispatch(u,t,i,a):(this._state=$e,this.sendFrame(s.frame(u,i),a),this.dequeue())}).catch(c=>{process.nextTick(_y,this,c,a)})}dispatch(e,t,i,a){if(!t){this.sendFrame(s.frame(e,i),a);return}let c=this._extensions[Rl.extensionName];this._bufferedBytes+=i[Ne],this._state=my,c.compress(e,i.fin,(u,p)=>{if(this._socket.destroyed){let g=new Error("The socket was closed while data was being compressed");ti(this,g,a);return}this._bufferedBytes-=i[Ne],this._state=$e,i.readOnly=!1,this.sendFrame(s.frame(p,i),a),this.dequeue()})}dequeue(){for(;this._state===$e&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ne],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ne],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)}};Il.exports=ei;function ti(s,e,t){typeof t=="function"&&t(e);for(let i=0;i<s._queue.length;i++){let a=s._queue[i],c=a[a.length-1];typeof c=="function"&&c(e)}}function _y(s,e,t){ti(s,e,t),s.onerror(e)}});var Bl=$((xC,ql)=>{"use strict";var{kForOnEventAttribute:ys,kListener:ni}=Xe(),Ml=Symbol("kCode"),xl=Symbol("kData"),Nl=Symbol("kError"),Ll=Symbol("kMessage"),Dl=Symbol("kReason"),$t=Symbol("kTarget"),Ul=Symbol("kType"),jl=Symbol("kWasClean"),et=class{constructor(e){this[$t]=null,this[Ul]=e}get target(){return this[$t]}get type(){return this[Ul]}};Object.defineProperty(et.prototype,"target",{enumerable:!0});Object.defineProperty(et.prototype,"type",{enumerable:!0});var vt=class extends et{constructor(e,t={}){super(e),this[Ml]=t.code===void 0?0:t.code,this[Dl]=t.reason===void 0?"":t.reason,this[jl]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Ml]}get reason(){return this[Dl]}get wasClean(){return this[jl]}};Object.defineProperty(vt.prototype,"code",{enumerable:!0});Object.defineProperty(vt.prototype,"reason",{enumerable:!0});Object.defineProperty(vt.prototype,"wasClean",{enumerable:!0});var Ht=class extends et{constructor(e,t={}){super(e),this[Nl]=t.error===void 0?null:t.error,this[Ll]=t.message===void 0?"":t.message}get error(){return this[Nl]}get message(){return this[Ll]}};Object.defineProperty(Ht.prototype,"error",{enumerable:!0});Object.defineProperty(Ht.prototype,"message",{enumerable:!0});var _s=class extends et{constructor(e,t={}){super(e),this[xl]=t.data===void 0?null:t.data}get data(){return this[xl]}};Object.defineProperty(_s.prototype,"data",{enumerable:!0});var by={addEventListener(s,e,t={}){for(let a of this.listeners(s))if(!t[ys]&&a[ni]===e&&!a[ys])return;let i;if(s==="message")i=function(c,u){let p=new _s("message",{data:u?c:c.toString()});p[$t]=this,cn(e,this,p)};else if(s==="close")i=function(c,u){let p=new vt("close",{code:c,reason:u.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});p[$t]=this,cn(e,this,p)};else if(s==="error")i=function(c){let u=new Ht("error",{error:c,message:c.message});u[$t]=this,cn(e,this,u)};else if(s==="open")i=function(){let c=new et("open");c[$t]=this,cn(e,this,c)};else return;i[ys]=!!t[ys],i[ni]=e,t.once?this.once(s,i):this.on(s,i)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[ni]===e&&!t[ys]){this.removeListener(s,t);break}}};ql.exports={CloseEvent:vt,ErrorEvent:Ht,Event:et,EventTarget:by,MessageEvent:_s};function cn(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}});var ri=$((NC,$l)=>{"use strict";var{tokenChars:bs}=jt();function Fe(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}function vy(s){let e=Object.create(null),t=Object.create(null),i=!1,a=!1,c=!1,u,p,g=-1,m=-1,_=-1,w=0;for(;w<s.length;w++)if(m=s.charCodeAt(w),u===void 0)if(_===-1&&bs[m]===1)g===-1&&(g=w);else if(w!==0&&(m===32||m===9))_===-1&&g!==-1&&(_=w);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${w}`);_===-1&&(_=w);let T=s.slice(g,_);m===44?(Fe(e,T,t),t=Object.create(null)):u=T,g=_=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(p===void 0)if(_===-1&&bs[m]===1)g===-1&&(g=w);else if(m===32||m===9)_===-1&&g!==-1&&(_=w);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${w}`);_===-1&&(_=w),Fe(t,s.slice(g,_),!0),m===44&&(Fe(e,u,t),t=Object.create(null),u=void 0),g=_=-1}else if(m===61&&g!==-1&&_===-1)p=s.slice(g,w),g=_=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(a){if(bs[m]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1?g=w:i||(i=!0),a=!1}else if(c)if(bs[m]===1)g===-1&&(g=w);else if(m===34&&g!==-1)c=!1,_=w;else if(m===92)a=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(m===34&&s.charCodeAt(w-1)===61)c=!0;else if(_===-1&&bs[m]===1)g===-1&&(g=w);else if(g!==-1&&(m===32||m===9))_===-1&&(_=w);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${w}`);_===-1&&(_=w);let T=s.slice(g,_);i&&(T=T.replace(/\\/g,""),i=!1),Fe(t,p,T),m===44&&(Fe(e,u,t),t=Object.create(null),u=void 0),p=void 0,g=_=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(g===-1||c||m===32||m===9)throw new SyntaxError("Unexpected end of input");_===-1&&(_=w);let C=s.slice(g,_);return u===void 0?Fe(e,C,t):(p===void 0?Fe(t,C,!0):i?Fe(t,p,C.replace(/\\/g,"")):Fe(t,p,C),Fe(e,u,t)),e}function wy(s){return Object.keys(s).map(e=>{let t=s[e];return Array.isArray(t)||(t=[t]),t.map(i=>[e].concat(Object.keys(i).map(a=>{let c=i[a];return Array.isArray(c)||(c=[c]),c.map(u=>u===!0?a:`${a}=${u}`).join("; ")})).join("; ")).join(", ")}).join(", ")}$l.exports={format:wy,parse:vy}});var dn=$((UC,Zl)=>{"use strict";var Cy=q("events"),Ey=q("https"),ky=q("http"),Fl=q("net"),Oy=q("tls"),{randomBytes:Ty,createHash:Sy}=q("crypto"),{Duplex:LC,Readable:DC}=q("stream"),{URL:ii}=q("url"),ht=ms(),Ay=Zr(),Ry=si(),{isBlob:Py}=jt(),{BINARY_TYPES:Hl,CLOSE_TIMEOUT:Iy,EMPTY_BUFFER:ln,GUID:My,kForOnEventAttribute:oi,kListener:xy,kStatusCode:Ny,kWebSocket:pe,NOOP:Wl}=Xe(),{EventTarget:{addEventListener:Ly,removeEventListener:Dy}}=Bl(),{format:Uy,parse:jy}=ri(),{toBuffer:qy}=ps(),Vl=Symbol("kAborted"),ai=[8,13],tt=["CONNECTING","OPEN","CLOSING","CLOSED"],By=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ie=class s extends Cy{constructor(e,t,i){super(),this._binaryType=Hl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ln,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=s.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?(i=t,t=[]):t=[t]),zl(this,e,t,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Hl.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,i){let a=new Ay({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new Ry(e,this._extensions,i.generateMask);this._receiver=a,this._sender=c,this._socket=e,a[pe]=this,c[pe]=this,e[pe]=this,a.on("conclude",Gy),a.on("drain",Fy),a.on("error",Wy),a.on("message",Vy),a.on("ping",zy),a.on("pong",Ky),c.onerror=Jy,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Yl),e.on("data",hn),e.on("end",Ql),e.on("error",Xl),this._readyState=s.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ht.extensionName]&&this._extensions[ht.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Ae(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===s.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=s.CLOSING,this._sender.close(e,t,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Jl(this)}}pause(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,i){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ci(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||ln,t,i)}pong(e,t,i){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ci(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||ln,t,i)}resume(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,i){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(i=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ci(this,e,i);return}let a={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ht.extensionName]||(a.compress=!1),this._sender.send(e||ln,a,i)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Ae(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=s.CLOSING,this._socket.destroy())}}};Object.defineProperty(ie,"CONNECTING",{enumerable:!0,value:tt.indexOf("CONNECTING")});Object.defineProperty(ie.prototype,"CONNECTING",{enumerable:!0,value:tt.indexOf("CONNECTING")});Object.defineProperty(ie,"OPEN",{enumerable:!0,value:tt.indexOf("OPEN")});Object.defineProperty(ie.prototype,"OPEN",{enumerable:!0,value:tt.indexOf("OPEN")});Object.defineProperty(ie,"CLOSING",{enumerable:!0,value:tt.indexOf("CLOSING")});Object.defineProperty(ie.prototype,"CLOSING",{enumerable:!0,value:tt.indexOf("CLOSING")});Object.defineProperty(ie,"CLOSED",{enumerable:!0,value:tt.indexOf("CLOSED")});Object.defineProperty(ie.prototype,"CLOSED",{enumerable:!0,value:tt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(s=>{Object.defineProperty(ie.prototype,s,{enumerable:!0})});["open","error","close","message"].forEach(s=>{Object.defineProperty(ie.prototype,`on${s}`,{enumerable:!0,get(){for(let e of this.listeners(s))if(e[oi])return e[xy];return null},set(e){for(let t of this.listeners(s))if(t[oi]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[oi]:!0})}})});ie.prototype.addEventListener=Ly;ie.prototype.removeEventListener=Dy;Zl.exports=ie;function zl(s,e,t,i){let a={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Iy,protocolVersion:ai[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(s._autoPong=a.autoPong,s._closeTimeout=a.closeTimeout,!ai.includes(a.protocolVersion))throw new RangeError(`Unsupported protocol version: ${a.protocolVersion} (supported versions: ${ai.join(", ")})`);let c;if(e instanceof ii)c=e;else try{c=new ii(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),s._url=c.href;let u=c.protocol==="wss:",p=c.protocol==="ws+unix:",g;if(c.protocol!=="ws:"&&!u&&!p?g=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!c.pathname?g="The URL's pathname is empty":c.hash&&(g="The URL contains a fragment identifier"),g){let O=new SyntaxError(g);if(s._redirects===0)throw O;un(s,O);return}let m=u?443:80,_=Ty(16).toString("base64"),w=u?Ey.request:ky.request,C=new Set,T;if(a.createConnection=a.createConnection||(u?Hy:$y),a.defaultPort=a.defaultPort||m,a.port=c.port||m,a.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,a.headers={...a.headers,"Sec-WebSocket-Version":a.protocolVersion,"Sec-WebSocket-Key":_,Connection:"Upgrade",Upgrade:"websocket"},a.path=c.pathname+c.search,a.timeout=a.handshakeTimeout,a.perMessageDeflate&&(T=new ht(a.perMessageDeflate!==!0?a.perMessageDeflate:{},!1,a.maxPayload),a.headers["Sec-WebSocket-Extensions"]=Uy({[ht.extensionName]:T.offer()})),t.length){for(let O of t){if(typeof O!="string"||!By.test(O)||C.has(O))throw new SyntaxError("An invalid or duplicated subprotocol was specified");C.add(O)}a.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(a.origin&&(a.protocolVersion<13?a.headers["Sec-WebSocket-Origin"]=a.origin:a.headers.Origin=a.origin),(c.username||c.password)&&(a.auth=`${c.username}:${c.password}`),p){let O=a.path.split(":");a.socketPath=O[0],a.path=O[1]}let S;if(a.followRedirects){if(s._redirects===0){s._originalIpc=p,s._originalSecure=u,s._originalHostOrSocketPath=p?a.socketPath:c.host;let O=i&&i.headers;if(i={...i,headers:{}},O)for(let[k,N]of Object.entries(O))i.headers[k.toLowerCase()]=N}else if(s.listenerCount("redirect")===0){let O=p?s._originalIpc?a.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:c.host===s._originalHostOrSocketPath;(!O||s._originalSecure&&!u)&&(delete a.headers.authorization,delete a.headers.cookie,O||delete a.headers.host,a.auth=void 0)}a.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(a.auth).toString("base64")),S=s._req=w(a),s._redirects&&s.emit("redirect",s.url,S)}else S=s._req=w(a);a.timeout&&S.on("timeout",()=>{Ae(s,S,"Opening handshake has timed out")}),S.on("error",O=>{S===null||S[Vl]||(S=s._req=null,un(s,O))}),S.on("response",O=>{let k=O.headers.location,N=O.statusCode;if(k&&a.followRedirects&&N>=300&&N<400){if(++s._redirects>a.maxRedirects){Ae(s,S,"Maximum redirects exceeded");return}S.abort();let G;try{G=new ii(k,e)}catch{let X=new SyntaxError(`Invalid URL: ${k}`);un(s,X);return}zl(s,G,t,i)}else s.emit("unexpected-response",S,O)||Ae(s,S,`Unexpected server response: ${O.statusCode}`)}),S.on("upgrade",(O,k,N)=>{if(s.emit("upgrade",O),s.readyState!==ie.CONNECTING)return;S=s._req=null;let G=O.headers.upgrade;if(G===void 0||G.toLowerCase()!=="websocket"){Ae(s,k,"Invalid Upgrade header");return}let Y=Sy("sha1").update(_+My).digest("base64");if(O.headers["sec-websocket-accept"]!==Y){Ae(s,k,"Invalid Sec-WebSocket-Accept header");return}let X=O.headers["sec-websocket-protocol"],Q;if(X!==void 0?C.size?C.has(X)||(Q="Server sent an invalid subprotocol"):Q="Server sent a subprotocol but none was requested":C.size&&(Q="Server sent no subprotocol"),Q){Ae(s,k,Q);return}X&&(s._protocol=X);let Z=O.headers["sec-websocket-extensions"];if(Z!==void 0){if(!T){Ae(s,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let oe;try{oe=jy(Z)}catch{Ae(s,k,"Invalid Sec-WebSocket-Extensions header");return}let Re=Object.keys(oe);if(Re.length!==1||Re[0]!==ht.extensionName){Ae(s,k,"Server indicated an extension that was not requested");return}try{T.accept(oe[ht.extensionName])}catch{Ae(s,k,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[ht.extensionName]=T}s.setSocket(k,N,{allowSynchronousEvents:a.allowSynchronousEvents,generateMask:a.generateMask,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation})}),a.finishRequest?a.finishRequest(S,s):S.end()}function un(s,e){s._readyState=ie.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}function $y(s){return s.path=s.socketPath,Fl.connect(s)}function Hy(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=Fl.isIP(s.host)?"":s.host),Oy.connect(s)}function Ae(s,e,t){s._readyState=ie.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Ae),e.setHeader?(e[Vl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(un,s,i)):(e.destroy(i),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}function ci(s,e,t){if(e){let i=Py(e)?e.size:qy(e).length;s._socket?s._sender._bufferedBytes+=i:s._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${s.readyState} (${tt[s.readyState]})`);process.nextTick(t,i)}}function Gy(s,e){let t=this[pe];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[pe]!==void 0&&(t._socket.removeListener("data",hn),process.nextTick(Kl,t._socket),s===1005?t.close():t.close(s,e))}function Fy(){let s=this[pe];s.isPaused||s._socket.resume()}function Wy(s){let e=this[pe];e._socket[pe]!==void 0&&(e._socket.removeListener("data",hn),process.nextTick(Kl,e._socket),e.close(s[Ny])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}function Gl(){this[pe].emitClose()}function Vy(s,e){this[pe].emit("message",s,e)}function zy(s){let e=this[pe];e._autoPong&&e.pong(s,!this._isServer,Wl),e.emit("ping",s)}function Ky(s){this[pe].emit("pong",s)}function Kl(s){s.resume()}function Jy(s){let e=this[pe];e.readyState!==ie.CLOSED&&(e.readyState===ie.OPEN&&(e._readyState=ie.CLOSING,Jl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}function Jl(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}function Yl(){let s=this[pe];if(this.removeListener("close",Yl),this.removeListener("data",hn),this.removeListener("end",Ql),s._readyState=ie.CLOSING,!this._readableState.endEmitted&&!s._closeFrameReceived&&!s._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);s._receiver.write(e)}s._receiver.end(),this[pe]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",Gl),s._receiver.on("finish",Gl))}function hn(s){this[pe]._receiver.write(s)||this.pause()}function Ql(){let s=this[pe];s._readyState=ie.CLOSING,s._receiver.end(),this.end()}function Xl(){let s=this[pe];this.removeListener("error",Xl),this.on("error",Wl),s&&(s._readyState=ie.CLOSING,this.destroy())}});var nu=$((qC,su)=>{"use strict";var jC=dn(),{Duplex:Yy}=q("stream");function eu(s){s.emit("close")}function Qy(){!this.destroyed&&this._writableState.finished&&this.destroy()}function tu(s){this.removeListener("error",tu),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}function Xy(s,e){let t=!0,i=new Yy({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return s.on("message",function(c,u){let p=!u&&i._readableState.objectMode?c.toString():c;i.push(p)||s.pause()}),s.once("error",function(c){i.destroyed||(t=!1,i.destroy(c))}),s.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(a,c){if(s.readyState===s.CLOSED){c(a),process.nextTick(eu,i);return}let u=!1;s.once("error",function(g){u=!0,c(g)}),s.once("close",function(){u||c(a),process.nextTick(eu,i)}),t&&s.terminate()},i._final=function(a){if(s.readyState===s.CONNECTING){s.once("open",function(){i._final(a)});return}s._socket!==null&&(s._socket._writableState.finished?(a(),i._readableState.endEmitted&&i.destroy()):(s._socket.once("finish",function(){a()}),s.close()))},i._read=function(){s.isPaused&&s.resume()},i._write=function(a,c,u){if(s.readyState===s.CONNECTING){s.once("open",function(){i._write(a,c,u)});return}s.send(a,u)},i.on("end",Qy),i.on("error",tu),i}su.exports=Xy});var iu=$((BC,ru)=>{"use strict";var{tokenChars:Zy}=jt();function e_(s){let e=new Set,t=-1,i=-1,a=0;for(a;a<s.length;a++){let u=s.charCodeAt(a);if(i===-1&&Zy[u]===1)t===-1&&(t=a);else if(a!==0&&(u===32||u===9))i===-1&&t!==-1&&(i=a);else if(u===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let p=s.slice(t,i);if(e.has(p))throw new SyntaxError(`The "${p}" subprotocol is duplicated`);e.add(p),t=i=-1}else throw new SyntaxError(`Unexpected character at index ${a}`)}if(t===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=s.slice(t,a);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}ru.exports={parse:e_}});var du=$((HC,hu)=>{"use strict";var t_=q("events"),fn=q("http"),{Duplex:$C}=q("stream"),{createHash:s_}=q("crypto"),ou=ri(),wt=ms(),n_=iu(),r_=dn(),{CLOSE_TIMEOUT:i_,GUID:o_,kWebSocket:a_}=Xe(),c_=/^[+/0-9A-Za-z]{22}==$/,au=0,cu=1,uu=2,li=class extends t_{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:i_,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:r_,...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=fn.createServer((i,a)=>{let c=fn.STATUS_CODES[426];a.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),a.end(c)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=l_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(a,c,u)=>{this.handleUpgrade(a,c,u,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=au}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===uu){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(vs,this);return}if(e&&this.once("close",e),this._state!==cu)if(this._state=cu,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(vs,this):process.nextTick(vs,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{vs(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,i,a){t.on("error",lu);let c=e.headers["sec-websocket-key"],u=e.headers.upgrade,p=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ct(this,e,t,405,"Invalid HTTP method");return}if(u===void 0||u.toLowerCase()!=="websocket"){Ct(this,e,t,400,"Invalid Upgrade header");return}if(c===void 0||!c_.test(c)){Ct(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(p!==13&&p!==8){Ct(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ws(t,400);return}let g=e.headers["sec-websocket-protocol"],m=new Set;if(g!==void 0)try{m=n_.parse(g)}catch{Ct(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let _=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&_!==void 0){let C=new wt(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let T=ou.parse(_);T[wt.extensionName]&&(C.accept(T[wt.extensionName]),w[wt.extensionName]=C)}catch{Ct(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let C={origin:e.headers[`${p===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(C,(T,S,O,k)=>{if(!T)return ws(t,S||401,O,k);this.completeUpgrade(w,c,m,e,t,i,a)});return}if(!this.options.verifyClient(C))return ws(t,401)}this.completeUpgrade(w,c,m,e,t,i,a)}completeUpgrade(e,t,i,a,c,u,p){if(!c.readable||!c.writable)return c.destroy();if(c[a_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>au)return ws(c,503);let m=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${s_("sha1").update(t+o_).digest("base64")}`],_=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,a):i.values().next().value;w&&(m.push(`Sec-WebSocket-Protocol: ${w}`),_._protocol=w)}if(e[wt.extensionName]){let w=e[wt.extensionName].params,C=ou.format({[wt.extensionName]:[w]});m.push(`Sec-WebSocket-Extensions: ${C}`),_._extensions=e}this.emit("headers",m,a),c.write(m.concat(`\r
28
28
  `).join(`\r
29
29
  `)),c.removeListener("error",lu),_.setSocket(c,u,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(_),_.on("close",()=>{this.clients.delete(_),this._shouldEmitClose&&!this.clients.size&&process.nextTick(vs,this)})),p(_,a)}};hu.exports=li;function l_(s,e){for(let t of Object.keys(e))s.on(t,e[t]);return function(){for(let i of Object.keys(e))s.removeListener(i,e[i])}}function vs(s){s._state=uu,s.emit("close")}function lu(){this.destroy()}function ws(s,e,t,i){t=t||fn.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...i},s.once("finish",s.destroy),s.end(`HTTP/1.1 ${e} ${fn.STATUS_CODES[e]}\r
30
30
  `+Object.keys(i).map(a=>`${a}: ${i[a]}`).join(`\r
31
31
  `)+`\r
32
32
  \r
33
- `+t)}function Ct(s,e,t,i,a,c){if(s.listenerCount("wsClientError")){let u=new Error(a);Error.captureStackTrace(u,Ct),s.emit("wsClientError",u,t,e)}else ws(t,i,a,c)}});var pn=$((qC,fu)=>{"use strict";var st=dn();st.createWebSocketStream=nu();st.Server=du();st.Receiver=Zr();st.Sender=si();st.WebSocket=st;st.WebSocketServer=st.Server;fu.exports=st});var rt=$((nt,gn)=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});var pu=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function u_(s){return pu.includes(s)}var h_=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Blob","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","FormData","URLSearchParams","HTMLElement",...pu];function d_(s){return h_.includes(s)}var f_=["null","undefined","string","number","bigint","boolean","symbol"];function p_(s){return f_.includes(s)}function Gt(s){return e=>typeof e===s}var{toString:gu}=Object.prototype,Cs=s=>{let e=gu.call(s).slice(8,-1);if(/HTML\w+Element/.test(e)&&v.domElement(s))return"HTMLElement";if(d_(e))return e},ne=s=>e=>Cs(e)===s;function v(s){if(s===null)return"null";switch(typeof s){case"undefined":return"undefined";case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"function":return"Function";case"bigint":return"bigint";case"symbol":return"symbol";default:}if(v.observable(s))return"Observable";if(v.array(s))return"Array";if(v.buffer(s))return"Buffer";let e=Cs(s);if(e)return e;if(s instanceof String||s instanceof Boolean||s instanceof Number)throw new TypeError("Please don't use object wrappers for primitive types");return"Object"}v.undefined=Gt("undefined");v.string=Gt("string");var g_=Gt("number");v.number=s=>g_(s)&&!v.nan(s);v.bigint=Gt("bigint");v.function_=Gt("function");v.null_=s=>s===null;v.class_=s=>v.function_(s)&&s.toString().startsWith("class ");v.boolean=s=>s===!0||s===!1;v.symbol=Gt("symbol");v.numericString=s=>v.string(s)&&!v.emptyStringOrWhitespace(s)&&!Number.isNaN(Number(s));v.array=(s,e)=>Array.isArray(s)?v.function_(e)?s.every(e):!0:!1;v.buffer=s=>{var e,t,i,a;return(a=(i=(t=(e=s)===null||e===void 0?void 0:e.constructor)===null||t===void 0?void 0:t.isBuffer)===null||i===void 0?void 0:i.call(t,s))!==null&&a!==void 0?a:!1};v.blob=s=>ne("Blob")(s);v.nullOrUndefined=s=>v.null_(s)||v.undefined(s);v.object=s=>!v.null_(s)&&(typeof s=="object"||v.function_(s));v.iterable=s=>{var e;return v.function_((e=s)===null||e===void 0?void 0:e[Symbol.iterator])};v.asyncIterable=s=>{var e;return v.function_((e=s)===null||e===void 0?void 0:e[Symbol.asyncIterator])};v.generator=s=>{var e,t;return v.iterable(s)&&v.function_((e=s)===null||e===void 0?void 0:e.next)&&v.function_((t=s)===null||t===void 0?void 0:t.throw)};v.asyncGenerator=s=>v.asyncIterable(s)&&v.function_(s.next)&&v.function_(s.throw);v.nativePromise=s=>ne("Promise")(s);var m_=s=>{var e,t;return v.function_((e=s)===null||e===void 0?void 0:e.then)&&v.function_((t=s)===null||t===void 0?void 0:t.catch)};v.promise=s=>v.nativePromise(s)||m_(s);v.generatorFunction=ne("GeneratorFunction");v.asyncGeneratorFunction=s=>Cs(s)==="AsyncGeneratorFunction";v.asyncFunction=s=>Cs(s)==="AsyncFunction";v.boundFunction=s=>v.function_(s)&&!s.hasOwnProperty("prototype");v.regExp=ne("RegExp");v.date=ne("Date");v.error=ne("Error");v.map=s=>ne("Map")(s);v.set=s=>ne("Set")(s);v.weakMap=s=>ne("WeakMap")(s);v.weakSet=s=>ne("WeakSet")(s);v.int8Array=ne("Int8Array");v.uint8Array=ne("Uint8Array");v.uint8ClampedArray=ne("Uint8ClampedArray");v.int16Array=ne("Int16Array");v.uint16Array=ne("Uint16Array");v.int32Array=ne("Int32Array");v.uint32Array=ne("Uint32Array");v.float32Array=ne("Float32Array");v.float64Array=ne("Float64Array");v.bigInt64Array=ne("BigInt64Array");v.bigUint64Array=ne("BigUint64Array");v.arrayBuffer=ne("ArrayBuffer");v.sharedArrayBuffer=ne("SharedArrayBuffer");v.dataView=ne("DataView");v.enumCase=(s,e)=>Object.values(e).includes(s);v.directInstanceOf=(s,e)=>Object.getPrototypeOf(s)===e.prototype;v.urlInstance=s=>ne("URL")(s);v.urlString=s=>{if(!v.string(s))return!1;try{return new URL(s),!0}catch{return!1}};v.truthy=s=>!!s;v.falsy=s=>!s;v.nan=s=>Number.isNaN(s);v.primitive=s=>v.null_(s)||p_(typeof s);v.integer=s=>Number.isInteger(s);v.safeInteger=s=>Number.isSafeInteger(s);v.plainObject=s=>{if(gu.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||e===Object.getPrototypeOf({})};v.typedArray=s=>u_(Cs(s));var y_=s=>v.safeInteger(s)&&s>=0;v.arrayLike=s=>!v.nullOrUndefined(s)&&!v.function_(s)&&y_(s.length);v.inRange=(s,e)=>{if(v.number(e))return s>=Math.min(0,e)&&s<=Math.max(e,0);if(v.array(e)&&e.length===2)return s>=Math.min(...e)&&s<=Math.max(...e);throw new TypeError(`Invalid range: ${JSON.stringify(e)}`)};var __=1,b_=["innerHTML","ownerDocument","style","attributes","nodeValue"];v.domElement=s=>v.object(s)&&s.nodeType===__&&v.string(s.nodeName)&&!v.plainObject(s)&&b_.every(e=>e in s);v.observable=s=>{var e,t,i,a;return s?s===((t=(e=s)[Symbol.observable])===null||t===void 0?void 0:t.call(e))||s===((a=(i=s)["@@observable"])===null||a===void 0?void 0:a.call(i)):!1};v.nodeStream=s=>v.object(s)&&v.function_(s.pipe)&&!v.observable(s);v.infinite=s=>s===1/0||s===-1/0;var mu=s=>e=>v.integer(e)&&Math.abs(e%2)===s;v.evenInteger=mu(0);v.oddInteger=mu(1);v.emptyArray=s=>v.array(s)&&s.length===0;v.nonEmptyArray=s=>v.array(s)&&s.length>0;v.emptyString=s=>v.string(s)&&s.length===0;var v_=s=>v.string(s)&&!/\S/.test(s);v.emptyStringOrWhitespace=s=>v.emptyString(s)||v_(s);v.nonEmptyString=s=>v.string(s)&&s.length>0;v.nonEmptyStringAndNotWhitespace=s=>v.string(s)&&!v.emptyStringOrWhitespace(s);v.emptyObject=s=>v.object(s)&&!v.map(s)&&!v.set(s)&&Object.keys(s).length===0;v.nonEmptyObject=s=>v.object(s)&&!v.map(s)&&!v.set(s)&&Object.keys(s).length>0;v.emptySet=s=>v.set(s)&&s.size===0;v.nonEmptySet=s=>v.set(s)&&s.size>0;v.emptyMap=s=>v.map(s)&&s.size===0;v.nonEmptyMap=s=>v.map(s)&&s.size>0;v.propertyKey=s=>v.any([v.string,v.number,v.symbol],s);v.formData=s=>ne("FormData")(s);v.urlSearchParams=s=>ne("URLSearchParams")(s);var yu=(s,e,t)=>{if(!v.function_(e))throw new TypeError(`Invalid predicate: ${JSON.stringify(e)}`);if(t.length===0)throw new TypeError("Invalid number of values");return s.call(t,e)};v.any=(s,...e)=>(v.array(s)?s:[s]).some(i=>yu(Array.prototype.some,i,e));v.all=(s,...e)=>yu(Array.prototype.every,s,e);var B=(s,e,t,i={})=>{if(!s){let{multipleValues:a}=i,c=a?`received values of types ${[...new Set(t.map(u=>`\`${v(u)}\``))].join(", ")}`:`received value of type \`${v(t)}\``;throw new TypeError(`Expected value which is \`${e}\`, ${c}.`)}};nt.assert={undefined:s=>B(v.undefined(s),"undefined",s),string:s=>B(v.string(s),"string",s),number:s=>B(v.number(s),"number",s),bigint:s=>B(v.bigint(s),"bigint",s),function_:s=>B(v.function_(s),"Function",s),null_:s=>B(v.null_(s),"null",s),class_:s=>B(v.class_(s),"Class",s),boolean:s=>B(v.boolean(s),"boolean",s),symbol:s=>B(v.symbol(s),"symbol",s),numericString:s=>B(v.numericString(s),"string with a number",s),array:(s,e)=>{B(v.array(s),"Array",s),e&&s.forEach(e)},buffer:s=>B(v.buffer(s),"Buffer",s),blob:s=>B(v.blob(s),"Blob",s),nullOrUndefined:s=>B(v.nullOrUndefined(s),"null or undefined",s),object:s=>B(v.object(s),"Object",s),iterable:s=>B(v.iterable(s),"Iterable",s),asyncIterable:s=>B(v.asyncIterable(s),"AsyncIterable",s),generator:s=>B(v.generator(s),"Generator",s),asyncGenerator:s=>B(v.asyncGenerator(s),"AsyncGenerator",s),nativePromise:s=>B(v.nativePromise(s),"native Promise",s),promise:s=>B(v.promise(s),"Promise",s),generatorFunction:s=>B(v.generatorFunction(s),"GeneratorFunction",s),asyncGeneratorFunction:s=>B(v.asyncGeneratorFunction(s),"AsyncGeneratorFunction",s),asyncFunction:s=>B(v.asyncFunction(s),"AsyncFunction",s),boundFunction:s=>B(v.boundFunction(s),"Function",s),regExp:s=>B(v.regExp(s),"RegExp",s),date:s=>B(v.date(s),"Date",s),error:s=>B(v.error(s),"Error",s),map:s=>B(v.map(s),"Map",s),set:s=>B(v.set(s),"Set",s),weakMap:s=>B(v.weakMap(s),"WeakMap",s),weakSet:s=>B(v.weakSet(s),"WeakSet",s),int8Array:s=>B(v.int8Array(s),"Int8Array",s),uint8Array:s=>B(v.uint8Array(s),"Uint8Array",s),uint8ClampedArray:s=>B(v.uint8ClampedArray(s),"Uint8ClampedArray",s),int16Array:s=>B(v.int16Array(s),"Int16Array",s),uint16Array:s=>B(v.uint16Array(s),"Uint16Array",s),int32Array:s=>B(v.int32Array(s),"Int32Array",s),uint32Array:s=>B(v.uint32Array(s),"Uint32Array",s),float32Array:s=>B(v.float32Array(s),"Float32Array",s),float64Array:s=>B(v.float64Array(s),"Float64Array",s),bigInt64Array:s=>B(v.bigInt64Array(s),"BigInt64Array",s),bigUint64Array:s=>B(v.bigUint64Array(s),"BigUint64Array",s),arrayBuffer:s=>B(v.arrayBuffer(s),"ArrayBuffer",s),sharedArrayBuffer:s=>B(v.sharedArrayBuffer(s),"SharedArrayBuffer",s),dataView:s=>B(v.dataView(s),"DataView",s),enumCase:(s,e)=>B(v.enumCase(s,e),"EnumCase",s),urlInstance:s=>B(v.urlInstance(s),"URL",s),urlString:s=>B(v.urlString(s),"string with a URL",s),truthy:s=>B(v.truthy(s),"truthy",s),falsy:s=>B(v.falsy(s),"falsy",s),nan:s=>B(v.nan(s),"NaN",s),primitive:s=>B(v.primitive(s),"primitive",s),integer:s=>B(v.integer(s),"integer",s),safeInteger:s=>B(v.safeInteger(s),"integer",s),plainObject:s=>B(v.plainObject(s),"plain object",s),typedArray:s=>B(v.typedArray(s),"TypedArray",s),arrayLike:s=>B(v.arrayLike(s),"array-like",s),domElement:s=>B(v.domElement(s),"HTMLElement",s),observable:s=>B(v.observable(s),"Observable",s),nodeStream:s=>B(v.nodeStream(s),"Node.js Stream",s),infinite:s=>B(v.infinite(s),"infinite number",s),emptyArray:s=>B(v.emptyArray(s),"empty array",s),nonEmptyArray:s=>B(v.nonEmptyArray(s),"non-empty array",s),emptyString:s=>B(v.emptyString(s),"empty string",s),emptyStringOrWhitespace:s=>B(v.emptyStringOrWhitespace(s),"empty string or whitespace",s),nonEmptyString:s=>B(v.nonEmptyString(s),"non-empty string",s),nonEmptyStringAndNotWhitespace:s=>B(v.nonEmptyStringAndNotWhitespace(s),"non-empty string and not whitespace",s),emptyObject:s=>B(v.emptyObject(s),"empty object",s),nonEmptyObject:s=>B(v.nonEmptyObject(s),"non-empty object",s),emptySet:s=>B(v.emptySet(s),"empty set",s),nonEmptySet:s=>B(v.nonEmptySet(s),"non-empty set",s),emptyMap:s=>B(v.emptyMap(s),"empty map",s),nonEmptyMap:s=>B(v.nonEmptyMap(s),"non-empty map",s),propertyKey:s=>B(v.propertyKey(s),"PropertyKey",s),formData:s=>B(v.formData(s),"FormData",s),urlSearchParams:s=>B(v.urlSearchParams(s),"URLSearchParams",s),evenInteger:s=>B(v.evenInteger(s),"even integer",s),oddInteger:s=>B(v.oddInteger(s),"odd integer",s),directInstanceOf:(s,e)=>B(v.directInstanceOf(s,e),"T",s),inRange:(s,e)=>B(v.inRange(s,e),"in range",s),any:(s,...e)=>B(v.any(s,...e),"predicate returns truthy for any value",e,{multipleValues:!0}),all:(s,...e)=>B(v.all(s,...e),"predicate returns truthy for all values",e,{multipleValues:!0})};Object.defineProperties(v,{class:{value:v.class_},function:{value:v.function_},null:{value:v.null_}});Object.defineProperties(nt.assert,{class:{value:nt.assert.class_},function:{value:nt.assert.function_},null:{value:nt.assert.null_}});nt.default=v;gn.exports=v;gn.exports.default=v;gn.exports.assert=nt.assert});var _u=$((BC,ui)=>{"use strict";var mn=class extends Error{constructor(e){super(e||"Promise was canceled"),this.name="CancelError"}get isCanceled(){return!0}},yn=class s{static fn(e){return(...t)=>new s((i,a,c)=>{t.push(c),e(...t).then(i,a)})}constructor(e){this._cancelHandlers=[],this._isPending=!0,this._isCanceled=!1,this._rejectOnCancel=!0,this._promise=new Promise((t,i)=>{this._reject=i;let a=p=>{(!this._isCanceled||!u.shouldReject)&&(this._isPending=!1,t(p))},c=p=>{this._isPending=!1,i(p)},u=p=>{if(!this._isPending)throw new Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(p)};return Object.defineProperties(u,{shouldReject:{get:()=>this._rejectOnCancel,set:p=>{this._rejectOnCancel=p}}}),e(a,c,u)})}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(e){if(!(!this._isPending||this._isCanceled)){if(this._isCanceled=!0,this._cancelHandlers.length>0)try{for(let t of this._cancelHandlers)t()}catch(t){this._reject(t);return}this._rejectOnCancel&&this._reject(new mn(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(yn.prototype,Promise.prototype);ui.exports=yn;ui.exports.CancelError=mn});var bu=$((di,fi)=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});function w_(s){return s.encrypted}var hi=(s,e)=>{let t;typeof e=="function"?t={connect:e}:t=e;let i=typeof t.connect=="function",a=typeof t.secureConnect=="function",c=typeof t.close=="function",u=()=>{i&&t.connect(),w_(s)&&a&&(s.authorized?t.secureConnect():s.authorizationError||s.once("secureConnect",t.secureConnect)),c&&s.once("close",t.close)};s.writable&&!s.connecting?u():s.connecting?s.once("connect",u):s.destroyed&&c&&t.close(s._hadError)};di.default=hi;fi.exports=hi;fi.exports.default=hi});var vu=$((gi,mi)=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});var C_=bu(),E_=q("util"),k_=Number(process.versions.node.split(".")[0]),pi=s=>{if(s.timings)return s.timings;let e={start:Date.now(),socket:void 0,lookup:void 0,connect:void 0,secureConnect:void 0,upload:void 0,response:void 0,end:void 0,error:void 0,abort:void 0,phases:{wait:void 0,dns:void 0,tcp:void 0,tls:void 0,request:void 0,firstByte:void 0,download:void 0,total:void 0}};s.timings=e;let t=p=>{let g=p.emit.bind(p);p.emit=(m,..._)=>(m==="error"&&(e.error=Date.now(),e.phases.total=e.error-e.start,p.emit=g),g(m,..._))};t(s);let i=()=>{e.abort=Date.now(),(!e.response||k_>=13)&&(e.phases.total=Date.now()-e.start)};s.prependOnceListener("abort",i);let a=p=>{if(e.socket=Date.now(),e.phases.wait=e.socket-e.start,E_.types.isProxy(p))return;let g=()=>{e.lookup=Date.now(),e.phases.dns=e.lookup-e.socket};p.prependOnceListener("lookup",g),C_.default(p,{connect:()=>{e.connect=Date.now(),e.lookup===void 0&&(p.removeListener("lookup",g),e.lookup=e.connect,e.phases.dns=e.lookup-e.socket),e.phases.tcp=e.connect-e.lookup},secureConnect:()=>{e.secureConnect=Date.now(),e.phases.tls=e.secureConnect-e.connect}})};s.socket?a(s.socket):s.prependOnceListener("socket",a);let c=()=>{var p;e.upload=Date.now(),e.phases.request=e.upload-((p=e.secureConnect)!==null&&p!==void 0?p:e.connect)};return(typeof s.writableFinished=="boolean"?s.writableFinished:s.finished&&s.outputSize===0&&(!s.socket||s.socket.writableLength===0))?c():s.prependOnceListener("finish",c),s.prependOnceListener("response",p=>{e.response=Date.now(),e.phases.firstByte=e.response-e.upload,p.timings=e,t(p),p.prependOnceListener("end",()=>{e.end=Date.now(),e.phases.download=e.end-e.response,e.phases.total=e.end-e.start}),p.prependOnceListener("aborted",i)}),e};gi.default=pi;mi.exports=pi;mi.exports.default=pi});var Su=$(($C,bi)=>{"use strict";var{V4MAPPED:O_,ADDRCONFIG:T_,ALL:Tu,promises:{Resolver:wu},lookup:S_}=q("dns"),{promisify:yi}=q("util"),A_=q("os"),Ft=Symbol("cacheableLookupCreateConnection"),_i=Symbol("cacheableLookupInstance"),Cu=Symbol("expires"),R_=typeof Tu=="number",Eu=s=>{if(!(s&&typeof s.createConnection=="function"))throw new Error("Expected an Agent instance as the first argument")},P_=s=>{for(let e of s)e.family!==6&&(e.address=`::ffff:${e.address}`,e.family=6)},ku=()=>{let s=!1,e=!1;for(let t of Object.values(A_.networkInterfaces()))for(let i of t)if(!i.internal&&(i.family==="IPv6"?e=!0:s=!0,s&&e))return{has4:s,has6:e};return{has4:s,has6:e}},I_=s=>Symbol.iterator in s,Ou={ttl:!0},M_={all:!0},_n=class{constructor({cache:e=new Map,maxTtl:t=1/0,fallbackDuration:i=3600,errorTtl:a=.15,resolver:c=new wu,lookup:u=S_}={}){if(this.maxTtl=t,this.errorTtl=a,this._cache=e,this._resolver=c,this._dnsLookup=yi(u),this._resolver instanceof wu?(this._resolve4=this._resolver.resolve4.bind(this._resolver),this._resolve6=this._resolver.resolve6.bind(this._resolver)):(this._resolve4=yi(this._resolver.resolve4.bind(this._resolver)),this._resolve6=yi(this._resolver.resolve6.bind(this._resolver))),this._iface=ku(),this._pending={},this._nextRemovalTime=!1,this._hostnamesToFallback=new Set,i<1)this._fallback=!1;else{this._fallback=!0;let p=setInterval(()=>{this._hostnamesToFallback.clear()},i*1e3);p.unref&&p.unref()}this.lookup=this.lookup.bind(this),this.lookupAsync=this.lookupAsync.bind(this)}set servers(e){this.clear(),this._resolver.setServers(e)}get servers(){return this._resolver.getServers()}lookup(e,t,i){if(typeof t=="function"?(i=t,t={}):typeof t=="number"&&(t={family:t}),!i)throw new Error("Callback must be a function.");this.lookupAsync(e,t).then(a=>{t.all?i(null,a):i(null,a.address,a.family,a.expires,a.ttl)},i)}async lookupAsync(e,t={}){typeof t=="number"&&(t={family:t});let i=await this.query(e);if(t.family===6){let a=i.filter(c=>c.family===6);t.hints&O_&&(R_&&t.hints&Tu||a.length===0)?P_(i):i=a}else t.family===4&&(i=i.filter(a=>a.family===4));if(t.hints&T_){let{_iface:a}=this;i=i.filter(c=>c.family===6?a.has6:a.has4)}if(i.length===0){let a=new Error(`cacheableLookup ENOTFOUND ${e}`);throw a.code="ENOTFOUND",a.hostname=e,a}return t.all?i:i[0]}async query(e){let t=await this._cache.get(e);if(!t){let i=this._pending[e];if(i)t=await i;else{let a=this.queryAndCache(e);this._pending[e]=a;try{t=await a}finally{delete this._pending[e]}}}return t=t.map(i=>({...i})),t}async _resolve(e){let t=async m=>{try{return await m}catch(_){if(_.code==="ENODATA"||_.code==="ENOTFOUND")return[];throw _}},[i,a]=await Promise.all([this._resolve4(e,Ou),this._resolve6(e,Ou)].map(m=>t(m))),c=0,u=0,p=0,g=Date.now();for(let m of i)m.family=4,m.expires=g+m.ttl*1e3,c=Math.max(c,m.ttl);for(let m of a)m.family=6,m.expires=g+m.ttl*1e3,u=Math.max(u,m.ttl);return i.length>0?a.length>0?p=Math.min(c,u):p=c:p=u,{entries:[...i,...a],cacheTtl:p}}async _lookup(e){try{return{entries:await this._dnsLookup(e,{all:!0}),cacheTtl:0}}catch{return{entries:[],cacheTtl:0}}}async _set(e,t,i){if(this.maxTtl>0&&i>0){i=Math.min(i,this.maxTtl)*1e3,t[Cu]=Date.now()+i;try{await this._cache.set(e,t,i)}catch(a){this.lookupAsync=async()=>{let c=new Error("Cache Error. Please recreate the CacheableLookup instance.");throw c.cause=a,c}}I_(this._cache)&&this._tick(i)}}async queryAndCache(e){if(this._hostnamesToFallback.has(e))return this._dnsLookup(e,M_);let t=await this._resolve(e);t.entries.length===0&&this._fallback&&(t=await this._lookup(e),t.entries.length!==0&&this._hostnamesToFallback.add(e));let i=t.entries.length===0?this.errorTtl:t.cacheTtl;return await this._set(e,t.entries,i),t.entries}_tick(e){let t=this._nextRemovalTime;(!t||e<t)&&(clearTimeout(this._removalTimeout),this._nextRemovalTime=e,this._removalTimeout=setTimeout(()=>{this._nextRemovalTime=!1;let i=1/0,a=Date.now();for(let[c,u]of this._cache){let p=u[Cu];a>=p?this._cache.delete(c):p<i&&(i=p)}i!==1/0&&this._tick(i-a)},e),this._removalTimeout.unref&&this._removalTimeout.unref())}install(e){if(Eu(e),Ft in e)throw new Error("CacheableLookup has been already installed");e[Ft]=e.createConnection,e[_i]=this,e.createConnection=(t,i)=>("lookup"in t||(t.lookup=this.lookup),e[Ft](t,i))}uninstall(e){if(Eu(e),e[Ft]){if(e[_i]!==this)throw new Error("The agent is not owned by this CacheableLookup instance");e.createConnection=e[Ft],delete e[Ft],delete e[_i]}}updateInterfaceInfo(){let{_iface:e}=this;this._iface=ku(),(e.has4&&!this._iface.has4||e.has6&&!this._iface.has6)&&this._cache.clear()}clear(e){if(e){this._cache.delete(e);return}this._cache.clear()}};bi.exports=_n;bi.exports.default=_n});var Pu=$((HC,Ru)=>{"use strict";var x_="text/plain",N_="us-ascii",Au=(s,e)=>e.some(t=>t instanceof RegExp?t.test(s):t===s),L_=(s,{stripHash:e})=>{let t=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(s);if(!t)throw new Error(`Invalid URL: ${s}`);let{type:i,data:a,hash:c}=t.groups,u=i.split(";");c=e?"":c;let p=!1;u[u.length-1]==="base64"&&(u.pop(),p=!0);let g=(u.shift()||"").toLowerCase(),_=[...u.map(w=>{let[C,T=""]=w.split("=").map(S=>S.trim());return C==="charset"&&(T=T.toLowerCase(),T===N_)?"":`${C}${T?`=${T}`:""}`}).filter(Boolean)];return p&&_.push("base64"),(_.length!==0||g&&g!==x_)&&_.unshift(g),`data:${_.join(";")},${p?a.trim():a}${c?`#${c}`:""}`},D_=(s,e)=>{if(e={defaultProtocol:"http:",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,sortQueryParameters:!0,...e},s=s.trim(),/^data:/i.test(s))return L_(s,e);if(/^view-source:/i.test(s))throw new Error("`view-source:` is not supported as it is a non-standard protocol");let t=s.startsWith("//");!t&&/^\.*\//.test(s)||(s=s.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,e.defaultProtocol));let a=new URL(s);if(e.forceHttp&&e.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(e.forceHttp&&a.protocol==="https:"&&(a.protocol="http:"),e.forceHttps&&a.protocol==="http:"&&(a.protocol="https:"),e.stripAuthentication&&(a.username="",a.password=""),e.stripHash?a.hash="":e.stripTextFragment&&(a.hash=a.hash.replace(/#?:~:text.*?$/i,"")),a.pathname&&(a.pathname=a.pathname.replace(/(?<!\b(?:[a-z][a-z\d+\-.]{1,50}:))\/{2,}/g,"/")),a.pathname)try{a.pathname=decodeURI(a.pathname)}catch{}if(e.removeDirectoryIndex===!0&&(e.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(e.removeDirectoryIndex)&&e.removeDirectoryIndex.length>0){let u=a.pathname.split("/"),p=u[u.length-1];Au(p,e.removeDirectoryIndex)&&(u=u.slice(0,u.length-1),a.pathname=u.slice(1).join("/")+"/")}if(a.hostname&&(a.hostname=a.hostname.replace(/\.$/,""),e.stripWWW&&/^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(a.hostname)&&(a.hostname=a.hostname.replace(/^www\./,""))),Array.isArray(e.removeQueryParameters))for(let u of[...a.searchParams.keys()])Au(u,e.removeQueryParameters)&&a.searchParams.delete(u);e.removeQueryParameters===!0&&(a.search=""),e.sortQueryParameters&&a.searchParams.sort(),e.removeTrailingSlash&&(a.pathname=a.pathname.replace(/\/$/,""));let c=s;return s=a.toString(),!e.removeSingleSlash&&a.pathname==="/"&&!c.endsWith("/")&&a.hash===""&&(s=s.replace(/\/$/,"")),(e.removeTrailingSlash||a.pathname==="/")&&a.hash===""&&e.removeSingleSlash&&(s=s.replace(/\/$/,"")),t&&!e.normalizeProtocol&&(s=s.replace(/^http:\/\//,"//")),e.stripProtocol&&(s=s.replace(/^(?:https?:)?\/\//,"")),s};Ru.exports=D_});var xu=$((GC,Mu)=>{Mu.exports=Iu;function Iu(s,e){if(s&&e)return Iu(s)(e);if(typeof s!="function")throw new TypeError("need wrapper function");return Object.keys(s).forEach(function(i){t[i]=s[i]}),t;function t(){for(var i=new Array(arguments.length),a=0;a<i.length;a++)i[a]=arguments[a];var c=s.apply(this,i),u=i[i.length-1];return typeof c=="function"&&c!==u&&Object.keys(u).forEach(function(p){c[p]=u[p]}),c}}});var wi=$((FC,vi)=>{var Nu=xu();vi.exports=Nu(bn);vi.exports.strict=Nu(Lu);bn.proto=bn(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return bn(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return Lu(this)},configurable:!0})});function bn(s){var e=function(){return e.called?e.value:(e.called=!0,e.value=s.apply(this,arguments))};return e.called=!1,e}function Lu(s){var e=function(){if(e.called)throw new Error(e.onceError);return e.called=!0,e.value=s.apply(this,arguments)},t=s.name||"Function wrapped with `once`";return e.onceError=t+" shouldn't be called more than once",e.called=!1,e}});var ju=$((WC,Uu)=>{var U_=wi(),j_=function(){},q_=global.Bare?queueMicrotask:process.nextTick.bind(process),B_=function(s){return s.setHeader&&typeof s.abort=="function"},$_=function(s){return s.stdio&&Array.isArray(s.stdio)&&s.stdio.length===3},Du=function(s,e,t){if(typeof e=="function")return Du(s,null,e);e||(e={}),t=U_(t||j_);var i=s._writableState,a=s._readableState,c=e.readable||e.readable!==!1&&s.readable,u=e.writable||e.writable!==!1&&s.writable,p=!1,g=function(){s.writable||m()},m=function(){u=!1,c||t.call(s)},_=function(){c=!1,u||t.call(s)},w=function(k){t.call(s,k?new Error("exited with error code: "+k):null)},C=function(k){t.call(s,k)},T=function(){q_(S)},S=function(){if(!p){if(c&&!(a&&a.ended&&!a.destroyed))return t.call(s,new Error("premature close"));if(u&&!(i&&i.ended&&!i.destroyed))return t.call(s,new Error("premature close"))}},O=function(){s.req.on("finish",m)};return B_(s)?(s.on("complete",m),s.on("abort",T),s.req?O():s.on("request",O)):u&&!i&&(s.on("end",g),s.on("close",g)),$_(s)&&s.on("exit",w),s.on("end",_),s.on("finish",m),e.error!==!1&&s.on("error",C),s.on("close",T),function(){p=!0,s.removeListener("complete",m),s.removeListener("abort",T),s.removeListener("request",O),s.req&&s.req.removeListener("finish",m),s.removeListener("end",g),s.removeListener("close",g),s.removeListener("finish",m),s.removeListener("exit",w),s.removeListener("end",_),s.removeListener("error",C),s.removeListener("close",T)}};Uu.exports=Du});var $u=$((VC,Bu)=>{var H_=wi(),G_=ju(),vn;try{vn=q("fs")}catch{}var Es=function(){},F_=typeof process>"u"?!1:/^v?\.0/.test(process.version),wn=function(s){return typeof s=="function"},W_=function(s){return!F_||!vn?!1:(s instanceof(vn.ReadStream||Es)||s instanceof(vn.WriteStream||Es))&&wn(s.close)},V_=function(s){return s.setHeader&&wn(s.abort)},z_=function(s,e,t,i){i=H_(i);var a=!1;s.on("close",function(){a=!0}),G_(s,{readable:e,writable:t},function(u){if(u)return i(u);a=!0,i()});var c=!1;return function(u){if(!a&&!c){if(c=!0,W_(s))return s.close(Es);if(V_(s))return s.abort();if(wn(s.destroy))return s.destroy();i(u||new Error("stream was destroyed"))}}},qu=function(s){s()},K_=function(s,e){return s.pipe(e)},J_=function(){var s=Array.prototype.slice.call(arguments),e=wn(s[s.length-1]||Es)&&s.pop()||Es;if(Array.isArray(s[0])&&(s=s[0]),s.length<2)throw new Error("pump requires two streams per minimum");var t,i=s.map(function(a,c){var u=c<s.length-1,p=c>0;return z_(a,u,p,function(g){t||(t=g),g&&i.forEach(qu),!u&&(i.forEach(qu),e(t))})});return s.reduce(K_)};Bu.exports=J_});var Gu=$((zC,Hu)=>{"use strict";var{PassThrough:Y_}=q("stream");Hu.exports=s=>{s={...s};let{array:e}=s,{encoding:t}=s,i=t==="buffer",a=!1;e?a=!(t||i):t=t||"utf8",i&&(t=null);let c=new Y_({objectMode:a});t&&c.setEncoding(t);let u=0,p=[];return c.on("data",g=>{p.push(g),a?u=p.length:u+=g.length}),c.getBufferedValue=()=>e?p:i?Buffer.concat(p,u):p.join(""),c.getBufferedLength=()=>u,c}});var Fu=$((KC,Wt)=>{"use strict";var{constants:Q_}=q("buffer"),X_=$u(),Z_=Gu(),Cn=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function En(s,e){if(!s)return Promise.reject(new Error("Expected a stream"));e={maxBuffer:1/0,...e};let{maxBuffer:t}=e,i;return await new Promise((a,c)=>{let u=p=>{p&&i.getBufferedLength()<=Q_.MAX_LENGTH&&(p.bufferedData=i.getBufferedValue()),c(p)};i=X_(s,Z_(e),p=>{if(p){u(p);return}a()}),i.on("data",()=>{i.getBufferedLength()>t&&u(new Cn)})}),i.getBufferedValue()}Wt.exports=En;Wt.exports.default=En;Wt.exports.buffer=(s,e)=>En(s,{...e,encoding:"buffer"});Wt.exports.array=(s,e)=>En(s,{...e,array:!0});Wt.exports.MaxBufferError=Cn});var Vu=$((YC,Wu)=>{"use strict";var eb=new Set([200,203,204,206,300,301,308,404,405,410,414,501]),tb=new Set([200,203,204,300,301,302,303,307,308,404,405,410,414,501]),sb=new Set([500,502,503,504]),nb={date:!0,connection:!0,"keep-alive":!0,"proxy-authenticate":!0,"proxy-authorization":!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0},rb={"content-length":!0,"content-encoding":!0,"transfer-encoding":!0,"content-range":!0};function it(s){let e=parseInt(s,10);return isFinite(e)?e:0}function ib(s){return s?sb.has(s.status):!0}function Ci(s){let e={};if(!s)return e;let t=s.trim().split(/,/);for(let i of t){let[a,c]=i.split(/=/,2);e[a.trim()]=c===void 0?!0:c.trim().replace(/^"|"$/g,"")}return e}function ob(s){let e=[];for(let t in s){let i=s[t];e.push(i===!0?t:t+"="+i)}if(e.length)return e.join(", ")}Wu.exports=class{constructor(e,t,{shared:i,cacheHeuristic:a,immutableMinTimeToLive:c,ignoreCargoCult:u,_fromObject:p}={}){if(p){this._fromObject(p);return}if(!t||!t.headers)throw Error("Response headers missing");this._assertRequestHasHeaders(e),this._responseTime=this.now(),this._isShared=i!==!1,this._ignoreCargoCult=!!u,this._cacheHeuristic=a!==void 0?a:.1,this._immutableMinTtl=c!==void 0?c:24*3600*1e3,this._status="status"in t?t.status:200,this._resHeaders=t.headers,this._rescc=Ci(t.headers["cache-control"]),this._method="method"in e?e.method:"GET",this._url=e.url,this._host=e.headers.host,this._noAuthorization=!e.headers.authorization,this._reqHeaders=t.headers.vary?e.headers:null,this._reqcc=Ci(e.headers["cache-control"]),this._ignoreCargoCult&&"pre-check"in this._rescc&&"post-check"in this._rescc&&(delete this._rescc["pre-check"],delete this._rescc["post-check"],delete this._rescc["no-cache"],delete this._rescc["no-store"],delete this._rescc["must-revalidate"],this._resHeaders=Object.assign({},this._resHeaders,{"cache-control":ob(this._rescc)}),delete this._resHeaders.expires,delete this._resHeaders.pragma),t.headers["cache-control"]==null&&/no-cache/.test(t.headers.pragma)&&(this._rescc["no-cache"]=!0)}now(){return Date.now()}storable(){return!!(!this._reqcc["no-store"]&&(this._method==="GET"||this._method==="HEAD"||this._method==="POST"&&this._hasExplicitExpiration())&&tb.has(this._status)&&!this._rescc["no-store"]&&(!this._isShared||!this._rescc.private)&&(!this._isShared||this._noAuthorization||this._allowsStoringAuthenticated())&&(this._resHeaders.expires||this._rescc["max-age"]||this._isShared&&this._rescc["s-maxage"]||this._rescc.public||eb.has(this._status)))}_hasExplicitExpiration(){return!!(this._isShared&&this._rescc["s-maxage"]||this._rescc["max-age"]||this._resHeaders.expires)}_assertRequestHasHeaders(e){if(!e||!e.headers)throw Error("Request headers missing")}satisfiesWithoutRevalidation(e){return!this.evaluateRequest(e).revalidation}_evaluateRequestHitResult(e){return{response:{headers:this.responseHeaders()},revalidation:e}}_evaluateRequestRevalidation(e,t){return{synchronous:t,headers:this.revalidationHeaders(e)}}_evaluateRequestMissResult(e){return{response:void 0,revalidation:this._evaluateRequestRevalidation(e,!0)}}evaluateRequest(e){if(this._assertRequestHasHeaders(e),this._rescc["must-revalidate"])return this._evaluateRequestMissResult(e);if(!this._requestMatches(e,!1))return this._evaluateRequestMissResult(e);let t=Ci(e.headers["cache-control"]);return t["no-cache"]||/no-cache/.test(e.headers.pragma)?this._evaluateRequestMissResult(e):t["max-age"]&&this.age()>it(t["max-age"])?this._evaluateRequestMissResult(e):t["min-fresh"]&&this.maxAge()-this.age()<it(t["min-fresh"])?this._evaluateRequestMissResult(e):this.stale()?"max-stale"in t&&(t["max-stale"]===!0||t["max-stale"]>this.age()-this.maxAge())?this._evaluateRequestHitResult(void 0):this.useStaleWhileRevalidate()?this._evaluateRequestHitResult(this._evaluateRequestRevalidation(e,!1)):this._evaluateRequestMissResult(e):this._evaluateRequestHitResult(void 0)}_requestMatches(e,t){return!!((!this._url||this._url===e.url)&&this._host===e.headers.host&&(!e.method||this._method===e.method||t&&e.method==="HEAD")&&this._varyMatches(e))}_allowsStoringAuthenticated(){return!!(this._rescc["must-revalidate"]||this._rescc.public||this._rescc["s-maxage"])}_varyMatches(e){if(!this._resHeaders.vary)return!0;if(this._resHeaders.vary==="*")return!1;let t=this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/);for(let i of t)if(e.headers[i]!==this._reqHeaders[i])return!1;return!0}_copyWithoutHopByHopHeaders(e){let t={};for(let i in e)nb[i]||(t[i]=e[i]);if(e.connection){let i=e.connection.trim().split(/\s*,\s*/);for(let a of i)delete t[a]}if(t.warning){let i=t.warning.split(/,/).filter(a=>!/^\s*1[0-9][0-9]/.test(a));i.length?t.warning=i.join(",").trim():delete t.warning}return t}responseHeaders(){let e=this._copyWithoutHopByHopHeaders(this._resHeaders),t=this.age();return t>3600*24&&!this._hasExplicitExpiration()&&this.maxAge()>3600*24&&(e.warning=(e.warning?`${e.warning}, `:"")+'113 - "rfc7234 5.5.4"'),e.age=`${Math.round(t)}`,e.date=new Date(this.now()).toUTCString(),e}date(){let e=Date.parse(this._resHeaders.date);return isFinite(e)?e:this._responseTime}age(){let e=this._ageValue(),t=(this.now()-this._responseTime)/1e3;return e+t}_ageValue(){return it(this._resHeaders.age)}maxAge(){if(!this.storable()||this._rescc["no-cache"]||this._isShared&&this._resHeaders["set-cookie"]&&!this._rescc.public&&!this._rescc.immutable||this._resHeaders.vary==="*")return 0;if(this._isShared){if(this._rescc["proxy-revalidate"])return 0;if(this._rescc["s-maxage"])return it(this._rescc["s-maxage"])}if(this._rescc["max-age"])return it(this._rescc["max-age"]);let e=this._rescc.immutable?this._immutableMinTtl:0,t=this.date();if(this._resHeaders.expires){let i=Date.parse(this._resHeaders.expires);return Number.isNaN(i)||i<t?0:Math.max(e,(i-t)/1e3)}if(this._resHeaders["last-modified"]){let i=Date.parse(this._resHeaders["last-modified"]);if(isFinite(i)&&t>i)return Math.max(e,(t-i)/1e3*this._cacheHeuristic)}return e}timeToLive(){let e=this.maxAge()-this.age(),t=e+it(this._rescc["stale-if-error"]),i=e+it(this._rescc["stale-while-revalidate"]);return Math.round(Math.max(0,e,t,i)*1e3)}stale(){return this.maxAge()<=this.age()}_useStaleIfError(){return this.maxAge()+it(this._rescc["stale-if-error"])>this.age()}useStaleWhileRevalidate(){let e=it(this._rescc["stale-while-revalidate"]);return e>0&&this.maxAge()+e>this.age()}static fromObject(e){return new this(void 0,void 0,{_fromObject:e})}_fromObject(e){if(this._responseTime)throw Error("Reinitialized");if(!e||e.v!==1)throw Error("Invalid serialization");this._responseTime=e.t,this._isShared=e.sh,this._cacheHeuristic=e.ch,this._immutableMinTtl=e.imm!==void 0?e.imm:24*3600*1e3,this._ignoreCargoCult=!!e.icc,this._status=e.st,this._resHeaders=e.resh,this._rescc=e.rescc,this._method=e.m,this._url=e.u,this._host=e.h,this._noAuthorization=e.a,this._reqHeaders=e.reqh,this._reqcc=e.reqcc}toObject(){return{v:1,t:this._responseTime,sh:this._isShared,ch:this._cacheHeuristic,imm:this._immutableMinTtl,icc:this._ignoreCargoCult,st:this._status,resh:this._resHeaders,rescc:this._rescc,m:this._method,u:this._url,h:this._host,a:this._noAuthorization,reqh:this._reqHeaders,reqcc:this._reqcc}}revalidationHeaders(e){this._assertRequestHasHeaders(e);let t=this._copyWithoutHopByHopHeaders(e.headers);if(delete t["if-range"],!this._requestMatches(e,!0)||!this.storable())return delete t["if-none-match"],delete t["if-modified-since"],t;if(this._resHeaders.etag&&(t["if-none-match"]=t["if-none-match"]?`${t["if-none-match"]}, ${this._resHeaders.etag}`:this._resHeaders.etag),t["accept-ranges"]||t["if-match"]||t["if-unmodified-since"]||this._method&&this._method!="GET"){if(delete t["if-modified-since"],t["if-none-match"]){let a=t["if-none-match"].split(/,/).filter(c=>!/^\s*W\//.test(c));a.length?t["if-none-match"]=a.join(",").trim():delete t["if-none-match"]}}else this._resHeaders["last-modified"]&&!t["if-modified-since"]&&(t["if-modified-since"]=this._resHeaders["last-modified"]);return t}revalidatedPolicy(e,t){if(this._assertRequestHasHeaders(e),this._useStaleIfError()&&ib(t))return{policy:this,modified:!1,matches:!0};if(!t||!t.headers)throw Error("Response headers missing");let i=!1;t.status!==void 0&&t.status!=304?i=!1:t.headers.etag&&!/^\s*W\//.test(t.headers.etag)?i=this._resHeaders.etag&&this._resHeaders.etag.replace(/^\s*W\//,"")===t.headers.etag:this._resHeaders.etag&&t.headers.etag?i=this._resHeaders.etag.replace(/^\s*W\//,"")===t.headers.etag.replace(/^\s*W\//,""):this._resHeaders["last-modified"]?i=this._resHeaders["last-modified"]===t.headers["last-modified"]:!this._resHeaders.etag&&!this._resHeaders["last-modified"]&&!t.headers.etag&&!t.headers["last-modified"]&&(i=!0);let a={shared:this._isShared,cacheHeuristic:this._cacheHeuristic,immutableMinTimeToLive:this._immutableMinTtl,ignoreCargoCult:this._ignoreCargoCult};if(!i)return{policy:new this.constructor(e,t,a),modified:t.status!=304,matches:!1};let c={};for(let p in this._resHeaders)c[p]=p in t.headers&&!rb[p]?t.headers[p]:this._resHeaders[p];let u=Object.assign({},t,{status:this._status,method:this._method,headers:c});return{policy:new this.constructor(e,u,a),modified:!1,matches:!0}}}});var kn=$((QC,zu)=>{"use strict";zu.exports=s=>{let e={};for(let[t,i]of Object.entries(s))e[t.toLowerCase()]=i;return e}});var Ju=$((XC,Ku)=>{"use strict";var ab=q("stream").Readable,cb=kn(),Ei=class extends ab{constructor(e,t,i,a){if(typeof e!="number")throw new TypeError("Argument `statusCode` should be a number");if(typeof t!="object")throw new TypeError("Argument `headers` should be an object");if(!(i instanceof Buffer))throw new TypeError("Argument `body` should be a buffer");if(typeof a!="string")throw new TypeError("Argument `url` should be a string");super(),this.statusCode=e,this.headers=cb(t),this.body=i,this.url=a}_read(){this.push(this.body),this.push(null)}};Ku.exports=Ei});var Qu=$((ZC,Yu)=>{"use strict";var lb=["destroy","setTimeout","socket","headers","trailers","rawHeaders","statusCode","httpVersion","httpVersionMinor","httpVersionMajor","rawTrailers","statusMessage"];Yu.exports=(s,e)=>{let t=new Set(Object.keys(s).concat(lb));for(let i of t)i in e||(e[i]=typeof s[i]=="function"?s[i].bind(s):s[i])}});var Zu=$((e0,Xu)=>{"use strict";var ub=q("stream").PassThrough,hb=Qu(),db=s=>{if(!(s&&s.pipe))throw new TypeError("Parameter `response` must be a response stream.");let e=new ub;return hb(s,e),s.pipe(e)};Xu.exports=db});var eh=$(ki=>{ki.stringify=function s(e){if(typeof e>"u")return e;if(e&&Buffer.isBuffer(e))return JSON.stringify(":base64:"+e.toString("base64"));if(e&&e.toJSON&&(e=e.toJSON()),e&&typeof e=="object"){var t="",i=Array.isArray(e);t=i?"[":"{";var a=!0;for(var c in e){var u=typeof e[c]=="function"||!i&&typeof e[c]>"u";Object.hasOwnProperty.call(e,c)&&!u&&(a||(t+=","),a=!1,i?e[c]==null?t+="null":t+=s(e[c]):e[c]!==void 0&&(t+=s(c)+":"+s(e[c])))}return t+=i?"]":"}",t}else return typeof e=="string"?JSON.stringify(/^:/.test(e)?":"+e:e):typeof e>"u"?"null":JSON.stringify(e)};ki.parse=function(s){return JSON.parse(s,function(e,t){return typeof t=="string"?/^:base64:/.test(t)?Buffer.from(t.substring(8),"base64"):/^:/.test(t)?t.substring(1):t:t})}});var rh=$((s0,nh)=>{"use strict";var fb=q("events"),th=eh(),pb=s=>{let e={redis:"@keyv/redis",rediss:"@keyv/redis",mongodb:"@keyv/mongo",mongo:"@keyv/mongo",sqlite:"@keyv/sqlite",postgresql:"@keyv/postgres",postgres:"@keyv/postgres",mysql:"@keyv/mysql",etcd:"@keyv/etcd",offline:"@keyv/offline",tiered:"@keyv/tiered"};if(s.adapter||s.uri){let t=s.adapter||/^[^:+]*/.exec(s.uri)[0];return new(q(e[t]))(s)}return new Map},sh=["sqlite","postgres","mysql","mongo","redis","tiered"],Oi=class extends fb{constructor(e,{emitErrors:t=!0,...i}={}){if(super(),this.opts={namespace:"keyv",serialize:th.stringify,deserialize:th.parse,...typeof e=="string"?{uri:e}:e,...i},!this.opts.store){let c={...this.opts};this.opts.store=pb(c)}if(this.opts.compression){let c=this.opts.compression;this.opts.serialize=c.serialize.bind(c),this.opts.deserialize=c.deserialize.bind(c)}typeof this.opts.store.on=="function"&&t&&this.opts.store.on("error",c=>this.emit("error",c)),this.opts.store.namespace=this.opts.namespace;let a=c=>async function*(){for await(let[u,p]of typeof c=="function"?c(this.opts.store.namespace):c){let g=await this.opts.deserialize(p);if(!(this.opts.store.namespace&&!u.includes(this.opts.store.namespace))){if(typeof g.expires=="number"&&Date.now()>g.expires){this.delete(u);continue}yield[this._getKeyUnprefix(u),g.value]}}};typeof this.opts.store[Symbol.iterator]=="function"&&this.opts.store instanceof Map?this.iterator=a(this.opts.store):typeof this.opts.store.iterator=="function"&&this.opts.store.opts&&this._checkIterableAdaptar()&&(this.iterator=a(this.opts.store.iterator.bind(this.opts.store)))}_checkIterableAdaptar(){return sh.includes(this.opts.store.opts.dialect)||sh.findIndex(e=>this.opts.store.opts.url.includes(e))>=0}_getKeyPrefix(e){return`${this.opts.namespace}:${e}`}_getKeyPrefixArray(e){return e.map(t=>`${this.opts.namespace}:${t}`)}_getKeyUnprefix(e){return e.split(":").splice(1).join(":")}get(e,t){let{store:i}=this.opts,a=Array.isArray(e),c=a?this._getKeyPrefixArray(e):this._getKeyPrefix(e);if(a&&i.getMany===void 0){let u=[];for(let p of c)u.push(Promise.resolve().then(()=>i.get(p)).then(g=>typeof g=="string"?this.opts.deserialize(g):this.opts.compression?this.opts.deserialize(g):g).then(g=>{if(g!=null)return typeof g.expires=="number"&&Date.now()>g.expires?this.delete(p).then(()=>{}):t&&t.raw?g:g.value}));return Promise.allSettled(u).then(p=>{let g=[];for(let m of p)g.push(m.value);return g})}return Promise.resolve().then(()=>a?i.getMany(c):i.get(c)).then(u=>typeof u=="string"?this.opts.deserialize(u):this.opts.compression?this.opts.deserialize(u):u).then(u=>{if(u!=null)return a?u.map((p,g)=>{if(typeof p=="string"&&(p=this.opts.deserialize(p)),p!=null){if(typeof p.expires=="number"&&Date.now()>p.expires){this.delete(e[g]).then(()=>{});return}return t&&t.raw?p:p.value}}):typeof u.expires=="number"&&Date.now()>u.expires?this.delete(e).then(()=>{}):t&&t.raw?u:u.value})}set(e,t,i){let a=this._getKeyPrefix(e);typeof i>"u"&&(i=this.opts.ttl),i===0&&(i=void 0);let{store:c}=this.opts;return Promise.resolve().then(()=>{let u=typeof i=="number"?Date.now()+i:null;return typeof t=="symbol"&&this.emit("error","symbol cannot be serialized"),t={value:t,expires:u},this.opts.serialize(t)}).then(u=>c.set(a,u,i)).then(()=>!0)}delete(e){let{store:t}=this.opts;if(Array.isArray(e)){let a=this._getKeyPrefixArray(e);if(t.deleteMany===void 0){let c=[];for(let u of a)c.push(t.delete(u));return Promise.allSettled(c).then(u=>u.every(p=>p.value===!0))}return Promise.resolve().then(()=>t.deleteMany(a))}let i=this._getKeyPrefix(e);return Promise.resolve().then(()=>t.delete(i))}clear(){let{store:e}=this.opts;return Promise.resolve().then(()=>e.clear())}has(e){let t=this._getKeyPrefix(e),{store:i}=this.opts;return Promise.resolve().then(async()=>typeof i.has=="function"?i.has(t):await i.get(t)!==void 0)}disconnect(){let{store:e}=this.opts;if(typeof e.disconnect=="function")return e.disconnect()}};nh.exports=Oi});var ah=$((r0,oh)=>{"use strict";var gb=q("events"),On=q("url"),mb=Pu(),yb=Fu(),Ti=Vu(),ih=Ju(),_b=kn(),bb=Zu(),vb=rh(),ks=class s{constructor(e,t){if(typeof e!="function")throw new TypeError("Parameter `request` must be a function");return this.cache=new vb({uri:typeof t=="string"&&t,store:typeof t!="string"&&t,namespace:"cacheable-request"}),this.createCacheableRequest(e)}createCacheableRequest(e){return(t,i)=>{let a;if(typeof t=="string")a=Si(On.parse(t)),t={};else if(t instanceof On.URL)a=Si(On.parse(t.toString())),t={};else{let[w,...C]=(t.path||"").split("?"),T=C.length>0?`?${C.join("?")}`:"";a=Si({...t,pathname:w,search:T})}t={headers:{},method:"GET",cache:!0,strictTtl:!1,automaticFailover:!1,...t,...wb(a)},t.headers=_b(t.headers);let c=new gb,u=mb(On.format(a),{stripWWW:!1,removeTrailingSlash:!1,stripAuthentication:!1}),p=`${t.method}:${u}`,g=!1,m=!1,_=w=>{m=!0;let C=!1,T,S=new Promise(k=>{T=()=>{C||(C=!0,k())}}),O=k=>{if(g&&!w.forceRefresh){k.status=k.statusCode;let G=Ti.fromObject(g.cachePolicy).revalidatedPolicy(w,k);if(!G.modified){let Y=G.policy.responseHeaders();k=new ih(g.statusCode,Y,g.body,g.url),k.cachePolicy=G.policy,k.fromCache=!0}}k.fromCache||(k.cachePolicy=new Ti(w,k,w),k.fromCache=!1);let N;w.cache&&k.cachePolicy.storable()?(N=bb(k),(async()=>{try{let G=yb.buffer(k);if(await Promise.race([S,new Promise(Z=>k.once("end",Z))]),C)return;let Y=await G,X={cachePolicy:k.cachePolicy.toObject(),url:k.url,statusCode:k.fromCache?g.statusCode:k.statusCode,body:Y},Q=w.strictTtl?k.cachePolicy.timeToLive():void 0;w.maxTtl&&(Q=Q?Math.min(Q,w.maxTtl):w.maxTtl),await this.cache.set(p,X,Q)}catch(G){c.emit("error",new s.CacheError(G))}})()):w.cache&&g&&(async()=>{try{await this.cache.delete(p)}catch(G){c.emit("error",new s.CacheError(G))}})(),c.emit("response",N||k),typeof i=="function"&&i(N||k)};try{let k=e(w,O);k.once("error",T),k.once("abort",T),c.emit("request",k)}catch(k){c.emit("error",new s.RequestError(k))}};return(async()=>{let w=async T=>{await Promise.resolve();let S=T.cache?await this.cache.get(p):void 0;if(typeof S>"u")return _(T);let O=Ti.fromObject(S.cachePolicy);if(O.satisfiesWithoutRevalidation(T)&&!T.forceRefresh){let k=O.responseHeaders(),N=new ih(S.statusCode,k,S.body,S.url);N.cachePolicy=O,N.fromCache=!0,c.emit("response",N),typeof i=="function"&&i(N)}else g=S,T.headers=O.revalidationHeaders(T),_(T)},C=T=>c.emit("error",new s.CacheError(T));this.cache.once("error",C),c.on("response",()=>this.cache.removeListener("error",C));try{await w(t)}catch(T){t.automaticFailover&&!m&&_(t),c.emit("error",new s.CacheError(T))}})(),c}}};function wb(s){let e={...s};return e.path=`${s.pathname||"/"}${s.search||""}`,delete e.pathname,delete e.search,e}function Si(s){return{protocol:s.protocol,auth:s.auth,hostname:s.hostname||s.host||"localhost",port:s.port,pathname:s.pathname,search:s.search}}ks.RequestError=class extends Error{constructor(s){super(s.message),this.name="RequestError",Object.assign(this,s)}};ks.CacheError=class extends Error{constructor(s){super(s.message),this.name="CacheError",Object.assign(this,s)}};oh.exports=ks});var lh=$((a0,ch)=>{"use strict";var Cb=["aborted","complete","headers","httpVersion","httpVersionMinor","httpVersionMajor","method","rawHeaders","rawTrailers","setTimeout","socket","statusCode","statusMessage","trailers","url"];ch.exports=(s,e)=>{if(e._readableState.autoDestroy)throw new Error("The second stream must have the `autoDestroy` option set to `false`");let t=new Set(Object.keys(s).concat(Cb)),i={};for(let a of t)a in e||(i[a]={get(){let c=s[a];return typeof c=="function"?c.bind(s):c},set(c){s[a]=c},enumerable:!0,configurable:!1});return Object.defineProperties(e,i),s.once("aborted",()=>{e.destroy(),e.emit("aborted")}),s.once("close",()=>{s.complete&&e.readable?e.once("end",()=>{e.emit("close")}):e.emit("close")}),e}});var hh=$((c0,uh)=>{"use strict";var{Transform:Eb,PassThrough:kb}=q("stream"),Ai=q("zlib"),Ob=lh();uh.exports=s=>{let e=(s.headers["content-encoding"]||"").toLowerCase();if(!["gzip","deflate","br"].includes(e))return s;let t=e==="br";if(t&&typeof Ai.createBrotliDecompress!="function")return s.destroy(new Error("Brotli is not supported on Node.js < 12")),s;let i=!0,a=new Eb({transform(p,g,m){i=!1,m(null,p)},flush(p){p()}}),c=new kb({autoDestroy:!1,destroy(p,g){s.destroy(),g(p)}}),u=t?Ai.createBrotliDecompress():Ai.createUnzip();return u.once("error",p=>{if(i&&!s.readable){c.end();return}c.destroy(p)}),Ob(s,c),s.pipe(a).pipe(u).pipe(c),c}});var Pi=$((l0,dh)=>{"use strict";var Ri=class{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");this.maxSize=e.maxSize,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_set(e,t){if(this.cache.set(e,t),this._size++,this._size>=this.maxSize){if(this._size=0,typeof this.onEviction=="function")for(let[i,a]of this.oldCache.entries())this.onEviction(i,a);this.oldCache=this.cache,this.cache=new Map}}get(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e)){let t=this.oldCache.get(e);return this.oldCache.delete(e),this._set(e,t),t}}set(e,t){return this.cache.has(e)?this.cache.set(e,t):this._set(e,t),this}has(e){return this.cache.has(e)||this.oldCache.has(e)}peek(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e))return this.oldCache.get(e)}delete(e){let t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache)yield e;for(let e of this.oldCache){let[t]=e;this.cache.has(t)||(yield e)}}get size(){let e=0;for(let t of this.oldCache.keys())this.cache.has(t)||e++;return Math.min(this._size+e,this.maxSize)}};dh.exports=Ri});var Mi=$((u0,mh)=>{"use strict";var Tb=q("events"),Sb=q("tls"),Ab=q("http2"),Rb=Pi(),Ce=Symbol("currentStreamsCount"),fh=Symbol("request"),Le=Symbol("cachedOriginSet"),Vt=Symbol("gracefullyClosing"),Pb=["maxDeflateDynamicTableSize","maxSessionMemory","maxHeaderListPairs","maxOutstandingPings","maxReservedRemoteStreams","maxSendHeaderBlockLength","paddingStrategy","localAddress","path","rejectUnauthorized","minDHSize","ca","cert","clientCertEngine","ciphers","key","pfx","servername","minVersion","maxVersion","secureProtocol","crl","honorCipherOrder","ecdhCurve","dhparam","secureOptions","sessionIdContext"],Ib=(s,e,t)=>{let i=0,a=s.length;for(;i<a;){let c=i+a>>>1;t(s[c],e)?i=c+1:a=c}return i},Mb=(s,e)=>s.remoteSettings.maxConcurrentStreams>e.remoteSettings.maxConcurrentStreams,Ii=(s,e)=>{for(let t of s)t[Le].length<e[Le].length&&t[Le].every(i=>e[Le].includes(i))&&t[Ce]+e[Ce]<=e.remoteSettings.maxConcurrentStreams&&gh(t)},xb=(s,e)=>{for(let t of s)e[Le].length<t[Le].length&&e[Le].every(i=>t[Le].includes(i))&&e[Ce]+t[Ce]<=t.remoteSettings.maxConcurrentStreams&&gh(e)},ph=({agent:s,isFree:e})=>{let t={};for(let i in s.sessions){let c=s.sessions[i].filter(u=>{let p=u[Et.kCurrentStreamsCount]<u.remoteSettings.maxConcurrentStreams;return e?p:!p});c.length!==0&&(t[i]=c)}return t},gh=s=>{s[Vt]=!0,s[Ce]===0&&s.close()},Et=class s extends Tb{constructor({timeout:e=6e4,maxSessions:t=1/0,maxFreeSessions:i=10,maxCachedTlsSessions:a=100}={}){super(),this.sessions={},this.queue={},this.timeout=e,this.maxSessions=t,this.maxFreeSessions=i,this._freeSessionsCount=0,this._sessionsCount=0,this.settings={enablePush:!1},this.tlsSessionCache=new Rb({maxSize:a})}static normalizeOrigin(e,t){return typeof e=="string"&&(e=new URL(e)),t&&e.hostname!==t&&(e.hostname=t),e.origin}normalizeOptions(e){let t="";if(e)for(let i of Pb)e[i]&&(t+=`:${e[i]}`);return t}_tryToCreateNewSession(e,t){if(!(e in this.queue)||!(t in this.queue[e]))return;let i=this.queue[e][t];this._sessionsCount<this.maxSessions&&!i.completed&&(i.completed=!0,i())}getSession(e,t,i){return new Promise((a,c)=>{Array.isArray(i)?(i=[...i],a()):i=[{resolve:a,reject:c}];let u=this.normalizeOptions(t),p=s.normalizeOrigin(e,t&&t.servername);if(p===void 0){for(let{reject:_}of i)_(new TypeError("The `origin` argument needs to be a string or an URL object"));return}if(u in this.sessions){let _=this.sessions[u],w=-1,C=-1,T;for(let S of _){let O=S.remoteSettings.maxConcurrentStreams;if(O<w)break;if(S[Le].includes(p)){let k=S[Ce];if(k>=O||S[Vt]||S.destroyed)continue;T||(w=O),k>C&&(T=S,C=k)}}if(T){if(i.length!==1){for(let{reject:S}of i){let O=new Error(`Expected the length of listeners to be 1, got ${i.length}.
34
- Please report this to https://github.com/szmarczak/http2-wrapper/`);S(O)}return}i[0].resolve(T);return}}if(u in this.queue){if(p in this.queue[u]){this.queue[u][p].listeners.push(...i),this._tryToCreateNewSession(u,p);return}}else this.queue[u]={};let g=()=>{u in this.queue&&this.queue[u][p]===m&&(delete this.queue[u][p],Object.keys(this.queue[u]).length===0&&delete this.queue[u])},m=()=>{let _=`${p}:${u}`,w=!1;try{let C=Ab.connect(e,{createConnection:this.createConnection,settings:this.settings,session:this.tlsSessionCache.get(_),...t});C[Ce]=0,C[Vt]=!1;let T=()=>C[Ce]<C.remoteSettings.maxConcurrentStreams,S=!0;C.socket.once("session",k=>{this.tlsSessionCache.set(_,k)}),C.once("error",k=>{for(let{reject:N}of i)N(k);this.tlsSessionCache.delete(_)}),C.setTimeout(this.timeout,()=>{C.destroy()}),C.once("close",()=>{if(w){S&&this._freeSessionsCount--,this._sessionsCount--;let k=this.sessions[u];k.splice(k.indexOf(C),1),k.length===0&&delete this.sessions[u]}else{let k=new Error("Session closed without receiving a SETTINGS frame");k.code="HTTP2WRAPPER_NOSETTINGS";for(let{reject:N}of i)N(k);g()}this._tryToCreateNewSession(u,p)});let O=()=>{if(!(!(u in this.queue)||!T())){for(let k of C[Le])if(k in this.queue[u]){let{listeners:N}=this.queue[u][k];for(;N.length!==0&&T();)N.shift().resolve(C);let G=this.queue[u];if(G[k].listeners.length===0&&(delete G[k],Object.keys(G).length===0)){delete this.queue[u];break}if(!T())break}}};C.on("origin",()=>{C[Le]=C.originSet,T()&&(O(),Ii(this.sessions[u],C))}),C.once("remoteSettings",()=>{if(C.ref(),C.unref(),this._sessionsCount++,m.destroyed){let k=new Error("Agent has been destroyed");for(let N of i)N.reject(k);C.destroy();return}C[Le]=C.originSet;{let k=this.sessions;if(u in k){let N=k[u];N.splice(Ib(N,C,Mb),0,C)}else k[u]=[C]}this._freeSessionsCount+=1,w=!0,this.emit("session",C),O(),g(),C[Ce]===0&&this._freeSessionsCount>this.maxFreeSessions&&C.close(),i.length!==0&&(this.getSession(p,t,i),i.length=0),C.on("remoteSettings",()=>{O(),Ii(this.sessions[u],C)})}),C[fh]=C.request,C.request=(k,N)=>{if(C[Vt])throw new Error("The session is gracefully closing. No new streams are allowed.");let G=C[fh](k,N);return C.ref(),++C[Ce],C[Ce]===C.remoteSettings.maxConcurrentStreams&&this._freeSessionsCount--,G.once("close",()=>{if(S=T(),--C[Ce],!C.destroyed&&!C.closed&&(xb(this.sessions[u],C),T()&&!C.closed)){S||(this._freeSessionsCount++,S=!0);let Y=C[Ce]===0;Y&&C.unref(),Y&&(this._freeSessionsCount>this.maxFreeSessions||C[Vt])?C.close():(Ii(this.sessions[u],C),O())}}),G}}catch(C){for(let T of i)T.reject(C);g()}};m.listeners=i,m.completed=!1,m.destroyed=!1,this.queue[u][p]=m,this._tryToCreateNewSession(u,p)})}request(e,t,i,a){return new Promise((c,u)=>{this.getSession(e,t,[{reject:u,resolve:p=>{try{c(p.request(i,a))}catch(g){u(g)}}}])})}createConnection(e,t){return s.connect(e,t)}static connect(e,t){t.ALPNProtocols=["h2"];let i=e.port||443,a=e.hostname||e.host;return typeof t.servername>"u"&&(t.servername=a),Sb.connect(i,a,t)}closeFreeSessions(){for(let e of Object.values(this.sessions))for(let t of e)t[Ce]===0&&t.close()}destroy(e){for(let t of Object.values(this.sessions))for(let i of t)i.destroy(e);for(let t of Object.values(this.queue))for(let i of Object.values(t))i.destroyed=!0;this.queue={}}get freeSessions(){return ph({agent:this,isFree:!0})}get busySessions(){return ph({agent:this,isFree:!1})}};Et.kCurrentStreamsCount=Ce;Et.kGracefullyClosing=Vt;mh.exports={Agent:Et,globalAgent:new Et}});var Ni=$((h0,yh)=>{"use strict";var{Readable:Nb}=q("stream"),xi=class extends Nb{constructor(e,t){super({highWaterMark:t,autoDestroy:!1}),this.statusCode=null,this.statusMessage="",this.httpVersion="2.0",this.httpVersionMajor=2,this.httpVersionMinor=0,this.headers={},this.trailers={},this.req=null,this.aborted=!1,this.complete=!1,this.upgrade=null,this.rawHeaders=[],this.rawTrailers=[],this.socket=e,this.connection=e,this._dumped=!1}_destroy(e){this.req._request.destroy(e)}setTimeout(e,t){return this.req.setTimeout(e,t),this}_dump(){this._dumped||(this._dumped=!0,this.removeAllListeners("data"),this.resume())}_read(){this.req&&this.req._request.resume()}};yh.exports=xi});var Li=$((d0,_h)=>{"use strict";_h.exports=s=>{let e={protocol:s.protocol,hostname:typeof s.hostname=="string"&&s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,host:s.host,hash:s.hash,search:s.search,pathname:s.pathname,href:s.href,path:`${s.pathname||""}${s.search||""}`};return typeof s.port=="string"&&s.port.length!==0&&(e.port=Number(s.port)),(s.username||s.password)&&(e.auth=`${s.username||""}:${s.password||""}`),e}});var vh=$((f0,bh)=>{"use strict";bh.exports=(s,e,t)=>{for(let i of t)s.on(i,(...a)=>e.emit(i,...a))}});var Ch=$((p0,wh)=>{"use strict";wh.exports=s=>{switch(s){case":method":case":scheme":case":authority":case":path":return!0;default:return!1}}});var kh=$((m0,Eh)=>{"use strict";var zt=(s,e,t)=>{Eh.exports[e]=class extends s{constructor(...a){super(typeof t=="string"?t:t(a)),this.name=`${super.name} [${e}]`,this.code=e}}};zt(TypeError,"ERR_INVALID_ARG_TYPE",s=>{let e=s[0].includes(".")?"property":"argument",t=s[1],i=Array.isArray(t);return i&&(t=`${t.slice(0,-1).join(", ")} or ${t.slice(-1)}`),`The "${s[0]}" ${e} must be ${i?"one of":"of"} type ${t}. Received ${typeof s[2]}`});zt(TypeError,"ERR_INVALID_PROTOCOL",s=>`Protocol "${s[0]}" not supported. Expected "${s[1]}"`);zt(Error,"ERR_HTTP_HEADERS_SENT",s=>`Cannot ${s[0]} headers after they are sent to the client`);zt(TypeError,"ERR_INVALID_HTTP_TOKEN",s=>`${s[0]} must be a valid HTTP token [${s[1]}]`);zt(TypeError,"ERR_HTTP_INVALID_HEADER_VALUE",s=>`Invalid value "${s[0]} for header "${s[1]}"`);zt(TypeError,"ERR_INVALID_CHAR",s=>`Invalid character in ${s[0]} [${s[1]}]`)});var Bi=$((y0,Ih)=>{"use strict";var Lb=q("http2"),{Writable:Db}=q("stream"),{Agent:Oh,globalAgent:Ub}=Mi(),jb=Ni(),qb=Li(),Bb=vh(),$b=Ch(),{ERR_INVALID_ARG_TYPE:Di,ERR_INVALID_PROTOCOL:Hb,ERR_HTTP_HEADERS_SENT:Th,ERR_INVALID_HTTP_TOKEN:Gb,ERR_HTTP_INVALID_HEADER_VALUE:Fb,ERR_INVALID_CHAR:Wb}=kh(),{HTTP2_HEADER_STATUS:Sh,HTTP2_HEADER_METHOD:Ah,HTTP2_HEADER_PATH:Rh,HTTP2_METHOD_CONNECT:Vb}=Lb.constants,be=Symbol("headers"),Ui=Symbol("origin"),ji=Symbol("session"),Ph=Symbol("options"),Tn=Symbol("flushedHeaders"),Os=Symbol("jobs"),zb=/^[\^`\-\w!#$%&*+.|~]+$/,Kb=/[^\t\u0020-\u007E\u0080-\u00FF]/,qi=class extends Db{constructor(e,t,i){super({autoDestroy:!1});let a=typeof e=="string"||e instanceof URL;if(a&&(e=qb(e instanceof URL?e:new URL(e))),typeof t=="function"||t===void 0?(i=t,t=a?e:{...e}):t={...e,...t},t.h2session)this[ji]=t.h2session;else if(t.agent===!1)this.agent=new Oh({maxFreeSessions:0});else if(typeof t.agent>"u"||t.agent===null)typeof t.createConnection=="function"?(this.agent=new Oh({maxFreeSessions:0}),this.agent.createConnection=t.createConnection):this.agent=Ub;else if(typeof t.agent.request=="function")this.agent=t.agent;else throw new Di("options.agent",["Agent-like Object","undefined","false"],t.agent);if(t.protocol&&t.protocol!=="https:")throw new Hb(t.protocol,"https:");let c=t.port||t.defaultPort||this.agent&&this.agent.defaultPort||443,u=t.hostname||t.host||"localhost";delete t.hostname,delete t.host,delete t.port;let{timeout:p}=t;if(t.timeout=void 0,this[be]=Object.create(null),this[Os]=[],this.socket=null,this.connection=null,this.method=t.method||"GET",this.path=t.path,this.res=null,this.aborted=!1,this.reusedSocket=!1,t.headers)for(let[g,m]of Object.entries(t.headers))this.setHeader(g,m);t.auth&&!("authorization"in this[be])&&(this[be].authorization="Basic "+Buffer.from(t.auth).toString("base64")),t.session=t.tlsSession,t.path=t.socketPath,this[Ph]=t,c===443?(this[Ui]=`https://${u}`,":authority"in this[be]||(this[be][":authority"]=u)):(this[Ui]=`https://${u}:${c}`,":authority"in this[be]||(this[be][":authority"]=`${u}:${c}`)),p&&this.setTimeout(p),i&&this.once("response",i),this[Tn]=!1}get method(){return this[be][Ah]}set method(e){e&&(this[be][Ah]=e.toUpperCase())}get path(){return this[be][Rh]}set path(e){e&&(this[be][Rh]=e)}get _mustNotHaveABody(){return this.method==="GET"||this.method==="HEAD"||this.method==="DELETE"}_write(e,t,i){if(this._mustNotHaveABody){i(new Error("The GET, HEAD and DELETE methods must NOT have a body"));return}this.flushHeaders();let a=()=>this._request.write(e,t,i);this._request?a():this[Os].push(a)}_final(e){if(this.destroyed)return;this.flushHeaders();let t=()=>{if(this._mustNotHaveABody){e();return}this._request.end(e)};this._request?t():this[Os].push(t)}abort(){this.res&&this.res.complete||(this.aborted||process.nextTick(()=>this.emit("abort")),this.aborted=!0,this.destroy())}_destroy(e,t){this.res&&this.res._dump(),this._request&&this._request.destroy(),t(e)}async flushHeaders(){if(this[Tn]||this.destroyed)return;this[Tn]=!0;let e=this.method===Vb,t=i=>{if(this._request=i,this.destroyed){i.destroy();return}e||Bb(i,this,["timeout","continue","close","error"]);let a=u=>(...p)=>{!this.writable&&!this.destroyed?u(...p):this.once("finish",()=>{u(...p)})};i.once("response",a((u,p,g)=>{let m=new jb(this.socket,i.readableHighWaterMark);this.res=m,m.req=this,m.statusCode=u[Sh],m.headers=u,m.rawHeaders=g,m.once("end",()=>{this.aborted?(m.aborted=!0,m.emit("aborted")):(m.complete=!0,m.socket=null,m.connection=null)}),e?(m.upgrade=!0,this.emit("connect",m,i,Buffer.alloc(0))?this.emit("close"):i.destroy()):(i.on("data",_=>{!m._dumped&&!m.push(_)&&i.pause()}),i.once("end",()=>{m.push(null)}),this.emit("response",m)||m._dump())})),i.once("headers",a(u=>this.emit("information",{statusCode:u[Sh]}))),i.once("trailers",a((u,p,g)=>{let{res:m}=this;m.trailers=u,m.rawTrailers=g}));let{socket:c}=i.session;this.socket=c,this.connection=c;for(let u of this[Os])u();this.emit("socket",this.socket)};if(this[ji])try{t(this[ji].request(this[be]))}catch(i){this.emit("error",i)}else{this.reusedSocket=!0;try{t(await this.agent.request(this[Ui],this[Ph],this[be]))}catch(i){this.emit("error",i)}}}getHeader(e){if(typeof e!="string")throw new Di("name","string",e);return this[be][e.toLowerCase()]}get headersSent(){return this[Tn]}removeHeader(e){if(typeof e!="string")throw new Di("name","string",e);if(this.headersSent)throw new Th("remove");delete this[be][e.toLowerCase()]}setHeader(e,t){if(this.headersSent)throw new Th("set");if(typeof e!="string"||!zb.test(e)&&!$b(e))throw new Gb("Header name",e);if(typeof t>"u")throw new Fb(t,e);if(Kb.test(t))throw new Wb("header content",e);this[be][e.toLowerCase()]=t}setNoDelay(){}setSocketKeepAlive(){}setTimeout(e,t){let i=()=>this._request.setTimeout(e,t);return this._request?i():this[Os].push(i),this}get maxHeadersCount(){if(!this.destroyed&&this._request)return this._request.session.localSettings.maxHeaderListSize}set maxHeadersCount(e){}};Ih.exports=qi});var xh=$((_0,Mh)=>{"use strict";var Jb=q("tls");Mh.exports=(s={},e=Jb.connect)=>new Promise((t,i)=>{let a=!1,c,u=async()=>{await g,c.off("timeout",p),c.off("error",i),s.resolveSocket?(t({alpnProtocol:c.alpnProtocol,socket:c,timeout:a}),a&&(await Promise.resolve(),c.emit("timeout"))):(c.destroy(),t({alpnProtocol:c.alpnProtocol,timeout:a}))},p=async()=>{a=!0,u()},g=(async()=>{try{c=await e(s,u),c.on("error",i),c.once("timeout",p)}catch(m){i(m)}})()})});var Lh=$((b0,Nh)=>{"use strict";var Yb=q("net");Nh.exports=s=>{let e=s.host,t=s.headers&&s.headers.host;return t&&(t.startsWith("[")?t.indexOf("]")===-1?e=t:e=t.slice(1,-1):e=t.split(":",1)[0]),Yb.isIP(e)?"":e}});var jh=$((v0,Hi)=>{"use strict";var Dh=q("http"),$i=q("https"),Qb=xh(),Xb=Pi(),Zb=Bi(),ev=Lh(),tv=Li(),Sn=new Xb({maxSize:100}),Ts=new Map,Uh=(s,e,t)=>{e._httpMessage={shouldKeepAlive:!0};let i=()=>{s.emit("free",e,t)};e.on("free",i);let a=()=>{s.removeSocket(e,t)};e.on("close",a);let c=()=>{s.removeSocket(e,t),e.off("close",a),e.off("free",i),e.off("agentRemove",c)};e.on("agentRemove",c),s.emit("free",e,t)},sv=async s=>{let e=`${s.host}:${s.port}:${s.ALPNProtocols.sort()}`;if(!Sn.has(e)){if(Ts.has(e))return(await Ts.get(e)).alpnProtocol;let{path:t,agent:i}=s;s.path=s.socketPath;let a=Qb(s);Ts.set(e,a);try{let{socket:c,alpnProtocol:u}=await a;if(Sn.set(e,u),s.path=t,u==="h2")c.destroy();else{let{globalAgent:p}=$i,g=$i.Agent.prototype.createConnection;i?i.createConnection===g?Uh(i,c,s):c.destroy():p.createConnection===g?Uh(p,c,s):c.destroy()}return Ts.delete(e),u}catch(c){throw Ts.delete(e),c}}return Sn.get(e)};Hi.exports=async(s,e,t)=>{if((typeof s=="string"||s instanceof URL)&&(s=tv(new URL(s))),typeof e=="function"&&(t=e,e=void 0),e={ALPNProtocols:["h2","http/1.1"],...s,...e,resolveSocket:!0},!Array.isArray(e.ALPNProtocols)||e.ALPNProtocols.length===0)throw new Error("The `ALPNProtocols` option must be an Array with at least one entry");e.protocol=e.protocol||"https:";let i=e.protocol==="https:";e.host=e.hostname||e.host||"localhost",e.session=e.tlsSession,e.servername=e.servername||ev(e),e.port=e.port||(i?443:80),e._defaultAgent=i?$i.globalAgent:Dh.globalAgent;let a=e.agent;if(a){if(a.addRequest)throw new Error("The `options.agent` object can contain only `http`, `https` or `http2` properties");e.agent=a[i?"https":"http"]}return i&&await sv(e)==="h2"?(a&&(e.agent=a.http2),new Zb(e,t)):Dh.request(e,t)};Hi.exports.protocolCache=Sn});var Bh=$((w0,qh)=>{"use strict";var nv=q("http2"),rv=Mi(),Gi=Bi(),iv=Ni(),ov=jh(),av=(s,e,t)=>new Gi(s,e,t),cv=(s,e,t)=>{let i=new Gi(s,e,t);return i.end(),i};qh.exports={...nv,ClientRequest:Gi,IncomingMessage:iv,...rv,request:av,get:cv,auto:ov}});var Wi=$(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});var $h=rt();Fi.default=s=>$h.default.nodeStream(s)&&$h.default.function_(s.getBoundary)});var Wh=$(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});var Gh=q("fs"),Fh=q("util"),Hh=rt(),lv=Wi(),uv=Fh.promisify(Gh.stat);Vi.default=async(s,e)=>{if(e&&"content-length"in e)return Number(e["content-length"]);if(!s)return 0;if(Hh.default.string(s))return Buffer.byteLength(s);if(Hh.default.buffer(s))return s.length;if(lv.default(s))return Fh.promisify(s.getLength.bind(s))();if(s instanceof Gh.ReadStream){let{size:t}=await uv(s.path);return t===0?void 0:t}}});var Ki=$(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});function hv(s,e,t){let i={};for(let a of t)i[a]=(...c)=>{e.emit(a,...c)},s.on(a,i[a]);return()=>{for(let a of t)s.off(a,i[a])}}zi.default=hv});var Vh=$(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.default=()=>{let s=[];return{once(e,t,i){e.once(t,i),s.push({origin:e,event:t,fn:i})},unhandleAll(){for(let e of s){let{origin:t,event:i,fn:a}=e;t.removeListener(i,a)}s.length=0}}}});var Kh=$(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.TimeoutError=void 0;var dv=q("net"),fv=Vh(),zh=Symbol("reentry"),pv=()=>{},An=class extends Error{constructor(e,t){super(`Timeout awaiting '${t}' for ${e}ms`),this.event=t,this.name="TimeoutError",this.code="ETIMEDOUT"}};Ss.TimeoutError=An;Ss.default=(s,e,t)=>{if(zh in s)return pv;s[zh]=!0;let i=[],{once:a,unhandleAll:c}=fv.default(),u=(w,C,T)=>{var S;let O=setTimeout(C,w,w,T);(S=O.unref)===null||S===void 0||S.call(O);let k=()=>{clearTimeout(O)};return i.push(k),k},{host:p,hostname:g}=t,m=(w,C)=>{s.destroy(new An(w,C))},_=()=>{for(let w of i)w();c()};if(s.once("error",w=>{if(_(),s.listenerCount("error")===0)throw w}),s.once("close",_),a(s,"response",w=>{a(w,"end",_)}),typeof e.request<"u"&&u(e.request,m,"request"),typeof e.socket<"u"){let w=()=>{m(e.socket,"socket")};s.setTimeout(e.socket,w),i.push(()=>{s.removeListener("timeout",w)})}return a(s,"socket",w=>{var C;let{socketPath:T}=s;if(w.connecting){let S=!!(T??dv.isIP((C=g??p)!==null&&C!==void 0?C:"")!==0);if(typeof e.lookup<"u"&&!S&&typeof w.address().address>"u"){let O=u(e.lookup,m,"lookup");a(w,"lookup",O)}if(typeof e.connect<"u"){let O=()=>u(e.connect,m,"connect");S?a(w,"connect",O()):a(w,"lookup",k=>{k===null&&a(w,"connect",O())})}typeof e.secureConnect<"u"&&t.protocol==="https:"&&a(w,"connect",()=>{let O=u(e.secureConnect,m,"secureConnect");a(w,"secureConnect",O)})}if(typeof e.send<"u"){let S=()=>u(e.send,m,"send");w.connecting?a(w,"connect",()=>{a(s,"upload-complete",S())}):a(s,"upload-complete",S())}}),typeof e.response<"u"&&a(s,"upload-complete",()=>{let w=u(e.response,m,"response");a(s,"response",w)}),_}});var Yh=$(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});var Jh=rt();Yi.default=s=>{s=s;let e={protocol:s.protocol,hostname:Jh.default.string(s.hostname)&&s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,host:s.host,hash:s.hash,search:s.search,pathname:s.pathname,href:s.href,path:`${s.pathname||""}${s.search||""}`};return Jh.default.string(s.port)&&s.port.length>0&&(e.port=Number(s.port)),(s.username||s.password)&&(e.auth=`${s.username||""}:${s.password||""}`),e}});var Qh=$(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});var gv=q("url"),mv=["protocol","host","hostname","port","pathname","search"];Qi.default=(s,e)=>{var t,i;if(e.path){if(e.pathname)throw new TypeError("Parameters `path` and `pathname` are mutually exclusive.");if(e.search)throw new TypeError("Parameters `path` and `search` are mutually exclusive.");if(e.searchParams)throw new TypeError("Parameters `path` and `searchParams` are mutually exclusive.")}if(e.search&&e.searchParams)throw new TypeError("Parameters `search` and `searchParams` are mutually exclusive.");if(!s){if(!e.protocol)throw new TypeError("No URL protocol specified");s=`${e.protocol}//${(i=(t=e.hostname)!==null&&t!==void 0?t:e.host)!==null&&i!==void 0?i:""}`}let a=new gv.URL(s);if(e.path){let c=e.path.indexOf("?");c===-1?e.pathname=e.path:(e.pathname=e.path.slice(0,c),e.search=e.path.slice(c+1)),delete e.path}for(let c of mv)e[c]&&(a[c]=e[c].toString());return a}});var Xh=$(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});var Xi=class{constructor(){this.weakMap=new WeakMap,this.map=new Map}set(e,t){typeof e=="object"?this.weakMap.set(e,t):this.map.set(e,t)}get(e){return typeof e=="object"?this.weakMap.get(e):this.map.get(e)}has(e){return typeof e=="object"?this.weakMap.has(e):this.map.has(e)}};Zi.default=Xi});var to=$(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});var yv=async s=>{let e=[],t=0;for await(let i of s)e.push(i),t+=Buffer.byteLength(i);return Buffer.isBuffer(e[0])?Buffer.concat(e,t):Buffer.from(e.join(""))};eo.default=yv});var ed=$(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.dnsLookupIpVersionToFamily=kt.isDnsLookupIpVersion=void 0;var Zh={auto:0,ipv4:4,ipv6:6};kt.isDnsLookupIpVersion=s=>s in Zh;kt.dnsLookupIpVersionToFamily=s=>{if(kt.isDnsLookupIpVersion(s))return Zh[s];throw new Error("Invalid DNS lookup IP version")}});var so=$(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.isResponseOk=void 0;Rn.isResponseOk=s=>{let{statusCode:e}=s,t=s.request.options.followRedirect?299:399;return e>=200&&e<=t||e===304}});var sd=$(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});var td=new Set;no.default=s=>{td.has(s)||(td.add(s),process.emitWarning(`Got: ${s}`,{type:"DeprecationWarning"}))}});var nd=$(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});var re=rt(),_v=(s,e)=>{if(re.default.null_(s.encoding))throw new TypeError("To get a Buffer, set `options.responseType` to `buffer` instead");re.assert.any([re.default.string,re.default.undefined],s.encoding),re.assert.any([re.default.boolean,re.default.undefined],s.resolveBodyOnly),re.assert.any([re.default.boolean,re.default.undefined],s.methodRewriting),re.assert.any([re.default.boolean,re.default.undefined],s.isStream),re.assert.any([re.default.string,re.default.undefined],s.responseType),s.responseType===void 0&&(s.responseType="text");let{retry:t}=s;if(e?s.retry={...e.retry}:s.retry={calculateDelay:i=>i.computedValue,limit:0,methods:[],statusCodes:[],errorCodes:[],maxRetryAfter:void 0},re.default.object(t)?(s.retry={...s.retry,...t},s.retry.methods=[...new Set(s.retry.methods.map(i=>i.toUpperCase()))],s.retry.statusCodes=[...new Set(s.retry.statusCodes)],s.retry.errorCodes=[...new Set(s.retry.errorCodes)]):re.default.number(t)&&(s.retry.limit=t),re.default.undefined(s.retry.maxRetryAfter)&&(s.retry.maxRetryAfter=Math.min(...[s.timeout.request,s.timeout.connect].filter(re.default.number))),re.default.object(s.pagination)){e&&(s.pagination={...e.pagination,...s.pagination});let{pagination:i}=s;if(!re.default.function_(i.transform))throw new Error("`options.pagination.transform` must be implemented");if(!re.default.function_(i.shouldContinue))throw new Error("`options.pagination.shouldContinue` must be implemented");if(!re.default.function_(i.filter))throw new TypeError("`options.pagination.filter` must be implemented");if(!re.default.function_(i.paginate))throw new Error("`options.pagination.paginate` must be implemented")}return s.responseType==="json"&&s.headers.accept===void 0&&(s.headers.accept="application/json"),s};ro.default=_v});var rd=$(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.retryAfterStatusCodes=void 0;As.retryAfterStatusCodes=new Set([413,429,503]);var bv=({attemptCount:s,retryOptions:e,error:t,retryAfter:i})=>{if(s>e.limit)return 0;let a=e.methods.includes(t.options.method),c=e.errorCodes.includes(t.code),u=t.response&&e.statusCodes.includes(t.response.statusCode);if(!a||!c&&!u)return 0;if(t.response){if(i)return e.maxRetryAfter===void 0||i>e.maxRetryAfter?0:i;if(t.response.statusCode===413)return 0}let p=Math.random()*100;return 2**(s-1)*1e3+p};As.default=bv});var Is=$(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.UnsupportedProtocolError=ee.ReadError=ee.TimeoutError=ee.UploadError=ee.CacheError=ee.HTTPError=ee.MaxRedirectsError=ee.RequestError=ee.setNonEnumerableProperties=ee.knownHookEvents=ee.withoutBody=ee.kIsNormalizedAlready=void 0;var id=q("util"),od=q("stream"),vv=q("fs"),dt=q("url"),ad=q("http"),io=q("http"),wv=q("https"),Cv=vu(),Ev=Su(),cd=ah(),kv=hh(),Ov=Bh(),Tv=kn(),M=rt(),Sv=Wh(),ld=Wi(),Av=Ki(),ud=Kh(),Rv=Yh(),hd=Qh(),Pv=Xh(),Iv=to(),dd=ed(),Mv=so(),ft=sd(),xv=nd(),Nv=rd(),oo,ge=Symbol("request"),Mn=Symbol("response"),Kt=Symbol("responseSize"),Jt=Symbol("downloadedSize"),Yt=Symbol("bodySize"),Qt=Symbol("uploadedSize"),Pn=Symbol("serverResponsesPiped"),fd=Symbol("unproxyEvents"),pd=Symbol("isFromCache"),ao=Symbol("cancelTimeouts"),gd=Symbol("startedReading"),Xt=Symbol("stopReading"),In=Symbol("triggerRead"),pt=Symbol("body"),Rs=Symbol("jobs"),md=Symbol("originalResponse"),yd=Symbol("retryTimeout");ee.kIsNormalizedAlready=Symbol("isNormalizedAlready");var Lv=M.default.string(process.versions.brotli);ee.withoutBody=new Set(["GET","HEAD"]);ee.knownHookEvents=["init","beforeRequest","beforeRedirect","beforeError","beforeRetry","afterResponse"];function Dv(s){for(let e in s){let t=s[e];if(!M.default.string(t)&&!M.default.number(t)&&!M.default.boolean(t)&&!M.default.null_(t)&&!M.default.undefined(t))throw new TypeError(`The \`searchParams\` value '${String(t)}' must be a string, number, boolean or null`)}}function Uv(s){return M.default.object(s)&&!("statusCode"in s)}var co=new Pv.default,jv=async s=>new Promise((e,t)=>{let i=a=>{t(a)};s.pending||e(),s.once("error",i),s.once("ready",()=>{s.off("error",i),e()})}),qv=new Set([300,301,302,303,304,307,308]),Bv=["context","body","json","form"];ee.setNonEnumerableProperties=(s,e)=>{let t={};for(let i of s)if(i)for(let a of Bv)a in i&&(t[a]={writable:!0,configurable:!0,enumerable:!1,value:i[a]});Object.defineProperties(e,t)};var le=class extends Error{constructor(e,t,i){var a,c;if(super(e),Error.captureStackTrace(this,this.constructor),this.name="RequestError",this.code=(a=t.code)!==null&&a!==void 0?a:"ERR_GOT_REQUEST_ERROR",i instanceof qn?(Object.defineProperty(this,"request",{enumerable:!1,value:i}),Object.defineProperty(this,"response",{enumerable:!1,value:i[Mn]}),Object.defineProperty(this,"options",{enumerable:!1,value:i.options})):Object.defineProperty(this,"options",{enumerable:!1,value:i}),this.timings=(c=this.request)===null||c===void 0?void 0:c.timings,M.default.string(t.stack)&&M.default.string(this.stack)){let u=this.stack.indexOf(this.message)+this.message.length,p=this.stack.slice(u).split(`
33
+ `+t)}function Ct(s,e,t,i,a,c){if(s.listenerCount("wsClientError")){let u=new Error(a);Error.captureStackTrace(u,Ct),s.emit("wsClientError",u,t,e)}else ws(t,i,a,c)}});var pn=$((GC,fu)=>{"use strict";var st=dn();st.createWebSocketStream=nu();st.Server=du();st.Receiver=Zr();st.Sender=si();st.WebSocket=st;st.WebSocketServer=st.Server;fu.exports=st});var rt=$((nt,gn)=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});var pu=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function u_(s){return pu.includes(s)}var h_=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Blob","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","FormData","URLSearchParams","HTMLElement",...pu];function d_(s){return h_.includes(s)}var f_=["null","undefined","string","number","bigint","boolean","symbol"];function p_(s){return f_.includes(s)}function Gt(s){return e=>typeof e===s}var{toString:gu}=Object.prototype,Cs=s=>{let e=gu.call(s).slice(8,-1);if(/HTML\w+Element/.test(e)&&v.domElement(s))return"HTMLElement";if(d_(e))return e},ne=s=>e=>Cs(e)===s;function v(s){if(s===null)return"null";switch(typeof s){case"undefined":return"undefined";case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"function":return"Function";case"bigint":return"bigint";case"symbol":return"symbol";default:}if(v.observable(s))return"Observable";if(v.array(s))return"Array";if(v.buffer(s))return"Buffer";let e=Cs(s);if(e)return e;if(s instanceof String||s instanceof Boolean||s instanceof Number)throw new TypeError("Please don't use object wrappers for primitive types");return"Object"}v.undefined=Gt("undefined");v.string=Gt("string");var g_=Gt("number");v.number=s=>g_(s)&&!v.nan(s);v.bigint=Gt("bigint");v.function_=Gt("function");v.null_=s=>s===null;v.class_=s=>v.function_(s)&&s.toString().startsWith("class ");v.boolean=s=>s===!0||s===!1;v.symbol=Gt("symbol");v.numericString=s=>v.string(s)&&!v.emptyStringOrWhitespace(s)&&!Number.isNaN(Number(s));v.array=(s,e)=>Array.isArray(s)?v.function_(e)?s.every(e):!0:!1;v.buffer=s=>{var e,t,i,a;return(a=(i=(t=(e=s)===null||e===void 0?void 0:e.constructor)===null||t===void 0?void 0:t.isBuffer)===null||i===void 0?void 0:i.call(t,s))!==null&&a!==void 0?a:!1};v.blob=s=>ne("Blob")(s);v.nullOrUndefined=s=>v.null_(s)||v.undefined(s);v.object=s=>!v.null_(s)&&(typeof s=="object"||v.function_(s));v.iterable=s=>{var e;return v.function_((e=s)===null||e===void 0?void 0:e[Symbol.iterator])};v.asyncIterable=s=>{var e;return v.function_((e=s)===null||e===void 0?void 0:e[Symbol.asyncIterator])};v.generator=s=>{var e,t;return v.iterable(s)&&v.function_((e=s)===null||e===void 0?void 0:e.next)&&v.function_((t=s)===null||t===void 0?void 0:t.throw)};v.asyncGenerator=s=>v.asyncIterable(s)&&v.function_(s.next)&&v.function_(s.throw);v.nativePromise=s=>ne("Promise")(s);var m_=s=>{var e,t;return v.function_((e=s)===null||e===void 0?void 0:e.then)&&v.function_((t=s)===null||t===void 0?void 0:t.catch)};v.promise=s=>v.nativePromise(s)||m_(s);v.generatorFunction=ne("GeneratorFunction");v.asyncGeneratorFunction=s=>Cs(s)==="AsyncGeneratorFunction";v.asyncFunction=s=>Cs(s)==="AsyncFunction";v.boundFunction=s=>v.function_(s)&&!s.hasOwnProperty("prototype");v.regExp=ne("RegExp");v.date=ne("Date");v.error=ne("Error");v.map=s=>ne("Map")(s);v.set=s=>ne("Set")(s);v.weakMap=s=>ne("WeakMap")(s);v.weakSet=s=>ne("WeakSet")(s);v.int8Array=ne("Int8Array");v.uint8Array=ne("Uint8Array");v.uint8ClampedArray=ne("Uint8ClampedArray");v.int16Array=ne("Int16Array");v.uint16Array=ne("Uint16Array");v.int32Array=ne("Int32Array");v.uint32Array=ne("Uint32Array");v.float32Array=ne("Float32Array");v.float64Array=ne("Float64Array");v.bigInt64Array=ne("BigInt64Array");v.bigUint64Array=ne("BigUint64Array");v.arrayBuffer=ne("ArrayBuffer");v.sharedArrayBuffer=ne("SharedArrayBuffer");v.dataView=ne("DataView");v.enumCase=(s,e)=>Object.values(e).includes(s);v.directInstanceOf=(s,e)=>Object.getPrototypeOf(s)===e.prototype;v.urlInstance=s=>ne("URL")(s);v.urlString=s=>{if(!v.string(s))return!1;try{return new URL(s),!0}catch{return!1}};v.truthy=s=>!!s;v.falsy=s=>!s;v.nan=s=>Number.isNaN(s);v.primitive=s=>v.null_(s)||p_(typeof s);v.integer=s=>Number.isInteger(s);v.safeInteger=s=>Number.isSafeInteger(s);v.plainObject=s=>{if(gu.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||e===Object.getPrototypeOf({})};v.typedArray=s=>u_(Cs(s));var y_=s=>v.safeInteger(s)&&s>=0;v.arrayLike=s=>!v.nullOrUndefined(s)&&!v.function_(s)&&y_(s.length);v.inRange=(s,e)=>{if(v.number(e))return s>=Math.min(0,e)&&s<=Math.max(e,0);if(v.array(e)&&e.length===2)return s>=Math.min(...e)&&s<=Math.max(...e);throw new TypeError(`Invalid range: ${JSON.stringify(e)}`)};var __=1,b_=["innerHTML","ownerDocument","style","attributes","nodeValue"];v.domElement=s=>v.object(s)&&s.nodeType===__&&v.string(s.nodeName)&&!v.plainObject(s)&&b_.every(e=>e in s);v.observable=s=>{var e,t,i,a;return s?s===((t=(e=s)[Symbol.observable])===null||t===void 0?void 0:t.call(e))||s===((a=(i=s)["@@observable"])===null||a===void 0?void 0:a.call(i)):!1};v.nodeStream=s=>v.object(s)&&v.function_(s.pipe)&&!v.observable(s);v.infinite=s=>s===1/0||s===-1/0;var mu=s=>e=>v.integer(e)&&Math.abs(e%2)===s;v.evenInteger=mu(0);v.oddInteger=mu(1);v.emptyArray=s=>v.array(s)&&s.length===0;v.nonEmptyArray=s=>v.array(s)&&s.length>0;v.emptyString=s=>v.string(s)&&s.length===0;var v_=s=>v.string(s)&&!/\S/.test(s);v.emptyStringOrWhitespace=s=>v.emptyString(s)||v_(s);v.nonEmptyString=s=>v.string(s)&&s.length>0;v.nonEmptyStringAndNotWhitespace=s=>v.string(s)&&!v.emptyStringOrWhitespace(s);v.emptyObject=s=>v.object(s)&&!v.map(s)&&!v.set(s)&&Object.keys(s).length===0;v.nonEmptyObject=s=>v.object(s)&&!v.map(s)&&!v.set(s)&&Object.keys(s).length>0;v.emptySet=s=>v.set(s)&&s.size===0;v.nonEmptySet=s=>v.set(s)&&s.size>0;v.emptyMap=s=>v.map(s)&&s.size===0;v.nonEmptyMap=s=>v.map(s)&&s.size>0;v.propertyKey=s=>v.any([v.string,v.number,v.symbol],s);v.formData=s=>ne("FormData")(s);v.urlSearchParams=s=>ne("URLSearchParams")(s);var yu=(s,e,t)=>{if(!v.function_(e))throw new TypeError(`Invalid predicate: ${JSON.stringify(e)}`);if(t.length===0)throw new TypeError("Invalid number of values");return s.call(t,e)};v.any=(s,...e)=>(v.array(s)?s:[s]).some(i=>yu(Array.prototype.some,i,e));v.all=(s,...e)=>yu(Array.prototype.every,s,e);var B=(s,e,t,i={})=>{if(!s){let{multipleValues:a}=i,c=a?`received values of types ${[...new Set(t.map(u=>`\`${v(u)}\``))].join(", ")}`:`received value of type \`${v(t)}\``;throw new TypeError(`Expected value which is \`${e}\`, ${c}.`)}};nt.assert={undefined:s=>B(v.undefined(s),"undefined",s),string:s=>B(v.string(s),"string",s),number:s=>B(v.number(s),"number",s),bigint:s=>B(v.bigint(s),"bigint",s),function_:s=>B(v.function_(s),"Function",s),null_:s=>B(v.null_(s),"null",s),class_:s=>B(v.class_(s),"Class",s),boolean:s=>B(v.boolean(s),"boolean",s),symbol:s=>B(v.symbol(s),"symbol",s),numericString:s=>B(v.numericString(s),"string with a number",s),array:(s,e)=>{B(v.array(s),"Array",s),e&&s.forEach(e)},buffer:s=>B(v.buffer(s),"Buffer",s),blob:s=>B(v.blob(s),"Blob",s),nullOrUndefined:s=>B(v.nullOrUndefined(s),"null or undefined",s),object:s=>B(v.object(s),"Object",s),iterable:s=>B(v.iterable(s),"Iterable",s),asyncIterable:s=>B(v.asyncIterable(s),"AsyncIterable",s),generator:s=>B(v.generator(s),"Generator",s),asyncGenerator:s=>B(v.asyncGenerator(s),"AsyncGenerator",s),nativePromise:s=>B(v.nativePromise(s),"native Promise",s),promise:s=>B(v.promise(s),"Promise",s),generatorFunction:s=>B(v.generatorFunction(s),"GeneratorFunction",s),asyncGeneratorFunction:s=>B(v.asyncGeneratorFunction(s),"AsyncGeneratorFunction",s),asyncFunction:s=>B(v.asyncFunction(s),"AsyncFunction",s),boundFunction:s=>B(v.boundFunction(s),"Function",s),regExp:s=>B(v.regExp(s),"RegExp",s),date:s=>B(v.date(s),"Date",s),error:s=>B(v.error(s),"Error",s),map:s=>B(v.map(s),"Map",s),set:s=>B(v.set(s),"Set",s),weakMap:s=>B(v.weakMap(s),"WeakMap",s),weakSet:s=>B(v.weakSet(s),"WeakSet",s),int8Array:s=>B(v.int8Array(s),"Int8Array",s),uint8Array:s=>B(v.uint8Array(s),"Uint8Array",s),uint8ClampedArray:s=>B(v.uint8ClampedArray(s),"Uint8ClampedArray",s),int16Array:s=>B(v.int16Array(s),"Int16Array",s),uint16Array:s=>B(v.uint16Array(s),"Uint16Array",s),int32Array:s=>B(v.int32Array(s),"Int32Array",s),uint32Array:s=>B(v.uint32Array(s),"Uint32Array",s),float32Array:s=>B(v.float32Array(s),"Float32Array",s),float64Array:s=>B(v.float64Array(s),"Float64Array",s),bigInt64Array:s=>B(v.bigInt64Array(s),"BigInt64Array",s),bigUint64Array:s=>B(v.bigUint64Array(s),"BigUint64Array",s),arrayBuffer:s=>B(v.arrayBuffer(s),"ArrayBuffer",s),sharedArrayBuffer:s=>B(v.sharedArrayBuffer(s),"SharedArrayBuffer",s),dataView:s=>B(v.dataView(s),"DataView",s),enumCase:(s,e)=>B(v.enumCase(s,e),"EnumCase",s),urlInstance:s=>B(v.urlInstance(s),"URL",s),urlString:s=>B(v.urlString(s),"string with a URL",s),truthy:s=>B(v.truthy(s),"truthy",s),falsy:s=>B(v.falsy(s),"falsy",s),nan:s=>B(v.nan(s),"NaN",s),primitive:s=>B(v.primitive(s),"primitive",s),integer:s=>B(v.integer(s),"integer",s),safeInteger:s=>B(v.safeInteger(s),"integer",s),plainObject:s=>B(v.plainObject(s),"plain object",s),typedArray:s=>B(v.typedArray(s),"TypedArray",s),arrayLike:s=>B(v.arrayLike(s),"array-like",s),domElement:s=>B(v.domElement(s),"HTMLElement",s),observable:s=>B(v.observable(s),"Observable",s),nodeStream:s=>B(v.nodeStream(s),"Node.js Stream",s),infinite:s=>B(v.infinite(s),"infinite number",s),emptyArray:s=>B(v.emptyArray(s),"empty array",s),nonEmptyArray:s=>B(v.nonEmptyArray(s),"non-empty array",s),emptyString:s=>B(v.emptyString(s),"empty string",s),emptyStringOrWhitespace:s=>B(v.emptyStringOrWhitespace(s),"empty string or whitespace",s),nonEmptyString:s=>B(v.nonEmptyString(s),"non-empty string",s),nonEmptyStringAndNotWhitespace:s=>B(v.nonEmptyStringAndNotWhitespace(s),"non-empty string and not whitespace",s),emptyObject:s=>B(v.emptyObject(s),"empty object",s),nonEmptyObject:s=>B(v.nonEmptyObject(s),"non-empty object",s),emptySet:s=>B(v.emptySet(s),"empty set",s),nonEmptySet:s=>B(v.nonEmptySet(s),"non-empty set",s),emptyMap:s=>B(v.emptyMap(s),"empty map",s),nonEmptyMap:s=>B(v.nonEmptyMap(s),"non-empty map",s),propertyKey:s=>B(v.propertyKey(s),"PropertyKey",s),formData:s=>B(v.formData(s),"FormData",s),urlSearchParams:s=>B(v.urlSearchParams(s),"URLSearchParams",s),evenInteger:s=>B(v.evenInteger(s),"even integer",s),oddInteger:s=>B(v.oddInteger(s),"odd integer",s),directInstanceOf:(s,e)=>B(v.directInstanceOf(s,e),"T",s),inRange:(s,e)=>B(v.inRange(s,e),"in range",s),any:(s,...e)=>B(v.any(s,...e),"predicate returns truthy for any value",e,{multipleValues:!0}),all:(s,...e)=>B(v.all(s,...e),"predicate returns truthy for all values",e,{multipleValues:!0})};Object.defineProperties(v,{class:{value:v.class_},function:{value:v.function_},null:{value:v.null_}});Object.defineProperties(nt.assert,{class:{value:nt.assert.class_},function:{value:nt.assert.function_},null:{value:nt.assert.null_}});nt.default=v;gn.exports=v;gn.exports.default=v;gn.exports.assert=nt.assert});var _u=$((FC,ui)=>{"use strict";var mn=class extends Error{constructor(e){super(e||"Promise was canceled"),this.name="CancelError"}get isCanceled(){return!0}},yn=class s{static fn(e){return(...t)=>new s((i,a,c)=>{t.push(c),e(...t).then(i,a)})}constructor(e){this._cancelHandlers=[],this._isPending=!0,this._isCanceled=!1,this._rejectOnCancel=!0,this._promise=new Promise((t,i)=>{this._reject=i;let a=p=>{(!this._isCanceled||!u.shouldReject)&&(this._isPending=!1,t(p))},c=p=>{this._isPending=!1,i(p)},u=p=>{if(!this._isPending)throw new Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(p)};return Object.defineProperties(u,{shouldReject:{get:()=>this._rejectOnCancel,set:p=>{this._rejectOnCancel=p}}}),e(a,c,u)})}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(e){if(!(!this._isPending||this._isCanceled)){if(this._isCanceled=!0,this._cancelHandlers.length>0)try{for(let t of this._cancelHandlers)t()}catch(t){this._reject(t);return}this._rejectOnCancel&&this._reject(new mn(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(yn.prototype,Promise.prototype);ui.exports=yn;ui.exports.CancelError=mn});var bu=$((di,fi)=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});function w_(s){return s.encrypted}var hi=(s,e)=>{let t;typeof e=="function"?t={connect:e}:t=e;let i=typeof t.connect=="function",a=typeof t.secureConnect=="function",c=typeof t.close=="function",u=()=>{i&&t.connect(),w_(s)&&a&&(s.authorized?t.secureConnect():s.authorizationError||s.once("secureConnect",t.secureConnect)),c&&s.once("close",t.close)};s.writable&&!s.connecting?u():s.connecting?s.once("connect",u):s.destroyed&&c&&t.close(s._hadError)};di.default=hi;fi.exports=hi;fi.exports.default=hi});var vu=$((gi,mi)=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});var C_=bu(),E_=q("util"),k_=Number(process.versions.node.split(".")[0]),pi=s=>{if(s.timings)return s.timings;let e={start:Date.now(),socket:void 0,lookup:void 0,connect:void 0,secureConnect:void 0,upload:void 0,response:void 0,end:void 0,error:void 0,abort:void 0,phases:{wait:void 0,dns:void 0,tcp:void 0,tls:void 0,request:void 0,firstByte:void 0,download:void 0,total:void 0}};s.timings=e;let t=p=>{let g=p.emit.bind(p);p.emit=(m,..._)=>(m==="error"&&(e.error=Date.now(),e.phases.total=e.error-e.start,p.emit=g),g(m,..._))};t(s);let i=()=>{e.abort=Date.now(),(!e.response||k_>=13)&&(e.phases.total=Date.now()-e.start)};s.prependOnceListener("abort",i);let a=p=>{if(e.socket=Date.now(),e.phases.wait=e.socket-e.start,E_.types.isProxy(p))return;let g=()=>{e.lookup=Date.now(),e.phases.dns=e.lookup-e.socket};p.prependOnceListener("lookup",g),C_.default(p,{connect:()=>{e.connect=Date.now(),e.lookup===void 0&&(p.removeListener("lookup",g),e.lookup=e.connect,e.phases.dns=e.lookup-e.socket),e.phases.tcp=e.connect-e.lookup},secureConnect:()=>{e.secureConnect=Date.now(),e.phases.tls=e.secureConnect-e.connect}})};s.socket?a(s.socket):s.prependOnceListener("socket",a);let c=()=>{var p;e.upload=Date.now(),e.phases.request=e.upload-((p=e.secureConnect)!==null&&p!==void 0?p:e.connect)};return(typeof s.writableFinished=="boolean"?s.writableFinished:s.finished&&s.outputSize===0&&(!s.socket||s.socket.writableLength===0))?c():s.prependOnceListener("finish",c),s.prependOnceListener("response",p=>{e.response=Date.now(),e.phases.firstByte=e.response-e.upload,p.timings=e,t(p),p.prependOnceListener("end",()=>{e.end=Date.now(),e.phases.download=e.end-e.response,e.phases.total=e.end-e.start}),p.prependOnceListener("aborted",i)}),e};gi.default=pi;mi.exports=pi;mi.exports.default=pi});var Su=$((WC,bi)=>{"use strict";var{V4MAPPED:O_,ADDRCONFIG:T_,ALL:Tu,promises:{Resolver:wu},lookup:S_}=q("dns"),{promisify:yi}=q("util"),A_=q("os"),Ft=Symbol("cacheableLookupCreateConnection"),_i=Symbol("cacheableLookupInstance"),Cu=Symbol("expires"),R_=typeof Tu=="number",Eu=s=>{if(!(s&&typeof s.createConnection=="function"))throw new Error("Expected an Agent instance as the first argument")},P_=s=>{for(let e of s)e.family!==6&&(e.address=`::ffff:${e.address}`,e.family=6)},ku=()=>{let s=!1,e=!1;for(let t of Object.values(A_.networkInterfaces()))for(let i of t)if(!i.internal&&(i.family==="IPv6"?e=!0:s=!0,s&&e))return{has4:s,has6:e};return{has4:s,has6:e}},I_=s=>Symbol.iterator in s,Ou={ttl:!0},M_={all:!0},_n=class{constructor({cache:e=new Map,maxTtl:t=1/0,fallbackDuration:i=3600,errorTtl:a=.15,resolver:c=new wu,lookup:u=S_}={}){if(this.maxTtl=t,this.errorTtl=a,this._cache=e,this._resolver=c,this._dnsLookup=yi(u),this._resolver instanceof wu?(this._resolve4=this._resolver.resolve4.bind(this._resolver),this._resolve6=this._resolver.resolve6.bind(this._resolver)):(this._resolve4=yi(this._resolver.resolve4.bind(this._resolver)),this._resolve6=yi(this._resolver.resolve6.bind(this._resolver))),this._iface=ku(),this._pending={},this._nextRemovalTime=!1,this._hostnamesToFallback=new Set,i<1)this._fallback=!1;else{this._fallback=!0;let p=setInterval(()=>{this._hostnamesToFallback.clear()},i*1e3);p.unref&&p.unref()}this.lookup=this.lookup.bind(this),this.lookupAsync=this.lookupAsync.bind(this)}set servers(e){this.clear(),this._resolver.setServers(e)}get servers(){return this._resolver.getServers()}lookup(e,t,i){if(typeof t=="function"?(i=t,t={}):typeof t=="number"&&(t={family:t}),!i)throw new Error("Callback must be a function.");this.lookupAsync(e,t).then(a=>{t.all?i(null,a):i(null,a.address,a.family,a.expires,a.ttl)},i)}async lookupAsync(e,t={}){typeof t=="number"&&(t={family:t});let i=await this.query(e);if(t.family===6){let a=i.filter(c=>c.family===6);t.hints&O_&&(R_&&t.hints&Tu||a.length===0)?P_(i):i=a}else t.family===4&&(i=i.filter(a=>a.family===4));if(t.hints&T_){let{_iface:a}=this;i=i.filter(c=>c.family===6?a.has6:a.has4)}if(i.length===0){let a=new Error(`cacheableLookup ENOTFOUND ${e}`);throw a.code="ENOTFOUND",a.hostname=e,a}return t.all?i:i[0]}async query(e){let t=await this._cache.get(e);if(!t){let i=this._pending[e];if(i)t=await i;else{let a=this.queryAndCache(e);this._pending[e]=a;try{t=await a}finally{delete this._pending[e]}}}return t=t.map(i=>({...i})),t}async _resolve(e){let t=async m=>{try{return await m}catch(_){if(_.code==="ENODATA"||_.code==="ENOTFOUND")return[];throw _}},[i,a]=await Promise.all([this._resolve4(e,Ou),this._resolve6(e,Ou)].map(m=>t(m))),c=0,u=0,p=0,g=Date.now();for(let m of i)m.family=4,m.expires=g+m.ttl*1e3,c=Math.max(c,m.ttl);for(let m of a)m.family=6,m.expires=g+m.ttl*1e3,u=Math.max(u,m.ttl);return i.length>0?a.length>0?p=Math.min(c,u):p=c:p=u,{entries:[...i,...a],cacheTtl:p}}async _lookup(e){try{return{entries:await this._dnsLookup(e,{all:!0}),cacheTtl:0}}catch{return{entries:[],cacheTtl:0}}}async _set(e,t,i){if(this.maxTtl>0&&i>0){i=Math.min(i,this.maxTtl)*1e3,t[Cu]=Date.now()+i;try{await this._cache.set(e,t,i)}catch(a){this.lookupAsync=async()=>{let c=new Error("Cache Error. Please recreate the CacheableLookup instance.");throw c.cause=a,c}}I_(this._cache)&&this._tick(i)}}async queryAndCache(e){if(this._hostnamesToFallback.has(e))return this._dnsLookup(e,M_);let t=await this._resolve(e);t.entries.length===0&&this._fallback&&(t=await this._lookup(e),t.entries.length!==0&&this._hostnamesToFallback.add(e));let i=t.entries.length===0?this.errorTtl:t.cacheTtl;return await this._set(e,t.entries,i),t.entries}_tick(e){let t=this._nextRemovalTime;(!t||e<t)&&(clearTimeout(this._removalTimeout),this._nextRemovalTime=e,this._removalTimeout=setTimeout(()=>{this._nextRemovalTime=!1;let i=1/0,a=Date.now();for(let[c,u]of this._cache){let p=u[Cu];a>=p?this._cache.delete(c):p<i&&(i=p)}i!==1/0&&this._tick(i-a)},e),this._removalTimeout.unref&&this._removalTimeout.unref())}install(e){if(Eu(e),Ft in e)throw new Error("CacheableLookup has been already installed");e[Ft]=e.createConnection,e[_i]=this,e.createConnection=(t,i)=>("lookup"in t||(t.lookup=this.lookup),e[Ft](t,i))}uninstall(e){if(Eu(e),e[Ft]){if(e[_i]!==this)throw new Error("The agent is not owned by this CacheableLookup instance");e.createConnection=e[Ft],delete e[Ft],delete e[_i]}}updateInterfaceInfo(){let{_iface:e}=this;this._iface=ku(),(e.has4&&!this._iface.has4||e.has6&&!this._iface.has6)&&this._cache.clear()}clear(e){if(e){this._cache.delete(e);return}this._cache.clear()}};bi.exports=_n;bi.exports.default=_n});var Pu=$((VC,Ru)=>{"use strict";var x_="text/plain",N_="us-ascii",Au=(s,e)=>e.some(t=>t instanceof RegExp?t.test(s):t===s),L_=(s,{stripHash:e})=>{let t=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(s);if(!t)throw new Error(`Invalid URL: ${s}`);let{type:i,data:a,hash:c}=t.groups,u=i.split(";");c=e?"":c;let p=!1;u[u.length-1]==="base64"&&(u.pop(),p=!0);let g=(u.shift()||"").toLowerCase(),_=[...u.map(w=>{let[C,T=""]=w.split("=").map(S=>S.trim());return C==="charset"&&(T=T.toLowerCase(),T===N_)?"":`${C}${T?`=${T}`:""}`}).filter(Boolean)];return p&&_.push("base64"),(_.length!==0||g&&g!==x_)&&_.unshift(g),`data:${_.join(";")},${p?a.trim():a}${c?`#${c}`:""}`},D_=(s,e)=>{if(e={defaultProtocol:"http:",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,sortQueryParameters:!0,...e},s=s.trim(),/^data:/i.test(s))return L_(s,e);if(/^view-source:/i.test(s))throw new Error("`view-source:` is not supported as it is a non-standard protocol");let t=s.startsWith("//");!t&&/^\.*\//.test(s)||(s=s.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,e.defaultProtocol));let a=new URL(s);if(e.forceHttp&&e.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(e.forceHttp&&a.protocol==="https:"&&(a.protocol="http:"),e.forceHttps&&a.protocol==="http:"&&(a.protocol="https:"),e.stripAuthentication&&(a.username="",a.password=""),e.stripHash?a.hash="":e.stripTextFragment&&(a.hash=a.hash.replace(/#?:~:text.*?$/i,"")),a.pathname&&(a.pathname=a.pathname.replace(/(?<!\b(?:[a-z][a-z\d+\-.]{1,50}:))\/{2,}/g,"/")),a.pathname)try{a.pathname=decodeURI(a.pathname)}catch{}if(e.removeDirectoryIndex===!0&&(e.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(e.removeDirectoryIndex)&&e.removeDirectoryIndex.length>0){let u=a.pathname.split("/"),p=u[u.length-1];Au(p,e.removeDirectoryIndex)&&(u=u.slice(0,u.length-1),a.pathname=u.slice(1).join("/")+"/")}if(a.hostname&&(a.hostname=a.hostname.replace(/\.$/,""),e.stripWWW&&/^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(a.hostname)&&(a.hostname=a.hostname.replace(/^www\./,""))),Array.isArray(e.removeQueryParameters))for(let u of[...a.searchParams.keys()])Au(u,e.removeQueryParameters)&&a.searchParams.delete(u);e.removeQueryParameters===!0&&(a.search=""),e.sortQueryParameters&&a.searchParams.sort(),e.removeTrailingSlash&&(a.pathname=a.pathname.replace(/\/$/,""));let c=s;return s=a.toString(),!e.removeSingleSlash&&a.pathname==="/"&&!c.endsWith("/")&&a.hash===""&&(s=s.replace(/\/$/,"")),(e.removeTrailingSlash||a.pathname==="/")&&a.hash===""&&e.removeSingleSlash&&(s=s.replace(/\/$/,"")),t&&!e.normalizeProtocol&&(s=s.replace(/^http:\/\//,"//")),e.stripProtocol&&(s=s.replace(/^(?:https?:)?\/\//,"")),s};Ru.exports=D_});var xu=$((zC,Mu)=>{Mu.exports=Iu;function Iu(s,e){if(s&&e)return Iu(s)(e);if(typeof s!="function")throw new TypeError("need wrapper function");return Object.keys(s).forEach(function(i){t[i]=s[i]}),t;function t(){for(var i=new Array(arguments.length),a=0;a<i.length;a++)i[a]=arguments[a];var c=s.apply(this,i),u=i[i.length-1];return typeof c=="function"&&c!==u&&Object.keys(u).forEach(function(p){c[p]=u[p]}),c}}});var wi=$((KC,vi)=>{var Nu=xu();vi.exports=Nu(bn);vi.exports.strict=Nu(Lu);bn.proto=bn(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return bn(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return Lu(this)},configurable:!0})});function bn(s){var e=function(){return e.called?e.value:(e.called=!0,e.value=s.apply(this,arguments))};return e.called=!1,e}function Lu(s){var e=function(){if(e.called)throw new Error(e.onceError);return e.called=!0,e.value=s.apply(this,arguments)},t=s.name||"Function wrapped with `once`";return e.onceError=t+" shouldn't be called more than once",e.called=!1,e}});var ju=$((JC,Uu)=>{var U_=wi(),j_=function(){},q_=global.Bare?queueMicrotask:process.nextTick.bind(process),B_=function(s){return s.setHeader&&typeof s.abort=="function"},$_=function(s){return s.stdio&&Array.isArray(s.stdio)&&s.stdio.length===3},Du=function(s,e,t){if(typeof e=="function")return Du(s,null,e);e||(e={}),t=U_(t||j_);var i=s._writableState,a=s._readableState,c=e.readable||e.readable!==!1&&s.readable,u=e.writable||e.writable!==!1&&s.writable,p=!1,g=function(){s.writable||m()},m=function(){u=!1,c||t.call(s)},_=function(){c=!1,u||t.call(s)},w=function(k){t.call(s,k?new Error("exited with error code: "+k):null)},C=function(k){t.call(s,k)},T=function(){q_(S)},S=function(){if(!p){if(c&&!(a&&a.ended&&!a.destroyed))return t.call(s,new Error("premature close"));if(u&&!(i&&i.ended&&!i.destroyed))return t.call(s,new Error("premature close"))}},O=function(){s.req.on("finish",m)};return B_(s)?(s.on("complete",m),s.on("abort",T),s.req?O():s.on("request",O)):u&&!i&&(s.on("end",g),s.on("close",g)),$_(s)&&s.on("exit",w),s.on("end",_),s.on("finish",m),e.error!==!1&&s.on("error",C),s.on("close",T),function(){p=!0,s.removeListener("complete",m),s.removeListener("abort",T),s.removeListener("request",O),s.req&&s.req.removeListener("finish",m),s.removeListener("end",g),s.removeListener("close",g),s.removeListener("finish",m),s.removeListener("exit",w),s.removeListener("end",_),s.removeListener("error",C),s.removeListener("close",T)}};Uu.exports=Du});var $u=$((YC,Bu)=>{var H_=wi(),G_=ju(),vn;try{vn=q("fs")}catch{}var Es=function(){},F_=typeof process>"u"?!1:/^v?\.0/.test(process.version),wn=function(s){return typeof s=="function"},W_=function(s){return!F_||!vn?!1:(s instanceof(vn.ReadStream||Es)||s instanceof(vn.WriteStream||Es))&&wn(s.close)},V_=function(s){return s.setHeader&&wn(s.abort)},z_=function(s,e,t,i){i=H_(i);var a=!1;s.on("close",function(){a=!0}),G_(s,{readable:e,writable:t},function(u){if(u)return i(u);a=!0,i()});var c=!1;return function(u){if(!a&&!c){if(c=!0,W_(s))return s.close(Es);if(V_(s))return s.abort();if(wn(s.destroy))return s.destroy();i(u||new Error("stream was destroyed"))}}},qu=function(s){s()},K_=function(s,e){return s.pipe(e)},J_=function(){var s=Array.prototype.slice.call(arguments),e=wn(s[s.length-1]||Es)&&s.pop()||Es;if(Array.isArray(s[0])&&(s=s[0]),s.length<2)throw new Error("pump requires two streams per minimum");var t,i=s.map(function(a,c){var u=c<s.length-1,p=c>0;return z_(a,u,p,function(g){t||(t=g),g&&i.forEach(qu),!u&&(i.forEach(qu),e(t))})});return s.reduce(K_)};Bu.exports=J_});var Gu=$((QC,Hu)=>{"use strict";var{PassThrough:Y_}=q("stream");Hu.exports=s=>{s={...s};let{array:e}=s,{encoding:t}=s,i=t==="buffer",a=!1;e?a=!(t||i):t=t||"utf8",i&&(t=null);let c=new Y_({objectMode:a});t&&c.setEncoding(t);let u=0,p=[];return c.on("data",g=>{p.push(g),a?u=p.length:u+=g.length}),c.getBufferedValue=()=>e?p:i?Buffer.concat(p,u):p.join(""),c.getBufferedLength=()=>u,c}});var Fu=$((XC,Wt)=>{"use strict";var{constants:Q_}=q("buffer"),X_=$u(),Z_=Gu(),Cn=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function En(s,e){if(!s)return Promise.reject(new Error("Expected a stream"));e={maxBuffer:1/0,...e};let{maxBuffer:t}=e,i;return await new Promise((a,c)=>{let u=p=>{p&&i.getBufferedLength()<=Q_.MAX_LENGTH&&(p.bufferedData=i.getBufferedValue()),c(p)};i=X_(s,Z_(e),p=>{if(p){u(p);return}a()}),i.on("data",()=>{i.getBufferedLength()>t&&u(new Cn)})}),i.getBufferedValue()}Wt.exports=En;Wt.exports.default=En;Wt.exports.buffer=(s,e)=>En(s,{...e,encoding:"buffer"});Wt.exports.array=(s,e)=>En(s,{...e,array:!0});Wt.exports.MaxBufferError=Cn});var Vu=$((e0,Wu)=>{"use strict";var eb=new Set([200,203,204,206,300,301,308,404,405,410,414,501]),tb=new Set([200,203,204,300,301,302,303,307,308,404,405,410,414,501]),sb=new Set([500,502,503,504]),nb={date:!0,connection:!0,"keep-alive":!0,"proxy-authenticate":!0,"proxy-authorization":!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0},rb={"content-length":!0,"content-encoding":!0,"transfer-encoding":!0,"content-range":!0};function it(s){let e=parseInt(s,10);return isFinite(e)?e:0}function ib(s){return s?sb.has(s.status):!0}function Ci(s){let e={};if(!s)return e;let t=s.trim().split(/,/);for(let i of t){let[a,c]=i.split(/=/,2);e[a.trim()]=c===void 0?!0:c.trim().replace(/^"|"$/g,"")}return e}function ob(s){let e=[];for(let t in s){let i=s[t];e.push(i===!0?t:t+"="+i)}if(e.length)return e.join(", ")}Wu.exports=class{constructor(e,t,{shared:i,cacheHeuristic:a,immutableMinTimeToLive:c,ignoreCargoCult:u,_fromObject:p}={}){if(p){this._fromObject(p);return}if(!t||!t.headers)throw Error("Response headers missing");this._assertRequestHasHeaders(e),this._responseTime=this.now(),this._isShared=i!==!1,this._ignoreCargoCult=!!u,this._cacheHeuristic=a!==void 0?a:.1,this._immutableMinTtl=c!==void 0?c:24*3600*1e3,this._status="status"in t?t.status:200,this._resHeaders=t.headers,this._rescc=Ci(t.headers["cache-control"]),this._method="method"in e?e.method:"GET",this._url=e.url,this._host=e.headers.host,this._noAuthorization=!e.headers.authorization,this._reqHeaders=t.headers.vary?e.headers:null,this._reqcc=Ci(e.headers["cache-control"]),this._ignoreCargoCult&&"pre-check"in this._rescc&&"post-check"in this._rescc&&(delete this._rescc["pre-check"],delete this._rescc["post-check"],delete this._rescc["no-cache"],delete this._rescc["no-store"],delete this._rescc["must-revalidate"],this._resHeaders=Object.assign({},this._resHeaders,{"cache-control":ob(this._rescc)}),delete this._resHeaders.expires,delete this._resHeaders.pragma),t.headers["cache-control"]==null&&/no-cache/.test(t.headers.pragma)&&(this._rescc["no-cache"]=!0)}now(){return Date.now()}storable(){return!!(!this._reqcc["no-store"]&&(this._method==="GET"||this._method==="HEAD"||this._method==="POST"&&this._hasExplicitExpiration())&&tb.has(this._status)&&!this._rescc["no-store"]&&(!this._isShared||!this._rescc.private)&&(!this._isShared||this._noAuthorization||this._allowsStoringAuthenticated())&&(this._resHeaders.expires||this._rescc["max-age"]||this._isShared&&this._rescc["s-maxage"]||this._rescc.public||eb.has(this._status)))}_hasExplicitExpiration(){return!!(this._isShared&&this._rescc["s-maxage"]||this._rescc["max-age"]||this._resHeaders.expires)}_assertRequestHasHeaders(e){if(!e||!e.headers)throw Error("Request headers missing")}satisfiesWithoutRevalidation(e){return!this.evaluateRequest(e).revalidation}_evaluateRequestHitResult(e){return{response:{headers:this.responseHeaders()},revalidation:e}}_evaluateRequestRevalidation(e,t){return{synchronous:t,headers:this.revalidationHeaders(e)}}_evaluateRequestMissResult(e){return{response:void 0,revalidation:this._evaluateRequestRevalidation(e,!0)}}evaluateRequest(e){if(this._assertRequestHasHeaders(e),this._rescc["must-revalidate"])return this._evaluateRequestMissResult(e);if(!this._requestMatches(e,!1))return this._evaluateRequestMissResult(e);let t=Ci(e.headers["cache-control"]);return t["no-cache"]||/no-cache/.test(e.headers.pragma)?this._evaluateRequestMissResult(e):t["max-age"]&&this.age()>it(t["max-age"])?this._evaluateRequestMissResult(e):t["min-fresh"]&&this.maxAge()-this.age()<it(t["min-fresh"])?this._evaluateRequestMissResult(e):this.stale()?"max-stale"in t&&(t["max-stale"]===!0||t["max-stale"]>this.age()-this.maxAge())?this._evaluateRequestHitResult(void 0):this.useStaleWhileRevalidate()?this._evaluateRequestHitResult(this._evaluateRequestRevalidation(e,!1)):this._evaluateRequestMissResult(e):this._evaluateRequestHitResult(void 0)}_requestMatches(e,t){return!!((!this._url||this._url===e.url)&&this._host===e.headers.host&&(!e.method||this._method===e.method||t&&e.method==="HEAD")&&this._varyMatches(e))}_allowsStoringAuthenticated(){return!!(this._rescc["must-revalidate"]||this._rescc.public||this._rescc["s-maxage"])}_varyMatches(e){if(!this._resHeaders.vary)return!0;if(this._resHeaders.vary==="*")return!1;let t=this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/);for(let i of t)if(e.headers[i]!==this._reqHeaders[i])return!1;return!0}_copyWithoutHopByHopHeaders(e){let t={};for(let i in e)nb[i]||(t[i]=e[i]);if(e.connection){let i=e.connection.trim().split(/\s*,\s*/);for(let a of i)delete t[a]}if(t.warning){let i=t.warning.split(/,/).filter(a=>!/^\s*1[0-9][0-9]/.test(a));i.length?t.warning=i.join(",").trim():delete t.warning}return t}responseHeaders(){let e=this._copyWithoutHopByHopHeaders(this._resHeaders),t=this.age();return t>3600*24&&!this._hasExplicitExpiration()&&this.maxAge()>3600*24&&(e.warning=(e.warning?`${e.warning}, `:"")+'113 - "rfc7234 5.5.4"'),e.age=`${Math.round(t)}`,e.date=new Date(this.now()).toUTCString(),e}date(){let e=Date.parse(this._resHeaders.date);return isFinite(e)?e:this._responseTime}age(){let e=this._ageValue(),t=(this.now()-this._responseTime)/1e3;return e+t}_ageValue(){return it(this._resHeaders.age)}maxAge(){if(!this.storable()||this._rescc["no-cache"]||this._isShared&&this._resHeaders["set-cookie"]&&!this._rescc.public&&!this._rescc.immutable||this._resHeaders.vary==="*")return 0;if(this._isShared){if(this._rescc["proxy-revalidate"])return 0;if(this._rescc["s-maxage"])return it(this._rescc["s-maxage"])}if(this._rescc["max-age"])return it(this._rescc["max-age"]);let e=this._rescc.immutable?this._immutableMinTtl:0,t=this.date();if(this._resHeaders.expires){let i=Date.parse(this._resHeaders.expires);return Number.isNaN(i)||i<t?0:Math.max(e,(i-t)/1e3)}if(this._resHeaders["last-modified"]){let i=Date.parse(this._resHeaders["last-modified"]);if(isFinite(i)&&t>i)return Math.max(e,(t-i)/1e3*this._cacheHeuristic)}return e}timeToLive(){let e=this.maxAge()-this.age(),t=e+it(this._rescc["stale-if-error"]),i=e+it(this._rescc["stale-while-revalidate"]);return Math.round(Math.max(0,e,t,i)*1e3)}stale(){return this.maxAge()<=this.age()}_useStaleIfError(){return this.maxAge()+it(this._rescc["stale-if-error"])>this.age()}useStaleWhileRevalidate(){let e=it(this._rescc["stale-while-revalidate"]);return e>0&&this.maxAge()+e>this.age()}static fromObject(e){return new this(void 0,void 0,{_fromObject:e})}_fromObject(e){if(this._responseTime)throw Error("Reinitialized");if(!e||e.v!==1)throw Error("Invalid serialization");this._responseTime=e.t,this._isShared=e.sh,this._cacheHeuristic=e.ch,this._immutableMinTtl=e.imm!==void 0?e.imm:24*3600*1e3,this._ignoreCargoCult=!!e.icc,this._status=e.st,this._resHeaders=e.resh,this._rescc=e.rescc,this._method=e.m,this._url=e.u,this._host=e.h,this._noAuthorization=e.a,this._reqHeaders=e.reqh,this._reqcc=e.reqcc}toObject(){return{v:1,t:this._responseTime,sh:this._isShared,ch:this._cacheHeuristic,imm:this._immutableMinTtl,icc:this._ignoreCargoCult,st:this._status,resh:this._resHeaders,rescc:this._rescc,m:this._method,u:this._url,h:this._host,a:this._noAuthorization,reqh:this._reqHeaders,reqcc:this._reqcc}}revalidationHeaders(e){this._assertRequestHasHeaders(e);let t=this._copyWithoutHopByHopHeaders(e.headers);if(delete t["if-range"],!this._requestMatches(e,!0)||!this.storable())return delete t["if-none-match"],delete t["if-modified-since"],t;if(this._resHeaders.etag&&(t["if-none-match"]=t["if-none-match"]?`${t["if-none-match"]}, ${this._resHeaders.etag}`:this._resHeaders.etag),t["accept-ranges"]||t["if-match"]||t["if-unmodified-since"]||this._method&&this._method!="GET"){if(delete t["if-modified-since"],t["if-none-match"]){let a=t["if-none-match"].split(/,/).filter(c=>!/^\s*W\//.test(c));a.length?t["if-none-match"]=a.join(",").trim():delete t["if-none-match"]}}else this._resHeaders["last-modified"]&&!t["if-modified-since"]&&(t["if-modified-since"]=this._resHeaders["last-modified"]);return t}revalidatedPolicy(e,t){if(this._assertRequestHasHeaders(e),this._useStaleIfError()&&ib(t))return{policy:this,modified:!1,matches:!0};if(!t||!t.headers)throw Error("Response headers missing");let i=!1;t.status!==void 0&&t.status!=304?i=!1:t.headers.etag&&!/^\s*W\//.test(t.headers.etag)?i=this._resHeaders.etag&&this._resHeaders.etag.replace(/^\s*W\//,"")===t.headers.etag:this._resHeaders.etag&&t.headers.etag?i=this._resHeaders.etag.replace(/^\s*W\//,"")===t.headers.etag.replace(/^\s*W\//,""):this._resHeaders["last-modified"]?i=this._resHeaders["last-modified"]===t.headers["last-modified"]:!this._resHeaders.etag&&!this._resHeaders["last-modified"]&&!t.headers.etag&&!t.headers["last-modified"]&&(i=!0);let a={shared:this._isShared,cacheHeuristic:this._cacheHeuristic,immutableMinTimeToLive:this._immutableMinTtl,ignoreCargoCult:this._ignoreCargoCult};if(!i)return{policy:new this.constructor(e,t,a),modified:t.status!=304,matches:!1};let c={};for(let p in this._resHeaders)c[p]=p in t.headers&&!rb[p]?t.headers[p]:this._resHeaders[p];let u=Object.assign({},t,{status:this._status,method:this._method,headers:c});return{policy:new this.constructor(e,u,a),modified:!1,matches:!0}}}});var kn=$((t0,zu)=>{"use strict";zu.exports=s=>{let e={};for(let[t,i]of Object.entries(s))e[t.toLowerCase()]=i;return e}});var Ju=$((s0,Ku)=>{"use strict";var ab=q("stream").Readable,cb=kn(),Ei=class extends ab{constructor(e,t,i,a){if(typeof e!="number")throw new TypeError("Argument `statusCode` should be a number");if(typeof t!="object")throw new TypeError("Argument `headers` should be an object");if(!(i instanceof Buffer))throw new TypeError("Argument `body` should be a buffer");if(typeof a!="string")throw new TypeError("Argument `url` should be a string");super(),this.statusCode=e,this.headers=cb(t),this.body=i,this.url=a}_read(){this.push(this.body),this.push(null)}};Ku.exports=Ei});var Qu=$((n0,Yu)=>{"use strict";var lb=["destroy","setTimeout","socket","headers","trailers","rawHeaders","statusCode","httpVersion","httpVersionMinor","httpVersionMajor","rawTrailers","statusMessage"];Yu.exports=(s,e)=>{let t=new Set(Object.keys(s).concat(lb));for(let i of t)i in e||(e[i]=typeof s[i]=="function"?s[i].bind(s):s[i])}});var Zu=$((r0,Xu)=>{"use strict";var ub=q("stream").PassThrough,hb=Qu(),db=s=>{if(!(s&&s.pipe))throw new TypeError("Parameter `response` must be a response stream.");let e=new ub;return hb(s,e),s.pipe(e)};Xu.exports=db});var eh=$(ki=>{ki.stringify=function s(e){if(typeof e>"u")return e;if(e&&Buffer.isBuffer(e))return JSON.stringify(":base64:"+e.toString("base64"));if(e&&e.toJSON&&(e=e.toJSON()),e&&typeof e=="object"){var t="",i=Array.isArray(e);t=i?"[":"{";var a=!0;for(var c in e){var u=typeof e[c]=="function"||!i&&typeof e[c]>"u";Object.hasOwnProperty.call(e,c)&&!u&&(a||(t+=","),a=!1,i?e[c]==null?t+="null":t+=s(e[c]):e[c]!==void 0&&(t+=s(c)+":"+s(e[c])))}return t+=i?"]":"}",t}else return typeof e=="string"?JSON.stringify(/^:/.test(e)?":"+e:e):typeof e>"u"?"null":JSON.stringify(e)};ki.parse=function(s){return JSON.parse(s,function(e,t){return typeof t=="string"?/^:base64:/.test(t)?Buffer.from(t.substring(8),"base64"):/^:/.test(t)?t.substring(1):t:t})}});var rh=$((o0,nh)=>{"use strict";var fb=q("events"),th=eh(),pb=s=>{let e={redis:"@keyv/redis",rediss:"@keyv/redis",mongodb:"@keyv/mongo",mongo:"@keyv/mongo",sqlite:"@keyv/sqlite",postgresql:"@keyv/postgres",postgres:"@keyv/postgres",mysql:"@keyv/mysql",etcd:"@keyv/etcd",offline:"@keyv/offline",tiered:"@keyv/tiered"};if(s.adapter||s.uri){let t=s.adapter||/^[^:+]*/.exec(s.uri)[0];return new(q(e[t]))(s)}return new Map},sh=["sqlite","postgres","mysql","mongo","redis","tiered"],Oi=class extends fb{constructor(e,{emitErrors:t=!0,...i}={}){if(super(),this.opts={namespace:"keyv",serialize:th.stringify,deserialize:th.parse,...typeof e=="string"?{uri:e}:e,...i},!this.opts.store){let c={...this.opts};this.opts.store=pb(c)}if(this.opts.compression){let c=this.opts.compression;this.opts.serialize=c.serialize.bind(c),this.opts.deserialize=c.deserialize.bind(c)}typeof this.opts.store.on=="function"&&t&&this.opts.store.on("error",c=>this.emit("error",c)),this.opts.store.namespace=this.opts.namespace;let a=c=>async function*(){for await(let[u,p]of typeof c=="function"?c(this.opts.store.namespace):c){let g=await this.opts.deserialize(p);if(!(this.opts.store.namespace&&!u.includes(this.opts.store.namespace))){if(typeof g.expires=="number"&&Date.now()>g.expires){this.delete(u);continue}yield[this._getKeyUnprefix(u),g.value]}}};typeof this.opts.store[Symbol.iterator]=="function"&&this.opts.store instanceof Map?this.iterator=a(this.opts.store):typeof this.opts.store.iterator=="function"&&this.opts.store.opts&&this._checkIterableAdaptar()&&(this.iterator=a(this.opts.store.iterator.bind(this.opts.store)))}_checkIterableAdaptar(){return sh.includes(this.opts.store.opts.dialect)||sh.findIndex(e=>this.opts.store.opts.url.includes(e))>=0}_getKeyPrefix(e){return`${this.opts.namespace}:${e}`}_getKeyPrefixArray(e){return e.map(t=>`${this.opts.namespace}:${t}`)}_getKeyUnprefix(e){return e.split(":").splice(1).join(":")}get(e,t){let{store:i}=this.opts,a=Array.isArray(e),c=a?this._getKeyPrefixArray(e):this._getKeyPrefix(e);if(a&&i.getMany===void 0){let u=[];for(let p of c)u.push(Promise.resolve().then(()=>i.get(p)).then(g=>typeof g=="string"?this.opts.deserialize(g):this.opts.compression?this.opts.deserialize(g):g).then(g=>{if(g!=null)return typeof g.expires=="number"&&Date.now()>g.expires?this.delete(p).then(()=>{}):t&&t.raw?g:g.value}));return Promise.allSettled(u).then(p=>{let g=[];for(let m of p)g.push(m.value);return g})}return Promise.resolve().then(()=>a?i.getMany(c):i.get(c)).then(u=>typeof u=="string"?this.opts.deserialize(u):this.opts.compression?this.opts.deserialize(u):u).then(u=>{if(u!=null)return a?u.map((p,g)=>{if(typeof p=="string"&&(p=this.opts.deserialize(p)),p!=null){if(typeof p.expires=="number"&&Date.now()>p.expires){this.delete(e[g]).then(()=>{});return}return t&&t.raw?p:p.value}}):typeof u.expires=="number"&&Date.now()>u.expires?this.delete(e).then(()=>{}):t&&t.raw?u:u.value})}set(e,t,i){let a=this._getKeyPrefix(e);typeof i>"u"&&(i=this.opts.ttl),i===0&&(i=void 0);let{store:c}=this.opts;return Promise.resolve().then(()=>{let u=typeof i=="number"?Date.now()+i:null;return typeof t=="symbol"&&this.emit("error","symbol cannot be serialized"),t={value:t,expires:u},this.opts.serialize(t)}).then(u=>c.set(a,u,i)).then(()=>!0)}delete(e){let{store:t}=this.opts;if(Array.isArray(e)){let a=this._getKeyPrefixArray(e);if(t.deleteMany===void 0){let c=[];for(let u of a)c.push(t.delete(u));return Promise.allSettled(c).then(u=>u.every(p=>p.value===!0))}return Promise.resolve().then(()=>t.deleteMany(a))}let i=this._getKeyPrefix(e);return Promise.resolve().then(()=>t.delete(i))}clear(){let{store:e}=this.opts;return Promise.resolve().then(()=>e.clear())}has(e){let t=this._getKeyPrefix(e),{store:i}=this.opts;return Promise.resolve().then(async()=>typeof i.has=="function"?i.has(t):await i.get(t)!==void 0)}disconnect(){let{store:e}=this.opts;if(typeof e.disconnect=="function")return e.disconnect()}};nh.exports=Oi});var ah=$((c0,oh)=>{"use strict";var gb=q("events"),On=q("url"),mb=Pu(),yb=Fu(),Ti=Vu(),ih=Ju(),_b=kn(),bb=Zu(),vb=rh(),ks=class s{constructor(e,t){if(typeof e!="function")throw new TypeError("Parameter `request` must be a function");return this.cache=new vb({uri:typeof t=="string"&&t,store:typeof t!="string"&&t,namespace:"cacheable-request"}),this.createCacheableRequest(e)}createCacheableRequest(e){return(t,i)=>{let a;if(typeof t=="string")a=Si(On.parse(t)),t={};else if(t instanceof On.URL)a=Si(On.parse(t.toString())),t={};else{let[w,...C]=(t.path||"").split("?"),T=C.length>0?`?${C.join("?")}`:"";a=Si({...t,pathname:w,search:T})}t={headers:{},method:"GET",cache:!0,strictTtl:!1,automaticFailover:!1,...t,...wb(a)},t.headers=_b(t.headers);let c=new gb,u=mb(On.format(a),{stripWWW:!1,removeTrailingSlash:!1,stripAuthentication:!1}),p=`${t.method}:${u}`,g=!1,m=!1,_=w=>{m=!0;let C=!1,T,S=new Promise(k=>{T=()=>{C||(C=!0,k())}}),O=k=>{if(g&&!w.forceRefresh){k.status=k.statusCode;let G=Ti.fromObject(g.cachePolicy).revalidatedPolicy(w,k);if(!G.modified){let Y=G.policy.responseHeaders();k=new ih(g.statusCode,Y,g.body,g.url),k.cachePolicy=G.policy,k.fromCache=!0}}k.fromCache||(k.cachePolicy=new Ti(w,k,w),k.fromCache=!1);let N;w.cache&&k.cachePolicy.storable()?(N=bb(k),(async()=>{try{let G=yb.buffer(k);if(await Promise.race([S,new Promise(Z=>k.once("end",Z))]),C)return;let Y=await G,X={cachePolicy:k.cachePolicy.toObject(),url:k.url,statusCode:k.fromCache?g.statusCode:k.statusCode,body:Y},Q=w.strictTtl?k.cachePolicy.timeToLive():void 0;w.maxTtl&&(Q=Q?Math.min(Q,w.maxTtl):w.maxTtl),await this.cache.set(p,X,Q)}catch(G){c.emit("error",new s.CacheError(G))}})()):w.cache&&g&&(async()=>{try{await this.cache.delete(p)}catch(G){c.emit("error",new s.CacheError(G))}})(),c.emit("response",N||k),typeof i=="function"&&i(N||k)};try{let k=e(w,O);k.once("error",T),k.once("abort",T),c.emit("request",k)}catch(k){c.emit("error",new s.RequestError(k))}};return(async()=>{let w=async T=>{await Promise.resolve();let S=T.cache?await this.cache.get(p):void 0;if(typeof S>"u")return _(T);let O=Ti.fromObject(S.cachePolicy);if(O.satisfiesWithoutRevalidation(T)&&!T.forceRefresh){let k=O.responseHeaders(),N=new ih(S.statusCode,k,S.body,S.url);N.cachePolicy=O,N.fromCache=!0,c.emit("response",N),typeof i=="function"&&i(N)}else g=S,T.headers=O.revalidationHeaders(T),_(T)},C=T=>c.emit("error",new s.CacheError(T));this.cache.once("error",C),c.on("response",()=>this.cache.removeListener("error",C));try{await w(t)}catch(T){t.automaticFailover&&!m&&_(t),c.emit("error",new s.CacheError(T))}})(),c}}};function wb(s){let e={...s};return e.path=`${s.pathname||"/"}${s.search||""}`,delete e.pathname,delete e.search,e}function Si(s){return{protocol:s.protocol,auth:s.auth,hostname:s.hostname||s.host||"localhost",port:s.port,pathname:s.pathname,search:s.search}}ks.RequestError=class extends Error{constructor(s){super(s.message),this.name="RequestError",Object.assign(this,s)}};ks.CacheError=class extends Error{constructor(s){super(s.message),this.name="CacheError",Object.assign(this,s)}};oh.exports=ks});var lh=$((h0,ch)=>{"use strict";var Cb=["aborted","complete","headers","httpVersion","httpVersionMinor","httpVersionMajor","method","rawHeaders","rawTrailers","setTimeout","socket","statusCode","statusMessage","trailers","url"];ch.exports=(s,e)=>{if(e._readableState.autoDestroy)throw new Error("The second stream must have the `autoDestroy` option set to `false`");let t=new Set(Object.keys(s).concat(Cb)),i={};for(let a of t)a in e||(i[a]={get(){let c=s[a];return typeof c=="function"?c.bind(s):c},set(c){s[a]=c},enumerable:!0,configurable:!1});return Object.defineProperties(e,i),s.once("aborted",()=>{e.destroy(),e.emit("aborted")}),s.once("close",()=>{s.complete&&e.readable?e.once("end",()=>{e.emit("close")}):e.emit("close")}),e}});var hh=$((d0,uh)=>{"use strict";var{Transform:Eb,PassThrough:kb}=q("stream"),Ai=q("zlib"),Ob=lh();uh.exports=s=>{let e=(s.headers["content-encoding"]||"").toLowerCase();if(!["gzip","deflate","br"].includes(e))return s;let t=e==="br";if(t&&typeof Ai.createBrotliDecompress!="function")return s.destroy(new Error("Brotli is not supported on Node.js < 12")),s;let i=!0,a=new Eb({transform(p,g,m){i=!1,m(null,p)},flush(p){p()}}),c=new kb({autoDestroy:!1,destroy(p,g){s.destroy(),g(p)}}),u=t?Ai.createBrotliDecompress():Ai.createUnzip();return u.once("error",p=>{if(i&&!s.readable){c.end();return}c.destroy(p)}),Ob(s,c),s.pipe(a).pipe(u).pipe(c),c}});var Pi=$((f0,dh)=>{"use strict";var Ri=class{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");this.maxSize=e.maxSize,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_set(e,t){if(this.cache.set(e,t),this._size++,this._size>=this.maxSize){if(this._size=0,typeof this.onEviction=="function")for(let[i,a]of this.oldCache.entries())this.onEviction(i,a);this.oldCache=this.cache,this.cache=new Map}}get(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e)){let t=this.oldCache.get(e);return this.oldCache.delete(e),this._set(e,t),t}}set(e,t){return this.cache.has(e)?this.cache.set(e,t):this._set(e,t),this}has(e){return this.cache.has(e)||this.oldCache.has(e)}peek(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e))return this.oldCache.get(e)}delete(e){let t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache)yield e;for(let e of this.oldCache){let[t]=e;this.cache.has(t)||(yield e)}}get size(){let e=0;for(let t of this.oldCache.keys())this.cache.has(t)||e++;return Math.min(this._size+e,this.maxSize)}};dh.exports=Ri});var Mi=$((p0,mh)=>{"use strict";var Tb=q("events"),Sb=q("tls"),Ab=q("http2"),Rb=Pi(),Ce=Symbol("currentStreamsCount"),fh=Symbol("request"),Le=Symbol("cachedOriginSet"),Vt=Symbol("gracefullyClosing"),Pb=["maxDeflateDynamicTableSize","maxSessionMemory","maxHeaderListPairs","maxOutstandingPings","maxReservedRemoteStreams","maxSendHeaderBlockLength","paddingStrategy","localAddress","path","rejectUnauthorized","minDHSize","ca","cert","clientCertEngine","ciphers","key","pfx","servername","minVersion","maxVersion","secureProtocol","crl","honorCipherOrder","ecdhCurve","dhparam","secureOptions","sessionIdContext"],Ib=(s,e,t)=>{let i=0,a=s.length;for(;i<a;){let c=i+a>>>1;t(s[c],e)?i=c+1:a=c}return i},Mb=(s,e)=>s.remoteSettings.maxConcurrentStreams>e.remoteSettings.maxConcurrentStreams,Ii=(s,e)=>{for(let t of s)t[Le].length<e[Le].length&&t[Le].every(i=>e[Le].includes(i))&&t[Ce]+e[Ce]<=e.remoteSettings.maxConcurrentStreams&&gh(t)},xb=(s,e)=>{for(let t of s)e[Le].length<t[Le].length&&e[Le].every(i=>t[Le].includes(i))&&e[Ce]+t[Ce]<=t.remoteSettings.maxConcurrentStreams&&gh(e)},ph=({agent:s,isFree:e})=>{let t={};for(let i in s.sessions){let c=s.sessions[i].filter(u=>{let p=u[Et.kCurrentStreamsCount]<u.remoteSettings.maxConcurrentStreams;return e?p:!p});c.length!==0&&(t[i]=c)}return t},gh=s=>{s[Vt]=!0,s[Ce]===0&&s.close()},Et=class s extends Tb{constructor({timeout:e=6e4,maxSessions:t=1/0,maxFreeSessions:i=10,maxCachedTlsSessions:a=100}={}){super(),this.sessions={},this.queue={},this.timeout=e,this.maxSessions=t,this.maxFreeSessions=i,this._freeSessionsCount=0,this._sessionsCount=0,this.settings={enablePush:!1},this.tlsSessionCache=new Rb({maxSize:a})}static normalizeOrigin(e,t){return typeof e=="string"&&(e=new URL(e)),t&&e.hostname!==t&&(e.hostname=t),e.origin}normalizeOptions(e){let t="";if(e)for(let i of Pb)e[i]&&(t+=`:${e[i]}`);return t}_tryToCreateNewSession(e,t){if(!(e in this.queue)||!(t in this.queue[e]))return;let i=this.queue[e][t];this._sessionsCount<this.maxSessions&&!i.completed&&(i.completed=!0,i())}getSession(e,t,i){return new Promise((a,c)=>{Array.isArray(i)?(i=[...i],a()):i=[{resolve:a,reject:c}];let u=this.normalizeOptions(t),p=s.normalizeOrigin(e,t&&t.servername);if(p===void 0){for(let{reject:_}of i)_(new TypeError("The `origin` argument needs to be a string or an URL object"));return}if(u in this.sessions){let _=this.sessions[u],w=-1,C=-1,T;for(let S of _){let O=S.remoteSettings.maxConcurrentStreams;if(O<w)break;if(S[Le].includes(p)){let k=S[Ce];if(k>=O||S[Vt]||S.destroyed)continue;T||(w=O),k>C&&(T=S,C=k)}}if(T){if(i.length!==1){for(let{reject:S}of i){let O=new Error(`Expected the length of listeners to be 1, got ${i.length}.
34
+ Please report this to https://github.com/szmarczak/http2-wrapper/`);S(O)}return}i[0].resolve(T);return}}if(u in this.queue){if(p in this.queue[u]){this.queue[u][p].listeners.push(...i),this._tryToCreateNewSession(u,p);return}}else this.queue[u]={};let g=()=>{u in this.queue&&this.queue[u][p]===m&&(delete this.queue[u][p],Object.keys(this.queue[u]).length===0&&delete this.queue[u])},m=()=>{let _=`${p}:${u}`,w=!1;try{let C=Ab.connect(e,{createConnection:this.createConnection,settings:this.settings,session:this.tlsSessionCache.get(_),...t});C[Ce]=0,C[Vt]=!1;let T=()=>C[Ce]<C.remoteSettings.maxConcurrentStreams,S=!0;C.socket.once("session",k=>{this.tlsSessionCache.set(_,k)}),C.once("error",k=>{for(let{reject:N}of i)N(k);this.tlsSessionCache.delete(_)}),C.setTimeout(this.timeout,()=>{C.destroy()}),C.once("close",()=>{if(w){S&&this._freeSessionsCount--,this._sessionsCount--;let k=this.sessions[u];k.splice(k.indexOf(C),1),k.length===0&&delete this.sessions[u]}else{let k=new Error("Session closed without receiving a SETTINGS frame");k.code="HTTP2WRAPPER_NOSETTINGS";for(let{reject:N}of i)N(k);g()}this._tryToCreateNewSession(u,p)});let O=()=>{if(!(!(u in this.queue)||!T())){for(let k of C[Le])if(k in this.queue[u]){let{listeners:N}=this.queue[u][k];for(;N.length!==0&&T();)N.shift().resolve(C);let G=this.queue[u];if(G[k].listeners.length===0&&(delete G[k],Object.keys(G).length===0)){delete this.queue[u];break}if(!T())break}}};C.on("origin",()=>{C[Le]=C.originSet,T()&&(O(),Ii(this.sessions[u],C))}),C.once("remoteSettings",()=>{if(C.ref(),C.unref(),this._sessionsCount++,m.destroyed){let k=new Error("Agent has been destroyed");for(let N of i)N.reject(k);C.destroy();return}C[Le]=C.originSet;{let k=this.sessions;if(u in k){let N=k[u];N.splice(Ib(N,C,Mb),0,C)}else k[u]=[C]}this._freeSessionsCount+=1,w=!0,this.emit("session",C),O(),g(),C[Ce]===0&&this._freeSessionsCount>this.maxFreeSessions&&C.close(),i.length!==0&&(this.getSession(p,t,i),i.length=0),C.on("remoteSettings",()=>{O(),Ii(this.sessions[u],C)})}),C[fh]=C.request,C.request=(k,N)=>{if(C[Vt])throw new Error("The session is gracefully closing. No new streams are allowed.");let G=C[fh](k,N);return C.ref(),++C[Ce],C[Ce]===C.remoteSettings.maxConcurrentStreams&&this._freeSessionsCount--,G.once("close",()=>{if(S=T(),--C[Ce],!C.destroyed&&!C.closed&&(xb(this.sessions[u],C),T()&&!C.closed)){S||(this._freeSessionsCount++,S=!0);let Y=C[Ce]===0;Y&&C.unref(),Y&&(this._freeSessionsCount>this.maxFreeSessions||C[Vt])?C.close():(Ii(this.sessions[u],C),O())}}),G}}catch(C){for(let T of i)T.reject(C);g()}};m.listeners=i,m.completed=!1,m.destroyed=!1,this.queue[u][p]=m,this._tryToCreateNewSession(u,p)})}request(e,t,i,a){return new Promise((c,u)=>{this.getSession(e,t,[{reject:u,resolve:p=>{try{c(p.request(i,a))}catch(g){u(g)}}}])})}createConnection(e,t){return s.connect(e,t)}static connect(e,t){t.ALPNProtocols=["h2"];let i=e.port||443,a=e.hostname||e.host;return typeof t.servername>"u"&&(t.servername=a),Sb.connect(i,a,t)}closeFreeSessions(){for(let e of Object.values(this.sessions))for(let t of e)t[Ce]===0&&t.close()}destroy(e){for(let t of Object.values(this.sessions))for(let i of t)i.destroy(e);for(let t of Object.values(this.queue))for(let i of Object.values(t))i.destroyed=!0;this.queue={}}get freeSessions(){return ph({agent:this,isFree:!0})}get busySessions(){return ph({agent:this,isFree:!1})}};Et.kCurrentStreamsCount=Ce;Et.kGracefullyClosing=Vt;mh.exports={Agent:Et,globalAgent:new Et}});var Ni=$((g0,yh)=>{"use strict";var{Readable:Nb}=q("stream"),xi=class extends Nb{constructor(e,t){super({highWaterMark:t,autoDestroy:!1}),this.statusCode=null,this.statusMessage="",this.httpVersion="2.0",this.httpVersionMajor=2,this.httpVersionMinor=0,this.headers={},this.trailers={},this.req=null,this.aborted=!1,this.complete=!1,this.upgrade=null,this.rawHeaders=[],this.rawTrailers=[],this.socket=e,this.connection=e,this._dumped=!1}_destroy(e){this.req._request.destroy(e)}setTimeout(e,t){return this.req.setTimeout(e,t),this}_dump(){this._dumped||(this._dumped=!0,this.removeAllListeners("data"),this.resume())}_read(){this.req&&this.req._request.resume()}};yh.exports=xi});var Li=$((m0,_h)=>{"use strict";_h.exports=s=>{let e={protocol:s.protocol,hostname:typeof s.hostname=="string"&&s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,host:s.host,hash:s.hash,search:s.search,pathname:s.pathname,href:s.href,path:`${s.pathname||""}${s.search||""}`};return typeof s.port=="string"&&s.port.length!==0&&(e.port=Number(s.port)),(s.username||s.password)&&(e.auth=`${s.username||""}:${s.password||""}`),e}});var vh=$((y0,bh)=>{"use strict";bh.exports=(s,e,t)=>{for(let i of t)s.on(i,(...a)=>e.emit(i,...a))}});var Ch=$((_0,wh)=>{"use strict";wh.exports=s=>{switch(s){case":method":case":scheme":case":authority":case":path":return!0;default:return!1}}});var kh=$((v0,Eh)=>{"use strict";var zt=(s,e,t)=>{Eh.exports[e]=class extends s{constructor(...a){super(typeof t=="string"?t:t(a)),this.name=`${super.name} [${e}]`,this.code=e}}};zt(TypeError,"ERR_INVALID_ARG_TYPE",s=>{let e=s[0].includes(".")?"property":"argument",t=s[1],i=Array.isArray(t);return i&&(t=`${t.slice(0,-1).join(", ")} or ${t.slice(-1)}`),`The "${s[0]}" ${e} must be ${i?"one of":"of"} type ${t}. Received ${typeof s[2]}`});zt(TypeError,"ERR_INVALID_PROTOCOL",s=>`Protocol "${s[0]}" not supported. Expected "${s[1]}"`);zt(Error,"ERR_HTTP_HEADERS_SENT",s=>`Cannot ${s[0]} headers after they are sent to the client`);zt(TypeError,"ERR_INVALID_HTTP_TOKEN",s=>`${s[0]} must be a valid HTTP token [${s[1]}]`);zt(TypeError,"ERR_HTTP_INVALID_HEADER_VALUE",s=>`Invalid value "${s[0]} for header "${s[1]}"`);zt(TypeError,"ERR_INVALID_CHAR",s=>`Invalid character in ${s[0]} [${s[1]}]`)});var Bi=$((w0,Ih)=>{"use strict";var Lb=q("http2"),{Writable:Db}=q("stream"),{Agent:Oh,globalAgent:Ub}=Mi(),jb=Ni(),qb=Li(),Bb=vh(),$b=Ch(),{ERR_INVALID_ARG_TYPE:Di,ERR_INVALID_PROTOCOL:Hb,ERR_HTTP_HEADERS_SENT:Th,ERR_INVALID_HTTP_TOKEN:Gb,ERR_HTTP_INVALID_HEADER_VALUE:Fb,ERR_INVALID_CHAR:Wb}=kh(),{HTTP2_HEADER_STATUS:Sh,HTTP2_HEADER_METHOD:Ah,HTTP2_HEADER_PATH:Rh,HTTP2_METHOD_CONNECT:Vb}=Lb.constants,be=Symbol("headers"),Ui=Symbol("origin"),ji=Symbol("session"),Ph=Symbol("options"),Tn=Symbol("flushedHeaders"),Os=Symbol("jobs"),zb=/^[\^`\-\w!#$%&*+.|~]+$/,Kb=/[^\t\u0020-\u007E\u0080-\u00FF]/,qi=class extends Db{constructor(e,t,i){super({autoDestroy:!1});let a=typeof e=="string"||e instanceof URL;if(a&&(e=qb(e instanceof URL?e:new URL(e))),typeof t=="function"||t===void 0?(i=t,t=a?e:{...e}):t={...e,...t},t.h2session)this[ji]=t.h2session;else if(t.agent===!1)this.agent=new Oh({maxFreeSessions:0});else if(typeof t.agent>"u"||t.agent===null)typeof t.createConnection=="function"?(this.agent=new Oh({maxFreeSessions:0}),this.agent.createConnection=t.createConnection):this.agent=Ub;else if(typeof t.agent.request=="function")this.agent=t.agent;else throw new Di("options.agent",["Agent-like Object","undefined","false"],t.agent);if(t.protocol&&t.protocol!=="https:")throw new Hb(t.protocol,"https:");let c=t.port||t.defaultPort||this.agent&&this.agent.defaultPort||443,u=t.hostname||t.host||"localhost";delete t.hostname,delete t.host,delete t.port;let{timeout:p}=t;if(t.timeout=void 0,this[be]=Object.create(null),this[Os]=[],this.socket=null,this.connection=null,this.method=t.method||"GET",this.path=t.path,this.res=null,this.aborted=!1,this.reusedSocket=!1,t.headers)for(let[g,m]of Object.entries(t.headers))this.setHeader(g,m);t.auth&&!("authorization"in this[be])&&(this[be].authorization="Basic "+Buffer.from(t.auth).toString("base64")),t.session=t.tlsSession,t.path=t.socketPath,this[Ph]=t,c===443?(this[Ui]=`https://${u}`,":authority"in this[be]||(this[be][":authority"]=u)):(this[Ui]=`https://${u}:${c}`,":authority"in this[be]||(this[be][":authority"]=`${u}:${c}`)),p&&this.setTimeout(p),i&&this.once("response",i),this[Tn]=!1}get method(){return this[be][Ah]}set method(e){e&&(this[be][Ah]=e.toUpperCase())}get path(){return this[be][Rh]}set path(e){e&&(this[be][Rh]=e)}get _mustNotHaveABody(){return this.method==="GET"||this.method==="HEAD"||this.method==="DELETE"}_write(e,t,i){if(this._mustNotHaveABody){i(new Error("The GET, HEAD and DELETE methods must NOT have a body"));return}this.flushHeaders();let a=()=>this._request.write(e,t,i);this._request?a():this[Os].push(a)}_final(e){if(this.destroyed)return;this.flushHeaders();let t=()=>{if(this._mustNotHaveABody){e();return}this._request.end(e)};this._request?t():this[Os].push(t)}abort(){this.res&&this.res.complete||(this.aborted||process.nextTick(()=>this.emit("abort")),this.aborted=!0,this.destroy())}_destroy(e,t){this.res&&this.res._dump(),this._request&&this._request.destroy(),t(e)}async flushHeaders(){if(this[Tn]||this.destroyed)return;this[Tn]=!0;let e=this.method===Vb,t=i=>{if(this._request=i,this.destroyed){i.destroy();return}e||Bb(i,this,["timeout","continue","close","error"]);let a=u=>(...p)=>{!this.writable&&!this.destroyed?u(...p):this.once("finish",()=>{u(...p)})};i.once("response",a((u,p,g)=>{let m=new jb(this.socket,i.readableHighWaterMark);this.res=m,m.req=this,m.statusCode=u[Sh],m.headers=u,m.rawHeaders=g,m.once("end",()=>{this.aborted?(m.aborted=!0,m.emit("aborted")):(m.complete=!0,m.socket=null,m.connection=null)}),e?(m.upgrade=!0,this.emit("connect",m,i,Buffer.alloc(0))?this.emit("close"):i.destroy()):(i.on("data",_=>{!m._dumped&&!m.push(_)&&i.pause()}),i.once("end",()=>{m.push(null)}),this.emit("response",m)||m._dump())})),i.once("headers",a(u=>this.emit("information",{statusCode:u[Sh]}))),i.once("trailers",a((u,p,g)=>{let{res:m}=this;m.trailers=u,m.rawTrailers=g}));let{socket:c}=i.session;this.socket=c,this.connection=c;for(let u of this[Os])u();this.emit("socket",this.socket)};if(this[ji])try{t(this[ji].request(this[be]))}catch(i){this.emit("error",i)}else{this.reusedSocket=!0;try{t(await this.agent.request(this[Ui],this[Ph],this[be]))}catch(i){this.emit("error",i)}}}getHeader(e){if(typeof e!="string")throw new Di("name","string",e);return this[be][e.toLowerCase()]}get headersSent(){return this[Tn]}removeHeader(e){if(typeof e!="string")throw new Di("name","string",e);if(this.headersSent)throw new Th("remove");delete this[be][e.toLowerCase()]}setHeader(e,t){if(this.headersSent)throw new Th("set");if(typeof e!="string"||!zb.test(e)&&!$b(e))throw new Gb("Header name",e);if(typeof t>"u")throw new Fb(t,e);if(Kb.test(t))throw new Wb("header content",e);this[be][e.toLowerCase()]=t}setNoDelay(){}setSocketKeepAlive(){}setTimeout(e,t){let i=()=>this._request.setTimeout(e,t);return this._request?i():this[Os].push(i),this}get maxHeadersCount(){if(!this.destroyed&&this._request)return this._request.session.localSettings.maxHeaderListSize}set maxHeadersCount(e){}};Ih.exports=qi});var xh=$((C0,Mh)=>{"use strict";var Jb=q("tls");Mh.exports=(s={},e=Jb.connect)=>new Promise((t,i)=>{let a=!1,c,u=async()=>{await g,c.off("timeout",p),c.off("error",i),s.resolveSocket?(t({alpnProtocol:c.alpnProtocol,socket:c,timeout:a}),a&&(await Promise.resolve(),c.emit("timeout"))):(c.destroy(),t({alpnProtocol:c.alpnProtocol,timeout:a}))},p=async()=>{a=!0,u()},g=(async()=>{try{c=await e(s,u),c.on("error",i),c.once("timeout",p)}catch(m){i(m)}})()})});var Lh=$((E0,Nh)=>{"use strict";var Yb=q("net");Nh.exports=s=>{let e=s.host,t=s.headers&&s.headers.host;return t&&(t.startsWith("[")?t.indexOf("]")===-1?e=t:e=t.slice(1,-1):e=t.split(":",1)[0]),Yb.isIP(e)?"":e}});var jh=$((k0,Hi)=>{"use strict";var Dh=q("http"),$i=q("https"),Qb=xh(),Xb=Pi(),Zb=Bi(),ev=Lh(),tv=Li(),Sn=new Xb({maxSize:100}),Ts=new Map,Uh=(s,e,t)=>{e._httpMessage={shouldKeepAlive:!0};let i=()=>{s.emit("free",e,t)};e.on("free",i);let a=()=>{s.removeSocket(e,t)};e.on("close",a);let c=()=>{s.removeSocket(e,t),e.off("close",a),e.off("free",i),e.off("agentRemove",c)};e.on("agentRemove",c),s.emit("free",e,t)},sv=async s=>{let e=`${s.host}:${s.port}:${s.ALPNProtocols.sort()}`;if(!Sn.has(e)){if(Ts.has(e))return(await Ts.get(e)).alpnProtocol;let{path:t,agent:i}=s;s.path=s.socketPath;let a=Qb(s);Ts.set(e,a);try{let{socket:c,alpnProtocol:u}=await a;if(Sn.set(e,u),s.path=t,u==="h2")c.destroy();else{let{globalAgent:p}=$i,g=$i.Agent.prototype.createConnection;i?i.createConnection===g?Uh(i,c,s):c.destroy():p.createConnection===g?Uh(p,c,s):c.destroy()}return Ts.delete(e),u}catch(c){throw Ts.delete(e),c}}return Sn.get(e)};Hi.exports=async(s,e,t)=>{if((typeof s=="string"||s instanceof URL)&&(s=tv(new URL(s))),typeof e=="function"&&(t=e,e=void 0),e={ALPNProtocols:["h2","http/1.1"],...s,...e,resolveSocket:!0},!Array.isArray(e.ALPNProtocols)||e.ALPNProtocols.length===0)throw new Error("The `ALPNProtocols` option must be an Array with at least one entry");e.protocol=e.protocol||"https:";let i=e.protocol==="https:";e.host=e.hostname||e.host||"localhost",e.session=e.tlsSession,e.servername=e.servername||ev(e),e.port=e.port||(i?443:80),e._defaultAgent=i?$i.globalAgent:Dh.globalAgent;let a=e.agent;if(a){if(a.addRequest)throw new Error("The `options.agent` object can contain only `http`, `https` or `http2` properties");e.agent=a[i?"https":"http"]}return i&&await sv(e)==="h2"?(a&&(e.agent=a.http2),new Zb(e,t)):Dh.request(e,t)};Hi.exports.protocolCache=Sn});var Bh=$((O0,qh)=>{"use strict";var nv=q("http2"),rv=Mi(),Gi=Bi(),iv=Ni(),ov=jh(),av=(s,e,t)=>new Gi(s,e,t),cv=(s,e,t)=>{let i=new Gi(s,e,t);return i.end(),i};qh.exports={...nv,ClientRequest:Gi,IncomingMessage:iv,...rv,request:av,get:cv,auto:ov}});var Wi=$(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});var $h=rt();Fi.default=s=>$h.default.nodeStream(s)&&$h.default.function_(s.getBoundary)});var Wh=$(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});var Gh=q("fs"),Fh=q("util"),Hh=rt(),lv=Wi(),uv=Fh.promisify(Gh.stat);Vi.default=async(s,e)=>{if(e&&"content-length"in e)return Number(e["content-length"]);if(!s)return 0;if(Hh.default.string(s))return Buffer.byteLength(s);if(Hh.default.buffer(s))return s.length;if(lv.default(s))return Fh.promisify(s.getLength.bind(s))();if(s instanceof Gh.ReadStream){let{size:t}=await uv(s.path);return t===0?void 0:t}}});var Ki=$(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});function hv(s,e,t){let i={};for(let a of t)i[a]=(...c)=>{e.emit(a,...c)},s.on(a,i[a]);return()=>{for(let a of t)s.off(a,i[a])}}zi.default=hv});var Vh=$(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.default=()=>{let s=[];return{once(e,t,i){e.once(t,i),s.push({origin:e,event:t,fn:i})},unhandleAll(){for(let e of s){let{origin:t,event:i,fn:a}=e;t.removeListener(i,a)}s.length=0}}}});var Kh=$(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.TimeoutError=void 0;var dv=q("net"),fv=Vh(),zh=Symbol("reentry"),pv=()=>{},An=class extends Error{constructor(e,t){super(`Timeout awaiting '${t}' for ${e}ms`),this.event=t,this.name="TimeoutError",this.code="ETIMEDOUT"}};Ss.TimeoutError=An;Ss.default=(s,e,t)=>{if(zh in s)return pv;s[zh]=!0;let i=[],{once:a,unhandleAll:c}=fv.default(),u=(w,C,T)=>{var S;let O=setTimeout(C,w,w,T);(S=O.unref)===null||S===void 0||S.call(O);let k=()=>{clearTimeout(O)};return i.push(k),k},{host:p,hostname:g}=t,m=(w,C)=>{s.destroy(new An(w,C))},_=()=>{for(let w of i)w();c()};if(s.once("error",w=>{if(_(),s.listenerCount("error")===0)throw w}),s.once("close",_),a(s,"response",w=>{a(w,"end",_)}),typeof e.request<"u"&&u(e.request,m,"request"),typeof e.socket<"u"){let w=()=>{m(e.socket,"socket")};s.setTimeout(e.socket,w),i.push(()=>{s.removeListener("timeout",w)})}return a(s,"socket",w=>{var C;let{socketPath:T}=s;if(w.connecting){let S=!!(T??dv.isIP((C=g??p)!==null&&C!==void 0?C:"")!==0);if(typeof e.lookup<"u"&&!S&&typeof w.address().address>"u"){let O=u(e.lookup,m,"lookup");a(w,"lookup",O)}if(typeof e.connect<"u"){let O=()=>u(e.connect,m,"connect");S?a(w,"connect",O()):a(w,"lookup",k=>{k===null&&a(w,"connect",O())})}typeof e.secureConnect<"u"&&t.protocol==="https:"&&a(w,"connect",()=>{let O=u(e.secureConnect,m,"secureConnect");a(w,"secureConnect",O)})}if(typeof e.send<"u"){let S=()=>u(e.send,m,"send");w.connecting?a(w,"connect",()=>{a(s,"upload-complete",S())}):a(s,"upload-complete",S())}}),typeof e.response<"u"&&a(s,"upload-complete",()=>{let w=u(e.response,m,"response");a(s,"response",w)}),_}});var Yh=$(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});var Jh=rt();Yi.default=s=>{s=s;let e={protocol:s.protocol,hostname:Jh.default.string(s.hostname)&&s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,host:s.host,hash:s.hash,search:s.search,pathname:s.pathname,href:s.href,path:`${s.pathname||""}${s.search||""}`};return Jh.default.string(s.port)&&s.port.length>0&&(e.port=Number(s.port)),(s.username||s.password)&&(e.auth=`${s.username||""}:${s.password||""}`),e}});var Qh=$(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});var gv=q("url"),mv=["protocol","host","hostname","port","pathname","search"];Qi.default=(s,e)=>{var t,i;if(e.path){if(e.pathname)throw new TypeError("Parameters `path` and `pathname` are mutually exclusive.");if(e.search)throw new TypeError("Parameters `path` and `search` are mutually exclusive.");if(e.searchParams)throw new TypeError("Parameters `path` and `searchParams` are mutually exclusive.")}if(e.search&&e.searchParams)throw new TypeError("Parameters `search` and `searchParams` are mutually exclusive.");if(!s){if(!e.protocol)throw new TypeError("No URL protocol specified");s=`${e.protocol}//${(i=(t=e.hostname)!==null&&t!==void 0?t:e.host)!==null&&i!==void 0?i:""}`}let a=new gv.URL(s);if(e.path){let c=e.path.indexOf("?");c===-1?e.pathname=e.path:(e.pathname=e.path.slice(0,c),e.search=e.path.slice(c+1)),delete e.path}for(let c of mv)e[c]&&(a[c]=e[c].toString());return a}});var Xh=$(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});var Xi=class{constructor(){this.weakMap=new WeakMap,this.map=new Map}set(e,t){typeof e=="object"?this.weakMap.set(e,t):this.map.set(e,t)}get(e){return typeof e=="object"?this.weakMap.get(e):this.map.get(e)}has(e){return typeof e=="object"?this.weakMap.has(e):this.map.has(e)}};Zi.default=Xi});var to=$(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});var yv=async s=>{let e=[],t=0;for await(let i of s)e.push(i),t+=Buffer.byteLength(i);return Buffer.isBuffer(e[0])?Buffer.concat(e,t):Buffer.from(e.join(""))};eo.default=yv});var ed=$(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.dnsLookupIpVersionToFamily=kt.isDnsLookupIpVersion=void 0;var Zh={auto:0,ipv4:4,ipv6:6};kt.isDnsLookupIpVersion=s=>s in Zh;kt.dnsLookupIpVersionToFamily=s=>{if(kt.isDnsLookupIpVersion(s))return Zh[s];throw new Error("Invalid DNS lookup IP version")}});var so=$(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.isResponseOk=void 0;Rn.isResponseOk=s=>{let{statusCode:e}=s,t=s.request.options.followRedirect?299:399;return e>=200&&e<=t||e===304}});var sd=$(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});var td=new Set;no.default=s=>{td.has(s)||(td.add(s),process.emitWarning(`Got: ${s}`,{type:"DeprecationWarning"}))}});var nd=$(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});var re=rt(),_v=(s,e)=>{if(re.default.null_(s.encoding))throw new TypeError("To get a Buffer, set `options.responseType` to `buffer` instead");re.assert.any([re.default.string,re.default.undefined],s.encoding),re.assert.any([re.default.boolean,re.default.undefined],s.resolveBodyOnly),re.assert.any([re.default.boolean,re.default.undefined],s.methodRewriting),re.assert.any([re.default.boolean,re.default.undefined],s.isStream),re.assert.any([re.default.string,re.default.undefined],s.responseType),s.responseType===void 0&&(s.responseType="text");let{retry:t}=s;if(e?s.retry={...e.retry}:s.retry={calculateDelay:i=>i.computedValue,limit:0,methods:[],statusCodes:[],errorCodes:[],maxRetryAfter:void 0},re.default.object(t)?(s.retry={...s.retry,...t},s.retry.methods=[...new Set(s.retry.methods.map(i=>i.toUpperCase()))],s.retry.statusCodes=[...new Set(s.retry.statusCodes)],s.retry.errorCodes=[...new Set(s.retry.errorCodes)]):re.default.number(t)&&(s.retry.limit=t),re.default.undefined(s.retry.maxRetryAfter)&&(s.retry.maxRetryAfter=Math.min(...[s.timeout.request,s.timeout.connect].filter(re.default.number))),re.default.object(s.pagination)){e&&(s.pagination={...e.pagination,...s.pagination});let{pagination:i}=s;if(!re.default.function_(i.transform))throw new Error("`options.pagination.transform` must be implemented");if(!re.default.function_(i.shouldContinue))throw new Error("`options.pagination.shouldContinue` must be implemented");if(!re.default.function_(i.filter))throw new TypeError("`options.pagination.filter` must be implemented");if(!re.default.function_(i.paginate))throw new Error("`options.pagination.paginate` must be implemented")}return s.responseType==="json"&&s.headers.accept===void 0&&(s.headers.accept="application/json"),s};ro.default=_v});var rd=$(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.retryAfterStatusCodes=void 0;As.retryAfterStatusCodes=new Set([413,429,503]);var bv=({attemptCount:s,retryOptions:e,error:t,retryAfter:i})=>{if(s>e.limit)return 0;let a=e.methods.includes(t.options.method),c=e.errorCodes.includes(t.code),u=t.response&&e.statusCodes.includes(t.response.statusCode);if(!a||!c&&!u)return 0;if(t.response){if(i)return e.maxRetryAfter===void 0||i>e.maxRetryAfter?0:i;if(t.response.statusCode===413)return 0}let p=Math.random()*100;return 2**(s-1)*1e3+p};As.default=bv});var Is=$(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.UnsupportedProtocolError=ee.ReadError=ee.TimeoutError=ee.UploadError=ee.CacheError=ee.HTTPError=ee.MaxRedirectsError=ee.RequestError=ee.setNonEnumerableProperties=ee.knownHookEvents=ee.withoutBody=ee.kIsNormalizedAlready=void 0;var id=q("util"),od=q("stream"),vv=q("fs"),dt=q("url"),ad=q("http"),io=q("http"),wv=q("https"),Cv=vu(),Ev=Su(),cd=ah(),kv=hh(),Ov=Bh(),Tv=kn(),M=rt(),Sv=Wh(),ld=Wi(),Av=Ki(),ud=Kh(),Rv=Yh(),hd=Qh(),Pv=Xh(),Iv=to(),dd=ed(),Mv=so(),ft=sd(),xv=nd(),Nv=rd(),oo,ge=Symbol("request"),Mn=Symbol("response"),Kt=Symbol("responseSize"),Jt=Symbol("downloadedSize"),Yt=Symbol("bodySize"),Qt=Symbol("uploadedSize"),Pn=Symbol("serverResponsesPiped"),fd=Symbol("unproxyEvents"),pd=Symbol("isFromCache"),ao=Symbol("cancelTimeouts"),gd=Symbol("startedReading"),Xt=Symbol("stopReading"),In=Symbol("triggerRead"),pt=Symbol("body"),Rs=Symbol("jobs"),md=Symbol("originalResponse"),yd=Symbol("retryTimeout");ee.kIsNormalizedAlready=Symbol("isNormalizedAlready");var Lv=M.default.string(process.versions.brotli);ee.withoutBody=new Set(["GET","HEAD"]);ee.knownHookEvents=["init","beforeRequest","beforeRedirect","beforeError","beforeRetry","afterResponse"];function Dv(s){for(let e in s){let t=s[e];if(!M.default.string(t)&&!M.default.number(t)&&!M.default.boolean(t)&&!M.default.null_(t)&&!M.default.undefined(t))throw new TypeError(`The \`searchParams\` value '${String(t)}' must be a string, number, boolean or null`)}}function Uv(s){return M.default.object(s)&&!("statusCode"in s)}var co=new Pv.default,jv=async s=>new Promise((e,t)=>{let i=a=>{t(a)};s.pending||e(),s.once("error",i),s.once("ready",()=>{s.off("error",i),e()})}),qv=new Set([300,301,302,303,304,307,308]),Bv=["context","body","json","form"];ee.setNonEnumerableProperties=(s,e)=>{let t={};for(let i of s)if(i)for(let a of Bv)a in i&&(t[a]={writable:!0,configurable:!0,enumerable:!1,value:i[a]});Object.defineProperties(e,t)};var le=class extends Error{constructor(e,t,i){var a,c;if(super(e),Error.captureStackTrace(this,this.constructor),this.name="RequestError",this.code=(a=t.code)!==null&&a!==void 0?a:"ERR_GOT_REQUEST_ERROR",i instanceof qn?(Object.defineProperty(this,"request",{enumerable:!1,value:i}),Object.defineProperty(this,"response",{enumerable:!1,value:i[Mn]}),Object.defineProperty(this,"options",{enumerable:!1,value:i.options})):Object.defineProperty(this,"options",{enumerable:!1,value:i}),this.timings=(c=this.request)===null||c===void 0?void 0:c.timings,M.default.string(t.stack)&&M.default.string(this.stack)){let u=this.stack.indexOf(this.message)+this.message.length,p=this.stack.slice(u).split(`
35
35
  `).reverse(),g=t.stack.slice(t.stack.indexOf(t.message)+t.message.length).split(`
36
36
  `).reverse();for(;g.length!==0&&g[0]===p[0];)p.shift();this.stack=`${this.stack.slice(0,u)}${p.reverse().join(`
37
37
  `)}${g.reverse().join(`
@@ -42,7 +42,7 @@ Please report this to https://github.com/szmarczak/http2-wrapper/`);S(O)}return}
42
42
  `+D+`
43
43
  `+U+`
44
44
  `;return y.mac=y.mac||Gf(F,f),d.logAction(this.logger,d.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),y}async getAuthParams(){if(this.method=="basic")return{key:this.key};{let r=await this._ensureValidAuthCredentials(!1);if(!r)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:r.token}}}async getAuthHeaders(){if(this.method=="basic")return{authorization:"Basic "+this.basicKey};{let r=await this._ensureValidAuthCredentials(!1);if(!r)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+Bs(r.token)}}}_saveBasicOptions(r){this.method="basic",this.key=r.key,this.basicKey=Bs(r.key),this.authOptions=r||{},"clientId"in r&&this._userSetClientId(r.clientId)}_saveTokenOptions(r,n){this.method="token",r&&(this.tokenParams=r),n&&(n.token&&(n.tokenDetails=typeof n.token=="string"?{token:n.token}:n.token),n.tokenDetails&&(this.tokenDetails=n.tokenDetails),"clientId"in n&&this._userSetClientId(n.clientId),this.authOptions=n)}async _ensureValidAuthCredentials(r){let n=this.tokenDetails;if(n){if(this._tokenClientIdMismatch(n.clientId))throw new x("Mismatch between clientId in token ("+n.clientId+") and current clientId ("+this.clientId+")",40102,403);if(!this.client.isTimeOffsetSet()||!n.expires||n.expires>=this.client.getTimestampUsingOffset())return d.logAction(this.logger,d.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+n.expires),n;d.logAction(this.logger,d.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}let o=(this.waitingForTokenRequest||(this.waitingForTokenRequest=ha.create(this.logger))).createPromise();if(this.currentTokenRequestId!==null&&!r)return o;let l=this.currentTokenRequestId=zf(),h,f=null;try{h=await this.requestToken(this.tokenParams,this.authOptions)}catch(b){f=b}if(this.currentTokenRequestId>l)return d.logAction(this.logger,d.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one"),o;this.currentTokenRequestId=null;let y=this.waitingForTokenRequest;return this.waitingForTokenRequest=null,f?(y?.rejectAll(f),o):(y?.resolveAll(this.tokenDetails=h),o)}_userSetClientId(r){if(typeof r=="string"||r===null){if(r==="*")throw new x('Can\u2019t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);{let n=this._uncheckedSetClientId(r);if(n)throw n}}else throw new x("clientId must be either a string or null",40012,400)}_uncheckedSetClientId(r){if(this._tokenClientIdMismatch(r)){let n="Unexpected clientId mismatch: client has "+this.clientId+", requested "+r,o=new x(n,40102,401);return d.logAction(this.logger,d.LOG_ERROR,"Auth._uncheckedSetClientId()",n),o}else return this.clientId=this.tokenParams.clientId=r,null}_tokenClientIdMismatch(r){return!!(this.clientId&&this.clientId!=="*"&&r&&r!=="*"&&this.clientId!==r)}static isTokenErr(r){return r.code&&r.code>=40140&&r.code<40150}revokeTokens(r,n){return this.client.rest.revokeTokens(r,n)}async _getTimestamp(r){return this.client.getTimestamp(r||!!this.authOptions.queryTime)}},ze=Kf;function sr(r){let n=[];if(r)for(let o in r)n.push(o+"="+r[o]);return n.join("&")}function Tt(r,n){return r+(n?"?":"")+sr(n)}function Jf(r,n,o,l,h){r.error?d.logActionNoStrip(h,d.LOG_MICRO,"Http."+n+"()","Received Error; "+Tt(o,l)+"; Error: "+se(r.error)):d.logActionNoStrip(h,d.LOG_MICRO,"Http."+n+"()","Received; "+Tt(o,l)+"; Headers: "+sr(r.headers)+"; StatusCode: "+r.statusCode+"; Body"+(L.BufferUtils.isBuffer(r.body)?" (Base64): "+L.BufferUtils.base64Encode(r.body):": "+r.body))}function Yf(r,n,o,l,h){h.shouldLog(d.LOG_MICRO)&&d.logActionNoStrip(h,d.LOG_MICRO,"Http."+r+"()","Sending; "+Tt(n,l)+"; Body"+(L.BufferUtils.isBuffer(o)?" (Base64): "+L.BufferUtils.base64Encode(o):": "+o))}var nr=class{constructor(r){this.client=r,this.platformHttp=new L.Http(r),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var r,n;return(n=(r=this.client)==null?void 0:r.logger)!=null?n:d.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}_getHosts(r){let n=r.connection,o=n&&n.connectionManager.host;return o?[o].concat(K.getFallbackHosts(r.options)):K.getHosts(r.options)}async do(r,n,o,l,h){try{let f=this.client;if(!f)return{error:new x("http.do called without client",5e4,500)};let y=typeof n=="function"?n:function(D){return f.baseUri(D)+n},b=f._currentFallback;if(b)if(b.validUntil>Date.now()){let D=await this.doUri(r,y(b.host),o,l,h);return D.error&&this.platformHttp.shouldFallback(D.error)?(f._currentFallback=null,this.do(r,n,o,l,h)):D}else f._currentFallback=null;let A=this._getHosts(f);if(A.length===1)return this.doUri(r,y(A[0]),o,l,h);let I=null,U=async(D,F)=>{let E=D.shift();I=I??new Date;let R=await this.doUri(r,y(E),o,l,h);return R.error&&this.platformHttp.shouldFallback(R.error)&&D.length?Date.now()-I.getTime()>f.options.timeouts.httpMaxRetryDuration?{error:new x(`Timeout for trying fallback hosts retries. Total elapsed time exceeded the ${f.options.timeouts.httpMaxRetryDuration}ms limit`,50003,500)}:U(D,!0):(F&&(f._currentFallback={host:E,validUntil:Date.now()+f.options.timeouts.fallbackRetryTimeout}),R)};return U(A)}catch(f){return{error:new x(`Unexpected error in Http.do: ${se(f)}`,500,5e4)}}}async doUri(r,n,o,l,h){try{Yf(r,n,l,h,this.logger);let f=await this.platformHttp.doUri(r,n,o,l,h);return this.logger.shouldLog(d.LOG_MICRO)&&Jf(f,r,n,h,this.logger),f}catch(f){return{error:new x(`Unexpected error in Http.doUri: ${se(f)}`,500,5e4)}}}};function Qf(r,n,o,l){try{o.apply(n,l)}catch(h){d.logAction(r,d.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+h+"; stack = "+(h&&h.stack))}}function rr(r,n,o){let l,h,f;for(let y=0;y<r.length;y++)if(l=r[y],o&&(l=l[o]),Array.isArray(l)){for(;(h=l.indexOf(n))!==-1;)l.splice(h,1);o&&l.length===0&&delete r[y][o]}else if(Ot(l))for(f in l)Object.prototype.hasOwnProperty.call(l,f)&&Array.isArray(l[f])&&rr([l],n,f)}var Xf=class{constructor(r){this.logger=r,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(...r){if(r.length===1){let n=r[0];if(typeof n=="function")this.any.push(n);else throw new Error("EventListener.on(): Invalid arguments: "+L.Config.inspect(r))}if(r.length===2){let[n,o]=r;if(typeof o!="function")throw new Error("EventListener.on(): Invalid arguments: "+L.Config.inspect(r));if(Ve(n))this.any.push(o);else if(Array.isArray(n))n.forEach(l=>{this.on(l,o)});else{if(typeof n!="string")throw new Error("EventListener.on(): Invalid arguments: "+L.Config.inspect(r));(this.events[n]||(this.events[n]=[])).push(o)}}}off(...r){if(r.length==0||Ve(r[0])&&Ve(r[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}let[n,o]=r,l=null,h=null;if(r.length===1||!o)typeof n=="function"?l=n:h=n;else{if(typeof o!="function")throw new Error("EventEmitter.off(): invalid arguments:"+L.Config.inspect(r));[h,l]=[n,o]}if(l&&Ve(h)){rr([this.any,this.events,this.anyOnce,this.eventsOnce],l);return}if(Array.isArray(h)){h.forEach(f=>{this.off(f,l)});return}if(typeof h!="string")throw new Error("EventEmitter.off(): invalid arguments:"+L.Config.inspect(r));l?rr([this.events,this.eventsOnce],l,h):(delete this.events[h],delete this.eventsOnce[h])}listeners(r){if(r){let n=this.events[r]||[];return this.eventsOnce[r]&&Array.prototype.push.apply(n,this.eventsOnce[r]),n.length?n:null}return this.any.length?this.any:null}emit(r,...n){let o={event:r},l=[];this.anyOnce.length&&(Array.prototype.push.apply(l,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(l,this.any);let h=this.eventsOnce[r];h&&(Array.prototype.push.apply(l,h),delete this.eventsOnce[r]);let f=this.events[r];f&&Array.prototype.push.apply(l,f),l.forEach(y=>{Qf(this.logger,o,y,n)})}once(...r){let n=r.length;if(n===0||n===1&&typeof r[0]!="function"){let h=r[0];return new Promise(f=>{this.once(h,f)})}let[o,l]=r;if(r.length===1&&typeof o=="function")this.anyOnce.push(o);else if(Ve(o)){if(typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));this.anyOnce.push(l)}else if(Array.isArray(o)){let h=this,f=function(){let y=Array.prototype.slice.call(arguments);if(o.forEach(function(b){h.off(b,f)}),typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));l.apply(this,y)};o.forEach(function(y){h.on(y,f)})}else{if(typeof o!="string")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));let h=this.eventsOnce[o]||(this.eventsOnce[o]=[]);if(l){if(typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));h.push(l)}}}async whenState(r,n){if(typeof r!="string"||typeof n!="string")throw new Error("whenState requires a valid state String argument");return r===n?null:this.once(r)}},fe=Xf,z={HEARTBEAT:0,ACK:1,NACK:2,CONNECT:3,CONNECTED:4,DISCONNECT:5,DISCONNECTED:6,CLOSE:7,CLOSED:8,ERROR:9,ATTACH:10,ATTACHED:11,DETACH:12,DETACHED:13,PRESENCE:14,MESSAGE:15,SYNC:16,AUTH:17,ACTIVATE:18,OBJECT:19,OBJECT_SYNC:20,ANNOTATION:21},_a=[];Object.keys(z).forEach(function(r){_a[z[r]]=r});var Ee={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,HAS_OBJECTS:128,PRESENCE:65536,PUBLISH:1<<17,SUBSCRIBE:1<<18,PRESENCE_SUBSCRIBE:1<<19,ANNOTATION_PUBLISH:1<<21,ANNOTATION_SUBSCRIBE:1<<22,OBJECT_SUBSCRIBE:1<<24,OBJECT_PUBLISH:1<<25},Zf=Object.keys(Ee);Ee.MODE_ALL=Ee.PRESENCE|Ee.PUBLISH|Ee.SUBSCRIBE|Ee.PRESENCE_SUBSCRIBE|Ee.ANNOTATION_PUBLISH|Ee.ANNOTATION_SUBSCRIBE|Ee.OBJECT_SUBSCRIBE|Ee.OBJECT_PUBLISH;var ba=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function ep(r){return!r||!r.channelOptions?{channelOptions:r,plugins:{},baseEncodedPreviousPayload:void 0}:r}function va(r,n,o){if(o&&o.cipher){r||me("Crypto");let l=r.getCipher(o.cipher,n);return{cipher:l.cipherParams,channelCipher:l.cipher}}return o??{}}async function tp(r,n){let{data:o,encoding:l}=await wa(r.data,r.encoding,n);return r.data=o,r.encoding=l,r}async function wa(r,n,o){let l=o.channelCipher,h=r,f=n?n+"/":"";L.BufferUtils.isBuffer(h)||(h=L.BufferUtils.utf8Encode(String(h)),f=f+"utf-8/");let y=await l.encrypt(h);return f=f+"cipher+"+l.algorithm,{data:y,encoding:f}}async function ir(r,n){let{data:o,encoding:l}=Ca(r.data,r.encoding);return r.data=o,r.encoding=l,n!=null&&n.cipher?tp(r,n):r}function Ca(r,n){if(typeof r=="string"||L.BufferUtils.isBuffer(r)||r===null||r===void 0)return{data:r,encoding:n};if(Ot(r)||Array.isArray(r))return{data:JSON.stringify(r),encoding:n?n+"/json":"json"};throw new x("Data type is unsupported",40013,400)}async function or(r,n){let{data:o,encoding:l,error:h}=await Ea(r.data,r.encoding,n);if(r.data=o,r.encoding=l,h)throw h}async function Ea(r,n,o){let l=ep(o),h=r,f=r,y=n,b;if(n){let A=n.split("/"),I,U=A.length,D="";try{for(;(I=U)>0;){let F=A[--U].match(/([-\w]+)(\+([\w-]+))?/);if(!F)break;switch(D=F[1],D){case"base64":f=L.BufferUtils.base64Decode(String(f)),I==A.length&&(h=f);continue;case"utf-8":f=L.BufferUtils.utf8Decode(f);continue;case"json":f=JSON.parse(f);continue;case"cipher":if(l.channelOptions!=null&&l.channelOptions.cipher&&l.channelOptions.channelCipher){let E=F[3],R=l.channelOptions.channelCipher;if(E!=R.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");f=await R.decrypt(f);continue}else throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!l.plugins||!l.plugins.vcdiff)throw new x("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if(typeof Uint8Array>"u")throw new x("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{let E=l.baseEncodedPreviousPayload;typeof E=="string"&&(E=L.BufferUtils.utf8Encode(E));let R=L.BufferUtils.toBuffer(E);f=L.BufferUtils.toBuffer(f),f=L.BufferUtils.arrayBufferViewToBuffer(l.plugins.vcdiff.decode(f,R)),h=f}catch(E){throw new x("Vcdiff delta decode failed with "+E,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(F){let E=F;b=new x(`Error processing the ${D} encoding, decoder returned \u2018${E.message}\u2019`,E.code||40013,400)}finally{y=I<=0?null:A.slice(0,I).join("/")}}return b?{error:b,data:f,encoding:y}:(l.baseEncodedPreviousPayload=h,{data:f,encoding:y})}function ar(...r){let n=r.length>0?"json":"msgpack",{data:o,encoding:l}=ka(this.data,this.encoding,n);return Object.assign({},this,{encoding:l,data:o})}function ka(r,n,o){return!r||!L.BufferUtils.isBuffer(r)?{data:r,encoding:n}:o==="msgpack"?{data:L.BufferUtils.toBuffer(r),encoding:n}:{data:L.BufferUtils.base64Encode(r),encoding:n?n+"/base64":"base64"}}var Hs={encryptData:wa,encodeData:Ca,encodeDataForWire:ka,decodeData:Ea};function Gs(r){let{id:n,connectionId:o,timestamp:l}=r,h;switch(r.action){case z.MESSAGE:{h=r.messages;break}case z.PRESENCE:case z.SYNC:h=r.presence;break;case z.ANNOTATION:h=r.annotations;break;case z.OBJECT:case z.OBJECT_SYNC:h=r.state;break;default:throw new x("Unexpected action "+r.action,4e4,400)}for(let f=0;f<h.length;f++){let y=h[f];y.connectionId||(y.connectionId=o),y.timestamp||(y.timestamp=l),n&&!y.id&&(y.id=n+":"+f)}}function St(r,n){let o="["+n;for(let l in r)l==="data"?typeof r.data=="string"?o+="; data="+r.data:L.BufferUtils.isBuffer(r.data)?o+="; data (buffer)="+L.BufferUtils.base64Encode(r.data):typeof r.data<"u"&&(o+="; data (json)="+JSON.stringify(r.data)):l&&(l==="extras"||l==="operation")?o+="; "+l+"="+JSON.stringify(r[l]):l==="version"?o+="; version="+JSON.stringify(r[l]):l==="annotations"?o+="; annotations="+JSON.stringify(r[l]):r[l]!==void 0&&(o+="; "+l+"="+r[l]);return o+="]",o}var At=class{},Oa=class{constructor(r){this.Platform=L,this.ErrorInfo=x,this.Logger=d,this.Defaults=K,this.Utils=ts,this.EventEmitter=fe,this.MessageEncoding=Hs;var n,o,l,h,f,y,b,A,I,U;this._additionalHTTPRequestImplementations=(n=r.plugins)!=null?n:null,this.logger=new d,this.logger.setLog(r.logLevel,r.logHandler),d.logAction(this.logger,d.LOG_MICRO,"BaseClient()","initialized with clientOptions "+L.Config.inspect(r)),this._MsgPack=(l=(o=r.plugins)==null?void 0:o.MsgPack)!=null?l:null;let D=this.options=K.normaliseOptions(r,this._MsgPack,this.logger);if(D.key){let F=D.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!F){let E="invalid key parameter";throw d.logAction(this.logger,d.LOG_ERROR,"BaseClient()",E),new x(E,40400,404)}D.keyName=F[1],D.keySecret=F[2]}if("clientId"in D)if(typeof D.clientId=="string"||D.clientId===null){if(D.clientId==="*")throw new x('Can\u2019t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}else throw new x("clientId must be either a string or null",40012,400);d.logAction(this.logger,d.LOG_MINOR,"BaseClient()","started; version = "+K.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new nr(this),this.auth=new ze(this,D),this._rest=(h=r.plugins)!=null&&h.Rest?new r.plugins.Rest(this):null,this._Crypto=(y=(f=r.plugins)==null?void 0:f.Crypto)!=null?y:null,this.__FilteredSubscriptions=(A=(b=r.plugins)==null?void 0:b.MessageInteractions)!=null?A:null,this._Annotations=(U=(I=r.plugins)==null?void 0:I.Annotations)!=null?U:null}get rest(){return this._rest||me("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||me("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}device(){var r;return(!((r=this.options.plugins)!=null&&r.Push)||!this.push.LocalDevice)&&me("Push"),this._device||(this._device=this.push.LocalDevice.load(this)),this._device}baseUri(r){return K.getHttpScheme(this.options)+r+":"+K.getPort(this.options,!1)}async stats(r){return this.rest.stats(r)}async time(r){return this.rest.time(r)}async request(r,n,o,l,h,f){return this.rest.request(r,n,o,l,h,f)}batchPublish(r){return this.rest.batchPublish(r)}batchPresence(r){return this.rest.batchPresence(r)}setLog(r){this.logger.setLog(r.level,r.handler)}async getTimestamp(r){return!this.isTimeOffsetSet()&&r?this.time():this.getTimestampUsingOffset()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return this.serverTimeOffset!==null}};Oa.Platform=L;var Ta=Oa,sp=class Zt{toJSON(){var n,o,l;return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:(n=this.push)==null?void 0:n.recipient,state:(o=this.push)==null?void 0:o.state,error:(l=this.push)==null?void 0:l.error}}}toString(){var n,o,l,h;let f="[DeviceDetails";return this.id&&(f+="; id="+this.id),this.platform&&(f+="; platform="+this.platform),this.formFactor&&(f+="; formFactor="+this.formFactor),this.clientId&&(f+="; clientId="+this.clientId),this.metadata&&(f+="; metadata="+this.metadata),this.deviceIdentityToken&&(f+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),(n=this.push)!=null&&n.recipient&&(f+="; push.recipient="+JSON.stringify(this.push.recipient)),(o=this.push)!=null&&o.state&&(f+="; push.state="+this.push.state),(l=this.push)!=null&&l.error&&(f+="; push.error="+JSON.stringify(this.push.error)),(h=this.push)!=null&&h.metadata&&(f+="; push.metadata="+this.push.metadata),f+="]",f}static toRequestBody(n,o,l){return je(n,o,l)}static fromResponseBody(n,o,l){return l&&(n=de(n,o,l)),Array.isArray(n)?Zt.fromValuesArray(n):Zt.fromValues(n)}static fromValues(n){return n.error=n.error&&x.fromValues(n.error),Object.assign(new Zt,n)}static fromLocalDevice(n){return Object.assign(new Zt,n)}static fromValuesArray(n){let o=n.length,l=new Array(o);for(let h=0;h<o;h++)l[h]=Zt.fromValues(n[h]);return l}},Rt=sp;async function Sa(r,n,o,l){if(r.http.supportsAuthHeaders){let h=await r.auth.getAuthHeaders();return l(J(h,n),o)}else{let h=await r.auth.getAuthParams();return l(n,J(h,o))}}function np(r,n,o){if(r.err&&!r.body)return{err:r.err};if(r.statusCode===is.NoContent)return k(O({},r),{body:[],unpacked:!0});let l=r.body;if(!r.unpacked)try{l=de(l,n,o)}catch(b){return Qn(b)?{err:b}:{err:new Te(se(b),null)}}if(!l)return{err:new Te("unenvelope(): Response body is missing",null)};let{statusCode:h,response:f,headers:y}=l;if(h===void 0)return k(O({},r),{body:l,unpacked:!0});if(h<200||h>=300){let b=f&&f.error||r.err;return b||(b=new Error("Error in unenveloping "+l),b.statusCode=h),{err:b,body:f,headers:y,unpacked:!0,statusCode:h}}return{err:r.err,body:f,headers:y,unpacked:!0,statusCode:h}}function rp(r,n,o,l,h){r.err?d.logAction(h,d.LOG_MICRO,"Resource."+n+"()","Received Error; "+Tt(o,l)+"; Error: "+se(r.err)):d.logAction(h,d.LOG_MICRO,"Resource."+n+"()","Received; "+Tt(o,l)+"; Headers: "+sr(r.headers)+"; StatusCode: "+r.statusCode+"; Body: "+(L.BufferUtils.isBuffer(r.body)?" (Base64): "+L.BufferUtils.base64Encode(r.body):": "+L.Config.inspect(r.body)))}var ip=class es{static async get(n,o,l,h,f,y){return es.do(ue.Get,n,o,null,l,h,f,y??!1)}static async delete(n,o,l,h,f,y){return es.do(ue.Delete,n,o,null,l,h,f,y)}static async post(n,o,l,h,f,y,b){return es.do(ue.Post,n,o,l,h,f,y,b)}static async patch(n,o,l,h,f,y,b){return es.do(ue.Patch,n,o,l,h,f,y,b)}static async put(n,o,l,h,f,y,b){return es.do(ue.Put,n,o,l,h,f,y,b)}static async do(n,o,l,h,f,y,b,A){b&&((y=y||{}).envelope=b);let I=o.logger;async function U(F,E){var R;if(I.shouldLog(d.LOG_MICRO)){let j=h;if(((R=F["content-type"])==null?void 0:R.indexOf("msgpack"))>0)try{o._MsgPack||me("MsgPack"),j=o._MsgPack.decode(h)}catch(H){d.logAction(I,d.LOG_MICRO,"Resource."+n+"()","Sending MsgPack Decoding Error: "+se(H))}d.logAction(I,d.LOG_MICRO,"Resource."+n+"()","Sending; "+Tt(l,E)+"; Body: "+j)}let P=await o.http.do(n,l,F,h,E);return P.error&&ze.isTokenErr(P.error)?(await o.auth.authorize(null,null),Sa(o,F,E,U)):{err:P.error,body:P.body,headers:P.headers,unpacked:P.unpacked,statusCode:P.statusCode}}let D=await Sa(o,f,y,U);if(b&&(D=np(D,o._MsgPack,b)),I.shouldLog(d.LOG_MICRO)&&rp(D,n,l,y,I),A){if(D.err)throw D.err;{let F=O({},D);return delete F.err,F}}return D}},ae=ip;function op(r){let n=r.match(/^\.\/(\w+)\?(.*)$/);return n&&n[2]&&qs(n[2])}function ap(r){typeof r=="string"&&(r=r.split(","));let n={};for(let o=0;o<r.length;o++){let l=r[o].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(l){let h=op(l[1]);h&&(n[l[2]]=h)}}return n}function cp(r,n,o){return!(o&&(n||typeof r.code=="number"))}var lp=class{constructor(r,n,o,l,h,f){this.client=r,this.path=n,this.headers=o,this.envelope=l??null,this.bodyHandler=h,this.useHttpPaginatedResponse=f||!1}get logger(){return this.client.logger}async get(r){let n=await ae.get(this.client,this.path,this.headers,r,this.envelope,!1);return this.handlePage(n)}async delete(r){let n=await ae.delete(this.client,this.path,this.headers,r,this.envelope,!1);return this.handlePage(n)}async post(r,n){let o=await ae.post(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async put(r,n){let o=await ae.put(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async patch(r,n){let o=await ae.patch(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async handlePage(r){if(r.err&&cp(r.err,r.body,this.useHttpPaginatedResponse))throw d.logAction(this.logger,d.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+se(r.err)),r.err;let n,o,l;try{n=r.statusCode==is.NoContent?[]:await this.bodyHandler(r.body,r.headers||{},r.unpacked)}catch(h){throw r.err||h}return r.headers&&(o=r.headers.Link||r.headers.link)&&(l=ap(o)),this.useHttpPaginatedResponse?new up(this,n,r.headers||{},r.statusCode,l,r.err):new Aa(this,n,l)}},Aa=class{constructor(r,n,o){this.resource=r,this.items=n,this._relParams=o}async first(){if(this.hasFirst())return this.get(this._relParams.first);throw new x("No link to the first page of results",40400,404)}async current(){if(this.hasCurrent())return this.get(this._relParams.current);throw new x("No link to the current page of results",40400,404)}async next(){return this.hasNext()?this.get(this._relParams.next):null}hasFirst(){return this._relParams!=null&&"first"in this._relParams}hasCurrent(){return this._relParams!=null&&"current"in this._relParams}hasNext(){return this._relParams!=null&&"next"in this._relParams}isLast(){return!this.hasNext()}async get(r){let n=this.resource,o=await ae.get(n.client,n.path,n.headers,r,n.envelope,!1);return n.handlePage(o)}},up=class extends Aa{constructor(r,n,o,l,h,f){super(r,n,h),this.statusCode=l,this.success=l<300&&l>=200,this.headers=o,this.errorCode=f&&f.code,this.errorMessage=f&&f.message}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage}}},Be=lp,Ra=class Ns{toJSON(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}}toString(){let n="[PushChannelSubscription";return this.channel&&(n+="; channel="+this.channel),this.deviceId&&(n+="; deviceId="+this.deviceId),this.clientId&&(n+="; clientId="+this.clientId),n+="]",n}static fromResponseBody(n,o,l){return l&&(n=de(n,o,l)),Array.isArray(n)?Ns.fromValuesArray(n):Ns.fromValues(n)}static fromValues(n){return Object.assign(new Ns,n)}static fromValuesArray(n){let o=n.length,l=new Array(o);for(let h=0;h<o;h++)l[h]=Ns.fromValues(n[h]);return l}};Ra.toRequestBody=je;var hp=Ra,Fs=hp,dp=class{constructor(r){var n;this.client=r,this.admin=new fp(r),L.Config.push&&((n=r.options.plugins)!=null&&n.Push)&&(this.stateMachine=new r.options.plugins.Push.ActivationStateMachine(r),this.LocalDevice=r.options.plugins.Push.localDeviceFactory(Rt))}async activate(r,n){await new Promise((o,l)=>{var h;if(!((h=this.client.options.plugins)!=null&&h.Push)){l(rs("Push"));return}if(!this.stateMachine){l(new x("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.activatedCallback){l(new x("Activation already in progress",4e4,400));return}this.stateMachine.activatedCallback=f=>{if(f){l(f);return}o()},this.stateMachine.updateFailedCallback=n,this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledActivate(this.stateMachine,r))})}async deactivate(r){await new Promise((n,o)=>{var l;if(!((l=this.client.options.plugins)!=null&&l.Push)){o(rs("Push"));return}if(!this.stateMachine){o(new x("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.deactivatedCallback){o(new x("Deactivation already in progress",4e4,400));return}this.stateMachine.deactivatedCallback=h=>{if(h){o(h);return}n()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,r))})}},fp=class{constructor(r){this.client=r,this.deviceRegistrations=new pp(r),this.channelSubscriptions=new gp(r)}async publish(r,n){let o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",h=K.defaultPostHeaders(o.options),f={},y=J({recipient:r},n);J(h,o.options.headers),o.options.pushFullWait&&J(f,{fullWait:"true"});let b=je(y,o._MsgPack,l);await ae.post(o,"/push/publish",b,h,f,null,!0)}},pp=class{constructor(r){this.client=r}async save(r){let n=this.client,o=Rt.fromValues(r),l=n.options.useBinaryProtocol?"msgpack":"json",h=K.defaultPostHeaders(n.options),f={};J(h,n.options.headers),n.options.pushFullWait&&J(f,{fullWait:"true"});let y=je(o,n._MsgPack,l),b=await ae.put(n,"/push/deviceRegistrations/"+encodeURIComponent(r.id),y,h,f,null,!0);return Rt.fromResponseBody(b.body,n._MsgPack,b.unpacked?void 0:l)}async get(r){let n=this.client,o=n.options.useBinaryProtocol?"msgpack":"json",l=K.defaultGetHeaders(n.options),h=r.id||r;if(typeof h!="string"||!h.length)throw new x("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);J(l,n.options.headers);let f=await ae.get(n,"/push/deviceRegistrations/"+encodeURIComponent(h),l,{},null,!0);return Rt.fromResponseBody(f.body,n._MsgPack,f.unpacked?void 0:o)}async list(r){let n=this.client,o=n.options.useBinaryProtocol?"msgpack":"json",l=this.client.http.supportsLinkHeaders?void 0:o,h=K.defaultGetHeaders(n.options);return J(h,n.options.headers),new Be(n,"/push/deviceRegistrations",h,l,async function(f,y,b){return Rt.fromResponseBody(f,n._MsgPack,b?void 0:o)}).get(r)}async remove(r){let n=this.client,o=K.defaultGetHeaders(n.options),l={},h=r.id||r;if(typeof h!="string"||!h.length)throw new x("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);J(o,n.options.headers),n.options.pushFullWait&&J(l,{fullWait:"true"}),await ae.delete(n,"/push/deviceRegistrations/"+encodeURIComponent(h),o,l,null,!0)}async removeWhere(r){let n=this.client,o=n.options.useBinaryProtocol?"msgpack":"json",l=K.defaultGetHeaders(n.options,{format:o});J(l,n.options.headers),n.options.pushFullWait&&J(r,{fullWait:"true"}),await ae.delete(n,"/push/deviceRegistrations",l,r,null,!0)}},gp=class jd{constructor(n){this.remove=jd.prototype.removeWhere,this.client=n}async save(n){let o=this.client,l=Fs.fromValues(n),h=o.options.useBinaryProtocol?"msgpack":"json",f=K.defaultPostHeaders(o.options),y={};J(f,o.options.headers),o.options.pushFullWait&&J(y,{fullWait:"true"});let b=je(l,o._MsgPack,h),A=await ae.post(o,"/push/channelSubscriptions",b,f,y,null,!0);return Fs.fromResponseBody(A.body,o._MsgPack,A.unpacked?void 0:h)}async list(n){let o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",h=this.client.http.supportsLinkHeaders?void 0:l,f=K.defaultGetHeaders(o.options);return J(f,o.options.headers),new Be(o,"/push/channelSubscriptions",f,h,async function(y,b,A){return Fs.fromResponseBody(y,o._MsgPack,A?void 0:l)}).get(n)}async removeWhere(n){let o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",h=K.defaultGetHeaders(o.options,{format:l});J(h,o.options.headers),o.options.pushFullWait&&J(n,{fullWait:"true"}),await ae.delete(o,"/push/channelSubscriptions",h,n,null,!0)}async listChannels(n){let o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",h=this.client.http.supportsLinkHeaders?void 0:l,f=K.defaultGetHeaders(o.options);return J(f,o.options.headers),o.options.pushFullWait&&J(n,{fullWait:"true"}),new Be(o,"/push/channels",f,h,async function(y,b,A){let I=!A&&l?de(y,o._MsgPack,l):y;for(let U=0;U<I.length;U++)I[U]=String(I[U]);return I}).get(n)}},mp=dp,Pa=["absent","present","enter","leave","update"];async function Ia(r,n,o,l){let h=va(n,r,l??null);return os.fromValues(o).decode(h,r)}async function yp(r,n,o,l){return Promise.all(o.map(function(h){return Ia(r,n,h,l)}))}async function _p(r,n){return os.fromValues(r).decode(n.channelOptions,n.logger)}async function Ma(r,n){return Promise.all(r.map(function(o){return _p(o,n)}))}var xa=class Ls extends At{isSynthesized(){return!this.id||!this.connectionId?!0:this.id.substring(this.connectionId.length,0)!==this.connectionId}parseId(){if(!this.id)throw new Error("parseId(): Presence message does not contain an id");let n=this.id.split(":");return{connectionId:n[0],msgSerial:parseInt(n[1],10),index:parseInt(n[2],10)}}async encode(n){let o=Object.assign(new os,this,{action:Pa.indexOf(this.action||"present")});return ir(o,n)}static fromValues(n){return Object.assign(new Ls,n)}static fromValuesArray(n){return n.map(o=>Ls.fromValues(o))}static fromData(n){return n instanceof Ls?n:Ls.fromValues({data:n})}toString(){return St(this,"PresenceMessage")}},os=class vo extends At{toJSON(...n){return ar.call(this,...n)}static fromValues(n){return Object.assign(new vo,n)}static fromValuesArray(n){return n.map(o=>vo.fromValues(o))}async decode(n,o){let l=Object.assign(new xa,k(O({},this),{action:Pa[this.action]}));try{await or(l,n)}catch(h){d.logAction(o,d.LOG_ERROR,"WirePresenceMessage.decode()",se(h))}return l}toString(){return St(this,"WirePresenceMessage")}},Ke=xa,bp=class{constructor(r){this.channel=r}get logger(){return this.channel.logger}async get(r){d.logAction(this.logger,d.LOG_MICRO,"RestPresence.get()","channel = "+this.channel.name);let n=this.channel.client,o=n.options.useBinaryProtocol?"msgpack":"json",l=this.channel.client.http.supportsLinkHeaders?void 0:o,h=K.defaultGetHeaders(n.options);return J(h,n.options.headers),new Be(n,this.channel.client.rest.presenceMixin.basePath(this),h,l,async(f,y,b)=>{let A=b?f:de(f,n._MsgPack,o);return Ma(A,this.channel)}).get(r)}async history(r){return d.logAction(this.logger,d.LOG_MICRO,"RestPresence.history()","channel = "+this.channel.name),this.channel.client.rest.presenceMixin.history(this,r)}},vp=bp,Na=["message.create","message.update","message.delete","meta","message.summary","message.append"];function wp(r){return Na[r||0]||"unknown"}function Cp(r){let n=0;return r.name&&(n+=r.name.length),r.clientId&&(n+=r.clientId.length),r.extras&&(n+=JSON.stringify(r.extras).length),r.data&&(n+=Wo(r.data)),n}async function La(r,n,o,l){let h=va(n,r,l??null);return as.fromValues(o).decode(h,r)}async function Ep(r,n,o,l){return Promise.all(o.map(function(h){return La(r,n,h,l)}))}async function Da(r,n){return as.fromValues(r).decode(n.channelOptions,n.logger)}async function Ua(r,n){return Promise.all(r.map(function(o){return Da(o,n)}))}async function ja(r,n){return Promise.all(r.map(o=>o.encode(n)))}var qa=je;function Ba(r){let n,o=0;for(let l=0;l<r.length;l++)n=r[l],o+=n.size||(n.size=Cp(n));return o}var $a=class wo extends At{expandFields(){if(this.version||(this.version={}),!this.version.serial&&this.serial&&(this.version.serial=this.serial),!this.version.timestamp&&this.timestamp&&(this.version.timestamp=this.timestamp),this.annotations?this.annotations.summary||(this.annotations.summary={}):this.annotations={summary:{}},this.annotations&&this.annotations.summary)for(let[n,o]of Object.entries(this.annotations.summary))if(n.endsWith(":distinct.v1")||n.endsWith(":unique.v1")||n.endsWith(":multiple.v1"))for(let[,l]of Object.entries(o))l.clipped||(l.clipped=!1);else n.endsWith(":flag.v1")&&(o.clipped||(o.clipped=!1))}async encode(n){let o=Object.assign(new as,this,{action:Na.indexOf(this.action||"message.create")});return ir(o,n)}static fromValues(n){return Object.assign(new wo,n)}static fromValuesArray(n){return n.map(o=>wo.fromValues(o))}toString(){return St(this,"Message")}},as=class Co extends At{toJSON(...n){return ar.call(this,...n)}static fromValues(n){return Object.assign(new Co,n)}static fromValuesArray(n){return n.map(o=>Co.fromValues(o))}async decodeWithErr(n,o){let l=Object.assign(new $a,k(O({},this),{action:wp(this.action)})),h;try{await or(l,n)}catch(f){d.logAction(o,d.LOG_ERROR,"WireMessage.decode()",se(f)),h=f}return l.expandFields(),{decoded:l,err:h}}async decode(n,o){let{decoded:l}=await this.decodeWithErr(n,o);return l}toString(){return St(this,"WireMessage")}},Ge=$a,kp=9;function Op(r){return r.every(function(n){return!n.id})}var Tp=class{constructor(r,n,o){this._annotations=null;var l,h;d.logAction(r.logger,d.LOG_MINOR,"RestChannel()","started; name = "+n),this.name=n,this.client=r,this.presence=new vp(this),this.channelOptions=$s((l=r._Crypto)!=null?l:null,this.logger,o),(h=r.options.plugins)!=null&&h.Push&&(this._push=new r.options.plugins.Push.PushChannel(this)),r._Annotations&&(this._annotations=new r._Annotations.RestAnnotations(this))}get annotations(){return this._annotations||me("Annotations"),this._annotations}get push(){return this._push||me("Push"),this._push}get logger(){return this.client.logger}setOptions(r){var n;this.channelOptions=$s((n=this.client._Crypto)!=null?n:null,this.logger,r)}async history(r){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.history()","channel = "+this.name),this.client.rest.channelMixin.history(this,r)}async publish(...r){let n=r[0],o=r[1],l,h;if(typeof n=="string"||n===null)l=[Ge.fromValues({name:n,data:o})],h=r[2];else if(Ot(n))l=[Ge.fromValues(n)],h=r[1];else if(Array.isArray(n))l=Ge.fromValuesArray(n),h=r[1];else throw new x("The single-argument form of publish() expects a message object or an array of message objects",40013,400);h||(h={});let f=this.client,y=f.options,b=y.useBinaryProtocol?"msgpack":"json",A=f.options.idempotentRestPublishing,I=K.defaultPostHeaders(f.options);if(J(I,y.headers),A&&Op(l)){let E=await zo(kp);l.forEach(function(R,P){R.id=E+":"+P.toString()})}let U=await ja(l,this.channelOptions),D=Ba(U),F=y.maxMessageSize;if(D>F)throw new x(`Maximum size of messages that can be published at once exceeded (was ${D} bytes; limit is ${F} bytes)`,40009,400);return this._publish(qa(U,f._MsgPack,b),I,h)}async _publish(r,n,o){let l=this.client,h=l.options.useBinaryProtocol?"msgpack":"json",{body:f,unpacked:y}=await ae.post(l,l.rest.channelMixin.basePath(this)+"/messages",r,n,o,null,!0),b=(y?f:de(f,l._MsgPack,h))||{};return delete b.channel,delete b.messageId,b}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(r){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,r)}async updateMessage(r,n,o){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.updateMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.update",r,n,o)}async deleteMessage(r,n,o){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.deleteMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.delete",r,n,o)}async appendMessage(r,n,o){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.appendMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.append",r,n,o)}async getMessageVersions(r,n){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,r,n)}},Sp=Tp,Ap=class qd{constructor(n){this.entries=n&&n.entries||void 0,this.schema=n&&n.schema||void 0,this.appId=n&&n.appId||void 0,this.inProgress=n&&n.inProgress||void 0,this.unit=n&&n.unit||void 0,this.intervalId=n&&n.intervalId||void 0}static fromValues(n){return new qd(n)}},Rp=Ap,Ha=class{static basePath(r){return"/channels/"+encodeURIComponent(r.name)}static history(r,n){let o=r.client,l=o.options.useBinaryProtocol?"msgpack":"json",h=r.client.http.supportsLinkHeaders?void 0:l,f=K.defaultGetHeaders(o.options);return J(f,o.options.headers),new Be(o,this.basePath(r)+"/messages",f,h,async function(y,b,A){let I=A?y:de(y,o._MsgPack,l);return Ua(I,r)}).get(n)}static async status(r){let n=r.client.options.useBinaryProtocol?"msgpack":"json",o=K.defaultPostHeaders(r.client.options);return(await ae.get(r.client,this.basePath(r),o,{},n,!0)).body}static async getMessage(r,n){let o=typeof n=="string"?n:n.serial;if(!o)throw new x('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let l=r.client,h=l.options.useBinaryProtocol?"msgpack":"json",f=K.defaultGetHeaders(l.options);J(f,l.options.headers);let{body:y,unpacked:b}=await ae.get(l,this.basePath(r)+"/messages/"+encodeURIComponent(o),f,{},null,!0),A=b?y:de(y,l._MsgPack,h);return Da(A,r)}static async updateDeleteMessage(r,n,o,l,h){if(!o.serial)throw new x('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let f=r.client,y=f.options.useBinaryProtocol?"msgpack":"json",b=K.defaultPostHeaders(f.options);J(b,f.options.headers);let A=Ge.fromValues(o);A.action=n,A.version=l;let I=await A.encode(r.channelOptions),U=qa(I,f._MsgPack,y),D=ae.patch,{body:F,unpacked:E}=await D(f,this.basePath(r)+"/messages/"+encodeURIComponent(o.serial),U,b,h||{},null,!0);return(E?F:de(F,f._MsgPack,y))||{versionSerial:null}}static getMessageVersions(r,n,o){let l=typeof n=="string"?n:n.serial;if(!l)throw new x('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let h=r.client,f=h.options.useBinaryProtocol?"msgpack":"json",y=r.client.http.supportsLinkHeaders?void 0:f,b=K.defaultGetHeaders(h.options);return J(b,h.options.headers),new Be(h,this.basePath(r)+"/messages/"+encodeURIComponent(l)+"/versions",b,y,async(A,I,U)=>{let D=U?A:de(A,h._MsgPack,f);return Ua(D,r)}).get(o||{})}},Pp=class{static basePath(r){return Ha.basePath(r.channel)+"/presence"}static async history(r,n){let o=r.channel.client,l=o.options.useBinaryProtocol?"msgpack":"json",h=r.channel.client.http.supportsLinkHeaders?void 0:l,f=K.defaultGetHeaders(o.options);return J(f,o.options.headers),new Be(o,this.basePath(r)+"/history",f,h,async(y,b,A)=>{let I=A?y:de(y,o._MsgPack,l);return Ma(I,r.channel)}).get(n)}},Ga=class{constructor(r){this.channelMixin=Ha,this.presenceMixin=Pp,this.Resource=ae,this.PaginatedResource=Be,this.DeviceDetails=Rt,this.PushChannelSubscription=Fs,this.client=r,this.channels=new Ip(this.client),this.push=new mp(this.client)}async stats(r){let n=K.defaultGetHeaders(this.client.options),o=this.client.options.useBinaryProtocol?"msgpack":"json",l=this.client.http.supportsLinkHeaders?void 0:o;return J(n,this.client.options.headers),new Be(this.client,"/stats",n,l,async(h,f,y)=>{let b=y?h:de(h,this.client._MsgPack,o);for(let A=0;A<b.length;A++)b[A]=Rp.fromValues(b[A]);return b}).get(r)}async time(r){let n=K.defaultGetHeaders(this.client.options,{format:"json"});this.client.options.headers&&J(n,this.client.options.headers);let o=b=>this.client.baseUri(b)+"/time",{error:l,body:h,unpacked:f}=await this.client.http.do(ue.Get,o,n,null,r);if(l)throw l;f||(h=JSON.parse(h));let y=h[0];if(!y)throw new x("Internal error (unexpected result type from GET /time)",5e4,500);return this.client.serverTimeOffset=y-Date.now(),y}async request(r,n,o,l,h,f){var y;let[b,A,I]=this.client.options.useBinaryProtocol?(this.client._MsgPack||me("MsgPack"),[this.client._MsgPack.encode,this.client._MsgPack.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],U=this.client.http.supportsLinkHeaders?void 0:I;l=l||{};let D=r.toLowerCase(),F=D=="get"?K.defaultGetHeaders(this.client.options,{format:I,protocolVersion:o}):K.defaultPostHeaders(this.client.options,{format:I,protocolVersion:o});typeof h!="string"&&(h=(y=b(h))!=null?y:null),J(F,this.client.options.headers),f&&J(F,f);let E=new Be(this.client,n,F,U,async function(R,P,j){return Lo(j?R:A(R))},!0);if(!L.Http.methods.includes(D))throw new x("Unsupported method "+D,40500,405);return L.Http.methodsWithBody.includes(D)?E[D](l,h):E[D](l)}async batchPublish(r){let n,o;Array.isArray(r)?(n=r,o=!1):(n=[r],o=!0);let l=this.client.options.useBinaryProtocol?"msgpack":"json",h=K.defaultPostHeaders(this.client.options);this.client.options.headers&&J(h,this.client.options.headers);let f=je(n,this.client._MsgPack,l),y=await ae.post(this.client,"/messages",f,h,{},null,!0),b=y.unpacked?y.body:de(y.body,this.client._MsgPack,l);return o?b[0]:b}async batchPresence(r){let n=this.client.options.useBinaryProtocol?"msgpack":"json",o=K.defaultGetHeaders(this.client.options);this.client.options.headers&&J(o,this.client.options.headers);let l=r.join(","),h=await ae.get(this.client,"/presence",o,{channels:l},null,!0);return h.unpacked?h.body:de(h.body,this.client._MsgPack,n)}async revokeTokens(r,n){if(ya(this.client.options))throw new x("Cannot revoke tokens when using token auth",40162,401);let o=this.client.options.keyName,l=n??{},h=O({targets:r.map(I=>`${I.type}:${I.value}`)},l),f=this.client.options.useBinaryProtocol?"msgpack":"json",y=K.defaultPostHeaders(this.client.options);this.client.options.headers&&J(y,this.client.options.headers);let b=je(h,this.client._MsgPack,f),A=await ae.post(this.client,`/keys/${o}/revokeTokens`,b,y,{},null,!0);return A.unpacked?A.body:de(A.body,this.client._MsgPack,f)}},Ip=class{constructor(r){this.client=r,this.all=Object.create(null)}get(r,n){r=String(r);let o=this.all[r];return o?n&&o.setOptions(n):this.all[r]=o=new Sp(this.client,r,n),o}release(r){delete this.all[String(r)]}},Mp=class extends Ta{constructor(r){super(K.objectifyOptions(r,!1,"BaseRest",d.defaultLogger,{Rest:Ga}))}},Fa={Rest:Ga},Wa=class extends Ge{static async fromEncoded(r,n){return La(d.defaultLogger,L.Crypto,r,n)}static async fromEncodedArray(r,n){return Ep(d.defaultLogger,L.Crypto,r,n)}static fromValues(r){return Ge.fromValues(r)}},Va=class extends Ke{static async fromEncoded(r,n){return Ia(d.defaultLogger,L.Crypto,r,n)}static async fromEncodedArray(r,n){return yp(d.defaultLogger,L.Crypto,r,n)}static fromValues(r){return Ke.fromValues(r)}},za=["annotation.create","annotation.delete"];async function Ka(r,n,o){return Pt.fromValues(n).decode(o||{},r)}async function xp(r,n,o){return Promise.all(n.map(function(l){return Ka(r,l,o)}))}async function Np(r,n){return Pt.fromValues(r).decode(n.channelOptions,n.logger)}async function Lp(r,n){return Promise.all(r.map(function(o){return Np(o,n)}))}var Ja=class Eo extends At{async encode(){let n=Object.assign(new Pt,this,{action:za.indexOf(this.action||"annotation.create")});return ir(n,{})}static fromValues(n){return Object.assign(new Eo,n)}static fromValuesArray(n){return n.map(o=>Eo.fromValues(o))}toString(){return St(this,"Annotation")}},Pt=class ko extends At{toJSON(...n){return ar.call(this,...n)}static fromValues(n){return Object.assign(new ko,n)}static fromValuesArray(n){return n.map(o=>ko.fromValues(o))}async decode(n,o){let l=Object.assign(new Ja,k(O({},this),{action:za[this.action]}));try{await or(l,n)}catch(h){d.logAction(o,d.LOG_ERROR,"WireAnnotation.decode()",se(h))}return l}toString(){return St(this,"WireAnnotation")}},It=Ja,Ya=class extends It{static async fromEncoded(r,n){return Ka(d.defaultLogger,r,n)}static async fromEncodedArray(r,n){return xp(d.defaultLogger,r,n)}static fromValues(r){return It.fromValues(r)}};function Qa(r){let n;switch(typeof r){case"string":n=r;break;case"object":n=r.serial;break}if(!n||typeof n!="string")throw new x("First argument of annotations.publish() must be either a Message (or at least an object with a string `serial` property) or a message serial (string)",40003,400);return n}function Xa(r,n){let o=Qa(r);if(!n||typeof n!="object")throw new x("Second argument of annotations.publish() must be an object (the intended annotation to publish)",40003,400);let l=It.fromValues(n);return l.messageSerial=o,l.action||(l.action="annotation.create"),l}function Za(r,n){return r.client.rest.channelMixin.basePath(r)+"/messages/"+encodeURIComponent(n)+"/annotations"}var Dp=class{constructor(r){this.channel=r}async publish(r,n){let o=Xa(r,n),l=await o.encode(),h=this.channel.client,f=h.options,y=f.useBinaryProtocol?"msgpack":"json",b=K.defaultPostHeaders(h.options),A={};J(b,h.options.headers);let I=je([l],h._MsgPack,y);await ae.post(h,Za(this.channel,o.messageSerial),I,b,A,null,!0)}async delete(r,n){return n.action="annotation.delete",this.publish(r,n)}async get(r,n){let o=this.channel.client,l=Qa(r),h=o.options.useBinaryProtocol?"msgpack":"json",f=o.http.supportsLinkHeaders?void 0:h,y=K.defaultGetHeaders(o.options);return J(y,o.options.headers),new Be(o,Za(this.channel,l),y,f,async(b,A,I)=>{let U=I?b:de(b,o._MsgPack,h);return Lp(U,this.channel)}).get(n)}},Ws=Dp,Up=je;function Vs(r){let n=[];if(r)for(let o=0;o<r.length;o++)n.push(r[o].toString());return"[ "+n.join(", ")+" ]"}function jp(r,n,o,l,h,f){let y=de(r,n,f);return cr(y,o,l,h)}function cr(r,n,o,l){let h;r.error&&(h=x.fromValues(r.error));let f;r.messages&&(f=as.fromValuesArray(r.messages));let y;n&&r.presence&&(y=n.WirePresenceMessage.fromValuesArray(r.presence));let b;o&&r.annotations&&(b=o.WireAnnotation.fromValuesArray(r.annotations));let A;return l&&r.state&&(A=l.WireObjectMessage.fromValuesArray(r.state,ts,Hs)),Object.assign(new ur,k(O({},r),{presence:y,messages:f,annotations:b,state:A,error:h}))}function qp(r){return n=>{var o;return cr(n,{PresenceMessage:Ke,WirePresenceMessage:os},{Annotation:It,WireAnnotation:Pt,RealtimeAnnotations:dr,RestAnnotations:Ws},(o=r?.LiveObjectsPlugin)!=null?o:null)}}function ke(r){return Object.assign(new ur,r)}function lr(r,n,o,l){let h="[ProtocolMessage";r.action!==void 0&&(h+="; action="+_a[r.action]||r.action);let f=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"],y;for(let b=0;b<f.length;b++)y=f[b],r[y]!==void 0&&(h+="; "+y+"="+r[y]);if(r.messages&&(h+="; messages="+Vs(as.fromValuesArray(r.messages))),r.presence&&n&&(h+="; presence="+Vs(n.WirePresenceMessage.fromValuesArray(r.presence))),r.annotations&&o&&(h+="; annotations="+Vs(o.WireAnnotation.fromValuesArray(r.annotations))),r.state&&l&&(h+="; state="+Vs(l.WireObjectMessage.fromValuesArray(r.state,ts,Hs))),r.error&&(h+="; error="+x.fromValues(r.error).toString()),r.auth&&r.auth.accessToken&&(h+="; token="+r.auth.accessToken),r.flags&&(h+="; flags="+Zf.filter(r.hasFlag).join(",")),r.params){let b="";Ho(r.params,function(A){b.length>0&&(b+="; "),b+=A+"="+r.params[A]}),b.length>0&&(h+="; params=["+b+"]")}return h+="]",h}var ur=class{constructor(){this.hasFlag=r=>(this.flags&Ee[r])>0}setFlag(r){return this.flags=this.flags|Ee[r]}getMode(){return(this.flags||0)&Ee.MODE_ALL}encodeModesToFlags(r){r.forEach(n=>this.setFlag(n))}decodeModesFromFlags(){let r=[];return ba.forEach(n=>{this.hasFlag(n)&&r.push(n)}),r.length>0?r:void 0}},Bp=ur,$p=class{constructor(r,n,o,l,h){this.previous=r,this.current=n,n==="attached"&&(this.resumed=o,this.hasBacklog=l),h&&(this.reason=h)}},hr=$p,ec=function(){};function Hp(r){if(r&&"params"in r&&!Ot(r.params))return new x("options.params must be an object",4e4,400);if(r&&"modes"in r){if(!Array.isArray(r.modes))return new x("options.modes must be an array",4e4,400);for(let n=0;n<r.modes.length;n++){let o=r.modes[n];if(!o||typeof o!="string"||!ba.includes(String.prototype.toUpperCase.call(o)))return new x("Invalid channel mode: "+o,4e4,400)}}}var Gp=class Oo extends fe{constructor(n,o,l){var h,f,y;super(n.logger),this._annotations=null,this._mode=0,this.retryCount=0,this.history=async function(b){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);let A=this.client.rest.channelMixin;if(b&&b.untilAttach){if(this.state!=="attached")throw new x("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new x("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400);delete b.untilAttach,b.from_serial=this.properties.attachSerial}return A.history(this,b)},this.whenState=b=>fe.prototype.whenState.call(this,b,this.state),d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel()","started; name = "+o),this.name=o,this.channelOptions=$s((h=n._Crypto)!=null?h:null,this.logger,l),this.client=n,this._presence=n._RealtimePresence?new n._RealtimePresence.RealtimePresence(this):null,n._Annotations&&(this._annotations=new n._Annotations.RealtimeAnnotations(this)),this.connectionManager=n.connection.connectionManager,this.state="initialized",this.subscriptions=new fe(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(l),this.errorReason=null,this._attachResume=!1,this._decodingContext={channelOptions:this.channelOptions,plugins:n.options.plugins||{},baseEncodedPreviousPayload:void 0},this._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this._allChannelChanges=new fe(this.logger),(f=n.options.plugins)!=null&&f.Push&&(this._push=new n.options.plugins.Push.PushChannel(this)),(y=n.options.plugins)!=null&&y.LiveObjects&&(this._object=new n.options.plugins.LiveObjects.RealtimeObject(this))}get presence(){return this._presence||me("RealtimePresence"),this._presence}get annotations(){return this._annotations||me("Annotations"),this._annotations}get push(){return this._push||me("Push"),this._push}get object(){return this._object||me("LiveObjects"),this._object}invalidStateError(){return new x("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(n){return n=Array.prototype.slice.call(n),typeof n[0]=="function"&&n.unshift(null),n}async setOptions(n){var o;let l=this.channelOptions,h=Hp(n);if(h)throw h;if(this.channelOptions=$s((o=this.client._Crypto)!=null?o:null,this.logger,n),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(n,l))return this.attachImpl(),new Promise((f,y)=>{this._allChannelChanges.once(["attached","update","detached","failed"],function(b){switch(this.event){case"update":case"attached":f();break;default:y(b.reason)}})})}_shouldReattachToSetOptions(n,o){if(!(this.state==="attached"||this.state==="attaching"))return!1;if(n?.params){let l=tc(n.params),h=tc(o.params);if(Object.keys(l).length!==Object.keys(h).length||!Zn(h,l))return!0}return!!(n?.modes&&(!o.modes||!ea(n.modes,o.modes)))}async publish(...n){let o=n[0],l=n[1],h,f;if(typeof o=="string"||o===null||o===void 0)h=[Ge.fromValues({name:o,data:l})],f=n[2];else if(Ot(o))h=[Ge.fromValues(o)],f=n[1];else if(Array.isArray(o))h=Ge.fromValuesArray(o),f=n[1];else throw new x("The single-argument form of publish() expects a message object or an array of message objects",40013,400);let y=this.client.options.maxMessageSize,b=await ja(h,this.channelOptions),A=Ba(b);if(A>y)throw new x(`Maximum size of messages that can be published at once exceeded (was ${A} bytes; limit is ${y} bytes)`,40009,400);this.throwIfUnpublishableState(),d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+this.state+", message count = "+b.length);let I=ke({action:z.MESSAGE,channel:this.name,messages:b,params:f?Yn(f):void 0});return await this.sendMessage(I)||{serials:[]}}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if(this.state==="failed"||this.state==="suspended")throw this.invalidStateError()}onEvent(n){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.onEvent()","received message");let o=this.subscriptions;for(let l=0;l<n.length;l++){let h=n[l];o.emit(h.name,h)}}async attach(){return this.state==="attached"?null:new Promise((n,o)=>{this._attach(!1,null,(l,h)=>l?o(l):n(h))})}_attach(n,o,l){l||(l=f=>{f&&d.logAction(this.logger,d.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+f.toString())});let h=this.connectionManager;if(!h.activeState()){l(h.getError());return}(this.state!=="attaching"||n)&&this.requestState("attaching",o),this.once(function(f){switch(this.event){case"attached":l?.(null,f);break;case"detached":case"suspended":case"failed":l?.(f.reason||h.getError()||new x("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":l?.(new x("Attach request superseded by a subsequent detach request",9e4,409));break}})}attachImpl(){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");let n=ke({action:z.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&n.encodeModesToFlags(Yo(this.channelOptions.modes)),this._attachResume&&n.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(n.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(n).catch(ec)}async detach(){let n=this.connectionManager;switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new x("Unable to detach; channel state = failed",90001,400);default:if(n.state.state!=="connected"){this.notifyState("detached");return}this.requestState("detaching");case"detaching":return new Promise((o,l)=>{this.once(function(h){switch(this.event){case"detached":o();break;case"attached":case"suspended":case"failed":l(h.reason||n.getError()||new x("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":l(new x("Detach request superseded by a subsequent attach request",9e4,409));break}})})}}detachImpl(){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");let n=ke({action:z.DETACH,channel:this.name});this.sendMessage(n).catch(ec)}async subscribe(...n){let[o,l]=Oo.processListenerArgs(n);if(this.state==="failed")throw x.fromValues(this.invalidStateError());return o&&typeof o=="object"&&!Array.isArray(o)?this.client._FilteredSubscriptions.subscribeFilter(this,o,l):this.subscriptions.on(o,l),this.channelOptions.attachOnSubscribe!==!1?this.attach():null}unsubscribe(...n){var o;let[l,h]=Oo.processListenerArgs(n);if(typeof l=="object"&&!h||(o=this.filteredSubscriptions)!=null&&o.has(h)){this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,l,h).forEach(f=>this.subscriptions.off(f));return}this.subscriptions.off(l,h)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new Te("Unable to sync to channel; not attached",4e4);default:}let n=this.connectionManager;if(!n.activeState())throw n.getError();let o=ke({action:z.SYNC,channel:this.name});this.syncChannelSerial&&(o.channelSerial=this.syncChannelSerial),n.send(o)}async sendMessage(n){return new Promise((o,l)=>{this.connectionManager.send(n,this.client.options.queueMessages,(h,f)=>{h?l(h):o(f)})})}async sendPresence(n){let o=ke({action:z.PRESENCE,channel:this.name,presence:n});await this.sendMessage(o)}async sendState(n){let o=ke({action:z.OBJECT,channel:this.name,state:n});await this.sendMessage(o)}async processMessage(n){(n.action===z.ATTACHED||n.action===z.MESSAGE||n.action===z.PRESENCE||n.action===z.OBJECT||n.action===z.ANNOTATION)&&this.setChannelSerial(n.channelSerial);let o,l=!1;switch(n.action){case z.ATTACHED:{this.properties.attachSerial=n.channelSerial,this._mode=n.getMode(),this.params=n.params||{};let h=n.decodeModesFromFlags();this.modes=h&&Jo(h)||void 0;let f=n.hasFlag("RESUMED"),y=n.hasFlag("HAS_PRESENCE"),b=n.hasFlag("HAS_BACKLOG"),A=n.hasFlag("HAS_OBJECTS");if(this.state==="attached"){f||(this._presence&&this._presence.onAttached(y),this._object&&this._object.onAttached(A));let I=new hr(this.state,this.state,f,b,n.error);this._allChannelChanges.emit("update",I),(!f||this.channelOptions.updateOnAttached)&&this.emit("update",I)}else this.state==="detaching"?this.checkPendingState():this.notifyState("attached",n.error,f,y,b,A);break}case z.DETACHED:{let h=n.error?x.fromValues(n.error):new x("Channel detached",90001,404);this.state==="detaching"?this.notifyState("detached",h):this.state==="attaching"?this.notifyState("suspended",h):(this.state==="attached"||this.state==="suspended")&&this.requestState("attaching",h);break}case z.SYNC:if(l=!0,o=this.syncChannelSerial=n.channelSerial,!n.presence)break;case z.PRESENCE:{if(!n.presence)break;Gs(n);let h=this.channelOptions;if(this._presence){let f=await Promise.all(n.presence.map(y=>y.decode(h,this.logger)));this._presence.setPresence(f,l,o)}break}case z.OBJECT:case z.OBJECT_SYNC:{if(!this._object||!n.state)return;Gs(n);let h=this.client.connection.connectionManager.getActiveTransportFormat(),f=n.state.map(y=>y.decode(this.client,h));n.action===z.OBJECT?this._object.handleObjectMessages(f):this._object.handleObjectSyncMessages(f,n.channelSerial);break}case z.MESSAGE:{if(this.state!=="attached"){d.logAction(this.logger,d.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+n.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');return}Gs(n);let h=n.messages,f=h[0],y=h[h.length-1];if(f.extras&&f.extras.delta&&f.extras.delta.from!==this._lastPayload.messageId){let A='Delta message decode failure - previous message not available for message "'+n.id+'" on this channel "'+this.name+'".';d.logAction(this.logger,d.LOG_ERROR,"RealtimeChannel.processMessage()",A),this._startDecodeFailureRecovery(new x(A,40018,400));break}let b=[];for(let A=0;A<h.length;A++){let{decoded:I,err:U}=await h[A].decodeWithErr(this._decodingContext,this.logger);if(b[A]=I,U)switch(U.code){case 40018:this._startDecodeFailureRecovery(U);return;case 40019:case 40021:this.notifyState("failed",U);return;default:}}this._lastPayload.messageId=y.id,this._lastPayload.protocolMessageChannelSerial=n.channelSerial,this.onEvent(b);break}case z.ANNOTATION:{Gs(n);let h=this.channelOptions;if(this._annotations){let f=await Promise.all((n.annotations||[]).map(y=>y.decode(h,this.logger)));this._annotations._processIncoming(f)}break}case z.ERROR:{let h=n.error;h&&h.code==80016?this.checkPendingState():this.notifyState("failed",x.fromValues(h));break}default:d.logAction(this.logger,d.LOG_MAJOR,"RealtimeChannel.processMessage()","Protocol error: unrecognised message action ("+n.action+")")}}_startDecodeFailureRecovery(n){this._lastPayload.decodeFailureRecoveryInProgress||(d.logAction(this.logger,d.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,n,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(n,o,l,h,f,y){if(d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+n),this.clearStateTimer(),["detached","suspended","failed"].includes(n)&&(this.properties.channelSerial=null),n===this.state)return;this._presence&&this._presence.actOnChannelState(n,h,o),this._object&&this._object.actOnChannelState(n,y),n==="suspended"&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),o&&(this.errorReason=o);let b=new hr(this.state,n,l,f,o),A='Channel state for channel "'+this.name+'"',I=n+(o?"; reason: "+o:"");n==="failed"?d.logAction(this.logger,d.LOG_ERROR,A,I):d.logAction(this.logger,d.LOG_MAJOR,A,I),n!=="attaching"&&n!=="suspended"&&(this.retryCount=0),n==="attached"&&this.onAttached(),n==="attached"?this._attachResume=!0:(n==="detaching"||n==="failed")&&(this._attachResume=!1),this.state=n,this._allChannelChanges.emit(n,b),this.emit(n,b)}requestState(n,o){d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+n),this.notifyState(n,o),this.checkPendingState()}checkPendingState(){if(!this.connectionManager.state.sendEvents){d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);return}switch(d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.checkPendingState","name = "+this.name+", state = "+this.state),this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync();break;default:break}}timeoutPendingState(){switch(this.state){case"attaching":{let n=new x("Channel attach timed out",90007,408);this.notifyState("suspended",n);break}case"detaching":{let n=new x("Channel detach timed out",90007,408);this.notifyState("attached",n);break}default:this.checkPendingState();break}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired"),this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){let n=this.stateTimer;n&&(clearTimeout(n),this.stateTimer=null)}startRetryTimer(){if(this.retryTimer)return;this.retryCount++;let n=Xn(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{this.state==="suspended"&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),this.requestState("attaching"))},n)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){let n=this.state;return n==="initialized"||n==="detached"||n==="failed"?null:new x("Can only release a channel in a state where there is no possibility of further updates from the server being received (initialized, detached, or failed); was "+n,90001,400)}setChannelSerial(n){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+n+"; previous = "+this.properties.channelSerial),n&&(this.properties.channelSerial=n)}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(n){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,n)}async updateMessage(n,o,l){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.updateMessage()","channel = "+this.name),this.sendUpdate(n,"message.update",o,l)}async deleteMessage(n,o,l){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.deleteMessage()","channel = "+this.name),this.sendUpdate(n,"message.delete",o,l)}async appendMessage(n,o,l){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.appendMessage()","channel = "+this.name),this.sendUpdate(n,"message.append",o,l)}async sendUpdate(n,o,l,h){var f,y;if(!n.serial)throw new x('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);this.throwIfUnpublishableState();let A=await Ge.fromValues(k(O({},n),{action:o,version:l})).encode(this.channelOptions),I=ke({action:z.MESSAGE,channel:this.name,messages:[A],params:h?Yn(h):void 0}),U=await this.sendMessage(I);return{versionSerial:(y=(f=U?.serials)==null?void 0:f[0])!=null?y:null}}async getMessageVersions(n,o){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,n,o)}async ensureAttached(){switch(this.state){case"attached":case"suspended":break;case"initialized":case"detached":case"detaching":case"attaching":await this.attach();break;case"failed":default:throw x.fromValues(this.invalidStateError())}}};function tc(r){let n=r||{},{agent:o}=n;return N(n,["agent"])}var cs=Gp,Fp=class{constructor(r){this.channel=r,this.logger=r.logger,this.subscriptions=new fe(this.logger)}async publish(r,n){let o=this.channel.name,l=Xa(r,n),h=await l.encode();this.channel.throwIfUnpublishableState(),d.logAction(this.logger,d.LOG_MICRO,"RealtimeAnnotations.publish()","channelName = "+o+", sending annotation with messageSerial = "+l.messageSerial+", type = "+l.type);let f=ke({action:z.ANNOTATION,channel:o,annotations:[h]});await this.channel.sendMessage(f)}async delete(r,n){n.action="annotation.delete",await this.publish(r,n)}async subscribe(...r){let n=cs.processListenerArgs(r),o=n[0],l=n[1],h=this.channel;if(h.state==="failed")throw x.fromValues(h.invalidStateError());if(this.subscriptions.on(o,l),this.channel.channelOptions.attachOnSubscribe!==!1&&await h.attach(),(this.channel.state==="attached"&&this.channel._mode&Ee.ANNOTATION_SUBSCRIBE)===0)throw new x("You are trying to add an annotation listener, but you haven't requested the annotation_subscribe channel mode in ChannelOptions, so this won't do anything (we only deliver annotations to clients who have explicitly requested them)",93001,400)}unsubscribe(...r){let n=cs.processListenerArgs(r),o=n[0],l=n[1];this.subscriptions.off(o,l)}_processIncoming(r){for(let n of r)this.subscriptions.emit(n.type||"",n)}async get(r,n){return Ws.prototype.get.call(this,r,n)}},dr=Fp,mt=class Wn extends Mp{constructor(n){var o,l;if(!Wn._MsgPack)throw new Error("Expected DefaultRest._MsgPack to have been set");super(K.objectifyOptions(n,!0,"Rest",d.defaultLogger,k(O({},Fa),{Crypto:(o=Wn.Crypto)!=null?o:void 0,MsgPack:(l=Wn._MsgPack)!=null?l:void 0,Annotations:{Annotation:It,WireAnnotation:Pt,RealtimeAnnotations:dr,RestAnnotations:Ws}})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(n){this._Crypto=n}};mt._Crypto=null,mt.Message=Wa,mt.PresenceMessage=Va,mt.Annotation=Ya,mt._MsgPack=null,mt._Http=nr;var sc=mt,Wp=class extends fe{constructor(r){super(r),this.messages=[]}count(){return this.messages.length}push(r){this.messages.push(r)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(r){this.messages.push.apply(this.messages,r)}prepend(r){this.messages.unshift.apply(this.messages,r)}completeMessages(r,n,o){d.logAction(this.logger,d.LOG_MICRO,"MessageQueue.completeMessages()",r=="all"?"(all)":"serial = "+r.serial+"; count = "+r.count),n=n||null;let l=this.messages;if(l.length===0)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");let h=[];if(r==="all")h=l.splice(0);else{let f=l[0];if(f){let y=f.message.msgSerial,b=r.serial+r.count;b>y&&(h=l.splice(0,b-y))}}for(let f=0;f<h.length;f++){let y=h[f],b=o?.[f];y.callback(n,b)}l.length==0&&this.emit("idle")}completeAllMessages(r){this.completeMessages("all",r)}resetSendAttempted(){for(let r of this.messages)r.sendAttempted=!1}clear(){d.logAction(this.logger,d.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},nc=Wp,rc=class{constructor(r,n){this.message=r,this.callback=n,this.merged=!1;let o=r.action;this.sendAttempted=!1,this.ackRequired=typeof o=="number"&&[z.MESSAGE,z.PRESENCE,z.ANNOTATION,z.OBJECT].includes(o)}},Vp=class extends fe{constructor(r){super(r.logger),this.transport=r,this.messageQueue=new nc(this.logger),r.on("ack",(n,o,l)=>{this.onAck(n,o,l)}),r.on("nack",(n,o,l)=>{this.onNack(n,o,l)})}onAck(r,n,o){d.logAction(this.logger,d.LOG_MICRO,"Protocol.onAck()","serial = "+r+"; count = "+n),this.messageQueue.completeMessages({serial:r,count:n},null,o)}onNack(r,n,o){d.logAction(this.logger,d.LOG_ERROR,"Protocol.onNack()","serial = "+r+"; count = "+n+"; err = "+se(o)),o||(o=new x("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages({serial:r,count:n},o)}onceIdle(r){let n=this.messageQueue;if(n.count()===0){r();return}n.once("idle",r)}send(r){r.ackRequired&&this.messageQueue.push(r),this.logger.shouldLog(d.LOG_MICRO)&&d.logActionNoStrip(this.logger,d.LOG_MICRO,"Protocol.send()","sending msg; "+lr(r.message,this.transport.connectionManager.realtime._RealtimePresence,this.transport.connectionManager.realtime._Annotations,this.transport.connectionManager.realtime._liveObjectsPlugin)),r.sendAttempted=!0,this.transport.send(r.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){let r=this.transport;this.onceIdle(function(){r.disconnect()})}},zp=Vp,Kp=class{constructor(r,n,o,l){this.previous=r,this.current=n,o&&(this.retryIn=o),l&&(this.reason=l)}},zs=Kp,ct={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},Jp={disconnected:()=>x.fromValues({statusCode:400,code:ct.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>x.fromValues({statusCode:400,code:ct.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>x.fromValues({statusCode:400,code:ct.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>x.fromValues({statusCode:400,code:ct.CLOSING,message:"Connection closing"}),closed:()=>x.fromValues({statusCode:400,code:ct.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>x.fromValues({statusCode:500,code:ct.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>x.fromValues({statusCode:500,code:ct.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})};function Yp(r){return!r.statusCode||!r.code||r.statusCode>=500?!0:Object.values(ct).includes(r.code)}var yt=Jp,Qp=ke({action:z.CLOSE}),Xp=ke({action:z.DISCONNECT}),Zp=class extends fe{constructor(r,n,o,l){super(r.logger),l&&(o.format=void 0,o.heartbeats=!0),this.connectionManager=r,this.auth=n,this.params=o,this.timeouts=o.options.timeouts,this.format=o.format,this.isConnected=!1,this.isFinished=!1,this.isDisposed=!1,this.maxIdleInterval=null,this.idleTimer=null,this.lastActivity=null}connect(){}close(){this.isConnected&&this.requestClose(),this.finish("closed",yt.closed())}disconnect(r){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",r||yt.disconnected())}fail(r){this.isConnected&&this.requestDisconnect(),this.finish("failed",r||yt.failed())}finish(r,n){var o;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout((o=this.idleTimer)!=null?o:void 0),this.idleTimer=null,this.emit(r,n),this.dispose())}onProtocolMessage(r){switch(this.logger.shouldLog(d.LOG_MICRO)&&d.logActionNoStrip(this.logger,d.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+lr(r,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),r.action){case z.HEARTBEAT:d.logActionNoStrip(this.logger,d.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",r.id);break;case z.CONNECTED:this.onConnect(r),this.emit("connected",r.error,r.connectionId,r.connectionDetails,r);break;case z.CLOSED:this.onClose(r);break;case z.DISCONNECTED:this.onDisconnect(r);break;case z.ACK:this.emit("ack",r.msgSerial,r.count,r.res);break;case z.NACK:this.emit("nack",r.msgSerial,r.count,r.error);break;case z.SYNC:this.connectionManager.onChannelMessage(r,this);break;case z.ACTIVATE:break;case z.AUTH:Se(this.auth.authorize(),n=>{n&&d.logAction(this.logger,d.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+se(n))});break;case z.ERROR:if(d.logAction(this.logger,d.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+L.Config.inspect(r.error)+(r.channel?", channel: "+r.channel:"")),r.channel===void 0){this.onFatalError(r);break}this.connectionManager.onChannelMessage(r,this);break;default:this.connectionManager.onChannelMessage(r,this)}}onConnect(r){if(this.isConnected=!0,!r.connectionDetails)throw new Error("Transport.onConnect(): Connect message recieved without connectionDetails");let n=r.connectionDetails.maxIdleInterval;n&&(this.maxIdleInterval=n+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(r){let n=r&&r.error;d.logAction(this.logger,d.LOG_MINOR,"Transport.onDisconnect()","err = "+se(n)),this.finish("disconnected",n)}onFatalError(r){let n=r&&r.error;d.logAction(this.logger,d.LOG_MINOR,"Transport.onFatalError()","err = "+se(n)),this.finish("failed",n)}onClose(r){let n=r&&r.error;d.logAction(this.logger,d.LOG_MINOR,"Transport.onClose()","err = "+se(n)),this.finish("closed",n)}requestClose(){d.logAction(this.logger,d.LOG_MINOR,"Transport.requestClose()",""),this.send(Qp)}requestDisconnect(){d.logAction(this.logger,d.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(Xp)}ping(r){let n={action:z.HEARTBEAT};r&&(n.id=r),this.send(ke(n))}dispose(){d.logAction(this.logger,d.LOG_MINOR,"Transport.dispose()",""),this.isDisposed=!0,this.off()}onActivity(){this.maxIdleInterval&&(this.lastActivity=this.connectionManager.lastActivity=Date.now(),this.setIdleTimer(this.maxIdleInterval+100))}setIdleTimer(r){this.idleTimer||(this.idleTimer=setTimeout(()=>{this.onIdleTimerExpire()},r))}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;let r=Date.now()-this.lastActivity,n=this.maxIdleInterval-r;if(n<=0){let o="No activity seen from realtime in "+r+"ms; assuming connection has dropped";d.logAction(this.logger,d.LOG_ERROR,"Transport.onIdleTimerExpire()",o),this.disconnect(new x(o,80003,408))}else this.setIdleTimer(n+100)}static tryConnect(r,n,o,l,h){let f=new r(n,o,l),y,b=function(I){clearTimeout(y),h({event:this.event,error:I})},A=n.options.timeouts.realtimeRequestTimeout;return y=setTimeout(()=>{f.off(["preconnect","disconnected","failed"]),f.dispose(),b.call({event:"disconnected"},new x("Timeout waiting for transport to indicate itself viable",5e4,500))},A),f.on(["failed","disconnected"],b),f.on("preconnect",function(){d.logAction(n.logger,d.LOG_MINOR,"Transport.tryConnect()","viable transport "+f),clearTimeout(y),f.off(["failed","disconnected"],b),h(null,f)}),f.connect(),f}static isAvailable(){throw new x("isAvailable not implemented for transport",5e4,500)}},Mt=Zp,ye;(r=>{r.WebSocket="web_socket",r.Comet="comet",r.XhrPolling="xhr_polling"})(ye||(ye={}));var eg=typeof global<"u"?global:typeof window<"u"?window:self,fr=()=>{var r;return typeof L.WebStorage<"u"&&((r=L.WebStorage)==null?void 0:r.localSupported)},ls=()=>{var r;return typeof L.WebStorage<"u"&&((r=L.WebStorage)==null?void 0:r.sessionSupported)},ic=function(){},pr="ably-transport-preference";function gr(r){try{return JSON.parse(r)}catch{return null}}var tg=class{constructor(r,n,o,l){this.options=r,this.host=n,this.mode=o,this.connectionKey=l,this.format=r.useBinaryProtocol?"msgpack":"json"}getConnectParams(r){let n=r?ss(r):{},o=this.options;switch(this.mode){case"resume":n.resume=this.connectionKey;break;case"recover":{let l=gr(o.recover);l&&(n.recover=l.connectionKey);break}default:}return o.clientId!==void 0&&(n.clientId=o.clientId),o.echoMessages===!1&&(n.echo="false"),this.format!==void 0&&(n.format=this.format),this.stream!==void 0&&(n.stream=this.stream),this.heartbeats!==void 0&&(n.heartbeats=this.heartbeats),n.v=K.protocolVersion,n.agent=er(this.options),o.transportParams!==void 0&&J(n,o.transportParams),n}toString(){let r="[mode="+this.mode;return this.host&&(r+=",host="+this.host),this.connectionKey&&(r+=",connectionKey="+this.connectionKey),this.format&&(r+=",format="+this.format),r+="]",r}},sg=class Bd extends fe{constructor(n,o){super(n.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=n,this.initTransports(),this.options=o;let l=o.timeouts,h=l.webSocketConnectTimeout+l.realtimeRequestTimeout;if(this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:h,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:l.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:l.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:l.realtimeRequestTimeout,failState:"closed"},closed:{state:"closed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"closed"},failed:{state:"failed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"failed"}},this.state=this.states.initialized,this.errorReason=null,this.queuedMessages=new nc(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=l.connectionStateTtl,this.maxIdleInterval=null,this.transports=Uo(o.transports||K.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(ye.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(ye.XhrPolling)?this.baseTransport=ye.XhrPolling:this.transports.includes(ye.Comet)&&(this.baseTransport=ye.Comet),this.domains=K.getHosts(o),this.activeProtocol=null,this.host=null,this.lastAutoReconnectAttempt=null,this.lastActivity=null,this.forceFallbackHost=!1,this.connectCounter=0,this.wsCheckResult=null,this.webSocketSlowTimer=null,this.webSocketGiveUpTimer=null,this.abandonedWebSocket=!1,d.logAction(this.logger,d.LOG_MINOR,"Realtime.ConnectionManager()","started"),d.logAction(this.logger,d.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(o.transports||K.defaultTransports)+"]"),d.logAction(this.logger,d.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),d.logAction(this.logger,d.LOG_MICRO,"Realtime.ConnectionManager()","http domains = ["+this.domains+"]"),!this.transports.length){let y="no requested transports available";throw d.logAction(this.logger,d.LOG_ERROR,"realtime.ConnectionManager()",y),new Error(y)}let f=L.Config.addEventListener;f&&(ls()&&typeof o.recover=="function"&&f("beforeunload",this.persistConnection.bind(this)),o.closeOnUnload===!0&&f("beforeunload",()=>{d.logAction(this.logger,d.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),this.requestState({state:"closing"})}),f("online",()=>{var y;this.state==this.states.disconnected||this.state==this.states.suspended?(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager caught browser \u2018online\u2019 event","reattempting connection"),this.requestState({state:"connecting"})):this.state==this.states.connecting&&((y=this.pendingTransport)==null||y.off(),this.disconnectAllTransports(),this.startConnect())}),f("offline",()=>{this.state==this.states.connected&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager caught browser \u2018offline\u2019 event","disconnecting active transport"),this.disconnectAllTransports())}))}static supportedTransports(n){let o={supportedTransports:{}};return this.initTransports(n,o),o.supportedTransports}static initTransports(n,o){let l=O(O({},L.Transports.bundledImplementations),n);[ye.WebSocket,...L.Transports.order].forEach(h=>{let f=l[h];f&&f.isAvailable()&&(o.supportedTransports[h]=f)})}initTransports(){Bd.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(n,o){return new tg(this.options,n,o,this.connectionKey)}getTransportParams(n){(l=>{if(this.connectionKey){l("resume");return}if(typeof this.options.recover=="string"){l("recover");return}let h=this.options.recover,f=this.getSessionRecoverData(),y=this.sessionRecoveryName();if(f&&typeof h=="function"){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+y+")"),h(f,b=>{b?(this.options.recover=f.recoveryKey,l("recover")):l("clean")});return}l("clean")})(l=>{let h=this.createTransportParams(null,l);if(l==="recover"){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);let f=gr(this.options.recover);f&&(this.msgSerial=f.msgSerial)}else d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+h.toString());n(h)})}tryATransport(n,o,l){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+o),this.proposedTransport=Mt.tryConnect(this.supportedTransports[o],this,this.realtime.auth,n,(h,f)=>{let y=this.state;if(y==this.states.closing||y==this.states.closed||y==this.states.failed){f&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+y.state+" while we were attempting the transport; closing "+f),f.close()),l(!0);return}if(h){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+o+" "+h.event+", err: "+h.error.toString()),ze.isTokenErr(h.error)&&!(this.errorReason&&ze.isTokenErr(this.errorReason))?(this.errorReason=h.error,Se(this.realtime.auth._forceNewToken(null,null),b=>{if(b){this.actOnErrorFromAuthorize(b);return}this.tryATransport(n,o,l)})):h.event==="failed"?(this.notifyState({state:"failed",error:h.error}),l(!0)):h.event==="disconnected"&&(Yp(h.error)?l(!1):(this.notifyState({state:this.states.connecting.failState,error:h.error}),l(!0)));return}d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+o+"; setting pending"),this.setTransportPending(f,n),l(null,f)})}setTransportPending(n,o){let l=o.mode;d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+n+"; mode = "+l),this.pendingTransport=n,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),n.once("connected",(f,y,b)=>{this.activateTransport(f,n,y,b),l==="recover"&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});let h=this;n.on(["disconnected","closed","failed"],function(f){h.deactivateTransport(n,this.event,f)}),this.emit("transport.pending",n)}activateTransport(n,o,l,h){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+o),n&&d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+n),l&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+l),h&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(h)),this.persistTransportPreference(o);let f=this.state,y=this.states.connected.state;if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+f.state),f.state==this.states.closing.state||f.state==this.states.closed.state||f.state==this.states.failed.state)return d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),o.disconnect(),!1;if(delete this.pendingTransport,!o.isConnected)return d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+o+" since it appears to no longer be connected"),!1;let b=this.activeProtocol;this.activeProtocol=new zp(o),this.host=o.params.host;let A=h.connectionKey;if(A&&this.connectionKey!=A&&this.setConnection(l,h,!!n),this.onConnectionDetailsUpdate(h,o),L.Config.nextTick(()=>{o.on("connected",(I,U,D)=>{this.onConnectionDetailsUpdate(D,o),this.emit("update",new zs(y,y,null,I))})}),f.state===this.states.connected.state?n&&(this.errorReason=this.realtime.connection.errorReason=n,this.emit("update",new zs(y,y,null,n))):(this.notifyState({state:"connected",error:n}),this.errorReason=this.realtime.connection.errorReason=n||null),this.emit("transport.active",o),b)if(b.messageQueue.count()>0&&d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+b.transport.shortName+", new one is "+o.shortName+") finishing with "+b.messageQueue.count()+" messages still pending"),b.transport===o){let I="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+o.shortName+"; stack = "+new Error().stack;d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.activateTransport()",I)}else b.finish();return!0}deactivateTransport(n,o,l){let h=this.activeProtocol,f=h&&h.getTransport()===n,y=n===this.pendingTransport,b=this.noTransportsScheduledForActivation();if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+n),d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+o+(f?"; was active":y?"; was pending":"")+(b?"":"; another transport is scheduled for activation")),l&&l.message&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+l.message),f&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(h.getPendingMessages()),h.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",n),f&&b||f&&o==="failed"||o==="closed"||h===null&&y){if(o==="disconnected"&&l&&l.statusCode>500&&this.domains.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:o,error:l,retryImmediately:!0});return}let A=o==="failed"&&ze.isTokenErr(l)?"disconnected":o;this.notifyState({state:A,error:l});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(n,o,l){let h=this.connectionId;(h&&h!==n||!h&&l)&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==n&&d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=n,this.realtime.connection.key=this.connectionKey=o.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.unpersistConnection()}createRecoveryKey(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null}checkConnectionStateFreshness(){if(!this.lastActivity||!this.connectionId)return;let n=Date.now()-this.lastActivity;n>this.connectionStateTtl+this.maxIdleInterval&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+n+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}persistConnection(){if(ls()){let n=this.createRecoveryKey();n&&this.setSessionRecoverData({recoveryKey:n,disconnectedAt:Date.now(),location:eg.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getActiveTransportFormat(){var n;return(n=this.activeProtocol)==null?void 0:n.getTransport().format}getError(){if(this.errorReason){let n=Te.fromValues(this.errorReason);return n.cause=this.errorReason,n}return this.getStateError()}getStateError(){var n,o;return(o=(n=yt)[this.state.state])==null?void 0:o.call(n)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(n){let o="Connection state",l=n.current+(n.reason?"; reason: "+n.reason:"");n.current==="failed"?d.logAction(this.logger,d.LOG_ERROR,o,l):d.logAction(this.logger,d.LOG_MAJOR,o,l),d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+n.current+"; reason = "+(n.reason&&n.reason.message));let h=this.state=this.states[n.current];n.reason&&(this.errorReason=n.reason,this.realtime.connection.errorReason=n.reason),(h.terminal||h.state==="suspended")&&this.clearConnection(),this.emit("connectionstate",n)}startTransitionTimer(n){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+n.state),this.transitionTimer&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager "+n.state+" timer expired","requesting new state: "+n.failState),this.notifyState({state:n.failState}))},n.retryDelay)}cancelTransitionTimer(){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),this.states.connecting.failState="suspended",this.notifyState({state:"suspended"}))},this.connectionStateTtl))}checkSuspendTimer(n){n!=="disconnected"&&n!=="suspended"&&n!=="connecting"&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(n){this.retryTimer=setTimeout(()=>{d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),this.retryTimer=null,this.requestState({state:"connecting"})},n)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),this.checkWsConnectivity().then(()=>{d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{d.logAction(this.logger,d.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&Se(this.realtime.http.checkConnectivity(),(n,o)=>{n||!o?(d.logAction(this.logger,d.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new x("Unable to connect (network unreachable)",80003,404)})):d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager WebSocket slow timer","http connectivity check succeeded")})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(n){this.webSocketGiveUpTimer=setTimeout(()=>{var o,l;this.wsCheckResult||(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager WebSocket give up timer","websocket connection took more than 10s; "+(this.baseTransport?"trying base transport":"")),this.baseTransport?(this.abandonedWebSocket=!0,(o=this.proposedTransport)==null||o.dispose(),(l=this.pendingTransport)==null||l.dispose(),this.connectBase(n,++this.connectCounter)):d.logAction(this.logger,d.LOG_MAJOR,"ConnectionManager WebSocket give up timer","websocket connectivity appears to be unavailable but no other transports to try"))},this.options.timeouts.webSocketConnectTimeout)}cancelWebSocketGiveUpTimer(){this.webSocketGiveUpTimer&&(clearTimeout(this.webSocketGiveUpTimer),this.webSocketGiveUpTimer=null)}notifyState(n){var o,l;let h=n.state,f=h==="disconnected"&&(this.state===this.states.connected||n.retryImmediately||this.state===this.states.connecting&&n.error&&ze.isTokenErr(n.error)&&!(this.errorReason&&ze.isTokenErr(this.errorReason)));if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+h+(f?"; will retry connection immediately":"")),h==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(n.state),(h==="suspended"||h==="connected")&&(this.disconnectedRetryCount=0),this.state.terminal))return;let y=this.states[n.state],b=y.retryDelay;y.state==="disconnected"&&(this.disconnectedRetryCount++,b=Xn(y.retryDelay,this.disconnectedRetryCount));let A=new zs(this.state.state,y.state,b,n.error||((l=(o=yt)[y.state])==null?void 0:l.call(o)));if(f){let I=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},U=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;U&&U<1e3?(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+U+"ms ago, waiting another "+(1e3-U)+"ms before trying again"),setTimeout(I,1e3-U)):L.Config.nextTick(I)}else(h==="disconnected"||h==="suspended")&&this.startRetryTimer(b);(h==="disconnected"&&!f||h==="suspended"||y.terminal)&&L.Config.nextTick(()=>{this.disconnectAllTransports()}),h=="connected"&&!this.activeProtocol&&d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(A),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(h,A.reason),this.failQueuedMessages(A.reason))}requestState(n){var o,l;let h=n.state;if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+h+"; current state: "+this.state.state),h==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(h),h=="connecting"&&this.state.state=="connected")||h=="closing"&&this.state.state=="closed")return;let f=this.states[h],y=new zs(this.state.state,f.state,null,n.error||((l=(o=yt)[f.state])==null?void 0:l.call(o)));this.enactStateChange(y),h=="connecting"&&L.Config.nextTick(()=>{this.startConnect()}),h=="closing"&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);return}let n=this.realtime.auth,o=++this.connectCounter,l=()=>{this.checkConnectionStateFreshness(),this.getTransportParams(h=>{if(h.mode==="recover"&&h.options.recover){let f=gr(h.options.recover);f&&this.realtime.channels.recoverChannels(f.channelSerials)}o===this.connectCounter&&this.connectImpl(h,o)})};if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),n.method==="basic")l();else{let h=f=>{o===this.connectCounter&&(f?this.actOnErrorFromAuthorize(f):l())};this.errorReason&&ze.isTokenErr(this.errorReason)?Se(n._forceNewToken(null,null),h):Se(n._ensureValidAuthCredentials(!1),h)}}connectImpl(n,o){let l=this.state.state;if(l!==this.states.connecting.state){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect, but was "+l);return}let h=this.getTransportPreference();h&&h===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(n,++this.connectCounter))}).catch(ic),h&&h===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(n,o):this.connectWs(n,o)}connectWs(n,o){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.connectWs()"),this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(n),this.tryTransportWithFallbacks("web_socket",n,!0,o,()=>this.wsCheckResult!==!1&&!this.abandonedWebSocket)}connectBase(n,o){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,n,!1,o,()=>!0):this.notifyState({state:"disconnected",error:new x("No transports left to try",8e4,404)})}tryTransportWithFallbacks(n,o,l,h,f){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",n);let y=D=>{this.notifyState({state:this.states.connecting.failState,error:D})},b=this.domains.slice(),A=(D,F)=>{if(h===this.connectCounter){if(!f()){F&&F.dispose();return}!F&&!D&&U()}},I=b.shift();if(!I){y(new x("Unable to connect (no available host)",80003,404));return}o.host=I;let U=()=>{if(!b.length){y(new x("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!this.realtime.http.checkConnectivity){y(new Te("Internal error: Http.checkConnectivity not set",null,500));return}Se(this.realtime.http.checkConnectivity(),(D,F)=>{if(h===this.connectCounter&&f()){if(D){y(D);return}if(!F){y(new x("Unable to connect (network unreachable)",80003,404));return}o.host=Jn(b),this.tryATransport(o,n,A)}})};if(this.forceFallbackHost&&b.length){this.forceFallbackHost=!1,U();return}this.tryATransport(o,n,A)}closeImpl(){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})}onAuthUpdated(n,o){var l;switch(this.state.state){case"connected":{d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport");let h=(l=this.activeProtocol)==null?void 0:l.getTransport();h&&h.onAuthUpdated&&h.onAuthUpdated(n);let f=ke({action:z.AUTH,auth:{accessToken:n.token}});this.send(f);let y=()=>{this.off(b),o(null,n)},b=A=>{A.current==="failed"&&(this.off(y),this.off(b),o(A.reason||this.getStateError()))};this.once("connectiondetails",y),this.on("connectionstate",b);break}case"connecting":d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");let h=f=>{switch(f.current){case"connected":this.off(h),o(null,n);break;case"failed":case"closed":case"suspended":this.off(h),o(f.reason||this.getStateError());break;default:break}};this.on("connectionstate",h),this.state.state==="connecting"?this.startConnect():this.requestState({state:"connecting"})}}}disconnectAllTransports(){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(n,o,l){l=l||ic;let h=this.state;if(h.sendEvents){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new rc(n,l));return}if(!(o&&h.queueEvents)){let y="rejecting event, queueEvent was "+o+", state was "+h.state;d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()",y),l(this.errorReason||new x(y,9e4,400));return}this.logger.shouldLog(d.LOG_MICRO)&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+lr(n,this.realtime._RealtimePresence,this.realtime._Annotations,this.realtime._liveObjectsPlugin)),this.queue(n,l)}sendImpl(n){let o=n.message;n.ackRequired&&!n.sendAttempted&&(o.msgSerial=this.msgSerial++);try{this.activeProtocol.send(n)}catch(l){d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+l.stack)}}queue(n,o){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.queue()","queueing event"),this.queuedMessages.push(new rc(n,o))}sendQueuedMessages(){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");let n;for(;n=this.queuedMessages.shift();)this.sendImpl(n)}queuePendingMessages(n){n&&n.length&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+n.length+" pending messages"),this.queuedMessages.prepend(n))}failQueuedMessages(n){let o=this.queuedMessages.count();o>0&&(d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+o+" queued messages, err = "+se(n)),this.queuedMessages.completeAllMessages(n))}onChannelMessage(n,o){this.pendingChannelMessagesState.queue.push({message:n,transport:o}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;let n=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(n.message).catch(o=>{d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",o)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}async processChannelMessage(n){await this.realtime.channels.processChannelMessage(n)}async ping(){var n;if(this.state.state!=="connected")throw new x("Unable to ping service; not connected",4e4,400);let o=(n=this.activeProtocol)==null?void 0:n.getTransport();if(!o)throw this.getStateError();d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.ping()","transport = "+o);let l=Date.now(),h=Vo();return ta(new Promise(f=>{let y=b=>{b===h&&(o.off("heartbeat",y),f(Date.now()-l))};o.on("heartbeat",y),o.ping(h)}),this.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")}abort(n){this.activeProtocol.getTransport().fail(n)}getTransportPreference(){var n,o;return this.transportPreference||fr()&&((o=(n=L.WebStorage)==null?void 0:n.get)==null?void 0:o.call(n,pr))}persistTransportPreference(n){var o,l;this.transportPreference=n.shortName,fr()&&((l=(o=L.WebStorage)==null?void 0:o.set)==null||l.call(o,pr,n.shortName))}unpersistTransportPreference(){var n,o;this.transportPreference=null,fr()&&((o=(n=L.WebStorage)==null?void 0:n.remove)==null||o.call(n,pr))}actOnErrorFromAuthorize(n){if(n.code===40171)this.notifyState({state:"failed",error:n});else if(n.code===40102)this.notifyState({state:"failed",error:n});else if(n.statusCode===is.Forbidden){let o="Client configured authentication provider returned 403; failing the connection";d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",o),this.notifyState({state:"failed",error:new x(o,80019,403,n)})}else{let o="Client configured authentication provider request failed";d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",o),this.notifyState({state:this.state.failState,error:new x(o,80019,401,n)})}}onConnectionDetailsUpdate(n,o){if(!n)return;this.connectionDetails=n,n.maxMessageSize&&(this.options.maxMessageSize=n.maxMessageSize);let l=n.clientId;if(l){let f=this.realtime.auth._uncheckedSetClientId(l);if(f){d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",f.message),o.fail(f);return}}let h=n.connectionStateTtl;h&&(this.connectionStateTtl=h),this.maxIdleInterval=n.maxIdleInterval,this.emit("connectiondetails",n)}checkWsConnectivity(){let n=this.options.wsConnectivityCheckUrl||K.wsConnectivityCheckUrl,o=new L.Config.WebSocket(n);return new Promise((l,h)=>{let f=!1;o.onopen=()=>{f||(f=!0,l(),o.close())},o.onclose=o.onerror=()=>{f||(f=!0,h())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var n,o;return ls()&&((o=(n=L.WebStorage)==null?void 0:n.getSession)==null?void 0:o.call(n,this.sessionRecoveryName()))}setSessionRecoverData(n){var o,l;return ls()&&((l=(o=L.WebStorage)==null?void 0:o.setSession)==null?void 0:l.call(o,this.sessionRecoveryName(),n))}clearSessionRecoverData(){var n,o;return ls()&&((o=(n=L.WebStorage)==null?void 0:n.removeSession)==null?void 0:o.call(n,this.sessionRecoveryName()))}},oc=sg,ng=class extends fe{constructor(r,n){super(r.logger),this.whenState=o=>fe.prototype.whenState.call(this,o,this.state),this.ably=r,this.connectionManager=new oc(r,n),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",o=>{let l=this.state=o.current;L.Config.nextTick(()=>{this.emit(l,o)})}),this.connectionManager.on("update",o=>{L.Config.nextTick(()=>{this.emit("update",o)})})}connect(){d.logAction(this.logger,d.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}async ping(){return d.logAction(this.logger,d.LOG_MINOR,"Connection.ping()",""),this.connectionManager.ping()}close(){d.logAction(this.logger,d.LOG_MINOR,"Connection.close()","connectionKey = "+this.key),this.connectionManager.requestState({state:"closing"})}get recoveryKey(){return this.logger.deprecationWarning("The `Connection.recoveryKey` attribute has been replaced by the `Connection.createRecoveryKey()` method. Replace your usage of `recoveryKey` with the return value of `createRecoveryKey()`. `recoveryKey` will be removed in a future version."),this.createRecoveryKey()}createRecoveryKey(){return this.connectionManager.createRecoveryKey()}},rg=ng,ac=class $d extends Ta{constructor(n){var o,l,h,f;if(super(K.objectifyOptions(n,!1,"BaseRealtime",d.defaultLogger)),d.logAction(this.logger,d.LOG_MINOR,"Realtime()",""),typeof EdgeRuntime=="string")throw new x(`Ably.Realtime instance cannot be used in Vercel Edge runtime. If you are running Vercel Edge functions, please replace your "new Ably.Realtime()" with "new Ably.Rest()" and use Ably Rest API instead of the Realtime API. If you are server-rendering your application in the Vercel Edge runtime, please use the condition "if (typeof EdgeRuntime === 'string')" to prevent instantiating Ably.Realtime instance during SSR in the Vercel Edge runtime.`,4e4,400);this._additionalTransportImplementations=$d.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=(l=(o=this.options.plugins)==null?void 0:o.RealtimePresence)!=null?l:null,this._liveObjectsPlugin=(f=(h=this.options.plugins)==null?void 0:h.LiveObjects)!=null?f:null,this.connection=new rg(this,this.options),this._channels=new og(this),this.options.autoConnect!==!1&&this.connect()}static transportImplementationsFromPlugins(n){let o={};return n?.WebSocketTransport&&(o[ye.WebSocket]=n.WebSocketTransport),n?.XHRPolling&&(o[ye.XhrPolling]=n.XHRPolling),o}get channels(){return this._channels}get clientId(){return this.auth.clientId}connect(){d.logAction(this.logger,d.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){d.logAction(this.logger,d.LOG_MINOR,"Realtime.close()",""),this.connection.close()}};ac.EventEmitter=fe;var ig=ac,og=class extends fe{constructor(r){super(r.logger),this.realtime=r,this.all=Object.create(null),r.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){let r={};for(let n of js(this.all,!0)){let o=this.all[n];o.properties.channelSerial&&(r[n]=o.properties.channelSerial)}return r}recoverChannels(r){for(let n of js(r,!0)){let o=this.get(n);o.properties.channelSerial=r[n]}}async processChannelMessage(r){let n=r.channel;if(n===void 0){d.logAction(this.logger,d.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+r.action);return}let o=this.all[n];if(!o){d.logAction(this.logger,d.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+n);return}await o.processMessage(r)}onTransportActive(){for(let r in this.all){let n=this.all[r];n.state==="attaching"||n.state==="detaching"?n.checkPendingState():n.state==="suspended"?n._attach(!1,null):n.state==="attached"&&n.requestState("attaching")}}propogateConnectionInterruption(r,n){let o={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"},l=["attaching","attached","detaching","suspended"],h=o[r];for(let f in this.all){let y=this.all[f];l.includes(y.state)&&y.notifyState(h,n)}}get(r,n){r=String(r);let o=this.all[r];if(!o)o=this.all[r]=new cs(this.realtime,r,n);else if(n){if(o._shouldReattachToSetOptions(n,o.channelOptions))throw new x("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);o.setOptions(n)}return o}getDerived(r,n,o){if(n.filter){let l=Bs(n.filter),h=Zo(r);r=`[filter=${l}${h.qualifierParam}]${h.channelName}`}return this.get(r,o)}release(r){r=String(r);let n=this.all[r];if(!n)return;let o=n.getReleaseErr();if(o)throw o;delete this.all[r]}},ag=ig;function cg(r,n){if(r.isSynthesized()||n.isSynthesized())return r.timestamp>=n.timestamp;let o=r.parseId(),l=n.parseId();return o.msgSerial===l.msgSerial?o.index>l.index:o.msgSerial>l.msgSerial}var mr=class extends fe{constructor(r,n,o=cg){super(r.logger),this.presence=r,this.map=Object.create(null),this.syncInProgress=!1,this.residualMembers=null,this.memberKey=n,this.newerThan=o}get(r){return this.map[r]}getClient(r){let n=this.map,o=[];for(let l in n){let h=n[l];h.clientId==r&&h.action!="absent"&&o.push(h)}return o}list(r){let n=this.map,o=r&&r.clientId,l=r&&r.connectionId,h=[];for(let f in n){let y=n[f];y.action!=="absent"&&(o&&o!=y.clientId||l&&l!=y.connectionId||h.push(y))}return h}put(r){(r.action==="enter"||r.action==="update")&&(r=Ke.fromValues(r),r.action="present");let n=this.map,o=this.memberKey(r);this.residualMembers&&delete this.residualMembers[o];let l=n[o];return l&&!this.newerThan(r,l)?!1:(n[o]=r,!0)}values(){let r=this.map,n=[];for(let o in r){let l=r[o];l.action!="absent"&&n.push(l)}return n}remove(r){let n=this.map,o=this.memberKey(r),l=n[o];return l&&!this.newerThan(r,l)?!1:(this.syncInProgress?(r=Ke.fromValues(r),r.action="absent",n[o]=r):delete n[o],!!l)}startSync(){let r=this.map,n=this.syncInProgress;d.logAction(this.logger,d.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+n),this.syncInProgress||(this.residualMembers=ss(r),this.setInProgress(!0))}endSync(){let r=this.map,n=this.syncInProgress;if(d.logAction(this.logger,d.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+n),n){for(let o in r)r[o].action==="absent"&&delete r[o];this.presence._synthesizeLeaves($o(this.residualMembers));for(let o in this.residualMembers)delete r[o];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}async waitSync(){let r=this.syncInProgress;d.logAction(this.logger,d.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+r),r&&await this.once("sync")}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(r){d.logAction(this.logger,d.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+r),this.syncInProgress=r,this.presence.syncComplete=!r}};function lg(r){return r.channel.client.auth.clientId}function yr(r){let n=r.channel.client,o=n.auth.clientId;return(!o||o==="*")&&n.connection.state==="connected"}var ug=class extends fe{constructor(r){super(r.logger),this.channel=r,this.syncComplete=!1,this.members=new mr(this,n=>n.clientId+":"+n.connectionId),this._myMembers=new mr(this,n=>n.clientId),this.subscriptions=new fe(this.logger),this.pendingPresence=[]}async enter(r){if(yr(this))throw new x("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,r,"enter")}async update(r){if(yr(this))throw new x("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,void 0,r,"update")}async enterClient(r,n){return this._enterOrUpdateClient(void 0,r,n,"enter")}async updateClient(r,n){return this._enterOrUpdateClient(void 0,r,n,"update")}async _enterOrUpdateClient(r,n,o,l){let h=this.channel;if(!h.connectionManager.activeState())throw h.connectionManager.getError();d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence."+l+"Client()","channel = "+h.name+", id = "+r+", client = "+(n||"(implicit) "+lg(this)));let f=Ke.fromData(o);f.action=l,r&&(f.id=r),n&&(f.clientId=n);let y=await f.encode(h.channelOptions);switch(h.state){case"attached":return h.sendPresence([y]);case"initialized":case"detached":h.attach();case"attaching":return new Promise((b,A)=>{this.pendingPresence.push({presence:y,callback:I=>I?A(I):b()})});default:{let b=new Te("Unable to "+l+" presence channel while in "+h.state+" state",90001);throw b.code=90001,b}}}async leave(r){if(yr(this))throw new x("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,r)}async leaveClient(r,n){let o=this.channel;if(!o.connectionManager.activeState())throw o.connectionManager.getError();d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+r);let l=Ke.fromData(n);l.action="leave",r&&(l.clientId=r);let h=await l.encode(o.channelOptions);switch(o.state){case"attached":return o.sendPresence([h]);case"attaching":return new Promise((f,y)=>{this.pendingPresence.push({presence:h,callback:b=>b?y(b):f()})});case"initialized":case"failed":throw new Te("Unable to leave presence channel (incompatible state)",90001);default:throw o.invalidStateError()}}async get(r){let n=!r||("waitForSync"in r?r.waitForSync:!0);function o(h){return r?h.list(r):h.values()}if(this.channel.state==="suspended"){if(n)throw x.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"});return o(this.members)}await this.channel.ensureAttached();let l=this.members;return n&&await l.waitSync(),o(this.members)}async history(r){d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);let n=this.channel.client.rest.presenceMixin;if(r&&r.untilAttach)if(this.channel.state==="attached")delete r.untilAttach,r.from_serial=this.channel.properties.attachSerial;else throw new x("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400);return n.history(this,r)}setPresence(r,n,o){d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+r.length+" participants; syncChannelSerial = "+o);let l,h,f=this.members,y=this._myMembers,b=[],A=this.channel.connectionManager.connectionId;n&&(this.members.startSync(),o&&(h=o.match(/^[\w-]+:(.*)$/))&&(l=h[1]));for(let I of r)switch(I.action){case"leave":f.remove(I)&&b.push(I),I.connectionId===A&&!I.isSynthesized()&&y.remove(I);break;case"enter":case"present":case"update":f.put(I)&&b.push(I),I.connectionId===A&&y.put(I);break}n&&!l&&(f.endSync(),this.channel.syncChannelSerial=null);for(let I=0;I<b.length;I++){let U=b[I];this.subscriptions.emit(U.action,U)}}onAttached(r){d.logAction(this.logger,d.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+r),r?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();let n=this.pendingPresence,o=n.length;if(o){this.pendingPresence=[];let l=[],h=ha.create(this.logger);d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence.onAttached","sending "+o+" queued presence messages");for(let f=0;f<o;f++){let y=n[f];l.push(y.presence),h.push(y.callback)}this.channel.sendPresence(l).then(()=>h()).catch(f=>h(f))}}actOnChannelState(r,n,o){switch(r){case"attached":this.onAttached(n);break;case"detached":case"failed":this._clearMyMembers(),this.members.clear();case"suspended":this.failPendingPresence(o);break}}failPendingPresence(r){if(this.pendingPresence.length){d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+se(r));for(let n=0;n<this.pendingPresence.length;n++)try{this.pendingPresence[n].callback(r)}catch{}this.pendingPresence=[]}}_clearMyMembers(){this._myMembers.clear()}_ensureMyMembersPresent(){let r=this._myMembers,n=this.channel.connectionManager.connectionId;for(let o in r.map){let l=r.map[o];d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+l.clientId+'" into the presence set');let h=l.connectionId===n?l.id:void 0;this._enterOrUpdateClient(h,l.clientId,l.data,"enter").catch(f=>{let y=new x("Presence auto re-enter failed",91004,400,f);d.logAction(this.logger,d.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()","Presence auto re-enter failed; reason = "+se(f));let b=new hr(this.channel.state,this.channel.state,!0,!1,y);this.channel.emit("update",b)})}}_synthesizeLeaves(r){let n=this.subscriptions;r.forEach(function(o){let l=Ke.fromValues({action:"leave",connectionId:o.connectionId,clientId:o.clientId,data:o.data,encoding:o.encoding,timestamp:Date.now()});n.emit("leave",l)})}async subscribe(...r){let n=cs.processListenerArgs(r),o=n[0],l=n[1],h=this.channel;if(h.state==="failed")throw x.fromValues(h.invalidStateError());this.subscriptions.on(o,l),h.channelOptions.attachOnSubscribe!==!1&&await h.attach()}unsubscribe(...r){let n=cs.processListenerArgs(r),o=n[0],l=n[1];this.subscriptions.off(o,l)}},hg=ug,dg=ye.WebSocket;function fg(r){return!!r.on}var pg=class extends Mt{constructor(r,n,o){super(r,n,o),this.shortName=dg,o.heartbeats=L.Config.useProtocolHeartbeats,this.wsHost=o.host}static isAvailable(){return!!L.Config.WebSocket}createWebSocket(r,n){return this.uri=r+ns(n),new L.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.connect()","starting"),Mt.prototype.connect.call(this);let r=this,n=this.params,o=n.options,h=(o.tls?"wss://":"ws://")+this.wsHost+":"+K.getPort(o)+"/";d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.connect()","uri: "+h),Se(this.auth.getAuthParams(),function(f,y){if(r.isDisposed)return;let b="";for(let I in y)b+=" "+I+": "+y[I]+";";if(d.logAction(r.logger,d.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+b+" err: "+f),f){r.disconnect(f);return}let A=n.getConnectParams(y);try{let I=r.wsConnection=r.createWebSocket(h,A);I.binaryType=L.Config.binaryType,I.onopen=function(){r.onWsOpen()},I.onclose=function(U){r.onWsClose(U)},I.onmessage=function(U){r.onWsData(U.data)},I.onerror=function(U){r.onWsError(U)},fg(I)&&I.on("ping",function(){r.onActivity()})}catch(I){d.logAction(r.logger,d.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(I.stack||I.message)),r.disconnect(I)}})}send(r){let n=this.wsConnection;if(!n){d.logAction(this.logger,d.LOG_ERROR,"WebSocketTransport.send()","No socket connection");return}try{n.send(Up(r,this.connectionManager.realtime._MsgPack,this.params.format))}catch(o){let l="Exception from ws connection when trying to send: "+se(o);d.logAction(this.logger,d.LOG_ERROR,"WebSocketTransport.send()",l),this.finish("disconnected",new x(l,5e4,500))}}onWsData(r){d.logAction(this.logger,d.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+r.length+"; type = "+typeof r);try{this.onProtocolMessage(jp(r,this.connectionManager.realtime._MsgPack,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin,this.format))}catch(n){d.logAction(this.logger,d.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+n.stack)}}onWsOpen(){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")}onWsClose(r){let n,o;if(typeof r=="object"?(o=r.code,n=r.wasClean||o===1e3):(o=r,n=o==1e3),delete this.wsConnection,n){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");let l=new x("Websocket closed",80003,400);this.finish("disconnected",l)}else{let l="Unclean disconnection of WebSocket ; code = "+o,h=new x(l,80003,400);d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onWsClose()",l),this.finish("disconnected",h)}this.emit("disposed")}onWsError(r){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+r.message),L.Config.nextTick(()=>{this.disconnect(Error(r.message))})}dispose(){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;let r=this.wsConnection;r&&(r.onmessage=function(){},delete this.wsConnection,L.Config.nextTick(()=>{if(d.logAction(this.logger,d.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!r)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");r.close()}))}},cc=pg,gg=class{static subscribeFilter(r,n,o){let l=h=>{var f,y,b,A,I,U;let D={name:h.name,refTimeserial:(y=(f=h.extras)==null?void 0:f.ref)==null?void 0:y.timeserial,refType:(A=(b=h.extras)==null?void 0:b.ref)==null?void 0:A.type,isRef:!!((U=(I=h.extras)==null?void 0:I.ref)!=null&&U.timeserial),clientId:h.clientId};Object.entries(n).find(([F,E])=>E!==void 0?D[F]!==E:!1)||o(h)};this.addFilteredSubscription(r,n,o,l),r.subscriptions.on(l)}static addFilteredSubscription(r,n,o,l){var h;if(r.filteredSubscriptions||(r.filteredSubscriptions=new Map),r.filteredSubscriptions.has(o)){let f=r.filteredSubscriptions.get(o);f.set(n,((h=f?.get(n))==null?void 0:h.concat(l))||[l])}else r.filteredSubscriptions.set(o,new Map([[n,[l]]]))}static getAndDeleteFilteredSubscriptions(r,n,o){if(!r.filteredSubscriptions)return[];if(!o&&n)return Array.from(r.filteredSubscriptions.entries()).map(([f,y])=>{var b;let A=y.get(n);return y.delete(n),y.size===0&&((b=r.filteredSubscriptions)==null||b.delete(f)),A}).reduce((f,y)=>y?f.concat(...y):f,[]);if(!o||!r.filteredSubscriptions.has(o))return[];let l=r.filteredSubscriptions.get(o);if(!n){let f=Array.from(l.values()).reduce((y,b)=>y.concat(...b),[]);return r.filteredSubscriptions.delete(o),f}let h=l.get(n);return l.delete(n),h||[]}},Ie=class To extends ag{constructor(n){var o;let l=To._MsgPack;if(!l)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(K.objectifyOptions(n,!0,"Realtime",d.defaultLogger,k(O({},Fa),{Crypto:(o=To.Crypto)!=null?o:void 0,MsgPack:l,RealtimePresence:{RealtimePresence:hg,PresenceMessage:Ke,WirePresenceMessage:os},Annotations:{Annotation:It,WireAnnotation:Pt,RealtimeAnnotations:dr,RestAnnotations:Ws},WebSocketTransport:cc,MessageInteractions:gg})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(n){this._Crypto=n}};Ie.Utils=ts,Ie.ConnectionManager=oc,Ie.ProtocolMessage=Bp,Ie._Crypto=null,Ie.Message=Wa,Ie.PresenceMessage=Va,Ie.Annotation=Ya,Ie._MsgPack=null,Ie._Http=nr,Ie._PresenceMap=mr,Ie._MessageEncoding=Hs;var lc=Ie,uc=Q(q("crypto")),mg=class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}base64Decode(r){return Buffer.from(r,"base64")}base64Encode(r){return this.toBuffer(r).toString("base64")}base64UrlEncode(r){return this.toBuffer(r).toString("base64url")}areBuffersEqual(r,n){return!r||!n?!1:this.toBuffer(r).compare(this.toBuffer(n))==0}byteLength(r){return r.byteLength}hexDecode(r){return Buffer.from(r,"hex")}hexEncode(r){return this.toBuffer(r).toString("hex")}isBuffer(r){return Buffer.isBuffer(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)}toArrayBuffer(r){let n=this.toBuffer(r);return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}toBuffer(r){return Buffer.isBuffer(r)?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength)}arrayBufferViewToBuffer(r){return this.toBuffer(r)}utf8Decode(r){if(!this.isBuffer(r))throw new Error("Expected input of utf8Decode to be a buffer, arraybuffer, or view");return this.toBuffer(r).toString("utf8")}utf8Encode(r){return Buffer.from(r,"utf8")}concat(r){return Buffer.concat(r.map(n=>this.toBuffer(n)))}sha256(r){let n=this.toBuffer(r);return uc.default.createHash("SHA256").update(n).digest()}hmacSha256(r,n){let o=this.toBuffer(r),l=this.toBuffer(n);return uc.default.createHmac("SHA256",l).update(o).digest()}},hc=new mg,_r=Q(q("crypto")),yg=Q(q("util")),_g=function(r){var n="aes",o=256,l="cbc",h=16;async function f(j){return yg.default.promisify(_r.default.randomBytes)(j)}function y(j){return j+h&-h}function b(j){if(j.algorithm==="aes"&&j.mode==="cbc"){if(j.keyLength===128||j.keyLength===256)return;throw new Error("Unsupported key length "+j.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}}function A(j){return j.replace("_","/").replace("-","+")}function I(j,H){var V=Buffer.alloc(j);return V.fill(H),V}for(var U=[I(16,16)],D=1;D<=16;D++)U.push(I(D,D));class F{constructor(H,V,W,te){this.algorithm=H,this.keyLength=V,this.mode=W,this.key=te,this.iv=null}}function E(j){return!!(j.algorithm&&j.key&&j.keyLength&&j.mode)}class R{static getDefaultParams(H){var V;if(!H.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof H.key=="string"?V=r.base64Decode(A(H.key)):H.key instanceof ArrayBuffer?V=Buffer.from(H.key):V=H.key;var W=H.algorithm||n,te=V.length*8,Oe=H.mode||l,ve=new F(W,te,Oe,V);if(H.keyLength&&H.keyLength!==ve.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+H.keyLength+" was specified, but the key actually has length "+ve.keyLength);return b(ve),ve}static async generateRandomKey(H){try{return f((H||o)/8)}catch(V){throw new x("Failed to generate random key: "+V.message,500,5e4,V)}}static getCipher(H,V){var W,te=E(H)?H:this.getDefaultParams(H);return{cipherParams:te,cipher:new P(te,(W=H.iv)!=null?W:null,V)}}}R.CipherParams=F;class P{constructor(H,V,W){this.logger=W,this.encryptCipher=null,this.algorithm=H.algorithm+"-"+String(H.keyLength)+"-"+H.mode,this.key=H.key,this.iv=V}async encrypt(H){d.logAction(this.logger,d.LOG_MICRO,"CBCCipher.encrypt()","");let V=await this.getIv();this.encryptCipher||(this.encryptCipher=_r.default.createCipheriv(this.algorithm,this.key,V));var W=r.toBuffer(H),te=W.length,Oe=y(te),ve=this.encryptCipher.update(Buffer.concat([W,U[Oe-te]])),Je=Buffer.concat([V,ve]);return Je}async decrypt(H){var V=_r.default.createDecipheriv(this.algorithm,this.key,H.slice(0,h)),W=V.update(H.slice(h)),te=V.final();return te&&te.length&&(W=Buffer.concat([W,te])),W}async getIv(){if(this.iv){var H=this.iv;return this.iv=null,H}var V=await f(h);return this.encryptCipher?this.encryptCipher.update(V):V}}return R},dc=Q(Fn()),bg=Q(q("http")),vg=Q(q("https")),fc=[],us,wg=(us=class{constructor(r){this.agent=null,this.supportsAuthHeaders=!0,this.supportsLinkHeaders=!0,this.checkConnectivity=async()=>{var n,o,l,h,f;if((n=this.client)!=null&&n.options.disableConnectivityCheck)return!0;let y=((o=this.client)==null?void 0:o.options.connectivityCheckUrl)||K.connectivityCheckUrl,b=(h=(l=this.client)==null?void 0:l.options.connectivityCheckParams)!=null?h:null,A=!((f=this.client)!=null&&f.options.connectivityCheckUrl),{error:I,statusCode:U,body:D}=await this.doUri(ue.Get,y,null,null,b);return!I&&!A?Bf(U):!I&&D?.toString().trim()==="yes"},this.client=r??null}async doUri(r,n,o,l,h){var f;let y=this.client&&this.client.options.restAgentOptions||K.restAgentOptions,b={headers:o||void 0,responseType:"buffer"};if(!this.agent){let A=(f=fc.find(I=>Zn(y,I.options)))==null?void 0:f.agents;A?this.agent=A:(this.agent={http:new bg.default.Agent(y),https:new vg.default.Agent(y)},fc.push({options:y,agents:this.agent}))}l&&(b.body=l),h&&(b.searchParams=h),b.agent=this.agent,b.url=n,b.timeout={request:(this.client&&this.client.options.timeouts||K.TIMEOUTS).httpRequestTimeout},b.retry={limit:0};try{let A=await dc.default[r](b);return this._handler(null,A,A.body)}catch(A){return A instanceof dc.default.HTTPError?this._handler(null,A.response,A.response.body):this._handler(A)}}shouldFallback(r){let{code:n,statusCode:o}=r;return n==="ENETUNREACH"||n==="EHOSTUNREACH"||n==="EHOSTDOWN"||n==="ETIMEDOUT"||n==="ESOCKETTIMEDOUT"||n==="ENOTFOUND"||n==="ECONNRESET"||n==="ECONNREFUSED"||o>=500&&o<=504}_handler(r,n,o){var l;if(r)return{error:r};let h=n.statusCode,f=n.headers;if(h>=300){switch(f["content-type"]){case"application/json":o=JSON.parse(o);break;case"application/x-msgpack":if(!((l=this.client)!=null&&l._MsgPack))return{error:rs("MsgPack")};o=this.client._MsgPack.decode(o);break}return{error:o.error?x.fromValues(o.error):new x(f["x-ably-errormessage"]||"Error response received from server: "+h+" body was: "+L.Config.inspect(o),Number(f["x-ably-errorcode"]),h),body:o,headers:f,unpacked:!0,statusCode:h}}return{error:null,body:o,headers:f,unpacked:!1,statusCode:h}}},us.methods=[ue.Get,ue.Delete,ue.Post,ue.Put,ue.Patch],us.methodsWithoutBody=[ue.Get,ue.Delete],us.methodsWithBody=[ue.Post,ue.Put,ue.Patch],us),Cg=wg,Eg=Q(q("crypto")),kg=Q(pn()),br=Q(q("util")),Og={agent:"nodejs/"+process.versions.node,logTimestamps:!0,userAgent:null,binaryType:"nodebuffer",WebSocket:kg.default,useProtocolHeartbeats:!1,supportsBinary:!0,preferBinary:!0,nextTick:process.nextTick,inspect:br.default.inspect,stringByteSize:Buffer.byteLength,inherits:br.default.inherits,addEventListener:null,getRandomArrayBuffer:async function(r){return br.default.promisify(Eg.default.randomBytes)(r)}},Tg=Og,pc=(r=>(r[r.REQ_SEND=0]="REQ_SEND",r[r.REQ_RECV=1]="REQ_RECV",r[r.REQ_RECV_POLL=2]="REQ_RECV_POLL",r[r.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",r))(pc||{}),lt=pc;function Sg(r){let n=[80015,80017,80030];return r.code?ze.isTokenErr(r)?!1:n.includes(r.code)?!0:r.code>=4e4&&r.code<5e4:!1}function vr(r){return Sg(r)?[ke({action:z.ERROR,error:r})]:[ke({action:z.DISCONNECTED,error:r})]}var Ag=class extends Mt{constructor(r,n,o){super(r,n,o,!0),this.onAuthUpdated=l=>{this.authParams={access_token:l.token}},this.stream="stream"in o?o.stream:!0,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}connect(){d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","starting"),Mt.prototype.connect.call(this);let r=this.params,n=r.options,o=r.host||n.primaryDomain,l=K.getPort(n),h=n.tls?"https://":"http://";this.baseUri=h+o+":"+l+"/comet/";let f=this.baseUri+"connect";d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","uri: "+f),Se(this.auth.getAuthParams(),(y,b)=>{if(y){this.disconnect(y);return}if(this.isDisposed)return;this.authParams=b;let A=this.params.getConnectParams(b);"stream"in A&&(this.stream=A.stream),d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","connectParams:"+ns(A));let I=!1,U=this.recvRequest=this.createRequest(f,null,A,null,this.stream?lt.REQ_RECV_STREAM:lt.REQ_RECV);U.on("data",D=>{this.recvRequest&&(I||(I=!0,this.emit("preconnect")),this.onData(D))}),U.on("complete",D=>{if(this.recvRequest||(D=D||new x("Request cancelled",80003,400)),this.recvRequest=null,!I&&!D&&(I=!0,this.emit("preconnect")),this.onActivity(),D){D.code?this.onData(vr(D)):this.disconnect(D);return}L.Config.nextTick(()=>{this.recv()})}),U.exec()})}requestClose(){d.logAction(this.logger,d.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)}requestDisconnect(){d.logAction(this.logger,d.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)}_requestCloseOrDisconnect(r){let n=r?this.closeUri:this.disconnectUri;if(n){let o=this.createRequest(n,null,this.authParams,null,lt.REQ_SEND);o.on("complete",l=>{l&&(d.logAction(this.logger,d.LOG_ERROR,"CometTransport.request"+(r?"Close()":"Disconnect()"),"request returned err = "+se(l)),this.finish("disconnected",l))}),o.exec()}}dispose(){d.logAction(this.logger,d.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(d.logAction(this.logger,d.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",yt.disconnected()),L.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(r){var n;if(this.isDisposed)return;let o=(n=r.connectionDetails)==null?void 0:n.connectionKey;Mt.prototype.onConnect.call(this,r);let l=this.baseUri+o;d.logAction(this.logger,d.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+l),this.sendUri=l+"/send",this.recvUri=l+"/recv",this.closeUri=l+"/close",this.disconnectUri=l+"/disconnect"}send(r){if(this.sendRequest){this.pendingItems=this.pendingItems||[],this.pendingItems.push(r);return}let n=this.pendingItems||[];n.push(r),this.pendingItems=null,this.sendItems(n)}sendAnyPending(){let r=this.pendingItems;r&&(this.pendingItems=null,this.sendItems(r))}sendItems(r){let n=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(r),lt.REQ_SEND);n.on("complete",(o,l)=>{if(o&&d.logAction(this.logger,d.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+se(o)),this.sendRequest=null,o){o.code?this.onData(vr(o)):this.disconnect(o);return}l&&this.onData(l),this.pendingItems&&L.Config.nextTick(()=>{this.sendRequest||this.sendAnyPending()})}),n.exec()}recv(){if(this.recvRequest||!this.isConnected)return;let r=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?lt.REQ_RECV_STREAM:lt.REQ_RECV_POLL);r.on("data",n=>{this.onData(n)}),r.on("complete",n=>{if(this.recvRequest=null,this.onActivity(),n){n.code?this.onData(vr(n)):this.disconnect(n);return}L.Config.nextTick(()=>{this.recv()})}),r.exec()}onData(r){try{let n=this.decodeResponse(r);if(n&&n.length)for(let o=0;o<n.length;o++)this.onProtocolMessage(cr(n[o],this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin))}catch(n){d.logAction(this.logger,d.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+n.stack)}}encodeRequest(r){return JSON.stringify(r)}decodeResponse(r){return typeof r=="string"?JSON.parse(r):r}},gc=Ag,mc=Q(q("http")),yc=Q(q("https")),Rg=Q(q("url")),Pg=Q(q("util")),Ig=function(){},Mg=ye.Comet,xg=class extends gc{constructor(r,n,o){super(r,n,o),this.httpAgent=null,this.httpsAgent=null,this.pendingRequests=0,this.shortName=Mg}static isAvailable(){return!0}toString(){return"NodeCometTransport; uri="+this.baseUri+"; isConnected="+this.isConnected+"; format="+this.format+"; stream="+this.stream}getAgent(r){var n=r?"httpsAgent":"httpAgent",o=this[n];return o||(o=this[n]=new(r?yc.default:mc.default).Agent({keepAlive:!0})),o}dispose(){var r=this;this.onceNoPending(function(){r.httpAgent&&r.httpAgent.destroy(),r.httpsAgent&&r.httpsAgent.destroy()}),gc.prototype.dispose.call(this)}request(r,n,o,l,h){var f=this.createRequest(r,n,o,l);return f.once("complete",h),f.exec(),f}createRequest(r,n,o,l,h){return new Ng(r,n,o,l,h,this.format,this.timeouts,this)}addPending(){++this.pendingRequests}removePending(){--this.pendingRequests<=0&&this.emit("nopending")}onceNoPending(r){if(this.pendingRequests==0){r();return}this.once("nopending",r)}},Ng=class extends fe{constructor(r,n,o,l,h,f,y,b){super(b.logger),typeof r=="string"&&(r=Rg.default.parse(r));var A=r.protocol=="https:";this.client=A?yc.default:mc.default,this.requestMode=h,this.timeouts=y,this.transport=b,this.requestComplete=!1,this.req=this.res=null;var I="GET",U=f=="msgpack"?"application/x-msgpack":"application/json";n=n?J({},n):{},n.accept=U,l&&(I="POST",Buffer.isBuffer(l)||(typeof l=="object"&&(l=JSON.stringify(l)),l=Buffer.from(l)),this.body=l,n["Content-Length"]=l.length,n["Content-Type"]=U);var D=this.requestOptions={hostname:r.hostname,port:r.port,path:r.path+ns(o),method:I,headers:n};b&&(D.agent=b.getAgent(A))}exec(){var r=this.requestMode==lt.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,n=this,o=this.timer=setTimeout(function(){n.abort()},r),l=this.req=this.client.request(this.requestOptions);l.on("error",this.onReqError=function(h){h=new Te("Request error: "+h.message,null,400),clearTimeout(o),n.timer=null,n.complete(h)}),l.on("response",function(h){clearTimeout(o),n.timer=null;var f=h.statusCode;if(f==is.NoContent){h.resume(),n.complete();return}h.on("error",n.onResError=function(y){y=new Te("Response error: "+y.message,null,400),n.complete(y)}),n.res=h,n.requestMode==lt.REQ_RECV_STREAM&&f<400?n.readStream():n.readFully()}),this.transport&&this.transport.addPending(),l.end(this.body)}readStream(){var r=this.res,n=this;this.chunks=[],this.streamComplete=!1;function o(l){try{l=JSON.parse(l)}catch(f){var h="Malformed response body from server: "+f.message;d.logAction(n.logger,d.LOG_ERROR,"NodeCometTransport.Request.readStream()",h),n.complete(new Te(h,null,400));return}n.emit("data",l)}r.on("data",this.ondata=function(l){var h=String(l).split(`
45
- `),f=n.chunks;h.length>1&&f.length>0&&(f.push(h.shift()),n.chunks=[],o(f.join("")));var y=h.pop();y.length&&n.chunks.push(y),h.map(o)}),r.on("end",function(){n.streamComplete=!0,process.nextTick(function(){n.complete()})})}readFully(){var r=this.res,n=[],o=this;r.on("data",function(l){n.push(l)}),r.on("end",function(){process.nextTick(function(){var l=Buffer.concat(n),h=r.statusCode;try{l=JSON.parse(String(l))}catch(b){var f="Malformed response body from server: "+b.message;d.logAction(o.logger,d.LOG_ERROR,"NodeCometTransport.Request.readFully()",f),o.complete(new Te(f,null,400));return}if(h<400||Array.isArray(l)){o.complete(null,l);return}var y=l.error&&x.fromValues(l.error);y||(y=new Te("Error response received from server: "+h+", body was: "+Pg.default.inspect(l),null,h)),o.complete(y)})})}complete(r,n){this.requestComplete||(this.requestComplete=!0,n&&this.emit("data",n),this.emit("complete",r,n),r&&this.ondata&&!this.streamComplete&&this.ondata&&this.res&&this.res.removeListener("data",this.ondata),this.transport&&this.transport.removePending())}abort(){d.logAction(this.logger,d.LOG_MINOR,"NodeCometTransport.Request.abort()","");var r=this.timer;r&&(clearTimeout(r),this.timer=null);var n=this.req;n&&(d.logAction(this.logger,d.LOG_MINOR,"NodeCometTransport.Request.abort()","aborting request"),n.removeListener("error",this.onReqError),n.on("error",Ig),n.abort(),this.req=null),this.complete({statusCode:400,code:80003,message:"Cancelled"})}},Lg=xg,Dg={order:[ye.Comet],bundledImplementations:{[ye.WebSocket]:cc,[ye.Comet]:Lg}},Ug={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[ye.WebSocket],restAgentOptions:{maxSockets:40,keepAlive:!0}},jg=Ug,qg=gf(),_c=_g(hc);L.Crypto=_c,L.BufferUtils=hc,L.Http=Cg,L.Config=Tg,L.Transports=Dg,L.WebStorage=null;for(let r of[sc,lc])r.Crypto=_c,r._MsgPack=qg;if(d.initLogHandlers(),L.Defaults=jf(jg),L.Config.agent&&(L.Defaults.agent+=" "+L.Config.agent),i.exports={ErrorInfo:x,Rest:sc,Realtime:lc,msgpack:null,makeProtocolMessageFromDeserialized:qp},typeof i.exports=="object"&&typeof t=="object"){var Bg=(r,n,o,l)=>{if(n&&typeof n=="object"||typeof n=="function")for(let h of Object.getOwnPropertyNames(n))!Object.prototype.hasOwnProperty.call(r,h)&&h!==o&&Object.defineProperty(r,h,{get:()=>n[h],enumerable:!(l=Object.getOwnPropertyDescriptor(n,h))||l.enumerable});return r};i.exports=Bg(i.exports,t)}return i.exports})});var xc=wr(Mc(),1),{program:ds,createCommand:Jw,createArgument:Yw,createOption:Qw,CommanderError:Xw,InvalidArgumentError:Zw,InvalidOptionArgumentError:eC,Command:tC,Argument:sC,Option:nC,Help:rC}=xc.default;var of=wr(Bc(),1);import{resolve as rf}from"path";import{existsSync as Bw}from"fs";function Om(s){let e=s.apiKey||process.env.SEGO_API_KEY,t=s.apiUrl||process.env.SEGO_API_URL||"https://sego.pm",i=s.pollIntervalMs||(process.env.AUTO_TASK_POLL_INTERVAL_MS?parseInt(process.env.AUTO_TASK_POLL_INTERVAL_MS,10):3e4),a=s.timeoutMs||(process.env.AUTO_TASK_TIMEOUT_MS?parseInt(process.env.AUTO_TASK_TIMEOUT_MS,10):12e5),c=s.clientRequestTimeoutMs||(process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS?parseInt(process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS,10):3e5);if(!e)throw new Error("API key is required. Set SEGO_API_KEY environment variable or use --api-key flag.");let u=s.projectId||process.env.SEGO_PROJECT_ID,p=s.sseEnabled??process.env.AUTO_TASK_SSE_ENABLED!=="false",g=s.workingDirectory||process.env.SEGO_WORKING_DIR,m=s.useAgentSdk??process.env.USE_CLI_MODE!=="true",_=s.streamProgress??process.env.STREAM_PROGRESS!=="false",w=s.conversationOnly??process.env.CONVERSATION_ONLY==="true",C=s.autoCommit??process.env.AUTO_COMMIT==="true",T=s.autoPush??process.env.AUTO_PUSH==="true",S=s.autoSchemaMigration??process.env.AUTO_SCHEMA_MIGRATION!=="false",O=s.idleTimeoutMinutes??(process.env.IDLE_TIMEOUT_MINUTES?parseInt(process.env.IDLE_TIMEOUT_MINUTES,10):0),k=s.healthPort??(process.env.HEALTH_PORT?parseInt(process.env.HEALTH_PORT,10):3001);return{apiKey:e,apiUrl:t,pollIntervalMs:i,timeoutMs:a,dryRun:s.dryRun??!1,projectId:u,sseEnabled:p,clientRequestTimeoutMs:c,workingDirectory:g,useAgentSdk:m,streamProgress:_,conversationOnly:w,autoCommit:C,autoPush:T,autoSchemaMigration:S,idleTimeoutMinutes:O,healthPort:k}}function $c(s){let e={apiKey:s.apiKey?"cli":process.env.SEGO_API_KEY?"env":"default",apiUrl:s.apiUrl?"cli":process.env.SEGO_API_URL?"env":"default",pollIntervalMs:s.pollIntervalMs?"cli":process.env.AUTO_TASK_POLL_INTERVAL_MS?"env":"default",timeoutMs:s.timeoutMs?"cli":process.env.AUTO_TASK_TIMEOUT_MS?"env":"default",dryRun:s.dryRun!==void 0?"cli":"default",projectId:s.projectId?"cli":process.env.SEGO_PROJECT_ID?"env":"default",sseEnabled:s.sseEnabled!==void 0?"cli":process.env.AUTO_TASK_SSE_ENABLED?"env":"default",clientRequestTimeoutMs:s.clientRequestTimeoutMs?"cli":process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS?"env":"default",workingDirectory:s.workingDirectory?"cli":process.env.SEGO_WORKING_DIR?"env":"default",useAgentSdk:s.useAgentSdk!==void 0?"cli":process.env.USE_CLI_MODE?"env":"default",streamProgress:s.streamProgress!==void 0?"cli":process.env.STREAM_PROGRESS?"env":"default",conversationOnly:s.conversationOnly!==void 0?"cli":process.env.CONVERSATION_ONLY?"env":"default",autoCommit:s.autoCommit!==void 0?"cli":process.env.AUTO_COMMIT?"env":"default",autoPush:s.autoPush!==void 0?"cli":process.env.AUTO_PUSH?"env":"default",autoSchemaMigration:s.autoSchemaMigration!==void 0?"cli":process.env.AUTO_SCHEMA_MIGRATION?"env":"default",idleTimeoutMinutes:s.idleTimeoutMinutes!==void 0?"cli":process.env.IDLE_TIMEOUT_MINUTES?"env":"default",healthPort:s.healthPort!==void 0?"cli":process.env.HEALTH_PORT?"env":"default"};return{config:Om(s),sources:e}}function we(s){switch(s){case"cli":return"[cli]";case"env":return"[env]";case"default":return"[default]"}}var Qs=class{baseUrl;apiKey;projectId;constructor(e,t,i){this.baseUrl=e.replace(/\/$/,""),this.apiKey=t,this.projectId=i}async request(e,t={}){let i=`${this.baseUrl}${e}`,a=await fetch(i,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"ngrok-skip-browser-warning":"true",...t.headers}});if(!a.ok){let c=await a.text(),u;try{let p=JSON.parse(c);u=p.error||p.message||c}catch{u=c}throw new Error(`API error (${a.status}): ${u}`)}return a.json()}async getEligibleTask(){let e=this.projectId?`/api/mcp/tasks/auto-task/eligible?projectId=${this.projectId}`:"/api/mcp/tasks/auto-task/eligible";return(await this.request(e)).task}async startTask(e){return this.request("/api/mcp/tasks/auto-task/start",{method:"POST",body:JSON.stringify({taskId:e})})}async completeTask(e,t,i){return this.request("/api/mcp/tasks/auto-task/complete",{method:"POST",body:JSON.stringify({runId:e,status:t,comment:i?.comment,errorMessage:i?.errorMessage,costUsd:i?.costUsd,tokensUsed:i?.tokensUsed})})}async sendAlert(e,t,i){return this.request("/api/notifications/auto-task-alert",{method:"POST",body:JSON.stringify({runId:e,alertType:t,errorDetails:i})})}async validateAuth(){let e=`${this.baseUrl}/api/mcp/auth/validate`;console.log(`[API] Validating auth against: ${e}`);try{let t=await this.request("/api/mcp/auth/validate",{method:"POST"});return console.log(`[API] Auth validated for user: ${t.user?.email||"unknown"}`),!0}catch(t){if(t instanceof Error){if(console.error(`[API] Auth validation failed: ${t.message}`),"cause"in t&&t.cause){console.error(`[API] Cause: ${t.cause instanceof Error?t.cause.message:String(t.cause)}`);let i=t.cause;i.code&&console.error(`[API] Error code: ${i.code}`)}}else console.error("[API] Auth validation failed:",t);return!1}}getClientRequestMonitorUrl(){if(!this.projectId)throw new Error("Project ID is required for client request monitoring");return`${this.baseUrl}/api/projects/${this.projectId}/client-requests/monitor`}getApiKey(){return this.apiKey}getProjectId(){return this.projectId}async submitAnalysis(e,t,i,a,c){return this.request(`/api/client-requests/${e}/analysis`,{method:"POST",body:JSON.stringify({monitorId:t,analysis:i,processingTimeMs:a,costUsd:c?.costUsd,tokensUsed:c?.tokensUsed,inputTokens:c?.inputTokens,outputTokens:c?.outputTokens})})}async reportAnalysisFailure(e,t,i){return this.request(`/api/client-requests/${e}/analysis`,{method:"PUT",body:JSON.stringify({monitorId:t,error:i})})}async getClientRequest(e){try{let i=(await this.request(`/api/client-requests/${e}`)).request,a=i.project.brief;return{id:i.id,projectId:i.projectId,description:i.description,channel:i.channel,createdById:i.createdById,createdAt:i.createdAt,updatedAt:i.updatedAt,conversationMode:i.conversationMode,planFilePath:i.planFilePath,existingTasks:i.project.tasks,projectContext:{projectName:i.project.name,projectDescription:i.project.description,techStack:a?.techStack?.split(",").map(c=>c.trim()),existingFeatures:i.project.tasks?.map(c=>c.title),knowledgeBase:i.project.knowledgeBase||void 0}}}catch(t){return console.error(`[ApiClient] Failed to fetch client request ${e}:`,t),null}}async updatePlanFilePath(e,t){return{success:!0,requestId:(await this.request(`/api/client-requests/${e}`,{method:"PATCH",body:JSON.stringify({planFilePath:t})})).request.id}}async claimTask(e,t){if(!this.projectId)throw new Error("Project ID is required for claiming tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/claim`,{method:"POST",body:JSON.stringify({monitorId:t})})}async completeBacklogTask(e,t,i,a){if(!this.projectId)throw new Error("Project ID is required for completing tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/complete`,{method:"POST",body:JSON.stringify({monitorId:t,result:i,costUsd:a?.costUsd,tokensUsed:a?.tokensUsed})})}async failBacklogTask(e,t,i,a=!0){if(!this.projectId)throw new Error("Project ID is required for failing tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/fail`,{method:"POST",body:JSON.stringify({monitorId:t,error:i,returnToBacklog:a})})}formatEventPayload(e){return{type:e.type,timestamp:e.timestamp,message:e.message,emoji:e.emoji,data:e.data}}async sendAgentProgress(e,t,i){return this.request(`/api/client-requests/${e}/progress`,{method:"POST",body:JSON.stringify({monitorId:t,event:this.formatEventPayload(i)})})}async sendTaskAgentProgress(e,t,i){if(!this.projectId)throw new Error("Project ID is required for task progress events");return this.request(`/api/projects/${this.projectId}/tasks/${e}/progress`,{method:"POST",body:JSON.stringify({monitorId:t,event:this.formatEventPayload(i)})})}};import{spawn as Xs}from"child_process";import{existsSync as Hc,writeFileSync as Gc,unlinkSync as Fc}from"fs";import{homedir as Tm,tmpdir as Wc}from"os";import{join as qr}from"path";function Zs(){let s=[qr(Tm(),".claude","local","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude"];for(let e of s)if(Hc(e))return e;return"claude"}var _e=null;function Sm(s){let e=[`# Task: ${s.title}`,"",`**Project:** ${s.project.name}`,`**Priority:** ${s.priority}`,`**Type:** ${s.type}`,"","## Description",s.description,""];return s.acceptanceCriteria.length>0&&(e.push("## Acceptance Criteria"),s.acceptanceCriteria.forEach((t,i)=>{e.push(`${i+1}. ${t}`)}),e.push("")),s.technicalNotes&&(e.push("## Technical Notes"),e.push(s.technicalNotes),e.push("")),s.project.knowledgeBase&&(e.push("## Project Context"),e.push(s.project.knowledgeBase),e.push("")),e.push("---"),e.push(""),e.push("## Instructions"),e.push(""),e.push("Please work on this task."),e.push(""),e.push("**Work efficiently:**"),e.push("- Focus only on what's needed to meet the acceptance criteria"),e.push("- Avoid unnecessary exploration or refactoring beyond the scope"),e.push("- Make targeted file reads instead of scanning the entire codebase"),e.push("- If you have enough context, proceed with implementation"),e.push(""),e.push('When you have completed the task, output "TASK_COMPLETE" on its own line.'),e.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),e.join(`
45
+ `),f=n.chunks;h.length>1&&f.length>0&&(f.push(h.shift()),n.chunks=[],o(f.join("")));var y=h.pop();y.length&&n.chunks.push(y),h.map(o)}),r.on("end",function(){n.streamComplete=!0,process.nextTick(function(){n.complete()})})}readFully(){var r=this.res,n=[],o=this;r.on("data",function(l){n.push(l)}),r.on("end",function(){process.nextTick(function(){var l=Buffer.concat(n),h=r.statusCode;try{l=JSON.parse(String(l))}catch(b){var f="Malformed response body from server: "+b.message;d.logAction(o.logger,d.LOG_ERROR,"NodeCometTransport.Request.readFully()",f),o.complete(new Te(f,null,400));return}if(h<400||Array.isArray(l)){o.complete(null,l);return}var y=l.error&&x.fromValues(l.error);y||(y=new Te("Error response received from server: "+h+", body was: "+Pg.default.inspect(l),null,h)),o.complete(y)})})}complete(r,n){this.requestComplete||(this.requestComplete=!0,n&&this.emit("data",n),this.emit("complete",r,n),r&&this.ondata&&!this.streamComplete&&this.ondata&&this.res&&this.res.removeListener("data",this.ondata),this.transport&&this.transport.removePending())}abort(){d.logAction(this.logger,d.LOG_MINOR,"NodeCometTransport.Request.abort()","");var r=this.timer;r&&(clearTimeout(r),this.timer=null);var n=this.req;n&&(d.logAction(this.logger,d.LOG_MINOR,"NodeCometTransport.Request.abort()","aborting request"),n.removeListener("error",this.onReqError),n.on("error",Ig),n.abort(),this.req=null),this.complete({statusCode:400,code:80003,message:"Cancelled"})}},Lg=xg,Dg={order:[ye.Comet],bundledImplementations:{[ye.WebSocket]:cc,[ye.Comet]:Lg}},Ug={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[ye.WebSocket],restAgentOptions:{maxSockets:40,keepAlive:!0}},jg=Ug,qg=gf(),_c=_g(hc);L.Crypto=_c,L.BufferUtils=hc,L.Http=Cg,L.Config=Tg,L.Transports=Dg,L.WebStorage=null;for(let r of[sc,lc])r.Crypto=_c,r._MsgPack=qg;if(d.initLogHandlers(),L.Defaults=jf(jg),L.Config.agent&&(L.Defaults.agent+=" "+L.Config.agent),i.exports={ErrorInfo:x,Rest:sc,Realtime:lc,msgpack:null,makeProtocolMessageFromDeserialized:qp},typeof i.exports=="object"&&typeof t=="object"){var Bg=(r,n,o,l)=>{if(n&&typeof n=="object"||typeof n=="function")for(let h of Object.getOwnPropertyNames(n))!Object.prototype.hasOwnProperty.call(r,h)&&h!==o&&Object.defineProperty(r,h,{get:()=>n[h],enumerable:!(l=Object.getOwnPropertyDescriptor(n,h))||l.enumerable});return r};i.exports=Bg(i.exports,t)}return i.exports})});var xc=wr(Mc(),1),{program:ds,createCommand:Zw,createArgument:eC,createOption:tC,CommanderError:sC,InvalidArgumentError:nC,InvalidOptionArgumentError:rC,Command:iC,Argument:oC,Option:aC,Help:cC}=xc.default;var of=wr(Bc(),1);import{resolve as rf}from"path";import{existsSync as Fw}from"fs";function Om(s){let e=s.apiKey||process.env.SEGO_API_KEY,t=s.apiUrl||process.env.SEGO_API_URL||"https://sego.pm",i=s.pollIntervalMs||(process.env.AUTO_TASK_POLL_INTERVAL_MS?parseInt(process.env.AUTO_TASK_POLL_INTERVAL_MS,10):3e4),a=s.timeoutMs||(process.env.AUTO_TASK_TIMEOUT_MS?parseInt(process.env.AUTO_TASK_TIMEOUT_MS,10):12e5),c=s.clientRequestTimeoutMs||(process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS?parseInt(process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS,10):3e5);if(!e)throw new Error("API key is required. Set SEGO_API_KEY environment variable or use --api-key flag.");let u=s.projectId||process.env.SEGO_PROJECT_ID,p=s.sseEnabled??process.env.AUTO_TASK_SSE_ENABLED!=="false",g=s.workingDirectory||process.env.SEGO_WORKING_DIR,m=s.useAgentSdk??process.env.USE_CLI_MODE!=="true",_=s.streamProgress??process.env.STREAM_PROGRESS!=="false",w=s.conversationOnly??process.env.CONVERSATION_ONLY==="true",C=s.autoCommit??process.env.AUTO_COMMIT==="true",T=s.autoPush??process.env.AUTO_PUSH==="true",S=s.autoSchemaMigration??process.env.AUTO_SCHEMA_MIGRATION!=="false",O=s.idleTimeoutMinutes??(process.env.IDLE_TIMEOUT_MINUTES?parseInt(process.env.IDLE_TIMEOUT_MINUTES,10):0),k=s.healthPort??(process.env.HEALTH_PORT?parseInt(process.env.HEALTH_PORT,10):3001);return{apiKey:e,apiUrl:t,pollIntervalMs:i,timeoutMs:a,dryRun:s.dryRun??!1,projectId:u,sseEnabled:p,clientRequestTimeoutMs:c,workingDirectory:g,useAgentSdk:m,streamProgress:_,conversationOnly:w,autoCommit:C,autoPush:T,autoSchemaMigration:S,idleTimeoutMinutes:O,healthPort:k}}function $c(s){let e={apiKey:s.apiKey?"cli":process.env.SEGO_API_KEY?"env":"default",apiUrl:s.apiUrl?"cli":process.env.SEGO_API_URL?"env":"default",pollIntervalMs:s.pollIntervalMs?"cli":process.env.AUTO_TASK_POLL_INTERVAL_MS?"env":"default",timeoutMs:s.timeoutMs?"cli":process.env.AUTO_TASK_TIMEOUT_MS?"env":"default",dryRun:s.dryRun!==void 0?"cli":"default",projectId:s.projectId?"cli":process.env.SEGO_PROJECT_ID?"env":"default",sseEnabled:s.sseEnabled!==void 0?"cli":process.env.AUTO_TASK_SSE_ENABLED?"env":"default",clientRequestTimeoutMs:s.clientRequestTimeoutMs?"cli":process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS?"env":"default",workingDirectory:s.workingDirectory?"cli":process.env.SEGO_WORKING_DIR?"env":"default",useAgentSdk:s.useAgentSdk!==void 0?"cli":process.env.USE_CLI_MODE?"env":"default",streamProgress:s.streamProgress!==void 0?"cli":process.env.STREAM_PROGRESS?"env":"default",conversationOnly:s.conversationOnly!==void 0?"cli":process.env.CONVERSATION_ONLY?"env":"default",autoCommit:s.autoCommit!==void 0?"cli":process.env.AUTO_COMMIT?"env":"default",autoPush:s.autoPush!==void 0?"cli":process.env.AUTO_PUSH?"env":"default",autoSchemaMigration:s.autoSchemaMigration!==void 0?"cli":process.env.AUTO_SCHEMA_MIGRATION?"env":"default",idleTimeoutMinutes:s.idleTimeoutMinutes!==void 0?"cli":process.env.IDLE_TIMEOUT_MINUTES?"env":"default",healthPort:s.healthPort!==void 0?"cli":process.env.HEALTH_PORT?"env":"default"};return{config:Om(s),sources:e}}function we(s){switch(s){case"cli":return"[cli]";case"env":return"[env]";case"default":return"[default]"}}var Qs=class{baseUrl;apiKey;projectId;constructor(e,t,i){this.baseUrl=e.replace(/\/$/,""),this.apiKey=t,this.projectId=i}async request(e,t={}){let i=`${this.baseUrl}${e}`,a=await fetch(i,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"ngrok-skip-browser-warning":"true",...t.headers}});if(!a.ok){let c=await a.text(),u;try{let p=JSON.parse(c);u=p.error||p.message||c}catch{u=c}throw new Error(`API error (${a.status}): ${u}`)}return a.json()}async getEligibleTask(){let e=this.projectId?`/api/mcp/tasks/auto-task/eligible?projectId=${this.projectId}`:"/api/mcp/tasks/auto-task/eligible";return(await this.request(e)).task}async startTask(e){return this.request("/api/mcp/tasks/auto-task/start",{method:"POST",body:JSON.stringify({taskId:e})})}async completeTask(e,t,i){return this.request("/api/mcp/tasks/auto-task/complete",{method:"POST",body:JSON.stringify({runId:e,status:t,comment:i?.comment,errorMessage:i?.errorMessage,costUsd:i?.costUsd,tokensUsed:i?.tokensUsed})})}async sendAlert(e,t,i){return this.request("/api/notifications/auto-task-alert",{method:"POST",body:JSON.stringify({runId:e,alertType:t,errorDetails:i})})}async validateAuth(){let e=`${this.baseUrl}/api/mcp/auth/validate`;console.log(`[API] Validating auth against: ${e}`);try{let t=await this.request("/api/mcp/auth/validate",{method:"POST"});return console.log(`[API] Auth validated for user: ${t.user?.email||"unknown"}`),!0}catch(t){if(t instanceof Error){if(console.error(`[API] Auth validation failed: ${t.message}`),"cause"in t&&t.cause){console.error(`[API] Cause: ${t.cause instanceof Error?t.cause.message:String(t.cause)}`);let i=t.cause;i.code&&console.error(`[API] Error code: ${i.code}`)}}else console.error("[API] Auth validation failed:",t);return!1}}getClientRequestMonitorUrl(){if(!this.projectId)throw new Error("Project ID is required for client request monitoring");return`${this.baseUrl}/api/projects/${this.projectId}/client-requests/monitor`}getApiKey(){return this.apiKey}getProjectId(){return this.projectId}async submitAnalysis(e,t,i,a,c){return this.request(`/api/client-requests/${e}/analysis`,{method:"POST",body:JSON.stringify({monitorId:t,analysis:i,processingTimeMs:a,costUsd:c?.costUsd,tokensUsed:c?.tokensUsed,inputTokens:c?.inputTokens,outputTokens:c?.outputTokens})})}async reportAnalysisFailure(e,t,i){return this.request(`/api/client-requests/${e}/analysis`,{method:"PUT",body:JSON.stringify({monitorId:t,error:i})})}async getClientRequest(e){try{let i=(await this.request(`/api/client-requests/${e}`)).request,a=i.project.brief;return{id:i.id,projectId:i.projectId,description:i.description,channel:i.channel,createdById:i.createdById,createdAt:i.createdAt,updatedAt:i.updatedAt,conversationMode:i.conversationMode,planFilePath:i.planFilePath,existingTasks:i.project.tasks,projectContext:{projectName:i.project.name,projectDescription:i.project.description,techStack:a?.techStack?.split(",").map(c=>c.trim()),existingFeatures:i.project.tasks?.map(c=>c.title),knowledgeBase:i.project.knowledgeBase||void 0}}}catch(t){return console.error(`[ApiClient] Failed to fetch client request ${e}:`,t),null}}async updatePlanFilePath(e,t){return{success:!0,requestId:(await this.request(`/api/client-requests/${e}`,{method:"PATCH",body:JSON.stringify({planFilePath:t})})).request.id}}async claimTask(e,t){if(!this.projectId)throw new Error("Project ID is required for claiming tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/claim`,{method:"POST",body:JSON.stringify({monitorId:t})})}async completeBacklogTask(e,t,i,a){if(!this.projectId)throw new Error("Project ID is required for completing tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/complete`,{method:"POST",body:JSON.stringify({monitorId:t,result:i,costUsd:a?.costUsd,tokensUsed:a?.tokensUsed})})}async failBacklogTask(e,t,i,a=!0){if(!this.projectId)throw new Error("Project ID is required for failing tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/fail`,{method:"POST",body:JSON.stringify({monitorId:t,error:i,returnToBacklog:a})})}formatEventPayload(e){return{type:e.type,timestamp:e.timestamp,message:e.message,emoji:e.emoji,data:e.data}}async sendAgentProgress(e,t,i){return this.request(`/api/client-requests/${e}/progress`,{method:"POST",body:JSON.stringify({monitorId:t,event:this.formatEventPayload(i)})})}async sendTaskAgentProgress(e,t,i){if(!this.projectId)throw new Error("Project ID is required for task progress events");return this.request(`/api/projects/${this.projectId}/tasks/${e}/progress`,{method:"POST",body:JSON.stringify({monitorId:t,event:this.formatEventPayload(i)})})}};import{spawn as Xs}from"child_process";import{existsSync as Hc,writeFileSync as Gc,unlinkSync as Fc}from"fs";import{homedir as Tm,tmpdir as Wc}from"os";import{join as qr}from"path";function Zs(){let s=[qr(Tm(),".claude","local","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude"];for(let e of s)if(Hc(e))return e;return"claude"}var _e=null;function Sm(s){let e=[`# Task: ${s.title}`,"",`**Project:** ${s.project.name}`,`**Priority:** ${s.priority}`,`**Type:** ${s.type}`,"","## Description",s.description,""];return s.acceptanceCriteria.length>0&&(e.push("## Acceptance Criteria"),s.acceptanceCriteria.forEach((t,i)=>{e.push(`${i+1}. ${t}`)}),e.push("")),s.technicalNotes&&(e.push("## Technical Notes"),e.push(s.technicalNotes),e.push("")),s.project.knowledgeBase&&(e.push("## Project Context"),e.push(s.project.knowledgeBase),e.push("")),e.push("---"),e.push(""),e.push("## Instructions"),e.push(""),e.push("Please work on this task."),e.push(""),e.push("**Work efficiently:**"),e.push("- Focus only on what's needed to meet the acceptance criteria"),e.push("- Avoid unnecessary exploration or refactoring beyond the scope"),e.push("- Make targeted file reads instead of scanning the entire codebase"),e.push("- If you have enough context, proceed with implementation"),e.push(""),e.push('When you have completed the task, output "TASK_COMPLETE" on its own line.'),e.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),e.join(`
46
46
  `)}async function Vc(s,e){let t=Sm(s);return _e||(_e=Zs()),new Promise(i=>{let a="",c="",u=!1,p=!1,g=Xs(_e,["--print","--dangerously-skip-permissions","--mcp-config",'{"mcpServers":{}}'],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:process.cwd()}});g.stdin?.write(t),g.stdin?.end();let m=setTimeout(()=>{u=!0,p=!0,g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},5e3)},e);g.stdout?.on("data",_=>{a+=_.toString()}),g.stderr?.on("data",_=>{c+=_.toString()}),g.on("close",_=>{if(clearTimeout(m),u){i({success:!1,output:a,error:"Process timed out",timedOut:!0});return}let w=a.includes("TASK_COMPLETE")&&!a.includes("TASK_BLOCKED");if(_!==0&&!p){i({success:!1,output:a,error:c||`Process exited with code ${_}`,timedOut:!1});return}let C=a.match(/TASK_BLOCKED:\s*(.+)/i);if(C){i({success:!1,output:a,error:`Task blocked: ${C[1]}`,timedOut:!1});return}i({success:w,output:a,error:w?void 0:"Task did not complete successfully",timedOut:!1})}),g.on("error",_=>{clearTimeout(m),i({success:!1,output:a,error:`Failed to spawn claude: ${_.message}`,timedOut:!1})})})}async function zc(){return _e=Zs(),_e&&_e!=="claude"&&Hc(_e)?(console.log(`Found Claude CLI at: ${_e}`),!0):new Promise(s=>{let e=Xs(_e,["--version"],{stdio:["pipe","pipe","pipe"]});e.on("close",t=>{s(t===0)}),e.on("error",()=>{s(!1)}),setTimeout(()=>{e.kill(),s(!1)},5e3)})}function Am(s){let e=["# Client Request Analysis","","You are an expert software architect and project manager. A client has submitted a request for their project.","Your job is to analyze this request and break it down into actionable development tasks.","","## Client Request","",s.description,"","## Project Context","",`**Project Name:** ${s.projectContext.projectName}`];return s.projectContext.projectDescription&&e.push(`**Description:** ${s.projectContext.projectDescription}`),s.projectContext.techStack&&s.projectContext.techStack.length>0&&e.push(`**Tech Stack:** ${s.projectContext.techStack.join(", ")}`),s.projectContext.existingFeatures&&s.projectContext.existingFeatures.length>0&&(e.push(""),e.push("**Existing Features/Tasks:**"),s.projectContext.existingFeatures.forEach(t=>{e.push(`- ${t}`)})),e.push(""),e.push("---"),e.push(""),e.push("## Instructions"),e.push(""),e.push("Analyze this client request and produce a structured JSON response. You have access to the full codebase, so:"),e.push("1. Explore the codebase to understand the existing architecture and patterns"),e.push("2. Identify the specific files and components that would need to be modified"),e.push("3. Break down the request into 2-6 specific, actionable tasks"),e.push("4. Provide accurate time estimates based on the actual complexity you observe in the code"),e.push(""),e.push("Output your analysis as a JSON object with this structure:"),e.push("```json"),e.push("{"),e.push(' "summary": "Brief summary of what the client wants",'),e.push(' "reasoning": "Your analysis of how to approach this",'),e.push(' "suggestedTasks": ['),e.push(" {"),e.push(' "title": "Task title",'),e.push(' "description": "Detailed description",'),e.push(' "acceptanceCriteria": ["Criterion 1", "Criterion 2"],'),e.push(' "estimatedHours": 4,'),e.push(' "priority": "MEDIUM",'),e.push(' "type": "FEATURE",'),e.push(' "technicalNotes": "Implementation details",'),e.push(' "questionsForClient": [],'),e.push(' "aiConfidence": 0.85'),e.push(" }"),e.push(" ],"),e.push(' "questionsForClient": ["Any clarifying questions"],'),e.push(' "estimatedTotalHours": 12,'),e.push(' "aiConfidence": 0.85'),e.push("}"),e.push("```"),e.push(""),e.push("Valid priority values: LOW, MEDIUM, HIGH, URGENT"),e.push("Valid type values: FEATURE, BUG, ENHANCEMENT, DOCUMENTATION, DESIGN, TECHNICAL_DEBT"),e.push("aiConfidence should be between 0 and 1"),e.push(""),e.push("IMPORTANT: Output ONLY the JSON object, no additional text before or after."),e.join(`
47
47
  `)}function Rm(s){let e=s.match(/```(?:json)?\s*([\s\S]*?)```/);if(e)try{return JSON.parse(e[1].trim())}catch{}let t=s.match(/\{[\s\S]*\}/);if(t)try{return JSON.parse(t[0])}catch{}return null}async function Kc(s,e,t={}){let i=Am(s),a=t.verbose??!0;return a&&(console.log("[Claude] Starting analysis..."),console.log("[Claude] Prompt length:",i.length,"characters")),_e||(_e=Zs()),new Promise(c=>{let u="",p="",g=!1,m=!1;a&&console.log("[Claude] Spawning Claude CLI via shell with temp file...");let _=qr(Wc(),`claude-prompt-${Date.now()}.txt`);Gc(_,i,"utf-8");let w=`cat "${_}" | ${_e} --print --dangerously-skip-permissions`;a&&(console.log("[Claude] Working directory:",process.cwd()),console.log("[Claude] Temp file:",_),console.log("[Claude] Running via shell..."));let C=Xs("sh",["-c",w],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:process.cwd()},cwd:process.cwd()});a&&console.log("[Claude] Shell process started with PID:",C.pid),C.stdin?.end();let T=()=>{try{Fc(_),a&&console.log("[Claude] Temp file cleaned up")}catch{}},S=setTimeout(()=>{g=!0,m=!0,console.log("[Claude] Timeout reached, killing process..."),C.kill("SIGTERM"),setTimeout(()=>{C.killed||C.kill("SIGKILL")},5e3)},e);C.stdout?.on("data",O=>{let k=O.toString();u+=k,a&&process.stdout.write(k)}),C.stderr?.on("data",O=>{let k=O.toString();p+=k,a&&process.stderr.write(`[Claude stderr] ${k}`)}),C.on("close",(O,k)=>{clearTimeout(S),T(),a&&(console.log(""),console.log(`[Claude] Process exited with code ${O}, signal ${k}`),console.log(`[Claude] Output length: ${u.length} characters`),console.log(`[Claude] Error output length: ${p.length} characters`),p&&console.log(`[Claude] Stderr: ${p.substring(0,500)}`));let N=Rm(u);if(N&&N.summary&&Array.isArray(N.suggestedTasks)){a&&g&&console.log("[Claude] Timeout was triggered but we got valid output - treating as success"),c({success:!0,analysis:N,output:u,timedOut:!1});return}if(g){c({success:!1,output:u,error:"Process timed out without producing valid output",timedOut:!0});return}if(O!==0&&!m){c({success:!1,output:u,error:p||`Process exited with code ${O}`,timedOut:!1});return}if(!N){c({success:!1,output:u,error:"Failed to parse analysis JSON from output",timedOut:!1});return}if(!N.summary||!Array.isArray(N.suggestedTasks)){c({success:!1,output:u,error:"Invalid analysis structure - missing required fields",timedOut:!1});return}c({success:!0,analysis:N,output:u,timedOut:!1})}),C.on("error",O=>{clearTimeout(S),console.error("[Claude] Spawn error:",O),c({success:!1,output:u,error:`Failed to spawn claude: ${O.message}`,timedOut:!1})}),C.on("spawn",()=>{a&&console.log("[Claude] Process spawned successfully")})})}function Pm(s){let e=[`# Task: ${s.title}`,"",`**Project:** ${s.projectContext.projectName}`,`**Priority:** ${s.priority}`,`**Type:** ${s.type}`,`**Estimated Hours:** ${s.estimatedHours||"N/A"}`,"","## Description",s.description||"No description provided.",""];if(s.acceptanceCriteria&&s.acceptanceCriteria.length>0&&(e.push("## Acceptance Criteria"),s.acceptanceCriteria.forEach((t,i)=>{e.push(`${i+1}. ${t}`)}),e.push("")),s.technicalNotes&&(e.push("## Technical Notes"),e.push(s.technicalNotes),e.push("")),s.projectContext.projectDescription&&(e.push("## Project Description"),e.push(s.projectContext.projectDescription),e.push("")),s.projectContext.knowledgeBase){e.push("## Project Knowledge Base");let t=s.projectContext.knowledgeBase;t.length>1e4?e.push(t.substring(0,1e4)+`
48
48
 
@@ -54,19 +54,19 @@ ${Yc(s)}`,i=[];for(let a of Im){let c=Lt.join(s,a),u=Nm(c);u!==null&&i.push({pat
54
54
  `)}function Zc(s){let e=Lt.join(s,"src/index.ts");return Nt.existsSync(e)}function Lm(s,e){let t=e;switch(s){case"Read":return{emoji:"\u{1F4D6}",message:`Reading file: ${t?.file_path||"unknown"}`};case"Write":return{emoji:"\u270F\uFE0F",message:`Writing file: ${t?.file_path||"unknown"}`};case"Edit":return{emoji:"\u{1F4DD}",message:`Editing file: ${t?.file_path||"unknown"}`};case"Glob":return{emoji:"\u{1F50D}",message:`Searching for files: ${t?.pattern||"unknown pattern"}`};case"Grep":return{emoji:"\u{1F50E}",message:`Searching code: ${t?.pattern||"unknown pattern"}`};case"Bash":return{emoji:"\u{1F4BB}",message:`Running command: ${String(t?.command||"").substring(0,80)}${String(t?.command||"").length>80?"...":""}`};case"WebSearch":return{emoji:"\u{1F310}",message:`Web search: ${t?.query||"unknown query"}`};case"WebFetch":return{emoji:"\u{1F310}",message:`Fetching URL: ${t?.url||"unknown"}`};case"Task":return{emoji:"\u{1F916}",message:`Running sub-agent: ${t?.description||"task"}`};case"TodoWrite":return{emoji:"\u{1F4CB}",message:"Updating task list"};default:return{emoji:"\u{1F527}",message:`Using tool: ${s}`}}}function $r(s){let e={type:s.type,timestamp:s.timestamp};switch(s.type){case"tool_start":{let t=s.data,{message:i,emoji:a}=Lm(t.tool,t.input);return{...e,emoji:a,message:i,data:{toolUseId:t.toolUseId,tool:t.tool}}}case"tool_end":{let t=s.data;return{...e,emoji:t.isError?"\u274C":"\u2705",message:t.isError?"Tool failed":"Tool completed",data:{toolUseId:t.toolUseId}}}case"thinking":{let t=s.data,i=t.text.substring(0,150);return{...e,emoji:"\u{1F4AD}",message:`${i}${t.text.length>150?"...":""}`}}case"assistant_message":{let t=s.data,i=t.text.substring(0,200);return{...e,emoji:"\u{1F4AC}",message:`${i}${t.text.length>200?"...":""}`,data:{text:t.text,uuid:t.uuid}}}case"result":{let t=s.data;return{...e,emoji:t.success?"\u{1F389}":"\u26A0\uFE0F",message:t.success?"Analysis complete":"Analysis completed with issues",data:t}}case"error":{let t=s.data;return{...e,emoji:"\u2757",message:`Error: ${t.error}`,data:t}}case"session_start":return{...e,emoji:"\u{1F680}",message:"Starting analysis..."};case"processing":{let t=s.data;return{...e,emoji:"\u23F3",message:t.message||`Processing... (${Math.round((t.elapsedMs||0)/1e3)}s)`,data:t}}case"phase":{let t=s.data;return{...e,emoji:{claiming:"\u{1F4CB}",analyzing:"\u{1F50D}",implementing:"\u{1F6E0}\uFE0F",testing:"\u{1F9EA}",committing:"\u{1F4BE}","schema-migration":"\u{1F5C4}\uFE0F",completed:"\u2705",error:"\u274C"}[t.phase]||"\u2139\uFE0F",message:t.message,data:t}}default:return{...e,emoji:"\u2139\uFE0F",message:`Event: ${s.type}`,data:s.data}}}function Dm(s){let e=["# Client Request Analysis","","You are an expert software architect and project manager. A client has submitted a request for their project.","Your job is to analyze this request and break it down into actionable development tasks.","","## Client Request","",s.description,"","## Project Context","",`**Project Name:** ${s.projectContext.projectName}`];return s.projectContext.projectDescription&&e.push(`**Description:** ${s.projectContext.projectDescription}`),s.projectContext.techStack&&s.projectContext.techStack.length>0&&e.push(`**Tech Stack:** ${s.projectContext.techStack.join(", ")}`),s.projectContext.existingFeatures&&s.projectContext.existingFeatures.length>0&&(e.push(""),e.push("**Existing Features/Tasks:**"),s.projectContext.existingFeatures.forEach(t=>{e.push(`- ${t}`)})),e.push(""),e.push("---"),e.push(""),e.push("## Instructions"),e.push(""),e.push("Analyze this client request and produce a structured JSON response. You have access to the full codebase, so:"),e.push("1. Explore the codebase to understand the existing architecture and patterns"),e.push("2. Identify the specific files and components that would need to be modified"),e.push("3. Break down the request into 2-6 specific, actionable tasks"),e.push("4. Provide accurate time estimates based on the actual complexity you observe in the code"),e.push(""),e.push("Output your analysis as a JSON object with this structure:"),e.push("```json"),e.push("{"),e.push(' "summary": "Brief summary of what the client wants",'),e.push(' "reasoning": "Your analysis of how to approach this",'),e.push(' "suggestedTasks": ['),e.push(" {"),e.push(' "title": "Task title",'),e.push(' "description": "Detailed description",'),e.push(' "acceptanceCriteria": ["Criterion 1", "Criterion 2"],'),e.push(' "estimatedHours": 4,'),e.push(' "priority": "MEDIUM",'),e.push(' "type": "FEATURE",'),e.push(' "technicalNotes": "Implementation details",'),e.push(' "questionsForClient": [],'),e.push(' "aiConfidence": 0.85'),e.push(" }"),e.push(" ],"),e.push(' "questionsForClient": ["Any clarifying questions"],'),e.push(' "estimatedTotalHours": 12,'),e.push(' "aiConfidence": 0.85'),e.push("}"),e.push("```"),e.push(""),e.push("Valid priority values: LOW, MEDIUM, HIGH, URGENT"),e.push("Valid type values: FEATURE, BUG, ENHANCEMENT, DOCUMENTATION, DESIGN, TECHNICAL_DEBT"),e.push("aiConfidence should be between 0 and 1"),e.push(""),e.push("IMPORTANT: Output ONLY the JSON object, no additional text before or after."),e.join(`
55
55
  `)}function tl(s){let e=s.match(/```(?:json)?\s*([\s\S]*?)```/);if(e)try{return JSON.parse(e[1].trim())}catch{}let t=s.match(/\{[\s\S]*\}/);if(t)try{return JSON.parse(t[0])}catch{}return null}async function sl(s,e={}){let{timeoutMs:t=3e5,verbose:i=!0,workingDirectory:a,onEvent:c}=e,u=a||process.cwd(),p=Dm(s),g=Date.now(),m="",_=!1;i&&(console.log("[Agent] Starting analysis with Claude Agent SDK..."),console.log("[Agent] Prompt length:",p.length,"characters"),console.log("[Agent] Working directory:",u),console.log("[Agent] Model: claude-opus-4-5-20250929"));let w=new AbortController,C=setTimeout(()=>{_=!0,w.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),T=(S,O)=>{c&&c({type:S,timestamp:Date.now(),data:O})};T("session_start",{prompt:p.substring(0,200),cwd:u});try{let S=Br({prompt:p,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","WebSearch"],permissionMode:"acceptEdits",maxTurns:30}});for await(let O of S)switch(O.type){case"assistant":if(O.message.content){for(let N of O.message.content)if(N.type==="text")m+=N.text,i&&process.stdout.write(N.text),T("assistant_message",{text:N.text,uuid:O.uuid});else if(N.type==="thinking"){let G=N;i&&console.log(`[Agent] Thinking: ${G.thinking.substring(0,100)}...`),T("thinking",{text:G.thinking,uuid:O.uuid})}else if(N.type==="tool_use"||"name"in N){let G=N;i&&console.log(`[Agent] Tool: ${G.name}`),T("tool_start",{tool:G.name,toolUseId:G.id,input:G.input})}}break;case"user":if(O.message.content){for(let N of O.message.content)if(typeof N=="object"&&N!==null&&"type"in N&&N.type==="tool_result"){let G=N;T("tool_end",{toolUseId:G.tool_use_id,isError:G.is_error||!1,hasContent:!!G.content})}}break;case"result":i&&(console.log(""),console.log(`[Agent] Completed in ${O.duration_ms}ms`),console.log(`[Agent] Cost: $${O.total_cost_usd?.toFixed(4)||"N/A"}`)),clearTimeout(C);let k=tl(m);if(k&&k.summary&&Array.isArray(k.suggestedTasks))return T("result",{success:!0,analysis:k,costUsd:O.total_cost_usd,usage:O.usage}),{success:!0,analysis:k,output:m,timedOut:!1,totalCostUsd:O.total_cost_usd,usage:O.usage?{inputTokens:O.usage.input_tokens,outputTokens:O.usage.output_tokens}:void 0};if(O.subtype!=="success"){let N="result"in O?O.result:O.subtype;return T("error",{error:O.subtype,result:N}),{success:!1,output:m,error:`Agent error: ${O.subtype} - ${N}`,timedOut:!1,totalCostUsd:O.total_cost_usd}}return{success:!1,output:m,error:"Failed to parse analysis JSON from output",timedOut:!1,totalCostUsd:O.total_cost_usd}}return clearTimeout(C),{success:!1,output:m,error:"Query stream ended without result",timedOut:_}}catch(S){clearTimeout(C);let O=S instanceof Error?S.message:String(S);i&&console.error("[Agent] Error:",O),T("error",{error:O});let k=tl(m);return k&&k.summary&&Array.isArray(k.suggestedTasks)?(i&&console.log("[Agent] Got valid output despite error - treating as success"),{success:!0,analysis:k,output:m,timedOut:!1}):{success:!1,output:m,error:_?"Process timed out":O,timedOut:_}}}function Um(s,e){let t=[];if(e&&t.push(Xc(e)),t.push(`# Task: ${s.title}`),t.push(""),t.push(`**Project:** ${s.projectContext.projectName}`),t.push(`**Priority:** ${s.priority}`),t.push(`**Type:** ${s.type}`),t.push(`**Estimated Hours:** ${s.estimatedHours||"N/A"}`),t.push(""),t.push("## Description"),t.push(s.description||"No description provided."),t.push(""),s.acceptanceCriteria&&s.acceptanceCriteria.length>0&&(t.push("## Acceptance Criteria"),s.acceptanceCriteria.forEach((i,a)=>{t.push(`${a+1}. ${i}`)}),t.push("")),s.technicalNotes&&(t.push("## Technical Notes"),t.push(s.technicalNotes),t.push("")),s.projectContext.projectDescription&&(t.push("## Project Description"),t.push(s.projectContext.projectDescription),t.push("")),s.projectContext.knowledgeBase){t.push("## Project Knowledge Base");let i=s.projectContext.knowledgeBase;i.length>1e4?t.push(i.substring(0,1e4)+`
56
56
 
57
- [... truncated ...]`):t.push(i),t.push("")}return t.push("---"),t.push(""),t.push("## Instructions"),t.push(""),t.push("Please work on this task. Implement the required changes according to the acceptance criteria."),t.push(""),e&&(t.push("**IMPORTANT - Context Already Provided:**"),t.push("- Project structure and key files are shown above - DO NOT run `find`, `ls`, or re-read these files"),t.push("- Start implementing immediately using the pre-loaded context"),t.push("- Only read additional files if specifically needed for implementation"),t.push("")),t.push("**Work efficiently:**"),t.push("- Focus only on what's needed to meet the acceptance criteria"),t.push("- Avoid unnecessary exploration or refactoring beyond the scope"),t.push("- Make targeted file reads instead of scanning the entire codebase"),t.push("- If you have enough context, proceed with implementation"),t.push(""),t.push('When you have completed the task, output "TASK_COMPLETE" on its own line.'),t.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),t.join(`
57
+ [... truncated ...]`):t.push(i),t.push("")}return t.push("---"),t.push(""),t.push("## Instructions"),t.push(""),t.push("Please work on this task. Implement the required changes according to the acceptance criteria."),t.push(""),e&&(t.push("**IMPORTANT - Context Already Provided:**"),t.push("- Project structure and key files are shown above - DO NOT run `find`, `ls`, or re-read these files"),t.push("- Start implementing immediately using the pre-loaded context"),t.push("- Only read additional files if specifically needed for implementation"),t.push("")),t.push("**Work efficiently:**"),t.push("- Focus only on what's needed to meet the acceptance criteria"),t.push("- Avoid unnecessary exploration or refactoring beyond the scope"),t.push("- Make targeted file reads instead of scanning the entire codebase"),t.push("- If you have enough context, proceed with implementation"),t.push(""),t.push("**Verification and Stopping Rules (CRITICAL):**"),t.push("- After making code changes, verify with ONE build/test run"),t.push("- If verification fails due to YOUR code changes, fix them (max 2 fix attempts)"),t.push("- If verification fails due to ENVIRONMENT issues, STOP and use TASK_BLOCKED immediately"),t.push(""),t.push("**Environment issues that require immediate TASK_BLOCKED:**"),t.push("- Stale server processes or port conflicts"),t.push("- Multiple processes running from previous sessions"),t.push("- Build artifacts or caches showing outdated code"),t.push("- Cannot determine if your changes are actually running"),t.push("- Pre-existing TypeScript/lint errors unrelated to your changes"),t.push(""),t.push("**Anti-Rabbit-Hole Rules:**"),t.push("- NEVER spend more than 1 attempt fixing environment issues (pkill, port cleanup, etc.)"),t.push("- If process management becomes the focus, STOP - your job is code, not DevOps"),t.push("- If you're unsure whether your code or the environment is the problem, use TASK_BLOCKED"),t.push('- Do NOT substitute "the code looks right" for actual verification'),t.push(""),t.push('When you have completed AND verified the task, output "TASK_COMPLETE" on its own line.'),t.push('If you encounter ANY issues that prevent clean verification, output "TASK_BLOCKED: <reason>" with a specific reason.'),t.join(`
58
58
  `)}async function Hr(s,e={}){let{timeoutMs:t=12e5,verbose:i=!0,workingDirectory:a,onEvent:c}=e,u=a||process.cwd(),p;if(Zc(u))try{p=Qc(u),i&&console.log("[Agent] Generated pre-loaded context:",{fileTreeLines:p.fileTree.split(`
59
59
  `).length,keyFilesCount:p.keyFiles.length})}catch(O){i&&console.warn("[Agent] Failed to generate pre-loaded context:",O)}let g=Um(s,p),m=Date.now(),_="",w=!1;i&&(console.log("[Agent] Starting backlog task with Claude Agent SDK..."),console.log("[Agent] Task:",s.title),console.log("[Agent] Working directory:",u),console.log("[Agent] Model: claude-opus-4-5-20250929"));let C=new AbortController,T=setTimeout(()=>{w=!0,C.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),S=(O,k)=>{c&&c({type:O,timestamp:Date.now(),data:k})};S("session_start",{task:s.title,cwd:u});try{let O=Br({prompt:g,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","Write"],permissionMode:"acceptEdits",maxTurns:30}});for await(let k of O)switch(k.type){case"assistant":if(k.message.content){for(let Y of k.message.content)if(Y.type==="text")_+=Y.text,i&&process.stdout.write(Y.text);else if("name"in Y){let X=Y;i&&console.log(`[Agent] Tool: ${X.name}`),S("tool_start",{tool:X.name,toolUseId:X.id,input:X.input})}}break;case"result":clearTimeout(T),i&&(console.log(""),console.log(`[Agent] Completed in ${k.duration_ms}ms`),console.log(`[Agent] Cost: $${k.total_cost_usd?.toFixed(4)||"N/A"}`));let N=_.includes("TASK_COMPLETE"),G=_.match(/TASK_BLOCKED:\s*(.+)/);return G?{success:!1,output:_,error:`Task blocked: ${G[1]}`,timedOut:!1,totalCostUsd:k.total_cost_usd,inputTokens:k.usage?.input_tokens,outputTokens:k.usage?.output_tokens}:{success:N||k.subtype==="success",output:_,timedOut:!1,totalCostUsd:k.total_cost_usd,inputTokens:k.usage?.input_tokens,outputTokens:k.usage?.output_tokens}}return clearTimeout(T),{success:!1,output:_,error:"Query stream ended without result",timedOut:w}}catch(O){clearTimeout(T);let k=O instanceof Error?O.message:String(O);return i&&console.error("[Agent] Error:",k),S("error",{error:k}),{success:!1,output:_,error:w?"Process timed out":k,timedOut:w}}}async function nl(){try{return!0}catch{return!1}}function rl(s){return s.includes("[CONVERSATIONAL SESSION]")}function il(s){let e=Math.max(s.lastIndexOf("MODE: PLANNING"),s.lastIndexOf("[MODE: PLANNING")),t=Math.max(s.lastIndexOf("MODE: BUILD"),s.lastIndexOf("MODE: WORK"));return e>t?"planning":(t>e,"work")}function jm(s){let t=s.replace("[CONVERSATIONAL SESSION]","").trim().split(/\n---\nUser follow-up:\n/);if(t.length===1){let c=t[0].replace(/^User message:\s*/i,"").trim();return{initialMessage:c,followUps:[],latestMessage:c,isFollowUp:!1}}let i=t[0].replace(/^User message:\s*/i,"").trim(),a=t.slice(1).map(c=>c.trim());return{initialMessage:i,followUps:a,latestMessage:a[a.length-1],isFollowUp:!0}}function qm(s,e){let t=["# PLANNING MODE - Read-Only Exploration & Discovery","","## CRITICAL: THIS IS A READ-ONLY SESSION","","**You CANNOT make any changes to the codebase in this mode.**","","Planning mode is strictly read-only:","- You have access to read-only tools: Read, Glob, Grep, WebSearch, WebFetch","- Bash is available but LIMITED to read-only commands only (ls, git status, git log, git diff, pwd, etc.)","- Edit, Write, and NotebookEdit tools are NOT available","- You CANNOT modify any files or execute write operations","- Your role is purely to explore, understand, and discuss","","---","","## YOUR ROLE","","You are a thoughtful collaborator helping a user explore and refine their ideas. Your job is to ask questions, discuss trade-offs, and help clarify requirements.","","## STRICT RULES FOR PLANNING MODE","","**DO NOT generate any tasks.** This is a strict requirement.","- Never output <task>JSON</task> blocks","- Never suggest specific task titles or estimates","- Focus entirely on understanding and exploration","","**Your goals in planning mode:**","1. Ask clarifying questions to understand the user's goals","2. Discuss trade-offs and alternatives","3. Help the user think through their idea thoroughly","4. Explore the codebase to understand context (read-only exploration)","","---","",`**Project Name:** ${s.projectContext.projectName}`];return s.projectContext.projectDescription&&t.push(`**Project Description:** ${s.projectContext.projectDescription}`),s.projectContext.techStack&&s.projectContext.techStack.length>0&&t.push(`**Tech Stack:** ${s.projectContext.techStack.join(", ")}`),t.push(""),t.push("---"),t.push(""),e.isFollowUp?(t.push("## Conversation History"),t.push(""),t.push(`**Initial request:** ${e.initialMessage}`),t.push(""),e.followUps.length>1&&(t.push("**Previous follow-ups:**"),e.followUps.slice(0,-1).forEach((i,a)=>{t.push(`${a+1}. ${i}`)}),t.push("")),t.push("---"),t.push(""),t.push("## Latest Message"),t.push(""),t.push(e.latestMessage)):(t.push("## User's Message"),t.push(""),t.push(e.initialMessage)),t.push(""),t.push("---"),t.push(""),t.push("## IMPORTANT: Suggest Build Mode Proactively"),t.push(""),t.push("**Planning should be BRIEF.** After exploring the codebase and understanding the request:"),t.push(""),t.push("1. Ask AT MOST 2-3 clarifying questions"),t.push("2. Do NOT spend excessive time exploring - focus on key files only"),t.push("3. **Suggest Build mode quickly** - users want to create tasks, not have endless discussions"),t.push(""),t.push("When you are ready to proceed (which should be SOON), output:"),t.push(""),t.push("<suggest_build_mode>"),t.push("Brief reasoning for why we're ready to create tasks"),t.push("</suggest_build_mode>"),t.push(""),t.push("**Suggest Build mode when ANY of these are true:**"),t.push("- The user's request is reasonably clear (even if not perfect)"),t.push("- You've asked 2-3 questions and have enough context"),t.push("- The user seems ready to proceed"),t.push("- Basic scope is understood (details can be clarified during task creation)"),t.push(""),t.push("**DO NOT wait for perfect clarity.** Tasks can be refined later. The goal is to move forward, not to plan endlessly."),t.push(""),t.push("**IMPORTANT: ExitPlanMode tool is NOT available.** Use `<suggest_build_mode>` tags instead."),t.push(""),t.push("---"),t.push(""),t.push("## REMINDER: READ-ONLY MODE"),t.push(""),t.push("You are in Planning mode which is READ-ONLY:"),t.push("- You can READ files and search the codebase to understand context"),t.push("- You can run read-only Bash commands (ls, git status, git log, git diff, pwd, etc.)"),t.push("- You CANNOT modify files, edit code, or run write operations"),t.push("- You CANNOT generate tasks - only explore and discuss"),t.push("- ExitPlanMode tool is NOT available - use `<suggest_build_mode>` tags instead"),t.push("- Any actual implementation happens later, after tasks are created in Build mode"),t.join(`
60
60
  `)}function Bm(s){if(!s)return null;try{if(el.existsSync(s)){let e=el.readFileSync(s,"utf-8");return console.log(`[Agent] Successfully read plan file: ${s} (${e.length} chars)`),e}else return console.log(`[Agent] Plan file does not exist: ${s}`),null}catch(e){return console.error(`[Agent] Error reading plan file ${s}:`,e),null}}function $m(s,e){let t=[],i=Bm(s.planFilePath);return i&&(t.push("# PLANNING PHASE OUTPUT - FOLLOW THIS PLAN"),t.push(""),t.push("**CRITICAL: A planning phase was already completed.** The codebase has already been explored."),t.push(""),t.push("## DO NOT RE-EXPLORE"),t.push(""),t.push("- DO NOT search the codebase again - this was done in planning"),t.push('- DO NOT use Glob, Grep, or Read to "understand the codebase"'),t.push('- DO NOT say "let me explore" or "let me understand the implementation"'),t.push("- The planning phase already gathered all necessary context"),t.push(""),t.push("## YOUR ONLY JOB: Create Tasks From This Plan"),t.push(""),t.push("Review the plan below and immediately create <task>JSON</task> blocks based on it."),t.push("Only use read tools if you need a specific line number for a task description."),t.push(""),t.push("---"),t.push(""),t.push("## The Plan"),t.push(""),t.push("```markdown"),t.push(i),t.push("```"),t.push(""),t.push("---"),t.push("")),t.push("# BUILD MODE - Read-Only Task Creation"),t.push(""),t.push("## CRITICAL: THIS IS A READ-ONLY SESSION"),t.push(""),t.push("**You CANNOT make any changes to the codebase in this mode.**"),t.push(""),t.push("Build mode is strictly read-only:"),t.push("- You have access to read-only tools: Read, Glob, Grep, WebSearch, WebFetch"),t.push("- Bash is available but LIMITED to read-only commands only (ls, git status, git log, git diff, pwd, etc.)"),t.push("- Edit, Write, and NotebookEdit tools are NOT available"),t.push("- You CANNOT modify any files or execute write operations"),i?(t.push("- Your role is to CREATE TASK DEFINITIONS from the plan above"),t.push("- DO NOT re-explore - planning already did that")):t.push("- Your role is to explore, understand, and CREATE TASK DEFINITIONS"),t.push("- Actual implementation happens later, when tasks are executed separately"),t.push(""),i&&(t.push("**CRITICAL REMINDER:** The planning phase is COMPLETE. DO NOT explore the codebase again."),t.push("Immediately review the plan above and generate <task>JSON</task> blocks."),t.push("")),t.push("---"),t.push(""),t.push("## YOUR ROLE"),t.push(""),t.push("You are helping create actionable development tasks. Your goal is to generate well-structured task definitions based on the user's requirements."),t.push(""),t.push(`**Project Name:** ${s.projectContext.projectName}`),s.projectContext.projectDescription&&t.push(`**Project Description:** ${s.projectContext.projectDescription}`),s.projectContext.techStack&&s.projectContext.techStack.length>0&&t.push(`**Tech Stack:** ${s.projectContext.techStack.join(", ")}`),t.push(""),t.push("---"),t.push(""),e.isFollowUp?(t.push("## Conversation History"),t.push(""),t.push("This is an ongoing conversation. Here is what was discussed:"),t.push(""),t.push(`**Initial request:** ${e.initialMessage}`),t.push(""),e.followUps.length>1&&(t.push("**Previous follow-ups:**"),e.followUps.slice(0,-1).forEach((a,c)=>{t.push(`${c+1}. ${a}`)}),t.push("")),t.push("---"),t.push(""),t.push("## Latest Message (respond to this)"),t.push(""),t.push(e.latestMessage),t.push(""),t.push("---"),t.push(""),t.push("## Instructions"),t.push(""),t.push("This is a FOLLOW-UP message. DO NOT start over or re-introduce yourself."),t.push("Simply respond directly to their latest message, building on the context of the conversation."),t.push(""),i?(t.push("**IMPORTANT:** The planning phase already explored the codebase. DO NOT re-explore."),t.push("Use the plan above to generate tasks immediately.")):t.push("If you already explored the codebase in a previous turn, you do NOT need to explore it again unless the user asks about something new."),t.push(""),t.push("**Refinement mode:** If the user is providing feedback on suggested tasks, immediately update or regenerate the tasks with their input.")):(t.push("## User's Message"),t.push(""),t.push(e.initialMessage),t.push(""),t.push("---"),t.push(""),t.push("## Instructions"),t.push(""),i?(t.push("**A planning phase was completed.** The plan is shown above."),t.push(""),t.push("DO NOT explore the codebase - this was already done during planning."),t.push("Immediately generate <task>JSON</task> blocks based on the plan.")):(t.push("You have access to the full codebase, so explore it to understand the project structure."),t.push(""),t.push("**Your goal is to generate actionable tasks within this first exchange.** Don't spend time asking qualifying questions - use the codebase and project context to make informed assumptions. Briefly explore relevant files if needed, then propose concrete tasks."),t.push(""),t.push("The client should feel like their work is being shaped into actionable items immediately, not that they're entering an interview process."))),s.existingTasks&&s.existingTasks.length>0&&(t.push(""),t.push("## Existing Tasks in Project"),t.push(""),t.push("The following tasks already exist in this project. If the user wants to modify an existing task, use the <task_modify> format below:"),t.push(""),s.existingTasks.slice(0,20).forEach((a,c)=>{t.push(`- [${a.id}] "${a.title}" (${a.status})`)}),s.existingTasks.length>20&&t.push(`- ... and ${s.existingTasks.length-20} more tasks`),t.push("")),t.push(""),t.push("## Task Generation"),t.push(""),t.push("**IMPORTANT: Prioritize generating tasks quickly.** Clients want to feel like work is starting immediately."),t.push(""),t.push("- Generate initial task suggestions within your FIRST response whenever possible"),t.push("- Make reasonable assumptions based on the project context and codebase - don't ask questions you can answer yourself"),t.push("- If something is unclear, make a sensible default assumption, note it in the task, and let the client refine it"),t.push("- Only ask 1-2 critical questions if absolutely essential - prefer to suggest tasks with noted assumptions"),t.push("- Tasks can always be refined through follow-up conversation - the goal is momentum, not perfection"),t.push(""),t.push("### Creating New Tasks"),t.push(""),t.push("When you identify work that should become a NEW task, output it in this format:"),t.push("<task>"),t.push("{"),t.push(' "title": "Task title",'),t.push(' "description": "What needs to be done",'),t.push(' "acceptanceCriteria": ["Criterion 1", "Criterion 2"],'),t.push(' "estimatedHours": 4,'),t.push(' "priority": "MEDIUM",'),t.push(' "type": "FEATURE",'),t.push(' "technicalNotes": "Implementation notes (include any assumptions made)",'),t.push(' "aiConfidence": 0.85'),t.push("}"),t.push("</task>"),t.push(""),t.push("### Modifying Existing Tasks"),t.push(""),t.push("If the user wants to modify an existing task, use this format (only include fields that should change):"),t.push('<task_modify existingTaskId="[ID from existing tasks list]">'),t.push("{"),t.push(' "title": "Updated title",'),t.push(' "description": "Updated description",'),t.push(' "acceptanceCriteria": ["Updated criterion 1", "Updated criterion 2"],'),t.push(' "estimatedHours": 6,'),t.push(' "priority": "HIGH"'),t.push("}"),t.push("</task_modify>"),t.push(""),t.push('Include an "assumptions" section in technicalNotes if you made decisions the client might want to change.'),t.push(`After suggesting tasks, invite the client to refine: "These tasks are ready for review. Let me know if you'd like to adjust scope, estimates, or approach."`),t.push(""),t.push("Valid priority values: LOW, MEDIUM, HIGH, URGENT"),t.push("Valid type values: FEATURE, BUG, ENHANCEMENT, DOCUMENTATION, DESIGN, TECHNICAL_DEBT"),t.push(""),t.push("---"),t.push(""),t.push("## REMINDER: READ-ONLY MODE"),t.push(""),t.push("You are in Build mode which is READ-ONLY:"),t.push("- You can READ files and search the codebase to understand context"),t.push("- You can run read-only Bash commands (ls, git status, git log, git diff, pwd, etc.)"),t.push("- You CANNOT modify files, edit code, or run write operations"),t.push("- You CAN generate task definitions using <task>JSON</task> format"),t.push("- Any actual implementation happens later, when tasks are executed separately"),t.push("- DO NOT attempt to implement the changes yourself - only define the tasks"),t.join(`
61
61
  `)}function Hm(s,e="work"){let t=jm(s.description);return e==="planning"?qm(s,t):$m(s,t)}var ol=["LOW","MEDIUM","HIGH","URGENT"],al=["FEATURE","BUG","ENHANCEMENT","DOCUMENTATION","DESIGN","TECHNICAL_DEBT"];function Gm(s){let e=[],t=s.includes("<task>")&&s.includes("</task>");if(console.log(`[Agent] parseTasksFromOutput: hasTaskTags=${t}, outputLength=${s.length}`),!t)return console.log("[Agent] No <task> tags found in output"),e;let i=/<task>([\s\S]*?)<\/task>/g,a,c=0;for(;(a=i.exec(s))!==null;){c++;let u=a[1].trim();console.log(`[Agent] Found task block #${c}, parsing JSON...`);try{let p=u.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/i,"").trim(),g=p.match(/\{[\s\S]*\}/);g&&(p=g[0]);let m=JSON.parse(p);if(!m.title||typeof m.title!="string"){console.warn(`[Agent] Task #${c} missing or invalid title, skipping`);continue}let _=ol.includes(m.priority?.toUpperCase?.())?m.priority.toUpperCase():"MEDIUM",w=al.includes(m.type?.toUpperCase?.())?m.type.toUpperCase():"FEATURE",C=Array.isArray(m.acceptanceCriteria)?m.acceptanceCriteria.filter(O=>typeof O=="string").map(O=>O.trim()):[],T=Math.max(0,Number(m.estimatedHours)||4),S=Math.min(1,Math.max(0,Number(m.aiConfidence||m.confidence)||.8));console.log(`[Agent] Parsed task #${c}: "${m.title}" (${_}, ${w}, ${T}h)`),e.push({title:String(m.title).trim(),description:String(m.description||"").trim(),acceptanceCriteria:C,estimatedHours:T,priority:_,type:w,technicalNotes:m.technicalNotes?String(m.technicalNotes).trim():void 0,aiConfidence:S})}catch(p){console.error(`[Agent] Failed to parse task #${c} JSON:`,p instanceof Error?p.message:p),console.error("[Agent] Raw task content (first 500 chars):",u.substring(0,500))}}return console.log(`[Agent] parseTasksFromOutput: returning ${e.length} valid tasks (found ${c} total blocks)`),e}function Fm(s){let e=[];if(!(s.includes("<task_modify")&&s.includes("</task_modify>")))return e;let i=/<task_modify\s+existingTaskId=["']([^"']+)["']>([\s\S]*?)<\/task_modify>/g,a,c=0;for(;(a=i.exec(s))!==null;){c++;let u=a[1].trim(),p=a[2].trim();console.log(`[Agent] Found task_modify block #${c} for task ${u}`);try{let g=p.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/i,"").trim(),m=g.match(/\{[\s\S]*\}/);m&&(g=m[0]);let _=JSON.parse(g),w={};_.title!==void 0&&(w.title=String(_.title).trim()),_.description!==void 0&&(w.description=String(_.description).trim()),_.acceptanceCriteria!==void 0&&Array.isArray(_.acceptanceCriteria)&&(w.acceptanceCriteria=_.acceptanceCriteria.filter(C=>typeof C=="string").map(C=>C.trim())),_.estimatedHours!==void 0&&(w.estimatedHours=Math.max(0,Number(_.estimatedHours)||0)),_.priority!==void 0&&ol.includes(_.priority?.toUpperCase?.())&&(w.priority=_.priority.toUpperCase()),_.type!==void 0&&al.includes(_.type?.toUpperCase?.())&&(w.type=_.type.toUpperCase()),_.technicalNotes!==void 0&&(w.technicalNotes=String(_.technicalNotes).trim()),Object.keys(w).length>0?(console.log(`[Agent] Parsed task modification #${c}: ${Object.keys(w).length} fields for task ${u}`),e.push({existingTaskId:u,updates:w})):console.warn(`[Agent] Task modification #${c} has no valid updates, skipping`)}catch(g){console.error(`[Agent] Failed to parse task_modify #${c} JSON:`,g instanceof Error?g.message:g)}}return console.log(`[Agent] parseTaskModificationsFromOutput: returning ${e.length} modifications`),e}async function cl(s,e={}){let{timeoutMs:t=3e5,verbose:i=!0,workingDirectory:a,onEvent:c,mode:u="work"}=e,p=a||process.cwd(),g=Hm(s,u),m="",_=!1;i&&(console.log("[Agent] Starting conversational session..."),console.log("[Agent] Mode:",u),console.log("[Agent] Working directory:",p));let w=new AbortController,C=setTimeout(()=>{_=!0,w.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),T=(k,N)=>{c&&c({type:k,timestamp:Date.now(),data:N})};T("session_start",{cwd:p,mode:u});let S,O=(k,N)=>({allowed:!0});try{let k=u==="planning"?"plan":"acceptEdits";i&&console.log(`[Agent] SDK permissionMode: ${k}`);let N=Br({prompt:g,options:{permissionMode:k,maxTurns:30,...u==="planning"&&{thinking:{type:"enabled",budgetTokens:8e3}}}});for await(let G of N)switch(G.type){case"assistant":if(G.message.content){for(let Q of G.message.content)if(Q.type==="text")m+=Q.text,i&&process.stdout.write(Q.text),T("assistant_message",{text:Q.text,uuid:G.uuid});else if(Q.type==="thinking"){let Z=Q;i&&console.log(`[Agent] Thinking: ${Z.thinking.substring(0,100)}...`),T("thinking",{text:Z.thinking,uuid:G.uuid})}else if(Q.type==="tool_use"||"name"in Q){let Z=Q,oe=O(Z.name,Z.input);oe.allowed||(console.error(`[Agent] SECURITY VIOLATION: ${oe.reason}`),console.error(`[Agent] Tool attempt details: ${JSON.stringify({tool:Z.name,mode:u,toolUseId:Z.id,timestamp:new Date().toISOString()})}`),T("error",{error:oe.reason,securityViolation:!0,tool:Z.name,mode:u})),Z.name==="ExitPlanMode"&&i&&console.log("[Agent] ExitPlanMode tool used - will capture plan file path from result"),i&&console.log(`[Agent] Tool: ${Z.name}${oe.allowed?"":" (RESTRICTED - should not execute)"}`),T("tool_start",{tool:Z.name,toolUseId:Z.id,input:Z.input})}}break;case"user":if(G.message.content){for(let Q of G.message.content)if(typeof Q=="object"&&Q!==null&&"type"in Q&&Q.type==="tool_result"){let Z=Q;if(Z.content&&!Z.is_error){let oe="";typeof Z.content=="string"?oe=Z.content:Array.isArray(Z.content)&&(oe=Z.content.filter(Pe=>Pe.type==="text"&&typeof Pe.text=="string").map(Pe=>Pe.text).join(`
62
- `));let Re=oe.match(/(?:plan(?:ning)?(?:\s+)?(?:file)?(?:\s+)?(?:path|saved|written|at)?[:\s]+)?([^\s]+\.md)/i)||oe.match(/(\/[^\s]+\.md)/i)||oe.match(/([^\s]+\.md)/i);Re&&Re[1]&&(S=Re[1],i&&console.log(`[Agent] Captured plan file path: ${S}`))}T("tool_end",{toolUseId:Z.tool_use_id,isError:Z.is_error||!1,hasContent:!!Z.content})}}break;case"result":clearTimeout(C),i&&(console.log(""),console.log(`[Agent] Completed in ${G.duration_ms}ms`),console.log(`[Agent] Cost: $${G.total_cost_usd?.toFixed(4)||"N/A"}`));let Y=Gm(m),X=Fm(m);return i&&Y.length>0&&console.log(`[Agent] Found ${Y.length} new task(s) in output`),i&&X.length>0&&console.log(`[Agent] Found ${X.length} task modification(s) in output`),T("result",{success:!0,output:m,tasks:Y,modifications:X,costUsd:G.total_cost_usd,planFilePath:S}),{success:!0,output:m,tasks:Y,modifications:X,timedOut:!1,totalCostUsd:G.total_cost_usd,planFilePath:S}}return clearTimeout(C),{success:!1,output:m,tasks:[],modifications:[],error:"Query stream ended without result",timedOut:_}}catch(k){clearTimeout(C);let N=k instanceof Error?k.message:String(k);return i&&console.error("[Agent] Error:",N),T("error",{error:N}),{success:!1,output:m,tasks:[],modifications:[],error:_?"Process timed out":N,timedOut:_}}}var Gd=wr(Hd(),1),Vn=class s{baseUrl;apiKey;projectId;monitorId;ably=null;channel=null;isRunning=!1;isStopping=!1;heartbeatInterval=null;static HEARTBEAT_INTERVAL_MS=3e4;onNewWorkHandler=null;onConnectedHandler=null;onErrorHandler=null;onDisconnectedHandler=null;constructor(e,t,i,a){this.baseUrl=e.replace(/\/$/,""),this.apiKey=t,this.projectId=i,this.monitorId=a}async start(){if(this.isRunning){console.log("[AblyWorkClient] Already running");return}console.log(`[AblyWorkClient] Starting Ably client for project ${this.projectId}`),this.isRunning=!0,this.isStopping=!1;try{this.ably=new Gd.default.Realtime({authCallback:(e,t)=>{this.fetchToken().then(i=>t(null,i)).catch(i=>t(i,null))},disconnectedRetryTimeout:1e3,suspendedRetryTimeout:5e3}),this.ably.connection.on("connected",()=>{console.log("[AblyWorkClient] Connected to Ably"),this.onConnectedHandler&&this.onConnectedHandler({projectId:this.projectId,projectName:"",monitorId:this.monitorId,timestamp:new Date().toISOString()})}),this.ably.connection.on("disconnected",()=>{console.log("[AblyWorkClient] Disconnected from Ably (will auto-reconnect)")}),this.ably.connection.on("suspended",()=>{console.log("[AblyWorkClient] Connection suspended"),this.onDisconnectedHandler&&this.onDisconnectedHandler()}),this.ably.connection.on("failed",e=>{console.error("[AblyWorkClient] Connection failed:",e.reason),this.onErrorHandler&&this.onErrorHandler(new Error(`Ably connection failed: ${e.reason?.message||"Unknown error"}`))}),this.channel=this.ably.channels.get(`project:${this.projectId}:work`),this.channel.subscribe("new_request",e=>{let t=e.data;console.log("[AblyWorkClient] Received work notification:",t),this.onNewWorkHandler&&!this.isStopping&&Promise.resolve(this.onNewWorkHandler(t)).catch(i=>{console.error("[AblyWorkClient] Error in new work handler:",i)})}),console.log(`[AblyWorkClient] Subscribed to project:${this.projectId}:work channel`),await this.waitForConnection(),this.startHeartbeat()}catch(e){throw console.error("[AblyWorkClient] Failed to start:",e),this.isRunning=!1,this.onErrorHandler&&this.onErrorHandler(e instanceof Error?e:new Error(String(e))),e}}async fetchToken(){let e=`${this.baseUrl}/api/ably/token`,t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"ngrok-skip-browser-warning":"true"},body:JSON.stringify({projectId:this.projectId,monitorId:this.monitorId})});if(!t.ok){let a=await t.text();throw new Error(`Failed to get Ably token (${t.status}): ${a}`)}let{tokenRequest:i}=await t.json();return console.log("[AblyWorkClient] Got scoped Ably token (registered as active)"),i}startHeartbeat(){this.stopHeartbeat(),this.sendHeartbeat(),this.heartbeatInterval=setInterval(()=>{this.sendHeartbeat()},s.HEARTBEAT_INTERVAL_MS),console.log(`[AblyWorkClient] Started heartbeat (every ${s.HEARTBEAT_INTERVAL_MS/1e3}s)`)}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}async sendHeartbeat(){if(!(!this.isRunning||this.isStopping))try{let e=`${this.baseUrl}/api/projects/${this.projectId}/monitor/heartbeat`,t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"ngrok-skip-browser-warning":"true"},body:JSON.stringify({monitorId:this.monitorId})});t.ok||console.error(`[AblyWorkClient] Heartbeat failed (${t.status})`)}catch(e){this.isRunning&&!this.isStopping&&console.error("[AblyWorkClient] Heartbeat error:",e)}}waitForConnection(e=1e4){return new Promise((t,i)=>{if(!this.ably){i(new Error("Ably client not initialized"));return}if(this.ably.connection.state==="connected"){t();return}let a=setTimeout(()=>{i(new Error("Connection timeout"))},e),c=u=>{u.current==="connected"?(clearTimeout(a),this.ably?.connection.off(c),t()):u.current==="failed"&&(clearTimeout(a),this.ably?.connection.off(c),i(new Error(`Connection failed: ${u.reason?.message||"Unknown error"}`)))};this.ably.connection.on(c)})}stop(){console.log("[AblyWorkClient] Stopping..."),this.isStopping=!0,this.isRunning=!1,this.stopHeartbeat(),this.channel&&(this.channel.unsubscribe(),this.channel=null),this.ably&&(this.ably.close(),this.ably=null),this.onDisconnectedHandler&&this.onDisconnectedHandler()}isConnected(){return this.isRunning&&!this.isStopping&&this.ably?.connection.state==="connected"}onNewWork(e){this.onNewWorkHandler=e}onConnected(e){this.onConnectedHandler=e}onError(e){this.onErrorHandler=e}onDisconnected(e){this.onDisconnectedHandler=e}};import{exec as fw}from"child_process";import{promisify as pw}from"util";var Fd=pw(fw);async function at(s,e){try{return await Fd(s,{cwd:e,maxBuffer:10485760})}catch(t){let i=t;if(i.stdout!==void 0||i.stderr!==void 0)return{stdout:i.stdout||"",stderr:i.stderr||""};throw t}}async function gw(s){try{return await at("git rev-parse --is-inside-work-tree",s),!0}catch{return!1}}async function Ao(s){let{stdout:e}=await at("git status --porcelain",s),t=[],i=[],a=[],c=e.trim().split(`
63
- `).filter(Boolean);for(let u of c){let p=u[0],g=u[1],m=u.substring(3).trim();p!==" "&&p!=="?"&&t.push(m),g!==" "&&g!=="?"&&i.push(m),p==="?"&&g==="?"&&a.push(m)}return{hasChanges:t.length>0||i.length>0||a.length>0,staged:t,unstaged:i,untracked:a}}async function mw(s){let{stdout:e}=await at("git rev-parse --abbrev-ref HEAD",s);return e.trim()}async function yw(s){let{stdout:e}=await at("git rev-parse --short HEAD",s);return e.trim()}async function _w(s){await at("git add .",s)}async function bw(s,e,t){try{if(!(await Ao(s)).hasChanges)return{success:!1,filesCommitted:[],error:"No changes to commit"};await _w(s);let c=(await Ao(s)).staged,u=e;t&&(u=`${e}
62
+ `));let Re=oe.match(/(?:plan(?:ning)?(?:\s+)?(?:file)?(?:\s+)?(?:path|saved|written|at)?[:\s]+)?([^\s]+\.md)/i)||oe.match(/(\/[^\s]+\.md)/i)||oe.match(/([^\s]+\.md)/i);Re&&Re[1]&&(S=Re[1],i&&console.log(`[Agent] Captured plan file path: ${S}`))}T("tool_end",{toolUseId:Z.tool_use_id,isError:Z.is_error||!1,hasContent:!!Z.content})}}break;case"result":clearTimeout(C),i&&(console.log(""),console.log(`[Agent] Completed in ${G.duration_ms}ms`),console.log(`[Agent] Cost: $${G.total_cost_usd?.toFixed(4)||"N/A"}`));let Y=Gm(m),X=Fm(m);return i&&Y.length>0&&console.log(`[Agent] Found ${Y.length} new task(s) in output`),i&&X.length>0&&console.log(`[Agent] Found ${X.length} task modification(s) in output`),T("result",{success:!0,output:m,tasks:Y,modifications:X,costUsd:G.total_cost_usd,planFilePath:S}),{success:!0,output:m,tasks:Y,modifications:X,timedOut:!1,totalCostUsd:G.total_cost_usd,planFilePath:S}}return clearTimeout(C),{success:!1,output:m,tasks:[],modifications:[],error:"Query stream ended without result",timedOut:_}}catch(k){clearTimeout(C);let N=k instanceof Error?k.message:String(k);return i&&console.error("[Agent] Error:",N),T("error",{error:N}),{success:!1,output:m,tasks:[],modifications:[],error:_?"Process timed out":N,timedOut:_}}}var Gd=wr(Hd(),1),Vn=class s{baseUrl;apiKey;projectId;monitorId;ably=null;channel=null;isRunning=!1;isStopping=!1;heartbeatInterval=null;static HEARTBEAT_INTERVAL_MS=3e4;onNewWorkHandler=null;onConnectedHandler=null;onErrorHandler=null;onDisconnectedHandler=null;constructor(e,t,i,a){this.baseUrl=e.replace(/\/$/,""),this.apiKey=t,this.projectId=i,this.monitorId=a}async start(){if(this.isRunning){console.log("[AblyWorkClient] Already running");return}console.log(`[AblyWorkClient] Starting Ably client for project ${this.projectId}`),this.isRunning=!0,this.isStopping=!1;try{this.ably=new Gd.default.Realtime({authCallback:(e,t)=>{this.fetchToken().then(i=>t(null,i)).catch(i=>t(i,null))},disconnectedRetryTimeout:1e3,suspendedRetryTimeout:5e3}),this.ably.connection.on("connected",()=>{console.log("[AblyWorkClient] Connected to Ably"),this.onConnectedHandler&&this.onConnectedHandler({projectId:this.projectId,projectName:"",monitorId:this.monitorId,timestamp:new Date().toISOString()})}),this.ably.connection.on("disconnected",()=>{console.log("[AblyWorkClient] Disconnected from Ably (will auto-reconnect)")}),this.ably.connection.on("suspended",()=>{console.log("[AblyWorkClient] Connection suspended"),this.onDisconnectedHandler&&this.onDisconnectedHandler()}),this.ably.connection.on("failed",e=>{console.error("[AblyWorkClient] Connection failed:",e.reason),this.onErrorHandler&&this.onErrorHandler(new Error(`Ably connection failed: ${e.reason?.message||"Unknown error"}`))}),this.channel=this.ably.channels.get(`project:${this.projectId}:work`),this.channel.subscribe("new_request",e=>{let t=e.data;console.log("[AblyWorkClient] Received work notification:",t),this.onNewWorkHandler&&!this.isStopping&&Promise.resolve(this.onNewWorkHandler(t)).catch(i=>{console.error("[AblyWorkClient] Error in new work handler:",i)})}),console.log(`[AblyWorkClient] Subscribed to project:${this.projectId}:work channel`),await this.waitForConnection(),this.startHeartbeat()}catch(e){throw console.error("[AblyWorkClient] Failed to start:",e),this.isRunning=!1,this.onErrorHandler&&this.onErrorHandler(e instanceof Error?e:new Error(String(e))),e}}async fetchToken(){let e=`${this.baseUrl}/api/ably/token`,t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"ngrok-skip-browser-warning":"true"},body:JSON.stringify({projectId:this.projectId,monitorId:this.monitorId})});if(!t.ok){let a=await t.text();throw new Error(`Failed to get Ably token (${t.status}): ${a}`)}let{tokenRequest:i}=await t.json();return console.log("[AblyWorkClient] Got scoped Ably token (registered as active)"),i}startHeartbeat(){this.stopHeartbeat(),this.sendHeartbeat(),this.heartbeatInterval=setInterval(()=>{this.sendHeartbeat()},s.HEARTBEAT_INTERVAL_MS),console.log(`[AblyWorkClient] Started heartbeat (every ${s.HEARTBEAT_INTERVAL_MS/1e3}s)`)}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}async sendHeartbeat(){if(!(!this.isRunning||this.isStopping))try{let e=`${this.baseUrl}/api/projects/${this.projectId}/monitor/heartbeat`,t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"ngrok-skip-browser-warning":"true"},body:JSON.stringify({monitorId:this.monitorId})});t.ok||console.error(`[AblyWorkClient] Heartbeat failed (${t.status})`)}catch(e){this.isRunning&&!this.isStopping&&console.error("[AblyWorkClient] Heartbeat error:",e)}}waitForConnection(e=1e4){return new Promise((t,i)=>{if(!this.ably){i(new Error("Ably client not initialized"));return}if(this.ably.connection.state==="connected"){t();return}let a=setTimeout(()=>{i(new Error("Connection timeout"))},e),c=u=>{u.current==="connected"?(clearTimeout(a),this.ably?.connection.off(c),t()):u.current==="failed"&&(clearTimeout(a),this.ably?.connection.off(c),i(new Error(`Connection failed: ${u.reason?.message||"Unknown error"}`)))};this.ably.connection.on(c)})}stop(){console.log("[AblyWorkClient] Stopping..."),this.isStopping=!0,this.isRunning=!1,this.stopHeartbeat(),this.channel&&(this.channel.unsubscribe(),this.channel=null),this.ably&&(this.ably.close(),this.ably=null),this.onDisconnectedHandler&&this.onDisconnectedHandler()}isConnected(){return this.isRunning&&!this.isStopping&&this.ably?.connection.state==="connected"}onNewWork(e){this.onNewWorkHandler=e}onConnected(e){this.onConnectedHandler=e}onError(e){this.onErrorHandler=e}onDisconnected(e){this.onDisconnectedHandler=e}};import{exec as fw}from"child_process";import{promisify as pw}from"util";import{existsSync as gw,readFileSync as mw}from"fs";import{join as yw}from"path";var Fd=pw(fw);async function at(s,e){try{return await Fd(s,{cwd:e,maxBuffer:10485760})}catch(t){let i=t;if(i.stdout!==void 0||i.stderr!==void 0)return{stdout:i.stdout||"",stderr:i.stderr||""};throw t}}async function _w(s){try{return await at("git rev-parse --is-inside-work-tree",s),!0}catch{return!1}}async function Ao(s){let{stdout:e}=await at("git status --porcelain",s),t=[],i=[],a=[],c=e.trim().split(`
63
+ `).filter(Boolean);for(let u of c){let p=u[0],g=u[1],m=u.substring(3).trim();p!==" "&&p!=="?"&&t.push(m),g!==" "&&g!=="?"&&i.push(m),p==="?"&&g==="?"&&a.push(m)}return{hasChanges:t.length>0||i.length>0||a.length>0,staged:t,unstaged:i,untracked:a}}async function bw(s){let{stdout:e}=await at("git rev-parse --abbrev-ref HEAD",s);return e.trim()}async function vw(s){let{stdout:e}=await at("git rev-parse --short HEAD",s);return e.trim()}async function ww(s){await at("git add .",s)}async function Cw(s,e,t){try{if(!(await Ao(s)).hasChanges)return{success:!1,filesCommitted:[],error:"No changes to commit"};await ww(s);let c=(await Ao(s)).staged,u=e;t&&(u=`${e}
64
64
 
65
- Task-ID: ${t}`);let p=u.replace(/'/g,"'\\''");return await at(`git commit -m '${p}'`,s),{success:!0,commitHash:await yw(s),filesCommitted:c}}catch(i){return{success:!1,filesCommitted:[],error:i instanceof Error?i.message:"Unknown error during commit"}}}async function vw(s){try{let e=await mw(s);try{await at("git rev-parse --abbrev-ref --symbolic-full-name @{u}",s)}catch{return console.log(`[Git] No upstream configured, setting upstream to origin/${e}`),await at(`git push -u origin ${e}`,s),{success:!0,branch:e,remote:"origin"}}return await at("git push",s),{success:!0,branch:e,remote:"origin"}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error during push"}}}async function ww(s){console.log("[Git] Running full build verification before commit...");try{return await Fd("npm run build",{cwd:s,maxBuffer:10*1024*1024,timeout:3e5}),console.log("[Git] Build verification passed"),{success:!0}}catch(e){let t=e,i=t.stderr||t.stdout||t.message||"Unknown build error";return console.error("[Git] Build verification FAILED"),console.error("[Git] Build error output:",i.substring(0,1e3)),{success:!1,error:`Build verification failed: ${i.substring(0,500)}`}}}async function Ro(s,e){let t={committed:!1,pushed:!1,commitHash:void 0,filesCommitted:[],error:void 0,buildFailed:!1};if(!e.autoCommit)return t;if(!await gw(s))return t.error="Not a git repository",t;let a=await Ao(s);if(!a.hasChanges)return console.log("[Git] No changes to commit"),t;if(console.log(`[Git] Found ${a.unstaged.length+a.untracked.length} files with changes`),e.verifyBuild!==!1){let p=await ww(s);if(!p.success)return console.error("[Git] NOT committing code - build verification failed"),t.error=p.error,t.buildFailed=!0,t}let c=`feat: ${e.taskTitle}
65
+ Task-ID: ${t}`);let p=u.replace(/'/g,"'\\''");return await at(`git commit -m '${p}'`,s),{success:!0,commitHash:await vw(s),filesCommitted:c}}catch(i){return{success:!1,filesCommitted:[],error:i instanceof Error?i.message:"Unknown error during commit"}}}async function Ew(s){try{let e=await bw(s);try{await at("git rev-parse --abbrev-ref --symbolic-full-name @{u}",s)}catch{return console.log(`[Git] No upstream configured, setting upstream to origin/${e}`),await at(`git push -u origin ${e}`,s),{success:!0,branch:e,remote:"origin"}}return await at("git push",s),{success:!0,branch:e,remote:"origin"}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error during push"}}}function kw(s){let e=yw(s,"package.json");if(!gw(e))return!1;try{let t=JSON.parse(mw(e,"utf-8"));return!!(t.scripts&&t.scripts.build)}catch{return!1}}async function Ow(s){if(!kw(s))return console.log("[Git] No package.json or build script found - skipping build verification"),{success:!0,skipped:!0};console.log("[Git] Running full build verification before commit...");try{return await Fd("npm run build",{cwd:s,maxBuffer:10*1024*1024,timeout:3e5}),console.log("[Git] Build verification passed"),{success:!0}}catch(e){let t=e,i=t.stderr||t.stdout||t.message||"Unknown build error";return console.error("[Git] Build verification FAILED"),console.error("[Git] Build error output:",i.substring(0,1e3)),{success:!1,error:`Build verification failed: ${i.substring(0,500)}`}}}async function Ro(s,e){let t={committed:!1,pushed:!1,commitHash:void 0,filesCommitted:[],error:void 0,buildFailed:!1};if(!e.autoCommit)return t;if(!await _w(s))return t.error="Not a git repository",t;let a=await Ao(s);if(!a.hasChanges)return console.log("[Git] No changes to commit"),t;if(console.log(`[Git] Found ${a.unstaged.length+a.untracked.length} files with changes`),e.verifyBuild!==!1){let p=await Ow(s);if(!p.success)return console.error("[Git] NOT committing code - build verification failed"),t.error=p.error,t.buildFailed=!0,t}let c=`feat: ${e.taskTitle}
66
66
 
67
- Automatically committed by Sego Auto-Task Monitor`;console.log("[Git] Committing changes...");let u=await bw(s,c,e.taskId);if(!u.success)return t.error=u.error,t;if(t.committed=!0,t.commitHash=u.commitHash,t.filesCommitted=u.filesCommitted,console.log(`[Git] Committed ${u.filesCommitted.length} files (${u.commitHash})`),e.autoPush){console.log("[Git] Pushing to remote...");let p=await vw(s);p.success?(t.pushed=!0,console.log(`[Git] Pushed to ${p.remote}/${p.branch}`)):(console.error(`[Git] Push failed: ${p.error}`),t.error=`Commit succeeded but push failed: ${p.error}`)}return t}import{exec as Cw}from"child_process";import{promisify as Ew}from"util";var kw=Ew(Cw);function Ow(s){return s.some(e=>e==="prisma/schema.prisma"||e.endsWith("/schema.prisma")||e.includes("prisma/schema.prisma"))}async function Tw(s,e={}){let{skipGenerate:t=!0,acceptDataLoss:i=!0}=e;try{let a=[];t&&a.push("--skip-generate"),i&&a.push("--accept-data-loss");let c=`npx prisma db push ${a.join(" ")}`;console.log(`[Schema] Running: ${c}`);let{stdout:u,stderr:p}=await kw(c,{cwd:s,maxBuffer:10*1024*1024,timeout:12e4}),g=u+(p?`
67
+ Automatically committed by Sego Auto-Task Monitor`;console.log("[Git] Committing changes...");let u=await Cw(s,c,e.taskId);if(!u.success)return t.error=u.error,t;if(t.committed=!0,t.commitHash=u.commitHash,t.filesCommitted=u.filesCommitted,console.log(`[Git] Committed ${u.filesCommitted.length} files (${u.commitHash})`),e.autoPush){console.log("[Git] Pushing to remote...");let p=await Ew(s);p.success?(t.pushed=!0,console.log(`[Git] Pushed to ${p.remote}/${p.branch}`)):(console.error(`[Git] Push failed: ${p.error}`),t.error=`Commit succeeded but push failed: ${p.error}`)}return t}import{exec as Tw}from"child_process";import{promisify as Sw}from"util";var Aw=Sw(Tw);function Rw(s){return s.some(e=>e==="prisma/schema.prisma"||e.endsWith("/schema.prisma")||e.includes("prisma/schema.prisma"))}async function Pw(s,e={}){let{skipGenerate:t=!0,acceptDataLoss:i=!0}=e;try{let a=[];t&&a.push("--skip-generate"),i&&a.push("--accept-data-loss");let c=`npx prisma db push ${a.join(" ")}`;console.log(`[Schema] Running: ${c}`);let{stdout:u,stderr:p}=await Aw(c,{cwd:s,maxBuffer:10*1024*1024,timeout:12e4}),g=u+(p?`
68
68
  ${p}`:"");return g.includes("Your database is now in sync")||g.includes("Database is already in sync")?(console.log("[Schema] Database schema synced successfully"),{success:!0,applied:!0,output:g.trim()}):{success:!1,applied:!1,error:"Unexpected output from prisma db push",output:g.trim()}}catch(a){let c=a,u=[c.stdout,c.stderr].filter(Boolean).join(`
69
- `);return u.includes("Your database is now in sync")||u.includes("Database is already in sync")?(console.log("[Schema] Database schema synced successfully"),{success:!0,applied:!0,output:u.trim()}):(console.error("[Schema] Failed to apply schema:",c.message),{success:!1,applied:!1,error:c.message||"Unknown error applying schema",output:u.trim()})}}async function Wd(s,e,t={}){return Ow(e)?(console.log("[Schema] Prisma schema changes detected, syncing database..."),t.dryRun?(console.log("[Schema] Dry run mode - skipping actual schema push"),{success:!0,applied:!1,output:"Dry run - schema push skipped"}):Tw(s,{skipGenerate:!0,acceptDataLoss:t.acceptDataLoss??!0})):{success:!0,applied:!1}}import{randomBytes as Sw}from"crypto";import{createServer as Aw}from"http";var zn=class{client;config;isProcessing=!1;isProcessingClientRequest=!1;isProcessingBacklogTask=!1;isRunning=!1;pollTimeout=null;ablyClient=null;monitorId;backlogTaskQueue=[];lastActivityTime=Date.now();idleCheckInterval=null;healthServer=null;startedAt=Date.now();constructor(e){this.config=e,this.client=new Qs(e.apiUrl,e.apiKey,e.projectId),this.monitorId=`monitor-${Sw(8).toString("hex")}`}updateActivityTime(){this.lastActivityTime=Date.now()}startHealthServer(){let e=this.config.healthPort;this.healthServer=Aw((t,i)=>{if(t.url==="/health"||t.url==="/"){let a=Math.floor((Date.now()-this.startedAt)/1e3),c=Math.floor((Date.now()-this.lastActivityTime)/1e3),u={status:"healthy",monitorId:this.monitorId,projectId:this.config.projectId,uptime:a,idleSeconds:c,idleTimeoutMinutes:this.config.idleTimeoutMinutes,isProcessing:this.isProcessing||this.isProcessingClientRequest||this.isProcessingBacklogTask,queueLength:this.backlogTaskQueue.length,timestamp:Date.now()};i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify(u))}else i.writeHead(404,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Not found"}))}),this.healthServer.listen(e,()=>{console.log(`[Monitor] Health server listening on port ${e}`)}),this.healthServer.on("error",t=>{console.error("[Monitor] Health server error:",t)})}startIdleChecker(){if(this.config.idleTimeoutMinutes<=0){console.log("[Monitor] Idle timeout disabled");return}let e=this.config.idleTimeoutMinutes*60*1e3;console.log(`[Monitor] Idle timeout: ${this.config.idleTimeoutMinutes} minutes`),this.idleCheckInterval=setInterval(()=>{let t=Date.now()-this.lastActivityTime,i=t/6e4;this.isProcessing||this.isProcessingClientRequest||this.isProcessingBacklogTask||this.backlogTaskQueue.length>0||t>=e&&(console.log(`[Monitor] Idle timeout reached (${i.toFixed(1)} minutes)`),console.log("[Monitor] Initiating graceful shutdown..."),this.stop(),setTimeout(()=>{console.log("[Monitor] Exiting due to idle timeout"),process.exit(0)},2e3))},6e4)}async start(){if(this.isRunning){console.log("[Monitor] Already running");return}if(console.log("[Monitor] Starting auto-task monitor..."),console.log(`[Monitor] Monitor ID: ${this.monitorId}`),console.log(`[Monitor] API URL: ${this.config.apiUrl}`),console.log(`[Monitor] Project ID: ${this.config.projectId||"all projects"}`),console.log(`[Monitor] Poll interval: ${this.config.pollIntervalMs}ms`),console.log(`[Monitor] Task timeout: ${this.config.timeoutMs}ms`),console.log(`[Monitor] Real-time (Ably) enabled: ${this.config.sseEnabled}`),console.log(`[Monitor] Dry run: ${this.config.dryRun}`),console.log(`[Monitor] Working directory: ${this.config.workingDirectory||process.cwd()}`),console.log(`[Monitor] Use Agent SDK: ${this.config.useAgentSdk}`),console.log(`[Monitor] Stream progress: ${this.config.streamProgress}`),console.log(`[Monitor] Conversation only: ${this.config.conversationOnly}`),console.log(`[Monitor] Idle timeout: ${this.config.idleTimeoutMinutes>0?`${this.config.idleTimeoutMinutes} minutes`:"disabled"}`),console.log(`[Monitor] Health port: ${this.config.healthPort}`),!await this.client.validateAuth())throw new Error("API key validation failed");console.log("[Monitor] API key validated successfully"),this.isRunning=!0,this.startedAt=Date.now(),this.lastActivityTime=Date.now(),this.startHealthServer(),this.startIdleChecker(),this.config.sseEnabled&&this.config.projectId?await this.startAbly():this.config.sseEnabled&&!this.config.projectId&&console.log("[Monitor] Real-time disabled - project ID required for client request monitoring"),this.config.conversationOnly?console.log("[Monitor] Conversation-only mode - skipping auto-task polling"):await this.poll()}async startAbly(){try{console.log(`[Monitor] Connecting to Ably for project: ${this.config.projectId}`),this.ablyClient=new Vn(this.config.apiUrl,this.config.apiKey,this.config.projectId,this.monitorId),this.ablyClient.onConnected(e=>{console.log(`[Monitor] Ably connected to project: ${e.projectId}`),console.log(`[Monitor] Monitor ID: ${e.monitorId}`),console.log("[Monitor] Ready to receive work notifications")}),this.ablyClient.onNewWork(async e=>{console.log(`[Monitor] Received work notification: ${e.type} for ${e.requestId}`);try{let t=await this.client.getClientRequest(e.requestId);if(!t){console.error(`[Monitor] Client request ${e.requestId} not found`);return}let i={id:t.id,projectId:t.projectId,description:t.description,channel:t.channel,createdById:t.createdById,createdAt:t.createdAt||new Date().toISOString(),updatedAt:t.updatedAt||new Date().toISOString(),conversationMode:t.conversationMode,planFilePath:t.planFilePath,existingTasks:t.existingTasks,projectContext:t.projectContext||{projectName:"Unknown Project"}};await this.processClientRequest(i)}catch(t){console.error(`[Monitor] Error fetching client request ${e.requestId}:`,t)}}),this.ablyClient.onError(e=>{console.error("[Monitor] Ably error:",e.message)}),this.ablyClient.onDisconnected(()=>{console.log("[Monitor] Ably disconnected")}),await this.ablyClient.start()}catch(e){throw console.error("[Monitor] Failed to start Ably:",e),e}}async processClientRequest(e){if(this.isProcessingClientRequest){console.log("[Monitor] Already processing a client request, skipping");return}let t=rl(e.description);if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing client request: ${e.id}`),console.log(`[Monitor] Project: ${e.projectContext.projectName}`),console.log(`[Monitor] Mode: ${t?"Conversational":"Analysis"}`),console.log(`[Monitor] Description: ${e.description.substring(0,200)}${e.description.length>200?"...":""}`),console.log(`[Monitor] Timeout: ${this.config.clientRequestTimeoutMs}ms`),console.log(`[Monitor] SDK Mode: ${this.config.useAgentSdk?"Agent SDK":"CLI subprocess"}`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping client request processing");return}if(this.config.conversationOnly&&!t){console.log("[Monitor] Conversation-only mode - skipping non-conversational request analysis");return}this.isProcessingClientRequest=!0;let i=Date.now(),a=Date.now(),c="session_start",u=null;this.config.streamProgress&&(u=setInterval(async()=>{let p=Date.now()-a,g=Date.now()-i;if(p>5e3)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"processing",timestamp:Date.now(),message:c==="tool_end"?`Analyzing results... (${Math.round(g/1e3)}s)`:`Processing... (${Math.round(g/1e3)}s)`,emoji:"\u23F3",data:{elapsedMs:g,lastEventType:c,timeSinceLastEventMs:p}})}catch{}},5e3));try{console.log(`[Monitor] Running Claude for ${t?"conversation":"analysis"}...`),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60));let p=this.config.streamProgress?async w=>{a=Date.now(),c=w.type;let C=$r(w);console.log(`[Monitor] ${C.emoji} ${C.message}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,C)}catch(T){console.error("[Monitor] Failed to send progress event:",T)}}:void 0;if(t&&this.config.useAgentSdk){let w=e.conversationMode?e.conversationMode.toLowerCase():il(e.description);console.log(`[Monitor] Conversation mode: ${w} (from ${e.conversationMode?"payload":"description"})`);let C=await cl(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:p,mode:w});console.log("-".repeat(60));let T=Date.now()-i;if(C.totalCostUsd&&console.log(`[Monitor] Agent cost: $${C.totalCostUsd.toFixed(4)}`),C.timedOut){console.log("[Monitor] Claude timed out for conversation");try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"error",timestamp:Date.now(),message:"Conversation timed out",emoji:"\u23F1\uFE0F",data:{error:"timeout",message:"The agent took too long to respond"}})}catch(S){console.error("[Monitor] Failed to send timeout event:",S)}return}if(!C.success){console.log(`[Monitor] Conversation error: ${C.error}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"error",timestamp:Date.now(),message:C.error||"Unknown error",emoji:"\u274C",data:{error:C.error}})}catch(S){console.error("[Monitor] Failed to send error event:",S)}return}if(console.log(`[Monitor] Conversation completed (${T}ms)`),console.log(`[Monitor] Result has ${C.tasks?.length||0} tasks`),C.planFilePath){console.log(`[Monitor] Storing plan file path: ${C.planFilePath}`);try{await this.client.updatePlanFilePath(e.id,C.planFilePath),console.log("[Monitor] Plan file path stored successfully")}catch(S){console.error("[Monitor] Failed to store plan file path:",S)}}if(C.tasks&&C.tasks.length>0){console.log(`[Monitor] Sending ${C.tasks.length} suggested task(s) to frontend`);for(let S of C.tasks)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"task_suggested",timestamp:Date.now(),message:`Task suggested: ${S.title}`,emoji:"\u{1F4CB}",data:{task:S}}),console.log(`[Monitor] \u{1F4CB} Sent task: ${S.title}`)}catch(O){console.error("[Monitor] Failed to send task_suggested event:",O)}}try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"result",timestamp:Date.now(),message:`Conversation completed with ${C.tasks?.length||0} task(s)`,emoji:"\u2705",data:{success:!0,tasksCount:C.tasks?.length||0,processingTimeMs:T}}),console.log("[Monitor] \u2705 Sent result event")}catch(S){console.error("[Monitor] Failed to send result event:",S)}return}let g;this.config.useAgentSdk?(g=await sl(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:p}),g.totalCostUsd&&console.log(`[Monitor] Agent cost: $${g.totalCostUsd.toFixed(4)}`)):g=await Kc(e,this.config.clientRequestTimeoutMs,{verbose:!0}),console.log("-".repeat(60));let m=Date.now()-i;if(g.timedOut){console.log("[Monitor] Claude timed out for client request"),await this.client.reportAnalysisFailure(e.id,this.monitorId,"Analysis timed out");return}if(!g.success||!g.analysis){console.log(`[Monitor] Claude analysis failed: ${g.error}`),await this.client.reportAnalysisFailure(e.id,this.monitorId,g.error||"Unknown error");return}console.log("[Monitor] Submitting analysis...");let _=await this.client.submitAnalysis(e.id,this.monitorId,g.analysis,m,{costUsd:g.totalCostUsd,tokensUsed:g.usage?g.usage.inputTokens+g.usage.outputTokens:void 0,inputTokens:g.usage?.inputTokens,outputTokens:g.usage?.outputTokens});console.log(`[Monitor] Analysis submitted successfully - ${_.tasksCount} tasks suggested (${m}ms)`)}catch(p){console.error("[Monitor] Error processing client request:",p);try{await this.client.reportAnalysisFailure(e.id,this.monitorId,p instanceof Error?p.message:"Unknown error")}catch(g){console.error("[Monitor] Failed to report analysis failure:",g)}}finally{u&&clearInterval(u),this.isProcessingClientRequest=!1,this.updateActivityTime()}}async handleTaskAvailable(e){if(console.log(`[Monitor] Task available: ${e.id} - ${e.title}`),this.config.conversationOnly){console.log("[Monitor] Conversation-only mode - skipping task processing");return}this.backlogTaskQueue.some(t=>t.id===e.id)||(this.backlogTaskQueue.push(e),console.log(`[Monitor] Added to queue (${this.backlogTaskQueue.length} tasks in queue)`)),await this.processNextBacklogTask()}async processNextBacklogTask(){if(this.isProcessingBacklogTask){console.log("[Monitor] Already processing a backlog task");return}if(this.backlogTaskQueue.length===0){console.log("[Monitor] No backlog tasks in queue");return}let e=this.backlogTaskQueue.shift();if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing backlog task: ${e.id}`),console.log(`[Monitor] Title: ${e.title}`),console.log(`[Monitor] Type: ${e.type} | Priority: ${e.priority}`),console.log(`[Monitor] Estimated hours: ${e.estimatedHours||"N/A"}`),console.log(`[Monitor] Mode: ${this.config.useAgentSdk?"Agent SDK":"CLI subprocess"}`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping backlog task processing"),this.backlogTaskQueue.length>0&&await this.processNextBacklogTask();return}this.isProcessingBacklogTask=!0;let t=Date.now(),i=async(c,u)=>{if(!this.config.streamProgress)return;let p={type:"phase",timestamp:Date.now(),message:u,emoji:{claiming:"\u{1F4CB}",analyzing:"\u{1F50D}",implementing:"\u{1F6E0}\uFE0F",testing:"\u{1F9EA}",committing:"\u{1F4BE}","schema-migration":"\u{1F5C4}\uFE0F",completed:"\u2705",error:"\u274C"}[c]||"\u{1F504}",data:{phase:c,message:u}};console.log(`[Monitor] ${p.emoji} ${u}`);try{await this.client.sendTaskAgentProgress(e.id,this.monitorId,p)}catch(g){console.error("[Monitor] Failed to send phase event:",g)}},a="claiming";try{console.log("[Monitor] Claiming task..."),await i("claiming","Claiming task..."),await this.client.claimTask(e.id,this.monitorId),console.log("[Monitor] Task claimed successfully"),console.log("[Monitor] Running Claude for backlog task..."),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60)),await i("analyzing","Analyzing codebase..."),a="analyzing";let c;this.config.useAgentSdk?(c=await Hr(e,{timeoutMs:this.config.timeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:this.config.streamProgress?async w=>{if(w.type==="tool_start"){let T=w.data;if((T.tool==="Edit"||T.tool==="Write")&&a==="analyzing"&&(a="implementing",await i("implementing","Implementing changes...")),T.tool==="Bash"&&a==="implementing"){let O=T.input?.command||"";(O.includes("test")||O.includes("jest")||O.includes("pytest")||O.includes("npm run test")||O.includes("pnpm test")||O.includes("yarn test"))&&(a="testing",await i("testing","Running tests..."))}}let C=$r(w);console.log(`[Monitor] ${C.emoji} ${C.message}`);try{await this.client.sendTaskAgentProgress(e.id,this.monitorId,C)}catch(T){console.error("[Monitor] Failed to send progress event:",T)}}:void 0}),c.totalCostUsd&&console.log(`[Monitor] Agent cost: $${c.totalCostUsd.toFixed(4)}`)):c=await Jc(e,this.config.timeoutMs,{verbose:!0,workingDirectory:this.config.workingDirectory}),console.log("-".repeat(60));let u=Date.now()-t;if(c.timedOut){console.log("[Monitor] Claude timed out for backlog task"),await i("error","Task processing timed out"),await this.client.failBacklogTask(e.id,this.monitorId,"Task processing timed out",!0);return}if(!c.success){console.log(`[Monitor] Claude failed: ${c.error}`),await i("error",c.error||"Task processing failed"),await this.client.failBacklogTask(e.id,this.monitorId,c.error||"Unknown error",!0);return}let p,g=[];if(this.config.autoCommit){await i("committing","Verifying build and committing changes..."),console.log("[Monitor] Running build verification and auto-commit...");let w=this.config.workingDirectory||process.cwd(),C=await Ro(w,{taskId:e.id,taskTitle:e.title,autoCommit:this.config.autoCommit,autoPush:this.config.autoPush,verifyBuild:!0});if(C.buildFailed){console.error("[Monitor] Build verification failed - NOT pushing broken code"),console.error(`[Monitor] Build error: ${C.error}`),await i("error","Build verification failed - code not committed"),await this.client.failBacklogTask(e.id,this.monitorId,`Build verification failed: ${C.error?.substring(0,500)||"Unknown build error"}`,!0);return}if(C.committed){if(p=C.commitHash,g=C.filesCommitted,console.log(`[Monitor] Auto-commit successful: ${p} (${g.length} files)`),this.config.autoSchemaMigration&&g.length>0){await i("schema-migration","Applying database schema changes...");let T=await Wd(w,g,{dryRun:this.config.dryRun,acceptDataLoss:!0});T.applied?console.log("[Monitor] Schema migration applied successfully"):T.error&&console.warn(`[Monitor] Schema migration failed: ${T.error}`)}C.pushed?console.log("[Monitor] Auto-push successful"):this.config.autoPush&&C.error&&console.warn(`[Monitor] Auto-push failed: ${C.error}`)}else C.error&&C.error!=="No changes to commit"?console.warn(`[Monitor] Auto-commit failed: ${C.error}`):console.log("[Monitor] No changes to commit")}console.log("[Monitor] Completing task..."),await this.client.completeBacklogTask(e.id,this.monitorId,{summary:c.output?.substring(0,1e3)||"Task completed by auto-monitor",filesChanged:g.length>0?g:void 0,commitHash:p},{costUsd:c.totalCostUsd,tokensUsed:(c.inputTokens||0)+(c.outputTokens||0)||void 0});let m=(c.inputTokens||0)+(c.outputTokens||0),_=c.totalCostUsd?` (cost: $${c.totalCostUsd.toFixed(4)}${m?`, ${m.toLocaleString()} tokens`:""})`:"";await i("completed","Task completed successfully"),console.log(`[Monitor] Task ${e.id} completed successfully${_} (${u}ms)`),await this.triggerContainerRebuild()}catch(c){console.error("[Monitor] Error processing backlog task:",c);let u=c instanceof Error?c.message:"Unknown error";await i("error",u);try{await this.client.failBacklogTask(e.id,this.monitorId,u,!0)}catch(p){console.error("[Monitor] Failed to report task failure:",p)}}finally{this.isProcessingBacklogTask=!1,this.updateActivityTime(),this.backlogTaskQueue.length>0&&(console.log(`[Monitor] ${this.backlogTaskQueue.length} more tasks in queue, processing next...`),await this.processNextBacklogTask())}}async triggerContainerRebuild(){try{console.log("[Monitor] Triggering container rebuild...");let e=await fetch("http://localhost:3000/api/rebuild",{method:"POST",headers:{"Content-Type":"application/json"}});if(e.ok){let t=await e.json();console.log(`[Monitor] Rebuild completed in ${t.duration}ms`)}else console.warn("[Monitor] Rebuild request failed:",e.status)}catch(e){console.warn("[Monitor] Could not trigger rebuild:",e)}}stop(){console.log("[Monitor] Stopping..."),this.isRunning=!1,this.pollTimeout&&(clearTimeout(this.pollTimeout),this.pollTimeout=null),this.ablyClient&&(this.ablyClient.stop(),this.ablyClient=null),this.idleCheckInterval&&(clearInterval(this.idleCheckInterval),this.idleCheckInterval=null),this.healthServer&&(this.healthServer.close(),this.healthServer=null)}async poll(){if(this.isRunning){try{this.isProcessing||await this.checkForTask()}catch(e){console.error("[Monitor] Poll error:",e)}this.isRunning&&(this.pollTimeout=setTimeout(()=>this.poll(),this.config.pollIntervalMs))}}async checkForTask(){console.log("[Monitor] Checking for eligible tasks...");let e=await this.client.getEligibleTask();if(!e){console.log("[Monitor] No eligible tasks found");return}if(console.log(`[Monitor] Found eligible task: ${e.title} (confidence: ${e.aiConfidence})`),this.config.dryRun){console.log("[Monitor] Dry run - skipping task processing");return}await this.processTask(e)}async processTask(e){this.isProcessing=!0;try{console.log(`[Monitor] Starting task: ${e.id}`);let t=await this.client.startTask(e.id);console.log(`[Monitor] Task started, run ID: ${t.runId}`),console.log("[Monitor] Invoking Claude...");let i;if(this.config.useAgentSdk){let c={id:e.id,projectId:e.project.id,title:e.title,description:e.description,type:e.type||"FEATURE",status:e.status,priority:e.priority||"MEDIUM",estimatedHours:e.estimatedHours?parseFloat(e.estimatedHours):null,acceptanceCriteria:e.acceptanceCriteria||[],technicalNotes:e.technicalNotes,clientRequestId:null,createdById:e.createdBy?.id||"",projectContext:{projectName:e.project.name,knowledgeBase:e.project.knowledgeBase||void 0}};i=await Hr(c,{timeoutMs:this.config.timeoutMs,maxTurns:this.config.maxTurns,workingDirectory:this.config.workingDirectory,verbose:!0}),i.totalCostUsd&&console.log(`[Monitor] Agent cost: $${i.totalCostUsd.toFixed(4)}`)}else i=await Vc(e,this.config.timeoutMs);if(i.timedOut){console.log("[Monitor] Claude timed out"),await this.handleFailure(t.runId,e,"TIMEOUT",i.output,"Task processing timed out");return}if(!i.success){console.log(`[Monitor] Claude failed: ${i.error}`),await this.handleFailure(t.runId,e,"FAILED",i.output,i.error);return}console.log("[Monitor] Claude completed successfully");let a=(i.inputTokens||0)+(i.outputTokens||0);await this.handleSuccess(t.runId,e,i.output,i.totalCostUsd,a||void 0)}catch(t){console.error("[Monitor] Error processing task:",t)}finally{this.isProcessing=!1}}async handleSuccess(e,t,i,a,c){let u="";if(this.config.autoCommit){console.log("[Monitor] Running build verification and auto-commit...");let m=this.config.workingDirectory||process.cwd(),_=await Ro(m,{taskId:t.id,taskTitle:t.title,autoCommit:this.config.autoCommit,autoPush:this.config.autoPush,verifyBuild:!0});if(_.buildFailed){console.error("[Monitor] Build verification failed - NOT pushing broken code"),u=`
69
+ `);return u.includes("Your database is now in sync")||u.includes("Database is already in sync")?(console.log("[Schema] Database schema synced successfully"),{success:!0,applied:!0,output:u.trim()}):(console.error("[Schema] Failed to apply schema:",c.message),{success:!1,applied:!1,error:c.message||"Unknown error applying schema",output:u.trim()})}}async function Wd(s,e,t={}){return Rw(e)?(console.log("[Schema] Prisma schema changes detected, syncing database..."),t.dryRun?(console.log("[Schema] Dry run mode - skipping actual schema push"),{success:!0,applied:!1,output:"Dry run - schema push skipped"}):Pw(s,{skipGenerate:!0,acceptDataLoss:t.acceptDataLoss??!0})):{success:!0,applied:!1}}import{randomBytes as Iw}from"crypto";import{createServer as Mw}from"http";var zn=class{client;config;isProcessing=!1;isProcessingClientRequest=!1;isProcessingBacklogTask=!1;isRunning=!1;pollTimeout=null;ablyClient=null;monitorId;backlogTaskQueue=[];lastActivityTime=Date.now();idleCheckInterval=null;healthServer=null;startedAt=Date.now();constructor(e){this.config=e,this.client=new Qs(e.apiUrl,e.apiKey,e.projectId),this.monitorId=`monitor-${Iw(8).toString("hex")}`}updateActivityTime(){this.lastActivityTime=Date.now()}startHealthServer(){let e=this.config.healthPort;this.healthServer=Mw((t,i)=>{if(t.url==="/health"||t.url==="/"){let a=Math.floor((Date.now()-this.startedAt)/1e3),c=Math.floor((Date.now()-this.lastActivityTime)/1e3),u={status:"healthy",monitorId:this.monitorId,projectId:this.config.projectId,uptime:a,idleSeconds:c,idleTimeoutMinutes:this.config.idleTimeoutMinutes,isProcessing:this.isProcessing||this.isProcessingClientRequest||this.isProcessingBacklogTask,queueLength:this.backlogTaskQueue.length,timestamp:Date.now()};i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify(u))}else i.writeHead(404,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Not found"}))}),this.healthServer.listen(e,()=>{console.log(`[Monitor] Health server listening on port ${e}`)}),this.healthServer.on("error",t=>{console.error("[Monitor] Health server error:",t)})}startIdleChecker(){if(this.config.idleTimeoutMinutes<=0){console.log("[Monitor] Idle timeout disabled");return}let e=this.config.idleTimeoutMinutes*60*1e3;console.log(`[Monitor] Idle timeout: ${this.config.idleTimeoutMinutes} minutes`),this.idleCheckInterval=setInterval(()=>{let t=Date.now()-this.lastActivityTime,i=t/6e4;this.isProcessing||this.isProcessingClientRequest||this.isProcessingBacklogTask||this.backlogTaskQueue.length>0||t>=e&&(console.log(`[Monitor] Idle timeout reached (${i.toFixed(1)} minutes)`),console.log("[Monitor] Initiating graceful shutdown..."),this.stop(),setTimeout(()=>{console.log("[Monitor] Exiting due to idle timeout"),process.exit(0)},2e3))},6e4)}async start(){if(this.isRunning){console.log("[Monitor] Already running");return}if(console.log("[Monitor] Starting auto-task monitor..."),console.log(`[Monitor] Monitor ID: ${this.monitorId}`),console.log(`[Monitor] API URL: ${this.config.apiUrl}`),console.log(`[Monitor] Project ID: ${this.config.projectId||"all projects"}`),console.log(`[Monitor] Poll interval: ${this.config.pollIntervalMs}ms`),console.log(`[Monitor] Task timeout: ${this.config.timeoutMs}ms`),console.log(`[Monitor] Real-time (Ably) enabled: ${this.config.sseEnabled}`),console.log(`[Monitor] Dry run: ${this.config.dryRun}`),console.log(`[Monitor] Working directory: ${this.config.workingDirectory||process.cwd()}`),console.log(`[Monitor] Use Agent SDK: ${this.config.useAgentSdk}`),console.log(`[Monitor] Stream progress: ${this.config.streamProgress}`),console.log(`[Monitor] Conversation only: ${this.config.conversationOnly}`),console.log(`[Monitor] Idle timeout: ${this.config.idleTimeoutMinutes>0?`${this.config.idleTimeoutMinutes} minutes`:"disabled"}`),console.log(`[Monitor] Health port: ${this.config.healthPort}`),!await this.client.validateAuth())throw new Error("API key validation failed");console.log("[Monitor] API key validated successfully"),this.isRunning=!0,this.startedAt=Date.now(),this.lastActivityTime=Date.now(),this.startHealthServer(),this.startIdleChecker(),this.config.sseEnabled&&this.config.projectId?await this.startAbly():this.config.sseEnabled&&!this.config.projectId&&console.log("[Monitor] Real-time disabled - project ID required for client request monitoring"),this.config.conversationOnly?console.log("[Monitor] Conversation-only mode - skipping auto-task polling"):await this.poll()}async startAbly(){try{console.log(`[Monitor] Connecting to Ably for project: ${this.config.projectId}`),this.ablyClient=new Vn(this.config.apiUrl,this.config.apiKey,this.config.projectId,this.monitorId),this.ablyClient.onConnected(e=>{console.log(`[Monitor] Ably connected to project: ${e.projectId}`),console.log(`[Monitor] Monitor ID: ${e.monitorId}`),console.log("[Monitor] Ready to receive work notifications")}),this.ablyClient.onNewWork(async e=>{console.log(`[Monitor] Received work notification: ${e.type} for ${e.requestId}`);try{let t=await this.client.getClientRequest(e.requestId);if(!t){console.error(`[Monitor] Client request ${e.requestId} not found`);return}let i={id:t.id,projectId:t.projectId,description:t.description,channel:t.channel,createdById:t.createdById,createdAt:t.createdAt||new Date().toISOString(),updatedAt:t.updatedAt||new Date().toISOString(),conversationMode:t.conversationMode,planFilePath:t.planFilePath,existingTasks:t.existingTasks,projectContext:t.projectContext||{projectName:"Unknown Project"}};await this.processClientRequest(i)}catch(t){console.error(`[Monitor] Error fetching client request ${e.requestId}:`,t)}}),this.ablyClient.onError(e=>{console.error("[Monitor] Ably error:",e.message)}),this.ablyClient.onDisconnected(()=>{console.log("[Monitor] Ably disconnected")}),await this.ablyClient.start()}catch(e){throw console.error("[Monitor] Failed to start Ably:",e),e}}async processClientRequest(e){if(this.isProcessingClientRequest){console.log("[Monitor] Already processing a client request, skipping");return}let t=rl(e.description);if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing client request: ${e.id}`),console.log(`[Monitor] Project: ${e.projectContext.projectName}`),console.log(`[Monitor] Mode: ${t?"Conversational":"Analysis"}`),console.log(`[Monitor] Description: ${e.description.substring(0,200)}${e.description.length>200?"...":""}`),console.log(`[Monitor] Timeout: ${this.config.clientRequestTimeoutMs}ms`),console.log(`[Monitor] SDK Mode: ${this.config.useAgentSdk?"Agent SDK":"CLI subprocess"}`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping client request processing");return}if(this.config.conversationOnly&&!t){console.log("[Monitor] Conversation-only mode - skipping non-conversational request analysis");return}this.isProcessingClientRequest=!0;let i=Date.now(),a=Date.now(),c="session_start",u=null;this.config.streamProgress&&(u=setInterval(async()=>{let p=Date.now()-a,g=Date.now()-i;if(p>5e3)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"processing",timestamp:Date.now(),message:c==="tool_end"?`Analyzing results... (${Math.round(g/1e3)}s)`:`Processing... (${Math.round(g/1e3)}s)`,emoji:"\u23F3",data:{elapsedMs:g,lastEventType:c,timeSinceLastEventMs:p}})}catch{}},5e3));try{console.log(`[Monitor] Running Claude for ${t?"conversation":"analysis"}...`),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60));let p=this.config.streamProgress?async w=>{a=Date.now(),c=w.type;let C=$r(w);console.log(`[Monitor] ${C.emoji} ${C.message}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,C)}catch(T){console.error("[Monitor] Failed to send progress event:",T)}}:void 0;if(t&&this.config.useAgentSdk){let w=e.conversationMode?e.conversationMode.toLowerCase():il(e.description);console.log(`[Monitor] Conversation mode: ${w} (from ${e.conversationMode?"payload":"description"})`);let C=await cl(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:p,mode:w});console.log("-".repeat(60));let T=Date.now()-i;if(C.totalCostUsd&&console.log(`[Monitor] Agent cost: $${C.totalCostUsd.toFixed(4)}`),C.timedOut){console.log("[Monitor] Claude timed out for conversation");try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"error",timestamp:Date.now(),message:"Conversation timed out",emoji:"\u23F1\uFE0F",data:{error:"timeout",message:"The agent took too long to respond"}})}catch(S){console.error("[Monitor] Failed to send timeout event:",S)}return}if(!C.success){console.log(`[Monitor] Conversation error: ${C.error}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"error",timestamp:Date.now(),message:C.error||"Unknown error",emoji:"\u274C",data:{error:C.error}})}catch(S){console.error("[Monitor] Failed to send error event:",S)}return}if(console.log(`[Monitor] Conversation completed (${T}ms)`),console.log(`[Monitor] Result has ${C.tasks?.length||0} tasks`),C.planFilePath){console.log(`[Monitor] Storing plan file path: ${C.planFilePath}`);try{await this.client.updatePlanFilePath(e.id,C.planFilePath),console.log("[Monitor] Plan file path stored successfully")}catch(S){console.error("[Monitor] Failed to store plan file path:",S)}}if(C.tasks&&C.tasks.length>0){console.log(`[Monitor] Sending ${C.tasks.length} suggested task(s) to frontend`);for(let S of C.tasks)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"task_suggested",timestamp:Date.now(),message:`Task suggested: ${S.title}`,emoji:"\u{1F4CB}",data:{task:S}}),console.log(`[Monitor] \u{1F4CB} Sent task: ${S.title}`)}catch(O){console.error("[Monitor] Failed to send task_suggested event:",O)}}try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"result",timestamp:Date.now(),message:`Conversation completed with ${C.tasks?.length||0} task(s)`,emoji:"\u2705",data:{success:!0,tasksCount:C.tasks?.length||0,processingTimeMs:T}}),console.log("[Monitor] \u2705 Sent result event")}catch(S){console.error("[Monitor] Failed to send result event:",S)}return}let g;this.config.useAgentSdk?(g=await sl(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:p}),g.totalCostUsd&&console.log(`[Monitor] Agent cost: $${g.totalCostUsd.toFixed(4)}`)):g=await Kc(e,this.config.clientRequestTimeoutMs,{verbose:!0}),console.log("-".repeat(60));let m=Date.now()-i;if(g.timedOut){console.log("[Monitor] Claude timed out for client request"),await this.client.reportAnalysisFailure(e.id,this.monitorId,"Analysis timed out");return}if(!g.success||!g.analysis){console.log(`[Monitor] Claude analysis failed: ${g.error}`),await this.client.reportAnalysisFailure(e.id,this.monitorId,g.error||"Unknown error");return}console.log("[Monitor] Submitting analysis...");let _=await this.client.submitAnalysis(e.id,this.monitorId,g.analysis,m,{costUsd:g.totalCostUsd,tokensUsed:g.usage?g.usage.inputTokens+g.usage.outputTokens:void 0,inputTokens:g.usage?.inputTokens,outputTokens:g.usage?.outputTokens});console.log(`[Monitor] Analysis submitted successfully - ${_.tasksCount} tasks suggested (${m}ms)`)}catch(p){console.error("[Monitor] Error processing client request:",p);try{await this.client.reportAnalysisFailure(e.id,this.monitorId,p instanceof Error?p.message:"Unknown error")}catch(g){console.error("[Monitor] Failed to report analysis failure:",g)}}finally{u&&clearInterval(u),this.isProcessingClientRequest=!1,this.updateActivityTime()}}async handleTaskAvailable(e){if(console.log(`[Monitor] Task available: ${e.id} - ${e.title}`),this.config.conversationOnly){console.log("[Monitor] Conversation-only mode - skipping task processing");return}this.backlogTaskQueue.some(t=>t.id===e.id)||(this.backlogTaskQueue.push(e),console.log(`[Monitor] Added to queue (${this.backlogTaskQueue.length} tasks in queue)`)),await this.processNextBacklogTask()}async processNextBacklogTask(){if(this.isProcessingBacklogTask){console.log("[Monitor] Already processing a backlog task");return}if(this.backlogTaskQueue.length===0){console.log("[Monitor] No backlog tasks in queue");return}let e=this.backlogTaskQueue.shift();if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing backlog task: ${e.id}`),console.log(`[Monitor] Title: ${e.title}`),console.log(`[Monitor] Type: ${e.type} | Priority: ${e.priority}`),console.log(`[Monitor] Estimated hours: ${e.estimatedHours||"N/A"}`),console.log(`[Monitor] Mode: ${this.config.useAgentSdk?"Agent SDK":"CLI subprocess"}`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping backlog task processing"),this.backlogTaskQueue.length>0&&await this.processNextBacklogTask();return}this.isProcessingBacklogTask=!0;let t=Date.now(),i=async(c,u)=>{if(!this.config.streamProgress)return;let p={type:"phase",timestamp:Date.now(),message:u,emoji:{claiming:"\u{1F4CB}",analyzing:"\u{1F50D}",implementing:"\u{1F6E0}\uFE0F",testing:"\u{1F9EA}",committing:"\u{1F4BE}","schema-migration":"\u{1F5C4}\uFE0F",completed:"\u2705",error:"\u274C"}[c]||"\u{1F504}",data:{phase:c,message:u}};console.log(`[Monitor] ${p.emoji} ${u}`);try{await this.client.sendTaskAgentProgress(e.id,this.monitorId,p)}catch(g){console.error("[Monitor] Failed to send phase event:",g)}},a="claiming";try{console.log("[Monitor] Claiming task..."),await i("claiming","Claiming task..."),await this.client.claimTask(e.id,this.monitorId),console.log("[Monitor] Task claimed successfully"),console.log("[Monitor] Running Claude for backlog task..."),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60)),await i("analyzing","Analyzing codebase..."),a="analyzing";let c;this.config.useAgentSdk?(c=await Hr(e,{timeoutMs:this.config.timeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:this.config.streamProgress?async w=>{if(w.type==="tool_start"){let T=w.data;if((T.tool==="Edit"||T.tool==="Write")&&a==="analyzing"&&(a="implementing",await i("implementing","Implementing changes...")),T.tool==="Bash"&&a==="implementing"){let O=T.input?.command||"";(O.includes("test")||O.includes("jest")||O.includes("pytest")||O.includes("npm run test")||O.includes("pnpm test")||O.includes("yarn test"))&&(a="testing",await i("testing","Running tests..."))}}let C=$r(w);console.log(`[Monitor] ${C.emoji} ${C.message}`);try{await this.client.sendTaskAgentProgress(e.id,this.monitorId,C)}catch(T){console.error("[Monitor] Failed to send progress event:",T)}}:void 0}),c.totalCostUsd&&console.log(`[Monitor] Agent cost: $${c.totalCostUsd.toFixed(4)}`)):c=await Jc(e,this.config.timeoutMs,{verbose:!0,workingDirectory:this.config.workingDirectory}),console.log("-".repeat(60));let u=Date.now()-t;if(c.timedOut){console.log("[Monitor] Claude timed out for backlog task"),await i("error","Task processing timed out"),await this.client.failBacklogTask(e.id,this.monitorId,"Task processing timed out",!0);return}if(!c.success){console.log(`[Monitor] Claude failed: ${c.error}`),await i("error",c.error||"Task processing failed"),await this.client.failBacklogTask(e.id,this.monitorId,c.error||"Unknown error",!0);return}let p,g=[];if(this.config.autoCommit){await i("committing","Verifying build and committing changes..."),console.log("[Monitor] Running build verification and auto-commit...");let w=this.config.workingDirectory||process.cwd(),C=await Ro(w,{taskId:e.id,taskTitle:e.title,autoCommit:this.config.autoCommit,autoPush:this.config.autoPush,verifyBuild:!0});if(C.buildFailed){console.error("[Monitor] Build verification failed - NOT pushing broken code"),console.error(`[Monitor] Build error: ${C.error}`),await i("error","Build verification failed - code not committed"),await this.client.failBacklogTask(e.id,this.monitorId,`Build verification failed: ${C.error?.substring(0,500)||"Unknown build error"}`,!0);return}if(C.committed){if(p=C.commitHash,g=C.filesCommitted,console.log(`[Monitor] Auto-commit successful: ${p} (${g.length} files)`),this.config.autoSchemaMigration&&g.length>0){await i("schema-migration","Applying database schema changes...");let T=await Wd(w,g,{dryRun:this.config.dryRun,acceptDataLoss:!0});T.applied?console.log("[Monitor] Schema migration applied successfully"):T.error&&console.warn(`[Monitor] Schema migration failed: ${T.error}`)}C.pushed?console.log("[Monitor] Auto-push successful"):this.config.autoPush&&C.error&&console.warn(`[Monitor] Auto-push failed: ${C.error}`)}else C.error&&C.error!=="No changes to commit"?console.warn(`[Monitor] Auto-commit failed: ${C.error}`):console.log("[Monitor] No changes to commit")}console.log("[Monitor] Completing task..."),await this.client.completeBacklogTask(e.id,this.monitorId,{summary:c.output?.substring(0,1e3)||"Task completed by auto-monitor",filesChanged:g.length>0?g:void 0,commitHash:p},{costUsd:c.totalCostUsd,tokensUsed:(c.inputTokens||0)+(c.outputTokens||0)||void 0});let m=(c.inputTokens||0)+(c.outputTokens||0),_=c.totalCostUsd?` (cost: $${c.totalCostUsd.toFixed(4)}${m?`, ${m.toLocaleString()} tokens`:""})`:"";await i("completed","Task completed successfully"),console.log(`[Monitor] Task ${e.id} completed successfully${_} (${u}ms)`),await this.triggerContainerRebuild()}catch(c){console.error("[Monitor] Error processing backlog task:",c);let u=c instanceof Error?c.message:"Unknown error";await i("error",u);try{await this.client.failBacklogTask(e.id,this.monitorId,u,!0)}catch(p){console.error("[Monitor] Failed to report task failure:",p)}}finally{this.isProcessingBacklogTask=!1,this.updateActivityTime(),this.backlogTaskQueue.length>0&&(console.log(`[Monitor] ${this.backlogTaskQueue.length} more tasks in queue, processing next...`),await this.processNextBacklogTask())}}async triggerContainerRebuild(){try{console.log("[Monitor] Triggering container rebuild...");let e=await fetch("http://localhost:3000/api/rebuild",{method:"POST",headers:{"Content-Type":"application/json"}});if(e.ok){let t=await e.json();console.log(`[Monitor] Rebuild completed in ${t.duration}ms`)}else console.warn("[Monitor] Rebuild request failed:",e.status)}catch(e){console.warn("[Monitor] Could not trigger rebuild:",e)}}stop(){console.log("[Monitor] Stopping..."),this.isRunning=!1,this.pollTimeout&&(clearTimeout(this.pollTimeout),this.pollTimeout=null),this.ablyClient&&(this.ablyClient.stop(),this.ablyClient=null),this.idleCheckInterval&&(clearInterval(this.idleCheckInterval),this.idleCheckInterval=null),this.healthServer&&(this.healthServer.close(),this.healthServer=null)}async poll(){if(this.isRunning){try{this.isProcessing||await this.checkForTask()}catch(e){console.error("[Monitor] Poll error:",e)}this.isRunning&&(this.pollTimeout=setTimeout(()=>this.poll(),this.config.pollIntervalMs))}}async checkForTask(){console.log("[Monitor] Checking for eligible tasks...");let e=await this.client.getEligibleTask();if(!e){console.log("[Monitor] No eligible tasks found");return}if(console.log(`[Monitor] Found eligible task: ${e.title} (confidence: ${e.aiConfidence})`),this.config.dryRun){console.log("[Monitor] Dry run - skipping task processing");return}await this.processTask(e)}async processTask(e){this.isProcessing=!0;try{console.log(`[Monitor] Starting task: ${e.id}`);let t=await this.client.startTask(e.id);console.log(`[Monitor] Task started, run ID: ${t.runId}`),console.log("[Monitor] Invoking Claude...");let i;if(this.config.useAgentSdk){let c={id:e.id,projectId:e.project.id,title:e.title,description:e.description,type:e.type||"FEATURE",status:e.status,priority:e.priority||"MEDIUM",estimatedHours:e.estimatedHours?parseFloat(e.estimatedHours):null,acceptanceCriteria:e.acceptanceCriteria||[],technicalNotes:e.technicalNotes,clientRequestId:null,createdById:e.createdBy?.id||"",projectContext:{projectName:e.project.name,knowledgeBase:e.project.knowledgeBase||void 0}};i=await Hr(c,{timeoutMs:this.config.timeoutMs,maxTurns:this.config.maxTurns,workingDirectory:this.config.workingDirectory,verbose:!0}),i.totalCostUsd&&console.log(`[Monitor] Agent cost: $${i.totalCostUsd.toFixed(4)}`)}else i=await Vc(e,this.config.timeoutMs);if(i.timedOut){console.log("[Monitor] Claude timed out"),await this.handleFailure(t.runId,e,"TIMEOUT",i.output,"Task processing timed out");return}if(!i.success){console.log(`[Monitor] Claude failed: ${i.error}`),await this.handleFailure(t.runId,e,"FAILED",i.output,i.error);return}console.log("[Monitor] Claude completed successfully");let a=(i.inputTokens||0)+(i.outputTokens||0);await this.handleSuccess(t.runId,e,i.output,i.totalCostUsd,a||void 0)}catch(t){console.error("[Monitor] Error processing task:",t)}finally{this.isProcessing=!1}}async handleSuccess(e,t,i,a,c){let u="";if(this.config.autoCommit){console.log("[Monitor] Running build verification and auto-commit...");let m=this.config.workingDirectory||process.cwd(),_=await Ro(m,{taskId:t.id,taskTitle:t.title,autoCommit:this.config.autoCommit,autoPush:this.config.autoPush,verifyBuild:!0});if(_.buildFailed){console.error("[Monitor] Build verification failed - NOT pushing broken code"),u=`
70
70
 
71
71
  ### Git
72
72
  - \u26A0\uFE0F Build verification FAILED
@@ -84,10 +84,10 @@ ${p}`:"");return g.includes("Your database is now in sync")||g.includes("Databas
84
84
 
85
85
  [Output truncated]`:i;if(await this.client.completeTask(e,"COMPLETED",{comment:`## Auto-Task Completed
86
86
 
87
- ${g}${u}`,costUsd:a,tokensUsed:c}),a){let m=c?`, ${c.toLocaleString()} tokens`:"";console.log(`[Monitor] Task ${t.id} completed (cost: $${a.toFixed(4)}${m})`)}else console.log(`[Monitor] Task ${t.id} completed and moved to IN_REVIEW`)}async handleFailure(e,t,i,a,c){let p=a.length>3e3?`${a.substring(0,3e3)}...
87
+ ${g}${u}`,costUsd:a,tokensUsed:c}),a){let m=c?`, ${c.toLocaleString()} tokens`:"";console.log(`[Monitor] Task ${t.id} completed (cost: $${a.toFixed(4)}${m})`)}else console.log(`[Monitor] Task ${t.id} completed and moved to IN_REVIEW`)}async handleFailure(e,t,i,a,c){let g=(a.length>3e3?`${a.substring(0,3e3)}...
88
88
 
89
- [Output truncated]`:a,g=[`## Auto-Task ${i==="TIMEOUT"?"Timed Out":"Failed"}`,"",c?`**Error:** ${c}`:"","","### Output","```",p,"```"].filter(Boolean).join(`
90
- `);await this.client.completeTask(e,i,{comment:g,errorMessage:c}),console.log(`[Monitor] Task ${t.id} marked as ${i}, sending alert...`);try{let m=await this.client.sendAlert(e,i,c);console.log(`[Monitor] Alert sent to ${m.emailsSent} recipients`)}catch(m){console.error("[Monitor] Failed to send alert:",m)}}};import{createInterface as Rw}from"readline";import{writeFileSync as Vd,existsSync as Pw}from"fs";import{resolve as zd}from"path";function Iw(){let s=Rw({input:process.stdin,output:process.stdout});return{ask:e=>new Promise(t=>{s.question(e,i=>{t(i.trim())})}),close:()=>s.close()}}async function Kd(s,e){try{return(await fetch(`${s}/api/mcp/auth/validate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}})).ok}catch{return!1}}function Jd(s){let e=`# Sego Auto-Task Monitor Configuration
89
+ [Output truncated]`:a).replace(/\x1b\[[0-9;]*[a-zA-Z]/g,""),m=[`## Auto-Task ${i==="TIMEOUT"?"Timed Out":"Failed"}`,"",c?`**Error:** ${c}`:"","","<details>","<summary>Output (click to expand)</summary>","","```text",g,"```","</details>"].filter(Boolean).join(`
90
+ `);await this.client.completeTask(e,i,{comment:m,errorMessage:c}),console.log(`[Monitor] Task ${t.id} marked as ${i}, sending alert...`);try{let _=await this.client.sendAlert(e,i,c);console.log(`[Monitor] Alert sent to ${_.emailsSent} recipients`)}catch(_){console.error("[Monitor] Failed to send alert:",_)}}};import{createInterface as xw}from"readline";import{writeFileSync as Vd,existsSync as Nw}from"fs";import{resolve as zd}from"path";function Lw(){let s=xw({input:process.stdin,output:process.stdout});return{ask:e=>new Promise(t=>{s.question(e,i=>{t(i.trim())})}),close:()=>s.close()}}async function Kd(s,e){try{return(await fetch(`${s}/api/mcp/auth/validate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}})).ok}catch{return!1}}function Jd(s){let e=`# Sego Auto-Task Monitor Configuration
91
91
  # Generated by sego-auto-task init
92
92
 
93
93
  # Required: Your Sego PM API key
@@ -99,9 +99,9 @@ SEGO_API_URL=${s.apiUrl}
99
99
  # Filter to specific project
100
100
  SEGO_PROJECT_ID=${s.projectId}
101
101
  `),e}async function Qd(s={}){let e=s.yes||!1;if(console.log(""),console.log("=".repeat(50)),console.log(" Sego Auto-Task Monitor Setup Wizard"),console.log("=".repeat(50)),console.log(""),e){console.log("Running in non-interactive mode (--yes flag)"),console.log("");let i=process.env.SEGO_API_KEY,a=process.env.SEGO_API_URL||"https://sego.pm",c=process.env.SEGO_PROJECT_ID;i||(console.error("Error: SEGO_API_KEY environment variable is required in non-interactive mode."),console.error(""),console.error("Usage:"),console.error(" SEGO_API_KEY=your_key sego-auto-task init --yes"),console.error(""),console.error("Or run without --yes for interactive setup."),process.exit(1)),console.log("Validating API key..."),await Kd(a,i)||(console.error(`
102
- Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${a}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!");let p={apiKey:i,apiUrl:a,projectId:c||void 0},g=zd(process.cwd(),".env"),m=Jd(p);Vd(g,m),Yd(g);return}let t=Iw();try{console.log("Step 1: API Key"),console.log("Get your API key from: https://sego.pm/developer/api-keys"),console.log("");let i=await t.ask("Enter your Sego PM API key: ");i||(console.error(`
102
+ Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${a}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!");let p={apiKey:i,apiUrl:a,projectId:c||void 0},g=zd(process.cwd(),".env"),m=Jd(p);Vd(g,m),Yd(g);return}let t=Lw();try{console.log("Step 1: API Key"),console.log("Get your API key from: https://sego.pm/developer/api-keys"),console.log("");let i=await t.ask("Enter your Sego PM API key: ");i||(console.error(`
103
103
  Error: API key is required.`),process.exit(1)),console.log(""),console.log("Step 2: API URL");let c=await t.ask("Enter API URL (press Enter for https://sego.pm): ")||"https://sego.pm";console.log(""),console.log("Validating API key..."),await Kd(c,i)||(console.error(`
104
- Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${c}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!"),console.log(""),console.log("Step 3: Project ID (Optional)"),console.log("You can filter to a specific project, or monitor all projects.");let p=await t.ask("Enter Project ID (press Enter to skip): "),g={apiKey:i,apiUrl:c,projectId:p||void 0};console.log(""),console.log("Step 4: Save Configuration");let m=zd(process.cwd(),".env");if(Pw(m)&&(console.log(`Warning: .env file already exists at ${m}`),(await t.ask("Overwrite? (y/N): ")).toLowerCase()!=="y")){console.log(""),console.log("Configuration not saved. You can set these environment variables manually:"),console.log(""),console.log(`export SEGO_API_KEY="${g.apiKey}"`),console.log(`export SEGO_API_URL="${g.apiUrl}"`),g.projectId&&console.log(`export SEGO_PROJECT_ID="${g.projectId}"`),console.log(""),t.close();return}let w=Jd(g);Vd(m,w),Yd(m)}finally{t.close()}}function Yd(s){console.log(""),console.log("=".repeat(50)),console.log(" Setup Complete!"),console.log("=".repeat(50)),console.log(""),console.log(`Configuration saved to: ${s}`),console.log(""),console.log("Next steps:"),console.log(" 1. Make sure Claude Code CLI is installed and authenticated:"),console.log(" npm install -g @anthropic-ai/claude-code"),console.log(" claude auth login"),console.log(""),console.log(" 2. Start the monitor:"),console.log(" sego-auto-task"),console.log(""),console.log(" 3. Or run in dry-run mode to test:"),console.log(" sego-auto-task --dry-run"),console.log("")}import{existsSync as Zd,mkdirSync as Mw,readFileSync as xw,writeFileSync as Nw}from"fs";import{homedir as Lw}from"os";import{join as ef}from"path";var tf="@segosolutions/auto-task",Po=ef(Lw(),".sego-auto-task"),Io=ef(Po,"version-check.json"),Dw=24*60*60*1e3;function Xd(s,e){let t=s.replace(/^v/,"").split(".").map(Number),i=e.replace(/^v/,"").split(".").map(Number);for(let a=0;a<Math.max(t.length,i.length);a++){let c=t[a]||0,u=i[a]||0;if(c<u)return-1;if(c>u)return 1}return 0}function Uw(){try{if(!Zd(Io))return null;let s=JSON.parse(xw(Io,"utf-8"));return Date.now()-s.checkedAt<Dw?s:null}catch{return null}}function jw(s){try{Zd(Po)||Mw(Po,{recursive:!0});let e={latestVersion:s,checkedAt:Date.now()};Nw(Io,JSON.stringify(e,null,2))}catch{}}async function qw(){try{let s=new AbortController,e=setTimeout(()=>s.abort(),5e3),t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(tf)}/latest`,{signal:s.signal});return clearTimeout(e),t.ok&&(await t.json()).version||null}catch{return null}}async function sf(s){let e=Uw();if(e)return{currentVersion:s,latestVersion:e.latestVersion,updateAvailable:Xd(s,e.latestVersion)<0};let t=await qw();return t&&jw(t),{currentVersion:s,latestVersion:t,updateAvailable:t?Xd(s,t)<0:!1}}function nf(s){!s.updateAvailable||!s.latestVersion||(console.log(""),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("\x1B[33m Update available!\x1B[0m"),console.log(` Current version: \x1B[90m${s.currentVersion}\x1B[0m`),console.log(` Latest version: \x1B[32m${s.latestVersion}\x1B[0m`),console.log(""),console.log(" Run to update:"),console.log(` \x1B[36m npm update -g ${tf}\x1B[0m`),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""))}var af="1.7.7",Mo=null;ds.name("sego-auto-task").description(`Background task monitor for Sego PM - automatically processes high-confidence tasks using Claude.
104
+ Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${c}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!"),console.log(""),console.log("Step 3: Project ID (Optional)"),console.log("You can filter to a specific project, or monitor all projects.");let p=await t.ask("Enter Project ID (press Enter to skip): "),g={apiKey:i,apiUrl:c,projectId:p||void 0};console.log(""),console.log("Step 4: Save Configuration");let m=zd(process.cwd(),".env");if(Nw(m)&&(console.log(`Warning: .env file already exists at ${m}`),(await t.ask("Overwrite? (y/N): ")).toLowerCase()!=="y")){console.log(""),console.log("Configuration not saved. You can set these environment variables manually:"),console.log(""),console.log(`export SEGO_API_KEY="${g.apiKey}"`),console.log(`export SEGO_API_URL="${g.apiUrl}"`),g.projectId&&console.log(`export SEGO_PROJECT_ID="${g.projectId}"`),console.log(""),t.close();return}let w=Jd(g);Vd(m,w),Yd(m)}finally{t.close()}}function Yd(s){console.log(""),console.log("=".repeat(50)),console.log(" Setup Complete!"),console.log("=".repeat(50)),console.log(""),console.log(`Configuration saved to: ${s}`),console.log(""),console.log("Next steps:"),console.log(" 1. Make sure Claude Code CLI is installed and authenticated:"),console.log(" npm install -g @anthropic-ai/claude-code"),console.log(" claude auth login"),console.log(""),console.log(" 2. Start the monitor:"),console.log(" sego-auto-task"),console.log(""),console.log(" 3. Or run in dry-run mode to test:"),console.log(" sego-auto-task --dry-run"),console.log("")}import{existsSync as Zd,mkdirSync as Dw,readFileSync as Uw,writeFileSync as jw}from"fs";import{homedir as qw}from"os";import{join as ef}from"path";var tf="@segosolutions/auto-task",Po=ef(qw(),".sego-auto-task"),Io=ef(Po,"version-check.json"),Bw=24*60*60*1e3;function Xd(s,e){let t=s.replace(/^v/,"").split(".").map(Number),i=e.replace(/^v/,"").split(".").map(Number);for(let a=0;a<Math.max(t.length,i.length);a++){let c=t[a]||0,u=i[a]||0;if(c<u)return-1;if(c>u)return 1}return 0}function $w(){try{if(!Zd(Io))return null;let s=JSON.parse(Uw(Io,"utf-8"));return Date.now()-s.checkedAt<Bw?s:null}catch{return null}}function Hw(s){try{Zd(Po)||Dw(Po,{recursive:!0});let e={latestVersion:s,checkedAt:Date.now()};jw(Io,JSON.stringify(e,null,2))}catch{}}async function Gw(){try{let s=new AbortController,e=setTimeout(()=>s.abort(),5e3),t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(tf)}/latest`,{signal:s.signal});return clearTimeout(e),t.ok&&(await t.json()).version||null}catch{return null}}async function sf(s){let e=$w();if(e)return{currentVersion:s,latestVersion:e.latestVersion,updateAvailable:Xd(s,e.latestVersion)<0};let t=await Gw();return t&&Hw(t),{currentVersion:s,latestVersion:t,updateAvailable:t?Xd(s,t)<0:!1}}function nf(s){!s.updateAvailable||!s.latestVersion||(console.log(""),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("\x1B[33m Update available!\x1B[0m"),console.log(` Current version: \x1B[90m${s.currentVersion}\x1B[0m`),console.log(` Latest version: \x1B[32m${s.latestVersion}\x1B[0m`),console.log(""),console.log(" Run to update:"),console.log(` \x1B[36m npm update -g ${tf}\x1B[0m`),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""))}var af="1.7.9",Mo=null;ds.name("sego-auto-task").description(`Background task monitor for Sego PM - automatically processes high-confidence tasks using Claude.
105
105
 
106
106
  Runs in hybrid mode:
107
107
  - SSE: Listens for client request events and processes them with local Claude
@@ -109,7 +109,7 @@ Runs in hybrid mode:
109
109
 
110
110
  Environment variables are loaded from .env in the working directory.
111
111
 
112
- Use "sego-auto-task init" to run the interactive setup wizard.`).version(af);ds.command("init").description("Interactive setup wizard to configure your API key and settings").option("-y, --yes","Accept defaults without prompting").action(async s=>{await Qd({yes:s.yes})});ds.option("--api-key <key>","Sego PM API key (or set SEGO_API_KEY env)").option("--api-url <url>","Sego PM API URL (default: https://sego.pm)").option("--project-id <id>","Only process tasks for this project (or set SEGO_PROJECT_ID env). Required for SSE mode.").option("--poll <seconds>","Poll interval in seconds (default: 30)","30").option("--timeout <minutes>","Task timeout in minutes (default: 10)","10").option("--client-request-timeout <minutes>","Client request analysis timeout in minutes (default: 2)","2").option("--no-sse","Disable SSE mode for client request processing").option("--dry-run","Poll but do not process tasks",!1).option("--working-dir <path>","Working directory for Claude and .env loading (or set SEGO_WORKING_DIR env)").option("--no-update-check","Disable update check on startup").option("--use-cli-mode","Use CLI subprocess instead of Agent SDK (legacy mode)").option("--no-stream-progress","Disable streaming agent progress events to the web app").option("--auto-commit","Automatically commit changes after task completion").option("--auto-push","Automatically push commits to remote (requires --auto-commit)").option("--conversation-only","Only handle conversational sessions, skip automatic task processing").option("--idle-timeout <minutes>","Minutes of inactivity before auto-shutdown (0 = disabled, default: 0)","0").option("--health-port <port>","Port for health check endpoint (default: 3001)","3001").action(async s=>{try{s.updateCheck!==!1&&(Mo=sf(af).then(nf).catch(()=>{}));let e=s.workingDir||process.env.SEGO_WORKING_DIR||process.cwd(),t=rf(e),i=rf(t,".env");Bw(i)?(console.log(`Loading environment from: ${i}`),of.default.config({path:i})):console.log(`No .env file found in: ${t}`);let a=s.useCliMode||process.env.USE_CLI_MODE==="true";a?(console.log("Checking for Claude CLI (legacy mode)..."),await zc()||(console.error("Error: Claude CLI is not available. Please install Claude Code first."),console.error(" npm install -g @anthropic-ai/claude-code"),process.exit(1)),console.log("Claude CLI is available")):(console.log("Checking for Claude Agent SDK..."),await nl()||(console.error("Error: Claude Agent SDK is not available."),process.exit(1)),console.log("Claude Agent SDK is available"));let{config:c,sources:u}=$c({apiKey:s.apiKey,apiUrl:s.apiUrl,projectId:s.projectId,pollIntervalMs:parseInt(s.poll,10)*1e3,timeoutMs:parseInt(s.timeout,10)*60*1e3,clientRequestTimeoutMs:parseInt(s.clientRequestTimeout,10)*60*1e3,sseEnabled:s.sse!==!1?void 0:!1,dryRun:s.dryRun?!0:void 0,workingDirectory:t,useAgentSdk:a?!1:void 0,streamProgress:s.streamProgress===!1?!1:void 0,conversationOnly:s.conversationOnly?!0:void 0,autoCommit:s.autoCommit?!0:void 0,autoPush:s.autoPush?!0:void 0,idleTimeoutMinutes:parseInt(s.idleTimeout,10),healthPort:parseInt(s.healthPort,10)}),g=c.apiUrl.includes("sego.pm")||c.apiUrl.includes("vercel")?"PRODUCTION":"DEVELOPMENT";console.log(""),console.log("=".repeat(70)),console.log("Sego Auto-Task Monitor - Configuration"),console.log("=".repeat(70)),console.log(`Environment: ${g}`),console.log(`API URL: ${c.apiUrl} ${we(u.apiUrl)}`),console.log(`SSE Mode: ${c.sseEnabled?"enabled":"disabled"} ${we(u.sseEnabled)}`),console.log(`Project Filter: ${c.projectId||"all projects"} ${we(u.projectId)}`),console.log(`Poll Interval: ${c.pollIntervalMs/1e3}s ${we(u.pollIntervalMs)}`),console.log(`Task Timeout: ${c.timeoutMs/6e4}min ${we(u.timeoutMs)}`),console.log(`Dry Run: ${c.dryRun?"yes":"no"} ${we(u.dryRun)}`),console.log(`Working Dir: ${c.workingDirectory} ${we(u.workingDirectory)}`),console.log(`Execution Mode: ${c.useAgentSdk?"Agent SDK":"CLI subprocess (legacy)"} ${we(u.useAgentSdk)}`),console.log(`Stream Progress: ${c.streamProgress?"yes":"no"} ${we(u.streamProgress)}`),console.log(`Conv. Only: ${c.conversationOnly?"yes":"no"} ${we(u.conversationOnly)}`),console.log(`Auto-Commit: ${c.autoCommit?"yes":"no"} ${we(u.autoCommit)}`),console.log(`Auto-Push: ${c.autoPush?"yes":"no"} ${we(u.autoPush)}`),console.log(`Idle Timeout: ${c.idleTimeoutMinutes>0?`${c.idleTimeoutMinutes}min`:"disabled"} ${we(u.idleTimeoutMinutes)}`),console.log(`Health Port: ${c.healthPort} ${we(u.healthPort)}`),console.log("-".repeat(70)),console.log("Sources: [cli] = command line, [env] = environment variable, [default]"),console.log("=".repeat(70)),console.log(""),Mo&&await Mo;let m=new zn(c),_=()=>{console.log(`
112
+ Use "sego-auto-task init" to run the interactive setup wizard.`).version(af);ds.command("init").description("Interactive setup wizard to configure your API key and settings").option("-y, --yes","Accept defaults without prompting").action(async s=>{await Qd({yes:s.yes})});ds.option("--api-key <key>","Sego PM API key (or set SEGO_API_KEY env)").option("--api-url <url>","Sego PM API URL (default: https://sego.pm)").option("--project-id <id>","Only process tasks for this project (or set SEGO_PROJECT_ID env). Required for SSE mode.").option("--poll <seconds>","Poll interval in seconds (default: 30)","30").option("--timeout <minutes>","Task timeout in minutes (default: 10)","10").option("--client-request-timeout <minutes>","Client request analysis timeout in minutes (default: 2)","2").option("--no-sse","Disable SSE mode for client request processing").option("--dry-run","Poll but do not process tasks",!1).option("--working-dir <path>","Working directory for Claude and .env loading (or set SEGO_WORKING_DIR env)").option("--no-update-check","Disable update check on startup").option("--use-cli-mode","Use CLI subprocess instead of Agent SDK (legacy mode)").option("--no-stream-progress","Disable streaming agent progress events to the web app").option("--auto-commit","Automatically commit changes after task completion").option("--auto-push","Automatically push commits to remote (requires --auto-commit)").option("--conversation-only","Only handle conversational sessions, skip automatic task processing").option("--idle-timeout <minutes>","Minutes of inactivity before auto-shutdown (0 = disabled, default: 0)","0").option("--health-port <port>","Port for health check endpoint (default: 3001)","3001").action(async s=>{try{s.updateCheck!==!1&&(Mo=sf(af).then(nf).catch(()=>{}));let e=s.workingDir||process.env.SEGO_WORKING_DIR||process.cwd(),t=rf(e),i=rf(t,".env");Fw(i)?(console.log(`Loading environment from: ${i}`),of.default.config({path:i})):console.log(`No .env file found in: ${t}`);let a=s.useCliMode||process.env.USE_CLI_MODE==="true";a?(console.log("Checking for Claude CLI (legacy mode)..."),await zc()||(console.error("Error: Claude CLI is not available. Please install Claude Code first."),console.error(" npm install -g @anthropic-ai/claude-code"),process.exit(1)),console.log("Claude CLI is available")):(console.log("Checking for Claude Agent SDK..."),await nl()||(console.error("Error: Claude Agent SDK is not available."),process.exit(1)),console.log("Claude Agent SDK is available"));let{config:c,sources:u}=$c({apiKey:s.apiKey,apiUrl:s.apiUrl,projectId:s.projectId,pollIntervalMs:parseInt(s.poll,10)*1e3,timeoutMs:parseInt(s.timeout,10)*60*1e3,clientRequestTimeoutMs:parseInt(s.clientRequestTimeout,10)*60*1e3,sseEnabled:s.sse!==!1?void 0:!1,dryRun:s.dryRun?!0:void 0,workingDirectory:t,useAgentSdk:a?!1:void 0,streamProgress:s.streamProgress===!1?!1:void 0,conversationOnly:s.conversationOnly?!0:void 0,autoCommit:s.autoCommit?!0:void 0,autoPush:s.autoPush?!0:void 0,idleTimeoutMinutes:parseInt(s.idleTimeout,10),healthPort:parseInt(s.healthPort,10)}),g=c.apiUrl.includes("sego.pm")||c.apiUrl.includes("vercel")?"PRODUCTION":"DEVELOPMENT";console.log(""),console.log("=".repeat(70)),console.log("Sego Auto-Task Monitor - Configuration"),console.log("=".repeat(70)),console.log(`Environment: ${g}`),console.log(`API URL: ${c.apiUrl} ${we(u.apiUrl)}`),console.log(`SSE Mode: ${c.sseEnabled?"enabled":"disabled"} ${we(u.sseEnabled)}`),console.log(`Project Filter: ${c.projectId||"all projects"} ${we(u.projectId)}`),console.log(`Poll Interval: ${c.pollIntervalMs/1e3}s ${we(u.pollIntervalMs)}`),console.log(`Task Timeout: ${c.timeoutMs/6e4}min ${we(u.timeoutMs)}`),console.log(`Dry Run: ${c.dryRun?"yes":"no"} ${we(u.dryRun)}`),console.log(`Working Dir: ${c.workingDirectory} ${we(u.workingDirectory)}`),console.log(`Execution Mode: ${c.useAgentSdk?"Agent SDK":"CLI subprocess (legacy)"} ${we(u.useAgentSdk)}`),console.log(`Stream Progress: ${c.streamProgress?"yes":"no"} ${we(u.streamProgress)}`),console.log(`Conv. Only: ${c.conversationOnly?"yes":"no"} ${we(u.conversationOnly)}`),console.log(`Auto-Commit: ${c.autoCommit?"yes":"no"} ${we(u.autoCommit)}`),console.log(`Auto-Push: ${c.autoPush?"yes":"no"} ${we(u.autoPush)}`),console.log(`Idle Timeout: ${c.idleTimeoutMinutes>0?`${c.idleTimeoutMinutes}min`:"disabled"} ${we(u.idleTimeoutMinutes)}`),console.log(`Health Port: ${c.healthPort} ${we(u.healthPort)}`),console.log("-".repeat(70)),console.log("Sources: [cli] = command line, [env] = environment variable, [default]"),console.log("=".repeat(70)),console.log(""),Mo&&await Mo;let m=new zn(c),_=()=>{console.log(`
113
113
  Received shutdown signal`),m.stop(),process.exit(0)};process.on("SIGINT",_),process.on("SIGTERM",_),await m.start()}catch(e){console.error("Error:",e instanceof Error?e.message:e),process.exit(1)}});ds.parse();
114
114
  /*! Bundled license information:
115
115