airloom 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -503,7 +503,11 @@ var AblyAdapter = class {
503
503
  }
504
504
  async connect(sessionToken, role) {
505
505
  this.clientId = `airloom-${role}-${Date.now()}`;
506
- const clientOpts = { clientId: this.clientId };
506
+ const clientOpts = {
507
+ clientId: this.clientId,
508
+ // Enable server time sync to avoid "Timestamp not current" errors on machines with clock skew
509
+ queryTime: true
510
+ };
507
511
  if (this.opts.key) {
508
512
  clientOpts.key = this.opts.key;
509
513
  } else {
@@ -1457,7 +1461,10 @@ async function main() {
1457
1461
  let pairingData;
1458
1462
  if (useAbly) {
1459
1463
  const { Rest } = await import("ably");
1460
- const rest = new Rest({ key: ABLY_API_KEY });
1464
+ const rest = new Rest({
1465
+ key: ABLY_API_KEY,
1466
+ queryTime: true
1467
+ });
1461
1468
  const channelName = `airloom:${session.sessionToken}`;
1462
1469
  const tokenDetails = await rest.auth.requestToken({
1463
1470
  clientId: "*",
@@ -1 +1 @@
1
- import{g as c}from"./index-BoCit9Kx.js";function f(t,i){for(var o=0;o<i.length;o++){const e=i[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const s=Object.getOwnPropertyDescriptor(e,r);s&&Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var n,a;function b(){return a||(a=1,n=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),n}var u=b();const w=c(u),p=f({__proto__:null,default:w},[u]);export{p as b};
1
+ import{g as c}from"./index-DLLnAccl.js";function f(t,i){for(var o=0;o<i.length;o++){const e=i[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const s=Object.getOwnPropertyDescriptor(e,r);s&&Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var n,a;function b(){return a||(a=1,n=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),n}var u=b();const w=c(u),p=f({__proto__:null,default:w},[u]);export{p as b};
@@ -1,4 +1,4 @@
1
- var Wc=Object.defineProperty;var Vc=(f,o,l)=>o in f?Wc(f,o,{enumerable:!0,configurable:!0,writable:!0,value:l}):f[o]=l;var ce=(f,o,l)=>Vc(f,typeof o!="symbol"?o+"":o,l);(function(){const o=document.createElement("link").relList;if(o&&o.supports&&o.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))p(m);new MutationObserver(m=>{for(const x of m)if(x.type==="childList")for(const k of x.addedNodes)k.tagName==="LINK"&&k.rel==="modulepreload"&&p(k)}).observe(document,{childList:!0,subtree:!0});function l(m){const x={};return m.integrity&&(x.integrity=m.integrity),m.referrerPolicy&&(x.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?x.credentials="include":m.crossOrigin==="anonymous"?x.credentials="omit":x.credentials="same-origin",x}function p(m){if(m.ep)return;m.ep=!0;const x=l(m);fetch(m.href,x)}})();const $c="modulepreload",Fc=function(f,o){return new URL(f,o).href},$i={},ro=function(o,l,p){let m=Promise.resolve();if(l&&l.length>0){let k=function(D){return Promise.all(D.map(J=>Promise.resolve(J).then(oe=>({status:"fulfilled",value:oe}),oe=>({status:"rejected",reason:oe}))))};const v=document.getElementsByTagName("link"),I=document.querySelector("meta[property=csp-nonce]"),M=(I==null?void 0:I.nonce)||(I==null?void 0:I.getAttribute("nonce"));m=k(l.map(D=>{if(D=Fc(D,p),D in $i)return;$i[D]=!0;const J=D.endsWith(".css"),oe=J?'[rel="stylesheet"]':"";if(!!p)for(let de=v.length-1;de>=0;de--){const Ne=v[de];if(Ne.href===D&&(!J||Ne.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${D}"]${oe}`))return;const fe=document.createElement("link");if(fe.rel=J?"stylesheet":$c,J||(fe.as="script"),fe.crossOrigin="",fe.href=D,M&&fe.setAttribute("nonce",M),document.head.appendChild(fe),J)return new Promise((de,Ne)=>{fe.addEventListener("load",de),fe.addEventListener("error",()=>Ne(new Error(`Unable to preload CSS for ${D}`)))})}))}function x(k){const v=new Event("vite:preloadError",{cancelable:!0});if(v.payload=k,window.dispatchEvent(v),!v.defaultPrevented)throw k}return m.then(k=>{for(const v of k||[])v.status==="rejected"&&x(v.reason);return o().catch(x)})};var Kt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zc(f){return f&&f.__esModule&&Object.prototype.hasOwnProperty.call(f,"default")?f.default:f}function Jc(f){if(Object.prototype.hasOwnProperty.call(f,"__esModule"))return f;var o=f.default;if(typeof o=="function"){var l=function p(){return this instanceof p?Reflect.construct(o,arguments,this.constructor):o.apply(this,arguments)};l.prototype=o.prototype}else l={};return Object.defineProperty(l,"__esModule",{value:!0}),Object.keys(f).forEach(function(p){var m=Object.getOwnPropertyDescriptor(f,p);Object.defineProperty(l,p,m.get?m:{enumerable:!0,get:function(){return f[p]}})}),l}var ks={exports:{}},Fi;function Kc(){if(Fi)return ks.exports;Fi=1;var f=typeof Reflect=="object"?Reflect:null,o=f&&typeof f.apply=="function"?f.apply:function(W,_,le){return Function.prototype.apply.call(W,_,le)},l;f&&typeof f.ownKeys=="function"?l=f.ownKeys:Object.getOwnPropertySymbols?l=function(W){return Object.getOwnPropertyNames(W).concat(Object.getOwnPropertySymbols(W))}:l=function(W){return Object.getOwnPropertyNames(W)};function p(z){console&&console.warn&&console.warn(z)}var m=Number.isNaN||function(W){return W!==W};function x(){x.init.call(this)}ks.exports=x,ks.exports.once=ht,x.EventEmitter=x,x.prototype._events=void 0,x.prototype._eventsCount=0,x.prototype._maxListeners=void 0;var k=10;function v(z){if(typeof z!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof z)}Object.defineProperty(x,"defaultMaxListeners",{enumerable:!0,get:function(){return k},set:function(z){if(typeof z!="number"||z<0||m(z))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+z+".");k=z}}),x.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},x.prototype.setMaxListeners=function(W){if(typeof W!="number"||W<0||m(W))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+W+".");return this._maxListeners=W,this};function I(z){return z._maxListeners===void 0?x.defaultMaxListeners:z._maxListeners}x.prototype.getMaxListeners=function(){return I(this)},x.prototype.emit=function(W){for(var _=[],le=1;le<arguments.length;le++)_.push(arguments[le]);var he=W==="error",He=this._events;if(He!==void 0)he=he&&He.error===void 0;else if(!he)return!1;if(he){var Te;if(_.length>0&&(Te=_[0]),Te instanceof Error)throw Te;var $e=new Error("Unhandled error."+(Te?" ("+Te.message+")":""));throw $e.context=Te,$e}var bt=He[W];if(bt===void 0)return!1;if(typeof bt=="function")o(bt,this,_);else for(var c=bt.length,xt=fe(bt,c),le=0;le<c;++le)o(xt[le],this,_);return!0};function M(z,W,_,le){var he,He,Te;if(v(_),He=z._events,He===void 0?(He=z._events=Object.create(null),z._eventsCount=0):(He.newListener!==void 0&&(z.emit("newListener",W,_.listener?_.listener:_),He=z._events),Te=He[W]),Te===void 0)Te=He[W]=_,++z._eventsCount;else if(typeof Te=="function"?Te=He[W]=le?[_,Te]:[Te,_]:le?Te.unshift(_):Te.push(_),he=I(z),he>0&&Te.length>he&&!Te.warned){Te.warned=!0;var $e=new Error("Possible EventEmitter memory leak detected. "+Te.length+" "+String(W)+" listeners added. Use emitter.setMaxListeners() to increase limit");$e.name="MaxListenersExceededWarning",$e.emitter=z,$e.type=W,$e.count=Te.length,p($e)}return z}x.prototype.addListener=function(W,_){return M(this,W,_,!1)},x.prototype.on=x.prototype.addListener,x.prototype.prependListener=function(W,_){return M(this,W,_,!0)};function D(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function J(z,W,_){var le={fired:!1,wrapFn:void 0,target:z,type:W,listener:_},he=D.bind(le);return he.listener=_,le.wrapFn=he,he}x.prototype.once=function(W,_){return v(_),this.on(W,J(this,W,_)),this},x.prototype.prependOnceListener=function(W,_){return v(_),this.prependListener(W,J(this,W,_)),this},x.prototype.removeListener=function(W,_){var le,he,He,Te,$e;if(v(_),he=this._events,he===void 0)return this;if(le=he[W],le===void 0)return this;if(le===_||le.listener===_)--this._eventsCount===0?this._events=Object.create(null):(delete he[W],he.removeListener&&this.emit("removeListener",W,le.listener||_));else if(typeof le!="function"){for(He=-1,Te=le.length-1;Te>=0;Te--)if(le[Te]===_||le[Te].listener===_){$e=le[Te].listener,He=Te;break}if(He<0)return this;He===0?le.shift():de(le,He),le.length===1&&(he[W]=le[0]),he.removeListener!==void 0&&this.emit("removeListener",W,$e||_)}return this},x.prototype.off=x.prototype.removeListener,x.prototype.removeAllListeners=function(W){var _,le,he;if(le=this._events,le===void 0)return this;if(le.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):le[W]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete le[W]),this;if(arguments.length===0){var He=Object.keys(le),Te;for(he=0;he<He.length;++he)Te=He[he],Te!=="removeListener"&&this.removeAllListeners(Te);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(_=le[W],typeof _=="function")this.removeListener(W,_);else if(_!==void 0)for(he=_.length-1;he>=0;he--)this.removeListener(W,_[he]);return this};function oe(z,W,_){var le=z._events;if(le===void 0)return[];var he=le[W];return he===void 0?[]:typeof he=="function"?_?[he.listener||he]:[he]:_?Ne(he):fe(he,he.length)}x.prototype.listeners=function(W){return oe(this,W,!0)},x.prototype.rawListeners=function(W){return oe(this,W,!1)},x.listenerCount=function(z,W){return typeof z.listenerCount=="function"?z.listenerCount(W):H.call(z,W)},x.prototype.listenerCount=H;function H(z){var W=this._events;if(W!==void 0){var _=W[z];if(typeof _=="function")return 1;if(_!==void 0)return _.length}return 0}x.prototype.eventNames=function(){return this._eventsCount>0?l(this._events):[]};function fe(z,W){for(var _=new Array(W),le=0;le<W;++le)_[le]=z[le];return _}function de(z,W){for(;W+1<z.length;W++)z[W]=z[W+1];z.pop()}function Ne(z){for(var W=new Array(z.length),_=0;_<W.length;++_)W[_]=z[_].listener||z[_];return W}function ht(z,W){return new Promise(function(_,le){function he(Te){z.removeListener(W,He),le(Te)}function He(){typeof z.removeListener=="function"&&z.removeListener("error",he),_([].slice.call(arguments))}Rt(z,W,He,{once:!0}),W!=="error"&&At(z,he,{once:!0})})}function At(z,W,_){typeof z.on=="function"&&Rt(z,"error",W,_)}function Rt(z,W,_,le){if(typeof z.on=="function")le.once?z.once(W,_):z.on(W,_);else if(typeof z.addEventListener=="function")z.addEventListener(W,function he(He){le.once&&z.removeEventListener(W,he),_(He)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof z)}return ks.exports}var io=Kc();function Qc(f){if(typeof Buffer<"u")return Buffer.from(f).toString("base64");let o="";for(const l of f)o+=String.fromCharCode(l);return btoa(o)}function Yc(f){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(f,"base64"));const o=atob(f),l=new Uint8Array(o.length);for(let p=0;p<o.length;p++)l[p]=o.charCodeAt(p);return l}function Zc(f){return new TextEncoder().encode(JSON.stringify(f))}function Xc(f){const o=JSON.parse(new TextDecoder().decode(f));if(!o||typeof o!="object"||typeof o.type!="string"||typeof o.id!="string")throw new Error("Invalid channel message: missing type or id field");return o}function el(f){const o=JSON.parse(f);if(!o||typeof o!="object"||typeof o.relay!="string"||typeof o.session!="string"||typeof o.v!="number")throw new Error("Invalid pairing data: missing required fields");if(o.transport!==void 0&&o.transport!=="ws"&&o.transport!=="ably")throw new Error('Invalid pairing data: transport must be "ws" or "ably"');if(o.token!==void 0&&typeof o.token!="string")throw new Error("Invalid pairing data: token must be a string");if(o.transport==="ably"&&!o.token)throw new Error("Invalid pairing data: Ably transport requires a token");return o}function tl(f){throw new Error('Could not dynamically require "'+f+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var cr={exports:{}};const nl={},sl=Object.freeze(Object.defineProperty({__proto__:null,default:nl},Symbol.toStringTag,{value:"Module"})),rl=Jc(sl);var zi;function il(){return zi||(zi=1,(function(f){(function(o){var l=function(h){var d,u=new Float64Array(16);if(h)for(d=0;d<h.length;d++)u[d]=h[d];return u},p=function(){throw new Error("no PRNG")},m=new Uint8Array(16),x=new Uint8Array(32);x[0]=9;var k=l(),v=l([1]),I=l([56129,1]),M=l([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),D=l([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),J=l([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),oe=l([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),H=l([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function fe(h,d,u,i){h[d]=u>>24&255,h[d+1]=u>>16&255,h[d+2]=u>>8&255,h[d+3]=u&255,h[d+4]=i>>24&255,h[d+5]=i>>16&255,h[d+6]=i>>8&255,h[d+7]=i&255}function de(h,d,u,i,y){var C,O=0;for(C=0;C<y;C++)O|=h[d+C]^u[i+C];return(1&O-1>>>8)-1}function Ne(h,d,u,i){return de(h,d,u,i,16)}function ht(h,d,u,i){return de(h,d,u,i,32)}function At(h,d,u,i){for(var y=i[0]&255|(i[1]&255)<<8|(i[2]&255)<<16|(i[3]&255)<<24,C=u[0]&255|(u[1]&255)<<8|(u[2]&255)<<16|(u[3]&255)<<24,O=u[4]&255|(u[5]&255)<<8|(u[6]&255)<<16|(u[7]&255)<<24,B=u[8]&255|(u[9]&255)<<8|(u[10]&255)<<16|(u[11]&255)<<24,$=u[12]&255|(u[13]&255)<<8|(u[14]&255)<<16|(u[15]&255)<<24,ae=i[4]&255|(i[5]&255)<<8|(i[6]&255)<<16|(i[7]&255)<<24,Y=d[0]&255|(d[1]&255)<<8|(d[2]&255)<<16|(d[3]&255)<<24,Me=d[4]&255|(d[5]&255)<<8|(d[6]&255)<<16|(d[7]&255)<<24,ee=d[8]&255|(d[9]&255)<<8|(d[10]&255)<<16|(d[11]&255)<<24,ge=d[12]&255|(d[13]&255)<<8|(d[14]&255)<<16|(d[15]&255)<<24,be=i[8]&255|(i[9]&255)<<8|(i[10]&255)<<16|(i[11]&255)<<24,Ae=u[16]&255|(u[17]&255)<<8|(u[18]&255)<<16|(u[19]&255)<<24,V=u[20]&255|(u[21]&255)<<8|(u[22]&255)<<16|(u[23]&255)<<24,xe=u[24]&255|(u[25]&255)<<8|(u[26]&255)<<16|(u[27]&255)<<24,we=u[28]&255|(u[29]&255)<<8|(u[30]&255)<<16|(u[31]&255)<<24,me=i[12]&255|(i[13]&255)<<8|(i[14]&255)<<16|(i[15]&255)<<24,te=y,K=C,Z=O,ie=B,re=$,Q=ae,T=Y,E=Me,q=ee,N=ge,G=be,j=Ae,ue=V,ke=xe,Ce=we,Re=me,w,Ee=0;Ee<20;Ee+=2)w=te+ue|0,re^=w<<7|w>>>25,w=re+te|0,q^=w<<9|w>>>23,w=q+re|0,ue^=w<<13|w>>>19,w=ue+q|0,te^=w<<18|w>>>14,w=Q+K|0,N^=w<<7|w>>>25,w=N+Q|0,ke^=w<<9|w>>>23,w=ke+N|0,K^=w<<13|w>>>19,w=K+ke|0,Q^=w<<18|w>>>14,w=G+T|0,Ce^=w<<7|w>>>25,w=Ce+G|0,Z^=w<<9|w>>>23,w=Z+Ce|0,T^=w<<13|w>>>19,w=T+Z|0,G^=w<<18|w>>>14,w=Re+j|0,ie^=w<<7|w>>>25,w=ie+Re|0,E^=w<<9|w>>>23,w=E+ie|0,j^=w<<13|w>>>19,w=j+E|0,Re^=w<<18|w>>>14,w=te+ie|0,K^=w<<7|w>>>25,w=K+te|0,Z^=w<<9|w>>>23,w=Z+K|0,ie^=w<<13|w>>>19,w=ie+Z|0,te^=w<<18|w>>>14,w=Q+re|0,T^=w<<7|w>>>25,w=T+Q|0,E^=w<<9|w>>>23,w=E+T|0,re^=w<<13|w>>>19,w=re+E|0,Q^=w<<18|w>>>14,w=G+N|0,j^=w<<7|w>>>25,w=j+G|0,q^=w<<9|w>>>23,w=q+j|0,N^=w<<13|w>>>19,w=N+q|0,G^=w<<18|w>>>14,w=Re+Ce|0,ue^=w<<7|w>>>25,w=ue+Re|0,ke^=w<<9|w>>>23,w=ke+ue|0,Ce^=w<<13|w>>>19,w=Ce+ke|0,Re^=w<<18|w>>>14;te=te+y|0,K=K+C|0,Z=Z+O|0,ie=ie+B|0,re=re+$|0,Q=Q+ae|0,T=T+Y|0,E=E+Me|0,q=q+ee|0,N=N+ge|0,G=G+be|0,j=j+Ae|0,ue=ue+V|0,ke=ke+xe|0,Ce=Ce+we|0,Re=Re+me|0,h[0]=te>>>0&255,h[1]=te>>>8&255,h[2]=te>>>16&255,h[3]=te>>>24&255,h[4]=K>>>0&255,h[5]=K>>>8&255,h[6]=K>>>16&255,h[7]=K>>>24&255,h[8]=Z>>>0&255,h[9]=Z>>>8&255,h[10]=Z>>>16&255,h[11]=Z>>>24&255,h[12]=ie>>>0&255,h[13]=ie>>>8&255,h[14]=ie>>>16&255,h[15]=ie>>>24&255,h[16]=re>>>0&255,h[17]=re>>>8&255,h[18]=re>>>16&255,h[19]=re>>>24&255,h[20]=Q>>>0&255,h[21]=Q>>>8&255,h[22]=Q>>>16&255,h[23]=Q>>>24&255,h[24]=T>>>0&255,h[25]=T>>>8&255,h[26]=T>>>16&255,h[27]=T>>>24&255,h[28]=E>>>0&255,h[29]=E>>>8&255,h[30]=E>>>16&255,h[31]=E>>>24&255,h[32]=q>>>0&255,h[33]=q>>>8&255,h[34]=q>>>16&255,h[35]=q>>>24&255,h[36]=N>>>0&255,h[37]=N>>>8&255,h[38]=N>>>16&255,h[39]=N>>>24&255,h[40]=G>>>0&255,h[41]=G>>>8&255,h[42]=G>>>16&255,h[43]=G>>>24&255,h[44]=j>>>0&255,h[45]=j>>>8&255,h[46]=j>>>16&255,h[47]=j>>>24&255,h[48]=ue>>>0&255,h[49]=ue>>>8&255,h[50]=ue>>>16&255,h[51]=ue>>>24&255,h[52]=ke>>>0&255,h[53]=ke>>>8&255,h[54]=ke>>>16&255,h[55]=ke>>>24&255,h[56]=Ce>>>0&255,h[57]=Ce>>>8&255,h[58]=Ce>>>16&255,h[59]=Ce>>>24&255,h[60]=Re>>>0&255,h[61]=Re>>>8&255,h[62]=Re>>>16&255,h[63]=Re>>>24&255}function Rt(h,d,u,i){for(var y=i[0]&255|(i[1]&255)<<8|(i[2]&255)<<16|(i[3]&255)<<24,C=u[0]&255|(u[1]&255)<<8|(u[2]&255)<<16|(u[3]&255)<<24,O=u[4]&255|(u[5]&255)<<8|(u[6]&255)<<16|(u[7]&255)<<24,B=u[8]&255|(u[9]&255)<<8|(u[10]&255)<<16|(u[11]&255)<<24,$=u[12]&255|(u[13]&255)<<8|(u[14]&255)<<16|(u[15]&255)<<24,ae=i[4]&255|(i[5]&255)<<8|(i[6]&255)<<16|(i[7]&255)<<24,Y=d[0]&255|(d[1]&255)<<8|(d[2]&255)<<16|(d[3]&255)<<24,Me=d[4]&255|(d[5]&255)<<8|(d[6]&255)<<16|(d[7]&255)<<24,ee=d[8]&255|(d[9]&255)<<8|(d[10]&255)<<16|(d[11]&255)<<24,ge=d[12]&255|(d[13]&255)<<8|(d[14]&255)<<16|(d[15]&255)<<24,be=i[8]&255|(i[9]&255)<<8|(i[10]&255)<<16|(i[11]&255)<<24,Ae=u[16]&255|(u[17]&255)<<8|(u[18]&255)<<16|(u[19]&255)<<24,V=u[20]&255|(u[21]&255)<<8|(u[22]&255)<<16|(u[23]&255)<<24,xe=u[24]&255|(u[25]&255)<<8|(u[26]&255)<<16|(u[27]&255)<<24,we=u[28]&255|(u[29]&255)<<8|(u[30]&255)<<16|(u[31]&255)<<24,me=i[12]&255|(i[13]&255)<<8|(i[14]&255)<<16|(i[15]&255)<<24,te=y,K=C,Z=O,ie=B,re=$,Q=ae,T=Y,E=Me,q=ee,N=ge,G=be,j=Ae,ue=V,ke=xe,Ce=we,Re=me,w,Ee=0;Ee<20;Ee+=2)w=te+ue|0,re^=w<<7|w>>>25,w=re+te|0,q^=w<<9|w>>>23,w=q+re|0,ue^=w<<13|w>>>19,w=ue+q|0,te^=w<<18|w>>>14,w=Q+K|0,N^=w<<7|w>>>25,w=N+Q|0,ke^=w<<9|w>>>23,w=ke+N|0,K^=w<<13|w>>>19,w=K+ke|0,Q^=w<<18|w>>>14,w=G+T|0,Ce^=w<<7|w>>>25,w=Ce+G|0,Z^=w<<9|w>>>23,w=Z+Ce|0,T^=w<<13|w>>>19,w=T+Z|0,G^=w<<18|w>>>14,w=Re+j|0,ie^=w<<7|w>>>25,w=ie+Re|0,E^=w<<9|w>>>23,w=E+ie|0,j^=w<<13|w>>>19,w=j+E|0,Re^=w<<18|w>>>14,w=te+ie|0,K^=w<<7|w>>>25,w=K+te|0,Z^=w<<9|w>>>23,w=Z+K|0,ie^=w<<13|w>>>19,w=ie+Z|0,te^=w<<18|w>>>14,w=Q+re|0,T^=w<<7|w>>>25,w=T+Q|0,E^=w<<9|w>>>23,w=E+T|0,re^=w<<13|w>>>19,w=re+E|0,Q^=w<<18|w>>>14,w=G+N|0,j^=w<<7|w>>>25,w=j+G|0,q^=w<<9|w>>>23,w=q+j|0,N^=w<<13|w>>>19,w=N+q|0,G^=w<<18|w>>>14,w=Re+Ce|0,ue^=w<<7|w>>>25,w=ue+Re|0,ke^=w<<9|w>>>23,w=ke+ue|0,Ce^=w<<13|w>>>19,w=Ce+ke|0,Re^=w<<18|w>>>14;h[0]=te>>>0&255,h[1]=te>>>8&255,h[2]=te>>>16&255,h[3]=te>>>24&255,h[4]=Q>>>0&255,h[5]=Q>>>8&255,h[6]=Q>>>16&255,h[7]=Q>>>24&255,h[8]=G>>>0&255,h[9]=G>>>8&255,h[10]=G>>>16&255,h[11]=G>>>24&255,h[12]=Re>>>0&255,h[13]=Re>>>8&255,h[14]=Re>>>16&255,h[15]=Re>>>24&255,h[16]=T>>>0&255,h[17]=T>>>8&255,h[18]=T>>>16&255,h[19]=T>>>24&255,h[20]=E>>>0&255,h[21]=E>>>8&255,h[22]=E>>>16&255,h[23]=E>>>24&255,h[24]=q>>>0&255,h[25]=q>>>8&255,h[26]=q>>>16&255,h[27]=q>>>24&255,h[28]=N>>>0&255,h[29]=N>>>8&255,h[30]=N>>>16&255,h[31]=N>>>24&255}function z(h,d,u,i){At(h,d,u,i)}function W(h,d,u,i){Rt(h,d,u,i)}var _=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function le(h,d,u,i,y,C,O){var B=new Uint8Array(16),$=new Uint8Array(64),ae,Y;for(Y=0;Y<16;Y++)B[Y]=0;for(Y=0;Y<8;Y++)B[Y]=C[Y];for(;y>=64;){for(z($,B,O,_),Y=0;Y<64;Y++)h[d+Y]=u[i+Y]^$[Y];for(ae=1,Y=8;Y<16;Y++)ae=ae+(B[Y]&255)|0,B[Y]=ae&255,ae>>>=8;y-=64,d+=64,i+=64}if(y>0)for(z($,B,O,_),Y=0;Y<y;Y++)h[d+Y]=u[i+Y]^$[Y];return 0}function he(h,d,u,i,y){var C=new Uint8Array(16),O=new Uint8Array(64),B,$;for($=0;$<16;$++)C[$]=0;for($=0;$<8;$++)C[$]=i[$];for(;u>=64;){for(z(O,C,y,_),$=0;$<64;$++)h[d+$]=O[$];for(B=1,$=8;$<16;$++)B=B+(C[$]&255)|0,C[$]=B&255,B>>>=8;u-=64,d+=64}if(u>0)for(z(O,C,y,_),$=0;$<u;$++)h[d+$]=O[$];return 0}function He(h,d,u,i,y){var C=new Uint8Array(32);W(C,i,y,_);for(var O=new Uint8Array(8),B=0;B<8;B++)O[B]=i[B+16];return he(h,d,u,O,C)}function Te(h,d,u,i,y,C,O){var B=new Uint8Array(32);W(B,C,O,_);for(var $=new Uint8Array(8),ae=0;ae<8;ae++)$[ae]=C[ae+16];return le(h,d,u,i,y,$,B)}var $e=function(h){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var d,u,i,y,C,O,B,$;d=h[0]&255|(h[1]&255)<<8,this.r[0]=d&8191,u=h[2]&255|(h[3]&255)<<8,this.r[1]=(d>>>13|u<<3)&8191,i=h[4]&255|(h[5]&255)<<8,this.r[2]=(u>>>10|i<<6)&7939,y=h[6]&255|(h[7]&255)<<8,this.r[3]=(i>>>7|y<<9)&8191,C=h[8]&255|(h[9]&255)<<8,this.r[4]=(y>>>4|C<<12)&255,this.r[5]=C>>>1&8190,O=h[10]&255|(h[11]&255)<<8,this.r[6]=(C>>>14|O<<2)&8191,B=h[12]&255|(h[13]&255)<<8,this.r[7]=(O>>>11|B<<5)&8065,$=h[14]&255|(h[15]&255)<<8,this.r[8]=(B>>>8|$<<8)&8191,this.r[9]=$>>>5&127,this.pad[0]=h[16]&255|(h[17]&255)<<8,this.pad[1]=h[18]&255|(h[19]&255)<<8,this.pad[2]=h[20]&255|(h[21]&255)<<8,this.pad[3]=h[22]&255|(h[23]&255)<<8,this.pad[4]=h[24]&255|(h[25]&255)<<8,this.pad[5]=h[26]&255|(h[27]&255)<<8,this.pad[6]=h[28]&255|(h[29]&255)<<8,this.pad[7]=h[30]&255|(h[31]&255)<<8};$e.prototype.blocks=function(h,d,u){for(var i=this.fin?0:2048,y,C,O,B,$,ae,Y,Me,ee,ge,be,Ae,V,xe,we,me,te,K,Z,ie=this.h[0],re=this.h[1],Q=this.h[2],T=this.h[3],E=this.h[4],q=this.h[5],N=this.h[6],G=this.h[7],j=this.h[8],ue=this.h[9],ke=this.r[0],Ce=this.r[1],Re=this.r[2],w=this.r[3],Ee=this.r[4],Oe=this.r[5],Pe=this.r[6],ve=this.r[7],Le=this.r[8],Ue=this.r[9];u>=16;)y=h[d+0]&255|(h[d+1]&255)<<8,ie+=y&8191,C=h[d+2]&255|(h[d+3]&255)<<8,re+=(y>>>13|C<<3)&8191,O=h[d+4]&255|(h[d+5]&255)<<8,Q+=(C>>>10|O<<6)&8191,B=h[d+6]&255|(h[d+7]&255)<<8,T+=(O>>>7|B<<9)&8191,$=h[d+8]&255|(h[d+9]&255)<<8,E+=(B>>>4|$<<12)&8191,q+=$>>>1&8191,ae=h[d+10]&255|(h[d+11]&255)<<8,N+=($>>>14|ae<<2)&8191,Y=h[d+12]&255|(h[d+13]&255)<<8,G+=(ae>>>11|Y<<5)&8191,Me=h[d+14]&255|(h[d+15]&255)<<8,j+=(Y>>>8|Me<<8)&8191,ue+=Me>>>5|i,ee=0,ge=ee,ge+=ie*ke,ge+=re*(5*Ue),ge+=Q*(5*Le),ge+=T*(5*ve),ge+=E*(5*Pe),ee=ge>>>13,ge&=8191,ge+=q*(5*Oe),ge+=N*(5*Ee),ge+=G*(5*w),ge+=j*(5*Re),ge+=ue*(5*Ce),ee+=ge>>>13,ge&=8191,be=ee,be+=ie*Ce,be+=re*ke,be+=Q*(5*Ue),be+=T*(5*Le),be+=E*(5*ve),ee=be>>>13,be&=8191,be+=q*(5*Pe),be+=N*(5*Oe),be+=G*(5*Ee),be+=j*(5*w),be+=ue*(5*Re),ee+=be>>>13,be&=8191,Ae=ee,Ae+=ie*Re,Ae+=re*Ce,Ae+=Q*ke,Ae+=T*(5*Ue),Ae+=E*(5*Le),ee=Ae>>>13,Ae&=8191,Ae+=q*(5*ve),Ae+=N*(5*Pe),Ae+=G*(5*Oe),Ae+=j*(5*Ee),Ae+=ue*(5*w),ee+=Ae>>>13,Ae&=8191,V=ee,V+=ie*w,V+=re*Re,V+=Q*Ce,V+=T*ke,V+=E*(5*Ue),ee=V>>>13,V&=8191,V+=q*(5*Le),V+=N*(5*ve),V+=G*(5*Pe),V+=j*(5*Oe),V+=ue*(5*Ee),ee+=V>>>13,V&=8191,xe=ee,xe+=ie*Ee,xe+=re*w,xe+=Q*Re,xe+=T*Ce,xe+=E*ke,ee=xe>>>13,xe&=8191,xe+=q*(5*Ue),xe+=N*(5*Le),xe+=G*(5*ve),xe+=j*(5*Pe),xe+=ue*(5*Oe),ee+=xe>>>13,xe&=8191,we=ee,we+=ie*Oe,we+=re*Ee,we+=Q*w,we+=T*Re,we+=E*Ce,ee=we>>>13,we&=8191,we+=q*ke,we+=N*(5*Ue),we+=G*(5*Le),we+=j*(5*ve),we+=ue*(5*Pe),ee+=we>>>13,we&=8191,me=ee,me+=ie*Pe,me+=re*Oe,me+=Q*Ee,me+=T*w,me+=E*Re,ee=me>>>13,me&=8191,me+=q*Ce,me+=N*ke,me+=G*(5*Ue),me+=j*(5*Le),me+=ue*(5*ve),ee+=me>>>13,me&=8191,te=ee,te+=ie*ve,te+=re*Pe,te+=Q*Oe,te+=T*Ee,te+=E*w,ee=te>>>13,te&=8191,te+=q*Re,te+=N*Ce,te+=G*ke,te+=j*(5*Ue),te+=ue*(5*Le),ee+=te>>>13,te&=8191,K=ee,K+=ie*Le,K+=re*ve,K+=Q*Pe,K+=T*Oe,K+=E*Ee,ee=K>>>13,K&=8191,K+=q*w,K+=N*Re,K+=G*Ce,K+=j*ke,K+=ue*(5*Ue),ee+=K>>>13,K&=8191,Z=ee,Z+=ie*Ue,Z+=re*Le,Z+=Q*ve,Z+=T*Pe,Z+=E*Oe,ee=Z>>>13,Z&=8191,Z+=q*Ee,Z+=N*w,Z+=G*Re,Z+=j*Ce,Z+=ue*ke,ee+=Z>>>13,Z&=8191,ee=(ee<<2)+ee|0,ee=ee+ge|0,ge=ee&8191,ee=ee>>>13,be+=ee,ie=ge,re=be,Q=Ae,T=V,E=xe,q=we,N=me,G=te,j=K,ue=Z,d+=16,u-=16;this.h[0]=ie,this.h[1]=re,this.h[2]=Q,this.h[3]=T,this.h[4]=E,this.h[5]=q,this.h[6]=N,this.h[7]=G,this.h[8]=j,this.h[9]=ue},$e.prototype.finish=function(h,d){var u=new Uint16Array(10),i,y,C,O;if(this.leftover){for(O=this.leftover,this.buffer[O++]=1;O<16;O++)this.buffer[O]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(i=this.h[1]>>>13,this.h[1]&=8191,O=2;O<10;O++)this.h[O]+=i,i=this.h[O]>>>13,this.h[O]&=8191;for(this.h[0]+=i*5,i=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=i,i=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=i,u[0]=this.h[0]+5,i=u[0]>>>13,u[0]&=8191,O=1;O<10;O++)u[O]=this.h[O]+i,i=u[O]>>>13,u[O]&=8191;for(u[9]-=8192,y=(i^1)-1,O=0;O<10;O++)u[O]&=y;for(y=~y,O=0;O<10;O++)this.h[O]=this.h[O]&y|u[O];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,C=this.h[0]+this.pad[0],this.h[0]=C&65535,O=1;O<8;O++)C=(this.h[O]+this.pad[O]|0)+(C>>>16)|0,this.h[O]=C&65535;h[d+0]=this.h[0]>>>0&255,h[d+1]=this.h[0]>>>8&255,h[d+2]=this.h[1]>>>0&255,h[d+3]=this.h[1]>>>8&255,h[d+4]=this.h[2]>>>0&255,h[d+5]=this.h[2]>>>8&255,h[d+6]=this.h[3]>>>0&255,h[d+7]=this.h[3]>>>8&255,h[d+8]=this.h[4]>>>0&255,h[d+9]=this.h[4]>>>8&255,h[d+10]=this.h[5]>>>0&255,h[d+11]=this.h[5]>>>8&255,h[d+12]=this.h[6]>>>0&255,h[d+13]=this.h[6]>>>8&255,h[d+14]=this.h[7]>>>0&255,h[d+15]=this.h[7]>>>8&255},$e.prototype.update=function(h,d,u){var i,y;if(this.leftover){for(y=16-this.leftover,y>u&&(y=u),i=0;i<y;i++)this.buffer[this.leftover+i]=h[d+i];if(u-=y,d+=y,this.leftover+=y,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(u>=16&&(y=u-u%16,this.blocks(h,d,y),d+=y,u-=y),u){for(i=0;i<u;i++)this.buffer[this.leftover+i]=h[d+i];this.leftover+=u}};function bt(h,d,u,i,y,C){var O=new $e(C);return O.update(u,i,y),O.finish(h,d),0}function c(h,d,u,i,y,C){var O=new Uint8Array(16);return bt(O,0,u,i,y,C),Ne(h,d,O,0)}function xt(h,d,u,i,y){var C;if(u<32)return-1;for(Te(h,0,d,0,u,i,y),bt(h,16,h,32,u-32,h),C=0;C<16;C++)h[C]=0;return 0}function dn(h,d,u,i,y){var C,O=new Uint8Array(32);if(u<32||(He(O,0,32,i,y),c(d,16,d,32,u-32,O)!==0))return-1;for(Te(h,0,d,0,u,i,y),C=0;C<32;C++)h[C]=0;return 0}function S(h,d){var u;for(u=0;u<16;u++)h[u]=d[u]|0}function et(h){var d,u,i=1;for(d=0;d<16;d++)u=h[d]+i+65535,i=Math.floor(u/65536),h[d]=u-i*65536;h[0]+=i-1+37*(i-1)}function Gt(h,d,u){for(var i,y=~(u-1),C=0;C<16;C++)i=y&(h[C]^d[C]),h[C]^=i,d[C]^=i}function pe(h,d){var u,i,y,C=l(),O=l();for(u=0;u<16;u++)O[u]=d[u];for(et(O),et(O),et(O),i=0;i<2;i++){for(C[0]=O[0]-65517,u=1;u<15;u++)C[u]=O[u]-65535-(C[u-1]>>16&1),C[u-1]&=65535;C[15]=O[15]-32767-(C[14]>>16&1),y=C[15]>>16&1,C[14]&=65535,Gt(O,C,1-y)}for(u=0;u<16;u++)h[2*u]=O[u]&255,h[2*u+1]=O[u]>>8}function Pt(h,d){var u=new Uint8Array(32),i=new Uint8Array(32);return pe(u,h),pe(i,d),ht(u,0,i,0)}function In(h){var d=new Uint8Array(32);return pe(d,h),d[0]&1}function Ct(h,d){var u;for(u=0;u<16;u++)h[u]=d[2*u]+(d[2*u+1]<<8);h[15]&=32767}function gt(h,d,u){for(var i=0;i<16;i++)h[i]=d[i]+u[i]}function Ke(h,d,u){for(var i=0;i<16;i++)h[i]=d[i]-u[i]}function Ie(h,d,u){var i,y,C=0,O=0,B=0,$=0,ae=0,Y=0,Me=0,ee=0,ge=0,be=0,Ae=0,V=0,xe=0,we=0,me=0,te=0,K=0,Z=0,ie=0,re=0,Q=0,T=0,E=0,q=0,N=0,G=0,j=0,ue=0,ke=0,Ce=0,Re=0,w=u[0],Ee=u[1],Oe=u[2],Pe=u[3],ve=u[4],Le=u[5],Ue=u[6],Qe=u[7],De=u[8],ze=u[9],Ye=u[10],Se=u[11],X=u[12],nt=u[13],je=u[14],st=u[15];i=d[0],C+=i*w,O+=i*Ee,B+=i*Oe,$+=i*Pe,ae+=i*ve,Y+=i*Le,Me+=i*Ue,ee+=i*Qe,ge+=i*De,be+=i*ze,Ae+=i*Ye,V+=i*Se,xe+=i*X,we+=i*nt,me+=i*je,te+=i*st,i=d[1],O+=i*w,B+=i*Ee,$+=i*Oe,ae+=i*Pe,Y+=i*ve,Me+=i*Le,ee+=i*Ue,ge+=i*Qe,be+=i*De,Ae+=i*ze,V+=i*Ye,xe+=i*Se,we+=i*X,me+=i*nt,te+=i*je,K+=i*st,i=d[2],B+=i*w,$+=i*Ee,ae+=i*Oe,Y+=i*Pe,Me+=i*ve,ee+=i*Le,ge+=i*Ue,be+=i*Qe,Ae+=i*De,V+=i*ze,xe+=i*Ye,we+=i*Se,me+=i*X,te+=i*nt,K+=i*je,Z+=i*st,i=d[3],$+=i*w,ae+=i*Ee,Y+=i*Oe,Me+=i*Pe,ee+=i*ve,ge+=i*Le,be+=i*Ue,Ae+=i*Qe,V+=i*De,xe+=i*ze,we+=i*Ye,me+=i*Se,te+=i*X,K+=i*nt,Z+=i*je,ie+=i*st,i=d[4],ae+=i*w,Y+=i*Ee,Me+=i*Oe,ee+=i*Pe,ge+=i*ve,be+=i*Le,Ae+=i*Ue,V+=i*Qe,xe+=i*De,we+=i*ze,me+=i*Ye,te+=i*Se,K+=i*X,Z+=i*nt,ie+=i*je,re+=i*st,i=d[5],Y+=i*w,Me+=i*Ee,ee+=i*Oe,ge+=i*Pe,be+=i*ve,Ae+=i*Le,V+=i*Ue,xe+=i*Qe,we+=i*De,me+=i*ze,te+=i*Ye,K+=i*Se,Z+=i*X,ie+=i*nt,re+=i*je,Q+=i*st,i=d[6],Me+=i*w,ee+=i*Ee,ge+=i*Oe,be+=i*Pe,Ae+=i*ve,V+=i*Le,xe+=i*Ue,we+=i*Qe,me+=i*De,te+=i*ze,K+=i*Ye,Z+=i*Se,ie+=i*X,re+=i*nt,Q+=i*je,T+=i*st,i=d[7],ee+=i*w,ge+=i*Ee,be+=i*Oe,Ae+=i*Pe,V+=i*ve,xe+=i*Le,we+=i*Ue,me+=i*Qe,te+=i*De,K+=i*ze,Z+=i*Ye,ie+=i*Se,re+=i*X,Q+=i*nt,T+=i*je,E+=i*st,i=d[8],ge+=i*w,be+=i*Ee,Ae+=i*Oe,V+=i*Pe,xe+=i*ve,we+=i*Le,me+=i*Ue,te+=i*Qe,K+=i*De,Z+=i*ze,ie+=i*Ye,re+=i*Se,Q+=i*X,T+=i*nt,E+=i*je,q+=i*st,i=d[9],be+=i*w,Ae+=i*Ee,V+=i*Oe,xe+=i*Pe,we+=i*ve,me+=i*Le,te+=i*Ue,K+=i*Qe,Z+=i*De,ie+=i*ze,re+=i*Ye,Q+=i*Se,T+=i*X,E+=i*nt,q+=i*je,N+=i*st,i=d[10],Ae+=i*w,V+=i*Ee,xe+=i*Oe,we+=i*Pe,me+=i*ve,te+=i*Le,K+=i*Ue,Z+=i*Qe,ie+=i*De,re+=i*ze,Q+=i*Ye,T+=i*Se,E+=i*X,q+=i*nt,N+=i*je,G+=i*st,i=d[11],V+=i*w,xe+=i*Ee,we+=i*Oe,me+=i*Pe,te+=i*ve,K+=i*Le,Z+=i*Ue,ie+=i*Qe,re+=i*De,Q+=i*ze,T+=i*Ye,E+=i*Se,q+=i*X,N+=i*nt,G+=i*je,j+=i*st,i=d[12],xe+=i*w,we+=i*Ee,me+=i*Oe,te+=i*Pe,K+=i*ve,Z+=i*Le,ie+=i*Ue,re+=i*Qe,Q+=i*De,T+=i*ze,E+=i*Ye,q+=i*Se,N+=i*X,G+=i*nt,j+=i*je,ue+=i*st,i=d[13],we+=i*w,me+=i*Ee,te+=i*Oe,K+=i*Pe,Z+=i*ve,ie+=i*Le,re+=i*Ue,Q+=i*Qe,T+=i*De,E+=i*ze,q+=i*Ye,N+=i*Se,G+=i*X,j+=i*nt,ue+=i*je,ke+=i*st,i=d[14],me+=i*w,te+=i*Ee,K+=i*Oe,Z+=i*Pe,ie+=i*ve,re+=i*Le,Q+=i*Ue,T+=i*Qe,E+=i*De,q+=i*ze,N+=i*Ye,G+=i*Se,j+=i*X,ue+=i*nt,ke+=i*je,Ce+=i*st,i=d[15],te+=i*w,K+=i*Ee,Z+=i*Oe,ie+=i*Pe,re+=i*ve,Q+=i*Le,T+=i*Ue,E+=i*Qe,q+=i*De,N+=i*ze,G+=i*Ye,j+=i*Se,ue+=i*X,ke+=i*nt,Ce+=i*je,Re+=i*st,C+=38*K,O+=38*Z,B+=38*ie,$+=38*re,ae+=38*Q,Y+=38*T,Me+=38*E,ee+=38*q,ge+=38*N,be+=38*G,Ae+=38*j,V+=38*ue,xe+=38*ke,we+=38*Ce,me+=38*Re,y=1,i=C+y+65535,y=Math.floor(i/65536),C=i-y*65536,i=O+y+65535,y=Math.floor(i/65536),O=i-y*65536,i=B+y+65535,y=Math.floor(i/65536),B=i-y*65536,i=$+y+65535,y=Math.floor(i/65536),$=i-y*65536,i=ae+y+65535,y=Math.floor(i/65536),ae=i-y*65536,i=Y+y+65535,y=Math.floor(i/65536),Y=i-y*65536,i=Me+y+65535,y=Math.floor(i/65536),Me=i-y*65536,i=ee+y+65535,y=Math.floor(i/65536),ee=i-y*65536,i=ge+y+65535,y=Math.floor(i/65536),ge=i-y*65536,i=be+y+65535,y=Math.floor(i/65536),be=i-y*65536,i=Ae+y+65535,y=Math.floor(i/65536),Ae=i-y*65536,i=V+y+65535,y=Math.floor(i/65536),V=i-y*65536,i=xe+y+65535,y=Math.floor(i/65536),xe=i-y*65536,i=we+y+65535,y=Math.floor(i/65536),we=i-y*65536,i=me+y+65535,y=Math.floor(i/65536),me=i-y*65536,i=te+y+65535,y=Math.floor(i/65536),te=i-y*65536,C+=y-1+37*(y-1),y=1,i=C+y+65535,y=Math.floor(i/65536),C=i-y*65536,i=O+y+65535,y=Math.floor(i/65536),O=i-y*65536,i=B+y+65535,y=Math.floor(i/65536),B=i-y*65536,i=$+y+65535,y=Math.floor(i/65536),$=i-y*65536,i=ae+y+65535,y=Math.floor(i/65536),ae=i-y*65536,i=Y+y+65535,y=Math.floor(i/65536),Y=i-y*65536,i=Me+y+65535,y=Math.floor(i/65536),Me=i-y*65536,i=ee+y+65535,y=Math.floor(i/65536),ee=i-y*65536,i=ge+y+65535,y=Math.floor(i/65536),ge=i-y*65536,i=be+y+65535,y=Math.floor(i/65536),be=i-y*65536,i=Ae+y+65535,y=Math.floor(i/65536),Ae=i-y*65536,i=V+y+65535,y=Math.floor(i/65536),V=i-y*65536,i=xe+y+65535,y=Math.floor(i/65536),xe=i-y*65536,i=we+y+65535,y=Math.floor(i/65536),we=i-y*65536,i=me+y+65535,y=Math.floor(i/65536),me=i-y*65536,i=te+y+65535,y=Math.floor(i/65536),te=i-y*65536,C+=y-1+37*(y-1),h[0]=C,h[1]=O,h[2]=B,h[3]=$,h[4]=ae,h[5]=Y,h[6]=Me,h[7]=ee,h[8]=ge,h[9]=be,h[10]=Ae,h[11]=V,h[12]=xe,h[13]=we,h[14]=me,h[15]=te}function it(h,d){Ie(h,d,d)}function cs(h,d){var u=l(),i;for(i=0;i<16;i++)u[i]=d[i];for(i=253;i>=0;i--)it(u,u),i!==2&&i!==4&&Ie(u,u,d);for(i=0;i<16;i++)h[i]=u[i]}function ls(h,d){var u=l(),i;for(i=0;i<16;i++)u[i]=d[i];for(i=250;i>=0;i--)it(u,u),i!==1&&Ie(u,u,d);for(i=0;i<16;i++)h[i]=u[i]}function en(h,d,u){var i=new Uint8Array(32),y=new Float64Array(80),C,O,B=l(),$=l(),ae=l(),Y=l(),Me=l(),ee=l();for(O=0;O<31;O++)i[O]=d[O];for(i[31]=d[31]&127|64,i[0]&=248,Ct(y,u),O=0;O<16;O++)$[O]=y[O],Y[O]=B[O]=ae[O]=0;for(B[0]=Y[0]=1,O=254;O>=0;--O)C=i[O>>>3]>>>(O&7)&1,Gt(B,$,C),Gt(ae,Y,C),gt(Me,B,ae),Ke(B,B,ae),gt(ae,$,Y),Ke($,$,Y),it(Y,Me),it(ee,B),Ie(B,ae,B),Ie(ae,$,Me),gt(Me,B,ae),Ke(B,B,ae),it($,B),Ke(ae,Y,ee),Ie(B,ae,I),gt(B,B,Y),Ie(ae,ae,B),Ie(B,Y,ee),Ie(Y,$,y),it($,Me),Gt(B,$,C),Gt(ae,Y,C);for(O=0;O<16;O++)y[O+16]=B[O],y[O+32]=ae[O],y[O+48]=$[O],y[O+64]=Y[O];var ge=y.subarray(32),be=y.subarray(16);return cs(ge,ge),Ie(be,be,ge),pe(h,be),0}function tn(h,d){return en(h,d,x)}function Pn(h,d){return p(d,32),tn(h,d)}function nn(h,d,u){var i=new Uint8Array(32);return en(i,u,d),W(h,m,i,_)}var hs=xt,sn=dn;function fs(h,d,u,i,y,C){var O=new Uint8Array(32);return nn(O,y,C),hs(h,d,u,i,O)}function us(h,d,u,i,y,C){var O=new Uint8Array(32);return nn(O,y,C),sn(h,d,u,i,O)}var ds=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function Ln(h,d,u,i){for(var y=new Int32Array(16),C=new Int32Array(16),O,B,$,ae,Y,Me,ee,ge,be,Ae,V,xe,we,me,te,K,Z,ie,re,Q,T,E,q,N,G,j,ue=h[0],ke=h[1],Ce=h[2],Re=h[3],w=h[4],Ee=h[5],Oe=h[6],Pe=h[7],ve=d[0],Le=d[1],Ue=d[2],Qe=d[3],De=d[4],ze=d[5],Ye=d[6],Se=d[7],X=0;i>=128;){for(re=0;re<16;re++)Q=8*re+X,y[re]=u[Q+0]<<24|u[Q+1]<<16|u[Q+2]<<8|u[Q+3],C[re]=u[Q+4]<<24|u[Q+5]<<16|u[Q+6]<<8|u[Q+7];for(re=0;re<80;re++)if(O=ue,B=ke,$=Ce,ae=Re,Y=w,Me=Ee,ee=Oe,ge=Pe,be=ve,Ae=Le,V=Ue,xe=Qe,we=De,me=ze,te=Ye,K=Se,T=Pe,E=Se,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=(w>>>14|De<<18)^(w>>>18|De<<14)^(De>>>9|w<<23),E=(De>>>14|w<<18)^(De>>>18|w<<14)^(w>>>9|De<<23),q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,T=w&Ee^~w&Oe,E=De&ze^~De&Ye,q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,T=ds[re*2],E=ds[re*2+1],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,T=y[re%16],E=C[re%16],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,Z=G&65535|j<<16,ie=q&65535|N<<16,T=Z,E=ie,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=(ue>>>28|ve<<4)^(ve>>>2|ue<<30)^(ve>>>7|ue<<25),E=(ve>>>28|ue<<4)^(ue>>>2|ve<<30)^(ue>>>7|ve<<25),q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,T=ue&ke^ue&Ce^ke&Ce,E=ve&Le^ve&Ue^Le&Ue,q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,ge=G&65535|j<<16,K=q&65535|N<<16,T=ae,E=xe,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=Z,E=ie,q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,ae=G&65535|j<<16,xe=q&65535|N<<16,ke=O,Ce=B,Re=$,w=ae,Ee=Y,Oe=Me,Pe=ee,ue=ge,Le=be,Ue=Ae,Qe=V,De=xe,ze=we,Ye=me,Se=te,ve=K,re%16===15)for(Q=0;Q<16;Q++)T=y[Q],E=C[Q],q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=y[(Q+9)%16],E=C[(Q+9)%16],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,Z=y[(Q+1)%16],ie=C[(Q+1)%16],T=(Z>>>1|ie<<31)^(Z>>>8|ie<<24)^Z>>>7,E=(ie>>>1|Z<<31)^(ie>>>8|Z<<24)^(ie>>>7|Z<<25),q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,Z=y[(Q+14)%16],ie=C[(Q+14)%16],T=(Z>>>19|ie<<13)^(ie>>>29|Z<<3)^Z>>>6,E=(ie>>>19|Z<<13)^(Z>>>29|ie<<3)^(ie>>>6|Z<<26),q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,y[Q]=G&65535|j<<16,C[Q]=q&65535|N<<16;T=ue,E=ve,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[0],E=d[0],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[0]=ue=G&65535|j<<16,d[0]=ve=q&65535|N<<16,T=ke,E=Le,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[1],E=d[1],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[1]=ke=G&65535|j<<16,d[1]=Le=q&65535|N<<16,T=Ce,E=Ue,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[2],E=d[2],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[2]=Ce=G&65535|j<<16,d[2]=Ue=q&65535|N<<16,T=Re,E=Qe,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[3],E=d[3],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[3]=Re=G&65535|j<<16,d[3]=Qe=q&65535|N<<16,T=w,E=De,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[4],E=d[4],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[4]=w=G&65535|j<<16,d[4]=De=q&65535|N<<16,T=Ee,E=ze,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[5],E=d[5],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[5]=Ee=G&65535|j<<16,d[5]=ze=q&65535|N<<16,T=Oe,E=Ye,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[6],E=d[6],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[6]=Oe=G&65535|j<<16,d[6]=Ye=q&65535|N<<16,T=Pe,E=Se,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[7],E=d[7],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[7]=Pe=G&65535|j<<16,d[7]=Se=q&65535|N<<16,X+=128,i-=128}return i}function wt(h,d,u){var i=new Int32Array(8),y=new Int32Array(8),C=new Uint8Array(256),O,B=u;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,y[0]=4089235720,y[1]=2227873595,y[2]=4271175723,y[3]=1595750129,y[4]=2917565137,y[5]=725511199,y[6]=4215389547,y[7]=327033209,Ln(i,y,d,u),u%=128,O=0;O<u;O++)C[O]=d[B-u+O];for(C[u]=128,u=256-128*(u<112?1:0),C[u-9]=0,fe(C,u-8,B/536870912|0,B<<3),Ln(i,y,C,u),O=0;O<8;O++)fe(h,8*O,i[O],y[O]);return 0}function Ot(h,d){var u=l(),i=l(),y=l(),C=l(),O=l(),B=l(),$=l(),ae=l(),Y=l();Ke(u,h[1],h[0]),Ke(Y,d[1],d[0]),Ie(u,u,Y),gt(i,h[0],h[1]),gt(Y,d[0],d[1]),Ie(i,i,Y),Ie(y,h[3],d[3]),Ie(y,y,D),Ie(C,h[2],d[2]),gt(C,C,C),Ke(O,i,u),Ke(B,C,y),gt($,C,y),gt(ae,i,u),Ie(h[0],O,B),Ie(h[1],ae,$),Ie(h[2],$,B),Ie(h[3],O,ae)}function pn(h,d,u){var i;for(i=0;i<4;i++)Gt(h[i],d[i],u)}function qt(h,d){var u=l(),i=l(),y=l();cs(y,d[2]),Ie(u,d[0],y),Ie(i,d[1],y),pe(h,i),h[31]^=In(u)<<7}function rn(h,d,u){var i,y;for(S(h[0],k),S(h[1],v),S(h[2],v),S(h[3],k),y=255;y>=0;--y)i=u[y/8|0]>>(y&7)&1,pn(h,d,i),Ot(d,h),Ot(h,h),pn(h,d,i)}function Ge(h,d){var u=[l(),l(),l(),l()];S(u[0],J),S(u[1],oe),S(u[2],v),Ie(u[3],J,oe),rn(h,u,d)}function gn(h,d,u){var i=new Uint8Array(64),y=[l(),l(),l(),l()],C;for(u||p(d,32),wt(i,d,32),i[0]&=248,i[31]&=127,i[31]|=64,Ge(y,i),qt(h,y),C=0;C<32;C++)d[C+32]=h[C];return 0}var on=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Ht(h,d){var u,i,y,C;for(i=63;i>=32;--i){for(u=0,y=i-32,C=i-12;y<C;++y)d[y]+=u-16*d[i]*on[y-(i-32)],u=Math.floor((d[y]+128)/256),d[y]-=u*256;d[y]+=u,d[i]=0}for(u=0,y=0;y<32;y++)d[y]+=u-(d[31]>>4)*on[y],u=d[y]>>8,d[y]&=255;for(y=0;y<32;y++)d[y]-=u*on[y];for(i=0;i<32;i++)d[i+1]+=d[i]>>8,h[i]=d[i]&255}function mn(h){var d=new Float64Array(64),u;for(u=0;u<64;u++)d[u]=h[u];for(u=0;u<64;u++)h[u]=0;Ht(h,d)}function Un(h,d,u,i){var y=new Uint8Array(64),C=new Uint8Array(64),O=new Uint8Array(64),B,$,ae=new Float64Array(64),Y=[l(),l(),l(),l()];wt(y,i,32),y[0]&=248,y[31]&=127,y[31]|=64;var Me=u+64;for(B=0;B<u;B++)h[64+B]=d[B];for(B=0;B<32;B++)h[32+B]=y[32+B];for(wt(O,h.subarray(32),u+32),mn(O),Ge(Y,O),qt(h,Y),B=32;B<64;B++)h[B]=i[B];for(wt(C,h,u+64),mn(C),B=0;B<64;B++)ae[B]=0;for(B=0;B<32;B++)ae[B]=O[B];for(B=0;B<32;B++)for($=0;$<32;$++)ae[B+$]+=C[B]*y[$];return Ht(h.subarray(32),ae),Me}function ot(h,d){var u=l(),i=l(),y=l(),C=l(),O=l(),B=l(),$=l();return S(h[2],v),Ct(h[1],d),it(y,h[1]),Ie(C,y,M),Ke(y,y,h[2]),gt(C,h[2],C),it(O,C),it(B,O),Ie($,B,O),Ie(u,$,y),Ie(u,u,C),ls(u,u),Ie(u,u,y),Ie(u,u,C),Ie(u,u,C),Ie(h[0],u,C),it(i,h[0]),Ie(i,i,C),Pt(i,y)&&Ie(h[0],h[0],H),it(i,h[0]),Ie(i,i,C),Pt(i,y)?-1:(In(h[0])===d[31]>>7&&Ke(h[0],k,h[0]),Ie(h[3],h[0],h[1]),0)}function Ze(h,d,u,i){var y,C=new Uint8Array(32),O=new Uint8Array(64),B=[l(),l(),l(),l()],$=[l(),l(),l(),l()];if(u<64||ot($,i))return-1;for(y=0;y<u;y++)h[y]=d[y];for(y=0;y<32;y++)h[y+32]=i[y];if(wt(O,h,u),mn(O),rn(B,$,O),Ge($,d.subarray(32)),Ot(B,$),qt(C,B),u-=64,ht(d,0,C,0)){for(y=0;y<u;y++)h[y]=0;return-1}for(y=0;y<u;y++)h[y]=d[y+64];return u}var at=32,Dt=24,jt=32,Lt=16,Wt=32,Vt=32,Ut=32,$t=32,yn=32,an=Dt,ps=jt,bn=Lt,Fe=64,St=32,Ft=64,xn=32,Bn=64;o.lowlevel={crypto_core_hsalsa20:W,crypto_stream_xor:Te,crypto_stream:He,crypto_stream_salsa20_xor:le,crypto_stream_salsa20:he,crypto_onetimeauth:bt,crypto_onetimeauth_verify:c,crypto_verify_16:Ne,crypto_verify_32:ht,crypto_secretbox:xt,crypto_secretbox_open:dn,crypto_scalarmult:en,crypto_scalarmult_base:tn,crypto_box_beforenm:nn,crypto_box_afternm:hs,crypto_box:fs,crypto_box_open:us,crypto_box_keypair:Pn,crypto_hash:wt,crypto_sign:Un,crypto_sign_keypair:gn,crypto_sign_open:Ze,crypto_secretbox_KEYBYTES:at,crypto_secretbox_NONCEBYTES:Dt,crypto_secretbox_ZEROBYTES:jt,crypto_secretbox_BOXZEROBYTES:Lt,crypto_scalarmult_BYTES:Wt,crypto_scalarmult_SCALARBYTES:Vt,crypto_box_PUBLICKEYBYTES:Ut,crypto_box_SECRETKEYBYTES:$t,crypto_box_BEFORENMBYTES:yn,crypto_box_NONCEBYTES:an,crypto_box_ZEROBYTES:ps,crypto_box_BOXZEROBYTES:bn,crypto_sign_BYTES:Fe,crypto_sign_PUBLICKEYBYTES:St,crypto_sign_SECRETKEYBYTES:Ft,crypto_sign_SEEDBYTES:xn,crypto_hash_BYTES:Bn,gf:l,D:M,L:on,pack25519:pe,unpack25519:Ct,M:Ie,A:gt,S:it,Z:Ke,pow2523:ls,add:Ot,set25519:S,modL:Ht,scalarmult:rn,scalarbase:Ge};function ft(h,d){if(h.length!==at)throw new Error("bad key size");if(d.length!==Dt)throw new Error("bad nonce size")}function Ns(h,d){if(h.length!==Ut)throw new Error("bad public key size");if(d.length!==$t)throw new Error("bad secret key size")}function ct(){for(var h=0;h<arguments.length;h++)if(!(arguments[h]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function Nn(h){for(var d=0;d<h.length;d++)h[d]=0}o.randomBytes=function(h){var d=new Uint8Array(h);return p(d,h),d},o.secretbox=function(h,d,u){ct(h,d,u),ft(u,d);for(var i=new Uint8Array(jt+h.length),y=new Uint8Array(i.length),C=0;C<h.length;C++)i[C+jt]=h[C];return xt(y,i,i.length,d,u),y.subarray(Lt)},o.secretbox.open=function(h,d,u){ct(h,d,u),ft(u,d);for(var i=new Uint8Array(Lt+h.length),y=new Uint8Array(i.length),C=0;C<h.length;C++)i[C+Lt]=h[C];return i.length<32||dn(y,i,i.length,d,u)!==0?null:y.subarray(jt)},o.secretbox.keyLength=at,o.secretbox.nonceLength=Dt,o.secretbox.overheadLength=Lt,o.scalarMult=function(h,d){if(ct(h,d),h.length!==Vt)throw new Error("bad n size");if(d.length!==Wt)throw new Error("bad p size");var u=new Uint8Array(Wt);return en(u,h,d),u},o.scalarMult.base=function(h){if(ct(h),h.length!==Vt)throw new Error("bad n size");var d=new Uint8Array(Wt);return tn(d,h),d},o.scalarMult.scalarLength=Vt,o.scalarMult.groupElementLength=Wt,o.box=function(h,d,u,i){var y=o.box.before(u,i);return o.secretbox(h,d,y)},o.box.before=function(h,d){ct(h,d),Ns(h,d);var u=new Uint8Array(yn);return nn(u,h,d),u},o.box.after=o.secretbox,o.box.open=function(h,d,u,i){var y=o.box.before(u,i);return o.secretbox.open(h,d,y)},o.box.open.after=o.secretbox.open,o.box.keyPair=function(){var h=new Uint8Array(Ut),d=new Uint8Array($t);return Pn(h,d),{publicKey:h,secretKey:d}},o.box.keyPair.fromSecretKey=function(h){if(ct(h),h.length!==$t)throw new Error("bad secret key size");var d=new Uint8Array(Ut);return tn(d,h),{publicKey:d,secretKey:new Uint8Array(h)}},o.box.publicKeyLength=Ut,o.box.secretKeyLength=$t,o.box.sharedKeyLength=yn,o.box.nonceLength=an,o.box.overheadLength=o.secretbox.overheadLength,o.sign=function(h,d){if(ct(h,d),d.length!==Ft)throw new Error("bad secret key size");var u=new Uint8Array(Fe+h.length);return Un(u,h,h.length,d),u},o.sign.open=function(h,d){if(ct(h,d),d.length!==St)throw new Error("bad public key size");var u=new Uint8Array(h.length),i=Ze(u,h,h.length,d);if(i<0)return null;for(var y=new Uint8Array(i),C=0;C<y.length;C++)y[C]=u[C];return y},o.sign.detached=function(h,d){for(var u=o.sign(h,d),i=new Uint8Array(Fe),y=0;y<i.length;y++)i[y]=u[y];return i},o.sign.detached.verify=function(h,d,u){if(ct(h,d,u),d.length!==Fe)throw new Error("bad signature size");if(u.length!==St)throw new Error("bad public key size");var i=new Uint8Array(Fe+h.length),y=new Uint8Array(Fe+h.length),C;for(C=0;C<Fe;C++)i[C]=d[C];for(C=0;C<h.length;C++)i[C+Fe]=h[C];return Ze(y,i,i.length,u)>=0},o.sign.keyPair=function(){var h=new Uint8Array(St),d=new Uint8Array(Ft);return gn(h,d),{publicKey:h,secretKey:d}},o.sign.keyPair.fromSecretKey=function(h){if(ct(h),h.length!==Ft)throw new Error("bad secret key size");for(var d=new Uint8Array(St),u=0;u<d.length;u++)d[u]=h[32+u];return{publicKey:d,secretKey:new Uint8Array(h)}},o.sign.keyPair.fromSeed=function(h){if(ct(h),h.length!==xn)throw new Error("bad seed size");for(var d=new Uint8Array(St),u=new Uint8Array(Ft),i=0;i<32;i++)u[i]=h[i];return gn(d,u,!0),{publicKey:d,secretKey:u}},o.sign.publicKeyLength=St,o.sign.secretKeyLength=Ft,o.sign.seedLength=xn,o.sign.signatureLength=Fe,o.hash=function(h){ct(h);var d=new Uint8Array(Bn);return wt(d,h,h.length),d},o.hash.hashLength=Bn,o.verify=function(h,d){return ct(h,d),h.length===0||d.length===0||h.length!==d.length?!1:de(h,0,d,0,h.length)===0},o.setPRNG=function(h){p=h},(function(){var h=typeof self<"u"?self.crypto||self.msCrypto:null;if(h&&h.getRandomValues){var d=65536;o.setPRNG(function(u,i){var y,C=new Uint8Array(i);for(y=0;y<i;y+=d)h.getRandomValues(C.subarray(y,y+Math.min(i-y,d)));for(y=0;y<i;y++)u[y]=C[y];Nn(C)})}else typeof tl<"u"&&(h=rl,h&&h.randomBytes&&o.setPRNG(function(u,i){var y,C=h.randomBytes(i);for(y=0;y<i;y++)u[y]=C[y];Nn(C)}))})()})(f.exports?f.exports:self.nacl=self.nacl||{})})(cr)),cr.exports}var ol=il();const fr=zc(ol),Mn=24,al=16;function cl(f,o){const l=fr.randomBytes(Mn),p=fr.secretbox(f,l,o),m=new Uint8Array(Mn+p.length);return m.set(l),m.set(p,Mn),m}function ll(f,o){if(f.length<Mn+al)throw new Error("Sealed data too short");const l=f.slice(0,Mn),p=f.slice(Mn),m=fr.secretbox.open(p,l,o);if(!m)throw new Error("Decryption failed - data may be tampered with");return m}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function hl(f){return f instanceof Uint8Array||ArrayBuffer.isView(f)&&f.constructor.name==="Uint8Array"}function ur(f){if(!Number.isSafeInteger(f)||f<0)throw new Error("positive integer expected, got "+f)}function Ps(f,...o){if(!hl(f))throw new Error("Uint8Array expected");if(o.length>0&&!o.includes(f.length))throw new Error("Uint8Array expected of length "+o+", got length="+f.length)}function Or(f){if(typeof f!="function"||typeof f.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ur(f.outputLen),ur(f.blockLen)}function Ts(f,o=!0){if(f.destroyed)throw new Error("Hash instance has been destroyed");if(o&&f.finished)throw new Error("Hash#digest() has already been called")}function fl(f,o){Ps(f);const l=o.outputLen;if(f.length<l)throw new Error("digestInto() expects output buffer of length at least "+l)}function rs(...f){for(let o=0;o<f.length;o++)f[o].fill(0)}function lr(f){return new DataView(f.buffer,f.byteOffset,f.byteLength)}function Mt(f,o){return f<<32-o|f>>>o}function ul(f){if(typeof f!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(f))}function is(f){return typeof f=="string"&&(f=ul(f)),Ps(f),f}class oo{}function dl(f){const o=p=>f().update(is(p)).digest(),l=f();return o.outputLen=l.outputLen,o.blockLen=l.blockLen,o.create=()=>f(),o}function pl(f,o,l,p){if(typeof f.setBigUint64=="function")return f.setBigUint64(o,l,p);const m=BigInt(32),x=BigInt(4294967295),k=Number(l>>m&x),v=Number(l&x),I=p?4:0,M=p?0:4;f.setUint32(o+I,k,p),f.setUint32(o+M,v,p)}function gl(f,o,l){return f&o^~f&l}function ml(f,o,l){return f&o^f&l^o&l}class yl extends oo{constructor(o,l,p,m){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=o,this.outputLen=l,this.padOffset=p,this.isLE=m,this.buffer=new Uint8Array(o),this.view=lr(this.buffer)}update(o){Ts(this),o=is(o),Ps(o);const{view:l,buffer:p,blockLen:m}=this,x=o.length;for(let k=0;k<x;){const v=Math.min(m-this.pos,x-k);if(v===m){const I=lr(o);for(;m<=x-k;k+=m)this.process(I,k);continue}p.set(o.subarray(k,k+v),this.pos),this.pos+=v,k+=v,this.pos===m&&(this.process(l,0),this.pos=0)}return this.length+=o.length,this.roundClean(),this}digestInto(o){Ts(this),fl(o,this),this.finished=!0;const{buffer:l,view:p,blockLen:m,isLE:x}=this;let{pos:k}=this;l[k++]=128,rs(this.buffer.subarray(k)),this.padOffset>m-k&&(this.process(p,0),k=0);for(let J=k;J<m;J++)l[J]=0;pl(p,m-8,BigInt(this.length*8),x),this.process(p,0);const v=lr(o),I=this.outputLen;if(I%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const M=I/4,D=this.get();if(M>D.length)throw new Error("_sha2: outputLen bigger than state");for(let J=0;J<M;J++)v.setUint32(4*J,D[J],x)}digest(){const{buffer:o,outputLen:l}=this;this.digestInto(o);const p=o.slice(0,l);return this.destroy(),p}_cloneInto(o){o||(o=new this.constructor),o.set(...this.get());const{blockLen:l,buffer:p,length:m,finished:x,destroyed:k,pos:v}=this;return o.destroyed=k,o.finished=x,o.length=m,o.pos=v,m%l&&o.buffer.set(p),o}clone(){return this._cloneInto()}}const Qt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),bl=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Yt=new Uint32Array(64);class xl extends yl{constructor(o=32){super(64,o,8,!1),this.A=Qt[0]|0,this.B=Qt[1]|0,this.C=Qt[2]|0,this.D=Qt[3]|0,this.E=Qt[4]|0,this.F=Qt[5]|0,this.G=Qt[6]|0,this.H=Qt[7]|0}get(){const{A:o,B:l,C:p,D:m,E:x,F:k,G:v,H:I}=this;return[o,l,p,m,x,k,v,I]}set(o,l,p,m,x,k,v,I){this.A=o|0,this.B=l|0,this.C=p|0,this.D=m|0,this.E=x|0,this.F=k|0,this.G=v|0,this.H=I|0}process(o,l){for(let J=0;J<16;J++,l+=4)Yt[J]=o.getUint32(l,!1);for(let J=16;J<64;J++){const oe=Yt[J-15],H=Yt[J-2],fe=Mt(oe,7)^Mt(oe,18)^oe>>>3,de=Mt(H,17)^Mt(H,19)^H>>>10;Yt[J]=de+Yt[J-7]+fe+Yt[J-16]|0}let{A:p,B:m,C:x,D:k,E:v,F:I,G:M,H:D}=this;for(let J=0;J<64;J++){const oe=Mt(v,6)^Mt(v,11)^Mt(v,25),H=D+oe+gl(v,I,M)+bl[J]+Yt[J]|0,de=(Mt(p,2)^Mt(p,13)^Mt(p,22))+ml(p,m,x)|0;D=M,M=I,I=v,v=k+H|0,k=x,x=m,m=p,p=H+de|0}p=p+this.A|0,m=m+this.B|0,x=x+this.C|0,k=k+this.D|0,v=v+this.E|0,I=I+this.F|0,M=M+this.G|0,D=D+this.H|0,this.set(p,m,x,k,v,I,M,D)}roundClean(){rs(Yt)}destroy(){this.set(0,0,0,0,0,0,0,0),rs(this.buffer)}}const wl=dl(()=>new xl),Ls=wl;class ao extends oo{constructor(o,l){super(),this.finished=!1,this.destroyed=!1,Or(o);const p=is(l);if(this.iHash=o.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const m=this.blockLen,x=new Uint8Array(m);x.set(p.length>m?o.create().update(p).digest():p);for(let k=0;k<x.length;k++)x[k]^=54;this.iHash.update(x),this.oHash=o.create();for(let k=0;k<x.length;k++)x[k]^=106;this.oHash.update(x),rs(x)}update(o){return Ts(this),this.iHash.update(o),this}digestInto(o){Ts(this),Ps(o,this.outputLen),this.finished=!0,this.iHash.digestInto(o),this.oHash.update(o),this.oHash.digestInto(o),this.destroy()}digest(){const o=new Uint8Array(this.oHash.outputLen);return this.digestInto(o),o}_cloneInto(o){o||(o=Object.create(Object.getPrototypeOf(this),{}));const{oHash:l,iHash:p,finished:m,destroyed:x,blockLen:k,outputLen:v}=this;return o=o,o.finished=m,o.destroyed=x,o.blockLen=k,o.outputLen=v,o.oHash=l._cloneInto(o.oHash),o.iHash=p._cloneInto(o.iHash),o}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Sr=(f,o,l)=>new ao(f,o).update(l).digest();Sr.create=(f,o)=>new ao(f,o);function vl(f,o,l){return Or(f),l===void 0&&(l=new Uint8Array(f.outputLen)),Sr(f,is(l),is(o))}const hr=Uint8Array.from([0]),kl=Uint8Array.of();function _l(f,o,l,p=32){Or(f),ur(p);const m=f.outputLen;if(p>255*m)throw new Error("Length should be <= 255*HashLen");const x=Math.ceil(p/m),k=new Uint8Array(x*m),v=Sr.create(f,o),I=v._cloneInto(),M=new Uint8Array(v.outputLen);for(let D=0;D<x;D++)hr[0]=D+1,I.update(D===0?kl:M).update(l).update(hr).digestInto(M),k.set(M,m*D),v._cloneInto(I);return v.destroy(),I.destroy(),rs(M,hr),k.slice(0,p)}const Al=(f,o,l,p,m)=>_l(f,vl(f,o,l),p,m);function Rl(f){const o=Ls(new TextEncoder().encode(`airloom-session:${f}`));return Array.from(o.slice(0,16),l=>l.toString(16).padStart(2,"0")).join("")}function co(f,o){const l=new TextEncoder().encode("airloom-v1");return Al(Ls,f,l,"airloom-encryption",32)}function Cl(f){return f.replace(/[-\s]/g,"").toUpperCase()}class Ol{constructor(o,l,p){ce(this,"_ended",!1);this.id=o,this.sendFn=l,this.meta=p}write(o){if(this._ended)throw new Error("Cannot write after stream has ended");this.sendFn({type:"stream_chunk",id:this.id,data:o})}end(){this._ended||(this._ended=!0,this.sendFn({type:"stream_end",id:this.id}))}get ended(){return this._ended}}class Sl extends io.EventEmitter{constructor(l,p){super();ce(this,"id");ce(this,"meta");ce(this,"_ended",!1);this.id=l,this.meta=p}_pushChunk(l){this._ended||this.emit("data",l)}_end(){this._ended||(this._ended=!0,this.emit("end"))}get ended(){return this._ended}}class Tl extends io.EventEmitter{constructor(l){super();ce(this,"adapter");ce(this,"encryptionKey");ce(this,"role");ce(this,"streams",new Map);ce(this,"_ready",!1);ce(this,"msgCounter",0);this.adapter=l.adapter,this.encryptionKey=l.encryptionKey??null,this.role=l.role,this.setupHandlers()}setupHandlers(){this.adapter.onMessage(l=>{this.handlePayload(l)}),this.adapter.onPeerJoined(()=>{this.encryptionKey&&(this._ready=!0,this.emit("ready"))}),this.adapter.onPeerLeft(()=>{this._ready=!1,this.emit("peer_left")}),this.adapter.onError(l=>this.emit("error",l)),this.adapter.onDisconnect(()=>this.emit("disconnect"))}handlePayload(l){try{if(!this.encryptionKey){this.emit("error",new Error("Received data but no encryption key"));return}const p=Yc(l),m=ll(p,this.encryptionKey),x=Xc(m);this.handleMessage(x)}catch(p){this.emit("error",p)}}handleMessage(l){switch(l.type){case"message":this.emit("message",l.data);break;case"stream_start":{const p=new Sl(l.id,l.meta);this.streams.set(l.id,p),this.emit("stream",p);break}case"stream_chunk":{const p=this.streams.get(l.id);p&&p._pushChunk(l.data);break}case"stream_end":{const p=this.streams.get(l.id);p&&(p._end(),this.streams.delete(l.id));break}}}sendRaw(l){if(!this.encryptionKey)throw new Error("No encryption key established");const p=Zc(l),m=cl(p,this.encryptionKey);this.adapter.send(Qc(m))}send(l){const p=`msg-${++this.msgCounter}`;this.sendRaw({type:"message",id:p,data:l})}createStream(l){const p=`stream-${++this.msgCounter}`;return this.sendRaw({type:"stream_start",id:p,meta:l}),new Ol(p,m=>this.sendRaw(m),l)}async connect(l){await this.adapter.connect(l,this.role)}get ready(){return this._ready}waitForReady(l=3e4){return this._ready?Promise.resolve():new Promise((p,m)=>{const x=()=>{clearTimeout(M),this.removeListener("ready",k),this.removeListener("error",v),this.removeListener("disconnect",I)},k=()=>{x(),p()},v=D=>{x(),m(D)},I=()=>{x(),m(new Error("Disconnected before ready"))},M=setTimeout(()=>{x(),m(new Error("Timed out waiting for peer"))},l);this.once("ready",k),this.once("error",v),this.once("disconnect",I)})}close(){for(const l of this.streams.values())l._end();this.streams.clear(),this.adapter.close(),this.removeAllListeners()}}class El{constructor(o){ce(this,"ws",null);ce(this,"url");ce(this,"_connected",!1);ce(this,"messageHandlers",[]);ce(this,"peerJoinedHandlers",[]);ce(this,"peerLeftHandlers",[]);ce(this,"errorHandlers",[]);ce(this,"disconnectHandlers",[]);ce(this,"reconnectAttempts",0);ce(this,"maxReconnectAttempts",5);ce(this,"reconnectTimer",null);ce(this,"shouldReconnect",!1);ce(this,"sessionToken",null);ce(this,"role",null);this.url=o}get connected(){return this._connected}async connect(o,l){return this.sessionToken=o,this.role=l,this.doConnect()}async doConnect(){const o=await this.createWebSocket(this.url);return new Promise((l,p)=>{o.onopen=()=>{this._connected=!0,this.shouldReconnect=!0,this.reconnectAttempts=0;const m=this.role==="host"?{type:"create",sessionToken:this.sessionToken}:{type:"join",sessionToken:this.sessionToken};o.send(JSON.stringify(m)),l()},o.onmessage=m=>{const x=m.data,k=typeof x=="string"?x:typeof Buffer<"u"&&Buffer.isBuffer(x)?x.toString("utf-8"):new TextDecoder().decode(x);try{const v=JSON.parse(k);switch(v.type){case"created":case"joined":break;case"peer_joined":this.peerJoinedHandlers.forEach(I=>I());break;case"peer_left":this.peerLeftHandlers.forEach(I=>I());break;case"forward":this.messageHandlers.forEach(I=>I(v.payload));break;case"error":this.errorHandlers.forEach(I=>I(new Error(v.message)));break}}catch(v){this.errorHandlers.forEach(I=>I(v instanceof Error?v:new Error(String(v))))}},o.onclose=()=>{const m=this._connected;this._connected=!1,m&&this.disconnectHandlers.forEach(x=>x()),this.shouldReconnect&&!this.reconnectTimer&&this.attemptReconnect()},o.onerror=m=>{const x=m instanceof Error?m:new Error("WebSocket error");this.errorHandlers.forEach(k=>k(x)),this._connected||(this.shouldReconnect=!1,p(x))},this.ws=o})}async createWebSocket(o){if(typeof globalThis.WebSocket<"u")return new globalThis.WebSocket(o);try{const{default:l}=await ro(async()=>{const{default:p}=await import("./browser-Dl0EROMD.js").then(m=>m.b);return{default:p}},[],import.meta.url);return new l(o)}catch{throw new Error('No WebSocket implementation available. Install the "ws" package for Node.js.')}}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts||!this.sessionToken||!this.role)return;this.reconnectAttempts++;const o=Math.min(1e3*Math.pow(2,this.reconnectAttempts-1),3e4);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect().catch(()=>{})},o)}send(o){!this.ws||!this._connected||this.ws.send(JSON.stringify({type:"forward",payload:o}))}onMessage(o){this.messageHandlers.push(o)}onPeerJoined(o){this.peerJoinedHandlers.push(o)}onPeerLeft(o){this.peerLeftHandlers.push(o)}onError(o){this.errorHandlers.push(o)}onDisconnect(o){this.disconnectHandlers.push(o)}close(){var o;this.shouldReconnect=!1,this.maxReconnectAttempts=0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),(o=this.ws)==null||o.close(),this.ws=null,this._connected=!1}}var Cs={exports:{}};/*@license Copyright 2015-2022 Ably Real-time Ltd (ably.com)
1
+ var Wc=Object.defineProperty;var Vc=(f,o,l)=>o in f?Wc(f,o,{enumerable:!0,configurable:!0,writable:!0,value:l}):f[o]=l;var ce=(f,o,l)=>Vc(f,typeof o!="symbol"?o+"":o,l);(function(){const o=document.createElement("link").relList;if(o&&o.supports&&o.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))p(m);new MutationObserver(m=>{for(const x of m)if(x.type==="childList")for(const k of x.addedNodes)k.tagName==="LINK"&&k.rel==="modulepreload"&&p(k)}).observe(document,{childList:!0,subtree:!0});function l(m){const x={};return m.integrity&&(x.integrity=m.integrity),m.referrerPolicy&&(x.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?x.credentials="include":m.crossOrigin==="anonymous"?x.credentials="omit":x.credentials="same-origin",x}function p(m){if(m.ep)return;m.ep=!0;const x=l(m);fetch(m.href,x)}})();const $c="modulepreload",Fc=function(f,o){return new URL(f,o).href},$i={},ro=function(o,l,p){let m=Promise.resolve();if(l&&l.length>0){let k=function(D){return Promise.all(D.map(J=>Promise.resolve(J).then(oe=>({status:"fulfilled",value:oe}),oe=>({status:"rejected",reason:oe}))))};const v=document.getElementsByTagName("link"),I=document.querySelector("meta[property=csp-nonce]"),M=(I==null?void 0:I.nonce)||(I==null?void 0:I.getAttribute("nonce"));m=k(l.map(D=>{if(D=Fc(D,p),D in $i)return;$i[D]=!0;const J=D.endsWith(".css"),oe=J?'[rel="stylesheet"]':"";if(!!p)for(let de=v.length-1;de>=0;de--){const Ne=v[de];if(Ne.href===D&&(!J||Ne.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${D}"]${oe}`))return;const fe=document.createElement("link");if(fe.rel=J?"stylesheet":$c,J||(fe.as="script"),fe.crossOrigin="",fe.href=D,M&&fe.setAttribute("nonce",M),document.head.appendChild(fe),J)return new Promise((de,Ne)=>{fe.addEventListener("load",de),fe.addEventListener("error",()=>Ne(new Error(`Unable to preload CSS for ${D}`)))})}))}function x(k){const v=new Event("vite:preloadError",{cancelable:!0});if(v.payload=k,window.dispatchEvent(v),!v.defaultPrevented)throw k}return m.then(k=>{for(const v of k||[])v.status==="rejected"&&x(v.reason);return o().catch(x)})};var Kt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zc(f){return f&&f.__esModule&&Object.prototype.hasOwnProperty.call(f,"default")?f.default:f}function Jc(f){if(Object.prototype.hasOwnProperty.call(f,"__esModule"))return f;var o=f.default;if(typeof o=="function"){var l=function p(){return this instanceof p?Reflect.construct(o,arguments,this.constructor):o.apply(this,arguments)};l.prototype=o.prototype}else l={};return Object.defineProperty(l,"__esModule",{value:!0}),Object.keys(f).forEach(function(p){var m=Object.getOwnPropertyDescriptor(f,p);Object.defineProperty(l,p,m.get?m:{enumerable:!0,get:function(){return f[p]}})}),l}var ks={exports:{}},Fi;function Kc(){if(Fi)return ks.exports;Fi=1;var f=typeof Reflect=="object"?Reflect:null,o=f&&typeof f.apply=="function"?f.apply:function(W,_,le){return Function.prototype.apply.call(W,_,le)},l;f&&typeof f.ownKeys=="function"?l=f.ownKeys:Object.getOwnPropertySymbols?l=function(W){return Object.getOwnPropertyNames(W).concat(Object.getOwnPropertySymbols(W))}:l=function(W){return Object.getOwnPropertyNames(W)};function p(z){console&&console.warn&&console.warn(z)}var m=Number.isNaN||function(W){return W!==W};function x(){x.init.call(this)}ks.exports=x,ks.exports.once=ht,x.EventEmitter=x,x.prototype._events=void 0,x.prototype._eventsCount=0,x.prototype._maxListeners=void 0;var k=10;function v(z){if(typeof z!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof z)}Object.defineProperty(x,"defaultMaxListeners",{enumerable:!0,get:function(){return k},set:function(z){if(typeof z!="number"||z<0||m(z))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+z+".");k=z}}),x.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},x.prototype.setMaxListeners=function(W){if(typeof W!="number"||W<0||m(W))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+W+".");return this._maxListeners=W,this};function I(z){return z._maxListeners===void 0?x.defaultMaxListeners:z._maxListeners}x.prototype.getMaxListeners=function(){return I(this)},x.prototype.emit=function(W){for(var _=[],le=1;le<arguments.length;le++)_.push(arguments[le]);var he=W==="error",He=this._events;if(He!==void 0)he=he&&He.error===void 0;else if(!he)return!1;if(he){var Te;if(_.length>0&&(Te=_[0]),Te instanceof Error)throw Te;var $e=new Error("Unhandled error."+(Te?" ("+Te.message+")":""));throw $e.context=Te,$e}var bt=He[W];if(bt===void 0)return!1;if(typeof bt=="function")o(bt,this,_);else for(var c=bt.length,xt=fe(bt,c),le=0;le<c;++le)o(xt[le],this,_);return!0};function M(z,W,_,le){var he,He,Te;if(v(_),He=z._events,He===void 0?(He=z._events=Object.create(null),z._eventsCount=0):(He.newListener!==void 0&&(z.emit("newListener",W,_.listener?_.listener:_),He=z._events),Te=He[W]),Te===void 0)Te=He[W]=_,++z._eventsCount;else if(typeof Te=="function"?Te=He[W]=le?[_,Te]:[Te,_]:le?Te.unshift(_):Te.push(_),he=I(z),he>0&&Te.length>he&&!Te.warned){Te.warned=!0;var $e=new Error("Possible EventEmitter memory leak detected. "+Te.length+" "+String(W)+" listeners added. Use emitter.setMaxListeners() to increase limit");$e.name="MaxListenersExceededWarning",$e.emitter=z,$e.type=W,$e.count=Te.length,p($e)}return z}x.prototype.addListener=function(W,_){return M(this,W,_,!1)},x.prototype.on=x.prototype.addListener,x.prototype.prependListener=function(W,_){return M(this,W,_,!0)};function D(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function J(z,W,_){var le={fired:!1,wrapFn:void 0,target:z,type:W,listener:_},he=D.bind(le);return he.listener=_,le.wrapFn=he,he}x.prototype.once=function(W,_){return v(_),this.on(W,J(this,W,_)),this},x.prototype.prependOnceListener=function(W,_){return v(_),this.prependListener(W,J(this,W,_)),this},x.prototype.removeListener=function(W,_){var le,he,He,Te,$e;if(v(_),he=this._events,he===void 0)return this;if(le=he[W],le===void 0)return this;if(le===_||le.listener===_)--this._eventsCount===0?this._events=Object.create(null):(delete he[W],he.removeListener&&this.emit("removeListener",W,le.listener||_));else if(typeof le!="function"){for(He=-1,Te=le.length-1;Te>=0;Te--)if(le[Te]===_||le[Te].listener===_){$e=le[Te].listener,He=Te;break}if(He<0)return this;He===0?le.shift():de(le,He),le.length===1&&(he[W]=le[0]),he.removeListener!==void 0&&this.emit("removeListener",W,$e||_)}return this},x.prototype.off=x.prototype.removeListener,x.prototype.removeAllListeners=function(W){var _,le,he;if(le=this._events,le===void 0)return this;if(le.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):le[W]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete le[W]),this;if(arguments.length===0){var He=Object.keys(le),Te;for(he=0;he<He.length;++he)Te=He[he],Te!=="removeListener"&&this.removeAllListeners(Te);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(_=le[W],typeof _=="function")this.removeListener(W,_);else if(_!==void 0)for(he=_.length-1;he>=0;he--)this.removeListener(W,_[he]);return this};function oe(z,W,_){var le=z._events;if(le===void 0)return[];var he=le[W];return he===void 0?[]:typeof he=="function"?_?[he.listener||he]:[he]:_?Ne(he):fe(he,he.length)}x.prototype.listeners=function(W){return oe(this,W,!0)},x.prototype.rawListeners=function(W){return oe(this,W,!1)},x.listenerCount=function(z,W){return typeof z.listenerCount=="function"?z.listenerCount(W):H.call(z,W)},x.prototype.listenerCount=H;function H(z){var W=this._events;if(W!==void 0){var _=W[z];if(typeof _=="function")return 1;if(_!==void 0)return _.length}return 0}x.prototype.eventNames=function(){return this._eventsCount>0?l(this._events):[]};function fe(z,W){for(var _=new Array(W),le=0;le<W;++le)_[le]=z[le];return _}function de(z,W){for(;W+1<z.length;W++)z[W]=z[W+1];z.pop()}function Ne(z){for(var W=new Array(z.length),_=0;_<W.length;++_)W[_]=z[_].listener||z[_];return W}function ht(z,W){return new Promise(function(_,le){function he(Te){z.removeListener(W,He),le(Te)}function He(){typeof z.removeListener=="function"&&z.removeListener("error",he),_([].slice.call(arguments))}Rt(z,W,He,{once:!0}),W!=="error"&&At(z,he,{once:!0})})}function At(z,W,_){typeof z.on=="function"&&Rt(z,"error",W,_)}function Rt(z,W,_,le){if(typeof z.on=="function")le.once?z.once(W,_):z.on(W,_);else if(typeof z.addEventListener=="function")z.addEventListener(W,function he(He){le.once&&z.removeEventListener(W,he),_(He)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof z)}return ks.exports}var io=Kc();function Qc(f){if(typeof Buffer<"u")return Buffer.from(f).toString("base64");let o="";for(const l of f)o+=String.fromCharCode(l);return btoa(o)}function Yc(f){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(f,"base64"));const o=atob(f),l=new Uint8Array(o.length);for(let p=0;p<o.length;p++)l[p]=o.charCodeAt(p);return l}function Zc(f){return new TextEncoder().encode(JSON.stringify(f))}function Xc(f){const o=JSON.parse(new TextDecoder().decode(f));if(!o||typeof o!="object"||typeof o.type!="string"||typeof o.id!="string")throw new Error("Invalid channel message: missing type or id field");return o}function el(f){const o=JSON.parse(f);if(!o||typeof o!="object"||typeof o.relay!="string"||typeof o.session!="string"||typeof o.v!="number")throw new Error("Invalid pairing data: missing required fields");if(o.transport!==void 0&&o.transport!=="ws"&&o.transport!=="ably")throw new Error('Invalid pairing data: transport must be "ws" or "ably"');if(o.token!==void 0&&typeof o.token!="string")throw new Error("Invalid pairing data: token must be a string");if(o.transport==="ably"&&!o.token)throw new Error("Invalid pairing data: Ably transport requires a token");return o}function tl(f){throw new Error('Could not dynamically require "'+f+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var cr={exports:{}};const nl={},sl=Object.freeze(Object.defineProperty({__proto__:null,default:nl},Symbol.toStringTag,{value:"Module"})),rl=Jc(sl);var zi;function il(){return zi||(zi=1,(function(f){(function(o){var l=function(h){var d,u=new Float64Array(16);if(h)for(d=0;d<h.length;d++)u[d]=h[d];return u},p=function(){throw new Error("no PRNG")},m=new Uint8Array(16),x=new Uint8Array(32);x[0]=9;var k=l(),v=l([1]),I=l([56129,1]),M=l([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),D=l([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),J=l([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),oe=l([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),H=l([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function fe(h,d,u,i){h[d]=u>>24&255,h[d+1]=u>>16&255,h[d+2]=u>>8&255,h[d+3]=u&255,h[d+4]=i>>24&255,h[d+5]=i>>16&255,h[d+6]=i>>8&255,h[d+7]=i&255}function de(h,d,u,i,y){var C,O=0;for(C=0;C<y;C++)O|=h[d+C]^u[i+C];return(1&O-1>>>8)-1}function Ne(h,d,u,i){return de(h,d,u,i,16)}function ht(h,d,u,i){return de(h,d,u,i,32)}function At(h,d,u,i){for(var y=i[0]&255|(i[1]&255)<<8|(i[2]&255)<<16|(i[3]&255)<<24,C=u[0]&255|(u[1]&255)<<8|(u[2]&255)<<16|(u[3]&255)<<24,O=u[4]&255|(u[5]&255)<<8|(u[6]&255)<<16|(u[7]&255)<<24,B=u[8]&255|(u[9]&255)<<8|(u[10]&255)<<16|(u[11]&255)<<24,$=u[12]&255|(u[13]&255)<<8|(u[14]&255)<<16|(u[15]&255)<<24,ae=i[4]&255|(i[5]&255)<<8|(i[6]&255)<<16|(i[7]&255)<<24,Y=d[0]&255|(d[1]&255)<<8|(d[2]&255)<<16|(d[3]&255)<<24,Me=d[4]&255|(d[5]&255)<<8|(d[6]&255)<<16|(d[7]&255)<<24,ee=d[8]&255|(d[9]&255)<<8|(d[10]&255)<<16|(d[11]&255)<<24,ge=d[12]&255|(d[13]&255)<<8|(d[14]&255)<<16|(d[15]&255)<<24,be=i[8]&255|(i[9]&255)<<8|(i[10]&255)<<16|(i[11]&255)<<24,Ae=u[16]&255|(u[17]&255)<<8|(u[18]&255)<<16|(u[19]&255)<<24,V=u[20]&255|(u[21]&255)<<8|(u[22]&255)<<16|(u[23]&255)<<24,xe=u[24]&255|(u[25]&255)<<8|(u[26]&255)<<16|(u[27]&255)<<24,we=u[28]&255|(u[29]&255)<<8|(u[30]&255)<<16|(u[31]&255)<<24,me=i[12]&255|(i[13]&255)<<8|(i[14]&255)<<16|(i[15]&255)<<24,te=y,K=C,Z=O,ie=B,re=$,Q=ae,T=Y,E=Me,q=ee,N=ge,G=be,j=Ae,ue=V,ke=xe,Ce=we,Re=me,w,Ee=0;Ee<20;Ee+=2)w=te+ue|0,re^=w<<7|w>>>25,w=re+te|0,q^=w<<9|w>>>23,w=q+re|0,ue^=w<<13|w>>>19,w=ue+q|0,te^=w<<18|w>>>14,w=Q+K|0,N^=w<<7|w>>>25,w=N+Q|0,ke^=w<<9|w>>>23,w=ke+N|0,K^=w<<13|w>>>19,w=K+ke|0,Q^=w<<18|w>>>14,w=G+T|0,Ce^=w<<7|w>>>25,w=Ce+G|0,Z^=w<<9|w>>>23,w=Z+Ce|0,T^=w<<13|w>>>19,w=T+Z|0,G^=w<<18|w>>>14,w=Re+j|0,ie^=w<<7|w>>>25,w=ie+Re|0,E^=w<<9|w>>>23,w=E+ie|0,j^=w<<13|w>>>19,w=j+E|0,Re^=w<<18|w>>>14,w=te+ie|0,K^=w<<7|w>>>25,w=K+te|0,Z^=w<<9|w>>>23,w=Z+K|0,ie^=w<<13|w>>>19,w=ie+Z|0,te^=w<<18|w>>>14,w=Q+re|0,T^=w<<7|w>>>25,w=T+Q|0,E^=w<<9|w>>>23,w=E+T|0,re^=w<<13|w>>>19,w=re+E|0,Q^=w<<18|w>>>14,w=G+N|0,j^=w<<7|w>>>25,w=j+G|0,q^=w<<9|w>>>23,w=q+j|0,N^=w<<13|w>>>19,w=N+q|0,G^=w<<18|w>>>14,w=Re+Ce|0,ue^=w<<7|w>>>25,w=ue+Re|0,ke^=w<<9|w>>>23,w=ke+ue|0,Ce^=w<<13|w>>>19,w=Ce+ke|0,Re^=w<<18|w>>>14;te=te+y|0,K=K+C|0,Z=Z+O|0,ie=ie+B|0,re=re+$|0,Q=Q+ae|0,T=T+Y|0,E=E+Me|0,q=q+ee|0,N=N+ge|0,G=G+be|0,j=j+Ae|0,ue=ue+V|0,ke=ke+xe|0,Ce=Ce+we|0,Re=Re+me|0,h[0]=te>>>0&255,h[1]=te>>>8&255,h[2]=te>>>16&255,h[3]=te>>>24&255,h[4]=K>>>0&255,h[5]=K>>>8&255,h[6]=K>>>16&255,h[7]=K>>>24&255,h[8]=Z>>>0&255,h[9]=Z>>>8&255,h[10]=Z>>>16&255,h[11]=Z>>>24&255,h[12]=ie>>>0&255,h[13]=ie>>>8&255,h[14]=ie>>>16&255,h[15]=ie>>>24&255,h[16]=re>>>0&255,h[17]=re>>>8&255,h[18]=re>>>16&255,h[19]=re>>>24&255,h[20]=Q>>>0&255,h[21]=Q>>>8&255,h[22]=Q>>>16&255,h[23]=Q>>>24&255,h[24]=T>>>0&255,h[25]=T>>>8&255,h[26]=T>>>16&255,h[27]=T>>>24&255,h[28]=E>>>0&255,h[29]=E>>>8&255,h[30]=E>>>16&255,h[31]=E>>>24&255,h[32]=q>>>0&255,h[33]=q>>>8&255,h[34]=q>>>16&255,h[35]=q>>>24&255,h[36]=N>>>0&255,h[37]=N>>>8&255,h[38]=N>>>16&255,h[39]=N>>>24&255,h[40]=G>>>0&255,h[41]=G>>>8&255,h[42]=G>>>16&255,h[43]=G>>>24&255,h[44]=j>>>0&255,h[45]=j>>>8&255,h[46]=j>>>16&255,h[47]=j>>>24&255,h[48]=ue>>>0&255,h[49]=ue>>>8&255,h[50]=ue>>>16&255,h[51]=ue>>>24&255,h[52]=ke>>>0&255,h[53]=ke>>>8&255,h[54]=ke>>>16&255,h[55]=ke>>>24&255,h[56]=Ce>>>0&255,h[57]=Ce>>>8&255,h[58]=Ce>>>16&255,h[59]=Ce>>>24&255,h[60]=Re>>>0&255,h[61]=Re>>>8&255,h[62]=Re>>>16&255,h[63]=Re>>>24&255}function Rt(h,d,u,i){for(var y=i[0]&255|(i[1]&255)<<8|(i[2]&255)<<16|(i[3]&255)<<24,C=u[0]&255|(u[1]&255)<<8|(u[2]&255)<<16|(u[3]&255)<<24,O=u[4]&255|(u[5]&255)<<8|(u[6]&255)<<16|(u[7]&255)<<24,B=u[8]&255|(u[9]&255)<<8|(u[10]&255)<<16|(u[11]&255)<<24,$=u[12]&255|(u[13]&255)<<8|(u[14]&255)<<16|(u[15]&255)<<24,ae=i[4]&255|(i[5]&255)<<8|(i[6]&255)<<16|(i[7]&255)<<24,Y=d[0]&255|(d[1]&255)<<8|(d[2]&255)<<16|(d[3]&255)<<24,Me=d[4]&255|(d[5]&255)<<8|(d[6]&255)<<16|(d[7]&255)<<24,ee=d[8]&255|(d[9]&255)<<8|(d[10]&255)<<16|(d[11]&255)<<24,ge=d[12]&255|(d[13]&255)<<8|(d[14]&255)<<16|(d[15]&255)<<24,be=i[8]&255|(i[9]&255)<<8|(i[10]&255)<<16|(i[11]&255)<<24,Ae=u[16]&255|(u[17]&255)<<8|(u[18]&255)<<16|(u[19]&255)<<24,V=u[20]&255|(u[21]&255)<<8|(u[22]&255)<<16|(u[23]&255)<<24,xe=u[24]&255|(u[25]&255)<<8|(u[26]&255)<<16|(u[27]&255)<<24,we=u[28]&255|(u[29]&255)<<8|(u[30]&255)<<16|(u[31]&255)<<24,me=i[12]&255|(i[13]&255)<<8|(i[14]&255)<<16|(i[15]&255)<<24,te=y,K=C,Z=O,ie=B,re=$,Q=ae,T=Y,E=Me,q=ee,N=ge,G=be,j=Ae,ue=V,ke=xe,Ce=we,Re=me,w,Ee=0;Ee<20;Ee+=2)w=te+ue|0,re^=w<<7|w>>>25,w=re+te|0,q^=w<<9|w>>>23,w=q+re|0,ue^=w<<13|w>>>19,w=ue+q|0,te^=w<<18|w>>>14,w=Q+K|0,N^=w<<7|w>>>25,w=N+Q|0,ke^=w<<9|w>>>23,w=ke+N|0,K^=w<<13|w>>>19,w=K+ke|0,Q^=w<<18|w>>>14,w=G+T|0,Ce^=w<<7|w>>>25,w=Ce+G|0,Z^=w<<9|w>>>23,w=Z+Ce|0,T^=w<<13|w>>>19,w=T+Z|0,G^=w<<18|w>>>14,w=Re+j|0,ie^=w<<7|w>>>25,w=ie+Re|0,E^=w<<9|w>>>23,w=E+ie|0,j^=w<<13|w>>>19,w=j+E|0,Re^=w<<18|w>>>14,w=te+ie|0,K^=w<<7|w>>>25,w=K+te|0,Z^=w<<9|w>>>23,w=Z+K|0,ie^=w<<13|w>>>19,w=ie+Z|0,te^=w<<18|w>>>14,w=Q+re|0,T^=w<<7|w>>>25,w=T+Q|0,E^=w<<9|w>>>23,w=E+T|0,re^=w<<13|w>>>19,w=re+E|0,Q^=w<<18|w>>>14,w=G+N|0,j^=w<<7|w>>>25,w=j+G|0,q^=w<<9|w>>>23,w=q+j|0,N^=w<<13|w>>>19,w=N+q|0,G^=w<<18|w>>>14,w=Re+Ce|0,ue^=w<<7|w>>>25,w=ue+Re|0,ke^=w<<9|w>>>23,w=ke+ue|0,Ce^=w<<13|w>>>19,w=Ce+ke|0,Re^=w<<18|w>>>14;h[0]=te>>>0&255,h[1]=te>>>8&255,h[2]=te>>>16&255,h[3]=te>>>24&255,h[4]=Q>>>0&255,h[5]=Q>>>8&255,h[6]=Q>>>16&255,h[7]=Q>>>24&255,h[8]=G>>>0&255,h[9]=G>>>8&255,h[10]=G>>>16&255,h[11]=G>>>24&255,h[12]=Re>>>0&255,h[13]=Re>>>8&255,h[14]=Re>>>16&255,h[15]=Re>>>24&255,h[16]=T>>>0&255,h[17]=T>>>8&255,h[18]=T>>>16&255,h[19]=T>>>24&255,h[20]=E>>>0&255,h[21]=E>>>8&255,h[22]=E>>>16&255,h[23]=E>>>24&255,h[24]=q>>>0&255,h[25]=q>>>8&255,h[26]=q>>>16&255,h[27]=q>>>24&255,h[28]=N>>>0&255,h[29]=N>>>8&255,h[30]=N>>>16&255,h[31]=N>>>24&255}function z(h,d,u,i){At(h,d,u,i)}function W(h,d,u,i){Rt(h,d,u,i)}var _=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function le(h,d,u,i,y,C,O){var B=new Uint8Array(16),$=new Uint8Array(64),ae,Y;for(Y=0;Y<16;Y++)B[Y]=0;for(Y=0;Y<8;Y++)B[Y]=C[Y];for(;y>=64;){for(z($,B,O,_),Y=0;Y<64;Y++)h[d+Y]=u[i+Y]^$[Y];for(ae=1,Y=8;Y<16;Y++)ae=ae+(B[Y]&255)|0,B[Y]=ae&255,ae>>>=8;y-=64,d+=64,i+=64}if(y>0)for(z($,B,O,_),Y=0;Y<y;Y++)h[d+Y]=u[i+Y]^$[Y];return 0}function he(h,d,u,i,y){var C=new Uint8Array(16),O=new Uint8Array(64),B,$;for($=0;$<16;$++)C[$]=0;for($=0;$<8;$++)C[$]=i[$];for(;u>=64;){for(z(O,C,y,_),$=0;$<64;$++)h[d+$]=O[$];for(B=1,$=8;$<16;$++)B=B+(C[$]&255)|0,C[$]=B&255,B>>>=8;u-=64,d+=64}if(u>0)for(z(O,C,y,_),$=0;$<u;$++)h[d+$]=O[$];return 0}function He(h,d,u,i,y){var C=new Uint8Array(32);W(C,i,y,_);for(var O=new Uint8Array(8),B=0;B<8;B++)O[B]=i[B+16];return he(h,d,u,O,C)}function Te(h,d,u,i,y,C,O){var B=new Uint8Array(32);W(B,C,O,_);for(var $=new Uint8Array(8),ae=0;ae<8;ae++)$[ae]=C[ae+16];return le(h,d,u,i,y,$,B)}var $e=function(h){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var d,u,i,y,C,O,B,$;d=h[0]&255|(h[1]&255)<<8,this.r[0]=d&8191,u=h[2]&255|(h[3]&255)<<8,this.r[1]=(d>>>13|u<<3)&8191,i=h[4]&255|(h[5]&255)<<8,this.r[2]=(u>>>10|i<<6)&7939,y=h[6]&255|(h[7]&255)<<8,this.r[3]=(i>>>7|y<<9)&8191,C=h[8]&255|(h[9]&255)<<8,this.r[4]=(y>>>4|C<<12)&255,this.r[5]=C>>>1&8190,O=h[10]&255|(h[11]&255)<<8,this.r[6]=(C>>>14|O<<2)&8191,B=h[12]&255|(h[13]&255)<<8,this.r[7]=(O>>>11|B<<5)&8065,$=h[14]&255|(h[15]&255)<<8,this.r[8]=(B>>>8|$<<8)&8191,this.r[9]=$>>>5&127,this.pad[0]=h[16]&255|(h[17]&255)<<8,this.pad[1]=h[18]&255|(h[19]&255)<<8,this.pad[2]=h[20]&255|(h[21]&255)<<8,this.pad[3]=h[22]&255|(h[23]&255)<<8,this.pad[4]=h[24]&255|(h[25]&255)<<8,this.pad[5]=h[26]&255|(h[27]&255)<<8,this.pad[6]=h[28]&255|(h[29]&255)<<8,this.pad[7]=h[30]&255|(h[31]&255)<<8};$e.prototype.blocks=function(h,d,u){for(var i=this.fin?0:2048,y,C,O,B,$,ae,Y,Me,ee,ge,be,Ae,V,xe,we,me,te,K,Z,ie=this.h[0],re=this.h[1],Q=this.h[2],T=this.h[3],E=this.h[4],q=this.h[5],N=this.h[6],G=this.h[7],j=this.h[8],ue=this.h[9],ke=this.r[0],Ce=this.r[1],Re=this.r[2],w=this.r[3],Ee=this.r[4],Oe=this.r[5],Pe=this.r[6],ve=this.r[7],Le=this.r[8],Ue=this.r[9];u>=16;)y=h[d+0]&255|(h[d+1]&255)<<8,ie+=y&8191,C=h[d+2]&255|(h[d+3]&255)<<8,re+=(y>>>13|C<<3)&8191,O=h[d+4]&255|(h[d+5]&255)<<8,Q+=(C>>>10|O<<6)&8191,B=h[d+6]&255|(h[d+7]&255)<<8,T+=(O>>>7|B<<9)&8191,$=h[d+8]&255|(h[d+9]&255)<<8,E+=(B>>>4|$<<12)&8191,q+=$>>>1&8191,ae=h[d+10]&255|(h[d+11]&255)<<8,N+=($>>>14|ae<<2)&8191,Y=h[d+12]&255|(h[d+13]&255)<<8,G+=(ae>>>11|Y<<5)&8191,Me=h[d+14]&255|(h[d+15]&255)<<8,j+=(Y>>>8|Me<<8)&8191,ue+=Me>>>5|i,ee=0,ge=ee,ge+=ie*ke,ge+=re*(5*Ue),ge+=Q*(5*Le),ge+=T*(5*ve),ge+=E*(5*Pe),ee=ge>>>13,ge&=8191,ge+=q*(5*Oe),ge+=N*(5*Ee),ge+=G*(5*w),ge+=j*(5*Re),ge+=ue*(5*Ce),ee+=ge>>>13,ge&=8191,be=ee,be+=ie*Ce,be+=re*ke,be+=Q*(5*Ue),be+=T*(5*Le),be+=E*(5*ve),ee=be>>>13,be&=8191,be+=q*(5*Pe),be+=N*(5*Oe),be+=G*(5*Ee),be+=j*(5*w),be+=ue*(5*Re),ee+=be>>>13,be&=8191,Ae=ee,Ae+=ie*Re,Ae+=re*Ce,Ae+=Q*ke,Ae+=T*(5*Ue),Ae+=E*(5*Le),ee=Ae>>>13,Ae&=8191,Ae+=q*(5*ve),Ae+=N*(5*Pe),Ae+=G*(5*Oe),Ae+=j*(5*Ee),Ae+=ue*(5*w),ee+=Ae>>>13,Ae&=8191,V=ee,V+=ie*w,V+=re*Re,V+=Q*Ce,V+=T*ke,V+=E*(5*Ue),ee=V>>>13,V&=8191,V+=q*(5*Le),V+=N*(5*ve),V+=G*(5*Pe),V+=j*(5*Oe),V+=ue*(5*Ee),ee+=V>>>13,V&=8191,xe=ee,xe+=ie*Ee,xe+=re*w,xe+=Q*Re,xe+=T*Ce,xe+=E*ke,ee=xe>>>13,xe&=8191,xe+=q*(5*Ue),xe+=N*(5*Le),xe+=G*(5*ve),xe+=j*(5*Pe),xe+=ue*(5*Oe),ee+=xe>>>13,xe&=8191,we=ee,we+=ie*Oe,we+=re*Ee,we+=Q*w,we+=T*Re,we+=E*Ce,ee=we>>>13,we&=8191,we+=q*ke,we+=N*(5*Ue),we+=G*(5*Le),we+=j*(5*ve),we+=ue*(5*Pe),ee+=we>>>13,we&=8191,me=ee,me+=ie*Pe,me+=re*Oe,me+=Q*Ee,me+=T*w,me+=E*Re,ee=me>>>13,me&=8191,me+=q*Ce,me+=N*ke,me+=G*(5*Ue),me+=j*(5*Le),me+=ue*(5*ve),ee+=me>>>13,me&=8191,te=ee,te+=ie*ve,te+=re*Pe,te+=Q*Oe,te+=T*Ee,te+=E*w,ee=te>>>13,te&=8191,te+=q*Re,te+=N*Ce,te+=G*ke,te+=j*(5*Ue),te+=ue*(5*Le),ee+=te>>>13,te&=8191,K=ee,K+=ie*Le,K+=re*ve,K+=Q*Pe,K+=T*Oe,K+=E*Ee,ee=K>>>13,K&=8191,K+=q*w,K+=N*Re,K+=G*Ce,K+=j*ke,K+=ue*(5*Ue),ee+=K>>>13,K&=8191,Z=ee,Z+=ie*Ue,Z+=re*Le,Z+=Q*ve,Z+=T*Pe,Z+=E*Oe,ee=Z>>>13,Z&=8191,Z+=q*Ee,Z+=N*w,Z+=G*Re,Z+=j*Ce,Z+=ue*ke,ee+=Z>>>13,Z&=8191,ee=(ee<<2)+ee|0,ee=ee+ge|0,ge=ee&8191,ee=ee>>>13,be+=ee,ie=ge,re=be,Q=Ae,T=V,E=xe,q=we,N=me,G=te,j=K,ue=Z,d+=16,u-=16;this.h[0]=ie,this.h[1]=re,this.h[2]=Q,this.h[3]=T,this.h[4]=E,this.h[5]=q,this.h[6]=N,this.h[7]=G,this.h[8]=j,this.h[9]=ue},$e.prototype.finish=function(h,d){var u=new Uint16Array(10),i,y,C,O;if(this.leftover){for(O=this.leftover,this.buffer[O++]=1;O<16;O++)this.buffer[O]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(i=this.h[1]>>>13,this.h[1]&=8191,O=2;O<10;O++)this.h[O]+=i,i=this.h[O]>>>13,this.h[O]&=8191;for(this.h[0]+=i*5,i=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=i,i=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=i,u[0]=this.h[0]+5,i=u[0]>>>13,u[0]&=8191,O=1;O<10;O++)u[O]=this.h[O]+i,i=u[O]>>>13,u[O]&=8191;for(u[9]-=8192,y=(i^1)-1,O=0;O<10;O++)u[O]&=y;for(y=~y,O=0;O<10;O++)this.h[O]=this.h[O]&y|u[O];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,C=this.h[0]+this.pad[0],this.h[0]=C&65535,O=1;O<8;O++)C=(this.h[O]+this.pad[O]|0)+(C>>>16)|0,this.h[O]=C&65535;h[d+0]=this.h[0]>>>0&255,h[d+1]=this.h[0]>>>8&255,h[d+2]=this.h[1]>>>0&255,h[d+3]=this.h[1]>>>8&255,h[d+4]=this.h[2]>>>0&255,h[d+5]=this.h[2]>>>8&255,h[d+6]=this.h[3]>>>0&255,h[d+7]=this.h[3]>>>8&255,h[d+8]=this.h[4]>>>0&255,h[d+9]=this.h[4]>>>8&255,h[d+10]=this.h[5]>>>0&255,h[d+11]=this.h[5]>>>8&255,h[d+12]=this.h[6]>>>0&255,h[d+13]=this.h[6]>>>8&255,h[d+14]=this.h[7]>>>0&255,h[d+15]=this.h[7]>>>8&255},$e.prototype.update=function(h,d,u){var i,y;if(this.leftover){for(y=16-this.leftover,y>u&&(y=u),i=0;i<y;i++)this.buffer[this.leftover+i]=h[d+i];if(u-=y,d+=y,this.leftover+=y,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(u>=16&&(y=u-u%16,this.blocks(h,d,y),d+=y,u-=y),u){for(i=0;i<u;i++)this.buffer[this.leftover+i]=h[d+i];this.leftover+=u}};function bt(h,d,u,i,y,C){var O=new $e(C);return O.update(u,i,y),O.finish(h,d),0}function c(h,d,u,i,y,C){var O=new Uint8Array(16);return bt(O,0,u,i,y,C),Ne(h,d,O,0)}function xt(h,d,u,i,y){var C;if(u<32)return-1;for(Te(h,0,d,0,u,i,y),bt(h,16,h,32,u-32,h),C=0;C<16;C++)h[C]=0;return 0}function dn(h,d,u,i,y){var C,O=new Uint8Array(32);if(u<32||(He(O,0,32,i,y),c(d,16,d,32,u-32,O)!==0))return-1;for(Te(h,0,d,0,u,i,y),C=0;C<32;C++)h[C]=0;return 0}function S(h,d){var u;for(u=0;u<16;u++)h[u]=d[u]|0}function et(h){var d,u,i=1;for(d=0;d<16;d++)u=h[d]+i+65535,i=Math.floor(u/65536),h[d]=u-i*65536;h[0]+=i-1+37*(i-1)}function Gt(h,d,u){for(var i,y=~(u-1),C=0;C<16;C++)i=y&(h[C]^d[C]),h[C]^=i,d[C]^=i}function pe(h,d){var u,i,y,C=l(),O=l();for(u=0;u<16;u++)O[u]=d[u];for(et(O),et(O),et(O),i=0;i<2;i++){for(C[0]=O[0]-65517,u=1;u<15;u++)C[u]=O[u]-65535-(C[u-1]>>16&1),C[u-1]&=65535;C[15]=O[15]-32767-(C[14]>>16&1),y=C[15]>>16&1,C[14]&=65535,Gt(O,C,1-y)}for(u=0;u<16;u++)h[2*u]=O[u]&255,h[2*u+1]=O[u]>>8}function Pt(h,d){var u=new Uint8Array(32),i=new Uint8Array(32);return pe(u,h),pe(i,d),ht(u,0,i,0)}function In(h){var d=new Uint8Array(32);return pe(d,h),d[0]&1}function Ct(h,d){var u;for(u=0;u<16;u++)h[u]=d[2*u]+(d[2*u+1]<<8);h[15]&=32767}function gt(h,d,u){for(var i=0;i<16;i++)h[i]=d[i]+u[i]}function Ke(h,d,u){for(var i=0;i<16;i++)h[i]=d[i]-u[i]}function Ie(h,d,u){var i,y,C=0,O=0,B=0,$=0,ae=0,Y=0,Me=0,ee=0,ge=0,be=0,Ae=0,V=0,xe=0,we=0,me=0,te=0,K=0,Z=0,ie=0,re=0,Q=0,T=0,E=0,q=0,N=0,G=0,j=0,ue=0,ke=0,Ce=0,Re=0,w=u[0],Ee=u[1],Oe=u[2],Pe=u[3],ve=u[4],Le=u[5],Ue=u[6],Qe=u[7],De=u[8],ze=u[9],Ye=u[10],Se=u[11],X=u[12],nt=u[13],je=u[14],st=u[15];i=d[0],C+=i*w,O+=i*Ee,B+=i*Oe,$+=i*Pe,ae+=i*ve,Y+=i*Le,Me+=i*Ue,ee+=i*Qe,ge+=i*De,be+=i*ze,Ae+=i*Ye,V+=i*Se,xe+=i*X,we+=i*nt,me+=i*je,te+=i*st,i=d[1],O+=i*w,B+=i*Ee,$+=i*Oe,ae+=i*Pe,Y+=i*ve,Me+=i*Le,ee+=i*Ue,ge+=i*Qe,be+=i*De,Ae+=i*ze,V+=i*Ye,xe+=i*Se,we+=i*X,me+=i*nt,te+=i*je,K+=i*st,i=d[2],B+=i*w,$+=i*Ee,ae+=i*Oe,Y+=i*Pe,Me+=i*ve,ee+=i*Le,ge+=i*Ue,be+=i*Qe,Ae+=i*De,V+=i*ze,xe+=i*Ye,we+=i*Se,me+=i*X,te+=i*nt,K+=i*je,Z+=i*st,i=d[3],$+=i*w,ae+=i*Ee,Y+=i*Oe,Me+=i*Pe,ee+=i*ve,ge+=i*Le,be+=i*Ue,Ae+=i*Qe,V+=i*De,xe+=i*ze,we+=i*Ye,me+=i*Se,te+=i*X,K+=i*nt,Z+=i*je,ie+=i*st,i=d[4],ae+=i*w,Y+=i*Ee,Me+=i*Oe,ee+=i*Pe,ge+=i*ve,be+=i*Le,Ae+=i*Ue,V+=i*Qe,xe+=i*De,we+=i*ze,me+=i*Ye,te+=i*Se,K+=i*X,Z+=i*nt,ie+=i*je,re+=i*st,i=d[5],Y+=i*w,Me+=i*Ee,ee+=i*Oe,ge+=i*Pe,be+=i*ve,Ae+=i*Le,V+=i*Ue,xe+=i*Qe,we+=i*De,me+=i*ze,te+=i*Ye,K+=i*Se,Z+=i*X,ie+=i*nt,re+=i*je,Q+=i*st,i=d[6],Me+=i*w,ee+=i*Ee,ge+=i*Oe,be+=i*Pe,Ae+=i*ve,V+=i*Le,xe+=i*Ue,we+=i*Qe,me+=i*De,te+=i*ze,K+=i*Ye,Z+=i*Se,ie+=i*X,re+=i*nt,Q+=i*je,T+=i*st,i=d[7],ee+=i*w,ge+=i*Ee,be+=i*Oe,Ae+=i*Pe,V+=i*ve,xe+=i*Le,we+=i*Ue,me+=i*Qe,te+=i*De,K+=i*ze,Z+=i*Ye,ie+=i*Se,re+=i*X,Q+=i*nt,T+=i*je,E+=i*st,i=d[8],ge+=i*w,be+=i*Ee,Ae+=i*Oe,V+=i*Pe,xe+=i*ve,we+=i*Le,me+=i*Ue,te+=i*Qe,K+=i*De,Z+=i*ze,ie+=i*Ye,re+=i*Se,Q+=i*X,T+=i*nt,E+=i*je,q+=i*st,i=d[9],be+=i*w,Ae+=i*Ee,V+=i*Oe,xe+=i*Pe,we+=i*ve,me+=i*Le,te+=i*Ue,K+=i*Qe,Z+=i*De,ie+=i*ze,re+=i*Ye,Q+=i*Se,T+=i*X,E+=i*nt,q+=i*je,N+=i*st,i=d[10],Ae+=i*w,V+=i*Ee,xe+=i*Oe,we+=i*Pe,me+=i*ve,te+=i*Le,K+=i*Ue,Z+=i*Qe,ie+=i*De,re+=i*ze,Q+=i*Ye,T+=i*Se,E+=i*X,q+=i*nt,N+=i*je,G+=i*st,i=d[11],V+=i*w,xe+=i*Ee,we+=i*Oe,me+=i*Pe,te+=i*ve,K+=i*Le,Z+=i*Ue,ie+=i*Qe,re+=i*De,Q+=i*ze,T+=i*Ye,E+=i*Se,q+=i*X,N+=i*nt,G+=i*je,j+=i*st,i=d[12],xe+=i*w,we+=i*Ee,me+=i*Oe,te+=i*Pe,K+=i*ve,Z+=i*Le,ie+=i*Ue,re+=i*Qe,Q+=i*De,T+=i*ze,E+=i*Ye,q+=i*Se,N+=i*X,G+=i*nt,j+=i*je,ue+=i*st,i=d[13],we+=i*w,me+=i*Ee,te+=i*Oe,K+=i*Pe,Z+=i*ve,ie+=i*Le,re+=i*Ue,Q+=i*Qe,T+=i*De,E+=i*ze,q+=i*Ye,N+=i*Se,G+=i*X,j+=i*nt,ue+=i*je,ke+=i*st,i=d[14],me+=i*w,te+=i*Ee,K+=i*Oe,Z+=i*Pe,ie+=i*ve,re+=i*Le,Q+=i*Ue,T+=i*Qe,E+=i*De,q+=i*ze,N+=i*Ye,G+=i*Se,j+=i*X,ue+=i*nt,ke+=i*je,Ce+=i*st,i=d[15],te+=i*w,K+=i*Ee,Z+=i*Oe,ie+=i*Pe,re+=i*ve,Q+=i*Le,T+=i*Ue,E+=i*Qe,q+=i*De,N+=i*ze,G+=i*Ye,j+=i*Se,ue+=i*X,ke+=i*nt,Ce+=i*je,Re+=i*st,C+=38*K,O+=38*Z,B+=38*ie,$+=38*re,ae+=38*Q,Y+=38*T,Me+=38*E,ee+=38*q,ge+=38*N,be+=38*G,Ae+=38*j,V+=38*ue,xe+=38*ke,we+=38*Ce,me+=38*Re,y=1,i=C+y+65535,y=Math.floor(i/65536),C=i-y*65536,i=O+y+65535,y=Math.floor(i/65536),O=i-y*65536,i=B+y+65535,y=Math.floor(i/65536),B=i-y*65536,i=$+y+65535,y=Math.floor(i/65536),$=i-y*65536,i=ae+y+65535,y=Math.floor(i/65536),ae=i-y*65536,i=Y+y+65535,y=Math.floor(i/65536),Y=i-y*65536,i=Me+y+65535,y=Math.floor(i/65536),Me=i-y*65536,i=ee+y+65535,y=Math.floor(i/65536),ee=i-y*65536,i=ge+y+65535,y=Math.floor(i/65536),ge=i-y*65536,i=be+y+65535,y=Math.floor(i/65536),be=i-y*65536,i=Ae+y+65535,y=Math.floor(i/65536),Ae=i-y*65536,i=V+y+65535,y=Math.floor(i/65536),V=i-y*65536,i=xe+y+65535,y=Math.floor(i/65536),xe=i-y*65536,i=we+y+65535,y=Math.floor(i/65536),we=i-y*65536,i=me+y+65535,y=Math.floor(i/65536),me=i-y*65536,i=te+y+65535,y=Math.floor(i/65536),te=i-y*65536,C+=y-1+37*(y-1),y=1,i=C+y+65535,y=Math.floor(i/65536),C=i-y*65536,i=O+y+65535,y=Math.floor(i/65536),O=i-y*65536,i=B+y+65535,y=Math.floor(i/65536),B=i-y*65536,i=$+y+65535,y=Math.floor(i/65536),$=i-y*65536,i=ae+y+65535,y=Math.floor(i/65536),ae=i-y*65536,i=Y+y+65535,y=Math.floor(i/65536),Y=i-y*65536,i=Me+y+65535,y=Math.floor(i/65536),Me=i-y*65536,i=ee+y+65535,y=Math.floor(i/65536),ee=i-y*65536,i=ge+y+65535,y=Math.floor(i/65536),ge=i-y*65536,i=be+y+65535,y=Math.floor(i/65536),be=i-y*65536,i=Ae+y+65535,y=Math.floor(i/65536),Ae=i-y*65536,i=V+y+65535,y=Math.floor(i/65536),V=i-y*65536,i=xe+y+65535,y=Math.floor(i/65536),xe=i-y*65536,i=we+y+65535,y=Math.floor(i/65536),we=i-y*65536,i=me+y+65535,y=Math.floor(i/65536),me=i-y*65536,i=te+y+65535,y=Math.floor(i/65536),te=i-y*65536,C+=y-1+37*(y-1),h[0]=C,h[1]=O,h[2]=B,h[3]=$,h[4]=ae,h[5]=Y,h[6]=Me,h[7]=ee,h[8]=ge,h[9]=be,h[10]=Ae,h[11]=V,h[12]=xe,h[13]=we,h[14]=me,h[15]=te}function it(h,d){Ie(h,d,d)}function cs(h,d){var u=l(),i;for(i=0;i<16;i++)u[i]=d[i];for(i=253;i>=0;i--)it(u,u),i!==2&&i!==4&&Ie(u,u,d);for(i=0;i<16;i++)h[i]=u[i]}function ls(h,d){var u=l(),i;for(i=0;i<16;i++)u[i]=d[i];for(i=250;i>=0;i--)it(u,u),i!==1&&Ie(u,u,d);for(i=0;i<16;i++)h[i]=u[i]}function en(h,d,u){var i=new Uint8Array(32),y=new Float64Array(80),C,O,B=l(),$=l(),ae=l(),Y=l(),Me=l(),ee=l();for(O=0;O<31;O++)i[O]=d[O];for(i[31]=d[31]&127|64,i[0]&=248,Ct(y,u),O=0;O<16;O++)$[O]=y[O],Y[O]=B[O]=ae[O]=0;for(B[0]=Y[0]=1,O=254;O>=0;--O)C=i[O>>>3]>>>(O&7)&1,Gt(B,$,C),Gt(ae,Y,C),gt(Me,B,ae),Ke(B,B,ae),gt(ae,$,Y),Ke($,$,Y),it(Y,Me),it(ee,B),Ie(B,ae,B),Ie(ae,$,Me),gt(Me,B,ae),Ke(B,B,ae),it($,B),Ke(ae,Y,ee),Ie(B,ae,I),gt(B,B,Y),Ie(ae,ae,B),Ie(B,Y,ee),Ie(Y,$,y),it($,Me),Gt(B,$,C),Gt(ae,Y,C);for(O=0;O<16;O++)y[O+16]=B[O],y[O+32]=ae[O],y[O+48]=$[O],y[O+64]=Y[O];var ge=y.subarray(32),be=y.subarray(16);return cs(ge,ge),Ie(be,be,ge),pe(h,be),0}function tn(h,d){return en(h,d,x)}function Pn(h,d){return p(d,32),tn(h,d)}function nn(h,d,u){var i=new Uint8Array(32);return en(i,u,d),W(h,m,i,_)}var hs=xt,sn=dn;function fs(h,d,u,i,y,C){var O=new Uint8Array(32);return nn(O,y,C),hs(h,d,u,i,O)}function us(h,d,u,i,y,C){var O=new Uint8Array(32);return nn(O,y,C),sn(h,d,u,i,O)}var ds=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function Ln(h,d,u,i){for(var y=new Int32Array(16),C=new Int32Array(16),O,B,$,ae,Y,Me,ee,ge,be,Ae,V,xe,we,me,te,K,Z,ie,re,Q,T,E,q,N,G,j,ue=h[0],ke=h[1],Ce=h[2],Re=h[3],w=h[4],Ee=h[5],Oe=h[6],Pe=h[7],ve=d[0],Le=d[1],Ue=d[2],Qe=d[3],De=d[4],ze=d[5],Ye=d[6],Se=d[7],X=0;i>=128;){for(re=0;re<16;re++)Q=8*re+X,y[re]=u[Q+0]<<24|u[Q+1]<<16|u[Q+2]<<8|u[Q+3],C[re]=u[Q+4]<<24|u[Q+5]<<16|u[Q+6]<<8|u[Q+7];for(re=0;re<80;re++)if(O=ue,B=ke,$=Ce,ae=Re,Y=w,Me=Ee,ee=Oe,ge=Pe,be=ve,Ae=Le,V=Ue,xe=Qe,we=De,me=ze,te=Ye,K=Se,T=Pe,E=Se,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=(w>>>14|De<<18)^(w>>>18|De<<14)^(De>>>9|w<<23),E=(De>>>14|w<<18)^(De>>>18|w<<14)^(w>>>9|De<<23),q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,T=w&Ee^~w&Oe,E=De&ze^~De&Ye,q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,T=ds[re*2],E=ds[re*2+1],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,T=y[re%16],E=C[re%16],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,Z=G&65535|j<<16,ie=q&65535|N<<16,T=Z,E=ie,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=(ue>>>28|ve<<4)^(ve>>>2|ue<<30)^(ve>>>7|ue<<25),E=(ve>>>28|ue<<4)^(ue>>>2|ve<<30)^(ue>>>7|ve<<25),q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,T=ue&ke^ue&Ce^ke&Ce,E=ve&Le^ve&Ue^Le&Ue,q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,ge=G&65535|j<<16,K=q&65535|N<<16,T=ae,E=xe,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=Z,E=ie,q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,ae=G&65535|j<<16,xe=q&65535|N<<16,ke=O,Ce=B,Re=$,w=ae,Ee=Y,Oe=Me,Pe=ee,ue=ge,Le=be,Ue=Ae,Qe=V,De=xe,ze=we,Ye=me,Se=te,ve=K,re%16===15)for(Q=0;Q<16;Q++)T=y[Q],E=C[Q],q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=y[(Q+9)%16],E=C[(Q+9)%16],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,Z=y[(Q+1)%16],ie=C[(Q+1)%16],T=(Z>>>1|ie<<31)^(Z>>>8|ie<<24)^Z>>>7,E=(ie>>>1|Z<<31)^(ie>>>8|Z<<24)^(ie>>>7|Z<<25),q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,Z=y[(Q+14)%16],ie=C[(Q+14)%16],T=(Z>>>19|ie<<13)^(ie>>>29|Z<<3)^Z>>>6,E=(ie>>>19|Z<<13)^(Z>>>29|ie<<3)^(ie>>>6|Z<<26),q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,y[Q]=G&65535|j<<16,C[Q]=q&65535|N<<16;T=ue,E=ve,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[0],E=d[0],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[0]=ue=G&65535|j<<16,d[0]=ve=q&65535|N<<16,T=ke,E=Le,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[1],E=d[1],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[1]=ke=G&65535|j<<16,d[1]=Le=q&65535|N<<16,T=Ce,E=Ue,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[2],E=d[2],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[2]=Ce=G&65535|j<<16,d[2]=Ue=q&65535|N<<16,T=Re,E=Qe,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[3],E=d[3],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[3]=Re=G&65535|j<<16,d[3]=Qe=q&65535|N<<16,T=w,E=De,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[4],E=d[4],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[4]=w=G&65535|j<<16,d[4]=De=q&65535|N<<16,T=Ee,E=ze,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[5],E=d[5],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[5]=Ee=G&65535|j<<16,d[5]=ze=q&65535|N<<16,T=Oe,E=Ye,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[6],E=d[6],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[6]=Oe=G&65535|j<<16,d[6]=Ye=q&65535|N<<16,T=Pe,E=Se,q=E&65535,N=E>>>16,G=T&65535,j=T>>>16,T=h[7],E=d[7],q+=E&65535,N+=E>>>16,G+=T&65535,j+=T>>>16,N+=q>>>16,G+=N>>>16,j+=G>>>16,h[7]=Pe=G&65535|j<<16,d[7]=Se=q&65535|N<<16,X+=128,i-=128}return i}function wt(h,d,u){var i=new Int32Array(8),y=new Int32Array(8),C=new Uint8Array(256),O,B=u;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,y[0]=4089235720,y[1]=2227873595,y[2]=4271175723,y[3]=1595750129,y[4]=2917565137,y[5]=725511199,y[6]=4215389547,y[7]=327033209,Ln(i,y,d,u),u%=128,O=0;O<u;O++)C[O]=d[B-u+O];for(C[u]=128,u=256-128*(u<112?1:0),C[u-9]=0,fe(C,u-8,B/536870912|0,B<<3),Ln(i,y,C,u),O=0;O<8;O++)fe(h,8*O,i[O],y[O]);return 0}function Ot(h,d){var u=l(),i=l(),y=l(),C=l(),O=l(),B=l(),$=l(),ae=l(),Y=l();Ke(u,h[1],h[0]),Ke(Y,d[1],d[0]),Ie(u,u,Y),gt(i,h[0],h[1]),gt(Y,d[0],d[1]),Ie(i,i,Y),Ie(y,h[3],d[3]),Ie(y,y,D),Ie(C,h[2],d[2]),gt(C,C,C),Ke(O,i,u),Ke(B,C,y),gt($,C,y),gt(ae,i,u),Ie(h[0],O,B),Ie(h[1],ae,$),Ie(h[2],$,B),Ie(h[3],O,ae)}function pn(h,d,u){var i;for(i=0;i<4;i++)Gt(h[i],d[i],u)}function qt(h,d){var u=l(),i=l(),y=l();cs(y,d[2]),Ie(u,d[0],y),Ie(i,d[1],y),pe(h,i),h[31]^=In(u)<<7}function rn(h,d,u){var i,y;for(S(h[0],k),S(h[1],v),S(h[2],v),S(h[3],k),y=255;y>=0;--y)i=u[y/8|0]>>(y&7)&1,pn(h,d,i),Ot(d,h),Ot(h,h),pn(h,d,i)}function Ge(h,d){var u=[l(),l(),l(),l()];S(u[0],J),S(u[1],oe),S(u[2],v),Ie(u[3],J,oe),rn(h,u,d)}function gn(h,d,u){var i=new Uint8Array(64),y=[l(),l(),l(),l()],C;for(u||p(d,32),wt(i,d,32),i[0]&=248,i[31]&=127,i[31]|=64,Ge(y,i),qt(h,y),C=0;C<32;C++)d[C+32]=h[C];return 0}var on=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Ht(h,d){var u,i,y,C;for(i=63;i>=32;--i){for(u=0,y=i-32,C=i-12;y<C;++y)d[y]+=u-16*d[i]*on[y-(i-32)],u=Math.floor((d[y]+128)/256),d[y]-=u*256;d[y]+=u,d[i]=0}for(u=0,y=0;y<32;y++)d[y]+=u-(d[31]>>4)*on[y],u=d[y]>>8,d[y]&=255;for(y=0;y<32;y++)d[y]-=u*on[y];for(i=0;i<32;i++)d[i+1]+=d[i]>>8,h[i]=d[i]&255}function mn(h){var d=new Float64Array(64),u;for(u=0;u<64;u++)d[u]=h[u];for(u=0;u<64;u++)h[u]=0;Ht(h,d)}function Un(h,d,u,i){var y=new Uint8Array(64),C=new Uint8Array(64),O=new Uint8Array(64),B,$,ae=new Float64Array(64),Y=[l(),l(),l(),l()];wt(y,i,32),y[0]&=248,y[31]&=127,y[31]|=64;var Me=u+64;for(B=0;B<u;B++)h[64+B]=d[B];for(B=0;B<32;B++)h[32+B]=y[32+B];for(wt(O,h.subarray(32),u+32),mn(O),Ge(Y,O),qt(h,Y),B=32;B<64;B++)h[B]=i[B];for(wt(C,h,u+64),mn(C),B=0;B<64;B++)ae[B]=0;for(B=0;B<32;B++)ae[B]=O[B];for(B=0;B<32;B++)for($=0;$<32;$++)ae[B+$]+=C[B]*y[$];return Ht(h.subarray(32),ae),Me}function ot(h,d){var u=l(),i=l(),y=l(),C=l(),O=l(),B=l(),$=l();return S(h[2],v),Ct(h[1],d),it(y,h[1]),Ie(C,y,M),Ke(y,y,h[2]),gt(C,h[2],C),it(O,C),it(B,O),Ie($,B,O),Ie(u,$,y),Ie(u,u,C),ls(u,u),Ie(u,u,y),Ie(u,u,C),Ie(u,u,C),Ie(h[0],u,C),it(i,h[0]),Ie(i,i,C),Pt(i,y)&&Ie(h[0],h[0],H),it(i,h[0]),Ie(i,i,C),Pt(i,y)?-1:(In(h[0])===d[31]>>7&&Ke(h[0],k,h[0]),Ie(h[3],h[0],h[1]),0)}function Ze(h,d,u,i){var y,C=new Uint8Array(32),O=new Uint8Array(64),B=[l(),l(),l(),l()],$=[l(),l(),l(),l()];if(u<64||ot($,i))return-1;for(y=0;y<u;y++)h[y]=d[y];for(y=0;y<32;y++)h[y+32]=i[y];if(wt(O,h,u),mn(O),rn(B,$,O),Ge($,d.subarray(32)),Ot(B,$),qt(C,B),u-=64,ht(d,0,C,0)){for(y=0;y<u;y++)h[y]=0;return-1}for(y=0;y<u;y++)h[y]=d[y+64];return u}var at=32,Dt=24,jt=32,Lt=16,Wt=32,Vt=32,Ut=32,$t=32,yn=32,an=Dt,ps=jt,bn=Lt,Fe=64,St=32,Ft=64,xn=32,Bn=64;o.lowlevel={crypto_core_hsalsa20:W,crypto_stream_xor:Te,crypto_stream:He,crypto_stream_salsa20_xor:le,crypto_stream_salsa20:he,crypto_onetimeauth:bt,crypto_onetimeauth_verify:c,crypto_verify_16:Ne,crypto_verify_32:ht,crypto_secretbox:xt,crypto_secretbox_open:dn,crypto_scalarmult:en,crypto_scalarmult_base:tn,crypto_box_beforenm:nn,crypto_box_afternm:hs,crypto_box:fs,crypto_box_open:us,crypto_box_keypair:Pn,crypto_hash:wt,crypto_sign:Un,crypto_sign_keypair:gn,crypto_sign_open:Ze,crypto_secretbox_KEYBYTES:at,crypto_secretbox_NONCEBYTES:Dt,crypto_secretbox_ZEROBYTES:jt,crypto_secretbox_BOXZEROBYTES:Lt,crypto_scalarmult_BYTES:Wt,crypto_scalarmult_SCALARBYTES:Vt,crypto_box_PUBLICKEYBYTES:Ut,crypto_box_SECRETKEYBYTES:$t,crypto_box_BEFORENMBYTES:yn,crypto_box_NONCEBYTES:an,crypto_box_ZEROBYTES:ps,crypto_box_BOXZEROBYTES:bn,crypto_sign_BYTES:Fe,crypto_sign_PUBLICKEYBYTES:St,crypto_sign_SECRETKEYBYTES:Ft,crypto_sign_SEEDBYTES:xn,crypto_hash_BYTES:Bn,gf:l,D:M,L:on,pack25519:pe,unpack25519:Ct,M:Ie,A:gt,S:it,Z:Ke,pow2523:ls,add:Ot,set25519:S,modL:Ht,scalarmult:rn,scalarbase:Ge};function ft(h,d){if(h.length!==at)throw new Error("bad key size");if(d.length!==Dt)throw new Error("bad nonce size")}function Ns(h,d){if(h.length!==Ut)throw new Error("bad public key size");if(d.length!==$t)throw new Error("bad secret key size")}function ct(){for(var h=0;h<arguments.length;h++)if(!(arguments[h]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function Nn(h){for(var d=0;d<h.length;d++)h[d]=0}o.randomBytes=function(h){var d=new Uint8Array(h);return p(d,h),d},o.secretbox=function(h,d,u){ct(h,d,u),ft(u,d);for(var i=new Uint8Array(jt+h.length),y=new Uint8Array(i.length),C=0;C<h.length;C++)i[C+jt]=h[C];return xt(y,i,i.length,d,u),y.subarray(Lt)},o.secretbox.open=function(h,d,u){ct(h,d,u),ft(u,d);for(var i=new Uint8Array(Lt+h.length),y=new Uint8Array(i.length),C=0;C<h.length;C++)i[C+Lt]=h[C];return i.length<32||dn(y,i,i.length,d,u)!==0?null:y.subarray(jt)},o.secretbox.keyLength=at,o.secretbox.nonceLength=Dt,o.secretbox.overheadLength=Lt,o.scalarMult=function(h,d){if(ct(h,d),h.length!==Vt)throw new Error("bad n size");if(d.length!==Wt)throw new Error("bad p size");var u=new Uint8Array(Wt);return en(u,h,d),u},o.scalarMult.base=function(h){if(ct(h),h.length!==Vt)throw new Error("bad n size");var d=new Uint8Array(Wt);return tn(d,h),d},o.scalarMult.scalarLength=Vt,o.scalarMult.groupElementLength=Wt,o.box=function(h,d,u,i){var y=o.box.before(u,i);return o.secretbox(h,d,y)},o.box.before=function(h,d){ct(h,d),Ns(h,d);var u=new Uint8Array(yn);return nn(u,h,d),u},o.box.after=o.secretbox,o.box.open=function(h,d,u,i){var y=o.box.before(u,i);return o.secretbox.open(h,d,y)},o.box.open.after=o.secretbox.open,o.box.keyPair=function(){var h=new Uint8Array(Ut),d=new Uint8Array($t);return Pn(h,d),{publicKey:h,secretKey:d}},o.box.keyPair.fromSecretKey=function(h){if(ct(h),h.length!==$t)throw new Error("bad secret key size");var d=new Uint8Array(Ut);return tn(d,h),{publicKey:d,secretKey:new Uint8Array(h)}},o.box.publicKeyLength=Ut,o.box.secretKeyLength=$t,o.box.sharedKeyLength=yn,o.box.nonceLength=an,o.box.overheadLength=o.secretbox.overheadLength,o.sign=function(h,d){if(ct(h,d),d.length!==Ft)throw new Error("bad secret key size");var u=new Uint8Array(Fe+h.length);return Un(u,h,h.length,d),u},o.sign.open=function(h,d){if(ct(h,d),d.length!==St)throw new Error("bad public key size");var u=new Uint8Array(h.length),i=Ze(u,h,h.length,d);if(i<0)return null;for(var y=new Uint8Array(i),C=0;C<y.length;C++)y[C]=u[C];return y},o.sign.detached=function(h,d){for(var u=o.sign(h,d),i=new Uint8Array(Fe),y=0;y<i.length;y++)i[y]=u[y];return i},o.sign.detached.verify=function(h,d,u){if(ct(h,d,u),d.length!==Fe)throw new Error("bad signature size");if(u.length!==St)throw new Error("bad public key size");var i=new Uint8Array(Fe+h.length),y=new Uint8Array(Fe+h.length),C;for(C=0;C<Fe;C++)i[C]=d[C];for(C=0;C<h.length;C++)i[C+Fe]=h[C];return Ze(y,i,i.length,u)>=0},o.sign.keyPair=function(){var h=new Uint8Array(St),d=new Uint8Array(Ft);return gn(h,d),{publicKey:h,secretKey:d}},o.sign.keyPair.fromSecretKey=function(h){if(ct(h),h.length!==Ft)throw new Error("bad secret key size");for(var d=new Uint8Array(St),u=0;u<d.length;u++)d[u]=h[32+u];return{publicKey:d,secretKey:new Uint8Array(h)}},o.sign.keyPair.fromSeed=function(h){if(ct(h),h.length!==xn)throw new Error("bad seed size");for(var d=new Uint8Array(St),u=new Uint8Array(Ft),i=0;i<32;i++)u[i]=h[i];return gn(d,u,!0),{publicKey:d,secretKey:u}},o.sign.publicKeyLength=St,o.sign.secretKeyLength=Ft,o.sign.seedLength=xn,o.sign.signatureLength=Fe,o.hash=function(h){ct(h);var d=new Uint8Array(Bn);return wt(d,h,h.length),d},o.hash.hashLength=Bn,o.verify=function(h,d){return ct(h,d),h.length===0||d.length===0||h.length!==d.length?!1:de(h,0,d,0,h.length)===0},o.setPRNG=function(h){p=h},(function(){var h=typeof self<"u"?self.crypto||self.msCrypto:null;if(h&&h.getRandomValues){var d=65536;o.setPRNG(function(u,i){var y,C=new Uint8Array(i);for(y=0;y<i;y+=d)h.getRandomValues(C.subarray(y,y+Math.min(i-y,d)));for(y=0;y<i;y++)u[y]=C[y];Nn(C)})}else typeof tl<"u"&&(h=rl,h&&h.randomBytes&&o.setPRNG(function(u,i){var y,C=h.randomBytes(i);for(y=0;y<i;y++)u[y]=C[y];Nn(C)}))})()})(f.exports?f.exports:self.nacl=self.nacl||{})})(cr)),cr.exports}var ol=il();const fr=zc(ol),Mn=24,al=16;function cl(f,o){const l=fr.randomBytes(Mn),p=fr.secretbox(f,l,o),m=new Uint8Array(Mn+p.length);return m.set(l),m.set(p,Mn),m}function ll(f,o){if(f.length<Mn+al)throw new Error("Sealed data too short");const l=f.slice(0,Mn),p=f.slice(Mn),m=fr.secretbox.open(p,l,o);if(!m)throw new Error("Decryption failed - data may be tampered with");return m}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function hl(f){return f instanceof Uint8Array||ArrayBuffer.isView(f)&&f.constructor.name==="Uint8Array"}function ur(f){if(!Number.isSafeInteger(f)||f<0)throw new Error("positive integer expected, got "+f)}function Ps(f,...o){if(!hl(f))throw new Error("Uint8Array expected");if(o.length>0&&!o.includes(f.length))throw new Error("Uint8Array expected of length "+o+", got length="+f.length)}function Or(f){if(typeof f!="function"||typeof f.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ur(f.outputLen),ur(f.blockLen)}function Ts(f,o=!0){if(f.destroyed)throw new Error("Hash instance has been destroyed");if(o&&f.finished)throw new Error("Hash#digest() has already been called")}function fl(f,o){Ps(f);const l=o.outputLen;if(f.length<l)throw new Error("digestInto() expects output buffer of length at least "+l)}function rs(...f){for(let o=0;o<f.length;o++)f[o].fill(0)}function lr(f){return new DataView(f.buffer,f.byteOffset,f.byteLength)}function Mt(f,o){return f<<32-o|f>>>o}function ul(f){if(typeof f!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(f))}function is(f){return typeof f=="string"&&(f=ul(f)),Ps(f),f}class oo{}function dl(f){const o=p=>f().update(is(p)).digest(),l=f();return o.outputLen=l.outputLen,o.blockLen=l.blockLen,o.create=()=>f(),o}function pl(f,o,l,p){if(typeof f.setBigUint64=="function")return f.setBigUint64(o,l,p);const m=BigInt(32),x=BigInt(4294967295),k=Number(l>>m&x),v=Number(l&x),I=p?4:0,M=p?0:4;f.setUint32(o+I,k,p),f.setUint32(o+M,v,p)}function gl(f,o,l){return f&o^~f&l}function ml(f,o,l){return f&o^f&l^o&l}class yl extends oo{constructor(o,l,p,m){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=o,this.outputLen=l,this.padOffset=p,this.isLE=m,this.buffer=new Uint8Array(o),this.view=lr(this.buffer)}update(o){Ts(this),o=is(o),Ps(o);const{view:l,buffer:p,blockLen:m}=this,x=o.length;for(let k=0;k<x;){const v=Math.min(m-this.pos,x-k);if(v===m){const I=lr(o);for(;m<=x-k;k+=m)this.process(I,k);continue}p.set(o.subarray(k,k+v),this.pos),this.pos+=v,k+=v,this.pos===m&&(this.process(l,0),this.pos=0)}return this.length+=o.length,this.roundClean(),this}digestInto(o){Ts(this),fl(o,this),this.finished=!0;const{buffer:l,view:p,blockLen:m,isLE:x}=this;let{pos:k}=this;l[k++]=128,rs(this.buffer.subarray(k)),this.padOffset>m-k&&(this.process(p,0),k=0);for(let J=k;J<m;J++)l[J]=0;pl(p,m-8,BigInt(this.length*8),x),this.process(p,0);const v=lr(o),I=this.outputLen;if(I%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const M=I/4,D=this.get();if(M>D.length)throw new Error("_sha2: outputLen bigger than state");for(let J=0;J<M;J++)v.setUint32(4*J,D[J],x)}digest(){const{buffer:o,outputLen:l}=this;this.digestInto(o);const p=o.slice(0,l);return this.destroy(),p}_cloneInto(o){o||(o=new this.constructor),o.set(...this.get());const{blockLen:l,buffer:p,length:m,finished:x,destroyed:k,pos:v}=this;return o.destroyed=k,o.finished=x,o.length=m,o.pos=v,m%l&&o.buffer.set(p),o}clone(){return this._cloneInto()}}const Qt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),bl=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Yt=new Uint32Array(64);class xl extends yl{constructor(o=32){super(64,o,8,!1),this.A=Qt[0]|0,this.B=Qt[1]|0,this.C=Qt[2]|0,this.D=Qt[3]|0,this.E=Qt[4]|0,this.F=Qt[5]|0,this.G=Qt[6]|0,this.H=Qt[7]|0}get(){const{A:o,B:l,C:p,D:m,E:x,F:k,G:v,H:I}=this;return[o,l,p,m,x,k,v,I]}set(o,l,p,m,x,k,v,I){this.A=o|0,this.B=l|0,this.C=p|0,this.D=m|0,this.E=x|0,this.F=k|0,this.G=v|0,this.H=I|0}process(o,l){for(let J=0;J<16;J++,l+=4)Yt[J]=o.getUint32(l,!1);for(let J=16;J<64;J++){const oe=Yt[J-15],H=Yt[J-2],fe=Mt(oe,7)^Mt(oe,18)^oe>>>3,de=Mt(H,17)^Mt(H,19)^H>>>10;Yt[J]=de+Yt[J-7]+fe+Yt[J-16]|0}let{A:p,B:m,C:x,D:k,E:v,F:I,G:M,H:D}=this;for(let J=0;J<64;J++){const oe=Mt(v,6)^Mt(v,11)^Mt(v,25),H=D+oe+gl(v,I,M)+bl[J]+Yt[J]|0,de=(Mt(p,2)^Mt(p,13)^Mt(p,22))+ml(p,m,x)|0;D=M,M=I,I=v,v=k+H|0,k=x,x=m,m=p,p=H+de|0}p=p+this.A|0,m=m+this.B|0,x=x+this.C|0,k=k+this.D|0,v=v+this.E|0,I=I+this.F|0,M=M+this.G|0,D=D+this.H|0,this.set(p,m,x,k,v,I,M,D)}roundClean(){rs(Yt)}destroy(){this.set(0,0,0,0,0,0,0,0),rs(this.buffer)}}const wl=dl(()=>new xl),Ls=wl;class ao extends oo{constructor(o,l){super(),this.finished=!1,this.destroyed=!1,Or(o);const p=is(l);if(this.iHash=o.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const m=this.blockLen,x=new Uint8Array(m);x.set(p.length>m?o.create().update(p).digest():p);for(let k=0;k<x.length;k++)x[k]^=54;this.iHash.update(x),this.oHash=o.create();for(let k=0;k<x.length;k++)x[k]^=106;this.oHash.update(x),rs(x)}update(o){return Ts(this),this.iHash.update(o),this}digestInto(o){Ts(this),Ps(o,this.outputLen),this.finished=!0,this.iHash.digestInto(o),this.oHash.update(o),this.oHash.digestInto(o),this.destroy()}digest(){const o=new Uint8Array(this.oHash.outputLen);return this.digestInto(o),o}_cloneInto(o){o||(o=Object.create(Object.getPrototypeOf(this),{}));const{oHash:l,iHash:p,finished:m,destroyed:x,blockLen:k,outputLen:v}=this;return o=o,o.finished=m,o.destroyed=x,o.blockLen=k,o.outputLen=v,o.oHash=l._cloneInto(o.oHash),o.iHash=p._cloneInto(o.iHash),o}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Sr=(f,o,l)=>new ao(f,o).update(l).digest();Sr.create=(f,o)=>new ao(f,o);function vl(f,o,l){return Or(f),l===void 0&&(l=new Uint8Array(f.outputLen)),Sr(f,is(l),is(o))}const hr=Uint8Array.from([0]),kl=Uint8Array.of();function _l(f,o,l,p=32){Or(f),ur(p);const m=f.outputLen;if(p>255*m)throw new Error("Length should be <= 255*HashLen");const x=Math.ceil(p/m),k=new Uint8Array(x*m),v=Sr.create(f,o),I=v._cloneInto(),M=new Uint8Array(v.outputLen);for(let D=0;D<x;D++)hr[0]=D+1,I.update(D===0?kl:M).update(l).update(hr).digestInto(M),k.set(M,m*D),v._cloneInto(I);return v.destroy(),I.destroy(),rs(M,hr),k.slice(0,p)}const Al=(f,o,l,p,m)=>_l(f,vl(f,o,l),p,m);function Rl(f){const o=Ls(new TextEncoder().encode(`airloom-session:${f}`));return Array.from(o.slice(0,16),l=>l.toString(16).padStart(2,"0")).join("")}function co(f,o){const l=new TextEncoder().encode("airloom-v1");return Al(Ls,f,l,"airloom-encryption",32)}function Cl(f){return f.replace(/[-\s]/g,"").toUpperCase()}class Ol{constructor(o,l,p){ce(this,"_ended",!1);this.id=o,this.sendFn=l,this.meta=p}write(o){if(this._ended)throw new Error("Cannot write after stream has ended");this.sendFn({type:"stream_chunk",id:this.id,data:o})}end(){this._ended||(this._ended=!0,this.sendFn({type:"stream_end",id:this.id}))}get ended(){return this._ended}}class Sl extends io.EventEmitter{constructor(l,p){super();ce(this,"id");ce(this,"meta");ce(this,"_ended",!1);this.id=l,this.meta=p}_pushChunk(l){this._ended||this.emit("data",l)}_end(){this._ended||(this._ended=!0,this.emit("end"))}get ended(){return this._ended}}class Tl extends io.EventEmitter{constructor(l){super();ce(this,"adapter");ce(this,"encryptionKey");ce(this,"role");ce(this,"streams",new Map);ce(this,"_ready",!1);ce(this,"msgCounter",0);this.adapter=l.adapter,this.encryptionKey=l.encryptionKey??null,this.role=l.role,this.setupHandlers()}setupHandlers(){this.adapter.onMessage(l=>{this.handlePayload(l)}),this.adapter.onPeerJoined(()=>{this.encryptionKey&&(this._ready=!0,this.emit("ready"))}),this.adapter.onPeerLeft(()=>{this._ready=!1,this.emit("peer_left")}),this.adapter.onError(l=>this.emit("error",l)),this.adapter.onDisconnect(()=>this.emit("disconnect"))}handlePayload(l){try{if(!this.encryptionKey){this.emit("error",new Error("Received data but no encryption key"));return}const p=Yc(l),m=ll(p,this.encryptionKey),x=Xc(m);this.handleMessage(x)}catch(p){this.emit("error",p)}}handleMessage(l){switch(l.type){case"message":this.emit("message",l.data);break;case"stream_start":{const p=new Sl(l.id,l.meta);this.streams.set(l.id,p),this.emit("stream",p);break}case"stream_chunk":{const p=this.streams.get(l.id);p&&p._pushChunk(l.data);break}case"stream_end":{const p=this.streams.get(l.id);p&&(p._end(),this.streams.delete(l.id));break}}}sendRaw(l){if(!this.encryptionKey)throw new Error("No encryption key established");const p=Zc(l),m=cl(p,this.encryptionKey);this.adapter.send(Qc(m))}send(l){const p=`msg-${++this.msgCounter}`;this.sendRaw({type:"message",id:p,data:l})}createStream(l){const p=`stream-${++this.msgCounter}`;return this.sendRaw({type:"stream_start",id:p,meta:l}),new Ol(p,m=>this.sendRaw(m),l)}async connect(l){await this.adapter.connect(l,this.role)}get ready(){return this._ready}waitForReady(l=3e4){return this._ready?Promise.resolve():new Promise((p,m)=>{const x=()=>{clearTimeout(M),this.removeListener("ready",k),this.removeListener("error",v),this.removeListener("disconnect",I)},k=()=>{x(),p()},v=D=>{x(),m(D)},I=()=>{x(),m(new Error("Disconnected before ready"))},M=setTimeout(()=>{x(),m(new Error("Timed out waiting for peer"))},l);this.once("ready",k),this.once("error",v),this.once("disconnect",I)})}close(){for(const l of this.streams.values())l._end();this.streams.clear(),this.adapter.close(),this.removeAllListeners()}}class El{constructor(o){ce(this,"ws",null);ce(this,"url");ce(this,"_connected",!1);ce(this,"messageHandlers",[]);ce(this,"peerJoinedHandlers",[]);ce(this,"peerLeftHandlers",[]);ce(this,"errorHandlers",[]);ce(this,"disconnectHandlers",[]);ce(this,"reconnectAttempts",0);ce(this,"maxReconnectAttempts",5);ce(this,"reconnectTimer",null);ce(this,"shouldReconnect",!1);ce(this,"sessionToken",null);ce(this,"role",null);this.url=o}get connected(){return this._connected}async connect(o,l){return this.sessionToken=o,this.role=l,this.doConnect()}async doConnect(){const o=await this.createWebSocket(this.url);return new Promise((l,p)=>{o.onopen=()=>{this._connected=!0,this.shouldReconnect=!0,this.reconnectAttempts=0;const m=this.role==="host"?{type:"create",sessionToken:this.sessionToken}:{type:"join",sessionToken:this.sessionToken};o.send(JSON.stringify(m)),l()},o.onmessage=m=>{const x=m.data,k=typeof x=="string"?x:typeof Buffer<"u"&&Buffer.isBuffer(x)?x.toString("utf-8"):new TextDecoder().decode(x);try{const v=JSON.parse(k);switch(v.type){case"created":case"joined":break;case"peer_joined":this.peerJoinedHandlers.forEach(I=>I());break;case"peer_left":this.peerLeftHandlers.forEach(I=>I());break;case"forward":this.messageHandlers.forEach(I=>I(v.payload));break;case"error":this.errorHandlers.forEach(I=>I(new Error(v.message)));break}}catch(v){this.errorHandlers.forEach(I=>I(v instanceof Error?v:new Error(String(v))))}},o.onclose=()=>{const m=this._connected;this._connected=!1,m&&this.disconnectHandlers.forEach(x=>x()),this.shouldReconnect&&!this.reconnectTimer&&this.attemptReconnect()},o.onerror=m=>{const x=m instanceof Error?m:new Error("WebSocket error");this.errorHandlers.forEach(k=>k(x)),this._connected||(this.shouldReconnect=!1,p(x))},this.ws=o})}async createWebSocket(o){if(typeof globalThis.WebSocket<"u")return new globalThis.WebSocket(o);try{const{default:l}=await ro(async()=>{const{default:p}=await import("./browser-CHRQqYPW.js").then(m=>m.b);return{default:p}},[],import.meta.url);return new l(o)}catch{throw new Error('No WebSocket implementation available. Install the "ws" package for Node.js.')}}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts||!this.sessionToken||!this.role)return;this.reconnectAttempts++;const o=Math.min(1e3*Math.pow(2,this.reconnectAttempts-1),3e4);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect().catch(()=>{})},o)}send(o){!this.ws||!this._connected||this.ws.send(JSON.stringify({type:"forward",payload:o}))}onMessage(o){this.messageHandlers.push(o)}onPeerJoined(o){this.peerJoinedHandlers.push(o)}onPeerLeft(o){this.peerLeftHandlers.push(o)}onError(o){this.errorHandlers.push(o)}onDisconnect(o){this.disconnectHandlers.push(o)}close(){var o;this.shouldReconnect=!1,this.maxReconnectAttempts=0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),(o=this.ws)==null||o.close(),this.ws=null,this._connected=!1}}var Cs={exports:{}};/*@license Copyright 2015-2022 Ably Real-time Ltd (ably.com)
2
2
 
3
3
  Ably JavaScript Library v2.20.0
4
4
  https://github.com/ably/ably-js
@@ -11,7 +11,7 @@ Released under the Apache Licence v2.0*/var Ml=Cs.exports,Ji;function Il(){retur
11
11
  `+L+`
12
12
  `;return g.mac=g.mac||N(F,a),c.logAction(this.logger,c.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),g}async getAuthParams(){if(this.method=="basic")return{key:this.key};{let e=await this._ensureValidAuthCredentials(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:e.token}}}async getAuthHeaders(){if(this.method=="basic")return{authorization:"Basic "+this.basicKey};{const e=await this._ensureValidAuthCredentials(!1);if(!e)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+an(e.token)}}}_saveBasicOptions(e){this.method="basic",this.key=e.key,this.basicKey=an(e.key),this.authOptions=e||{},"clientId"in e&&this._userSetClientId(e.clientId)}_saveTokenOptions(e,t){this.method="token",e&&(this.tokenParams=e),t&&(t.token&&(t.tokenDetails=typeof t.token=="string"?{token:t.token}:t.token),t.tokenDetails&&(this.tokenDetails=t.tokenDetails),"clientId"in t&&this._userSetClientId(t.clientId),this.authOptions=t)}async _ensureValidAuthCredentials(e){const t=this.tokenDetails;if(t){if(this._tokenClientIdMismatch(t.clientId))throw new S("Mismatch between clientId in token ("+t.clientId+") and current clientId ("+this.clientId+")",40102,403);if(!this.client.isTimeOffsetSet()||!t.expires||t.expires>=this.client.getTimestampUsingOffset())return c.logAction(this.logger,c.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+t.expires),t;c.logAction(this.logger,c.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}const n=(this.waitingForTokenRequest||(this.waitingForTokenRequest=me.create(this.logger))).createPromise();if(this.currentTokenRequestId!==null&&!e)return n;const s=this.currentTokenRequestId=w();let r,a=null;try{r=await this.requestToken(this.tokenParams,this.authOptions)}catch(b){a=b}if(this.currentTokenRequestId>s)return c.logAction(this.logger,c.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one"),n;this.currentTokenRequestId=null;const g=this.waitingForTokenRequest;return this.waitingForTokenRequest=null,a?(g==null||g.rejectAll(a),n):(g==null||g.resolveAll(this.tokenDetails=r),n)}_userSetClientId(e){if(typeof e=="string"||e===null){if(e==="*")throw new S('Can’t 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);{const t=this._uncheckedSetClientId(e);if(t)throw t}}else throw new S("clientId must be either a string or null",40012,400)}_uncheckedSetClientId(e){if(this._tokenClientIdMismatch(e)){const t="Unexpected clientId mismatch: client has "+this.clientId+", requested "+e,n=new S(t,40102,401);return c.logAction(this.logger,c.LOG_ERROR,"Auth._uncheckedSetClientId()",t),n}else return this.clientId=this.tokenParams.clientId=e,null}_tokenClientIdMismatch(e){return!!(this.clientId&&this.clientId!=="*"&&e&&e!=="*"&&this.clientId!==e)}static isTokenErr(e){return e.code&&e.code>=40140&&e.code<40150}revokeTokens(e,t){return this.client.rest.revokeTokens(e,t)}async _getTimestamp(e){return this.client.getTimestamp(e||!!this.authOptions.queryTime)}},Oe=Ee;function Pe(e){const t=[];if(e)for(const n in e)t.push(n+"="+e[n]);return t.join("&")}function ve(e,t){return e+(t?"?":"")+Pe(t)}function Le(e,t,n,s,r){e.error?c.logActionNoStrip(r,c.LOG_MICRO,"Http."+t+"()","Received Error; "+ve(n,s)+"; Error: "+Ge(e.error)):c.logActionNoStrip(r,c.LOG_MICRO,"Http."+t+"()","Received; "+ve(n,s)+"; Headers: "+Pe(e.headers)+"; StatusCode: "+e.statusCode+"; Body"+(_.BufferUtils.isBuffer(e.body)?" (Base64): "+_.BufferUtils.base64Encode(e.body):": "+e.body))}function Ue(e,t,n,s,r){r.shouldLog(c.LOG_MICRO)&&c.logActionNoStrip(r,c.LOG_MICRO,"Http."+e+"()","Sending; "+ve(t,s)+"; Body"+(_.BufferUtils.isBuffer(n)?" (Base64): "+_.BufferUtils.base64Encode(n):": "+n))}var Qe=class{constructor(e){this.client=e,this.platformHttp=new _.Http(e),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var e,t;return(t=(e=this.client)==null?void 0:e.logger)!=null?t:c.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}_getHosts(e){const t=e.connection,n=t&&t.connectionManager.host;return n?[n].concat(V.getFallbackHosts(e.options)):V.getHosts(e.options)}async do(e,t,n,s,r){try{const a=this.client;if(!a)return{error:new S("http.do called without client",5e4,500)};const g=typeof t=="function"?t:function(U){return a.baseUri(U)+t},b=a._currentFallback;if(b)if(b.validUntil>Date.now()){const U=await this.doUri(e,g(b.host),n,s,r);return U.error&&this.platformHttp.shouldFallback(U.error)?(a._currentFallback=null,this.do(e,t,n,s,r)):U}else a._currentFallback=null;const R=this._getHosts(a);if(R.length===1)return this.doUri(e,g(R[0]),n,s,r);let A=null;const L=async(U,F)=>{const P=U.shift();A=A??new Date;const ne=await this.doUri(e,g(P),n,s,r);return ne.error&&this.platformHttp.shouldFallback(ne.error)&&U.length?Date.now()-A.getTime()>a.options.timeouts.httpMaxRetryDuration?{error:new S(`Timeout for trying fallback hosts retries. Total elapsed time exceeded the ${a.options.timeouts.httpMaxRetryDuration}ms limit`,50003,500)}:L(U,!0):(F&&(a._currentFallback={host:P,validUntil:Date.now()+a.options.timeouts.fallbackRetryTimeout}),ne)};return L(R)}catch(a){return{error:new S(`Unexpected error in Http.do: ${Ge(a)}`,500,5e4)}}}async doUri(e,t,n,s,r){try{Ue(e,t,s,r,this.logger);const a=await this.platformHttp.doUri(e,t,n,s,r);return this.logger.shouldLog(c.LOG_MICRO)&&Le(a,e,t,r,this.logger),a}catch(a){return{error:new S(`Unexpected error in Http.doUri: ${Ge(a)}`,500,5e4)}}}};function De(e,t,n,s){try{n.apply(t,s)}catch(r){c.logAction(e,c.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+r+"; stack = "+(r&&r.stack))}}function ze(e,t,n){let s,r,a;for(let g=0;g<e.length;g++)if(s=e[g],n&&(s=s[n]),Array.isArray(s)){for(;(r=s.indexOf(t))!==-1;)s.splice(r,1);n&&s.length===0&&delete e[g][n]}else if(Ct(s))for(a in s)Object.prototype.hasOwnProperty.call(s,a)&&Array.isArray(s[a])&&ze([s],t,a)}var Ye=class{constructor(e){this.logger=e,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(...e){if(e.length===1){const t=e[0];if(typeof t=="function")this.any.push(t);else throw new Error("EventListener.on(): Invalid arguments: "+_.Config.inspect(e))}if(e.length===2){const[t,n]=e;if(typeof n!="function")throw new Error("EventListener.on(): Invalid arguments: "+_.Config.inspect(e));if(Ke(t))this.any.push(n);else if(Array.isArray(t))t.forEach(s=>{this.on(s,n)});else{if(typeof t!="string")throw new Error("EventListener.on(): Invalid arguments: "+_.Config.inspect(e));(this.events[t]||(this.events[t]=[])).push(n)}}}off(...e){if(e.length==0||Ke(e[0])&&Ke(e[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}const[t,n]=e;let s=null,r=null;if(e.length===1||!n)typeof t=="function"?s=t:r=t;else{if(typeof n!="function")throw new Error("EventEmitter.off(): invalid arguments:"+_.Config.inspect(e));[r,s]=[t,n]}if(s&&Ke(r)){ze([this.any,this.events,this.anyOnce,this.eventsOnce],s);return}if(Array.isArray(r)){r.forEach(a=>{this.off(a,s)});return}if(typeof r!="string")throw new Error("EventEmitter.off(): invalid arguments:"+_.Config.inspect(e));s?ze([this.events,this.eventsOnce],s,r):(delete this.events[r],delete this.eventsOnce[r])}listeners(e){if(e){const t=this.events[e]||[];return this.eventsOnce[e]&&Array.prototype.push.apply(t,this.eventsOnce[e]),t.length?t:null}return this.any.length?this.any:null}emit(e,...t){const n={event:e},s=[];this.anyOnce.length&&(Array.prototype.push.apply(s,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(s,this.any);const r=this.eventsOnce[e];r&&(Array.prototype.push.apply(s,r),delete this.eventsOnce[e]);const a=this.events[e];a&&Array.prototype.push.apply(s,a),s.forEach(g=>{De(this.logger,n,g,t)})}once(...e){const t=e.length;if(t===0||t===1&&typeof e[0]!="function"){const r=e[0];return new Promise(a=>{this.once(r,a)})}const[n,s]=e;if(e.length===1&&typeof n=="function")this.anyOnce.push(n);else if(Ke(n)){if(typeof s!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+_.Config.inspect(e));this.anyOnce.push(s)}else if(Array.isArray(n)){const r=this,a=function(){const g=Array.prototype.slice.call(arguments);if(n.forEach(function(b){r.off(b,a)}),typeof s!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+_.Config.inspect(e));s.apply(this,g)};n.forEach(function(g){r.on(g,a)})}else{if(typeof n!="string")throw new Error("EventEmitter.once(): Invalid arguments:"+_.Config.inspect(e));const r=this.eventsOnce[n]||(this.eventsOnce[n]=[]);if(s){if(typeof s!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+_.Config.inspect(e));r.push(s)}}}async whenState(e,t){if(typeof e!="string"||typeof t!="string")throw new Error("whenState requires a valid state String argument");return e===t?null:this.once(e)}},Se=Ye,X={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},nt=[];Object.keys(X).forEach(function(e){nt[X[e]]=e});var je={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},st=Object.keys(je);je.MODE_ALL=je.PRESENCE|je.PUBLISH|je.SUBSCRIBE|je.PRESENCE_SUBSCRIBE|je.ANNOTATION_PUBLISH|je.ANNOTATION_SUBSCRIBE|je.OBJECT_SUBSCRIBE|je.OBJECT_PUBLISH;var Gr=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function Go(e){return!e||!e.channelOptions?{channelOptions:e,plugins:{},baseEncodedPreviousPayload:void 0}:e}function qr(e,t,n){if(n&&n.cipher){e||Fe("Crypto");const s=e.getCipher(n.cipher,t);return{cipher:s.cipherParams,channelCipher:s.cipher}}return n??{}}async function qo(e,t){const{data:n,encoding:s}=await Hr(e.data,e.encoding,t);return e.data=n,e.encoding=s,e}async function Hr(e,t,n){let s=n.channelCipher,r=e,a=t?t+"/":"";_.BufferUtils.isBuffer(r)||(r=_.BufferUtils.utf8Encode(String(r)),a=a+"utf-8/");const g=await s.encrypt(r);return a=a+"cipher+"+s.algorithm,{data:g,encoding:a}}async function Gs(e,t){const{data:n,encoding:s}=Dr(e.data,e.encoding);return e.data=n,e.encoding=s,t!=null&&t.cipher?qo(e,t):e}function Dr(e,t){if(typeof e=="string"||_.BufferUtils.isBuffer(e)||e===null||e===void 0)return{data:e,encoding:t};if(Ct(e)||Array.isArray(e))return{data:JSON.stringify(e),encoding:t?t+"/json":"json"};throw new S("Data type is unsupported",40013,400)}async function qs(e,t){const{data:n,encoding:s,error:r}=await jr(e.data,e.encoding,t);if(e.data=n,e.encoding=s,r)throw r}async function jr(e,t,n){const s=Go(n);let r=e,a=e,g=t,b;if(t){const R=t.split("/");let A,L=R.length,U="";try{for(;(A=L)>0;){const F=R[--L].match(/([-\w]+)(\+([\w-]+))?/);if(!F)break;switch(U=F[1],U){case"base64":a=_.BufferUtils.base64Decode(String(a)),A==R.length&&(r=a);continue;case"utf-8":a=_.BufferUtils.utf8Decode(a);continue;case"json":a=JSON.parse(a);continue;case"cipher":if(s.channelOptions!=null&&s.channelOptions.cipher&&s.channelOptions.channelCipher){const P=F[3],ne=s.channelOptions.channelCipher;if(P!=ne.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");a=await ne.decrypt(a);continue}else throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!s.plugins||!s.plugins.vcdiff)throw new S("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if(typeof Uint8Array>"u")throw new S("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{let P=s.baseEncodedPreviousPayload;typeof P=="string"&&(P=_.BufferUtils.utf8Encode(P));const ne=_.BufferUtils.toBuffer(P);a=_.BufferUtils.toBuffer(a),a=_.BufferUtils.arrayBufferViewToBuffer(s.plugins.vcdiff.decode(a,ne)),r=a}catch(P){throw new S("Vcdiff delta decode failed with "+P,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(F){const P=F;b=new S(`Error processing the ${U} encoding, decoder returned ‘${P.message}’`,P.code||40013,400)}finally{g=A<=0?null:R.slice(0,A).join("/")}}return b?{error:b,data:a,encoding:g}:(s.baseEncodedPreviousPayload=r,{data:a,encoding:g})}function Hs(...e){const t=e.length>0?"json":"msgpack",{data:n,encoding:s}=Wr(this.data,this.encoding,t);return Object.assign({},this,{encoding:s,data:n})}function Wr(e,t,n){return!e||!_.BufferUtils.isBuffer(e)?{data:e,encoding:t}:n==="msgpack"?{data:_.BufferUtils.toBuffer(e),encoding:t}:{data:_.BufferUtils.base64Encode(e),encoding:t?t+"/base64":"base64"}}var gs={encryptData:Hr,encodeData:Dr,encodeDataForWire:Wr,decodeData:jr};function ms(e){const{id:t,connectionId:n,timestamp:s}=e;let r;switch(e.action){case X.MESSAGE:{r=e.messages;break}case X.PRESENCE:case X.SYNC:r=e.presence;break;case X.ANNOTATION:r=e.annotations;break;case X.OBJECT:case X.OBJECT_SYNC:r=e.state;break;default:throw new S("Unexpected action "+e.action,4e4,400)}for(let a=0;a<r.length;a++){const g=r[a];g.connectionId||(g.connectionId=n),g.timestamp||(g.timestamp=s),t&&!g.id&&(g.id=t+":"+a)}}function wn(e,t){let n="["+t;for(const s in e)s==="data"?typeof e.data=="string"?n+="; data="+e.data:_.BufferUtils.isBuffer(e.data)?n+="; data (buffer)="+_.BufferUtils.base64Encode(e.data):typeof e.data<"u"&&(n+="; data (json)="+JSON.stringify(e.data)):s&&(s==="extras"||s==="operation")?n+="; "+s+"="+JSON.stringify(e[s]):s==="version"?n+="; version="+JSON.stringify(e[s]):s==="annotations"?n+="; annotations="+JSON.stringify(e[s]):e[s]!==void 0&&(n+="; "+s+"="+e[s]);return n+="]",n}var vn=class{},Vr=class{constructor(e){this.Platform=_,this.ErrorInfo=S,this.Logger=c,this.Defaults=V,this.Utils=xt,this.EventEmitter=Se,this.MessageEncoding=gs;var t,n,s,r,a,g,b,R,A,L;this._additionalHTTPRequestImplementations=(t=e.plugins)!=null?t:null,this.logger=new c,this.logger.setLog(e.logLevel,e.logHandler),c.logAction(this.logger,c.LOG_MICRO,"BaseClient()","initialized with clientOptions "+_.Config.inspect(e)),this._MsgPack=(s=(n=e.plugins)==null?void 0:n.MsgPack)!=null?s:null;const U=this.options=V.normaliseOptions(e,this._MsgPack,this.logger);if(U.key){const F=U.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!F){const P="invalid key parameter";throw c.logAction(this.logger,c.LOG_ERROR,"BaseClient()",P),new S(P,40400,404)}U.keyName=F[1],U.keySecret=F[2]}if("clientId"in U)if(typeof U.clientId=="string"||U.clientId===null){if(U.clientId==="*")throw new S('Can’t 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 S("clientId must be either a string or null",40012,400);c.logAction(this.logger,c.LOG_MINOR,"BaseClient()","started; version = "+V.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new Qe(this),this.auth=new Oe(this,U),this._rest=(r=e.plugins)!=null&&r.Rest?new e.plugins.Rest(this):null,this._Crypto=(g=(a=e.plugins)==null?void 0:a.Crypto)!=null?g:null,this.__FilteredSubscriptions=(R=(b=e.plugins)==null?void 0:b.MessageInteractions)!=null?R:null,this._Annotations=(L=(A=e.plugins)==null?void 0:A.Annotations)!=null?L:null}get rest(){return this._rest||Fe("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||Fe("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}device(){var e;return(!((e=this.options.plugins)!=null&&e.Push)||!this.push.LocalDevice)&&Fe("Push"),this._device||(this._device=this.push.LocalDevice.load(this)),this._device}baseUri(e){return V.getHttpScheme(this.options)+e+":"+V.getPort(this.options,!1)}async stats(e){return this.rest.stats(e)}async time(e){return this.rest.time(e)}async request(e,t,n,s,r,a){return this.rest.request(e,t,n,s,r,a)}batchPublish(e){return this.rest.batchPublish(e)}batchPresence(e){return this.rest.batchPresence(e)}setLog(e){this.logger.setLog(e.level,e.handler)}async getTimestamp(e){return!this.isTimeOffsetSet()&&e?this.time():this.getTimestampUsingOffset()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return this.serverTimeOffset!==null}};Vr.Platform=_;var $r=Vr,Ho=class Tn{toJSON(){var t,n,s;return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:(t=this.push)==null?void 0:t.recipient,state:(n=this.push)==null?void 0:n.state,error:(s=this.push)==null?void 0:s.error}}}toString(){var t,n,s,r;let a="[DeviceDetails";return this.id&&(a+="; id="+this.id),this.platform&&(a+="; platform="+this.platform),this.formFactor&&(a+="; formFactor="+this.formFactor),this.clientId&&(a+="; clientId="+this.clientId),this.metadata&&(a+="; metadata="+this.metadata),this.deviceIdentityToken&&(a+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),(t=this.push)!=null&&t.recipient&&(a+="; push.recipient="+JSON.stringify(this.push.recipient)),(n=this.push)!=null&&n.state&&(a+="; push.state="+this.push.state),(s=this.push)!=null&&s.error&&(a+="; push.error="+JSON.stringify(this.push.error)),(r=this.push)!=null&&r.metadata&&(a+="; push.metadata="+this.push.metadata),a+="]",a}static toRequestBody(t,n,s){return at(t,n,s)}static fromResponseBody(t,n,s){return s&&(t=Ze(t,n,s)),Array.isArray(t)?Tn.fromValuesArray(t):Tn.fromValues(t)}static fromValues(t){return t.error=t.error&&S.fromValues(t.error),Object.assign(new Tn,t)}static fromLocalDevice(t){return Object.assign(new Tn,t)}static fromValuesArray(t){const n=t.length,s=new Array(n);for(let r=0;r<n;r++)s[r]=Tn.fromValues(t[r]);return s}},kn=Ho;async function Fr(e,t,n,s){if(e.http.supportsAuthHeaders){const r=await e.auth.getAuthHeaders();return s(pe(r,t),n)}else{const r=await e.auth.getAuthParams();return s(t,pe(r,n))}}function Do(e,t,n){if(e.err&&!e.body)return{err:e.err};if(e.statusCode===re.NoContent)return fe(H({},e),{body:[],unpacked:!0});let s=e.body;if(!e.unpacked)try{s=Ze(s,t,n)}catch(b){return rn(b)?{err:b}:{err:new et(Ge(b),null)}}if(!s)return{err:new et("unenvelope(): Response body is missing",null)};const{statusCode:r,response:a,headers:g}=s;if(r===void 0)return fe(H({},e),{body:s,unpacked:!0});if(r<200||r>=300){let b=a&&a.error||e.err;return b||(b=new Error("Error in unenveloping "+s),b.statusCode=r),{err:b,body:a,headers:g,unpacked:!0,statusCode:r}}return{err:e.err,body:a,headers:g,unpacked:!0,statusCode:r}}function jo(e,t,n,s,r){e.err?c.logAction(r,c.LOG_MICRO,"Resource."+t+"()","Received Error; "+ve(n,s)+"; Error: "+Ge(e.err)):c.logAction(r,c.LOG_MICRO,"Resource."+t+"()","Received; "+ve(n,s)+"; Headers: "+Pe(e.headers)+"; StatusCode: "+e.statusCode+"; Body: "+(_.BufferUtils.isBuffer(e.body)?" (Base64): "+_.BufferUtils.base64Encode(e.body):": "+_.Config.inspect(e.body)))}var Wo=class En{static async get(t,n,s,r,a,g){return En.do(K.Get,t,n,null,s,r,a,g??!1)}static async delete(t,n,s,r,a,g){return En.do(K.Delete,t,n,null,s,r,a,g)}static async post(t,n,s,r,a,g,b){return En.do(K.Post,t,n,s,r,a,g,b)}static async patch(t,n,s,r,a,g,b){return En.do(K.Patch,t,n,s,r,a,g,b)}static async put(t,n,s,r,a,g,b){return En.do(K.Put,t,n,s,r,a,g,b)}static async do(t,n,s,r,a,g,b,R){b&&((g=g||{}).envelope=b);const A=n.logger;async function L(F,P){var ne;if(A.shouldLog(c.LOG_MICRO)){let ye=r;if(((ne=F["content-type"])==null?void 0:ne.indexOf("msgpack"))>0)try{n._MsgPack||Fe("MsgPack"),ye=n._MsgPack.decode(r)}catch(qe){c.logAction(A,c.LOG_MICRO,"Resource."+t+"()","Sending MsgPack Decoding Error: "+Ge(qe))}c.logAction(A,c.LOG_MICRO,"Resource."+t+"()","Sending; "+ve(s,P)+"; Body: "+ye)}const se=await n.http.do(t,s,F,r,P);return se.error&&Oe.isTokenErr(se.error)?(await n.auth.authorize(null,null),Fr(n,F,P,L)):{err:se.error,body:se.body,headers:se.headers,unpacked:se.unpacked,statusCode:se.statusCode}}let U=await Fr(n,a,g,L);if(b&&(U=Do(U,n._MsgPack,b)),A.shouldLog(c.LOG_MICRO)&&jo(U,t,s,g,A),R){if(U.err)throw U.err;{const F=H({},U);return delete F.err,F}}return U}},Xe=Wo;function Vo(e){const t=e.match(/^\.\/(\w+)\?(.*)$/);return t&&t[2]&&qt(t[2])}function $o(e){typeof e=="string"&&(e=e.split(","));const t={};for(let n=0;n<e.length;n++){const s=e[n].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(s){const r=Vo(s[1]);r&&(t[s[2]]=r)}}return t}function Fo(e,t,n){return!(n&&(t||typeof e.code=="number"))}var zo=class{constructor(e,t,n,s,r,a){this.client=e,this.path=t,this.headers=n,this.envelope=s??null,this.bodyHandler=r,this.useHttpPaginatedResponse=a||!1}get logger(){return this.client.logger}async get(e){const t=await Xe.get(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async delete(e){const t=await Xe.delete(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async post(e,t){const n=await Xe.post(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async put(e,t){const n=await Xe.put(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async patch(e,t){const n=await Xe.patch(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async handlePage(e){if(e.err&&Fo(e.err,e.body,this.useHttpPaginatedResponse))throw c.logAction(this.logger,c.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+Ge(e.err)),e.err;let t,n,s;try{t=e.statusCode==re.NoContent?[]:await this.bodyHandler(e.body,e.headers||{},e.unpacked)}catch(r){throw e.err||r}return e.headers&&(n=e.headers.Link||e.headers.link)&&(s=$o(n)),this.useHttpPaginatedResponse?new Jo(this,t,e.headers||{},e.statusCode,s,e.err):new zr(this,t,s)}},zr=class{constructor(e,t,n){this.resource=e,this.items=t,this._relParams=n}async first(){if(this.hasFirst())return this.get(this._relParams.first);throw new S("No link to the first page of results",40400,404)}async current(){if(this.hasCurrent())return this.get(this._relParams.current);throw new S("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(e){const t=this.resource,n=await Xe.get(t.client,t.path,t.headers,e,t.envelope,!1);return t.handlePage(n)}},Jo=class extends zr{constructor(e,t,n,s,r,a){super(e,t,r),this.statusCode=s,this.success=s<300&&s>=200,this.headers=n,this.errorCode=a&&a.code,this.errorMessage=a&&a.message,this.errorDetail=a==null?void 0:a.detail}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage,errorDetail:this.errorDetail}}},vt=zo,Jr=class ts{toJSON(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}}toString(){let t="[PushChannelSubscription";return this.channel&&(t+="; channel="+this.channel),this.deviceId&&(t+="; deviceId="+this.deviceId),this.clientId&&(t+="; clientId="+this.clientId),t+="]",t}static fromResponseBody(t,n,s){return s&&(t=Ze(t,n,s)),Array.isArray(t)?ts.fromValuesArray(t):ts.fromValues(t)}static fromValues(t){return Object.assign(new ts,t)}static fromValuesArray(t){const n=t.length,s=new Array(n);for(let r=0;r<n;r++)s[r]=ts.fromValues(t[r]);return s}};Jr.toRequestBody=at;var Ko=Jr,ys=Ko,Qo=class{constructor(e){var t;this.client=e,this.admin=new Yo(e),_.Config.push&&((t=e.options.plugins)!=null&&t.Push)&&(this.stateMachine=new e.options.plugins.Push.ActivationStateMachine(e),this.LocalDevice=e.options.plugins.Push.localDeviceFactory(kn))}async activate(e,t){await new Promise((n,s)=>{var r;if(!((r=this.client.options.plugins)!=null&&r.Push)){s(bn("Push"));return}if(!this.stateMachine){s(new S("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.activatedCallback){s(new S("Activation already in progress",4e4,400));return}this.stateMachine.activatedCallback=a=>{if(a){s(a);return}n()},this.stateMachine.updateFailedCallback=t,this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledActivate(this.stateMachine,e))})}async deactivate(e){await new Promise((t,n)=>{var s;if(!((s=this.client.options.plugins)!=null&&s.Push)){n(bn("Push"));return}if(!this.stateMachine){n(new S("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.deactivatedCallback){n(new S("Deactivation already in progress",4e4,400));return}this.stateMachine.deactivatedCallback=r=>{if(r){n(r);return}t()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,e))})}},Yo=class{constructor(e){this.client=e,this.deviceRegistrations=new Zo(e),this.channelSubscriptions=new Xo(e)}async publish(e,t){const n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",r=V.defaultPostHeaders(n.options),a={},g=pe({recipient:e},t);pe(r,n.options.headers),n.options.pushFullWait&&pe(a,{fullWait:"true"});const b=at(g,n._MsgPack,s);await Xe.post(n,"/push/publish",b,r,a,null,!0)}},Zo=class{constructor(e){this.client=e}async save(e){const t=this.client,n=kn.fromValues(e),s=t.options.useBinaryProtocol?"msgpack":"json",r=V.defaultPostHeaders(t.options),a={};pe(r,t.options.headers),t.options.pushFullWait&&pe(a,{fullWait:"true"});const g=at(n,t._MsgPack,s),b=await Xe.put(t,"/push/deviceRegistrations/"+encodeURIComponent(e.id),g,r,a,null,!0);return kn.fromResponseBody(b.body,t._MsgPack,b.unpacked?void 0:s)}async get(e){const t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=V.defaultGetHeaders(t.options),r=e.id||e;if(typeof r!="string"||!r.length)throw new S("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);pe(s,t.options.headers);const a=await Xe.get(t,"/push/deviceRegistrations/"+encodeURIComponent(r),s,{},null,!0);return kn.fromResponseBody(a.body,t._MsgPack,a.unpacked?void 0:n)}async list(e){const t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n,r=V.defaultGetHeaders(t.options);return pe(r,t.options.headers),new vt(t,"/push/deviceRegistrations",r,s,async function(a,g,b){return kn.fromResponseBody(a,t._MsgPack,b?void 0:n)}).get(e)}async remove(e){const t=this.client,n=V.defaultGetHeaders(t.options),s={},r=e.id||e;if(typeof r!="string"||!r.length)throw new S("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);pe(n,t.options.headers),t.options.pushFullWait&&pe(s,{fullWait:"true"}),await Xe.delete(t,"/push/deviceRegistrations/"+encodeURIComponent(r),n,s,null,!0)}async removeWhere(e){const t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=V.defaultGetHeaders(t.options,{format:n});pe(s,t.options.headers),t.options.pushFullWait&&pe(e,{fullWait:"true"}),await Xe.delete(t,"/push/deviceRegistrations",s,e,null,!0)}},Xo=class ho{constructor(t){this.remove=ho.prototype.removeWhere,this.client=t}async save(t){const n=this.client,s=ys.fromValues(t),r=n.options.useBinaryProtocol?"msgpack":"json",a=V.defaultPostHeaders(n.options),g={};pe(a,n.options.headers),n.options.pushFullWait&&pe(g,{fullWait:"true"});const b=at(s,n._MsgPack,r),R=await Xe.post(n,"/push/channelSubscriptions",b,a,g,null,!0);return ys.fromResponseBody(R.body,n._MsgPack,R.unpacked?void 0:r)}async list(t){const n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",r=this.client.http.supportsLinkHeaders?void 0:s,a=V.defaultGetHeaders(n.options);return pe(a,n.options.headers),new vt(n,"/push/channelSubscriptions",a,r,async function(g,b,R){return ys.fromResponseBody(g,n._MsgPack,R?void 0:s)}).get(t)}async removeWhere(t){const n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",r=V.defaultGetHeaders(n.options,{format:s});pe(r,n.options.headers),n.options.pushFullWait&&pe(t,{fullWait:"true"}),await Xe.delete(n,"/push/channelSubscriptions",r,t,null,!0)}async listChannels(t){const n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",r=this.client.http.supportsLinkHeaders?void 0:s,a=V.defaultGetHeaders(n.options);return pe(a,n.options.headers),n.options.pushFullWait&&pe(t,{fullWait:"true"}),new vt(n,"/push/channels",a,r,async function(g,b,R){const A=!R&&s?Ze(g,n._MsgPack,s):g;for(let L=0;L<A.length;L++)A[L]=String(A[L]);return A}).get(t)}},ea=Qo,Kr=["absent","present","enter","leave","update"];async function Qr(e,t,n,s){const r=qr(t,e,s??null);return Gn.fromValues(n).decode(r,e)}async function ta(e,t,n,s){return Promise.all(n.map(function(r){return Qr(e,t,r,s)}))}async function na(e,t){return Gn.fromValues(e).decode(t.channelOptions,t.logger)}async function Yr(e,t){return Promise.all(e.map(function(n){return na(n,t)}))}var Zr=class ns extends vn{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");const t=this.id.split(":");return{connectionId:t[0],msgSerial:parseInt(t[1],10),index:parseInt(t[2],10)}}async encode(t){const n=Object.assign(new Gn,this,{action:Kr.indexOf(this.action||"present")});return Gs(n,t)}static fromValues(t){return Object.assign(new ns,t)}static fromValuesArray(t){return t.map(n=>ns.fromValues(n))}static fromData(t){return t instanceof ns?t:ns.fromValues({data:t})}toString(){return wn(this,"PresenceMessage")}},Gn=class gr extends vn{toJSON(...t){return Hs.call(this,...t)}static fromValues(t){return Object.assign(new gr,t)}static fromValuesArray(t){return t.map(n=>gr.fromValues(n))}async decode(t,n){const s=Object.assign(new Zr,fe(H({},this),{action:Kr[this.action]}));try{await qs(s,t)}catch(r){c.logAction(n,c.LOG_ERROR,"WirePresenceMessage.decode()",Ge(r))}return s}toString(){return wn(this,"WirePresenceMessage")}},zt=Zr,sa=class{constructor(e){this.channel=e}get logger(){return this.channel.logger}async get(e){c.logAction(this.logger,c.LOG_MICRO,"RestPresence.get()","channel = "+this.channel.name);const t=this.channel.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.channel.client.http.supportsLinkHeaders?void 0:n,r=V.defaultGetHeaders(t.options);return pe(r,t.options.headers),new vt(t,this.channel.client.rest.presenceMixin.basePath(this),r,s,async(a,g,b)=>{const R=b?a:Ze(a,t._MsgPack,n);return Yr(R,this.channel)}).get(e)}async history(e){return c.logAction(this.logger,c.LOG_MICRO,"RestPresence.history()","channel = "+this.channel.name),this.channel.client.rest.presenceMixin.history(this,e)}},ra=sa,Xr=["message.create","message.update","message.delete","meta","message.summary","message.append"];function ia(e){return Xr[e||0]||"unknown"}function oa(e){let t=0;return e.name&&(t+=e.name.length),e.clientId&&(t+=e.clientId.length),e.extras&&(t+=JSON.stringify(e.extras).length),e.data&&(t+=on(e.data)),t}async function ei(e,t,n,s){const r=qr(t,e,s??null);return qn.fromValues(n).decode(r,e)}async function aa(e,t,n,s){return Promise.all(n.map(function(r){return ei(e,t,r,s)}))}async function ti(e,t){return qn.fromValues(e).decode(t.channelOptions,t.logger)}async function ni(e,t){return Promise.all(e.map(function(n){return ti(n,t)}))}async function si(e,t){return Promise.all(e.map(n=>n.encode(t)))}var ri=at;function ii(e){let t,n=0;for(let s=0;s<e.length;s++)t=e[s],n+=t.size||(t.size=oa(t));return n}var oi=class mr extends vn{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(const[t,n]of Object.entries(this.annotations.summary))if(t.endsWith(":distinct.v1")||t.endsWith(":unique.v1")||t.endsWith(":multiple.v1"))for(const[,s]of Object.entries(n))s.clipped||(s.clipped=!1);else t.endsWith(":flag.v1")&&(n.clipped||(n.clipped=!1))}async encode(t){const n=Object.assign(new qn,this,{action:Xr.indexOf(this.action||"message.create")});return Gs(n,t)}static fromValues(t){return Object.assign(new mr,t)}static fromValuesArray(t){return t.map(n=>mr.fromValues(n))}toString(){return wn(this,"Message")}},qn=class yr extends vn{toJSON(...t){return Hs.call(this,...t)}static fromValues(t){return Object.assign(new yr,t)}static fromValuesArray(t){return t.map(n=>yr.fromValues(n))}async decodeWithErr(t,n){const s=Object.assign(new oi,fe(H({},this),{action:ia(this.action)}));let r;try{await qs(s,t)}catch(a){c.logAction(n,c.LOG_ERROR,"WireMessage.decode()",Ge(a)),r=a}return s.expandFields(),{decoded:s,err:r}}async decode(t,n){const{decoded:s}=await this.decodeWithErr(t,n);return s}toString(){return wn(this,"WireMessage")}},Tt=oi,ca=9;function la(e){return e.every(function(t){return!t.id})}var ha=class{constructor(e,t,n){this._annotations=null;var s,r;c.logAction(e.logger,c.LOG_MINOR,"RestChannel()","started; name = "+t),this.name=t,this.client=e,this.presence=new ra(this),this.channelOptions=Me((s=e._Crypto)!=null?s:null,this.logger,n),(r=e.options.plugins)!=null&&r.Push&&(this._push=new e.options.plugins.Push.PushChannel(this)),e._Annotations&&(this._annotations=new e._Annotations.RestAnnotations(this))}get annotations(){return this._annotations||Fe("Annotations"),this._annotations}get push(){return this._push||Fe("Push"),this._push}get logger(){return this.client.logger}setOptions(e){var t;this.channelOptions=Me((t=this.client._Crypto)!=null?t:null,this.logger,e)}async history(e){return c.logAction(this.logger,c.LOG_MICRO,"RestChannel.history()","channel = "+this.name),this.client.rest.channelMixin.history(this,e)}async publish(...e){const t=e[0],n=e[1];let s,r;if(typeof t=="string"||t===null)s=[Tt.fromValues({name:t,data:n})],r=e[2];else if(Ct(t))s=[Tt.fromValues(t)],r=e[1];else if(Array.isArray(t))s=Tt.fromValuesArray(t),r=e[1];else throw new S("The single-argument form of publish() expects a message object or an array of message objects",40013,400);r||(r={});const a=this.client,g=a.options,b=g.useBinaryProtocol?"msgpack":"json",R=a.options.idempotentRestPublishing,A=V.defaultPostHeaders(a.options);if(pe(A,g.headers),R&&la(s)){const P=await mn(ca);s.forEach(function(ne,se){ne.id=P+":"+se.toString()})}const L=await si(s,this.channelOptions),U=ii(L),F=g.maxMessageSize;if(U>F)throw new S(`Maximum size of messages that can be published at once exceeded (was ${U} bytes; limit is ${F} bytes)`,40009,400);return this._publish(ri(L,a._MsgPack,b),A,r)}async _publish(e,t,n){const s=this.client,r=s.options.useBinaryProtocol?"msgpack":"json",{body:a,unpacked:g}=await Xe.post(s,s.rest.channelMixin.basePath(this)+"/messages",e,t,n,null,!0),b=(g?a:Ze(a,s._MsgPack,r))||{};return delete b.channel,delete b.messageId,b}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(e){return c.logAction(this.logger,c.LOG_MICRO,"RestChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,e)}async updateMessage(e,t,n){return c.logAction(this.logger,c.LOG_MICRO,"RestChannel.updateMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.update",e,t,n)}async deleteMessage(e,t,n){return c.logAction(this.logger,c.LOG_MICRO,"RestChannel.deleteMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.delete",e,t,n)}async appendMessage(e,t,n){return c.logAction(this.logger,c.LOG_MICRO,"RestChannel.appendMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.append",e,t,n)}async getMessageVersions(e,t){return c.logAction(this.logger,c.LOG_MICRO,"RestChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,e,t)}},fa=ha,ua=class fo{constructor(t){this.entries=t&&t.entries||void 0,this.schema=t&&t.schema||void 0,this.appId=t&&t.appId||void 0,this.inProgress=t&&t.inProgress||void 0,this.unit=t&&t.unit||void 0,this.intervalId=t&&t.intervalId||void 0}static fromValues(t){return new fo(t)}},da=ua,ai=class{static basePath(e){return"/channels/"+encodeURIComponent(e.name)}static history(e,t){const n=e.client,s=n.options.useBinaryProtocol?"msgpack":"json",r=e.client.http.supportsLinkHeaders?void 0:s,a=V.defaultGetHeaders(n.options);return pe(a,n.options.headers),new vt(n,this.basePath(e)+"/messages",a,r,async function(g,b,R){const A=R?g:Ze(g,n._MsgPack,s);return ni(A,e)}).get(t)}static async status(e){const t=e.client.options.useBinaryProtocol?"msgpack":"json",n=V.defaultPostHeaders(e.client.options);return(await Xe.get(e.client,this.basePath(e),n,{},t,!0)).body}static async getMessage(e,t){const n=typeof t=="string"?t:t.serial;if(!n)throw new S('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);const s=e.client,r=s.options.useBinaryProtocol?"msgpack":"json",a=V.defaultGetHeaders(s.options);pe(a,s.options.headers);const{body:g,unpacked:b}=await Xe.get(s,this.basePath(e)+"/messages/"+encodeURIComponent(n),a,{},null,!0),R=b?g:Ze(g,s._MsgPack,r);return ti(R,e)}static async updateDeleteMessage(e,t,n,s,r){if(!n.serial)throw new S('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);const a=e.client,g=a.options.useBinaryProtocol?"msgpack":"json",b=V.defaultPostHeaders(a.options);pe(b,a.options.headers);const R=Tt.fromValues(n);R.action=t,R.version=s;const A=await R.encode(e.channelOptions),L=ri(A,a._MsgPack,g);let U=Xe.patch;const{body:F,unpacked:P}=await U(a,this.basePath(e)+"/messages/"+encodeURIComponent(n.serial),L,b,r||{},null,!0);return(P?F:Ze(F,a._MsgPack,g))||{versionSerial:null}}static getMessageVersions(e,t,n){const s=typeof t=="string"?t:t.serial;if(!s)throw new S('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);const r=e.client,a=r.options.useBinaryProtocol?"msgpack":"json",g=e.client.http.supportsLinkHeaders?void 0:a,b=V.defaultGetHeaders(r.options);return pe(b,r.options.headers),new vt(r,this.basePath(e)+"/messages/"+encodeURIComponent(s)+"/versions",b,g,async(R,A,L)=>{const U=L?R:Ze(R,r._MsgPack,a);return ni(U,e)}).get(n||{})}},pa=class{static basePath(e){return ai.basePath(e.channel)+"/presence"}static async history(e,t){const n=e.channel.client,s=n.options.useBinaryProtocol?"msgpack":"json",r=e.channel.client.http.supportsLinkHeaders?void 0:s,a=V.defaultGetHeaders(n.options);return pe(a,n.options.headers),new vt(n,this.basePath(e)+"/history",a,r,async(g,b,R)=>{const A=R?g:Ze(g,n._MsgPack,s);return Yr(A,e.channel)}).get(t)}},ci=class{constructor(e){this.channelMixin=ai,this.presenceMixin=pa,this.Resource=Xe,this.PaginatedResource=vt,this.DeviceDetails=kn,this.PushChannelSubscription=ys,this.client=e,this.channels=new ga(this.client),this.push=new ea(this.client)}async stats(e){const t=V.defaultGetHeaders(this.client.options),n=this.client.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n;return pe(t,this.client.options.headers),new vt(this.client,"/stats",t,s,async(r,a,g)=>{const b=g?r:Ze(r,this.client._MsgPack,n);for(let R=0;R<b.length;R++)b[R]=da.fromValues(b[R]);return b}).get(e)}async time(e){const t=V.defaultGetHeaders(this.client.options,{format:"json"});this.client.options.headers&&pe(t,this.client.options.headers);const n=b=>this.client.baseUri(b)+"/time";let{error:s,body:r,unpacked:a}=await this.client.http.do(K.Get,n,t,null,e);if(s)throw s;a||(r=JSON.parse(r));const g=r[0];if(!g)throw new S("Internal error (unexpected result type from GET /time)",5e4,500);return this.client.serverTimeOffset=g-Date.now(),g}async request(e,t,n,s,r,a){var g;const[b,R,A]=this.client.options.useBinaryProtocol?(this.client._MsgPack||Fe("MsgPack"),[this.client._MsgPack.encode,this.client._MsgPack.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],L=this.client.http.supportsLinkHeaders?void 0:A;s=s||{};const U=e.toLowerCase(),F=U=="get"?V.defaultGetHeaders(this.client.options,{format:A,protocolVersion:n}):V.defaultPostHeaders(this.client.options,{format:A,protocolVersion:n});typeof r!="string"&&(r=(g=b(r))!=null?g:null),pe(F,this.client.options.headers),a&&pe(F,a);const P=new vt(this.client,t,F,L,async function(ne,se,ye){return In(ye?ne:R(ne))},!0);if(!_.Http.methods.includes(U))throw new S("Unsupported method "+U,40500,405);return _.Http.methodsWithBody.includes(U)?P[U](s,r):P[U](s)}async batchPublish(e){let t,n;Array.isArray(e)?(t=e,n=!1):(t=[e],n=!0);const s=this.client.options.useBinaryProtocol?"msgpack":"json",r=V.defaultPostHeaders(this.client.options);this.client.options.headers&&pe(r,this.client.options.headers);const a=at(t,this.client._MsgPack,s),g=await Xe.post(this.client,"/messages",a,r,{},null,!0),b=g.unpacked?g.body:Ze(g.body,this.client._MsgPack,s);return n?b[0]:b}async batchPresence(e){const t=this.client.options.useBinaryProtocol?"msgpack":"json",n=V.defaultGetHeaders(this.client.options);this.client.options.headers&&pe(n,this.client.options.headers);const s=e.join(","),r=await Xe.get(this.client,"/presence",n,{channels:s},null,!0);return r.unpacked?r.body:Ze(r.body,this.client._MsgPack,t)}async revokeTokens(e,t){if(ke(this.client.options))throw new S("Cannot revoke tokens when using token auth",40162,401);const n=this.client.options.keyName;let s=t??{};const r=H({targets:e.map(A=>`${A.type}:${A.value}`)},s),a=this.client.options.useBinaryProtocol?"msgpack":"json",g=V.defaultPostHeaders(this.client.options);this.client.options.headers&&pe(g,this.client.options.headers);const b=at(r,this.client._MsgPack,a),R=await Xe.post(this.client,`/keys/${n}/revokeTokens`,b,g,{},null,!0);return R.unpacked?R.body:Ze(R.body,this.client._MsgPack,a)}},ga=class{constructor(e){this.client=e,this.all=Object.create(null)}get(e,t){e=String(e);let n=this.all[e];return n?t&&n.setOptions(t):this.all[e]=n=new fa(this.client,e,t),n}release(e){delete this.all[String(e)]}},ma=class extends $r{constructor(e){super(V.objectifyOptions(e,!1,"BaseRest",c.defaultLogger,{Rest:ci}))}},li={Rest:ci},hi=class extends Tt{static async fromEncoded(e,t){return ei(c.defaultLogger,_.Crypto,e,t)}static async fromEncodedArray(e,t){return aa(c.defaultLogger,_.Crypto,e,t)}static fromValues(e){return Tt.fromValues(e)}},fi=class extends zt{static async fromEncoded(e,t){return Qr(c.defaultLogger,_.Crypto,e,t)}static async fromEncodedArray(e,t){return ta(c.defaultLogger,_.Crypto,e,t)}static fromValues(e){return zt.fromValues(e)}},ui=["annotation.create","annotation.delete"];async function di(e,t,n){return _n.fromValues(t).decode(n||{},e)}async function ya(e,t,n){return Promise.all(t.map(function(s){return di(e,s,n)}))}async function ba(e,t){return _n.fromValues(e).decode(t.channelOptions,t.logger)}async function xa(e,t){return Promise.all(e.map(function(n){return ba(n,t)}))}var pi=class br extends vn{async encode(){const t=Object.assign(new _n,this,{action:ui.indexOf(this.action||"annotation.create")});return Gs(t,{})}static fromValues(t){return Object.assign(new br,t)}static fromValuesArray(t){return t.map(n=>br.fromValues(n))}toString(){return wn(this,"Annotation")}},_n=class xr extends vn{toJSON(...t){return Hs.call(this,...t)}static fromValues(t){return Object.assign(new xr,t)}static fromValuesArray(t){return t.map(n=>xr.fromValues(n))}async decode(t,n){const s=Object.assign(new pi,fe(H({},this),{action:ui[this.action]}));try{await qs(s,t)}catch(r){c.logAction(n,c.LOG_ERROR,"WireAnnotation.decode()",Ge(r))}return s}toString(){return wn(this,"WireAnnotation")}},Hn=pi,gi=class extends Hn{static async fromEncoded(e,t){return di(c.defaultLogger,e,t)}static async fromEncodedArray(e,t){return ya(c.defaultLogger,e,t)}static fromValues(e){return Hn.fromValues(e)}};function mi(e){let t;switch(typeof e){case"string":t=e;break;case"object":t=e.serial;break}if(!t||typeof t!="string")throw new S("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 t}function yi(e,t){const n=mi(e);if(!t||typeof t!="object")throw new S("Second argument of annotations.publish() must be an object (the intended annotation to publish)",40003,400);const s=Hn.fromValues(t);return s.messageSerial=n,s.action||(s.action="annotation.create"),s}function bi(e,t){return e.client.rest.channelMixin.basePath(e)+"/messages/"+encodeURIComponent(t)+"/annotations"}var wa=class{constructor(e){this.channel=e}async publish(e,t){const n=yi(e,t),s=await n.encode(),r=this.channel.client,a=r.options,g=a.useBinaryProtocol?"msgpack":"json",b=V.defaultPostHeaders(r.options),R={};pe(b,r.options.headers);const A=at([s],r._MsgPack,g);await Xe.post(r,bi(this.channel,n.messageSerial),A,b,R,null,!0)}async delete(e,t){return t.action="annotation.delete",this.publish(e,t)}async get(e,t){const n=this.channel.client,s=mi(e),r=n.options.useBinaryProtocol?"msgpack":"json",a=n.http.supportsLinkHeaders?void 0:r,g=V.defaultGetHeaders(n.options);return pe(g,n.options.headers),new vt(n,bi(this.channel,s),g,a,async(b,R,A)=>{const L=A?b:Ze(b,n._MsgPack,r);return xa(L,this.channel)}).get(t)}},Ds=wa,va=at;function bs(e){const t=[];if(e)for(let n=0;n<e.length;n++)t.push(e[n].toString());return"[ "+t.join(", ")+" ]"}function ka(e,t,n,s,r,a){const g=Ze(e,t,a);return js(g,n,s,r)}function js(e,t,n,s){let r;e.error&&(r=S.fromValues(e.error));let a;e.messages&&(a=qn.fromValuesArray(e.messages));let g;t&&e.presence&&(g=t.WirePresenceMessage.fromValuesArray(e.presence));let b;n&&e.annotations&&(b=n.WireAnnotation.fromValuesArray(e.annotations));let R;return s&&e.state&&(R=s.WireObjectMessage.fromValuesArray(e.state,xt,gs)),Object.assign(new Vs,fe(H({},e),{presence:g,messages:a,annotations:b,state:R,error:r}))}function xi(e){return t=>{var n;return js(t,{WirePresenceMessage:Gn},{WireAnnotation:_n},(n=e==null?void 0:e.LiveObjectsPlugin)!=null?n:null)}}function ut(e){return Object.assign(new Vs,e)}function Ws(e,t,n,s){let r="[ProtocolMessage";e.action!==void 0&&(r+="; action="+nt[e.action]||e.action);const a=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"];let g;for(let b=0;b<a.length;b++)g=a[b],e[g]!==void 0&&(r+="; "+g+"="+e[g]);if(e.messages&&(r+="; messages="+bs(qn.fromValuesArray(e.messages))),e.presence&&t&&(r+="; presence="+bs(t.WirePresenceMessage.fromValuesArray(e.presence))),e.annotations&&n&&(r+="; annotations="+bs(n.WireAnnotation.fromValuesArray(e.annotations))),e.state&&s&&(r+="; state="+bs(s.WireObjectMessage.fromValuesArray(e.state,xt,gs))),e.error&&(r+="; error="+S.fromValues(e.error).toString()),e.auth&&e.auth.accessToken&&(r+="; token="+e.auth.accessToken),e.flags&&(r+="; flags="+st.filter(e.hasFlag).join(",")),e.params){let b="";us(e.params,function(R){b.length>0&&(b+="; "),b+=R+"="+e.params[R]}),b.length>0&&(r+="; params=["+b+"]")}return r+="]",r}var Vs=class{constructor(){this.hasFlag=e=>(this.flags&je[e])>0}setFlag(e){return this.flags=this.flags|je[e]}getMode(){return(this.flags||0)&je.MODE_ALL}encodeModesToFlags(e){e.forEach(t=>this.setFlag(t))}decodeModesFromFlags(){const e=[];return Gr.forEach(t=>{this.hasFlag(t)&&e.push(t)}),e.length>0?e:void 0}},_a=Vs,Aa=class{constructor(e,t,n,s,r){this.previous=e,this.current=t,t==="attached"&&(this.resumed=n,this.hasBacklog=s),r&&(this.reason=r)}},$s=Aa;function Ra(e){if(e&&"params"in e&&!Ct(e.params))return new S("options.params must be an object",4e4,400);if(e&&"modes"in e){if(!Array.isArray(e.modes))return new S("options.modes must be an array",4e4,400);for(let t=0;t<e.modes.length;t++){const n=e.modes[t];if(!n||typeof n!="string"||!Gr.includes(String.prototype.toUpperCase.call(n)))return new S("Invalid channel mode: "+n,4e4,400)}}}var Ca=class wr extends Se{constructor(t,n,s){var r,a,g;super(t.logger),this._annotations=null,this._mode=0,this.retryCount=0,this.history=async function(b){c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);const R=this.client.rest.channelMixin;if(b&&b.untilAttach){if(this.state!=="attached")throw new S("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new S("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400);delete b.untilAttach,b.from_serial=this.properties.attachSerial}return R.history(this,b)},this.whenState=b=>Se.prototype.whenState.call(this,b,this.state),c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel()","started; name = "+n),this.name=n,this.channelOptions=Me((r=t._Crypto)!=null?r:null,this.logger,s),this.client=t,this._presence=t._RealtimePresence?new t._RealtimePresence.RealtimePresence(this):null,t._Annotations&&(this._annotations=new t._Annotations.RealtimeAnnotations(this)),this.connectionManager=t.connection.connectionManager,this.state="initialized",this.subscriptions=new Se(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(s),this.errorReason=null,this._attachResume=!1,this._decodingContext={channelOptions:this.channelOptions,plugins:t.options.plugins||{},baseEncodedPreviousPayload:void 0},this._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this._attachedReceived=new Se(this.logger),this.internalStateChanges=new Se(this.logger),(a=t.options.plugins)!=null&&a.Push&&(this._push=new t.options.plugins.Push.PushChannel(this)),(g=t.options.plugins)!=null&&g.LiveObjects&&(this._object=new t.options.plugins.LiveObjects.RealtimeObject(this))}get presence(){return this._presence||Fe("RealtimePresence"),this._presence}get annotations(){return this._annotations||Fe("Annotations"),this._annotations}get push(){return this._push||Fe("Push"),this._push}get object(){return this._object||Fe("LiveObjects"),this._object}emit(t,...n){super.emit(t,...n),this.internalStateChanges.emit(t,...n)}invalidStateError(){return new S("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(t){return t=Array.prototype.slice.call(t),typeof t[0]=="function"&&t.unshift(null),t}async setOptions(t){var n;const s=this.channelOptions,r=Ra(t);if(r)throw r;if(this.channelOptions=Me((n=this.client._Crypto)!=null?n:null,this.logger,t),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(t,s))return this.attachImpl(),new Promise((a,g)=>{const b=()=>{this._attachedReceived.off(R),this.internalStateChanges.off(A)},R=()=>{b(),a()},A=L=>{b(),g(L.reason)};this._attachedReceived.once("attached",R),this.internalStateChanges.once(["detached","failed"],A)})}_shouldReattachToSetOptions(t,n){if(!(this.state==="attached"||this.state==="attaching"))return!1;if(t!=null&&t.params){const s=wi(t.params),r=wi(n.params);if(Object.keys(s).length!==Object.keys(r).length||!$t(r,s))return!0}return!!(t!=null&&t.modes&&(!n.modes||!ps(t.modes,n.modes)))}async publish(...t){const n=t[0],s=t[1];let r,a;if(typeof n=="string"||n===null||n===void 0)r=[Tt.fromValues({name:n,data:s})],a=t[2];else if(Ct(n))r=[Tt.fromValues(n)],a=t[1];else if(Array.isArray(n))r=Tt.fromValuesArray(n),a=t[1];else throw new S("The single-argument form of publish() expects a message object or an array of message objects",40013,400);const g=this.client.options.maxMessageSize,b=await si(r,this.channelOptions),R=ii(b);if(R>g)throw new S(`Maximum size of messages that can be published at once exceeded (was ${R} bytes; limit is ${g} bytes)`,40009,400);this.throwIfUnpublishableState(),c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+this.state+", message count = "+b.length);const A=ut({action:X.MESSAGE,channel:this.name,messages:b,params:a?pn(a):void 0});return this.sendAndAwaitAck(A)}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if(this.state==="failed"||this.state==="suspended")throw this.invalidStateError()}onEvent(t){c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.onEvent()","received message");const n=this.subscriptions;for(let s=0;s<t.length;s++){const r=t[s];n.emit(r.name,r)}}async attach(){return this.state==="attached"?null:new Promise((t,n)=>{this._attach(!1,null,(s,r)=>s?n(s):t(r))})}_attach(t,n,s){s||(s=a=>{a&&c.logAction(this.logger,c.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+a.toString())});const r=this.connectionManager;if(!r.activeState()){s(r.getError());return}(this.state!=="attaching"||t)&&this.requestState("attaching",n),this.internalStateChanges.once(function(a){switch(this.event){case"attached":s==null||s(null,a);break;case"detached":case"suspended":case"failed":s==null||s(a.reason||r.getError()||new S("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":s==null||s(new S("Attach request superseded by a subsequent detach request",9e4,409));break}})}attachImpl(){c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");const t=ut({action:X.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&t.encodeModesToFlags(jt(this.channelOptions.modes)),this._attachResume&&t.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(t.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.send(t)}async detach(){const t=this.connectionManager;switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new S("Unable to detach; channel state = failed",90001,400);default:if(t.state.state!=="connected"){this.notifyState("detached");return}this.requestState("detaching");case"detaching":return new Promise((n,s)=>{this.internalStateChanges.once(function(r){switch(this.event){case"detached":n();break;case"attached":case"suspended":case"failed":s(r.reason||t.getError()||new S("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":s(new S("Detach request superseded by a subsequent attach request",9e4,409));break}})})}}detachImpl(){c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");const t=ut({action:X.DETACH,channel:this.name});this.send(t)}async subscribe(...t){const[n,s]=wr.processListenerArgs(t);if(this.state==="failed")throw S.fromValues(this.invalidStateError());return n&&typeof n=="object"&&!Array.isArray(n)?this.client._FilteredSubscriptions.subscribeFilter(this,n,s):this.subscriptions.on(n,s),this.channelOptions.attachOnSubscribe!==!1?this.attach():null}unsubscribe(...t){var n;const[s,r]=wr.processListenerArgs(t);if(typeof s=="object"&&!r||(n=this.filteredSubscriptions)!=null&&n.has(r)){this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,s,r).forEach(a=>this.subscriptions.off(a));return}this.subscriptions.off(s,r)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new et("Unable to sync to channel; not attached",4e4)}const t=this.connectionManager;if(!t.activeState())throw t.getError();const n=ut({action:X.SYNC,channel:this.name});this.syncChannelSerial&&(n.channelSerial=this.syncChannelSerial),t.send(n)}send(t){this.connectionManager.send(t)}async sendAndAwaitAck(t){return new Promise((n,s)=>{this.connectionManager.send(t,this.client.options.queueMessages,(r,a)=>{r?s(r):n(a)})})}async sendPresence(t){const n=ut({action:X.PRESENCE,channel:this.name,presence:t});await this.sendAndAwaitAck(n)}async sendState(t){const n=ut({action:X.OBJECT,channel:this.name,state:t});return this.sendAndAwaitAck(n)}async processMessage(t){(t.action===X.ATTACHED||t.action===X.MESSAGE||t.action===X.PRESENCE||t.action===X.OBJECT||t.action===X.ANNOTATION)&&this.setChannelSerial(t.channelSerial);let n,s=!1;switch(t.action){case X.ATTACHED:{this.properties.attachSerial=t.channelSerial,this._mode=t.getMode(),this.params=t.params||{};const r=t.decodeModesFromFlags();this.modes=r&&Dt(r)||void 0;const a=t.hasFlag("RESUMED"),g=t.hasFlag("HAS_PRESENCE"),b=t.hasFlag("HAS_BACKLOG"),R=t.hasFlag("HAS_OBJECTS");if(this._attachedReceived.emit("attached"),this.state==="attached"){a||this._presence&&this._presence.onAttached(g),this._object&&this._object.onAttached(R);const A=new $s(this.state,this.state,a,b,t.error);(!a||this.channelOptions.updateOnAttached)&&this.emit("update",A)}else this.state==="detaching"?this.checkPendingState():this.notifyState("attached",t.error,a,g,b,R);break}case X.DETACHED:{const r=t.error?S.fromValues(t.error):new S("Channel detached",90001,404);this.state==="detaching"?this.notifyState("detached",r):this.state==="attaching"?this.notifyState("suspended",r):(this.state==="attached"||this.state==="suspended")&&this.requestState("attaching",r);break}case X.SYNC:if(s=!0,n=this.syncChannelSerial=t.channelSerial,!t.presence)break;case X.PRESENCE:{if(!t.presence)break;ms(t);const r=this.channelOptions;if(this._presence){const a=await Promise.all(t.presence.map(g=>g.decode(r,this.logger)));this._presence.setPresence(a,s,n)}break}case X.OBJECT:case X.OBJECT_SYNC:{if(!this._object||!t.state)return;ms(t);const r=this.client.connection.connectionManager.getActiveTransportFormat(),a=t.state.map(g=>g.decode(this.client,r));t.action===X.OBJECT?this._object.handleObjectMessages(a):this._object.handleObjectSyncMessages(a,t.channelSerial);break}case X.MESSAGE:{if(this.state!=="attached"){c.logAction(this.logger,c.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+t.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');return}ms(t);const r=t.messages,a=r[0],g=r[r.length-1];if(a.extras&&a.extras.delta&&a.extras.delta.from!==this._lastPayload.messageId){const R='Delta message decode failure - previous message not available for message "'+t.id+'" on this channel "'+this.name+'".';c.logAction(this.logger,c.LOG_ERROR,"RealtimeChannel.processMessage()",R),this._startDecodeFailureRecovery(new S(R,40018,400));break}let b=[];for(let R=0;R<r.length;R++){const{decoded:A,err:L}=await r[R].decodeWithErr(this._decodingContext,this.logger);if(b[R]=A,L)switch(L.code){case 40018:this._startDecodeFailureRecovery(L);return;case 40019:case 40021:this.notifyState("failed",L);return}}this._lastPayload.messageId=g.id,this._lastPayload.protocolMessageChannelSerial=t.channelSerial,this.onEvent(b);break}case X.ANNOTATION:{ms(t);const r=this.channelOptions;if(this._annotations){const a=await Promise.all((t.annotations||[]).map(g=>g.decode(r,this.logger)));this._annotations._processIncoming(a)}break}case X.ERROR:{const r=t.error;r&&r.code==80016?this.checkPendingState():this.notifyState("failed",S.fromValues(r));break}default:c.logAction(this.logger,c.LOG_MAJOR,"RealtimeChannel.processMessage()","Protocol error: unrecognised message action ("+t.action+")")}}_startDecodeFailureRecovery(t){this._lastPayload.decodeFailureRecoveryInProgress||(c.logAction(this.logger,c.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,t,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(t,n,s,r,a,g){if(c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+t),this.clearStateTimer(),["detached","suspended","failed"].includes(t)&&(this.properties.channelSerial=null),t===this.state)return;this._presence&&this._presence.actOnChannelState(t,r,n),this._object&&this._object.actOnChannelState(t,g),t==="suspended"&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),n&&(this.errorReason=n);const b=new $s(this.state,t,s,a,n),R='Channel state for channel "'+this.name+'"',A=t+(n?"; reason: "+n:"");t==="failed"?c.logAction(this.logger,c.LOG_ERROR,R,A):c.logAction(this.logger,c.LOG_MAJOR,R,A),t!=="attaching"&&t!=="suspended"&&(this.retryCount=0),t==="attached"&&this.onAttached(),t==="attached"?this._attachResume=!0:(t==="detaching"||t==="failed")&&(this._attachResume=!1),this.state=t,this.emit(t,b)}requestState(t,n){c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+t),this.notifyState(t,n),this.checkPendingState()}checkPendingState(){if(!this.connectionManager.state.sendEvents){c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);return}switch(c.logAction(this.logger,c.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}}timeoutPendingState(){switch(this.state){case"attaching":{const t=new S("Channel attach timed out",90007,408);this.notifyState("suspended",t);break}case"detaching":{const t=new S("Channel detach timed out",90007,408);this.notifyState("attached",t);break}default:this.checkPendingState();break}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired"),this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){const t=this.stateTimer;t&&(clearTimeout(t),this.stateTimer=null)}startRetryTimer(){if(this.retryTimer)return;this.retryCount++;const t=Vt(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{this.state==="suspended"&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),this.requestState("attaching"))},t)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){const t=this.state;return t==="initialized"||t==="detached"||t==="failed"?null:new S("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 "+t,90001,400)}setChannelSerial(t){c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+t+"; previous = "+this.properties.channelSerial),t&&(this.properties.channelSerial=t)}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(t){return c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,t)}async updateMessage(t,n,s){return c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.updateMessage()","channel = "+this.name),this.sendUpdate(t,"message.update",n,s)}async deleteMessage(t,n,s){return c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.deleteMessage()","channel = "+this.name),this.sendUpdate(t,"message.delete",n,s)}async appendMessage(t,n,s){return c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.appendMessage()","channel = "+this.name),this.sendUpdate(t,"message.append",n,s)}async sendUpdate(t,n,s,r){var a;if(!t.serial)throw new S('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();const b=await Tt.fromValues(fe(H({},t),{action:n,version:s})).encode(this.channelOptions),R=ut({action:X.MESSAGE,channel:this.name,messages:[b],params:r?pn(r):void 0});return{versionSerial:(a=(await this.sendAndAwaitAck(R)).serials[0])!=null?a:null}}async getMessageVersions(t,n){return c.logAction(this.logger,c.LOG_MICRO,"RealtimeChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,t,n)}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 S.fromValues(this.invalidStateError())}}};function wi(e){const t=e||{},{agent:n}=t;return de(t,["agent"])}var Dn=Ca,Oa=class{constructor(e){this.channel=e,this.logger=e.logger,this.subscriptions=new Se(this.logger)}async publish(e,t){const n=this.channel.name,s=yi(e,t),r=await s.encode();this.channel.throwIfUnpublishableState(),c.logAction(this.logger,c.LOG_MICRO,"RealtimeAnnotations.publish()","channelName = "+n+", sending annotation with messageSerial = "+s.messageSerial+", type = "+s.type);const a=ut({action:X.ANNOTATION,channel:n,annotations:[r]});await this.channel.sendAndAwaitAck(a)}async delete(e,t){t.action="annotation.delete",await this.publish(e,t)}async subscribe(...e){const t=Dn.processListenerArgs(e),n=t[0],s=t[1],r=this.channel;if(r.state==="failed")throw S.fromValues(r.invalidStateError());if(this.subscriptions.on(n,s),this.channel.channelOptions.attachOnSubscribe!==!1&&await r.attach(),(this.channel.state==="attached"&&this.channel._mode&je.ANNOTATION_SUBSCRIBE)===0)throw new S("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(...e){const t=Dn.processListenerArgs(e),n=t[0],s=t[1];this.subscriptions.off(n,s)}_processIncoming(e){for(const t of e)this.subscriptions.emit(t.type||"",t)}async get(e,t){return Ds.prototype.get.call(this,e,t)}},vi=Oa,cn=class Os extends ma{constructor(t){var n,s;if(!Os._MsgPack)throw new Error("Expected DefaultRest._MsgPack to have been set");super(V.objectifyOptions(t,!0,"Rest",c.defaultLogger,fe(H({},li),{Crypto:(n=Os.Crypto)!=null?n:void 0,MsgPack:(s=Os._MsgPack)!=null?s:void 0,Annotations:{Annotation:Hn,WireAnnotation:_n,RealtimeAnnotations:vi,RestAnnotations:Ds}})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(t){this._Crypto=t}};cn._Crypto=null,cn.Message=hi,cn.PresenceMessage=fi,cn.Annotation=gi,cn._MsgPack=null,cn._Http=Qe;var Fs=cn,Sa=class extends Se{constructor(e){super(e),this.messages=[]}count(){return this.messages.length}push(e){this.messages.push(e)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(e){this.messages.push.apply(this.messages,e)}prepend(e){this.messages.unshift.apply(this.messages,e)}completeMessages(e,t,n){c.logAction(this.logger,c.LOG_MICRO,"MessageQueue.completeMessages()",e=="all"?"(all)":"serial = "+e.serial+"; count = "+e.count),t=t||null;const s=this.messages;if(s.length===0)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");let r=[];if(e==="all")r=s.splice(0);else{const a=s[0];if(a){const g=a.message.msgSerial,b=e.serial+e.count;b>g&&(r=s.splice(0,b-g))}}for(let a=0;a<r.length;a++){const g=r[a],b=n==null?void 0:n[a];g.callback(t,b)}s.length==0&&this.emit("idle")}completeAllMessages(e){this.completeMessages("all",e)}resetSendAttempted(){for(let e of this.messages)e.sendAttempted=!1}clear(){c.logAction(this.logger,c.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},ki=Sa,_i=class{constructor(e,t){this.message=e,this.callback=t,this.merged=!1;const n=e.action;this.sendAttempted=!1,this.ackRequired=typeof n=="number"&&[X.MESSAGE,X.PRESENCE,X.ANNOTATION,X.OBJECT].includes(n)}},Ta=class extends Se{constructor(e){super(e.logger),this.transport=e,this.messageQueue=new ki(this.logger),e.on("ack",(t,n,s)=>{this.onAck(t,n,s)}),e.on("nack",(t,n,s)=>{this.onNack(t,n,s)})}onAck(e,t,n){c.logAction(this.logger,c.LOG_MICRO,"Protocol.onAck()","serial = "+e+"; count = "+t),this.messageQueue.completeMessages({serial:e,count:t},null,n)}onNack(e,t,n){c.logAction(this.logger,c.LOG_ERROR,"Protocol.onNack()","serial = "+e+"; count = "+t+"; err = "+Ge(n)),n||(n=new S("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages({serial:e,count:t},n)}onceIdle(e){const t=this.messageQueue;if(t.count()===0){e();return}t.once("idle",e)}send(e){e.ackRequired&&this.messageQueue.push(e),this.logger.shouldLog(c.LOG_MICRO)&&c.logActionNoStrip(this.logger,c.LOG_MICRO,"Protocol.send()","sending msg; "+Ws(e.message,this.transport.connectionManager.realtime._RealtimePresence,this.transport.connectionManager.realtime._Annotations,this.transport.connectionManager.realtime._liveObjectsPlugin)),e.sendAttempted=!0,this.transport.send(e.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){const e=this.transport;this.onceIdle(function(){e.disconnect()})}},Ea=Ta,Ma=class{constructor(e,t,n,s){this.previous=e,this.current=t,n&&(this.retryIn=n),s&&(this.reason=s)}},xs=Ma,Jt={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},Ia={disconnected:()=>S.fromValues({statusCode:400,code:Jt.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>S.fromValues({statusCode:400,code:Jt.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>S.fromValues({statusCode:400,code:Jt.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>S.fromValues({statusCode:400,code:Jt.CLOSING,message:"Connection closing"}),closed:()=>S.fromValues({statusCode:400,code:Jt.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>S.fromValues({statusCode:500,code:Jt.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>S.fromValues({statusCode:500,code:Jt.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})};function Pa(e){return!e.statusCode||!e.code||e.statusCode>=500?!0:Object.values(Jt).includes(e.code)}var ln=Ia,La=ut({action:X.CLOSE}),Ua=ut({action:X.DISCONNECT}),Ba=class extends Se{constructor(e,t,n,s){super(e.logger),s&&(n.format=void 0,n.heartbeats=!0),this.connectionManager=e,this.auth=t,this.params=n,this.timeouts=n.options.timeouts,this.format=n.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",ln.closed())}disconnect(e){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",e||ln.disconnected())}fail(e){this.isConnected&&this.requestDisconnect(),this.finish("failed",e||ln.failed())}finish(e,t){var n;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout((n=this.idleTimer)!=null?n:void 0),this.idleTimer=null,this.emit(e,t),this.dispose())}onProtocolMessage(e){switch(this.logger.shouldLog(c.LOG_MICRO)&&c.logActionNoStrip(this.logger,c.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+Ws(e,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),e.action){case X.HEARTBEAT:c.logActionNoStrip(this.logger,c.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",e.id);break;case X.CONNECTED:this.onConnect(e),this.emit("connected",e.error,e.connectionId,e.connectionDetails,e);break;case X.CLOSED:this.onClose(e);break;case X.DISCONNECTED:this.onDisconnect(e);break;case X.ACK:this.emit("ack",e.msgSerial,e.count,e.res);break;case X.NACK:this.emit("nack",e.msgSerial,e.count,e.error);break;case X.SYNC:this.connectionManager.onChannelMessage(e,this);break;case X.ACTIVATE:break;case X.AUTH:ot(this.auth.authorize(),t=>{t&&c.logAction(this.logger,c.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+Ge(t))});break;case X.ERROR:if(c.logAction(this.logger,c.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+_.Config.inspect(e.error)+(e.channel?", channel: "+e.channel:"")),e.channel===void 0){this.onFatalError(e);break}this.connectionManager.onChannelMessage(e,this);break;default:this.connectionManager.onChannelMessage(e,this)}}onConnect(e){if(this.isConnected=!0,!e.connectionDetails)throw new Error("Transport.onConnect(): Connect message recieved without connectionDetails");const t=e.connectionDetails.maxIdleInterval;t&&(this.maxIdleInterval=t+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(e){const t=e&&e.error;c.logAction(this.logger,c.LOG_MINOR,"Transport.onDisconnect()","err = "+Ge(t)),this.finish("disconnected",t)}onFatalError(e){const t=e&&e.error;c.logAction(this.logger,c.LOG_MINOR,"Transport.onFatalError()","err = "+Ge(t)),this.finish("failed",t)}onClose(e){const t=e&&e.error;c.logAction(this.logger,c.LOG_MINOR,"Transport.onClose()","err = "+Ge(t)),this.finish("closed",t)}requestClose(){c.logAction(this.logger,c.LOG_MINOR,"Transport.requestClose()",""),this.send(La)}requestDisconnect(){c.logAction(this.logger,c.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(Ua)}ping(e){const t={action:X.HEARTBEAT};e&&(t.id=e),this.send(ut(t))}dispose(){c.logAction(this.logger,c.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(e){this.idleTimer||(this.idleTimer=setTimeout(()=>{this.onIdleTimerExpire()},e))}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;const e=Date.now()-this.lastActivity,t=this.maxIdleInterval-e;if(t<=0){const n="No activity seen from realtime in "+e+"ms; assuming connection has dropped";c.logAction(this.logger,c.LOG_ERROR,"Transport.onIdleTimerExpire()",n),this.disconnect(new S(n,80003,408))}else this.setIdleTimer(t+100)}static tryConnect(e,t,n,s,r){const a=new e(t,n,s);let g;const b=function(A){clearTimeout(g),r({event:this.event,error:A})},R=t.options.timeouts.realtimeRequestTimeout;return g=setTimeout(()=>{a.off(["preconnect","disconnected","failed"]),a.dispose(),b.call({event:"disconnected"},new S("Timeout waiting for transport to indicate itself viable",5e4,500))},R),a.on(["failed","disconnected"],b),a.on("preconnect",function(){c.logAction(t.logger,c.LOG_MINOR,"Transport.tryConnect()","viable transport "+a),clearTimeout(g),a.off(["failed","disconnected"],b),r(null,a)}),a.connect(),a}static isAvailable(){throw new S("isAvailable not implemented for transport",5e4,500)}},An=Ba,dt;(e=>{e.WebSocket="web_socket",e.Comet="comet",e.XhrPolling="xhr_polling"})(dt||(dt={}));var Na=typeof Kt<"u"?Kt:typeof window<"u"?window:self,zs=()=>{var e;return typeof _.WebStorage<"u"&&((e=_.WebStorage)==null?void 0:e.localSupported)},jn=()=>{var e;return typeof _.WebStorage<"u"&&((e=_.WebStorage)==null?void 0:e.sessionSupported)},Ai=function(){},Js="ably-transport-preference";function Ks(e){try{return JSON.parse(e)}catch{return null}}var Ga=class{constructor(e,t,n,s){this.options=e,this.host=t,this.mode=n,this.connectionKey=s,this.format=e.useBinaryProtocol?"msgpack":"json"}getConnectParams(e){const t=e?Pt(e):{},n=this.options;switch(this.mode){case"resume":t.resume=this.connectionKey;break;case"recover":{const s=Ks(n.recover);s&&(t.recover=s.connectionKey);break}}return n.clientId!==void 0&&(t.clientId=n.clientId),n.echoMessages===!1&&(t.echo="false"),this.format!==void 0&&(t.format=this.format),this.stream!==void 0&&(t.stream=this.stream),this.heartbeats!==void 0&&(t.heartbeats=this.heartbeats),t.v=V.protocolVersion,t.agent=B(this.options),n.transportParams!==void 0&&pe(t,n.transportParams),t}toString(){let e="[mode="+this.mode;return this.host&&(e+=",host="+this.host),this.connectionKey&&(e+=",connectionKey="+this.connectionKey),this.format&&(e+=",format="+this.format),e+="]",e}},qa=class uo extends Se{constructor(t,n){super(t.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=t,this.initTransports(),this.options=n;const s=n.timeouts,r=s.webSocketConnectTimeout+s.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:r,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:s.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:s.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:s.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 ki(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=s.connectionStateTtl,this.maxIdleInterval=null,this.transports=en(n.transports||V.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(dt.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(dt.XhrPolling)?this.baseTransport=dt.XhrPolling:this.transports.includes(dt.Comet)&&(this.baseTransport=dt.Comet),this.domains=V.getHosts(n),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,c.logAction(this.logger,c.LOG_MINOR,"Realtime.ConnectionManager()","started"),c.logAction(this.logger,c.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(n.transports||V.defaultTransports)+"]"),c.logAction(this.logger,c.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),c.logAction(this.logger,c.LOG_MICRO,"Realtime.ConnectionManager()","http domains = ["+this.domains+"]"),!this.transports.length){const g="no requested transports available";throw c.logAction(this.logger,c.LOG_ERROR,"realtime.ConnectionManager()",g),new Error(g)}const a=_.Config.addEventListener;a&&(jn()&&typeof n.recover=="function"&&a("beforeunload",this.persistConnection.bind(this)),n.closeOnUnload===!0&&a("beforeunload",()=>{c.logAction(this.logger,c.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),this.requestState({state:"closing"})}),a("online",()=>{var g;this.state==this.states.disconnected||this.state==this.states.suspended?(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager caught browser ‘online’ event","reattempting connection"),this.requestState({state:"connecting"})):this.state==this.states.connecting&&((g=this.pendingTransport)==null||g.off(),this.disconnectAllTransports(),this.startConnect())}),a("offline",()=>{this.state==this.states.connected&&(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager caught browser ‘offline’ event","disconnecting active transport"),this.disconnectAllTransports())}))}static supportedTransports(t){const n={supportedTransports:{}};return this.initTransports(t,n),n.supportedTransports}static initTransports(t,n){const s=H(H({},_.Transports.bundledImplementations),t);[dt.WebSocket,..._.Transports.order].forEach(r=>{const a=s[r];a&&a.isAvailable()&&(n.supportedTransports[r]=a)})}initTransports(){uo.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(t,n){return new Ga(this.options,t,n,this.connectionKey)}getTransportParams(t){(s=>{if(this.connectionKey){s("resume");return}if(typeof this.options.recover=="string"){s("recover");return}const r=this.options.recover,a=this.getSessionRecoverData(),g=this.sessionRecoveryName();if(a&&typeof r=="function"){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+g+")"),r(a,b=>{b?(this.options.recover=a.recoveryKey,s("recover")):s("clean")});return}s("clean")})(s=>{const r=this.createTransportParams(null,s);if(s==="recover"){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);const a=Ks(this.options.recover);a&&(this.msgSerial=a.msgSerial)}else c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+r.toString());t(r)})}tryATransport(t,n,s){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+n),this.proposedTransport=An.tryConnect(this.supportedTransports[n],this,this.realtime.auth,t,(r,a)=>{const g=this.state;if(g==this.states.closing||g==this.states.closed||g==this.states.failed){a&&(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+g.state+" while we were attempting the transport; closing "+a),a.close()),s(!0);return}if(r){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+n+" "+r.event+", err: "+r.error.toString()),Oe.isTokenErr(r.error)&&!(this.errorReason&&Oe.isTokenErr(this.errorReason))?(this.errorReason=r.error,ot(this.realtime.auth._forceNewToken(null,null),b=>{if(b){this.actOnErrorFromAuthorize(b);return}this.tryATransport(t,n,s)})):r.event==="failed"?(this.notifyState({state:"failed",error:r.error}),s(!0)):r.event==="disconnected"&&(Pa(r.error)?s(!1):(this.notifyState({state:this.states.connecting.failState,error:r.error}),s(!0)));return}c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+n+"; setting pending"),this.setTransportPending(a,t),s(null,a)})}setTransportPending(t,n){const s=n.mode;c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+t+"; mode = "+s),this.pendingTransport=t,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),t.once("connected",(a,g,b)=>{this.activateTransport(a,t,g,b),s==="recover"&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});const r=this;t.on(["disconnected","closed","failed"],function(a){r.deactivateTransport(t,this.event,a)}),this.emit("transport.pending",t)}activateTransport(t,n,s,r){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+n),t&&c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+t),s&&c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+s),r&&c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(r)),this.persistTransportPreference(n);const a=this.state,g=this.states.connected.state;if(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+a.state),a.state==this.states.closing.state||a.state==this.states.closed.state||a.state==this.states.failed.state)return c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),n.disconnect(),!1;if(delete this.pendingTransport,!n.isConnected)return c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+n+" since it appears to no longer be connected"),!1;const b=this.activeProtocol;this.activeProtocol=new Ea(n),this.host=n.params.host;const R=r.connectionKey;if(R&&this.connectionKey!=R&&this.setConnection(s,r,!!t),this.onConnectionDetailsUpdate(r,n),_.Config.nextTick(()=>{n.on("connected",(A,L,U)=>{this.onConnectionDetailsUpdate(U,n),this.emit("update",new xs(g,g,null,A))})}),a.state===this.states.connected.state?t&&(this.errorReason=this.realtime.connection.errorReason=t,this.emit("update",new xs(g,g,null,t))):(this.notifyState({state:"connected",error:t}),this.errorReason=this.realtime.connection.errorReason=t||null),this.emit("transport.active",n),b)if(b.messageQueue.count()>0&&c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+b.transport.shortName+", new one is "+n.shortName+") finishing with "+b.messageQueue.count()+" messages still pending"),b.transport===n){const A="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+n.shortName+"; stack = "+new Error().stack;c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.activateTransport()",A)}else b.finish();return!0}deactivateTransport(t,n,s){const r=this.activeProtocol,a=r&&r.getTransport()===t,g=t===this.pendingTransport,b=this.noTransportsScheduledForActivation();if(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+t),c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+n+(a?"; was active":g?"; was pending":"")+(b?"":"; another transport is scheduled for activation")),s&&s.message&&c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+s.message),a&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(r.getPendingMessages()),r.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",t),a&&b||a&&n==="failed"||n==="closed"||r===null&&g){if(n==="disconnected"&&s&&s.statusCode>500&&this.domains.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:n,error:s,retryImmediately:!0});return}const R=n==="failed"&&Oe.isTokenErr(s)?"disconnected":n;this.notifyState({state:R,error:s});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(t,n,s){const r=this.connectionId;(r&&r!==t||!r&&s)&&(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==t&&c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=t,this.realtime.connection.key=this.connectionKey=n.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.queuedMessages.resetSendAttempted(),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;const t=Date.now()-this.lastActivity;t>this.connectionStateTtl+this.maxIdleInterval&&(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+t+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}persistConnection(){if(jn()){const t=this.createRecoveryKey();t&&this.setSessionRecoverData({recoveryKey:t,disconnectedAt:Date.now(),location:Na.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getActiveTransportFormat(){var t;return(t=this.activeProtocol)==null?void 0:t.getTransport().format}getError(){if(this.errorReason){const t=et.fromValues(this.errorReason);return t.cause=this.errorReason,t}return this.getStateError()}getStateError(){var t,n;return(n=(t=ln)[this.state.state])==null?void 0:n.call(t)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(t){const n="Connection state",s=t.current+(t.reason?"; reason: "+t.reason:"");t.current==="failed"?c.logAction(this.logger,c.LOG_ERROR,n,s):c.logAction(this.logger,c.LOG_MAJOR,n,s),c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+t.current+"; reason = "+(t.reason&&t.reason.message));const r=this.state=this.states[t.current];t.reason&&(this.errorReason=t.reason,this.realtime.connection.errorReason=t.reason),(r.terminal||r.state==="suspended")&&this.clearConnection(),this.emit("connectionstate",t)}startTransitionTimer(t){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+t.state),this.transitionTimer&&(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager "+t.state+" timer expired","requesting new state: "+t.failState),this.notifyState({state:t.failState}))},t.retryDelay)}cancelTransitionTimer(){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),this.states.connecting.failState="suspended",this.notifyState({state:"suspended"}))},this.connectionStateTtl))}checkSuspendTimer(t){t!=="disconnected"&&t!=="suspended"&&t!=="connecting"&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(t){this.retryTimer=setTimeout(()=>{c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),this.retryTimer=null,this.requestState({state:"connecting"})},t)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),this.checkWsConnectivity().then(()=>{c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{c.logAction(this.logger,c.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&ot(this.realtime.http.checkConnectivity(),(t,n)=>{t||!n?(c.logAction(this.logger,c.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new S("Unable to connect (network unreachable)",80003,404)})):c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager WebSocket slow timer","http connectivity check succeeded")})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(t){this.webSocketGiveUpTimer=setTimeout(()=>{var n,s;this.wsCheckResult||(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager WebSocket give up timer","websocket connection took more than 10s; "+(this.baseTransport?"trying base transport":"")),this.baseTransport?(this.abandonedWebSocket=!0,(n=this.proposedTransport)==null||n.dispose(),(s=this.pendingTransport)==null||s.dispose(),this.connectBase(t,++this.connectCounter)):c.logAction(this.logger,c.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(t){var n,s;const r=t.state,a=r==="disconnected"&&(this.state===this.states.connected||t.retryImmediately||this.state===this.states.connecting&&t.error&&Oe.isTokenErr(t.error)&&!(this.errorReason&&Oe.isTokenErr(this.errorReason)));if(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+r+(a?"; will retry connection immediately":"")),r==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(t.state),(r==="suspended"||r==="connected")&&(this.disconnectedRetryCount=0),this.state.terminal))return;const g=this.states[t.state];let b=g.retryDelay;g.state==="disconnected"&&(this.disconnectedRetryCount++,b=Vt(g.retryDelay,this.disconnectedRetryCount));const R=new xs(this.state.state,g.state,b,t.error||((s=(n=ln)[g.state])==null?void 0:s.call(n)));if(a){const A=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},L=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;L&&L<1e3?(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+L+"ms ago, waiting another "+(1e3-L)+"ms before trying again"),setTimeout(A,1e3-L)):_.Config.nextTick(A)}else(r==="disconnected"||r==="suspended")&&this.startRetryTimer(b);(r==="disconnected"&&!a||r==="suspended"||g.terminal)&&_.Config.nextTick(()=>{this.disconnectAllTransports()}),r=="connected"&&!this.activeProtocol&&c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(R),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(r,R.reason),this.failQueuedMessages(R.reason))}requestState(t){var n,s;const r=t.state;if(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+r+"; current state: "+this.state.state),r==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(r),r=="connecting"&&this.state.state=="connected")||r=="closing"&&this.state.state=="closed")return;const a=this.states[r],g=new xs(this.state.state,a.state,null,t.error||((s=(n=ln)[a.state])==null?void 0:s.call(n)));this.enactStateChange(g),r=="connecting"&&_.Config.nextTick(()=>{this.startConnect()}),r=="closing"&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);return}const t=this.realtime.auth,n=++this.connectCounter,s=()=>{this.checkConnectionStateFreshness(),this.getTransportParams(r=>{if(r.mode==="recover"&&r.options.recover){const a=Ks(r.options.recover);a&&this.realtime.channels.recoverChannels(a.channelSerials)}n===this.connectCounter&&this.connectImpl(r,n)})};if(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),t.method==="basic")s();else{const r=a=>{n===this.connectCounter&&(a?this.actOnErrorFromAuthorize(a):s())};this.errorReason&&Oe.isTokenErr(this.errorReason)?ot(t._forceNewToken(null,null),r):ot(t._ensureValidAuthCredentials(!1),r)}}connectImpl(t,n){const s=this.state.state;if(s!==this.states.connecting.state){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect, but was "+s);return}const r=this.getTransportPreference();r&&r===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(t,++this.connectCounter))}).catch(Ai),r&&r===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(t,n):this.connectWs(t,n)}connectWs(t,n){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.connectWs()"),this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(t),this.tryTransportWithFallbacks("web_socket",t,!0,n,()=>this.wsCheckResult!==!1&&!this.abandonedWebSocket)}connectBase(t,n){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,t,!1,n,()=>!0):this.notifyState({state:"disconnected",error:new S("No transports left to try",8e4,404)})}tryTransportWithFallbacks(t,n,s,r,a){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",t);const g=U=>{this.notifyState({state:this.states.connecting.failState,error:U})},b=this.domains.slice(),R=(U,F)=>{if(r===this.connectCounter){if(!a()){F&&F.dispose();return}!F&&!U&&L()}},A=b.shift();if(!A){g(new S("Unable to connect (no available host)",80003,404));return}n.host=A;const L=()=>{if(!b.length){g(new S("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!this.realtime.http.checkConnectivity){g(new et("Internal error: Http.checkConnectivity not set",null,500));return}ot(this.realtime.http.checkConnectivity(),(U,F)=>{if(r===this.connectCounter&&a()){if(U){g(U);return}if(!F){g(new S("Unable to connect (network unreachable)",80003,404));return}n.host=wt(b),this.tryATransport(n,t,R)}})};if(this.forceFallbackHost&&b.length){this.forceFallbackHost=!1,L();return}this.tryATransport(n,t,R)}closeImpl(){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})}onAuthUpdated(t,n){var s;switch(this.state.state){case"connected":{c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport");const r=(s=this.activeProtocol)==null?void 0:s.getTransport();r&&r.onAuthUpdated&&r.onAuthUpdated(t);const a=ut({action:X.AUTH,auth:{accessToken:t.token}});this.send(a);const g=()=>{this.off(b),n(null,t)},b=R=>{R.current==="failed"&&(this.off(g),this.off(b),n(R.reason||this.getStateError()))};this.once("connectiondetails",g),this.on("connectionstate",b);break}case"connecting":c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");const r=a=>{switch(a.current){case"connected":this.off(r),n(null,t);break;case"failed":case"closed":case"suspended":this.off(r),n(a.reason||this.getStateError());break}};this.on("connectionstate",r),this.state.state==="connecting"?this.startConnect():this.requestState({state:"connecting"})}}}disconnectAllTransports(){c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(t,n,s){s=s||Ai;const r=this.state;if(r.sendEvents){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new _i(t,s));return}if(!(n&&r.queueEvents)){const g="rejecting event, queueEvent was "+n+", state was "+r.state;c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.send()",g),s(this.errorReason||new S(g,9e4,400));return}this.logger.shouldLog(c.LOG_MICRO)&&c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+Ws(t,this.realtime._RealtimePresence,this.realtime._Annotations,this.realtime._liveObjectsPlugin)),this.queue(t,s)}sendImpl(t){const n=t.message;t.ackRequired&&!t.sendAttempted&&(n.msgSerial=this.msgSerial++);try{this.activeProtocol.send(t)}catch(s){c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+s.stack)}}queue(t,n){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.queue()","queueing event"),this.queuedMessages.push(new _i(t,n))}sendQueuedMessages(){c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");let t;for(;t=this.queuedMessages.shift();)this.sendImpl(t)}queuePendingMessages(t){t&&t.length&&(c.logAction(this.logger,c.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+t.length+" pending messages"),this.queuedMessages.prepend(t))}failQueuedMessages(t){const n=this.queuedMessages.count();n>0&&(c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+n+" queued messages, err = "+Ge(t)),this.queuedMessages.completeAllMessages(t))}onChannelMessage(t,n){this.pendingChannelMessagesState.queue.push({message:t,transport:n}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;const t=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(t.message).catch(n=>{c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",n)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}async processChannelMessage(t){await this.realtime.channels.processChannelMessage(t)}async ping(){var t;if(this.state.state!=="connected")throw new S("Unable to ping service; not connected",4e4,400);const n=(t=this.activeProtocol)==null?void 0:t.getTransport();if(!n)throw this.getStateError();c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.ping()","transport = "+n);const s=Date.now(),r=Ht();return St(new Promise(a=>{const g=b=>{b===r&&(n.off("heartbeat",g),a(Date.now()-s))};n.on("heartbeat",g),n.ping(r)}),this.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")}abort(t){this.activeProtocol.getTransport().fail(t)}getTransportPreference(){var t,n;return this.transportPreference||zs()&&((n=(t=_.WebStorage)==null?void 0:t.get)==null?void 0:n.call(t,Js))}persistTransportPreference(t){var n,s;this.transportPreference=t.shortName,zs()&&((s=(n=_.WebStorage)==null?void 0:n.set)==null||s.call(n,Js,t.shortName))}unpersistTransportPreference(){var t,n;this.transportPreference=null,zs()&&((n=(t=_.WebStorage)==null?void 0:t.remove)==null||n.call(t,Js))}actOnErrorFromAuthorize(t){if(t.code===40171)this.notifyState({state:"failed",error:t});else if(t.code===40102)this.notifyState({state:"failed",error:t});else if(t.statusCode===re.Forbidden){const n="Client configured authentication provider returned 403; failing the connection";c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",n),this.notifyState({state:"failed",error:new S(n,80019,403,t)})}else{const n="Client configured authentication provider request failed";c.logAction(this.logger,c.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",n),this.notifyState({state:this.state.failState,error:new S(n,80019,401,t)})}}onConnectionDetailsUpdate(t,n){if(!t)return;this.connectionDetails=t,t.maxMessageSize&&(this.options.maxMessageSize=t.maxMessageSize);const s=t.clientId;if(s){const a=this.realtime.auth._uncheckedSetClientId(s);if(a){c.logAction(this.logger,c.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",a.message),n.fail(a);return}}const r=t.connectionStateTtl;r&&(this.connectionStateTtl=r),this.maxIdleInterval=t.maxIdleInterval,this.emit("connectiondetails",t)}checkWsConnectivity(){const t=this.options.wsConnectivityCheckUrl||V.wsConnectivityCheckUrl,n=new _.Config.WebSocket(t);return new Promise((s,r)=>{let a=!1;n.onopen=()=>{a||(a=!0,s(),n.close())},n.onclose=n.onerror=()=>{a||(a=!0,r())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var t,n;return jn()&&((n=(t=_.WebStorage)==null?void 0:t.getSession)==null?void 0:n.call(t,this.sessionRecoveryName()))}setSessionRecoverData(t){var n,s;return jn()&&((s=(n=_.WebStorage)==null?void 0:n.setSession)==null?void 0:s.call(n,this.sessionRecoveryName(),t))}clearSessionRecoverData(){var t,n;return jn()&&((n=(t=_.WebStorage)==null?void 0:t.removeSession)==null?void 0:n.call(t,this.sessionRecoveryName()))}},Ri=qa,Ha=class extends Se{constructor(e,t){super(e.logger),this.whenState=n=>Se.prototype.whenState.call(this,n,this.state),this.ably=e,this.connectionManager=new Ri(e,t),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",n=>{const s=this.state=n.current;_.Config.nextTick(()=>{this.emit(s,n)})}),this.connectionManager.on("update",n=>{_.Config.nextTick(()=>{this.emit("update",n)})})}connect(){c.logAction(this.logger,c.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}async ping(){return c.logAction(this.logger,c.LOG_MINOR,"Connection.ping()",""),this.connectionManager.ping()}close(){c.logAction(this.logger,c.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()}},Da=Ha,Ci=class po extends $r{constructor(t){var n,s,r,a;if(super(V.objectifyOptions(t,!1,"BaseRealtime",c.defaultLogger)),c.logAction(this.logger,c.LOG_MINOR,"Realtime()",""),typeof EdgeRuntime=="string")throw new S(`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=po.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=(s=(n=this.options.plugins)==null?void 0:n.RealtimePresence)!=null?s:null,this._liveObjectsPlugin=(a=(r=this.options.plugins)==null?void 0:r.LiveObjects)!=null?a:null,this.connection=new Da(this,this.options),this._channels=new Wa(this),this.options.autoConnect!==!1&&this.connect()}static transportImplementationsFromPlugins(t){const n={};return t!=null&&t.WebSocketTransport&&(n[dt.WebSocket]=t.WebSocketTransport),t!=null&&t.XHRPolling&&(n[dt.XhrPolling]=t.XHRPolling),n}get channels(){return this._channels}get clientId(){return this.auth.clientId}connect(){c.logAction(this.logger,c.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){c.logAction(this.logger,c.LOG_MINOR,"Realtime.close()",""),this.connection.close()}};Ci.EventEmitter=Se;var ja=Ci,Wa=class extends Se{constructor(e){super(e.logger),this.realtime=e,this.all=Object.create(null),e.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){let e={};for(const t of sn(this.all,!0)){const n=this.all[t];n.properties.channelSerial&&(e[t]=n.properties.channelSerial)}return e}recoverChannels(e){for(const t of sn(e,!0)){const n=this.get(t);n.properties.channelSerial=e[t]}}async processChannelMessage(e){const t=e.channel;if(t===void 0){c.logAction(this.logger,c.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+e.action);return}const n=this.all[t];if(!n){c.logAction(this.logger,c.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+t);return}await n.processMessage(e)}onTransportActive(){for(const e in this.all){const t=this.all[e];t.state==="attaching"||t.state==="detaching"?t.checkPendingState():t.state==="suspended"?t._attach(!1,null):t.state==="attached"&&t.requestState("attaching")}}propogateConnectionInterruption(e,t){const n={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"},s=["attaching","attached","detaching","suspended"],r=n[e];for(const a in this.all){const g=this.all[a];s.includes(g.state)&&g.notifyState(r,t)}}get(e,t){e=String(e);let n=this.all[e];if(!n)n=this.all[e]=new Dn(this.realtime,e,t);else if(t){if(n._shouldReattachToSetOptions(t,n.channelOptions))throw new S("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);n.setOptions(t)}return n}getDerived(e,t,n){if(t.filter){const s=an(t.filter),r=yn(e);e=`[filter=${s}${r.qualifierParam}]${r.channelName}`}return this.get(e,n)}release(e){e=String(e);const t=this.all[e];if(!t)return;const n=t.getReleaseErr();if(n)throw n;delete this.all[e]}},Va=ja;function $a(e,t){if(e.isSynthesized()||t.isSynthesized())return e.timestamp>=t.timestamp;const n=e.parseId(),s=t.parseId();return n.msgSerial===s.msgSerial?n.index>s.index:n.msgSerial>s.msgSerial}var Qs=class extends Se{constructor(e,t,n=$a){super(e.logger),this.presence=e,this.map=Object.create(null),this.syncInProgress=!1,this.residualMembers=null,this.memberKey=t,this.newerThan=n}get(e){return this.map[e]}getClient(e){const t=this.map,n=[];for(const s in t){const r=t[s];r.clientId==e&&r.action!="absent"&&n.push(r)}return n}list(e){const t=this.map,n=e&&e.clientId,s=e&&e.connectionId,r=[];for(const a in t){const g=t[a];g.action!=="absent"&&(n&&n!=g.clientId||s&&s!=g.connectionId||r.push(g))}return r}put(e){(e.action==="enter"||e.action==="update")&&(e=zt.fromValues(e),e.action="present");const t=this.map,n=this.memberKey(e);this.residualMembers&&delete this.residualMembers[n];const s=t[n];return s&&!this.newerThan(e,s)?!1:(t[n]=e,!0)}values(){const e=this.map,t=[];for(const n in e){const s=e[n];s.action!="absent"&&t.push(s)}return t}remove(e){const t=this.map,n=this.memberKey(e),s=t[n];return s&&!this.newerThan(e,s)?!1:(this.syncInProgress?(e=zt.fromValues(e),e.action="absent",t[n]=e):delete t[n],!!s)}startSync(){const e=this.map,t=this.syncInProgress;c.logAction(this.logger,c.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),this.syncInProgress||(this.residualMembers=Pt(e),this.setInProgress(!0))}endSync(){const e=this.map,t=this.syncInProgress;if(c.logAction(this.logger,c.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),t){for(const n in e)e[n].action==="absent"&&delete e[n];this.presence._synthesizeLeaves(fs(this.residualMembers));for(const n in this.residualMembers)delete e[n];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}async waitSync(){const e=this.syncInProgress;c.logAction(this.logger,c.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+e),e&&await this.once("sync")}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(e){c.logAction(this.logger,c.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+e),this.syncInProgress=e,this.presence.syncComplete=!e}};function Fa(e){return e.channel.client.auth.clientId}function Ys(e){const t=e.channel.client,n=t.auth.clientId;return(!n||n==="*")&&t.connection.state==="connected"}var za=class extends Se{constructor(e){super(e.logger),this.channel=e,this.syncComplete=!1,this.members=new Qs(this,t=>t.clientId+":"+t.connectionId),this._myMembers=new Qs(this,t=>t.clientId),this.subscriptions=new Se(this.logger),this.pendingPresence=[]}async enter(e){if(Ys(this))throw new S("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,e,"enter")}async update(e){if(Ys(this))throw new S("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,void 0,e,"update")}async enterClient(e,t){return this._enterOrUpdateClient(void 0,e,t,"enter")}async updateClient(e,t){return this._enterOrUpdateClient(void 0,e,t,"update")}async _enterOrUpdateClient(e,t,n,s){const r=this.channel;if(!r.connectionManager.activeState())throw r.connectionManager.getError();c.logAction(this.logger,c.LOG_MICRO,"RealtimePresence."+s+"Client()","channel = "+r.name+", id = "+e+", client = "+(t||"(implicit) "+Fa(this)));const a=zt.fromData(n);a.action=s,e&&(a.id=e),t&&(a.clientId=t);const g=await a.encode(r.channelOptions);switch(r.state){case"attached":return r.sendPresence([g]);case"initialized":case"detached":r.attach();case"attaching":return new Promise((b,R)=>{this.pendingPresence.push({presence:g,callback:A=>A?R(A):b()})});default:{const b=new et("Unable to "+s+" presence channel while in "+r.state+" state",90001);throw b.code=90001,b}}}async leave(e){if(Ys(this))throw new S("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,e)}async leaveClient(e,t){const n=this.channel;if(!n.connectionManager.activeState())throw n.connectionManager.getError();c.logAction(this.logger,c.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+e);const s=zt.fromData(t);s.action="leave",e&&(s.clientId=e);const r=await s.encode(n.channelOptions);switch(n.state){case"attached":return n.sendPresence([r]);case"attaching":return new Promise((a,g)=>{this.pendingPresence.push({presence:r,callback:b=>b?g(b):a()})});case"initialized":case"failed":throw new et("Unable to leave presence channel (incompatible state)",90001);default:throw n.invalidStateError()}}async get(e){const t=!e||("waitForSync"in e?e.waitForSync:!0);function n(r){return e?r.list(e):r.values()}if(this.channel.state==="suspended"){if(t)throw S.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"});return n(this.members)}await this.channel.ensureAttached();const s=this.members;return t&&await s.waitSync(),n(this.members)}async history(e){c.logAction(this.logger,c.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);const t=this.channel.client.rest.presenceMixin;if(e&&e.untilAttach)if(this.channel.state==="attached")delete e.untilAttach,e.from_serial=this.channel.properties.attachSerial;else throw new S("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400);return t.history(this,e)}setPresence(e,t,n){c.logAction(this.logger,c.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+e.length+" participants; syncChannelSerial = "+n);let s,r;const a=this.members,g=this._myMembers,b=[],R=this.channel.connectionManager.connectionId;t&&(this.members.startSync(),n&&(r=n.match(/^[\w-]+:(.*)$/))&&(s=r[1]));for(let A of e)switch(A.action){case"leave":a.remove(A)&&b.push(A),A.connectionId===R&&!A.isSynthesized()&&g.remove(A);break;case"enter":case"present":case"update":a.put(A)&&b.push(A),A.connectionId===R&&g.put(A);break}t&&!s&&(a.endSync(),this.channel.syncChannelSerial=null);for(let A=0;A<b.length;A++){const L=b[A];this.subscriptions.emit(L.action,L)}}onAttached(e){c.logAction(this.logger,c.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+e),e?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();const t=this.pendingPresence,n=t.length;if(n){this.pendingPresence=[];const s=[],r=me.create(this.logger);c.logAction(this.logger,c.LOG_MICRO,"RealtimePresence.onAttached","sending "+n+" queued presence messages");for(let a=0;a<n;a++){const g=t[a];s.push(g.presence),r.push(g.callback)}this.channel.sendPresence(s).then(()=>r()).catch(a=>r(a))}}actOnChannelState(e,t,n){switch(e){case"attached":this.onAttached(t);break;case"detached":case"failed":this._clearMyMembers(),this.members.clear();case"suspended":this.failPendingPresence(n);break}}failPendingPresence(e){if(this.pendingPresence.length){c.logAction(this.logger,c.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+Ge(e));for(let t=0;t<this.pendingPresence.length;t++)try{this.pendingPresence[t].callback(e)}catch{}this.pendingPresence=[]}}_clearMyMembers(){this._myMembers.clear()}_ensureMyMembersPresent(){const e=this._myMembers,t=this.channel.connectionManager.connectionId;for(const n in e.map){const s=e.map[n];c.logAction(this.logger,c.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+s.clientId+'" into the presence set');const r=s.connectionId===t?s.id:void 0;this._enterOrUpdateClient(r,s.clientId,s.data,"enter").catch(a=>{const g=new S("Presence auto re-enter failed",91004,400,a);c.logAction(this.logger,c.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()","Presence auto re-enter failed; reason = "+Ge(a));const b=new $s(this.channel.state,this.channel.state,!0,!1,g);this.channel.emit("update",b)})}}_synthesizeLeaves(e){const t=this.subscriptions;e.forEach(function(n){const s=zt.fromValues({action:"leave",connectionId:n.connectionId,clientId:n.clientId,data:n.data,encoding:n.encoding,timestamp:Date.now()});t.emit("leave",s)})}async subscribe(...e){const t=Dn.processListenerArgs(e),n=t[0],s=t[1],r=this.channel;if(r.state==="failed")throw S.fromValues(r.invalidStateError());this.subscriptions.on(n,s),r.channelOptions.attachOnSubscribe!==!1&&await r.attach()}unsubscribe(...e){const t=Dn.processListenerArgs(e),n=t[0],s=t[1];this.subscriptions.off(n,s)}},Ja=za,Ka=dt.WebSocket;function Qa(e){return!!e.on}var Ya=class extends An{constructor(e,t,n){super(e,t,n),this.shortName=Ka,n.heartbeats=_.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!_.Config.WebSocket}createWebSocket(e,t){return this.uri=e+Ot(t),new _.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.connect()","starting"),An.prototype.connect.call(this);const e=this,t=this.params,n=t.options,r=(n.tls?"wss://":"ws://")+this.wsHost+":"+V.getPort(n)+"/";c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.connect()","uri: "+r),ot(this.auth.getAuthParams(),function(a,g){if(e.isDisposed)return;let b="";for(const A in g)b+=" "+A+": "+g[A]+";";if(c.logAction(e.logger,c.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+b+" err: "+a),a){e.disconnect(a);return}const R=t.getConnectParams(g);try{const A=e.wsConnection=e.createWebSocket(r,R);A.binaryType=_.Config.binaryType,A.onopen=function(){e.onWsOpen()},A.onclose=function(L){e.onWsClose(L)},A.onmessage=function(L){e.onWsData(L.data)},A.onerror=function(L){e.onWsError(L)},Qa(A)&&A.on("ping",function(){e.onActivity()})}catch(A){c.logAction(e.logger,c.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(A.stack||A.message)),e.disconnect(A)}})}send(e){const t=this.wsConnection;if(!t){c.logAction(this.logger,c.LOG_ERROR,"WebSocketTransport.send()","No socket connection");return}try{t.send(va(e,this.connectionManager.realtime._MsgPack,this.params.format))}catch(n){const s="Exception from ws connection when trying to send: "+Ge(n);c.logAction(this.logger,c.LOG_ERROR,"WebSocketTransport.send()",s),this.finish("disconnected",new S(s,5e4,500))}}onWsData(e){c.logAction(this.logger,c.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+e.length+"; type = "+typeof e);try{this.onProtocolMessage(ka(e,this.connectionManager.realtime._MsgPack,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin,this.format))}catch(t){c.logAction(this.logger,c.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+t.stack)}}onWsOpen(){c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")}onWsClose(e){let t,n;if(typeof e=="object"?(n=e.code,t=e.wasClean||n===1e3):(n=e,t=n==1e3),delete this.wsConnection,t){c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");const s=new S("Websocket closed",80003,400);this.finish("disconnected",s)}else{const s="Unclean disconnection of WebSocket ; code = "+n,r=new S(s,80003,400);c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.onWsClose()",s),this.finish("disconnected",r)}this.emit("disposed")}onWsError(e){c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+e.message),_.Config.nextTick(()=>{this.disconnect(Error(e.message))})}dispose(){c.logAction(this.logger,c.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;const e=this.wsConnection;e&&(e.onmessage=function(){},delete this.wsConnection,_.Config.nextTick(()=>{if(c.logAction(this.logger,c.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!e)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");e.close()}))}},Oi=Ya,Za=class{static subscribeFilter(e,t,n){const s=r=>{var a,g,b,R,A,L;const U={name:r.name,refTimeserial:(g=(a=r.extras)==null?void 0:a.ref)==null?void 0:g.timeserial,refType:(R=(b=r.extras)==null?void 0:b.ref)==null?void 0:R.type,isRef:!!((L=(A=r.extras)==null?void 0:A.ref)!=null&&L.timeserial),clientId:r.clientId};Object.entries(t).find(([F,P])=>P!==void 0?U[F]!==P:!1)||n(r)};this.addFilteredSubscription(e,t,n,s),e.subscriptions.on(s)}static addFilteredSubscription(e,t,n,s){var r;if(e.filteredSubscriptions||(e.filteredSubscriptions=new Map),e.filteredSubscriptions.has(n)){const a=e.filteredSubscriptions.get(n);a.set(t,((r=a==null?void 0:a.get(t))==null?void 0:r.concat(s))||[s])}else e.filteredSubscriptions.set(n,new Map([[t,[s]]]))}static getAndDeleteFilteredSubscriptions(e,t,n){if(!e.filteredSubscriptions)return[];if(!n&&t)return Array.from(e.filteredSubscriptions.entries()).map(([a,g])=>{var b;let R=g.get(t);return g.delete(t),g.size===0&&((b=e.filteredSubscriptions)==null||b.delete(a)),R}).reduce((a,g)=>g?a.concat(...g):a,[]);if(!n||!e.filteredSubscriptions.has(n))return[];const s=e.filteredSubscriptions.get(n);if(!t){const a=Array.from(s.values()).reduce((g,b)=>g.concat(...b),[]);return e.filteredSubscriptions.delete(n),a}let r=s.get(t);return s.delete(t),r||[]}},yt=class vr extends Va{constructor(t){var n;const s=vr._MsgPack;if(!s)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(V.objectifyOptions(t,!0,"Realtime",c.defaultLogger,fe(H({},li),{Crypto:(n=vr.Crypto)!=null?n:void 0,MsgPack:s,RealtimePresence:{RealtimePresence:Ja,PresenceMessage:zt,WirePresenceMessage:Gn},Annotations:{Annotation:Hn,WireAnnotation:_n,RealtimeAnnotations:vi,RestAnnotations:Ds},WebSocketTransport:Oi,MessageInteractions:Za})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(t){this._Crypto=t}};yt.Utils=xt,yt.ConnectionManager=Ri,yt.ProtocolMessage=_a,yt._Crypto=null,yt.Message=hi,yt.PresenceMessage=fi,yt.Annotation=gi,yt._MsgPack=null,yt._Http=Qe,yt._PresenceMap=Qs,yt._MessageEncoding=gs;var Zs=yt,Xs=Uint8Array,Wn=Uint32Array,er=Math.pow,Si=new Wn(8),Ti=[],Vn=new Wn(64);function Ei(e){return(e-(e|0))*er(2,32)|0}for(var $n=2,Fn=0;Fn<64;){for(tr=!0,ws=2;ws<=$n/2;ws++)$n%ws===0&&(tr=!1);tr&&(Fn<8&&(Si[Fn]=Ei(er($n,1/2))),Ti[Fn]=Ei(er($n,1/3)),Fn++),$n++}var tr,ws,Xa=!!new Xs(new Wn([1]).buffer)[0];function nr(e){return Xa?e>>>24|(e>>>16&255)<<8|(e&65280)<<8|e<<24:e}function Et(e,t){return e>>>t|e<<32-t}function vs(e){var t=Si.slice(),n=e.length,s=n*8,r=512-(s+64)%512-1+s+65,a=new Xs(r/8),g=new Wn(a.buffer);a.set(e,0),a[n]=128,g[g.length-1]=nr(s);for(var b,R=0;R<r/32;R+=16){var A=t.slice();for(b=0;b<64;b++){var L;if(b<16)L=nr(g[R+b]);else{var U=Vn[b-15],F=Vn[b-2];L=Vn[b-7]+Vn[b-16]+(Et(U,7)^Et(U,18)^U>>>3)+(Et(F,17)^Et(F,19)^F>>>10)}Vn[b]=L|=0;for(var P=(Et(A[4],6)^Et(A[4],11)^Et(A[4],25))+(A[4]&A[5]^~A[4]&A[6])+A[7]+L+Ti[b],ne=(Et(A[0],2)^Et(A[0],13)^Et(A[0],22))+(A[0]&A[1]^A[2]&(A[0]^A[1])),se=7;se>0;se--)A[se]=A[se-1];A[0]=P+ne|0,A[4]=A[4]+P|0}for(b=0;b<8;b++)t[b]=t[b]+A[b]|0}return new Xs(new Wn(t.map(function(ye){return nr(ye)})).buffer)}function ec(e,t){if(e.length>64&&(e=vs(e)),e.length<64){const b=new Uint8Array(64);b.set(e,0),e=b}for(var n=new Uint8Array(64),s=new Uint8Array(64),r=0;r<64;r++)n[r]=54^e[r],s[r]=92^e[r];var a=new Uint8Array(t.length+64);a.set(n,0),a.set(t,64);var g=new Uint8Array(96);return g.set(s,0),g.set(vs(a),64),vs(g)}var tc=class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(e){let t="";const n=this.base64CharSet,s=e.byteLength,r=s%3,a=s-r;let g,b,R,A,L;for(let U=0;U<a;U=U+3)L=e[U]<<16|e[U+1]<<8|e[U+2],g=(L&16515072)>>18,b=(L&258048)>>12,R=(L&4032)>>6,A=L&63,t+=n[g]+n[b]+n[R]+n[A];return r==1?(L=e[a],g=(L&252)>>2,b=(L&3)<<4,t+=n[g]+n[b]+"=="):r==2&&(L=e[a]<<8|e[a+1],g=(L&64512)>>10,b=(L&1008)>>4,R=(L&15)<<2,t+=n[g]+n[b]+n[R]+"="),t}base64ToArrayBuffer(e){const t=atob==null?void 0:atob(e),n=t.length,s=new Uint8Array(n);for(let r=0;r<n;r++){const a=t.charCodeAt(r);s[r]=a}return this.toArrayBuffer(s)}isBuffer(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}toBuffer(e){if(!ArrayBuffer)throw new Error("Can't convert to Buffer: browser does not support the necessary types");if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(this.toArrayBuffer(e));throw new Error("BufferUtils.toBuffer expected an ArrayBuffer or a view onto one")}toArrayBuffer(e){if(!ArrayBuffer)throw new Error("Can't convert to ArrayBuffer: browser does not support the necessary types");if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);throw new Error("BufferUtils.toArrayBuffer expected an ArrayBuffer or a view onto one")}base64Encode(e){return this.uint8ViewToBase64(this.toBuffer(e))}base64UrlEncode(e){return this.base64Encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}base64Decode(e){if(ArrayBuffer&&_.Config.atob)return this.base64ToArrayBuffer(e);throw new Error("Expected ArrayBuffer to exist and Platform.Config.atob to be configured")}hexEncode(e){return this.toBuffer(e).reduce((n,s)=>n+s.toString(16).padStart(2,"0"),"")}hexDecode(e){if(e.length%2!==0)throw new Error("Can't create a byte array from a hex string of odd length");const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(2*n,2*(n+1)),16);return this.toArrayBuffer(t)}utf8Encode(e){if(_.Config.TextEncoder){const t=new _.Config.TextEncoder().encode(e);return this.toArrayBuffer(t)}else throw new Error("Expected TextEncoder to be configured")}utf8Decode(e){if(!this.isBuffer(e))throw new Error("Expected input of utf8decode to be an arraybuffer or typed array");if(TextDecoder)return new TextDecoder().decode(e);throw new Error("Expected TextDecoder to be configured")}areBuffersEqual(e,t){if(!e||!t)return!1;const n=this.toArrayBuffer(e),s=this.toArrayBuffer(t);if(n.byteLength!=s.byteLength)return!1;const r=new Uint8Array(n),a=new Uint8Array(s);for(var g=0;g<r.length;g++)if(r[g]!=a[g])return!1;return!0}byteLength(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}arrayBufferViewToBuffer(e){return this.toArrayBuffer(e)}concat(e){const t=e.reduce((r,a)=>r+a.byteLength,0),n=new Uint8Array(t);let s=0;for(const r of e){const a=this.toBuffer(r);n.set(a,s),s+=a.byteLength}return n.buffer}sha256(e){const t=vs(this.toBuffer(e));return this.toArrayBuffer(t)}hmacSha256(e,t){const n=ec(this.toBuffer(t),this.toBuffer(e));return this.toArrayBuffer(n)}},Mi=new tc,nc=function(e,t){var n="aes",s=256,r="cbc",a=16;function g(F){if(F.algorithm==="aes"&&F.mode==="cbc"){if(F.keyLength===128||F.keyLength===256)return;throw new Error("Unsupported key length "+F.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}}function b(F){return F.replace("_","/").replace("-","+")}function R(F){return F instanceof A}class A{constructor(P,ne,se,ye){this.algorithm=P,this.keyLength=ne,this.mode=se,this.key=ye}}class L{static getDefaultParams(P){var ne;if(!P.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof P.key=="string"?ne=t.toArrayBuffer(t.base64Decode(b(P.key))):P.key instanceof ArrayBuffer?ne=P.key:ne=t.toArrayBuffer(P.key);var se=P.algorithm||n,ye=ne.byteLength*8,qe=P.mode||r,Ve=new A(se,ye,qe,ne);if(P.keyLength&&P.keyLength!==Ve.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+P.keyLength+" was specified, but the key actually has length "+Ve.keyLength);return g(Ve),Ve}static async generateRandomKey(P){try{return e.getRandomArrayBuffer((P||s)/8)}catch(ne){throw new S("Failed to generate random key: "+ne.message,400,5e4)}}static getCipher(P,ne){var se,ye=R(P)?P:this.getDefaultParams(P);return{cipherParams:ye,cipher:new U(ye,(se=P.iv)!=null?se:null,ne)}}}L.CipherParams=A;class U{constructor(P,ne,se){if(this.logger=se,!crypto.subtle)throw isSecureContext?new Error("Crypto operations are not possible since the browser’s SubtleCrypto class is unavailable (reason unknown)."):new Error("Crypto operations are is not possible since the current environment is a non-secure context and hence the browser’s SubtleCrypto class is not available.");this.algorithm=P.algorithm+"-"+String(P.keyLength)+"-"+P.mode,this.webCryptoAlgorithm=P.algorithm+"-"+P.mode,this.key=t.toArrayBuffer(P.key),this.iv=ne?t.toArrayBuffer(ne):null}concat(P,ne){const se=new ArrayBuffer(P.byteLength+ne.byteLength),ye=new DataView(se),qe=new DataView(t.toArrayBuffer(P));for(let Je=0;Je<qe.byteLength;Je++)ye.setInt8(Je,qe.getInt8(Je));const Ve=new DataView(t.toArrayBuffer(ne));for(let Je=0;Je<Ve.byteLength;Je++)ye.setInt8(qe.byteLength+Je,Ve.getInt8(Je));return se}async encrypt(P){c.logAction(this.logger,c.LOG_MICRO,"CBCCipher.encrypt()","");const ne=await this.getIv(),se=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["encrypt"]),ye=await crypto.subtle.encrypt({name:this.webCryptoAlgorithm,iv:ne},se,P);return this.concat(ne,ye)}async decrypt(P){c.logAction(this.logger,c.LOG_MICRO,"CBCCipher.decrypt()","");const ne=t.toArrayBuffer(P),se=ne.slice(0,a),ye=ne.slice(a),qe=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["decrypt"]);return crypto.subtle.decrypt({name:this.webCryptoAlgorithm,iv:se},qe,ye)}async getIv(){if(this.iv){var P=this.iv;return this.iv=null,P}const ne=await e.getRandomArrayBuffer(a);return t.toArrayBuffer(ne)}}return L},Ii=(e=>(e[e.REQ_SEND=0]="REQ_SEND",e[e.REQ_RECV=1]="REQ_RECV",e[e.REQ_RECV_POLL=2]="REQ_RECV_POLL",e[e.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",e))(Ii||{}),Bt=Ii;function Pi(){return new S("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var zn,Li=(zn=class{constructor(e){this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1;var t;this.client=e??null;const n=(e==null?void 0:e.options.connectivityCheckUrl)||V.connectivityCheckUrl,s=(t=e==null?void 0:e.options.connectivityCheckParams)!=null?t:null,r=!(e!=null&&e.options.connectivityCheckUrl),a=H(H({},Li.bundledRequestImplementations),e==null?void 0:e._additionalHTTPRequestImplementations),g=a.XHRRequest,b=a.FetchRequest,R=!!(g||b);if(!R)throw Pi();_.Config.xhrSupported&&g?(this.supportsAuthHeaders=!0,this.Request=async function(A,L,U,F,P){return new Promise(ne=>{var se;const ye=g.createRequest(L,U,F,P,Bt.REQ_SEND,(se=e&&e.options.timeouts)!=null?se:null,this.logger,A);ye.once("complete",(qe,Ve,Je,_e,mt)=>ne({error:qe,body:Ve,headers:Je,unpacked:_e,statusCode:mt})),ye.exec()})},e!=null&&e.options.disableConnectivityCheck?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var A;c.logAction(this.logger,c.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+n);const L=await this.doUri(K.Get,n,null,null,s);let U=!1;return r?U=!L.error&&((A=L.body)==null?void 0:A.replace(/\n/,""))=="yes":U=!L.error&&ie(L.statusCode),c.logAction(this.logger,c.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+U),U}):_.Config.fetchSupported&&b?(this.supportsAuthHeaders=!0,this.Request=async(A,L,U,F,P)=>b(A,e??null,L,U,F,P),e!=null&&e.options.disableConnectivityCheck?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var A;c.logAction(this.logger,c.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Sending; "+n);const L=await this.doUri(K.Get,n,null,null,null),U=!L.error&&((A=L.body)==null?void 0:A.replace(/\n/,""))=="yes";return c.logAction(this.logger,c.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Result: "+U),U}):this.Request=async()=>({error:R?new et("no supported HTTP transports available",null,400):Pi()})}get logger(){var e,t;return(t=(e=this.client)==null?void 0:e.logger)!=null?t:c.defaultLogger}async doUri(e,t,n,s,r){return this.Request?this.Request(e,t,n,r,s):{error:new et("Request invoked before assigned to",null,500)}}shouldFallback(e){const t=e.statusCode;return t===408&&!e.code||t===400&&!e.code||t>=500&&t<=504}},zn.methods=[K.Get,K.Delete,K.Post,K.Put,K.Patch],zn.methodsWithoutBody=[K.Get,K.Delete],zn.methodsWithBody=[K.Post,K.Put,K.Patch],zn),Ui=Li,Rn="ablyjs-storage-test",Cn=typeof Kt<"u"?Kt:typeof window<"u"?window:self,sc=class{constructor(){try{Cn.sessionStorage.setItem(Rn,Rn),Cn.sessionStorage.removeItem(Rn),this.sessionSupported=!0}catch{this.sessionSupported=!1}try{Cn.localStorage.setItem(Rn,Rn),Cn.localStorage.removeItem(Rn),this.localSupported=!0}catch{this.localSupported=!1}}get(e){return this._get(e,!1)}getSession(e){return this._get(e,!0)}remove(e){return this._remove(e,!1)}removeSession(e){return this._remove(e,!0)}set(e,t,n){return this._set(e,t,n,!1)}setSession(e,t,n){return this._set(e,t,n,!0)}_set(e,t,n,s){const r={value:t};return n&&(r.expires=Date.now()+n),this.storageInterface(s).setItem(e,JSON.stringify(r))}_get(e,t){if(t&&!this.sessionSupported)throw new Error("Session Storage not supported");if(!t&&!this.localSupported)throw new Error("Local Storage not supported");const n=this.storageInterface(t).getItem(e);if(!n)return null;const s=JSON.parse(n);return s.expires&&s.expires<Date.now()?(this.storageInterface(t).removeItem(e),null):s.value}_remove(e,t){return this.storageInterface(t).removeItem(e)}storageInterface(e){return e?Cn.sessionStorage:Cn.localStorage}},Bi=new sc,tt=Ut(),rc=typeof EdgeRuntime=="string";typeof Window>"u"&&typeof WorkerGlobalScope>"u"&&!rc&&console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");function ic(){const e=tt.location;return!tt.WebSocket||!e||!e.origin||e.origin.indexOf("http")>-1}function oc(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}var ac=tt.navigator&&tt.navigator.userAgent.toString(),cc=tt.location&&tt.location.href,lc={agent:"browser",logTimestamps:!0,userAgent:ac,currentUrl:cc,binaryType:"arraybuffer",WebSocket:tt.WebSocket,fetchSupported:!!tt.fetch,xhrSupported:tt.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:ic(),useProtocolHeartbeats:!0,supportsBinary:!!tt.TextDecoder,preferBinary:!1,ArrayBuffer:tt.ArrayBuffer,atob:tt.atob,nextTick:typeof tt.queueMicrotask=="function"?e=>tt.queueMicrotask(e):e=>Promise.resolve().then(e),addEventListener:tt.addEventListener,inspect:JSON.stringify,stringByteSize:function(e){return tt.TextDecoder&&new tt.TextEncoder().encode(e).length||e.length},TextEncoder:tt.TextEncoder,TextDecoder:tt.TextDecoder,getRandomArrayBuffer:async function(e){const t=new Uint8Array(e);return tt.crypto.getRandomValues(t),t.buffer},isWebworker:oc(),push:{platform:"browser",formFactor:"desktop",storage:Bi}},Ni=lc;function hc(e){const t=[80015,80017,80030];return e.code?Oe.isTokenErr(e)?!1:t.includes(e.code)?!0:e.code>=4e4&&e.code<5e4:!1}function sr(e){return hc(e)?[ut({action:X.ERROR,error:e})]:[ut({action:X.DISCONNECTED,error:e})]}var fc=class extends An{constructor(e,t,n){super(e,t,n,!0),this.onAuthUpdated=s=>{this.authParams={access_token:s.token}},this.stream="stream"in n?n.stream:!0,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}connect(){c.logAction(this.logger,c.LOG_MINOR,"CometTransport.connect()","starting"),An.prototype.connect.call(this);const e=this.params,t=e.options,n=e.host||t.primaryDomain,s=V.getPort(t),r=t.tls?"https://":"http://";this.baseUri=r+n+":"+s+"/comet/";const a=this.baseUri+"connect";c.logAction(this.logger,c.LOG_MINOR,"CometTransport.connect()","uri: "+a),ot(this.auth.getAuthParams(),(g,b)=>{if(g){this.disconnect(g);return}if(this.isDisposed)return;this.authParams=b;const R=this.params.getConnectParams(b);"stream"in R&&(this.stream=R.stream),c.logAction(this.logger,c.LOG_MINOR,"CometTransport.connect()","connectParams:"+Ot(R));let A=!1;const L=this.recvRequest=this.createRequest(a,null,R,null,this.stream?Bt.REQ_RECV_STREAM:Bt.REQ_RECV);L.on("data",U=>{this.recvRequest&&(A||(A=!0,this.emit("preconnect")),this.onData(U))}),L.on("complete",U=>{if(this.recvRequest||(U=U||new S("Request cancelled",80003,400)),this.recvRequest=null,!A&&!U&&(A=!0,this.emit("preconnect")),this.onActivity(),U){U.code?this.onData(sr(U)):this.disconnect(U);return}_.Config.nextTick(()=>{this.recv()})}),L.exec()})}requestClose(){c.logAction(this.logger,c.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)}requestDisconnect(){c.logAction(this.logger,c.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)}_requestCloseOrDisconnect(e){const t=e?this.closeUri:this.disconnectUri;if(t){const n=this.createRequest(t,null,this.authParams,null,Bt.REQ_SEND);n.on("complete",s=>{s&&(c.logAction(this.logger,c.LOG_ERROR,"CometTransport.request"+(e?"Close()":"Disconnect()"),"request returned err = "+Ge(s)),this.finish("disconnected",s))}),n.exec()}}dispose(){c.logAction(this.logger,c.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(c.logAction(this.logger,c.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",ln.disconnected()),_.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(e){var t;if(this.isDisposed)return;const n=(t=e.connectionDetails)==null?void 0:t.connectionKey;An.prototype.onConnect.call(this,e);const s=this.baseUri+n;c.logAction(this.logger,c.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+s),this.sendUri=s+"/send",this.recvUri=s+"/recv",this.closeUri=s+"/close",this.disconnectUri=s+"/disconnect"}send(e){if(this.sendRequest){this.pendingItems=this.pendingItems||[],this.pendingItems.push(e);return}const t=this.pendingItems||[];t.push(e),this.pendingItems=null,this.sendItems(t)}sendAnyPending(){const e=this.pendingItems;e&&(this.pendingItems=null,this.sendItems(e))}sendItems(e){const t=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(e),Bt.REQ_SEND);t.on("complete",(n,s)=>{if(n&&c.logAction(this.logger,c.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+Ge(n)),this.sendRequest=null,n){n.code?this.onData(sr(n)):this.disconnect(n);return}s&&this.onData(s),this.pendingItems&&_.Config.nextTick(()=>{this.sendRequest||this.sendAnyPending()})}),t.exec()}recv(){if(this.recvRequest||!this.isConnected)return;const e=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?Bt.REQ_RECV_STREAM:Bt.REQ_RECV_POLL);e.on("data",t=>{this.onData(t)}),e.on("complete",t=>{if(this.recvRequest=null,this.onActivity(),t){t.code?this.onData(sr(t)):this.disconnect(t);return}_.Config.nextTick(()=>{this.recv()})}),e.exec()}onData(e){try{const t=this.decodeResponse(e);if(t&&t.length)for(let n=0;n<t.length;n++)this.onProtocolMessage(js(t[n],this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin))}catch(t){c.logAction(this.logger,c.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+t.stack)}}encodeRequest(e){return JSON.stringify(e)}decodeResponse(e){return typeof e=="string"?JSON.parse(e):e}},uc=fc;function dc(e,t){return Dt(sn(t)).includes("x-ably-errorcode")}function pc(e,t){if(dc(e,t))return e.error&&S.fromValues(e.error)}var gc=function(){},mc=0,Gi={};function yc(e,t){return e.getResponseHeader&&e.getResponseHeader(t)}function bc(e){return e.getResponseHeader&&(e.getResponseHeader("transfer-encoding")||!e.getResponseHeader("content-length"))}function xc(e){const t=e.getAllResponseHeaders().trim().split(`\r
13
13
  `),n={};for(let s=0;s<t.length;s++){const r=t[s].split(":").map(a=>a.trim());n[r[0].toLowerCase()]=r[1]}return n}var wc=class go extends Se{constructor(t,n,s,r,a,g,b,R){super(b),s=s||{},s.rnd=Ht(),this.uri=t+Ot(s),this.headers=n||{},this.body=r,this.method=R?R.toUpperCase():Ke(r)?"GET":"POST",this.requestMode=a,this.timeouts=g,this.timedOut=!1,this.requestComplete=!1,this.id=String(++mc),Gi[this.id]=this}static createRequest(t,n,s,r,a,g,b,R){const A=g||V.TIMEOUTS;return new go(t,n,Pt(s),r,a,A,b,R)}complete(t,n,s,r,a){this.requestComplete||(this.requestComplete=!0,!t&&n&&this.emit("data",n),this.emit("complete",t,n,s,r,a),this.dispose())}abort(){this.dispose()}exec(){let t=this.headers;const n=this.requestMode==Bt.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,s=this.timer=setTimeout(()=>{this.timedOut=!0,a.abort()},n),r=this.method,a=this.xhr=new XMLHttpRequest,g=t.accept;let b=this.body,R="text";g?g.indexOf("application/x-msgpack")===0&&(R="arraybuffer"):t.accept="application/json",b&&(t["content-type"]||(t["content-type"]="application/json")).indexOf("application/json")>-1&&typeof b!="string"&&(b=JSON.stringify(b)),a.open(r,this.uri,!0),a.responseType=R,"authorization"in t&&(a.withCredentials=!0);for(const _e in t)a.setRequestHeader(_e,t[_e]);const A=(_e,mt,rt,Yn)=>{var On;let ar=mt+" (event type: "+_e.type+")";(On=this==null?void 0:this.xhr)!=null&&On.statusText&&(ar+=", current statusText is "+this.xhr.statusText),c.logAction(this.logger,c.LOG_ERROR,"Request.on"+_e.type+"()",ar),this.complete(new et(ar,rt,Yn))};a.onerror=_e=>{A(_e,"XHR error occurred",null,400)},a.onabort=_e=>{this.timedOut?A(_e,"Request aborted due to request timeout expiring",null,408):A(_e,"Request cancelled",null,400)},a.ontimeout=_e=>{A(_e,"Request timed out",null,408)};let L,U,F,P=0,ne=!1;const se=()=>{if(clearTimeout(s),F=U<400,U==204){this.complete(null,null,null,null,U);return}L=this.requestMode==Bt.REQ_RECV_STREAM&&F&&bc(a)},ye=()=>{let _e;try{const rt=yc(a,"content-type");if(rt?rt.indexOf("application/json")>=0:a.responseType=="text"){const On=a.responseType==="arraybuffer"?_.BufferUtils.utf8Decode(a.response):String(a.responseText);On.length?_e=JSON.parse(On):_e=On,ne=!0}else _e=a.response;_e.response!==void 0?(U=_e.statusCode,F=U<400,t=_e.headers,_e=_e.response):t=xc(a)}catch(rt){this.complete(new et("Malformed response body from server: "+rt.message,null,400));return}if(F||Array.isArray(_e)){this.complete(null,_e,t,ne,U);return}let mt=pc(_e,t);mt||(mt=new et("Error response received from server: "+U+" body was: "+_.Config.inspect(_e),null,U)),this.complete(mt,_e,t,ne,U)};function qe(){const _e=a.responseText,mt=_e.length-1;let rt,Yn;for(;P<mt&&(rt=_e.indexOf(`
14
- `,P))>-1;)Yn=_e.slice(P,rt),P=rt+1,Ve(Yn)}const Ve=_e=>{try{_e=JSON.parse(_e)}catch(mt){this.complete(new et("Malformed response body from server: "+mt.message,null,400));return}this.emit("data",_e)},Je=()=>{qe(),this.streamComplete=!0,_.Config.nextTick(()=>{this.complete()})};a.onreadystatechange=()=>{const _e=a.readyState;_e<3||a.status!==0&&(U===void 0&&(U=a.status,se()),_e==3&&L?qe():_e==4&&(L?Je():ye()))},a.send(b)}dispose(){const t=this.xhr;if(t){t.onreadystatechange=t.onerror=t.onabort=t.ontimeout=gc,this.xhr=null;const n=this.timer;n&&(clearTimeout(n),this.timer=null),this.requestComplete||t.abort()}delete Gi[this.id]}},qi=wc,Hi=dt.XhrPolling,vc=class extends uc{constructor(e,t,n){super(e,t,n),this.shortName=Hi,n.stream=!1,this.shortName=Hi}static isAvailable(){return!!(_.Config.xhrSupported&&_.Config.allowComet)}toString(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected}createRequest(e,t,n,s,r){return qi.createRequest(e,t,n,s,r,this.timeouts,this.logger)}},kc=vc,_c=["xhr_polling"],Ac={order:_c,bundledImplementations:{web_socket:Oi,xhr_polling:kc}},Rc=Ac,Cc={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[dt.XhrPolling,dt.WebSocket]},Oc=Cc;function Sc(e){if(e===void 0)return"undefined";let t,n;if(e instanceof ArrayBuffer?(n="ArrayBuffer",t=new DataView(e)):e instanceof DataView&&(n="DataView",t=e),!t)return JSON.stringify(e);const s=[];for(let r=0;r<e.byteLength;r++){if(r>20){s.push("...");break}let a=t.getUint8(r).toString(16);a.length===1&&(a="0"+a),s.push(a)}return"<"+n+" "+s.join(" ")+">"}function Jn(e,t,n){const r=new TextEncoder().encode(n);for(let a=0;a<r.length;a++)e.setUint8(t+a,r[a])}function Di(e,t,n){return new TextDecoder().decode(e.buffer.slice(t,t+n))}function rr(e){return new TextEncoder().encode(e).length}function Tc(e,t){const n=Qn(e,t);if(n===0)return;const s=new ArrayBuffer(n),r=new DataView(s);return Kn(e,r,0,t),s}var ir=65536*65536,ji=1/ir;function Ec(e,t){return t=t||0,e.getInt32(t)*ir+e.getUint32(t+4)}function Mc(e,t){return t=t||0,e.getUint32(t)*ir+e.getUint32(t+4)}function Ic(e,t,n){n<9223372036854776e3?(e.setInt32(t,Math.floor(n*ji)),e.setInt32(t+4,n&-1)):(e.setUint32(t,2147483647),e.setUint32(t+4,2147483647))}function Pc(e,t,n){n<18446744073709552e3?(e.setUint32(t,Math.floor(n*ji)),e.setInt32(t+4,n&-1)):(e.setUint32(t,4294967295),e.setUint32(t+4,4294967295))}var Lc=class{constructor(e,t){this.map=n=>{const s={};for(let r=0;r<n;r++){const a=this.parse();s[a]=this.parse()}return s},this.bin=n=>{const s=new ArrayBuffer(n);return new Uint8Array(s).set(new Uint8Array(this.view.buffer,this.offset,n),0),this.offset+=n,s},this.buf=this.bin,this.str=n=>{const s=Di(this.view,this.offset,n);return this.offset+=n,s},this.array=n=>{const s=new Array(n);for(let r=0;r<n;r++)s[r]=this.parse();return s},this.ext=n=>(this.offset+=n,{type:this.view.getInt8(this.offset),data:this.buf(n)}),this.parse=()=>{const n=this.view.getUint8(this.offset);let s,r;if((n&128)===0)return this.offset++,n;if((n&240)===128)return r=n&15,this.offset++,this.map(r);if((n&240)===144)return r=n&15,this.offset++,this.array(r);if((n&224)===160)return r=n&31,this.offset++,this.str(r);if((n&224)===224)return s=this.view.getInt8(this.offset),this.offset++,s;switch(n){case 192:return this.offset++,null;case 193:this.offset++;return;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return r=this.view.getUint8(this.offset+1),this.offset+=2,this.bin(r);case 197:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.bin(r);case 198:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.bin(r);case 199:return r=this.view.getUint8(this.offset+1),this.offset+=2,this.ext(r);case 200:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.ext(r);case 201:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.ext(r);case 202:return s=this.view.getFloat32(this.offset+1),this.offset+=5,s;case 203:return s=this.view.getFloat64(this.offset+1),this.offset+=9,s;case 204:return s=this.view.getUint8(this.offset+1),this.offset+=2,s;case 205:return s=this.view.getUint16(this.offset+1),this.offset+=3,s;case 206:return s=this.view.getUint32(this.offset+1),this.offset+=5,s;case 207:return s=Mc(this.view,this.offset+1),this.offset+=9,s;case 208:return s=this.view.getInt8(this.offset+1),this.offset+=2,s;case 209:return s=this.view.getInt16(this.offset+1),this.offset+=3,s;case 210:return s=this.view.getInt32(this.offset+1),this.offset+=5,s;case 211:return s=Ec(this.view,this.offset+1),this.offset+=9,s;case 212:return r=1,this.offset++,this.ext(r);case 213:return r=2,this.offset++,this.ext(r);case 214:return r=4,this.offset++,this.ext(r);case 215:return r=8,this.offset++,this.ext(r);case 216:return r=16,this.offset++,this.ext(r);case 217:return r=this.view.getUint8(this.offset+1),this.offset+=2,this.str(r);case 218:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.str(r);case 219:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.str(r);case 220:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.array(r);case 221:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.array(r);case 222:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.map(r);case 223:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.map(r)}throw new Error("Unknown type 0x"+n.toString(16))},this.offset=t||0,this.view=e}};function Uc(e){const t=new DataView(e),n=new Lc(t),s=n.parse();if(n.offset!==e.byteLength)throw new Error(e.byteLength-n.offset+" trailing bytes");return s}function Wi(e,t){return Object.keys(e).filter(function(n){const s=e[n],r=typeof s;return(!t||s!=null)&&(r!=="function"||!!s.toJSON)})}function Kn(e,t,n,s){const r=typeof e;if(typeof e=="string"){const a=rr(e);if(a<32)return t.setUint8(n,a|160),Jn(t,n+1,e),1+a;if(a<256)return t.setUint8(n,217),t.setUint8(n+1,a),Jn(t,n+2,e),2+a;if(a<65536)return t.setUint8(n,218),t.setUint16(n+1,a),Jn(t,n+3,e),3+a;if(a<4294967296)return t.setUint8(n,219),t.setUint32(n+1,a),Jn(t,n+5,e),5+a}if(ArrayBuffer.isView&&ArrayBuffer.isView(e)&&(e=e.buffer),e instanceof ArrayBuffer){const a=e.byteLength;if(a<256)return t.setUint8(n,196),t.setUint8(n+1,a),new Uint8Array(t.buffer).set(new Uint8Array(e),n+2),2+a;if(a<65536)return t.setUint8(n,197),t.setUint16(n+1,a),new Uint8Array(t.buffer).set(new Uint8Array(e),n+3),3+a;if(a<4294967296)return t.setUint8(n,198),t.setUint32(n+1,a),new Uint8Array(t.buffer).set(new Uint8Array(e),n+5),5+a}if(typeof e=="number"){if(Math.floor(e)!==e)return t.setUint8(n,203),t.setFloat64(n+1,e),9;if(e>=0){if(e<128)return t.setUint8(n,e),1;if(e<256)return t.setUint8(n,204),t.setUint8(n+1,e),2;if(e<65536)return t.setUint8(n,205),t.setUint16(n+1,e),3;if(e<4294967296)return t.setUint8(n,206),t.setUint32(n+1,e),5;if(e<18446744073709552e3)return t.setUint8(n,207),Pc(t,n+1,e),9;throw new Error("Number too big 0x"+e.toString(16))}if(e>=-32)return t.setInt8(n,e),1;if(e>=-128)return t.setUint8(n,208),t.setInt8(n+1,e),2;if(e>=-32768)return t.setUint8(n,209),t.setInt16(n+1,e),3;if(e>=-2147483648)return t.setUint8(n,210),t.setInt32(n+1,e),5;if(e>=-9223372036854776e3)return t.setUint8(n,211),Ic(t,n+1,e),9;throw new Error("Number too small -0x"+(-e).toString(16).substr(1))}if(r==="undefined")return s?0:(t.setUint8(n,212),t.setUint8(n+1,0),t.setUint8(n+2,0),3);if(e===null)return s?0:(t.setUint8(n,192),1);if(r==="boolean")return t.setUint8(n,e?195:194),1;if(typeof e.toJSON=="function")return Kn(e.toJSON(),t,n,s);if(r==="object"){let a,g=0,b;const R=Array.isArray(e);if(R?a=e.length:(b=Wi(e,s),a=b.length),a<16?(t.setUint8(n,a|(R?144:128)),g=1):a<65536?(t.setUint8(n,R?220:222),t.setUint16(n+1,a),g=3):a<4294967296&&(t.setUint8(n,R?221:223),t.setUint32(n+1,a),g=5),R)for(let A=0;A<a;A++)g+=Kn(e[A],t,n+g,s);else if(b)for(let A=0;A<a;A++){const L=b[A];g+=Kn(L,t,n+g),g+=Kn(e[L],t,n+g,s)}return g}if(r==="function")return 0;throw new Error("Unknown type "+r)}function Qn(e,t){const n=typeof e;if(n==="string"){const s=rr(e);if(s<32)return 1+s;if(s<256)return 2+s;if(s<65536)return 3+s;if(s<4294967296)return 5+s}if(ArrayBuffer.isView&&ArrayBuffer.isView(e)&&(e=e.buffer),e instanceof ArrayBuffer){const s=e.byteLength;if(s<256)return 2+s;if(s<65536)return 3+s;if(s<4294967296)return 5+s}if(typeof e=="number"){if(Math.floor(e)!==e)return 9;if(e>=0){if(e<128)return 1;if(e<256)return 2;if(e<65536)return 3;if(e<4294967296)return 5;if(e<18446744073709552e3)return 9;throw new Error("Number too big 0x"+e.toString(16))}if(e>=-32)return 1;if(e>=-128)return 2;if(e>=-32768)return 3;if(e>=-2147483648)return 5;if(e>=-9223372036854776e3)return 9;throw new Error("Number too small -0x"+e.toString(16).substr(1))}if(n==="boolean")return 1;if(e===null)return t?0:1;if(e===void 0)return t?0:3;if(typeof e.toJSON=="function")return Qn(e.toJSON(),t);if(n==="object"){let s,r=0;if(Array.isArray(e)){s=e.length;for(let a=0;a<s;a++)r+=Qn(e[a],t)}else{const a=Wi(e,t);s=a.length;for(let g=0;g<s;g++){const b=a[g];r+=Qn(b)+Qn(e[b],t)}}if(s<16)return 1+r;if(s<65536)return 3+r;if(s<4294967296)return 5+r;throw new Error("Array or object too long 0x"+s.toString(16))}if(n==="function")return 0;throw new Error("Unknown type "+n)}var or={encode:Tc,decode:Uc,inspect:Sc,utf8Write:Jn,utf8Read:Di,utf8ByteCount:rr};function Bc(e,t){return!!t.get("x-ably-errorcode")}function Nc(e,t){if(Bc(e,t))return e.error&&S.fromValues(e.error)}function Gc(e){const t={};return e.forEach((n,s)=>{t[s]=n}),t}async function qc(e,t,n,s,r,a){const g=new Headers(s||{}),b=e?e.toUpperCase():Ke(a)?"GET":"POST",R=new AbortController;let A;const L=new Promise(P=>{A=setTimeout(()=>{R.abort(),P({error:new et("Request timed out",null,408)})},t?t.options.timeouts.httpRequestTimeout:V.TIMEOUTS.httpRequestTimeout)}),U={method:b,headers:g,body:a,signal:R.signal};_.Config.isWebworker||(U.credentials=g.has("authorization")?"include":"same-origin");const F=(async()=>{try{const P=new URLSearchParams(r||{});P.set("rnd",Ht());const ne=n+"?"+P,se=await Ut().fetch(ne,U);if(clearTimeout(A),se.status==204)return{error:null,statusCode:se.status};const ye=se.headers.get("Content-Type");let qe;ye&&ye.indexOf("application/x-msgpack")>-1?qe=await se.arrayBuffer():ye&&ye.indexOf("application/json")>-1?qe=await se.json():qe=await se.text();const Ve=!!ye&&ye.indexOf("application/x-msgpack")===-1,Je=Gc(se.headers);return se.ok?{error:null,body:qe,headers:Je,unpacked:Ve,statusCode:se.status}:{error:Nc(qe,se.headers)||new et("Error response received from server: "+se.status+" body was: "+_.Config.inspect(qe),null,se.status),body:qe,headers:Je,unpacked:Ve,statusCode:se.status}}catch(P){return clearTimeout(A),{error:P}}})();return Promise.race([L,F])}var Hc={XHRRequest:qi,FetchRequest:qc},Vi=nc(Ni,Mi);_.Crypto=Vi,_.BufferUtils=Mi,_.Http=Ui,_.Config=Ni,_.Transports=Rc,_.WebStorage=Bi;for(const e of[Fs,Zs])e.Crypto=Vi,e._MsgPack=or;Ui.bundledRequestImplementations=Hc,c.initLogHandlers(),_.Defaults=xe(Oc),_.Config.agent&&(_.Defaults.agent+=" "+_.Config.agent);var Dc={ErrorInfo:S,Rest:Fs,Realtime:Zs,msgpack:or,makeProtocolMessageFromDeserialized:xi};if(typeof p.exports=="object"&&typeof l=="object"){var jc=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Object.getOwnPropertyNames(t))!Object.prototype.hasOwnProperty.call(e,r)&&r!==n&&Object.defineProperty(e,r,{get:()=>t[r],enumerable:!(s=Object.getOwnPropertyDescriptor(t,r))||s.enumerable});return e};p.exports=jc(p.exports,l)}return p.exports})})(Cs)),Cs.exports}var Pl=Il();class Ll{constructor(o){ce(this,"ably",null);ce(this,"channel",null);ce(this,"opts");ce(this,"_connected",!1);ce(this,"clientId",null);ce(this,"messageHandlers",[]);ce(this,"peerJoinedHandlers",[]);ce(this,"peerLeftHandlers",[]);ce(this,"errorHandlers",[]);ce(this,"disconnectHandlers",[]);if(!o.key&&!o.token)throw new Error("Ably API key or token is required");this.opts=o}get connected(){return this._connected}async connect(o,l){this.clientId=`airloom-${l}-${Date.now()}`;const p={clientId:this.clientId};this.opts.key?p.key=this.opts.key:p.token=this.opts.token,this.ably=new Pl.Realtime(p),await new Promise((k,v)=>{this.ably.connection.once("connected",()=>k()),this.ably.connection.once("failed",I=>{var M;v(new Error(((M=I==null?void 0:I.reason)==null?void 0:M.message)??"Ably connection failed"))})}),this._connected=!0,this.ably.connection.on("disconnected",()=>{this._connected=!1,this.disconnectHandlers.forEach(k=>k())}),this.ably.connection.on("connected",()=>{this._connected=!0,this.channel&&this.channel.presence.get().then(k=>{k.some(I=>I.clientId!==this.clientId)&&this.peerJoinedHandlers.forEach(I=>I())}).catch(()=>{})}),this.ably.connection.on("failed",k=>{var I;this._connected=!1;const v=new Error(((I=k==null?void 0:k.reason)==null?void 0:I.message)??"Ably connection failed");this.errorHandlers.forEach(M=>M(v))}),this.channel=this.ably.channels.get(`airloom:${o}`),this.channel.subscribe("forward",k=>{k.clientId!==this.clientId&&typeof k.data=="string"&&this.messageHandlers.forEach(v=>v(k.data))}),this.channel.presence.subscribe("enter",k=>{k.clientId!==this.clientId&&this.peerJoinedHandlers.forEach(v=>v())}),this.channel.presence.subscribe("leave",k=>{k.clientId!==this.clientId&&this.peerLeftHandlers.forEach(v=>v())}),await this.channel.presence.enter({role:l}),(await this.channel.presence.get()).some(k=>k.clientId!==this.clientId)&&this.peerJoinedHandlers.forEach(k=>k())}send(o){!this.channel||!this._connected||this.channel.publish("forward",o)}onMessage(o){this.messageHandlers.push(o)}onPeerJoined(o){this.peerJoinedHandlers.push(o)}onPeerLeft(o){this.peerLeftHandlers.push(o)}onError(o){this.errorHandlers.push(o)}onDisconnect(o){this.disconnectHandlers.push(o)}close(){var o,l,p;(o=this.channel)==null||o.presence.leave().catch(()=>{}),(l=this.channel)==null||l.detach().catch(()=>{});try{(p=this.ably)==null||p.close()}catch{}this.channel=null,this.ably=null,this._connected=!1}}function Tr(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var un=Tr();function mo(f){un=f}var hn={exec:()=>null};function Be(f,o=""){let l=typeof f=="string"?f:f.source,p={replace:(m,x)=>{let k=typeof x=="string"?x:x.source;return k=k.replace(lt.caret,"$1"),l=l.replace(m,k),p},getRegex:()=>new RegExp(l,o)};return p}var Ul=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),lt={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:f=>new RegExp(`^( {0,3}${f})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:f=>new RegExp(`^ {0,${Math.min(3,f-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:f=>new RegExp(`^ {0,${Math.min(3,f-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:f=>new RegExp(`^ {0,${Math.min(3,f-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:f=>new RegExp(`^ {0,${Math.min(3,f-1)}}#`),htmlBeginRegex:f=>new RegExp(`^ {0,${Math.min(3,f-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:f=>new RegExp(`^ {0,${Math.min(3,f-1)}}>`)},Bl=/^(?:[ \t]*(?:\n|$))+/,Nl=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Gl=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,as=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ql=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Er=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,yo=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,bo=Be(yo).replace(/bull/g,Er).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Hl=Be(yo).replace(/bull/g,Er).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Mr=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Dl=/^[^\n]+/,Ir=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,jl=Be(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ir).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Wl=Be(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Er).getRegex(),Us="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Pr=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Vl=Be("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Pr).replace("tag",Us).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),xo=Be(Mr).replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Us).getRegex(),$l=Be(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",xo).getRegex(),Lr={blockquote:$l,code:Nl,def:jl,fences:Gl,heading:ql,hr:as,html:Vl,lheading:bo,list:Wl,newline:Bl,paragraph:xo,table:hn,text:Dl},Ki=Be("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Us).getRegex(),Fl={...Lr,lheading:Hl,table:Ki,paragraph:Be(Mr).replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ki).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Us).getRegex()},zl={...Lr,html:Be(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Pr).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:hn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Be(Mr).replace("hr",as).replace("heading",` *#{1,6} *[^
14
+ `,P))>-1;)Yn=_e.slice(P,rt),P=rt+1,Ve(Yn)}const Ve=_e=>{try{_e=JSON.parse(_e)}catch(mt){this.complete(new et("Malformed response body from server: "+mt.message,null,400));return}this.emit("data",_e)},Je=()=>{qe(),this.streamComplete=!0,_.Config.nextTick(()=>{this.complete()})};a.onreadystatechange=()=>{const _e=a.readyState;_e<3||a.status!==0&&(U===void 0&&(U=a.status,se()),_e==3&&L?qe():_e==4&&(L?Je():ye()))},a.send(b)}dispose(){const t=this.xhr;if(t){t.onreadystatechange=t.onerror=t.onabort=t.ontimeout=gc,this.xhr=null;const n=this.timer;n&&(clearTimeout(n),this.timer=null),this.requestComplete||t.abort()}delete Gi[this.id]}},qi=wc,Hi=dt.XhrPolling,vc=class extends uc{constructor(e,t,n){super(e,t,n),this.shortName=Hi,n.stream=!1,this.shortName=Hi}static isAvailable(){return!!(_.Config.xhrSupported&&_.Config.allowComet)}toString(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected}createRequest(e,t,n,s,r){return qi.createRequest(e,t,n,s,r,this.timeouts,this.logger)}},kc=vc,_c=["xhr_polling"],Ac={order:_c,bundledImplementations:{web_socket:Oi,xhr_polling:kc}},Rc=Ac,Cc={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[dt.XhrPolling,dt.WebSocket]},Oc=Cc;function Sc(e){if(e===void 0)return"undefined";let t,n;if(e instanceof ArrayBuffer?(n="ArrayBuffer",t=new DataView(e)):e instanceof DataView&&(n="DataView",t=e),!t)return JSON.stringify(e);const s=[];for(let r=0;r<e.byteLength;r++){if(r>20){s.push("...");break}let a=t.getUint8(r).toString(16);a.length===1&&(a="0"+a),s.push(a)}return"<"+n+" "+s.join(" ")+">"}function Jn(e,t,n){const r=new TextEncoder().encode(n);for(let a=0;a<r.length;a++)e.setUint8(t+a,r[a])}function Di(e,t,n){return new TextDecoder().decode(e.buffer.slice(t,t+n))}function rr(e){return new TextEncoder().encode(e).length}function Tc(e,t){const n=Qn(e,t);if(n===0)return;const s=new ArrayBuffer(n),r=new DataView(s);return Kn(e,r,0,t),s}var ir=65536*65536,ji=1/ir;function Ec(e,t){return t=t||0,e.getInt32(t)*ir+e.getUint32(t+4)}function Mc(e,t){return t=t||0,e.getUint32(t)*ir+e.getUint32(t+4)}function Ic(e,t,n){n<9223372036854776e3?(e.setInt32(t,Math.floor(n*ji)),e.setInt32(t+4,n&-1)):(e.setUint32(t,2147483647),e.setUint32(t+4,2147483647))}function Pc(e,t,n){n<18446744073709552e3?(e.setUint32(t,Math.floor(n*ji)),e.setInt32(t+4,n&-1)):(e.setUint32(t,4294967295),e.setUint32(t+4,4294967295))}var Lc=class{constructor(e,t){this.map=n=>{const s={};for(let r=0;r<n;r++){const a=this.parse();s[a]=this.parse()}return s},this.bin=n=>{const s=new ArrayBuffer(n);return new Uint8Array(s).set(new Uint8Array(this.view.buffer,this.offset,n),0),this.offset+=n,s},this.buf=this.bin,this.str=n=>{const s=Di(this.view,this.offset,n);return this.offset+=n,s},this.array=n=>{const s=new Array(n);for(let r=0;r<n;r++)s[r]=this.parse();return s},this.ext=n=>(this.offset+=n,{type:this.view.getInt8(this.offset),data:this.buf(n)}),this.parse=()=>{const n=this.view.getUint8(this.offset);let s,r;if((n&128)===0)return this.offset++,n;if((n&240)===128)return r=n&15,this.offset++,this.map(r);if((n&240)===144)return r=n&15,this.offset++,this.array(r);if((n&224)===160)return r=n&31,this.offset++,this.str(r);if((n&224)===224)return s=this.view.getInt8(this.offset),this.offset++,s;switch(n){case 192:return this.offset++,null;case 193:this.offset++;return;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return r=this.view.getUint8(this.offset+1),this.offset+=2,this.bin(r);case 197:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.bin(r);case 198:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.bin(r);case 199:return r=this.view.getUint8(this.offset+1),this.offset+=2,this.ext(r);case 200:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.ext(r);case 201:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.ext(r);case 202:return s=this.view.getFloat32(this.offset+1),this.offset+=5,s;case 203:return s=this.view.getFloat64(this.offset+1),this.offset+=9,s;case 204:return s=this.view.getUint8(this.offset+1),this.offset+=2,s;case 205:return s=this.view.getUint16(this.offset+1),this.offset+=3,s;case 206:return s=this.view.getUint32(this.offset+1),this.offset+=5,s;case 207:return s=Mc(this.view,this.offset+1),this.offset+=9,s;case 208:return s=this.view.getInt8(this.offset+1),this.offset+=2,s;case 209:return s=this.view.getInt16(this.offset+1),this.offset+=3,s;case 210:return s=this.view.getInt32(this.offset+1),this.offset+=5,s;case 211:return s=Ec(this.view,this.offset+1),this.offset+=9,s;case 212:return r=1,this.offset++,this.ext(r);case 213:return r=2,this.offset++,this.ext(r);case 214:return r=4,this.offset++,this.ext(r);case 215:return r=8,this.offset++,this.ext(r);case 216:return r=16,this.offset++,this.ext(r);case 217:return r=this.view.getUint8(this.offset+1),this.offset+=2,this.str(r);case 218:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.str(r);case 219:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.str(r);case 220:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.array(r);case 221:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.array(r);case 222:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.map(r);case 223:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.map(r)}throw new Error("Unknown type 0x"+n.toString(16))},this.offset=t||0,this.view=e}};function Uc(e){const t=new DataView(e),n=new Lc(t),s=n.parse();if(n.offset!==e.byteLength)throw new Error(e.byteLength-n.offset+" trailing bytes");return s}function Wi(e,t){return Object.keys(e).filter(function(n){const s=e[n],r=typeof s;return(!t||s!=null)&&(r!=="function"||!!s.toJSON)})}function Kn(e,t,n,s){const r=typeof e;if(typeof e=="string"){const a=rr(e);if(a<32)return t.setUint8(n,a|160),Jn(t,n+1,e),1+a;if(a<256)return t.setUint8(n,217),t.setUint8(n+1,a),Jn(t,n+2,e),2+a;if(a<65536)return t.setUint8(n,218),t.setUint16(n+1,a),Jn(t,n+3,e),3+a;if(a<4294967296)return t.setUint8(n,219),t.setUint32(n+1,a),Jn(t,n+5,e),5+a}if(ArrayBuffer.isView&&ArrayBuffer.isView(e)&&(e=e.buffer),e instanceof ArrayBuffer){const a=e.byteLength;if(a<256)return t.setUint8(n,196),t.setUint8(n+1,a),new Uint8Array(t.buffer).set(new Uint8Array(e),n+2),2+a;if(a<65536)return t.setUint8(n,197),t.setUint16(n+1,a),new Uint8Array(t.buffer).set(new Uint8Array(e),n+3),3+a;if(a<4294967296)return t.setUint8(n,198),t.setUint32(n+1,a),new Uint8Array(t.buffer).set(new Uint8Array(e),n+5),5+a}if(typeof e=="number"){if(Math.floor(e)!==e)return t.setUint8(n,203),t.setFloat64(n+1,e),9;if(e>=0){if(e<128)return t.setUint8(n,e),1;if(e<256)return t.setUint8(n,204),t.setUint8(n+1,e),2;if(e<65536)return t.setUint8(n,205),t.setUint16(n+1,e),3;if(e<4294967296)return t.setUint8(n,206),t.setUint32(n+1,e),5;if(e<18446744073709552e3)return t.setUint8(n,207),Pc(t,n+1,e),9;throw new Error("Number too big 0x"+e.toString(16))}if(e>=-32)return t.setInt8(n,e),1;if(e>=-128)return t.setUint8(n,208),t.setInt8(n+1,e),2;if(e>=-32768)return t.setUint8(n,209),t.setInt16(n+1,e),3;if(e>=-2147483648)return t.setUint8(n,210),t.setInt32(n+1,e),5;if(e>=-9223372036854776e3)return t.setUint8(n,211),Ic(t,n+1,e),9;throw new Error("Number too small -0x"+(-e).toString(16).substr(1))}if(r==="undefined")return s?0:(t.setUint8(n,212),t.setUint8(n+1,0),t.setUint8(n+2,0),3);if(e===null)return s?0:(t.setUint8(n,192),1);if(r==="boolean")return t.setUint8(n,e?195:194),1;if(typeof e.toJSON=="function")return Kn(e.toJSON(),t,n,s);if(r==="object"){let a,g=0,b;const R=Array.isArray(e);if(R?a=e.length:(b=Wi(e,s),a=b.length),a<16?(t.setUint8(n,a|(R?144:128)),g=1):a<65536?(t.setUint8(n,R?220:222),t.setUint16(n+1,a),g=3):a<4294967296&&(t.setUint8(n,R?221:223),t.setUint32(n+1,a),g=5),R)for(let A=0;A<a;A++)g+=Kn(e[A],t,n+g,s);else if(b)for(let A=0;A<a;A++){const L=b[A];g+=Kn(L,t,n+g),g+=Kn(e[L],t,n+g,s)}return g}if(r==="function")return 0;throw new Error("Unknown type "+r)}function Qn(e,t){const n=typeof e;if(n==="string"){const s=rr(e);if(s<32)return 1+s;if(s<256)return 2+s;if(s<65536)return 3+s;if(s<4294967296)return 5+s}if(ArrayBuffer.isView&&ArrayBuffer.isView(e)&&(e=e.buffer),e instanceof ArrayBuffer){const s=e.byteLength;if(s<256)return 2+s;if(s<65536)return 3+s;if(s<4294967296)return 5+s}if(typeof e=="number"){if(Math.floor(e)!==e)return 9;if(e>=0){if(e<128)return 1;if(e<256)return 2;if(e<65536)return 3;if(e<4294967296)return 5;if(e<18446744073709552e3)return 9;throw new Error("Number too big 0x"+e.toString(16))}if(e>=-32)return 1;if(e>=-128)return 2;if(e>=-32768)return 3;if(e>=-2147483648)return 5;if(e>=-9223372036854776e3)return 9;throw new Error("Number too small -0x"+e.toString(16).substr(1))}if(n==="boolean")return 1;if(e===null)return t?0:1;if(e===void 0)return t?0:3;if(typeof e.toJSON=="function")return Qn(e.toJSON(),t);if(n==="object"){let s,r=0;if(Array.isArray(e)){s=e.length;for(let a=0;a<s;a++)r+=Qn(e[a],t)}else{const a=Wi(e,t);s=a.length;for(let g=0;g<s;g++){const b=a[g];r+=Qn(b)+Qn(e[b],t)}}if(s<16)return 1+r;if(s<65536)return 3+r;if(s<4294967296)return 5+r;throw new Error("Array or object too long 0x"+s.toString(16))}if(n==="function")return 0;throw new Error("Unknown type "+n)}var or={encode:Tc,decode:Uc,inspect:Sc,utf8Write:Jn,utf8Read:Di,utf8ByteCount:rr};function Bc(e,t){return!!t.get("x-ably-errorcode")}function Nc(e,t){if(Bc(e,t))return e.error&&S.fromValues(e.error)}function Gc(e){const t={};return e.forEach((n,s)=>{t[s]=n}),t}async function qc(e,t,n,s,r,a){const g=new Headers(s||{}),b=e?e.toUpperCase():Ke(a)?"GET":"POST",R=new AbortController;let A;const L=new Promise(P=>{A=setTimeout(()=>{R.abort(),P({error:new et("Request timed out",null,408)})},t?t.options.timeouts.httpRequestTimeout:V.TIMEOUTS.httpRequestTimeout)}),U={method:b,headers:g,body:a,signal:R.signal};_.Config.isWebworker||(U.credentials=g.has("authorization")?"include":"same-origin");const F=(async()=>{try{const P=new URLSearchParams(r||{});P.set("rnd",Ht());const ne=n+"?"+P,se=await Ut().fetch(ne,U);if(clearTimeout(A),se.status==204)return{error:null,statusCode:se.status};const ye=se.headers.get("Content-Type");let qe;ye&&ye.indexOf("application/x-msgpack")>-1?qe=await se.arrayBuffer():ye&&ye.indexOf("application/json")>-1?qe=await se.json():qe=await se.text();const Ve=!!ye&&ye.indexOf("application/x-msgpack")===-1,Je=Gc(se.headers);return se.ok?{error:null,body:qe,headers:Je,unpacked:Ve,statusCode:se.status}:{error:Nc(qe,se.headers)||new et("Error response received from server: "+se.status+" body was: "+_.Config.inspect(qe),null,se.status),body:qe,headers:Je,unpacked:Ve,statusCode:se.status}}catch(P){return clearTimeout(A),{error:P}}})();return Promise.race([L,F])}var Hc={XHRRequest:qi,FetchRequest:qc},Vi=nc(Ni,Mi);_.Crypto=Vi,_.BufferUtils=Mi,_.Http=Ui,_.Config=Ni,_.Transports=Rc,_.WebStorage=Bi;for(const e of[Fs,Zs])e.Crypto=Vi,e._MsgPack=or;Ui.bundledRequestImplementations=Hc,c.initLogHandlers(),_.Defaults=xe(Oc),_.Config.agent&&(_.Defaults.agent+=" "+_.Config.agent);var Dc={ErrorInfo:S,Rest:Fs,Realtime:Zs,msgpack:or,makeProtocolMessageFromDeserialized:xi};if(typeof p.exports=="object"&&typeof l=="object"){var jc=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Object.getOwnPropertyNames(t))!Object.prototype.hasOwnProperty.call(e,r)&&r!==n&&Object.defineProperty(e,r,{get:()=>t[r],enumerable:!(s=Object.getOwnPropertyDescriptor(t,r))||s.enumerable});return e};p.exports=jc(p.exports,l)}return p.exports})})(Cs)),Cs.exports}var Pl=Il();class Ll{constructor(o){ce(this,"ably",null);ce(this,"channel",null);ce(this,"opts");ce(this,"_connected",!1);ce(this,"clientId",null);ce(this,"messageHandlers",[]);ce(this,"peerJoinedHandlers",[]);ce(this,"peerLeftHandlers",[]);ce(this,"errorHandlers",[]);ce(this,"disconnectHandlers",[]);if(!o.key&&!o.token)throw new Error("Ably API key or token is required");this.opts=o}get connected(){return this._connected}async connect(o,l){this.clientId=`airloom-${l}-${Date.now()}`;const p={clientId:this.clientId,queryTime:!0};this.opts.key?p.key=this.opts.key:p.token=this.opts.token,this.ably=new Pl.Realtime(p),await new Promise((k,v)=>{this.ably.connection.once("connected",()=>k()),this.ably.connection.once("failed",I=>{var M;v(new Error(((M=I==null?void 0:I.reason)==null?void 0:M.message)??"Ably connection failed"))})}),this._connected=!0,this.ably.connection.on("disconnected",()=>{this._connected=!1,this.disconnectHandlers.forEach(k=>k())}),this.ably.connection.on("connected",()=>{this._connected=!0,this.channel&&this.channel.presence.get().then(k=>{k.some(I=>I.clientId!==this.clientId)&&this.peerJoinedHandlers.forEach(I=>I())}).catch(()=>{})}),this.ably.connection.on("failed",k=>{var I;this._connected=!1;const v=new Error(((I=k==null?void 0:k.reason)==null?void 0:I.message)??"Ably connection failed");this.errorHandlers.forEach(M=>M(v))}),this.channel=this.ably.channels.get(`airloom:${o}`),this.channel.subscribe("forward",k=>{k.clientId!==this.clientId&&typeof k.data=="string"&&this.messageHandlers.forEach(v=>v(k.data))}),this.channel.presence.subscribe("enter",k=>{k.clientId!==this.clientId&&this.peerJoinedHandlers.forEach(v=>v())}),this.channel.presence.subscribe("leave",k=>{k.clientId!==this.clientId&&this.peerLeftHandlers.forEach(v=>v())}),await this.channel.presence.enter({role:l}),(await this.channel.presence.get()).some(k=>k.clientId!==this.clientId)&&this.peerJoinedHandlers.forEach(k=>k())}send(o){!this.channel||!this._connected||this.channel.publish("forward",o)}onMessage(o){this.messageHandlers.push(o)}onPeerJoined(o){this.peerJoinedHandlers.push(o)}onPeerLeft(o){this.peerLeftHandlers.push(o)}onError(o){this.errorHandlers.push(o)}onDisconnect(o){this.disconnectHandlers.push(o)}close(){var o,l,p;(o=this.channel)==null||o.presence.leave().catch(()=>{}),(l=this.channel)==null||l.detach().catch(()=>{});try{(p=this.ably)==null||p.close()}catch{}this.channel=null,this.ably=null,this._connected=!1}}function Tr(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var un=Tr();function mo(f){un=f}var hn={exec:()=>null};function Be(f,o=""){let l=typeof f=="string"?f:f.source,p={replace:(m,x)=>{let k=typeof x=="string"?x:x.source;return k=k.replace(lt.caret,"$1"),l=l.replace(m,k),p},getRegex:()=>new RegExp(l,o)};return p}var Ul=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),lt={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:f=>new RegExp(`^( {0,3}${f})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:f=>new RegExp(`^ {0,${Math.min(3,f-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:f=>new RegExp(`^ {0,${Math.min(3,f-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:f=>new RegExp(`^ {0,${Math.min(3,f-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:f=>new RegExp(`^ {0,${Math.min(3,f-1)}}#`),htmlBeginRegex:f=>new RegExp(`^ {0,${Math.min(3,f-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:f=>new RegExp(`^ {0,${Math.min(3,f-1)}}>`)},Bl=/^(?:[ \t]*(?:\n|$))+/,Nl=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Gl=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,as=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ql=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Er=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,yo=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,bo=Be(yo).replace(/bull/g,Er).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Hl=Be(yo).replace(/bull/g,Er).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Mr=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Dl=/^[^\n]+/,Ir=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,jl=Be(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ir).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Wl=Be(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Er).getRegex(),Us="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Pr=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Vl=Be("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Pr).replace("tag",Us).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),xo=Be(Mr).replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Us).getRegex(),$l=Be(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",xo).getRegex(),Lr={blockquote:$l,code:Nl,def:jl,fences:Gl,heading:ql,hr:as,html:Vl,lheading:bo,list:Wl,newline:Bl,paragraph:xo,table:hn,text:Dl},Ki=Be("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Us).getRegex(),Fl={...Lr,lheading:Hl,table:Ki,paragraph:Be(Mr).replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ki).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Us).getRegex()},zl={...Lr,html:Be(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Pr).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:hn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Be(Mr).replace("hr",as).replace("heading",` *#{1,6} *[^
15
15
  ]`).replace("lheading",bo).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Jl=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Kl=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,wo=/^( {2,}|\\)\n(?!\s*$)/,Ql=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Bs=/[\p{P}\p{S}]/u,Ur=/[\s\p{P}\p{S}]/u,vo=/[^\s\p{P}\p{S}]/u,Yl=Be(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ur).getRegex(),ko=/(?!~)[\p{P}\p{S}]/u,Zl=/(?!~)[\s\p{P}\p{S}]/u,Xl=/(?:[^\s\p{P}\p{S}]|~)/u,_o=/(?![*_])[\p{P}\p{S}]/u,eh=/(?![*_])[\s\p{P}\p{S}]/u,th=/(?:[^\s\p{P}\p{S}]|[*_])/u,nh=Be(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Ul?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Ao=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,sh=Be(Ao,"u").replace(/punct/g,Bs).getRegex(),rh=Be(Ao,"u").replace(/punct/g,ko).getRegex(),Ro="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",ih=Be(Ro,"gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,Ur).replace(/punct/g,Bs).getRegex(),oh=Be(Ro,"gu").replace(/notPunctSpace/g,Xl).replace(/punctSpace/g,Zl).replace(/punct/g,ko).getRegex(),ah=Be("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,vo).replace(/punctSpace/g,Ur).replace(/punct/g,Bs).getRegex(),ch=Be(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,_o).getRegex(),lh="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",hh=Be(lh,"gu").replace(/notPunctSpace/g,th).replace(/punctSpace/g,eh).replace(/punct/g,_o).getRegex(),fh=Be(/\\(punct)/,"gu").replace(/punct/g,Bs).getRegex(),uh=Be(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),dh=Be(Pr).replace("(?:-->|$)","-->").getRegex(),ph=Be("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",dh).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Es=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,gh=Be(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Es).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Co=Be(/^!?\[(label)\]\[(ref)\]/).replace("label",Es).replace("ref",Ir).getRegex(),Oo=Be(/^!?\[(ref)\](?:\[\])?/).replace("ref",Ir).getRegex(),mh=Be("reflink|nolink(?!\\()","g").replace("reflink",Co).replace("nolink",Oo).getRegex(),Qi=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Br={_backpedal:hn,anyPunctuation:fh,autolink:uh,blockSkip:nh,br:wo,code:Kl,del:hn,delLDelim:hn,delRDelim:hn,emStrongLDelim:sh,emStrongRDelimAst:ih,emStrongRDelimUnd:ah,escape:Jl,link:gh,nolink:Oo,punctuation:Yl,reflink:Co,reflinkSearch:mh,tag:ph,text:Ql,url:hn},yh={...Br,link:Be(/^!?\[(label)\]\((.*?)\)/).replace("label",Es).getRegex(),reflink:Be(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Es).getRegex()},kr={...Br,emStrongRDelimAst:oh,emStrongLDelim:rh,delLDelim:ch,delRDelim:hh,url:Be(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Qi).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Be(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Qi).getRegex()},bh={...kr,br:Be(wo).replace("{2,}","*").getRegex(),text:Be(kr.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},_s={normal:Lr,gfm:Fl,pedantic:zl},Zn={normal:Br,gfm:kr,breaks:bh,pedantic:yh},xh={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Yi=f=>xh[f];function It(f,o){if(o){if(lt.escapeTest.test(f))return f.replace(lt.escapeReplace,Yi)}else if(lt.escapeTestNoEncode.test(f))return f.replace(lt.escapeReplaceNoEncode,Yi);return f}function Zi(f){try{f=encodeURI(f).replace(lt.percentDecode,"%")}catch{return null}return f}function Xi(f,o){var x;let l=f.replace(lt.findPipe,(k,v,I)=>{let M=!1,D=v;for(;--D>=0&&I[D]==="\\";)M=!M;return M?"|":" |"}),p=l.split(lt.splitPipe),m=0;if(p[0].trim()||p.shift(),p.length>0&&!((x=p.at(-1))!=null&&x.trim())&&p.pop(),o)if(p.length>o)p.splice(o);else for(;p.length<o;)p.push("");for(;m<p.length;m++)p[m]=p[m].trim().replace(lt.slashPipe,"|");return p}function Xn(f,o,l){let p=f.length;if(p===0)return"";let m=0;for(;m<p&&f.charAt(p-m-1)===o;)m++;return f.slice(0,p-m)}function wh(f,o){if(f.indexOf(o[1])===-1)return-1;let l=0;for(let p=0;p<f.length;p++)if(f[p]==="\\")p++;else if(f[p]===o[0])l++;else if(f[p]===o[1]&&(l--,l<0))return p;return l>0?-2:-1}function vh(f,o=0){let l=o,p="";for(let m of f)if(m===" "){let x=4-l%4;p+=" ".repeat(x),l+=x}else p+=m,l++;return p}function eo(f,o,l,p,m){let x=o.href,k=o.title||null,v=f[1].replace(m.other.outputLinkReplace,"$1");p.state.inLink=!0;let I={type:f[0].charAt(0)==="!"?"image":"link",raw:l,href:x,title:k,text:v,tokens:p.inlineTokens(v)};return p.state.inLink=!1,I}function kh(f,o,l){let p=f.match(l.other.indentCodeCompensation);if(p===null)return o;let m=p[1];return o.split(`
16
16
  `).map(x=>{let k=x.match(l.other.beginningSpace);if(k===null)return x;let[v]=k;return v.length>=m.length?x.slice(m.length):x}).join(`
17
17
  `)}var Ms=class{constructor(f){ce(this,"options");ce(this,"rules");ce(this,"lexer");this.options=f||un}space(f){let o=this.rules.block.newline.exec(f);if(o&&o[0].length>0)return{type:"space",raw:o[0]}}code(f){let o=this.rules.block.code.exec(f);if(o){let l=o[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:o[0],codeBlockStyle:"indented",text:this.options.pedantic?l:Xn(l,`
@@ -69,4 +69,4 @@ ${this.parser.parse(f)}</blockquote>
69
69
  ${f}</tr>
70
70
  `}tablecell(f){let o=this.parser.parseInline(f.tokens),l=f.header?"th":"td";return(f.align?`<${l} align="${f.align}">`:`<${l}>`)+o+`</${l}>
71
71
  `}strong({tokens:f}){return`<strong>${this.parser.parseInline(f)}</strong>`}em({tokens:f}){return`<em>${this.parser.parseInline(f)}</em>`}codespan({text:f}){return`<code>${It(f,!0)}</code>`}br(f){return"<br>"}del({tokens:f}){return`<del>${this.parser.parseInline(f)}</del>`}link({href:f,title:o,tokens:l}){let p=this.parser.parseInline(l),m=Zi(f);if(m===null)return p;f=m;let x='<a href="'+f+'"';return o&&(x+=' title="'+It(o)+'"'),x+=">"+p+"</a>",x}image({href:f,title:o,text:l,tokens:p}){p&&(l=this.parser.parseInline(p,this.parser.textRenderer));let m=Zi(f);if(m===null)return It(l);f=m;let x=`<img src="${f}" alt="${It(l)}"`;return o&&(x+=` title="${It(o)}"`),x+=">",x}text(f){return"tokens"in f&&f.tokens?this.parser.parseInline(f.tokens):"escaped"in f&&f.escaped?f.text:It(f.text)}},Nr=class{strong({text:f}){return f}em({text:f}){return f}codespan({text:f}){return f}del({text:f}){return f}html({text:f}){return f}text({text:f}){return f}link({text:f}){return""+f}image({text:f}){return""+f}br(){return""}checkbox({raw:f}){return f}},_t=class Ar{constructor(o){ce(this,"options");ce(this,"renderer");ce(this,"textRenderer");this.options=o||un,this.options.renderer=this.options.renderer||new Is,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Nr}static parse(o,l){return new Ar(l).parse(o)}static parseInline(o,l){return new Ar(l).parseInline(o)}parse(o){var p,m;let l="";for(let x=0;x<o.length;x++){let k=o[x];if((m=(p=this.options.extensions)==null?void 0:p.renderers)!=null&&m[k.type]){let I=k,M=this.options.extensions.renderers[I.type].call({parser:this},I);if(M!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(I.type)){l+=M||"";continue}}let v=k;switch(v.type){case"space":{l+=this.renderer.space(v);break}case"hr":{l+=this.renderer.hr(v);break}case"heading":{l+=this.renderer.heading(v);break}case"code":{l+=this.renderer.code(v);break}case"table":{l+=this.renderer.table(v);break}case"blockquote":{l+=this.renderer.blockquote(v);break}case"list":{l+=this.renderer.list(v);break}case"checkbox":{l+=this.renderer.checkbox(v);break}case"html":{l+=this.renderer.html(v);break}case"def":{l+=this.renderer.def(v);break}case"paragraph":{l+=this.renderer.paragraph(v);break}case"text":{l+=this.renderer.text(v);break}default:{let I='Token with "'+v.type+'" type was not found.';if(this.options.silent)return console.error(I),"";throw new Error(I)}}}return l}parseInline(o,l=this.renderer){var m,x;let p="";for(let k=0;k<o.length;k++){let v=o[k];if((x=(m=this.options.extensions)==null?void 0:m.renderers)!=null&&x[v.type]){let M=this.options.extensions.renderers[v.type].call({parser:this},v);if(M!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(v.type)){p+=M||"";continue}}let I=v;switch(I.type){case"escape":{p+=l.text(I);break}case"html":{p+=l.html(I);break}case"link":{p+=l.link(I);break}case"image":{p+=l.image(I);break}case"checkbox":{p+=l.checkbox(I);break}case"strong":{p+=l.strong(I);break}case"em":{p+=l.em(I);break}case"codespan":{p+=l.codespan(I);break}case"br":{p+=l.br(I);break}case"del":{p+=l.del(I);break}case"text":{p+=l.text(I);break}default:{let M='Token with "'+I.type+'" type was not found.';if(this.options.silent)return console.error(M),"";throw new Error(M)}}}return p}},Rs,ss=(Rs=class{constructor(f){ce(this,"options");ce(this,"block");this.options=f||un}preprocess(f){return f}postprocess(f){return f}processAllTokens(f){return f}emStrongMask(f){return f}provideLexer(){return this.block?kt.lex:kt.lexInline}provideParser(){return this.block?_t.parse:_t.parseInline}},ce(Rs,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),ce(Rs,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),Rs),_h=class{constructor(...f){ce(this,"defaults",Tr());ce(this,"options",this.setOptions);ce(this,"parse",this.parseMarkdown(!0));ce(this,"parseInline",this.parseMarkdown(!1));ce(this,"Parser",_t);ce(this,"Renderer",Is);ce(this,"TextRenderer",Nr);ce(this,"Lexer",kt);ce(this,"Tokenizer",Ms);ce(this,"Hooks",ss);this.use(...f)}walkTokens(f,o){var p,m;let l=[];for(let x of f)switch(l=l.concat(o.call(this,x)),x.type){case"table":{let k=x;for(let v of k.header)l=l.concat(this.walkTokens(v.tokens,o));for(let v of k.rows)for(let I of v)l=l.concat(this.walkTokens(I.tokens,o));break}case"list":{let k=x;l=l.concat(this.walkTokens(k.items,o));break}default:{let k=x;(m=(p=this.defaults.extensions)==null?void 0:p.childTokens)!=null&&m[k.type]?this.defaults.extensions.childTokens[k.type].forEach(v=>{let I=k[v].flat(1/0);l=l.concat(this.walkTokens(I,o))}):k.tokens&&(l=l.concat(this.walkTokens(k.tokens,o)))}}return l}use(...f){let o=this.defaults.extensions||{renderers:{},childTokens:{}};return f.forEach(l=>{let p={...l};if(p.async=this.defaults.async||p.async||!1,l.extensions&&(l.extensions.forEach(m=>{if(!m.name)throw new Error("extension name required");if("renderer"in m){let x=o.renderers[m.name];x?o.renderers[m.name]=function(...k){let v=m.renderer.apply(this,k);return v===!1&&(v=x.apply(this,k)),v}:o.renderers[m.name]=m.renderer}if("tokenizer"in m){if(!m.level||m.level!=="block"&&m.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let x=o[m.level];x?x.unshift(m.tokenizer):o[m.level]=[m.tokenizer],m.start&&(m.level==="block"?o.startBlock?o.startBlock.push(m.start):o.startBlock=[m.start]:m.level==="inline"&&(o.startInline?o.startInline.push(m.start):o.startInline=[m.start]))}"childTokens"in m&&m.childTokens&&(o.childTokens[m.name]=m.childTokens)}),p.extensions=o),l.renderer){let m=this.defaults.renderer||new Is(this.defaults);for(let x in l.renderer){if(!(x in m))throw new Error(`renderer '${x}' does not exist`);if(["options","parser"].includes(x))continue;let k=x,v=l.renderer[k],I=m[k];m[k]=(...M)=>{let D=v.apply(m,M);return D===!1&&(D=I.apply(m,M)),D||""}}p.renderer=m}if(l.tokenizer){let m=this.defaults.tokenizer||new Ms(this.defaults);for(let x in l.tokenizer){if(!(x in m))throw new Error(`tokenizer '${x}' does not exist`);if(["options","rules","lexer"].includes(x))continue;let k=x,v=l.tokenizer[k],I=m[k];m[k]=(...M)=>{let D=v.apply(m,M);return D===!1&&(D=I.apply(m,M)),D}}p.tokenizer=m}if(l.hooks){let m=this.defaults.hooks||new ss;for(let x in l.hooks){if(!(x in m))throw new Error(`hook '${x}' does not exist`);if(["options","block"].includes(x))continue;let k=x,v=l.hooks[k],I=m[k];ss.passThroughHooks.has(x)?m[k]=M=>{if(this.defaults.async&&ss.passThroughHooksRespectAsync.has(x))return(async()=>{let J=await v.call(m,M);return I.call(m,J)})();let D=v.call(m,M);return I.call(m,D)}:m[k]=(...M)=>{if(this.defaults.async)return(async()=>{let J=await v.apply(m,M);return J===!1&&(J=await I.apply(m,M)),J})();let D=v.apply(m,M);return D===!1&&(D=I.apply(m,M)),D}}p.hooks=m}if(l.walkTokens){let m=this.defaults.walkTokens,x=l.walkTokens;p.walkTokens=function(k){let v=[];return v.push(x.call(this,k)),m&&(v=v.concat(m.call(this,k))),v}}this.defaults={...this.defaults,...p}}),this}setOptions(f){return this.defaults={...this.defaults,...f},this}lexer(f,o){return kt.lex(f,o??this.defaults)}parser(f,o){return _t.parse(f,o??this.defaults)}parseMarkdown(f){return(o,l)=>{let p={...l},m={...this.defaults,...p},x=this.onError(!!m.silent,!!m.async);if(this.defaults.async===!0&&p.async===!1)return x(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof o>"u"||o===null)return x(new Error("marked(): input parameter is undefined or null"));if(typeof o!="string")return x(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(o)+", string expected"));if(m.hooks&&(m.hooks.options=m,m.hooks.block=f),m.async)return(async()=>{let k=m.hooks?await m.hooks.preprocess(o):o,v=await(m.hooks?await m.hooks.provideLexer():f?kt.lex:kt.lexInline)(k,m),I=m.hooks?await m.hooks.processAllTokens(v):v;m.walkTokens&&await Promise.all(this.walkTokens(I,m.walkTokens));let M=await(m.hooks?await m.hooks.provideParser():f?_t.parse:_t.parseInline)(I,m);return m.hooks?await m.hooks.postprocess(M):M})().catch(x);try{m.hooks&&(o=m.hooks.preprocess(o));let k=(m.hooks?m.hooks.provideLexer():f?kt.lex:kt.lexInline)(o,m);m.hooks&&(k=m.hooks.processAllTokens(k)),m.walkTokens&&this.walkTokens(k,m.walkTokens);let v=(m.hooks?m.hooks.provideParser():f?_t.parse:_t.parseInline)(k,m);return m.hooks&&(v=m.hooks.postprocess(v)),v}catch(k){return x(k)}}}onError(f,o){return l=>{if(l.message+=`
72
- Please report this to https://github.com/markedjs/marked.`,f){let p="<p>An error occurred:</p><pre>"+It(l.message+"",!0)+"</pre>";return o?Promise.resolve(p):p}if(o)return Promise.reject(l);throw l}}},fn=new _h;function We(f,o){return fn.parse(f,o)}We.options=We.setOptions=function(f){return fn.setOptions(f),We.defaults=fn.defaults,mo(We.defaults),We};We.getDefaults=Tr;We.defaults=un;We.use=function(...f){return fn.use(...f),We.defaults=fn.defaults,mo(We.defaults),We};We.walkTokens=function(f,o){return fn.walkTokens(f,o)};We.parseInline=fn.parseInline;We.Parser=_t;We.parser=_t.parse;We.Renderer=Is;We.TextRenderer=Nr;We.Lexer=kt;We.lexer=kt.lex;We.Tokenizer=Ms;We.Hooks=ss;We.parse=We;We.options;We.setOptions;We.use;We.walkTokens;We.parseInline;_t.parse;kt.lex;We.setOptions({gfm:!0,breaks:!0});function So(f){return We.parse(f,{async:!1})}"serviceWorker"in navigator&&navigator.serviceWorker.register("./sw.js").then(f=>(f.active?Promise.resolve():new Promise(o=>{const l=f.installing??f.waiting;l?l.addEventListener("statechange",()=>{l.state==="activated"&&o()}):o()})).then(async()=>{const o=await caches.open("airloom-v2"),l=location.href.split("#")[0];await o.match(l)||await o.add(l).catch(()=>{});const x=performance.getEntriesByType("resource").map(k=>k.name).filter(k=>{try{return new URL(k).origin===location.origin}catch{return!1}});await Promise.all(x.map(k=>o.match(k).then(v=>{if(!v)return o.add(k).catch(()=>{})})))})).catch(()=>{});const To=document.getElementById("connectScreen"),Eo=document.getElementById("chatScreen"),Ah=document.getElementById("scanBtn"),Rh=document.getElementById("joinBtn"),Xt=document.getElementById("codeInput"),Rr=document.getElementById("relayInput"),Cr=document.getElementById("connectError"),to=document.getElementById("connectStatus"),Mo=document.getElementById("messages"),Zt=document.getElementById("messageInput"),Ch=document.getElementById("sendBtn"),Oh=document.getElementById("disconnectBtn"),Sn=document.getElementById("chatStatus"),no=document.getElementById("qrReader");let pt=null,Nt=null,As="";function Io(f,o){try{f&&localStorage.setItem("airloom:lastCode",f),localStorage.setItem("airloom:lastRelay",o)}catch{}}function Po(){try{const f=localStorage.getItem("airloom:lastCode"),o=localStorage.getItem("airloom:lastRelay");f&&!Xt.value&&(Xt.value=f),o&&!Rr.value&&(Rr.value=o)}catch{}}Po();Xt.addEventListener("input",()=>{let f=Xt.value.replace(/[^A-Za-z0-9]/g,"").toUpperCase();f.length>4&&(f=f.slice(0,4)+"-"+f.slice(4,8)),Xt.value=f});Rh.addEventListener("click",()=>Lo());Xt.addEventListener("keydown",f=>{f.key==="Enter"&&Lo()});Ah.addEventListener("click",async()=>{try{const{Html5Qrcode:f}=await ro(async()=>{const{Html5Qrcode:l}=await import("./index-B-Rf55SG.js");return{Html5Qrcode:l}},[],import.meta.url);no.style.display="block";const o=new f("qrReader");await o.start({facingMode:"environment"},{fps:10,qrbox:{width:250,height:250}},async l=>{await o.stop(),no.style.display="none",Uo(l)},()=>{})}catch{os("Camera access denied or not available")}});Ch.addEventListener("click",No);Zt.addEventListener("keydown",f=>{f.key==="Enter"&&!f.shiftKey&&(f.preventDefault(),No())});Zt.addEventListener("input",()=>{Zt.style.height="auto",Zt.style.height=Math.min(Zt.scrollHeight,120)+"px"});Oh.addEventListener("click",()=>{pt==null||pt.close(),pt=null,Eo.style.display="none",To.style.display="flex",Mo.innerHTML="",Po()});(async()=>{const f=location.hash.slice(1);if(f)try{const o=atob(f.replace(/-/g,"+").replace(/_/g,"/"));await Uo(o)}catch{}})();async function Lo(){const f=Cl(Xt.value);if(f.length!==8){os("Code must be 8 characters");return}const o=Rr.value.trim()||"ws://localhost:4500";Io(Xt.value,o);const l=Rl(f),p=Ls(new TextEncoder().encode("airloom-key:"+l)),m=co(p);await Bo(o,l,m)}async function Uo(f){try{const o=el(f);Io(null,o.relay);const l=Ls(new TextEncoder().encode("airloom-key:"+o.session)),p=co(l),m=o.transport??"ws";await Bo(o.relay,o.session,p,m,o.token)}catch(o){const l=o instanceof Error?o.message:"Unknown error";os("Invalid QR code: "+l)}}async function Bo(f,o,l,p="ws",m){so("Connecting..."),Sh();try{let x;if(p==="ably"){if(!m){os("Ably transport requires a token");return}x=new Ll({token:m})}else x=new El(f);pt=new Tl({adapter:x,role:"viewer",encryptionKey:l}),pt.on("ready",()=>{To.style.display="none",Eo.style.display="flex",Sn.textContent="Connected",Sn.className="status-badge"}),pt.on("peer_left",()=>{Sn.textContent="Disconnected",Sn.className="status-badge disconnected"}),pt.on("message",k=>{if(typeof k=="string")Ss("assistant",k);else if(typeof k=="object"&&k!==null&&"content"in k){const v=k,I=typeof v.role=="string"?v.role:"assistant";typeof v.content=="string"&&Ss(I,v.content)}}),pt.on("stream",k=>{Nt=Ss("assistant",""),Nt.classList.add("typing"),Nt.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',As="",k.on("data",v=>{if(As+=v,Nt){Nt.classList.contains("typing")&&Nt.classList.remove("typing");const I=As.trimStart();Nt.innerHTML=So(I),Nt.scrollIntoView({block:"end",behavior:"smooth"})}}),k.on("end",()=>{Nt=null,As=""})}),pt.on("error",k=>console.error("Channel error:",k)),pt.on("disconnect",()=>{Sn.textContent="Reconnecting…",Sn.className="status-badge reconnecting"}),await pt.connect(o),so("Connected to relay, waiting for host...")}catch(x){const k=x instanceof Error?x.message:"Unknown error";os("Connection failed: "+k)}}function No(){const f=Zt.value.trim();!f||!pt||(Zt.value="",Zt.style.height="auto",Ss("user",f),pt.send({type:"chat",content:f}))}function Ss(f,o){const l=document.createElement("div");return l.className=`msg ${f}`,f==="user"||!o?l.textContent=o:l.innerHTML=So(o),Mo.appendChild(l),l.scrollIntoView({block:"end",behavior:"smooth"}),l}function os(f){Cr.textContent=f,Cr.style.display="block"}function Sh(){Cr.style.display="none"}function so(f){to.textContent=f,to.style.display="block"}export{Kt as c,zc as g};
72
+ Please report this to https://github.com/markedjs/marked.`,f){let p="<p>An error occurred:</p><pre>"+It(l.message+"",!0)+"</pre>";return o?Promise.resolve(p):p}if(o)return Promise.reject(l);throw l}}},fn=new _h;function We(f,o){return fn.parse(f,o)}We.options=We.setOptions=function(f){return fn.setOptions(f),We.defaults=fn.defaults,mo(We.defaults),We};We.getDefaults=Tr;We.defaults=un;We.use=function(...f){return fn.use(...f),We.defaults=fn.defaults,mo(We.defaults),We};We.walkTokens=function(f,o){return fn.walkTokens(f,o)};We.parseInline=fn.parseInline;We.Parser=_t;We.parser=_t.parse;We.Renderer=Is;We.TextRenderer=Nr;We.Lexer=kt;We.lexer=kt.lex;We.Tokenizer=Ms;We.Hooks=ss;We.parse=We;We.options;We.setOptions;We.use;We.walkTokens;We.parseInline;_t.parse;kt.lex;We.setOptions({gfm:!0,breaks:!0});function So(f){return We.parse(f,{async:!1})}"serviceWorker"in navigator&&navigator.serviceWorker.register("./sw.js").then(f=>(f.active?Promise.resolve():new Promise(o=>{const l=f.installing??f.waiting;l?l.addEventListener("statechange",()=>{l.state==="activated"&&o()}):o()})).then(async()=>{const o=await caches.open("airloom-v2"),l=location.href.split("#")[0];await o.match(l)||await o.add(l).catch(()=>{});const x=performance.getEntriesByType("resource").map(k=>k.name).filter(k=>{try{return new URL(k).origin===location.origin}catch{return!1}});await Promise.all(x.map(k=>o.match(k).then(v=>{if(!v)return o.add(k).catch(()=>{})})))})).catch(()=>{});const To=document.getElementById("connectScreen"),Eo=document.getElementById("chatScreen"),Ah=document.getElementById("scanBtn"),Rh=document.getElementById("joinBtn"),Xt=document.getElementById("codeInput"),Rr=document.getElementById("relayInput"),Cr=document.getElementById("connectError"),to=document.getElementById("connectStatus"),Mo=document.getElementById("messages"),Zt=document.getElementById("messageInput"),Ch=document.getElementById("sendBtn"),Oh=document.getElementById("disconnectBtn"),Sn=document.getElementById("chatStatus"),no=document.getElementById("qrReader");let pt=null,Nt=null,As="";function Io(f,o){try{f&&localStorage.setItem("airloom:lastCode",f),localStorage.setItem("airloom:lastRelay",o)}catch{}}function Po(){try{const f=localStorage.getItem("airloom:lastCode"),o=localStorage.getItem("airloom:lastRelay");f&&!Xt.value&&(Xt.value=f),o&&!Rr.value&&(Rr.value=o)}catch{}}Po();Xt.addEventListener("input",()=>{let f=Xt.value.replace(/[^A-Za-z0-9]/g,"").toUpperCase();f.length>4&&(f=f.slice(0,4)+"-"+f.slice(4,8)),Xt.value=f});Rh.addEventListener("click",()=>Lo());Xt.addEventListener("keydown",f=>{f.key==="Enter"&&Lo()});Ah.addEventListener("click",async()=>{try{const{Html5Qrcode:f}=await ro(async()=>{const{Html5Qrcode:l}=await import("./index-m5PBOzJQ.js");return{Html5Qrcode:l}},[],import.meta.url);no.style.display="block";const o=new f("qrReader");await o.start({facingMode:"environment"},{fps:10,qrbox:{width:250,height:250}},async l=>{await o.stop(),no.style.display="none",Uo(l)},()=>{})}catch{os("Camera access denied or not available")}});Ch.addEventListener("click",No);Zt.addEventListener("keydown",f=>{f.key==="Enter"&&!f.shiftKey&&(f.preventDefault(),No())});Zt.addEventListener("input",()=>{Zt.style.height="auto",Zt.style.height=Math.min(Zt.scrollHeight,120)+"px"});Oh.addEventListener("click",()=>{pt==null||pt.close(),pt=null,Eo.style.display="none",To.style.display="flex",Mo.innerHTML="",Po()});(async()=>{const f=location.hash.slice(1);if(f)try{const o=atob(f.replace(/-/g,"+").replace(/_/g,"/"));await Uo(o)}catch{}})();async function Lo(){const f=Cl(Xt.value);if(f.length!==8){os("Code must be 8 characters");return}const o=Rr.value.trim()||"ws://localhost:4500";Io(Xt.value,o);const l=Rl(f),p=Ls(new TextEncoder().encode("airloom-key:"+l)),m=co(p);await Bo(o,l,m)}async function Uo(f){try{const o=el(f);Io(null,o.relay);const l=Ls(new TextEncoder().encode("airloom-key:"+o.session)),p=co(l),m=o.transport??"ws";await Bo(o.relay,o.session,p,m,o.token)}catch(o){const l=o instanceof Error?o.message:"Unknown error";os("Invalid QR code: "+l)}}async function Bo(f,o,l,p="ws",m){so("Connecting..."),Sh();try{let x;if(p==="ably"){if(!m){os("Ably transport requires a token");return}x=new Ll({token:m})}else x=new El(f);pt=new Tl({adapter:x,role:"viewer",encryptionKey:l}),pt.on("ready",()=>{To.style.display="none",Eo.style.display="flex",Sn.textContent="Connected",Sn.className="status-badge"}),pt.on("peer_left",()=>{Sn.textContent="Disconnected",Sn.className="status-badge disconnected"}),pt.on("message",k=>{if(typeof k=="string")Ss("assistant",k);else if(typeof k=="object"&&k!==null&&"content"in k){const v=k,I=typeof v.role=="string"?v.role:"assistant";typeof v.content=="string"&&Ss(I,v.content)}}),pt.on("stream",k=>{Nt=Ss("assistant",""),Nt.classList.add("typing"),Nt.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',As="",k.on("data",v=>{if(As+=v,Nt){Nt.classList.contains("typing")&&Nt.classList.remove("typing");const I=As.trimStart();Nt.innerHTML=So(I),Nt.scrollIntoView({block:"end",behavior:"smooth"})}}),k.on("end",()=>{Nt=null,As=""})}),pt.on("error",k=>console.error("Channel error:",k)),pt.on("disconnect",()=>{Sn.textContent="Reconnecting…",Sn.className="status-badge reconnecting"}),await pt.connect(o),so("Connected to relay, waiting for host...")}catch(x){const k=x instanceof Error?x.message:"Unknown error";os("Connection failed: "+k)}}function No(){const f=Zt.value.trim();!f||!pt||(Zt.value="",Zt.style.height="auto",Ss("user",f),pt.send({type:"chat",content:f}))}function Ss(f,o){const l=document.createElement("div");return l.className=`msg ${f}`,f==="user"||!o?l.textContent=o:l.innerHTML=So(o),Mo.appendChild(l),l.scrollIntoView({block:"end",behavior:"smooth"}),l}function os(f){Cr.textContent=f,Cr.style.display="block"}function Sh(){Cr.style.display="none"}function so(f){to.textContent=f,to.style.display="block"}export{Kt as c,zc as g};
@@ -1,4 +1,4 @@
1
- import{c as vn}from"./index-BoCit9Kx.js";var z;(function(f){f[f.QR_CODE=0]="QR_CODE",f[f.AZTEC=1]="AZTEC",f[f.CODABAR=2]="CODABAR",f[f.CODE_39=3]="CODE_39",f[f.CODE_93=4]="CODE_93",f[f.CODE_128=5]="CODE_128",f[f.DATA_MATRIX=6]="DATA_MATRIX",f[f.MAXICODE=7]="MAXICODE",f[f.ITF=8]="ITF",f[f.EAN_13=9]="EAN_13",f[f.EAN_8=10]="EAN_8",f[f.PDF_417=11]="PDF_417",f[f.RSS_14=12]="RSS_14",f[f.RSS_EXPANDED=13]="RSS_EXPANDED",f[f.UPC_A=14]="UPC_A",f[f.UPC_E=15]="UPC_E",f[f.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(z||(z={}));var _r=new Map([[z.QR_CODE,"QR_CODE"],[z.AZTEC,"AZTEC"],[z.CODABAR,"CODABAR"],[z.CODE_39,"CODE_39"],[z.CODE_93,"CODE_93"],[z.CODE_128,"CODE_128"],[z.DATA_MATRIX,"DATA_MATRIX"],[z.MAXICODE,"MAXICODE"],[z.ITF,"ITF"],[z.EAN_13,"EAN_13"],[z.EAN_8,"EAN_8"],[z.PDF_417,"PDF_417"],[z.RSS_14,"RSS_14"],[z.RSS_EXPANDED,"RSS_EXPANDED"],[z.UPC_A,"UPC_A"],[z.UPC_E,"UPC_E"],[z.UPC_EAN_EXTENSION,"UPC_EAN_EXTENSION"]]),Dr;(function(f){f[f.UNKNOWN=0]="UNKNOWN",f[f.URL=1]="URL"})(Dr||(Dr={}));function _i(f){return Object.values(z).includes(f)}var Vt;(function(f){f[f.SCAN_TYPE_CAMERA=0]="SCAN_TYPE_CAMERA",f[f.SCAN_TYPE_FILE=1]="SCAN_TYPE_FILE"})(Vt||(Vt={}));var Et=(function(){function f(){}return f.GITHUB_PROJECT_URL="https://github.com/mebjas/html5-qrcode",f.SCAN_DEFAULT_FPS=2,f.DEFAULT_DISABLE_FLIP=!1,f.DEFAULT_REMEMBER_LAST_CAMERA_USED=!0,f.DEFAULT_SUPPORTED_SCAN_TYPE=[Vt.SCAN_TYPE_CAMERA,Vt.SCAN_TYPE_FILE],f})(),Yr=(function(){function f(u,l){this.format=u,this.formatName=l}return f.prototype.toString=function(){return this.formatName},f.create=function(u){if(!_r.has(u))throw"".concat(u," not in html5QrcodeSupportedFormatsTextMap");return new f(u,_r.get(u))},f})(),Rr=(function(){function f(){}return f.createFromText=function(u){var l={text:u};return{decodedText:u,result:l}},f.createFromQrcodeResult=function(u){return{decodedText:u.text,result:u}},f})(),or;(function(f){f[f.UNKWOWN_ERROR=0]="UNKWOWN_ERROR",f[f.IMPLEMENTATION_ERROR=1]="IMPLEMENTATION_ERROR",f[f.NO_CODE_FOUND_ERROR=2]="NO_CODE_FOUND_ERROR"})(or||(or={}));var Xr=(function(){function f(){}return f.createFrom=function(u){return{errorMessage:u,type:or.UNKWOWN_ERROR}},f})(),Zr=(function(){function f(u){this.verbose=u}return f.prototype.log=function(u){this.verbose&&console.log(u)},f.prototype.warn=function(u){this.verbose&&console.warn(u)},f.prototype.logError=function(u,l){(this.verbose||l===!0)&&console.error(u)},f.prototype.logErrors=function(u){if(u.length===0)throw"Logger#logError called without arguments";this.verbose&&console.error(u)},f})();function Nt(f){return typeof f>"u"||f===null}function Di(f,u,l){return f>l?l:f<u?u:f}var an=(function(){function f(){}return f.codeParseError=function(u){return"QR code parse error, error = ".concat(u)},f.errorGettingUserMedia=function(u){return"Error getting userMedia, error = ".concat(u)},f.onlyDeviceSupportedError=function(){return"The device doesn't support navigator.mediaDevices , only supported cameraIdOrConfig in this case is deviceId parameter (string)."},f.cameraStreamingNotSupported=function(){return"Camera streaming not supported by the browser."},f.unableToQuerySupportedDevices=function(){return"Unable to query supported devices, unknown error."},f.insecureContextCameraQueryError=function(){return"Camera access is only supported in secure context like https or localhost."},f.scannerPaused=function(){return"Scanner paused"},f})(),xe=(function(){function f(){}return f.scanningStatus=function(){return"Scanning"},f.idleStatus=function(){return"Idle"},f.errorStatus=function(){return"Error"},f.permissionStatus=function(){return"Permission"},f.noCameraFoundErrorStatus=function(){return"No Cameras"},f.lastMatch=function(u){return"Last Match: ".concat(u)},f.codeScannerTitle=function(){return"Code Scanner"},f.cameraPermissionTitle=function(){return"Request Camera Permissions"},f.cameraPermissionRequesting=function(){return"Requesting camera permissions..."},f.noCameraFound=function(){return"No camera found"},f.scanButtonStopScanningText=function(){return"Stop Scanning"},f.scanButtonStartScanningText=function(){return"Start Scanning"},f.torchOnButton=function(){return"Switch On Torch"},f.torchOffButton=function(){return"Switch Off Torch"},f.torchOnFailedMessage=function(){return"Failed to turn on torch"},f.torchOffFailedMessage=function(){return"Failed to turn off torch"},f.scanButtonScanningStarting=function(){return"Launching Camera..."},f.textIfCameraScanSelected=function(){return"Scan an Image File"},f.textIfFileScanSelected=function(){return"Scan using camera directly"},f.selectCamera=function(){return"Select Camera"},f.fileSelectionChooseImage=function(){return"Choose Image"},f.fileSelectionChooseAnother=function(){return"Choose Another"},f.fileSelectionNoImageSelected=function(){return"No image choosen"},f.anonymousCameraPrefix=function(){return"Anonymous Camera"},f.dragAndDropMessage=function(){return"Or drop an image to scan"},f.dragAndDropMessageOnlyImages=function(){return"Or drop an image to scan (other files not supported)"},f.zoom=function(){return"zoom"},f.loadingImage=function(){return"Loading image..."},f.cameraScanAltText=function(){return"Camera based scan"},f.fileScanAltText=function(){return"Fule based scan"},f})(),Lr=(function(){function f(){}return f.poweredBy=function(){return"Powered by "},f.reportIssues=function(){return"Report issues"},f})(),Qr=(function(){function f(){}return f.isMediaStreamConstraintsValid=function(u,l){if(typeof u!="object"){var w=typeof u;return l.logError("videoConstraints should be of type object, the "+"object passed is of type ".concat(w,"."),!0),!1}for(var E=["autoGainControl","channelCount","echoCancellation","latency","noiseSuppression","sampleRate","sampleSize","volume"],x=new Set(E),T=Object.keys(u),D=0,L=T;D<L.length;D++){var C=L[D];if(x.has(C))return l.logError("".concat(C," is not supported videoConstaints."),!0),!1}return!0},f})(),mn={exports:{}},Ri=mn.exports,Br;function Li(){return Br||(Br=1,(function(f,u){(function(l,w){w(u)})(Ri,(function(l){function w(d){return d==null}var E=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,e){d.__proto__=e}||function(d,e){for(var t in e)e.hasOwnProperty(t)&&(d[t]=e[t])};function x(d,e){E(d,e);function t(){this.constructor=d}d.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function T(d,e){var t=Object.setPrototypeOf;t?t(d,e):d.__proto__=e}function D(d,e){e===void 0&&(e=d.constructor);var t=Error.captureStackTrace;t&&t(d,e)}var L=(function(d){x(e,d);function e(t){var n=this.constructor,r=d.call(this,t)||this;return Object.defineProperty(r,"name",{value:n.name,enumerable:!1}),T(r,n.prototype),D(r),r}return e})(Error);class C extends L{constructor(e=void 0){super(e),this.message=e}getKind(){return this.constructor.kind}}C.kind="Exception";class _ extends C{}_.kind="ArgumentException";class O extends C{}O.kind="IllegalArgumentException";class ie{constructor(e){if(this.binarizer=e,e===null)throw new O("Binarizer must be non-null.")}getWidth(){return this.binarizer.getWidth()}getHeight(){return this.binarizer.getHeight()}getBlackRow(e,t){return this.binarizer.getBlackRow(e,t)}getBlackMatrix(){return(this.matrix===null||this.matrix===void 0)&&(this.matrix=this.binarizer.getBlackMatrix()),this.matrix}isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported()}crop(e,t,n,r){const i=this.binarizer.getLuminanceSource().crop(e,t,n,r);return new ie(this.binarizer.createBinarizer(i))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new ie(this.binarizer.createBinarizer(e))}rotateCounterClockwise45(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new ie(this.binarizer.createBinarizer(e))}toString(){try{return this.getBlackMatrix().toString()}catch{return""}}}class J extends C{static getChecksumInstance(){return new J}}J.kind="ChecksumException";class Be{constructor(e){this.source=e}getLuminanceSource(){return this.source}getWidth(){return this.source.getWidth()}getHeight(){return this.source.getHeight()}}class K{static arraycopy(e,t,n,r,i){for(;i--;)n[r++]=e[t++]}static currentTimeMillis(){return Date.now()}}class Ie extends C{}Ie.kind="IndexOutOfBoundsException";class Ze extends Ie{constructor(e=void 0,t=void 0){super(t),this.index=e,this.message=t}}Ze.kind="ArrayIndexOutOfBoundsException";class le{static fill(e,t){for(let n=0,r=e.length;n<r;n++)e[n]=t}static fillWithin(e,t,n,r){le.rangeCheck(e.length,t,n);for(let i=t;i<n;i++)e[i]=r}static rangeCheck(e,t,n){if(t>n)throw new O("fromIndex("+t+") > toIndex("+n+")");if(t<0)throw new Ze(t);if(n>e)throw new Ze(n)}static asList(...e){return e}static create(e,t,n){return Array.from({length:e}).map(i=>Array.from({length:t}).fill(n))}static createInt32Array(e,t,n){return Array.from({length:e}).map(i=>Int32Array.from({length:t}).fill(n))}static equals(e,t){if(!e||!t||!e.length||!t.length||e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(e[n]!==t[n])return!1;return!0}static hashCode(e){if(e===null)return 0;let t=1;for(const n of e)t=31*t+n;return t}static fillUint8Array(e,t){for(let n=0;n!==e.length;n++)e[n]=t}static copyOf(e,t){return e.slice(0,t)}static copyOfUint8Array(e,t){if(e.length<=t){const n=new Uint8Array(t);return n.set(e),n}return e.slice(0,t)}static copyOfRange(e,t,n){const r=n-t,i=new Int32Array(r);return K.arraycopy(e,t,i,0,r),i}static binarySearch(e,t,n){n===void 0&&(n=le.numberComparator);let r=0,i=e.length-1;for(;r<=i;){const s=i+r>>1,o=n(t,e[s]);if(o>0)r=s+1;else if(o<0)i=s-1;else return s}return-r-1}static numberComparator(e,t){return e-t}}class Q{static numberOfTrailingZeros(e){let t;if(e===0)return 32;let n=31;return t=e<<16,t!==0&&(n-=16,e=t),t=e<<8,t!==0&&(n-=8,e=t),t=e<<4,t!==0&&(n-=4,e=t),t=e<<2,t!==0&&(n-=2,e=t),n-(e<<1>>>31)}static numberOfLeadingZeros(e){if(e===0)return 32;let t=1;return e>>>16||(t+=16,e<<=16),e>>>24||(t+=8,e<<=8),e>>>28||(t+=4,e<<=4),e>>>30||(t+=2,e<<=2),t-=e>>>31,t}static toHexString(e){return e.toString(16)}static toBinaryString(e){return String(parseInt(String(e),2))}static bitCount(e){return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,e=e+(e>>>8),e=e+(e>>>16),e&63}static truncDivision(e,t){return Math.trunc(e/t)}static parseInt(e,t=void 0){return parseInt(e,t)}}Q.MIN_VALUE_32_BITS=-2147483648,Q.MAX_VALUE=Number.MAX_SAFE_INTEGER;class ce{constructor(e,t){e===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=e,t==null?this.bits=ce.makeArray(e):this.bits=t)}getSize(){return this.size}getSizeInBytes(){return Math.floor((this.size+7)/8)}ensureCapacity(e){if(e>this.bits.length*32){const t=ce.makeArray(e);K.arraycopy(this.bits,0,t,0,this.bits.length),this.bits=t}}get(e){return(this.bits[Math.floor(e/32)]&1<<(e&31))!==0}set(e){this.bits[Math.floor(e/32)]|=1<<(e&31)}flip(e){this.bits[Math.floor(e/32)]^=1<<(e&31)}getNextSet(e){const t=this.size;if(e>=t)return t;const n=this.bits;let r=Math.floor(e/32),i=n[r];i&=~((1<<(e&31))-1);const s=n.length;for(;i===0;){if(++r===s)return t;i=n[r]}const o=r*32+Q.numberOfTrailingZeros(i);return o>t?t:o}getNextUnset(e){const t=this.size;if(e>=t)return t;const n=this.bits;let r=Math.floor(e/32),i=~n[r];i&=~((1<<(e&31))-1);const s=n.length;for(;i===0;){if(++r===s)return t;i=~n[r]}const o=r*32+Q.numberOfTrailingZeros(i);return o>t?t:o}setBulk(e,t){this.bits[Math.floor(e/32)]=t}setRange(e,t){if(t<e||e<0||t>this.size)throw new O;if(t===e)return;t--;const n=Math.floor(e/32),r=Math.floor(t/32),i=this.bits;for(let s=n;s<=r;s++){const o=s>n?0:e&31,c=(2<<(s<r?31:t&31))-(1<<o);i[s]|=c}}clear(){const e=this.bits.length,t=this.bits;for(let n=0;n<e;n++)t[n]=0}isRange(e,t,n){if(t<e||e<0||t>this.size)throw new O;if(t===e)return!0;t--;const r=Math.floor(e/32),i=Math.floor(t/32),s=this.bits;for(let o=r;o<=i;o++){const a=o>r?0:e&31,h=(2<<(o<i?31:t&31))-(1<<a)&4294967295;if((s[o]&h)!==(n?h:0))return!1}return!0}appendBit(e){this.ensureCapacity(this.size+1),e&&(this.bits[Math.floor(this.size/32)]|=1<<(this.size&31)),this.size++}appendBits(e,t){if(t<0||t>32)throw new O("Num bits must be between 0 and 32");this.ensureCapacity(this.size+t);for(let n=t;n>0;n--)this.appendBit((e>>n-1&1)===1)}appendBitArray(e){const t=e.size;this.ensureCapacity(this.size+t);for(let n=0;n<t;n++)this.appendBit(e.get(n))}xor(e){if(this.size!==e.size)throw new O("Sizes don't match");const t=this.bits;for(let n=0,r=t.length;n<r;n++)t[n]^=e.bits[n]}toBytes(e,t,n,r){for(let i=0;i<r;i++){let s=0;for(let o=0;o<8;o++)this.get(e)&&(s|=1<<7-o),e++;t[n+i]=s}}getBitArray(){return this.bits}reverse(){const e=new Int32Array(this.bits.length),t=Math.floor((this.size-1)/32),n=t+1,r=this.bits;for(let i=0;i<n;i++){let s=r[i];s=s>>1&1431655765|(s&1431655765)<<1,s=s>>2&858993459|(s&858993459)<<2,s=s>>4&252645135|(s&252645135)<<4,s=s>>8&16711935|(s&16711935)<<8,s=s>>16&65535|(s&65535)<<16,e[t-i]=s}if(this.size!==n*32){const i=n*32-this.size;let s=e[0]>>>i;for(let o=1;o<n;o++){const a=e[o];s|=a<<32-i,e[o-1]=s,s=a>>>i}e[n-1]=s}this.bits=e}static makeArray(e){return new Int32Array(Math.floor((e+31)/32))}equals(e){if(!(e instanceof ce))return!1;const t=e;return this.size===t.size&&le.equals(this.bits,t.bits)}hashCode(){return 31*this.size+le.hashCode(this.bits)}toString(){let e="";for(let t=0,n=this.size;t<n;t++)(t&7)===0&&(e+=" "),e+=this.get(t)?"X":".";return e}clone(){return new ce(this.size,this.bits.slice())}}var _t;(function(d){d[d.OTHER=0]="OTHER",d[d.PURE_BARCODE=1]="PURE_BARCODE",d[d.POSSIBLE_FORMATS=2]="POSSIBLE_FORMATS",d[d.TRY_HARDER=3]="TRY_HARDER",d[d.CHARACTER_SET=4]="CHARACTER_SET",d[d.ALLOWED_LENGTHS=5]="ALLOWED_LENGTHS",d[d.ASSUME_CODE_39_CHECK_DIGIT=6]="ASSUME_CODE_39_CHECK_DIGIT",d[d.ASSUME_GS1=7]="ASSUME_GS1",d[d.RETURN_CODABAR_START_END=8]="RETURN_CODABAR_START_END",d[d.NEED_RESULT_POINT_CALLBACK=9]="NEED_RESULT_POINT_CALLBACK",d[d.ALLOWED_EAN_EXTENSIONS=10]="ALLOWED_EAN_EXTENSIONS"})(_t||(_t={}));var we=_t;class U extends C{static getFormatInstance(){return new U}}U.kind="FormatException";var ge;(function(d){d[d.Cp437=0]="Cp437",d[d.ISO8859_1=1]="ISO8859_1",d[d.ISO8859_2=2]="ISO8859_2",d[d.ISO8859_3=3]="ISO8859_3",d[d.ISO8859_4=4]="ISO8859_4",d[d.ISO8859_5=5]="ISO8859_5",d[d.ISO8859_6=6]="ISO8859_6",d[d.ISO8859_7=7]="ISO8859_7",d[d.ISO8859_8=8]="ISO8859_8",d[d.ISO8859_9=9]="ISO8859_9",d[d.ISO8859_10=10]="ISO8859_10",d[d.ISO8859_11=11]="ISO8859_11",d[d.ISO8859_13=12]="ISO8859_13",d[d.ISO8859_14=13]="ISO8859_14",d[d.ISO8859_15=14]="ISO8859_15",d[d.ISO8859_16=15]="ISO8859_16",d[d.SJIS=16]="SJIS",d[d.Cp1250=17]="Cp1250",d[d.Cp1251=18]="Cp1251",d[d.Cp1252=19]="Cp1252",d[d.Cp1256=20]="Cp1256",d[d.UnicodeBigUnmarked=21]="UnicodeBigUnmarked",d[d.UTF8=22]="UTF8",d[d.ASCII=23]="ASCII",d[d.Big5=24]="Big5",d[d.GB18030=25]="GB18030",d[d.EUC_KR=26]="EUC_KR"})(ge||(ge={}));class k{constructor(e,t,n,...r){this.valueIdentifier=e,this.name=n,typeof t=="number"?this.values=Int32Array.from([t]):this.values=t,this.otherEncodingNames=r,k.VALUE_IDENTIFIER_TO_ECI.set(e,this),k.NAME_TO_ECI.set(n,this);const i=this.values;for(let s=0,o=i.length;s!==o;s++){const a=i[s];k.VALUES_TO_ECI.set(a,this)}for(const s of r)k.NAME_TO_ECI.set(s,this)}getValueIdentifier(){return this.valueIdentifier}getName(){return this.name}getValue(){return this.values[0]}static getCharacterSetECIByValue(e){if(e<0||e>=900)throw new U("incorect value");const t=k.VALUES_TO_ECI.get(e);if(t===void 0)throw new U("incorect value");return t}static getCharacterSetECIByName(e){const t=k.NAME_TO_ECI.get(e);if(t===void 0)throw new U("incorect value");return t}equals(e){if(!(e instanceof k))return!1;const t=e;return this.getName()===t.getName()}}k.VALUE_IDENTIFIER_TO_ECI=new Map,k.VALUES_TO_ECI=new Map,k.NAME_TO_ECI=new Map,k.Cp437=new k(ge.Cp437,Int32Array.from([0,2]),"Cp437"),k.ISO8859_1=new k(ge.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),k.ISO8859_2=new k(ge.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),k.ISO8859_3=new k(ge.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),k.ISO8859_4=new k(ge.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),k.ISO8859_5=new k(ge.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),k.ISO8859_6=new k(ge.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),k.ISO8859_7=new k(ge.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),k.ISO8859_8=new k(ge.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),k.ISO8859_9=new k(ge.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),k.ISO8859_10=new k(ge.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),k.ISO8859_11=new k(ge.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),k.ISO8859_13=new k(ge.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),k.ISO8859_14=new k(ge.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),k.ISO8859_15=new k(ge.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),k.ISO8859_16=new k(ge.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),k.SJIS=new k(ge.SJIS,20,"SJIS","Shift_JIS"),k.Cp1250=new k(ge.Cp1250,21,"Cp1250","windows-1250"),k.Cp1251=new k(ge.Cp1251,22,"Cp1251","windows-1251"),k.Cp1252=new k(ge.Cp1252,23,"Cp1252","windows-1252"),k.Cp1256=new k(ge.Cp1256,24,"Cp1256","windows-1256"),k.UnicodeBigUnmarked=new k(ge.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),k.UTF8=new k(ge.UTF8,26,"UTF8","UTF-8"),k.ASCII=new k(ge.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),k.Big5=new k(ge.Big5,28,"Big5"),k.GB18030=new k(ge.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),k.EUC_KR=new k(ge.EUC_KR,30,"EUC_KR","EUC-KR");class Qt extends C{}Qt.kind="UnsupportedOperationException";class tt{static decode(e,t){const n=this.encodingName(t);return this.customDecoder?this.customDecoder(e,n):typeof TextDecoder>"u"||this.shouldDecodeOnFallback(n)?this.decodeFallback(e,n):new TextDecoder(n).decode(e)}static shouldDecodeOnFallback(e){return!tt.isBrowser()&&e==="ISO-8859-1"}static encode(e,t){const n=this.encodingName(t);return this.customEncoder?this.customEncoder(e,n):typeof TextEncoder>"u"?this.encodeFallback(e):new TextEncoder().encode(e)}static isBrowser(){return typeof window<"u"&&{}.toString.call(window)==="[object Window]"}static encodingName(e){return typeof e=="string"?e:e.getName()}static encodingCharacterSet(e){return e instanceof k?e:k.getCharacterSetECIByName(e)}static decodeFallback(e,t){const n=this.encodingCharacterSet(t);if(tt.isDecodeFallbackSupported(n)){let r="";for(let i=0,s=e.length;i<s;i++){let o=e[i].toString(16);o.length<2&&(o="0"+o),r+="%"+o}return decodeURIComponent(r)}if(n.equals(k.UnicodeBigUnmarked))return String.fromCharCode.apply(null,new Uint16Array(e.buffer));throw new Qt(`Encoding ${this.encodingName(t)} not supported by fallback.`)}static isDecodeFallbackSupported(e){return e.equals(k.UTF8)||e.equals(k.ISO8859_1)||e.equals(k.ASCII)}static encodeFallback(e){const n=btoa(unescape(encodeURIComponent(e))).split(""),r=[];for(let i=0;i<n.length;i++)r.push(n[i].charCodeAt(0));return new Uint8Array(r)}}class q{static castAsNonUtf8Char(e,t=null){const n=t?t.getName():this.ISO88591;return tt.decode(new Uint8Array([e]),n)}static guessEncoding(e,t){if(t!=null&&t.get(we.CHARACTER_SET)!==void 0)return t.get(we.CHARACTER_SET).toString();const n=e.length;let r=!0,i=!0,s=!0,o=0,a=0,c=0,h=0,g=0,A=0,m=0,I=0,S=0,y=0,M=0;const P=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let F=0;F<n&&(r||i||s);F++){const v=e[F]&255;s&&(o>0?(v&128)===0?s=!1:o--:(v&128)!==0&&((v&64)===0?s=!1:(o++,(v&32)===0?a++:(o++,(v&16)===0?c++:(o++,(v&8)===0?h++:s=!1))))),r&&(v>127&&v<160?r=!1:v>159&&(v<192||v===215||v===247)&&M++),i&&(g>0?v<64||v===127||v>252?i=!1:g--:v===128||v===160||v>239?i=!1:v>160&&v<224?(A++,I=0,m++,m>S&&(S=m)):v>127?(g++,m=0,I++,I>y&&(y=I)):(m=0,I=0))}return s&&o>0&&(s=!1),i&&g>0&&(i=!1),s&&(P||a+c+h>0)?q.UTF8:i&&(q.ASSUME_SHIFT_JIS||S>=3||y>=3)?q.SHIFT_JIS:r&&i?S===2&&A===2||M*10>=n?q.SHIFT_JIS:q.ISO88591:r?q.ISO88591:i?q.SHIFT_JIS:s?q.UTF8:q.PLATFORM_DEFAULT_ENCODING}static format(e,...t){let n=-1;function r(s,o,a,c,h,g){if(s==="%%")return"%";if(t[++n]===void 0)return;s=c?parseInt(c.substr(1)):void 0;let A=h?parseInt(h.substr(1)):void 0,m;switch(g){case"s":m=t[n];break;case"c":m=t[n][0];break;case"f":m=parseFloat(t[n]).toFixed(s);break;case"p":m=parseFloat(t[n]).toPrecision(s);break;case"e":m=parseFloat(t[n]).toExponential(s);break;case"x":m=parseInt(t[n]).toString(A||16);break;case"d":m=parseFloat(parseInt(t[n],A||10).toPrecision(s)).toFixed(0);break}m=typeof m=="object"?JSON.stringify(m):(+m).toString(A);let I=parseInt(a),S=a&&a[0]+""=="0"?"0":" ";for(;m.length<I;)m=o!==void 0?m+S:S+m;return m}let i=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(i,r)}static getBytes(e,t){return tt.encode(e,t)}static getCharCode(e,t=0){return e.charCodeAt(t)}static getCharAt(e){return String.fromCharCode(e)}}q.SHIFT_JIS=k.SJIS.getName(),q.GB2312="GB2312",q.ISO88591=k.ISO8859_1.getName(),q.EUC_JP="EUC_JP",q.UTF8=k.UTF8.getName(),q.PLATFORM_DEFAULT_ENCODING=q.UTF8,q.ASSUME_SHIFT_JIS=!1;class Ae{constructor(e=""){this.value=e}enableDecoding(e){return this.encoding=e,this}append(e){return typeof e=="string"?this.value+=e.toString():this.encoding?this.value+=q.castAsNonUtf8Char(e,this.encoding):this.value+=String.fromCharCode(e),this}appendChars(e,t,n){for(let r=t;t<t+n;r++)this.append(e[r]);return this}length(){return this.value.length}charAt(e){return this.value.charAt(e)}deleteCharAt(e){this.value=this.value.substr(0,e)+this.value.substring(e+1)}setCharAt(e,t){this.value=this.value.substr(0,e)+t+this.value.substr(e+1)}substring(e,t){return this.value.substring(e,t)}setLengthToZero(){this.value=""}toString(){return this.value}insert(e,t){this.value=this.value.substr(0,e)+t+this.value.substr(e+t.length)}}class Ue{constructor(e,t,n,r){if(this.width=e,this.height=t,this.rowSize=n,this.bits=r,t==null&&(t=e),this.height=t,e<1||t<1)throw new O("Both dimensions must be greater than 0");n==null&&(n=Math.floor((e+31)/32)),this.rowSize=n,r==null&&(this.bits=new Int32Array(this.rowSize*this.height))}static parseFromBooleanArray(e){const t=e.length,n=e[0].length,r=new Ue(n,t);for(let i=0;i<t;i++){const s=e[i];for(let o=0;o<n;o++)s[o]&&r.set(o,i)}return r}static parseFromString(e,t,n){if(e===null)throw new O("stringRepresentation cannot be null");const r=new Array(e.length);let i=0,s=0,o=-1,a=0,c=0;for(;c<e.length;)if(e.charAt(c)===`
1
+ import{c as vn}from"./index-DLLnAccl.js";var z;(function(f){f[f.QR_CODE=0]="QR_CODE",f[f.AZTEC=1]="AZTEC",f[f.CODABAR=2]="CODABAR",f[f.CODE_39=3]="CODE_39",f[f.CODE_93=4]="CODE_93",f[f.CODE_128=5]="CODE_128",f[f.DATA_MATRIX=6]="DATA_MATRIX",f[f.MAXICODE=7]="MAXICODE",f[f.ITF=8]="ITF",f[f.EAN_13=9]="EAN_13",f[f.EAN_8=10]="EAN_8",f[f.PDF_417=11]="PDF_417",f[f.RSS_14=12]="RSS_14",f[f.RSS_EXPANDED=13]="RSS_EXPANDED",f[f.UPC_A=14]="UPC_A",f[f.UPC_E=15]="UPC_E",f[f.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(z||(z={}));var _r=new Map([[z.QR_CODE,"QR_CODE"],[z.AZTEC,"AZTEC"],[z.CODABAR,"CODABAR"],[z.CODE_39,"CODE_39"],[z.CODE_93,"CODE_93"],[z.CODE_128,"CODE_128"],[z.DATA_MATRIX,"DATA_MATRIX"],[z.MAXICODE,"MAXICODE"],[z.ITF,"ITF"],[z.EAN_13,"EAN_13"],[z.EAN_8,"EAN_8"],[z.PDF_417,"PDF_417"],[z.RSS_14,"RSS_14"],[z.RSS_EXPANDED,"RSS_EXPANDED"],[z.UPC_A,"UPC_A"],[z.UPC_E,"UPC_E"],[z.UPC_EAN_EXTENSION,"UPC_EAN_EXTENSION"]]),Dr;(function(f){f[f.UNKNOWN=0]="UNKNOWN",f[f.URL=1]="URL"})(Dr||(Dr={}));function _i(f){return Object.values(z).includes(f)}var Vt;(function(f){f[f.SCAN_TYPE_CAMERA=0]="SCAN_TYPE_CAMERA",f[f.SCAN_TYPE_FILE=1]="SCAN_TYPE_FILE"})(Vt||(Vt={}));var Et=(function(){function f(){}return f.GITHUB_PROJECT_URL="https://github.com/mebjas/html5-qrcode",f.SCAN_DEFAULT_FPS=2,f.DEFAULT_DISABLE_FLIP=!1,f.DEFAULT_REMEMBER_LAST_CAMERA_USED=!0,f.DEFAULT_SUPPORTED_SCAN_TYPE=[Vt.SCAN_TYPE_CAMERA,Vt.SCAN_TYPE_FILE],f})(),Yr=(function(){function f(u,l){this.format=u,this.formatName=l}return f.prototype.toString=function(){return this.formatName},f.create=function(u){if(!_r.has(u))throw"".concat(u," not in html5QrcodeSupportedFormatsTextMap");return new f(u,_r.get(u))},f})(),Rr=(function(){function f(){}return f.createFromText=function(u){var l={text:u};return{decodedText:u,result:l}},f.createFromQrcodeResult=function(u){return{decodedText:u.text,result:u}},f})(),or;(function(f){f[f.UNKWOWN_ERROR=0]="UNKWOWN_ERROR",f[f.IMPLEMENTATION_ERROR=1]="IMPLEMENTATION_ERROR",f[f.NO_CODE_FOUND_ERROR=2]="NO_CODE_FOUND_ERROR"})(or||(or={}));var Xr=(function(){function f(){}return f.createFrom=function(u){return{errorMessage:u,type:or.UNKWOWN_ERROR}},f})(),Zr=(function(){function f(u){this.verbose=u}return f.prototype.log=function(u){this.verbose&&console.log(u)},f.prototype.warn=function(u){this.verbose&&console.warn(u)},f.prototype.logError=function(u,l){(this.verbose||l===!0)&&console.error(u)},f.prototype.logErrors=function(u){if(u.length===0)throw"Logger#logError called without arguments";this.verbose&&console.error(u)},f})();function Nt(f){return typeof f>"u"||f===null}function Di(f,u,l){return f>l?l:f<u?u:f}var an=(function(){function f(){}return f.codeParseError=function(u){return"QR code parse error, error = ".concat(u)},f.errorGettingUserMedia=function(u){return"Error getting userMedia, error = ".concat(u)},f.onlyDeviceSupportedError=function(){return"The device doesn't support navigator.mediaDevices , only supported cameraIdOrConfig in this case is deviceId parameter (string)."},f.cameraStreamingNotSupported=function(){return"Camera streaming not supported by the browser."},f.unableToQuerySupportedDevices=function(){return"Unable to query supported devices, unknown error."},f.insecureContextCameraQueryError=function(){return"Camera access is only supported in secure context like https or localhost."},f.scannerPaused=function(){return"Scanner paused"},f})(),xe=(function(){function f(){}return f.scanningStatus=function(){return"Scanning"},f.idleStatus=function(){return"Idle"},f.errorStatus=function(){return"Error"},f.permissionStatus=function(){return"Permission"},f.noCameraFoundErrorStatus=function(){return"No Cameras"},f.lastMatch=function(u){return"Last Match: ".concat(u)},f.codeScannerTitle=function(){return"Code Scanner"},f.cameraPermissionTitle=function(){return"Request Camera Permissions"},f.cameraPermissionRequesting=function(){return"Requesting camera permissions..."},f.noCameraFound=function(){return"No camera found"},f.scanButtonStopScanningText=function(){return"Stop Scanning"},f.scanButtonStartScanningText=function(){return"Start Scanning"},f.torchOnButton=function(){return"Switch On Torch"},f.torchOffButton=function(){return"Switch Off Torch"},f.torchOnFailedMessage=function(){return"Failed to turn on torch"},f.torchOffFailedMessage=function(){return"Failed to turn off torch"},f.scanButtonScanningStarting=function(){return"Launching Camera..."},f.textIfCameraScanSelected=function(){return"Scan an Image File"},f.textIfFileScanSelected=function(){return"Scan using camera directly"},f.selectCamera=function(){return"Select Camera"},f.fileSelectionChooseImage=function(){return"Choose Image"},f.fileSelectionChooseAnother=function(){return"Choose Another"},f.fileSelectionNoImageSelected=function(){return"No image choosen"},f.anonymousCameraPrefix=function(){return"Anonymous Camera"},f.dragAndDropMessage=function(){return"Or drop an image to scan"},f.dragAndDropMessageOnlyImages=function(){return"Or drop an image to scan (other files not supported)"},f.zoom=function(){return"zoom"},f.loadingImage=function(){return"Loading image..."},f.cameraScanAltText=function(){return"Camera based scan"},f.fileScanAltText=function(){return"Fule based scan"},f})(),Lr=(function(){function f(){}return f.poweredBy=function(){return"Powered by "},f.reportIssues=function(){return"Report issues"},f})(),Qr=(function(){function f(){}return f.isMediaStreamConstraintsValid=function(u,l){if(typeof u!="object"){var w=typeof u;return l.logError("videoConstraints should be of type object, the "+"object passed is of type ".concat(w,"."),!0),!1}for(var E=["autoGainControl","channelCount","echoCancellation","latency","noiseSuppression","sampleRate","sampleSize","volume"],x=new Set(E),T=Object.keys(u),D=0,L=T;D<L.length;D++){var C=L[D];if(x.has(C))return l.logError("".concat(C," is not supported videoConstaints."),!0),!1}return!0},f})(),mn={exports:{}},Ri=mn.exports,Br;function Li(){return Br||(Br=1,(function(f,u){(function(l,w){w(u)})(Ri,(function(l){function w(d){return d==null}var E=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,e){d.__proto__=e}||function(d,e){for(var t in e)e.hasOwnProperty(t)&&(d[t]=e[t])};function x(d,e){E(d,e);function t(){this.constructor=d}d.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function T(d,e){var t=Object.setPrototypeOf;t?t(d,e):d.__proto__=e}function D(d,e){e===void 0&&(e=d.constructor);var t=Error.captureStackTrace;t&&t(d,e)}var L=(function(d){x(e,d);function e(t){var n=this.constructor,r=d.call(this,t)||this;return Object.defineProperty(r,"name",{value:n.name,enumerable:!1}),T(r,n.prototype),D(r),r}return e})(Error);class C extends L{constructor(e=void 0){super(e),this.message=e}getKind(){return this.constructor.kind}}C.kind="Exception";class _ extends C{}_.kind="ArgumentException";class O extends C{}O.kind="IllegalArgumentException";class ie{constructor(e){if(this.binarizer=e,e===null)throw new O("Binarizer must be non-null.")}getWidth(){return this.binarizer.getWidth()}getHeight(){return this.binarizer.getHeight()}getBlackRow(e,t){return this.binarizer.getBlackRow(e,t)}getBlackMatrix(){return(this.matrix===null||this.matrix===void 0)&&(this.matrix=this.binarizer.getBlackMatrix()),this.matrix}isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported()}crop(e,t,n,r){const i=this.binarizer.getLuminanceSource().crop(e,t,n,r);return new ie(this.binarizer.createBinarizer(i))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new ie(this.binarizer.createBinarizer(e))}rotateCounterClockwise45(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new ie(this.binarizer.createBinarizer(e))}toString(){try{return this.getBlackMatrix().toString()}catch{return""}}}class J extends C{static getChecksumInstance(){return new J}}J.kind="ChecksumException";class Be{constructor(e){this.source=e}getLuminanceSource(){return this.source}getWidth(){return this.source.getWidth()}getHeight(){return this.source.getHeight()}}class K{static arraycopy(e,t,n,r,i){for(;i--;)n[r++]=e[t++]}static currentTimeMillis(){return Date.now()}}class Ie extends C{}Ie.kind="IndexOutOfBoundsException";class Ze extends Ie{constructor(e=void 0,t=void 0){super(t),this.index=e,this.message=t}}Ze.kind="ArrayIndexOutOfBoundsException";class le{static fill(e,t){for(let n=0,r=e.length;n<r;n++)e[n]=t}static fillWithin(e,t,n,r){le.rangeCheck(e.length,t,n);for(let i=t;i<n;i++)e[i]=r}static rangeCheck(e,t,n){if(t>n)throw new O("fromIndex("+t+") > toIndex("+n+")");if(t<0)throw new Ze(t);if(n>e)throw new Ze(n)}static asList(...e){return e}static create(e,t,n){return Array.from({length:e}).map(i=>Array.from({length:t}).fill(n))}static createInt32Array(e,t,n){return Array.from({length:e}).map(i=>Int32Array.from({length:t}).fill(n))}static equals(e,t){if(!e||!t||!e.length||!t.length||e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(e[n]!==t[n])return!1;return!0}static hashCode(e){if(e===null)return 0;let t=1;for(const n of e)t=31*t+n;return t}static fillUint8Array(e,t){for(let n=0;n!==e.length;n++)e[n]=t}static copyOf(e,t){return e.slice(0,t)}static copyOfUint8Array(e,t){if(e.length<=t){const n=new Uint8Array(t);return n.set(e),n}return e.slice(0,t)}static copyOfRange(e,t,n){const r=n-t,i=new Int32Array(r);return K.arraycopy(e,t,i,0,r),i}static binarySearch(e,t,n){n===void 0&&(n=le.numberComparator);let r=0,i=e.length-1;for(;r<=i;){const s=i+r>>1,o=n(t,e[s]);if(o>0)r=s+1;else if(o<0)i=s-1;else return s}return-r-1}static numberComparator(e,t){return e-t}}class Q{static numberOfTrailingZeros(e){let t;if(e===0)return 32;let n=31;return t=e<<16,t!==0&&(n-=16,e=t),t=e<<8,t!==0&&(n-=8,e=t),t=e<<4,t!==0&&(n-=4,e=t),t=e<<2,t!==0&&(n-=2,e=t),n-(e<<1>>>31)}static numberOfLeadingZeros(e){if(e===0)return 32;let t=1;return e>>>16||(t+=16,e<<=16),e>>>24||(t+=8,e<<=8),e>>>28||(t+=4,e<<=4),e>>>30||(t+=2,e<<=2),t-=e>>>31,t}static toHexString(e){return e.toString(16)}static toBinaryString(e){return String(parseInt(String(e),2))}static bitCount(e){return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,e=e+(e>>>8),e=e+(e>>>16),e&63}static truncDivision(e,t){return Math.trunc(e/t)}static parseInt(e,t=void 0){return parseInt(e,t)}}Q.MIN_VALUE_32_BITS=-2147483648,Q.MAX_VALUE=Number.MAX_SAFE_INTEGER;class ce{constructor(e,t){e===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=e,t==null?this.bits=ce.makeArray(e):this.bits=t)}getSize(){return this.size}getSizeInBytes(){return Math.floor((this.size+7)/8)}ensureCapacity(e){if(e>this.bits.length*32){const t=ce.makeArray(e);K.arraycopy(this.bits,0,t,0,this.bits.length),this.bits=t}}get(e){return(this.bits[Math.floor(e/32)]&1<<(e&31))!==0}set(e){this.bits[Math.floor(e/32)]|=1<<(e&31)}flip(e){this.bits[Math.floor(e/32)]^=1<<(e&31)}getNextSet(e){const t=this.size;if(e>=t)return t;const n=this.bits;let r=Math.floor(e/32),i=n[r];i&=~((1<<(e&31))-1);const s=n.length;for(;i===0;){if(++r===s)return t;i=n[r]}const o=r*32+Q.numberOfTrailingZeros(i);return o>t?t:o}getNextUnset(e){const t=this.size;if(e>=t)return t;const n=this.bits;let r=Math.floor(e/32),i=~n[r];i&=~((1<<(e&31))-1);const s=n.length;for(;i===0;){if(++r===s)return t;i=~n[r]}const o=r*32+Q.numberOfTrailingZeros(i);return o>t?t:o}setBulk(e,t){this.bits[Math.floor(e/32)]=t}setRange(e,t){if(t<e||e<0||t>this.size)throw new O;if(t===e)return;t--;const n=Math.floor(e/32),r=Math.floor(t/32),i=this.bits;for(let s=n;s<=r;s++){const o=s>n?0:e&31,c=(2<<(s<r?31:t&31))-(1<<o);i[s]|=c}}clear(){const e=this.bits.length,t=this.bits;for(let n=0;n<e;n++)t[n]=0}isRange(e,t,n){if(t<e||e<0||t>this.size)throw new O;if(t===e)return!0;t--;const r=Math.floor(e/32),i=Math.floor(t/32),s=this.bits;for(let o=r;o<=i;o++){const a=o>r?0:e&31,h=(2<<(o<i?31:t&31))-(1<<a)&4294967295;if((s[o]&h)!==(n?h:0))return!1}return!0}appendBit(e){this.ensureCapacity(this.size+1),e&&(this.bits[Math.floor(this.size/32)]|=1<<(this.size&31)),this.size++}appendBits(e,t){if(t<0||t>32)throw new O("Num bits must be between 0 and 32");this.ensureCapacity(this.size+t);for(let n=t;n>0;n--)this.appendBit((e>>n-1&1)===1)}appendBitArray(e){const t=e.size;this.ensureCapacity(this.size+t);for(let n=0;n<t;n++)this.appendBit(e.get(n))}xor(e){if(this.size!==e.size)throw new O("Sizes don't match");const t=this.bits;for(let n=0,r=t.length;n<r;n++)t[n]^=e.bits[n]}toBytes(e,t,n,r){for(let i=0;i<r;i++){let s=0;for(let o=0;o<8;o++)this.get(e)&&(s|=1<<7-o),e++;t[n+i]=s}}getBitArray(){return this.bits}reverse(){const e=new Int32Array(this.bits.length),t=Math.floor((this.size-1)/32),n=t+1,r=this.bits;for(let i=0;i<n;i++){let s=r[i];s=s>>1&1431655765|(s&1431655765)<<1,s=s>>2&858993459|(s&858993459)<<2,s=s>>4&252645135|(s&252645135)<<4,s=s>>8&16711935|(s&16711935)<<8,s=s>>16&65535|(s&65535)<<16,e[t-i]=s}if(this.size!==n*32){const i=n*32-this.size;let s=e[0]>>>i;for(let o=1;o<n;o++){const a=e[o];s|=a<<32-i,e[o-1]=s,s=a>>>i}e[n-1]=s}this.bits=e}static makeArray(e){return new Int32Array(Math.floor((e+31)/32))}equals(e){if(!(e instanceof ce))return!1;const t=e;return this.size===t.size&&le.equals(this.bits,t.bits)}hashCode(){return 31*this.size+le.hashCode(this.bits)}toString(){let e="";for(let t=0,n=this.size;t<n;t++)(t&7)===0&&(e+=" "),e+=this.get(t)?"X":".";return e}clone(){return new ce(this.size,this.bits.slice())}}var _t;(function(d){d[d.OTHER=0]="OTHER",d[d.PURE_BARCODE=1]="PURE_BARCODE",d[d.POSSIBLE_FORMATS=2]="POSSIBLE_FORMATS",d[d.TRY_HARDER=3]="TRY_HARDER",d[d.CHARACTER_SET=4]="CHARACTER_SET",d[d.ALLOWED_LENGTHS=5]="ALLOWED_LENGTHS",d[d.ASSUME_CODE_39_CHECK_DIGIT=6]="ASSUME_CODE_39_CHECK_DIGIT",d[d.ASSUME_GS1=7]="ASSUME_GS1",d[d.RETURN_CODABAR_START_END=8]="RETURN_CODABAR_START_END",d[d.NEED_RESULT_POINT_CALLBACK=9]="NEED_RESULT_POINT_CALLBACK",d[d.ALLOWED_EAN_EXTENSIONS=10]="ALLOWED_EAN_EXTENSIONS"})(_t||(_t={}));var we=_t;class U extends C{static getFormatInstance(){return new U}}U.kind="FormatException";var ge;(function(d){d[d.Cp437=0]="Cp437",d[d.ISO8859_1=1]="ISO8859_1",d[d.ISO8859_2=2]="ISO8859_2",d[d.ISO8859_3=3]="ISO8859_3",d[d.ISO8859_4=4]="ISO8859_4",d[d.ISO8859_5=5]="ISO8859_5",d[d.ISO8859_6=6]="ISO8859_6",d[d.ISO8859_7=7]="ISO8859_7",d[d.ISO8859_8=8]="ISO8859_8",d[d.ISO8859_9=9]="ISO8859_9",d[d.ISO8859_10=10]="ISO8859_10",d[d.ISO8859_11=11]="ISO8859_11",d[d.ISO8859_13=12]="ISO8859_13",d[d.ISO8859_14=13]="ISO8859_14",d[d.ISO8859_15=14]="ISO8859_15",d[d.ISO8859_16=15]="ISO8859_16",d[d.SJIS=16]="SJIS",d[d.Cp1250=17]="Cp1250",d[d.Cp1251=18]="Cp1251",d[d.Cp1252=19]="Cp1252",d[d.Cp1256=20]="Cp1256",d[d.UnicodeBigUnmarked=21]="UnicodeBigUnmarked",d[d.UTF8=22]="UTF8",d[d.ASCII=23]="ASCII",d[d.Big5=24]="Big5",d[d.GB18030=25]="GB18030",d[d.EUC_KR=26]="EUC_KR"})(ge||(ge={}));class k{constructor(e,t,n,...r){this.valueIdentifier=e,this.name=n,typeof t=="number"?this.values=Int32Array.from([t]):this.values=t,this.otherEncodingNames=r,k.VALUE_IDENTIFIER_TO_ECI.set(e,this),k.NAME_TO_ECI.set(n,this);const i=this.values;for(let s=0,o=i.length;s!==o;s++){const a=i[s];k.VALUES_TO_ECI.set(a,this)}for(const s of r)k.NAME_TO_ECI.set(s,this)}getValueIdentifier(){return this.valueIdentifier}getName(){return this.name}getValue(){return this.values[0]}static getCharacterSetECIByValue(e){if(e<0||e>=900)throw new U("incorect value");const t=k.VALUES_TO_ECI.get(e);if(t===void 0)throw new U("incorect value");return t}static getCharacterSetECIByName(e){const t=k.NAME_TO_ECI.get(e);if(t===void 0)throw new U("incorect value");return t}equals(e){if(!(e instanceof k))return!1;const t=e;return this.getName()===t.getName()}}k.VALUE_IDENTIFIER_TO_ECI=new Map,k.VALUES_TO_ECI=new Map,k.NAME_TO_ECI=new Map,k.Cp437=new k(ge.Cp437,Int32Array.from([0,2]),"Cp437"),k.ISO8859_1=new k(ge.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),k.ISO8859_2=new k(ge.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),k.ISO8859_3=new k(ge.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),k.ISO8859_4=new k(ge.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),k.ISO8859_5=new k(ge.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),k.ISO8859_6=new k(ge.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),k.ISO8859_7=new k(ge.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),k.ISO8859_8=new k(ge.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),k.ISO8859_9=new k(ge.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),k.ISO8859_10=new k(ge.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),k.ISO8859_11=new k(ge.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),k.ISO8859_13=new k(ge.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),k.ISO8859_14=new k(ge.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),k.ISO8859_15=new k(ge.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),k.ISO8859_16=new k(ge.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),k.SJIS=new k(ge.SJIS,20,"SJIS","Shift_JIS"),k.Cp1250=new k(ge.Cp1250,21,"Cp1250","windows-1250"),k.Cp1251=new k(ge.Cp1251,22,"Cp1251","windows-1251"),k.Cp1252=new k(ge.Cp1252,23,"Cp1252","windows-1252"),k.Cp1256=new k(ge.Cp1256,24,"Cp1256","windows-1256"),k.UnicodeBigUnmarked=new k(ge.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),k.UTF8=new k(ge.UTF8,26,"UTF8","UTF-8"),k.ASCII=new k(ge.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),k.Big5=new k(ge.Big5,28,"Big5"),k.GB18030=new k(ge.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),k.EUC_KR=new k(ge.EUC_KR,30,"EUC_KR","EUC-KR");class Qt extends C{}Qt.kind="UnsupportedOperationException";class tt{static decode(e,t){const n=this.encodingName(t);return this.customDecoder?this.customDecoder(e,n):typeof TextDecoder>"u"||this.shouldDecodeOnFallback(n)?this.decodeFallback(e,n):new TextDecoder(n).decode(e)}static shouldDecodeOnFallback(e){return!tt.isBrowser()&&e==="ISO-8859-1"}static encode(e,t){const n=this.encodingName(t);return this.customEncoder?this.customEncoder(e,n):typeof TextEncoder>"u"?this.encodeFallback(e):new TextEncoder().encode(e)}static isBrowser(){return typeof window<"u"&&{}.toString.call(window)==="[object Window]"}static encodingName(e){return typeof e=="string"?e:e.getName()}static encodingCharacterSet(e){return e instanceof k?e:k.getCharacterSetECIByName(e)}static decodeFallback(e,t){const n=this.encodingCharacterSet(t);if(tt.isDecodeFallbackSupported(n)){let r="";for(let i=0,s=e.length;i<s;i++){let o=e[i].toString(16);o.length<2&&(o="0"+o),r+="%"+o}return decodeURIComponent(r)}if(n.equals(k.UnicodeBigUnmarked))return String.fromCharCode.apply(null,new Uint16Array(e.buffer));throw new Qt(`Encoding ${this.encodingName(t)} not supported by fallback.`)}static isDecodeFallbackSupported(e){return e.equals(k.UTF8)||e.equals(k.ISO8859_1)||e.equals(k.ASCII)}static encodeFallback(e){const n=btoa(unescape(encodeURIComponent(e))).split(""),r=[];for(let i=0;i<n.length;i++)r.push(n[i].charCodeAt(0));return new Uint8Array(r)}}class q{static castAsNonUtf8Char(e,t=null){const n=t?t.getName():this.ISO88591;return tt.decode(new Uint8Array([e]),n)}static guessEncoding(e,t){if(t!=null&&t.get(we.CHARACTER_SET)!==void 0)return t.get(we.CHARACTER_SET).toString();const n=e.length;let r=!0,i=!0,s=!0,o=0,a=0,c=0,h=0,g=0,A=0,m=0,I=0,S=0,y=0,M=0;const P=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let F=0;F<n&&(r||i||s);F++){const v=e[F]&255;s&&(o>0?(v&128)===0?s=!1:o--:(v&128)!==0&&((v&64)===0?s=!1:(o++,(v&32)===0?a++:(o++,(v&16)===0?c++:(o++,(v&8)===0?h++:s=!1))))),r&&(v>127&&v<160?r=!1:v>159&&(v<192||v===215||v===247)&&M++),i&&(g>0?v<64||v===127||v>252?i=!1:g--:v===128||v===160||v>239?i=!1:v>160&&v<224?(A++,I=0,m++,m>S&&(S=m)):v>127?(g++,m=0,I++,I>y&&(y=I)):(m=0,I=0))}return s&&o>0&&(s=!1),i&&g>0&&(i=!1),s&&(P||a+c+h>0)?q.UTF8:i&&(q.ASSUME_SHIFT_JIS||S>=3||y>=3)?q.SHIFT_JIS:r&&i?S===2&&A===2||M*10>=n?q.SHIFT_JIS:q.ISO88591:r?q.ISO88591:i?q.SHIFT_JIS:s?q.UTF8:q.PLATFORM_DEFAULT_ENCODING}static format(e,...t){let n=-1;function r(s,o,a,c,h,g){if(s==="%%")return"%";if(t[++n]===void 0)return;s=c?parseInt(c.substr(1)):void 0;let A=h?parseInt(h.substr(1)):void 0,m;switch(g){case"s":m=t[n];break;case"c":m=t[n][0];break;case"f":m=parseFloat(t[n]).toFixed(s);break;case"p":m=parseFloat(t[n]).toPrecision(s);break;case"e":m=parseFloat(t[n]).toExponential(s);break;case"x":m=parseInt(t[n]).toString(A||16);break;case"d":m=parseFloat(parseInt(t[n],A||10).toPrecision(s)).toFixed(0);break}m=typeof m=="object"?JSON.stringify(m):(+m).toString(A);let I=parseInt(a),S=a&&a[0]+""=="0"?"0":" ";for(;m.length<I;)m=o!==void 0?m+S:S+m;return m}let i=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(i,r)}static getBytes(e,t){return tt.encode(e,t)}static getCharCode(e,t=0){return e.charCodeAt(t)}static getCharAt(e){return String.fromCharCode(e)}}q.SHIFT_JIS=k.SJIS.getName(),q.GB2312="GB2312",q.ISO88591=k.ISO8859_1.getName(),q.EUC_JP="EUC_JP",q.UTF8=k.UTF8.getName(),q.PLATFORM_DEFAULT_ENCODING=q.UTF8,q.ASSUME_SHIFT_JIS=!1;class Ae{constructor(e=""){this.value=e}enableDecoding(e){return this.encoding=e,this}append(e){return typeof e=="string"?this.value+=e.toString():this.encoding?this.value+=q.castAsNonUtf8Char(e,this.encoding):this.value+=String.fromCharCode(e),this}appendChars(e,t,n){for(let r=t;t<t+n;r++)this.append(e[r]);return this}length(){return this.value.length}charAt(e){return this.value.charAt(e)}deleteCharAt(e){this.value=this.value.substr(0,e)+this.value.substring(e+1)}setCharAt(e,t){this.value=this.value.substr(0,e)+t+this.value.substr(e+1)}substring(e,t){return this.value.substring(e,t)}setLengthToZero(){this.value=""}toString(){return this.value}insert(e,t){this.value=this.value.substr(0,e)+t+this.value.substr(e+t.length)}}class Ue{constructor(e,t,n,r){if(this.width=e,this.height=t,this.rowSize=n,this.bits=r,t==null&&(t=e),this.height=t,e<1||t<1)throw new O("Both dimensions must be greater than 0");n==null&&(n=Math.floor((e+31)/32)),this.rowSize=n,r==null&&(this.bits=new Int32Array(this.rowSize*this.height))}static parseFromBooleanArray(e){const t=e.length,n=e[0].length,r=new Ue(n,t);for(let i=0;i<t;i++){const s=e[i];for(let o=0;o<n;o++)s[o]&&r.set(o,i)}return r}static parseFromString(e,t,n){if(e===null)throw new O("stringRepresentation cannot be null");const r=new Array(e.length);let i=0,s=0,o=-1,a=0,c=0;for(;c<e.length;)if(e.charAt(c)===`
2
2
  `||e.charAt(c)==="\r"){if(i>s){if(o===-1)o=i-s;else if(i-s!==o)throw new O("row lengths do not match");s=i,a++}c++}else if(e.substring(c,c+t.length)===t)c+=t.length,r[i]=!0,i++;else if(e.substring(c,c+n.length)===n)c+=n.length,r[i]=!1,i++;else throw new O("illegal character encountered: "+e.substring(c));if(i>s){if(o===-1)o=i-s;else if(i-s!==o)throw new O("row lengths do not match");a++}const h=new Ue(o,a);for(let g=0;g<i;g++)r[g]&&h.set(Math.floor(g%o),Math.floor(g/o));return h}get(e,t){const n=t*this.rowSize+Math.floor(e/32);return(this.bits[n]>>>(e&31)&1)!==0}set(e,t){const n=t*this.rowSize+Math.floor(e/32);this.bits[n]|=1<<(e&31)&4294967295}unset(e,t){const n=t*this.rowSize+Math.floor(e/32);this.bits[n]&=~(1<<(e&31)&4294967295)}flip(e,t){const n=t*this.rowSize+Math.floor(e/32);this.bits[n]^=1<<(e&31)&4294967295}xor(e){if(this.width!==e.getWidth()||this.height!==e.getHeight()||this.rowSize!==e.getRowSize())throw new O("input matrix dimensions do not match");const t=new ce(Math.floor(this.width/32)+1),n=this.rowSize,r=this.bits;for(let i=0,s=this.height;i<s;i++){const o=i*n,a=e.getRow(i,t).getBitArray();for(let c=0;c<n;c++)r[o+c]^=a[c]}}clear(){const e=this.bits,t=e.length;for(let n=0;n<t;n++)e[n]=0}setRegion(e,t,n,r){if(t<0||e<0)throw new O("Left and top must be nonnegative");if(r<1||n<1)throw new O("Height and width must be at least 1");const i=e+n,s=t+r;if(s>this.height||i>this.width)throw new O("The region must fit inside the matrix");const o=this.rowSize,a=this.bits;for(let c=t;c<s;c++){const h=c*o;for(let g=e;g<i;g++)a[h+Math.floor(g/32)]|=1<<(g&31)&4294967295}}getRow(e,t){t==null||t.getSize()<this.width?t=new ce(this.width):t.clear();const n=this.rowSize,r=this.bits,i=e*n;for(let s=0;s<n;s++)t.setBulk(s*32,r[i+s]);return t}setRow(e,t){K.arraycopy(t.getBitArray(),0,this.bits,e*this.rowSize,this.rowSize)}rotate180(){const e=this.getWidth(),t=this.getHeight();let n=new ce(e),r=new ce(e);for(let i=0,s=Math.floor((t+1)/2);i<s;i++)n=this.getRow(i,n),r=this.getRow(t-1-i,r),n.reverse(),r.reverse(),this.setRow(i,r),this.setRow(t-1-i,n)}getEnclosingRectangle(){const e=this.width,t=this.height,n=this.rowSize,r=this.bits;let i=e,s=t,o=-1,a=-1;for(let c=0;c<t;c++)for(let h=0;h<n;h++){const g=r[c*n+h];if(g!==0){if(c<s&&(s=c),c>a&&(a=c),h*32<i){let A=0;for(;(g<<31-A&4294967295)===0;)A++;h*32+A<i&&(i=h*32+A)}if(h*32+31>o){let A=31;for(;!(g>>>A);)A--;h*32+A>o&&(o=h*32+A)}}}return o<i||a<s?null:Int32Array.from([i,s,o-i+1,a-s+1])}getTopLeftOnBit(){const e=this.rowSize,t=this.bits;let n=0;for(;n<t.length&&t[n]===0;)n++;if(n===t.length)return null;const r=n/e;let i=n%e*32;const s=t[n];let o=0;for(;(s<<31-o&4294967295)===0;)o++;return i+=o,Int32Array.from([i,r])}getBottomRightOnBit(){const e=this.rowSize,t=this.bits;let n=t.length-1;for(;n>=0&&t[n]===0;)n--;if(n<0)return null;const r=Math.floor(n/e);let i=Math.floor(n%e)*32;const s=t[n];let o=31;for(;!(s>>>o);)o--;return i+=o,Int32Array.from([i,r])}getWidth(){return this.width}getHeight(){return this.height}getRowSize(){return this.rowSize}equals(e){if(!(e instanceof Ue))return!1;const t=e;return this.width===t.width&&this.height===t.height&&this.rowSize===t.rowSize&&le.equals(this.bits,t.bits)}hashCode(){let e=this.width;return e=31*e+this.width,e=31*e+this.height,e=31*e+this.rowSize,e=31*e+le.hashCode(this.bits),e}toString(e="X ",t=" ",n=`
3
3
  `){return this.buildToString(e,t,n)}buildToString(e,t,n){let r=new Ae;for(let i=0,s=this.height;i<s;i++){for(let o=0,a=this.width;o<a;o++)r.append(this.get(o,i)?e:t);r.append(n)}return r.toString()}clone(){return new Ue(this.width,this.height,this.rowSize,this.bits.slice())}}class R extends C{static getNotFoundInstance(){return new R}}R.kind="NotFoundException";class He extends Be{constructor(e){super(e),this.luminances=He.EMPTY,this.buckets=new Int32Array(He.LUMINANCE_BUCKETS)}getBlackRow(e,t){const n=this.getLuminanceSource(),r=n.getWidth();t==null||t.getSize()<r?t=new ce(r):t.clear(),this.initArrays(r);const i=n.getRow(e,this.luminances),s=this.buckets;for(let a=0;a<r;a++)s[(i[a]&255)>>He.LUMINANCE_SHIFT]++;const o=He.estimateBlackPoint(s);if(r<3)for(let a=0;a<r;a++)(i[a]&255)<o&&t.set(a);else{let a=i[0]&255,c=i[1]&255;for(let h=1;h<r-1;h++){const g=i[h+1]&255;(c*4-a-g)/2<o&&t.set(h),a=c,c=g}}return t}getBlackMatrix(){const e=this.getLuminanceSource(),t=e.getWidth(),n=e.getHeight(),r=new Ue(t,n);this.initArrays(t);const i=this.buckets;for(let a=1;a<5;a++){const c=Math.floor(n*a/5),h=e.getRow(c,this.luminances),g=Math.floor(t*4/5);for(let A=Math.floor(t/5);A<g;A++){const m=h[A]&255;i[m>>He.LUMINANCE_SHIFT]++}}const s=He.estimateBlackPoint(i),o=e.getMatrix();for(let a=0;a<n;a++){const c=a*t;for(let h=0;h<t;h++)(o[c+h]&255)<s&&r.set(h,a)}return r}createBinarizer(e){return new He(e)}initArrays(e){this.luminances.length<e&&(this.luminances=new Uint8ClampedArray(e));const t=this.buckets;for(let n=0;n<He.LUMINANCE_BUCKETS;n++)t[n]=0}static estimateBlackPoint(e){const t=e.length;let n=0,r=0,i=0;for(let h=0;h<t;h++)e[h]>i&&(r=h,i=e[h]),e[h]>n&&(n=e[h]);let s=0,o=0;for(let h=0;h<t;h++){const g=h-r,A=e[h]*g*g;A>o&&(s=h,o=A)}if(r>s){const h=r;r=s,s=h}if(s-r<=t/16)throw new R;let a=s-1,c=-1;for(let h=s-1;h>r;h--){const g=h-r,A=g*g*(s-h)*(n-e[h]);A>c&&(a=h,c=A)}return a<<He.LUMINANCE_SHIFT}}He.LUMINANCE_BITS=5,He.LUMINANCE_SHIFT=8-He.LUMINANCE_BITS,He.LUMINANCE_BUCKETS=1<<He.LUMINANCE_BITS,He.EMPTY=Uint8ClampedArray.from([0]);class ee extends He{constructor(e){super(e),this.matrix=null}getBlackMatrix(){if(this.matrix!==null)return this.matrix;const e=this.getLuminanceSource(),t=e.getWidth(),n=e.getHeight();if(t>=ee.MINIMUM_DIMENSION&&n>=ee.MINIMUM_DIMENSION){const r=e.getMatrix();let i=t>>ee.BLOCK_SIZE_POWER;(t&ee.BLOCK_SIZE_MASK)!==0&&i++;let s=n>>ee.BLOCK_SIZE_POWER;(n&ee.BLOCK_SIZE_MASK)!==0&&s++;const o=ee.calculateBlackPoints(r,i,s,t,n),a=new Ue(t,n);ee.calculateThresholdForBlock(r,i,s,t,n,o,a),this.matrix=a}else this.matrix=super.getBlackMatrix();return this.matrix}createBinarizer(e){return new ee(e)}static calculateThresholdForBlock(e,t,n,r,i,s,o){const a=i-ee.BLOCK_SIZE,c=r-ee.BLOCK_SIZE;for(let h=0;h<n;h++){let g=h<<ee.BLOCK_SIZE_POWER;g>a&&(g=a);const A=ee.cap(h,2,n-3);for(let m=0;m<t;m++){let I=m<<ee.BLOCK_SIZE_POWER;I>c&&(I=c);const S=ee.cap(m,2,t-3);let y=0;for(let P=-2;P<=2;P++){const F=s[A+P];y+=F[S-2]+F[S-1]+F[S]+F[S+1]+F[S+2]}const M=y/25;ee.thresholdBlock(e,I,g,M,r,o)}}}static cap(e,t,n){return e<t?t:e>n?n:e}static thresholdBlock(e,t,n,r,i,s){for(let o=0,a=n*i+t;o<ee.BLOCK_SIZE;o++,a+=i)for(let c=0;c<ee.BLOCK_SIZE;c++)(e[a+c]&255)<=r&&s.set(t+c,n+o)}static calculateBlackPoints(e,t,n,r,i){const s=i-ee.BLOCK_SIZE,o=r-ee.BLOCK_SIZE,a=new Array(n);for(let c=0;c<n;c++){a[c]=new Int32Array(t);let h=c<<ee.BLOCK_SIZE_POWER;h>s&&(h=s);for(let g=0;g<t;g++){let A=g<<ee.BLOCK_SIZE_POWER;A>o&&(A=o);let m=0,I=255,S=0;for(let M=0,P=h*r+A;M<ee.BLOCK_SIZE;M++,P+=r){for(let F=0;F<ee.BLOCK_SIZE;F++){const v=e[P+F]&255;m+=v,v<I&&(I=v),v>S&&(S=v)}if(S-I>ee.MIN_DYNAMIC_RANGE)for(M++,P+=r;M<ee.BLOCK_SIZE;M++,P+=r)for(let F=0;F<ee.BLOCK_SIZE;F++)m+=e[P+F]&255}let y=m>>ee.BLOCK_SIZE_POWER*2;if(S-I<=ee.MIN_DYNAMIC_RANGE&&(y=I/2,c>0&&g>0)){const M=(a[c-1][g]+2*a[c][g-1]+a[c-1][g-1])/4;I<M&&(y=M)}a[c][g]=y}}return a}}ee.BLOCK_SIZE_POWER=3,ee.BLOCK_SIZE=1<<ee.BLOCK_SIZE_POWER,ee.BLOCK_SIZE_MASK=ee.BLOCK_SIZE-1,ee.MINIMUM_DIMENSION=ee.BLOCK_SIZE*5,ee.MIN_DYNAMIC_RANGE=24;class cn{constructor(e,t){this.width=e,this.height=t}getWidth(){return this.width}getHeight(){return this.height}isCropSupported(){return!1}crop(e,t,n,r){throw new Qt("This luminance source does not support cropping.")}isRotateSupported(){return!1}rotateCounterClockwise(){throw new Qt("This luminance source does not support rotation by 90 degrees.")}rotateCounterClockwise45(){throw new Qt("This luminance source does not support rotation by 45 degrees.")}toString(){const e=new Uint8ClampedArray(this.width);let t=new Ae;for(let n=0;n<this.height;n++){const r=this.getRow(n,e);for(let i=0;i<this.width;i++){const s=r[i]&255;let o;s<64?o="#":s<128?o="+":s<192?o=".":o=" ",t.append(o)}t.append(`
4
4
  `)}return t.toString()}}class Dt extends cn{constructor(e){super(e.getWidth(),e.getHeight()),this.delegate=e}getRow(e,t){const n=this.delegate.getRow(e,t),r=this.getWidth();for(let i=0;i<r;i++)n[i]=255-(n[i]&255);return n}getMatrix(){const e=this.delegate.getMatrix(),t=this.getWidth()*this.getHeight(),n=new Uint8ClampedArray(t);for(let r=0;r<t;r++)n[r]=255-(e[r]&255);return n}isCropSupported(){return this.delegate.isCropSupported()}crop(e,t,n,r){return new Dt(this.delegate.crop(e,t,n,r))}isRotateSupported(){return this.delegate.isRotateSupported()}invert(){return this.delegate}rotateCounterClockwise(){return new Dt(this.delegate.rotateCounterClockwise())}rotateCounterClockwise45(){return new Dt(this.delegate.rotateCounterClockwise45())}}class Rt extends cn{constructor(e){super(e.width,e.height),this.canvas=e,this.tempCanvasElement=null,this.buffer=Rt.makeBufferFromCanvasImageData(e)}static makeBufferFromCanvasImageData(e){const t=e.getContext("2d").getImageData(0,0,e.width,e.height);return Rt.toGrayscaleBuffer(t.data,e.width,e.height)}static toGrayscaleBuffer(e,t,n){const r=new Uint8ClampedArray(t*n);for(let i=0,s=0,o=e.length;i<o;i+=4,s++){let a;if(e[i+3]===0)a=255;else{const h=e[i],g=e[i+1],A=e[i+2];a=306*h+601*g+117*A+512>>10}r[s]=a}return r}getRow(e,t){if(e<0||e>=this.getHeight())throw new O("Requested row is outside the image: "+e);const n=this.getWidth(),r=e*n;return t===null?t=this.buffer.slice(r,r+n):(t.length<n&&(t=new Uint8ClampedArray(n)),t.set(this.buffer.slice(r,r+n))),t}getMatrix(){return this.buffer}isCropSupported(){return!0}crop(e,t,n,r){return super.crop(e,t,n,r),this}isRotateSupported(){return!0}rotateCounterClockwise(){return this.rotate(-90),this}rotateCounterClockwise45(){return this.rotate(-45),this}getTempCanvasElement(){if(this.tempCanvasElement===null){const e=this.canvas.ownerDocument.createElement("canvas");e.width=this.canvas.width,e.height=this.canvas.height,this.tempCanvasElement=e}return this.tempCanvasElement}rotate(e){const t=this.getTempCanvasElement(),n=t.getContext("2d"),r=e*Rt.DEGREE_TO_RADIANS,i=this.canvas.width,s=this.canvas.height,o=Math.ceil(Math.abs(Math.cos(r))*i+Math.abs(Math.sin(r))*s),a=Math.ceil(Math.abs(Math.sin(r))*i+Math.abs(Math.cos(r))*s);return t.width=o,t.height=a,n.translate(o/2,a/2),n.rotate(r),n.drawImage(this.canvas,i/-2,s/-2),this.buffer=Rt.makeBufferFromCanvasImageData(t),this}invert(){return new Dt(this)}}Rt.DEGREE_TO_RADIANS=Math.PI/180;class lr{constructor(e,t,n){this.deviceId=e,this.label=t,this.kind="videoinput",this.groupId=n||void 0}toJSON(){return{kind:this.kind,groupId:this.groupId,deviceId:this.deviceId,label:this.label}}}var qe=(globalThis||vn||self||window||void 0)&&(globalThis||vn||self||window||void 0).__awaiter||function(d,e,t,n){function r(i){return i instanceof t?i:new t(function(s){s(i)})}return new(t||(t=Promise))(function(i,s){function o(h){try{c(n.next(h))}catch(g){s(g)}}function a(h){try{c(n.throw(h))}catch(g){s(g)}}function c(h){h.done?i(h.value):r(h.value).then(o,a)}c((n=n.apply(d,e||[])).next())})};class zt{constructor(e,t=500,n){this.reader=e,this.timeBetweenScansMillis=t,this._hints=n,this._stopContinuousDecode=!1,this._stopAsyncDecode=!1,this._timeBetweenDecodingAttempts=0}get hasNavigator(){return typeof navigator<"u"}get isMediaDevicesSuported(){return this.hasNavigator&&!!navigator.mediaDevices}get canEnumerateDevices(){return!!(this.isMediaDevicesSuported&&navigator.mediaDevices.enumerateDevices)}get timeBetweenDecodingAttempts(){return this._timeBetweenDecodingAttempts}set timeBetweenDecodingAttempts(e){this._timeBetweenDecodingAttempts=e<0?0:e}set hints(e){this._hints=e||null}get hints(){return this._hints}listVideoInputDevices(){return qe(this,void 0,void 0,function*(){if(!this.hasNavigator)throw new Error("Can't enumerate devices, navigator is not present.");if(!this.canEnumerateDevices)throw new Error("Can't enumerate devices, method not supported.");const e=yield navigator.mediaDevices.enumerateDevices(),t=[];for(const n of e){const r=n.kind==="video"?"videoinput":n.kind;if(r!=="videoinput")continue;const i=n.deviceId||n.id,s=n.label||`Video device ${t.length+1}`,o=n.groupId,a={deviceId:i,label:s,kind:r,groupId:o};t.push(a)}return t})}getVideoInputDevices(){return qe(this,void 0,void 0,function*(){return(yield this.listVideoInputDevices()).map(t=>new lr(t.deviceId,t.label))})}findDeviceById(e){return qe(this,void 0,void 0,function*(){const t=yield this.listVideoInputDevices();return t?t.find(n=>n.deviceId===e):null})}decodeFromInputVideoDevice(e,t){return qe(this,void 0,void 0,function*(){return yield this.decodeOnceFromVideoDevice(e,t)})}decodeOnceFromVideoDevice(e,t){return qe(this,void 0,void 0,function*(){this.reset();let n;e?n={deviceId:{exact:e}}:n={facingMode:"environment"};const r={video:n};return yield this.decodeOnceFromConstraints(r,t)})}decodeOnceFromConstraints(e,t){return qe(this,void 0,void 0,function*(){const n=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeOnceFromStream(n,t)})}decodeOnceFromStream(e,t){return qe(this,void 0,void 0,function*(){this.reset();const n=yield this.attachStreamToVideo(e,t);return yield this.decodeOnce(n)})}decodeFromInputVideoDeviceContinuously(e,t,n){return qe(this,void 0,void 0,function*(){return yield this.decodeFromVideoDevice(e,t,n)})}decodeFromVideoDevice(e,t,n){return qe(this,void 0,void 0,function*(){let r;e?r={deviceId:{exact:e}}:r={facingMode:"environment"};const i={video:r};return yield this.decodeFromConstraints(i,t,n)})}decodeFromConstraints(e,t,n){return qe(this,void 0,void 0,function*(){const r=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeFromStream(r,t,n)})}decodeFromStream(e,t,n){return qe(this,void 0,void 0,function*(){this.reset();const r=yield this.attachStreamToVideo(e,t);return yield this.decodeContinuously(r,n)})}stopAsyncDecode(){this._stopAsyncDecode=!0}stopContinuousDecode(){this._stopContinuousDecode=!0}attachStreamToVideo(e,t){return qe(this,void 0,void 0,function*(){const n=this.prepareVideoElement(t);return this.addVideoSource(n,e),this.videoElement=n,this.stream=e,yield this.playVideoOnLoadAsync(n),n})}playVideoOnLoadAsync(e){return new Promise((t,n)=>this.playVideoOnLoad(e,()=>t()))}playVideoOnLoad(e,t){this.videoEndedListener=()=>this.stopStreams(),this.videoCanPlayListener=()=>this.tryPlayVideo(e),e.addEventListener("ended",this.videoEndedListener),e.addEventListener("canplay",this.videoCanPlayListener),e.addEventListener("playing",t),this.tryPlayVideo(e)}isVideoPlaying(e){return e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>2}tryPlayVideo(e){return qe(this,void 0,void 0,function*(){if(this.isVideoPlaying(e)){console.warn("Trying to play video that is already playing.");return}try{yield e.play()}catch{console.warn("It was not possible to play the video.")}})}getMediaElement(e,t){const n=document.getElementById(e);if(!n)throw new _(`element with id '${e}' not found`);if(n.nodeName.toLowerCase()!==t.toLowerCase())throw new _(`element with id '${e}' must be an ${t} element`);return n}decodeFromImage(e,t){if(!e&&!t)throw new _("either imageElement with a src set or an url must be provided");return t&&!e?this.decodeFromImageUrl(t):this.decodeFromImageElement(e)}decodeFromVideo(e,t){if(!e&&!t)throw new _("Either an element with a src set or an URL must be provided");return t&&!e?this.decodeFromVideoUrl(t):this.decodeFromVideoElement(e)}decodeFromVideoContinuously(e,t,n){if(e===void 0&&t===void 0)throw new _("Either an element with a src set or an URL must be provided");return t&&!e?this.decodeFromVideoUrlContinuously(t,n):this.decodeFromVideoElementContinuously(e,n)}decodeFromImageElement(e){if(!e)throw new _("An image element must be provided.");this.reset();const t=this.prepareImageElement(e);this.imageElement=t;let n;return this.isImageLoaded(t)?n=this.decodeOnce(t,!1,!0):n=this._decodeOnLoadImage(t),n}decodeFromVideoElement(e){const t=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideo(t)}decodeFromVideoElementContinuously(e,t){const n=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideoContinuously(n,t)}_decodeFromVideoElementSetup(e){if(!e)throw new _("A video element must be provided.");this.reset();const t=this.prepareVideoElement(e);return this.videoElement=t,t}decodeFromImageUrl(e){if(!e)throw new _("An URL must be provided.");this.reset();const t=this.prepareImageElement();this.imageElement=t;const n=this._decodeOnLoadImage(t);return t.src=e,n}decodeFromVideoUrl(e){if(!e)throw new _("An URL must be provided.");this.reset();const t=this.prepareVideoElement(),n=this.decodeFromVideoElement(t);return t.src=e,n}decodeFromVideoUrlContinuously(e,t){if(!e)throw new _("An URL must be provided.");this.reset();const n=this.prepareVideoElement(),r=this.decodeFromVideoElementContinuously(n,t);return n.src=e,r}_decodeOnLoadImage(e){return new Promise((t,n)=>{this.imageLoadedListener=()=>this.decodeOnce(e,!1,!0).then(t,n),e.addEventListener("load",this.imageLoadedListener)})}_decodeOnLoadVideo(e){return qe(this,void 0,void 0,function*(){return yield this.playVideoOnLoadAsync(e),yield this.decodeOnce(e)})}_decodeOnLoadVideoContinuously(e,t){return qe(this,void 0,void 0,function*(){yield this.playVideoOnLoadAsync(e),this.decodeContinuously(e,t)})}isImageLoaded(e){return!(!e.complete||e.naturalWidth===0)}prepareImageElement(e){let t;return typeof e>"u"&&(t=document.createElement("img"),t.width=200,t.height=200),typeof e=="string"&&(t=this.getMediaElement(e,"img")),e instanceof HTMLImageElement&&(t=e),t}prepareVideoElement(e){let t;return!e&&typeof document<"u"&&(t=document.createElement("video"),t.width=200,t.height=200),typeof e=="string"&&(t=this.getMediaElement(e,"video")),e instanceof HTMLVideoElement&&(t=e),t.setAttribute("autoplay","true"),t.setAttribute("muted","true"),t.setAttribute("playsinline","true"),t}decodeOnce(e,t=!0,n=!0){this._stopAsyncDecode=!1;const r=(i,s)=>{if(this._stopAsyncDecode){s(new R("Video stream has ended before any code could be detected.")),this._stopAsyncDecode=void 0;return}try{const o=this.decode(e);i(o)}catch(o){const a=t&&o instanceof R,h=(o instanceof J||o instanceof U)&&n;if(a||h)return setTimeout(r,this._timeBetweenDecodingAttempts,i,s);s(o)}};return new Promise((i,s)=>r(i,s))}decodeContinuously(e,t){this._stopContinuousDecode=!1;const n=()=>{if(this._stopContinuousDecode){this._stopContinuousDecode=void 0;return}try{const r=this.decode(e);t(r,null),setTimeout(n,this.timeBetweenScansMillis)}catch(r){t(null,r);const i=r instanceof J||r instanceof U,s=r instanceof R;(i||s)&&setTimeout(n,this._timeBetweenDecodingAttempts)}};n()}decode(e){const t=this.createBinaryBitmap(e);return this.decodeBitmap(t)}_isHTMLVideoElement(e){return e.videoWidth!==0}drawFrameOnCanvas(e,t,n){t||(t={sx:0,sy:0,sWidth:e.videoWidth,sHeight:e.videoHeight,dx:0,dy:0,dWidth:e.videoWidth,dHeight:e.videoHeight}),n||(n=this.captureCanvasContext),n.drawImage(e,t.sx,t.sy,t.sWidth,t.sHeight,t.dx,t.dy,t.dWidth,t.dHeight)}drawImageOnCanvas(e,t,n=this.captureCanvasContext){t||(t={sx:0,sy:0,sWidth:e.naturalWidth,sHeight:e.naturalHeight,dx:0,dy:0,dWidth:e.naturalWidth,dHeight:e.naturalHeight}),n||(n=this.captureCanvasContext),n.drawImage(e,t.sx,t.sy,t.sWidth,t.sHeight,t.dx,t.dy,t.dWidth,t.dHeight)}createBinaryBitmap(e){this.getCaptureCanvasContext(e),this._isHTMLVideoElement(e)?this.drawFrameOnCanvas(e):this.drawImageOnCanvas(e);const t=this.getCaptureCanvas(e),n=new Rt(t),r=new ee(n);return new ie(r)}getCaptureCanvasContext(e){if(!this.captureCanvasContext){const n=this.getCaptureCanvas(e).getContext("2d");this.captureCanvasContext=n}return this.captureCanvasContext}getCaptureCanvas(e){if(!this.captureCanvas){const t=this.createCaptureCanvas(e);this.captureCanvas=t}return this.captureCanvas}decodeBitmap(e){return this.reader.decode(e,this._hints)}createCaptureCanvas(e){if(typeof document>"u")return this._destroyCaptureCanvas(),null;const t=document.createElement("canvas");let n,r;return typeof e<"u"&&(e instanceof HTMLVideoElement?(n=e.videoWidth,r=e.videoHeight):e instanceof HTMLImageElement&&(n=e.naturalWidth||e.width,r=e.naturalHeight||e.height)),t.style.width=n+"px",t.style.height=r+"px",t.width=n,t.height=r,t}stopStreams(){this.stream&&(this.stream.getVideoTracks().forEach(e=>e.stop()),this.stream=void 0),this._stopAsyncDecode===!1&&this.stopAsyncDecode(),this._stopContinuousDecode===!1&&this.stopContinuousDecode()}reset(){this.stopStreams(),this._destroyVideoElement(),this._destroyImageElement(),this._destroyCaptureCanvas()}_destroyVideoElement(){this.videoElement&&(typeof this.videoEndedListener<"u"&&this.videoElement.removeEventListener("ended",this.videoEndedListener),typeof this.videoPlayingEventListener<"u"&&this.videoElement.removeEventListener("playing",this.videoPlayingEventListener),typeof this.videoCanPlayListener<"u"&&this.videoElement.removeEventListener("loadedmetadata",this.videoCanPlayListener),this.cleanVideoSource(this.videoElement),this.videoElement=void 0)}_destroyImageElement(){this.imageElement&&(this.imageLoadedListener!==void 0&&this.imageElement.removeEventListener("load",this.imageLoadedListener),this.imageElement.src=void 0,this.imageElement.removeAttribute("src"),this.imageElement=void 0)}_destroyCaptureCanvas(){this.captureCanvasContext=void 0,this.captureCanvas=void 0}addVideoSource(e,t){try{e.srcObject=t}catch{e.src=URL.createObjectURL(t)}}cleanVideoSource(e){try{e.srcObject=null}catch{e.src=""}this.videoElement.removeAttribute("src")}}class Je{constructor(e,t,n=t==null?0:8*t.length,r,i,s=K.currentTimeMillis()){this.text=e,this.rawBytes=t,this.numBits=n,this.resultPoints=r,this.format=i,this.timestamp=s,this.text=e,this.rawBytes=t,n==null?this.numBits=t==null?0:8*t.length:this.numBits=n,this.resultPoints=r,this.format=i,this.resultMetadata=null,s==null?this.timestamp=K.currentTimeMillis():this.timestamp=s}getText(){return this.text}getRawBytes(){return this.rawBytes}getNumBits(){return this.numBits}getResultPoints(){return this.resultPoints}getBarcodeFormat(){return this.format}getResultMetadata(){return this.resultMetadata}putMetadata(e,t){this.resultMetadata===null&&(this.resultMetadata=new Map),this.resultMetadata.set(e,t)}putAllMetadata(e){e!==null&&(this.resultMetadata===null?this.resultMetadata=e:this.resultMetadata=new Map(e))}addResultPoints(e){const t=this.resultPoints;if(t===null)this.resultPoints=e;else if(e!==null&&e.length>0){const n=new Array(t.length+e.length);K.arraycopy(t,0,n,0,t.length),K.arraycopy(e,0,n,t.length,e.length),this.resultPoints=n}}getTimestamp(){return this.timestamp}toString(){return this.text}}var kn;(function(d){d[d.AZTEC=0]="AZTEC",d[d.CODABAR=1]="CODABAR",d[d.CODE_39=2]="CODE_39",d[d.CODE_93=3]="CODE_93",d[d.CODE_128=4]="CODE_128",d[d.DATA_MATRIX=5]="DATA_MATRIX",d[d.EAN_8=6]="EAN_8",d[d.EAN_13=7]="EAN_13",d[d.ITF=8]="ITF",d[d.MAXICODE=9]="MAXICODE",d[d.PDF_417=10]="PDF_417",d[d.QR_CODE=11]="QR_CODE",d[d.RSS_14=12]="RSS_14",d[d.RSS_EXPANDED=13]="RSS_EXPANDED",d[d.UPC_A=14]="UPC_A",d[d.UPC_E=15]="UPC_E",d[d.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(kn||(kn={}));var Y=kn,Un;(function(d){d[d.OTHER=0]="OTHER",d[d.ORIENTATION=1]="ORIENTATION",d[d.BYTE_SEGMENTS=2]="BYTE_SEGMENTS",d[d.ERROR_CORRECTION_LEVEL=3]="ERROR_CORRECTION_LEVEL",d[d.ISSUE_NUMBER=4]="ISSUE_NUMBER",d[d.SUGGESTED_PRICE=5]="SUGGESTED_PRICE",d[d.POSSIBLE_COUNTRY=6]="POSSIBLE_COUNTRY",d[d.UPC_EAN_EXTENSION=7]="UPC_EAN_EXTENSION",d[d.PDF417_EXTRA_METADATA=8]="PDF417_EXTRA_METADATA",d[d.STRUCTURED_APPEND_SEQUENCE=9]="STRUCTURED_APPEND_SEQUENCE",d[d.STRUCTURED_APPEND_PARITY=10]="STRUCTURED_APPEND_PARITY"})(Un||(Un={}));var Ve=Un;class ln{constructor(e,t,n,r,i=-1,s=-1){this.rawBytes=e,this.text=t,this.byteSegments=n,this.ecLevel=r,this.structuredAppendSequenceNumber=i,this.structuredAppendParity=s,this.numBits=e==null?0:8*e.length}getRawBytes(){return this.rawBytes}getNumBits(){return this.numBits}setNumBits(e){this.numBits=e}getText(){return this.text}getByteSegments(){return this.byteSegments}getECLevel(){return this.ecLevel}getErrorsCorrected(){return this.errorsCorrected}setErrorsCorrected(e){this.errorsCorrected=e}getErasures(){return this.erasures}setErasures(e){this.erasures=e}getOther(){return this.other}setOther(e){this.other=e}hasStructuredAppend(){return this.structuredAppendParity>=0&&this.structuredAppendSequenceNumber>=0}getStructuredAppendParity(){return this.structuredAppendParity}getStructuredAppendSequenceNumber(){return this.structuredAppendSequenceNumber}}class un{exp(e){return this.expTable[e]}log(e){if(e===0)throw new O;return this.logTable[e]}static addOrSubtract(e,t){return e^t}}class nt{constructor(e,t){if(t.length===0)throw new O;this.field=e;const n=t.length;if(n>1&&t[0]===0){let r=1;for(;r<n&&t[r]===0;)r++;r===n?this.coefficients=Int32Array.from([0]):(this.coefficients=new Int32Array(n-r),K.arraycopy(t,r,this.coefficients,0,this.coefficients.length))}else this.coefficients=t}getCoefficients(){return this.coefficients}getDegree(){return this.coefficients.length-1}isZero(){return this.coefficients[0]===0}getCoefficient(e){return this.coefficients[this.coefficients.length-1-e]}evaluateAt(e){if(e===0)return this.getCoefficient(0);const t=this.coefficients;let n;if(e===1){n=0;for(let s=0,o=t.length;s!==o;s++){const a=t[s];n=un.addOrSubtract(n,a)}return n}n=t[0];const r=t.length,i=this.field;for(let s=1;s<r;s++)n=un.addOrSubtract(i.multiply(e,n),t[s]);return n}addOrSubtract(e){if(!this.field.equals(e.field))throw new O("GenericGFPolys do not have same GenericGF field");if(this.isZero())return e;if(e.isZero())return this;let t=this.coefficients,n=e.coefficients;if(t.length>n.length){const s=t;t=n,n=s}let r=new Int32Array(n.length);const i=n.length-t.length;K.arraycopy(n,0,r,0,i);for(let s=i;s<n.length;s++)r[s]=un.addOrSubtract(t[s-i],n[s]);return new nt(this.field,r)}multiply(e){if(!this.field.equals(e.field))throw new O("GenericGFPolys do not have same GenericGF field");if(this.isZero()||e.isZero())return this.field.getZero();const t=this.coefficients,n=t.length,r=e.coefficients,i=r.length,s=new Int32Array(n+i-1),o=this.field;for(let a=0;a<n;a++){const c=t[a];for(let h=0;h<i;h++)s[a+h]=un.addOrSubtract(s[a+h],o.multiply(c,r[h]))}return new nt(o,s)}multiplyScalar(e){if(e===0)return this.field.getZero();if(e===1)return this;const t=this.coefficients.length,n=this.field,r=new Int32Array(t),i=this.coefficients;for(let s=0;s<t;s++)r[s]=n.multiply(i[s],e);return new nt(n,r)}multiplyByMonomial(e,t){if(e<0)throw new O;if(t===0)return this.field.getZero();const n=this.coefficients,r=n.length,i=new Int32Array(r+e),s=this.field;for(let o=0;o<r;o++)i[o]=s.multiply(n[o],t);return new nt(s,i)}divide(e){if(!this.field.equals(e.field))throw new O("GenericGFPolys do not have same GenericGF field");if(e.isZero())throw new O("Divide by 0");const t=this.field;let n=t.getZero(),r=this;const i=e.getCoefficient(e.getDegree()),s=t.inverse(i);for(;r.getDegree()>=e.getDegree()&&!r.isZero();){const o=r.getDegree()-e.getDegree(),a=t.multiply(r.getCoefficient(r.getDegree()),s),c=e.multiplyByMonomial(o,a),h=t.buildMonomial(o,a);n=n.addOrSubtract(h),r=r.addOrSubtract(c)}return[n,r]}toString(){let e="";for(let t=this.getDegree();t>=0;t--){let n=this.getCoefficient(t);if(n!==0){if(n<0?(e+=" - ",n=-n):e.length>0&&(e+=" + "),t===0||n!==1){const r=this.field.log(n);r===0?e+="1":r===1?e+="a":(e+="a^",e+=r)}t!==0&&(t===1?e+="x":(e+="x^",e+=t))}}return e}}class In extends C{}In.kind="ArithmeticException";class ue extends un{constructor(e,t,n){super(),this.primitive=e,this.size=t,this.generatorBase=n;const r=new Int32Array(t);let i=1;for(let o=0;o<t;o++)r[o]=i,i*=2,i>=t&&(i^=e,i&=t-1);this.expTable=r;const s=new Int32Array(t);for(let o=0;o<t-1;o++)s[r[o]]=o;this.logTable=s,this.zero=new nt(this,Int32Array.from([0])),this.one=new nt(this,Int32Array.from([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,t){if(e<0)throw new O;if(t===0)return this.zero;const n=new Int32Array(e+1);return n[0]=t,new nt(this,n)}inverse(e){if(e===0)throw new In;return this.expTable[this.size-this.logTable[e]-1]}multiply(e,t){return e===0||t===0?0:this.expTable[(this.logTable[e]+this.logTable[t])%(this.size-1)]}getSize(){return this.size}getGeneratorBase(){return this.generatorBase}toString(){return"GF(0x"+Q.toHexString(this.primitive)+","+this.size+")"}equals(e){return e===this}}ue.AZTEC_DATA_12=new ue(4201,4096,1),ue.AZTEC_DATA_10=new ue(1033,1024,1),ue.AZTEC_DATA_6=new ue(67,64,1),ue.AZTEC_PARAM=new ue(19,16,1),ue.QR_CODE_FIELD_256=new ue(285,256,0),ue.DATA_MATRIX_FIELD_256=new ue(301,256,1),ue.AZTEC_DATA_8=ue.DATA_MATRIX_FIELD_256,ue.MAXICODE_FIELD_64=ue.AZTEC_DATA_6;class Kt extends C{}Kt.kind="ReedSolomonException";class pt extends C{}pt.kind="IllegalStateException";class hn{constructor(e){this.field=e}decode(e,t){const n=this.field,r=new nt(n,e),i=new Int32Array(t);let s=!0;for(let m=0;m<t;m++){const I=r.evaluateAt(n.exp(m+n.getGeneratorBase()));i[i.length-1-m]=I,I!==0&&(s=!1)}if(s)return;const o=new nt(n,i),a=this.runEuclideanAlgorithm(n.buildMonomial(t,1),o,t),c=a[0],h=a[1],g=this.findErrorLocations(c),A=this.findErrorMagnitudes(h,g);for(let m=0;m<g.length;m++){const I=e.length-1-n.log(g[m]);if(I<0)throw new Kt("Bad error location");e[I]=ue.addOrSubtract(e[I],A[m])}}runEuclideanAlgorithm(e,t,n){if(e.getDegree()<t.getDegree()){const m=e;e=t,t=m}const r=this.field;let i=e,s=t,o=r.getZero(),a=r.getOne();for(;s.getDegree()>=(n/2|0);){let m=i,I=o;if(i=s,o=a,i.isZero())throw new Kt("r_{i-1} was zero");s=m;let S=r.getZero();const y=i.getCoefficient(i.getDegree()),M=r.inverse(y);for(;s.getDegree()>=i.getDegree()&&!s.isZero();){const P=s.getDegree()-i.getDegree(),F=r.multiply(s.getCoefficient(s.getDegree()),M);S=S.addOrSubtract(r.buildMonomial(P,F)),s=s.addOrSubtract(i.multiplyByMonomial(P,F))}if(a=S.multiply(o).addOrSubtract(I),s.getDegree()>=i.getDegree())throw new pt("Division algorithm failed to reduce polynomial?")}const c=a.getCoefficient(0);if(c===0)throw new Kt("sigmaTilde(0) was zero");const h=r.inverse(c),g=a.multiplyScalar(h),A=s.multiplyScalar(h);return[g,A]}findErrorLocations(e){const t=e.getDegree();if(t===1)return Int32Array.from([e.getCoefficient(1)]);const n=new Int32Array(t);let r=0;const i=this.field;for(let s=1;s<i.getSize()&&r<t;s++)e.evaluateAt(s)===0&&(n[r]=i.inverse(s),r++);if(r!==t)throw new Kt("Error locator degree does not match number of roots");return n}findErrorMagnitudes(e,t){const n=t.length,r=new Int32Array(n),i=this.field;for(let s=0;s<n;s++){const o=i.inverse(t[s]);let a=1;for(let c=0;c<n;c++)if(s!==c){const h=i.multiply(t[c],o),g=(h&1)===0?h|1:h&-2;a=i.multiply(a,g)}r[s]=i.multiply(e.evaluateAt(o),i.inverse(a)),i.getGeneratorBase()!==0&&(r[s]=i.multiply(r[s],o))}return r}}var je;(function(d){d[d.UPPER=0]="UPPER",d[d.LOWER=1]="LOWER",d[d.MIXED=2]="MIXED",d[d.DIGIT=3]="DIGIT",d[d.PUNCT=4]="PUNCT",d[d.BINARY=5]="BINARY"})(je||(je={}));class Se{decode(e){this.ddata=e;let t=e.getBits(),n=this.extractBits(t),r=this.correctBits(n),i=Se.convertBoolArrayToByteArray(r),s=Se.getEncodedData(r),o=new ln(i,s,null,null);return o.setNumBits(r.length),o}static highLevelDecode(e){return this.getEncodedData(e)}static getEncodedData(e){let t=e.length,n=je.UPPER,r=je.UPPER,i="",s=0;for(;s<t;)if(r===je.BINARY){if(t-s<5)break;let o=Se.readCode(e,s,5);if(s+=5,o===0){if(t-s<11)break;o=Se.readCode(e,s,11)+31,s+=11}for(let a=0;a<o;a++){if(t-s<8){s=t;break}const c=Se.readCode(e,s,8);i+=q.castAsNonUtf8Char(c),s+=8}r=n}else{let o=r===je.DIGIT?4:5;if(t-s<o)break;let a=Se.readCode(e,s,o);s+=o;let c=Se.getCharacter(r,a);c.startsWith("CTRL_")?(n=r,r=Se.getTable(c.charAt(5)),c.charAt(6)==="L"&&(n=r)):(i+=c,r=n)}return i}static getTable(e){switch(e){case"L":return je.LOWER;case"P":return je.PUNCT;case"M":return je.MIXED;case"D":return je.DIGIT;case"B":return je.BINARY;case"U":default:return je.UPPER}}static getCharacter(e,t){switch(e){case je.UPPER:return Se.UPPER_TABLE[t];case je.LOWER:return Se.LOWER_TABLE[t];case je.MIXED:return Se.MIXED_TABLE[t];case je.PUNCT:return Se.PUNCT_TABLE[t];case je.DIGIT:return Se.DIGIT_TABLE[t];default:throw new pt("Bad table")}}correctBits(e){let t,n;this.ddata.getNbLayers()<=2?(n=6,t=ue.AZTEC_DATA_6):this.ddata.getNbLayers()<=8?(n=8,t=ue.AZTEC_DATA_8):this.ddata.getNbLayers()<=22?(n=10,t=ue.AZTEC_DATA_10):(n=12,t=ue.AZTEC_DATA_12);let r=this.ddata.getNbDatablocks(),i=e.length/n;if(i<r)throw new U;let s=e.length%n,o=new Int32Array(i);for(let A=0;A<i;A++,s+=n)o[A]=Se.readCode(e,s,n);try{new hn(t).decode(o,i-r)}catch(A){throw new U(A)}let a=(1<<n)-1,c=0;for(let A=0;A<r;A++){let m=o[A];if(m===0||m===a)throw new U;(m===1||m===a-1)&&c++}let h=new Array(r*n-c),g=0;for(let A=0;A<r;A++){let m=o[A];if(m===1||m===a-1)h.fill(m>1,g,g+n-1),g+=n-1;else for(let I=n-1;I>=0;--I)h[g++]=(m&1<<I)!==0}return h}extractBits(e){let t=this.ddata.isCompact(),n=this.ddata.getNbLayers(),r=(t?11:14)+n*4,i=new Int32Array(r),s=new Array(this.totalBitsInLayer(n,t));if(t)for(let o=0;o<i.length;o++)i[o]=o;else{let o=r+1+2*Q.truncDivision(Q.truncDivision(r,2)-1,15),a=r/2,c=Q.truncDivision(o,2);for(let h=0;h<a;h++){let g=h+Q.truncDivision(h,15);i[a-h-1]=c-g-1,i[a+h]=c+g+1}}for(let o=0,a=0;o<n;o++){let c=(n-o)*4+(t?9:12),h=o*2,g=r-1-h;for(let A=0;A<c;A++){let m=A*2;for(let I=0;I<2;I++)s[a+m+I]=e.get(i[h+I],i[h+A]),s[a+2*c+m+I]=e.get(i[h+A],i[g-I]),s[a+4*c+m+I]=e.get(i[g-I],i[g-A]),s[a+6*c+m+I]=e.get(i[g-A],i[h+I])}a+=c*8}return s}static readCode(e,t,n){let r=0;for(let i=t;i<t+n;i++)r<<=1,e[i]&&(r|=1);return r}static readByte(e,t){let n=e.length-t;return n>=8?Se.readCode(e,t,8):Se.readCode(e,t,n)<<8-n}static convertBoolArrayToByteArray(e){let t=new Uint8Array((e.length+7)/8);for(let n=0;n<t.length;n++)t[n]=Se.readByte(e,8*n);return t}totalBitsInLayer(e,t){return((t?88:112)+16*e)*e}}Se.UPPER_TABLE=["CTRL_PS"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","CTRL_LL","CTRL_ML","CTRL_DL","CTRL_BS"],Se.LOWER_TABLE=["CTRL_PS"," ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","CTRL_US","CTRL_ML","CTRL_DL","CTRL_BS"],Se.MIXED_TABLE=["CTRL_PS"," ","\\1","\\2","\\3","\\4","\\5","\\6","\\7","\b"," ",`
@@ -7,7 +7,7 @@
7
7
  <meta name="apple-mobile-web-app-capable" content="yes" />
8
8
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
9
9
  <title>Airloom</title>
10
- <script type="module" crossorigin src="./assets/index-BoCit9Kx.js"></script>
10
+ <script type="module" crossorigin src="./assets/index-DLLnAccl.js"></script>
11
11
  <link rel="stylesheet" crossorigin href="./assets/index-mDTBX0lq.css">
12
12
  </head>
13
13
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "airloom",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Run AI on your computer, control it from your phone. E2E encrypted.",
5
5
  "type": "module",
6
6
  "bin": {