@segosolutions/auto-task 1.7.1 → 1.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +0 -0
- package/dist/index.mjs +32 -32
- package/package.json +9 -8
package/dist/index.mjs
CHANGED
|
@@ -1,66 +1,66 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from "module";
|
|
3
3
|
const require = createRequire(import.meta.url);
|
|
4
|
-
var Mg=Object.create;var yc=Object.defineProperty;var xg=Object.getOwnPropertyDescriptor;var Ng=Object.getOwnPropertyNames;var Lg=Object.getPrototypeOf,Dg=Object.prototype.hasOwnProperty;var q=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var $=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var Ug=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ng(e))!Dg.call(s,a)&&a!==t&&yc(s,a,{get:()=>e[a],enumerable:!(i=xg(e,a))||i.enumerable});return s};var br=(s,e,t)=>(t=s!=null?Mg(Lg(s)):{},Ug(e||!s||!s.__esModule?yc(t,"default",{value:s,enumerable:!0}):t,s));var
|
|
5
|
-
`).replace(/^/gm," ".repeat(c))}let m=[`Usage: ${t.commandUsage(e)}`,""],v=t.commandDescription(e);v.length>0&&(m=m.concat([t.wrap(v,a,0),""]));let w=t.visibleArguments(e).map(
|
|
4
|
+
var Mg=Object.create;var yc=Object.defineProperty;var xg=Object.getOwnPropertyDescriptor;var Ng=Object.getOwnPropertyNames;var Lg=Object.getPrototypeOf,Dg=Object.prototype.hasOwnProperty;var q=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var $=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var Ug=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ng(e))!Dg.call(s,a)&&a!==t&&yc(s,a,{get:()=>e[a],enumerable:!(i=xg(e,a))||i.enumerable});return s};var br=(s,e,t)=>(t=s!=null?Mg(Lg(s)):{},Ug(e||!s||!s.__esModule?yc(t,"default",{value:s,enumerable:!0}):t,s));var us=$(wr=>{var zs=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},vr=class extends zs{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};wr.CommanderError=zs;wr.InvalidArgumentError=vr});var Ks=$(Er=>{var{InvalidArgumentError:jg}=us(),Cr=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new jg(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function qg(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}Er.Argument=Cr;Er.humanReadableArgName=qg});var Or=$(_c=>{var{humanReadableArgName:Bg}=Ks(),kr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(a=>!a._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((a,c)=>a.name().localeCompare(c.name())),t}compareOptions(e,t){let i=a=>a.short?a.short.replace(/^-/,""):a.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(a=>!a.hidden),i=e._getHelpOption();if(i&&!i.hidden){let a=i.short&&e._findOption(i.short),c=i.long&&e._findOption(i.long);!a&&!c?t.push(i):i.long&&!c?t.push(e.createOption(i.long,i.description)):i.short&&!a&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let a=i.options.filter(c=>!c.hidden);t.push(...a)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(i=>Bg(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,a)=>Math.max(i,t.subcommandTerm(a).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,a)=>Math.max(i,t.optionTerm(a).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,a)=>Math.max(i,t.optionTerm(a).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,a)=>Math.max(i,t.argumentTerm(a).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let a=e.parent;a;a=a.parent)i=a.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),a=t.helpWidth||80,c=2,h=2;function p(T,k){if(k){let A=`${T.padEnd(i+h)}${k}`;return t.wrap(A,a-c,i+h)}return T}function g(T){return T.join(`
|
|
5
|
+
`).replace(/^/gm," ".repeat(c))}let m=[`Usage: ${t.commandUsage(e)}`,""],v=t.commandDescription(e);v.length>0&&(m=m.concat([t.wrap(v,a,0),""]));let w=t.visibleArguments(e).map(T=>p(t.argumentTerm(T),t.argumentDescription(T)));w.length>0&&(m=m.concat(["Arguments:",g(w),""]));let E=t.visibleOptions(e).map(T=>p(t.optionTerm(T),t.optionDescription(T)));if(E.length>0&&(m=m.concat(["Options:",g(E),""])),this.showGlobalOptions){let T=t.visibleGlobalOptions(e).map(k=>p(t.optionTerm(k),t.optionDescription(k)));T.length>0&&(m=m.concat(["Global Options:",g(T),""]))}let O=t.visibleCommands(e).map(T=>p(t.subcommandTerm(T),t.subcommandDescription(T)));return O.length>0&&(m=m.concat(["Commands:",g(O),""])),m.join(`
|
|
6
6
|
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,i,a=40){let c=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",h=new RegExp(`[\\n][${c}]+`);if(e.match(h))return e;let p=t-i;if(p<a)return e;let g=e.slice(0,i),m=e.slice(i).replace(`\r
|
|
7
7
|
`,`
|
|
8
8
|
`),v=" ".repeat(i),E="\\s\u200B",O=new RegExp(`
|
|
9
|
-
|.{1,${p-1}}([${E}]|$)|[^${E}]+?([${E}]|$)`,"g"),
|
|
10
|
-
`?"":(
|
|
11
|
-
`)}};_c.Help=kr});var Rr=$(Ar=>{var{InvalidArgumentError:$g}=
|
|
9
|
+
|.{1,${p-1}}([${E}]|$)|[^${E}]+?([${E}]|$)`,"g"),T=m.match(O)||[];return g+T.map((k,A)=>k===`
|
|
10
|
+
`?"":(A>0?v:"")+k.trimEnd()).join(`
|
|
11
|
+
`)}};_c.Help=kr});var Rr=$(Ar=>{var{InvalidArgumentError:$g}=us(),Sr=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=Gg(e);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new $g(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Hg(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Tr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let a=this.negativeOptions.get(i).presetArg,c=a!==void 0?a:!1;return t.negate===(c===e)}};function Hg(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Gg(s){let e,t,i=s.split(/[ |,]+/);return i.length>1&&!/^[[<]/.test(i[1])&&(e=i.shift()),t=i.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}Ar.Option=Sr;Ar.DualOptions=Tr});var vc=$(bc=>{function Fg(s,e){if(Math.abs(s.length-e.length)>3)return Math.max(s.length,e.length);let t=[];for(let i=0;i<=s.length;i++)t[i]=[i];for(let i=0;i<=e.length;i++)t[0][i]=i;for(let i=1;i<=e.length;i++)for(let a=1;a<=s.length;a++){let c=1;s[a-1]===e[i-1]?c=0:c=1,t[a][i]=Math.min(t[a-1][i]+1,t[a][i-1]+1,t[a-1][i-1]+c),a>1&&i>1&&s[a-1]===e[i-2]&&s[a-2]===e[i-1]&&(t[a][i]=Math.min(t[a][i],t[a-2][i-2]+1))}return t[s.length][e.length]}function Wg(s,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=s.startsWith("--");t&&(s=s.slice(2),e=e.map(h=>h.slice(2)));let i=[],a=3,c=.4;return e.forEach(h=>{if(h.length<=1)return;let p=Fg(s,h),g=Math.max(s.length,h.length);(g-p)/g>c&&(p<a?(a=p,i=[h]):p===a&&i.push(h))}),i.sort((h,p)=>h.localeCompare(p)),t&&(i=i.map(h=>`--${h}`)),i.length>1?`
|
|
12
12
|
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
13
|
-
(Did you mean ${i[0]}?)`:""}bc.suggestSimilar=Wg});var Oc=$(kc=>{var Vg=q("node:events").EventEmitter,Pr=q("node:child_process"),
|
|
13
|
+
(Did you mean ${i[0]}?)`:""}bc.suggestSimilar=Wg});var Oc=$(kc=>{var Vg=q("node:events").EventEmitter,Pr=q("node:child_process"),Qe=q("node:path"),Ir=q("node:fs"),ue=q("node:process"),{Argument:zg,humanReadableArgName:Kg}=Ks(),{CommanderError:Mr}=us(),{Help:Jg}=Or(),{Option:wc,DualOptions:Yg}=Rr(),{suggestSimilar:Cc}=vc(),xr=class s extends Vg{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>ue.stdout.write(t),writeErr:t=>ue.stderr.write(t),getOutHelpWidth:()=>ue.stdout.isTTY?ue.stdout.columns:void 0,getErrHelpWidth:()=>ue.stderr.isTTY?ue.stderr.columns:void 0,outputError:(t,i)=>i(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,i){let a=t,c=i;typeof a=="object"&&a!==null&&(c=a,a=null),c=c||{};let[,h,p]=e.match(/([^ ]+) *(.*)/),g=this.createCommand(h);return a&&(g.description(a),g._executableHandler=!0),c.isDefault&&(this._defaultCommandName=g._name),g._hidden=!!(c.noHelp||c.hidden),g._executableFile=c.executableFile||null,p&&g.arguments(p),this._registerCommand(g),g.parent=this,g.copyInheritedSettings(this),a?this:g}createCommand(e){return new s(e)}createHelp(){return Object.assign(new Jg,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
14
14
|
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new zg(e,t)}argument(e,t,i,a){let c=this.createArgument(e,t);return typeof i=="function"?c.default(a).argParser(i):c.default(i),this.addArgument(c),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,i,a]=e.match(/([^ ]+) *(.*)/),c=t??"display help for command",h=this.createCommand(i);return h.helpOption(!1),a&&h.arguments(a),c&&h.description(c),this._addImplicitHelpCommand=!0,this._helpCommand=h,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
15
|
-
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,i){this._exitCallback&&this._exitCallback(new Mr(e,t,i)),
|
|
16
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=a=>[a.name()].concat(a.aliases()),i=t(e).find(a=>this._findCommand(a));if(i){let a=t(this._findCommand(i)).join("|"),c=t(e).join("|");throw new Error(`cannot add command '${c}' as already have command '${a}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let c=e.long.replace(/^--no-/,"--");this._findOption(c)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let a=(c,h,p)=>{c==null&&e.presetArg!==void 0&&(c=e.presetArg);let g=this.getOptionValue(i);c!==null&&e.parseArg?c=this._callParseArg(e,c,g,h):c!==null&&e.variadic&&(c=e._concatValue(c,g)),c==null&&(e.negate?c=!1:e.isBoolean()||e.optional?c=!0:c=""),this.setOptionValueWithSource(i,c,p)};return this.on("option:"+t,c=>{let h=`error: option '${e.flags}' argument '${c}' is invalid.`;a(c,h,"cli")}),e.envVar&&this.on("optionEnv:"+t,c=>{let h=`error: option '${e.flags}' value '${c}' from env '${e.envVar}' is invalid.`;a(c,h,"env")}),this}_optionEx(e,t,i,a,c){if(typeof t=="object"&&t instanceof wc)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let h=this.createOption(t,i);if(h.makeOptionMandatory(!!e.mandatory),typeof a=="function")h.default(c).argParser(a);else if(a instanceof RegExp){let p=a;a=(g,m)=>{let v=p.exec(g);return v?v[0]:m},h.default(c).argParser(a)}else h.default(a);return this.addOption(h)}option(e,t,i,a){return this._optionEx({},e,t,i,a)}requiredOption(e,t,i,a){return this._optionEx({mandatory:!0},e,t,i,a)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,i){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(t=i.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){
|
|
15
|
+
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,i){this._exitCallback&&this._exitCallback(new Mr(e,t,i)),ue.exit(e)}action(e){let t=i=>{let a=this.registeredArguments.length,c=i.slice(0,a);return this._storeOptionsAsProperties?c[a]=this:c[a]=this.opts(),c.push(this),e.apply(this,c)};return this._actionHandler=t,this}createOption(e,t){return new wc(e,t)}_callParseArg(e,t,i,a){try{return e.parseArg(t,i)}catch(c){if(c.code==="commander.invalidArgument"){let h=`${a} ${c.message}`;this.error(h,{exitCode:c.exitCode,code:c.code})}throw c}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let i=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
|
|
16
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=a=>[a.name()].concat(a.aliases()),i=t(e).find(a=>this._findCommand(a));if(i){let a=t(this._findCommand(i)).join("|"),c=t(e).join("|");throw new Error(`cannot add command '${c}' as already have command '${a}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let c=e.long.replace(/^--no-/,"--");this._findOption(c)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let a=(c,h,p)=>{c==null&&e.presetArg!==void 0&&(c=e.presetArg);let g=this.getOptionValue(i);c!==null&&e.parseArg?c=this._callParseArg(e,c,g,h):c!==null&&e.variadic&&(c=e._concatValue(c,g)),c==null&&(e.negate?c=!1:e.isBoolean()||e.optional?c=!0:c=""),this.setOptionValueWithSource(i,c,p)};return this.on("option:"+t,c=>{let h=`error: option '${e.flags}' argument '${c}' is invalid.`;a(c,h,"cli")}),e.envVar&&this.on("optionEnv:"+t,c=>{let h=`error: option '${e.flags}' value '${c}' from env '${e.envVar}' is invalid.`;a(c,h,"env")}),this}_optionEx(e,t,i,a,c){if(typeof t=="object"&&t instanceof wc)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let h=this.createOption(t,i);if(h.makeOptionMandatory(!!e.mandatory),typeof a=="function")h.default(c).argParser(a);else if(a instanceof RegExp){let p=a;a=(g,m)=>{let v=p.exec(g);return v?v[0]:m},h.default(c).argParser(a)}else h.default(a);return this.addOption(h)}option(e,t,i,a){return this._optionEx({},e,t,i,a)}requiredOption(e,t,i,a){return this._optionEx({mandatory:!0},e,t,i,a)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,i){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(t=i.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){ue.versions?.electron&&(t.from="electron");let a=ue.execArgv??[];(a.includes("-e")||a.includes("--eval")||a.includes("-p")||a.includes("--print"))&&(t.from="eval")}e===void 0&&(e=ue.argv),this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":ue.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(e,t){let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_executeSubCommand(e,t){t=t.slice();let i=!1,a=[".js",".ts",".tsx",".mjs",".cjs"];function c(v,w){let E=Qe.resolve(v,w);if(Ir.existsSync(E))return E;if(a.includes(Qe.extname(w)))return;let O=a.find(T=>Ir.existsSync(`${E}${T}`));if(O)return`${E}${O}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let h=e._executableFile||`${this._name}-${e._name}`,p=this._executableDir||"";if(this._scriptPath){let v;try{v=Ir.realpathSync(this._scriptPath)}catch{v=this._scriptPath}p=Qe.resolve(Qe.dirname(v),p)}if(p){let v=c(p,h);if(!v&&!e._executableFile&&this._scriptPath){let w=Qe.basename(this._scriptPath,Qe.extname(this._scriptPath));w!==this._name&&(v=c(p,`${w}-${e._name}`))}h=v||h}i=a.includes(Qe.extname(h));let g;ue.platform!=="win32"?i?(t.unshift(h),t=Ec(ue.execArgv).concat(t),g=Pr.spawn(ue.argv[0],t,{stdio:"inherit"})):g=Pr.spawn(h,t,{stdio:"inherit"}):(t.unshift(h),t=Ec(ue.execArgv).concat(t),g=Pr.spawn(ue.execPath,t,{stdio:"inherit"})),g.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(w=>{ue.on(w,()=>{g.killed===!1&&g.exitCode===null&&g.kill(w)})});let m=this._exitCallback;g.on("close",v=>{v=v??1,m?m(new Mr(v,"commander.executeSubCommandAsync","(close)")):ue.exit(v)}),g.on("error",v=>{if(v.code==="ENOENT"){let w=p?`searched for local subcommand relative to directory '${p}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",E=`'${h}' does not exist
|
|
17
17
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
18
18
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
19
|
-
- ${w}`;throw new Error(E)}else if(v.code==="EACCES")throw new Error(`'${h}' not executable`);if(!m)
|
|
19
|
+
- ${w}`;throw new Error(E)}else if(v.code==="EACCES")throw new Error(`'${h}' not executable`);if(!m)ue.exit(1);else{let w=new Mr(1,"commander.executeSubCommandAsync","(error)");w.nestedError=v,m(w)}}),this.runningCommand=g}_dispatchSubcommand(e,t,i){let a=this._findCommand(e);a||this.help({error:!0});let c;return c=this._chainOrCallSubCommandHook(c,a,"preSubcommand"),c=this._chainOrCall(c,()=>{if(a._executableHandler)this._executeSubCommand(a,t.concat(i));else return a._parseCommand(t,i)}),c}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(i,a,c)=>{let h=a;if(a!==null&&i.parseArg){let p=`error: command-argument value '${a}' is invalid for argument '${i.name()}'.`;h=this._callParseArg(i,a,c,p)}return h};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,a)=>{let c=i.defaultValue;i.variadic?a<this.args.length?(c=this.args.slice(a),i.parseArg&&(c=c.reduce((h,p)=>e(i,p,h),i.defaultValue))):c===void 0&&(c=[]):a<this.args.length&&(c=this.args[a],i.parseArg&&(c=e(i,c,i.defaultValue))),t[a]=c}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let i=e,a=[];return this._getCommandAndAncestors().reverse().filter(c=>c._lifeCycleHooks[t]!==void 0).forEach(c=>{c._lifeCycleHooks[t].forEach(h=>{a.push({hookedCommand:c,callback:h})})}),t==="postAction"&&a.reverse(),a.forEach(c=>{i=this._chainOrCall(i,()=>c.callback(c.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let a=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(c=>{a=this._chainOrCall(a,()=>c(this,t))}),a}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},c=`command:${this.name()}`;if(this._actionHandler){a(),this._processArguments();let h;return h=this._chainOrCallHooks(h,"preAction"),h=this._chainOrCall(h,()=>this._actionHandler(this.processedArgs)),this.parent&&(h=this._chainOrCall(h,()=>{this.parent.emit(c,e,t)})),h=this._chainOrCallHooks(h,"postAction"),h}if(this.parent&&this.parent.listenerCount(c))a(),this._processArguments(),this.parent.emit(c,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(a(),this._processArguments())}else this.commands.length?(a(),this.help({error:!0})):(a(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(i=>{let a=i.attributeName();return this.getOptionValue(a)===void 0?!1:this.getOptionValueSource(a)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let a=e.find(c=>i.conflictsWith.includes(c.attributeName()));a&&this._conflictingOption(i,a)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],a=t,c=e.slice();function h(g){return g.length>1&&g[0]==="-"}let p=null;for(;c.length;){let g=c.shift();if(g==="--"){a===i&&a.push(g),a.push(...c);break}if(p&&!h(g)){this.emit(`option:${p.name()}`,g);continue}if(p=null,h(g)){let m=this._findOption(g);if(m){if(m.required){let v=c.shift();v===void 0&&this.optionMissingArgument(m),this.emit(`option:${m.name()}`,v)}else if(m.optional){let v=null;c.length>0&&!h(c[0])&&(v=c.shift()),this.emit(`option:${m.name()}`,v)}else this.emit(`option:${m.name()}`);p=m.variadic?m:null;continue}}if(g.length>2&&g[0]==="-"&&g[1]!=="-"){let m=this._findOption(`-${g[1]}`);if(m){m.required||m.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${m.name()}`,g.slice(2)):(this.emit(`option:${m.name()}`),c.unshift(`-${g.slice(2)}`));continue}}if(/^--[^=]+=/.test(g)){let m=g.indexOf("="),v=this._findOption(g.slice(0,m));if(v&&(v.required||v.optional)){this.emit(`option:${v.name()}`,g.slice(m+1));continue}}if(h(g)&&(a=i),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(g)){t.push(g),c.length>0&&i.push(...c);break}else if(this._getHelpCommand()&&g===this._getHelpCommand().name()){t.push(g),c.length>0&&t.push(...c);break}else if(this._defaultCommandName){i.push(g),c.length>0&&i.push(...c);break}}if(this._passThroughOptions){a.push(g),c.length>0&&a.push(...c);break}a.push(g)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let a=this.options[i].attributeName();e[a]=a===this._versionOptionName?this._version:this[a]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
20
20
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
21
21
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
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
|
|
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=>Kg(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=
|
|
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 ue.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()}`,ue.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Yg(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=h=>{let p=h.attributeName(),g=this.getOptionValue(p),m=this.options.find(w=>w.negate&&p===w.attributeName()),v=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:v||h},a=h=>{let p=i(h),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 h=c.createHelp().visibleOptions(c).filter(p=>p.long).map(p=>p.long);a=a.concat(h),c=c.parent}while(c&&!c._enablePositionalOptions);t=Cc(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=Cc(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
|
+
`),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=>Kg(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=Qe.basename(e,Qe.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=ue.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 h;typeof t=="function"?h=t({error:c.error,command:c.command}):h=t,h&&c.write(`${h}
|
|
25
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(a=>t.is(a))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ec(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})}kc.Command=xr});var Rc=$(
|
|
25
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(a=>t.is(a))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ec(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})}kc.Command=xr});var Rc=$(Me=>{var{Argument:Sc}=Ks(),{Command:Nr}=Oc(),{CommanderError:Qg,InvalidArgumentError:Tc}=us(),{Help:Xg}=Or(),{Option:Ac}=Rr();Me.program=new Nr;Me.createCommand=s=>new Nr(s);Me.createOption=(s,e)=>new Ac(s,e);Me.createArgument=(s,e)=>new Sc(s,e);Me.Command=Nr;Me.Option=Ac;Me.Argument=Sc;Me.Help=Xg;Me.CommanderError=Qg;Me.InvalidArgumentError=Tc;Me.InvalidOptionArgumentError=Tc});var Ic=$((zw,Zg)=>{Zg.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 Uc=$((Kw,Xe)=>{var Lr=q("fs"),Js=q("path"),em=q("os"),tm=q("crypto"),sm=Ic(),Dr=sm.version,Mc=["\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 nm(){return Mc[Math.floor(Math.random()*Mc.length)]}function Nt(s){return typeof s=="string"?!["false","0","no","off",""].includes(s.toLowerCase()):!!s}function rm(){return process.stdout.isTTY}function im(s){return rm()?`\x1B[2m${s}\x1B[0m`:s}var om=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function am(s){let e={},t=s.toString();t=t.replace(/\r\n?/mg,`
|
|
26
26
|
`);let i;for(;(i=om.exec(t))!=null;){let a=i[1],c=i[2]||"";c=c.trim();let h=c[0];c=c.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),h==='"'&&(c=c.replace(/\\n/g,`
|
|
27
|
-
`),c=c.replace(/\\r/g,"\r")),e[a]=c}return e}function cm(s){s=s||{};let e=Dc(s);s.path=e;let t=ue.configDotenv(s);if(!t.parsed){let h=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw h.code="MISSING_DATA",h}let i=Lc(s).split(","),a=i.length,c;for(let h=0;h<a;h++)try{let p=i[h].trim(),g=um(t,p);c=ue.decrypt(g.ciphertext,g.key);break}catch(p){if(h+1>=a)throw p}return ue.parse(c)}function lm(s){console.error(`[dotenv@${Dr}][WARN] ${s}`)}function hs(s){console.log(`[dotenv@${Dr}][DEBUG] ${s}`)}function Nc(s){console.log(`[dotenv@${Dr}] ${s}`)}function Lc(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 um(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()}`,h=s.parsed[c];if(!h){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:h,key:i}}function Dc(s){let e=null;if(s&&s.path&&s.path.length>0)if(Array.isArray(s.path))for(let t of s.path)Lr.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=s.path.endsWith(".vault")?s.path:`${s.path}.vault`;else e=Ks.resolve(process.cwd(),".env.vault");return Lr.existsSync(e)?e:null}function xc(s){return s[0]==="~"?Ks.join(em.homedir(),s.slice(1)):s}function hm(s){let e=xt(process.env.DOTENV_CONFIG_DEBUG||s&&s.debug),t=xt(process.env.DOTENV_CONFIG_QUIET||s&&s.quiet);(e||!t)&&Nc("Loading env from encrypted .env.vault");let i=ue._parseVault(s),a=process.env;return s&&s.processEnv!=null&&(a=s.processEnv),ue.populate(a,i,s),{parsed:i}}function dm(s){let e=Ks.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&&hs("No encoding is specified. UTF-8 is used by default");let h=[e];if(s&&s.path)if(!Array.isArray(s.path))h=[xc(s.path)];else{h=[];for(let v of s.path)h.push(xc(v))}let p,g={};for(let v of h)try{let w=ue.parse(Lr.readFileSync(v,{encoding:t}));ue.populate(g,w,s)}catch(w){a&&hs(`Failed to load ${v} ${w.message}`),p=w}let m=ue.populate(i,g,s);if(a=xt(i.DOTENV_CONFIG_DEBUG||a),c=xt(i.DOTENV_CONFIG_QUIET||c),a||!c){let v=Object.keys(m).length,w=[];for(let E of h)try{let O=Ks.relative(process.cwd(),E);w.push(O)}catch(O){a&&hs(`Failed to load ${E} ${O.message}`),p=O}Nc(`injecting env (${v}) from ${w.join(",")} ${im(`-- tip: ${nm()}`)}`)}return p?{parsed:g,error:p}:{parsed:g}}function fm(s){if(Lc(s).length===0)return ue.configDotenv(s);let e=Dc(s);return e?ue._configVault(s):(lm(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),ue.configDotenv(s))}function pm(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 h=tm.createDecipheriv("aes-256-gcm",t,a);return h.setAuthTag(c),`${h.update(i)}${h.final()}`}catch(h){let p=h instanceof RangeError,g=h.message==="Invalid key length",m=h.message==="Unsupported state or unable to authenticate data";if(p||g){let v=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw v.code="INVALID_DOTENV_KEY",v}else if(m){let v=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw v.code="DECRYPTION_FAILED",v}else throw h}}function gm(s,e,t={}){let i=!!(t&&t.debug),a=!!(t&&t.override),c={};if(typeof e!="object"){let h=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw h.code="OBJECT_REQUIRED",h}for(let h of Object.keys(e))Object.prototype.hasOwnProperty.call(s,h)?(a===!0&&(s[h]=e[h],c[h]=e[h]),i&&hs(a===!0?`"${h}" is already defined and WAS overwritten`:`"${h}" is already defined and was NOT overwritten`)):(s[h]=e[h],c[h]=e[h]);return c}var ue={configDotenv:dm,_configVault:hm,_parseVault:cm,config:fm,decrypt:pm,parse:am,populate:gm};Je.exports.configDotenv=ue.configDotenv;Je.exports._configVault=ue._configVault;Je.exports._parseVault=ue._parseVault;Je.exports.config=ue.config;Je.exports.decrypt=ue.decrypt;Je.exports.parse=ue.parse;Je.exports.populate=ue.populate;Je.exports=ue});var Ye=$((iC,sl)=>{"use strict";var el=["nodebuffer","arraybuffer","fragments"],tl=typeof Blob<"u";tl&&el.push("blob");sl.exports={BINARY_TYPES:el,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:tl,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ds=$((oC,Xs)=>{"use strict";var{EMPTY_BUFFER:Mm}=Ye(),Br=Buffer[Symbol.species];function xm(s,e){if(s.length===0)return Mm;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 Br(t.buffer,t.byteOffset,i):t}function nl(s,e,t,i,a){for(let c=0;c<a;c++)t[i+c]=s[c]^e[c&3]}function rl(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}function Nm(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}function $r(s){if($r.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new Br(s):ArrayBuffer.isView(s)?e=new Br(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),$r.readOnly=!1),e}Xs.exports={concat:xm,mask:nl,toArrayBuffer:Nm,toBuffer:$r,unmask:rl};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=q("bufferutil");Xs.exports.mask=function(e,t,i,a,c){c<48?nl(e,t,i,a,c):s.mask(e,t,i,a,c)},Xs.exports.unmask=function(e,t){e.length<32?rl(e,t):s.unmask(e,t)}}catch{}});var al=$((aC,ol)=>{"use strict";var il=Symbol("kDone"),Hr=Symbol("kRun"),Gr=class{constructor(e){this[il]=()=>{this.pending--,this[Hr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Hr]()}[Hr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[il])}}};ol.exports=Gr});var ps=$((cC,hl)=>{"use strict";var fs=q("zlib"),cl=ds(),Lm=al(),{kStatusCode:ll}=Ye(),Dm=Buffer[Symbol.species],Um=Buffer.from([0,0,255,255]),en=Symbol("permessage-deflate"),Qe=Symbol("total-length"),Nt=Symbol("callback"),lt=Symbol("buffers"),Lt=Symbol("error"),Zs,Fr=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,!Zs){let a=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Zs=new Lm(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[Nt];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){Zs.add(a=>{this._decompress(e,t,(c,h)=>{a(),i(c,h)})})}compress(e,t,i){Zs.add(a=>{this._compress(e,t,(c,h)=>{a(),i(c,h)})})}_decompress(e,t,i){let a=this._isServer?"client":"server";if(!this._inflate){let c=`${a}_max_window_bits`,h=typeof this.params[c]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=fs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:h}),this._inflate[en]=this,this._inflate[Qe]=0,this._inflate[lt]=[],this._inflate.on("error",qm),this._inflate.on("data",ul)}this._inflate[Nt]=i,this._inflate.write(e),t&&this._inflate.write(Um),this._inflate.flush(()=>{let c=this._inflate[Lt];if(c){this._inflate.close(),this._inflate=null,i(c);return}let h=cl.concat(this._inflate[lt],this._inflate[Qe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Qe]=0,this._inflate[lt]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,h)})}_compress(e,t,i){let a=this._isServer?"server":"client";if(!this._deflate){let c=`${a}_max_window_bits`,h=typeof this.params[c]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=fs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:h}),this._deflate[Qe]=0,this._deflate[lt]=[],this._deflate.on("data",jm)}this._deflate[Nt]=i,this._deflate.write(e),this._deflate.flush(fs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=cl.concat(this._deflate[lt],this._deflate[Qe]);t&&(c=new Dm(c.buffer,c.byteOffset,c.length-4)),this._deflate[Nt]=null,this._deflate[Qe]=0,this._deflate[lt]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};hl.exports=Fr;function jm(s){this[lt].push(s),this[Qe]+=s.length}function ul(s){if(this[Qe]+=s.length,this[en]._maxPayload<1||this[Qe]<=this[en]._maxPayload){this[lt].push(s);return}this[Lt]=new RangeError("Max payload size exceeded"),this[Lt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Lt][ll]=1009,this.removeListener("data",ul),this.reset()}function qm(s){if(this[en]._inflate=null,this[Lt]){this[Nt](this[Lt]);return}s[ll]=1007,this[Nt](s)}});var Dt=$((lC,tn)=>{"use strict";var{isUtf8:dl}=q("buffer"),{hasBlob:Bm}=Ye(),$m=[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 Hm(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}function Wr(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 Gm(s){return Bm&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}tn.exports={isBlob:Gm,isValidStatusCode:Hm,isValidUTF8:Wr,tokenChars:$m};if(dl)tn.exports.isValidUTF8=function(s){return s.length<24?Wr(s):dl(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=q("utf-8-validate");tn.exports.isValidUTF8=function(e){return e.length<32?Wr(e):s(e)}}catch{}});var Yr=$((uC,bl)=>{"use strict";var{Writable:Fm}=q("stream"),fl=ps(),{BINARY_TYPES:Wm,EMPTY_BUFFER:pl,kStatusCode:Vm,kWebSocket:zm}=Ye(),{concat:Vr,toArrayBuffer:Km,unmask:Jm}=ds(),{isValidStatusCode:Ym,isValidUTF8:gl}=Dt(),sn=Buffer[Symbol.species],Ie=0,ml=1,yl=2,_l=3,zr=4,Kr=5,nn=6,Jr=class extends Fm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Wm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[zm]=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=Ie}_write(e,t,i){if(this._opcode===8&&this._state==Ie)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 sn(i.buffer,i.byteOffset+e,i.length-e),new sn(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 sn(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 Ie:this.getInfo(e);break;case ml:this.getPayloadLength16(e);break;case yl:this.getPayloadLength64(e);break;case _l:this.getMask();break;case zr:this.getData(e);break;case Kr:case nn: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[fl.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=ml:this._payloadLength===127?this._state=yl: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=_l:this._state=zr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=zr}getData(e){let t=pl;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]&&Jm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Kr,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[fl.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 h=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(h);return}this._fragments.push(c)}this.dataMessage(t),this._state===Ie&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ie;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=Vr(i,t):this._binaryType==="arraybuffer"?a=Km(Vr(i,t)):this._binaryType==="blob"?a=new Blob(i):a=i,this._allowSynchronousEvents?(this.emit("message",a,!0),this._state=Ie):(this._state=nn,setImmediate(()=>{this.emit("message",a,!0),this._state=Ie,this.startLoop(e)}))}else{let a=Vr(i,t);if(!this._skipUTF8Validation&&!gl(a)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Kr||this._allowSynchronousEvents?(this.emit("message",a,!1),this._state=Ie):(this._state=nn,setImmediate(()=>{this.emit("message",a,!1),this._state=Ie,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,pl),this.end();else{let i=e.readUInt16BE(0);if(!Ym(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(c);return}let a=new sn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!gl(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=Ie;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ie):(this._state=nn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ie,this.startLoop(t)}))}createError(e,t,i,a,c){this._loop=!1,this._errored=!0;let h=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(h,this.createError),h.code=c,h[Vm]=a,h}};bl.exports=Jr});var Zr=$((dC,Cl)=>{"use strict";var{Duplex:hC}=q("stream"),{randomFillSync:Qm}=q("crypto"),vl=ps(),{EMPTY_BUFFER:Xm,kWebSocket:Zm,NOOP:ey}=Ye(),{isBlob:Ut,isValidStatusCode:ty}=Dt(),{mask:wl,toBuffer:_t}=ds(),Me=Symbol("kByteLength"),sy=Buffer.alloc(4),rn=8*1024,bt,jt=rn,qe=0,ny=1,ry=2,Qr=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=qe,this.onerror=ey,this[Zm]=void 0}static frame(e,t){let i,a=!1,c=2,h=!1;t.mask&&(i=t.maskBuffer||sy,t.generateMask?t.generateMask(i):(jt===rn&&(bt===void 0&&(bt=Buffer.alloc(rn)),Qm(bt,0,rn),jt=0),i[0]=bt[jt++],i[1]=bt[jt++],i[2]=bt[jt++],i[3]=bt[jt++]),h=(i[0]|i[1]|i[2]|i[3])===0,c=6);let p;typeof e=="string"?(!t.mask||h)&&t[Me]!==void 0?p=t[Me]:(e=Buffer.from(e),p=e.length):(p=e.length,a=t.mask&&t.readOnly&&!h);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],h?[m,e]:a?(wl(e,i,m,c,p),[m]):(wl(e,i,e,0,p),[m,e])):[m,e]}close(e,t,i,a){let c;if(e===void 0)c=Xm;else{if(typeof e!="number"||!ty(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 h={[Me]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==qe?this.enqueue([this.dispatch,c,!1,h,a]):this.sendFrame(s.frame(c,h),a)}ping(e,t,i){let a,c;if(typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Ut(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 h={[Me]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Ut(e)?this._state!==qe?this.enqueue([this.getBlobData,e,!1,h,i]):this.getBlobData(e,!1,h,i):this._state!==qe?this.enqueue([this.dispatch,e,!1,h,i]):this.sendFrame(s.frame(e,h),i)}pong(e,t,i){let a,c;if(typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Ut(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 h={[Me]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Ut(e)?this._state!==qe?this.enqueue([this.getBlobData,e,!1,h,i]):this.getBlobData(e,!1,h,i):this._state!==qe?this.enqueue([this.dispatch,e,!1,h,i]):this.sendFrame(s.frame(e,h),i)}send(e,t,i){let a=this._extensions[vl.extensionName],c=t.binary?2:1,h=t.compress,p,g;typeof e=="string"?(p=Buffer.byteLength(e),g=!1):Ut(e)?(p=e.size,g=!1):(e=_t(e),p=e.length,g=_t.readOnly),this._firstFragment?(this._firstFragment=!1,h&&a&&a.params[a._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(h=p>=a._threshold),this._compress=h):(h=!1,c=0),t.fin&&(this._firstFragment=!0);let m={[Me]:p,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:g,rsv1:h};Ut(e)?this._state!==qe?this.enqueue([this.getBlobData,e,this._compress,m,i]):this.getBlobData(e,this._compress,m,i):this._state!==qe?this.enqueue([this.dispatch,e,this._compress,m,i]):this.dispatch(e,this._compress,m,i)}getBlobData(e,t,i,a){this._bufferedBytes+=i[Me],this._state=ry,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let p=new Error("The socket was closed while the blob was being read");process.nextTick(Xr,this,p,a);return}this._bufferedBytes-=i[Me];let h=_t(c);t?this.dispatch(h,t,i,a):(this._state=qe,this.sendFrame(s.frame(h,i),a),this.dequeue())}).catch(c=>{process.nextTick(iy,this,c,a)})}dispatch(e,t,i,a){if(!t){this.sendFrame(s.frame(e,i),a);return}let c=this._extensions[vl.extensionName];this._bufferedBytes+=i[Me],this._state=ny,c.compress(e,i.fin,(h,p)=>{if(this._socket.destroyed){let g=new Error("The socket was closed while data was being compressed");Xr(this,g,a);return}this._bufferedBytes-=i[Me],this._state=qe,i.readOnly=!1,this.sendFrame(s.frame(p,i),a),this.dequeue()})}dequeue(){for(;this._state===qe&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],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)}};Cl.exports=Qr;function Xr(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 iy(s,e,t){Xr(s,e,t),s.onerror(e)}});var Il=$((fC,Pl)=>{"use strict";var{kForOnEventAttribute:gs,kListener:ei}=Ye(),El=Symbol("kCode"),kl=Symbol("kData"),Ol=Symbol("kError"),Sl=Symbol("kMessage"),Tl=Symbol("kReason"),qt=Symbol("kTarget"),Al=Symbol("kType"),Rl=Symbol("kWasClean"),Xe=class{constructor(e){this[qt]=null,this[Al]=e}get target(){return this[qt]}get type(){return this[Al]}};Object.defineProperty(Xe.prototype,"target",{enumerable:!0});Object.defineProperty(Xe.prototype,"type",{enumerable:!0});var vt=class extends Xe{constructor(e,t={}){super(e),this[El]=t.code===void 0?0:t.code,this[Tl]=t.reason===void 0?"":t.reason,this[Rl]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[El]}get reason(){return this[Tl]}get wasClean(){return this[Rl]}};Object.defineProperty(vt.prototype,"code",{enumerable:!0});Object.defineProperty(vt.prototype,"reason",{enumerable:!0});Object.defineProperty(vt.prototype,"wasClean",{enumerable:!0});var Bt=class extends Xe{constructor(e,t={}){super(e),this[Ol]=t.error===void 0?null:t.error,this[Sl]=t.message===void 0?"":t.message}get error(){return this[Ol]}get message(){return this[Sl]}};Object.defineProperty(Bt.prototype,"error",{enumerable:!0});Object.defineProperty(Bt.prototype,"message",{enumerable:!0});var ms=class extends Xe{constructor(e,t={}){super(e),this[kl]=t.data===void 0?null:t.data}get data(){return this[kl]}};Object.defineProperty(ms.prototype,"data",{enumerable:!0});var oy={addEventListener(s,e,t={}){for(let a of this.listeners(s))if(!t[gs]&&a[ei]===e&&!a[gs])return;let i;if(s==="message")i=function(c,h){let p=new ms("message",{data:h?c:c.toString()});p[qt]=this,on(e,this,p)};else if(s==="close")i=function(c,h){let p=new vt("close",{code:c,reason:h.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});p[qt]=this,on(e,this,p)};else if(s==="error")i=function(c){let h=new Bt("error",{error:c,message:c.message});h[qt]=this,on(e,this,h)};else if(s==="open")i=function(){let c=new Xe("open");c[qt]=this,on(e,this,c)};else return;i[gs]=!!t[gs],i[ei]=e,t.once?this.once(s,i):this.on(s,i)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[ei]===e&&!t[gs]){this.removeListener(s,t);break}}};Pl.exports={CloseEvent:vt,ErrorEvent:Bt,Event:Xe,EventTarget:oy,MessageEvent:ms};function on(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}});var ti=$((pC,Ml)=>{"use strict";var{tokenChars:ys}=Dt();function He(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}function ay(s){let e=Object.create(null),t=Object.create(null),i=!1,a=!1,c=!1,h,p,g=-1,m=-1,v=-1,w=0;for(;w<s.length;w++)if(m=s.charCodeAt(w),h===void 0)if(v===-1&&ys[m]===1)g===-1&&(g=w);else if(w!==0&&(m===32||m===9))v===-1&&g!==-1&&(v=w);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${w}`);v===-1&&(v=w);let O=s.slice(g,v);m===44?(He(e,O,t),t=Object.create(null)):h=O,g=v=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(p===void 0)if(v===-1&&ys[m]===1)g===-1&&(g=w);else if(m===32||m===9)v===-1&&g!==-1&&(v=w);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${w}`);v===-1&&(v=w),He(t,s.slice(g,v),!0),m===44&&(He(e,h,t),t=Object.create(null),h=void 0),g=v=-1}else if(m===61&&g!==-1&&v===-1)p=s.slice(g,w),g=v=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(a){if(ys[m]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1?g=w:i||(i=!0),a=!1}else if(c)if(ys[m]===1)g===-1&&(g=w);else if(m===34&&g!==-1)c=!1,v=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(v===-1&&ys[m]===1)g===-1&&(g=w);else if(g!==-1&&(m===32||m===9))v===-1&&(v=w);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${w}`);v===-1&&(v=w);let O=s.slice(g,v);i&&(O=O.replace(/\\/g,""),i=!1),He(t,p,O),m===44&&(He(e,h,t),t=Object.create(null),h=void 0),p=void 0,g=v=-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");v===-1&&(v=w);let E=s.slice(g,v);return h===void 0?He(e,E,t):(p===void 0?He(t,E,!0):i?He(t,p,E.replace(/\\/g,"")):He(t,p,E),He(e,h,t)),e}function cy(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(h=>h===!0?a:`${a}=${h}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ml.exports={format:cy,parse:ay}});var un=$((yC,Fl)=>{"use strict";var ly=q("events"),uy=q("https"),hy=q("http"),Ll=q("net"),dy=q("tls"),{randomBytes:fy,createHash:py}=q("crypto"),{Duplex:gC,Readable:mC}=q("stream"),{URL:si}=q("url"),ut=ps(),gy=Yr(),my=Zr(),{isBlob:yy}=Dt(),{BINARY_TYPES:xl,CLOSE_TIMEOUT:_y,EMPTY_BUFFER:an,GUID:by,kForOnEventAttribute:ni,kListener:vy,kStatusCode:wy,kWebSocket:fe,NOOP:Dl}=Ye(),{EventTarget:{addEventListener:Cy,removeEventListener:Ey}}=Il(),{format:ky,parse:Oy}=ti(),{toBuffer:Sy}=ds(),Ul=Symbol("kAborted"),ri=[8,13],Ze=["CONNECTING","OPEN","CLOSING","CLOSED"],Ty=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ie=class s extends ly{constructor(e,t,i){super(),this._binaryType=xl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=an,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]),jl(this,e,t,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){xl.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 gy({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new my(e,this._extensions,i.generateMask);this._receiver=a,this._sender=c,this._socket=e,a[fe]=this,c[fe]=this,e[fe]=this,a.on("conclude",Py),a.on("drain",Iy),a.on("error",My),a.on("message",xy),a.on("ping",Ny),a.on("pong",Ly),c.onerror=Dy,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",$l),e.on("data",ln),e.on("end",Hl),e.on("error",Gl),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[ut.extensionName]&&this._extensions[ut.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())}),Bl(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){ii(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||an,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){ii(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||an,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){ii(this,e,i);return}let a={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ut.extensionName]||(a.compress=!1),this._sender.send(e||an,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:Ze.indexOf("CONNECTING")});Object.defineProperty(ie.prototype,"CONNECTING",{enumerable:!0,value:Ze.indexOf("CONNECTING")});Object.defineProperty(ie,"OPEN",{enumerable:!0,value:Ze.indexOf("OPEN")});Object.defineProperty(ie.prototype,"OPEN",{enumerable:!0,value:Ze.indexOf("OPEN")});Object.defineProperty(ie,"CLOSING",{enumerable:!0,value:Ze.indexOf("CLOSING")});Object.defineProperty(ie.prototype,"CLOSING",{enumerable:!0,value:Ze.indexOf("CLOSING")});Object.defineProperty(ie,"CLOSED",{enumerable:!0,value:Ze.indexOf("CLOSED")});Object.defineProperty(ie.prototype,"CLOSED",{enumerable:!0,value:Ze.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[ni])return e[vy];return null},set(e){for(let t of this.listeners(s))if(t[ni]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[ni]:!0})}})});ie.prototype.addEventListener=Cy;ie.prototype.removeEventListener=Ey;Fl.exports=ie;function jl(s,e,t,i){let a={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_y,protocolVersion:ri[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,!ri.includes(a.protocolVersion))throw new RangeError(`Unsupported protocol version: ${a.protocolVersion} (supported versions: ${ri.join(", ")})`);let c;if(e instanceof si)c=e;else try{c=new si(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 h=c.protocol==="wss:",p=c.protocol==="ws+unix:",g;if(c.protocol!=="ws:"&&!h&&!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 k=new SyntaxError(g);if(s._redirects===0)throw k;cn(s,k);return}let m=h?443:80,v=fy(16).toString("base64"),w=h?uy.request:hy.request,E=new Set,O;if(a.createConnection=a.createConnection||(h?Ry:Ay),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":v,Connection:"Upgrade",Upgrade:"websocket"},a.path=c.pathname+c.search,a.timeout=a.handshakeTimeout,a.perMessageDeflate&&(O=new ut(a.perMessageDeflate!==!0?a.perMessageDeflate:{},!1,a.maxPayload),a.headers["Sec-WebSocket-Extensions"]=ky({[ut.extensionName]:O.offer()})),t.length){for(let k of t){if(typeof k!="string"||!Ty.test(k)||E.has(k))throw new SyntaxError("An invalid or duplicated subprotocol was specified");E.add(k)}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 k=a.path.split(":");a.socketPath=k[0],a.path=k[1]}let A;if(a.followRedirects){if(s._redirects===0){s._originalIpc=p,s._originalSecure=h,s._originalHostOrSocketPath=p?a.socketPath:c.host;let k=i&&i.headers;if(i={...i,headers:{}},k)for(let[T,N]of Object.entries(k))i.headers[T.toLowerCase()]=N}else if(s.listenerCount("redirect")===0){let k=p?s._originalIpc?a.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:c.host===s._originalHostOrSocketPath;(!k||s._originalSecure&&!h)&&(delete a.headers.authorization,delete a.headers.cookie,k||delete a.headers.host,a.auth=void 0)}a.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(a.auth).toString("base64")),A=s._req=w(a),s._redirects&&s.emit("redirect",s.url,A)}else A=s._req=w(a);a.timeout&&A.on("timeout",()=>{Ae(s,A,"Opening handshake has timed out")}),A.on("error",k=>{A===null||A[Ul]||(A=s._req=null,cn(s,k))}),A.on("response",k=>{let T=k.headers.location,N=k.statusCode;if(T&&a.followRedirects&&N>=300&&N<400){if(++s._redirects>a.maxRedirects){Ae(s,A,"Maximum redirects exceeded");return}A.abort();let H;try{H=new si(T,e)}catch{let Z=new SyntaxError(`Invalid URL: ${T}`);cn(s,Z);return}jl(s,H,t,i)}else s.emit("unexpected-response",A,k)||Ae(s,A,`Unexpected server response: ${k.statusCode}`)}),A.on("upgrade",(k,T,N)=>{if(s.emit("upgrade",k),s.readyState!==ie.CONNECTING)return;A=s._req=null;let H=k.headers.upgrade;if(H===void 0||H.toLowerCase()!=="websocket"){Ae(s,T,"Invalid Upgrade header");return}let V=py("sha1").update(v+by).digest("base64");if(k.headers["sec-websocket-accept"]!==V){Ae(s,T,"Invalid Sec-WebSocket-Accept header");return}let Z=k.headers["sec-websocket-protocol"],Q;if(Z!==void 0?E.size?E.has(Z)||(Q="Server sent an invalid subprotocol"):Q="Server sent a subprotocol but none was requested":E.size&&(Q="Server sent no subprotocol"),Q){Ae(s,T,Q);return}Z&&(s._protocol=Z);let te=k.headers["sec-websocket-extensions"];if(te!==void 0){if(!O){Ae(s,T,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ge;try{ge=Oy(te)}catch{Ae(s,T,"Invalid Sec-WebSocket-Extensions header");return}let ot=Object.keys(ge);if(ot.length!==1||ot[0]!==ut.extensionName){Ae(s,T,"Server indicated an extension that was not requested");return}try{O.accept(ge[ut.extensionName])}catch{Ae(s,T,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[ut.extensionName]=O}s.setSocket(T,N,{allowSynchronousEvents:a.allowSynchronousEvents,generateMask:a.generateMask,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation})}),a.finishRequest?a.finishRequest(A,s):A.end()}function cn(s,e){s._readyState=ie.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}function Ay(s){return s.path=s.socketPath,Ll.connect(s)}function Ry(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=Ll.isIP(s.host)?"":s.host),dy.connect(s)}function Ae(s,e,t){s._readyState=ie.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Ae),e.setHeader?(e[Ul]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(cn,s,i)):(e.destroy(i),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}function ii(s,e,t){if(e){let i=yy(e)?e.size:Sy(e).length;s._socket?s._sender._bufferedBytes+=i:s._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${s.readyState} (${Ze[s.readyState]})`);process.nextTick(t,i)}}function Py(s,e){let t=this[fe];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[fe]!==void 0&&(t._socket.removeListener("data",ln),process.nextTick(ql,t._socket),s===1005?t.close():t.close(s,e))}function Iy(){let s=this[fe];s.isPaused||s._socket.resume()}function My(s){let e=this[fe];e._socket[fe]!==void 0&&(e._socket.removeListener("data",ln),process.nextTick(ql,e._socket),e.close(s[wy])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}function Nl(){this[fe].emitClose()}function xy(s,e){this[fe].emit("message",s,e)}function Ny(s){let e=this[fe];e._autoPong&&e.pong(s,!this._isServer,Dl),e.emit("ping",s)}function Ly(s){this[fe].emit("pong",s)}function ql(s){s.resume()}function Dy(s){let e=this[fe];e.readyState!==ie.CLOSED&&(e.readyState===ie.OPEN&&(e._readyState=ie.CLOSING,Bl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}function Bl(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}function $l(){let s=this[fe];if(this.removeListener("close",$l),this.removeListener("data",ln),this.removeListener("end",Hl),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[fe]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",Nl),s._receiver.on("finish",Nl))}function ln(s){this[fe]._receiver.write(s)||this.pause()}function Hl(){let s=this[fe];s._readyState=ie.CLOSING,s._receiver.end(),this.end()}function Gl(){let s=this[fe];this.removeListener("error",Gl),this.on("error",Dl),s&&(s._readyState=ie.CLOSING,this.destroy())}});var Kl=$((bC,zl)=>{"use strict";var _C=un(),{Duplex:Uy}=q("stream");function Wl(s){s.emit("close")}function jy(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vl(s){this.removeListener("error",Vl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}function qy(s,e){let t=!0,i=new Uy({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return s.on("message",function(c,h){let p=!h&&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(Wl,i);return}let h=!1;s.once("error",function(g){h=!0,c(g)}),s.once("close",function(){h||c(a),process.nextTick(Wl,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,h){if(s.readyState===s.CONNECTING){s.once("open",function(){i._write(a,c,h)});return}s.send(a,h)},i.on("end",jy),i.on("error",Vl),i}zl.exports=qy});var Yl=$((vC,Jl)=>{"use strict";var{tokenChars:By}=Dt();function $y(s){let e=new Set,t=-1,i=-1,a=0;for(a;a<s.length;a++){let h=s.charCodeAt(a);if(i===-1&&By[h]===1)t===-1&&(t=a);else if(a!==0&&(h===32||h===9))i===-1&&t!==-1&&(i=a);else if(h===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}Jl.exports={parse:$y}});var nu=$((CC,su)=>{"use strict";var Hy=q("events"),hn=q("http"),{Duplex:wC}=q("stream"),{createHash:Gy}=q("crypto"),Ql=ti(),wt=ps(),Fy=Yl(),Wy=un(),{CLOSE_TIMEOUT:Vy,GUID:zy,kWebSocket:Ky}=Ye(),Jy=/^[+/0-9A-Za-z]{22}==$/,Xl=0,Zl=1,tu=2,oi=class extends Hy{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Vy,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wy,...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=hn.createServer((i,a)=>{let c=hn.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=Yy(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(a,c,h)=>{this.handleUpgrade(a,c,h,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Xl}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===tu){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(_s,this);return}if(e&&this.once("close",e),this._state!==Zl)if(this._state=Zl,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(_s,this):process.nextTick(_s,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{_s(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",eu);let c=e.headers["sec-websocket-key"],h=e.headers.upgrade,p=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ct(this,e,t,405,"Invalid HTTP method");return}if(h===void 0||h.toLowerCase()!=="websocket"){Ct(this,e,t,400,"Invalid Upgrade header");return}if(c===void 0||!Jy.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)){bs(t,400);return}let g=e.headers["sec-websocket-protocol"],m=new Set;if(g!==void 0)try{m=Fy.parse(g)}catch{Ct(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let v=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&v!==void 0){let E=new wt(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let O=Ql.parse(v);O[wt.extensionName]&&(E.accept(O[wt.extensionName]),w[wt.extensionName]=E)}catch{Ct(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let E={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(E,(O,A,k,T)=>{if(!O)return bs(t,A||401,k,T);this.completeUpgrade(w,c,m,e,t,i,a)});return}if(!this.options.verifyClient(E))return bs(t,401)}this.completeUpgrade(w,c,m,e,t,i,a)}completeUpgrade(e,t,i,a,c,h,p){if(!c.readable||!c.writable)return c.destroy();if(c[Ky])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Xl)return bs(c,503);let m=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Gy("sha1").update(t+zy).digest("base64")}`],v=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}`),v._protocol=w)}if(e[wt.extensionName]){let w=e[wt.extensionName].params,E=Ql.format({[wt.extensionName]:[w]});m.push(`Sec-WebSocket-Extensions: ${E}`),v._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 cm(s){s=s||{};let e=Dc(s);s.path=e;let t=fe.configDotenv(s);if(!t.parsed){let h=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw h.code="MISSING_DATA",h}let i=Lc(s).split(","),a=i.length,c;for(let h=0;h<a;h++)try{let p=i[h].trim(),g=um(t,p);c=fe.decrypt(g.ciphertext,g.key);break}catch(p){if(h+1>=a)throw p}return fe.parse(c)}function lm(s){console.error(`[dotenv@${Dr}][WARN] ${s}`)}function ds(s){console.log(`[dotenv@${Dr}][DEBUG] ${s}`)}function Nc(s){console.log(`[dotenv@${Dr}] ${s}`)}function Lc(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 um(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()}`,h=s.parsed[c];if(!h){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:h,key:i}}function Dc(s){let e=null;if(s&&s.path&&s.path.length>0)if(Array.isArray(s.path))for(let t of s.path)Lr.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=s.path.endsWith(".vault")?s.path:`${s.path}.vault`;else e=Js.resolve(process.cwd(),".env.vault");return Lr.existsSync(e)?e:null}function xc(s){return s[0]==="~"?Js.join(em.homedir(),s.slice(1)):s}function hm(s){let e=Nt(process.env.DOTENV_CONFIG_DEBUG||s&&s.debug),t=Nt(process.env.DOTENV_CONFIG_QUIET||s&&s.quiet);(e||!t)&&Nc("Loading env from encrypted .env.vault");let i=fe._parseVault(s),a=process.env;return s&&s.processEnv!=null&&(a=s.processEnv),fe.populate(a,i,s),{parsed:i}}function dm(s){let e=Js.resolve(process.cwd(),".env"),t="utf8",i=process.env;s&&s.processEnv!=null&&(i=s.processEnv);let a=Nt(i.DOTENV_CONFIG_DEBUG||s&&s.debug),c=Nt(i.DOTENV_CONFIG_QUIET||s&&s.quiet);s&&s.encoding?t=s.encoding:a&&ds("No encoding is specified. UTF-8 is used by default");let h=[e];if(s&&s.path)if(!Array.isArray(s.path))h=[xc(s.path)];else{h=[];for(let v of s.path)h.push(xc(v))}let p,g={};for(let v of h)try{let w=fe.parse(Lr.readFileSync(v,{encoding:t}));fe.populate(g,w,s)}catch(w){a&&ds(`Failed to load ${v} ${w.message}`),p=w}let m=fe.populate(i,g,s);if(a=Nt(i.DOTENV_CONFIG_DEBUG||a),c=Nt(i.DOTENV_CONFIG_QUIET||c),a||!c){let v=Object.keys(m).length,w=[];for(let E of h)try{let O=Js.relative(process.cwd(),E);w.push(O)}catch(O){a&&ds(`Failed to load ${E} ${O.message}`),p=O}Nc(`injecting env (${v}) from ${w.join(",")} ${im(`-- tip: ${nm()}`)}`)}return p?{parsed:g,error:p}:{parsed:g}}function fm(s){if(Lc(s).length===0)return fe.configDotenv(s);let e=Dc(s);return e?fe._configVault(s):(lm(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),fe.configDotenv(s))}function pm(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 h=tm.createDecipheriv("aes-256-gcm",t,a);return h.setAuthTag(c),`${h.update(i)}${h.final()}`}catch(h){let p=h instanceof RangeError,g=h.message==="Invalid key length",m=h.message==="Unsupported state or unable to authenticate data";if(p||g){let v=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw v.code="INVALID_DOTENV_KEY",v}else if(m){let v=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw v.code="DECRYPTION_FAILED",v}else throw h}}function gm(s,e,t={}){let i=!!(t&&t.debug),a=!!(t&&t.override),c={};if(typeof e!="object"){let h=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw h.code="OBJECT_REQUIRED",h}for(let h of Object.keys(e))Object.prototype.hasOwnProperty.call(s,h)?(a===!0&&(s[h]=e[h],c[h]=e[h]),i&&ds(a===!0?`"${h}" is already defined and WAS overwritten`:`"${h}" is already defined and was NOT overwritten`)):(s[h]=e[h],c[h]=e[h]);return c}var fe={configDotenv:dm,_configVault:hm,_parseVault:cm,config:fm,decrypt:pm,parse:am,populate:gm};Xe.exports.configDotenv=fe.configDotenv;Xe.exports._configVault=fe._configVault;Xe.exports._parseVault=fe._parseVault;Xe.exports.config=fe.config;Xe.exports.decrypt=fe.decrypt;Xe.exports.parse=fe.parse;Xe.exports.populate=fe.populate;Xe.exports=fe});var Ze=$((iC,sl)=>{"use strict";var el=["nodebuffer","arraybuffer","fragments"],tl=typeof Blob<"u";tl&&el.push("blob");sl.exports={BINARY_TYPES:el,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:tl,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var fs=$((oC,Zs)=>{"use strict";var{EMPTY_BUFFER:Mm}=Ze(),Br=Buffer[Symbol.species];function xm(s,e){if(s.length===0)return Mm;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 Br(t.buffer,t.byteOffset,i):t}function nl(s,e,t,i,a){for(let c=0;c<a;c++)t[i+c]=s[c]^e[c&3]}function rl(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}function Nm(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}function $r(s){if($r.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new Br(s):ArrayBuffer.isView(s)?e=new Br(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),$r.readOnly=!1),e}Zs.exports={concat:xm,mask:nl,toArrayBuffer:Nm,toBuffer:$r,unmask:rl};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=q("bufferutil");Zs.exports.mask=function(e,t,i,a,c){c<48?nl(e,t,i,a,c):s.mask(e,t,i,a,c)},Zs.exports.unmask=function(e,t){e.length<32?rl(e,t):s.unmask(e,t)}}catch{}});var al=$((aC,ol)=>{"use strict";var il=Symbol("kDone"),Hr=Symbol("kRun"),Gr=class{constructor(e){this[il]=()=>{this.pending--,this[Hr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Hr]()}[Hr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[il])}}};ol.exports=Gr});var gs=$((cC,hl)=>{"use strict";var ps=q("zlib"),cl=fs(),Lm=al(),{kStatusCode:ll}=Ze(),Dm=Buffer[Symbol.species],Um=Buffer.from([0,0,255,255]),tn=Symbol("permessage-deflate"),et=Symbol("total-length"),Lt=Symbol("callback"),ht=Symbol("buffers"),Dt=Symbol("error"),en,Fr=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,!en){let a=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;en=new Lm(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[Lt];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){en.add(a=>{this._decompress(e,t,(c,h)=>{a(),i(c,h)})})}compress(e,t,i){en.add(a=>{this._compress(e,t,(c,h)=>{a(),i(c,h)})})}_decompress(e,t,i){let a=this._isServer?"client":"server";if(!this._inflate){let c=`${a}_max_window_bits`,h=typeof this.params[c]!="number"?ps.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=ps.createInflateRaw({...this._options.zlibInflateOptions,windowBits:h}),this._inflate[tn]=this,this._inflate[et]=0,this._inflate[ht]=[],this._inflate.on("error",qm),this._inflate.on("data",ul)}this._inflate[Lt]=i,this._inflate.write(e),t&&this._inflate.write(Um),this._inflate.flush(()=>{let c=this._inflate[Dt];if(c){this._inflate.close(),this._inflate=null,i(c);return}let h=cl.concat(this._inflate[ht],this._inflate[et]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[et]=0,this._inflate[ht]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,h)})}_compress(e,t,i){let a=this._isServer?"server":"client";if(!this._deflate){let c=`${a}_max_window_bits`,h=typeof this.params[c]!="number"?ps.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=ps.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:h}),this._deflate[et]=0,this._deflate[ht]=[],this._deflate.on("data",jm)}this._deflate[Lt]=i,this._deflate.write(e),this._deflate.flush(ps.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=cl.concat(this._deflate[ht],this._deflate[et]);t&&(c=new Dm(c.buffer,c.byteOffset,c.length-4)),this._deflate[Lt]=null,this._deflate[et]=0,this._deflate[ht]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};hl.exports=Fr;function jm(s){this[ht].push(s),this[et]+=s.length}function ul(s){if(this[et]+=s.length,this[tn]._maxPayload<1||this[et]<=this[tn]._maxPayload){this[ht].push(s);return}this[Dt]=new RangeError("Max payload size exceeded"),this[Dt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Dt][ll]=1009,this.removeListener("data",ul),this.reset()}function qm(s){if(this[tn]._inflate=null,this[Dt]){this[Lt](this[Dt]);return}s[ll]=1007,this[Lt](s)}});var Ut=$((lC,sn)=>{"use strict";var{isUtf8:dl}=q("buffer"),{hasBlob:Bm}=Ze(),$m=[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 Hm(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}function Wr(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 Gm(s){return Bm&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}sn.exports={isBlob:Gm,isValidStatusCode:Hm,isValidUTF8:Wr,tokenChars:$m};if(dl)sn.exports.isValidUTF8=function(s){return s.length<24?Wr(s):dl(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=q("utf-8-validate");sn.exports.isValidUTF8=function(e){return e.length<32?Wr(e):s(e)}}catch{}});var Yr=$((uC,bl)=>{"use strict";var{Writable:Fm}=q("stream"),fl=gs(),{BINARY_TYPES:Wm,EMPTY_BUFFER:pl,kStatusCode:Vm,kWebSocket:zm}=Ze(),{concat:Vr,toArrayBuffer:Km,unmask:Jm}=fs(),{isValidStatusCode:Ym,isValidUTF8:gl}=Ut(),nn=Buffer[Symbol.species],xe=0,ml=1,yl=2,_l=3,zr=4,Kr=5,rn=6,Jr=class extends Fm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Wm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[zm]=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 nn(i.buffer,i.byteOffset+e,i.length-e),new nn(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 nn(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 ml:this.getPayloadLength16(e);break;case yl:this.getPayloadLength64(e);break;case _l:this.getMask();break;case zr:this.getData(e);break;case Kr:case rn: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[fl.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=ml:this._payloadLength===127?this._state=yl: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=_l:this._state=zr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=zr}getData(e){let t=pl;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]&&Jm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Kr,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[fl.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 h=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(h);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=Vr(i,t):this._binaryType==="arraybuffer"?a=Km(Vr(i,t)):this._binaryType==="blob"?a=new Blob(i):a=i,this._allowSynchronousEvents?(this.emit("message",a,!0),this._state=xe):(this._state=rn,setImmediate(()=>{this.emit("message",a,!0),this._state=xe,this.startLoop(e)}))}else{let a=Vr(i,t);if(!this._skipUTF8Validation&&!gl(a)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Kr||this._allowSynchronousEvents?(this.emit("message",a,!1),this._state=xe):(this._state=rn,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,pl),this.end();else{let i=e.readUInt16BE(0);if(!Ym(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(c);return}let a=new nn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!gl(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=rn,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 h=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(h,this.createError),h.code=c,h[Vm]=a,h}};bl.exports=Jr});var Zr=$((dC,Cl)=>{"use strict";var{Duplex:hC}=q("stream"),{randomFillSync:Qm}=q("crypto"),vl=gs(),{EMPTY_BUFFER:Xm,kWebSocket:Zm,NOOP:ey}=Ze(),{isBlob:jt,isValidStatusCode:ty}=Ut(),{mask:wl,toBuffer:bt}=fs(),Ne=Symbol("kByteLength"),sy=Buffer.alloc(4),on=8*1024,vt,qt=on,$e=0,ny=1,ry=2,Qr=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=ey,this[Zm]=void 0}static frame(e,t){let i,a=!1,c=2,h=!1;t.mask&&(i=t.maskBuffer||sy,t.generateMask?t.generateMask(i):(qt===on&&(vt===void 0&&(vt=Buffer.alloc(on)),Qm(vt,0,on),qt=0),i[0]=vt[qt++],i[1]=vt[qt++],i[2]=vt[qt++],i[3]=vt[qt++]),h=(i[0]|i[1]|i[2]|i[3])===0,c=6);let p;typeof e=="string"?(!t.mask||h)&&t[Ne]!==void 0?p=t[Ne]:(e=Buffer.from(e),p=e.length):(p=e.length,a=t.mask&&t.readOnly&&!h);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],h?[m,e]:a?(wl(e,i,m,c,p),[m]):(wl(e,i,e,0,p),[m,e])):[m,e]}close(e,t,i,a){let c;if(e===void 0)c=Xm;else{if(typeof e!="number"||!ty(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 h={[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,h,a]):this.sendFrame(s.frame(c,h),a)}ping(e,t,i){let a,c;if(typeof e=="string"?(a=Buffer.byteLength(e),c=!1):jt(e)?(a=e.size,c=!1):(e=bt(e),a=e.length,c=bt.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let h={[Ne]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};jt(e)?this._state!==$e?this.enqueue([this.getBlobData,e,!1,h,i]):this.getBlobData(e,!1,h,i):this._state!==$e?this.enqueue([this.dispatch,e,!1,h,i]):this.sendFrame(s.frame(e,h),i)}pong(e,t,i){let a,c;if(typeof e=="string"?(a=Buffer.byteLength(e),c=!1):jt(e)?(a=e.size,c=!1):(e=bt(e),a=e.length,c=bt.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let h={[Ne]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};jt(e)?this._state!==$e?this.enqueue([this.getBlobData,e,!1,h,i]):this.getBlobData(e,!1,h,i):this._state!==$e?this.enqueue([this.dispatch,e,!1,h,i]):this.sendFrame(s.frame(e,h),i)}send(e,t,i){let a=this._extensions[vl.extensionName],c=t.binary?2:1,h=t.compress,p,g;typeof e=="string"?(p=Buffer.byteLength(e),g=!1):jt(e)?(p=e.size,g=!1):(e=bt(e),p=e.length,g=bt.readOnly),this._firstFragment?(this._firstFragment=!1,h&&a&&a.params[a._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(h=p>=a._threshold),this._compress=h):(h=!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:h};jt(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=ry,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let p=new Error("The socket was closed while the blob was being read");process.nextTick(Xr,this,p,a);return}this._bufferedBytes-=i[Ne];let h=bt(c);t?this.dispatch(h,t,i,a):(this._state=$e,this.sendFrame(s.frame(h,i),a),this.dequeue())}).catch(c=>{process.nextTick(iy,this,c,a)})}dispatch(e,t,i,a){if(!t){this.sendFrame(s.frame(e,i),a);return}let c=this._extensions[vl.extensionName];this._bufferedBytes+=i[Ne],this._state=ny,c.compress(e,i.fin,(h,p)=>{if(this._socket.destroyed){let g=new Error("The socket was closed while data was being compressed");Xr(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)}};Cl.exports=Qr;function Xr(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 iy(s,e,t){Xr(s,e,t),s.onerror(e)}});var Il=$((fC,Pl)=>{"use strict";var{kForOnEventAttribute:ms,kListener:ei}=Ze(),El=Symbol("kCode"),kl=Symbol("kData"),Ol=Symbol("kError"),Sl=Symbol("kMessage"),Tl=Symbol("kReason"),Bt=Symbol("kTarget"),Al=Symbol("kType"),Rl=Symbol("kWasClean"),tt=class{constructor(e){this[Bt]=null,this[Al]=e}get target(){return this[Bt]}get type(){return this[Al]}};Object.defineProperty(tt.prototype,"target",{enumerable:!0});Object.defineProperty(tt.prototype,"type",{enumerable:!0});var wt=class extends tt{constructor(e,t={}){super(e),this[El]=t.code===void 0?0:t.code,this[Tl]=t.reason===void 0?"":t.reason,this[Rl]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[El]}get reason(){return this[Tl]}get wasClean(){return this[Rl]}};Object.defineProperty(wt.prototype,"code",{enumerable:!0});Object.defineProperty(wt.prototype,"reason",{enumerable:!0});Object.defineProperty(wt.prototype,"wasClean",{enumerable:!0});var $t=class extends tt{constructor(e,t={}){super(e),this[Ol]=t.error===void 0?null:t.error,this[Sl]=t.message===void 0?"":t.message}get error(){return this[Ol]}get message(){return this[Sl]}};Object.defineProperty($t.prototype,"error",{enumerable:!0});Object.defineProperty($t.prototype,"message",{enumerable:!0});var ys=class extends tt{constructor(e,t={}){super(e),this[kl]=t.data===void 0?null:t.data}get data(){return this[kl]}};Object.defineProperty(ys.prototype,"data",{enumerable:!0});var oy={addEventListener(s,e,t={}){for(let a of this.listeners(s))if(!t[ms]&&a[ei]===e&&!a[ms])return;let i;if(s==="message")i=function(c,h){let p=new ys("message",{data:h?c:c.toString()});p[Bt]=this,an(e,this,p)};else if(s==="close")i=function(c,h){let p=new wt("close",{code:c,reason:h.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});p[Bt]=this,an(e,this,p)};else if(s==="error")i=function(c){let h=new $t("error",{error:c,message:c.message});h[Bt]=this,an(e,this,h)};else if(s==="open")i=function(){let c=new tt("open");c[Bt]=this,an(e,this,c)};else return;i[ms]=!!t[ms],i[ei]=e,t.once?this.once(s,i):this.on(s,i)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[ei]===e&&!t[ms]){this.removeListener(s,t);break}}};Pl.exports={CloseEvent:wt,ErrorEvent:$t,Event:tt,EventTarget:oy,MessageEvent:ys};function an(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}});var ti=$((pC,Ml)=>{"use strict";var{tokenChars:_s}=Ut();function We(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}function ay(s){let e=Object.create(null),t=Object.create(null),i=!1,a=!1,c=!1,h,p,g=-1,m=-1,v=-1,w=0;for(;w<s.length;w++)if(m=s.charCodeAt(w),h===void 0)if(v===-1&&_s[m]===1)g===-1&&(g=w);else if(w!==0&&(m===32||m===9))v===-1&&g!==-1&&(v=w);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${w}`);v===-1&&(v=w);let O=s.slice(g,v);m===44?(We(e,O,t),t=Object.create(null)):h=O,g=v=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(p===void 0)if(v===-1&&_s[m]===1)g===-1&&(g=w);else if(m===32||m===9)v===-1&&g!==-1&&(v=w);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${w}`);v===-1&&(v=w),We(t,s.slice(g,v),!0),m===44&&(We(e,h,t),t=Object.create(null),h=void 0),g=v=-1}else if(m===61&&g!==-1&&v===-1)p=s.slice(g,w),g=v=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(a){if(_s[m]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1?g=w:i||(i=!0),a=!1}else if(c)if(_s[m]===1)g===-1&&(g=w);else if(m===34&&g!==-1)c=!1,v=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(v===-1&&_s[m]===1)g===-1&&(g=w);else if(g!==-1&&(m===32||m===9))v===-1&&(v=w);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${w}`);v===-1&&(v=w);let O=s.slice(g,v);i&&(O=O.replace(/\\/g,""),i=!1),We(t,p,O),m===44&&(We(e,h,t),t=Object.create(null),h=void 0),p=void 0,g=v=-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");v===-1&&(v=w);let E=s.slice(g,v);return h===void 0?We(e,E,t):(p===void 0?We(t,E,!0):i?We(t,p,E.replace(/\\/g,"")):We(t,p,E),We(e,h,t)),e}function cy(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(h=>h===!0?a:`${a}=${h}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ml.exports={format:cy,parse:ay}});var hn=$((yC,Fl)=>{"use strict";var ly=q("events"),uy=q("https"),hy=q("http"),Ll=q("net"),dy=q("tls"),{randomBytes:fy,createHash:py}=q("crypto"),{Duplex:gC,Readable:mC}=q("stream"),{URL:si}=q("url"),dt=gs(),gy=Yr(),my=Zr(),{isBlob:yy}=Ut(),{BINARY_TYPES:xl,CLOSE_TIMEOUT:_y,EMPTY_BUFFER:cn,GUID:by,kForOnEventAttribute:ni,kListener:vy,kStatusCode:wy,kWebSocket:me,NOOP:Dl}=Ze(),{EventTarget:{addEventListener:Cy,removeEventListener:Ey}}=Il(),{format:ky,parse:Oy}=ti(),{toBuffer:Sy}=fs(),Ul=Symbol("kAborted"),ri=[8,13],st=["CONNECTING","OPEN","CLOSING","CLOSED"],Ty=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ae=class s extends ly{constructor(e,t,i){super(),this._binaryType=xl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=cn,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]),jl(this,e,t,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){xl.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 gy({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new my(e,this._extensions,i.generateMask);this._receiver=a,this._sender=c,this._socket=e,a[me]=this,c[me]=this,e[me]=this,a.on("conclude",Py),a.on("drain",Iy),a.on("error",My),a.on("message",xy),a.on("ping",Ny),a.on("pong",Ly),c.onerror=Dy,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",$l),e.on("data",un),e.on("end",Hl),e.on("error",Gl),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[dt.extensionName]&&this._extensions[dt.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){Pe(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())}),Bl(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){ii(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||cn,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){ii(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||cn,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){ii(this,e,i);return}let a={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[dt.extensionName]||(a.compress=!1),this._sender.send(e||cn,a,i)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Pe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=s.CLOSING,this._socket.destroy())}}};Object.defineProperty(ae,"CONNECTING",{enumerable:!0,value:st.indexOf("CONNECTING")});Object.defineProperty(ae.prototype,"CONNECTING",{enumerable:!0,value:st.indexOf("CONNECTING")});Object.defineProperty(ae,"OPEN",{enumerable:!0,value:st.indexOf("OPEN")});Object.defineProperty(ae.prototype,"OPEN",{enumerable:!0,value:st.indexOf("OPEN")});Object.defineProperty(ae,"CLOSING",{enumerable:!0,value:st.indexOf("CLOSING")});Object.defineProperty(ae.prototype,"CLOSING",{enumerable:!0,value:st.indexOf("CLOSING")});Object.defineProperty(ae,"CLOSED",{enumerable:!0,value:st.indexOf("CLOSED")});Object.defineProperty(ae.prototype,"CLOSED",{enumerable:!0,value:st.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(s=>{Object.defineProperty(ae.prototype,s,{enumerable:!0})});["open","error","close","message"].forEach(s=>{Object.defineProperty(ae.prototype,`on${s}`,{enumerable:!0,get(){for(let e of this.listeners(s))if(e[ni])return e[vy];return null},set(e){for(let t of this.listeners(s))if(t[ni]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[ni]:!0})}})});ae.prototype.addEventListener=Cy;ae.prototype.removeEventListener=Ey;Fl.exports=ae;function jl(s,e,t,i){let a={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_y,protocolVersion:ri[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,!ri.includes(a.protocolVersion))throw new RangeError(`Unsupported protocol version: ${a.protocolVersion} (supported versions: ${ri.join(", ")})`);let c;if(e instanceof si)c=e;else try{c=new si(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 h=c.protocol==="wss:",p=c.protocol==="ws+unix:",g;if(c.protocol!=="ws:"&&!h&&!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 k=new SyntaxError(g);if(s._redirects===0)throw k;ln(s,k);return}let m=h?443:80,v=fy(16).toString("base64"),w=h?uy.request:hy.request,E=new Set,O;if(a.createConnection=a.createConnection||(h?Ry:Ay),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":v,Connection:"Upgrade",Upgrade:"websocket"},a.path=c.pathname+c.search,a.timeout=a.handshakeTimeout,a.perMessageDeflate&&(O=new dt(a.perMessageDeflate!==!0?a.perMessageDeflate:{},!1,a.maxPayload),a.headers["Sec-WebSocket-Extensions"]=ky({[dt.extensionName]:O.offer()})),t.length){for(let k of t){if(typeof k!="string"||!Ty.test(k)||E.has(k))throw new SyntaxError("An invalid or duplicated subprotocol was specified");E.add(k)}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 k=a.path.split(":");a.socketPath=k[0],a.path=k[1]}let T;if(a.followRedirects){if(s._redirects===0){s._originalIpc=p,s._originalSecure=h,s._originalHostOrSocketPath=p?a.socketPath:c.host;let k=i&&i.headers;if(i={...i,headers:{}},k)for(let[A,N]of Object.entries(k))i.headers[A.toLowerCase()]=N}else if(s.listenerCount("redirect")===0){let k=p?s._originalIpc?a.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:c.host===s._originalHostOrSocketPath;(!k||s._originalSecure&&!h)&&(delete a.headers.authorization,delete a.headers.cookie,k||delete a.headers.host,a.auth=void 0)}a.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(a.auth).toString("base64")),T=s._req=w(a),s._redirects&&s.emit("redirect",s.url,T)}else T=s._req=w(a);a.timeout&&T.on("timeout",()=>{Pe(s,T,"Opening handshake has timed out")}),T.on("error",k=>{T===null||T[Ul]||(T=s._req=null,ln(s,k))}),T.on("response",k=>{let A=k.headers.location,N=k.statusCode;if(A&&a.followRedirects&&N>=300&&N<400){if(++s._redirects>a.maxRedirects){Pe(s,T,"Maximum redirects exceeded");return}T.abort();let W;try{W=new si(A,e)}catch{let se=new SyntaxError(`Invalid URL: ${A}`);ln(s,se);return}jl(s,W,t,i)}else s.emit("unexpected-response",T,k)||Pe(s,T,`Unexpected server response: ${k.statusCode}`)}),T.on("upgrade",(k,A,N)=>{if(s.emit("upgrade",k),s.readyState!==ae.CONNECTING)return;T=s._req=null;let W=k.headers.upgrade;if(W===void 0||W.toLowerCase()!=="websocket"){Pe(s,A,"Invalid Upgrade header");return}let Q=py("sha1").update(v+by).digest("base64");if(k.headers["sec-websocket-accept"]!==Q){Pe(s,A,"Invalid Sec-WebSocket-Accept header");return}let se=k.headers["sec-websocket-protocol"],Y;if(se!==void 0?E.size?E.has(se)||(Y="Server sent an invalid subprotocol"):Y="Server sent a subprotocol but none was requested":E.size&&(Y="Server sent no subprotocol"),Y){Pe(s,A,Y);return}se&&(s._protocol=se);let X=k.headers["sec-websocket-extensions"];if(X!==void 0){if(!O){Pe(s,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ce;try{ce=Oy(X)}catch{Pe(s,A,"Invalid Sec-WebSocket-Extensions header");return}let ie=Object.keys(ce);if(ie.length!==1||ie[0]!==dt.extensionName){Pe(s,A,"Server indicated an extension that was not requested");return}try{O.accept(ce[dt.extensionName])}catch{Pe(s,A,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[dt.extensionName]=O}s.setSocket(A,N,{allowSynchronousEvents:a.allowSynchronousEvents,generateMask:a.generateMask,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation})}),a.finishRequest?a.finishRequest(T,s):T.end()}function ln(s,e){s._readyState=ae.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}function Ay(s){return s.path=s.socketPath,Ll.connect(s)}function Ry(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=Ll.isIP(s.host)?"":s.host),dy.connect(s)}function Pe(s,e,t){s._readyState=ae.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Pe),e.setHeader?(e[Ul]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ln,s,i)):(e.destroy(i),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}function ii(s,e,t){if(e){let i=yy(e)?e.size:Sy(e).length;s._socket?s._sender._bufferedBytes+=i:s._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${s.readyState} (${st[s.readyState]})`);process.nextTick(t,i)}}function Py(s,e){let t=this[me];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[me]!==void 0&&(t._socket.removeListener("data",un),process.nextTick(ql,t._socket),s===1005?t.close():t.close(s,e))}function Iy(){let s=this[me];s.isPaused||s._socket.resume()}function My(s){let e=this[me];e._socket[me]!==void 0&&(e._socket.removeListener("data",un),process.nextTick(ql,e._socket),e.close(s[wy])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}function Nl(){this[me].emitClose()}function xy(s,e){this[me].emit("message",s,e)}function Ny(s){let e=this[me];e._autoPong&&e.pong(s,!this._isServer,Dl),e.emit("ping",s)}function Ly(s){this[me].emit("pong",s)}function ql(s){s.resume()}function Dy(s){let e=this[me];e.readyState!==ae.CLOSED&&(e.readyState===ae.OPEN&&(e._readyState=ae.CLOSING,Bl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}function Bl(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}function $l(){let s=this[me];if(this.removeListener("close",$l),this.removeListener("data",un),this.removeListener("end",Hl),s._readyState=ae.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[me]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",Nl),s._receiver.on("finish",Nl))}function un(s){this[me]._receiver.write(s)||this.pause()}function Hl(){let s=this[me];s._readyState=ae.CLOSING,s._receiver.end(),this.end()}function Gl(){let s=this[me];this.removeListener("error",Gl),this.on("error",Dl),s&&(s._readyState=ae.CLOSING,this.destroy())}});var Kl=$((bC,zl)=>{"use strict";var _C=hn(),{Duplex:Uy}=q("stream");function Wl(s){s.emit("close")}function jy(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vl(s){this.removeListener("error",Vl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}function qy(s,e){let t=!0,i=new Uy({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return s.on("message",function(c,h){let p=!h&&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(Wl,i);return}let h=!1;s.once("error",function(g){h=!0,c(g)}),s.once("close",function(){h||c(a),process.nextTick(Wl,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,h){if(s.readyState===s.CONNECTING){s.once("open",function(){i._write(a,c,h)});return}s.send(a,h)},i.on("end",jy),i.on("error",Vl),i}zl.exports=qy});var Yl=$((vC,Jl)=>{"use strict";var{tokenChars:By}=Ut();function $y(s){let e=new Set,t=-1,i=-1,a=0;for(a;a<s.length;a++){let h=s.charCodeAt(a);if(i===-1&&By[h]===1)t===-1&&(t=a);else if(a!==0&&(h===32||h===9))i===-1&&t!==-1&&(i=a);else if(h===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}Jl.exports={parse:$y}});var nu=$((CC,su)=>{"use strict";var Hy=q("events"),dn=q("http"),{Duplex:wC}=q("stream"),{createHash:Gy}=q("crypto"),Ql=ti(),Ct=gs(),Fy=Yl(),Wy=hn(),{CLOSE_TIMEOUT:Vy,GUID:zy,kWebSocket:Ky}=Ze(),Jy=/^[+/0-9A-Za-z]{22}==$/,Xl=0,Zl=1,tu=2,oi=class extends Hy{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Vy,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wy,...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=dn.createServer((i,a)=>{let c=dn.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=Yy(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(a,c,h)=>{this.handleUpgrade(a,c,h,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Xl}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===tu){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(bs,this);return}if(e&&this.once("close",e),this._state!==Zl)if(this._state=Zl,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(bs,this):process.nextTick(bs,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{bs(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",eu);let c=e.headers["sec-websocket-key"],h=e.headers.upgrade,p=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Et(this,e,t,405,"Invalid HTTP method");return}if(h===void 0||h.toLowerCase()!=="websocket"){Et(this,e,t,400,"Invalid Upgrade header");return}if(c===void 0||!Jy.test(c)){Et(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(p!==13&&p!==8){Et(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){vs(t,400);return}let g=e.headers["sec-websocket-protocol"],m=new Set;if(g!==void 0)try{m=Fy.parse(g)}catch{Et(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let v=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&v!==void 0){let E=new Ct(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let O=Ql.parse(v);O[Ct.extensionName]&&(E.accept(O[Ct.extensionName]),w[Ct.extensionName]=E)}catch{Et(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let E={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(E,(O,T,k,A)=>{if(!O)return vs(t,T||401,k,A);this.completeUpgrade(w,c,m,e,t,i,a)});return}if(!this.options.verifyClient(E))return vs(t,401)}this.completeUpgrade(w,c,m,e,t,i,a)}completeUpgrade(e,t,i,a,c,h,p){if(!c.readable||!c.writable)return c.destroy();if(c[Ky])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Xl)return vs(c,503);let m=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Gy("sha1").update(t+zy).digest("base64")}`],v=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}`),v._protocol=w)}if(e[Ct.extensionName]){let w=e[Ct.extensionName].params,E=Ql.format({[Ct.extensionName]:[w]});m.push(`Sec-WebSocket-Extensions: ${E}`),v._extensions=e}this.emit("headers",m,a),c.write(m.concat(`\r
|
|
28
28
|
`).join(`\r
|
|
29
|
-
`)),c.removeListener("error",eu),v.setSocket(c,h,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(v),v.on("close",()=>{this.clients.delete(v),this._shouldEmitClose&&!this.clients.size&&process.nextTick(
|
|
29
|
+
`)),c.removeListener("error",eu),v.setSocket(c,h,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(v),v.on("close",()=>{this.clients.delete(v),this._shouldEmitClose&&!this.clients.size&&process.nextTick(bs,this)})),p(v,a)}};su.exports=oi;function Yy(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 bs(s){s._state=tu,s.emit("close")}function eu(){this.destroy()}function vs(s,e,t,i){t=t||dn.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} ${dn.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 h=new Error(a);Error.captureStackTrace(h,Ct),s.emit("wsClientError",h,t,e)}else bs(t,i,a,c)}});var dn=$((EC,ru)=>{"use strict";var et=un();et.createWebSocketStream=Kl();et.Server=nu();et.Receiver=Yr();et.Sender=Zr();et.WebSocket=et;et.WebSocketServer=et.Server;ru.exports=et});var st=$((tt,fn)=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});var iu=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Qy(s){return iu.includes(s)}var Xy=["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",...iu];function Zy(s){return Xy.includes(s)}var e_=["null","undefined","string","number","bigint","boolean","symbol"];function t_(s){return e_.includes(s)}function $t(s){return e=>typeof e===s}var{toString:ou}=Object.prototype,vs=s=>{let e=ou.call(s).slice(8,-1);if(/HTML\w+Element/.test(e)&&b.domElement(s))return"HTMLElement";if(Zy(e))return e},ne=s=>e=>vs(e)===s;function b(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(b.observable(s))return"Observable";if(b.array(s))return"Array";if(b.buffer(s))return"Buffer";let e=vs(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"}b.undefined=$t("undefined");b.string=$t("string");var s_=$t("number");b.number=s=>s_(s)&&!b.nan(s);b.bigint=$t("bigint");b.function_=$t("function");b.null_=s=>s===null;b.class_=s=>b.function_(s)&&s.toString().startsWith("class ");b.boolean=s=>s===!0||s===!1;b.symbol=$t("symbol");b.numericString=s=>b.string(s)&&!b.emptyStringOrWhitespace(s)&&!Number.isNaN(Number(s));b.array=(s,e)=>Array.isArray(s)?b.function_(e)?s.every(e):!0:!1;b.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};b.blob=s=>ne("Blob")(s);b.nullOrUndefined=s=>b.null_(s)||b.undefined(s);b.object=s=>!b.null_(s)&&(typeof s=="object"||b.function_(s));b.iterable=s=>{var e;return b.function_((e=s)===null||e===void 0?void 0:e[Symbol.iterator])};b.asyncIterable=s=>{var e;return b.function_((e=s)===null||e===void 0?void 0:e[Symbol.asyncIterator])};b.generator=s=>{var e,t;return b.iterable(s)&&b.function_((e=s)===null||e===void 0?void 0:e.next)&&b.function_((t=s)===null||t===void 0?void 0:t.throw)};b.asyncGenerator=s=>b.asyncIterable(s)&&b.function_(s.next)&&b.function_(s.throw);b.nativePromise=s=>ne("Promise")(s);var n_=s=>{var e,t;return b.function_((e=s)===null||e===void 0?void 0:e.then)&&b.function_((t=s)===null||t===void 0?void 0:t.catch)};b.promise=s=>b.nativePromise(s)||n_(s);b.generatorFunction=ne("GeneratorFunction");b.asyncGeneratorFunction=s=>vs(s)==="AsyncGeneratorFunction";b.asyncFunction=s=>vs(s)==="AsyncFunction";b.boundFunction=s=>b.function_(s)&&!s.hasOwnProperty("prototype");b.regExp=ne("RegExp");b.date=ne("Date");b.error=ne("Error");b.map=s=>ne("Map")(s);b.set=s=>ne("Set")(s);b.weakMap=s=>ne("WeakMap")(s);b.weakSet=s=>ne("WeakSet")(s);b.int8Array=ne("Int8Array");b.uint8Array=ne("Uint8Array");b.uint8ClampedArray=ne("Uint8ClampedArray");b.int16Array=ne("Int16Array");b.uint16Array=ne("Uint16Array");b.int32Array=ne("Int32Array");b.uint32Array=ne("Uint32Array");b.float32Array=ne("Float32Array");b.float64Array=ne("Float64Array");b.bigInt64Array=ne("BigInt64Array");b.bigUint64Array=ne("BigUint64Array");b.arrayBuffer=ne("ArrayBuffer");b.sharedArrayBuffer=ne("SharedArrayBuffer");b.dataView=ne("DataView");b.enumCase=(s,e)=>Object.values(e).includes(s);b.directInstanceOf=(s,e)=>Object.getPrototypeOf(s)===e.prototype;b.urlInstance=s=>ne("URL")(s);b.urlString=s=>{if(!b.string(s))return!1;try{return new URL(s),!0}catch{return!1}};b.truthy=s=>!!s;b.falsy=s=>!s;b.nan=s=>Number.isNaN(s);b.primitive=s=>b.null_(s)||t_(typeof s);b.integer=s=>Number.isInteger(s);b.safeInteger=s=>Number.isSafeInteger(s);b.plainObject=s=>{if(ou.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||e===Object.getPrototypeOf({})};b.typedArray=s=>Qy(vs(s));var r_=s=>b.safeInteger(s)&&s>=0;b.arrayLike=s=>!b.nullOrUndefined(s)&&!b.function_(s)&&r_(s.length);b.inRange=(s,e)=>{if(b.number(e))return s>=Math.min(0,e)&&s<=Math.max(e,0);if(b.array(e)&&e.length===2)return s>=Math.min(...e)&&s<=Math.max(...e);throw new TypeError(`Invalid range: ${JSON.stringify(e)}`)};var i_=1,o_=["innerHTML","ownerDocument","style","attributes","nodeValue"];b.domElement=s=>b.object(s)&&s.nodeType===i_&&b.string(s.nodeName)&&!b.plainObject(s)&&o_.every(e=>e in s);b.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};b.nodeStream=s=>b.object(s)&&b.function_(s.pipe)&&!b.observable(s);b.infinite=s=>s===1/0||s===-1/0;var au=s=>e=>b.integer(e)&&Math.abs(e%2)===s;b.evenInteger=au(0);b.oddInteger=au(1);b.emptyArray=s=>b.array(s)&&s.length===0;b.nonEmptyArray=s=>b.array(s)&&s.length>0;b.emptyString=s=>b.string(s)&&s.length===0;var a_=s=>b.string(s)&&!/\S/.test(s);b.emptyStringOrWhitespace=s=>b.emptyString(s)||a_(s);b.nonEmptyString=s=>b.string(s)&&s.length>0;b.nonEmptyStringAndNotWhitespace=s=>b.string(s)&&!b.emptyStringOrWhitespace(s);b.emptyObject=s=>b.object(s)&&!b.map(s)&&!b.set(s)&&Object.keys(s).length===0;b.nonEmptyObject=s=>b.object(s)&&!b.map(s)&&!b.set(s)&&Object.keys(s).length>0;b.emptySet=s=>b.set(s)&&s.size===0;b.nonEmptySet=s=>b.set(s)&&s.size>0;b.emptyMap=s=>b.map(s)&&s.size===0;b.nonEmptyMap=s=>b.map(s)&&s.size>0;b.propertyKey=s=>b.any([b.string,b.number,b.symbol],s);b.formData=s=>ne("FormData")(s);b.urlSearchParams=s=>ne("URLSearchParams")(s);var cu=(s,e,t)=>{if(!b.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)};b.any=(s,...e)=>(b.array(s)?s:[s]).some(i=>cu(Array.prototype.some,i,e));b.all=(s,...e)=>cu(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(h=>`\`${b(h)}\``))].join(", ")}`:`received value of type \`${b(t)}\``;throw new TypeError(`Expected value which is \`${e}\`, ${c}.`)}};tt.assert={undefined:s=>B(b.undefined(s),"undefined",s),string:s=>B(b.string(s),"string",s),number:s=>B(b.number(s),"number",s),bigint:s=>B(b.bigint(s),"bigint",s),function_:s=>B(b.function_(s),"Function",s),null_:s=>B(b.null_(s),"null",s),class_:s=>B(b.class_(s),"Class",s),boolean:s=>B(b.boolean(s),"boolean",s),symbol:s=>B(b.symbol(s),"symbol",s),numericString:s=>B(b.numericString(s),"string with a number",s),array:(s,e)=>{B(b.array(s),"Array",s),e&&s.forEach(e)},buffer:s=>B(b.buffer(s),"Buffer",s),blob:s=>B(b.blob(s),"Blob",s),nullOrUndefined:s=>B(b.nullOrUndefined(s),"null or undefined",s),object:s=>B(b.object(s),"Object",s),iterable:s=>B(b.iterable(s),"Iterable",s),asyncIterable:s=>B(b.asyncIterable(s),"AsyncIterable",s),generator:s=>B(b.generator(s),"Generator",s),asyncGenerator:s=>B(b.asyncGenerator(s),"AsyncGenerator",s),nativePromise:s=>B(b.nativePromise(s),"native Promise",s),promise:s=>B(b.promise(s),"Promise",s),generatorFunction:s=>B(b.generatorFunction(s),"GeneratorFunction",s),asyncGeneratorFunction:s=>B(b.asyncGeneratorFunction(s),"AsyncGeneratorFunction",s),asyncFunction:s=>B(b.asyncFunction(s),"AsyncFunction",s),boundFunction:s=>B(b.boundFunction(s),"Function",s),regExp:s=>B(b.regExp(s),"RegExp",s),date:s=>B(b.date(s),"Date",s),error:s=>B(b.error(s),"Error",s),map:s=>B(b.map(s),"Map",s),set:s=>B(b.set(s),"Set",s),weakMap:s=>B(b.weakMap(s),"WeakMap",s),weakSet:s=>B(b.weakSet(s),"WeakSet",s),int8Array:s=>B(b.int8Array(s),"Int8Array",s),uint8Array:s=>B(b.uint8Array(s),"Uint8Array",s),uint8ClampedArray:s=>B(b.uint8ClampedArray(s),"Uint8ClampedArray",s),int16Array:s=>B(b.int16Array(s),"Int16Array",s),uint16Array:s=>B(b.uint16Array(s),"Uint16Array",s),int32Array:s=>B(b.int32Array(s),"Int32Array",s),uint32Array:s=>B(b.uint32Array(s),"Uint32Array",s),float32Array:s=>B(b.float32Array(s),"Float32Array",s),float64Array:s=>B(b.float64Array(s),"Float64Array",s),bigInt64Array:s=>B(b.bigInt64Array(s),"BigInt64Array",s),bigUint64Array:s=>B(b.bigUint64Array(s),"BigUint64Array",s),arrayBuffer:s=>B(b.arrayBuffer(s),"ArrayBuffer",s),sharedArrayBuffer:s=>B(b.sharedArrayBuffer(s),"SharedArrayBuffer",s),dataView:s=>B(b.dataView(s),"DataView",s),enumCase:(s,e)=>B(b.enumCase(s,e),"EnumCase",s),urlInstance:s=>B(b.urlInstance(s),"URL",s),urlString:s=>B(b.urlString(s),"string with a URL",s),truthy:s=>B(b.truthy(s),"truthy",s),falsy:s=>B(b.falsy(s),"falsy",s),nan:s=>B(b.nan(s),"NaN",s),primitive:s=>B(b.primitive(s),"primitive",s),integer:s=>B(b.integer(s),"integer",s),safeInteger:s=>B(b.safeInteger(s),"integer",s),plainObject:s=>B(b.plainObject(s),"plain object",s),typedArray:s=>B(b.typedArray(s),"TypedArray",s),arrayLike:s=>B(b.arrayLike(s),"array-like",s),domElement:s=>B(b.domElement(s),"HTMLElement",s),observable:s=>B(b.observable(s),"Observable",s),nodeStream:s=>B(b.nodeStream(s),"Node.js Stream",s),infinite:s=>B(b.infinite(s),"infinite number",s),emptyArray:s=>B(b.emptyArray(s),"empty array",s),nonEmptyArray:s=>B(b.nonEmptyArray(s),"non-empty array",s),emptyString:s=>B(b.emptyString(s),"empty string",s),emptyStringOrWhitespace:s=>B(b.emptyStringOrWhitespace(s),"empty string or whitespace",s),nonEmptyString:s=>B(b.nonEmptyString(s),"non-empty string",s),nonEmptyStringAndNotWhitespace:s=>B(b.nonEmptyStringAndNotWhitespace(s),"non-empty string and not whitespace",s),emptyObject:s=>B(b.emptyObject(s),"empty object",s),nonEmptyObject:s=>B(b.nonEmptyObject(s),"non-empty object",s),emptySet:s=>B(b.emptySet(s),"empty set",s),nonEmptySet:s=>B(b.nonEmptySet(s),"non-empty set",s),emptyMap:s=>B(b.emptyMap(s),"empty map",s),nonEmptyMap:s=>B(b.nonEmptyMap(s),"non-empty map",s),propertyKey:s=>B(b.propertyKey(s),"PropertyKey",s),formData:s=>B(b.formData(s),"FormData",s),urlSearchParams:s=>B(b.urlSearchParams(s),"URLSearchParams",s),evenInteger:s=>B(b.evenInteger(s),"even integer",s),oddInteger:s=>B(b.oddInteger(s),"odd integer",s),directInstanceOf:(s,e)=>B(b.directInstanceOf(s,e),"T",s),inRange:(s,e)=>B(b.inRange(s,e),"in range",s),any:(s,...e)=>B(b.any(s,...e),"predicate returns truthy for any value",e,{multipleValues:!0}),all:(s,...e)=>B(b.all(s,...e),"predicate returns truthy for all values",e,{multipleValues:!0})};Object.defineProperties(b,{class:{value:b.class_},function:{value:b.function_},null:{value:b.null_}});Object.defineProperties(tt.assert,{class:{value:tt.assert.class_},function:{value:tt.assert.function_},null:{value:tt.assert.null_}});tt.default=b;fn.exports=b;fn.exports.default=b;fn.exports.assert=tt.assert});var lu=$((kC,ai)=>{"use strict";var pn=class extends Error{constructor(e){super(e||"Promise was canceled"),this.name="CancelError"}get isCanceled(){return!0}},gn=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||!h.shouldReject)&&(this._isPending=!1,t(p))},c=p=>{this._isPending=!1,i(p)},h=p=>{if(!this._isPending)throw new Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(p)};return Object.defineProperties(h,{shouldReject:{get:()=>this._rejectOnCancel,set:p=>{this._rejectOnCancel=p}}}),e(a,c,h)})}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 pn(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(gn.prototype,Promise.prototype);ai.exports=gn;ai.exports.CancelError=pn});var uu=$((li,ui)=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});function c_(s){return s.encrypted}var ci=(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",h=()=>{i&&t.connect(),c_(s)&&a&&(s.authorized?t.secureConnect():s.authorizationError||s.once("secureConnect",t.secureConnect)),c&&s.once("close",t.close)};s.writable&&!s.connecting?h():s.connecting?s.once("connect",h):s.destroyed&&c&&t.close(s._hadError)};li.default=ci;ui.exports=ci;ui.exports.default=ci});var hu=$((di,fi)=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});var l_=uu(),u_=q("util"),h_=Number(process.versions.node.split(".")[0]),hi=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,...v)=>(m==="error"&&(e.error=Date.now(),e.phases.total=e.error-e.start,p.emit=g),g(m,...v))};t(s);let i=()=>{e.abort=Date.now(),(!e.response||h_>=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,u_.types.isProxy(p))return;let g=()=>{e.lookup=Date.now(),e.phases.dns=e.lookup-e.socket};p.prependOnceListener("lookup",g),l_.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};di.default=hi;fi.exports=hi;fi.exports.default=hi});var _u=$((OC,mi)=>{"use strict";var{V4MAPPED:d_,ADDRCONFIG:f_,ALL:yu,promises:{Resolver:du},lookup:p_}=q("dns"),{promisify:pi}=q("util"),g_=q("os"),Ht=Symbol("cacheableLookupCreateConnection"),gi=Symbol("cacheableLookupInstance"),fu=Symbol("expires"),m_=typeof yu=="number",pu=s=>{if(!(s&&typeof s.createConnection=="function"))throw new Error("Expected an Agent instance as the first argument")},y_=s=>{for(let e of s)e.family!==6&&(e.address=`::ffff:${e.address}`,e.family=6)},gu=()=>{let s=!1,e=!1;for(let t of Object.values(g_.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}},__=s=>Symbol.iterator in s,mu={ttl:!0},b_={all:!0},mn=class{constructor({cache:e=new Map,maxTtl:t=1/0,fallbackDuration:i=3600,errorTtl:a=.15,resolver:c=new du,lookup:h=p_}={}){if(this.maxTtl=t,this.errorTtl=a,this._cache=e,this._resolver=c,this._dnsLookup=pi(h),this._resolver instanceof du?(this._resolve4=this._resolver.resolve4.bind(this._resolver),this._resolve6=this._resolver.resolve6.bind(this._resolver)):(this._resolve4=pi(this._resolver.resolve4.bind(this._resolver)),this._resolve6=pi(this._resolver.resolve6.bind(this._resolver))),this._iface=gu(),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&d_&&(m_&&t.hints&yu||a.length===0)?y_(i):i=a}else t.family===4&&(i=i.filter(a=>a.family===4));if(t.hints&f_){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(v){if(v.code==="ENODATA"||v.code==="ENOTFOUND")return[];throw v}},[i,a]=await Promise.all([this._resolve4(e,mu),this._resolve6(e,mu)].map(m=>t(m))),c=0,h=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,h=Math.max(h,m.ttl);return i.length>0?a.length>0?p=Math.min(c,h):p=c:p=h,{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[fu]=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}}__(this._cache)&&this._tick(i)}}async queryAndCache(e){if(this._hostnamesToFallback.has(e))return this._dnsLookup(e,b_);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,h]of this._cache){let p=h[fu];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(pu(e),Ht in e)throw new Error("CacheableLookup has been already installed");e[Ht]=e.createConnection,e[gi]=this,e.createConnection=(t,i)=>("lookup"in t||(t.lookup=this.lookup),e[Ht](t,i))}uninstall(e){if(pu(e),e[Ht]){if(e[gi]!==this)throw new Error("The agent is not owned by this CacheableLookup instance");e.createConnection=e[Ht],delete e[Ht],delete e[gi]}}updateInterfaceInfo(){let{_iface:e}=this;this._iface=gu(),(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()}};mi.exports=mn;mi.exports.default=mn});var wu=$((SC,vu)=>{"use strict";var v_="text/plain",w_="us-ascii",bu=(s,e)=>e.some(t=>t instanceof RegExp?t.test(s):t===s),C_=(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,h=i.split(";");c=e?"":c;let p=!1;h[h.length-1]==="base64"&&(h.pop(),p=!0);let g=(h.shift()||"").toLowerCase(),v=[...h.map(w=>{let[E,O=""]=w.split("=").map(A=>A.trim());return E==="charset"&&(O=O.toLowerCase(),O===w_)?"":`${E}${O?`=${O}`:""}`}).filter(Boolean)];return p&&v.push("base64"),(v.length!==0||g&&g!==v_)&&v.unshift(g),`data:${v.join(";")},${p?a.trim():a}${c?`#${c}`:""}`},E_=(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 C_(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 h=a.pathname.split("/"),p=h[h.length-1];bu(p,e.removeDirectoryIndex)&&(h=h.slice(0,h.length-1),a.pathname=h.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 h of[...a.searchParams.keys()])bu(h,e.removeQueryParameters)&&a.searchParams.delete(h);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};vu.exports=E_});var ku=$((TC,Eu)=>{Eu.exports=Cu;function Cu(s,e){if(s&&e)return Cu(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),h=i[i.length-1];return typeof c=="function"&&c!==h&&Object.keys(h).forEach(function(p){c[p]=h[p]}),c}}});var _i=$((AC,yi)=>{var Ou=ku();yi.exports=Ou(yn);yi.exports.strict=Ou(Su);yn.proto=yn(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return yn(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return Su(this)},configurable:!0})});function yn(s){var e=function(){return e.called?e.value:(e.called=!0,e.value=s.apply(this,arguments))};return e.called=!1,e}function Su(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 Ru=$((RC,Au)=>{var k_=_i(),O_=function(){},S_=global.Bare?queueMicrotask:process.nextTick.bind(process),T_=function(s){return s.setHeader&&typeof s.abort=="function"},A_=function(s){return s.stdio&&Array.isArray(s.stdio)&&s.stdio.length===3},Tu=function(s,e,t){if(typeof e=="function")return Tu(s,null,e);e||(e={}),t=k_(t||O_);var i=s._writableState,a=s._readableState,c=e.readable||e.readable!==!1&&s.readable,h=e.writable||e.writable!==!1&&s.writable,p=!1,g=function(){s.writable||m()},m=function(){h=!1,c||t.call(s)},v=function(){c=!1,h||t.call(s)},w=function(T){t.call(s,T?new Error("exited with error code: "+T):null)},E=function(T){t.call(s,T)},O=function(){S_(A)},A=function(){if(!p){if(c&&!(a&&a.ended&&!a.destroyed))return t.call(s,new Error("premature close"));if(h&&!(i&&i.ended&&!i.destroyed))return t.call(s,new Error("premature close"))}},k=function(){s.req.on("finish",m)};return T_(s)?(s.on("complete",m),s.on("abort",O),s.req?k():s.on("request",k)):h&&!i&&(s.on("end",g),s.on("close",g)),A_(s)&&s.on("exit",w),s.on("end",v),s.on("finish",m),e.error!==!1&&s.on("error",E),s.on("close",O),function(){p=!0,s.removeListener("complete",m),s.removeListener("abort",O),s.removeListener("request",k),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",v),s.removeListener("error",E),s.removeListener("close",O)}};Au.exports=Tu});var Mu=$((PC,Iu)=>{var R_=_i(),P_=Ru(),_n;try{_n=q("fs")}catch{}var ws=function(){},I_=typeof process>"u"?!1:/^v?\.0/.test(process.version),bn=function(s){return typeof s=="function"},M_=function(s){return!I_||!_n?!1:(s instanceof(_n.ReadStream||ws)||s instanceof(_n.WriteStream||ws))&&bn(s.close)},x_=function(s){return s.setHeader&&bn(s.abort)},N_=function(s,e,t,i){i=R_(i);var a=!1;s.on("close",function(){a=!0}),P_(s,{readable:e,writable:t},function(h){if(h)return i(h);a=!0,i()});var c=!1;return function(h){if(!a&&!c){if(c=!0,M_(s))return s.close(ws);if(x_(s))return s.abort();if(bn(s.destroy))return s.destroy();i(h||new Error("stream was destroyed"))}}},Pu=function(s){s()},L_=function(s,e){return s.pipe(e)},D_=function(){var s=Array.prototype.slice.call(arguments),e=bn(s[s.length-1]||ws)&&s.pop()||ws;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 h=c<s.length-1,p=c>0;return N_(a,h,p,function(g){t||(t=g),g&&i.forEach(Pu),!h&&(i.forEach(Pu),e(t))})});return s.reduce(L_)};Iu.exports=D_});var Nu=$((IC,xu)=>{"use strict";var{PassThrough:U_}=q("stream");xu.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 U_({objectMode:a});t&&c.setEncoding(t);let h=0,p=[];return c.on("data",g=>{p.push(g),a?h=p.length:h+=g.length}),c.getBufferedValue=()=>e?p:i?Buffer.concat(p,h):p.join(""),c.getBufferedLength=()=>h,c}});var Lu=$((MC,Gt)=>{"use strict";var{constants:j_}=q("buffer"),q_=Mu(),B_=Nu(),vn=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function wn(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 h=p=>{p&&i.getBufferedLength()<=j_.MAX_LENGTH&&(p.bufferedData=i.getBufferedValue()),c(p)};i=q_(s,B_(e),p=>{if(p){h(p);return}a()}),i.on("data",()=>{i.getBufferedLength()>t&&h(new vn)})}),i.getBufferedValue()}Gt.exports=wn;Gt.exports.default=wn;Gt.exports.buffer=(s,e)=>wn(s,{...e,encoding:"buffer"});Gt.exports.array=(s,e)=>wn(s,{...e,array:!0});Gt.exports.MaxBufferError=vn});var Uu=$((NC,Du)=>{"use strict";var $_=new Set([200,203,204,206,300,301,308,404,405,410,414,501]),H_=new Set([200,203,204,300,301,302,303,307,308,404,405,410,414,501]),G_=new Set([500,502,503,504]),F_={date:!0,connection:!0,"keep-alive":!0,"proxy-authenticate":!0,"proxy-authorization":!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0},W_={"content-length":!0,"content-encoding":!0,"transfer-encoding":!0,"content-range":!0};function nt(s){let e=parseInt(s,10);return isFinite(e)?e:0}function V_(s){return s?G_.has(s.status):!0}function bi(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 z_(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(", ")}Du.exports=class{constructor(e,t,{shared:i,cacheHeuristic:a,immutableMinTimeToLive:c,ignoreCargoCult:h,_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=!!h,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=bi(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=bi(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":z_(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())&&H_.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||$_.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=bi(e.headers["cache-control"]);return t["no-cache"]||/no-cache/.test(e.headers.pragma)?this._evaluateRequestMissResult(e):t["max-age"]&&this.age()>nt(t["max-age"])?this._evaluateRequestMissResult(e):t["min-fresh"]&&this.maxAge()-this.age()<nt(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)F_[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 nt(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 nt(this._rescc["s-maxage"])}if(this._rescc["max-age"])return nt(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+nt(this._rescc["stale-if-error"]),i=e+nt(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()+nt(this._rescc["stale-if-error"])>this.age()}useStaleWhileRevalidate(){let e=nt(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()&&V_(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&&!W_[p]?t.headers[p]:this._resHeaders[p];let h=Object.assign({},t,{status:this._status,method:this._method,headers:c});return{policy:new this.constructor(e,h,a),modified:!1,matches:!0}}}});var Cn=$((LC,ju)=>{"use strict";ju.exports=s=>{let e={};for(let[t,i]of Object.entries(s))e[t.toLowerCase()]=i;return e}});var Bu=$((DC,qu)=>{"use strict";var K_=q("stream").Readable,J_=Cn(),vi=class extends K_{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=J_(t),this.body=i,this.url=a}_read(){this.push(this.body),this.push(null)}};qu.exports=vi});var Hu=$((UC,$u)=>{"use strict";var Y_=["destroy","setTimeout","socket","headers","trailers","rawHeaders","statusCode","httpVersion","httpVersionMinor","httpVersionMajor","rawTrailers","statusMessage"];$u.exports=(s,e)=>{let t=new Set(Object.keys(s).concat(Y_));for(let i of t)i in e||(e[i]=typeof s[i]=="function"?s[i].bind(s):s[i])}});var Fu=$((jC,Gu)=>{"use strict";var Q_=q("stream").PassThrough,X_=Hu(),Z_=s=>{if(!(s&&s.pipe))throw new TypeError("Parameter `response` must be a response stream.");let e=new Q_;return X_(s,e),s.pipe(e)};Gu.exports=Z_});var Wu=$(wi=>{wi.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 h=typeof e[c]=="function"||!i&&typeof e[c]>"u";Object.hasOwnProperty.call(e,c)&&!h&&(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)};wi.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 Ju=$((BC,Ku)=>{"use strict";var eb=q("events"),Vu=Wu(),tb=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},zu=["sqlite","postgres","mysql","mongo","redis","tiered"],Ci=class extends eb{constructor(e,{emitErrors:t=!0,...i}={}){if(super(),this.opts={namespace:"keyv",serialize:Vu.stringify,deserialize:Vu.parse,...typeof e=="string"?{uri:e}:e,...i},!this.opts.store){let c={...this.opts};this.opts.store=tb(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[h,p]of typeof c=="function"?c(this.opts.store.namespace):c){let g=await this.opts.deserialize(p);if(!(this.opts.store.namespace&&!h.includes(this.opts.store.namespace))){if(typeof g.expires=="number"&&Date.now()>g.expires){this.delete(h);continue}yield[this._getKeyUnprefix(h),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 zu.includes(this.opts.store.opts.dialect)||zu.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 h=[];for(let p of c)h.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(h).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(h=>typeof h=="string"?this.opts.deserialize(h):this.opts.compression?this.opts.deserialize(h):h).then(h=>{if(h!=null)return a?h.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 h.expires=="number"&&Date.now()>h.expires?this.delete(e).then(()=>{}):t&&t.raw?h:h.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 h=typeof i=="number"?Date.now()+i:null;return typeof t=="symbol"&&this.emit("error","symbol cannot be serialized"),t={value:t,expires:h},this.opts.serialize(t)}).then(h=>c.set(a,h,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 h of a)c.push(t.delete(h));return Promise.allSettled(c).then(h=>h.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()}};Ku.exports=Ci});var Xu=$((HC,Qu)=>{"use strict";var sb=q("events"),En=q("url"),nb=wu(),rb=Lu(),Ei=Uu(),Yu=Bu(),ib=Cn(),ob=Fu(),ab=Ju(),Cs=class s{constructor(e,t){if(typeof e!="function")throw new TypeError("Parameter `request` must be a function");return this.cache=new ab({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=ki(En.parse(t)),t={};else if(t instanceof En.URL)a=ki(En.parse(t.toString())),t={};else{let[w,...E]=(t.path||"").split("?"),O=E.length>0?`?${E.join("?")}`:"";a=ki({...t,pathname:w,search:O})}t={headers:{},method:"GET",cache:!0,strictTtl:!1,automaticFailover:!1,...t,...cb(a)},t.headers=ib(t.headers);let c=new sb,h=nb(En.format(a),{stripWWW:!1,removeTrailingSlash:!1,stripAuthentication:!1}),p=`${t.method}:${h}`,g=!1,m=!1,v=w=>{m=!0;let E=!1,O,A=new Promise(T=>{O=()=>{E||(E=!0,T())}}),k=T=>{if(g&&!w.forceRefresh){T.status=T.statusCode;let H=Ei.fromObject(g.cachePolicy).revalidatedPolicy(w,T);if(!H.modified){let V=H.policy.responseHeaders();T=new Yu(g.statusCode,V,g.body,g.url),T.cachePolicy=H.policy,T.fromCache=!0}}T.fromCache||(T.cachePolicy=new Ei(w,T,w),T.fromCache=!1);let N;w.cache&&T.cachePolicy.storable()?(N=ob(T),(async()=>{try{let H=rb.buffer(T);if(await Promise.race([A,new Promise(te=>T.once("end",te))]),E)return;let V=await H,Z={cachePolicy:T.cachePolicy.toObject(),url:T.url,statusCode:T.fromCache?g.statusCode:T.statusCode,body:V},Q=w.strictTtl?T.cachePolicy.timeToLive():void 0;w.maxTtl&&(Q=Q?Math.min(Q,w.maxTtl):w.maxTtl),await this.cache.set(p,Z,Q)}catch(H){c.emit("error",new s.CacheError(H))}})()):w.cache&&g&&(async()=>{try{await this.cache.delete(p)}catch(H){c.emit("error",new s.CacheError(H))}})(),c.emit("response",N||T),typeof i=="function"&&i(N||T)};try{let T=e(w,k);T.once("error",O),T.once("abort",O),c.emit("request",T)}catch(T){c.emit("error",new s.RequestError(T))}};return(async()=>{let w=async O=>{await Promise.resolve();let A=O.cache?await this.cache.get(p):void 0;if(typeof A>"u")return v(O);let k=Ei.fromObject(A.cachePolicy);if(k.satisfiesWithoutRevalidation(O)&&!O.forceRefresh){let T=k.responseHeaders(),N=new Yu(A.statusCode,T,A.body,A.url);N.cachePolicy=k,N.fromCache=!0,c.emit("response",N),typeof i=="function"&&i(N)}else g=A,O.headers=k.revalidationHeaders(O),v(O)},E=O=>c.emit("error",new s.CacheError(O));this.cache.once("error",E),c.on("response",()=>this.cache.removeListener("error",E));try{await w(t)}catch(O){t.automaticFailover&&!m&&v(t),c.emit("error",new s.CacheError(O))}})(),c}}};function cb(s){let e={...s};return e.path=`${s.pathname||"/"}${s.search||""}`,delete e.pathname,delete e.search,e}function ki(s){return{protocol:s.protocol,auth:s.auth,hostname:s.hostname||s.host||"localhost",port:s.port,pathname:s.pathname,search:s.search}}Cs.RequestError=class extends Error{constructor(s){super(s.message),this.name="RequestError",Object.assign(this,s)}};Cs.CacheError=class extends Error{constructor(s){super(s.message),this.name="CacheError",Object.assign(this,s)}};Qu.exports=Cs});var eh=$((WC,Zu)=>{"use strict";var lb=["aborted","complete","headers","httpVersion","httpVersionMinor","httpVersionMajor","method","rawHeaders","rawTrailers","setTimeout","socket","statusCode","statusMessage","trailers","url"];Zu.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(lb)),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 sh=$((VC,th)=>{"use strict";var{Transform:ub,PassThrough:hb}=q("stream"),Oi=q("zlib"),db=eh();th.exports=s=>{let e=(s.headers["content-encoding"]||"").toLowerCase();if(!["gzip","deflate","br"].includes(e))return s;let t=e==="br";if(t&&typeof Oi.createBrotliDecompress!="function")return s.destroy(new Error("Brotli is not supported on Node.js < 12")),s;let i=!0,a=new ub({transform(p,g,m){i=!1,m(null,p)},flush(p){p()}}),c=new hb({autoDestroy:!1,destroy(p,g){s.destroy(),g(p)}}),h=t?Oi.createBrotliDecompress():Oi.createUnzip();return h.once("error",p=>{if(i&&!s.readable){c.end();return}c.destroy(p)}),db(s,c),s.pipe(a).pipe(h).pipe(c),c}});var Ti=$((zC,nh)=>{"use strict";var Si=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)}};nh.exports=Si});var Ri=$((KC,ah)=>{"use strict";var fb=q("events"),pb=q("tls"),gb=q("http2"),mb=Ti(),Ce=Symbol("currentStreamsCount"),rh=Symbol("request"),xe=Symbol("cachedOriginSet"),Ft=Symbol("gracefullyClosing"),yb=["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"],_b=(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},bb=(s,e)=>s.remoteSettings.maxConcurrentStreams>e.remoteSettings.maxConcurrentStreams,Ai=(s,e)=>{for(let t of s)t[xe].length<e[xe].length&&t[xe].every(i=>e[xe].includes(i))&&t[Ce]+e[Ce]<=e.remoteSettings.maxConcurrentStreams&&oh(t)},vb=(s,e)=>{for(let t of s)e[xe].length<t[xe].length&&e[xe].every(i=>t[xe].includes(i))&&e[Ce]+t[Ce]<=t.remoteSettings.maxConcurrentStreams&&oh(e)},ih=({agent:s,isFree:e})=>{let t={};for(let i in s.sessions){let c=s.sessions[i].filter(h=>{let p=h[Et.kCurrentStreamsCount]<h.remoteSettings.maxConcurrentStreams;return e?p:!p});c.length!==0&&(t[i]=c)}return t},oh=s=>{s[Ft]=!0,s[Ce]===0&&s.close()},Et=class s extends fb{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 mb({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 yb)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 h=this.normalizeOptions(t),p=s.normalizeOrigin(e,t&&t.servername);if(p===void 0){for(let{reject:v}of i)v(new TypeError("The `origin` argument needs to be a string or an URL object"));return}if(h in this.sessions){let v=this.sessions[h],w=-1,E=-1,O;for(let A of v){let k=A.remoteSettings.maxConcurrentStreams;if(k<w)break;if(A[xe].includes(p)){let T=A[Ce];if(T>=k||A[Ft]||A.destroyed)continue;O||(w=k),T>E&&(O=A,E=T)}}if(O){if(i.length!==1){for(let{reject:A}of i){let k=new Error(`Expected the length of listeners to be 1, got ${i.length}.
|
|
34
|
-
Please report this to https://github.com/szmarczak/http2-wrapper/`);A(k)}return}i[0].resolve(O);return}}if(h in this.queue){if(p in this.queue[h]){this.queue[h][p].listeners.push(...i),this._tryToCreateNewSession(h,p);return}}else this.queue[h]={};let g=()=>{h in this.queue&&this.queue[h][p]===m&&(delete this.queue[h][p],Object.keys(this.queue[h]).length===0&&delete this.queue[h])},m=()=>{let v=`${p}:${h}`,w=!1;try{let E=gb.connect(e,{createConnection:this.createConnection,settings:this.settings,session:this.tlsSessionCache.get(v),...t});E[Ce]=0,E[Ft]=!1;let O=()=>E[Ce]<E.remoteSettings.maxConcurrentStreams,A=!0;E.socket.once("session",T=>{this.tlsSessionCache.set(v,T)}),E.once("error",T=>{for(let{reject:N}of i)N(T);this.tlsSessionCache.delete(v)}),E.setTimeout(this.timeout,()=>{E.destroy()}),E.once("close",()=>{if(w){A&&this._freeSessionsCount--,this._sessionsCount--;let T=this.sessions[h];T.splice(T.indexOf(E),1),T.length===0&&delete this.sessions[h]}else{let T=new Error("Session closed without receiving a SETTINGS frame");T.code="HTTP2WRAPPER_NOSETTINGS";for(let{reject:N}of i)N(T);g()}this._tryToCreateNewSession(h,p)});let k=()=>{if(!(!(h in this.queue)||!O())){for(let T of E[xe])if(T in this.queue[h]){let{listeners:N}=this.queue[h][T];for(;N.length!==0&&O();)N.shift().resolve(E);let H=this.queue[h];if(H[T].listeners.length===0&&(delete H[T],Object.keys(H).length===0)){delete this.queue[h];break}if(!O())break}}};E.on("origin",()=>{E[xe]=E.originSet,O()&&(k(),Ai(this.sessions[h],E))}),E.once("remoteSettings",()=>{if(E.ref(),E.unref(),this._sessionsCount++,m.destroyed){let T=new Error("Agent has been destroyed");for(let N of i)N.reject(T);E.destroy();return}E[xe]=E.originSet;{let T=this.sessions;if(h in T){let N=T[h];N.splice(_b(N,E,bb),0,E)}else T[h]=[E]}this._freeSessionsCount+=1,w=!0,this.emit("session",E),k(),g(),E[Ce]===0&&this._freeSessionsCount>this.maxFreeSessions&&E.close(),i.length!==0&&(this.getSession(p,t,i),i.length=0),E.on("remoteSettings",()=>{k(),Ai(this.sessions[h],E)})}),E[rh]=E.request,E.request=(T,N)=>{if(E[Ft])throw new Error("The session is gracefully closing. No new streams are allowed.");let H=E[rh](T,N);return E.ref(),++E[Ce],E[Ce]===E.remoteSettings.maxConcurrentStreams&&this._freeSessionsCount--,H.once("close",()=>{if(A=O(),--E[Ce],!E.destroyed&&!E.closed&&(vb(this.sessions[h],E),O()&&!E.closed)){A||(this._freeSessionsCount++,A=!0);let V=E[Ce]===0;V&&E.unref(),V&&(this._freeSessionsCount>this.maxFreeSessions||E[Ft])?E.close():(Ai(this.sessions[h],E),k())}}),H}}catch(E){for(let O of i)O.reject(E);g()}};m.listeners=i,m.completed=!1,m.destroyed=!1,this.queue[h][p]=m,this._tryToCreateNewSession(h,p)})}request(e,t,i,a){return new Promise((c,h)=>{this.getSession(e,t,[{reject:h,resolve:p=>{try{c(p.request(i,a))}catch(g){h(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),pb.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 ih({agent:this,isFree:!0})}get busySessions(){return ih({agent:this,isFree:!1})}};Et.kCurrentStreamsCount=Ce;Et.kGracefullyClosing=Ft;ah.exports={Agent:Et,globalAgent:new Et}});var Ii=$((JC,ch)=>{"use strict";var{Readable:wb}=q("stream"),Pi=class extends wb{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()}};ch.exports=Pi});var Mi=$((YC,lh)=>{"use strict";lh.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 hh=$((QC,uh)=>{"use strict";uh.exports=(s,e,t)=>{for(let i of t)s.on(i,(...a)=>e.emit(i,...a))}});var fh=$((XC,dh)=>{"use strict";dh.exports=s=>{switch(s){case":method":case":scheme":case":authority":case":path":return!0;default:return!1}}});var gh=$((e0,ph)=>{"use strict";var Wt=(s,e,t)=>{ph.exports[e]=class extends s{constructor(...a){super(typeof t=="string"?t:t(a)),this.name=`${super.name} [${e}]`,this.code=e}}};Wt(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]}`});Wt(TypeError,"ERR_INVALID_PROTOCOL",s=>`Protocol "${s[0]}" not supported. Expected "${s[1]}"`);Wt(Error,"ERR_HTTP_HEADERS_SENT",s=>`Cannot ${s[0]} headers after they are sent to the client`);Wt(TypeError,"ERR_INVALID_HTTP_TOKEN",s=>`${s[0]} must be a valid HTTP token [${s[1]}]`);Wt(TypeError,"ERR_HTTP_INVALID_HEADER_VALUE",s=>`Invalid value "${s[0]} for header "${s[1]}"`);Wt(TypeError,"ERR_INVALID_CHAR",s=>`Invalid character in ${s[0]} [${s[1]}]`)});var Ui=$((t0,Ch)=>{"use strict";var Cb=q("http2"),{Writable:Eb}=q("stream"),{Agent:mh,globalAgent:kb}=Ri(),Ob=Ii(),Sb=Mi(),Tb=hh(),Ab=fh(),{ERR_INVALID_ARG_TYPE:xi,ERR_INVALID_PROTOCOL:Rb,ERR_HTTP_HEADERS_SENT:yh,ERR_INVALID_HTTP_TOKEN:Pb,ERR_HTTP_INVALID_HEADER_VALUE:Ib,ERR_INVALID_CHAR:Mb}=gh(),{HTTP2_HEADER_STATUS:_h,HTTP2_HEADER_METHOD:bh,HTTP2_HEADER_PATH:vh,HTTP2_METHOD_CONNECT:xb}=Cb.constants,be=Symbol("headers"),Ni=Symbol("origin"),Li=Symbol("session"),wh=Symbol("options"),kn=Symbol("flushedHeaders"),Es=Symbol("jobs"),Nb=/^[\^`\-\w!#$%&*+.|~]+$/,Lb=/[^\t\u0020-\u007E\u0080-\u00FF]/,Di=class extends Eb{constructor(e,t,i){super({autoDestroy:!1});let a=typeof e=="string"||e instanceof URL;if(a&&(e=Sb(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[Li]=t.h2session;else if(t.agent===!1)this.agent=new mh({maxFreeSessions:0});else if(typeof t.agent>"u"||t.agent===null)typeof t.createConnection=="function"?(this.agent=new mh({maxFreeSessions:0}),this.agent.createConnection=t.createConnection):this.agent=kb;else if(typeof t.agent.request=="function")this.agent=t.agent;else throw new xi("options.agent",["Agent-like Object","undefined","false"],t.agent);if(t.protocol&&t.protocol!=="https:")throw new Rb(t.protocol,"https:");let c=t.port||t.defaultPort||this.agent&&this.agent.defaultPort||443,h=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[Es]=[],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[wh]=t,c===443?(this[Ni]=`https://${h}`,":authority"in this[be]||(this[be][":authority"]=h)):(this[Ni]=`https://${h}:${c}`,":authority"in this[be]||(this[be][":authority"]=`${h}:${c}`)),p&&this.setTimeout(p),i&&this.once("response",i),this[kn]=!1}get method(){return this[be][bh]}set method(e){e&&(this[be][bh]=e.toUpperCase())}get path(){return this[be][vh]}set path(e){e&&(this[be][vh]=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[Es].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[Es].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[kn]||this.destroyed)return;this[kn]=!0;let e=this.method===xb,t=i=>{if(this._request=i,this.destroyed){i.destroy();return}e||Tb(i,this,["timeout","continue","close","error"]);let a=h=>(...p)=>{!this.writable&&!this.destroyed?h(...p):this.once("finish",()=>{h(...p)})};i.once("response",a((h,p,g)=>{let m=new Ob(this.socket,i.readableHighWaterMark);this.res=m,m.req=this,m.statusCode=h[_h],m.headers=h,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",v=>{!m._dumped&&!m.push(v)&&i.pause()}),i.once("end",()=>{m.push(null)}),this.emit("response",m)||m._dump())})),i.once("headers",a(h=>this.emit("information",{statusCode:h[_h]}))),i.once("trailers",a((h,p,g)=>{let{res:m}=this;m.trailers=h,m.rawTrailers=g}));let{socket:c}=i.session;this.socket=c,this.connection=c;for(let h of this[Es])h();this.emit("socket",this.socket)};if(this[Li])try{t(this[Li].request(this[be]))}catch(i){this.emit("error",i)}else{this.reusedSocket=!0;try{t(await this.agent.request(this[Ni],this[wh],this[be]))}catch(i){this.emit("error",i)}}}getHeader(e){if(typeof e!="string")throw new xi("name","string",e);return this[be][e.toLowerCase()]}get headersSent(){return this[kn]}removeHeader(e){if(typeof e!="string")throw new xi("name","string",e);if(this.headersSent)throw new yh("remove");delete this[be][e.toLowerCase()]}setHeader(e,t){if(this.headersSent)throw new yh("set");if(typeof e!="string"||!Nb.test(e)&&!Ab(e))throw new Pb("Header name",e);if(typeof t>"u")throw new Ib(t,e);if(Lb.test(t))throw new Mb("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[Es].push(i),this}get maxHeadersCount(){if(!this.destroyed&&this._request)return this._request.session.localSettings.maxHeaderListSize}set maxHeadersCount(e){}};Ch.exports=Di});var kh=$((s0,Eh)=>{"use strict";var Db=q("tls");Eh.exports=(s={},e=Db.connect)=>new Promise((t,i)=>{let a=!1,c,h=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,h()},g=(async()=>{try{c=await e(s,h),c.on("error",i),c.once("timeout",p)}catch(m){i(m)}})()})});var Sh=$((n0,Oh)=>{"use strict";var Ub=q("net");Oh.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]),Ub.isIP(e)?"":e}});var Rh=$((r0,qi)=>{"use strict";var Th=q("http"),ji=q("https"),jb=kh(),qb=Ti(),Bb=Ui(),$b=Sh(),Hb=Mi(),On=new qb({maxSize:100}),ks=new Map,Ah=(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)},Gb=async s=>{let e=`${s.host}:${s.port}:${s.ALPNProtocols.sort()}`;if(!On.has(e)){if(ks.has(e))return(await ks.get(e)).alpnProtocol;let{path:t,agent:i}=s;s.path=s.socketPath;let a=jb(s);ks.set(e,a);try{let{socket:c,alpnProtocol:h}=await a;if(On.set(e,h),s.path=t,h==="h2")c.destroy();else{let{globalAgent:p}=ji,g=ji.Agent.prototype.createConnection;i?i.createConnection===g?Ah(i,c,s):c.destroy():p.createConnection===g?Ah(p,c,s):c.destroy()}return ks.delete(e),h}catch(c){throw ks.delete(e),c}}return On.get(e)};qi.exports=async(s,e,t)=>{if((typeof s=="string"||s instanceof URL)&&(s=Hb(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||$b(e),e.port=e.port||(i?443:80),e._defaultAgent=i?ji.globalAgent:Th.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 Gb(e)==="h2"?(a&&(e.agent=a.http2),new Bb(e,t)):Th.request(e,t)};qi.exports.protocolCache=On});var Ih=$((i0,Ph)=>{"use strict";var Fb=q("http2"),Wb=Ri(),Bi=Ui(),Vb=Ii(),zb=Rh(),Kb=(s,e,t)=>new Bi(s,e,t),Jb=(s,e,t)=>{let i=new Bi(s,e,t);return i.end(),i};Ph.exports={...Fb,ClientRequest:Bi,IncomingMessage:Vb,...Wb,request:Kb,get:Jb,auto:zb}});var Hi=$($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});var Mh=st();$i.default=s=>Mh.default.nodeStream(s)&&Mh.default.function_(s.getBoundary)});var Dh=$(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});var Nh=q("fs"),Lh=q("util"),xh=st(),Yb=Hi(),Qb=Lh.promisify(Nh.stat);Gi.default=async(s,e)=>{if(e&&"content-length"in e)return Number(e["content-length"]);if(!s)return 0;if(xh.default.string(s))return Buffer.byteLength(s);if(xh.default.buffer(s))return s.length;if(Yb.default(s))return Lh.promisify(s.getLength.bind(s))();if(s instanceof Nh.ReadStream){let{size:t}=await Qb(s.path);return t===0?void 0:t}}});var Wi=$(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});function Xb(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])}}Fi.default=Xb});var Uh=$(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.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 qh=$(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.TimeoutError=void 0;var Zb=q("net"),ev=Uh(),jh=Symbol("reentry"),tv=()=>{},Sn=class extends Error{constructor(e,t){super(`Timeout awaiting '${t}' for ${e}ms`),this.event=t,this.name="TimeoutError",this.code="ETIMEDOUT"}};Os.TimeoutError=Sn;Os.default=(s,e,t)=>{if(jh in s)return tv;s[jh]=!0;let i=[],{once:a,unhandleAll:c}=ev.default(),h=(w,E,O)=>{var A;let k=setTimeout(E,w,w,O);(A=k.unref)===null||A===void 0||A.call(k);let T=()=>{clearTimeout(k)};return i.push(T),T},{host:p,hostname:g}=t,m=(w,E)=>{s.destroy(new Sn(w,E))},v=()=>{for(let w of i)w();c()};if(s.once("error",w=>{if(v(),s.listenerCount("error")===0)throw w}),s.once("close",v),a(s,"response",w=>{a(w,"end",v)}),typeof e.request<"u"&&h(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 E;let{socketPath:O}=s;if(w.connecting){let A=!!(O??Zb.isIP((E=g??p)!==null&&E!==void 0?E:"")!==0);if(typeof e.lookup<"u"&&!A&&typeof w.address().address>"u"){let k=h(e.lookup,m,"lookup");a(w,"lookup",k)}if(typeof e.connect<"u"){let k=()=>h(e.connect,m,"connect");A?a(w,"connect",k()):a(w,"lookup",T=>{T===null&&a(w,"connect",k())})}typeof e.secureConnect<"u"&&t.protocol==="https:"&&a(w,"connect",()=>{let k=h(e.secureConnect,m,"secureConnect");a(w,"secureConnect",k)})}if(typeof e.send<"u"){let A=()=>h(e.send,m,"send");w.connecting?a(w,"connect",()=>{a(s,"upload-complete",A())}):a(s,"upload-complete",A())}}),typeof e.response<"u"&&a(s,"upload-complete",()=>{let w=h(e.response,m,"response");a(s,"response",w)}),v}});var $h=$(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});var Bh=st();zi.default=s=>{s=s;let e={protocol:s.protocol,hostname:Bh.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 Bh.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 Hh=$(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});var sv=q("url"),nv=["protocol","host","hostname","port","pathname","search"];Ki.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 sv.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 nv)e[c]&&(a[c]=e[c].toString());return a}});var Gh=$(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});var Ji=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)}};Yi.default=Ji});var Xi=$(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});var rv=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(""))};Qi.default=rv});var Wh=$(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.dnsLookupIpVersionToFamily=kt.isDnsLookupIpVersion=void 0;var Fh={auto:0,ipv4:4,ipv6:6};kt.isDnsLookupIpVersion=s=>s in Fh;kt.dnsLookupIpVersionToFamily=s=>{if(kt.isDnsLookupIpVersion(s))return Fh[s];throw new Error("Invalid DNS lookup IP version")}});var Zi=$(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.isResponseOk=void 0;Tn.isResponseOk=s=>{let{statusCode:e}=s,t=s.request.options.followRedirect?299:399;return e>=200&&e<=t||e===304}});var zh=$(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});var Vh=new Set;eo.default=s=>{Vh.has(s)||(Vh.add(s),process.emitWarning(`Got: ${s}`,{type:"DeprecationWarning"}))}});var Kh=$(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});var re=st(),iv=(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};to.default=iv});var Jh=$(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.retryAfterStatusCodes=void 0;Ss.retryAfterStatusCodes=new Set([413,429,503]);var ov=({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),h=t.response&&e.statusCodes.includes(t.response.statusCode);if(!a||!c&&!h)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};Ss.default=ov});var Rs=$(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.UnsupportedProtocolError=X.ReadError=X.TimeoutError=X.UploadError=X.CacheError=X.HTTPError=X.MaxRedirectsError=X.RequestError=X.setNonEnumerableProperties=X.knownHookEvents=X.withoutBody=X.kIsNormalizedAlready=void 0;var Yh=q("util"),Qh=q("stream"),av=q("fs"),ht=q("url"),Xh=q("http"),so=q("http"),cv=q("https"),lv=hu(),uv=_u(),Zh=Xu(),hv=sh(),dv=Ih(),fv=Cn(),M=st(),pv=Dh(),ed=Hi(),gv=Wi(),td=qh(),mv=$h(),sd=Hh(),yv=Gh(),_v=Xi(),nd=Wh(),bv=Zi(),dt=zh(),vv=Kh(),wv=Jh(),no,pe=Symbol("request"),Pn=Symbol("response"),Vt=Symbol("responseSize"),zt=Symbol("downloadedSize"),Kt=Symbol("bodySize"),Jt=Symbol("uploadedSize"),An=Symbol("serverResponsesPiped"),rd=Symbol("unproxyEvents"),id=Symbol("isFromCache"),ro=Symbol("cancelTimeouts"),od=Symbol("startedReading"),Yt=Symbol("stopReading"),Rn=Symbol("triggerRead"),ft=Symbol("body"),Ts=Symbol("jobs"),ad=Symbol("originalResponse"),cd=Symbol("retryTimeout");X.kIsNormalizedAlready=Symbol("isNormalizedAlready");var Cv=M.default.string(process.versions.brotli);X.withoutBody=new Set(["GET","HEAD"]);X.knownHookEvents=["init","beforeRequest","beforeRedirect","beforeError","beforeRetry","afterResponse"];function Ev(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 kv(s){return M.default.object(s)&&!("statusCode"in s)}var io=new yv.default,Ov=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()})}),Sv=new Set([300,301,302,303,304,307,308]),Tv=["context","body","json","form"];X.setNonEnumerableProperties=(s,e)=>{let t={};for(let i of s)if(i)for(let a of Tv)a in i&&(t[a]={writable:!0,configurable:!0,enumerable:!1,value:i[a]});Object.defineProperties(e,t)};var ce=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 Un?(Object.defineProperty(this,"request",{enumerable:!1,value:i}),Object.defineProperty(this,"response",{enumerable:!1,value:i[Pn]}),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 h=this.stack.indexOf(this.message)+this.message.length,p=this.stack.slice(h).split(`
|
|
33
|
+
`+t)}function Et(s,e,t,i,a,c){if(s.listenerCount("wsClientError")){let h=new Error(a);Error.captureStackTrace(h,Et),s.emit("wsClientError",h,t,e)}else vs(t,i,a,c)}});var fn=$((EC,ru)=>{"use strict";var nt=hn();nt.createWebSocketStream=Kl();nt.Server=nu();nt.Receiver=Yr();nt.Sender=Zr();nt.WebSocket=nt;nt.WebSocketServer=nt.Server;ru.exports=nt});var it=$((rt,pn)=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});var iu=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Qy(s){return iu.includes(s)}var Xy=["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",...iu];function Zy(s){return Xy.includes(s)}var e_=["null","undefined","string","number","bigint","boolean","symbol"];function t_(s){return e_.includes(s)}function Ht(s){return e=>typeof e===s}var{toString:ou}=Object.prototype,ws=s=>{let e=ou.call(s).slice(8,-1);if(/HTML\w+Element/.test(e)&&b.domElement(s))return"HTMLElement";if(Zy(e))return e},re=s=>e=>ws(e)===s;function b(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(b.observable(s))return"Observable";if(b.array(s))return"Array";if(b.buffer(s))return"Buffer";let e=ws(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"}b.undefined=Ht("undefined");b.string=Ht("string");var s_=Ht("number");b.number=s=>s_(s)&&!b.nan(s);b.bigint=Ht("bigint");b.function_=Ht("function");b.null_=s=>s===null;b.class_=s=>b.function_(s)&&s.toString().startsWith("class ");b.boolean=s=>s===!0||s===!1;b.symbol=Ht("symbol");b.numericString=s=>b.string(s)&&!b.emptyStringOrWhitespace(s)&&!Number.isNaN(Number(s));b.array=(s,e)=>Array.isArray(s)?b.function_(e)?s.every(e):!0:!1;b.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};b.blob=s=>re("Blob")(s);b.nullOrUndefined=s=>b.null_(s)||b.undefined(s);b.object=s=>!b.null_(s)&&(typeof s=="object"||b.function_(s));b.iterable=s=>{var e;return b.function_((e=s)===null||e===void 0?void 0:e[Symbol.iterator])};b.asyncIterable=s=>{var e;return b.function_((e=s)===null||e===void 0?void 0:e[Symbol.asyncIterator])};b.generator=s=>{var e,t;return b.iterable(s)&&b.function_((e=s)===null||e===void 0?void 0:e.next)&&b.function_((t=s)===null||t===void 0?void 0:t.throw)};b.asyncGenerator=s=>b.asyncIterable(s)&&b.function_(s.next)&&b.function_(s.throw);b.nativePromise=s=>re("Promise")(s);var n_=s=>{var e,t;return b.function_((e=s)===null||e===void 0?void 0:e.then)&&b.function_((t=s)===null||t===void 0?void 0:t.catch)};b.promise=s=>b.nativePromise(s)||n_(s);b.generatorFunction=re("GeneratorFunction");b.asyncGeneratorFunction=s=>ws(s)==="AsyncGeneratorFunction";b.asyncFunction=s=>ws(s)==="AsyncFunction";b.boundFunction=s=>b.function_(s)&&!s.hasOwnProperty("prototype");b.regExp=re("RegExp");b.date=re("Date");b.error=re("Error");b.map=s=>re("Map")(s);b.set=s=>re("Set")(s);b.weakMap=s=>re("WeakMap")(s);b.weakSet=s=>re("WeakSet")(s);b.int8Array=re("Int8Array");b.uint8Array=re("Uint8Array");b.uint8ClampedArray=re("Uint8ClampedArray");b.int16Array=re("Int16Array");b.uint16Array=re("Uint16Array");b.int32Array=re("Int32Array");b.uint32Array=re("Uint32Array");b.float32Array=re("Float32Array");b.float64Array=re("Float64Array");b.bigInt64Array=re("BigInt64Array");b.bigUint64Array=re("BigUint64Array");b.arrayBuffer=re("ArrayBuffer");b.sharedArrayBuffer=re("SharedArrayBuffer");b.dataView=re("DataView");b.enumCase=(s,e)=>Object.values(e).includes(s);b.directInstanceOf=(s,e)=>Object.getPrototypeOf(s)===e.prototype;b.urlInstance=s=>re("URL")(s);b.urlString=s=>{if(!b.string(s))return!1;try{return new URL(s),!0}catch{return!1}};b.truthy=s=>!!s;b.falsy=s=>!s;b.nan=s=>Number.isNaN(s);b.primitive=s=>b.null_(s)||t_(typeof s);b.integer=s=>Number.isInteger(s);b.safeInteger=s=>Number.isSafeInteger(s);b.plainObject=s=>{if(ou.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||e===Object.getPrototypeOf({})};b.typedArray=s=>Qy(ws(s));var r_=s=>b.safeInteger(s)&&s>=0;b.arrayLike=s=>!b.nullOrUndefined(s)&&!b.function_(s)&&r_(s.length);b.inRange=(s,e)=>{if(b.number(e))return s>=Math.min(0,e)&&s<=Math.max(e,0);if(b.array(e)&&e.length===2)return s>=Math.min(...e)&&s<=Math.max(...e);throw new TypeError(`Invalid range: ${JSON.stringify(e)}`)};var i_=1,o_=["innerHTML","ownerDocument","style","attributes","nodeValue"];b.domElement=s=>b.object(s)&&s.nodeType===i_&&b.string(s.nodeName)&&!b.plainObject(s)&&o_.every(e=>e in s);b.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};b.nodeStream=s=>b.object(s)&&b.function_(s.pipe)&&!b.observable(s);b.infinite=s=>s===1/0||s===-1/0;var au=s=>e=>b.integer(e)&&Math.abs(e%2)===s;b.evenInteger=au(0);b.oddInteger=au(1);b.emptyArray=s=>b.array(s)&&s.length===0;b.nonEmptyArray=s=>b.array(s)&&s.length>0;b.emptyString=s=>b.string(s)&&s.length===0;var a_=s=>b.string(s)&&!/\S/.test(s);b.emptyStringOrWhitespace=s=>b.emptyString(s)||a_(s);b.nonEmptyString=s=>b.string(s)&&s.length>0;b.nonEmptyStringAndNotWhitespace=s=>b.string(s)&&!b.emptyStringOrWhitespace(s);b.emptyObject=s=>b.object(s)&&!b.map(s)&&!b.set(s)&&Object.keys(s).length===0;b.nonEmptyObject=s=>b.object(s)&&!b.map(s)&&!b.set(s)&&Object.keys(s).length>0;b.emptySet=s=>b.set(s)&&s.size===0;b.nonEmptySet=s=>b.set(s)&&s.size>0;b.emptyMap=s=>b.map(s)&&s.size===0;b.nonEmptyMap=s=>b.map(s)&&s.size>0;b.propertyKey=s=>b.any([b.string,b.number,b.symbol],s);b.formData=s=>re("FormData")(s);b.urlSearchParams=s=>re("URLSearchParams")(s);var cu=(s,e,t)=>{if(!b.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)};b.any=(s,...e)=>(b.array(s)?s:[s]).some(i=>cu(Array.prototype.some,i,e));b.all=(s,...e)=>cu(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(h=>`\`${b(h)}\``))].join(", ")}`:`received value of type \`${b(t)}\``;throw new TypeError(`Expected value which is \`${e}\`, ${c}.`)}};rt.assert={undefined:s=>B(b.undefined(s),"undefined",s),string:s=>B(b.string(s),"string",s),number:s=>B(b.number(s),"number",s),bigint:s=>B(b.bigint(s),"bigint",s),function_:s=>B(b.function_(s),"Function",s),null_:s=>B(b.null_(s),"null",s),class_:s=>B(b.class_(s),"Class",s),boolean:s=>B(b.boolean(s),"boolean",s),symbol:s=>B(b.symbol(s),"symbol",s),numericString:s=>B(b.numericString(s),"string with a number",s),array:(s,e)=>{B(b.array(s),"Array",s),e&&s.forEach(e)},buffer:s=>B(b.buffer(s),"Buffer",s),blob:s=>B(b.blob(s),"Blob",s),nullOrUndefined:s=>B(b.nullOrUndefined(s),"null or undefined",s),object:s=>B(b.object(s),"Object",s),iterable:s=>B(b.iterable(s),"Iterable",s),asyncIterable:s=>B(b.asyncIterable(s),"AsyncIterable",s),generator:s=>B(b.generator(s),"Generator",s),asyncGenerator:s=>B(b.asyncGenerator(s),"AsyncGenerator",s),nativePromise:s=>B(b.nativePromise(s),"native Promise",s),promise:s=>B(b.promise(s),"Promise",s),generatorFunction:s=>B(b.generatorFunction(s),"GeneratorFunction",s),asyncGeneratorFunction:s=>B(b.asyncGeneratorFunction(s),"AsyncGeneratorFunction",s),asyncFunction:s=>B(b.asyncFunction(s),"AsyncFunction",s),boundFunction:s=>B(b.boundFunction(s),"Function",s),regExp:s=>B(b.regExp(s),"RegExp",s),date:s=>B(b.date(s),"Date",s),error:s=>B(b.error(s),"Error",s),map:s=>B(b.map(s),"Map",s),set:s=>B(b.set(s),"Set",s),weakMap:s=>B(b.weakMap(s),"WeakMap",s),weakSet:s=>B(b.weakSet(s),"WeakSet",s),int8Array:s=>B(b.int8Array(s),"Int8Array",s),uint8Array:s=>B(b.uint8Array(s),"Uint8Array",s),uint8ClampedArray:s=>B(b.uint8ClampedArray(s),"Uint8ClampedArray",s),int16Array:s=>B(b.int16Array(s),"Int16Array",s),uint16Array:s=>B(b.uint16Array(s),"Uint16Array",s),int32Array:s=>B(b.int32Array(s),"Int32Array",s),uint32Array:s=>B(b.uint32Array(s),"Uint32Array",s),float32Array:s=>B(b.float32Array(s),"Float32Array",s),float64Array:s=>B(b.float64Array(s),"Float64Array",s),bigInt64Array:s=>B(b.bigInt64Array(s),"BigInt64Array",s),bigUint64Array:s=>B(b.bigUint64Array(s),"BigUint64Array",s),arrayBuffer:s=>B(b.arrayBuffer(s),"ArrayBuffer",s),sharedArrayBuffer:s=>B(b.sharedArrayBuffer(s),"SharedArrayBuffer",s),dataView:s=>B(b.dataView(s),"DataView",s),enumCase:(s,e)=>B(b.enumCase(s,e),"EnumCase",s),urlInstance:s=>B(b.urlInstance(s),"URL",s),urlString:s=>B(b.urlString(s),"string with a URL",s),truthy:s=>B(b.truthy(s),"truthy",s),falsy:s=>B(b.falsy(s),"falsy",s),nan:s=>B(b.nan(s),"NaN",s),primitive:s=>B(b.primitive(s),"primitive",s),integer:s=>B(b.integer(s),"integer",s),safeInteger:s=>B(b.safeInteger(s),"integer",s),plainObject:s=>B(b.plainObject(s),"plain object",s),typedArray:s=>B(b.typedArray(s),"TypedArray",s),arrayLike:s=>B(b.arrayLike(s),"array-like",s),domElement:s=>B(b.domElement(s),"HTMLElement",s),observable:s=>B(b.observable(s),"Observable",s),nodeStream:s=>B(b.nodeStream(s),"Node.js Stream",s),infinite:s=>B(b.infinite(s),"infinite number",s),emptyArray:s=>B(b.emptyArray(s),"empty array",s),nonEmptyArray:s=>B(b.nonEmptyArray(s),"non-empty array",s),emptyString:s=>B(b.emptyString(s),"empty string",s),emptyStringOrWhitespace:s=>B(b.emptyStringOrWhitespace(s),"empty string or whitespace",s),nonEmptyString:s=>B(b.nonEmptyString(s),"non-empty string",s),nonEmptyStringAndNotWhitespace:s=>B(b.nonEmptyStringAndNotWhitespace(s),"non-empty string and not whitespace",s),emptyObject:s=>B(b.emptyObject(s),"empty object",s),nonEmptyObject:s=>B(b.nonEmptyObject(s),"non-empty object",s),emptySet:s=>B(b.emptySet(s),"empty set",s),nonEmptySet:s=>B(b.nonEmptySet(s),"non-empty set",s),emptyMap:s=>B(b.emptyMap(s),"empty map",s),nonEmptyMap:s=>B(b.nonEmptyMap(s),"non-empty map",s),propertyKey:s=>B(b.propertyKey(s),"PropertyKey",s),formData:s=>B(b.formData(s),"FormData",s),urlSearchParams:s=>B(b.urlSearchParams(s),"URLSearchParams",s),evenInteger:s=>B(b.evenInteger(s),"even integer",s),oddInteger:s=>B(b.oddInteger(s),"odd integer",s),directInstanceOf:(s,e)=>B(b.directInstanceOf(s,e),"T",s),inRange:(s,e)=>B(b.inRange(s,e),"in range",s),any:(s,...e)=>B(b.any(s,...e),"predicate returns truthy for any value",e,{multipleValues:!0}),all:(s,...e)=>B(b.all(s,...e),"predicate returns truthy for all values",e,{multipleValues:!0})};Object.defineProperties(b,{class:{value:b.class_},function:{value:b.function_},null:{value:b.null_}});Object.defineProperties(rt.assert,{class:{value:rt.assert.class_},function:{value:rt.assert.function_},null:{value:rt.assert.null_}});rt.default=b;pn.exports=b;pn.exports.default=b;pn.exports.assert=rt.assert});var lu=$((kC,ai)=>{"use strict";var gn=class extends Error{constructor(e){super(e||"Promise was canceled"),this.name="CancelError"}get isCanceled(){return!0}},mn=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||!h.shouldReject)&&(this._isPending=!1,t(p))},c=p=>{this._isPending=!1,i(p)},h=p=>{if(!this._isPending)throw new Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(p)};return Object.defineProperties(h,{shouldReject:{get:()=>this._rejectOnCancel,set:p=>{this._rejectOnCancel=p}}}),e(a,c,h)})}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 gn(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(mn.prototype,Promise.prototype);ai.exports=mn;ai.exports.CancelError=gn});var uu=$((li,ui)=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});function c_(s){return s.encrypted}var ci=(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",h=()=>{i&&t.connect(),c_(s)&&a&&(s.authorized?t.secureConnect():s.authorizationError||s.once("secureConnect",t.secureConnect)),c&&s.once("close",t.close)};s.writable&&!s.connecting?h():s.connecting?s.once("connect",h):s.destroyed&&c&&t.close(s._hadError)};li.default=ci;ui.exports=ci;ui.exports.default=ci});var hu=$((di,fi)=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});var l_=uu(),u_=q("util"),h_=Number(process.versions.node.split(".")[0]),hi=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,...v)=>(m==="error"&&(e.error=Date.now(),e.phases.total=e.error-e.start,p.emit=g),g(m,...v))};t(s);let i=()=>{e.abort=Date.now(),(!e.response||h_>=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,u_.types.isProxy(p))return;let g=()=>{e.lookup=Date.now(),e.phases.dns=e.lookup-e.socket};p.prependOnceListener("lookup",g),l_.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};di.default=hi;fi.exports=hi;fi.exports.default=hi});var _u=$((OC,mi)=>{"use strict";var{V4MAPPED:d_,ADDRCONFIG:f_,ALL:yu,promises:{Resolver:du},lookup:p_}=q("dns"),{promisify:pi}=q("util"),g_=q("os"),Gt=Symbol("cacheableLookupCreateConnection"),gi=Symbol("cacheableLookupInstance"),fu=Symbol("expires"),m_=typeof yu=="number",pu=s=>{if(!(s&&typeof s.createConnection=="function"))throw new Error("Expected an Agent instance as the first argument")},y_=s=>{for(let e of s)e.family!==6&&(e.address=`::ffff:${e.address}`,e.family=6)},gu=()=>{let s=!1,e=!1;for(let t of Object.values(g_.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}},__=s=>Symbol.iterator in s,mu={ttl:!0},b_={all:!0},yn=class{constructor({cache:e=new Map,maxTtl:t=1/0,fallbackDuration:i=3600,errorTtl:a=.15,resolver:c=new du,lookup:h=p_}={}){if(this.maxTtl=t,this.errorTtl=a,this._cache=e,this._resolver=c,this._dnsLookup=pi(h),this._resolver instanceof du?(this._resolve4=this._resolver.resolve4.bind(this._resolver),this._resolve6=this._resolver.resolve6.bind(this._resolver)):(this._resolve4=pi(this._resolver.resolve4.bind(this._resolver)),this._resolve6=pi(this._resolver.resolve6.bind(this._resolver))),this._iface=gu(),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&d_&&(m_&&t.hints&yu||a.length===0)?y_(i):i=a}else t.family===4&&(i=i.filter(a=>a.family===4));if(t.hints&f_){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(v){if(v.code==="ENODATA"||v.code==="ENOTFOUND")return[];throw v}},[i,a]=await Promise.all([this._resolve4(e,mu),this._resolve6(e,mu)].map(m=>t(m))),c=0,h=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,h=Math.max(h,m.ttl);return i.length>0?a.length>0?p=Math.min(c,h):p=c:p=h,{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[fu]=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}}__(this._cache)&&this._tick(i)}}async queryAndCache(e){if(this._hostnamesToFallback.has(e))return this._dnsLookup(e,b_);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,h]of this._cache){let p=h[fu];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(pu(e),Gt in e)throw new Error("CacheableLookup has been already installed");e[Gt]=e.createConnection,e[gi]=this,e.createConnection=(t,i)=>("lookup"in t||(t.lookup=this.lookup),e[Gt](t,i))}uninstall(e){if(pu(e),e[Gt]){if(e[gi]!==this)throw new Error("The agent is not owned by this CacheableLookup instance");e.createConnection=e[Gt],delete e[Gt],delete e[gi]}}updateInterfaceInfo(){let{_iface:e}=this;this._iface=gu(),(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()}};mi.exports=yn;mi.exports.default=yn});var wu=$((SC,vu)=>{"use strict";var v_="text/plain",w_="us-ascii",bu=(s,e)=>e.some(t=>t instanceof RegExp?t.test(s):t===s),C_=(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,h=i.split(";");c=e?"":c;let p=!1;h[h.length-1]==="base64"&&(h.pop(),p=!0);let g=(h.shift()||"").toLowerCase(),v=[...h.map(w=>{let[E,O=""]=w.split("=").map(T=>T.trim());return E==="charset"&&(O=O.toLowerCase(),O===w_)?"":`${E}${O?`=${O}`:""}`}).filter(Boolean)];return p&&v.push("base64"),(v.length!==0||g&&g!==v_)&&v.unshift(g),`data:${v.join(";")},${p?a.trim():a}${c?`#${c}`:""}`},E_=(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 C_(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 h=a.pathname.split("/"),p=h[h.length-1];bu(p,e.removeDirectoryIndex)&&(h=h.slice(0,h.length-1),a.pathname=h.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 h of[...a.searchParams.keys()])bu(h,e.removeQueryParameters)&&a.searchParams.delete(h);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};vu.exports=E_});var ku=$((TC,Eu)=>{Eu.exports=Cu;function Cu(s,e){if(s&&e)return Cu(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),h=i[i.length-1];return typeof c=="function"&&c!==h&&Object.keys(h).forEach(function(p){c[p]=h[p]}),c}}});var _i=$((AC,yi)=>{var Ou=ku();yi.exports=Ou(_n);yi.exports.strict=Ou(Su);_n.proto=_n(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return _n(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return Su(this)},configurable:!0})});function _n(s){var e=function(){return e.called?e.value:(e.called=!0,e.value=s.apply(this,arguments))};return e.called=!1,e}function Su(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 Ru=$((RC,Au)=>{var k_=_i(),O_=function(){},S_=global.Bare?queueMicrotask:process.nextTick.bind(process),T_=function(s){return s.setHeader&&typeof s.abort=="function"},A_=function(s){return s.stdio&&Array.isArray(s.stdio)&&s.stdio.length===3},Tu=function(s,e,t){if(typeof e=="function")return Tu(s,null,e);e||(e={}),t=k_(t||O_);var i=s._writableState,a=s._readableState,c=e.readable||e.readable!==!1&&s.readable,h=e.writable||e.writable!==!1&&s.writable,p=!1,g=function(){s.writable||m()},m=function(){h=!1,c||t.call(s)},v=function(){c=!1,h||t.call(s)},w=function(A){t.call(s,A?new Error("exited with error code: "+A):null)},E=function(A){t.call(s,A)},O=function(){S_(T)},T=function(){if(!p){if(c&&!(a&&a.ended&&!a.destroyed))return t.call(s,new Error("premature close"));if(h&&!(i&&i.ended&&!i.destroyed))return t.call(s,new Error("premature close"))}},k=function(){s.req.on("finish",m)};return T_(s)?(s.on("complete",m),s.on("abort",O),s.req?k():s.on("request",k)):h&&!i&&(s.on("end",g),s.on("close",g)),A_(s)&&s.on("exit",w),s.on("end",v),s.on("finish",m),e.error!==!1&&s.on("error",E),s.on("close",O),function(){p=!0,s.removeListener("complete",m),s.removeListener("abort",O),s.removeListener("request",k),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",v),s.removeListener("error",E),s.removeListener("close",O)}};Au.exports=Tu});var Mu=$((PC,Iu)=>{var R_=_i(),P_=Ru(),bn;try{bn=q("fs")}catch{}var Cs=function(){},I_=typeof process>"u"?!1:/^v?\.0/.test(process.version),vn=function(s){return typeof s=="function"},M_=function(s){return!I_||!bn?!1:(s instanceof(bn.ReadStream||Cs)||s instanceof(bn.WriteStream||Cs))&&vn(s.close)},x_=function(s){return s.setHeader&&vn(s.abort)},N_=function(s,e,t,i){i=R_(i);var a=!1;s.on("close",function(){a=!0}),P_(s,{readable:e,writable:t},function(h){if(h)return i(h);a=!0,i()});var c=!1;return function(h){if(!a&&!c){if(c=!0,M_(s))return s.close(Cs);if(x_(s))return s.abort();if(vn(s.destroy))return s.destroy();i(h||new Error("stream was destroyed"))}}},Pu=function(s){s()},L_=function(s,e){return s.pipe(e)},D_=function(){var s=Array.prototype.slice.call(arguments),e=vn(s[s.length-1]||Cs)&&s.pop()||Cs;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 h=c<s.length-1,p=c>0;return N_(a,h,p,function(g){t||(t=g),g&&i.forEach(Pu),!h&&(i.forEach(Pu),e(t))})});return s.reduce(L_)};Iu.exports=D_});var Nu=$((IC,xu)=>{"use strict";var{PassThrough:U_}=q("stream");xu.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 U_({objectMode:a});t&&c.setEncoding(t);let h=0,p=[];return c.on("data",g=>{p.push(g),a?h=p.length:h+=g.length}),c.getBufferedValue=()=>e?p:i?Buffer.concat(p,h):p.join(""),c.getBufferedLength=()=>h,c}});var Lu=$((MC,Ft)=>{"use strict";var{constants:j_}=q("buffer"),q_=Mu(),B_=Nu(),wn=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function Cn(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 h=p=>{p&&i.getBufferedLength()<=j_.MAX_LENGTH&&(p.bufferedData=i.getBufferedValue()),c(p)};i=q_(s,B_(e),p=>{if(p){h(p);return}a()}),i.on("data",()=>{i.getBufferedLength()>t&&h(new wn)})}),i.getBufferedValue()}Ft.exports=Cn;Ft.exports.default=Cn;Ft.exports.buffer=(s,e)=>Cn(s,{...e,encoding:"buffer"});Ft.exports.array=(s,e)=>Cn(s,{...e,array:!0});Ft.exports.MaxBufferError=wn});var Uu=$((NC,Du)=>{"use strict";var $_=new Set([200,203,204,206,300,301,308,404,405,410,414,501]),H_=new Set([200,203,204,300,301,302,303,307,308,404,405,410,414,501]),G_=new Set([500,502,503,504]),F_={date:!0,connection:!0,"keep-alive":!0,"proxy-authenticate":!0,"proxy-authorization":!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0},W_={"content-length":!0,"content-encoding":!0,"transfer-encoding":!0,"content-range":!0};function ot(s){let e=parseInt(s,10);return isFinite(e)?e:0}function V_(s){return s?G_.has(s.status):!0}function bi(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 z_(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(", ")}Du.exports=class{constructor(e,t,{shared:i,cacheHeuristic:a,immutableMinTimeToLive:c,ignoreCargoCult:h,_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=!!h,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=bi(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=bi(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":z_(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())&&H_.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||$_.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=bi(e.headers["cache-control"]);return t["no-cache"]||/no-cache/.test(e.headers.pragma)?this._evaluateRequestMissResult(e):t["max-age"]&&this.age()>ot(t["max-age"])?this._evaluateRequestMissResult(e):t["min-fresh"]&&this.maxAge()-this.age()<ot(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)F_[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 ot(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 ot(this._rescc["s-maxage"])}if(this._rescc["max-age"])return ot(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+ot(this._rescc["stale-if-error"]),i=e+ot(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()+ot(this._rescc["stale-if-error"])>this.age()}useStaleWhileRevalidate(){let e=ot(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()&&V_(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&&!W_[p]?t.headers[p]:this._resHeaders[p];let h=Object.assign({},t,{status:this._status,method:this._method,headers:c});return{policy:new this.constructor(e,h,a),modified:!1,matches:!0}}}});var En=$((LC,ju)=>{"use strict";ju.exports=s=>{let e={};for(let[t,i]of Object.entries(s))e[t.toLowerCase()]=i;return e}});var Bu=$((DC,qu)=>{"use strict";var K_=q("stream").Readable,J_=En(),vi=class extends K_{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=J_(t),this.body=i,this.url=a}_read(){this.push(this.body),this.push(null)}};qu.exports=vi});var Hu=$((UC,$u)=>{"use strict";var Y_=["destroy","setTimeout","socket","headers","trailers","rawHeaders","statusCode","httpVersion","httpVersionMinor","httpVersionMajor","rawTrailers","statusMessage"];$u.exports=(s,e)=>{let t=new Set(Object.keys(s).concat(Y_));for(let i of t)i in e||(e[i]=typeof s[i]=="function"?s[i].bind(s):s[i])}});var Fu=$((jC,Gu)=>{"use strict";var Q_=q("stream").PassThrough,X_=Hu(),Z_=s=>{if(!(s&&s.pipe))throw new TypeError("Parameter `response` must be a response stream.");let e=new Q_;return X_(s,e),s.pipe(e)};Gu.exports=Z_});var Wu=$(wi=>{wi.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 h=typeof e[c]=="function"||!i&&typeof e[c]>"u";Object.hasOwnProperty.call(e,c)&&!h&&(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)};wi.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 Ju=$((BC,Ku)=>{"use strict";var eb=q("events"),Vu=Wu(),tb=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},zu=["sqlite","postgres","mysql","mongo","redis","tiered"],Ci=class extends eb{constructor(e,{emitErrors:t=!0,...i}={}){if(super(),this.opts={namespace:"keyv",serialize:Vu.stringify,deserialize:Vu.parse,...typeof e=="string"?{uri:e}:e,...i},!this.opts.store){let c={...this.opts};this.opts.store=tb(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[h,p]of typeof c=="function"?c(this.opts.store.namespace):c){let g=await this.opts.deserialize(p);if(!(this.opts.store.namespace&&!h.includes(this.opts.store.namespace))){if(typeof g.expires=="number"&&Date.now()>g.expires){this.delete(h);continue}yield[this._getKeyUnprefix(h),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 zu.includes(this.opts.store.opts.dialect)||zu.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 h=[];for(let p of c)h.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(h).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(h=>typeof h=="string"?this.opts.deserialize(h):this.opts.compression?this.opts.deserialize(h):h).then(h=>{if(h!=null)return a?h.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 h.expires=="number"&&Date.now()>h.expires?this.delete(e).then(()=>{}):t&&t.raw?h:h.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 h=typeof i=="number"?Date.now()+i:null;return typeof t=="symbol"&&this.emit("error","symbol cannot be serialized"),t={value:t,expires:h},this.opts.serialize(t)}).then(h=>c.set(a,h,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 h of a)c.push(t.delete(h));return Promise.allSettled(c).then(h=>h.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()}};Ku.exports=Ci});var Xu=$((HC,Qu)=>{"use strict";var sb=q("events"),kn=q("url"),nb=wu(),rb=Lu(),Ei=Uu(),Yu=Bu(),ib=En(),ob=Fu(),ab=Ju(),Es=class s{constructor(e,t){if(typeof e!="function")throw new TypeError("Parameter `request` must be a function");return this.cache=new ab({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=ki(kn.parse(t)),t={};else if(t instanceof kn.URL)a=ki(kn.parse(t.toString())),t={};else{let[w,...E]=(t.path||"").split("?"),O=E.length>0?`?${E.join("?")}`:"";a=ki({...t,pathname:w,search:O})}t={headers:{},method:"GET",cache:!0,strictTtl:!1,automaticFailover:!1,...t,...cb(a)},t.headers=ib(t.headers);let c=new sb,h=nb(kn.format(a),{stripWWW:!1,removeTrailingSlash:!1,stripAuthentication:!1}),p=`${t.method}:${h}`,g=!1,m=!1,v=w=>{m=!0;let E=!1,O,T=new Promise(A=>{O=()=>{E||(E=!0,A())}}),k=A=>{if(g&&!w.forceRefresh){A.status=A.statusCode;let W=Ei.fromObject(g.cachePolicy).revalidatedPolicy(w,A);if(!W.modified){let Q=W.policy.responseHeaders();A=new Yu(g.statusCode,Q,g.body,g.url),A.cachePolicy=W.policy,A.fromCache=!0}}A.fromCache||(A.cachePolicy=new Ei(w,A,w),A.fromCache=!1);let N;w.cache&&A.cachePolicy.storable()?(N=ob(A),(async()=>{try{let W=rb.buffer(A);if(await Promise.race([T,new Promise(X=>A.once("end",X))]),E)return;let Q=await W,se={cachePolicy:A.cachePolicy.toObject(),url:A.url,statusCode:A.fromCache?g.statusCode:A.statusCode,body:Q},Y=w.strictTtl?A.cachePolicy.timeToLive():void 0;w.maxTtl&&(Y=Y?Math.min(Y,w.maxTtl):w.maxTtl),await this.cache.set(p,se,Y)}catch(W){c.emit("error",new s.CacheError(W))}})()):w.cache&&g&&(async()=>{try{await this.cache.delete(p)}catch(W){c.emit("error",new s.CacheError(W))}})(),c.emit("response",N||A),typeof i=="function"&&i(N||A)};try{let A=e(w,k);A.once("error",O),A.once("abort",O),c.emit("request",A)}catch(A){c.emit("error",new s.RequestError(A))}};return(async()=>{let w=async O=>{await Promise.resolve();let T=O.cache?await this.cache.get(p):void 0;if(typeof T>"u")return v(O);let k=Ei.fromObject(T.cachePolicy);if(k.satisfiesWithoutRevalidation(O)&&!O.forceRefresh){let A=k.responseHeaders(),N=new Yu(T.statusCode,A,T.body,T.url);N.cachePolicy=k,N.fromCache=!0,c.emit("response",N),typeof i=="function"&&i(N)}else g=T,O.headers=k.revalidationHeaders(O),v(O)},E=O=>c.emit("error",new s.CacheError(O));this.cache.once("error",E),c.on("response",()=>this.cache.removeListener("error",E));try{await w(t)}catch(O){t.automaticFailover&&!m&&v(t),c.emit("error",new s.CacheError(O))}})(),c}}};function cb(s){let e={...s};return e.path=`${s.pathname||"/"}${s.search||""}`,delete e.pathname,delete e.search,e}function ki(s){return{protocol:s.protocol,auth:s.auth,hostname:s.hostname||s.host||"localhost",port:s.port,pathname:s.pathname,search:s.search}}Es.RequestError=class extends Error{constructor(s){super(s.message),this.name="RequestError",Object.assign(this,s)}};Es.CacheError=class extends Error{constructor(s){super(s.message),this.name="CacheError",Object.assign(this,s)}};Qu.exports=Es});var eh=$((WC,Zu)=>{"use strict";var lb=["aborted","complete","headers","httpVersion","httpVersionMinor","httpVersionMajor","method","rawHeaders","rawTrailers","setTimeout","socket","statusCode","statusMessage","trailers","url"];Zu.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(lb)),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 sh=$((VC,th)=>{"use strict";var{Transform:ub,PassThrough:hb}=q("stream"),Oi=q("zlib"),db=eh();th.exports=s=>{let e=(s.headers["content-encoding"]||"").toLowerCase();if(!["gzip","deflate","br"].includes(e))return s;let t=e==="br";if(t&&typeof Oi.createBrotliDecompress!="function")return s.destroy(new Error("Brotli is not supported on Node.js < 12")),s;let i=!0,a=new ub({transform(p,g,m){i=!1,m(null,p)},flush(p){p()}}),c=new hb({autoDestroy:!1,destroy(p,g){s.destroy(),g(p)}}),h=t?Oi.createBrotliDecompress():Oi.createUnzip();return h.once("error",p=>{if(i&&!s.readable){c.end();return}c.destroy(p)}),db(s,c),s.pipe(a).pipe(h).pipe(c),c}});var Ti=$((zC,nh)=>{"use strict";var Si=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)}};nh.exports=Si});var Ri=$((KC,ah)=>{"use strict";var fb=q("events"),pb=q("tls"),gb=q("http2"),mb=Ti(),ke=Symbol("currentStreamsCount"),rh=Symbol("request"),Le=Symbol("cachedOriginSet"),Wt=Symbol("gracefullyClosing"),yb=["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"],_b=(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},bb=(s,e)=>s.remoteSettings.maxConcurrentStreams>e.remoteSettings.maxConcurrentStreams,Ai=(s,e)=>{for(let t of s)t[Le].length<e[Le].length&&t[Le].every(i=>e[Le].includes(i))&&t[ke]+e[ke]<=e.remoteSettings.maxConcurrentStreams&&oh(t)},vb=(s,e)=>{for(let t of s)e[Le].length<t[Le].length&&e[Le].every(i=>t[Le].includes(i))&&e[ke]+t[ke]<=t.remoteSettings.maxConcurrentStreams&&oh(e)},ih=({agent:s,isFree:e})=>{let t={};for(let i in s.sessions){let c=s.sessions[i].filter(h=>{let p=h[kt.kCurrentStreamsCount]<h.remoteSettings.maxConcurrentStreams;return e?p:!p});c.length!==0&&(t[i]=c)}return t},oh=s=>{s[Wt]=!0,s[ke]===0&&s.close()},kt=class s extends fb{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 mb({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 yb)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 h=this.normalizeOptions(t),p=s.normalizeOrigin(e,t&&t.servername);if(p===void 0){for(let{reject:v}of i)v(new TypeError("The `origin` argument needs to be a string or an URL object"));return}if(h in this.sessions){let v=this.sessions[h],w=-1,E=-1,O;for(let T of v){let k=T.remoteSettings.maxConcurrentStreams;if(k<w)break;if(T[Le].includes(p)){let A=T[ke];if(A>=k||T[Wt]||T.destroyed)continue;O||(w=k),A>E&&(O=T,E=A)}}if(O){if(i.length!==1){for(let{reject:T}of i){let k=new Error(`Expected the length of listeners to be 1, got ${i.length}.
|
|
34
|
+
Please report this to https://github.com/szmarczak/http2-wrapper/`);T(k)}return}i[0].resolve(O);return}}if(h in this.queue){if(p in this.queue[h]){this.queue[h][p].listeners.push(...i),this._tryToCreateNewSession(h,p);return}}else this.queue[h]={};let g=()=>{h in this.queue&&this.queue[h][p]===m&&(delete this.queue[h][p],Object.keys(this.queue[h]).length===0&&delete this.queue[h])},m=()=>{let v=`${p}:${h}`,w=!1;try{let E=gb.connect(e,{createConnection:this.createConnection,settings:this.settings,session:this.tlsSessionCache.get(v),...t});E[ke]=0,E[Wt]=!1;let O=()=>E[ke]<E.remoteSettings.maxConcurrentStreams,T=!0;E.socket.once("session",A=>{this.tlsSessionCache.set(v,A)}),E.once("error",A=>{for(let{reject:N}of i)N(A);this.tlsSessionCache.delete(v)}),E.setTimeout(this.timeout,()=>{E.destroy()}),E.once("close",()=>{if(w){T&&this._freeSessionsCount--,this._sessionsCount--;let A=this.sessions[h];A.splice(A.indexOf(E),1),A.length===0&&delete this.sessions[h]}else{let A=new Error("Session closed without receiving a SETTINGS frame");A.code="HTTP2WRAPPER_NOSETTINGS";for(let{reject:N}of i)N(A);g()}this._tryToCreateNewSession(h,p)});let k=()=>{if(!(!(h in this.queue)||!O())){for(let A of E[Le])if(A in this.queue[h]){let{listeners:N}=this.queue[h][A];for(;N.length!==0&&O();)N.shift().resolve(E);let W=this.queue[h];if(W[A].listeners.length===0&&(delete W[A],Object.keys(W).length===0)){delete this.queue[h];break}if(!O())break}}};E.on("origin",()=>{E[Le]=E.originSet,O()&&(k(),Ai(this.sessions[h],E))}),E.once("remoteSettings",()=>{if(E.ref(),E.unref(),this._sessionsCount++,m.destroyed){let A=new Error("Agent has been destroyed");for(let N of i)N.reject(A);E.destroy();return}E[Le]=E.originSet;{let A=this.sessions;if(h in A){let N=A[h];N.splice(_b(N,E,bb),0,E)}else A[h]=[E]}this._freeSessionsCount+=1,w=!0,this.emit("session",E),k(),g(),E[ke]===0&&this._freeSessionsCount>this.maxFreeSessions&&E.close(),i.length!==0&&(this.getSession(p,t,i),i.length=0),E.on("remoteSettings",()=>{k(),Ai(this.sessions[h],E)})}),E[rh]=E.request,E.request=(A,N)=>{if(E[Wt])throw new Error("The session is gracefully closing. No new streams are allowed.");let W=E[rh](A,N);return E.ref(),++E[ke],E[ke]===E.remoteSettings.maxConcurrentStreams&&this._freeSessionsCount--,W.once("close",()=>{if(T=O(),--E[ke],!E.destroyed&&!E.closed&&(vb(this.sessions[h],E),O()&&!E.closed)){T||(this._freeSessionsCount++,T=!0);let Q=E[ke]===0;Q&&E.unref(),Q&&(this._freeSessionsCount>this.maxFreeSessions||E[Wt])?E.close():(Ai(this.sessions[h],E),k())}}),W}}catch(E){for(let O of i)O.reject(E);g()}};m.listeners=i,m.completed=!1,m.destroyed=!1,this.queue[h][p]=m,this._tryToCreateNewSession(h,p)})}request(e,t,i,a){return new Promise((c,h)=>{this.getSession(e,t,[{reject:h,resolve:p=>{try{c(p.request(i,a))}catch(g){h(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),pb.connect(i,a,t)}closeFreeSessions(){for(let e of Object.values(this.sessions))for(let t of e)t[ke]===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 ih({agent:this,isFree:!0})}get busySessions(){return ih({agent:this,isFree:!1})}};kt.kCurrentStreamsCount=ke;kt.kGracefullyClosing=Wt;ah.exports={Agent:kt,globalAgent:new kt}});var Ii=$((JC,ch)=>{"use strict";var{Readable:wb}=q("stream"),Pi=class extends wb{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()}};ch.exports=Pi});var Mi=$((YC,lh)=>{"use strict";lh.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 hh=$((QC,uh)=>{"use strict";uh.exports=(s,e,t)=>{for(let i of t)s.on(i,(...a)=>e.emit(i,...a))}});var fh=$((XC,dh)=>{"use strict";dh.exports=s=>{switch(s){case":method":case":scheme":case":authority":case":path":return!0;default:return!1}}});var gh=$((e0,ph)=>{"use strict";var Vt=(s,e,t)=>{ph.exports[e]=class extends s{constructor(...a){super(typeof t=="string"?t:t(a)),this.name=`${super.name} [${e}]`,this.code=e}}};Vt(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]}`});Vt(TypeError,"ERR_INVALID_PROTOCOL",s=>`Protocol "${s[0]}" not supported. Expected "${s[1]}"`);Vt(Error,"ERR_HTTP_HEADERS_SENT",s=>`Cannot ${s[0]} headers after they are sent to the client`);Vt(TypeError,"ERR_INVALID_HTTP_TOKEN",s=>`${s[0]} must be a valid HTTP token [${s[1]}]`);Vt(TypeError,"ERR_HTTP_INVALID_HEADER_VALUE",s=>`Invalid value "${s[0]} for header "${s[1]}"`);Vt(TypeError,"ERR_INVALID_CHAR",s=>`Invalid character in ${s[0]} [${s[1]}]`)});var Ui=$((t0,Ch)=>{"use strict";var Cb=q("http2"),{Writable:Eb}=q("stream"),{Agent:mh,globalAgent:kb}=Ri(),Ob=Ii(),Sb=Mi(),Tb=hh(),Ab=fh(),{ERR_INVALID_ARG_TYPE:xi,ERR_INVALID_PROTOCOL:Rb,ERR_HTTP_HEADERS_SENT:yh,ERR_INVALID_HTTP_TOKEN:Pb,ERR_HTTP_INVALID_HEADER_VALUE:Ib,ERR_INVALID_CHAR:Mb}=gh(),{HTTP2_HEADER_STATUS:_h,HTTP2_HEADER_METHOD:bh,HTTP2_HEADER_PATH:vh,HTTP2_METHOD_CONNECT:xb}=Cb.constants,we=Symbol("headers"),Ni=Symbol("origin"),Li=Symbol("session"),wh=Symbol("options"),On=Symbol("flushedHeaders"),ks=Symbol("jobs"),Nb=/^[\^`\-\w!#$%&*+.|~]+$/,Lb=/[^\t\u0020-\u007E\u0080-\u00FF]/,Di=class extends Eb{constructor(e,t,i){super({autoDestroy:!1});let a=typeof e=="string"||e instanceof URL;if(a&&(e=Sb(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[Li]=t.h2session;else if(t.agent===!1)this.agent=new mh({maxFreeSessions:0});else if(typeof t.agent>"u"||t.agent===null)typeof t.createConnection=="function"?(this.agent=new mh({maxFreeSessions:0}),this.agent.createConnection=t.createConnection):this.agent=kb;else if(typeof t.agent.request=="function")this.agent=t.agent;else throw new xi("options.agent",["Agent-like Object","undefined","false"],t.agent);if(t.protocol&&t.protocol!=="https:")throw new Rb(t.protocol,"https:");let c=t.port||t.defaultPort||this.agent&&this.agent.defaultPort||443,h=t.hostname||t.host||"localhost";delete t.hostname,delete t.host,delete t.port;let{timeout:p}=t;if(t.timeout=void 0,this[we]=Object.create(null),this[ks]=[],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[we])&&(this[we].authorization="Basic "+Buffer.from(t.auth).toString("base64")),t.session=t.tlsSession,t.path=t.socketPath,this[wh]=t,c===443?(this[Ni]=`https://${h}`,":authority"in this[we]||(this[we][":authority"]=h)):(this[Ni]=`https://${h}:${c}`,":authority"in this[we]||(this[we][":authority"]=`${h}:${c}`)),p&&this.setTimeout(p),i&&this.once("response",i),this[On]=!1}get method(){return this[we][bh]}set method(e){e&&(this[we][bh]=e.toUpperCase())}get path(){return this[we][vh]}set path(e){e&&(this[we][vh]=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[ks].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[ks].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[On]||this.destroyed)return;this[On]=!0;let e=this.method===xb,t=i=>{if(this._request=i,this.destroyed){i.destroy();return}e||Tb(i,this,["timeout","continue","close","error"]);let a=h=>(...p)=>{!this.writable&&!this.destroyed?h(...p):this.once("finish",()=>{h(...p)})};i.once("response",a((h,p,g)=>{let m=new Ob(this.socket,i.readableHighWaterMark);this.res=m,m.req=this,m.statusCode=h[_h],m.headers=h,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",v=>{!m._dumped&&!m.push(v)&&i.pause()}),i.once("end",()=>{m.push(null)}),this.emit("response",m)||m._dump())})),i.once("headers",a(h=>this.emit("information",{statusCode:h[_h]}))),i.once("trailers",a((h,p,g)=>{let{res:m}=this;m.trailers=h,m.rawTrailers=g}));let{socket:c}=i.session;this.socket=c,this.connection=c;for(let h of this[ks])h();this.emit("socket",this.socket)};if(this[Li])try{t(this[Li].request(this[we]))}catch(i){this.emit("error",i)}else{this.reusedSocket=!0;try{t(await this.agent.request(this[Ni],this[wh],this[we]))}catch(i){this.emit("error",i)}}}getHeader(e){if(typeof e!="string")throw new xi("name","string",e);return this[we][e.toLowerCase()]}get headersSent(){return this[On]}removeHeader(e){if(typeof e!="string")throw new xi("name","string",e);if(this.headersSent)throw new yh("remove");delete this[we][e.toLowerCase()]}setHeader(e,t){if(this.headersSent)throw new yh("set");if(typeof e!="string"||!Nb.test(e)&&!Ab(e))throw new Pb("Header name",e);if(typeof t>"u")throw new Ib(t,e);if(Lb.test(t))throw new Mb("header content",e);this[we][e.toLowerCase()]=t}setNoDelay(){}setSocketKeepAlive(){}setTimeout(e,t){let i=()=>this._request.setTimeout(e,t);return this._request?i():this[ks].push(i),this}get maxHeadersCount(){if(!this.destroyed&&this._request)return this._request.session.localSettings.maxHeaderListSize}set maxHeadersCount(e){}};Ch.exports=Di});var kh=$((s0,Eh)=>{"use strict";var Db=q("tls");Eh.exports=(s={},e=Db.connect)=>new Promise((t,i)=>{let a=!1,c,h=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,h()},g=(async()=>{try{c=await e(s,h),c.on("error",i),c.once("timeout",p)}catch(m){i(m)}})()})});var Sh=$((n0,Oh)=>{"use strict";var Ub=q("net");Oh.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]),Ub.isIP(e)?"":e}});var Rh=$((r0,qi)=>{"use strict";var Th=q("http"),ji=q("https"),jb=kh(),qb=Ti(),Bb=Ui(),$b=Sh(),Hb=Mi(),Sn=new qb({maxSize:100}),Os=new Map,Ah=(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)},Gb=async s=>{let e=`${s.host}:${s.port}:${s.ALPNProtocols.sort()}`;if(!Sn.has(e)){if(Os.has(e))return(await Os.get(e)).alpnProtocol;let{path:t,agent:i}=s;s.path=s.socketPath;let a=jb(s);Os.set(e,a);try{let{socket:c,alpnProtocol:h}=await a;if(Sn.set(e,h),s.path=t,h==="h2")c.destroy();else{let{globalAgent:p}=ji,g=ji.Agent.prototype.createConnection;i?i.createConnection===g?Ah(i,c,s):c.destroy():p.createConnection===g?Ah(p,c,s):c.destroy()}return Os.delete(e),h}catch(c){throw Os.delete(e),c}}return Sn.get(e)};qi.exports=async(s,e,t)=>{if((typeof s=="string"||s instanceof URL)&&(s=Hb(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||$b(e),e.port=e.port||(i?443:80),e._defaultAgent=i?ji.globalAgent:Th.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 Gb(e)==="h2"?(a&&(e.agent=a.http2),new Bb(e,t)):Th.request(e,t)};qi.exports.protocolCache=Sn});var Ih=$((i0,Ph)=>{"use strict";var Fb=q("http2"),Wb=Ri(),Bi=Ui(),Vb=Ii(),zb=Rh(),Kb=(s,e,t)=>new Bi(s,e,t),Jb=(s,e,t)=>{let i=new Bi(s,e,t);return i.end(),i};Ph.exports={...Fb,ClientRequest:Bi,IncomingMessage:Vb,...Wb,request:Kb,get:Jb,auto:zb}});var Hi=$($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});var Mh=it();$i.default=s=>Mh.default.nodeStream(s)&&Mh.default.function_(s.getBoundary)});var Dh=$(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});var Nh=q("fs"),Lh=q("util"),xh=it(),Yb=Hi(),Qb=Lh.promisify(Nh.stat);Gi.default=async(s,e)=>{if(e&&"content-length"in e)return Number(e["content-length"]);if(!s)return 0;if(xh.default.string(s))return Buffer.byteLength(s);if(xh.default.buffer(s))return s.length;if(Yb.default(s))return Lh.promisify(s.getLength.bind(s))();if(s instanceof Nh.ReadStream){let{size:t}=await Qb(s.path);return t===0?void 0:t}}});var Wi=$(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});function Xb(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])}}Fi.default=Xb});var Uh=$(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.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 qh=$(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.TimeoutError=void 0;var Zb=q("net"),ev=Uh(),jh=Symbol("reentry"),tv=()=>{},Tn=class extends Error{constructor(e,t){super(`Timeout awaiting '${t}' for ${e}ms`),this.event=t,this.name="TimeoutError",this.code="ETIMEDOUT"}};Ss.TimeoutError=Tn;Ss.default=(s,e,t)=>{if(jh in s)return tv;s[jh]=!0;let i=[],{once:a,unhandleAll:c}=ev.default(),h=(w,E,O)=>{var T;let k=setTimeout(E,w,w,O);(T=k.unref)===null||T===void 0||T.call(k);let A=()=>{clearTimeout(k)};return i.push(A),A},{host:p,hostname:g}=t,m=(w,E)=>{s.destroy(new Tn(w,E))},v=()=>{for(let w of i)w();c()};if(s.once("error",w=>{if(v(),s.listenerCount("error")===0)throw w}),s.once("close",v),a(s,"response",w=>{a(w,"end",v)}),typeof e.request<"u"&&h(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 E;let{socketPath:O}=s;if(w.connecting){let T=!!(O??Zb.isIP((E=g??p)!==null&&E!==void 0?E:"")!==0);if(typeof e.lookup<"u"&&!T&&typeof w.address().address>"u"){let k=h(e.lookup,m,"lookup");a(w,"lookup",k)}if(typeof e.connect<"u"){let k=()=>h(e.connect,m,"connect");T?a(w,"connect",k()):a(w,"lookup",A=>{A===null&&a(w,"connect",k())})}typeof e.secureConnect<"u"&&t.protocol==="https:"&&a(w,"connect",()=>{let k=h(e.secureConnect,m,"secureConnect");a(w,"secureConnect",k)})}if(typeof e.send<"u"){let T=()=>h(e.send,m,"send");w.connecting?a(w,"connect",()=>{a(s,"upload-complete",T())}):a(s,"upload-complete",T())}}),typeof e.response<"u"&&a(s,"upload-complete",()=>{let w=h(e.response,m,"response");a(s,"response",w)}),v}});var $h=$(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});var Bh=it();zi.default=s=>{s=s;let e={protocol:s.protocol,hostname:Bh.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 Bh.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 Hh=$(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});var sv=q("url"),nv=["protocol","host","hostname","port","pathname","search"];Ki.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 sv.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 nv)e[c]&&(a[c]=e[c].toString());return a}});var Gh=$(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});var Ji=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)}};Yi.default=Ji});var Xi=$(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});var rv=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(""))};Qi.default=rv});var Wh=$(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.dnsLookupIpVersionToFamily=Ot.isDnsLookupIpVersion=void 0;var Fh={auto:0,ipv4:4,ipv6:6};Ot.isDnsLookupIpVersion=s=>s in Fh;Ot.dnsLookupIpVersionToFamily=s=>{if(Ot.isDnsLookupIpVersion(s))return Fh[s];throw new Error("Invalid DNS lookup IP version")}});var Zi=$(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.isResponseOk=void 0;An.isResponseOk=s=>{let{statusCode:e}=s,t=s.request.options.followRedirect?299:399;return e>=200&&e<=t||e===304}});var zh=$(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});var Vh=new Set;eo.default=s=>{Vh.has(s)||(Vh.add(s),process.emitWarning(`Got: ${s}`,{type:"DeprecationWarning"}))}});var Kh=$(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});var oe=it(),iv=(s,e)=>{if(oe.default.null_(s.encoding))throw new TypeError("To get a Buffer, set `options.responseType` to `buffer` instead");oe.assert.any([oe.default.string,oe.default.undefined],s.encoding),oe.assert.any([oe.default.boolean,oe.default.undefined],s.resolveBodyOnly),oe.assert.any([oe.default.boolean,oe.default.undefined],s.methodRewriting),oe.assert.any([oe.default.boolean,oe.default.undefined],s.isStream),oe.assert.any([oe.default.string,oe.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},oe.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)]):oe.default.number(t)&&(s.retry.limit=t),oe.default.undefined(s.retry.maxRetryAfter)&&(s.retry.maxRetryAfter=Math.min(...[s.timeout.request,s.timeout.connect].filter(oe.default.number))),oe.default.object(s.pagination)){e&&(s.pagination={...e.pagination,...s.pagination});let{pagination:i}=s;if(!oe.default.function_(i.transform))throw new Error("`options.pagination.transform` must be implemented");if(!oe.default.function_(i.shouldContinue))throw new Error("`options.pagination.shouldContinue` must be implemented");if(!oe.default.function_(i.filter))throw new TypeError("`options.pagination.filter` must be implemented");if(!oe.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};to.default=iv});var Jh=$(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});Ts.retryAfterStatusCodes=void 0;Ts.retryAfterStatusCodes=new Set([413,429,503]);var ov=({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),h=t.response&&e.statusCodes.includes(t.response.statusCode);if(!a||!c&&!h)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};Ts.default=ov});var Ps=$(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.UnsupportedProtocolError=Z.ReadError=Z.TimeoutError=Z.UploadError=Z.CacheError=Z.HTTPError=Z.MaxRedirectsError=Z.RequestError=Z.setNonEnumerableProperties=Z.knownHookEvents=Z.withoutBody=Z.kIsNormalizedAlready=void 0;var Yh=q("util"),Qh=q("stream"),av=q("fs"),ft=q("url"),Xh=q("http"),so=q("http"),cv=q("https"),lv=hu(),uv=_u(),Zh=Xu(),hv=sh(),dv=Ih(),fv=En(),M=it(),pv=Dh(),ed=Hi(),gv=Wi(),td=qh(),mv=$h(),sd=Hh(),yv=Gh(),_v=Xi(),nd=Wh(),bv=Zi(),pt=zh(),vv=Kh(),wv=Jh(),no,ye=Symbol("request"),In=Symbol("response"),zt=Symbol("responseSize"),Kt=Symbol("downloadedSize"),Jt=Symbol("bodySize"),Yt=Symbol("uploadedSize"),Rn=Symbol("serverResponsesPiped"),rd=Symbol("unproxyEvents"),id=Symbol("isFromCache"),ro=Symbol("cancelTimeouts"),od=Symbol("startedReading"),Qt=Symbol("stopReading"),Pn=Symbol("triggerRead"),gt=Symbol("body"),As=Symbol("jobs"),ad=Symbol("originalResponse"),cd=Symbol("retryTimeout");Z.kIsNormalizedAlready=Symbol("isNormalizedAlready");var Cv=M.default.string(process.versions.brotli);Z.withoutBody=new Set(["GET","HEAD"]);Z.knownHookEvents=["init","beforeRequest","beforeRedirect","beforeError","beforeRetry","afterResponse"];function Ev(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 kv(s){return M.default.object(s)&&!("statusCode"in s)}var io=new yv.default,Ov=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()})}),Sv=new Set([300,301,302,303,304,307,308]),Tv=["context","body","json","form"];Z.setNonEnumerableProperties=(s,e)=>{let t={};for(let i of s)if(i)for(let a of Tv)a in i&&(t[a]={writable:!0,configurable:!0,enumerable:!1,value:i[a]});Object.defineProperties(e,t)};var he=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 jn?(Object.defineProperty(this,"request",{enumerable:!1,value:i}),Object.defineProperty(this,"response",{enumerable:!1,value:i[In]}),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 h=this.stack.indexOf(this.message)+this.message.length,p=this.stack.slice(h).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,h)}${p.reverse().join(`
|
|
37
37
|
`)}${g.reverse().join(`
|
|
38
|
-
`)}`}}};X.RequestError=ce;var In=class extends ce{constructor(e){super(`Redirected ${e.options.maxRedirects} times. Aborting.`,{},e),this.name="MaxRedirectsError",this.code="ERR_TOO_MANY_REDIRECTS"}};X.MaxRedirectsError=In;var Mn=class extends ce{constructor(e){super(`Response code ${e.statusCode} (${e.statusMessage})`,{},e.request),this.name="HTTPError",this.code="ERR_NON_2XX_3XX_RESPONSE"}};X.HTTPError=Mn;var xn=class extends ce{constructor(e,t){super(e.message,e,t),this.name="CacheError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_CACHE_ACCESS":this.code}};X.CacheError=xn;var Nn=class extends ce{constructor(e,t){super(e.message,e,t),this.name="UploadError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_UPLOAD":this.code}};X.UploadError=Nn;var Ln=class extends ce{constructor(e,t,i){super(e.message,e,i),this.name="TimeoutError",this.event=e.event,this.timings=t}};X.TimeoutError=Ln;var As=class extends ce{constructor(e,t){super(e.message,e,t),this.name="ReadError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_READING_RESPONSE_STREAM":this.code}};X.ReadError=As;var Dn=class extends ce{constructor(e){super(`Unsupported protocol "${e.url.protocol}"`,{},e),this.name="UnsupportedProtocolError",this.code="ERR_UNSUPPORTED_PROTOCOL"}};X.UnsupportedProtocolError=Dn;var Av=["socket","connect","continue","information","upgrade","timeout"],Un=class extends Qh.Duplex{constructor(e,t={},i){super({autoDestroy:!1,highWaterMark:0}),this[zt]=0,this[Jt]=0,this.requestInitialized=!1,this[An]=new Set,this.redirects=[],this[Yt]=!1,this[Rn]=!1,this[Ts]=[],this.retryCount=0,this._progressCallbacks=[];let a=()=>this._unlockWrite(),c=()=>this._lockWrite();this.on("pipe",m=>{m.prependListener("data",a),m.on("data",c),m.prependListener("end",a),m.on("end",c)}),this.on("unpipe",m=>{m.off("data",a),m.off("data",c),m.off("end",a),m.off("end",c)}),this.on("pipe",m=>{m instanceof so.IncomingMessage&&(this.options.headers={...m.headers,...this.options.headers})});let{json:h,body:p,form:g}=t;if((h||p||g)&&this._lockWrite(),X.kIsNormalizedAlready in t)this.options=t;else try{this.options=this.constructor.normalizeArguments(e,t,i)}catch(m){M.default.nodeStream(t.body)&&t.body.destroy(),this.destroy(m);return}(async()=>{var m;try{this.options.body instanceof av.ReadStream&&await Ov(this.options.body);let{url:v}=this.options;if(!v)throw new TypeError("Missing `url` property");if(this.requestUrl=v.toString(),decodeURI(this.requestUrl),await this._finalizeBody(),await this._makeRequest(),this.destroyed){(m=this[pe])===null||m===void 0||m.destroy();return}for(let w of this[Ts])w();this[Ts].length=0,this.requestInitialized=!0}catch(v){if(v instanceof ce){this._beforeError(v);return}this.destroyed||this.destroy(v)}})()}static normalizeArguments(e,t,i){var a,c,h,p,g;let m=t;if(M.default.object(e)&&!M.default.urlInstance(e))t={...i,...e,...t};else{if(e&&t&&t.url!==void 0)throw new TypeError("The `url` option is mutually exclusive with the `input` argument");t={...i,...t},e!==void 0&&(t.url=e),M.default.urlInstance(t.url)&&(t.url=new ht.URL(t.url.toString()))}if(t.cache===!1&&(t.cache=void 0),t.dnsCache===!1&&(t.dnsCache=void 0),M.assert.any([M.default.string,M.default.undefined],t.method),M.assert.any([M.default.object,M.default.undefined],t.headers),M.assert.any([M.default.string,M.default.urlInstance,M.default.undefined],t.prefixUrl),M.assert.any([M.default.object,M.default.undefined],t.cookieJar),M.assert.any([M.default.object,M.default.string,M.default.undefined],t.searchParams),M.assert.any([M.default.object,M.default.string,M.default.undefined],t.cache),M.assert.any([M.default.object,M.default.number,M.default.undefined],t.timeout),M.assert.any([M.default.object,M.default.undefined],t.context),M.assert.any([M.default.object,M.default.undefined],t.hooks),M.assert.any([M.default.boolean,M.default.undefined],t.decompress),M.assert.any([M.default.boolean,M.default.undefined],t.ignoreInvalidCookies),M.assert.any([M.default.boolean,M.default.undefined],t.followRedirect),M.assert.any([M.default.number,M.default.undefined],t.maxRedirects),M.assert.any([M.default.boolean,M.default.undefined],t.throwHttpErrors),M.assert.any([M.default.boolean,M.default.undefined],t.http2),M.assert.any([M.default.boolean,M.default.undefined],t.allowGetBody),M.assert.any([M.default.string,M.default.undefined],t.localAddress),M.assert.any([nd.isDnsLookupIpVersion,M.default.undefined],t.dnsLookupIpVersion),M.assert.any([M.default.object,M.default.undefined],t.https),M.assert.any([M.default.boolean,M.default.undefined],t.rejectUnauthorized),t.https&&(M.assert.any([M.default.boolean,M.default.undefined],t.https.rejectUnauthorized),M.assert.any([M.default.function_,M.default.undefined],t.https.checkServerIdentity),M.assert.any([M.default.string,M.default.object,M.default.array,M.default.undefined],t.https.certificateAuthority),M.assert.any([M.default.string,M.default.object,M.default.array,M.default.undefined],t.https.key),M.assert.any([M.default.string,M.default.object,M.default.array,M.default.undefined],t.https.certificate),M.assert.any([M.default.string,M.default.undefined],t.https.passphrase),M.assert.any([M.default.string,M.default.buffer,M.default.array,M.default.undefined],t.https.pfx)),M.assert.any([M.default.object,M.default.undefined],t.cacheOptions),M.default.string(t.method)?t.method=t.method.toUpperCase():t.method="GET",t.headers===i?.headers?t.headers={...t.headers}:t.headers=fv({...i?.headers,...t.headers}),"slashes"in t)throw new TypeError("The legacy `url.Url` has been deprecated. Use `URL` instead.");if("auth"in t)throw new TypeError("Parameter `auth` is deprecated. Use `username` / `password` instead.");if("searchParams"in t&&t.searchParams&&t.searchParams!==i?.searchParams){let O;if(M.default.string(t.searchParams)||t.searchParams instanceof ht.URLSearchParams)O=new ht.URLSearchParams(t.searchParams);else{Ev(t.searchParams),O=new ht.URLSearchParams;for(let A in t.searchParams){let k=t.searchParams[A];k===null?O.append(A,""):k!==void 0&&O.append(A,k)}}(a=i?.searchParams)===null||a===void 0||a.forEach((A,k)=>{O.has(k)||O.append(k,A)}),t.searchParams=O}if(t.username=(c=t.username)!==null&&c!==void 0?c:"",t.password=(h=t.password)!==null&&h!==void 0?h:"",M.default.undefined(t.prefixUrl)?t.prefixUrl=(p=i?.prefixUrl)!==null&&p!==void 0?p:"":(t.prefixUrl=t.prefixUrl.toString(),t.prefixUrl!==""&&!t.prefixUrl.endsWith("/")&&(t.prefixUrl+="/")),M.default.string(t.url)){if(t.url.startsWith("/"))throw new Error("`input` must not start with a slash when using `prefixUrl`");t.url=sd.default(t.prefixUrl+t.url,t)}else(M.default.undefined(t.url)&&t.prefixUrl!==""||t.protocol)&&(t.url=sd.default(t.prefixUrl,t));if(t.url){"port"in t&&delete t.port;let{prefixUrl:O}=t;Object.defineProperty(t,"prefixUrl",{set:k=>{let T=t.url;if(!T.href.startsWith(k))throw new Error(`Cannot change \`prefixUrl\` from ${O} to ${k}: ${T.href}`);t.url=new ht.URL(k+T.href.slice(O.length)),O=k},get:()=>O});let{protocol:A}=t.url;if(A==="unix:"&&(A="http:",t.url=new ht.URL(`http://unix${t.url.pathname}${t.url.search}`)),t.searchParams&&(t.url.search=t.searchParams.toString()),A!=="http:"&&A!=="https:")throw new Dn(t);t.username===""?t.username=t.url.username:t.url.username=t.username,t.password===""?t.password=t.url.password:t.url.password=t.password}let{cookieJar:v}=t;if(v){let{setCookie:O,getCookieString:A}=v;M.assert.function_(O),M.assert.function_(A),O.length===4&&A.length===0&&(O=Yh.promisify(O.bind(t.cookieJar)),A=Yh.promisify(A.bind(t.cookieJar)),t.cookieJar={setCookie:O,getCookieString:A})}let{cache:w}=t;if(w&&(io.has(w)||io.set(w,new Zh((O,A)=>{let k=O[pe](O,A);return M.default.promise(k)&&(k.once=(T,N)=>{if(T==="error")k.catch(N);else if(T==="abort")(async()=>{try{(await k).once("abort",N)}catch{}})();else throw new Error(`Unknown HTTP2 promise event: ${T}`);return k}),k},w))),t.cacheOptions={...t.cacheOptions},t.dnsCache===!0)no||(no=new uv.default),t.dnsCache=no;else if(!M.default.undefined(t.dnsCache)&&!t.dnsCache.lookup)throw new TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${M.default(t.dnsCache)}`);M.default.number(t.timeout)?t.timeout={request:t.timeout}:i&&t.timeout!==i.timeout?t.timeout={...i.timeout,...t.timeout}:t.timeout={...t.timeout},t.context||(t.context={});let E=t.hooks===i?.hooks;t.hooks={...t.hooks};for(let O of X.knownHookEvents)if(O in t.hooks)if(M.default.array(t.hooks[O]))t.hooks[O]=[...t.hooks[O]];else throw new TypeError(`Parameter \`${O}\` must be an Array, got ${M.default(t.hooks[O])}`);else t.hooks[O]=[];if(i&&!E)for(let O of X.knownHookEvents)i.hooks[O].length>0&&(t.hooks[O]=[...i.hooks[O],...t.hooks[O]]);if("family"in t&&dt.default('"options.family" was never documented, please use "options.dnsLookupIpVersion"'),i?.https&&(t.https={...i.https,...t.https}),"rejectUnauthorized"in t&&dt.default('"options.rejectUnauthorized" is now deprecated, please use "options.https.rejectUnauthorized"'),"checkServerIdentity"in t&&dt.default('"options.checkServerIdentity" was never documented, please use "options.https.checkServerIdentity"'),"ca"in t&&dt.default('"options.ca" was never documented, please use "options.https.certificateAuthority"'),"key"in t&&dt.default('"options.key" was never documented, please use "options.https.key"'),"cert"in t&&dt.default('"options.cert" was never documented, please use "options.https.certificate"'),"passphrase"in t&&dt.default('"options.passphrase" was never documented, please use "options.https.passphrase"'),"pfx"in t&&dt.default('"options.pfx" was never documented, please use "options.https.pfx"'),"followRedirects"in t)throw new TypeError("The `followRedirects` option does not exist. Use `followRedirect` instead.");if(t.agent){for(let O in t.agent)if(O!=="http"&&O!=="https"&&O!=="http2")throw new TypeError(`Expected the \`options.agent\` properties to be \`http\`, \`https\` or \`http2\`, got \`${O}\``)}return t.maxRedirects=(g=t.maxRedirects)!==null&&g!==void 0?g:0,X.setNonEnumerableProperties([i,m],t),vv.default(t,i)}_lockWrite(){let e=()=>{throw new TypeError("The payload has been already provided")};this.write=e,this.end=e}_unlockWrite(){this.write=super.write,this.end=super.end}async _finalizeBody(){let{options:e}=this,{headers:t}=e,i=!M.default.undefined(e.form),a=!M.default.undefined(e.json),c=!M.default.undefined(e.body),h=i||a||c,p=X.withoutBody.has(e.method)&&!(e.method==="GET"&&e.allowGetBody);if(this._cannotHaveBody=p,h){if(p)throw new TypeError(`The \`${e.method}\` method cannot be used with a body`);if([c,i,a].filter(g=>g).length>1)throw new TypeError("The `body`, `json` and `form` options are mutually exclusive");if(c&&!(e.body instanceof Qh.Readable)&&!M.default.string(e.body)&&!M.default.buffer(e.body)&&!ed.default(e.body))throw new TypeError("The `body` option must be a stream.Readable, string or Buffer");if(i&&!M.default.object(e.form))throw new TypeError("The `form` option must be an Object");{let g=!M.default.string(t["content-type"]);c?(ed.default(e.body)&&g&&(t["content-type"]=`multipart/form-data; boundary=${e.body.getBoundary()}`),this[ft]=e.body):i?(g&&(t["content-type"]="application/x-www-form-urlencoded"),this[ft]=new ht.URLSearchParams(e.form).toString()):(g&&(t["content-type"]="application/json"),this[ft]=e.stringifyJson(e.json));let m=await pv.default(this[ft],e.headers);M.default.undefined(t["content-length"])&&M.default.undefined(t["transfer-encoding"])&&!p&&!M.default.undefined(m)&&(t["content-length"]=String(m))}}else p?this._lockWrite():this._unlockWrite();this[Kt]=Number(t["content-length"])||void 0}async _onResponseBase(e){let{options:t}=this,{url:i}=t;this[ad]=e,t.decompress&&(e=hv(e));let a=e.statusCode,c=e;c.statusMessage=c.statusMessage?c.statusMessage:Xh.STATUS_CODES[a],c.url=t.url.toString(),c.requestUrl=this.requestUrl,c.redirectUrls=this.redirects,c.request=this,c.isFromCache=e.fromCache||!1,c.ip=this.ip,c.retryCount=this.retryCount,this[id]=c.isFromCache,this[Vt]=Number(e.headers["content-length"])||void 0,this[Pn]=e,e.once("end",()=>{this[Vt]=this[zt],this.emit("downloadProgress",this.downloadProgress)}),e.once("error",p=>{e.destroy(),this._beforeError(new As(p,this))}),e.once("aborted",()=>{this._beforeError(new As({name:"Error",message:"The server aborted pending request",code:"ECONNRESET"},this))}),this.emit("downloadProgress",this.downloadProgress);let h=e.headers["set-cookie"];if(M.default.object(t.cookieJar)&&h){let p=h.map(async g=>t.cookieJar.setCookie(g,i.toString()));t.ignoreInvalidCookies&&(p=p.map(async g=>g.catch(()=>{})));try{await Promise.all(p)}catch(g){this._beforeError(g);return}}if(t.followRedirect&&e.headers.location&&Sv.has(a)){if(e.resume(),this[pe]&&(this[ro](),delete this[pe],this[rd]()),(a===303&&t.method!=="GET"&&t.method!=="HEAD"||!t.methodRewriting)&&(t.method="GET","body"in t&&delete t.body,"json"in t&&delete t.json,"form"in t&&delete t.form,this[ft]=void 0,delete t.headers["content-length"]),this.redirects.length>=t.maxRedirects){this._beforeError(new In(this));return}try{let w=function(E){return E.protocol==="unix:"||E.hostname==="unix"},g=Buffer.from(e.headers.location,"binary").toString(),m=new ht.URL(g,i),v=m.toString();if(decodeURI(v),!w(i)&&w(m)){this._beforeError(new ce("Cannot redirect to UNIX socket",{},this));return}m.hostname!==i.hostname||m.port!==i.port?("host"in t.headers&&delete t.headers.host,"cookie"in t.headers&&delete t.headers.cookie,"authorization"in t.headers&&delete t.headers.authorization,(t.username||t.password)&&(t.username="",t.password="")):(m.username=t.username,m.password=t.password),this.redirects.push(v),t.url=m;for(let E of t.hooks.beforeRedirect)await E(t,c);this.emit("redirect",c,t),await this._makeRequest()}catch(g){this._beforeError(g);return}return}if(t.isStream&&t.throwHttpErrors&&!bv.isResponseOk(c)){this._beforeError(new Mn(c));return}e.on("readable",()=>{this[Rn]&&this._read()}),this.on("resume",()=>{e.resume()}),this.on("pause",()=>{e.pause()}),e.once("end",()=>{this.push(null)}),this.emit("response",e);for(let p of this[An])if(!p.headersSent){for(let g in e.headers){let m=t.decompress?g!=="content-encoding":!0,v=e.headers[g];m&&p.setHeader(g,v)}p.statusCode=a}}async _onResponse(e){try{await this._onResponseBase(e)}catch(t){this._beforeError(t)}}_onRequest(e){let{options:t}=this,{timeout:i,url:a}=t;lv.default(e),this[ro]=td.default(e,i,a);let c=t.cache?"cacheableResponse":"response";e.once(c,g=>{this._onResponse(g)}),e.once("error",g=>{var m;e.destroy(),(m=e.res)===null||m===void 0||m.removeAllListeners("end"),g=g instanceof td.TimeoutError?new Ln(g,this.timings,this):new ce(g.message,g,this),this._beforeError(g)}),this[rd]=gv.default(e,this,Av),this[pe]=e,this.emit("uploadProgress",this.uploadProgress);let h=this[ft],p=this.redirects.length===0?this:e;M.default.nodeStream(h)?(h.pipe(p),h.once("error",g=>{this._beforeError(new Nn(g,this))})):(this._unlockWrite(),M.default.undefined(h)?(this._cannotHaveBody||this._noPipe)&&(p.end(),this._lockWrite()):(this._writeRequest(h,void 0,()=>{}),p.end(),this._lockWrite())),this.emit("request",e)}async _createCacheableRequest(e,t){return new Promise((i,a)=>{Object.assign(t,mv.default(e)),delete t.url;let c,h=io.get(t.cache)(t,async p=>{p._readableState.autoDestroy=!1,c&&(await c).emit("cacheableResponse",p),i(p)});t.url=e,h.once("error",a),h.once("request",async p=>{c=p,i(c)})})}async _makeRequest(){var e,t,i,a,c;let{options:h}=this,{headers:p}=h;for(let N in p)if(M.default.undefined(p[N]))delete p[N];else if(M.default.null_(p[N]))throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${N}\` header`);if(h.decompress&&M.default.undefined(p["accept-encoding"])&&(p["accept-encoding"]=Cv?"gzip, deflate, br":"gzip, deflate"),h.cookieJar){let N=await h.cookieJar.getCookieString(h.url.toString());M.default.nonEmptyString(N)&&(h.headers.cookie=N)}for(let N of h.hooks.beforeRequest){let H=await N(h);if(!M.default.undefined(H)){h.request=()=>H;break}}h.body&&this[ft]!==h.body&&(this[ft]=h.body);let{agent:g,request:m,timeout:v,url:w}=h;if(h.dnsCache&&!("lookup"in h)&&(h.lookup=h.dnsCache.lookup),w.hostname==="unix"){let N=/(?<socketPath>.+?):(?<path>.+)/.exec(`${w.pathname}${w.search}`);if(N?.groups){let{socketPath:H,path:V}=N.groups;Object.assign(h,{socketPath:H,path:V,host:""})}}let E=w.protocol==="https:",O;h.http2?O=dv.auto:O=E?cv.request:Xh.request;let A=(e=h.request)!==null&&e!==void 0?e:O,k=h.cache?this._createCacheableRequest:A;g&&!h.http2&&(h.agent=g[E?"https":"http"]),h[pe]=A,delete h.request,delete h.timeout;let T=h;if(T.shared=(t=h.cacheOptions)===null||t===void 0?void 0:t.shared,T.cacheHeuristic=(i=h.cacheOptions)===null||i===void 0?void 0:i.cacheHeuristic,T.immutableMinTimeToLive=(a=h.cacheOptions)===null||a===void 0?void 0:a.immutableMinTimeToLive,T.ignoreCargoCult=(c=h.cacheOptions)===null||c===void 0?void 0:c.ignoreCargoCult,h.dnsLookupIpVersion!==void 0)try{T.family=nd.dnsLookupIpVersionToFamily(h.dnsLookupIpVersion)}catch{throw new Error("Invalid `dnsLookupIpVersion` option value")}h.https&&("rejectUnauthorized"in h.https&&(T.rejectUnauthorized=h.https.rejectUnauthorized),h.https.checkServerIdentity&&(T.checkServerIdentity=h.https.checkServerIdentity),h.https.certificateAuthority&&(T.ca=h.https.certificateAuthority),h.https.certificate&&(T.cert=h.https.certificate),h.https.key&&(T.key=h.https.key),h.https.passphrase&&(T.passphrase=h.https.passphrase),h.https.pfx&&(T.pfx=h.https.pfx));try{let N=await k(w,T);M.default.undefined(N)&&(N=O(w,T)),h.request=m,h.timeout=v,h.agent=g,h.https&&("rejectUnauthorized"in h.https&&delete T.rejectUnauthorized,h.https.checkServerIdentity&&delete T.checkServerIdentity,h.https.certificateAuthority&&delete T.ca,h.https.certificate&&delete T.cert,h.https.key&&delete T.key,h.https.passphrase&&delete T.passphrase,h.https.pfx&&delete T.pfx),kv(N)?this._onRequest(N):this.writable?(this.once("finish",()=>{this._onResponse(N)}),this._unlockWrite(),this.end(),this._lockWrite()):this._onResponse(N)}catch(N){throw N instanceof Zh.CacheError?new xn(N,this):new ce(N.message,N,this)}}async _error(e){try{for(let t of this.options.hooks.beforeError)e=await t(e)}catch(t){e=new ce(t.message,t,this)}this.destroy(e)}_beforeError(e){if(this[Yt])return;let{options:t}=this,i=this.retryCount+1;this[Yt]=!0,e instanceof ce||(e=new ce(e.message,e,this));let a=e,{response:c}=a;(async()=>{if(c&&!c.body){c.setEncoding(this._readableState.encoding);try{c.rawBody=await _v.default(c),c.body=c.rawBody.toString()}catch{}}if(this.listenerCount("retry")!==0){let h;try{let p;c&&"retry-after"in c.headers&&(p=Number(c.headers["retry-after"]),Number.isNaN(p)?(p=Date.parse(c.headers["retry-after"])-Date.now(),p<=0&&(p=1)):p*=1e3),h=await t.retry.calculateDelay({attemptCount:i,retryOptions:t.retry,error:a,retryAfter:p,computedValue:wv.default({attemptCount:i,retryOptions:t.retry,error:a,retryAfter:p,computedValue:0})})}catch(p){this._error(new ce(p.message,p,this));return}if(h){let p=async()=>{try{for(let g of this.options.hooks.beforeRetry)await g(this.options,a,i)}catch(g){this._error(new ce(g.message,e,this));return}this.destroyed||(this.destroy(),this.emit("retry",i,e))};this[cd]=setTimeout(p,h);return}}this._error(a)})()}_read(){this[Rn]=!0;let e=this[Pn];if(e&&!this[Yt]){e.readableLength&&(this[Rn]=!1);let t;for(;(t=e.read())!==null;){this[zt]+=t.length,this[od]=!0;let i=this.downloadProgress;i.percent<1&&this.emit("downloadProgress",i),this.push(t)}}}_write(e,t,i){let a=()=>{this._writeRequest(e,t,i)};this.requestInitialized?a():this[Ts].push(a)}_writeRequest(e,t,i){this[pe].destroyed||(this._progressCallbacks.push(()=>{this[Jt]+=Buffer.byteLength(e,t);let a=this.uploadProgress;a.percent<1&&this.emit("uploadProgress",a)}),this[pe].write(e,t,a=>{!a&&this._progressCallbacks.length>0&&this._progressCallbacks.shift()(),i(a)}))}_final(e){let t=()=>{for(;this._progressCallbacks.length!==0;)this._progressCallbacks.shift()();if(!(pe in this)){e();return}if(this[pe].destroyed){e();return}this[pe].end(i=>{i||(this[Kt]=this[Jt],this.emit("uploadProgress",this.uploadProgress),this[pe].emit("upload-complete")),e(i)})};this.requestInitialized?t():this[Ts].push(t)}_destroy(e,t){var i;this[Yt]=!0,clearTimeout(this[cd]),pe in this&&(this[ro](),!((i=this[Pn])===null||i===void 0)&&i.complete||this[pe].destroy()),e!==null&&!M.default.undefined(e)&&!(e instanceof ce)&&(e=new ce(e.message,e,this)),t(e)}get _isAboutToError(){return this[Yt]}get ip(){var e;return(e=this.socket)===null||e===void 0?void 0:e.remoteAddress}get aborted(){var e,t,i;return((t=(e=this[pe])===null||e===void 0?void 0:e.destroyed)!==null&&t!==void 0?t:this.destroyed)&&!(!((i=this[ad])===null||i===void 0)&&i.complete)}get socket(){var e,t;return(t=(e=this[pe])===null||e===void 0?void 0:e.socket)!==null&&t!==void 0?t:void 0}get downloadProgress(){let e;return this[Vt]?e=this[zt]/this[Vt]:this[Vt]===this[zt]?e=1:e=0,{percent:e,transferred:this[zt],total:this[Vt]}}get uploadProgress(){let e;return this[Kt]?e=this[Jt]/this[Kt]:this[Kt]===this[Jt]?e=1:e=0,{percent:e,transferred:this[Jt],total:this[Kt]}}get timings(){var e;return(e=this[pe])===null||e===void 0?void 0:e.timings}get isFromCache(){return this[id]}pipe(e,t){if(this[od])throw new Error("Failed to pipe. The response has been emitted already.");return e instanceof so.ServerResponse&&this[An].add(e),super.pipe(e,t)}unpipe(e){return e instanceof so.ServerResponse&&this[An].delete(e),super.unpipe(e),this}};X.default=Un});var Ps=$(Be=>{"use strict";var Rv=Be&&Be.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),Pv=Be&&Be.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Rv(e,s,t)};Object.defineProperty(Be,"__esModule",{value:!0});Be.CancelError=Be.ParseError=void 0;var ld=Rs(),oo=class extends ld.RequestError{constructor(e,t){let{options:i}=t.request;super(`${e.message} in "${i.url.toString()}"`,e,t.request),this.name="ParseError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_BODY_PARSE_FAILURE":this.code}};Be.ParseError=oo;var ao=class extends ld.RequestError{constructor(e){super("Promise was canceled",{},e),this.name="CancelError",this.code="ERR_CANCELED"}get isCanceled(){return!0}};Be.CancelError=ao;Pv(Rs(),Be)});var hd=$(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});var ud=Ps(),Iv=(s,e,t,i)=>{let{rawBody:a}=s;try{if(e==="text")return a.toString(i);if(e==="json")return a.length===0?"":t(a.toString());if(e==="buffer")return a;throw new ud.ParseError({message:`Unknown body type '${e}'`,name:"Error"},s)}catch(c){throw new ud.ParseError(c,s)}};co.default=Iv});var lo=$(pt=>{"use strict";var Mv=pt&&pt.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),xv=pt&&pt.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Mv(e,s,t)};Object.defineProperty(pt,"__esModule",{value:!0});var Nv=q("events"),Lv=st(),Dv=lu(),jn=Ps(),dd=hd(),fd=Rs(),Uv=Wi(),jv=Xi(),pd=Zi(),qv=["request","response","redirect","uploadProgress","downloadProgress"];function gd(s){let e,t,i=new Nv.EventEmitter,a=new Dv((h,p,g)=>{let m=v=>{let w=new fd.default(void 0,s);w.retryCount=v,w._noPipe=!0,g(()=>w.destroy()),g.shouldReject=!1,g(()=>p(new jn.CancelError(w))),e=w,w.once("response",async A=>{var k;if(A.retryCount=v,A.request.aborted)return;let T;try{T=await jv.default(w),A.rawBody=T}catch{return}if(w._isAboutToError)return;let N=((k=A.headers["content-encoding"])!==null&&k!==void 0?k:"").toLowerCase(),H=["gzip","deflate","br"].includes(N),{options:V}=w;if(H&&!V.decompress)A.body=T;else try{A.body=dd.default(A,V.responseType,V.parseJson,V.encoding)}catch(Z){if(A.body=T.toString(),pd.isResponseOk(A)){w._beforeError(Z);return}}try{for(let[Z,Q]of V.hooks.afterResponse.entries())A=await Q(A,async te=>{let ge=fd.default.normalizeArguments(void 0,{...te,retry:{calculateDelay:()=>0},throwHttpErrors:!1,resolveBodyOnly:!1},V);ge.hooks.afterResponse=ge.hooks.afterResponse.slice(0,Z);for(let gt of ge.hooks.beforeRetry)await gt(ge);let ot=gd(ge);return g(()=>{ot.catch(()=>{}),ot.cancel()}),ot})}catch(Z){w._beforeError(new jn.RequestError(Z.message,Z,w));return}if(t=A,!pd.isResponseOk(A)){w._beforeError(new jn.HTTPError(A));return}w.destroy(),h(w.options.resolveBodyOnly?A.body:A)});let E=A=>{if(a.isCanceled)return;let{options:k}=w;if(A instanceof jn.HTTPError&&!k.throwHttpErrors){let{response:T}=A;h(w.options.resolveBodyOnly?T.body:T);return}p(A)};w.once("error",E);let O=w.options.body;w.once("retry",(A,k)=>{var T,N;if(O===((T=k.request)===null||T===void 0?void 0:T.options.body)&&Lv.default.nodeStream((N=k.request)===null||N===void 0?void 0:N.options.body)){E(k);return}m(A)}),Uv.default(w,i,qv)};m(0)});a.on=(h,p)=>(i.on(h,p),a);let c=h=>{let p=(async()=>{await a;let{options:g}=t.request;return dd.default(t,h,g.parseJson,g.encoding)})();return Object.defineProperties(p,Object.getOwnPropertyDescriptors(a)),p};return a.json=()=>{let{headers:h}=e.options;return!e.writableFinished&&h.accept===void 0&&(h.accept="application/json"),c("json")},a.buffer=()=>c("buffer"),a.text=()=>c("text"),a}pt.default=gd;xv(Ps(),pt)});var md=$(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});var Bv=Ps();function $v(s,...e){let t=(async()=>{if(s instanceof Bv.RequestError)try{for(let a of e)if(a)for(let c of a)s=await c(s)}catch(a){s=a}throw s})(),i=()=>t;return t.json=i,t.text=i,t.buffer=i,t.on=i,t}uo.default=$v});var bd=$(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});var yd=st();function _d(s){for(let e of Object.values(s))(yd.default.plainObject(e)||yd.default.array(e))&&_d(e);return Object.freeze(s)}ho.default=_d});var wd=$(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0})});var fo=$(Le=>{"use strict";var Hv=Le&&Le.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),Gv=Le&&Le.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Hv(e,s,t)};Object.defineProperty(Le,"__esModule",{value:!0});Le.defaultHandler=void 0;var Cd=st(),Ne=lo(),Fv=md(),Bn=Rs(),Wv=bd(),Vv={RequestError:Ne.RequestError,CacheError:Ne.CacheError,ReadError:Ne.ReadError,HTTPError:Ne.HTTPError,MaxRedirectsError:Ne.MaxRedirectsError,TimeoutError:Ne.TimeoutError,ParseError:Ne.ParseError,CancelError:Ne.CancelError,UnsupportedProtocolError:Ne.UnsupportedProtocolError,UploadError:Ne.UploadError},zv=async s=>new Promise(e=>{setTimeout(e,s)}),{normalizeArguments:qn}=Bn.default,Ed=(...s)=>{let e;for(let t of s)e=qn(void 0,t,e);return e},Kv=s=>s.isStream?new Bn.default(void 0,s):Ne.default(s),Jv=s=>"defaults"in s&&"options"in s.defaults,Yv=["get","post","put","patch","head","delete"];Le.defaultHandler=(s,e)=>e(s);var kd=(s,e)=>{if(s)for(let t of s)t(e)},Od=s=>{s._rawHandlers=s.handlers,s.handlers=s.handlers.map(i=>(a,c)=>{let h,p=i(a,g=>(h=c(g),h));if(p!==h&&!a.isStream&&h){let g=p,{then:m,catch:v,finally:w}=g;Object.setPrototypeOf(g,Object.getPrototypeOf(h)),Object.defineProperties(g,Object.getOwnPropertyDescriptors(h)),g.then=m,g.catch=v,g.finally=w}return p});let e=(i,a={},c)=>{var h,p;let g=0,m=v=>s.handlers[g++](v,g===s.handlers.length?Kv:m);if(Cd.default.plainObject(i)){let v={...i,...a};Bn.setNonEnumerableProperties([i,a],v),a=v,i=void 0}try{let v;try{kd(s.options.hooks.init,a),kd((h=a.hooks)===null||h===void 0?void 0:h.init,a)}catch(E){v=E}let w=qn(i,a,c??s.options);if(w[Bn.kIsNormalizedAlready]=!0,v)throw new Ne.RequestError(v.message,v,w);return m(w)}catch(v){if(a.isStream)throw v;return Fv.default(v,s.options.hooks.beforeError,(p=a.hooks)===null||p===void 0?void 0:p.beforeError)}};e.extend=(...i)=>{let a=[s.options],c=[...s._rawHandlers],h;for(let p of i)Jv(p)?(a.push(p.defaults.options),c.push(...p.defaults._rawHandlers),h=p.defaults.mutableDefaults):(a.push(p),"handlers"in p&&c.push(...p.handlers),h=p.mutableDefaults);return c=c.filter(p=>p!==Le.defaultHandler),c.length===0&&c.push(Le.defaultHandler),Od({options:Ed(...a),handlers:c,mutableDefaults:!!h})};let t=async function*(i,a){let c=qn(i,a,s.options);c.resolveBodyOnly=!1;let h=c.pagination;if(!Cd.default.object(h))throw new TypeError("`options.pagination` must be implemented");let p=[],{countLimit:g}=h,m=0;for(;m<h.requestLimit;){m!==0&&await zv(h.backoff);let v=await e(void 0,void 0,c),w=await h.transform(v),E=[];for(let A of w)if(h.filter(A,p,E)&&(!h.shouldContinue(A,p,E)||(yield A,h.stackAllItems&&p.push(A),E.push(A),--g<=0)))return;let O=h.paginate(v,p,E);if(O===!1)return;O===v.request.options?c=v.request.options:O!==void 0&&(c=qn(void 0,O,c)),m++}};e.paginate=t,e.paginate.all=async(i,a)=>{let c=[];for await(let h of t(i,a))c.push(h);return c},e.paginate.each=t,e.stream=(i,a)=>e(i,{...a,isStream:!0});for(let i of Yv)e[i]=(a,c)=>e(a,{...c,method:i}),e.stream[i]=(a,c)=>e(a,{...c,method:i,isStream:!0});return Object.assign(e,Vv),Object.defineProperty(e,"defaults",{value:s.mutableDefaults?s:Wv.default(s),writable:s.mutableDefaults,configurable:s.mutableDefaults,enumerable:!0}),e.mergeOptions=Ed,e};Le.default=Od;Gv(wd(),Le)});var Hn=$((rt,$n)=>{"use strict";var Qv=rt&&rt.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),Sd=rt&&rt.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Qv(e,s,t)};Object.defineProperty(rt,"__esModule",{value:!0});var Xv=q("url"),Td=fo(),Zv={options:{method:"GET",retry:{limit:2,methods:["GET","PUT","HEAD","DELETE","OPTIONS","TRACE"],statusCodes:[408,413,429,500,502,503,504,521,522,524],errorCodes:["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"],maxRetryAfter:void 0,calculateDelay:({computedValue:s})=>s},timeout:{},headers:{"user-agent":"got (https://github.com/sindresorhus/got)"},hooks:{init:[],beforeRequest:[],beforeRedirect:[],beforeRetry:[],beforeError:[],afterResponse:[]},cache:void 0,dnsCache:void 0,decompress:!0,throwHttpErrors:!0,followRedirect:!0,isStream:!1,responseType:"text",resolveBodyOnly:!1,maxRedirects:10,prefixUrl:"",methodRewriting:!0,ignoreInvalidCookies:!1,context:{},http2:!1,allowGetBody:!1,https:void 0,pagination:{transform:s=>s.request.options.responseType==="json"?s.body:JSON.parse(s.body),paginate:s=>{if(!Reflect.has(s.headers,"link"))return!1;let e=s.headers.link.split(","),t;for(let i of e){let a=i.split(";");if(a[1].includes("next")){t=a[0].trimStart().trim(),t=t.slice(1,-1);break}}return t?{url:new Xv.URL(t)}:!1},filter:()=>!0,shouldContinue:()=>!0,countLimit:1/0,backoff:0,requestLimit:1e4,stackAllItems:!0},parseJson:s=>JSON.parse(s),stringifyJson:s=>JSON.stringify(s),cacheOptions:{}},handlers:[Td.defaultHandler],mutableDefaults:!1},po=Td.default(Zv);rt.default=po;$n.exports=po;$n.exports.default=po;$n.exports.__esModule=!0;Sd(fo(),rt);Sd(lo(),rt)});var xd=$((Ns,ko)=>{(function(s,e){typeof Ns=="object"&&typeof ko=="object"?ko.exports=e(dn(),Hn()):typeof define=="function"&&define.amd?define(["ws","got"],e):typeof Ns=="object"?Ns.Ably=e(dn(),Hn()):s.Ably=e(s.ws,s.got)})(Ns,(s,e)=>{var t={},i={exports:t},a=Object.create,c=Object.defineProperty,h=Object.defineProperties,p=Object.getOwnPropertyDescriptor,g=Object.getOwnPropertyDescriptors,m=Object.getOwnPropertyNames,v=Object.getOwnPropertySymbols,w=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty,O=Object.prototype.propertyIsEnumerable,A=(r,n,o)=>n in r?c(r,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):r[n]=o,k=(r,n)=>{for(var o in n||(n={}))E.call(n,o)&&A(r,o,n[o]);if(v)for(var o of v(n))O.call(n,o)&&A(r,o,n[o]);return r},T=(r,n)=>h(r,g(n)),N=(r,n)=>{var o={};for(var l in r)E.call(r,l)&&n.indexOf(l)<0&&(o[l]=r[l]);if(r!=null&&v)for(var l of v(r))n.indexOf(l)<0&&O.call(r,l)&&(o[l]=r[l]);return o},H=(r,n)=>function(){return n||(0,r[m(r)[0]])((n={exports:{}}).exports,n),n.exports},V=(r,n)=>{for(var o in n)c(r,o,{get:n[o],enumerable:!0})},Z=(r,n,o,l)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of m(n))!E.call(r,u)&&u!==o&&c(r,u,{get:()=>n[u],enumerable:!(l=p(n,u))||l.enumerable});return r},Q=(r,n,o)=>(o=r!=null?a(w(r)):{},Z(n||!r||!r.__esModule?c(o,"default",{value:r,enumerable:!0}):o,r)),te=function(r,n){this[0]=r,this[1]=n},ge=(r,n,o)=>{var l=(y,_,S,I)=>{try{var U=o[y](_),D=(_=U.value)instanceof te,F=U.done;Promise.resolve(D?_[0]:_).then(C=>D?l(y==="return"?y:"next",_[1]?{done:C.done,value:C.value}:C,S,I):S({value:C,done:F})).catch(C=>l("throw",C,S,I))}catch(C){I(C)}},u=y=>f[y]=_=>new Promise((S,I)=>l(y,_,S,I)),f={};return o=o.apply(r,n),f[Symbol.asyncIterator]=()=>f,u("next"),u("throw"),u("return"),f},ot=H({"node_modules/bops/from.js"(r,n){var o=q("buffer").Buffer,l=((process||{}).version||"v0.0.0").slice(1).split(".")[0];n.exports=Number(l)<6?function(f,y){return new o(f,y)}:function(f,y){return o.from(f,y)}}}),gt=H({"node_modules/bops/to.js"(r,n){n.exports=function(o,l){return o.toString(l)}}}),Vn=H({"node_modules/bops/is.js"(r,n){var o=q("buffer").Buffer;n.exports=function(l){return o.isBuffer(l)}}}),Xd=H({"node_modules/bops/subarray.js"(r,n){n.exports=function(o,l,u){return arguments.length===2?o.slice(l):o.slice(l,u)}}}),Zd=H({"node_modules/bops/join.js"(r,n){var o=q("buffer").Buffer;n.exports=function(l,u){return u!==void 0?o.concat(l,u):o.concat(l)}}}),ef=H({"node_modules/bops/copy.js"(r,n){n.exports=o;function o(l,u,f,y,_){return l.copy(u,f,y,_)}}}),tf=H({"node_modules/bops/create.js"(r,n){var o=q("buffer").Buffer,l=((process||{}).version||"v0.0.0").slice(1).split(".")[0];n.exports=Number(l)<6?function(f){return new o(f)}:function(f){return o.alloc(f)}}}),sf=H({"node_modules/bops/read.js"(r,n){var o={},l=/read.+/,u;u=function(y){var _="return buf."+y+"("+["a","b","c"].join(",")+")";return new Function(["buf","a","b","c"],_)},n.exports=o;for(f in Buffer.prototype)l.test(f)&&(o[f]=u(f));var f}}),nf=H({"node_modules/bops/write.js"(r,n){var o=q("buffer").Buffer,l={},u=/write.+/,f;f=function(_){var S="return buf."+_+"("+["a","b","c"].join(",")+")";return new Function(["buf","a","b","c"],S)},n.exports=l;for(y in o.prototype)u.test(y)&&(l[y]=f(y));var y}}),rf=H({"node_modules/bops/index.js"(r,n){var o={};n.exports=o,o.from=ot(),o.to=gt(),o.is=Vn(),o.subarray=Xd(),o.join=Zd(),o.copy=ef(),o.create=tf(),l(sf(),o),l(nf(),o);function l(u,f){for(var y in u)f[y]=u[y]}}}),of=H({"node_modules/@ably/msgpack-js/msgpack.js"(r){"use strict";var n=rf();r.encode=function(C,R){var P=F(C,R);if(P!=0){var j=n.create(P);return D(C,j,0,R),j}},r.decode=I;var o=65536*65536,l=1/o;function u(C,R){return R=R||0,C.readInt32BE(R+0)*o+C.readUInt32BE(R+4)}function f(C,R){return R=R||0,C.readUInt32BE(R+0)*o+C.readUInt32BE(R+4)}function y(C,R,P){R<9223372036854776e3?(C.writeInt32BE(Math.floor(R*l),P),C.writeInt32BE(R&-1,P+4)):(C.writeUInt32BE(2147483647,P),C.writeUInt32BE(4294967295,P+4))}function _(C,R,P){R<18446744073709552e3?(C.writeUInt32BE(Math.floor(R*l),P),C.writeInt32BE(R&-1,P+4)):(C.writeUInt32BE(4294967295,P),C.writeUInt32BE(4294967295,P+4))}function S(C,R){this.offset=R||0,this.buffer=C,this.bufferLength=C.length}S.prototype.map=function(C){if(C*2>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced a map of length ${C})`);for(var R={},P=0;P<C;P++){var j=this.parse();R[j]=this.parse()}return R},S.prototype.bin=S.prototype.buf=function(C){if(C>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced a binary of length ${C})`);var R=n.subarray(this.buffer,this.offset,this.offset+C);return this.offset+=C,R},S.prototype.str=function(C){if(C>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced a string of length ${C})`);var R=n.to(n.subarray(this.buffer,this.offset,this.offset+C));return this.offset+=C,R},S.prototype.array=function(C){if(C>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced an array of length ${C})`);for(var R=new Array(C),P=0;P<C;P++)R[P]=this.parse();return R},S.prototype.parse=function(){var C=this.buffer[this.offset],R,P,j;if(C===void 0)throw new Error("malformed messagepack (referenced offset is outside buffer)");if(!(C&128))return this.offset++,C;if((C&240)===128)return P=C&15,this.offset++,this.map(P);if((C&240)===144)return P=C&15,this.offset++,this.array(P);if((C&224)===160)return P=C&31,this.offset++,this.str(P);if((C&224)===224)return R=n.readInt8(this.buffer,this.offset),this.offset++,R;switch(C){case 192:return this.offset++,null;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return P=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,this.bin(P);case 197:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.bin(P);case 198:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.bin(P);case 199:return P=n.readUInt8(this.buffer,this.offset+1),j=n.readUInt8(this.buffer,this.offset+2),this.offset+=3,[j,this.bin(P)];case 200:return P=n.readUInt16BE(this.buffer,this.offset+1),j=n.readUInt8(this.buffer,this.offset+3),this.offset+=4,[j,this.bin(P)];case 201:return P=n.readUInt32BE(this.buffer,this.offset+1),j=n.readUInt8(this.buffer,this.offset+5),this.offset+=6,[j,this.bin(P)];case 202:return R=n.readFloatBE(this.buffer,this.offset+1),this.offset+=5,R;case 203:return R=n.readDoubleBE(this.buffer,this.offset+1),this.offset+=9,R;case 204:return R=this.buffer[this.offset+1],this.offset+=2,R;case 205:return R=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,R;case 206:return R=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,R;case 207:return R=f(this.buffer,this.offset+1),this.offset+=9,R;case 208:return R=n.readInt8(this.buffer,this.offset+1),this.offset+=2,R;case 209:return R=n.readInt16BE(this.buffer,this.offset+1),this.offset+=3,R;case 210:return R=n.readInt32BE(this.buffer,this.offset+1),this.offset+=5,R;case 211:return R=u(this.buffer,this.offset+1),this.offset+=9,R;case 212:return j=n.readUInt8(this.buffer,this.offset+1),R=n.readUInt8(this.buffer,this.offset+2),this.offset+=3,j===0&&R===0?void 0:[j,R];case 213:return j=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[j,this.bin(2)];case 214:return j=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[j,this.bin(4)];case 215:return j=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[j,this.bin(8)];case 216:return j=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[j,this.bin(16)];case 217:return P=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,this.str(P);case 218:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.str(P);case 219:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.str(P);case 220:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.array(P);case 221:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.array(P);case 222:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.map(P);case 223:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.map(P)}throw new Error("Unknown type 0x"+C.toString(16))};function I(C){var R=new S(C),P=R.parse();if(R.offset!==C.length)throw new Error(C.length-R.offset+" trailing bytes");return P}function U(C,R){return Object.keys(C).filter(function(P){var j=C[P],G=typeof j;return(!R||j!=null)&&(G!=="function"||!!j.toJSON)})}function D(C,R,P,j,G){var z=typeof C,W,ee;if(z==="string"){if(C=n.from(C),W=C.length,W<32)return R[P]=W|160,n.copy(C,R,P+1),1+W;if(W<256)return R[P]=217,n.writeUInt8(R,W,P+1),n.copy(C,R,P+2),2+W;if(W<65536)return R[P]=218,n.writeUInt16BE(R,W,P+1),n.copy(C,R,P+3),3+W;if(W<4294967296)return R[P]=219,n.writeUInt32BE(R,W,P+1),n.copy(C,R,P+5),5+W}if(n.is(C)){if(W=C.length,W<256)return R[P]=196,n.writeUInt8(R,W,P+1),n.copy(C,R,P+2),2+W;if(W<65536)return R[P]=197,n.writeUInt16BE(R,W,P+1),n.copy(C,R,P+3),3+W;if(W<4294967296)return R[P]=198,n.writeUInt32BE(R,W,P+1),n.copy(C,R,P+5),5+W}if(z==="number"){if(Math.floor(C)!==C)return R[P]=203,n.writeDoubleBE(R,C,P+1),9;if(C>=0){if(C<128)return R[P]=C,1;if(C<256)return R[P]=204,R[P+1]=C,2;if(C<65536)return R[P]=205,n.writeUInt16BE(R,C,P+1),3;if(C<4294967296)return R[P]=206,n.writeUInt32BE(R,C,P+1),5;if(C<18446744073709552e3)return R[P]=207,_(R,C,P+1),9;throw new Error("Number too big 0x"+C.toString(16))}if(C>=-32)return n.writeInt8(R,C,P),1;if(C>=-128)return R[P]=208,n.writeInt8(R,C,P+1),2;if(C>=-32768)return R[P]=209,n.writeInt16BE(R,C,P+1),3;if(C>=-2147483648)return R[P]=210,n.writeInt32BE(R,C,P+1),5;if(C>=-9223372036854776e3)return R[P]=211,y(R,C,P+1),9;throw new Error("Number too small -0x"+C.toString(16).substr(1))}if(z==="undefined")return j&&G?0:(R[P]=212,R[P+1]=0,R[P+2]=0,3);if(C===null)return j&&G?0:(R[P]=192,1);if(z==="boolean")return R[P]=C?195:194,1;if(typeof C.toJSON=="function")return D(C.toJSON(),R,P,j);if(z==="object"){ee=0;var Oe=Array.isArray(C);if(Oe)W=C.length;else{var ve=U(C,j);W=ve.length}if(W<16?(R[P]=W|(Oe?144:128),ee=1):W<65536?(R[P]=Oe?220:222,n.writeUInt16BE(R,W,P+1),ee=3):W<4294967296&&(R[P]=Oe?221:223,n.writeUInt32BE(R,W,P+1),ee=5),Oe)for(var ze=0;ze<W;ze++)ee+=D(C[ze],R,P+ee,j);else for(var ze=0;ze<W;ze++){var mc=ve[ze];ee+=D(mc,R,P+ee),ee+=D(C[mc],R,P+ee,j,!0)}return ee}if(z!=="function")throw new Error("Unknown type "+z)}function F(C,R,P){var j=typeof C,G,z;if(j==="string"){if(G=n.from(C).length,G<32)return 1+G;if(G<256)return 2+G;if(G<65536)return 3+G;if(G<4294967296)return 5+G}if(n.is(C)){if(G=C.length,G<256)return 2+G;if(G<65536)return 3+G;if(G<4294967296)return 5+G}if(j==="number"){if(Math.floor(C)!==C)return 9;if(C>=0){if(C<128)return 1;if(C<256)return 2;if(C<65536)return 3;if(C<4294967296)return 5;if(C<18446744073709552e3)return 9;throw new Error("Number too big 0x"+C.toString(16))}if(C>=-32)return 1;if(C>=-128)return 2;if(C>=-32768)return 3;if(C>=-2147483648)return 5;if(C>=-9223372036854776e3)return 9;throw new Error("Number too small -0x"+C.toString(16).substr(1))}if(j==="boolean")return 1;if(C===null)return R&&P?0:1;if(C===void 0)return R&&P?0:3;if(typeof C.toJSON=="function")return F(C.toJSON(),R);if(j==="object"){if(z=0,Array.isArray(C)){G=C.length;for(var W=0;W<G;W++)z+=F(C[W],R)}else{var ee=U(C,R);G=ee.length;for(var W=0;W<G;W++){var Oe=ee[W];z+=F(Oe)+F(C[Oe],R,!0)}}if(G<16)return 1+z;if(G<65536)return 3+z;if(G<4294967296)return 5+z;throw new Error("Array or object too long 0x"+G.toString(16))}if(j==="function")return 0;throw new Error("Unknown type "+j)}}}),L=class{},Po=typeof global<"u"?global:typeof window<"u"?window:self;function Ls(r,n){return`${r}`.padStart(n?3:2,"0")}function af(r){return L.Config.logTimestamps?function(n){let o=new Date;r(Ls(o.getHours())+":"+Ls(o.getMinutes())+":"+Ls(o.getSeconds())+"."+Ls(o.getMilliseconds(),1)+" "+n)}:function(n){r(n)}}var cf=()=>{var r;let n,o;return typeof((r=Po?.console)==null?void 0:r.log)=="function"?(n=function(...l){console.log.apply(console,l)},o=console.warn?function(...l){console.warn.apply(console,l)}:n):n=o=function(){},[n,o].map(af)},Ge=class Is{constructor(){this.deprecated=(n,o)=>{this.deprecationWarning(`${n} is deprecated and will be removed in a future version. ${o}`)},this.shouldLog=n=>n<=this.logLevel,this.setLog=(n,o)=>{n!==void 0&&(this.logLevel=n),o!==void 0&&(this.logHandler=this.logErrorHandler=o)},this.logLevel=Is.defaultLogLevel,this.logHandler=Is.defaultLogHandler,this.logErrorHandler=Is.defaultLogErrorHandler}static initLogHandlers(){let[n,o]=cf();this.defaultLogHandler=n,this.defaultLogErrorHandler=o,this.defaultLogger=new Is}static logActionNoStrip(n,o,l,u){n.logAction(o,l,u)}logAction(n,o,l){this.shouldLog(n)&&(n===1?this.logErrorHandler:this.logHandler)("Ably: "+o+": "+l,n)}renamedClientOption(n,o){this.deprecationWarning(`The \`${n}\` client option has been renamed to \`${o}\`. Please update your code to use \`${o}\` instead. \`${n}\` will be removed in a future version.`)}renamedMethod(n,o,l){this.deprecationWarning(`\`${n}\`\u2019s \`${o}\` method has been renamed to \`${l}\`. Please update your code to use \`${l}\` instead. \`${o}\` will be removed in a future version.`)}deprecationWarning(n){this.shouldLog(1)&&this.logErrorHandler(`Ably: Deprecation warning - ${n}`,1)}};Ge.defaultLogLevel=1,Ge.LOG_NONE=0,Ge.LOG_ERROR=1,Ge.LOG_MAJOR=2,Ge.LOG_MINOR=3,Ge.LOG_MICRO=4,Ge.logAction=(r,n,o,l)=>{Ge.logActionNoStrip(r,n,o,l)};var lf=Ge,d=lf,Zt={};V(Zt,{Format:()=>Bo,allSame:()=>mf,allToLowerCase:()=>Vo,allToUpperCase:()=>zo,arrChooseN:()=>Wo,arrDeleteValue:()=>Uo,arrEquals:()=>Qo,arrIntersect:()=>Lo,arrIntersectOb:()=>Do,arrPopRandomElement:()=>zn,arrWithoutValue:()=>gf,cheapRandStr:()=>Go,containsValue:()=>pf,copy:()=>es,createMissingPluginError:()=>ss,dataSizeBytes:()=>Ho,decodeBody:()=>he,encodeBody:()=>De,ensureArray:()=>Mo,forInOwnNonNullProperties:()=>qo,getBackoffCoefficient:()=>Ko,getGlobalObject:()=>yf,getJitterCoefficient:()=>Jo,getRetryTime:()=>Yn,inherits:()=>ff,inspectBody:()=>$o,inspectError:()=>se,intersect:()=>No,isEmpty:()=>hf,isErrorInfoOrPartialErrorInfo:()=>Jn,isNil:()=>Fe,isObject:()=>Ot,keysArray:()=>Ds,listenerToAsyncIterator:()=>_f,matchDerivedChannel:()=>Yo,mixin:()=>Y,parseQueryString:()=>Us,prototypicalClone:()=>xo,randomString:()=>Fo,shallowClone:()=>df,shallowEquals:()=>Qn,stringifyValues:()=>Kn,throwMissingPluginError:()=>me,toBase64:()=>js,toQueryString:()=>ts,valuesArray:()=>jo,whenPromiseSettles:()=>Te,withTimeoutAsync:()=>Xo});function Io(r){let n="["+r.constructor.name;return r.message&&(n+=": "+r.message),r.statusCode&&(n+="; statusCode="+r.statusCode),r.code&&(n+="; code="+r.code),r.cause&&(n+="; cause="+se(r.cause)),r.href&&!(r.message&&r.message.indexOf("help.ably.io")>-1)&&(n+="; see "+r.href+" "),n+="]",n}var x=class go extends Error{constructor(n,o,l,u){super(n),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,go.prototype),this.code=o,this.statusCode=l,this.cause=u}toString(){return Io(this)}static fromValues(n){let{message:o,code:l,statusCode:u}=n;if(typeof o!="string"||typeof l!="number"||typeof u!="number")throw new Error("ErrorInfo.fromValues(): invalid values: "+L.Config.inspect(n));let f=Object.assign(new go(o,l,u),n);return f.code&&!f.href&&(f.href="https://help.ably.io/error/"+f.code),f}},Se=class mo extends Error{constructor(n,o,l,u){super(n),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,mo.prototype),this.code=o,this.statusCode=l,this.cause=u}toString(){return Io(this)}static fromValues(n){let{message:o,code:l,statusCode:u}=n;if(typeof o!="string"||!Fe(l)&&typeof l!="number"||!Fe(u)&&typeof u!="number")throw new Error("PartialErrorInfo.fromValues(): invalid values: "+L.Config.inspect(n));let f=Object.assign(new mo(o,l,u),n);return f.code&&!f.href&&(f.href="https://help.ably.io/error/"+f.code),f}};function uf(r){return Math.floor(Math.random()*r.length)}function Y(r,...n){for(let o=0;o<n.length;o++){let l=n[o];if(!l)break;for(let u in l)Object.prototype.hasOwnProperty.call(l,u)&&(r[u]=l[u])}return r}function es(r){return Y({},r)}function Mo(r){return Fe(r)?[]:Array.isArray(r)?r:[r]}function Ot(r){return Object.prototype.toString.call(r)=="[object Object]"}function hf(r){for(let n in r)return!1;return!0}function Fe(r){return r==null}function df(r){let n=new Object;for(let o in r)n[o]=r[o];return n}function xo(r,n){class o{}o.prototype=r;let l=new o;return n&&Y(l,n),l}var ff=function(r,n){if(L.Config.inherits){L.Config.inherits(r,n);return}r.super_=n,r.prototype=xo(n.prototype,{constructor:r})};function pf(r,n){for(let o in r)if(r[o]==n)return!0;return!1}function No(r,n){return Array.isArray(n)?Lo(r,n):Do(r,n)}function Lo(r,n){let o=[];for(let l=0;l<r.length;l++){let u=r[l];n.indexOf(u)!=-1&&o.push(u)}return o}function Do(r,n){let o=[];for(let l=0;l<r.length;l++){let u=r[l];u in n&&o.push(u)}return o}function Uo(r,n){let o=r.indexOf(n),l=o!=-1;return l&&r.splice(o,1),l}function gf(r,n){let o=r.slice();return Uo(o,n),o}function Ds(r,n){let o=[];for(let l in r)n&&!Object.prototype.hasOwnProperty.call(r,l)||o.push(l);return o}function jo(r,n){let o=[];for(let l in r)n&&!Object.prototype.hasOwnProperty.call(r,l)||o.push(r[l]);return o}function qo(r,n){for(let o in r)Object.prototype.hasOwnProperty.call(r,o)&&r[o]&&n(o)}function mf(r,n){if(r.length===0)return!0;let o=r[0][n];return r.every(function(l){return l[n]===o})}var Bo=(r=>(r.msgpack="msgpack",r.json="json",r))(Bo||{});function zn(r){return r.splice(uf(r),1)[0]}function ts(r){let n=[];if(r)for(let o in r)n.push(encodeURIComponent(o)+"="+encodeURIComponent(r[o]));return n.length?"?"+n.join("&"):""}function Kn(r){return Object.fromEntries(Object.entries(r).map(([n,o])=>[n,String(o)]))}function Us(r){let n,o=/([^?&=]+)=?([^&]*)/g,l={};for(;n=o.exec(r);)l[decodeURIComponent(n[1])]=decodeURIComponent(n[2]);return l}function Jn(r){return typeof r=="object"&&r!==null&&(r instanceof x||r instanceof Se)}function se(r){var n,o;return r instanceof Error||((n=r?.constructor)==null?void 0:n.name)==="ErrorInfo"||((o=r?.constructor)==null?void 0:o.name)==="PartialErrorInfo"?r.toString():L.Config.inspect(r)}function $o(r){return L.BufferUtils.isBuffer(r)?r.toString():typeof r=="string"?r:L.Config.inspect(r)}function Ho(r){if(L.BufferUtils.isBuffer(r))return L.BufferUtils.byteLength(r);if(typeof r=="string")return L.Config.stringByteSize(r);if(typeof r=="number")return 8;if(typeof r=="boolean")return 1;throw new Error(`Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: ${typeof r}`)}function Go(){return String(Math.random()).substr(2)}var Fo=async r=>{let n=await L.Config.getRandomArrayBuffer(r);return L.BufferUtils.base64Encode(n)};function Wo(r,n){let o=Math.min(n,r.length),l=r.slice(),u=[];for(let f=0;f<o;f++)u.push(zn(l));return u}function Te(r,n){r.then(o=>{n?.(null,o)}).catch(o=>{n?.(o)})}function he(r,n,o){return o=="msgpack"?(n||me("MsgPack"),n.decode(r)):JSON.parse(String(r))}function De(r,n,o){return o=="msgpack"?(n||me("MsgPack"),n.encode(r,!0)):JSON.stringify(r)}function Vo(r){return r.map(function(n){return n&&n.toLowerCase()})}function zo(r){return r.map(function(n){return n&&n.toUpperCase()})}function Ko(r){return Math.min((r+2)/3,2)}function Jo(){return 1-Math.random()*.2}function Yn(r,n){return r*Ko(n)*Jo()}function yf(){return typeof global<"u"?global:typeof window<"u"?window:self}function Qn(r,n){return Object.keys(r).every(o=>r[o]===n[o])&&Object.keys(n).every(o=>n[o]===r[o])}function Yo(r){let n=/^(\[([^?]*)(?:(.*))\])?(.+)$/,o=r.match(n);if(!o||!o.length||o.length<5)throw new x("regex match failed",400,40010);if(o[2])throw new x(`cannot use a derived option with a ${o[2]} channel`,400,40010);return{qualifierParam:o[3]||"",channelName:o[4]}}function js(r){let n=L.BufferUtils,o=n.utf8Encode(r);return n.base64Encode(o)}function Qo(r,n){return r.length===n.length&&r.every(function(o,l){return o===n[l]})}function ss(r){return new x(`${r} plugin not provided`,40019,400)}function me(r){throw ss(r)}async function Xo(r,n=5e3,o="Timeout expired"){let l=new x(o,5e4,500);return Promise.race([r,new Promise((u,f)=>setTimeout(()=>f(l),n))])}function _f(r){return ge(this,null,function*(){let n=[],o=null,l=r(u=>{if(o){let f=o;o=null,f(u)}else n.push(u)});try{for(;;)if(n.length>0)yield n.shift();else{if(o)throw new x("Concurrent next() calls are not supported",4e4,400);yield yield new te(new Promise(f=>{o=f}))}}finally{l()}})}var Zo="2.17.0",bf="ably-js/"+Zo,Ue={ENDPOINT:"main",ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["main.a.fallback.ably-realtime.com","main.b.fallback.ably-realtime.com","main.c.fallback.ably-realtime.com","main.d.fallback.ably-realtime.com","main.e.fallback.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:1e4,httpMaxRetryDuration:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,webSocketConnectTimeout:1e4,webSocketSlowTimeout:4e3},httpMaxRetryCount:3,maxMessageSize:65536,version:Zo,protocolVersion:5,agent:bf,getPort:vf,getHttpScheme:wf,getPrimaryDomainFromEndpoint:ta,getEndpointFallbackHosts:sa,getFallbackHosts:ra,getHosts:Cf,checkHost:ia,objectifyOptions:kf,normaliseOptions:Sf,defaultGetHeaders:Tf,defaultPostHeaders:Af};function vf(r,n){return n||r.tls?r.tlsPort:r.port}function wf(r){return r.tls?"https://":"http://"}function ea(r){return r.includes(".")||r.includes("::")||r==="localhost"}function ta(r){return ea(r)?r:r.startsWith("nonprod:")?`${r.replace("nonprod:","")}.realtime.ably-nonprod.net`:`${r}.realtime.ably.net`}function sa(r){if(ea(r))return[];if(r.startsWith("nonprod:")){let n=r.replace("nonprod:","");return na(n,"ably-realtime-nonprod.com")}return na(r,"ably-realtime.com")}function na(r,n){return["a","b","c","d","e"].map(o=>`${r}.${o}.fallback.${n}`)}function ra(r){let n=r.fallbackHosts,o=typeof r.httpMaxRetryCount<"u"?r.httpMaxRetryCount:Ue.httpMaxRetryCount;return n?Wo(n,o):[]}function Cf(r){return[r.primaryDomain].concat(ra(r))}function ia(r){if(typeof r!="string")throw new x("host must be a string; was a "+typeof r,4e4,400);if(!r.length)throw new x("host must not be zero-length",4e4,400)}function Ef(r){let n={};for(let o in Ue.TIMEOUTS)n[o]=r[o]||Ue.TIMEOUTS[o];return n}function Xn(r){let n=Ue.agent;if(r.agents)for(var o in r.agents)n+=" "+o+"/"+r.agents[o];return n}function kf(r,n,o,l,u){if(r===void 0){let y=n?`${o} must be initialized with either a client options object, an Ably API key, or an Ably Token`:`${o} must be initialized with a client options object`;throw d.logAction(l,d.LOG_ERROR,`${o}()`,y),new Error(y)}let f;if(typeof r=="string")if(r.indexOf(":")==-1){if(!n){let y=`${o} cannot be initialized with just an Ably Token; you must provide a client options object with a \`plugins\` property. (Set this Ably Token as the object\u2019s \`token\` property.)`;throw d.logAction(l,d.LOG_ERROR,`${o}()`,y),new Error(y)}f={token:r}}else{if(!n){let y=`${o} cannot be initialized with just an Ably API key; you must provide a client options object with a \`plugins\` property. (Set this Ably API key as the object\u2019s \`key\` property.)`;throw d.logAction(l,d.LOG_ERROR,`${o}()`,y),new Error(y)}f={key:r}}else f=r;return u&&(f=T(k({},f),{plugins:k(k({},u),f.plugins)})),f}function Of(r){if(r.endpoint&&(r.environment||r.restHost||r.realtimeHost))throw new x("The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",40106,400);if(r.environment&&(r.restHost||r.realtimeHost))throw new x("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function Sf(r,n,o){let l=o??d.defaultLogger;r.environment&&l.deprecated("The `environment` client option","Use the `endpoint` client option instead."),r.restHost&&l.deprecated("The `restHost` client option","Use the `endpoint` client option instead."),r.realtimeHost&&l.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead."),Of(r),typeof r.recover=="function"&&r.closeOnUnload===!0&&(d.logAction(l,d.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),r.recover=void 0),"closeOnUnload"in r||(r.closeOnUnload=!r.recover),"queueMessages"in r||(r.queueMessages=!0);let u=r.endpoint||Ue.ENDPOINT;!r.fallbackHosts&&!r.restHost&&!r.realtimeHost&&!r.port&&!r.tlsPort&&(r.fallbackHosts=sa(r.environment||u));let f=r.environment&&`${r.environment}.realtime.ably.net`,_=r.restHost||r.realtimeHost||f||ta(u);(r.fallbackHosts||[]).concat(_).forEach(ia),r.port=r.port||Ue.PORT,r.tlsPort=r.tlsPort||Ue.TLS_PORT,"tls"in r||(r.tls=!0);let S=Ef(r);n?"useBinaryProtocol"in r?r.useBinaryProtocol=L.Config.supportsBinary&&r.useBinaryProtocol:r.useBinaryProtocol=L.Config.preferBinary:r.useBinaryProtocol=!1;let I={};r.clientId&&(I["X-Ably-ClientId"]=L.BufferUtils.base64Encode(L.BufferUtils.utf8Encode(r.clientId))),"idempotentRestPublishing"in r||(r.idempotentRestPublishing=!0);let U=null,D=r.connectivityCheckUrl;if(r.connectivityCheckUrl){let[C,R]=r.connectivityCheckUrl.split("?");U=R?Us(R):{},C.indexOf("://")===-1&&(C="https://"+C),D=C}let F=r.wsConnectivityCheckUrl;return F&&F.indexOf("://")===-1&&(F="wss://"+F),T(k({},r),{primaryDomain:_,maxMessageSize:r.maxMessageSize||Ue.maxMessageSize,timeouts:S,connectivityCheckParams:U,connectivityCheckUrl:D,wsConnectivityCheckUrl:F,headers:I})}function qs(r,n,o){let l=o||{};if(l.cipher){r||me("Crypto");let u=r.getCipher(l.cipher,n);l.cipher=u.cipherParams,l.channelCipher=u.cipher}else"cipher"in l&&(l.cipher=void 0,l.channelCipher=null);return l}var oa={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},aa={format:"json",protocolVersion:Ue.protocolVersion};function Tf(r,{format:n,protocolVersion:o=aa.protocolVersion}={}){return{accept:oa[n??(r.useBinaryProtocol?"msgpack":"json")],"X-Ably-Version":o.toString(),"Ably-Agent":Xn(r)}}function Af(r,{format:n,protocolVersion:o=aa.protocolVersion}={}){let l=oa[n??(r.useBinaryProtocol?"msgpack":"json")];return{accept:l,"content-type":l,"X-Ably-Version":o.toString(),"Ably-Agent":Xn(r)}}var J=Ue;function Rf(r){return Object.assign(Ue,r)}var Pf=class Ad{constructor(n,o){this.logger=n,this.members=o||[]}call(n,o){for(let l of this.members)if(l)try{l(n,o)}catch(u){d.logAction(this.logger,d.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+u+"; stack = "+u.stack)}}push(...n){this.members.push(...n)}createPromise(){return new Promise((n,o)=>{this.push((l,u)=>{l?o(l):n(u)})})}resolveAll(n){this.call(null,n)}rejectAll(n){this.call(n)}static create(n,o){let l=new Ad(n,o);return Object.assign((u,f)=>l.call(u,f),{push:u=>l.push(u),createPromise:()=>l.createPromise(),resolveAll:u=>l.resolveAll(u),rejectAll:u=>l.rejectAll(u)})}},ca=Pf,la=(r=>(r.Get="get",r.Delete="delete",r.Post="post",r.Put="put",r.Patch="patch",r))(la||{}),le=la,ua=(r=>(r[r.Success=200]="Success",r[r.NoContent=204]="NoContent",r[r.BadRequest=400]="BadRequest",r[r.Unauthorized=401]="Unauthorized",r[r.Forbidden=403]="Forbidden",r[r.RequestTimeout=408]="RequestTimeout",r[r.InternalServerError=500]="InternalServerError",r))(ua||{});function If(r){return r>=200&&r<400}var ns=ua,Zn=Math.pow(2,17);function Mf(){return("000000"+Math.floor(Math.random()*1e16)).slice(-16)}function xf(r){return!!r.connection}function ha(r){return Jn(r)?(r.code||(r.statusCode===403?r.code=40300:(r.code=40170,r.statusCode=401)),r):new x(se(r),r.code||40170,r.statusCode||401)}var Nf=(r,n)=>{let o=L.BufferUtils,l=o.utf8Encode(r),u=o.utf8Encode(n),f=o.hmacSha256(l,u);return o.base64Encode(f)};function da(r){if(!r)return"";typeof r=="string"&&(r=JSON.parse(r));let n=Object.create(null),o=Ds(r,!0);if(!o)return"";o.sort();for(let l=0;l<o.length;l++)n[o[l]]=r[o[l]].sort();return JSON.stringify(n)}function fa(r,n){if(r.authCallback)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with authCallback");else if(r.authUrl)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with authUrl");else if(r.key)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(r.tokenDetails)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with supplied token only");else{let o="authOptions must include valid authentication parameters";throw d.logAction(n,d.LOG_ERROR,"Auth()",o),new Error(o)}}function Lf(r){return"useTokenAuth"in r&&!r.useTokenAuth}function pa(r){return r.useTokenAuth||!Lf(r)&&(r.authCallback||r.authUrl||r.token||r.tokenDetails)}function Df(r){return!r.key&&!r.authCallback&&!r.authUrl}var Uf=0;function jf(){return Uf++}var qf=class{constructor(r,n){if(this.authOptions={},this.client=r,this.tokenParams=n.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,pa(n))Df(n)&&d.logAction(this.logger,d.LOG_ERROR,"Auth()","Warning: library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),this._saveTokenOptions(n.defaultTokenParams,n),fa(this.authOptions,this.logger);else{if(!n.key){let o="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw d.logAction(this.logger,d.LOG_ERROR,"Auth()",o),new x(o,40160,401)}d.logAction(this.logger,d.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(n)}}get logger(){return this.client.logger}async authorize(r,n){if(n&&n.key&&this.authOptions.key!==n.key)throw new x("Unable to update auth options with incompatible key",40102,401);try{let o=await this._forceNewToken(r??null,n??null);return xf(this.client)?new Promise((l,u)=>{this.client.connection.connectionManager.onAuthUpdated(o,(f,y)=>f?u(f):l(y))}):o}catch(o){throw this.client.connection&&o.statusCode===ns.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(o),o}}async _forceNewToken(r,n){this.tokenDetails=null,this._saveTokenOptions(r,n),fa(this.authOptions,this.logger);try{return this._ensureValidAuthCredentials(!0)}finally{delete this.tokenParams.timestamp,delete this.authOptions.queryTime}}async requestToken(r,n){let o=n||this.authOptions,l=r||es(this.tokenParams),u,f=this.client;if(o.authCallback)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),u=o.authCallback;else if(o.authUrl)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),u=(_,S)=>{let I=Y({accept:"application/json, text/plain"},o.authHeaders),U=o.authMethod&&o.authMethod.toLowerCase()==="post",D,F=o.authUrl.indexOf("?");F>-1&&(D=Us(o.authUrl.slice(F)),o.authUrl=o.authUrl.slice(0,F),U||(o.authParams=Y(D,o.authParams)));let C=Y({},o.authParams||{},_),R=P=>{var j,G;let z=(j=P.body)!=null?j:null,W=null;if(P.error)d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+se(P.error));else{let ve=(G=P.headers["content-type"])!=null?G:null;Array.isArray(ve)?W=ve.join(", "):W=ve,d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+W+"; body: "+$o(z))}if(P.error){S(P.error,null);return}if(P.unpacked){S(null,z);return}if(L.BufferUtils.isBuffer(z)&&(z=z.toString()),!W){S(new x("authUrl response is missing a content-type header",40170,401),null);return}let ee=W.indexOf("application/json")>-1,Oe=W.indexOf("text/plain")>-1||W.indexOf("application/jwt")>-1;if(!ee&&!Oe){S(new x("authUrl responded with unacceptable content-type "+W+", should be either text/plain, application/jwt or application/json",40170,401),null);return}if(ee){if(z.length>Zn){S(new x("authUrl response exceeded max permitted length",40170,401),null);return}try{z=JSON.parse(z)}catch(ve){S(new x("Unexpected error processing authURL response; err = "+ve.message,40170,401),null);return}}S(null,z,W)};if(d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+o.authUrl+"; Params: "+JSON.stringify(C)+"; method: "+(U?"POST":"GET")),U){let P=I||{};P["content-type"]="application/x-www-form-urlencoded";let j=ts(C).slice(1);Te(this.client.http.doUri(le.Post,o.authUrl,P,j,D),(G,z)=>R(G||z))}else Te(this.client.http.doUri(le.Get,o.authUrl,I||{},null,C),(P,j)=>R(P||j))};else if(o.key)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),u=(_,S)=>{Te(this.createTokenRequest(_,o),(I,U)=>S(I,U??null))};else{let _="Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)";throw d.logAction(this.logger,d.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),new x(_,40171,403)}"capability"in l&&(l.capability=da(l.capability));let y=(_,S)=>{let I=_.keyName,U="/keys/"+I+"/requestToken",D=function(C){return f.baseUri(C)+U},F=J.defaultPostHeaders(this.client.options,{format:"json"});o.requestHeaders&&Y(F,o.requestHeaders),d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+U+"; Token params: "+JSON.stringify(_)),Te(this.client.http.do(le.Post,D,F,JSON.stringify(_),null),(C,R)=>C?S(C):S(R.error,R.body,R.unpacked))};return new Promise((_,S)=>{let I=!1,U=this.client.options.timeouts.realtimeRequestTimeout,D=setTimeout(()=>{I=!0;let F="Token request callback timed out after "+U/1e3+" seconds";d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()",F),S(new x(F,40170,401))},U);u(l,(F,C,R)=>{if(I)return;if(clearTimeout(D),F){d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+se(F)),S(ha(F));return}if(typeof C=="string"){C.length===0?S(new x("Token string is empty",40170,401)):C.length>Zn?S(new x("Token string exceeded max permitted length (was "+C.length+" bytes)",40170,401)):C==="undefined"||C==="null"?S(new x("Token string was literal null/undefined",40170,401)):C[0]==="{"&&!(R&&R.indexOf("application/jwt")>-1)?S(new x("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401)):_({token:C});return}if(typeof C!="object"||C===null){let j="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof C;d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()",j),S(new x(j,40170,401));return}let P=JSON.stringify(C).length;if(P>Zn&&!o.suppressMaxLengthCheck){S(new x("Token request/details object exceeded max permitted stringified size (was "+P+" bytes)",40170,401));return}if("issued"in C){_(C);return}if(!("keyName"in C)){let j="Expected token request callback to call back with a token string, token request object, or token details object";d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()",j),S(new x(j,40170,401));return}y(C,(j,G,z)=>{if(j){d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+se(j)),S(ha(j));return}z||(G=JSON.parse(G)),d.logAction(this.logger,d.LOG_MINOR,"Auth.getToken()","token received"),_(G)})})})}async createTokenRequest(r,n){n=n||this.authOptions,r=r||es(this.tokenParams);let o=n.key;if(!o)throw new x("No key specified",40101,403);let l=o.split(":"),u=l[0],f=l[1];if(!f)throw new x("Invalid key specified",40101,403);if(r.clientId==="")throw new x("clientId can\u2019t be an empty string",40012,400);"capability"in r&&(r.capability=da(r.capability));let y=Y({keyName:u},r),_=r.clientId||"",S=r.ttl||"",I=r.capability||"";y.timestamp||(y.timestamp=await this._getTimestamp(n&&n.queryTime));let U=y.nonce||(y.nonce=Mf()),D=y.timestamp,F=y.keyName+`
|
|
38
|
+
`)}`}}};Z.RequestError=he;var Mn=class extends he{constructor(e){super(`Redirected ${e.options.maxRedirects} times. Aborting.`,{},e),this.name="MaxRedirectsError",this.code="ERR_TOO_MANY_REDIRECTS"}};Z.MaxRedirectsError=Mn;var xn=class extends he{constructor(e){super(`Response code ${e.statusCode} (${e.statusMessage})`,{},e.request),this.name="HTTPError",this.code="ERR_NON_2XX_3XX_RESPONSE"}};Z.HTTPError=xn;var Nn=class extends he{constructor(e,t){super(e.message,e,t),this.name="CacheError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_CACHE_ACCESS":this.code}};Z.CacheError=Nn;var Ln=class extends he{constructor(e,t){super(e.message,e,t),this.name="UploadError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_UPLOAD":this.code}};Z.UploadError=Ln;var Dn=class extends he{constructor(e,t,i){super(e.message,e,i),this.name="TimeoutError",this.event=e.event,this.timings=t}};Z.TimeoutError=Dn;var Rs=class extends he{constructor(e,t){super(e.message,e,t),this.name="ReadError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_READING_RESPONSE_STREAM":this.code}};Z.ReadError=Rs;var Un=class extends he{constructor(e){super(`Unsupported protocol "${e.url.protocol}"`,{},e),this.name="UnsupportedProtocolError",this.code="ERR_UNSUPPORTED_PROTOCOL"}};Z.UnsupportedProtocolError=Un;var Av=["socket","connect","continue","information","upgrade","timeout"],jn=class extends Qh.Duplex{constructor(e,t={},i){super({autoDestroy:!1,highWaterMark:0}),this[Kt]=0,this[Yt]=0,this.requestInitialized=!1,this[Rn]=new Set,this.redirects=[],this[Qt]=!1,this[Pn]=!1,this[As]=[],this.retryCount=0,this._progressCallbacks=[];let a=()=>this._unlockWrite(),c=()=>this._lockWrite();this.on("pipe",m=>{m.prependListener("data",a),m.on("data",c),m.prependListener("end",a),m.on("end",c)}),this.on("unpipe",m=>{m.off("data",a),m.off("data",c),m.off("end",a),m.off("end",c)}),this.on("pipe",m=>{m instanceof so.IncomingMessage&&(this.options.headers={...m.headers,...this.options.headers})});let{json:h,body:p,form:g}=t;if((h||p||g)&&this._lockWrite(),Z.kIsNormalizedAlready in t)this.options=t;else try{this.options=this.constructor.normalizeArguments(e,t,i)}catch(m){M.default.nodeStream(t.body)&&t.body.destroy(),this.destroy(m);return}(async()=>{var m;try{this.options.body instanceof av.ReadStream&&await Ov(this.options.body);let{url:v}=this.options;if(!v)throw new TypeError("Missing `url` property");if(this.requestUrl=v.toString(),decodeURI(this.requestUrl),await this._finalizeBody(),await this._makeRequest(),this.destroyed){(m=this[ye])===null||m===void 0||m.destroy();return}for(let w of this[As])w();this[As].length=0,this.requestInitialized=!0}catch(v){if(v instanceof he){this._beforeError(v);return}this.destroyed||this.destroy(v)}})()}static normalizeArguments(e,t,i){var a,c,h,p,g;let m=t;if(M.default.object(e)&&!M.default.urlInstance(e))t={...i,...e,...t};else{if(e&&t&&t.url!==void 0)throw new TypeError("The `url` option is mutually exclusive with the `input` argument");t={...i,...t},e!==void 0&&(t.url=e),M.default.urlInstance(t.url)&&(t.url=new ft.URL(t.url.toString()))}if(t.cache===!1&&(t.cache=void 0),t.dnsCache===!1&&(t.dnsCache=void 0),M.assert.any([M.default.string,M.default.undefined],t.method),M.assert.any([M.default.object,M.default.undefined],t.headers),M.assert.any([M.default.string,M.default.urlInstance,M.default.undefined],t.prefixUrl),M.assert.any([M.default.object,M.default.undefined],t.cookieJar),M.assert.any([M.default.object,M.default.string,M.default.undefined],t.searchParams),M.assert.any([M.default.object,M.default.string,M.default.undefined],t.cache),M.assert.any([M.default.object,M.default.number,M.default.undefined],t.timeout),M.assert.any([M.default.object,M.default.undefined],t.context),M.assert.any([M.default.object,M.default.undefined],t.hooks),M.assert.any([M.default.boolean,M.default.undefined],t.decompress),M.assert.any([M.default.boolean,M.default.undefined],t.ignoreInvalidCookies),M.assert.any([M.default.boolean,M.default.undefined],t.followRedirect),M.assert.any([M.default.number,M.default.undefined],t.maxRedirects),M.assert.any([M.default.boolean,M.default.undefined],t.throwHttpErrors),M.assert.any([M.default.boolean,M.default.undefined],t.http2),M.assert.any([M.default.boolean,M.default.undefined],t.allowGetBody),M.assert.any([M.default.string,M.default.undefined],t.localAddress),M.assert.any([nd.isDnsLookupIpVersion,M.default.undefined],t.dnsLookupIpVersion),M.assert.any([M.default.object,M.default.undefined],t.https),M.assert.any([M.default.boolean,M.default.undefined],t.rejectUnauthorized),t.https&&(M.assert.any([M.default.boolean,M.default.undefined],t.https.rejectUnauthorized),M.assert.any([M.default.function_,M.default.undefined],t.https.checkServerIdentity),M.assert.any([M.default.string,M.default.object,M.default.array,M.default.undefined],t.https.certificateAuthority),M.assert.any([M.default.string,M.default.object,M.default.array,M.default.undefined],t.https.key),M.assert.any([M.default.string,M.default.object,M.default.array,M.default.undefined],t.https.certificate),M.assert.any([M.default.string,M.default.undefined],t.https.passphrase),M.assert.any([M.default.string,M.default.buffer,M.default.array,M.default.undefined],t.https.pfx)),M.assert.any([M.default.object,M.default.undefined],t.cacheOptions),M.default.string(t.method)?t.method=t.method.toUpperCase():t.method="GET",t.headers===i?.headers?t.headers={...t.headers}:t.headers=fv({...i?.headers,...t.headers}),"slashes"in t)throw new TypeError("The legacy `url.Url` has been deprecated. Use `URL` instead.");if("auth"in t)throw new TypeError("Parameter `auth` is deprecated. Use `username` / `password` instead.");if("searchParams"in t&&t.searchParams&&t.searchParams!==i?.searchParams){let O;if(M.default.string(t.searchParams)||t.searchParams instanceof ft.URLSearchParams)O=new ft.URLSearchParams(t.searchParams);else{Ev(t.searchParams),O=new ft.URLSearchParams;for(let T in t.searchParams){let k=t.searchParams[T];k===null?O.append(T,""):k!==void 0&&O.append(T,k)}}(a=i?.searchParams)===null||a===void 0||a.forEach((T,k)=>{O.has(k)||O.append(k,T)}),t.searchParams=O}if(t.username=(c=t.username)!==null&&c!==void 0?c:"",t.password=(h=t.password)!==null&&h!==void 0?h:"",M.default.undefined(t.prefixUrl)?t.prefixUrl=(p=i?.prefixUrl)!==null&&p!==void 0?p:"":(t.prefixUrl=t.prefixUrl.toString(),t.prefixUrl!==""&&!t.prefixUrl.endsWith("/")&&(t.prefixUrl+="/")),M.default.string(t.url)){if(t.url.startsWith("/"))throw new Error("`input` must not start with a slash when using `prefixUrl`");t.url=sd.default(t.prefixUrl+t.url,t)}else(M.default.undefined(t.url)&&t.prefixUrl!==""||t.protocol)&&(t.url=sd.default(t.prefixUrl,t));if(t.url){"port"in t&&delete t.port;let{prefixUrl:O}=t;Object.defineProperty(t,"prefixUrl",{set:k=>{let A=t.url;if(!A.href.startsWith(k))throw new Error(`Cannot change \`prefixUrl\` from ${O} to ${k}: ${A.href}`);t.url=new ft.URL(k+A.href.slice(O.length)),O=k},get:()=>O});let{protocol:T}=t.url;if(T==="unix:"&&(T="http:",t.url=new ft.URL(`http://unix${t.url.pathname}${t.url.search}`)),t.searchParams&&(t.url.search=t.searchParams.toString()),T!=="http:"&&T!=="https:")throw new Un(t);t.username===""?t.username=t.url.username:t.url.username=t.username,t.password===""?t.password=t.url.password:t.url.password=t.password}let{cookieJar:v}=t;if(v){let{setCookie:O,getCookieString:T}=v;M.assert.function_(O),M.assert.function_(T),O.length===4&&T.length===0&&(O=Yh.promisify(O.bind(t.cookieJar)),T=Yh.promisify(T.bind(t.cookieJar)),t.cookieJar={setCookie:O,getCookieString:T})}let{cache:w}=t;if(w&&(io.has(w)||io.set(w,new Zh((O,T)=>{let k=O[ye](O,T);return M.default.promise(k)&&(k.once=(A,N)=>{if(A==="error")k.catch(N);else if(A==="abort")(async()=>{try{(await k).once("abort",N)}catch{}})();else throw new Error(`Unknown HTTP2 promise event: ${A}`);return k}),k},w))),t.cacheOptions={...t.cacheOptions},t.dnsCache===!0)no||(no=new uv.default),t.dnsCache=no;else if(!M.default.undefined(t.dnsCache)&&!t.dnsCache.lookup)throw new TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${M.default(t.dnsCache)}`);M.default.number(t.timeout)?t.timeout={request:t.timeout}:i&&t.timeout!==i.timeout?t.timeout={...i.timeout,...t.timeout}:t.timeout={...t.timeout},t.context||(t.context={});let E=t.hooks===i?.hooks;t.hooks={...t.hooks};for(let O of Z.knownHookEvents)if(O in t.hooks)if(M.default.array(t.hooks[O]))t.hooks[O]=[...t.hooks[O]];else throw new TypeError(`Parameter \`${O}\` must be an Array, got ${M.default(t.hooks[O])}`);else t.hooks[O]=[];if(i&&!E)for(let O of Z.knownHookEvents)i.hooks[O].length>0&&(t.hooks[O]=[...i.hooks[O],...t.hooks[O]]);if("family"in t&&pt.default('"options.family" was never documented, please use "options.dnsLookupIpVersion"'),i?.https&&(t.https={...i.https,...t.https}),"rejectUnauthorized"in t&&pt.default('"options.rejectUnauthorized" is now deprecated, please use "options.https.rejectUnauthorized"'),"checkServerIdentity"in t&&pt.default('"options.checkServerIdentity" was never documented, please use "options.https.checkServerIdentity"'),"ca"in t&&pt.default('"options.ca" was never documented, please use "options.https.certificateAuthority"'),"key"in t&&pt.default('"options.key" was never documented, please use "options.https.key"'),"cert"in t&&pt.default('"options.cert" was never documented, please use "options.https.certificate"'),"passphrase"in t&&pt.default('"options.passphrase" was never documented, please use "options.https.passphrase"'),"pfx"in t&&pt.default('"options.pfx" was never documented, please use "options.https.pfx"'),"followRedirects"in t)throw new TypeError("The `followRedirects` option does not exist. Use `followRedirect` instead.");if(t.agent){for(let O in t.agent)if(O!=="http"&&O!=="https"&&O!=="http2")throw new TypeError(`Expected the \`options.agent\` properties to be \`http\`, \`https\` or \`http2\`, got \`${O}\``)}return t.maxRedirects=(g=t.maxRedirects)!==null&&g!==void 0?g:0,Z.setNonEnumerableProperties([i,m],t),vv.default(t,i)}_lockWrite(){let e=()=>{throw new TypeError("The payload has been already provided")};this.write=e,this.end=e}_unlockWrite(){this.write=super.write,this.end=super.end}async _finalizeBody(){let{options:e}=this,{headers:t}=e,i=!M.default.undefined(e.form),a=!M.default.undefined(e.json),c=!M.default.undefined(e.body),h=i||a||c,p=Z.withoutBody.has(e.method)&&!(e.method==="GET"&&e.allowGetBody);if(this._cannotHaveBody=p,h){if(p)throw new TypeError(`The \`${e.method}\` method cannot be used with a body`);if([c,i,a].filter(g=>g).length>1)throw new TypeError("The `body`, `json` and `form` options are mutually exclusive");if(c&&!(e.body instanceof Qh.Readable)&&!M.default.string(e.body)&&!M.default.buffer(e.body)&&!ed.default(e.body))throw new TypeError("The `body` option must be a stream.Readable, string or Buffer");if(i&&!M.default.object(e.form))throw new TypeError("The `form` option must be an Object");{let g=!M.default.string(t["content-type"]);c?(ed.default(e.body)&&g&&(t["content-type"]=`multipart/form-data; boundary=${e.body.getBoundary()}`),this[gt]=e.body):i?(g&&(t["content-type"]="application/x-www-form-urlencoded"),this[gt]=new ft.URLSearchParams(e.form).toString()):(g&&(t["content-type"]="application/json"),this[gt]=e.stringifyJson(e.json));let m=await pv.default(this[gt],e.headers);M.default.undefined(t["content-length"])&&M.default.undefined(t["transfer-encoding"])&&!p&&!M.default.undefined(m)&&(t["content-length"]=String(m))}}else p?this._lockWrite():this._unlockWrite();this[Jt]=Number(t["content-length"])||void 0}async _onResponseBase(e){let{options:t}=this,{url:i}=t;this[ad]=e,t.decompress&&(e=hv(e));let a=e.statusCode,c=e;c.statusMessage=c.statusMessage?c.statusMessage:Xh.STATUS_CODES[a],c.url=t.url.toString(),c.requestUrl=this.requestUrl,c.redirectUrls=this.redirects,c.request=this,c.isFromCache=e.fromCache||!1,c.ip=this.ip,c.retryCount=this.retryCount,this[id]=c.isFromCache,this[zt]=Number(e.headers["content-length"])||void 0,this[In]=e,e.once("end",()=>{this[zt]=this[Kt],this.emit("downloadProgress",this.downloadProgress)}),e.once("error",p=>{e.destroy(),this._beforeError(new Rs(p,this))}),e.once("aborted",()=>{this._beforeError(new Rs({name:"Error",message:"The server aborted pending request",code:"ECONNRESET"},this))}),this.emit("downloadProgress",this.downloadProgress);let h=e.headers["set-cookie"];if(M.default.object(t.cookieJar)&&h){let p=h.map(async g=>t.cookieJar.setCookie(g,i.toString()));t.ignoreInvalidCookies&&(p=p.map(async g=>g.catch(()=>{})));try{await Promise.all(p)}catch(g){this._beforeError(g);return}}if(t.followRedirect&&e.headers.location&&Sv.has(a)){if(e.resume(),this[ye]&&(this[ro](),delete this[ye],this[rd]()),(a===303&&t.method!=="GET"&&t.method!=="HEAD"||!t.methodRewriting)&&(t.method="GET","body"in t&&delete t.body,"json"in t&&delete t.json,"form"in t&&delete t.form,this[gt]=void 0,delete t.headers["content-length"]),this.redirects.length>=t.maxRedirects){this._beforeError(new Mn(this));return}try{let w=function(E){return E.protocol==="unix:"||E.hostname==="unix"},g=Buffer.from(e.headers.location,"binary").toString(),m=new ft.URL(g,i),v=m.toString();if(decodeURI(v),!w(i)&&w(m)){this._beforeError(new he("Cannot redirect to UNIX socket",{},this));return}m.hostname!==i.hostname||m.port!==i.port?("host"in t.headers&&delete t.headers.host,"cookie"in t.headers&&delete t.headers.cookie,"authorization"in t.headers&&delete t.headers.authorization,(t.username||t.password)&&(t.username="",t.password="")):(m.username=t.username,m.password=t.password),this.redirects.push(v),t.url=m;for(let E of t.hooks.beforeRedirect)await E(t,c);this.emit("redirect",c,t),await this._makeRequest()}catch(g){this._beforeError(g);return}return}if(t.isStream&&t.throwHttpErrors&&!bv.isResponseOk(c)){this._beforeError(new xn(c));return}e.on("readable",()=>{this[Pn]&&this._read()}),this.on("resume",()=>{e.resume()}),this.on("pause",()=>{e.pause()}),e.once("end",()=>{this.push(null)}),this.emit("response",e);for(let p of this[Rn])if(!p.headersSent){for(let g in e.headers){let m=t.decompress?g!=="content-encoding":!0,v=e.headers[g];m&&p.setHeader(g,v)}p.statusCode=a}}async _onResponse(e){try{await this._onResponseBase(e)}catch(t){this._beforeError(t)}}_onRequest(e){let{options:t}=this,{timeout:i,url:a}=t;lv.default(e),this[ro]=td.default(e,i,a);let c=t.cache?"cacheableResponse":"response";e.once(c,g=>{this._onResponse(g)}),e.once("error",g=>{var m;e.destroy(),(m=e.res)===null||m===void 0||m.removeAllListeners("end"),g=g instanceof td.TimeoutError?new Dn(g,this.timings,this):new he(g.message,g,this),this._beforeError(g)}),this[rd]=gv.default(e,this,Av),this[ye]=e,this.emit("uploadProgress",this.uploadProgress);let h=this[gt],p=this.redirects.length===0?this:e;M.default.nodeStream(h)?(h.pipe(p),h.once("error",g=>{this._beforeError(new Ln(g,this))})):(this._unlockWrite(),M.default.undefined(h)?(this._cannotHaveBody||this._noPipe)&&(p.end(),this._lockWrite()):(this._writeRequest(h,void 0,()=>{}),p.end(),this._lockWrite())),this.emit("request",e)}async _createCacheableRequest(e,t){return new Promise((i,a)=>{Object.assign(t,mv.default(e)),delete t.url;let c,h=io.get(t.cache)(t,async p=>{p._readableState.autoDestroy=!1,c&&(await c).emit("cacheableResponse",p),i(p)});t.url=e,h.once("error",a),h.once("request",async p=>{c=p,i(c)})})}async _makeRequest(){var e,t,i,a,c;let{options:h}=this,{headers:p}=h;for(let N in p)if(M.default.undefined(p[N]))delete p[N];else if(M.default.null_(p[N]))throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${N}\` header`);if(h.decompress&&M.default.undefined(p["accept-encoding"])&&(p["accept-encoding"]=Cv?"gzip, deflate, br":"gzip, deflate"),h.cookieJar){let N=await h.cookieJar.getCookieString(h.url.toString());M.default.nonEmptyString(N)&&(h.headers.cookie=N)}for(let N of h.hooks.beforeRequest){let W=await N(h);if(!M.default.undefined(W)){h.request=()=>W;break}}h.body&&this[gt]!==h.body&&(this[gt]=h.body);let{agent:g,request:m,timeout:v,url:w}=h;if(h.dnsCache&&!("lookup"in h)&&(h.lookup=h.dnsCache.lookup),w.hostname==="unix"){let N=/(?<socketPath>.+?):(?<path>.+)/.exec(`${w.pathname}${w.search}`);if(N?.groups){let{socketPath:W,path:Q}=N.groups;Object.assign(h,{socketPath:W,path:Q,host:""})}}let E=w.protocol==="https:",O;h.http2?O=dv.auto:O=E?cv.request:Xh.request;let T=(e=h.request)!==null&&e!==void 0?e:O,k=h.cache?this._createCacheableRequest:T;g&&!h.http2&&(h.agent=g[E?"https":"http"]),h[ye]=T,delete h.request,delete h.timeout;let A=h;if(A.shared=(t=h.cacheOptions)===null||t===void 0?void 0:t.shared,A.cacheHeuristic=(i=h.cacheOptions)===null||i===void 0?void 0:i.cacheHeuristic,A.immutableMinTimeToLive=(a=h.cacheOptions)===null||a===void 0?void 0:a.immutableMinTimeToLive,A.ignoreCargoCult=(c=h.cacheOptions)===null||c===void 0?void 0:c.ignoreCargoCult,h.dnsLookupIpVersion!==void 0)try{A.family=nd.dnsLookupIpVersionToFamily(h.dnsLookupIpVersion)}catch{throw new Error("Invalid `dnsLookupIpVersion` option value")}h.https&&("rejectUnauthorized"in h.https&&(A.rejectUnauthorized=h.https.rejectUnauthorized),h.https.checkServerIdentity&&(A.checkServerIdentity=h.https.checkServerIdentity),h.https.certificateAuthority&&(A.ca=h.https.certificateAuthority),h.https.certificate&&(A.cert=h.https.certificate),h.https.key&&(A.key=h.https.key),h.https.passphrase&&(A.passphrase=h.https.passphrase),h.https.pfx&&(A.pfx=h.https.pfx));try{let N=await k(w,A);M.default.undefined(N)&&(N=O(w,A)),h.request=m,h.timeout=v,h.agent=g,h.https&&("rejectUnauthorized"in h.https&&delete A.rejectUnauthorized,h.https.checkServerIdentity&&delete A.checkServerIdentity,h.https.certificateAuthority&&delete A.ca,h.https.certificate&&delete A.cert,h.https.key&&delete A.key,h.https.passphrase&&delete A.passphrase,h.https.pfx&&delete A.pfx),kv(N)?this._onRequest(N):this.writable?(this.once("finish",()=>{this._onResponse(N)}),this._unlockWrite(),this.end(),this._lockWrite()):this._onResponse(N)}catch(N){throw N instanceof Zh.CacheError?new Nn(N,this):new he(N.message,N,this)}}async _error(e){try{for(let t of this.options.hooks.beforeError)e=await t(e)}catch(t){e=new he(t.message,t,this)}this.destroy(e)}_beforeError(e){if(this[Qt])return;let{options:t}=this,i=this.retryCount+1;this[Qt]=!0,e instanceof he||(e=new he(e.message,e,this));let a=e,{response:c}=a;(async()=>{if(c&&!c.body){c.setEncoding(this._readableState.encoding);try{c.rawBody=await _v.default(c),c.body=c.rawBody.toString()}catch{}}if(this.listenerCount("retry")!==0){let h;try{let p;c&&"retry-after"in c.headers&&(p=Number(c.headers["retry-after"]),Number.isNaN(p)?(p=Date.parse(c.headers["retry-after"])-Date.now(),p<=0&&(p=1)):p*=1e3),h=await t.retry.calculateDelay({attemptCount:i,retryOptions:t.retry,error:a,retryAfter:p,computedValue:wv.default({attemptCount:i,retryOptions:t.retry,error:a,retryAfter:p,computedValue:0})})}catch(p){this._error(new he(p.message,p,this));return}if(h){let p=async()=>{try{for(let g of this.options.hooks.beforeRetry)await g(this.options,a,i)}catch(g){this._error(new he(g.message,e,this));return}this.destroyed||(this.destroy(),this.emit("retry",i,e))};this[cd]=setTimeout(p,h);return}}this._error(a)})()}_read(){this[Pn]=!0;let e=this[In];if(e&&!this[Qt]){e.readableLength&&(this[Pn]=!1);let t;for(;(t=e.read())!==null;){this[Kt]+=t.length,this[od]=!0;let i=this.downloadProgress;i.percent<1&&this.emit("downloadProgress",i),this.push(t)}}}_write(e,t,i){let a=()=>{this._writeRequest(e,t,i)};this.requestInitialized?a():this[As].push(a)}_writeRequest(e,t,i){this[ye].destroyed||(this._progressCallbacks.push(()=>{this[Yt]+=Buffer.byteLength(e,t);let a=this.uploadProgress;a.percent<1&&this.emit("uploadProgress",a)}),this[ye].write(e,t,a=>{!a&&this._progressCallbacks.length>0&&this._progressCallbacks.shift()(),i(a)}))}_final(e){let t=()=>{for(;this._progressCallbacks.length!==0;)this._progressCallbacks.shift()();if(!(ye in this)){e();return}if(this[ye].destroyed){e();return}this[ye].end(i=>{i||(this[Jt]=this[Yt],this.emit("uploadProgress",this.uploadProgress),this[ye].emit("upload-complete")),e(i)})};this.requestInitialized?t():this[As].push(t)}_destroy(e,t){var i;this[Qt]=!0,clearTimeout(this[cd]),ye in this&&(this[ro](),!((i=this[In])===null||i===void 0)&&i.complete||this[ye].destroy()),e!==null&&!M.default.undefined(e)&&!(e instanceof he)&&(e=new he(e.message,e,this)),t(e)}get _isAboutToError(){return this[Qt]}get ip(){var e;return(e=this.socket)===null||e===void 0?void 0:e.remoteAddress}get aborted(){var e,t,i;return((t=(e=this[ye])===null||e===void 0?void 0:e.destroyed)!==null&&t!==void 0?t:this.destroyed)&&!(!((i=this[ad])===null||i===void 0)&&i.complete)}get socket(){var e,t;return(t=(e=this[ye])===null||e===void 0?void 0:e.socket)!==null&&t!==void 0?t:void 0}get downloadProgress(){let e;return this[zt]?e=this[Kt]/this[zt]:this[zt]===this[Kt]?e=1:e=0,{percent:e,transferred:this[Kt],total:this[zt]}}get uploadProgress(){let e;return this[Jt]?e=this[Yt]/this[Jt]:this[Jt]===this[Yt]?e=1:e=0,{percent:e,transferred:this[Yt],total:this[Jt]}}get timings(){var e;return(e=this[ye])===null||e===void 0?void 0:e.timings}get isFromCache(){return this[id]}pipe(e,t){if(this[od])throw new Error("Failed to pipe. The response has been emitted already.");return e instanceof so.ServerResponse&&this[Rn].add(e),super.pipe(e,t)}unpipe(e){return e instanceof so.ServerResponse&&this[Rn].delete(e),super.unpipe(e),this}};Z.default=jn});var Is=$(He=>{"use strict";var Rv=He&&He.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),Pv=He&&He.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Rv(e,s,t)};Object.defineProperty(He,"__esModule",{value:!0});He.CancelError=He.ParseError=void 0;var ld=Ps(),oo=class extends ld.RequestError{constructor(e,t){let{options:i}=t.request;super(`${e.message} in "${i.url.toString()}"`,e,t.request),this.name="ParseError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_BODY_PARSE_FAILURE":this.code}};He.ParseError=oo;var ao=class extends ld.RequestError{constructor(e){super("Promise was canceled",{},e),this.name="CancelError",this.code="ERR_CANCELED"}get isCanceled(){return!0}};He.CancelError=ao;Pv(Ps(),He)});var hd=$(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});var ud=Is(),Iv=(s,e,t,i)=>{let{rawBody:a}=s;try{if(e==="text")return a.toString(i);if(e==="json")return a.length===0?"":t(a.toString());if(e==="buffer")return a;throw new ud.ParseError({message:`Unknown body type '${e}'`,name:"Error"},s)}catch(c){throw new ud.ParseError(c,s)}};co.default=Iv});var lo=$(mt=>{"use strict";var Mv=mt&&mt.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),xv=mt&&mt.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Mv(e,s,t)};Object.defineProperty(mt,"__esModule",{value:!0});var Nv=q("events"),Lv=it(),Dv=lu(),qn=Is(),dd=hd(),fd=Ps(),Uv=Wi(),jv=Xi(),pd=Zi(),qv=["request","response","redirect","uploadProgress","downloadProgress"];function gd(s){let e,t,i=new Nv.EventEmitter,a=new Dv((h,p,g)=>{let m=v=>{let w=new fd.default(void 0,s);w.retryCount=v,w._noPipe=!0,g(()=>w.destroy()),g.shouldReject=!1,g(()=>p(new qn.CancelError(w))),e=w,w.once("response",async T=>{var k;if(T.retryCount=v,T.request.aborted)return;let A;try{A=await jv.default(w),T.rawBody=A}catch{return}if(w._isAboutToError)return;let N=((k=T.headers["content-encoding"])!==null&&k!==void 0?k:"").toLowerCase(),W=["gzip","deflate","br"].includes(N),{options:Q}=w;if(W&&!Q.decompress)T.body=A;else try{T.body=dd.default(T,Q.responseType,Q.parseJson,Q.encoding)}catch(se){if(T.body=A.toString(),pd.isResponseOk(T)){w._beforeError(se);return}}try{for(let[se,Y]of Q.hooks.afterResponse.entries())T=await Y(T,async X=>{let ce=fd.default.normalizeArguments(void 0,{...X,retry:{calculateDelay:()=>0},throwHttpErrors:!1,resolveBodyOnly:!1},Q);ce.hooks.afterResponse=ce.hooks.afterResponse.slice(0,se);for(let ee of ce.hooks.beforeRetry)await ee(ce);let ie=gd(ce);return g(()=>{ie.catch(()=>{}),ie.cancel()}),ie})}catch(se){w._beforeError(new qn.RequestError(se.message,se,w));return}if(t=T,!pd.isResponseOk(T)){w._beforeError(new qn.HTTPError(T));return}w.destroy(),h(w.options.resolveBodyOnly?T.body:T)});let E=T=>{if(a.isCanceled)return;let{options:k}=w;if(T instanceof qn.HTTPError&&!k.throwHttpErrors){let{response:A}=T;h(w.options.resolveBodyOnly?A.body:A);return}p(T)};w.once("error",E);let O=w.options.body;w.once("retry",(T,k)=>{var A,N;if(O===((A=k.request)===null||A===void 0?void 0:A.options.body)&&Lv.default.nodeStream((N=k.request)===null||N===void 0?void 0:N.options.body)){E(k);return}m(T)}),Uv.default(w,i,qv)};m(0)});a.on=(h,p)=>(i.on(h,p),a);let c=h=>{let p=(async()=>{await a;let{options:g}=t.request;return dd.default(t,h,g.parseJson,g.encoding)})();return Object.defineProperties(p,Object.getOwnPropertyDescriptors(a)),p};return a.json=()=>{let{headers:h}=e.options;return!e.writableFinished&&h.accept===void 0&&(h.accept="application/json"),c("json")},a.buffer=()=>c("buffer"),a.text=()=>c("text"),a}mt.default=gd;xv(Is(),mt)});var md=$(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});var Bv=Is();function $v(s,...e){let t=(async()=>{if(s instanceof Bv.RequestError)try{for(let a of e)if(a)for(let c of a)s=await c(s)}catch(a){s=a}throw s})(),i=()=>t;return t.json=i,t.text=i,t.buffer=i,t.on=i,t}uo.default=$v});var bd=$(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});var yd=it();function _d(s){for(let e of Object.values(s))(yd.default.plainObject(e)||yd.default.array(e))&&_d(e);return Object.freeze(s)}ho.default=_d});var wd=$(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0})});var fo=$(Ue=>{"use strict";var Hv=Ue&&Ue.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),Gv=Ue&&Ue.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Hv(e,s,t)};Object.defineProperty(Ue,"__esModule",{value:!0});Ue.defaultHandler=void 0;var Cd=it(),De=lo(),Fv=md(),$n=Ps(),Wv=bd(),Vv={RequestError:De.RequestError,CacheError:De.CacheError,ReadError:De.ReadError,HTTPError:De.HTTPError,MaxRedirectsError:De.MaxRedirectsError,TimeoutError:De.TimeoutError,ParseError:De.ParseError,CancelError:De.CancelError,UnsupportedProtocolError:De.UnsupportedProtocolError,UploadError:De.UploadError},zv=async s=>new Promise(e=>{setTimeout(e,s)}),{normalizeArguments:Bn}=$n.default,Ed=(...s)=>{let e;for(let t of s)e=Bn(void 0,t,e);return e},Kv=s=>s.isStream?new $n.default(void 0,s):De.default(s),Jv=s=>"defaults"in s&&"options"in s.defaults,Yv=["get","post","put","patch","head","delete"];Ue.defaultHandler=(s,e)=>e(s);var kd=(s,e)=>{if(s)for(let t of s)t(e)},Od=s=>{s._rawHandlers=s.handlers,s.handlers=s.handlers.map(i=>(a,c)=>{let h,p=i(a,g=>(h=c(g),h));if(p!==h&&!a.isStream&&h){let g=p,{then:m,catch:v,finally:w}=g;Object.setPrototypeOf(g,Object.getPrototypeOf(h)),Object.defineProperties(g,Object.getOwnPropertyDescriptors(h)),g.then=m,g.catch=v,g.finally=w}return p});let e=(i,a={},c)=>{var h,p;let g=0,m=v=>s.handlers[g++](v,g===s.handlers.length?Kv:m);if(Cd.default.plainObject(i)){let v={...i,...a};$n.setNonEnumerableProperties([i,a],v),a=v,i=void 0}try{let v;try{kd(s.options.hooks.init,a),kd((h=a.hooks)===null||h===void 0?void 0:h.init,a)}catch(E){v=E}let w=Bn(i,a,c??s.options);if(w[$n.kIsNormalizedAlready]=!0,v)throw new De.RequestError(v.message,v,w);return m(w)}catch(v){if(a.isStream)throw v;return Fv.default(v,s.options.hooks.beforeError,(p=a.hooks)===null||p===void 0?void 0:p.beforeError)}};e.extend=(...i)=>{let a=[s.options],c=[...s._rawHandlers],h;for(let p of i)Jv(p)?(a.push(p.defaults.options),c.push(...p.defaults._rawHandlers),h=p.defaults.mutableDefaults):(a.push(p),"handlers"in p&&c.push(...p.handlers),h=p.mutableDefaults);return c=c.filter(p=>p!==Ue.defaultHandler),c.length===0&&c.push(Ue.defaultHandler),Od({options:Ed(...a),handlers:c,mutableDefaults:!!h})};let t=async function*(i,a){let c=Bn(i,a,s.options);c.resolveBodyOnly=!1;let h=c.pagination;if(!Cd.default.object(h))throw new TypeError("`options.pagination` must be implemented");let p=[],{countLimit:g}=h,m=0;for(;m<h.requestLimit;){m!==0&&await zv(h.backoff);let v=await e(void 0,void 0,c),w=await h.transform(v),E=[];for(let T of w)if(h.filter(T,p,E)&&(!h.shouldContinue(T,p,E)||(yield T,h.stackAllItems&&p.push(T),E.push(T),--g<=0)))return;let O=h.paginate(v,p,E);if(O===!1)return;O===v.request.options?c=v.request.options:O!==void 0&&(c=Bn(void 0,O,c)),m++}};e.paginate=t,e.paginate.all=async(i,a)=>{let c=[];for await(let h of t(i,a))c.push(h);return c},e.paginate.each=t,e.stream=(i,a)=>e(i,{...a,isStream:!0});for(let i of Yv)e[i]=(a,c)=>e(a,{...c,method:i}),e.stream[i]=(a,c)=>e(a,{...c,method:i,isStream:!0});return Object.assign(e,Vv),Object.defineProperty(e,"defaults",{value:s.mutableDefaults?s:Wv.default(s),writable:s.mutableDefaults,configurable:s.mutableDefaults,enumerable:!0}),e.mergeOptions=Ed,e};Ue.default=Od;Gv(wd(),Ue)});var Gn=$((at,Hn)=>{"use strict";var Qv=at&&at.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),Sd=at&&at.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Qv(e,s,t)};Object.defineProperty(at,"__esModule",{value:!0});var Xv=q("url"),Td=fo(),Zv={options:{method:"GET",retry:{limit:2,methods:["GET","PUT","HEAD","DELETE","OPTIONS","TRACE"],statusCodes:[408,413,429,500,502,503,504,521,522,524],errorCodes:["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"],maxRetryAfter:void 0,calculateDelay:({computedValue:s})=>s},timeout:{},headers:{"user-agent":"got (https://github.com/sindresorhus/got)"},hooks:{init:[],beforeRequest:[],beforeRedirect:[],beforeRetry:[],beforeError:[],afterResponse:[]},cache:void 0,dnsCache:void 0,decompress:!0,throwHttpErrors:!0,followRedirect:!0,isStream:!1,responseType:"text",resolveBodyOnly:!1,maxRedirects:10,prefixUrl:"",methodRewriting:!0,ignoreInvalidCookies:!1,context:{},http2:!1,allowGetBody:!1,https:void 0,pagination:{transform:s=>s.request.options.responseType==="json"?s.body:JSON.parse(s.body),paginate:s=>{if(!Reflect.has(s.headers,"link"))return!1;let e=s.headers.link.split(","),t;for(let i of e){let a=i.split(";");if(a[1].includes("next")){t=a[0].trimStart().trim(),t=t.slice(1,-1);break}}return t?{url:new Xv.URL(t)}:!1},filter:()=>!0,shouldContinue:()=>!0,countLimit:1/0,backoff:0,requestLimit:1e4,stackAllItems:!0},parseJson:s=>JSON.parse(s),stringifyJson:s=>JSON.stringify(s),cacheOptions:{}},handlers:[Td.defaultHandler],mutableDefaults:!1},po=Td.default(Zv);at.default=po;Hn.exports=po;Hn.exports.default=po;Hn.exports.__esModule=!0;Sd(fo(),at);Sd(lo(),at)});var xd=$((Ls,ko)=>{(function(s,e){typeof Ls=="object"&&typeof ko=="object"?ko.exports=e(fn(),Gn()):typeof define=="function"&&define.amd?define(["ws","got"],e):typeof Ls=="object"?Ls.Ably=e(fn(),Gn()):s.Ably=e(s.ws,s.got)})(Ls,(s,e)=>{var t={},i={exports:t},a=Object.create,c=Object.defineProperty,h=Object.defineProperties,p=Object.getOwnPropertyDescriptor,g=Object.getOwnPropertyDescriptors,m=Object.getOwnPropertyNames,v=Object.getOwnPropertySymbols,w=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty,O=Object.prototype.propertyIsEnumerable,T=(r,n,o)=>n in r?c(r,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):r[n]=o,k=(r,n)=>{for(var o in n||(n={}))E.call(n,o)&&T(r,o,n[o]);if(v)for(var o of v(n))O.call(n,o)&&T(r,o,n[o]);return r},A=(r,n)=>h(r,g(n)),N=(r,n)=>{var o={};for(var l in r)E.call(r,l)&&n.indexOf(l)<0&&(o[l]=r[l]);if(r!=null&&v)for(var l of v(r))n.indexOf(l)<0&&O.call(r,l)&&(o[l]=r[l]);return o},W=(r,n)=>function(){return n||(0,r[m(r)[0]])((n={exports:{}}).exports,n),n.exports},Q=(r,n)=>{for(var o in n)c(r,o,{get:n[o],enumerable:!0})},se=(r,n,o,l)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of m(n))!E.call(r,u)&&u!==o&&c(r,u,{get:()=>n[u],enumerable:!(l=p(n,u))||l.enumerable});return r},Y=(r,n,o)=>(o=r!=null?a(w(r)):{},se(n||!r||!r.__esModule?c(o,"default",{value:r,enumerable:!0}):o,r)),X=function(r,n){this[0]=r,this[1]=n},ce=(r,n,o)=>{var l=(y,_,S,I)=>{try{var U=o[y](_),D=(_=U.value)instanceof X,G=U.done;Promise.resolve(D?_[0]:_).then(C=>D?l(y==="return"?y:"next",_[1]?{done:C.done,value:C.value}:C,S,I):S({value:C,done:G})).catch(C=>l("throw",C,S,I))}catch(C){I(C)}},u=y=>f[y]=_=>new Promise((S,I)=>l(y,_,S,I)),f={};return o=o.apply(r,n),f[Symbol.asyncIterator]=()=>f,u("next"),u("throw"),u("return"),f},ie=W({"node_modules/bops/from.js"(r,n){var o=q("buffer").Buffer,l=((process||{}).version||"v0.0.0").slice(1).split(".")[0];n.exports=Number(l)<6?function(f,y){return new o(f,y)}:function(f,y){return o.from(f,y)}}}),ee=W({"node_modules/bops/to.js"(r,n){n.exports=function(o,l){return o.toString(l)}}}),Ge=W({"node_modules/bops/is.js"(r,n){var o=q("buffer").Buffer;n.exports=function(l){return o.isBuffer(l)}}}),Xd=W({"node_modules/bops/subarray.js"(r,n){n.exports=function(o,l,u){return arguments.length===2?o.slice(l):o.slice(l,u)}}}),Zd=W({"node_modules/bops/join.js"(r,n){var o=q("buffer").Buffer;n.exports=function(l,u){return u!==void 0?o.concat(l,u):o.concat(l)}}}),ef=W({"node_modules/bops/copy.js"(r,n){n.exports=o;function o(l,u,f,y,_){return l.copy(u,f,y,_)}}}),tf=W({"node_modules/bops/create.js"(r,n){var o=q("buffer").Buffer,l=((process||{}).version||"v0.0.0").slice(1).split(".")[0];n.exports=Number(l)<6?function(f){return new o(f)}:function(f){return o.alloc(f)}}}),sf=W({"node_modules/bops/read.js"(r,n){var o={},l=/read.+/,u;u=function(y){var _="return buf."+y+"("+["a","b","c"].join(",")+")";return new Function(["buf","a","b","c"],_)},n.exports=o;for(f in Buffer.prototype)l.test(f)&&(o[f]=u(f));var f}}),nf=W({"node_modules/bops/write.js"(r,n){var o=q("buffer").Buffer,l={},u=/write.+/,f;f=function(_){var S="return buf."+_+"("+["a","b","c"].join(",")+")";return new Function(["buf","a","b","c"],S)},n.exports=l;for(y in o.prototype)u.test(y)&&(l[y]=f(y));var y}}),rf=W({"node_modules/bops/index.js"(r,n){var o={};n.exports=o,o.from=ie(),o.to=ee(),o.is=Ge(),o.subarray=Xd(),o.join=Zd(),o.copy=ef(),o.create=tf(),l(sf(),o),l(nf(),o);function l(u,f){for(var y in u)f[y]=u[y]}}}),of=W({"node_modules/@ably/msgpack-js/msgpack.js"(r){"use strict";var n=rf();r.encode=function(C,R){var P=G(C,R);if(P!=0){var j=n.create(P);return D(C,j,0,R),j}},r.decode=I;var o=65536*65536,l=1/o;function u(C,R){return R=R||0,C.readInt32BE(R+0)*o+C.readUInt32BE(R+4)}function f(C,R){return R=R||0,C.readUInt32BE(R+0)*o+C.readUInt32BE(R+4)}function y(C,R,P){R<9223372036854776e3?(C.writeInt32BE(Math.floor(R*l),P),C.writeInt32BE(R&-1,P+4)):(C.writeUInt32BE(2147483647,P),C.writeUInt32BE(4294967295,P+4))}function _(C,R,P){R<18446744073709552e3?(C.writeUInt32BE(Math.floor(R*l),P),C.writeInt32BE(R&-1,P+4)):(C.writeUInt32BE(4294967295,P),C.writeUInt32BE(4294967295,P+4))}function S(C,R){this.offset=R||0,this.buffer=C,this.bufferLength=C.length}S.prototype.map=function(C){if(C*2>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced a map of length ${C})`);for(var R={},P=0;P<C;P++){var j=this.parse();R[j]=this.parse()}return R},S.prototype.bin=S.prototype.buf=function(C){if(C>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced a binary of length ${C})`);var R=n.subarray(this.buffer,this.offset,this.offset+C);return this.offset+=C,R},S.prototype.str=function(C){if(C>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced a string of length ${C})`);var R=n.to(n.subarray(this.buffer,this.offset,this.offset+C));return this.offset+=C,R},S.prototype.array=function(C){if(C>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced an array of length ${C})`);for(var R=new Array(C),P=0;P<C;P++)R[P]=this.parse();return R},S.prototype.parse=function(){var C=this.buffer[this.offset],R,P,j;if(C===void 0)throw new Error("malformed messagepack (referenced offset is outside buffer)");if(!(C&128))return this.offset++,C;if((C&240)===128)return P=C&15,this.offset++,this.map(P);if((C&240)===144)return P=C&15,this.offset++,this.array(P);if((C&224)===160)return P=C&31,this.offset++,this.str(P);if((C&224)===224)return R=n.readInt8(this.buffer,this.offset),this.offset++,R;switch(C){case 192:return this.offset++,null;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return P=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,this.bin(P);case 197:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.bin(P);case 198:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.bin(P);case 199:return P=n.readUInt8(this.buffer,this.offset+1),j=n.readUInt8(this.buffer,this.offset+2),this.offset+=3,[j,this.bin(P)];case 200:return P=n.readUInt16BE(this.buffer,this.offset+1),j=n.readUInt8(this.buffer,this.offset+3),this.offset+=4,[j,this.bin(P)];case 201:return P=n.readUInt32BE(this.buffer,this.offset+1),j=n.readUInt8(this.buffer,this.offset+5),this.offset+=6,[j,this.bin(P)];case 202:return R=n.readFloatBE(this.buffer,this.offset+1),this.offset+=5,R;case 203:return R=n.readDoubleBE(this.buffer,this.offset+1),this.offset+=9,R;case 204:return R=this.buffer[this.offset+1],this.offset+=2,R;case 205:return R=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,R;case 206:return R=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,R;case 207:return R=f(this.buffer,this.offset+1),this.offset+=9,R;case 208:return R=n.readInt8(this.buffer,this.offset+1),this.offset+=2,R;case 209:return R=n.readInt16BE(this.buffer,this.offset+1),this.offset+=3,R;case 210:return R=n.readInt32BE(this.buffer,this.offset+1),this.offset+=5,R;case 211:return R=u(this.buffer,this.offset+1),this.offset+=9,R;case 212:return j=n.readUInt8(this.buffer,this.offset+1),R=n.readUInt8(this.buffer,this.offset+2),this.offset+=3,j===0&&R===0?void 0:[j,R];case 213:return j=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[j,this.bin(2)];case 214:return j=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[j,this.bin(4)];case 215:return j=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[j,this.bin(8)];case 216:return j=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[j,this.bin(16)];case 217:return P=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,this.str(P);case 218:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.str(P);case 219:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.str(P);case 220:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.array(P);case 221:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.array(P);case 222:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.map(P);case 223:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.map(P)}throw new Error("Unknown type 0x"+C.toString(16))};function I(C){var R=new S(C),P=R.parse();if(R.offset!==C.length)throw new Error(C.length-R.offset+" trailing bytes");return P}function U(C,R){return Object.keys(C).filter(function(P){var j=C[P],H=typeof j;return(!R||j!=null)&&(H!=="function"||!!j.toJSON)})}function D(C,R,P,j,H){var V=typeof C,F,te;if(V==="string"){if(C=n.from(C),F=C.length,F<32)return R[P]=F|160,n.copy(C,R,P+1),1+F;if(F<256)return R[P]=217,n.writeUInt8(R,F,P+1),n.copy(C,R,P+2),2+F;if(F<65536)return R[P]=218,n.writeUInt16BE(R,F,P+1),n.copy(C,R,P+3),3+F;if(F<4294967296)return R[P]=219,n.writeUInt32BE(R,F,P+1),n.copy(C,R,P+5),5+F}if(n.is(C)){if(F=C.length,F<256)return R[P]=196,n.writeUInt8(R,F,P+1),n.copy(C,R,P+2),2+F;if(F<65536)return R[P]=197,n.writeUInt16BE(R,F,P+1),n.copy(C,R,P+3),3+F;if(F<4294967296)return R[P]=198,n.writeUInt32BE(R,F,P+1),n.copy(C,R,P+5),5+F}if(V==="number"){if(Math.floor(C)!==C)return R[P]=203,n.writeDoubleBE(R,C,P+1),9;if(C>=0){if(C<128)return R[P]=C,1;if(C<256)return R[P]=204,R[P+1]=C,2;if(C<65536)return R[P]=205,n.writeUInt16BE(R,C,P+1),3;if(C<4294967296)return R[P]=206,n.writeUInt32BE(R,C,P+1),5;if(C<18446744073709552e3)return R[P]=207,_(R,C,P+1),9;throw new Error("Number too big 0x"+C.toString(16))}if(C>=-32)return n.writeInt8(R,C,P),1;if(C>=-128)return R[P]=208,n.writeInt8(R,C,P+1),2;if(C>=-32768)return R[P]=209,n.writeInt16BE(R,C,P+1),3;if(C>=-2147483648)return R[P]=210,n.writeInt32BE(R,C,P+1),5;if(C>=-9223372036854776e3)return R[P]=211,y(R,C,P+1),9;throw new Error("Number too small -0x"+C.toString(16).substr(1))}if(V==="undefined")return j&&H?0:(R[P]=212,R[P+1]=0,R[P+2]=0,3);if(C===null)return j&&H?0:(R[P]=192,1);if(V==="boolean")return R[P]=C?195:194,1;if(typeof C.toJSON=="function")return D(C.toJSON(),R,P,j);if(V==="object"){te=0;var Te=Array.isArray(C);if(Te)F=C.length;else{var Ce=U(C,j);F=Ce.length}if(F<16?(R[P]=F|(Te?144:128),te=1):F<65536?(R[P]=Te?220:222,n.writeUInt16BE(R,F,P+1),te=3):F<4294967296&&(R[P]=Te?221:223,n.writeUInt32BE(R,F,P+1),te=5),Te)for(var Ye=0;Ye<F;Ye++)te+=D(C[Ye],R,P+te,j);else for(var Ye=0;Ye<F;Ye++){var mc=Ce[Ye];te+=D(mc,R,P+te),te+=D(C[mc],R,P+te,j,!0)}return te}if(V!=="function")throw new Error("Unknown type "+V)}function G(C,R,P){var j=typeof C,H,V;if(j==="string"){if(H=n.from(C).length,H<32)return 1+H;if(H<256)return 2+H;if(H<65536)return 3+H;if(H<4294967296)return 5+H}if(n.is(C)){if(H=C.length,H<256)return 2+H;if(H<65536)return 3+H;if(H<4294967296)return 5+H}if(j==="number"){if(Math.floor(C)!==C)return 9;if(C>=0){if(C<128)return 1;if(C<256)return 2;if(C<65536)return 3;if(C<4294967296)return 5;if(C<18446744073709552e3)return 9;throw new Error("Number too big 0x"+C.toString(16))}if(C>=-32)return 1;if(C>=-128)return 2;if(C>=-32768)return 3;if(C>=-2147483648)return 5;if(C>=-9223372036854776e3)return 9;throw new Error("Number too small -0x"+C.toString(16).substr(1))}if(j==="boolean")return 1;if(C===null)return R&&P?0:1;if(C===void 0)return R&&P?0:3;if(typeof C.toJSON=="function")return G(C.toJSON(),R);if(j==="object"){if(V=0,Array.isArray(C)){H=C.length;for(var F=0;F<H;F++)V+=G(C[F],R)}else{var te=U(C,R);H=te.length;for(var F=0;F<H;F++){var Te=te[F];V+=G(Te)+G(C[Te],R,!0)}}if(H<16)return 1+V;if(H<65536)return 3+V;if(H<4294967296)return 5+V;throw new Error("Array or object too long 0x"+H.toString(16))}if(j==="function")return 0;throw new Error("Unknown type "+j)}}}),L=class{},Po=typeof global<"u"?global:typeof window<"u"?window:self;function Ds(r,n){return`${r}`.padStart(n?3:2,"0")}function af(r){return L.Config.logTimestamps?function(n){let o=new Date;r(Ds(o.getHours())+":"+Ds(o.getMinutes())+":"+Ds(o.getSeconds())+"."+Ds(o.getMilliseconds(),1)+" "+n)}:function(n){r(n)}}var cf=()=>{var r;let n,o;return typeof((r=Po?.console)==null?void 0:r.log)=="function"?(n=function(...l){console.log.apply(console,l)},o=console.warn?function(...l){console.warn.apply(console,l)}:n):n=o=function(){},[n,o].map(af)},Ve=class Ms{constructor(){this.deprecated=(n,o)=>{this.deprecationWarning(`${n} is deprecated and will be removed in a future version. ${o}`)},this.shouldLog=n=>n<=this.logLevel,this.setLog=(n,o)=>{n!==void 0&&(this.logLevel=n),o!==void 0&&(this.logHandler=this.logErrorHandler=o)},this.logLevel=Ms.defaultLogLevel,this.logHandler=Ms.defaultLogHandler,this.logErrorHandler=Ms.defaultLogErrorHandler}static initLogHandlers(){let[n,o]=cf();this.defaultLogHandler=n,this.defaultLogErrorHandler=o,this.defaultLogger=new Ms}static logActionNoStrip(n,o,l,u){n.logAction(o,l,u)}logAction(n,o,l){this.shouldLog(n)&&(n===1?this.logErrorHandler:this.logHandler)("Ably: "+o+": "+l,n)}renamedClientOption(n,o){this.deprecationWarning(`The \`${n}\` client option has been renamed to \`${o}\`. Please update your code to use \`${o}\` instead. \`${n}\` will be removed in a future version.`)}renamedMethod(n,o,l){this.deprecationWarning(`\`${n}\`\u2019s \`${o}\` method has been renamed to \`${l}\`. Please update your code to use \`${l}\` instead. \`${o}\` will be removed in a future version.`)}deprecationWarning(n){this.shouldLog(1)&&this.logErrorHandler(`Ably: Deprecation warning - ${n}`,1)}};Ve.defaultLogLevel=1,Ve.LOG_NONE=0,Ve.LOG_ERROR=1,Ve.LOG_MAJOR=2,Ve.LOG_MINOR=3,Ve.LOG_MICRO=4,Ve.logAction=(r,n,o,l)=>{Ve.logActionNoStrip(r,n,o,l)};var lf=Ve,d=lf,es={};Q(es,{Format:()=>Bo,allSame:()=>mf,allToLowerCase:()=>Vo,allToUpperCase:()=>zo,arrChooseN:()=>Wo,arrDeleteValue:()=>Uo,arrEquals:()=>Qo,arrIntersect:()=>Lo,arrIntersectOb:()=>Do,arrPopRandomElement:()=>zn,arrWithoutValue:()=>gf,cheapRandStr:()=>Go,containsValue:()=>pf,copy:()=>ts,createMissingPluginError:()=>ns,dataSizeBytes:()=>Ho,decodeBody:()=>pe,encodeBody:()=>je,ensureArray:()=>Mo,forInOwnNonNullProperties:()=>qo,getBackoffCoefficient:()=>Ko,getGlobalObject:()=>yf,getJitterCoefficient:()=>Jo,getRetryTime:()=>Yn,inherits:()=>ff,inspectBody:()=>$o,inspectError:()=>ne,intersect:()=>No,isEmpty:()=>hf,isErrorInfoOrPartialErrorInfo:()=>Jn,isNil:()=>ze,isObject:()=>St,keysArray:()=>Us,listenerToAsyncIterator:()=>_f,matchDerivedChannel:()=>Yo,mixin:()=>J,parseQueryString:()=>js,prototypicalClone:()=>xo,randomString:()=>Fo,shallowClone:()=>df,shallowEquals:()=>Qn,stringifyValues:()=>Kn,throwMissingPluginError:()=>_e,toBase64:()=>qs,toQueryString:()=>ss,valuesArray:()=>jo,whenPromiseSettles:()=>Re,withTimeoutAsync:()=>Xo});function Io(r){let n="["+r.constructor.name;return r.message&&(n+=": "+r.message),r.statusCode&&(n+="; statusCode="+r.statusCode),r.code&&(n+="; code="+r.code),r.cause&&(n+="; cause="+ne(r.cause)),r.href&&!(r.message&&r.message.indexOf("help.ably.io")>-1)&&(n+="; see "+r.href+" "),n+="]",n}var x=class go extends Error{constructor(n,o,l,u){super(n),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,go.prototype),this.code=o,this.statusCode=l,this.cause=u}toString(){return Io(this)}static fromValues(n){let{message:o,code:l,statusCode:u}=n;if(typeof o!="string"||typeof l!="number"||typeof u!="number")throw new Error("ErrorInfo.fromValues(): invalid values: "+L.Config.inspect(n));let f=Object.assign(new go(o,l,u),n);return f.code&&!f.href&&(f.href="https://help.ably.io/error/"+f.code),f}},Ae=class mo extends Error{constructor(n,o,l,u){super(n),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,mo.prototype),this.code=o,this.statusCode=l,this.cause=u}toString(){return Io(this)}static fromValues(n){let{message:o,code:l,statusCode:u}=n;if(typeof o!="string"||!ze(l)&&typeof l!="number"||!ze(u)&&typeof u!="number")throw new Error("PartialErrorInfo.fromValues(): invalid values: "+L.Config.inspect(n));let f=Object.assign(new mo(o,l,u),n);return f.code&&!f.href&&(f.href="https://help.ably.io/error/"+f.code),f}};function uf(r){return Math.floor(Math.random()*r.length)}function J(r,...n){for(let o=0;o<n.length;o++){let l=n[o];if(!l)break;for(let u in l)Object.prototype.hasOwnProperty.call(l,u)&&(r[u]=l[u])}return r}function ts(r){return J({},r)}function Mo(r){return ze(r)?[]:Array.isArray(r)?r:[r]}function St(r){return Object.prototype.toString.call(r)=="[object Object]"}function hf(r){for(let n in r)return!1;return!0}function ze(r){return r==null}function df(r){let n=new Object;for(let o in r)n[o]=r[o];return n}function xo(r,n){class o{}o.prototype=r;let l=new o;return n&&J(l,n),l}var ff=function(r,n){if(L.Config.inherits){L.Config.inherits(r,n);return}r.super_=n,r.prototype=xo(n.prototype,{constructor:r})};function pf(r,n){for(let o in r)if(r[o]==n)return!0;return!1}function No(r,n){return Array.isArray(n)?Lo(r,n):Do(r,n)}function Lo(r,n){let o=[];for(let l=0;l<r.length;l++){let u=r[l];n.indexOf(u)!=-1&&o.push(u)}return o}function Do(r,n){let o=[];for(let l=0;l<r.length;l++){let u=r[l];u in n&&o.push(u)}return o}function Uo(r,n){let o=r.indexOf(n),l=o!=-1;return l&&r.splice(o,1),l}function gf(r,n){let o=r.slice();return Uo(o,n),o}function Us(r,n){let o=[];for(let l in r)n&&!Object.prototype.hasOwnProperty.call(r,l)||o.push(l);return o}function jo(r,n){let o=[];for(let l in r)n&&!Object.prototype.hasOwnProperty.call(r,l)||o.push(r[l]);return o}function qo(r,n){for(let o in r)Object.prototype.hasOwnProperty.call(r,o)&&r[o]&&n(o)}function mf(r,n){if(r.length===0)return!0;let o=r[0][n];return r.every(function(l){return l[n]===o})}var Bo=(r=>(r.msgpack="msgpack",r.json="json",r))(Bo||{});function zn(r){return r.splice(uf(r),1)[0]}function ss(r){let n=[];if(r)for(let o in r)n.push(encodeURIComponent(o)+"="+encodeURIComponent(r[o]));return n.length?"?"+n.join("&"):""}function Kn(r){return Object.fromEntries(Object.entries(r).map(([n,o])=>[n,String(o)]))}function js(r){let n,o=/([^?&=]+)=?([^&]*)/g,l={};for(;n=o.exec(r);)l[decodeURIComponent(n[1])]=decodeURIComponent(n[2]);return l}function Jn(r){return typeof r=="object"&&r!==null&&(r instanceof x||r instanceof Ae)}function ne(r){var n,o;return r instanceof Error||((n=r?.constructor)==null?void 0:n.name)==="ErrorInfo"||((o=r?.constructor)==null?void 0:o.name)==="PartialErrorInfo"?r.toString():L.Config.inspect(r)}function $o(r){return L.BufferUtils.isBuffer(r)?r.toString():typeof r=="string"?r:L.Config.inspect(r)}function Ho(r){if(L.BufferUtils.isBuffer(r))return L.BufferUtils.byteLength(r);if(typeof r=="string")return L.Config.stringByteSize(r);if(typeof r=="number")return 8;if(typeof r=="boolean")return 1;throw new Error(`Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: ${typeof r}`)}function Go(){return String(Math.random()).substr(2)}var Fo=async r=>{let n=await L.Config.getRandomArrayBuffer(r);return L.BufferUtils.base64Encode(n)};function Wo(r,n){let o=Math.min(n,r.length),l=r.slice(),u=[];for(let f=0;f<o;f++)u.push(zn(l));return u}function Re(r,n){r.then(o=>{n?.(null,o)}).catch(o=>{n?.(o)})}function pe(r,n,o){return o=="msgpack"?(n||_e("MsgPack"),n.decode(r)):JSON.parse(String(r))}function je(r,n,o){return o=="msgpack"?(n||_e("MsgPack"),n.encode(r,!0)):JSON.stringify(r)}function Vo(r){return r.map(function(n){return n&&n.toLowerCase()})}function zo(r){return r.map(function(n){return n&&n.toUpperCase()})}function Ko(r){return Math.min((r+2)/3,2)}function Jo(){return 1-Math.random()*.2}function Yn(r,n){return r*Ko(n)*Jo()}function yf(){return typeof global<"u"?global:typeof window<"u"?window:self}function Qn(r,n){return Object.keys(r).every(o=>r[o]===n[o])&&Object.keys(n).every(o=>n[o]===r[o])}function Yo(r){let n=/^(\[([^?]*)(?:(.*))\])?(.+)$/,o=r.match(n);if(!o||!o.length||o.length<5)throw new x("regex match failed",400,40010);if(o[2])throw new x(`cannot use a derived option with a ${o[2]} channel`,400,40010);return{qualifierParam:o[3]||"",channelName:o[4]}}function qs(r){let n=L.BufferUtils,o=n.utf8Encode(r);return n.base64Encode(o)}function Qo(r,n){return r.length===n.length&&r.every(function(o,l){return o===n[l]})}function ns(r){return new x(`${r} plugin not provided`,40019,400)}function _e(r){throw ns(r)}async function Xo(r,n=5e3,o="Timeout expired"){let l=new x(o,5e4,500);return Promise.race([r,new Promise((u,f)=>setTimeout(()=>f(l),n))])}function _f(r){return ce(this,null,function*(){let n=[],o=null,l=r(u=>{if(o){let f=o;o=null,f(u)}else n.push(u)});try{for(;;)if(n.length>0)yield n.shift();else{if(o)throw new x("Concurrent next() calls are not supported",4e4,400);yield yield new X(new Promise(f=>{o=f}))}}finally{l()}})}var Zo="2.17.0",bf="ably-js/"+Zo,qe={ENDPOINT:"main",ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["main.a.fallback.ably-realtime.com","main.b.fallback.ably-realtime.com","main.c.fallback.ably-realtime.com","main.d.fallback.ably-realtime.com","main.e.fallback.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:1e4,httpMaxRetryDuration:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,webSocketConnectTimeout:1e4,webSocketSlowTimeout:4e3},httpMaxRetryCount:3,maxMessageSize:65536,version:Zo,protocolVersion:5,agent:bf,getPort:vf,getHttpScheme:wf,getPrimaryDomainFromEndpoint:ta,getEndpointFallbackHosts:sa,getFallbackHosts:ra,getHosts:Cf,checkHost:ia,objectifyOptions:kf,normaliseOptions:Sf,defaultGetHeaders:Tf,defaultPostHeaders:Af};function vf(r,n){return n||r.tls?r.tlsPort:r.port}function wf(r){return r.tls?"https://":"http://"}function ea(r){return r.includes(".")||r.includes("::")||r==="localhost"}function ta(r){return ea(r)?r:r.startsWith("nonprod:")?`${r.replace("nonprod:","")}.realtime.ably-nonprod.net`:`${r}.realtime.ably.net`}function sa(r){if(ea(r))return[];if(r.startsWith("nonprod:")){let n=r.replace("nonprod:","");return na(n,"ably-realtime-nonprod.com")}return na(r,"ably-realtime.com")}function na(r,n){return["a","b","c","d","e"].map(o=>`${r}.${o}.fallback.${n}`)}function ra(r){let n=r.fallbackHosts,o=typeof r.httpMaxRetryCount<"u"?r.httpMaxRetryCount:qe.httpMaxRetryCount;return n?Wo(n,o):[]}function Cf(r){return[r.primaryDomain].concat(ra(r))}function ia(r){if(typeof r!="string")throw new x("host must be a string; was a "+typeof r,4e4,400);if(!r.length)throw new x("host must not be zero-length",4e4,400)}function Ef(r){let n={};for(let o in qe.TIMEOUTS)n[o]=r[o]||qe.TIMEOUTS[o];return n}function Xn(r){let n=qe.agent;if(r.agents)for(var o in r.agents)n+=" "+o+"/"+r.agents[o];return n}function kf(r,n,o,l,u){if(r===void 0){let y=n?`${o} must be initialized with either a client options object, an Ably API key, or an Ably Token`:`${o} must be initialized with a client options object`;throw d.logAction(l,d.LOG_ERROR,`${o}()`,y),new Error(y)}let f;if(typeof r=="string")if(r.indexOf(":")==-1){if(!n){let y=`${o} cannot be initialized with just an Ably Token; you must provide a client options object with a \`plugins\` property. (Set this Ably Token as the object\u2019s \`token\` property.)`;throw d.logAction(l,d.LOG_ERROR,`${o}()`,y),new Error(y)}f={token:r}}else{if(!n){let y=`${o} cannot be initialized with just an Ably API key; you must provide a client options object with a \`plugins\` property. (Set this Ably API key as the object\u2019s \`key\` property.)`;throw d.logAction(l,d.LOG_ERROR,`${o}()`,y),new Error(y)}f={key:r}}else f=r;return u&&(f=A(k({},f),{plugins:k(k({},u),f.plugins)})),f}function Of(r){if(r.endpoint&&(r.environment||r.restHost||r.realtimeHost))throw new x("The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",40106,400);if(r.environment&&(r.restHost||r.realtimeHost))throw new x("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function Sf(r,n,o){let l=o??d.defaultLogger;r.environment&&l.deprecated("The `environment` client option","Use the `endpoint` client option instead."),r.restHost&&l.deprecated("The `restHost` client option","Use the `endpoint` client option instead."),r.realtimeHost&&l.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead."),Of(r),typeof r.recover=="function"&&r.closeOnUnload===!0&&(d.logAction(l,d.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),r.recover=void 0),"closeOnUnload"in r||(r.closeOnUnload=!r.recover),"queueMessages"in r||(r.queueMessages=!0);let u=r.endpoint||qe.ENDPOINT;!r.fallbackHosts&&!r.restHost&&!r.realtimeHost&&!r.port&&!r.tlsPort&&(r.fallbackHosts=sa(r.environment||u));let f=r.environment&&`${r.environment}.realtime.ably.net`,_=r.restHost||r.realtimeHost||f||ta(u);(r.fallbackHosts||[]).concat(_).forEach(ia),r.port=r.port||qe.PORT,r.tlsPort=r.tlsPort||qe.TLS_PORT,"tls"in r||(r.tls=!0);let S=Ef(r);n?"useBinaryProtocol"in r?r.useBinaryProtocol=L.Config.supportsBinary&&r.useBinaryProtocol:r.useBinaryProtocol=L.Config.preferBinary:r.useBinaryProtocol=!1;let I={};r.clientId&&(I["X-Ably-ClientId"]=L.BufferUtils.base64Encode(L.BufferUtils.utf8Encode(r.clientId))),"idempotentRestPublishing"in r||(r.idempotentRestPublishing=!0);let U=null,D=r.connectivityCheckUrl;if(r.connectivityCheckUrl){let[C,R]=r.connectivityCheckUrl.split("?");U=R?js(R):{},C.indexOf("://")===-1&&(C="https://"+C),D=C}let G=r.wsConnectivityCheckUrl;return G&&G.indexOf("://")===-1&&(G="wss://"+G),A(k({},r),{primaryDomain:_,maxMessageSize:r.maxMessageSize||qe.maxMessageSize,timeouts:S,connectivityCheckParams:U,connectivityCheckUrl:D,wsConnectivityCheckUrl:G,headers:I})}function Bs(r,n,o){let l=o||{};if(l.cipher){r||_e("Crypto");let u=r.getCipher(l.cipher,n);l.cipher=u.cipherParams,l.channelCipher=u.cipher}else"cipher"in l&&(l.cipher=void 0,l.channelCipher=null);return l}var oa={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},aa={format:"json",protocolVersion:qe.protocolVersion};function Tf(r,{format:n,protocolVersion:o=aa.protocolVersion}={}){return{accept:oa[n??(r.useBinaryProtocol?"msgpack":"json")],"X-Ably-Version":o.toString(),"Ably-Agent":Xn(r)}}function Af(r,{format:n,protocolVersion:o=aa.protocolVersion}={}){let l=oa[n??(r.useBinaryProtocol?"msgpack":"json")];return{accept:l,"content-type":l,"X-Ably-Version":o.toString(),"Ably-Agent":Xn(r)}}var K=qe;function Rf(r){return Object.assign(qe,r)}var Pf=class Ad{constructor(n,o){this.logger=n,this.members=o||[]}call(n,o){for(let l of this.members)if(l)try{l(n,o)}catch(u){d.logAction(this.logger,d.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+u+"; stack = "+u.stack)}}push(...n){this.members.push(...n)}createPromise(){return new Promise((n,o)=>{this.push((l,u)=>{l?o(l):n(u)})})}resolveAll(n){this.call(null,n)}rejectAll(n){this.call(n)}static create(n,o){let l=new Ad(n,o);return Object.assign((u,f)=>l.call(u,f),{push:u=>l.push(u),createPromise:()=>l.createPromise(),resolveAll:u=>l.resolveAll(u),rejectAll:u=>l.rejectAll(u)})}},ca=Pf,la=(r=>(r.Get="get",r.Delete="delete",r.Post="post",r.Put="put",r.Patch="patch",r))(la||{}),de=la,ua=(r=>(r[r.Success=200]="Success",r[r.NoContent=204]="NoContent",r[r.BadRequest=400]="BadRequest",r[r.Unauthorized=401]="Unauthorized",r[r.Forbidden=403]="Forbidden",r[r.RequestTimeout=408]="RequestTimeout",r[r.InternalServerError=500]="InternalServerError",r))(ua||{});function If(r){return r>=200&&r<400}var rs=ua,Zn=Math.pow(2,17);function Mf(){return("000000"+Math.floor(Math.random()*1e16)).slice(-16)}function xf(r){return!!r.connection}function ha(r){return Jn(r)?(r.code||(r.statusCode===403?r.code=40300:(r.code=40170,r.statusCode=401)),r):new x(ne(r),r.code||40170,r.statusCode||401)}var Nf=(r,n)=>{let o=L.BufferUtils,l=o.utf8Encode(r),u=o.utf8Encode(n),f=o.hmacSha256(l,u);return o.base64Encode(f)};function da(r){if(!r)return"";typeof r=="string"&&(r=JSON.parse(r));let n=Object.create(null),o=Us(r,!0);if(!o)return"";o.sort();for(let l=0;l<o.length;l++)n[o[l]]=r[o[l]].sort();return JSON.stringify(n)}function fa(r,n){if(r.authCallback)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with authCallback");else if(r.authUrl)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with authUrl");else if(r.key)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(r.tokenDetails)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with supplied token only");else{let o="authOptions must include valid authentication parameters";throw d.logAction(n,d.LOG_ERROR,"Auth()",o),new Error(o)}}function Lf(r){return"useTokenAuth"in r&&!r.useTokenAuth}function pa(r){return r.useTokenAuth||!Lf(r)&&(r.authCallback||r.authUrl||r.token||r.tokenDetails)}function Df(r){return!r.key&&!r.authCallback&&!r.authUrl}var Uf=0;function jf(){return Uf++}var qf=class{constructor(r,n){if(this.authOptions={},this.client=r,this.tokenParams=n.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,pa(n))Df(n)&&d.logAction(this.logger,d.LOG_ERROR,"Auth()","Warning: library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),this._saveTokenOptions(n.defaultTokenParams,n),fa(this.authOptions,this.logger);else{if(!n.key){let o="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw d.logAction(this.logger,d.LOG_ERROR,"Auth()",o),new x(o,40160,401)}d.logAction(this.logger,d.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(n)}}get logger(){return this.client.logger}async authorize(r,n){if(n&&n.key&&this.authOptions.key!==n.key)throw new x("Unable to update auth options with incompatible key",40102,401);try{let o=await this._forceNewToken(r??null,n??null);return xf(this.client)?new Promise((l,u)=>{this.client.connection.connectionManager.onAuthUpdated(o,(f,y)=>f?u(f):l(y))}):o}catch(o){throw this.client.connection&&o.statusCode===rs.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(o),o}}async _forceNewToken(r,n){this.tokenDetails=null,this._saveTokenOptions(r,n),fa(this.authOptions,this.logger);try{return this._ensureValidAuthCredentials(!0)}finally{delete this.tokenParams.timestamp,delete this.authOptions.queryTime}}async requestToken(r,n){let o=n||this.authOptions,l=r||ts(this.tokenParams),u,f=this.client;if(o.authCallback)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),u=o.authCallback;else if(o.authUrl)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),u=(_,S)=>{let I=J({accept:"application/json, text/plain"},o.authHeaders),U=o.authMethod&&o.authMethod.toLowerCase()==="post",D,G=o.authUrl.indexOf("?");G>-1&&(D=js(o.authUrl.slice(G)),o.authUrl=o.authUrl.slice(0,G),U||(o.authParams=J(D,o.authParams)));let C=J({},o.authParams||{},_),R=P=>{var j,H;let V=(j=P.body)!=null?j:null,F=null;if(P.error)d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+ne(P.error));else{let Ce=(H=P.headers["content-type"])!=null?H:null;Array.isArray(Ce)?F=Ce.join(", "):F=Ce,d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+F+"; body: "+$o(V))}if(P.error){S(P.error,null);return}if(P.unpacked){S(null,V);return}if(L.BufferUtils.isBuffer(V)&&(V=V.toString()),!F){S(new x("authUrl response is missing a content-type header",40170,401),null);return}let te=F.indexOf("application/json")>-1,Te=F.indexOf("text/plain")>-1||F.indexOf("application/jwt")>-1;if(!te&&!Te){S(new x("authUrl responded with unacceptable content-type "+F+", should be either text/plain, application/jwt or application/json",40170,401),null);return}if(te){if(V.length>Zn){S(new x("authUrl response exceeded max permitted length",40170,401),null);return}try{V=JSON.parse(V)}catch(Ce){S(new x("Unexpected error processing authURL response; err = "+Ce.message,40170,401),null);return}}S(null,V,F)};if(d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+o.authUrl+"; Params: "+JSON.stringify(C)+"; method: "+(U?"POST":"GET")),U){let P=I||{};P["content-type"]="application/x-www-form-urlencoded";let j=ss(C).slice(1);Re(this.client.http.doUri(de.Post,o.authUrl,P,j,D),(H,V)=>R(H||V))}else Re(this.client.http.doUri(de.Get,o.authUrl,I||{},null,C),(P,j)=>R(P||j))};else if(o.key)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),u=(_,S)=>{Re(this.createTokenRequest(_,o),(I,U)=>S(I,U??null))};else{let _="Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)";throw d.logAction(this.logger,d.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),new x(_,40171,403)}"capability"in l&&(l.capability=da(l.capability));let y=(_,S)=>{let I=_.keyName,U="/keys/"+I+"/requestToken",D=function(C){return f.baseUri(C)+U},G=K.defaultPostHeaders(this.client.options,{format:"json"});o.requestHeaders&&J(G,o.requestHeaders),d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+U+"; Token params: "+JSON.stringify(_)),Re(this.client.http.do(de.Post,D,G,JSON.stringify(_),null),(C,R)=>C?S(C):S(R.error,R.body,R.unpacked))};return new Promise((_,S)=>{let I=!1,U=this.client.options.timeouts.realtimeRequestTimeout,D=setTimeout(()=>{I=!0;let G="Token request callback timed out after "+U/1e3+" seconds";d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()",G),S(new x(G,40170,401))},U);u(l,(G,C,R)=>{if(I)return;if(clearTimeout(D),G){d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+ne(G)),S(ha(G));return}if(typeof C=="string"){C.length===0?S(new x("Token string is empty",40170,401)):C.length>Zn?S(new x("Token string exceeded max permitted length (was "+C.length+" bytes)",40170,401)):C==="undefined"||C==="null"?S(new x("Token string was literal null/undefined",40170,401)):C[0]==="{"&&!(R&&R.indexOf("application/jwt")>-1)?S(new x("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401)):_({token:C});return}if(typeof C!="object"||C===null){let j="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof C;d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()",j),S(new x(j,40170,401));return}let P=JSON.stringify(C).length;if(P>Zn&&!o.suppressMaxLengthCheck){S(new x("Token request/details object exceeded max permitted stringified size (was "+P+" bytes)",40170,401));return}if("issued"in C){_(C);return}if(!("keyName"in C)){let j="Expected token request callback to call back with a token string, token request object, or token details object";d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()",j),S(new x(j,40170,401));return}y(C,(j,H,V)=>{if(j){d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+ne(j)),S(ha(j));return}V||(H=JSON.parse(H)),d.logAction(this.logger,d.LOG_MINOR,"Auth.getToken()","token received"),_(H)})})})}async createTokenRequest(r,n){n=n||this.authOptions,r=r||ts(this.tokenParams);let o=n.key;if(!o)throw new x("No key specified",40101,403);let l=o.split(":"),u=l[0],f=l[1];if(!f)throw new x("Invalid key specified",40101,403);if(r.clientId==="")throw new x("clientId can\u2019t be an empty string",40012,400);"capability"in r&&(r.capability=da(r.capability));let y=J({keyName:u},r),_=r.clientId||"",S=r.ttl||"",I=r.capability||"";y.timestamp||(y.timestamp=await this._getTimestamp(n&&n.queryTime));let U=y.nonce||(y.nonce=Mf()),D=y.timestamp,G=y.keyName+`
|
|
39
39
|
`+S+`
|
|
40
40
|
`+I+`
|
|
41
41
|
`+_+`
|
|
42
42
|
`+D+`
|
|
43
43
|
`+U+`
|
|
44
|
-
`;return y.mac=y.mac||Nf(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 "+js(r.token)}}}_saveBasicOptions(r){this.method="basic",this.key=r.key,this.basicKey=js(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=ca.create(this.logger))).createPromise();if(this.currentTokenRequestId!==null&&!r)return o;let l=this.currentTokenRequestId=jf(),u,f=null;try{u=await this.requestToken(this.tokenParams,this.authOptions)}catch(_){f=_}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=u),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)}},We=qf;function er(r){let n=[];if(r)for(let o in r)n.push(o+"="+r[o]);return n.join("&")}function St(r,n){return r+(n?"?":"")+er(n)}function Bf(r,n,o,l,u){r.error?d.logActionNoStrip(u,d.LOG_MICRO,"Http."+n+"()","Received Error; "+St(o,l)+"; Error: "+se(r.error)):d.logActionNoStrip(u,d.LOG_MICRO,"Http."+n+"()","Received; "+St(o,l)+"; Headers: "+er(r.headers)+"; StatusCode: "+r.statusCode+"; Body"+(L.BufferUtils.isBuffer(r.body)?" (Base64): "+L.BufferUtils.base64Encode(r.body):": "+r.body))}function $f(r,n,o,l,u){u.shouldLog(d.LOG_MICRO)&&d.logActionNoStrip(u,d.LOG_MICRO,"Http."+r+"()","Sending; "+St(n,l)+"; Body"+(L.BufferUtils.isBuffer(o)?" (Base64): "+L.BufferUtils.base64Encode(o):": "+o))}var tr=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(J.getFallbackHosts(r.options)):J.getHosts(r.options)}async do(r,n,o,l,u){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},_=f._currentFallback;if(_)if(_.validUntil>Date.now()){let D=await this.doUri(r,y(_.host),o,l,u);return D.error&&this.platformHttp.shouldFallback(D.error)?(f._currentFallback=null,this.do(r,n,o,l,u)):D}else f._currentFallback=null;let S=this._getHosts(f);if(S.length===1)return this.doUri(r,y(S[0]),o,l,u);let I=null,U=async(D,F)=>{let C=D.shift();I=I??new Date;let R=await this.doUri(r,y(C),o,l,u);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:C,validUntil:Date.now()+f.options.timeouts.fallbackRetryTimeout}),R)};return U(S)}catch(f){return{error:new x(`Unexpected error in Http.do: ${se(f)}`,500,5e4)}}}async doUri(r,n,o,l,u){try{$f(r,n,l,u,this.logger);let f=await this.platformHttp.doUri(r,n,o,l,u);return this.logger.shouldLog(d.LOG_MICRO)&&Bf(f,r,n,u,this.logger),f}catch(f){return{error:new x(`Unexpected error in Http.doUri: ${se(f)}`,500,5e4)}}}};function Hf(r,n,o,l){try{o.apply(n,l)}catch(u){d.logAction(r,d.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+u+"; stack = "+(u&&u.stack))}}function sr(r,n,o){let l,u,f;for(let y=0;y<r.length;y++)if(l=r[y],o&&(l=l[o]),Array.isArray(l)){for(;(u=l.indexOf(n))!==-1;)l.splice(u,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])&&sr([l],n,f)}var Gf=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(Fe(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||Fe(r[0])&&Fe(r[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}let[n,o]=r,l=null,u=null;if(r.length===1||!o)typeof n=="function"?l=n:u=n;else{if(typeof o!="function")throw new Error("EventEmitter.off(): invalid arguments:"+L.Config.inspect(r));[u,l]=[n,o]}if(l&&Fe(u)){sr([this.any,this.events,this.anyOnce,this.eventsOnce],l);return}if(Array.isArray(u)){u.forEach(f=>{this.off(f,l)});return}if(typeof u!="string")throw new Error("EventEmitter.off(): invalid arguments:"+L.Config.inspect(r));l?sr([this.events,this.eventsOnce],l,u):(delete this.events[u],delete this.eventsOnce[u])}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 u=this.eventsOnce[r];u&&(Array.prototype.push.apply(l,u),delete this.eventsOnce[r]);let f=this.events[r];f&&Array.prototype.push.apply(l,f),l.forEach(y=>{Hf(this.logger,o,y,n)})}once(...r){let n=r.length;if(n===0||n===1&&typeof r[0]!="function"){let u=r[0];return new Promise(f=>{this.once(u,f)})}let[o,l]=r;if(r.length===1&&typeof o=="function")this.anyOnce.push(o);else if(Fe(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 u=this,f=function(){let y=Array.prototype.slice.call(arguments);if(o.forEach(function(_){u.off(_,f)}),typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));l.apply(this,y)};o.forEach(function(y){u.on(y,f)})}else{if(typeof o!="string")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));let u=this.eventsOnce[o]||(this.eventsOnce[o]=[]);if(l){if(typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));u.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)}},de=Gf,K={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},ga=[];Object.keys(K).forEach(function(r){ga[K[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},Ff=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 ma=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function Wf(r){return!r||!r.channelOptions?{channelOptions:r,plugins:{},baseEncodedPreviousPayload:void 0}:r}function ya(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 Vf(r,n){let{data:o,encoding:l}=await _a(r.data,r.encoding,n);return r.data=o,r.encoding=l,r}async function _a(r,n,o){let l=o.channelCipher,u=r,f=n?n+"/":"";L.BufferUtils.isBuffer(u)||(u=L.BufferUtils.utf8Encode(String(u)),f=f+"utf-8/");let y=await l.encrypt(u);return f=f+"cipher+"+l.algorithm,{data:y,encoding:f}}async function nr(r,n){let{data:o,encoding:l}=ba(r.data,r.encoding);return r.data=o,r.encoding=l,n!=null&&n.cipher?Vf(r,n):r}function ba(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 rr(r,n){let{data:o,encoding:l,error:u}=await va(r.data,r.encoding,n);if(r.data=o,r.encoding=l,u)throw u}async function va(r,n,o){let l=Wf(o),u=r,f=r,y=n,_;if(n){let S=n.split("/"),I,U=S.length,D="";try{for(;(I=U)>0;){let F=S[--U].match(/([-\w]+)(\+([\w-]+))?/);if(!F)break;switch(D=F[1],D){case"base64":f=L.BufferUtils.base64Decode(String(f)),I==S.length&&(u=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 C=F[3],R=l.channelOptions.channelCipher;if(C!=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 C=l.baseEncodedPreviousPayload;typeof C=="string"&&(C=L.BufferUtils.utf8Encode(C));let R=L.BufferUtils.toBuffer(C);f=L.BufferUtils.toBuffer(f),f=L.BufferUtils.arrayBufferViewToBuffer(l.plugins.vcdiff.decode(f,R)),u=f}catch(C){throw new x("Vcdiff delta decode failed with "+C,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(F){let C=F;_=new x(`Error processing the ${D} encoding, decoder returned \u2018${C.message}\u2019`,C.code||40013,400)}finally{y=I<=0?null:S.slice(0,I).join("/")}}return _?{error:_,data:f,encoding:y}:(l.baseEncodedPreviousPayload=u,{data:f,encoding:y})}function ir(...r){let n=r.length>0?"json":"msgpack",{data:o,encoding:l}=wa(this.data,this.encoding,n);return Object.assign({},this,{encoding:l,data:o})}function wa(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 Bs={encryptData:_a,encodeData:ba,encodeDataForWire:wa,decodeData:va};function $s(r){let{id:n,connectionId:o,timestamp:l}=r,u;switch(r.action){case K.MESSAGE:{u=r.messages;break}case K.PRESENCE:case K.SYNC:u=r.presence;break;case K.ANNOTATION:u=r.annotations;break;case K.OBJECT:case K.OBJECT_SYNC:u=r.state;break;default:throw new x("Unexpected action "+r.action,4e4,400)}for(let f=0;f<u.length;f++){let y=u[f];y.connectionId||(y.connectionId=o),y.timestamp||(y.timestamp=l),n&&!y.id&&(y.id=n+":"+f)}}function Tt(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{},Ca=class{constructor(r){this.Platform=L,this.ErrorInfo=x,this.Logger=d,this.Defaults=J,this.Utils=Zt,this.EventEmitter=de,this.MessageEncoding=Bs;var n,o,l,u,f,y,_,S,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=J.normaliseOptions(r,this._MsgPack,this.logger);if(D.key){let F=D.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!F){let C="invalid key parameter";throw d.logAction(this.logger,d.LOG_ERROR,"BaseClient()",C),new x(C,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 = "+J.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new tr(this),this.auth=new We(this,D),this._rest=(u=r.plugins)!=null&&u.Rest?new r.plugins.Rest(this):null,this._Crypto=(y=(f=r.plugins)==null?void 0:f.Crypto)!=null?y:null,this.__FilteredSubscriptions=(S=(_=r.plugins)==null?void 0:_.MessageInteractions)!=null?S: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 J.getHttpScheme(this.options)+r+":"+J.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,u,f){return this.rest.request(r,n,o,l,u,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}};Ca.Platform=L;var Ea=Ca,zf=class Qt{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,u;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)),(u=this.push)!=null&&u.metadata&&(f+="; push.metadata="+this.push.metadata),f+="]",f}static toRequestBody(n,o,l){return De(n,o,l)}static fromResponseBody(n,o,l){return l&&(n=he(n,o,l)),Array.isArray(n)?Qt.fromValuesArray(n):Qt.fromValues(n)}static fromValues(n){return n.error=n.error&&x.fromValues(n.error),Object.assign(new Qt,n)}static fromLocalDevice(n){return Object.assign(new Qt,n)}static fromValuesArray(n){let o=n.length,l=new Array(o);for(let u=0;u<o;u++)l[u]=Qt.fromValues(n[u]);return l}},Rt=zf;async function ka(r,n,o,l){if(r.http.supportsAuthHeaders){let u=await r.auth.getAuthHeaders();return l(Y(u,n),o)}else{let u=await r.auth.getAuthParams();return l(n,Y(u,o))}}function Kf(r,n,o){if(r.err&&!r.body)return{err:r.err};if(r.statusCode===ns.NoContent)return T(k({},r),{body:[],unpacked:!0});let l=r.body;if(!r.unpacked)try{l=he(l,n,o)}catch(_){return Jn(_)?{err:_}:{err:new Se(se(_),null)}}if(!l)return{err:new Se("unenvelope(): Response body is missing",null)};let{statusCode:u,response:f,headers:y}=l;if(u===void 0)return T(k({},r),{body:l,unpacked:!0});if(u<200||u>=300){let _=f&&f.error||r.err;return _||(_=new Error("Error in unenveloping "+l),_.statusCode=u),{err:_,body:f,headers:y,unpacked:!0,statusCode:u}}return{err:r.err,body:f,headers:y,unpacked:!0,statusCode:u}}function Jf(r,n,o,l,u){r.err?d.logAction(u,d.LOG_MICRO,"Resource."+n+"()","Received Error; "+St(o,l)+"; Error: "+se(r.err)):d.logAction(u,d.LOG_MICRO,"Resource."+n+"()","Received; "+St(o,l)+"; Headers: "+er(r.headers)+"; StatusCode: "+r.statusCode+"; Body: "+(L.BufferUtils.isBuffer(r.body)?" (Base64): "+L.BufferUtils.base64Encode(r.body):": "+L.Config.inspect(r.body)))}var Yf=class Xt{static async get(n,o,l,u,f,y){return Xt.do(le.Get,n,o,null,l,u,f,y??!1)}static async delete(n,o,l,u,f,y){return Xt.do(le.Delete,n,o,null,l,u,f,y)}static async post(n,o,l,u,f,y,_){return Xt.do(le.Post,n,o,l,u,f,y,_)}static async patch(n,o,l,u,f,y,_){return Xt.do(le.Patch,n,o,l,u,f,y,_)}static async put(n,o,l,u,f,y,_){return Xt.do(le.Put,n,o,l,u,f,y,_)}static async do(n,o,l,u,f,y,_,S){_&&((y=y||{}).envelope=_);let I=o.logger;async function U(F,C){var R;if(I.shouldLog(d.LOG_MICRO)){let j=u;if(((R=F["content-type"])==null?void 0:R.indexOf("msgpack"))>0)try{o._MsgPack||me("MsgPack"),j=o._MsgPack.decode(u)}catch(G){d.logAction(I,d.LOG_MICRO,"Resource."+n+"()","Sending MsgPack Decoding Error: "+se(G))}d.logAction(I,d.LOG_MICRO,"Resource."+n+"()","Sending; "+St(l,C)+"; Body: "+j)}let P=await o.http.do(n,l,F,u,C);return P.error&&We.isTokenErr(P.error)?(await o.auth.authorize(null,null),ka(o,F,C,U)):{err:P.error,body:P.body,headers:P.headers,unpacked:P.unpacked,statusCode:P.statusCode}}let D=await ka(o,f,y,U);if(_&&(D=Kf(D,o._MsgPack,_)),I.shouldLog(d.LOG_MICRO)&&Jf(D,n,l,y,I),S){if(D.err)throw D.err;{let F=k({},D);return delete F.err,F}}return D}},oe=Yf;function Qf(r){let n=r.match(/^\.\/(\w+)\?(.*)$/);return n&&n[2]&&Us(n[2])}function Xf(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 u=Qf(l[1]);u&&(n[l[2]]=u)}}return n}function Zf(r,n,o){return!(o&&(n||typeof r.code=="number"))}var ep=class{constructor(r,n,o,l,u,f){this.client=r,this.path=n,this.headers=o,this.envelope=l??null,this.bodyHandler=u,this.useHttpPaginatedResponse=f||!1}get logger(){return this.client.logger}async get(r){let n=await oe.get(this.client,this.path,this.headers,r,this.envelope,!1);return this.handlePage(n)}async delete(r){let n=await oe.delete(this.client,this.path,this.headers,r,this.envelope,!1);return this.handlePage(n)}async post(r,n){let o=await oe.post(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async put(r,n){let o=await oe.put(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async patch(r,n){let o=await oe.patch(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async handlePage(r){if(r.err&&Zf(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==ns.NoContent?[]:await this.bodyHandler(r.body,r.headers||{},r.unpacked)}catch(u){throw r.err||u}return r.headers&&(o=r.headers.Link||r.headers.link)&&(l=Xf(o)),this.useHttpPaginatedResponse?new tp(this,n,r.headers||{},r.statusCode,l,r.err):new Oa(this,n,l)}},Oa=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 oe.get(n.client,n.path,n.headers,r,n.envelope,!1);return n.handlePage(o)}},tp=class extends Oa{constructor(r,n,o,l,u,f){super(r,n,u),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}}},je=ep,Sa=class Ms{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=he(n,o,l)),Array.isArray(n)?Ms.fromValuesArray(n):Ms.fromValues(n)}static fromValues(n){return Object.assign(new Ms,n)}static fromValuesArray(n){let o=n.length,l=new Array(o);for(let u=0;u<o;u++)l[u]=Ms.fromValues(n[u]);return l}};Sa.toRequestBody=De;var sp=Sa,Hs=sp,np=class{constructor(r){var n;this.client=r,this.admin=new rp(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 u;if(!((u=this.client.options.plugins)!=null&&u.Push)){l(ss("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(ss("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=u=>{if(u){o(u);return}n()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,r))})}},rp=class{constructor(r){this.client=r,this.deviceRegistrations=new ip(r),this.channelSubscriptions=new op(r)}async publish(r,n){let o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",u=J.defaultPostHeaders(o.options),f={},y=Y({recipient:r},n);Y(u,o.options.headers),o.options.pushFullWait&&Y(f,{fullWait:"true"});let _=De(y,o._MsgPack,l);await oe.post(o,"/push/publish",_,u,f,null,!0)}},ip=class{constructor(r){this.client=r}async save(r){let n=this.client,o=Rt.fromValues(r),l=n.options.useBinaryProtocol?"msgpack":"json",u=J.defaultPostHeaders(n.options),f={};Y(u,n.options.headers),n.options.pushFullWait&&Y(f,{fullWait:"true"});let y=De(o,n._MsgPack,l),_=await oe.put(n,"/push/deviceRegistrations/"+encodeURIComponent(r.id),y,u,f,null,!0);return Rt.fromResponseBody(_.body,n._MsgPack,_.unpacked?void 0:l)}async get(r){let n=this.client,o=n.options.useBinaryProtocol?"msgpack":"json",l=J.defaultGetHeaders(n.options),u=r.id||r;if(typeof u!="string"||!u.length)throw new x("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);Y(l,n.options.headers);let f=await oe.get(n,"/push/deviceRegistrations/"+encodeURIComponent(u),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,u=J.defaultGetHeaders(n.options);return Y(u,n.options.headers),new je(n,"/push/deviceRegistrations",u,l,async function(f,y,_){return Rt.fromResponseBody(f,n._MsgPack,_?void 0:o)}).get(r)}async remove(r){let n=this.client,o=J.defaultGetHeaders(n.options),l={},u=r.id||r;if(typeof u!="string"||!u.length)throw new x("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);Y(o,n.options.headers),n.options.pushFullWait&&Y(l,{fullWait:"true"}),await oe.delete(n,"/push/deviceRegistrations/"+encodeURIComponent(u),o,l,null,!0)}async removeWhere(r){let n=this.client,o=n.options.useBinaryProtocol?"msgpack":"json",l=J.defaultGetHeaders(n.options,{format:o});Y(l,n.options.headers),n.options.pushFullWait&&Y(r,{fullWait:"true"}),await oe.delete(n,"/push/deviceRegistrations",l,r,null,!0)}},op=class Rd{constructor(n){this.remove=Rd.prototype.removeWhere,this.client=n}async save(n){let o=this.client,l=Hs.fromValues(n),u=o.options.useBinaryProtocol?"msgpack":"json",f=J.defaultPostHeaders(o.options),y={};Y(f,o.options.headers),o.options.pushFullWait&&Y(y,{fullWait:"true"});let _=De(l,o._MsgPack,u),S=await oe.post(o,"/push/channelSubscriptions",_,f,y,null,!0);return Hs.fromResponseBody(S.body,o._MsgPack,S.unpacked?void 0:u)}async list(n){let o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",u=this.client.http.supportsLinkHeaders?void 0:l,f=J.defaultGetHeaders(o.options);return Y(f,o.options.headers),new je(o,"/push/channelSubscriptions",f,u,async function(y,_,S){return Hs.fromResponseBody(y,o._MsgPack,S?void 0:l)}).get(n)}async removeWhere(n){let o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",u=J.defaultGetHeaders(o.options,{format:l});Y(u,o.options.headers),o.options.pushFullWait&&Y(n,{fullWait:"true"}),await oe.delete(o,"/push/channelSubscriptions",u,n,null,!0)}async listChannels(n){let o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",u=this.client.http.supportsLinkHeaders?void 0:l,f=J.defaultGetHeaders(o.options);return Y(f,o.options.headers),o.options.pushFullWait&&Y(n,{fullWait:"true"}),new je(o,"/push/channels",f,u,async function(y,_,S){let I=!S&&l?he(y,o._MsgPack,l):y;for(let U=0;U<I.length;U++)I[U]=String(I[U]);return I}).get(n)}},ap=np,Ta=["absent","present","enter","leave","update"];async function Aa(r,n,o,l){let u=ya(n,r,l??null);return rs.fromValues(o).decode(u,r)}async function cp(r,n,o,l){return Promise.all(o.map(function(u){return Aa(r,n,u,l)}))}async function lp(r,n){return rs.fromValues(r).decode(n.channelOptions,n.logger)}async function Ra(r,n){return Promise.all(r.map(function(o){return lp(o,n)}))}var Pa=class xs 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 rs,this,{action:Ta.indexOf(this.action||"present")});return nr(o,n)}static fromValues(n){return Object.assign(new xs,n)}static fromValuesArray(n){return n.map(o=>xs.fromValues(o))}static fromData(n){return n instanceof xs?n:xs.fromValues({data:n})}toString(){return Tt(this,"PresenceMessage")}},rs=class yo extends At{toJSON(...n){return ir.call(this,...n)}static fromValues(n){return Object.assign(new yo,n)}static fromValuesArray(n){return n.map(o=>yo.fromValues(o))}async decode(n,o){let l=Object.assign(new Pa,T(k({},this),{action:Ta[this.action]}));try{await rr(l,n)}catch(u){d.logAction(o,d.LOG_ERROR,"WirePresenceMessage.decode()",se(u))}return l}toString(){return Tt(this,"WirePresenceMessage")}},Ve=Pa,up=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,u=J.defaultGetHeaders(n.options);return Y(u,n.options.headers),new je(n,this.channel.client.rest.presenceMixin.basePath(this),u,l,async(f,y,_)=>{let S=_?f:he(f,n._MsgPack,o);return Ra(S,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)}},hp=up,Ia=["message.create","message.update","message.delete","meta","message.summary","message.append"];function dp(r){return Ia[r||0]||"unknown"}function fp(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+=Ho(r.data)),n}async function Ma(r,n,o,l){let u=ya(n,r,l??null);return is.fromValues(o).decode(u,r)}async function pp(r,n,o,l){return Promise.all(o.map(function(u){return Ma(r,n,u,l)}))}async function xa(r,n){return is.fromValues(r).decode(n.channelOptions,n.logger)}async function Na(r,n){return Promise.all(r.map(function(o){return xa(o,n)}))}async function La(r,n){return Promise.all(r.map(o=>o.encode(n)))}var Da=De;function Ua(r){let n,o=0;for(let l=0;l<r.length;l++)n=r[l],o+=n.size||(n.size=fp(n));return o}var ja=class _o 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 is,this,{action:Ia.indexOf(this.action||"message.create")});return nr(o,n)}static fromValues(n){return Object.assign(new _o,n)}static fromValuesArray(n){return n.map(o=>_o.fromValues(o))}toString(){return Tt(this,"Message")}},is=class bo extends At{toJSON(...n){return ir.call(this,...n)}static fromValues(n){return Object.assign(new bo,n)}static fromValuesArray(n){return n.map(o=>bo.fromValues(o))}async decodeWithErr(n,o){let l=Object.assign(new ja,T(k({},this),{action:dp(this.action)})),u;try{await rr(l,n)}catch(f){d.logAction(o,d.LOG_ERROR,"WireMessage.decode()",se(f)),u=f}return l.expandFields(),{decoded:l,err:u}}async decode(n,o){let{decoded:l}=await this.decodeWithErr(n,o);return l}toString(){return Tt(this,"WireMessage")}},$e=ja,gp=9;function mp(r){return r.every(function(n){return!n.id})}var yp=class{constructor(r,n,o){this._annotations=null;var l,u;d.logAction(r.logger,d.LOG_MINOR,"RestChannel()","started; name = "+n),this.name=n,this.client=r,this.presence=new hp(this),this.channelOptions=qs((l=r._Crypto)!=null?l:null,this.logger,o),(u=r.options.plugins)!=null&&u.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=qs((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,u;if(typeof n=="string"||n===null)l=[$e.fromValues({name:n,data:o})],u=r[2];else if(Ot(n))l=[$e.fromValues(n)],u=r[1];else if(Array.isArray(n))l=$e.fromValuesArray(n),u=r[1];else throw new x("The single-argument form of publish() expects a message object or an array of message objects",40013,400);u||(u={});let f=this.client,y=f.options,_=y.useBinaryProtocol?"msgpack":"json",S=f.options.idempotentRestPublishing,I=J.defaultPostHeaders(f.options);if(Y(I,y.headers),S&&mp(l)){let C=await Fo(gp);l.forEach(function(R,P){R.id=C+":"+P.toString()})}let U=await La(l,this.channelOptions),D=Ua(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(Da(U,f._MsgPack,_),I,u)}async _publish(r,n,o){let l=this.client,u=l.options.useBinaryProtocol?"msgpack":"json",{body:f,unpacked:y}=await oe.post(l,l.rest.channelMixin.basePath(this)+"/messages",r,n,o,null,!0),_=(y?f:he(f,l._MsgPack,u))||{};return delete _.channel,delete _.messageId,_}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)}},_p=yp,bp=class Pd{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 Pd(n)}},vp=bp,qa=class{static basePath(r){return"/channels/"+encodeURIComponent(r.name)}static history(r,n){let o=r.client,l=o.options.useBinaryProtocol?"msgpack":"json",u=r.client.http.supportsLinkHeaders?void 0:l,f=J.defaultGetHeaders(o.options);return Y(f,o.options.headers),new je(o,this.basePath(r)+"/messages",f,u,async function(y,_,S){let I=S?y:he(y,o._MsgPack,l);return Na(I,r)}).get(n)}static async status(r){let n=r.client.options.useBinaryProtocol?"msgpack":"json",o=J.defaultPostHeaders(r.client.options);return(await oe.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,u=l.options.useBinaryProtocol?"msgpack":"json",f=J.defaultGetHeaders(l.options);Y(f,l.options.headers);let{body:y,unpacked:_}=await oe.get(l,this.basePath(r)+"/messages/"+encodeURIComponent(o),f,{},null,!0),S=_?y:he(y,l._MsgPack,u);return xa(S,r)}static async updateDeleteMessage(r,n,o,l,u){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",_=J.defaultPostHeaders(f.options);Y(_,f.options.headers);let S=$e.fromValues(o);S.action=n,S.version=l;let I=await S.encode(r.channelOptions),U=Da(I,f._MsgPack,y),D=oe.patch,{body:F,unpacked:C}=await D(f,this.basePath(r)+"/messages/"+encodeURIComponent(o.serial),U,_,u||{},null,!0);return(C?F:he(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 u=r.client,f=u.options.useBinaryProtocol?"msgpack":"json",y=r.client.http.supportsLinkHeaders?void 0:f,_=J.defaultGetHeaders(u.options);return Y(_,u.options.headers),new je(u,this.basePath(r)+"/messages/"+encodeURIComponent(l)+"/versions",_,y,async(S,I,U)=>{let D=U?S:he(S,u._MsgPack,f);return Na(D,r)}).get(o||{})}},wp=class{static basePath(r){return qa.basePath(r.channel)+"/presence"}static async history(r,n){let o=r.channel.client,l=o.options.useBinaryProtocol?"msgpack":"json",u=r.channel.client.http.supportsLinkHeaders?void 0:l,f=J.defaultGetHeaders(o.options);return Y(f,o.options.headers),new je(o,this.basePath(r)+"/history",f,u,async(y,_,S)=>{let I=S?y:he(y,o._MsgPack,l);return Ra(I,r.channel)}).get(n)}},Ba=class{constructor(r){this.channelMixin=qa,this.presenceMixin=wp,this.Resource=oe,this.PaginatedResource=je,this.DeviceDetails=Rt,this.PushChannelSubscription=Hs,this.client=r,this.channels=new Cp(this.client),this.push=new ap(this.client)}async stats(r){let n=J.defaultGetHeaders(this.client.options),o=this.client.options.useBinaryProtocol?"msgpack":"json",l=this.client.http.supportsLinkHeaders?void 0:o;return Y(n,this.client.options.headers),new je(this.client,"/stats",n,l,async(u,f,y)=>{let _=y?u:he(u,this.client._MsgPack,o);for(let S=0;S<_.length;S++)_[S]=vp.fromValues(_[S]);return _}).get(r)}async time(r){let n=J.defaultGetHeaders(this.client.options,{format:"json"});this.client.options.headers&&Y(n,this.client.options.headers);let o=_=>this.client.baseUri(_)+"/time",{error:l,body:u,unpacked:f}=await this.client.http.do(le.Get,o,n,null,r);if(l)throw l;f||(u=JSON.parse(u));let y=u[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,u,f){var y;let[_,S,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"?J.defaultGetHeaders(this.client.options,{format:I,protocolVersion:o}):J.defaultPostHeaders(this.client.options,{format:I,protocolVersion:o});typeof u!="string"&&(u=(y=_(u))!=null?y:null),Y(F,this.client.options.headers),f&&Y(F,f);let C=new je(this.client,n,F,U,async function(R,P,j){return Mo(j?R:S(R))},!0);if(!L.Http.methods.includes(D))throw new x("Unsupported method "+D,40500,405);return L.Http.methodsWithBody.includes(D)?C[D](l,u):C[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",u=J.defaultPostHeaders(this.client.options);this.client.options.headers&&Y(u,this.client.options.headers);let f=De(n,this.client._MsgPack,l),y=await oe.post(this.client,"/messages",f,u,{},null,!0),_=y.unpacked?y.body:he(y.body,this.client._MsgPack,l);return o?_[0]:_}async batchPresence(r){let n=this.client.options.useBinaryProtocol?"msgpack":"json",o=J.defaultGetHeaders(this.client.options);this.client.options.headers&&Y(o,this.client.options.headers);let l=r.join(","),u=await oe.get(this.client,"/presence",o,{channels:l},null,!0);return u.unpacked?u.body:he(u.body,this.client._MsgPack,n)}async revokeTokens(r,n){if(pa(this.client.options))throw new x("Cannot revoke tokens when using token auth",40162,401);let o=this.client.options.keyName,l=n??{},u=k({targets:r.map(I=>`${I.type}:${I.value}`)},l),f=this.client.options.useBinaryProtocol?"msgpack":"json",y=J.defaultPostHeaders(this.client.options);this.client.options.headers&&Y(y,this.client.options.headers);let _=De(u,this.client._MsgPack,f),S=await oe.post(this.client,`/keys/${o}/revokeTokens`,_,y,{},null,!0);return S.unpacked?S.body:he(S.body,this.client._MsgPack,f)}},Cp=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 _p(this.client,r,n),o}release(r){delete this.all[String(r)]}},Ep=class extends Ea{constructor(r){super(J.objectifyOptions(r,!1,"BaseRest",d.defaultLogger,{Rest:Ba}))}},$a={Rest:Ba},Ha=class extends $e{static async fromEncoded(r,n){return Ma(d.defaultLogger,L.Crypto,r,n)}static async fromEncodedArray(r,n){return pp(d.defaultLogger,L.Crypto,r,n)}static fromValues(r){return $e.fromValues(r)}},Ga=class extends Ve{static async fromEncoded(r,n){return Aa(d.defaultLogger,L.Crypto,r,n)}static async fromEncodedArray(r,n){return cp(d.defaultLogger,L.Crypto,r,n)}static fromValues(r){return Ve.fromValues(r)}},Fa=["annotation.create","annotation.delete"];async function Wa(r,n,o){return Pt.fromValues(n).decode(o||{},r)}async function kp(r,n,o){return Promise.all(n.map(function(l){return Wa(r,l,o)}))}async function Op(r,n){return Pt.fromValues(r).decode(n.channelOptions,n.logger)}async function Sp(r,n){return Promise.all(r.map(function(o){return Op(o,n)}))}var Va=class vo extends At{async encode(){let n=Object.assign(new Pt,this,{action:Fa.indexOf(this.action||"annotation.create")});return nr(n,{})}static fromValues(n){return Object.assign(new vo,n)}static fromValuesArray(n){return n.map(o=>vo.fromValues(o))}toString(){return Tt(this,"Annotation")}},Pt=class wo extends At{toJSON(...n){return ir.call(this,...n)}static fromValues(n){return Object.assign(new wo,n)}static fromValuesArray(n){return n.map(o=>wo.fromValues(o))}async decode(n,o){let l=Object.assign(new Va,T(k({},this),{action:Fa[this.action]}));try{await rr(l,n)}catch(u){d.logAction(o,d.LOG_ERROR,"WireAnnotation.decode()",se(u))}return l}toString(){return Tt(this,"WireAnnotation")}},It=Va,za=class extends It{static async fromEncoded(r,n){return Wa(d.defaultLogger,r,n)}static async fromEncodedArray(r,n){return kp(d.defaultLogger,r,n)}static fromValues(r){return It.fromValues(r)}};function Ka(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 Ja(r,n){let o=Ka(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 Ya(r,n){return r.client.rest.channelMixin.basePath(r)+"/messages/"+encodeURIComponent(n)+"/annotations"}var Tp=class{constructor(r){this.channel=r}async publish(r,n){let o=Ja(r,n),l=await o.encode(),u=this.channel.client,f=u.options,y=f.useBinaryProtocol?"msgpack":"json",_=J.defaultPostHeaders(u.options),S={};Y(_,u.options.headers);let I=De([l],u._MsgPack,y);await oe.post(u,Ya(this.channel,o.messageSerial),I,_,S,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=Ka(r),u=o.options.useBinaryProtocol?"msgpack":"json",f=o.http.supportsLinkHeaders?void 0:u,y=J.defaultGetHeaders(o.options);return Y(y,o.options.headers),new je(o,Ya(this.channel,l),y,f,async(_,S,I)=>{let U=I?_:he(_,o._MsgPack,u);return Sp(U,this.channel)}).get(n)}},Gs=Tp,Ap=De;function Fs(r){let n=[];if(r)for(let o=0;o<r.length;o++)n.push(r[o].toString());return"[ "+n.join(", ")+" ]"}function Rp(r,n,o,l,u,f){let y=he(r,n,f);return or(y,o,l,u)}function or(r,n,o,l){let u;r.error&&(u=x.fromValues(r.error));let f;r.messages&&(f=is.fromValuesArray(r.messages));let y;n&&r.presence&&(y=n.WirePresenceMessage.fromValuesArray(r.presence));let _;o&&r.annotations&&(_=o.WireAnnotation.fromValuesArray(r.annotations));let S;return l&&r.state&&(S=l.WireObjectMessage.fromValuesArray(r.state,Zt,Bs)),Object.assign(new cr,T(k({},r),{presence:y,messages:f,annotations:_,state:S,error:u}))}function Pp(r){return n=>{var o;return or(n,{PresenceMessage:Ve,WirePresenceMessage:rs},{Annotation:It,WireAnnotation:Pt,RealtimeAnnotations:ur,RestAnnotations:Gs},(o=r?.LiveObjectsPlugin)!=null?o:null)}}function ke(r){return Object.assign(new cr,r)}function ar(r,n,o,l){let u="[ProtocolMessage";r.action!==void 0&&(u+="; action="+ga[r.action]||r.action);let f=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"],y;for(let _=0;_<f.length;_++)y=f[_],r[y]!==void 0&&(u+="; "+y+"="+r[y]);if(r.messages&&(u+="; messages="+Fs(is.fromValuesArray(r.messages))),r.presence&&n&&(u+="; presence="+Fs(n.WirePresenceMessage.fromValuesArray(r.presence))),r.annotations&&o&&(u+="; annotations="+Fs(o.WireAnnotation.fromValuesArray(r.annotations))),r.state&&l&&(u+="; state="+Fs(l.WireObjectMessage.fromValuesArray(r.state,Zt,Bs))),r.error&&(u+="; error="+x.fromValues(r.error).toString()),r.auth&&r.auth.accessToken&&(u+="; token="+r.auth.accessToken),r.flags&&(u+="; flags="+Ff.filter(r.hasFlag).join(",")),r.params){let _="";qo(r.params,function(S){_.length>0&&(_+="; "),_+=S+"="+r.params[S]}),_.length>0&&(u+="; params=["+_+"]")}return u+="]",u}var cr=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 ma.forEach(n=>{this.hasFlag(n)&&r.push(n)}),r.length>0?r:void 0}},Ip=cr,Mp=class{constructor(r,n,o,l,u){this.previous=r,this.current=n,n==="attached"&&(this.resumed=o,this.hasBacklog=l),u&&(this.reason=u)}},lr=Mp,Qa=function(){};function xp(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"||!ma.includes(String.prototype.toUpperCase.call(o)))return new x("Invalid channel mode: "+o,4e4,400)}}}var Np=class Co extends de{constructor(n,o,l){var u,f,y;super(n.logger),this._annotations=null,this._mode=0,this.retryCount=0,this.history=async function(_){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);let S=this.client.rest.channelMixin;if(_&&_.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 _.untilAttach,_.from_serial=this.properties.attachSerial}return S.history(this,_)},this.whenState=_=>de.prototype.whenState.call(this,_,this.state),d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel()","started; name = "+o),this.name=o,this.channelOptions=qs((u=n._Crypto)!=null?u: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 de(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 de(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,u=xp(n);if(u)throw u;if(this.channelOptions=qs((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(_){switch(this.event){case"update":case"attached":f();break;default:y(_.reason)}})})}_shouldReattachToSetOptions(n,o){if(!(this.state==="attached"||this.state==="attaching"))return!1;if(n?.params){let l=Xa(n.params),u=Xa(o.params);if(Object.keys(l).length!==Object.keys(u).length||!Qn(u,l))return!0}return!!(n?.modes&&(!o.modes||!Qo(n.modes,o.modes)))}async publish(...n){let o=n[0],l=n[1],u,f;if(typeof o=="string"||o===null||o===void 0)u=[$e.fromValues({name:o,data:l})],f=n[2];else if(Ot(o))u=[$e.fromValues(o)],f=n[1];else if(Array.isArray(o))u=$e.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,_=await La(u,this.channelOptions),S=Ua(_);if(S>y)throw new x(`Maximum size of messages that can be published at once exceeded (was ${S} 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 = "+_.length);let I=ke({action:K.MESSAGE,channel:this.name,messages:_,params:f?Kn(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 u=n[l];o.emit(u.name,u)}}async attach(){return this.state==="attached"?null:new Promise((n,o)=>{this._attach(!1,null,(l,u)=>l?o(l):n(u))})}_attach(n,o,l){l||(l=f=>{f&&d.logAction(this.logger,d.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+f.toString())});let u=this.connectionManager;if(!u.activeState()){l(u.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||u.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:K.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&n.encodeModesToFlags(zo(this.channelOptions.modes)),this._attachResume&&n.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(n.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(n).catch(Qa)}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(u){switch(this.event){case"detached":o();break;case"attached":case"suspended":case"failed":l(u.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:K.DETACH,channel:this.name});this.sendMessage(n).catch(Qa)}async subscribe(...n){let[o,l]=Co.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,u]=Co.processListenerArgs(n);if(typeof l=="object"&&!u||(o=this.filteredSubscriptions)!=null&&o.has(u)){this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,l,u).forEach(f=>this.subscriptions.off(f));return}this.subscriptions.off(l,u)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new Se("Unable to sync to channel; not attached",4e4);default:}let n=this.connectionManager;if(!n.activeState())throw n.getError();let o=ke({action:K.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,(u,f)=>{u?l(u):o(f)})})}async sendPresence(n){let o=ke({action:K.PRESENCE,channel:this.name,presence:n});await this.sendMessage(o)}async sendState(n){let o=ke({action:K.OBJECT,channel:this.name,state:n});await this.sendMessage(o)}async processMessage(n){(n.action===K.ATTACHED||n.action===K.MESSAGE||n.action===K.PRESENCE||n.action===K.OBJECT||n.action===K.ANNOTATION)&&this.setChannelSerial(n.channelSerial);let o,l=!1;switch(n.action){case K.ATTACHED:{this.properties.attachSerial=n.channelSerial,this._mode=n.getMode(),this.params=n.params||{};let u=n.decodeModesFromFlags();this.modes=u&&Vo(u)||void 0;let f=n.hasFlag("RESUMED"),y=n.hasFlag("HAS_PRESENCE"),_=n.hasFlag("HAS_BACKLOG"),S=n.hasFlag("HAS_OBJECTS");if(this.state==="attached"){f||(this._presence&&this._presence.onAttached(y),this._object&&this._object.onAttached(S));let I=new lr(this.state,this.state,f,_,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,_,S);break}case K.DETACHED:{let u=n.error?x.fromValues(n.error):new x("Channel detached",90001,404);this.state==="detaching"?this.notifyState("detached",u):this.state==="attaching"?this.notifyState("suspended",u):(this.state==="attached"||this.state==="suspended")&&this.requestState("attaching",u);break}case K.SYNC:if(l=!0,o=this.syncChannelSerial=n.channelSerial,!n.presence)break;case K.PRESENCE:{if(!n.presence)break;$s(n);let u=this.channelOptions;if(this._presence){let f=await Promise.all(n.presence.map(y=>y.decode(u,this.logger)));this._presence.setPresence(f,l,o)}break}case K.OBJECT:case K.OBJECT_SYNC:{if(!this._object||!n.state)return;$s(n);let u=this.client.connection.connectionManager.getActiveTransportFormat(),f=n.state.map(y=>y.decode(this.client,u));n.action===K.OBJECT?this._object.handleObjectMessages(f):this._object.handleObjectSyncMessages(f,n.channelSerial);break}case K.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}$s(n);let u=n.messages,f=u[0],y=u[u.length-1];if(f.extras&&f.extras.delta&&f.extras.delta.from!==this._lastPayload.messageId){let S='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()",S),this._startDecodeFailureRecovery(new x(S,40018,400));break}let _=[];for(let S=0;S<u.length;S++){let{decoded:I,err:U}=await u[S].decodeWithErr(this._decodingContext,this.logger);if(_[S]=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(_);break}case K.ANNOTATION:{$s(n);let u=this.channelOptions;if(this._annotations){let f=await Promise.all((n.annotations||[]).map(y=>y.decode(u,this.logger)));this._annotations._processIncoming(f)}break}case K.ERROR:{let u=n.error;u&&u.code==80016?this.checkPendingState():this.notifyState("failed",x.fromValues(u));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,u,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,u,o),this._object&&this._object.actOnChannelState(n,y),n==="suspended"&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),o&&(this.errorReason=o);let _=new lr(this.state,n,l,f,o),S='Channel state for channel "'+this.name+'"',I=n+(o?"; reason: "+o:"");n==="failed"?d.logAction(this.logger,d.LOG_ERROR,S,I):d.logAction(this.logger,d.LOG_MAJOR,S,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,_),this.emit(n,_)}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=Yn(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,u){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 S=await $e.fromValues(T(k({},n),{action:o,version:l})).encode(this.channelOptions),I=ke({action:K.MESSAGE,channel:this.name,messages:[S],params:u?Kn(u):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 Xa(r){let n=r||{},{agent:o}=n;return N(n,["agent"])}var os=Np,Lp=class{constructor(r){this.channel=r,this.logger=r.logger,this.subscriptions=new de(this.logger)}async publish(r,n){let o=this.channel.name,l=Ja(r,n),u=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:K.ANNOTATION,channel:o,annotations:[u]});await this.channel.sendMessage(f)}async delete(r,n){n.action="annotation.delete",await this.publish(r,n)}async subscribe(...r){let n=os.processListenerArgs(r),o=n[0],l=n[1],u=this.channel;if(u.state==="failed")throw x.fromValues(u.invalidStateError());if(this.subscriptions.on(o,l),this.channel.channelOptions.attachOnSubscribe!==!1&&await u.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=os.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 Gs.prototype.get.call(this,r,n)}},ur=Lp,mt=class Gn extends Ep{constructor(n){var o,l;if(!Gn._MsgPack)throw new Error("Expected DefaultRest._MsgPack to have been set");super(J.objectifyOptions(n,!0,"Rest",d.defaultLogger,T(k({},$a),{Crypto:(o=Gn.Crypto)!=null?o:void 0,MsgPack:(l=Gn._MsgPack)!=null?l:void 0,Annotations:{Annotation:It,WireAnnotation:Pt,RealtimeAnnotations:ur,RestAnnotations:Gs}})))}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=Ha,mt.PresenceMessage=Ga,mt.Annotation=za,mt._MsgPack=null,mt._Http=tr;var Za=mt,Dp=class extends de{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 u=[];if(r==="all")u=l.splice(0);else{let f=l[0];if(f){let y=f.message.msgSerial,_=r.serial+r.count;_>y&&(u=l.splice(0,_-y))}}for(let f=0;f<u.length;f++){let y=u[f],_=o?.[f];y.callback(n,_)}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")}},ec=Dp,tc=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"&&[K.MESSAGE,K.PRESENCE,K.ANNOTATION,K.OBJECT].includes(o)}},Up=class extends de{constructor(r){super(r.logger),this.transport=r,this.messageQueue=new ec(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; "+ar(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()})}},jp=Up,qp=class{constructor(r,n,o,l){this.previous=r,this.current=n,o&&(this.retryIn=o),l&&(this.reason=l)}},Ws=qp,at={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},Bp={disconnected:()=>x.fromValues({statusCode:400,code:at.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>x.fromValues({statusCode:400,code:at.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>x.fromValues({statusCode:400,code:at.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>x.fromValues({statusCode:400,code:at.CLOSING,message:"Connection closing"}),closed:()=>x.fromValues({statusCode:400,code:at.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>x.fromValues({statusCode:500,code:at.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>x.fromValues({statusCode:500,code:at.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})};function $p(r){return!r.statusCode||!r.code||r.statusCode>=500?!0:Object.values(at).includes(r.code)}var yt=Bp,Hp=ke({action:K.CLOSE}),Gp=ke({action:K.DISCONNECT}),Fp=class extends de{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+": "+ar(r,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),r.action){case K.HEARTBEAT:d.logActionNoStrip(this.logger,d.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",r.id);break;case K.CONNECTED:this.onConnect(r),this.emit("connected",r.error,r.connectionId,r.connectionDetails,r);break;case K.CLOSED:this.onClose(r);break;case K.DISCONNECTED:this.onDisconnect(r);break;case K.ACK:this.emit("ack",r.msgSerial,r.count,r.res);break;case K.NACK:this.emit("nack",r.msgSerial,r.count,r.error);break;case K.SYNC:this.connectionManager.onChannelMessage(r,this);break;case K.ACTIVATE:break;case K.AUTH:Te(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 K.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(Hp)}requestDisconnect(){d.logAction(this.logger,d.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(Gp)}ping(r){let n={action:K.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,u){let f=new r(n,o,l),y,_=function(I){clearTimeout(y),u({event:this.event,error:I})},S=n.options.timeouts.realtimeRequestTimeout;return y=setTimeout(()=>{f.off(["preconnect","disconnected","failed"]),f.dispose(),_.call({event:"disconnected"},new x("Timeout waiting for transport to indicate itself viable",5e4,500))},S),f.on(["failed","disconnected"],_),f.on("preconnect",function(){d.logAction(n.logger,d.LOG_MINOR,"Transport.tryConnect()","viable transport "+f),clearTimeout(y),f.off(["failed","disconnected"],_),u(null,f)}),f.connect(),f}static isAvailable(){throw new x("isAvailable not implemented for transport",5e4,500)}},Mt=Fp,ye;(r=>{r.WebSocket="web_socket",r.Comet="comet",r.XhrPolling="xhr_polling"})(ye||(ye={}));var Wp=typeof global<"u"?global:typeof window<"u"?window:self,hr=()=>{var r;return typeof L.WebStorage<"u"&&((r=L.WebStorage)==null?void 0:r.localSupported)},as=()=>{var r;return typeof L.WebStorage<"u"&&((r=L.WebStorage)==null?void 0:r.sessionSupported)},sc=function(){},dr="ably-transport-preference";function fr(r){try{return JSON.parse(r)}catch{return null}}var Vp=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?es(r):{},o=this.options;switch(this.mode){case"resume":n.resume=this.connectionKey;break;case"recover":{let l=fr(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=J.protocolVersion,n.agent=Xn(this.options),o.transportParams!==void 0&&Y(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}},zp=class Id extends de{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,u=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:u,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 ec(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=No(o.transports||J.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=J.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||J.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&&(as()&&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=k(k({},L.Transports.bundledImplementations),n);[ye.WebSocket,...L.Transports.order].forEach(u=>{let f=l[u];f&&f.isAvailable()&&(o.supportedTransports[u]=f)})}initTransports(){Id.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(n,o){return new Vp(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 u=this.options.recover,f=this.getSessionRecoverData(),y=this.sessionRecoveryName();if(f&&typeof u=="function"){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+y+")"),u(f,_=>{_?(this.options.recover=f.recoveryKey,l("recover")):l("clean")});return}l("clean")})(l=>{let u=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=fr(this.options.recover);f&&(this.msgSerial=f.msgSerial)}else d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+u.toString());n(u)})}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,(u,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(u){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+o+" "+u.event+", err: "+u.error.toString()),We.isTokenErr(u.error)&&!(this.errorReason&&We.isTokenErr(this.errorReason))?(this.errorReason=u.error,Te(this.realtime.auth._forceNewToken(null,null),_=>{if(_){this.actOnErrorFromAuthorize(_);return}this.tryATransport(n,o,l)})):u.event==="failed"?(this.notifyState({state:"failed",error:u.error}),l(!0)):u.event==="disconnected"&&($p(u.error)?l(!1):(this.notifyState({state:this.states.connecting.failState,error:u.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,_)=>{this.activateTransport(f,n,y,_),l==="recover"&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});let u=this;n.on(["disconnected","closed","failed"],function(f){u.deactivateTransport(n,this.event,f)}),this.emit("transport.pending",n)}activateTransport(n,o,l,u){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),u&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(u)),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 _=this.activeProtocol;this.activeProtocol=new jp(o),this.host=o.params.host;let S=u.connectionKey;if(S&&this.connectionKey!=S&&this.setConnection(l,u,!!n),this.onConnectionDetailsUpdate(u,o),L.Config.nextTick(()=>{o.on("connected",(I,U,D)=>{this.onConnectionDetailsUpdate(D,o),this.emit("update",new Ws(y,y,null,I))})}),f.state===this.states.connected.state?n&&(this.errorReason=this.realtime.connection.errorReason=n,this.emit("update",new Ws(y,y,null,n))):(this.notifyState({state:"connected",error:n}),this.errorReason=this.realtime.connection.errorReason=n||null),this.emit("transport.active",o),_)if(_.messageQueue.count()>0&&d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+_.transport.shortName+", new one is "+o.shortName+") finishing with "+_.messageQueue.count()+" messages still pending"),_.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 _.finish();return!0}deactivateTransport(n,o,l){let u=this.activeProtocol,f=u&&u.getTransport()===n,y=n===this.pendingTransport,_=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":"")+(_?"":"; 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(u.getPendingMessages()),u.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",n),f&&_||f&&o==="failed"||o==="closed"||u===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 S=o==="failed"&&We.isTokenErr(l)?"disconnected":o;this.notifyState({state:S,error:l});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(n,o,l){let u=this.connectionId;(u&&u!==n||!u&&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(as()){let n=this.createRecoveryKey();n&&this.setSessionRecoverData({recoveryKey:n,disconnectedAt:Date.now(),location:Wp.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=Se.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 u=this.state=this.states[n.current];n.reason&&(this.errorReason=n.reason,this.realtime.connection.errorReason=n.reason),(u.terminal||u.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&&Te(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 u=n.state,f=u==="disconnected"&&(this.state===this.states.connected||n.retryImmediately||this.state===this.states.connecting&&n.error&&We.isTokenErr(n.error)&&!(this.errorReason&&We.isTokenErr(this.errorReason)));if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+u+(f?"; will retry connection immediately":"")),u==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(n.state),(u==="suspended"||u==="connected")&&(this.disconnectedRetryCount=0),this.state.terminal))return;let y=this.states[n.state],_=y.retryDelay;y.state==="disconnected"&&(this.disconnectedRetryCount++,_=Yn(y.retryDelay,this.disconnectedRetryCount));let S=new Ws(this.state.state,y.state,_,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(u==="disconnected"||u==="suspended")&&this.startRetryTimer(_);(u==="disconnected"&&!f||u==="suspended"||y.terminal)&&L.Config.nextTick(()=>{this.disconnectAllTransports()}),u=="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(S),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(u,S.reason),this.failQueuedMessages(S.reason))}requestState(n){var o,l;let u=n.state;if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+u+"; current state: "+this.state.state),u==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(u),u=="connecting"&&this.state.state=="connected")||u=="closing"&&this.state.state=="closed")return;let f=this.states[u],y=new Ws(this.state.state,f.state,null,n.error||((l=(o=yt)[f.state])==null?void 0:l.call(o)));this.enactStateChange(y),u=="connecting"&&L.Config.nextTick(()=>{this.startConnect()}),u=="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(u=>{if(u.mode==="recover"&&u.options.recover){let f=fr(u.options.recover);f&&this.realtime.channels.recoverChannels(f.channelSerials)}o===this.connectCounter&&this.connectImpl(u,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 u=f=>{o===this.connectCounter&&(f?this.actOnErrorFromAuthorize(f):l())};this.errorReason&&We.isTokenErr(this.errorReason)?Te(n._forceNewToken(null,null),u):Te(n._ensureValidAuthCredentials(!1),u)}}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 u=this.getTransportPreference();u&&u===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(sc),u&&u===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,u,f){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",n);let y=D=>{this.notifyState({state:this.states.connecting.failState,error:D})},_=this.domains.slice(),S=(D,F)=>{if(u===this.connectCounter){if(!f()){F&&F.dispose();return}!F&&!D&&U()}},I=_.shift();if(!I){y(new x("Unable to connect (no available host)",80003,404));return}o.host=I;let U=()=>{if(!_.length){y(new x("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!this.realtime.http.checkConnectivity){y(new Se("Internal error: Http.checkConnectivity not set",null,500));return}Te(this.realtime.http.checkConnectivity(),(D,F)=>{if(u===this.connectCounter&&f()){if(D){y(D);return}if(!F){y(new x("Unable to connect (network unreachable)",80003,404));return}o.host=zn(_),this.tryATransport(o,n,S)}})};if(this.forceFallbackHost&&_.length){this.forceFallbackHost=!1,U();return}this.tryATransport(o,n,S)}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 u=(l=this.activeProtocol)==null?void 0:l.getTransport();u&&u.onAuthUpdated&&u.onAuthUpdated(n);let f=ke({action:K.AUTH,auth:{accessToken:n.token}});this.send(f);let y=()=>{this.off(_),o(null,n)},_=S=>{S.current==="failed"&&(this.off(y),this.off(_),o(S.reason||this.getStateError()))};this.once("connectiondetails",y),this.on("connectionstate",_);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 u=f=>{switch(f.current){case"connected":this.off(u),o(null,n);break;case"failed":case"closed":case"suspended":this.off(u),o(f.reason||this.getStateError());break;default:break}};this.on("connectionstate",u),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||sc;let u=this.state;if(u.sendEvents){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new tc(n,l));return}if(!(o&&u.queueEvents)){let y="rejecting event, queueEvent was "+o+", state was "+u.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; "+ar(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 tc(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(),u=Go();return Xo(new Promise(f=>{let y=_=>{_===u&&(o.off("heartbeat",y),f(Date.now()-l))};o.on("heartbeat",y),o.ping(u)}),this.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")}abort(n){this.activeProtocol.getTransport().fail(n)}getTransportPreference(){var n,o;return this.transportPreference||hr()&&((o=(n=L.WebStorage)==null?void 0:n.get)==null?void 0:o.call(n,dr))}persistTransportPreference(n){var o,l;this.transportPreference=n.shortName,hr()&&((l=(o=L.WebStorage)==null?void 0:o.set)==null||l.call(o,dr,n.shortName))}unpersistTransportPreference(){var n,o;this.transportPreference=null,hr()&&((o=(n=L.WebStorage)==null?void 0:n.remove)==null||o.call(n,dr))}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===ns.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 u=n.connectionStateTtl;u&&(this.connectionStateTtl=u),this.maxIdleInterval=n.maxIdleInterval,this.emit("connectiondetails",n)}checkWsConnectivity(){let n=this.options.wsConnectivityCheckUrl||J.wsConnectivityCheckUrl,o=new L.Config.WebSocket(n);return new Promise((l,u)=>{let f=!1;o.onopen=()=>{f||(f=!0,l(),o.close())},o.onclose=o.onerror=()=>{f||(f=!0,u())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var n,o;return as()&&((o=(n=L.WebStorage)==null?void 0:n.getSession)==null?void 0:o.call(n,this.sessionRecoveryName()))}setSessionRecoverData(n){var o,l;return as()&&((l=(o=L.WebStorage)==null?void 0:o.setSession)==null?void 0:l.call(o,this.sessionRecoveryName(),n))}clearSessionRecoverData(){var n,o;return as()&&((o=(n=L.WebStorage)==null?void 0:n.removeSession)==null?void 0:o.call(n,this.sessionRecoveryName()))}},nc=zp,Kp=class extends de{constructor(r,n){super(r.logger),this.whenState=o=>de.prototype.whenState.call(this,o,this.state),this.ably=r,this.connectionManager=new nc(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()}},Jp=Kp,rc=class Md extends Ea{constructor(n){var o,l,u,f;if(super(J.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=Md.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=(l=(o=this.options.plugins)==null?void 0:o.RealtimePresence)!=null?l:null,this._liveObjectsPlugin=(f=(u=this.options.plugins)==null?void 0:u.LiveObjects)!=null?f:null,this.connection=new Jp(this,this.options),this._channels=new Qp(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()}};rc.EventEmitter=de;var Yp=rc,Qp=class extends de{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 Ds(this.all,!0)){let o=this.all[n];o.properties.channelSerial&&(r[n]=o.properties.channelSerial)}return r}recoverChannels(r){for(let n of Ds(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"],u=o[r];for(let f in this.all){let y=this.all[f];l.includes(y.state)&&y.notifyState(u,n)}}get(r,n){r=String(r);let o=this.all[r];if(!o)o=this.all[r]=new os(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=js(n.filter),u=Yo(r);r=`[filter=${l}${u.qualifierParam}]${u.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]}},Xp=Yp;function Zp(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 pr=class extends de{constructor(r,n,o=Zp){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 u=n[l];u.clientId==r&&u.action!="absent"&&o.push(u)}return o}list(r){let n=this.map,o=r&&r.clientId,l=r&&r.connectionId,u=[];for(let f in n){let y=n[f];y.action!=="absent"&&(o&&o!=y.clientId||l&&l!=y.connectionId||u.push(y))}return u}put(r){(r.action==="enter"||r.action==="update")&&(r=Ve.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=Ve.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=es(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(jo(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 eg(r){return r.channel.client.auth.clientId}function gr(r){let n=r.channel.client,o=n.auth.clientId;return(!o||o==="*")&&n.connection.state==="connected"}var tg=class extends de{constructor(r){super(r.logger),this.channel=r,this.syncComplete=!1,this.members=new pr(this,n=>n.clientId+":"+n.connectionId),this._myMembers=new pr(this,n=>n.clientId),this.subscriptions=new de(this.logger),this.pendingPresence=[]}async enter(r){if(gr(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(gr(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 u=this.channel;if(!u.connectionManager.activeState())throw u.connectionManager.getError();d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence."+l+"Client()","channel = "+u.name+", id = "+r+", client = "+(n||"(implicit) "+eg(this)));let f=Ve.fromData(o);f.action=l,r&&(f.id=r),n&&(f.clientId=n);let y=await f.encode(u.channelOptions);switch(u.state){case"attached":return u.sendPresence([y]);case"initialized":case"detached":u.attach();case"attaching":return new Promise((_,S)=>{this.pendingPresence.push({presence:y,callback:I=>I?S(I):_()})});default:{let _=new Se("Unable to "+l+" presence channel while in "+u.state+" state",90001);throw _.code=90001,_}}}async leave(r){if(gr(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=Ve.fromData(n);l.action="leave",r&&(l.clientId=r);let u=await l.encode(o.channelOptions);switch(o.state){case"attached":return o.sendPresence([u]);case"attaching":return new Promise((f,y)=>{this.pendingPresence.push({presence:u,callback:_=>_?y(_):f()})});case"initialized":case"failed":throw new Se("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(u){return r?u.list(r):u.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,u,f=this.members,y=this._myMembers,_=[],S=this.channel.connectionManager.connectionId;n&&(this.members.startSync(),o&&(u=o.match(/^[\w-]+:(.*)$/))&&(l=u[1]));for(let I of r)switch(I.action){case"leave":f.remove(I)&&_.push(I),I.connectionId===S&&!I.isSynthesized()&&y.remove(I);break;case"enter":case"present":case"update":f.put(I)&&_.push(I),I.connectionId===S&&y.put(I);break}n&&!l&&(f.endSync(),this.channel.syncChannelSerial=null);for(let I=0;I<_.length;I++){let U=_[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=[],u=ca.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),u.push(y.callback)}this.channel.sendPresence(l).then(()=>u()).catch(f=>u(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 u=l.connectionId===n?l.id:void 0;this._enterOrUpdateClient(u,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 _=new lr(this.channel.state,this.channel.state,!0,!1,y);this.channel.emit("update",_)})}}_synthesizeLeaves(r){let n=this.subscriptions;r.forEach(function(o){let l=Ve.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=os.processListenerArgs(r),o=n[0],l=n[1],u=this.channel;if(u.state==="failed")throw x.fromValues(u.invalidStateError());this.subscriptions.on(o,l),u.channelOptions.attachOnSubscribe!==!1&&await u.attach()}unsubscribe(...r){let n=os.processListenerArgs(r),o=n[0],l=n[1];this.subscriptions.off(o,l)}},sg=tg,ng=ye.WebSocket;function rg(r){return!!r.on}var ig=class extends Mt{constructor(r,n,o){super(r,n,o),this.shortName=ng,o.heartbeats=L.Config.useProtocolHeartbeats,this.wsHost=o.host}static isAvailable(){return!!L.Config.WebSocket}createWebSocket(r,n){return this.uri=r+ts(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,u=(o.tls?"wss://":"ws://")+this.wsHost+":"+J.getPort(o)+"/";d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.connect()","uri: "+u),Te(this.auth.getAuthParams(),function(f,y){if(r.isDisposed)return;let _="";for(let I in y)_+=" "+I+": "+y[I]+";";if(d.logAction(r.logger,d.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+_+" err: "+f),f){r.disconnect(f);return}let S=n.getConnectParams(y);try{let I=r.wsConnection=r.createWebSocket(u,S);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)},rg(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(Ap(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(Rp(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,u=new x(l,80003,400);d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onWsClose()",l),this.finish("disconnected",u)}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()}))}},ic=ig,og=class{static subscribeFilter(r,n,o){let l=u=>{var f,y,_,S,I,U;let D={name:u.name,refTimeserial:(y=(f=u.extras)==null?void 0:f.ref)==null?void 0:y.timeserial,refType:(S=(_=u.extras)==null?void 0:_.ref)==null?void 0:S.type,isRef:!!((U=(I=u.extras)==null?void 0:I.ref)!=null&&U.timeserial),clientId:u.clientId};Object.entries(n).find(([F,C])=>C!==void 0?D[F]!==C:!1)||o(u)};this.addFilteredSubscription(r,n,o,l),r.subscriptions.on(l)}static addFilteredSubscription(r,n,o,l){var u;if(r.filteredSubscriptions||(r.filteredSubscriptions=new Map),r.filteredSubscriptions.has(o)){let f=r.filteredSubscriptions.get(o);f.set(n,((u=f?.get(n))==null?void 0:u.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 _;let S=y.get(n);return y.delete(n),y.size===0&&((_=r.filteredSubscriptions)==null||_.delete(f)),S}).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,_)=>y.concat(..._),[]);return r.filteredSubscriptions.delete(o),f}let u=l.get(n);return l.delete(n),u||[]}},Re=class Eo extends Xp{constructor(n){var o;let l=Eo._MsgPack;if(!l)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(J.objectifyOptions(n,!0,"Realtime",d.defaultLogger,T(k({},$a),{Crypto:(o=Eo.Crypto)!=null?o:void 0,MsgPack:l,RealtimePresence:{RealtimePresence:sg,PresenceMessage:Ve,WirePresenceMessage:rs},Annotations:{Annotation:It,WireAnnotation:Pt,RealtimeAnnotations:ur,RestAnnotations:Gs},WebSocketTransport:ic,MessageInteractions:og})))}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}};Re.Utils=Zt,Re.ConnectionManager=nc,Re.ProtocolMessage=Ip,Re._Crypto=null,Re.Message=Ha,Re.PresenceMessage=Ga,Re.Annotation=za,Re._MsgPack=null,Re._Http=tr,Re._PresenceMap=pr,Re._MessageEncoding=Bs;var oc=Re,ac=Q(q("crypto")),ag=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 ac.default.createHash("SHA256").update(n).digest()}hmacSha256(r,n){let o=this.toBuffer(r),l=this.toBuffer(n);return ac.default.createHmac("SHA256",l).update(o).digest()}},cc=new ag,mr=Q(q("crypto")),cg=Q(q("util")),lg=function(r){var n="aes",o=256,l="cbc",u=16;async function f(j){return cg.default.promisify(mr.default.randomBytes)(j)}function y(j){return j+u&-u}function _(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 S(j){return j.replace("_","/").replace("-","+")}function I(j,G){var z=Buffer.alloc(j);return z.fill(G),z}for(var U=[I(16,16)],D=1;D<=16;D++)U.push(I(D,D));class F{constructor(G,z,W,ee){this.algorithm=G,this.keyLength=z,this.mode=W,this.key=ee,this.iv=null}}function C(j){return!!(j.algorithm&&j.key&&j.keyLength&&j.mode)}class R{static getDefaultParams(G){var z;if(!G.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof G.key=="string"?z=r.base64Decode(S(G.key)):G.key instanceof ArrayBuffer?z=Buffer.from(G.key):z=G.key;var W=G.algorithm||n,ee=z.length*8,Oe=G.mode||l,ve=new F(W,ee,Oe,z);if(G.keyLength&&G.keyLength!==ve.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+G.keyLength+" was specified, but the key actually has length "+ve.keyLength);return _(ve),ve}static async generateRandomKey(G){try{return f((G||o)/8)}catch(z){throw new x("Failed to generate random key: "+z.message,500,5e4,z)}}static getCipher(G,z){var W,ee=C(G)?G:this.getDefaultParams(G);return{cipherParams:ee,cipher:new P(ee,(W=G.iv)!=null?W:null,z)}}}R.CipherParams=F;class P{constructor(G,z,W){this.logger=W,this.encryptCipher=null,this.algorithm=G.algorithm+"-"+String(G.keyLength)+"-"+G.mode,this.key=G.key,this.iv=z}async encrypt(G){d.logAction(this.logger,d.LOG_MICRO,"CBCCipher.encrypt()","");let z=await this.getIv();this.encryptCipher||(this.encryptCipher=mr.default.createCipheriv(this.algorithm,this.key,z));var W=r.toBuffer(G),ee=W.length,Oe=y(ee),ve=this.encryptCipher.update(Buffer.concat([W,U[Oe-ee]])),ze=Buffer.concat([z,ve]);return ze}async decrypt(G){var z=mr.default.createDecipheriv(this.algorithm,this.key,G.slice(0,u)),W=z.update(G.slice(u)),ee=z.final();return ee&&ee.length&&(W=Buffer.concat([W,ee])),W}async getIv(){if(this.iv){var G=this.iv;return this.iv=null,G}var z=await f(u);return this.encryptCipher?this.encryptCipher.update(z):z}}return R},lc=Q(Hn()),ug=Q(q("http")),hg=Q(q("https")),uc=[],cs,dg=(cs=class{constructor(r){this.agent=null,this.supportsAuthHeaders=!0,this.supportsLinkHeaders=!0,this.checkConnectivity=async()=>{var n,o,l,u,f;if((n=this.client)!=null&&n.options.disableConnectivityCheck)return!0;let y=((o=this.client)==null?void 0:o.options.connectivityCheckUrl)||J.connectivityCheckUrl,_=(u=(l=this.client)==null?void 0:l.options.connectivityCheckParams)!=null?u:null,S=!((f=this.client)!=null&&f.options.connectivityCheckUrl),{error:I,statusCode:U,body:D}=await this.doUri(le.Get,y,null,null,_);return!I&&!S?If(U):!I&&D?.toString().trim()==="yes"},this.client=r??null}async doUri(r,n,o,l,u){var f;let y=this.client&&this.client.options.restAgentOptions||J.restAgentOptions,_={headers:o||void 0,responseType:"buffer"};if(!this.agent){let S=(f=uc.find(I=>Qn(y,I.options)))==null?void 0:f.agents;S?this.agent=S:(this.agent={http:new ug.default.Agent(y),https:new hg.default.Agent(y)},uc.push({options:y,agents:this.agent}))}l&&(_.body=l),u&&(_.searchParams=u),_.agent=this.agent,_.url=n,_.timeout={request:(this.client&&this.client.options.timeouts||J.TIMEOUTS).httpRequestTimeout},_.retry={limit:0};try{let S=await lc.default[r](_);return this._handler(null,S,S.body)}catch(S){return S instanceof lc.default.HTTPError?this._handler(null,S.response,S.response.body):this._handler(S)}}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 u=n.statusCode,f=n.headers;if(u>=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:ss("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: "+u+" body was: "+L.Config.inspect(o),Number(f["x-ably-errorcode"]),u),body:o,headers:f,unpacked:!0,statusCode:u}}return{error:null,body:o,headers:f,unpacked:!1,statusCode:u}}},cs.methods=[le.Get,le.Delete,le.Post,le.Put,le.Patch],cs.methodsWithoutBody=[le.Get,le.Delete],cs.methodsWithBody=[le.Post,le.Put,le.Patch],cs),fg=dg,pg=Q(q("crypto")),gg=Q(dn()),yr=Q(q("util")),mg={agent:"nodejs/"+process.versions.node,logTimestamps:!0,userAgent:null,binaryType:"nodebuffer",WebSocket:gg.default,useProtocolHeartbeats:!1,supportsBinary:!0,preferBinary:!0,nextTick:process.nextTick,inspect:yr.default.inspect,stringByteSize:Buffer.byteLength,inherits:yr.default.inherits,addEventListener:null,getRandomArrayBuffer:async function(r){return yr.default.promisify(pg.default.randomBytes)(r)}},yg=mg,hc=(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))(hc||{}),ct=hc;function _g(r){let n=[80015,80017,80030];return r.code?We.isTokenErr(r)?!1:n.includes(r.code)?!0:r.code>=4e4&&r.code<5e4:!1}function _r(r){return _g(r)?[ke({action:K.ERROR,error:r})]:[ke({action:K.DISCONNECTED,error:r})]}var bg=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=J.getPort(n),u=n.tls?"https://":"http://";this.baseUri=u+o+":"+l+"/comet/";let f=this.baseUri+"connect";d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","uri: "+f),Te(this.auth.getAuthParams(),(y,_)=>{if(y){this.disconnect(y);return}if(this.isDisposed)return;this.authParams=_;let S=this.params.getConnectParams(_);"stream"in S&&(this.stream=S.stream),d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","connectParams:"+ts(S));let I=!1,U=this.recvRequest=this.createRequest(f,null,S,null,this.stream?ct.REQ_RECV_STREAM:ct.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(_r(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,ct.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),ct.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(_r(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?ct.REQ_RECV_STREAM:ct.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(_r(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(or(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}},dc=bg,fc=Q(q("http")),pc=Q(q("https")),vg=Q(q("url")),wg=Q(q("util")),Cg=function(){},Eg=ye.Comet,kg=class extends dc{constructor(r,n,o){super(r,n,o),this.httpAgent=null,this.httpsAgent=null,this.pendingRequests=0,this.shortName=Eg}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?pc.default:fc.default).Agent({keepAlive:!0})),o}dispose(){var r=this;this.onceNoPending(function(){r.httpAgent&&r.httpAgent.destroy(),r.httpsAgent&&r.httpsAgent.destroy()}),dc.prototype.dispose.call(this)}request(r,n,o,l,u){var f=this.createRequest(r,n,o,l);return f.once("complete",u),f.exec(),f}createRequest(r,n,o,l,u){return new Og(r,n,o,l,u,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)}},Og=class extends de{constructor(r,n,o,l,u,f,y,_){super(_.logger),typeof r=="string"&&(r=vg.default.parse(r));var S=r.protocol=="https:";this.client=S?pc.default:fc.default,this.requestMode=u,this.timeouts=y,this.transport=_,this.requestComplete=!1,this.req=this.res=null;var I="GET",U=f=="msgpack"?"application/x-msgpack":"application/json";n=n?Y({},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+ts(o),method:I,headers:n};_&&(D.agent=_.getAgent(S))}exec(){var r=this.requestMode==ct.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(u){u=new Se("Request error: "+u.message,null,400),clearTimeout(o),n.timer=null,n.complete(u)}),l.on("response",function(u){clearTimeout(o),n.timer=null;var f=u.statusCode;if(f==ns.NoContent){u.resume(),n.complete();return}u.on("error",n.onResError=function(y){y=new Se("Response error: "+y.message,null,400),n.complete(y)}),n.res=u,n.requestMode==ct.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 u="Malformed response body from server: "+f.message;d.logAction(n.logger,d.LOG_ERROR,"NodeCometTransport.Request.readStream()",u),n.complete(new Se(u,null,400));return}n.emit("data",l)}r.on("data",this.ondata=function(l){var u=String(l).split(`
|
|
45
|
-
`),f=n.chunks;u.length>1&&f.length>0&&(f.push(u.shift()),n.chunks=[],o(f.join("")));var y=u.pop();y.length&&n.chunks.push(y),u.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),u=r.statusCode;try{l=JSON.parse(String(l))}catch(_){var f="Malformed response body from server: "+_.message;d.logAction(o.logger,d.LOG_ERROR,"NodeCometTransport.Request.readFully()",f),o.complete(new Se(f,null,400));return}if(u<400||Array.isArray(l)){o.complete(null,l);return}var y=l.error&&x.fromValues(l.error);y||(y=new Se("Error response received from server: "+u+", body was: "+wg.default.inspect(l),null,u)),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",Cg),n.abort(),this.req=null),this.complete({statusCode:400,code:80003,message:"Cancelled"})}},Sg=kg,Tg={order:[ye.Comet],bundledImplementations:{[ye.WebSocket]:ic,[ye.Comet]:Sg}},Ag={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}},Rg=Ag,Pg=of(),gc=lg(cc);L.Crypto=gc,L.BufferUtils=cc,L.Http=fg,L.Config=yg,L.Transports=Tg,L.WebStorage=null;for(let r of[Za,oc])r.Crypto=gc,r._MsgPack=Pg;if(d.initLogHandlers(),L.Defaults=Rf(Rg),L.Config.agent&&(L.Defaults.agent+=" "+L.Config.agent),i.exports={ErrorInfo:x,Rest:Za,Realtime:oc,msgpack:null,makeProtocolMessageFromDeserialized:Pp},typeof i.exports=="object"&&typeof t=="object"){var Ig=(r,n,o,l)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of Object.getOwnPropertyNames(n))!Object.prototype.hasOwnProperty.call(r,u)&&u!==o&&Object.defineProperty(r,u,{get:()=>n[u],enumerable:!(l=Object.getOwnPropertyDescriptor(n,u))||l.enumerable});return r};i.exports=Ig(i.exports,t)}return i.exports})});var Pc=br(Rc(),1),{program:us,createCommand:Dw,createArgument:Uw,createOption:jw,CommanderError:qw,InvalidArgumentError:Bw,InvalidOptionArgumentError:$w,Command:Hw,Argument:Gw,Option:Fw,Help:Ww}=Pc.default;var Yd=br(Uc(),1);import{resolve as Jd}from"path";import{existsSync as Tw}from"fs";function mm(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 h=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",v=s.streamProgress??process.env.STREAM_PROGRESS!=="false",w=s.conversationOnly??process.env.CONVERSATION_ONLY==="true",E=s.autoCommit??process.env.AUTO_COMMIT==="true",O=s.autoPush??process.env.AUTO_PUSH==="true",A=s.autoSchemaMigration??process.env.AUTO_SCHEMA_MIGRATION!=="false",k=s.idleTimeoutMinutes??(process.env.IDLE_TIMEOUT_MINUTES?parseInt(process.env.IDLE_TIMEOUT_MINUTES,10):0),T=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:h,sseEnabled:p,clientRequestTimeoutMs:c,workingDirectory:g,useAgentSdk:m,streamProgress:v,conversationOnly:w,autoCommit:E,autoPush:O,autoSchemaMigration:A,idleTimeoutMinutes:k,healthPort:T}}function jc(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:mm(s),sources:e}}function we(s){switch(s){case"cli":return"[cli]";case"env":return"[env]";case"default":return"[default]"}}var Js=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(),h;try{let p=JSON.parse(c);h=p.error||p.message||c}catch{h=c}throw new Error(`API error (${a.status}): ${h}`)}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})})}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){return this.request(`/api/client-requests/${e}/analysis`,{method:"POST",body:JSON.stringify({monitorId:t,analysis:i,processingTimeMs:a})})}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,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 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){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})})}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 Ys}from"child_process";import{existsSync as qc,writeFileSync as Bc,unlinkSync as $c}from"fs";import{homedir as ym,tmpdir as Hc}from"os";import{join as Ur}from"path";function Qs(){let s=[Ur(ym(),".claude","local","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude"];for(let e of s)if(qc(e))return e;return"claude"}var _e=null;function _m(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
|
-
`)}async function Gc(s,e){let t=_m(s);return
|
|
47
|
-
`)}function vm(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 Wc(s,e,t={}){let i=bm(s),a=t.verbose??!0;return a&&(console.log("[Claude] Starting analysis..."),console.log("[Claude] Prompt length:",i.length,"characters")),
|
|
44
|
+
`;return y.mac=y.mac||Nf(G,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 "+qs(r.token)}}}_saveBasicOptions(r){this.method="basic",this.key=r.key,this.basicKey=qs(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=ca.create(this.logger))).createPromise();if(this.currentTokenRequestId!==null&&!r)return o;let l=this.currentTokenRequestId=jf(),u,f=null;try{u=await this.requestToken(this.tokenParams,this.authOptions)}catch(_){f=_}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=u),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)}},Ke=qf;function er(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?"?":"")+er(n)}function Bf(r,n,o,l,u){r.error?d.logActionNoStrip(u,d.LOG_MICRO,"Http."+n+"()","Received Error; "+Tt(o,l)+"; Error: "+ne(r.error)):d.logActionNoStrip(u,d.LOG_MICRO,"Http."+n+"()","Received; "+Tt(o,l)+"; Headers: "+er(r.headers)+"; StatusCode: "+r.statusCode+"; Body"+(L.BufferUtils.isBuffer(r.body)?" (Base64): "+L.BufferUtils.base64Encode(r.body):": "+r.body))}function $f(r,n,o,l,u){u.shouldLog(d.LOG_MICRO)&&d.logActionNoStrip(u,d.LOG_MICRO,"Http."+r+"()","Sending; "+Tt(n,l)+"; Body"+(L.BufferUtils.isBuffer(o)?" (Base64): "+L.BufferUtils.base64Encode(o):": "+o))}var tr=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,u){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},_=f._currentFallback;if(_)if(_.validUntil>Date.now()){let D=await this.doUri(r,y(_.host),o,l,u);return D.error&&this.platformHttp.shouldFallback(D.error)?(f._currentFallback=null,this.do(r,n,o,l,u)):D}else f._currentFallback=null;let S=this._getHosts(f);if(S.length===1)return this.doUri(r,y(S[0]),o,l,u);let I=null,U=async(D,G)=>{let C=D.shift();I=I??new Date;let R=await this.doUri(r,y(C),o,l,u);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):(G&&(f._currentFallback={host:C,validUntil:Date.now()+f.options.timeouts.fallbackRetryTimeout}),R)};return U(S)}catch(f){return{error:new x(`Unexpected error in Http.do: ${ne(f)}`,500,5e4)}}}async doUri(r,n,o,l,u){try{$f(r,n,l,u,this.logger);let f=await this.platformHttp.doUri(r,n,o,l,u);return this.logger.shouldLog(d.LOG_MICRO)&&Bf(f,r,n,u,this.logger),f}catch(f){return{error:new x(`Unexpected error in Http.doUri: ${ne(f)}`,500,5e4)}}}};function Hf(r,n,o,l){try{o.apply(n,l)}catch(u){d.logAction(r,d.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+u+"; stack = "+(u&&u.stack))}}function sr(r,n,o){let l,u,f;for(let y=0;y<r.length;y++)if(l=r[y],o&&(l=l[o]),Array.isArray(l)){for(;(u=l.indexOf(n))!==-1;)l.splice(u,1);o&&l.length===0&&delete r[y][o]}else if(St(l))for(f in l)Object.prototype.hasOwnProperty.call(l,f)&&Array.isArray(l[f])&&sr([l],n,f)}var Gf=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(ze(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||ze(r[0])&&ze(r[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}let[n,o]=r,l=null,u=null;if(r.length===1||!o)typeof n=="function"?l=n:u=n;else{if(typeof o!="function")throw new Error("EventEmitter.off(): invalid arguments:"+L.Config.inspect(r));[u,l]=[n,o]}if(l&&ze(u)){sr([this.any,this.events,this.anyOnce,this.eventsOnce],l);return}if(Array.isArray(u)){u.forEach(f=>{this.off(f,l)});return}if(typeof u!="string")throw new Error("EventEmitter.off(): invalid arguments:"+L.Config.inspect(r));l?sr([this.events,this.eventsOnce],l,u):(delete this.events[u],delete this.eventsOnce[u])}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 u=this.eventsOnce[r];u&&(Array.prototype.push.apply(l,u),delete this.eventsOnce[r]);let f=this.events[r];f&&Array.prototype.push.apply(l,f),l.forEach(y=>{Hf(this.logger,o,y,n)})}once(...r){let n=r.length;if(n===0||n===1&&typeof r[0]!="function"){let u=r[0];return new Promise(f=>{this.once(u,f)})}let[o,l]=r;if(r.length===1&&typeof o=="function")this.anyOnce.push(o);else if(ze(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 u=this,f=function(){let y=Array.prototype.slice.call(arguments);if(o.forEach(function(_){u.off(_,f)}),typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));l.apply(this,y)};o.forEach(function(y){u.on(y,f)})}else{if(typeof o!="string")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));let u=this.eventsOnce[o]||(this.eventsOnce[o]=[]);if(l){if(typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));u.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)}},ge=Gf,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},ga=[];Object.keys(z).forEach(function(r){ga[z[r]]=r});var Oe={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},Ff=Object.keys(Oe);Oe.MODE_ALL=Oe.PRESENCE|Oe.PUBLISH|Oe.SUBSCRIBE|Oe.PRESENCE_SUBSCRIBE|Oe.ANNOTATION_PUBLISH|Oe.ANNOTATION_SUBSCRIBE|Oe.OBJECT_SUBSCRIBE|Oe.OBJECT_PUBLISH;var ma=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function Wf(r){return!r||!r.channelOptions?{channelOptions:r,plugins:{},baseEncodedPreviousPayload:void 0}:r}function ya(r,n,o){if(o&&o.cipher){r||_e("Crypto");let l=r.getCipher(o.cipher,n);return{cipher:l.cipherParams,channelCipher:l.cipher}}return o??{}}async function Vf(r,n){let{data:o,encoding:l}=await _a(r.data,r.encoding,n);return r.data=o,r.encoding=l,r}async function _a(r,n,o){let l=o.channelCipher,u=r,f=n?n+"/":"";L.BufferUtils.isBuffer(u)||(u=L.BufferUtils.utf8Encode(String(u)),f=f+"utf-8/");let y=await l.encrypt(u);return f=f+"cipher+"+l.algorithm,{data:y,encoding:f}}async function nr(r,n){let{data:o,encoding:l}=ba(r.data,r.encoding);return r.data=o,r.encoding=l,n!=null&&n.cipher?Vf(r,n):r}function ba(r,n){if(typeof r=="string"||L.BufferUtils.isBuffer(r)||r===null||r===void 0)return{data:r,encoding:n};if(St(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 rr(r,n){let{data:o,encoding:l,error:u}=await va(r.data,r.encoding,n);if(r.data=o,r.encoding=l,u)throw u}async function va(r,n,o){let l=Wf(o),u=r,f=r,y=n,_;if(n){let S=n.split("/"),I,U=S.length,D="";try{for(;(I=U)>0;){let G=S[--U].match(/([-\w]+)(\+([\w-]+))?/);if(!G)break;switch(D=G[1],D){case"base64":f=L.BufferUtils.base64Decode(String(f)),I==S.length&&(u=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 C=G[3],R=l.channelOptions.channelCipher;if(C!=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 C=l.baseEncodedPreviousPayload;typeof C=="string"&&(C=L.BufferUtils.utf8Encode(C));let R=L.BufferUtils.toBuffer(C);f=L.BufferUtils.toBuffer(f),f=L.BufferUtils.arrayBufferViewToBuffer(l.plugins.vcdiff.decode(f,R)),u=f}catch(C){throw new x("Vcdiff delta decode failed with "+C,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(G){let C=G;_=new x(`Error processing the ${D} encoding, decoder returned \u2018${C.message}\u2019`,C.code||40013,400)}finally{y=I<=0?null:S.slice(0,I).join("/")}}return _?{error:_,data:f,encoding:y}:(l.baseEncodedPreviousPayload=u,{data:f,encoding:y})}function ir(...r){let n=r.length>0?"json":"msgpack",{data:o,encoding:l}=wa(this.data,this.encoding,n);return Object.assign({},this,{encoding:l,data:o})}function wa(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 $s={encryptData:_a,encodeData:ba,encodeDataForWire:wa,decodeData:va};function Hs(r){let{id:n,connectionId:o,timestamp:l}=r,u;switch(r.action){case z.MESSAGE:{u=r.messages;break}case z.PRESENCE:case z.SYNC:u=r.presence;break;case z.ANNOTATION:u=r.annotations;break;case z.OBJECT:case z.OBJECT_SYNC:u=r.state;break;default:throw new x("Unexpected action "+r.action,4e4,400)}for(let f=0;f<u.length;f++){let y=u[f];y.connectionId||(y.connectionId=o),y.timestamp||(y.timestamp=l),n&&!y.id&&(y.id=n+":"+f)}}function At(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 Rt=class{},Ca=class{constructor(r){this.Platform=L,this.ErrorInfo=x,this.Logger=d,this.Defaults=K,this.Utils=es,this.EventEmitter=ge,this.MessageEncoding=$s;var n,o,l,u,f,y,_,S,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 G=D.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!G){let C="invalid key parameter";throw d.logAction(this.logger,d.LOG_ERROR,"BaseClient()",C),new x(C,40400,404)}D.keyName=G[1],D.keySecret=G[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 tr(this),this.auth=new Ke(this,D),this._rest=(u=r.plugins)!=null&&u.Rest?new r.plugins.Rest(this):null,this._Crypto=(y=(f=r.plugins)==null?void 0:f.Crypto)!=null?y:null,this.__FilteredSubscriptions=(S=(_=r.plugins)==null?void 0:_.MessageInteractions)!=null?S:null,this._Annotations=(U=(I=r.plugins)==null?void 0:I.Annotations)!=null?U:null}get rest(){return this._rest||_e("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||_e("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)&&_e("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,u,f){return this.rest.request(r,n,o,l,u,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}};Ca.Platform=L;var Ea=Ca,zf=class Xt{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,u;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)),(u=this.push)!=null&&u.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=pe(n,o,l)),Array.isArray(n)?Xt.fromValuesArray(n):Xt.fromValues(n)}static fromValues(n){return n.error=n.error&&x.fromValues(n.error),Object.assign(new Xt,n)}static fromLocalDevice(n){return Object.assign(new Xt,n)}static fromValuesArray(n){let o=n.length,l=new Array(o);for(let u=0;u<o;u++)l[u]=Xt.fromValues(n[u]);return l}},Pt=zf;async function ka(r,n,o,l){if(r.http.supportsAuthHeaders){let u=await r.auth.getAuthHeaders();return l(J(u,n),o)}else{let u=await r.auth.getAuthParams();return l(n,J(u,o))}}function Kf(r,n,o){if(r.err&&!r.body)return{err:r.err};if(r.statusCode===rs.NoContent)return A(k({},r),{body:[],unpacked:!0});let l=r.body;if(!r.unpacked)try{l=pe(l,n,o)}catch(_){return Jn(_)?{err:_}:{err:new Ae(ne(_),null)}}if(!l)return{err:new Ae("unenvelope(): Response body is missing",null)};let{statusCode:u,response:f,headers:y}=l;if(u===void 0)return A(k({},r),{body:l,unpacked:!0});if(u<200||u>=300){let _=f&&f.error||r.err;return _||(_=new Error("Error in unenveloping "+l),_.statusCode=u),{err:_,body:f,headers:y,unpacked:!0,statusCode:u}}return{err:r.err,body:f,headers:y,unpacked:!0,statusCode:u}}function Jf(r,n,o,l,u){r.err?d.logAction(u,d.LOG_MICRO,"Resource."+n+"()","Received Error; "+Tt(o,l)+"; Error: "+ne(r.err)):d.logAction(u,d.LOG_MICRO,"Resource."+n+"()","Received; "+Tt(o,l)+"; Headers: "+er(r.headers)+"; StatusCode: "+r.statusCode+"; Body: "+(L.BufferUtils.isBuffer(r.body)?" (Base64): "+L.BufferUtils.base64Encode(r.body):": "+L.Config.inspect(r.body)))}var Yf=class Zt{static async get(n,o,l,u,f,y){return Zt.do(de.Get,n,o,null,l,u,f,y??!1)}static async delete(n,o,l,u,f,y){return Zt.do(de.Delete,n,o,null,l,u,f,y)}static async post(n,o,l,u,f,y,_){return Zt.do(de.Post,n,o,l,u,f,y,_)}static async patch(n,o,l,u,f,y,_){return Zt.do(de.Patch,n,o,l,u,f,y,_)}static async put(n,o,l,u,f,y,_){return Zt.do(de.Put,n,o,l,u,f,y,_)}static async do(n,o,l,u,f,y,_,S){_&&((y=y||{}).envelope=_);let I=o.logger;async function U(G,C){var R;if(I.shouldLog(d.LOG_MICRO)){let j=u;if(((R=G["content-type"])==null?void 0:R.indexOf("msgpack"))>0)try{o._MsgPack||_e("MsgPack"),j=o._MsgPack.decode(u)}catch(H){d.logAction(I,d.LOG_MICRO,"Resource."+n+"()","Sending MsgPack Decoding Error: "+ne(H))}d.logAction(I,d.LOG_MICRO,"Resource."+n+"()","Sending; "+Tt(l,C)+"; Body: "+j)}let P=await o.http.do(n,l,G,u,C);return P.error&&Ke.isTokenErr(P.error)?(await o.auth.authorize(null,null),ka(o,G,C,U)):{err:P.error,body:P.body,headers:P.headers,unpacked:P.unpacked,statusCode:P.statusCode}}let D=await ka(o,f,y,U);if(_&&(D=Kf(D,o._MsgPack,_)),I.shouldLog(d.LOG_MICRO)&&Jf(D,n,l,y,I),S){if(D.err)throw D.err;{let G=k({},D);return delete G.err,G}}return D}},le=Yf;function Qf(r){let n=r.match(/^\.\/(\w+)\?(.*)$/);return n&&n[2]&&js(n[2])}function Xf(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 u=Qf(l[1]);u&&(n[l[2]]=u)}}return n}function Zf(r,n,o){return!(o&&(n||typeof r.code=="number"))}var ep=class{constructor(r,n,o,l,u,f){this.client=r,this.path=n,this.headers=o,this.envelope=l??null,this.bodyHandler=u,this.useHttpPaginatedResponse=f||!1}get logger(){return this.client.logger}async get(r){let n=await le.get(this.client,this.path,this.headers,r,this.envelope,!1);return this.handlePage(n)}async delete(r){let n=await le.delete(this.client,this.path,this.headers,r,this.envelope,!1);return this.handlePage(n)}async post(r,n){let o=await le.post(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async put(r,n){let o=await le.put(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async patch(r,n){let o=await le.patch(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async handlePage(r){if(r.err&&Zf(r.err,r.body,this.useHttpPaginatedResponse))throw d.logAction(this.logger,d.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+ne(r.err)),r.err;let n,o,l;try{n=r.statusCode==rs.NoContent?[]:await this.bodyHandler(r.body,r.headers||{},r.unpacked)}catch(u){throw r.err||u}return r.headers&&(o=r.headers.Link||r.headers.link)&&(l=Xf(o)),this.useHttpPaginatedResponse?new tp(this,n,r.headers||{},r.statusCode,l,r.err):new Oa(this,n,l)}},Oa=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 le.get(n.client,n.path,n.headers,r,n.envelope,!1);return n.handlePage(o)}},tp=class extends Oa{constructor(r,n,o,l,u,f){super(r,n,u),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=ep,Sa=class xs{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=pe(n,o,l)),Array.isArray(n)?xs.fromValuesArray(n):xs.fromValues(n)}static fromValues(n){return Object.assign(new xs,n)}static fromValuesArray(n){let o=n.length,l=new Array(o);for(let u=0;u<o;u++)l[u]=xs.fromValues(n[u]);return l}};Sa.toRequestBody=je;var sp=Sa,Gs=sp,np=class{constructor(r){var n;this.client=r,this.admin=new rp(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(Pt))}async activate(r,n){await new Promise((o,l)=>{var u;if(!((u=this.client.options.plugins)!=null&&u.Push)){l(ns("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(ns("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=u=>{if(u){o(u);return}n()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,r))})}},rp=class{constructor(r){this.client=r,this.deviceRegistrations=new ip(r),this.channelSubscriptions=new op(r)}async publish(r,n){let o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",u=K.defaultPostHeaders(o.options),f={},y=J({recipient:r},n);J(u,o.options.headers),o.options.pushFullWait&&J(f,{fullWait:"true"});let _=je(y,o._MsgPack,l);await le.post(o,"/push/publish",_,u,f,null,!0)}},ip=class{constructor(r){this.client=r}async save(r){let n=this.client,o=Pt.fromValues(r),l=n.options.useBinaryProtocol?"msgpack":"json",u=K.defaultPostHeaders(n.options),f={};J(u,n.options.headers),n.options.pushFullWait&&J(f,{fullWait:"true"});let y=je(o,n._MsgPack,l),_=await le.put(n,"/push/deviceRegistrations/"+encodeURIComponent(r.id),y,u,f,null,!0);return Pt.fromResponseBody(_.body,n._MsgPack,_.unpacked?void 0:l)}async get(r){let n=this.client,o=n.options.useBinaryProtocol?"msgpack":"json",l=K.defaultGetHeaders(n.options),u=r.id||r;if(typeof u!="string"||!u.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 le.get(n,"/push/deviceRegistrations/"+encodeURIComponent(u),l,{},null,!0);return Pt.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,u=K.defaultGetHeaders(n.options);return J(u,n.options.headers),new Be(n,"/push/deviceRegistrations",u,l,async function(f,y,_){return Pt.fromResponseBody(f,n._MsgPack,_?void 0:o)}).get(r)}async remove(r){let n=this.client,o=K.defaultGetHeaders(n.options),l={},u=r.id||r;if(typeof u!="string"||!u.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 le.delete(n,"/push/deviceRegistrations/"+encodeURIComponent(u),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 le.delete(n,"/push/deviceRegistrations",l,r,null,!0)}},op=class Rd{constructor(n){this.remove=Rd.prototype.removeWhere,this.client=n}async save(n){let o=this.client,l=Gs.fromValues(n),u=o.options.useBinaryProtocol?"msgpack":"json",f=K.defaultPostHeaders(o.options),y={};J(f,o.options.headers),o.options.pushFullWait&&J(y,{fullWait:"true"});let _=je(l,o._MsgPack,u),S=await le.post(o,"/push/channelSubscriptions",_,f,y,null,!0);return Gs.fromResponseBody(S.body,o._MsgPack,S.unpacked?void 0:u)}async list(n){let o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",u=this.client.http.supportsLinkHeaders?void 0:l,f=K.defaultGetHeaders(o.options);return J(f,o.options.headers),new Be(o,"/push/channelSubscriptions",f,u,async function(y,_,S){return Gs.fromResponseBody(y,o._MsgPack,S?void 0:l)}).get(n)}async removeWhere(n){let o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",u=K.defaultGetHeaders(o.options,{format:l});J(u,o.options.headers),o.options.pushFullWait&&J(n,{fullWait:"true"}),await le.delete(o,"/push/channelSubscriptions",u,n,null,!0)}async listChannels(n){let o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",u=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,u,async function(y,_,S){let I=!S&&l?pe(y,o._MsgPack,l):y;for(let U=0;U<I.length;U++)I[U]=String(I[U]);return I}).get(n)}},ap=np,Ta=["absent","present","enter","leave","update"];async function Aa(r,n,o,l){let u=ya(n,r,l??null);return is.fromValues(o).decode(u,r)}async function cp(r,n,o,l){return Promise.all(o.map(function(u){return Aa(r,n,u,l)}))}async function lp(r,n){return is.fromValues(r).decode(n.channelOptions,n.logger)}async function Ra(r,n){return Promise.all(r.map(function(o){return lp(o,n)}))}var Pa=class Ns extends Rt{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 is,this,{action:Ta.indexOf(this.action||"present")});return nr(o,n)}static fromValues(n){return Object.assign(new Ns,n)}static fromValuesArray(n){return n.map(o=>Ns.fromValues(o))}static fromData(n){return n instanceof Ns?n:Ns.fromValues({data:n})}toString(){return At(this,"PresenceMessage")}},is=class yo extends Rt{toJSON(...n){return ir.call(this,...n)}static fromValues(n){return Object.assign(new yo,n)}static fromValuesArray(n){return n.map(o=>yo.fromValues(o))}async decode(n,o){let l=Object.assign(new Pa,A(k({},this),{action:Ta[this.action]}));try{await rr(l,n)}catch(u){d.logAction(o,d.LOG_ERROR,"WirePresenceMessage.decode()",ne(u))}return l}toString(){return At(this,"WirePresenceMessage")}},Je=Pa,up=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,u=K.defaultGetHeaders(n.options);return J(u,n.options.headers),new Be(n,this.channel.client.rest.presenceMixin.basePath(this),u,l,async(f,y,_)=>{let S=_?f:pe(f,n._MsgPack,o);return Ra(S,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)}},hp=up,Ia=["message.create","message.update","message.delete","meta","message.summary","message.append"];function dp(r){return Ia[r||0]||"unknown"}function fp(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+=Ho(r.data)),n}async function Ma(r,n,o,l){let u=ya(n,r,l??null);return os.fromValues(o).decode(u,r)}async function pp(r,n,o,l){return Promise.all(o.map(function(u){return Ma(r,n,u,l)}))}async function xa(r,n){return os.fromValues(r).decode(n.channelOptions,n.logger)}async function Na(r,n){return Promise.all(r.map(function(o){return xa(o,n)}))}async function La(r,n){return Promise.all(r.map(o=>o.encode(n)))}var Da=je;function Ua(r){let n,o=0;for(let l=0;l<r.length;l++)n=r[l],o+=n.size||(n.size=fp(n));return o}var ja=class _o extends Rt{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 os,this,{action:Ia.indexOf(this.action||"message.create")});return nr(o,n)}static fromValues(n){return Object.assign(new _o,n)}static fromValuesArray(n){return n.map(o=>_o.fromValues(o))}toString(){return At(this,"Message")}},os=class bo extends Rt{toJSON(...n){return ir.call(this,...n)}static fromValues(n){return Object.assign(new bo,n)}static fromValuesArray(n){return n.map(o=>bo.fromValues(o))}async decodeWithErr(n,o){let l=Object.assign(new ja,A(k({},this),{action:dp(this.action)})),u;try{await rr(l,n)}catch(f){d.logAction(o,d.LOG_ERROR,"WireMessage.decode()",ne(f)),u=f}return l.expandFields(),{decoded:l,err:u}}async decode(n,o){let{decoded:l}=await this.decodeWithErr(n,o);return l}toString(){return At(this,"WireMessage")}},Fe=ja,gp=9;function mp(r){return r.every(function(n){return!n.id})}var yp=class{constructor(r,n,o){this._annotations=null;var l,u;d.logAction(r.logger,d.LOG_MINOR,"RestChannel()","started; name = "+n),this.name=n,this.client=r,this.presence=new hp(this),this.channelOptions=Bs((l=r._Crypto)!=null?l:null,this.logger,o),(u=r.options.plugins)!=null&&u.Push&&(this._push=new r.options.plugins.Push.PushChannel(this)),r._Annotations&&(this._annotations=new r._Annotations.RestAnnotations(this))}get annotations(){return this._annotations||_e("Annotations"),this._annotations}get push(){return this._push||_e("Push"),this._push}get logger(){return this.client.logger}setOptions(r){var n;this.channelOptions=Bs((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,u;if(typeof n=="string"||n===null)l=[Fe.fromValues({name:n,data:o})],u=r[2];else if(St(n))l=[Fe.fromValues(n)],u=r[1];else if(Array.isArray(n))l=Fe.fromValuesArray(n),u=r[1];else throw new x("The single-argument form of publish() expects a message object or an array of message objects",40013,400);u||(u={});let f=this.client,y=f.options,_=y.useBinaryProtocol?"msgpack":"json",S=f.options.idempotentRestPublishing,I=K.defaultPostHeaders(f.options);if(J(I,y.headers),S&&mp(l)){let C=await Fo(gp);l.forEach(function(R,P){R.id=C+":"+P.toString()})}let U=await La(l,this.channelOptions),D=Ua(U),G=y.maxMessageSize;if(D>G)throw new x(`Maximum size of messages that can be published at once exceeded (was ${D} bytes; limit is ${G} bytes)`,40009,400);return this._publish(Da(U,f._MsgPack,_),I,u)}async _publish(r,n,o){let l=this.client,u=l.options.useBinaryProtocol?"msgpack":"json",{body:f,unpacked:y}=await le.post(l,l.rest.channelMixin.basePath(this)+"/messages",r,n,o,null,!0),_=(y?f:pe(f,l._MsgPack,u))||{};return delete _.channel,delete _.messageId,_}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)}},_p=yp,bp=class Pd{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 Pd(n)}},vp=bp,qa=class{static basePath(r){return"/channels/"+encodeURIComponent(r.name)}static history(r,n){let o=r.client,l=o.options.useBinaryProtocol?"msgpack":"json",u=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,u,async function(y,_,S){let I=S?y:pe(y,o._MsgPack,l);return Na(I,r)}).get(n)}static async status(r){let n=r.client.options.useBinaryProtocol?"msgpack":"json",o=K.defaultPostHeaders(r.client.options);return(await le.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,u=l.options.useBinaryProtocol?"msgpack":"json",f=K.defaultGetHeaders(l.options);J(f,l.options.headers);let{body:y,unpacked:_}=await le.get(l,this.basePath(r)+"/messages/"+encodeURIComponent(o),f,{},null,!0),S=_?y:pe(y,l._MsgPack,u);return xa(S,r)}static async updateDeleteMessage(r,n,o,l,u){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",_=K.defaultPostHeaders(f.options);J(_,f.options.headers);let S=Fe.fromValues(o);S.action=n,S.version=l;let I=await S.encode(r.channelOptions),U=Da(I,f._MsgPack,y),D=le.patch,{body:G,unpacked:C}=await D(f,this.basePath(r)+"/messages/"+encodeURIComponent(o.serial),U,_,u||{},null,!0);return(C?G:pe(G,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 u=r.client,f=u.options.useBinaryProtocol?"msgpack":"json",y=r.client.http.supportsLinkHeaders?void 0:f,_=K.defaultGetHeaders(u.options);return J(_,u.options.headers),new Be(u,this.basePath(r)+"/messages/"+encodeURIComponent(l)+"/versions",_,y,async(S,I,U)=>{let D=U?S:pe(S,u._MsgPack,f);return Na(D,r)}).get(o||{})}},wp=class{static basePath(r){return qa.basePath(r.channel)+"/presence"}static async history(r,n){let o=r.channel.client,l=o.options.useBinaryProtocol?"msgpack":"json",u=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,u,async(y,_,S)=>{let I=S?y:pe(y,o._MsgPack,l);return Ra(I,r.channel)}).get(n)}},Ba=class{constructor(r){this.channelMixin=qa,this.presenceMixin=wp,this.Resource=le,this.PaginatedResource=Be,this.DeviceDetails=Pt,this.PushChannelSubscription=Gs,this.client=r,this.channels=new Cp(this.client),this.push=new ap(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(u,f,y)=>{let _=y?u:pe(u,this.client._MsgPack,o);for(let S=0;S<_.length;S++)_[S]=vp.fromValues(_[S]);return _}).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=_=>this.client.baseUri(_)+"/time",{error:l,body:u,unpacked:f}=await this.client.http.do(de.Get,o,n,null,r);if(l)throw l;f||(u=JSON.parse(u));let y=u[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,u,f){var y;let[_,S,I]=this.client.options.useBinaryProtocol?(this.client._MsgPack||_e("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(),G=D=="get"?K.defaultGetHeaders(this.client.options,{format:I,protocolVersion:o}):K.defaultPostHeaders(this.client.options,{format:I,protocolVersion:o});typeof u!="string"&&(u=(y=_(u))!=null?y:null),J(G,this.client.options.headers),f&&J(G,f);let C=new Be(this.client,n,G,U,async function(R,P,j){return Mo(j?R:S(R))},!0);if(!L.Http.methods.includes(D))throw new x("Unsupported method "+D,40500,405);return L.Http.methodsWithBody.includes(D)?C[D](l,u):C[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",u=K.defaultPostHeaders(this.client.options);this.client.options.headers&&J(u,this.client.options.headers);let f=je(n,this.client._MsgPack,l),y=await le.post(this.client,"/messages",f,u,{},null,!0),_=y.unpacked?y.body:pe(y.body,this.client._MsgPack,l);return o?_[0]:_}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(","),u=await le.get(this.client,"/presence",o,{channels:l},null,!0);return u.unpacked?u.body:pe(u.body,this.client._MsgPack,n)}async revokeTokens(r,n){if(pa(this.client.options))throw new x("Cannot revoke tokens when using token auth",40162,401);let o=this.client.options.keyName,l=n??{},u=k({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 _=je(u,this.client._MsgPack,f),S=await le.post(this.client,`/keys/${o}/revokeTokens`,_,y,{},null,!0);return S.unpacked?S.body:pe(S.body,this.client._MsgPack,f)}},Cp=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 _p(this.client,r,n),o}release(r){delete this.all[String(r)]}},Ep=class extends Ea{constructor(r){super(K.objectifyOptions(r,!1,"BaseRest",d.defaultLogger,{Rest:Ba}))}},$a={Rest:Ba},Ha=class extends Fe{static async fromEncoded(r,n){return Ma(d.defaultLogger,L.Crypto,r,n)}static async fromEncodedArray(r,n){return pp(d.defaultLogger,L.Crypto,r,n)}static fromValues(r){return Fe.fromValues(r)}},Ga=class extends Je{static async fromEncoded(r,n){return Aa(d.defaultLogger,L.Crypto,r,n)}static async fromEncodedArray(r,n){return cp(d.defaultLogger,L.Crypto,r,n)}static fromValues(r){return Je.fromValues(r)}},Fa=["annotation.create","annotation.delete"];async function Wa(r,n,o){return It.fromValues(n).decode(o||{},r)}async function kp(r,n,o){return Promise.all(n.map(function(l){return Wa(r,l,o)}))}async function Op(r,n){return It.fromValues(r).decode(n.channelOptions,n.logger)}async function Sp(r,n){return Promise.all(r.map(function(o){return Op(o,n)}))}var Va=class vo extends Rt{async encode(){let n=Object.assign(new It,this,{action:Fa.indexOf(this.action||"annotation.create")});return nr(n,{})}static fromValues(n){return Object.assign(new vo,n)}static fromValuesArray(n){return n.map(o=>vo.fromValues(o))}toString(){return At(this,"Annotation")}},It=class wo extends Rt{toJSON(...n){return ir.call(this,...n)}static fromValues(n){return Object.assign(new wo,n)}static fromValuesArray(n){return n.map(o=>wo.fromValues(o))}async decode(n,o){let l=Object.assign(new Va,A(k({},this),{action:Fa[this.action]}));try{await rr(l,n)}catch(u){d.logAction(o,d.LOG_ERROR,"WireAnnotation.decode()",ne(u))}return l}toString(){return At(this,"WireAnnotation")}},Mt=Va,za=class extends Mt{static async fromEncoded(r,n){return Wa(d.defaultLogger,r,n)}static async fromEncodedArray(r,n){return kp(d.defaultLogger,r,n)}static fromValues(r){return Mt.fromValues(r)}};function Ka(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 Ja(r,n){let o=Ka(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=Mt.fromValues(n);return l.messageSerial=o,l.action||(l.action="annotation.create"),l}function Ya(r,n){return r.client.rest.channelMixin.basePath(r)+"/messages/"+encodeURIComponent(n)+"/annotations"}var Tp=class{constructor(r){this.channel=r}async publish(r,n){let o=Ja(r,n),l=await o.encode(),u=this.channel.client,f=u.options,y=f.useBinaryProtocol?"msgpack":"json",_=K.defaultPostHeaders(u.options),S={};J(_,u.options.headers);let I=je([l],u._MsgPack,y);await le.post(u,Ya(this.channel,o.messageSerial),I,_,S,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=Ka(r),u=o.options.useBinaryProtocol?"msgpack":"json",f=o.http.supportsLinkHeaders?void 0:u,y=K.defaultGetHeaders(o.options);return J(y,o.options.headers),new Be(o,Ya(this.channel,l),y,f,async(_,S,I)=>{let U=I?_:pe(_,o._MsgPack,u);return Sp(U,this.channel)}).get(n)}},Fs=Tp,Ap=je;function Ws(r){let n=[];if(r)for(let o=0;o<r.length;o++)n.push(r[o].toString());return"[ "+n.join(", ")+" ]"}function Rp(r,n,o,l,u,f){let y=pe(r,n,f);return or(y,o,l,u)}function or(r,n,o,l){let u;r.error&&(u=x.fromValues(r.error));let f;r.messages&&(f=os.fromValuesArray(r.messages));let y;n&&r.presence&&(y=n.WirePresenceMessage.fromValuesArray(r.presence));let _;o&&r.annotations&&(_=o.WireAnnotation.fromValuesArray(r.annotations));let S;return l&&r.state&&(S=l.WireObjectMessage.fromValuesArray(r.state,es,$s)),Object.assign(new cr,A(k({},r),{presence:y,messages:f,annotations:_,state:S,error:u}))}function Pp(r){return n=>{var o;return or(n,{PresenceMessage:Je,WirePresenceMessage:is},{Annotation:Mt,WireAnnotation:It,RealtimeAnnotations:ur,RestAnnotations:Fs},(o=r?.LiveObjectsPlugin)!=null?o:null)}}function Se(r){return Object.assign(new cr,r)}function ar(r,n,o,l){let u="[ProtocolMessage";r.action!==void 0&&(u+="; action="+ga[r.action]||r.action);let f=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"],y;for(let _=0;_<f.length;_++)y=f[_],r[y]!==void 0&&(u+="; "+y+"="+r[y]);if(r.messages&&(u+="; messages="+Ws(os.fromValuesArray(r.messages))),r.presence&&n&&(u+="; presence="+Ws(n.WirePresenceMessage.fromValuesArray(r.presence))),r.annotations&&o&&(u+="; annotations="+Ws(o.WireAnnotation.fromValuesArray(r.annotations))),r.state&&l&&(u+="; state="+Ws(l.WireObjectMessage.fromValuesArray(r.state,es,$s))),r.error&&(u+="; error="+x.fromValues(r.error).toString()),r.auth&&r.auth.accessToken&&(u+="; token="+r.auth.accessToken),r.flags&&(u+="; flags="+Ff.filter(r.hasFlag).join(",")),r.params){let _="";qo(r.params,function(S){_.length>0&&(_+="; "),_+=S+"="+r.params[S]}),_.length>0&&(u+="; params=["+_+"]")}return u+="]",u}var cr=class{constructor(){this.hasFlag=r=>(this.flags&Oe[r])>0}setFlag(r){return this.flags=this.flags|Oe[r]}getMode(){return(this.flags||0)&Oe.MODE_ALL}encodeModesToFlags(r){r.forEach(n=>this.setFlag(n))}decodeModesFromFlags(){let r=[];return ma.forEach(n=>{this.hasFlag(n)&&r.push(n)}),r.length>0?r:void 0}},Ip=cr,Mp=class{constructor(r,n,o,l,u){this.previous=r,this.current=n,n==="attached"&&(this.resumed=o,this.hasBacklog=l),u&&(this.reason=u)}},lr=Mp,Qa=function(){};function xp(r){if(r&&"params"in r&&!St(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"||!ma.includes(String.prototype.toUpperCase.call(o)))return new x("Invalid channel mode: "+o,4e4,400)}}}var Np=class Co extends ge{constructor(n,o,l){var u,f,y;super(n.logger),this._annotations=null,this._mode=0,this.retryCount=0,this.history=async function(_){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);let S=this.client.rest.channelMixin;if(_&&_.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 _.untilAttach,_.from_serial=this.properties.attachSerial}return S.history(this,_)},this.whenState=_=>ge.prototype.whenState.call(this,_,this.state),d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel()","started; name = "+o),this.name=o,this.channelOptions=Bs((u=n._Crypto)!=null?u: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 ge(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 ge(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||_e("RealtimePresence"),this._presence}get annotations(){return this._annotations||_e("Annotations"),this._annotations}get push(){return this._push||_e("Push"),this._push}get object(){return this._object||_e("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,u=xp(n);if(u)throw u;if(this.channelOptions=Bs((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(_){switch(this.event){case"update":case"attached":f();break;default:y(_.reason)}})})}_shouldReattachToSetOptions(n,o){if(!(this.state==="attached"||this.state==="attaching"))return!1;if(n?.params){let l=Xa(n.params),u=Xa(o.params);if(Object.keys(l).length!==Object.keys(u).length||!Qn(u,l))return!0}return!!(n?.modes&&(!o.modes||!Qo(n.modes,o.modes)))}async publish(...n){let o=n[0],l=n[1],u,f;if(typeof o=="string"||o===null||o===void 0)u=[Fe.fromValues({name:o,data:l})],f=n[2];else if(St(o))u=[Fe.fromValues(o)],f=n[1];else if(Array.isArray(o))u=Fe.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,_=await La(u,this.channelOptions),S=Ua(_);if(S>y)throw new x(`Maximum size of messages that can be published at once exceeded (was ${S} 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 = "+_.length);let I=Se({action:z.MESSAGE,channel:this.name,messages:_,params:f?Kn(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 u=n[l];o.emit(u.name,u)}}async attach(){return this.state==="attached"?null:new Promise((n,o)=>{this._attach(!1,null,(l,u)=>l?o(l):n(u))})}_attach(n,o,l){l||(l=f=>{f&&d.logAction(this.logger,d.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+f.toString())});let u=this.connectionManager;if(!u.activeState()){l(u.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||u.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=Se({action:z.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&n.encodeModesToFlags(zo(this.channelOptions.modes)),this._attachResume&&n.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(n.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(n).catch(Qa)}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(u){switch(this.event){case"detached":o();break;case"attached":case"suspended":case"failed":l(u.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=Se({action:z.DETACH,channel:this.name});this.sendMessage(n).catch(Qa)}async subscribe(...n){let[o,l]=Co.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,u]=Co.processListenerArgs(n);if(typeof l=="object"&&!u||(o=this.filteredSubscriptions)!=null&&o.has(u)){this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,l,u).forEach(f=>this.subscriptions.off(f));return}this.subscriptions.off(l,u)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new Ae("Unable to sync to channel; not attached",4e4);default:}let n=this.connectionManager;if(!n.activeState())throw n.getError();let o=Se({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,(u,f)=>{u?l(u):o(f)})})}async sendPresence(n){let o=Se({action:z.PRESENCE,channel:this.name,presence:n});await this.sendMessage(o)}async sendState(n){let o=Se({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 u=n.decodeModesFromFlags();this.modes=u&&Vo(u)||void 0;let f=n.hasFlag("RESUMED"),y=n.hasFlag("HAS_PRESENCE"),_=n.hasFlag("HAS_BACKLOG"),S=n.hasFlag("HAS_OBJECTS");if(this.state==="attached"){f||(this._presence&&this._presence.onAttached(y),this._object&&this._object.onAttached(S));let I=new lr(this.state,this.state,f,_,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,_,S);break}case z.DETACHED:{let u=n.error?x.fromValues(n.error):new x("Channel detached",90001,404);this.state==="detaching"?this.notifyState("detached",u):this.state==="attaching"?this.notifyState("suspended",u):(this.state==="attached"||this.state==="suspended")&&this.requestState("attaching",u);break}case z.SYNC:if(l=!0,o=this.syncChannelSerial=n.channelSerial,!n.presence)break;case z.PRESENCE:{if(!n.presence)break;Hs(n);let u=this.channelOptions;if(this._presence){let f=await Promise.all(n.presence.map(y=>y.decode(u,this.logger)));this._presence.setPresence(f,l,o)}break}case z.OBJECT:case z.OBJECT_SYNC:{if(!this._object||!n.state)return;Hs(n);let u=this.client.connection.connectionManager.getActiveTransportFormat(),f=n.state.map(y=>y.decode(this.client,u));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}Hs(n);let u=n.messages,f=u[0],y=u[u.length-1];if(f.extras&&f.extras.delta&&f.extras.delta.from!==this._lastPayload.messageId){let S='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()",S),this._startDecodeFailureRecovery(new x(S,40018,400));break}let _=[];for(let S=0;S<u.length;S++){let{decoded:I,err:U}=await u[S].decodeWithErr(this._decodingContext,this.logger);if(_[S]=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(_);break}case z.ANNOTATION:{Hs(n);let u=this.channelOptions;if(this._annotations){let f=await Promise.all((n.annotations||[]).map(y=>y.decode(u,this.logger)));this._annotations._processIncoming(f)}break}case z.ERROR:{let u=n.error;u&&u.code==80016?this.checkPendingState():this.notifyState("failed",x.fromValues(u));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,u,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,u,o),this._object&&this._object.actOnChannelState(n,y),n==="suspended"&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),o&&(this.errorReason=o);let _=new lr(this.state,n,l,f,o),S='Channel state for channel "'+this.name+'"',I=n+(o?"; reason: "+o:"");n==="failed"?d.logAction(this.logger,d.LOG_ERROR,S,I):d.logAction(this.logger,d.LOG_MAJOR,S,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,_),this.emit(n,_)}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=Yn(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,u){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 S=await Fe.fromValues(A(k({},n),{action:o,version:l})).encode(this.channelOptions),I=Se({action:z.MESSAGE,channel:this.name,messages:[S],params:u?Kn(u):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 Xa(r){let n=r||{},{agent:o}=n;return N(n,["agent"])}var as=Np,Lp=class{constructor(r){this.channel=r,this.logger=r.logger,this.subscriptions=new ge(this.logger)}async publish(r,n){let o=this.channel.name,l=Ja(r,n),u=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=Se({action:z.ANNOTATION,channel:o,annotations:[u]});await this.channel.sendMessage(f)}async delete(r,n){n.action="annotation.delete",await this.publish(r,n)}async subscribe(...r){let n=as.processListenerArgs(r),o=n[0],l=n[1],u=this.channel;if(u.state==="failed")throw x.fromValues(u.invalidStateError());if(this.subscriptions.on(o,l),this.channel.channelOptions.attachOnSubscribe!==!1&&await u.attach(),(this.channel.state==="attached"&&this.channel._mode&Oe.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=as.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 Fs.prototype.get.call(this,r,n)}},ur=Lp,yt=class Fn extends Ep{constructor(n){var o,l;if(!Fn._MsgPack)throw new Error("Expected DefaultRest._MsgPack to have been set");super(K.objectifyOptions(n,!0,"Rest",d.defaultLogger,A(k({},$a),{Crypto:(o=Fn.Crypto)!=null?o:void 0,MsgPack:(l=Fn._MsgPack)!=null?l:void 0,Annotations:{Annotation:Mt,WireAnnotation:It,RealtimeAnnotations:ur,RestAnnotations:Fs}})))}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}};yt._Crypto=null,yt.Message=Ha,yt.PresenceMessage=Ga,yt.Annotation=za,yt._MsgPack=null,yt._Http=tr;var Za=yt,Dp=class extends ge{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 u=[];if(r==="all")u=l.splice(0);else{let f=l[0];if(f){let y=f.message.msgSerial,_=r.serial+r.count;_>y&&(u=l.splice(0,_-y))}}for(let f=0;f<u.length;f++){let y=u[f],_=o?.[f];y.callback(n,_)}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")}},ec=Dp,tc=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)}},Up=class extends ge{constructor(r){super(r.logger),this.transport=r,this.messageQueue=new ec(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 = "+ne(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; "+ar(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()})}},jp=Up,qp=class{constructor(r,n,o,l){this.previous=r,this.current=n,o&&(this.retryIn=o),l&&(this.reason=l)}},Vs=qp,lt={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},Bp={disconnected:()=>x.fromValues({statusCode:400,code:lt.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>x.fromValues({statusCode:400,code:lt.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>x.fromValues({statusCode:400,code:lt.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>x.fromValues({statusCode:400,code:lt.CLOSING,message:"Connection closing"}),closed:()=>x.fromValues({statusCode:400,code:lt.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>x.fromValues({statusCode:500,code:lt.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>x.fromValues({statusCode:500,code:lt.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})};function $p(r){return!r.statusCode||!r.code||r.statusCode>=500?!0:Object.values(lt).includes(r.code)}var _t=Bp,Hp=Se({action:z.CLOSE}),Gp=Se({action:z.DISCONNECT}),Fp=class extends ge{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",_t.closed())}disconnect(r){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",r||_t.disconnected())}fail(r){this.isConnected&&this.requestDisconnect(),this.finish("failed",r||_t.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+": "+ar(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:Re(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: "+ne(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 = "+ne(n)),this.finish("disconnected",n)}onFatalError(r){let n=r&&r.error;d.logAction(this.logger,d.LOG_MINOR,"Transport.onFatalError()","err = "+ne(n)),this.finish("failed",n)}onClose(r){let n=r&&r.error;d.logAction(this.logger,d.LOG_MINOR,"Transport.onClose()","err = "+ne(n)),this.finish("closed",n)}requestClose(){d.logAction(this.logger,d.LOG_MINOR,"Transport.requestClose()",""),this.send(Hp)}requestDisconnect(){d.logAction(this.logger,d.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(Gp)}ping(r){let n={action:z.HEARTBEAT};r&&(n.id=r),this.send(Se(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,u){let f=new r(n,o,l),y,_=function(I){clearTimeout(y),u({event:this.event,error:I})},S=n.options.timeouts.realtimeRequestTimeout;return y=setTimeout(()=>{f.off(["preconnect","disconnected","failed"]),f.dispose(),_.call({event:"disconnected"},new x("Timeout waiting for transport to indicate itself viable",5e4,500))},S),f.on(["failed","disconnected"],_),f.on("preconnect",function(){d.logAction(n.logger,d.LOG_MINOR,"Transport.tryConnect()","viable transport "+f),clearTimeout(y),f.off(["failed","disconnected"],_),u(null,f)}),f.connect(),f}static isAvailable(){throw new x("isAvailable not implemented for transport",5e4,500)}},xt=Fp,be;(r=>{r.WebSocket="web_socket",r.Comet="comet",r.XhrPolling="xhr_polling"})(be||(be={}));var Wp=typeof global<"u"?global:typeof window<"u"?window:self,hr=()=>{var r;return typeof L.WebStorage<"u"&&((r=L.WebStorage)==null?void 0:r.localSupported)},cs=()=>{var r;return typeof L.WebStorage<"u"&&((r=L.WebStorage)==null?void 0:r.sessionSupported)},sc=function(){},dr="ably-transport-preference";function fr(r){try{return JSON.parse(r)}catch{return null}}var Vp=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?ts(r):{},o=this.options;switch(this.mode){case"resume":n.resume=this.connectionKey;break;case"recover":{let l=fr(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=Xn(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}},zp=class Id extends ge{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,u=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:u,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 ec(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=No(o.transports||K.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(be.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(be.XhrPolling)?this.baseTransport=be.XhrPolling:this.transports.includes(be.Comet)&&(this.baseTransport=be.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&&(cs()&&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=k(k({},L.Transports.bundledImplementations),n);[be.WebSocket,...L.Transports.order].forEach(u=>{let f=l[u];f&&f.isAvailable()&&(o.supportedTransports[u]=f)})}initTransports(){Id.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(n,o){return new Vp(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 u=this.options.recover,f=this.getSessionRecoverData(),y=this.sessionRecoveryName();if(f&&typeof u=="function"){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+y+")"),u(f,_=>{_?(this.options.recover=f.recoveryKey,l("recover")):l("clean")});return}l("clean")})(l=>{let u=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=fr(this.options.recover);f&&(this.msgSerial=f.msgSerial)}else d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+u.toString());n(u)})}tryATransport(n,o,l){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+o),this.proposedTransport=xt.tryConnect(this.supportedTransports[o],this,this.realtime.auth,n,(u,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(u){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+o+" "+u.event+", err: "+u.error.toString()),Ke.isTokenErr(u.error)&&!(this.errorReason&&Ke.isTokenErr(this.errorReason))?(this.errorReason=u.error,Re(this.realtime.auth._forceNewToken(null,null),_=>{if(_){this.actOnErrorFromAuthorize(_);return}this.tryATransport(n,o,l)})):u.event==="failed"?(this.notifyState({state:"failed",error:u.error}),l(!0)):u.event==="disconnected"&&($p(u.error)?l(!1):(this.notifyState({state:this.states.connecting.failState,error:u.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,_)=>{this.activateTransport(f,n,y,_),l==="recover"&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});let u=this;n.on(["disconnected","closed","failed"],function(f){u.deactivateTransport(n,this.event,f)}),this.emit("transport.pending",n)}activateTransport(n,o,l,u){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),u&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(u)),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 _=this.activeProtocol;this.activeProtocol=new jp(o),this.host=o.params.host;let S=u.connectionKey;if(S&&this.connectionKey!=S&&this.setConnection(l,u,!!n),this.onConnectionDetailsUpdate(u,o),L.Config.nextTick(()=>{o.on("connected",(I,U,D)=>{this.onConnectionDetailsUpdate(D,o),this.emit("update",new Vs(y,y,null,I))})}),f.state===this.states.connected.state?n&&(this.errorReason=this.realtime.connection.errorReason=n,this.emit("update",new Vs(y,y,null,n))):(this.notifyState({state:"connected",error:n}),this.errorReason=this.realtime.connection.errorReason=n||null),this.emit("transport.active",o),_)if(_.messageQueue.count()>0&&d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+_.transport.shortName+", new one is "+o.shortName+") finishing with "+_.messageQueue.count()+" messages still pending"),_.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 _.finish();return!0}deactivateTransport(n,o,l){let u=this.activeProtocol,f=u&&u.getTransport()===n,y=n===this.pendingTransport,_=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":"")+(_?"":"; 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(u.getPendingMessages()),u.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",n),f&&_||f&&o==="failed"||o==="closed"||u===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 S=o==="failed"&&Ke.isTokenErr(l)?"disconnected":o;this.notifyState({state:S,error:l});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(n,o,l){let u=this.connectionId;(u&&u!==n||!u&&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(cs()){let n=this.createRecoveryKey();n&&this.setSessionRecoverData({recoveryKey:n,disconnectedAt:Date.now(),location:Wp.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=Ae.fromValues(this.errorReason);return n.cause=this.errorReason,n}return this.getStateError()}getStateError(){var n,o;return(o=(n=_t)[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 u=this.state=this.states[n.current];n.reason&&(this.errorReason=n.reason,this.realtime.connection.errorReason=n.reason),(u.terminal||u.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&&Re(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 u=n.state,f=u==="disconnected"&&(this.state===this.states.connected||n.retryImmediately||this.state===this.states.connecting&&n.error&&Ke.isTokenErr(n.error)&&!(this.errorReason&&Ke.isTokenErr(this.errorReason)));if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+u+(f?"; will retry connection immediately":"")),u==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(n.state),(u==="suspended"||u==="connected")&&(this.disconnectedRetryCount=0),this.state.terminal))return;let y=this.states[n.state],_=y.retryDelay;y.state==="disconnected"&&(this.disconnectedRetryCount++,_=Yn(y.retryDelay,this.disconnectedRetryCount));let S=new Vs(this.state.state,y.state,_,n.error||((l=(o=_t)[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(u==="disconnected"||u==="suspended")&&this.startRetryTimer(_);(u==="disconnected"&&!f||u==="suspended"||y.terminal)&&L.Config.nextTick(()=>{this.disconnectAllTransports()}),u=="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(S),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(u,S.reason),this.failQueuedMessages(S.reason))}requestState(n){var o,l;let u=n.state;if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+u+"; current state: "+this.state.state),u==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(u),u=="connecting"&&this.state.state=="connected")||u=="closing"&&this.state.state=="closed")return;let f=this.states[u],y=new Vs(this.state.state,f.state,null,n.error||((l=(o=_t)[f.state])==null?void 0:l.call(o)));this.enactStateChange(y),u=="connecting"&&L.Config.nextTick(()=>{this.startConnect()}),u=="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(u=>{if(u.mode==="recover"&&u.options.recover){let f=fr(u.options.recover);f&&this.realtime.channels.recoverChannels(f.channelSerials)}o===this.connectCounter&&this.connectImpl(u,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 u=f=>{o===this.connectCounter&&(f?this.actOnErrorFromAuthorize(f):l())};this.errorReason&&Ke.isTokenErr(this.errorReason)?Re(n._forceNewToken(null,null),u):Re(n._ensureValidAuthCredentials(!1),u)}}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 u=this.getTransportPreference();u&&u===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(sc),u&&u===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,u,f){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",n);let y=D=>{this.notifyState({state:this.states.connecting.failState,error:D})},_=this.domains.slice(),S=(D,G)=>{if(u===this.connectCounter){if(!f()){G&&G.dispose();return}!G&&!D&&U()}},I=_.shift();if(!I){y(new x("Unable to connect (no available host)",80003,404));return}o.host=I;let U=()=>{if(!_.length){y(new x("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!this.realtime.http.checkConnectivity){y(new Ae("Internal error: Http.checkConnectivity not set",null,500));return}Re(this.realtime.http.checkConnectivity(),(D,G)=>{if(u===this.connectCounter&&f()){if(D){y(D);return}if(!G){y(new x("Unable to connect (network unreachable)",80003,404));return}o.host=zn(_),this.tryATransport(o,n,S)}})};if(this.forceFallbackHost&&_.length){this.forceFallbackHost=!1,U();return}this.tryATransport(o,n,S)}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 u=(l=this.activeProtocol)==null?void 0:l.getTransport();u&&u.onAuthUpdated&&u.onAuthUpdated(n);let f=Se({action:z.AUTH,auth:{accessToken:n.token}});this.send(f);let y=()=>{this.off(_),o(null,n)},_=S=>{S.current==="failed"&&(this.off(y),this.off(_),o(S.reason||this.getStateError()))};this.once("connectiondetails",y),this.on("connectionstate",_);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 u=f=>{switch(f.current){case"connected":this.off(u),o(null,n);break;case"failed":case"closed":case"suspended":this.off(u),o(f.reason||this.getStateError());break;default:break}};this.on("connectionstate",u),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||sc;let u=this.state;if(u.sendEvents){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new tc(n,l));return}if(!(o&&u.queueEvents)){let y="rejecting event, queueEvent was "+o+", state was "+u.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; "+ar(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 tc(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 = "+ne(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(),u=Go();return Xo(new Promise(f=>{let y=_=>{_===u&&(o.off("heartbeat",y),f(Date.now()-l))};o.on("heartbeat",y),o.ping(u)}),this.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")}abort(n){this.activeProtocol.getTransport().fail(n)}getTransportPreference(){var n,o;return this.transportPreference||hr()&&((o=(n=L.WebStorage)==null?void 0:n.get)==null?void 0:o.call(n,dr))}persistTransportPreference(n){var o,l;this.transportPreference=n.shortName,hr()&&((l=(o=L.WebStorage)==null?void 0:o.set)==null||l.call(o,dr,n.shortName))}unpersistTransportPreference(){var n,o;this.transportPreference=null,hr()&&((o=(n=L.WebStorage)==null?void 0:n.remove)==null||o.call(n,dr))}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===rs.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 u=n.connectionStateTtl;u&&(this.connectionStateTtl=u),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,u)=>{let f=!1;o.onopen=()=>{f||(f=!0,l(),o.close())},o.onclose=o.onerror=()=>{f||(f=!0,u())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var n,o;return cs()&&((o=(n=L.WebStorage)==null?void 0:n.getSession)==null?void 0:o.call(n,this.sessionRecoveryName()))}setSessionRecoverData(n){var o,l;return cs()&&((l=(o=L.WebStorage)==null?void 0:o.setSession)==null?void 0:l.call(o,this.sessionRecoveryName(),n))}clearSessionRecoverData(){var n,o;return cs()&&((o=(n=L.WebStorage)==null?void 0:n.removeSession)==null?void 0:o.call(n,this.sessionRecoveryName()))}},nc=zp,Kp=class extends ge{constructor(r,n){super(r.logger),this.whenState=o=>ge.prototype.whenState.call(this,o,this.state),this.ably=r,this.connectionManager=new nc(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()}},Jp=Kp,rc=class Md extends Ea{constructor(n){var o,l,u,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=Md.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=(l=(o=this.options.plugins)==null?void 0:o.RealtimePresence)!=null?l:null,this._liveObjectsPlugin=(f=(u=this.options.plugins)==null?void 0:u.LiveObjects)!=null?f:null,this.connection=new Jp(this,this.options),this._channels=new Qp(this),this.options.autoConnect!==!1&&this.connect()}static transportImplementationsFromPlugins(n){let o={};return n?.WebSocketTransport&&(o[be.WebSocket]=n.WebSocketTransport),n?.XHRPolling&&(o[be.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()}};rc.EventEmitter=ge;var Yp=rc,Qp=class extends ge{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 Us(this.all,!0)){let o=this.all[n];o.properties.channelSerial&&(r[n]=o.properties.channelSerial)}return r}recoverChannels(r){for(let n of Us(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"],u=o[r];for(let f in this.all){let y=this.all[f];l.includes(y.state)&&y.notifyState(u,n)}}get(r,n){r=String(r);let o=this.all[r];if(!o)o=this.all[r]=new as(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=qs(n.filter),u=Yo(r);r=`[filter=${l}${u.qualifierParam}]${u.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]}},Xp=Yp;function Zp(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 pr=class extends ge{constructor(r,n,o=Zp){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 u=n[l];u.clientId==r&&u.action!="absent"&&o.push(u)}return o}list(r){let n=this.map,o=r&&r.clientId,l=r&&r.connectionId,u=[];for(let f in n){let y=n[f];y.action!=="absent"&&(o&&o!=y.clientId||l&&l!=y.connectionId||u.push(y))}return u}put(r){(r.action==="enter"||r.action==="update")&&(r=Je.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=Je.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=ts(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(jo(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 eg(r){return r.channel.client.auth.clientId}function gr(r){let n=r.channel.client,o=n.auth.clientId;return(!o||o==="*")&&n.connection.state==="connected"}var tg=class extends ge{constructor(r){super(r.logger),this.channel=r,this.syncComplete=!1,this.members=new pr(this,n=>n.clientId+":"+n.connectionId),this._myMembers=new pr(this,n=>n.clientId),this.subscriptions=new ge(this.logger),this.pendingPresence=[]}async enter(r){if(gr(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(gr(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 u=this.channel;if(!u.connectionManager.activeState())throw u.connectionManager.getError();d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence."+l+"Client()","channel = "+u.name+", id = "+r+", client = "+(n||"(implicit) "+eg(this)));let f=Je.fromData(o);f.action=l,r&&(f.id=r),n&&(f.clientId=n);let y=await f.encode(u.channelOptions);switch(u.state){case"attached":return u.sendPresence([y]);case"initialized":case"detached":u.attach();case"attaching":return new Promise((_,S)=>{this.pendingPresence.push({presence:y,callback:I=>I?S(I):_()})});default:{let _=new Ae("Unable to "+l+" presence channel while in "+u.state+" state",90001);throw _.code=90001,_}}}async leave(r){if(gr(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=Je.fromData(n);l.action="leave",r&&(l.clientId=r);let u=await l.encode(o.channelOptions);switch(o.state){case"attached":return o.sendPresence([u]);case"attaching":return new Promise((f,y)=>{this.pendingPresence.push({presence:u,callback:_=>_?y(_):f()})});case"initialized":case"failed":throw new Ae("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(u){return r?u.list(r):u.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,u,f=this.members,y=this._myMembers,_=[],S=this.channel.connectionManager.connectionId;n&&(this.members.startSync(),o&&(u=o.match(/^[\w-]+:(.*)$/))&&(l=u[1]));for(let I of r)switch(I.action){case"leave":f.remove(I)&&_.push(I),I.connectionId===S&&!I.isSynthesized()&&y.remove(I);break;case"enter":case"present":case"update":f.put(I)&&_.push(I),I.connectionId===S&&y.put(I);break}n&&!l&&(f.endSync(),this.channel.syncChannelSerial=null);for(let I=0;I<_.length;I++){let U=_[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=[],u=ca.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),u.push(y.callback)}this.channel.sendPresence(l).then(()=>u()).catch(f=>u(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 = "+ne(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 u=l.connectionId===n?l.id:void 0;this._enterOrUpdateClient(u,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 = "+ne(f));let _=new lr(this.channel.state,this.channel.state,!0,!1,y);this.channel.emit("update",_)})}}_synthesizeLeaves(r){let n=this.subscriptions;r.forEach(function(o){let l=Je.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=as.processListenerArgs(r),o=n[0],l=n[1],u=this.channel;if(u.state==="failed")throw x.fromValues(u.invalidStateError());this.subscriptions.on(o,l),u.channelOptions.attachOnSubscribe!==!1&&await u.attach()}unsubscribe(...r){let n=as.processListenerArgs(r),o=n[0],l=n[1];this.subscriptions.off(o,l)}},sg=tg,ng=be.WebSocket;function rg(r){return!!r.on}var ig=class extends xt{constructor(r,n,o){super(r,n,o),this.shortName=ng,o.heartbeats=L.Config.useProtocolHeartbeats,this.wsHost=o.host}static isAvailable(){return!!L.Config.WebSocket}createWebSocket(r,n){return this.uri=r+ss(n),new L.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.connect()","starting"),xt.prototype.connect.call(this);let r=this,n=this.params,o=n.options,u=(o.tls?"wss://":"ws://")+this.wsHost+":"+K.getPort(o)+"/";d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.connect()","uri: "+u),Re(this.auth.getAuthParams(),function(f,y){if(r.isDisposed)return;let _="";for(let I in y)_+=" "+I+": "+y[I]+";";if(d.logAction(r.logger,d.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+_+" err: "+f),f){r.disconnect(f);return}let S=n.getConnectParams(y);try{let I=r.wsConnection=r.createWebSocket(u,S);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)},rg(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(Ap(r,this.connectionManager.realtime._MsgPack,this.params.format))}catch(o){let l="Exception from ws connection when trying to send: "+ne(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(Rp(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,u=new x(l,80003,400);d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onWsClose()",l),this.finish("disconnected",u)}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()}))}},ic=ig,og=class{static subscribeFilter(r,n,o){let l=u=>{var f,y,_,S,I,U;let D={name:u.name,refTimeserial:(y=(f=u.extras)==null?void 0:f.ref)==null?void 0:y.timeserial,refType:(S=(_=u.extras)==null?void 0:_.ref)==null?void 0:S.type,isRef:!!((U=(I=u.extras)==null?void 0:I.ref)!=null&&U.timeserial),clientId:u.clientId};Object.entries(n).find(([G,C])=>C!==void 0?D[G]!==C:!1)||o(u)};this.addFilteredSubscription(r,n,o,l),r.subscriptions.on(l)}static addFilteredSubscription(r,n,o,l){var u;if(r.filteredSubscriptions||(r.filteredSubscriptions=new Map),r.filteredSubscriptions.has(o)){let f=r.filteredSubscriptions.get(o);f.set(n,((u=f?.get(n))==null?void 0:u.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 _;let S=y.get(n);return y.delete(n),y.size===0&&((_=r.filteredSubscriptions)==null||_.delete(f)),S}).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,_)=>y.concat(..._),[]);return r.filteredSubscriptions.delete(o),f}let u=l.get(n);return l.delete(n),u||[]}},Ie=class Eo extends Xp{constructor(n){var o;let l=Eo._MsgPack;if(!l)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(K.objectifyOptions(n,!0,"Realtime",d.defaultLogger,A(k({},$a),{Crypto:(o=Eo.Crypto)!=null?o:void 0,MsgPack:l,RealtimePresence:{RealtimePresence:sg,PresenceMessage:Je,WirePresenceMessage:is},Annotations:{Annotation:Mt,WireAnnotation:It,RealtimeAnnotations:ur,RestAnnotations:Fs},WebSocketTransport:ic,MessageInteractions:og})))}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=es,Ie.ConnectionManager=nc,Ie.ProtocolMessage=Ip,Ie._Crypto=null,Ie.Message=Ha,Ie.PresenceMessage=Ga,Ie.Annotation=za,Ie._MsgPack=null,Ie._Http=tr,Ie._PresenceMap=pr,Ie._MessageEncoding=$s;var oc=Ie,ac=Y(q("crypto")),ag=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 ac.default.createHash("SHA256").update(n).digest()}hmacSha256(r,n){let o=this.toBuffer(r),l=this.toBuffer(n);return ac.default.createHmac("SHA256",l).update(o).digest()}},cc=new ag,mr=Y(q("crypto")),cg=Y(q("util")),lg=function(r){var n="aes",o=256,l="cbc",u=16;async function f(j){return cg.default.promisify(mr.default.randomBytes)(j)}function y(j){return j+u&-u}function _(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 S(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 G{constructor(H,V,F,te){this.algorithm=H,this.keyLength=V,this.mode=F,this.key=te,this.iv=null}}function C(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(S(H.key)):H.key instanceof ArrayBuffer?V=Buffer.from(H.key):V=H.key;var F=H.algorithm||n,te=V.length*8,Te=H.mode||l,Ce=new G(F,te,Te,V);if(H.keyLength&&H.keyLength!==Ce.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+H.keyLength+" was specified, but the key actually has length "+Ce.keyLength);return _(Ce),Ce}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 F,te=C(H)?H:this.getDefaultParams(H);return{cipherParams:te,cipher:new P(te,(F=H.iv)!=null?F:null,V)}}}R.CipherParams=G;class P{constructor(H,V,F){this.logger=F,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=mr.default.createCipheriv(this.algorithm,this.key,V));var F=r.toBuffer(H),te=F.length,Te=y(te),Ce=this.encryptCipher.update(Buffer.concat([F,U[Te-te]])),Ye=Buffer.concat([V,Ce]);return Ye}async decrypt(H){var V=mr.default.createDecipheriv(this.algorithm,this.key,H.slice(0,u)),F=V.update(H.slice(u)),te=V.final();return te&&te.length&&(F=Buffer.concat([F,te])),F}async getIv(){if(this.iv){var H=this.iv;return this.iv=null,H}var V=await f(u);return this.encryptCipher?this.encryptCipher.update(V):V}}return R},lc=Y(Gn()),ug=Y(q("http")),hg=Y(q("https")),uc=[],ls,dg=(ls=class{constructor(r){this.agent=null,this.supportsAuthHeaders=!0,this.supportsLinkHeaders=!0,this.checkConnectivity=async()=>{var n,o,l,u,f;if((n=this.client)!=null&&n.options.disableConnectivityCheck)return!0;let y=((o=this.client)==null?void 0:o.options.connectivityCheckUrl)||K.connectivityCheckUrl,_=(u=(l=this.client)==null?void 0:l.options.connectivityCheckParams)!=null?u:null,S=!((f=this.client)!=null&&f.options.connectivityCheckUrl),{error:I,statusCode:U,body:D}=await this.doUri(de.Get,y,null,null,_);return!I&&!S?If(U):!I&&D?.toString().trim()==="yes"},this.client=r??null}async doUri(r,n,o,l,u){var f;let y=this.client&&this.client.options.restAgentOptions||K.restAgentOptions,_={headers:o||void 0,responseType:"buffer"};if(!this.agent){let S=(f=uc.find(I=>Qn(y,I.options)))==null?void 0:f.agents;S?this.agent=S:(this.agent={http:new ug.default.Agent(y),https:new hg.default.Agent(y)},uc.push({options:y,agents:this.agent}))}l&&(_.body=l),u&&(_.searchParams=u),_.agent=this.agent,_.url=n,_.timeout={request:(this.client&&this.client.options.timeouts||K.TIMEOUTS).httpRequestTimeout},_.retry={limit:0};try{let S=await lc.default[r](_);return this._handler(null,S,S.body)}catch(S){return S instanceof lc.default.HTTPError?this._handler(null,S.response,S.response.body):this._handler(S)}}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 u=n.statusCode,f=n.headers;if(u>=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:ns("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: "+u+" body was: "+L.Config.inspect(o),Number(f["x-ably-errorcode"]),u),body:o,headers:f,unpacked:!0,statusCode:u}}return{error:null,body:o,headers:f,unpacked:!1,statusCode:u}}},ls.methods=[de.Get,de.Delete,de.Post,de.Put,de.Patch],ls.methodsWithoutBody=[de.Get,de.Delete],ls.methodsWithBody=[de.Post,de.Put,de.Patch],ls),fg=dg,pg=Y(q("crypto")),gg=Y(fn()),yr=Y(q("util")),mg={agent:"nodejs/"+process.versions.node,logTimestamps:!0,userAgent:null,binaryType:"nodebuffer",WebSocket:gg.default,useProtocolHeartbeats:!1,supportsBinary:!0,preferBinary:!0,nextTick:process.nextTick,inspect:yr.default.inspect,stringByteSize:Buffer.byteLength,inherits:yr.default.inherits,addEventListener:null,getRandomArrayBuffer:async function(r){return yr.default.promisify(pg.default.randomBytes)(r)}},yg=mg,hc=(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))(hc||{}),ut=hc;function _g(r){let n=[80015,80017,80030];return r.code?Ke.isTokenErr(r)?!1:n.includes(r.code)?!0:r.code>=4e4&&r.code<5e4:!1}function _r(r){return _g(r)?[Se({action:z.ERROR,error:r})]:[Se({action:z.DISCONNECTED,error:r})]}var bg=class extends xt{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"),xt.prototype.connect.call(this);let r=this.params,n=r.options,o=r.host||n.primaryDomain,l=K.getPort(n),u=n.tls?"https://":"http://";this.baseUri=u+o+":"+l+"/comet/";let f=this.baseUri+"connect";d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","uri: "+f),Re(this.auth.getAuthParams(),(y,_)=>{if(y){this.disconnect(y);return}if(this.isDisposed)return;this.authParams=_;let S=this.params.getConnectParams(_);"stream"in S&&(this.stream=S.stream),d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","connectParams:"+ss(S));let I=!1,U=this.recvRequest=this.createRequest(f,null,S,null,this.stream?ut.REQ_RECV_STREAM:ut.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(_r(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,ut.REQ_SEND);o.on("complete",l=>{l&&(d.logAction(this.logger,d.LOG_ERROR,"CometTransport.request"+(r?"Close()":"Disconnect()"),"request returned err = "+ne(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",_t.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;xt.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),ut.REQ_SEND);n.on("complete",(o,l)=>{if(o&&d.logAction(this.logger,d.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+ne(o)),this.sendRequest=null,o){o.code?this.onData(_r(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?ut.REQ_RECV_STREAM:ut.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(_r(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(or(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}},dc=bg,fc=Y(q("http")),pc=Y(q("https")),vg=Y(q("url")),wg=Y(q("util")),Cg=function(){},Eg=be.Comet,kg=class extends dc{constructor(r,n,o){super(r,n,o),this.httpAgent=null,this.httpsAgent=null,this.pendingRequests=0,this.shortName=Eg}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?pc.default:fc.default).Agent({keepAlive:!0})),o}dispose(){var r=this;this.onceNoPending(function(){r.httpAgent&&r.httpAgent.destroy(),r.httpsAgent&&r.httpsAgent.destroy()}),dc.prototype.dispose.call(this)}request(r,n,o,l,u){var f=this.createRequest(r,n,o,l);return f.once("complete",u),f.exec(),f}createRequest(r,n,o,l,u){return new Og(r,n,o,l,u,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)}},Og=class extends ge{constructor(r,n,o,l,u,f,y,_){super(_.logger),typeof r=="string"&&(r=vg.default.parse(r));var S=r.protocol=="https:";this.client=S?pc.default:fc.default,this.requestMode=u,this.timeouts=y,this.transport=_,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+ss(o),method:I,headers:n};_&&(D.agent=_.getAgent(S))}exec(){var r=this.requestMode==ut.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(u){u=new Ae("Request error: "+u.message,null,400),clearTimeout(o),n.timer=null,n.complete(u)}),l.on("response",function(u){clearTimeout(o),n.timer=null;var f=u.statusCode;if(f==rs.NoContent){u.resume(),n.complete();return}u.on("error",n.onResError=function(y){y=new Ae("Response error: "+y.message,null,400),n.complete(y)}),n.res=u,n.requestMode==ut.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 u="Malformed response body from server: "+f.message;d.logAction(n.logger,d.LOG_ERROR,"NodeCometTransport.Request.readStream()",u),n.complete(new Ae(u,null,400));return}n.emit("data",l)}r.on("data",this.ondata=function(l){var u=String(l).split(`
|
|
45
|
+
`),f=n.chunks;u.length>1&&f.length>0&&(f.push(u.shift()),n.chunks=[],o(f.join("")));var y=u.pop();y.length&&n.chunks.push(y),u.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),u=r.statusCode;try{l=JSON.parse(String(l))}catch(_){var f="Malformed response body from server: "+_.message;d.logAction(o.logger,d.LOG_ERROR,"NodeCometTransport.Request.readFully()",f),o.complete(new Ae(f,null,400));return}if(u<400||Array.isArray(l)){o.complete(null,l);return}var y=l.error&&x.fromValues(l.error);y||(y=new Ae("Error response received from server: "+u+", body was: "+wg.default.inspect(l),null,u)),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",Cg),n.abort(),this.req=null),this.complete({statusCode:400,code:80003,message:"Cancelled"})}},Sg=kg,Tg={order:[be.Comet],bundledImplementations:{[be.WebSocket]:ic,[be.Comet]:Sg}},Ag={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[be.WebSocket],restAgentOptions:{maxSockets:40,keepAlive:!0}},Rg=Ag,Pg=of(),gc=lg(cc);L.Crypto=gc,L.BufferUtils=cc,L.Http=fg,L.Config=yg,L.Transports=Tg,L.WebStorage=null;for(let r of[Za,oc])r.Crypto=gc,r._MsgPack=Pg;if(d.initLogHandlers(),L.Defaults=Rf(Rg),L.Config.agent&&(L.Defaults.agent+=" "+L.Config.agent),i.exports={ErrorInfo:x,Rest:Za,Realtime:oc,msgpack:null,makeProtocolMessageFromDeserialized:Pp},typeof i.exports=="object"&&typeof t=="object"){var Ig=(r,n,o,l)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of Object.getOwnPropertyNames(n))!Object.prototype.hasOwnProperty.call(r,u)&&u!==o&&Object.defineProperty(r,u,{get:()=>n[u],enumerable:!(l=Object.getOwnPropertyDescriptor(n,u))||l.enumerable});return r};i.exports=Ig(i.exports,t)}return i.exports})});var Pc=br(Rc(),1),{program:hs,createCommand:Dw,createArgument:Uw,createOption:jw,CommanderError:qw,InvalidArgumentError:Bw,InvalidOptionArgumentError:$w,Command:Hw,Argument:Gw,Option:Fw,Help:Ww}=Pc.default;var Yd=br(Uc(),1);import{resolve as Jd}from"path";import{existsSync as Tw}from"fs";function mm(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 h=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",v=s.streamProgress??process.env.STREAM_PROGRESS!=="false",w=s.conversationOnly??process.env.CONVERSATION_ONLY==="true",E=s.autoCommit??process.env.AUTO_COMMIT==="true",O=s.autoPush??process.env.AUTO_PUSH==="true",T=s.autoSchemaMigration??process.env.AUTO_SCHEMA_MIGRATION!=="false",k=s.idleTimeoutMinutes??(process.env.IDLE_TIMEOUT_MINUTES?parseInt(process.env.IDLE_TIMEOUT_MINUTES,10):0),A=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:h,sseEnabled:p,clientRequestTimeoutMs:c,workingDirectory:g,useAgentSdk:m,streamProgress:v,conversationOnly:w,autoCommit:E,autoPush:O,autoSchemaMigration:T,idleTimeoutMinutes:k,healthPort:A}}function jc(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:mm(s),sources:e}}function Ee(s){switch(s){case"cli":return"[cli]";case"env":return"[env]";case"default":return"[default]"}}var Ys=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(),h;try{let p=JSON.parse(c);h=p.error||p.message||c}catch{h=c}throw new Error(`API error (${a.status}): ${h}`)}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})})}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){return this.request(`/api/client-requests/${e}/analysis`,{method:"POST",body:JSON.stringify({monitorId:t,analysis:i,processingTimeMs:a})})}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,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 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){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})})}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 Qs}from"child_process";import{existsSync as qc,writeFileSync as Bc,unlinkSync as $c}from"fs";import{homedir as ym,tmpdir as Hc}from"os";import{join as Ur}from"path";function Xs(){let s=[Ur(ym(),".claude","local","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude"];for(let e of s)if(qc(e))return e;return"claude"}var ve=null;function _m(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
|
+
`)}async function Gc(s,e){let t=_m(s);return ve||(ve=Xs()),new Promise(i=>{let a="",c="",h=!1,p=!1,g=Qs(ve,["--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(()=>{h=!0,p=!0,g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},5e3)},e);g.stdout?.on("data",v=>{a+=v.toString()}),g.stderr?.on("data",v=>{c+=v.toString()}),g.on("close",v=>{if(clearTimeout(m),h){i({success:!1,output:a,error:"Process timed out",timedOut:!0});return}let w=a.includes("TASK_COMPLETE")&&!a.includes("TASK_BLOCKED");if(v!==0&&!p){i({success:!1,output:a,error:c||`Process exited with code ${v}`,timedOut:!1});return}let E=a.match(/TASK_BLOCKED:\s*(.+)/i);if(E){i({success:!1,output:a,error:`Task blocked: ${E[1]}`,timedOut:!1});return}i({success:w,output:a,error:w?void 0:"Task did not complete successfully",timedOut:!1})}),g.on("error",v=>{clearTimeout(m),i({success:!1,output:a,error:`Failed to spawn claude: ${v.message}`,timedOut:!1})})})}async function Fc(){return ve=Xs(),ve&&ve!=="claude"&&qc(ve)?(console.log(`Found Claude CLI at: ${ve}`),!0):new Promise(s=>{let e=Qs(ve,["--version"],{stdio:["pipe","pipe","pipe"]});e.on("close",t=>{s(t===0)}),e.on("error",()=>{s(!1)}),setTimeout(()=>{e.kill(),s(!1)},5e3)})}function bm(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
|
+
`)}function vm(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 Wc(s,e,t={}){let i=bm(s),a=t.verbose??!0;return a&&(console.log("[Claude] Starting analysis..."),console.log("[Claude] Prompt length:",i.length,"characters")),ve||(ve=Xs()),new Promise(c=>{let h="",p="",g=!1,m=!1;a&&console.log("[Claude] Spawning Claude CLI via shell with temp file...");let v=Ur(Hc(),`claude-prompt-${Date.now()}.txt`);Bc(v,i,"utf-8");let w=`cat "${v}" | ${ve} --print --dangerously-skip-permissions`;a&&(console.log("[Claude] Working directory:",process.cwd()),console.log("[Claude] Temp file:",v),console.log("[Claude] Running via shell..."));let E=Qs("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:",E.pid),E.stdin?.end();let O=()=>{try{$c(v),a&&console.log("[Claude] Temp file cleaned up")}catch{}},T=setTimeout(()=>{g=!0,m=!0,console.log("[Claude] Timeout reached, killing process..."),E.kill("SIGTERM"),setTimeout(()=>{E.killed||E.kill("SIGKILL")},5e3)},e);E.stdout?.on("data",k=>{let A=k.toString();h+=A,a&&process.stdout.write(A)}),E.stderr?.on("data",k=>{let A=k.toString();p+=A,a&&process.stderr.write(`[Claude stderr] ${A}`)}),E.on("close",(k,A)=>{clearTimeout(T),O(),a&&(console.log(""),console.log(`[Claude] Process exited with code ${k}, signal ${A}`),console.log(`[Claude] Output length: ${h.length} characters`),console.log(`[Claude] Error output length: ${p.length} characters`),p&&console.log(`[Claude] Stderr: ${p.substring(0,500)}`));let N=vm(h);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:h,timedOut:!1});return}if(g){c({success:!1,output:h,error:"Process timed out without producing valid output",timedOut:!0});return}if(k!==0&&!m){c({success:!1,output:h,error:p||`Process exited with code ${k}`,timedOut:!1});return}if(!N){c({success:!1,output:h,error:"Failed to parse analysis JSON from output",timedOut:!1});return}if(!N.summary||!Array.isArray(N.suggestedTasks)){c({success:!1,output:h,error:"Invalid analysis structure - missing required fields",timedOut:!1});return}c({success:!0,analysis:N,output:h,timedOut:!1})}),E.on("error",k=>{clearTimeout(T),console.error("[Claude] Spawn error:",k),c({success:!1,output:h,error:`Failed to spawn claude: ${k.message}`,timedOut:!1})}),E.on("spawn",()=>{a&&console.log("[Claude] Process spawned successfully")})})}function wm(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
|
|
|
49
49
|
[... truncated ...]`):e.push(t),e.push("")}return e.push("---"),e.push(""),e.push("## Instructions"),e.push(""),e.push("Please work on this task. Implement the required changes according to the acceptance criteria."),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(`
|
|
50
|
-
`)}async function Vc(s,e,t={}){let i=wm(s),a=t.verbose??!0,c=t.workingDirectory||process.cwd();return a&&(console.log("[Claude] Starting backlog task processing..."),console.log("[Claude] Prompt length:",i.length,"characters"),console.log("[Claude] Working directory:",c)),
|
|
51
|
-
`)}function zc(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={}){let{timeoutMs:t=3e5,verbose:i=!0,workingDirectory:a,onEvent:c}=e,h=a||process.cwd(),p=Em(s),g=Date.now(),m="",v=!1;i&&(console.log("[Agent] Starting analysis with Claude Agent SDK..."),console.log("[Agent] Prompt length:",p.length,"characters"),console.log("[Agent] Working directory:",h),console.log("[Agent] Model: claude-opus-4-5-20250929"));let w=new AbortController,E=setTimeout(()=>{v=!0,w.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),O=(
|
|
50
|
+
`)}async function Vc(s,e,t={}){let i=wm(s),a=t.verbose??!0,c=t.workingDirectory||process.cwd();return a&&(console.log("[Claude] Starting backlog task processing..."),console.log("[Claude] Prompt length:",i.length,"characters"),console.log("[Claude] Working directory:",c)),ve||(ve=Xs()),a&&console.log("[Claude] Claude path:",ve),new Promise(h=>{let p="",g="",m=!1,v=!1;a&&console.log("[Claude] Spawning Claude CLI via shell with temp file...");let w=Ur(Hc(),`claude-task-${Date.now()}.txt`);Bc(w,i,"utf-8");let E=`cat "${w}" | ${ve} --print --dangerously-skip-permissions`;a&&(console.log("[Claude] Temp file:",w),console.log("[Claude] Running via shell..."));let O=Qs("sh",["-c",E],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:c},cwd:c});a&&console.log("[Claude] Shell process started with PID:",O.pid);let T=0,k=setInterval(()=>{if(a&&!m){let Q=Math.floor((Date.now()-A)/1e3);p.length===T&&console.log(`[Claude] Still running... ${Q}s elapsed, ${p.length} bytes output, waiting for response...`),T=p.length}},3e4),A=Date.now();O.stdin?.end();let N=()=>{try{$c(w),a&&console.log("[Claude] Temp file cleaned up")}catch{}},W=setTimeout(()=>{m=!0,v=!0,clearInterval(k),console.log("[Claude] Timeout reached, killing process..."),console.log(`[Claude] Output collected: ${p.length} characters`),p.length>0&&console.log(`[Claude] Last 500 chars of output: ${p.slice(-500)}`),g.length>0&&console.log(`[Claude] Stderr: ${g.substring(0,500)}`),O.kill("SIGTERM"),setTimeout(()=>{O.killed||O.kill("SIGKILL")},5e3)},e);O.stdout?.on("data",Q=>{let se=Q.toString();p+=se,a&&process.stdout.write(se)}),O.stderr?.on("data",Q=>{let se=Q.toString();g+=se,a&&process.stderr.write(`[Claude stderr] ${se}`)}),O.on("close",(Q,se)=>{clearTimeout(W),clearInterval(k),N(),a&&(console.log(""),console.log(`[Claude] Process exited with code ${Q}, signal ${se}`),console.log(`[Claude] Output length: ${p.length} characters`),g&&console.log(`[Claude] Stderr: ${g.substring(0,1e3)}`));let Y=p.includes("TASK_COMPLETE"),X=p.match(/TASK_BLOCKED:\s*(.+)/);if(m&&!Y){h({success:!1,output:p,error:"Process timed out",timedOut:!0});return}if(X){h({success:!1,output:p,error:`Task blocked: ${X[1]}`,timedOut:!1});return}if(Q!==0&&!v){h({success:!1,output:p,error:g||`Process exited with code ${Q}`,timedOut:!1});return}h({success:!0,output:p,timedOut:!1})}),O.on("error",Q=>{clearTimeout(W),clearInterval(k),N(),console.error("[Claude] Spawn error:",Q),h({success:!1,output:p,error:`Failed to spawn claude: ${Q.message}`,timedOut:!1})}),O.on("spawn",()=>{a&&console.log("[Claude] Process spawned successfully")})})}import{query as jr}from"@anthropic-ai/claude-agent-sdk";function Cm(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 qr(s){let e={type:s.type,timestamp:s.timestamp};switch(s.type){case"tool_start":{let t=s.data,{message:i,emoji:a}=Cm(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 Em(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(`
|
|
51
|
+
`)}function zc(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={}){let{timeoutMs:t=3e5,verbose:i=!0,workingDirectory:a,onEvent:c}=e,h=a||process.cwd(),p=Em(s),g=Date.now(),m="",v=!1;i&&(console.log("[Agent] Starting analysis with Claude Agent SDK..."),console.log("[Agent] Prompt length:",p.length,"characters"),console.log("[Agent] Working directory:",h),console.log("[Agent] Model: claude-opus-4-5-20250929"));let w=new AbortController,E=setTimeout(()=>{v=!0,w.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),O=(T,k)=>{c&&c({type:T,timestamp:Date.now(),data:k})};O("session_start",{prompt:p.substring(0,200),cwd:h});try{let T=jr({prompt:p,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","WebSearch"],permissionMode:"acceptEdits",maxTurns:30}});for await(let k of T)switch(k.type){case"assistant":if(k.message.content){for(let N of k.message.content)if(N.type==="text")m+=N.text,i&&process.stdout.write(N.text),O("assistant_message",{text:N.text,uuid:k.uuid});else if(N.type==="thinking"){let W=N;i&&console.log(`[Agent] Thinking: ${W.thinking.substring(0,100)}...`),O("thinking",{text:W.thinking,uuid:k.uuid})}else if(N.type==="tool_use"||"name"in N){let W=N;i&&console.log(`[Agent] Tool: ${W.name}`),O("tool_start",{tool:W.name,toolUseId:W.id,input:W.input})}}break;case"user":if(k.message.content){for(let N of k.message.content)if(typeof N=="object"&&N!==null&&"type"in N&&N.type==="tool_result"){let W=N;O("tool_end",{toolUseId:W.tool_use_id,isError:W.is_error||!1,hasContent:!!W.content})}}break;case"result":i&&(console.log(""),console.log(`[Agent] Completed in ${k.duration_ms}ms`),console.log(`[Agent] Cost: $${k.total_cost_usd?.toFixed(4)||"N/A"}`)),clearTimeout(E);let A=zc(m);if(A&&A.summary&&Array.isArray(A.suggestedTasks))return O("result",{success:!0,analysis:A,costUsd:k.total_cost_usd,usage:k.usage}),{success:!0,analysis:A,output:m,timedOut:!1,totalCostUsd:k.total_cost_usd,usage:k.usage?{inputTokens:k.usage.input_tokens,outputTokens:k.usage.output_tokens}:void 0};if(k.subtype!=="success"){let N="result"in k?k.result:k.subtype;return O("error",{error:k.subtype,result:N}),{success:!1,output:m,error:`Agent error: ${k.subtype} - ${N}`,timedOut:!1,totalCostUsd:k.total_cost_usd}}return{success:!1,output:m,error:"Failed to parse analysis JSON from output",timedOut:!1,totalCostUsd:k.total_cost_usd}}return clearTimeout(E),{success:!1,output:m,error:"Query stream ended without result",timedOut:v}}catch(T){clearTimeout(E);let k=T instanceof Error?T.message:String(T);i&&console.error("[Agent] Error:",k),O("error",{error:k});let A=zc(m);return A&&A.summary&&Array.isArray(A.suggestedTasks)?(i&&console.log("[Agent] Got valid output despite error - treating as success"),{success:!0,analysis:A,output:m,timedOut:!1}):{success:!1,output:m,error:v?"Process timed out":k,timedOut:v}}}function km(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)+`
|
|
52
52
|
|
|
53
53
|
[... truncated ...]`):e.push(t),e.push("")}return e.push("---"),e.push(""),e.push("## Instructions"),e.push(""),e.push("Please work on this task. Implement the required changes according to the acceptance criteria."),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(`
|
|
54
|
-
`)}async function Jc(s,e={}){let{timeoutMs:t=12e5,verbose:i=!0,workingDirectory:a,onEvent:c}=e,h=a||process.cwd(),p=km(s),g=Date.now(),m="",v=!1;i&&(console.log("[Agent] Starting backlog task with Claude Agent SDK..."),console.log("[Agent] Task:",s.title),console.log("[Agent] Working directory:",h),console.log("[Agent] Model: claude-opus-4-5-20250929"));let w=new AbortController,E=setTimeout(()=>{v=!0,w.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),O=(
|
|
55
|
-
`)}function Tm(s,e){let t=["# BUILD MODE - Read-Only Task Creation","","## CRITICAL: THIS IS A READ-ONLY SESSION","","**You CANNOT make any changes to the codebase in this mode.**","","Build mode is strictly read-only:","- You
|
|
56
|
-
`)}function Am(s,e="work"){let t=Om(s.description);return e==="planning"?Sm(s,t):Tm(s,t)}var Rm=["LOW","MEDIUM","HIGH","URGENT"],Pm=["FEATURE","BUG","ENHANCEMENT","DOCUMENTATION","DESIGN","TECHNICAL_DEBT"];function Im(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 h=a[1].trim();console.log(`[Agent] Found task block #${c}, parsing JSON...`);try{let p=h.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 v=Rm.includes(m.priority?.toUpperCase?.())?m.priority.toUpperCase():"MEDIUM",w=Pm.includes(m.type?.toUpperCase?.())?m.type.toUpperCase():"FEATURE",E=Array.isArray(m.acceptanceCriteria)?m.acceptanceCriteria.filter(k=>typeof k=="string").map(k=>k.trim()):[],O=Math.max(0,Number(m.estimatedHours)||4),A=Math.min(1,Math.max(0,Number(m.aiConfidence||m.confidence)||.8));console.log(`[Agent] Parsed task #${c}: "${m.title}" (${v}, ${w}, ${O}h)`),e.push({title:String(m.title).trim(),description:String(m.description||"").trim(),acceptanceCriteria:E,estimatedHours:O,priority:v,type:w,technicalNotes:m.technicalNotes?String(m.technicalNotes).trim():void 0,aiConfidence:A})}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):",h.substring(0,500))}}return console.log(`[Agent] parseTasksFromOutput: returning ${e.length} valid tasks (found ${c} total blocks)`),e}async function Zc(s,e={}){let{timeoutMs:t=3e5,verbose:i=!0,workingDirectory:a,onEvent:c,mode:h="work"}=e,p=a||process.cwd(),g=Am(s,h),m="",v=!1;i&&(console.log("[Agent] Starting conversational session..."),console.log("[Agent] Mode:",h),console.log("[Agent] Working directory:",p));let w=new AbortController,E=setTimeout(()=>{v=!0,w.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),O=(H,V)=>{c&&c({type:H,timestamp:Date.now(),data:V})};O("session_start",{cwd:p,mode:h});let A=["Read","Glob","Grep","WebSearch","WebFetch"],k=["Edit","Write","Bash","NotebookEdit"],T=[...A];i&&(console.log(`[Agent] Mode: ${h}, Allowed tools: ${T.join(", ")}`),console.log(`[Agent] Restricted tools (not available): ${k.join(", ")}`));let N=H=>k.includes(H)?{allowed:!1,reason:`Tool "${H}" is restricted in ${h} mode. Conversation sessions are read-only.`}:T.includes(H)?{allowed:!0}:{allowed:!1,reason:`Tool "${H}" is not in the allowed list for ${h} mode.`};try{let H=jr({prompt:g,options:{allowedTools:T,permissionMode:"acceptEdits"}});for await(let V of H)switch(V.type){case"assistant":if(V.message.content){for(let Q of V.message.content)if(Q.type==="text")m+=Q.text,i&&process.stdout.write(Q.text),O("assistant_message",{text:Q.text,uuid:V.uuid});else if(Q.type==="thinking"){let te=Q;i&&console.log(`[Agent] Thinking: ${te.thinking.substring(0,100)}...`),O("thinking",{text:te.thinking,uuid:V.uuid})}else if(Q.type==="tool_use"||"name"in Q){let te=Q,ge=N(te.name);ge.allowed||(console.error(`[Agent] SECURITY VIOLATION: ${ge.reason}`),console.error(`[Agent] Tool attempt details: ${JSON.stringify({tool:te.name,mode:h,toolUseId:te.id,timestamp:new Date().toISOString()})}`),O("error",{error:ge.reason,securityViolation:!0,tool:te.name,mode:h})),i&&console.log(`[Agent] Tool: ${te.name}${ge.allowed?"":" (RESTRICTED - should not execute)"}`),O("tool_start",{tool:te.name,toolUseId:te.id,input:te.input})}}break;case"user":if(V.message.content){for(let Q of V.message.content)if(typeof Q=="object"&&Q!==null&&"type"in Q&&Q.type==="tool_result"){let te=Q;O("tool_end",{toolUseId:te.tool_use_id,isError:te.is_error||!1,hasContent:!!te.content})}}break;case"result":clearTimeout(E),i&&(console.log(""),console.log(`[Agent] Completed in ${V.duration_ms}ms`),console.log(`[Agent] Cost: $${V.total_cost_usd?.toFixed(4)||"N/A"}`));let Z=Im(m);return i&&Z.length>0&&console.log(`[Agent] Found ${Z.length} task(s) in output`),O("result",{success:!0,output:m,tasks:Z,costUsd:V.total_cost_usd}),{success:!0,output:m,tasks:Z,timedOut:!1,totalCostUsd:V.total_cost_usd}}return clearTimeout(E),{success:!1,output:m,tasks:[],error:"Query stream ended without result",timedOut:v}}catch(H){clearTimeout(E);let V=H instanceof Error?H.message:String(H);return i&&console.error("[Agent] Error:",V),O("error",{error:V}),{success:!1,output:m,tasks:[],error:v?"Process timed out":V,timedOut:v}}}var Nd=br(xd(),1),Fn=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 Nd.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=h=>{h.current==="connected"?(clearTimeout(a),this.ably?.connection.off(c),t()):h.current==="failed"&&(clearTimeout(a),this.ably?.connection.off(c),i(new Error(`Connection failed: ${h.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 ew}from"child_process";import{promisify as tw}from"util";var Ld=tw(ew);async function it(s,e){try{return await Ld(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 sw(s){try{return await it("git rev-parse --is-inside-work-tree",s),!0}catch{return!1}}async function Oo(s){let{stdout:e}=await it("git status --porcelain",s),t=[],i=[],a=[],c=e.trim().split(`
|
|
57
|
-
`).filter(Boolean);for(let h of c){let p=h[0],g=h[1],m=h.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 nw(s){let{stdout:e}=await
|
|
54
|
+
`)}async function Jc(s,e={}){let{timeoutMs:t=12e5,verbose:i=!0,workingDirectory:a,onEvent:c}=e,h=a||process.cwd(),p=km(s),g=Date.now(),m="",v=!1;i&&(console.log("[Agent] Starting backlog task with Claude Agent SDK..."),console.log("[Agent] Task:",s.title),console.log("[Agent] Working directory:",h),console.log("[Agent] Model: claude-opus-4-5-20250929"));let w=new AbortController,E=setTimeout(()=>{v=!0,w.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),O=(T,k)=>{c&&c({type:T,timestamp:Date.now(),data:k})};O("session_start",{task:s.title,cwd:h});try{let T=jr({prompt:p,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","Write"],permissionMode:"acceptEdits",maxTurns:30}});for await(let k of T)switch(k.type){case"assistant":if(k.message.content){for(let W of k.message.content)if(W.type==="text")m+=W.text,i&&process.stdout.write(W.text);else if("name"in W){let Q=W;i&&console.log(`[Agent] Tool: ${Q.name}`),O("tool_start",{tool:Q.name,toolUseId:Q.id,input:Q.input})}}break;case"result":clearTimeout(E),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 A=m.includes("TASK_COMPLETE"),N=m.match(/TASK_BLOCKED:\s*(.+)/);return N?{success:!1,output:m,error:`Task blocked: ${N[1]}`,timedOut:!1,totalCostUsd:k.total_cost_usd}:{success:A||k.subtype==="success",output:m,timedOut:!1,totalCostUsd:k.total_cost_usd}}return clearTimeout(E),{success:!1,output:m,error:"Query stream ended without result",timedOut:v}}catch(T){clearTimeout(E);let k=T instanceof Error?T.message:String(T);return i&&console.error("[Agent] Error:",k),O("error",{error:k}),{success:!1,output:m,error:v?"Process timed out":k,timedOut:v}}}async function Yc(){try{return!0}catch{return!1}}function Qc(s){return s.includes("[CONVERSATIONAL SESSION]")}function Xc(s){return s.includes("MODE: PLANNING")?"planning":s.includes("MODE: BUILD")||s.includes("MODE: WORK")?"work":s.includes("[MODE: PLANNING")?"planning":"work"}function Om(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 Sm(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("## Mode Switch Suggestion"),t.push(""),t.push("When you believe the requirements are clear enough to create actionable tasks, suggest switching to Build mode by outputting:"),t.push(""),t.push("<suggest_build_mode>"),t.push("Your reasoning for why the requirements are now clear enough"),t.push("</suggest_build_mode>"),t.push(""),t.push("Only suggest this when:"),t.push("- You have a good understanding of what the user wants to accomplish"),t.push("- Key technical decisions have been discussed"),t.push("- The scope is reasonably defined"),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("- Any actual implementation happens later, after tasks are created in Build mode"),t.join(`
|
|
55
|
+
`)}function Tm(s,e){let t=["# BUILD MODE - Read-Only Task Creation","","## CRITICAL: THIS IS A READ-ONLY SESSION","","**You CANNOT make any changes to the codebase in this mode.**","","Build 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 to explore, understand, and CREATE TASK DEFINITIONS","- Actual implementation happens later, when tasks are executed separately","","---","","## YOUR ROLE","","You are helping create actionable development tasks. Your goal is to generate well-structured task definitions based on the user's requirements.","",`**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("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((i,a)=>{t.push(`${a+1}. ${i}`)}),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(""),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(""),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.")),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("When you identify work that should become a 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('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(`
|
|
56
|
+
`)}function Am(s,e="work"){let t=Om(s.description);return e==="planning"?Sm(s,t):Tm(s,t)}var Rm=["LOW","MEDIUM","HIGH","URGENT"],Pm=["FEATURE","BUG","ENHANCEMENT","DOCUMENTATION","DESIGN","TECHNICAL_DEBT"];function Im(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 h=a[1].trim();console.log(`[Agent] Found task block #${c}, parsing JSON...`);try{let p=h.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 v=Rm.includes(m.priority?.toUpperCase?.())?m.priority.toUpperCase():"MEDIUM",w=Pm.includes(m.type?.toUpperCase?.())?m.type.toUpperCase():"FEATURE",E=Array.isArray(m.acceptanceCriteria)?m.acceptanceCriteria.filter(k=>typeof k=="string").map(k=>k.trim()):[],O=Math.max(0,Number(m.estimatedHours)||4),T=Math.min(1,Math.max(0,Number(m.aiConfidence||m.confidence)||.8));console.log(`[Agent] Parsed task #${c}: "${m.title}" (${v}, ${w}, ${O}h)`),e.push({title:String(m.title).trim(),description:String(m.description||"").trim(),acceptanceCriteria:E,estimatedHours:O,priority:v,type:w,technicalNotes:m.technicalNotes?String(m.technicalNotes).trim():void 0,aiConfidence:T})}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):",h.substring(0,500))}}return console.log(`[Agent] parseTasksFromOutput: returning ${e.length} valid tasks (found ${c} total blocks)`),e}async function Zc(s,e={}){let{timeoutMs:t=3e5,verbose:i=!0,workingDirectory:a,onEvent:c,mode:h="work"}=e,p=a||process.cwd(),g=Am(s,h),m="",v=!1;i&&(console.log("[Agent] Starting conversational session..."),console.log("[Agent] Mode:",h),console.log("[Agent] Working directory:",p));let w=new AbortController,E=setTimeout(()=>{v=!0,w.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),O=(Y,X)=>{c&&c({type:Y,timestamp:Date.now(),data:X})};O("session_start",{cwd:p,mode:h});let T=["Read","Glob","Grep","WebSearch","WebFetch","Bash"],k=["Edit","Write","NotebookEdit"],A=["ls","pwd","tree","find","which","whereis","file","stat","git status","git log","git diff","git branch","git show","git blame","git remote","git tag","git stash list","git rev-parse","npm list","npm ls","npm outdated","npm view","pnpm list","pnpm ls","pnpm outdated","yarn list","yarn info","whoami","hostname","uname","date","uptime","env","printenv","wc","sort","uniq","head","tail","cat","less","more","ps","top","htop","du","df"],N=[/[;]/,/&&/,/\|\|/,/[`]/,/\$\(/,/>\s*[^&]/,/>>/,/\bsudo\b/,/\brm\b/,/\bmv\b/,/\bcp\b/,/\bmkdir\b/,/\btouch\b/,/\bchmod\b/,/\bchown\b/,/\bcurl\b.*-[dXPo]/,/\bwget\b/,/\bnpm\s+(install|i|uninstall|remove|update|publish|link)/,/\bpnpm\s+(install|i|add|remove|update|publish|link)/,/\byarn\s+(add|remove|install|upgrade|publish|link)/,/\bgit\s+(commit|push|pull|merge|rebase|reset|checkout|add|rm|stash\s+(?!list))/,/\bkill\b/,/\bpkill\b/],W=Y=>{let X=Y.trim();for(let ee of N)if(ee.test(X))return{allowed:!1,reason:"Bash command contains restricted pattern. Only read-only commands are allowed in conversation sessions."};let ce=X.split(/\s+/)[0];return A.some(ee=>{if(X.startsWith(ee+" ")||X===ee)return!0;let Ge=ee.split(" ")[0];return ce===Ge&&ee.split(" ").length===1})?{allowed:!0}:{allowed:!1,reason:`Bash command "${ce}" is not in the read-only whitelist. Only read-only commands (ls, git status, git log, etc.) are allowed in conversation sessions.`}},Q=[...T];i&&(console.log(`[Agent] Mode: ${h}, Allowed tools: ${Q.join(", ")}`),console.log(`[Agent] Restricted tools (not available): ${k.join(", ")}`));let se=(Y,X)=>{if(Y==="Bash"){let ce=X;return ce?.command?W(ce.command):{allowed:!1,reason:"Bash command is empty or missing."}}return k.includes(Y)?{allowed:!1,reason:`Tool "${Y}" is restricted in ${h} mode. Conversation sessions are read-only.`}:Q.includes(Y)?{allowed:!0}:{allowed:!1,reason:`Tool "${Y}" is not in the allowed list for ${h} mode.`}};try{let Y=jr({prompt:g,options:{allowedTools:Q,permissionMode:"acceptEdits",maxTurns:30}});for await(let X of Y)switch(X.type){case"assistant":if(X.message.content){for(let ie of X.message.content)if(ie.type==="text")m+=ie.text,i&&process.stdout.write(ie.text),O("assistant_message",{text:ie.text,uuid:X.uuid});else if(ie.type==="thinking"){let ee=ie;i&&console.log(`[Agent] Thinking: ${ee.thinking.substring(0,100)}...`),O("thinking",{text:ee.thinking,uuid:X.uuid})}else if(ie.type==="tool_use"||"name"in ie){let ee=ie,Ge=se(ee.name,ee.input);Ge.allowed||(console.error(`[Agent] SECURITY VIOLATION: ${Ge.reason}`),console.error(`[Agent] Tool attempt details: ${JSON.stringify({tool:ee.name,mode:h,toolUseId:ee.id,timestamp:new Date().toISOString()})}`),O("error",{error:Ge.reason,securityViolation:!0,tool:ee.name,mode:h})),i&&console.log(`[Agent] Tool: ${ee.name}${Ge.allowed?"":" (RESTRICTED - should not execute)"}`),O("tool_start",{tool:ee.name,toolUseId:ee.id,input:ee.input})}}break;case"user":if(X.message.content){for(let ie of X.message.content)if(typeof ie=="object"&&ie!==null&&"type"in ie&&ie.type==="tool_result"){let ee=ie;O("tool_end",{toolUseId:ee.tool_use_id,isError:ee.is_error||!1,hasContent:!!ee.content})}}break;case"result":clearTimeout(E),i&&(console.log(""),console.log(`[Agent] Completed in ${X.duration_ms}ms`),console.log(`[Agent] Cost: $${X.total_cost_usd?.toFixed(4)||"N/A"}`));let ce=Im(m);return i&&ce.length>0&&console.log(`[Agent] Found ${ce.length} task(s) in output`),O("result",{success:!0,output:m,tasks:ce,costUsd:X.total_cost_usd}),{success:!0,output:m,tasks:ce,timedOut:!1,totalCostUsd:X.total_cost_usd}}return clearTimeout(E),{success:!1,output:m,tasks:[],error:"Query stream ended without result",timedOut:v}}catch(Y){clearTimeout(E);let X=Y instanceof Error?Y.message:String(Y);return i&&console.error("[Agent] Error:",X),O("error",{error:X}),{success:!1,output:m,tasks:[],error:v?"Process timed out":X,timedOut:v}}}var Nd=br(xd(),1),Wn=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 Nd.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=h=>{h.current==="connected"?(clearTimeout(a),this.ably?.connection.off(c),t()):h.current==="failed"&&(clearTimeout(a),this.ably?.connection.off(c),i(new Error(`Connection failed: ${h.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 ew}from"child_process";import{promisify as tw}from"util";var Ld=tw(ew);async function ct(s,e){try{return await Ld(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 sw(s){try{return await ct("git rev-parse --is-inside-work-tree",s),!0}catch{return!1}}async function Oo(s){let{stdout:e}=await ct("git status --porcelain",s),t=[],i=[],a=[],c=e.trim().split(`
|
|
57
|
+
`).filter(Boolean);for(let h of c){let p=h[0],g=h[1],m=h.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 nw(s){let{stdout:e}=await ct("git rev-parse --abbrev-ref HEAD",s);return e.trim()}async function rw(s){let{stdout:e}=await ct("git rev-parse --short HEAD",s);return e.trim()}async function iw(s){await ct("git add .",s)}async function ow(s,e,t){try{if(!(await Oo(s)).hasChanges)return{success:!1,filesCommitted:[],error:"No changes to commit"};await iw(s);let c=(await Oo(s)).staged,h=e;t&&(h=`${e}
|
|
58
58
|
|
|
59
|
-
Task-ID: ${t}`);let p=h.replace(/'/g,"'\\''");return await
|
|
59
|
+
Task-ID: ${t}`);let p=h.replace(/'/g,"'\\''");return await ct(`git commit -m '${p}'`,s),{success:!0,commitHash:await rw(s),filesCommitted:c}}catch(i){return{success:!1,filesCommitted:[],error:i instanceof Error?i.message:"Unknown error during commit"}}}async function aw(s){try{let e=await nw(s);try{await ct("git rev-parse --abbrev-ref --symbolic-full-name @{u}",s)}catch{return console.log(`[Git] No upstream configured, setting upstream to origin/${e}`),await ct(`git push -u origin ${e}`,s),{success:!0,branch:e,remote:"origin"}}return await ct("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 cw(s){console.log("[Git] Running full build verification before commit...");try{return await Ld("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 So(s,e){let t={committed:!1,pushed:!1,commitHash:void 0,filesCommitted:[],error:void 0,buildFailed:!1};if(!e.autoCommit)return t;if(!await sw(s))return t.error="Not a git repository",t;let a=await Oo(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 cw(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}
|
|
60
60
|
|
|
61
61
|
Automatically committed by Sego Auto-Task Monitor`;console.log("[Git] Committing changes...");let h=await ow(s,c,e.taskId);if(!h.success)return t.error=h.error,t;if(t.committed=!0,t.commitHash=h.commitHash,t.filesCommitted=h.filesCommitted,console.log(`[Git] Committed ${h.filesCommitted.length} files (${h.commitHash})`),e.autoPush){console.log("[Git] Pushing to remote...");let p=await aw(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 lw}from"child_process";import{promisify as uw}from"util";var hw=uw(lw);function dw(s){return s.some(e=>e==="prisma/schema.prisma"||e.endsWith("/schema.prisma")||e.includes("prisma/schema.prisma"))}async function fw(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:h,stderr:p}=await hw(c,{cwd:s,maxBuffer:10*1024*1024,timeout:12e4}),g=h+(p?`
|
|
62
62
|
${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,h=[c.stdout,c.stderr].filter(Boolean).join(`
|
|
63
|
-
`);return h.includes("Your database is now in sync")||h.includes("Database is already in sync")?(console.log("[Schema] Database schema synced successfully"),{success:!0,applied:!0,output:h.trim()}):(console.error("[Schema] Failed to apply schema:",c.message),{success:!1,applied:!1,error:c.message||"Unknown error applying schema",output:h.trim()})}}async function Dd(s,e,t={}){return dw(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"}):fw(s,{skipGenerate:!0,acceptDataLoss:t.acceptDataLoss??!0})):{success:!0,applied:!1}}import{randomBytes as pw}from"crypto";import{createServer as gw}from"http";var Wn=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 Js(e.apiUrl,e.apiKey,e.projectId),this.monitorId=`monitor-${pw(8).toString("hex")}`}updateActivityTime(){this.lastActivityTime=Date.now()}startHealthServer(){let e=this.config.healthPort;this.healthServer=gw((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),h={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(h))}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 Fn(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,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=Qc(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",h=null;this.config.streamProgress&&(h=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 E=qr(w);console.log(`[Monitor] ${E.emoji} ${E.message}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,E)}catch(O){console.error("[Monitor] Failed to send progress event:",O)}}:void 0;if(t&&this.config.useAgentSdk){let w=Xc(e.description);console.log(`[Monitor] Conversation mode: ${w}`);let E=await Zc(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:p,mode:w});console.log("-".repeat(60));let O=Date.now()-i;if(E.totalCostUsd&&console.log(`[Monitor] Agent cost: $${E.totalCostUsd.toFixed(4)}`),E.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(A){console.error("[Monitor] Failed to send timeout event:",A)}return}if(!E.success){console.log(`[Monitor] Conversation error: ${E.error}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"error",timestamp:Date.now(),message:E.error||"Unknown error",emoji:"\u274C",data:{error:E.error}})}catch(A){console.error("[Monitor] Failed to send error event:",A)}return}if(console.log(`[Monitor] Conversation completed (${O}ms)`),console.log(`[Monitor] Result has ${E.tasks?.length||0} tasks`),E.tasks&&E.tasks.length>0){console.log(`[Monitor] Sending ${E.tasks.length} suggested task(s) to frontend`);for(let A of E.tasks)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"task_suggested",timestamp:Date.now(),message:`Task suggested: ${A.title}`,emoji:"\u{1F4CB}",data:{task:A}}),console.log(`[Monitor] \u{1F4CB} Sent task: ${A.title}`)}catch(k){console.error("[Monitor] Failed to send task_suggested event:",k)}}try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"result",timestamp:Date.now(),message:`Conversation completed with ${E.tasks?.length||0} task(s)`,emoji:"\u2705",data:{success:!0,tasksCount:E.tasks?.length||0,processingTimeMs:O}}),console.log("[Monitor] \u2705 Sent result event")}catch(A){console.error("[Monitor] Failed to send result event:",A)}return}let g;this.config.useAgentSdk?(g=await Kc(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 Wc(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 v=await this.client.submitAnalysis(e.id,this.monitorId,g.analysis,m);console.log(`[Monitor] Analysis submitted successfully - ${v.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{h&&clearInterval(h),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,h)=>{if(!this.config.streamProgress)return;let p={type:"phase",timestamp:Date.now(),message:h,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:h}};console.log(`[Monitor] ${p.emoji} ${h}`);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 Jc(e,{timeoutMs:this.config.timeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:this.config.streamProgress?async m=>{if(m.type==="tool_start"){let w=m.data;if((w.tool==="Edit"||w.tool==="Write")&&a==="analyzing"&&(a="implementing",await i("implementing","Implementing changes...")),w.tool==="Bash"&&a==="implementing"){let O=w.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 v=qr(m);console.log(`[Monitor] ${v.emoji} ${v.message}`);try{await this.client.sendTaskAgentProgress(e.id,this.monitorId,v)}catch(w){console.error("[Monitor] Failed to send progress event:",w)}}:void 0}),c.totalCostUsd&&console.log(`[Monitor] Agent cost: $${c.totalCostUsd.toFixed(4)}`)):c=await Vc(e,this.config.timeoutMs,{verbose:!0,workingDirectory:this.config.workingDirectory}),console.log("-".repeat(60));let h=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 m=this.config.workingDirectory||process.cwd(),v=await So(m,{taskId:e.id,taskTitle:e.title,autoCommit:this.config.autoCommit,autoPush:this.config.autoPush,verifyBuild:!0});if(v.buildFailed){console.error("[Monitor] Build verification failed - NOT pushing broken code"),console.error(`[Monitor] Build error: ${v.error}`),await i("error","Build verification failed - code not committed"),await this.client.failBacklogTask(e.id,this.monitorId,`Build verification failed: ${v.error?.substring(0,500)||"Unknown build error"}`,!0);return}if(v.committed){if(p=v.commitHash,g=v.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 w=await Dd(m,g,{dryRun:this.config.dryRun,acceptDataLoss:!0});w.applied?console.log("[Monitor] Schema migration applied successfully"):w.error&&console.warn(`[Monitor] Schema migration failed: ${w.error}`)}v.pushed?console.log("[Monitor] Auto-push successful"):this.config.autoPush&&v.error&&console.warn(`[Monitor] Auto-push failed: ${v.error}`)}else v.error&&v.error!=="No changes to commit"?console.warn(`[Monitor] Auto-commit failed: ${v.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}),await i("completed","Task completed successfully"),console.log(`[Monitor] Task ${e.id} completed successfully (${h}ms)`),await this.triggerContainerRebuild()}catch(c){console.error("[Monitor] Error processing backlog task:",c);let h=c instanceof Error?c.message:"Unknown error";await i("error",h);try{await this.client.failBacklogTask(e.id,this.monitorId,h,!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=await Gc(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"),await this.handleSuccess(t.runId,e,i.output)}catch(t){console.error("[Monitor] Error processing task:",t)}finally{this.isProcessing=!1}}async handleSuccess(e,t,i){let a="";if(this.config.autoCommit){console.log("[Monitor] Running build verification and auto-commit...");let p=this.config.workingDirectory||process.cwd(),g=await So(p,{taskId:t.id,taskTitle:t.title,autoCommit:this.config.autoCommit,autoPush:this.config.autoPush,verifyBuild:!0});if(g.buildFailed){console.error("[Monitor] Build verification failed - NOT pushing broken code"),a=`
|
|
63
|
+
`);return h.includes("Your database is now in sync")||h.includes("Database is already in sync")?(console.log("[Schema] Database schema synced successfully"),{success:!0,applied:!0,output:h.trim()}):(console.error("[Schema] Failed to apply schema:",c.message),{success:!1,applied:!1,error:c.message||"Unknown error applying schema",output:h.trim()})}}async function Dd(s,e,t={}){return dw(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"}):fw(s,{skipGenerate:!0,acceptDataLoss:t.acceptDataLoss??!0})):{success:!0,applied:!1}}import{randomBytes as pw}from"crypto";import{createServer as gw}from"http";var Vn=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 Ys(e.apiUrl,e.apiKey,e.projectId),this.monitorId=`monitor-${pw(8).toString("hex")}`}updateActivityTime(){this.lastActivityTime=Date.now()}startHealthServer(){let e=this.config.healthPort;this.healthServer=gw((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),h={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(h))}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 Wn(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,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=Qc(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",h=null;this.config.streamProgress&&(h=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 E=qr(w);console.log(`[Monitor] ${E.emoji} ${E.message}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,E)}catch(O){console.error("[Monitor] Failed to send progress event:",O)}}:void 0;if(t&&this.config.useAgentSdk){let w=Xc(e.description);console.log(`[Monitor] Conversation mode: ${w}`);let E=await Zc(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:p,mode:w});console.log("-".repeat(60));let O=Date.now()-i;if(E.totalCostUsd&&console.log(`[Monitor] Agent cost: $${E.totalCostUsd.toFixed(4)}`),E.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(T){console.error("[Monitor] Failed to send timeout event:",T)}return}if(!E.success){console.log(`[Monitor] Conversation error: ${E.error}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"error",timestamp:Date.now(),message:E.error||"Unknown error",emoji:"\u274C",data:{error:E.error}})}catch(T){console.error("[Monitor] Failed to send error event:",T)}return}if(console.log(`[Monitor] Conversation completed (${O}ms)`),console.log(`[Monitor] Result has ${E.tasks?.length||0} tasks`),E.tasks&&E.tasks.length>0){console.log(`[Monitor] Sending ${E.tasks.length} suggested task(s) to frontend`);for(let T of E.tasks)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"task_suggested",timestamp:Date.now(),message:`Task suggested: ${T.title}`,emoji:"\u{1F4CB}",data:{task:T}}),console.log(`[Monitor] \u{1F4CB} Sent task: ${T.title}`)}catch(k){console.error("[Monitor] Failed to send task_suggested event:",k)}}try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"result",timestamp:Date.now(),message:`Conversation completed with ${E.tasks?.length||0} task(s)`,emoji:"\u2705",data:{success:!0,tasksCount:E.tasks?.length||0,processingTimeMs:O}}),console.log("[Monitor] \u2705 Sent result event")}catch(T){console.error("[Monitor] Failed to send result event:",T)}return}let g;this.config.useAgentSdk?(g=await Kc(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 Wc(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 v=await this.client.submitAnalysis(e.id,this.monitorId,g.analysis,m);console.log(`[Monitor] Analysis submitted successfully - ${v.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{h&&clearInterval(h),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,h)=>{if(!this.config.streamProgress)return;let p={type:"phase",timestamp:Date.now(),message:h,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:h}};console.log(`[Monitor] ${p.emoji} ${h}`);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 Jc(e,{timeoutMs:this.config.timeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:this.config.streamProgress?async m=>{if(m.type==="tool_start"){let w=m.data;if((w.tool==="Edit"||w.tool==="Write")&&a==="analyzing"&&(a="implementing",await i("implementing","Implementing changes...")),w.tool==="Bash"&&a==="implementing"){let O=w.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 v=qr(m);console.log(`[Monitor] ${v.emoji} ${v.message}`);try{await this.client.sendTaskAgentProgress(e.id,this.monitorId,v)}catch(w){console.error("[Monitor] Failed to send progress event:",w)}}:void 0}),c.totalCostUsd&&console.log(`[Monitor] Agent cost: $${c.totalCostUsd.toFixed(4)}`)):c=await Vc(e,this.config.timeoutMs,{verbose:!0,workingDirectory:this.config.workingDirectory}),console.log("-".repeat(60));let h=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 m=this.config.workingDirectory||process.cwd(),v=await So(m,{taskId:e.id,taskTitle:e.title,autoCommit:this.config.autoCommit,autoPush:this.config.autoPush,verifyBuild:!0});if(v.buildFailed){console.error("[Monitor] Build verification failed - NOT pushing broken code"),console.error(`[Monitor] Build error: ${v.error}`),await i("error","Build verification failed - code not committed"),await this.client.failBacklogTask(e.id,this.monitorId,`Build verification failed: ${v.error?.substring(0,500)||"Unknown build error"}`,!0);return}if(v.committed){if(p=v.commitHash,g=v.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 w=await Dd(m,g,{dryRun:this.config.dryRun,acceptDataLoss:!0});w.applied?console.log("[Monitor] Schema migration applied successfully"):w.error&&console.warn(`[Monitor] Schema migration failed: ${w.error}`)}v.pushed?console.log("[Monitor] Auto-push successful"):this.config.autoPush&&v.error&&console.warn(`[Monitor] Auto-push failed: ${v.error}`)}else v.error&&v.error!=="No changes to commit"?console.warn(`[Monitor] Auto-commit failed: ${v.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}),await i("completed","Task completed successfully"),console.log(`[Monitor] Task ${e.id} completed successfully (${h}ms)`),await this.triggerContainerRebuild()}catch(c){console.error("[Monitor] Error processing backlog task:",c);let h=c instanceof Error?c.message:"Unknown error";await i("error",h);try{await this.client.failBacklogTask(e.id,this.monitorId,h,!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=await Gc(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"),await this.handleSuccess(t.runId,e,i.output)}catch(t){console.error("[Monitor] Error processing task:",t)}finally{this.isProcessing=!1}}async handleSuccess(e,t,i){let a="";if(this.config.autoCommit){console.log("[Monitor] Running build verification and auto-commit...");let p=this.config.workingDirectory||process.cwd(),g=await So(p,{taskId:t.id,taskTitle:t.title,autoCommit:this.config.autoCommit,autoPush:this.config.autoPush,verifyBuild:!0});if(g.buildFailed){console.error("[Monitor] Build verification failed - NOT pushing broken code"),a=`
|
|
64
64
|
|
|
65
65
|
### Git
|
|
66
66
|
- \u26A0\uFE0F Build verification FAILED
|
|
@@ -95,7 +95,7 @@ SEGO_PROJECT_ID=${s.projectId}
|
|
|
95
95
|
`),e}async function Hd(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 qd(a,i)||(console.error(`
|
|
96
96
|
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=jd(process.cwd(),".env"),m=Bd(p);Ud(g,m),$d(g);return}let t=_w();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(`
|
|
97
97
|
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 qd(c,i)||(console.error(`
|
|
98
|
-
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=jd(process.cwd(),".env");if(yw(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=Bd(g);Ud(m,w),$d(m)}finally{t.close()}}function $d(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 Fd,mkdirSync as bw,readFileSync as vw,writeFileSync as ww}from"fs";import{homedir as Cw}from"os";import{join as Wd}from"path";var Vd="@segosolutions/auto-task",To=Wd(Cw(),".sego-auto-task"),Ao=Wd(To,"version-check.json"),Ew=24*60*60*1e3;function Gd(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,h=i[a]||0;if(c<h)return-1;if(c>h)return 1}return 0}function kw(){try{if(!Fd(Ao))return null;let s=JSON.parse(vw(Ao,"utf-8"));return Date.now()-s.checkedAt<Ew?s:null}catch{return null}}function Ow(s){try{Fd(To)||bw(To,{recursive:!0});let e={latestVersion:s,checkedAt:Date.now()};ww(Ao,JSON.stringify(e,null,2))}catch{}}async function Sw(){try{let s=new AbortController,e=setTimeout(()=>s.abort(),5e3),t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(Vd)}/latest`,{signal:s.signal});return clearTimeout(e),t.ok&&(await t.json()).version||null}catch{return null}}async function zd(s){let e=kw();if(e)return{currentVersion:s,latestVersion:e.latestVersion,updateAvailable:Gd(s,e.latestVersion)<0};let t=await Sw();return t&&Ow(t),{currentVersion:s,latestVersion:t,updateAvailable:t?Gd(s,t)<0:!1}}function Kd(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 ${Vd}\x1B[0m`),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""))}var Qd="1.7.
|
|
98
|
+
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=jd(process.cwd(),".env");if(yw(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=Bd(g);Ud(m,w),$d(m)}finally{t.close()}}function $d(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 Fd,mkdirSync as bw,readFileSync as vw,writeFileSync as ww}from"fs";import{homedir as Cw}from"os";import{join as Wd}from"path";var Vd="@segosolutions/auto-task",To=Wd(Cw(),".sego-auto-task"),Ao=Wd(To,"version-check.json"),Ew=24*60*60*1e3;function Gd(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,h=i[a]||0;if(c<h)return-1;if(c>h)return 1}return 0}function kw(){try{if(!Fd(Ao))return null;let s=JSON.parse(vw(Ao,"utf-8"));return Date.now()-s.checkedAt<Ew?s:null}catch{return null}}function Ow(s){try{Fd(To)||bw(To,{recursive:!0});let e={latestVersion:s,checkedAt:Date.now()};ww(Ao,JSON.stringify(e,null,2))}catch{}}async function Sw(){try{let s=new AbortController,e=setTimeout(()=>s.abort(),5e3),t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(Vd)}/latest`,{signal:s.signal});return clearTimeout(e),t.ok&&(await t.json()).version||null}catch{return null}}async function zd(s){let e=kw();if(e)return{currentVersion:s,latestVersion:e.latestVersion,updateAvailable:Gd(s,e.latestVersion)<0};let t=await Sw();return t&&Ow(t),{currentVersion:s,latestVersion:t,updateAvailable:t?Gd(s,t)<0:!1}}function Kd(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 ${Vd}\x1B[0m`),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""))}var Qd="1.7.2",Ro=null;hs.name("sego-auto-task").description(`Background task monitor for Sego PM - automatically processes high-confidence tasks using Claude.
|
|
99
99
|
|
|
100
100
|
Runs in hybrid mode:
|
|
101
101
|
- SSE: Listens for client request events and processes them with local Claude
|
|
@@ -103,8 +103,8 @@ Runs in hybrid mode:
|
|
|
103
103
|
|
|
104
104
|
Environment variables are loaded from .env in the working directory.
|
|
105
105
|
|
|
106
|
-
Use "sego-auto-task init" to run the interactive setup wizard.`).version(Qd);
|
|
107
|
-
Received shutdown signal`),m.stop(),process.exit(0)};process.on("SIGINT",v),process.on("SIGTERM",v),await m.start()}catch(e){console.error("Error:",e instanceof Error?e.message:e),process.exit(1)}});
|
|
106
|
+
Use "sego-auto-task init" to run the interactive setup wizard.`).version(Qd);hs.command("init").description("Interactive setup wizard to configure your API key and settings").option("-y, --yes","Accept defaults without prompting").action(async s=>{await Hd({yes:s.yes})});hs.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&&(Ro=zd(Qd).then(Kd).catch(()=>{}));let e=s.workingDir||process.env.SEGO_WORKING_DIR||process.cwd(),t=Jd(e),i=Jd(t,".env");Tw(i)?(console.log(`Loading environment from: ${i}`),Yd.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 Fc()||(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 Yc()||(console.error("Error: Claude Agent SDK is not available."),process.exit(1)),console.log("Claude Agent SDK is available"));let{config:c,sources:h}=jc({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} ${Ee(h.apiUrl)}`),console.log(`SSE Mode: ${c.sseEnabled?"enabled":"disabled"} ${Ee(h.sseEnabled)}`),console.log(`Project Filter: ${c.projectId||"all projects"} ${Ee(h.projectId)}`),console.log(`Poll Interval: ${c.pollIntervalMs/1e3}s ${Ee(h.pollIntervalMs)}`),console.log(`Task Timeout: ${c.timeoutMs/6e4}min ${Ee(h.timeoutMs)}`),console.log(`Dry Run: ${c.dryRun?"yes":"no"} ${Ee(h.dryRun)}`),console.log(`Working Dir: ${c.workingDirectory} ${Ee(h.workingDirectory)}`),console.log(`Execution Mode: ${c.useAgentSdk?"Agent SDK":"CLI subprocess (legacy)"} ${Ee(h.useAgentSdk)}`),console.log(`Stream Progress: ${c.streamProgress?"yes":"no"} ${Ee(h.streamProgress)}`),console.log(`Conv. Only: ${c.conversationOnly?"yes":"no"} ${Ee(h.conversationOnly)}`),console.log(`Auto-Commit: ${c.autoCommit?"yes":"no"} ${Ee(h.autoCommit)}`),console.log(`Auto-Push: ${c.autoPush?"yes":"no"} ${Ee(h.autoPush)}`),console.log(`Idle Timeout: ${c.idleTimeoutMinutes>0?`${c.idleTimeoutMinutes}min`:"disabled"} ${Ee(h.idleTimeoutMinutes)}`),console.log(`Health Port: ${c.healthPort} ${Ee(h.healthPort)}`),console.log("-".repeat(70)),console.log("Sources: [cli] = command line, [env] = environment variable, [default]"),console.log("=".repeat(70)),console.log(""),Ro&&await Ro;let m=new Vn(c),v=()=>{console.log(`
|
|
107
|
+
Received shutdown signal`),m.stop(),process.exit(0)};process.on("SIGINT",v),process.on("SIGTERM",v),await m.start()}catch(e){console.error("Error:",e instanceof Error?e.message:e),process.exit(1)}});hs.parse();
|
|
108
108
|
/*! Bundled license information:
|
|
109
109
|
|
|
110
110
|
ably/build/ably-node.js:
|