123456789101112131415161718192021222324252627282930313233343536 |
- var aa=Object.defineProperty;var ca=(r,e,t)=>e in r?aa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var c=(r,e,t)=>(ca(r,typeof e!="symbol"?e+"":e,t),t);import{c as Ve,i as ua,d as Ni,e as At,f as Mi,l as vn,t as la,m as ha,S as fa,r as da,P as pa,g as ma,h as ba,_ as Sn,a as ga,b as _a}from"./main-74e469cd.js";function ya(r){let e=Pa();return wa(r,e),Ca(e)}function wa(r,e){let t=r.sub;t!==void 0&&(Ce(e,10),sr(e,t));let s=r.msg;s!==void 0&&(Ce(e,18),sr(e,s));let n=r.error;n!==void 0&&(Ce(e,26),sr(e,n));let i=r.type;i!==void 0&&(Ce(e,34),sr(e,i));let o=r.fva11;o!==void 0&&(Ce(e,45),On(e,o));let a=r.fva12;a!==void 0&&(Ce(e,53),On(e,a));let u=r.iva11;u!==void 0&&(Ce(e,56),Cn(e,En(u)));let h=r.iva12;h!==void 0&&(Ce(e,64),Cn(e,En(h)))}function xa(r){return va(Oa(r))}function va(r){let e={};e:for(;!ka(r);){let t=$e(r);switch(t>>>3){case 0:break e;case 1:{e.sub=rr(r,$e(r));break}case 2:{e.msg=rr(r,$e(r));break}case 3:{e.error=rr(r,$e(r));break}case 4:{e.type=rr(r,$e(r));break}case 5:{e.fva11=Pn(r);break}case 6:{e.fva12=Pn(r);break}case 7:{e.iva11=$e(r);break}case 8:{e.iva12=$e(r);break}default:Sa(r,t&7)}}return e}function Sa(r,e){switch(e){case 0:for(;Ui(r)&128;);break;case 2:Xr(r,$e(r));break;case 5:Xr(r,4);break;case 1:Xr(r,8);break;default:throw new Error("Unimplemented type: "+e)}}let Ds=new Float32Array(1),Le=new Uint8Array(Ds.buffer),Ea=new Float64Array(1);new Uint8Array(Ea.buffer);function En(r){return r|=0,{low:r,high:r>>31,unsigned:r>=0}}let Aa=[];function Pa(){const r=Aa.pop();return r?(r.offset=r.limit=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function Oa(r){return{bytes:r,offset:0,limit:r.length}}function Ca(r){let e=r.bytes,t=r.limit;return e.length===t?e:e.subarray(0,t)}function Xr(r,e){if(r.offset+e>r.limit)throw new Error("Skip past limit");r.offset+=e}function ka(r){return r.offset>=r.limit}function Cr(r,e){let t=r.bytes,s=r.offset,n=r.limit,i=s+e;if(i>t.length){let o=new Uint8Array(i*2);o.set(t),r.bytes=o}return r.offset=i,i>n&&(r.limit=i),s}function qs(r,e){let t=r.offset;if(t+e>r.limit)throw new Error("Read past limit");return r.offset+=e,t}function rr(r,e){let t=qs(r,e),s=String.fromCharCode,n=r.bytes,i="�",o="";for(let a=0;a<e;a++){let u=n[a+t],h,p,g,b;u&128?(u&224)===192?a+1>=e?o+=i:(h=n[a+t+1],(h&192)!==128?o+=i:(b=(u&31)<<6|h&63,b<128?o+=i:(o+=s(b),a++))):(u&240)==224?a+2>=e?o+=i:(h=n[a+t+1],p=n[a+t+2],((h|p<<8)&49344)!==32896?o+=i:(b=(u&15)<<12|(h&63)<<6|p&63,b<2048||b>=55296&&b<=57343?o+=i:(o+=s(b),a+=2))):(u&248)==240?a+3>=e?o+=i:(h=n[a+t+1],p=n[a+t+2],g=n[a+t+3],((h|p<<8|g<<16)&12632256)!==8421504?o+=i:(b=(u&7)<<18|(h&63)<<12|(p&63)<<6|g&63,b<65536||b>1114111?o+=i:(b-=65536,o+=s((b>>10)+55296,(b&1023)+56320),a+=3))):o+=i:o+=s(u)}return o}function sr(r,e){let t=e.length,s=0;for(let o=0;o<t;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<t&&(a=(a<<10)+e.charCodeAt(++o)-56613888),s+=a<128?1:a<2048?2:a<65536?3:4}Ce(r,s);let n=Cr(r,s),i=r.bytes;for(let o=0;o<t;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<t&&(a=(a<<10)+e.charCodeAt(++o)-56613888),a<128?i[n++]=a:(a<2048?i[n++]=a>>6&31|192:(a<65536?i[n++]=a>>12&15|224:(i[n++]=a>>18&7|240,i[n++]=a>>12&63|128),i[n++]=a>>6&63|128),i[n++]=a&63|128)}}function Ui(r){return r.bytes[qs(r,1)]}function An(r,e){let t=Cr(r,1);r.bytes[t]=e}function Pn(r){let e=qs(r,4),t=r.bytes;return Le[0]=t[e++],Le[1]=t[e++],Le[2]=t[e++],Le[3]=t[e++],Ds[0]}function On(r,e){let t=Cr(r,4),s=r.bytes;Ds[0]=e,s[t++]=Le[0],s[t++]=Le[1],s[t++]=Le[2],s[t++]=Le[3]}function $e(r){let e=0,t=0,s;do s=Ui(r),e<32&&(t|=(s&127)<<e),e+=7;while(s&128);return t}function Ce(r,e){for(e>>>=0;e>=128;)An(r,e&127|128),e>>>=7;An(r,e)}function Cn(r,e){let t=e.low>>>0,s=(e.low>>>28|e.high<<4)>>>0,n=e.high>>>24,i=n===0?s===0?t<1<<14?t<1<<7?1:2:t<1<<21?3:4:s<1<<14?s<1<<7?5:6:s<1<<21?7:8:n<1<<7?9:10,o=Cr(r,i),a=r.bytes;switch(i){case 10:a[o+9]=n>>>7&1;break;case 9:a[o+8]=i!==9?n|128:n&127;break;case 8:a[o+7]=i!==8?s>>>21|128:s>>>21&127;break;case 7:a[o+6]=i!==7?s>>>14|128:s>>>14&127;break;case 6:a[o+5]=i!==6?s>>>7|128:s>>>7&127;break;case 5:a[o+4]=i!==5?s|128:s&127;break;case 4:a[o+3]=i!==4?t>>>21|128:t>>>21&127;break;case 3:a[o+2]=i!==3?t>>>14|128:t>>>14&127;break;case 2:a[o+1]=i!==2?t>>>7|128:t>>>7&127;break;case 1:a[o]=i!==1?t|128:t&127}}class Ra{constructor(){c(this,"_hooks",{})}method(e,t){if(this._hooks[e]!==void 0)throw new Error("can't override hook: "+e);this._hooks[e]=t}methodRemove(e){delete this._hooks[e]}call(e,...t){if(this._hooks[e])try{return this._hooks[e].apply(null,t)}catch(s){console.info("%c%s %c(editor.method error)","color: #06f",e,"color: #f00"),console.error(s)}return null}}class ja{constructor(e,t,s){c(this,"owner");c(this,"name");c(this,"fn");this.owner=e,this.name=t,this.fn=s}unbind(){this.owner&&(this.owner.unbind(this.name,this.fn),this.owner=null,this.name=null,this.fn=null)}call(){this.fn&&this.fn.call(this.owner,arguments[0],arguments[1],arguments[2],arguments[3],arguments[4],arguments[5],arguments[6],arguments[7])}on(e,t){return this.owner.on(e,t)}}let Ia=class{constructor(){c(this,"_events");c(this,"_suspendEvents");this._events={},this._suspendEvents=!1}get suspendEvents(){return this._suspendEvents}set suspendEvents(e){this._suspendEvents=!!e}nextTick(e,t){this.on(e,function(){let s=null;return function(...n){s&&clearTimeout(s),s=setTimeout(t.bind(null,...n))}}())}on(e,t){const s=this._events[e];return s===void 0?this._events[e]=[t]:s.indexOf(t)==-1&&s.push(t),new ja(this,e,t)}once(e,t){const s=this,n=this.on(e,function(...i){t.call(s,...i),n.unbind()});return n}emit(e,...t){if(this._suspendEvents)return;let s=this._events[e];if(s){s=s.slice(0);for(let n=0;n<s.length;n++)if(s[n])try{s[n].call(this,...t)}catch(i){console.info("%c%s %c(event error)","color: #06f",e,"color: #f00"),console.error(i)}}}unbind(e,t){if(e){const s=this._events[e];if(!s)return this;if(t){const n=s.indexOf(t);n!==-1&&(s.length===1?delete this._events[e]:s.splice(n,1))}else delete this._events[e]}else this._events={};return this}};function Ta(r){return typeof r=="function"||Object.prototype.toString.call(r)==="[object Object]"&&!ua(r)}const Na=function(r){delete r.slotOptions;const{slots:e={},...t}=r,s=Ni(t),n=function(o){let a;const{slots:u,...h}=o;return Ve(s,h,Ta(a=Ma(this,u))?a:{default:()=>[a]})},i=n.bind(()=>i);return Object.setPrototypeOf(i,n),Object.keys(e).forEach(o=>{i[o]=e[o]}),i.slots=function(o){return o},i};function Ma(r,e={}){const t=r();return Object.keys(t).forEach(n=>{e[n]=Ua(e,n,t[n])}),e}function Ua(r,e,t){const s=r[e];return s?(n={},i={})=>{const o=s(n,i);if(o)return o!=n?o:Ve(t,o,null)}:n=>Ve(t,n,null)}Na({setup(){return()=>null}});const Ee=new Ra;function $a(r){Ee.call("ui:showLoading",r)}function Fa(){Ee.call("ui:hideLoading")}function La(r){Ee.call("ui:message:success",r)}function Da(r){Ee.call("ui:message:info",r)}function qa(r){return Ee.call("ui:message:warn",r),r}function Ba(r){return Ee.call("ui:message:error",r),r}function Ha(r){return Ee.call("ui:dialog:input",r)}function Ja(r){return Ee.call("ui:dialog:confirm",r)}function za(r,e,t){return Ee.call("ui:dialog:custom",r,e,t)}function Ga(){return Ee.call("ui:dialog:use")}const Va=Object.freeze(Object.defineProperty({__proto__:null,dialog:za,hideLoading:Fa,messageError:Ba,messageInfo:Da,messageSuccess:La,messageWarn:qa,showConfirm:Ja,showInput:Ha,showLoading:$a,useDialog:Ga},Symbol.toStringTag,{value:"Module"}));function Wa(r){return new Promise((e,t)=>{const s=document.createElement("input");s.type="file",s.accept=(r==null?void 0:r.accept)||"images/*",s.multiple=(r==null?void 0:r.multiple)||!1,s.onchange=function(){e([...this.files])},window.addEventListener("mousedown",()=>{t(Rt.cancel("select file cancel"))},{once:!0}),s.click()})}const Ya=Object.freeze(Object.defineProperty({__proto__:null,selectFile:Wa},Symbol.toStringTag,{value:"Module"})),Ka=URL.createObjectURL,Xa=URL.revokeObjectURL;URL.createObjectURL=function(r){const e=Ka(r);return qt.set(e,r),e};URL.revokeObjectURL=function(r){Xa(r),qt.delete(r)};const qt=new Map;function Za(r){var e;return(e=qt.get(r))==null?void 0:e.name}function Qa(r){const e=qt.get(r);let t="unkown";if(e){const s=/^.+\.(.+)$/;return e.name&&s.test(e.name)?t=s.exec(e.name)[1]:e.type&&(t=e.type.split("/").pop()),t.toLowerCase()}else return t}function ec(r){return/^blob:/.test(r)}const tc=Object.freeze(Object.defineProperty({__proto__:null,blobURLMaps:qt,getBlobURLExt:Qa,getBlobURLName:Za,isBlobURL:ec},Symbol.toStringTag,{value:"Module"})),ke={router:{},...Va,...tc,...Ya},kn={Cancel:{label:"取消",silence:!0},Warn:{label:"警告",silence:!1},Error:{label:"错误",silence:!1}};class Rt{constructor(e,t){c(this,"msg");c(this,"silence");c(this,"result");if(this.type=e,this.msg=kn[e].label,this.silence=kn[e].silence,t&&Object.assign(this,typeof t=="string"?{msg:t}:t),!this.silence)switch(this.type){case"Cancel":case"Warn":ke.messageWarn(this.msg);break;case"Error":ke.messageError(this.msg);break}}static cancel(e){return new Rt("Cancel",e)}static warn(e){return new Rt("Warn",e)}static error(e){return new Rt("Error",e)}}var $i={exports:{}},Fi=function(e,t){return function(){for(var n=new Array(arguments.length),i=0;i<n.length;i++)n[i]=arguments[i];return e.apply(t,n)}},rc=Fi,Bs=Object.prototype.toString,Hs=function(r){return function(e){var t=Bs.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())}}(Object.create(null));function Ye(r){return r=r.toLowerCase(),function(t){return Hs(t)===r}}function Js(r){return Array.isArray(r)}function br(r){return typeof r>"u"}function sc(r){return r!==null&&!br(r)&&r.constructor!==null&&!br(r.constructor)&&typeof r.constructor.isBuffer=="function"&&r.constructor.isBuffer(r)}var Li=Ye("ArrayBuffer");function nc(r){var e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&Li(r.buffer),e}function ic(r){return typeof r=="string"}function oc(r){return typeof r=="number"}function Di(r){return r!==null&&typeof r=="object"}function lr(r){if(Hs(r)!=="object")return!1;var e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}var ac=Ye("Date"),cc=Ye("File"),uc=Ye("Blob"),lc=Ye("FileList");function zs(r){return Bs.call(r)==="[object Function]"}function hc(r){return Di(r)&&zs(r.pipe)}function fc(r){var e="[object FormData]";return r&&(typeof FormData=="function"&&r instanceof FormData||Bs.call(r)===e||zs(r.toString)&&r.toString()===e)}var dc=Ye("URLSearchParams");function pc(r){return r.trim?r.trim():r.replace(/^\s+|\s+$/g,"")}function mc(){return typeof navigator<"u"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window<"u"&&typeof document<"u"}function Gs(r,e){if(!(r===null||typeof r>"u"))if(typeof r!="object"&&(r=[r]),Js(r))for(var t=0,s=r.length;t<s;t++)e.call(null,r[t],t,r);else for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.call(null,r[n],n,r)}function Ss(){var r={};function e(n,i){lr(r[i])&&lr(n)?r[i]=Ss(r[i],n):lr(n)?r[i]=Ss({},n):Js(n)?r[i]=n.slice():r[i]=n}for(var t=0,s=arguments.length;t<s;t++)Gs(arguments[t],e);return r}function bc(r,e,t){return Gs(e,function(n,i){t&&typeof n=="function"?r[i]=rc(n,t):r[i]=n}),r}function gc(r){return r.charCodeAt(0)===65279&&(r=r.slice(1)),r}function _c(r,e,t,s){r.prototype=Object.create(e.prototype,s),r.prototype.constructor=r,t&&Object.assign(r.prototype,t)}function yc(r,e,t){var s,n,i,o={};e=e||{};do{for(s=Object.getOwnPropertyNames(r),n=s.length;n-- >0;)i=s[n],o[i]||(e[i]=r[i],o[i]=!0);r=Object.getPrototypeOf(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e}function wc(r,e,t){r=String(r),(t===void 0||t>r.length)&&(t=r.length),t-=e.length;var s=r.indexOf(e,t);return s!==-1&&s===t}function xc(r){if(!r)return null;var e=r.length;if(br(e))return null;for(var t=new Array(e);e-- >0;)t[e]=r[e];return t}var vc=function(r){return function(e){return r&&e instanceof r}}(typeof Uint8Array<"u"&&Object.getPrototypeOf(Uint8Array)),K={isArray:Js,isArrayBuffer:Li,isBuffer:sc,isFormData:fc,isArrayBufferView:nc,isString:ic,isNumber:oc,isObject:Di,isPlainObject:lr,isUndefined:br,isDate:ac,isFile:cc,isBlob:uc,isFunction:zs,isStream:hc,isURLSearchParams:dc,isStandardBrowserEnv:mc,forEach:Gs,merge:Ss,extend:bc,trim:pc,stripBOM:gc,inherits:_c,toFlatObject:yc,kindOf:Hs,kindOfTest:Ye,endsWith:wc,toArray:xc,isTypedArray:vc,isFileList:lc},st=K;function Rn(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var qi=function(e,t,s){if(!t)return e;var n;if(s)n=s(t);else if(st.isURLSearchParams(t))n=t.toString();else{var i=[];st.forEach(t,function(u,h){u===null||typeof u>"u"||(st.isArray(u)?h=h+"[]":u=[u],st.forEach(u,function(g){st.isDate(g)?g=g.toISOString():st.isObject(g)&&(g=JSON.stringify(g)),i.push(Rn(h)+"="+Rn(g))}))}),n=i.join("&")}if(n){var o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+n}return e},Sc=K;function kr(){this.handlers=[]}kr.prototype.use=function(e,t,s){return this.handlers.push({fulfilled:e,rejected:t,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1};kr.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)};kr.prototype.forEach=function(e){Sc.forEach(this.handlers,function(s){s!==null&&e(s)})};var Ec=kr,Ac=K,Pc=function(e,t){Ac.forEach(e,function(n,i){i!==t&&i.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[i])})},Bi=K;function ht(r,e,t,s,n){Error.call(this),this.message=r,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),s&&(this.request=s),n&&(this.response=n)}Bi.inherits(ht,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var Hi=ht.prototype,Ji={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach(function(r){Ji[r]={value:r}});Object.defineProperties(ht,Ji);Object.defineProperty(Hi,"isAxiosError",{value:!0});ht.from=function(r,e,t,s,n,i){var o=Object.create(Hi);return Bi.toFlatObject(r,o,function(u){return u!==Error.prototype}),ht.call(o,r.message,e,t,s,n),o.name=r.name,i&&Object.assign(o,i),o};var gt=ht,zi={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ge=K;function Oc(r,e){e=e||new FormData;var t=[];function s(i){return i===null?"":ge.isDate(i)?i.toISOString():ge.isArrayBuffer(i)||ge.isTypedArray(i)?typeof Blob=="function"?new Blob([i]):Buffer.from(i):i}function n(i,o){if(ge.isPlainObject(i)||ge.isArray(i)){if(t.indexOf(i)!==-1)throw Error("Circular reference detected in "+o);t.push(i),ge.forEach(i,function(u,h){if(!ge.isUndefined(u)){var p=o?o+"."+h:h,g;if(u&&!o&&typeof u=="object"){if(ge.endsWith(h,"{}"))u=JSON.stringify(u);else if(ge.endsWith(h,"[]")&&(g=ge.toArray(u))){g.forEach(function(b){!ge.isUndefined(b)&&e.append(p,s(b))});return}}n(u,p)}}),t.pop()}else e.append(o,s(i))}return n(r),e}var Gi=Oc,Zr,jn;function Cc(){if(jn)return Zr;jn=1;var r=gt;return Zr=function(t,s,n){var i=n.config.validateStatus;!n.status||!i||i(n.status)?t(n):s(new r("Request failed with status code "+n.status,[r.ERR_BAD_REQUEST,r.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))},Zr}var Qr,In;function kc(){if(In)return Qr;In=1;var r=K;return Qr=r.isStandardBrowserEnv()?function(){return{write:function(s,n,i,o,a,u){var h=[];h.push(s+"="+encodeURIComponent(n)),r.isNumber(i)&&h.push("expires="+new Date(i).toGMTString()),r.isString(o)&&h.push("path="+o),r.isString(a)&&h.push("domain="+a),u===!0&&h.push("secure"),document.cookie=h.join("; ")},read:function(s){var n=document.cookie.match(new RegExp("(^|;\\s*)("+s+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(s){this.write(s,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),Qr}var Rc=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},jc=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},Ic=Rc,Tc=jc,Vi=function(e,t){return e&&!Ic(t)?Tc(e,t):t},es,Tn;function Nc(){if(Tn)return es;Tn=1;var r=K,e=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return es=function(s){var n={},i,o,a;return s&&r.forEach(s.split(`
- `),function(h){if(a=h.indexOf(":"),i=r.trim(h.substr(0,a)).toLowerCase(),o=r.trim(h.substr(a+1)),i){if(n[i]&&e.indexOf(i)>=0)return;i==="set-cookie"?n[i]=(n[i]?n[i]:[]).concat([o]):n[i]=n[i]?n[i]+", "+o:o}}),n},es}var ts,Nn;function Mc(){if(Nn)return ts;Nn=1;var r=K;return ts=r.isStandardBrowserEnv()?function(){var t=/(msie|trident)/i.test(navigator.userAgent),s=document.createElement("a"),n;function i(o){var a=o;return t&&(s.setAttribute("href",a),a=s.href),s.setAttribute("href",a),{href:s.href,protocol:s.protocol?s.protocol.replace(/:$/,""):"",host:s.host,search:s.search?s.search.replace(/^\?/,""):"",hash:s.hash?s.hash.replace(/^#/,""):"",hostname:s.hostname,port:s.port,pathname:s.pathname.charAt(0)==="/"?s.pathname:"/"+s.pathname}}return n=i(window.location.href),function(a){var u=r.isString(a)?i(a):a;return u.protocol===n.protocol&&u.host===n.host}}():function(){return function(){return!0}}(),ts}var rs,Mn;function Rr(){if(Mn)return rs;Mn=1;var r=gt,e=K;function t(s){r.call(this,s??"canceled",r.ERR_CANCELED),this.name="CanceledError"}return e.inherits(t,r,{__CANCEL__:!0}),rs=t,rs}var ss,Un;function Uc(){return Un||(Un=1,ss=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}),ss}var ns,$n;function Fn(){if($n)return ns;$n=1;var r=K,e=Cc(),t=kc(),s=qi,n=Vi,i=Nc(),o=Mc(),a=zi,u=gt,h=Rr(),p=Uc();return ns=function(b){return new Promise(function(A,k){var R=b.data,U=b.headers,N=b.responseType,M;function J(){b.cancelToken&&b.cancelToken.unsubscribe(M),b.signal&&b.signal.removeEventListener("abort",M)}r.isFormData(R)&&r.isStandardBrowserEnv()&&delete U["Content-Type"];var T=new XMLHttpRequest;if(b.auth){var Me=b.auth.username||"",Xe=b.auth.password?unescape(encodeURIComponent(b.auth.password)):"";U.Authorization="Basic "+btoa(Me+":"+Xe)}var de=n(b.baseURL,b.url);T.open(b.method.toUpperCase(),s(de,b.params,b.paramsSerializer),!0),T.timeout=b.timeout;function ee(){if(T){var z="getAllResponseHeaders"in T?i(T.getAllResponseHeaders()):null,ue=!N||N==="text"||N==="json"?T.responseText:T.response,X={data:ue,status:T.status,statusText:T.statusText,headers:z,config:b,request:T};e(function(Je){A(Je),J()},function(Je){k(Je),J()},X),T=null}}if("onloadend"in T?T.onloadend=ee:T.onreadystatechange=function(){!T||T.readyState!==4||T.status===0&&!(T.responseURL&&T.responseURL.indexOf("file:")===0)||setTimeout(ee)},T.onabort=function(){T&&(k(new u("Request aborted",u.ECONNABORTED,b,T)),T=null)},T.onerror=function(){k(new u("Network Error",u.ERR_NETWORK,b,T,T)),T=null},T.ontimeout=function(){var ue=b.timeout?"timeout of "+b.timeout+"ms exceeded":"timeout exceeded",X=b.transitional||a;b.timeoutErrorMessage&&(ue=b.timeoutErrorMessage),k(new u(ue,X.clarifyTimeoutError?u.ETIMEDOUT:u.ECONNABORTED,b,T)),T=null},r.isStandardBrowserEnv()){var Ae=(b.withCredentials||o(de))&&b.xsrfCookieName?t.read(b.xsrfCookieName):void 0;Ae&&(U[b.xsrfHeaderName]=Ae)}"setRequestHeader"in T&&r.forEach(U,function(ue,X){typeof R>"u"&&X.toLowerCase()==="content-type"?delete U[X]:T.setRequestHeader(X,ue)}),r.isUndefined(b.withCredentials)||(T.withCredentials=!!b.withCredentials),N&&N!=="json"&&(T.responseType=b.responseType),typeof b.onDownloadProgress=="function"&&T.addEventListener("progress",b.onDownloadProgress),typeof b.onUploadProgress=="function"&&T.upload&&T.upload.addEventListener("progress",b.onUploadProgress),(b.cancelToken||b.signal)&&(M=function(z){T&&(k(!z||z&&z.type?new h:z),T.abort(),T=null)},b.cancelToken&&b.cancelToken.subscribe(M),b.signal&&(b.signal.aborted?M():b.signal.addEventListener("abort",M))),R||(R=null);var Ue=p(de);if(Ue&&["http","https","file"].indexOf(Ue)===-1){k(new u("Unsupported protocol "+Ue+":",u.ERR_BAD_REQUEST,b));return}T.send(R)})},ns}var is,Ln;function $c(){return Ln||(Ln=1,is=null),is}var G=K,Dn=Pc,qn=gt,Fc=zi,Lc=Gi,Dc={"Content-Type":"application/x-www-form-urlencoded"};function Bn(r,e){!G.isUndefined(r)&&G.isUndefined(r["Content-Type"])&&(r["Content-Type"]=e)}function qc(){var r;return(typeof XMLHttpRequest<"u"||typeof process<"u"&&Object.prototype.toString.call(process)==="[object process]")&&(r=Fn()),r}function Bc(r,e,t){if(G.isString(r))try{return(e||JSON.parse)(r),G.trim(r)}catch(s){if(s.name!=="SyntaxError")throw s}return(t||JSON.stringify)(r)}var jr={transitional:Fc,adapter:qc(),transformRequest:[function(e,t){if(Dn(t,"Accept"),Dn(t,"Content-Type"),G.isFormData(e)||G.isArrayBuffer(e)||G.isBuffer(e)||G.isStream(e)||G.isFile(e)||G.isBlob(e))return e;if(G.isArrayBufferView(e))return e.buffer;if(G.isURLSearchParams(e))return Bn(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var s=G.isObject(e),n=t&&t["Content-Type"],i;if((i=G.isFileList(e))||s&&n==="multipart/form-data"){var o=this.env&&this.env.FormData;return Lc(i?{"files[]":e}:e,o&&new o)}else if(s||n==="application/json")return Bn(t,"application/json"),Bc(e);return e}],transformResponse:[function(e){var t=this.transitional||jr.transitional,s=t&&t.silentJSONParsing,n=t&&t.forcedJSONParsing,i=!s&&this.responseType==="json";if(i||n&&G.isString(e)&&e.length)try{return JSON.parse(e)}catch(o){if(i)throw o.name==="SyntaxError"?qn.from(o,qn.ERR_BAD_RESPONSE,this,null,this.response):o}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:$c()},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};G.forEach(["delete","get","head"],function(e){jr.headers[e]={}});G.forEach(["post","put","patch"],function(e){jr.headers[e]=G.merge(Dc)});var Vs=jr,Hc=K,Jc=Vs,zc=function(e,t,s){var n=this||Jc;return Hc.forEach(s,function(o){e=o.call(n,e,t)}),e},os,Hn;function Wi(){return Hn||(Hn=1,os=function(e){return!!(e&&e.__CANCEL__)}),os}var Jn=K,as=zc,Gc=Wi(),Vc=Vs,Wc=Rr();function cs(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new Wc}var Yc=function(e){cs(e),e.headers=e.headers||{},e.data=as.call(e,e.data,e.headers,e.transformRequest),e.headers=Jn.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),Jn.forEach(["delete","get","head","post","put","patch","common"],function(n){delete e.headers[n]});var t=e.adapter||Vc.adapter;return t(e).then(function(n){return cs(e),n.data=as.call(e,n.data,n.headers,e.transformResponse),n},function(n){return Gc(n)||(cs(e),n&&n.response&&(n.response.data=as.call(e,n.response.data,n.response.headers,e.transformResponse))),Promise.reject(n)})},ie=K,Yi=function(e,t){t=t||{};var s={};function n(p,g){return ie.isPlainObject(p)&&ie.isPlainObject(g)?ie.merge(p,g):ie.isPlainObject(g)?ie.merge({},g):ie.isArray(g)?g.slice():g}function i(p){if(ie.isUndefined(t[p])){if(!ie.isUndefined(e[p]))return n(void 0,e[p])}else return n(e[p],t[p])}function o(p){if(!ie.isUndefined(t[p]))return n(void 0,t[p])}function a(p){if(ie.isUndefined(t[p])){if(!ie.isUndefined(e[p]))return n(void 0,e[p])}else return n(void 0,t[p])}function u(p){if(p in t)return n(e[p],t[p]);if(p in e)return n(void 0,e[p])}var h={url:o,method:o,data:o,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:u};return ie.forEach(Object.keys(e).concat(Object.keys(t)),function(g){var b=h[g]||i,w=b(g);ie.isUndefined(w)&&b!==u||(s[g]=w)}),s},us,zn;function Ki(){return zn||(zn=1,us={version:"0.27.2"}),us}var Kc=Ki().version,Fe=gt,Ws={};["object","boolean","number","function","string","symbol"].forEach(function(r,e){Ws[r]=function(s){return typeof s===r||"a"+(e<1?"n ":" ")+r}});var Gn={};Ws.transitional=function(e,t,s){function n(i,o){return"[Axios v"+Kc+"] Transitional option '"+i+"'"+o+(s?". "+s:"")}return function(i,o,a){if(e===!1)throw new Fe(n(o," has been removed"+(t?" in "+t:"")),Fe.ERR_DEPRECATED);return t&&!Gn[o]&&(Gn[o]=!0,console.warn(n(o," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(i,o,a):!0}};function Xc(r,e,t){if(typeof r!="object")throw new Fe("options must be an object",Fe.ERR_BAD_OPTION_VALUE);for(var s=Object.keys(r),n=s.length;n-- >0;){var i=s[n],o=e[i];if(o){var a=r[i],u=a===void 0||o(a,i,r);if(u!==!0)throw new Fe("option "+i+" must be "+u,Fe.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new Fe("Unknown option "+i,Fe.ERR_BAD_OPTION)}}var Zc={assertOptions:Xc,validators:Ws},Xi=K,Qc=qi,Vn=Ec,Wn=Yc,Ir=Yi,eu=Vi,Zi=Zc,nt=Zi.validators;function ft(r){this.defaults=r,this.interceptors={request:new Vn,response:new Vn}}ft.prototype.request=function(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=Ir(this.defaults,t),t.method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var s=t.transitional;s!==void 0&&Zi.assertOptions(s,{silentJSONParsing:nt.transitional(nt.boolean),forcedJSONParsing:nt.transitional(nt.boolean),clarifyTimeoutError:nt.transitional(nt.boolean)},!1);var n=[],i=!0;this.interceptors.request.forEach(function(w){typeof w.runWhen=="function"&&w.runWhen(t)===!1||(i=i&&w.synchronous,n.unshift(w.fulfilled,w.rejected))});var o=[];this.interceptors.response.forEach(function(w){o.push(w.fulfilled,w.rejected)});var a;if(!i){var u=[Wn,void 0];for(Array.prototype.unshift.apply(u,n),u=u.concat(o),a=Promise.resolve(t);u.length;)a=a.then(u.shift(),u.shift());return a}for(var h=t;n.length;){var p=n.shift(),g=n.shift();try{h=p(h)}catch(b){g(b);break}}try{a=Wn(h)}catch(b){return Promise.reject(b)}for(;o.length;)a=a.then(o.shift(),o.shift());return a};ft.prototype.getUri=function(e){e=Ir(this.defaults,e);var t=eu(e.baseURL,e.url);return Qc(t,e.params,e.paramsSerializer)};Xi.forEach(["delete","get","head","options"],function(e){ft.prototype[e]=function(t,s){return this.request(Ir(s||{},{method:e,url:t,data:(s||{}).data}))}});Xi.forEach(["post","put","patch"],function(e){function t(s){return function(i,o,a){return this.request(Ir(a||{},{method:e,headers:s?{"Content-Type":"multipart/form-data"}:{},url:i,data:o}))}}ft.prototype[e]=t(),ft.prototype[e+"Form"]=t(!0)});var tu=ft,ls,Yn;function ru(){if(Yn)return ls;Yn=1;var r=Rr();function e(t){if(typeof t!="function")throw new TypeError("executor must be a function.");var s;this.promise=new Promise(function(o){s=o});var n=this;this.promise.then(function(i){if(n._listeners){var o,a=n._listeners.length;for(o=0;o<a;o++)n._listeners[o](i);n._listeners=null}}),this.promise.then=function(i){var o,a=new Promise(function(u){n.subscribe(u),o=u}).then(i);return a.cancel=function(){n.unsubscribe(o)},a},t(function(o){n.reason||(n.reason=new r(o),s(n.reason))})}return e.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},e.prototype.subscribe=function(s){if(this.reason){s(this.reason);return}this._listeners?this._listeners.push(s):this._listeners=[s]},e.prototype.unsubscribe=function(s){if(this._listeners){var n=this._listeners.indexOf(s);n!==-1&&this._listeners.splice(n,1)}},e.source=function(){var s,n=new e(function(o){s=o});return{token:n,cancel:s}},ls=e,ls}var hs,Kn;function su(){return Kn||(Kn=1,hs=function(e){return function(s){return e.apply(null,s)}}),hs}var fs,Xn;function nu(){if(Xn)return fs;Xn=1;var r=K;return fs=function(t){return r.isObject(t)&&t.isAxiosError===!0},fs}var Zn=K,iu=Fi,hr=tu,ou=Yi,au=Vs;function Qi(r){var e=new hr(r),t=iu(hr.prototype.request,e);return Zn.extend(t,hr.prototype,e),Zn.extend(t,e),t.create=function(n){return Qi(ou(r,n))},t}var re=Qi(au);re.Axios=hr;re.CanceledError=Rr();re.CancelToken=ru();re.isCancel=Wi();re.VERSION=Ki().version;re.toFormData=Gi;re.AxiosError=gt;re.Cancel=re.CanceledError;re.all=function(e){return Promise.all(e)};re.spread=su();re.isAxiosError=nu();$i.exports=re;$i.exports.default=re;var cu={exports:{}};(function(r){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function n(u,h,p){this.fn=u,this.context=h,this.once=p||!1}function i(u,h,p,g,b){if(typeof p!="function")throw new TypeError("The listener must be a function");var w=new n(p,g||u,b),A=t?t+h:h;return u._events[A]?u._events[A].fn?u._events[A]=[u._events[A],w]:u._events[A].push(w):(u._events[A]=w,u._eventsCount++),u}function o(u,h){--u._eventsCount===0?u._events=new s:delete u._events[h]}function a(){this._events=new s,this._eventsCount=0}a.prototype.eventNames=function(){var h=[],p,g;if(this._eventsCount===0)return h;for(g in p=this._events)e.call(p,g)&&h.push(t?g.slice(1):g);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(p)):h},a.prototype.listeners=function(h){var p=t?t+h:h,g=this._events[p];if(!g)return[];if(g.fn)return[g.fn];for(var b=0,w=g.length,A=new Array(w);b<w;b++)A[b]=g[b].fn;return A},a.prototype.listenerCount=function(h){var p=t?t+h:h,g=this._events[p];return g?g.fn?1:g.length:0},a.prototype.emit=function(h,p,g,b,w,A){var k=t?t+h:h;if(!this._events[k])return!1;var R=this._events[k],U=arguments.length,N,M;if(R.fn){switch(R.once&&this.removeListener(h,R.fn,void 0,!0),U){case 1:return R.fn.call(R.context),!0;case 2:return R.fn.call(R.context,p),!0;case 3:return R.fn.call(R.context,p,g),!0;case 4:return R.fn.call(R.context,p,g,b),!0;case 5:return R.fn.call(R.context,p,g,b,w),!0;case 6:return R.fn.call(R.context,p,g,b,w,A),!0}for(M=1,N=new Array(U-1);M<U;M++)N[M-1]=arguments[M];R.fn.apply(R.context,N)}else{var J=R.length,T;for(M=0;M<J;M++)switch(R[M].once&&this.removeListener(h,R[M].fn,void 0,!0),U){case 1:R[M].fn.call(R[M].context);break;case 2:R[M].fn.call(R[M].context,p);break;case 3:R[M].fn.call(R[M].context,p,g);break;case 4:R[M].fn.call(R[M].context,p,g,b);break;default:if(!N)for(T=1,N=new Array(U-1);T<U;T++)N[T-1]=arguments[T];R[M].fn.apply(R[M].context,N)}}return!0},a.prototype.on=function(h,p,g){return i(this,h,p,g,!1)},a.prototype.once=function(h,p,g){return i(this,h,p,g,!0)},a.prototype.removeListener=function(h,p,g,b){var w=t?t+h:h;if(!this._events[w])return this;if(!p)return o(this,w),this;var A=this._events[w];if(A.fn)A.fn===p&&(!b||A.once)&&(!g||A.context===g)&&o(this,w);else{for(var k=0,R=[],U=A.length;k<U;k++)(A[k].fn!==p||b&&!A[k].once||g&&A[k].context!==g)&&R.push(A[k]);R.length?this._events[w]=R.length===1?R[0]:R:o(this,w)}return this},a.prototype.removeAllListeners=function(h){var p;return h?(p=t?t+h:h,this._events[p]&&o(this,p)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,r.exports=a})(cu);class Tr extends Ia{constructor(){super(),this.init()}init(){console.log("controller init")}onReady(){console.log("here can call other controller")}}var eo={exports:{}};(function(r,e){(function(t,s){s()})(At,function(){function t(h,p){return typeof p>"u"?p={autoBom:!1}:typeof p!="object"&&(console.warn("Deprecated: Expected third argument to be a object"),p={autoBom:!p}),p.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(h.type)?new Blob(["\uFEFF",h],{type:h.type}):h}function s(h,p,g){var b=new XMLHttpRequest;b.open("GET",h),b.responseType="blob",b.onload=function(){u(b.response,p,g)},b.onerror=function(){console.error("could not download file")},b.send()}function n(h){var p=new XMLHttpRequest;p.open("HEAD",h,!1);try{p.send()}catch{}return 200<=p.status&&299>=p.status}function i(h){try{h.dispatchEvent(new MouseEvent("click"))}catch{var p=document.createEvent("MouseEvents");p.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),h.dispatchEvent(p)}}var o=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof At=="object"&&At.global===At?At:void 0,a=o.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),u=o.saveAs||(typeof window!="object"||window!==o?function(){}:"download"in HTMLAnchorElement.prototype&&!a?function(h,p,g){var b=o.URL||o.webkitURL,w=document.createElement("a");p=p||h.name||"download",w.download=p,w.rel="noopener",typeof h=="string"?(w.href=h,w.origin===location.origin?i(w):n(w.href)?s(h,p,g):i(w,w.target="_blank")):(w.href=b.createObjectURL(h),setTimeout(function(){b.revokeObjectURL(w.href)},4e4),setTimeout(function(){i(w)},0))}:"msSaveOrOpenBlob"in navigator?function(h,p,g){if(p=p||h.name||"download",typeof h!="string")navigator.msSaveOrOpenBlob(t(h,g),p);else if(n(h))s(h,p,g);else{var b=document.createElement("a");b.href=h,b.target="_blank",setTimeout(function(){i(b)})}}:function(h,p,g,b){if(b=b||open("","_blank"),b&&(b.document.title=b.document.body.innerText="downloading..."),typeof h=="string")return s(h,p,g);var w=h.type==="application/octet-stream",A=/constructor/i.test(o.HTMLElement)||o.safari,k=/CriOS\/[\d]+/.test(navigator.userAgent);if((k||w&&A||a)&&typeof FileReader<"u"){var R=new FileReader;R.onloadend=function(){var M=R.result;M=k?M:M.replace(/^data:[^;]*;/,"data:attachment/file;"),b?b.location.href=M:location=M,b=null},R.readAsDataURL(h)}else{var U=o.URL||o.webkitURL,N=U.createObjectURL(h);b?b.location=N:location.href=N,b=null,setTimeout(function(){U.revokeObjectURL(N)},4e4)}});o.saveAs=u.saveAs=u,r.exports=u})})(eo);var uu=eo.exports;const to="3.7.5",lu=to,hu=typeof atob=="function",fu=typeof btoa=="function",_t=typeof Buffer=="function",Qn=typeof TextDecoder=="function"?new TextDecoder:void 0,ei=typeof TextEncoder=="function"?new TextEncoder:void 0,du="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Ot=Array.prototype.slice.call(du),nr=(r=>{let e={};return r.forEach((t,s)=>e[t]=s),e})(Ot),pu=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,W=String.fromCharCode.bind(String),ti=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):r=>new Uint8Array(Array.prototype.slice.call(r,0)),ro=r=>r.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),so=r=>r.replace(/[^A-Za-z0-9\+\/]/g,""),no=r=>{let e,t,s,n,i="";const o=r.length%3;for(let a=0;a<r.length;){if((t=r.charCodeAt(a++))>255||(s=r.charCodeAt(a++))>255||(n=r.charCodeAt(a++))>255)throw new TypeError("invalid character found");e=t<<16|s<<8|n,i+=Ot[e>>18&63]+Ot[e>>12&63]+Ot[e>>6&63]+Ot[e&63]}return o?i.slice(0,o-3)+"===".substring(o):i},Ys=fu?r=>btoa(r):_t?r=>Buffer.from(r,"binary").toString("base64"):no,Es=_t?r=>Buffer.from(r).toString("base64"):r=>{let t=[];for(let s=0,n=r.length;s<n;s+=4096)t.push(W.apply(null,r.subarray(s,s+4096)));return Ys(t.join(""))},fr=(r,e=!1)=>e?ro(Es(r)):Es(r),mu=r=>{if(r.length<2){var e=r.charCodeAt(0);return e<128?r:e<2048?W(192|e>>>6)+W(128|e&63):W(224|e>>>12&15)+W(128|e>>>6&63)+W(128|e&63)}else{var e=65536+(r.charCodeAt(0)-55296)*1024+(r.charCodeAt(1)-56320);return W(240|e>>>18&7)+W(128|e>>>12&63)+W(128|e>>>6&63)+W(128|e&63)}},bu=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,io=r=>r.replace(bu,mu),ri=_t?r=>Buffer.from(r,"utf8").toString("base64"):ei?r=>Es(ei.encode(r)):r=>Ys(io(r)),at=(r,e=!1)=>e?ro(ri(r)):ri(r),si=r=>at(r,!0),gu=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,_u=r=>{switch(r.length){case 4:var e=(7&r.charCodeAt(0))<<18|(63&r.charCodeAt(1))<<12|(63&r.charCodeAt(2))<<6|63&r.charCodeAt(3),t=e-65536;return W((t>>>10)+55296)+W((t&1023)+56320);case 3:return W((15&r.charCodeAt(0))<<12|(63&r.charCodeAt(1))<<6|63&r.charCodeAt(2));default:return W((31&r.charCodeAt(0))<<6|63&r.charCodeAt(1))}},oo=r=>r.replace(gu,_u),ao=r=>{if(r=r.replace(/\s+/g,""),!pu.test(r))throw new TypeError("malformed base64.");r+="==".slice(2-(r.length&3));let e,t="",s,n;for(let i=0;i<r.length;)e=nr[r.charAt(i++)]<<18|nr[r.charAt(i++)]<<12|(s=nr[r.charAt(i++)])<<6|(n=nr[r.charAt(i++)]),t+=s===64?W(e>>16&255):n===64?W(e>>16&255,e>>8&255):W(e>>16&255,e>>8&255,e&255);return t},Ks=hu?r=>atob(so(r)):_t?r=>Buffer.from(r,"base64").toString("binary"):ao,co=_t?r=>ti(Buffer.from(r,"base64")):r=>ti(Ks(r).split("").map(e=>e.charCodeAt(0))),uo=r=>co(lo(r)),yu=_t?r=>Buffer.from(r,"base64").toString("utf8"):Qn?r=>Qn.decode(co(r)):r=>oo(Ks(r)),lo=r=>so(r.replace(/[-_]/g,e=>e=="-"?"+":"/")),As=r=>yu(lo(r)),wu=r=>{if(typeof r!="string")return!1;const e=r.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(e)||!/[^\s0-9a-zA-Z\-_]/.test(e)},ho=r=>({value:r,enumerable:!1,writable:!0,configurable:!0}),fo=function(){const r=(e,t)=>Object.defineProperty(String.prototype,e,ho(t));r("fromBase64",function(){return As(this)}),r("toBase64",function(e){return at(this,e)}),r("toBase64URI",function(){return at(this,!0)}),r("toBase64URL",function(){return at(this,!0)}),r("toUint8Array",function(){return uo(this)})},po=function(){const r=(e,t)=>Object.defineProperty(Uint8Array.prototype,e,ho(t));r("toBase64",function(e){return fr(this,e)}),r("toBase64URI",function(){return fr(this,!0)}),r("toBase64URL",function(){return fr(this,!0)})},xu=()=>{fo(),po()},mo={version:to,VERSION:lu,atob:Ks,atobPolyfill:ao,btoa:Ys,btoaPolyfill:no,fromBase64:As,toBase64:at,encode:at,encodeURI:si,encodeURL:si,utob:io,btou:oo,decode:As,isValid:wu,fromUint8Array:fr,toUint8Array:uo,extendString:fo,extendUint8Array:po,extendBuiltins:xu};class vu extends Tr{constructor(){super();c(this,"ipc");c(this,"_conn");c(this,"profile",{wsPort:"",version:"",dataDir:"",exeDir:"",exeName:"",exePath:""});window.ipc?this.ipc=window.ipc:this.ipc={emit(t,...s){console.error("emit msg=>",t,s)},on(t){console.error("on message",t)}},this.initEvent()}initEvent(){const t=this;this.ipc.on("OnDragEnter",function(s){t.emit("onDragEnter",s)}),this.ipc.on("downloadsucc",(s,n)=>{t.emit("downloadsucc",s,n)}),this.ipc.emit("GetSocketUri",[],s=>{let n=new WebSocket(s);n.onopen=i=>{console.log("bus socket connected!!!")},n.onclose=i=>{console.log("app bus socket conn closed",i),setTimeout(()=>{this._conn=new WebSocket(s)},1e3)},n.onmessage=function(i){if(!(!i.data||i.data==""))try{i.data.arrayBuffer().then(a=>{const u=xa(new Uint8Array(a));t.emit("on"+u.sub,u)})}catch(o){console.error(i.data,typeof i.data,o)}},this._conn=n})}async onReady(){this.profile=await this.getLocalAppProfile()}getLocalAppProfile(){return new Promise(t=>{this.ipc.emit("LocalAppProfile",[],function(n){t(n)})})}SelectDir(){const t=Date.now(),s="c"+t;return new Promise(n=>{const i=this.ipc;i.emit("SelectDir",[t],function(o){console.log("call=>",o),o||n(""),i.on(s,function(a){n(a)})})})}IsDirEmpty(t){return new Promise(s=>{this.ipc.emit("IsDirEmpty",[t],function(i){s(i)})})}IsFileExit(t){return new Promise(s=>{this.ipc.emit("IsFileExit",[t],function(i){s(i)})})}WriteFileText(t,s){return new Promise(n=>{this.ipc.emit("WriteFileText",[t,s],function(o){n(o)})})}ReadFileText(t){return new Promise(s=>{this.ipc.emit("ReadFileText",[t],function(i){s(i)})})}CopyFile(t,s){const i="copy"+Date.now();return new Promise(o=>{const a=this.ipc;a.on(i,function(u){o(u)}),a.emit("CopyFile",[i,t,s])})}SaveSysConfigItem(t,s){return new Promise(n=>{this.ipc.emit("SaveAppConfigItem",[t,s],function(o){n(o)})})}GetSysConfigItem(t){return new Promise(s=>{this.ipc.emit("GetAppConfigItem",[t],function(i){s(i)})})}RemoveSysConfigItem(t){return new Promise(s=>{this.ipc.emit("RemoveSysConfigItem",[t],function(i){s(i)})})}GetSysDataBaseUrl(){return new Promise(t=>{this.ipc.emit("GetAppDataBaseUrl",[],function(n){t(n)})})}CopyFileToAppData(t,s){return new Promise(n=>{this.ipc.emit("CopyFileToAppData",[t,s],function(o){n(o)})})}RemoveAppData(t){return new Promise(s=>{this.ipc.emit("RemoveAppData",[t],function(i){s(i)})})}OpenDir(t){return new Promise(s=>{this.ipc.emit("OpenDir",[t],function(i){s(i)})})}SelectOneFilePath(t,s){const n=Date.now();return new Promise(i=>{const o=this.ipc,a="c"+n;o.emit("SelectOneFilePath",[n,t,s],function(u){u||i(""),o.on(a,function(h){i(h)})})})}StartHttpServer(t){return new Promise(s=>{this.ipc.emit("StartProjectHttpServer",[t],function(i){s(i)})})}DownloadFile(t,s,n=60*20,i){const o="d"+Date.now();return new Promise(a=>{console.log(t,"==>",s);const u=this.OnMsg(o,p=>{if(i&&i(p.type,p),p.type=="succ"){a(!0),u.unbind();return}p.type=="error"&&(a(!1),u.unbind())});this.ipc.emit("DownloadFile",[o,s,t,n],function(p){console.log("DownloadFile callback"),p&&(console.error(p),a(!1))})})}Unzip(t,s,n){const i="unzip"+Date.now();return new Promise(o=>{const a=this.OnMsg(i,h=>{if(n&&n(h.type,h),h.type=="succ"){o(!0),a.unbind();return}h.type=="error"&&(o(!1),a.unbind())});this.ipc.emit("Unzip",[i,t,s])})}GetDirSize(t){return new Promise(s=>{this.ipc.emit("GetDirSize",[t],function(i){s(i)})})}GetAppDataDir(){return new Promise(t=>{this.ipc.emit("GetAppDataDir",[],function(n){t(n)})})}OpenAssetWindow(t){return new Promise(s=>{this.ipc.emit("openAssetsWindow",[`${location.host}/library.html?path=${t}`,"资源管理库",1280,960],function(i){s(i)})})}SendMsg(t,s){const n=this._conn;if(!n){console.error("应用socket异常");return}n.send(ya({sub:t,msg:s}))}OnMsg(t,s){return this.on("on"+t,s)}UploadSync(t){return new Promise(s=>{this.ipc.emit("UploadSync",[t],function(i){s(i)})})}UploadASync(t){const s="u"+Date.now();return new Promise(n=>{const i=this.ipc;i.emit("UploadASync",[s,t],function(o){if(!o){n([]);return}i.on(s,a=>{n(a)})})})}UploadDir(t,s){const n="u"+Date.now();return new Promise(i=>{const o=this.ipc;o.emit("UploadDir",[n,t,s],function(a){if(!a){i([]);return}o.on(n,u=>{i(u)})})})}GetFilesInDir(t,s){return new Promise(n=>{this.ipc.emit("GetFilesInDir",[t,s],function(o){n(o)})})}GetRunningApp(){return new Promise(t=>{this.ipc.emit("GetRunningApp",[],function(n){t(n)})})}GetSubDirNames(t){return new Promise(s=>{this.ipc.emit("GetSubDirNames",[t],function(i){s(i)})})}RemoveFile(t){return new Promise(s=>{this.ipc.emit("RemoveFile",[t],function(i){s(i)})})}RemoveDir(t){return new Promise(s=>{this.ipc.emit("RemoveDir",[t],function(i){s(i)})})}GetSaveFile(t,s="图片(*.png;*.jpg)"){const n="sf"+Date.now();return new Promise(i=>{const o=this.ipc;o.emit("GetSaveFile",[n,t,s],function(a){if(a){o.on(n,u=>{i(u)});return}i("")})})}OpenOneFile(t,s="图片(*.png;*.jpg)"){const n="sf"+Date.now();return new Promise(i=>{this.ipc.emit("OpenOneFile",[n,t,s],function(a){setTimeout(()=>{i(a)},0)})})}GetImageMeta(t){return new Promise(s=>{const n=new Image;n.onload=()=>{s({Width:n.width,Height:n.height,Size:0})},n.src=t})}SetMainTitle(t){return new Promise(s=>{this.ipc.emit("SetMainTitle",[t],function(i){s(i)})})}SaveFile(t,s){return new Promise(n=>{this.ipc.emit("SaveFile",[t,Array.from(s)],function(o){n(o)})})}OpenQueen5(t,s){return new Promise(n=>{this.ipc.emit("OpenQueen5",[t,s],function(o){n(o)})})}OpenQueen5Play(t,s){return new Promise(n=>{this.ipc.emit("OpenQueen5Play",[t,s],function(o){n(o)})})}SaveBlobFile(t,s){return console.log("save blob to ",s),new Promise(n=>{const i=this.on("downloadsucc",o=>{console.log("fpath=>",o),s==mo.encode(o)&&(i.unbind(),n(!0))});uu.saveAs(t,s)})}SaveClipboard(t){return navigator.clipboard.write([new ClipboardItem({"image/png":t})])}GetNatsProfile(){return new Promise(t=>{this.ipc.emit("NatsProfile",[],function(n){t(n)})})}OpenWeb(t,s,n=1280,i=720){return new Promise(o=>{this.ipc.emit("OpenWeb",[t,s,n,i],function(u){o(u)})})}RunNativeApp(t,s,n,i,o){return new Promise(a=>{this.ipc.emit("RunNativeApp",[t,s,n,i,o],function(h){console.log("xxxx",h),a(h)})})}RunCmdSvcApp(t,s,n,i,o,a){return new Promise(u=>{this.ipc.emit("RunCmdSvcApp",[t,s,n,i,o,a],function(p){console.log("xxxx",p),u(p)})})}StopNativeApp(t){return new Promise(s=>{this.ipc.emit("StopNativeApp",[t],function(i){s(i)})})}LancherUpgrade(t,s){return new Promise(n=>{this.ipc.emit("Upgrade",[t,s],function(o){n(o)})})}CreateShortcut(t,s,n){return new Promise(i=>{this.ipc.emit("CreateShortcut",[t,s,n],function(a){i(a)})})}DeleteShortcut(t){return new Promise(s=>{this.ipc.emit("DeleteShortcut",[t],function(i){s(i)})})}ResumeMainWnd(){return new Promise(t=>{this.ipc.emit("ResumeMainWnd",[],function(n){t(n)})})}HideMainWnd(){return new Promise(t=>{this.ipc.emit("HideMainWnd",[],function(n){t(n)})})}QuitLancher(){return new Promise(t=>{this.ipc.emit("QuitLancher",[],function(n){t(n)})})}MaxWindow(t){return new Promise(s=>{this.ipc.emit("MaxWindow",[t],function(i){s(i)})})}FoldWindow(t){return new Promise(s=>{this.ipc.emit("FoldWindow",[t],function(i){s(i)})})}TrayNotice(t){return new Promise(s=>{this.ipc.emit("TrayNotice",[t.title||"提示",t.context,t.timeout||2e3],function(i){s(i)})})}UpdateConfig(t){return new Promise(s=>{this.ipc.emit("UpdateConfig",[t],function(i){s(i)})})}}class Su extends Tr{constructor(){super(...arguments);c(this,"RootDir","");c(this,"DataDir","");c(this,"HostURL","");c(this,"_swiftLocal",!0);c(this,"_spu3dFile");c(this,"UserId","spu3d");c(this,"NatsProfile",{apiPort:"",wsPort:"",ip:""})}async onReady(){const t=ve().deviceCtrl;t.GetAppDataDir().then(s=>{this.DataDir=s,this.RootDir=s}),this.NatsProfile=await t.GetNatsProfile(),console.log("nats profile=>",this.NatsProfile)}getOutputDir(){return this.RootDir+"/outputs"}getAppDataDir(){return this.DataDir}getAppInstallDir(){return this.createPath("installDir")}getDefaultLogo(){return this.DataDir+"/static/thumbnail.png"}createPath(t){return this.RootDir+"/"+t}createBase64Path(t){const s=mo.encode(this.createPath(t));return console.log("str",s),s}getSwiftUri(t){return this._swiftLocal?this.getLocalAbsoluteUri(t):this.getHttpAbsoluteUri(t)}getHttpAbsoluteUri(t){return t?t.substring(0,2)=="//"?"http://"+t:t.substring(0,4)=="http"?t:t.charAt(0)=="/"?this.HostURL+t.substring(1):this.HostURL+t:""}getLocalAbsoluteUri(t){return t?t.substring(0,2)=="//"?"http://"+t:t.substring(0,4)=="http"?t:t.charAt(0)=="/"?this.RootDir+t:this.RootDir+"/"+t:""}getRelativeUri(t){let s=this.HostURL.length,n=t.substring(0,s);return n==this.HostURL||(s=this.RootDir.length,n=t.substring(0,s),n==this.RootDir)?t.substring(s+1):""}async pickProject(){const s=await ve().deviceCtrl.SelectDir();return await this.isProjectExit(s)?s:Promise.reject()}async isProjectExit(t){return await ve().deviceCtrl.IsFileExit(`${t}/project.spu3d`)}isProjectFile(t){return t.substring(0,this.RootDir.length)==this.RootDir}async copy2Project(t,s){if(this.isProjectFile(t))return t.substring(this.RootDir.length+1);const n=t.substring(t.lastIndexOf(".")),i=s(n);return await ve().deviceCtrl.CopyFile(t,this.createPath(i)),i}}var Ps=function(r,e){return Ps=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,s){t.__proto__=s}||function(t,s){for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&(t[n]=s[n])},Ps(r,e)};function Bt(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Ps(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Os(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],s=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&s>=r.length&&(r=void 0),{value:r&&r[s++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function gr(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var s=t.call(r),n,i=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)i.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return i}function _r(r,e,t){if(t||arguments.length===2)for(var s=0,n=e.length,i;s<n;s++)(i||!(s in e))&&(i||(i=Array.prototype.slice.call(e,0,s)),i[s]=e[s]);return r.concat(i||Array.prototype.slice.call(e))}function Ie(r){return typeof r=="function"}function bo(r){var e=function(s){Error.call(s),s.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var ds=bo(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
- `+t.map(function(s,n){return n+1+") "+s.toString()}).join(`
- `):"",this.name="UnsubscriptionError",this.errors=t}});function Cs(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var Nr=function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,s,n,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=Os(o),u=a.next();!u.done;u=a.next()){var h=u.value;h.remove(this)}}catch(k){e={error:k}}finally{try{u&&!u.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else o.remove(this);var p=this.initialTeardown;if(Ie(p))try{p()}catch(k){i=k instanceof ds?k.errors:[k]}var g=this._finalizers;if(g){this._finalizers=null;try{for(var b=Os(g),w=b.next();!w.done;w=b.next()){var A=w.value;try{ni(A)}catch(k){i=i??[],k instanceof ds?i=_r(_r([],gr(i)),gr(k.errors)):i.push(k)}}}catch(k){s={error:k}}finally{try{w&&!w.done&&(n=b.return)&&n.call(b)}finally{if(s)throw s.error}}}if(i)throw new ds(i)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)ni(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Cs(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&Cs(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),go=Nr.EMPTY;function _o(r){return r instanceof Nr||r&&"closed"in r&&Ie(r.remove)&&Ie(r.add)&&Ie(r.unsubscribe)}function ni(r){Ie(r)?r():r.unsubscribe()}var yo={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},ks={setTimeout:function(r,e){for(var t=[],s=2;s<arguments.length;s++)t[s-2]=arguments[s];var n=ks.delegate;return n!=null&&n.setTimeout?n.setTimeout.apply(n,_r([r,e],gr(t))):setTimeout.apply(void 0,_r([r,e],gr(t)))},clearTimeout:function(r){var e=ks.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function Eu(r){ks.setTimeout(function(){throw r})}function ii(){}function dr(r){r()}var wo=function(r){Bt(e,r);function e(t){var s=r.call(this)||this;return s.isStopped=!1,t?(s.destination=t,_o(t)&&t.add(s)):s.destination=Cu,s}return e.create=function(t,s,n){return new Rs(t,s,n)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Nr),Au=Function.prototype.bind;function ps(r,e){return Au.call(r,e)}var Pu=function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(s){ir(s)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(s){ir(s)}else ir(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){ir(t)}},r}(),Rs=function(r){Bt(e,r);function e(t,s,n){var i=r.call(this)||this,o;if(Ie(t)||!t)o={next:t??void 0,error:s??void 0,complete:n??void 0};else{var a;i&&yo.useDeprecatedNextContext?(a=Object.create(t),a.unsubscribe=function(){return i.unsubscribe()},o={next:t.next&&ps(t.next,a),error:t.error&&ps(t.error,a),complete:t.complete&&ps(t.complete,a)}):o=t}return i.destination=new Pu(o),i}return e}(wo);function ir(r){Eu(r)}function Ou(r){throw r}var Cu={closed:!0,next:ii,error:Ou,complete:ii},ku=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Ru(r){return r}function ju(r){return r.length===0?Ru:r.length===1?r[0]:function(t){return r.reduce(function(s,n){return n(s)},t)}}var oi=function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,s){var n=this,i=Tu(e)?e:new Rs(e,t,s);return dr(function(){var o=n,a=o.operator,u=o.source;i.add(a?a.call(i,u):u?n._subscribe(i):n._trySubscribe(i))}),i},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var s=this;return t=ai(t),new t(function(n,i){var o=new Rs({next:function(a){try{e(a)}catch(u){i(u),o.unsubscribe()}},error:i,complete:n});s.subscribe(o)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[ku]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ju(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=ai(e),new e(function(s,n){var i;t.subscribe(function(o){return i=o},function(o){return n(o)},function(){return s(i)})})},r.create=function(e){return new r(e)},r}();function ai(r){var e;return(e=r??yo.Promise)!==null&&e!==void 0?e:Promise}function Iu(r){return r&&Ie(r.next)&&Ie(r.error)&&Ie(r.complete)}function Tu(r){return r&&r instanceof wo||Iu(r)&&_o(r)}var Nu=bo(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),xo=function(r){Bt(e,r);function e(){var t=r.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var s=new ci(this,this);return s.operator=t,s},e.prototype._throwIfClosed=function(){if(this.closed)throw new Nu},e.prototype.next=function(t){var s=this;dr(function(){var n,i;if(s._throwIfClosed(),!s.isStopped){s.currentObservers||(s.currentObservers=Array.from(s.observers));try{for(var o=Os(s.currentObservers),a=o.next();!a.done;a=o.next()){var u=a.value;u.next(t)}}catch(h){n={error:h}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}}})},e.prototype.error=function(t){var s=this;dr(function(){if(s._throwIfClosed(),!s.isStopped){s.hasError=s.isStopped=!0,s.thrownError=t;for(var n=s.observers;n.length;)n.shift().error(t)}})},e.prototype.complete=function(){var t=this;dr(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var s=t.observers;s.length;)s.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var s=this,n=this,i=n.hasError,o=n.isStopped,a=n.observers;return i||o?go:(this.currentObservers=null,a.push(t),new Nr(function(){s.currentObservers=null,Cs(a,t)}))},e.prototype._checkFinalizedStatuses=function(t){var s=this,n=s.hasError,i=s.thrownError,o=s.isStopped;n?t.error(i):o&&t.complete()},e.prototype.asObservable=function(){var t=new oi;return t.source=this,t},e.create=function(t,s){return new ci(t,s)},e}(oi),ci=function(r){Bt(e,r);function e(t,s){var n=r.call(this)||this;return n.destination=t,n.source=s,n}return e.prototype.next=function(t){var s,n;(n=(s=this.destination)===null||s===void 0?void 0:s.next)===null||n===void 0||n.call(s,t)},e.prototype.error=function(t){var s,n;(n=(s=this.destination)===null||s===void 0?void 0:s.error)===null||n===void 0||n.call(s,t)},e.prototype.complete=function(){var t,s;(s=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||s===void 0||s.call(t)},e.prototype._subscribe=function(t){var s,n;return(n=(s=this.source)===null||s===void 0?void 0:s.subscribe(t))!==null&&n!==void 0?n:go},e}(xo),Mu=function(r){Bt(e,r);function e(t){var s=r.call(this)||this;return s._value=t,s}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(t){var s=r.prototype._subscribe.call(this,t);return!s.closed&&t.next(this._value),s},e.prototype.getValue=function(){var t=this,s=t.hasError,n=t.thrownError,i=t._value;if(s)throw n;return this._throwIfClosed(),i},e.prototype.next=function(t){r.prototype.next.call(this,this._value=t)},e}(xo);class Xs{constructor(e,t,s,n){c(this,"Id");c(this,"Value");c(this,"OldValue");c(this,"Rx");this.Id=e,this.Value=t,this.OldValue=s,this.Rx=n}redo(){this.Rx.next({value:this.Value,_hstry:!1})}undo(){this.Rx.next({value:this.OldValue,_hstry:!1})}clone(){return new Xs(this.Id,this.Value,this.OldValue,this.Rx)}}function Uu(r,e){return new Mu({value:r,_hstry:e})}let ui=0;function $u(r,e,t){let s=ui+1;return ui+=1,new Xs(s+"",r,e,t)}class Fu{static create(e,t){let s={__rx:!0};return s._historySnap={},s._historySub={},s._rxs={},s._fields=e,s._history=t,s._refs={},Object.keys(e).forEach(i=>{const o=i,a=e[o];if(typeof a=="object"&&a.__rx){s[o]=a;return}const h=Uu(a,!!t);s._rxs[i]=h;const p=$u(a,a,h);s._historySnap[i]=p;const g=Mi({value:a});Object.defineProperty(s,o,{get:function(){return g.value},set:function(w){h.next({value:w})},configurable:!0,enumerable:!0});const b=o.slice(0,1).toUpperCase()+o.slice(1);s["set"+b]=function(w,A=!1){h.next({value:w,_hstry:!A})},s["on"+b+"Changed"]=function(w){return h.subscribe(A=>{w(A.value,p.OldValue)})},s._historySub[i]=h.subscribe(w=>{if(p.OldValue=g.value,g.value=w.value,s._history&&s._history.enable){if(!w._hstry)return;const A=p.clone();A.Value=w.value,s._history.record(A)}})}),s.setHistory=function(i){s._history=i},s.toJson=function(){const i={};return Object.keys(e).forEach(a=>{const u=e[a];if(typeof u=="object"&&u.__rx){i[a]=s[a].toJson();return}i[a]=vn.cloneDeep(la(s._rxs[a].getValue().value))}),i},s.fromJson=function(i){const o={};return Object.keys(e).forEach(u=>{const h=e[u];if(typeof h=="object"&&h.__rx){i[u]&&(o[u]=s[u].fromJson(i[u]));return}s._rxs[u].next({value:i[u]!=null?i[u]:vn.cloneDeep(h),_hstry:!1})}),o},s}}class Lu extends Tr{constructor(){super(...arguments);c(this,"state",Fu.create({apps:[],installing:!1,downProgress:"",installProgress:""}))}async onReady(){return await this.parseInstalledApp()}async parseInstalledApp(){const{deviceCtrl:t,prjCtrl:s}=ve(),n=[];try{const i=await t.ReadFileText(`${s.RootDir}/app.json`);if(!i.error&&i.text){const o=JSON.parse(i.text);n.push(o)}}catch(i){console.error(i)}this.state.setApps(n)}async install(t){console.log("install=>",t);const{deviceCtrl:s,prjCtrl:n}=ve(),i=n.createPath(`${t._id}.zip`);this.state.installing=!0,await s.DownloadFile(t.url,i,60*10,(a,u)=>{console.log("down",a,u.fva11),a=="progress"&&(this.state.downProgress=((u.fva11||0)*100).toFixed(1)),a=="succ"&&(this.state.downProgress="",ha.success("下载成功,开始安装...")),a=="error"&&(this.state.installing=!1,s.TrayNotice({context:"软件下载失败,请检查你的网络设置"}))})&&await s.Unzip(i,n.RootDir,(u,h)=>{console.log("install",u,h.fva11),u=="progress"&&(this.state.installProgress=((h.fva11||0)*10).toFixed(1)),u=="succ"&&(this.state.installProgress="",this.state.installing=!1,s.TrayNotice({context:"软件安装成功"})),u=="error"&&(this.state.installing=!1,this.state.installProgress="",s.TrayNotice({context:"软件安装失败,请重新安装"}))})&&(await s.UpdateConfig(t.version),await this.parseInstalledApp(),s.RemoveFile(i))}async update(t){const{deviceCtrl:s,prjCtrl:n}=ve(),i=await s.GetRunningApp();let o=i.find(h=>h.Key==t.name);if(console.log("running",i),o){ke.messageWarn("请先关闭应用程序,再进行更新!");return}const a=n.getAppInstallDir()+`/${t.name}`;await s.RemoveDir(a)&&this.install(t)}async uninstall(t){const{deviceCtrl:s,prjCtrl:n}=ve();if((await s.GetRunningApp()).find(h=>h.Key==t.key)){ke.messageWarn("请先关闭应用程序,再进行卸载!");return}const a=n.getAppInstallDir()+`/${t.key}`;await s.RemoveDir(a)&&(s.DeleteShortcut(t.key),s.TrayNotice({context:`${t.name}卸载成功!`}),await this.parseInstalledApp())}async CreateShortcut(t){const{deviceCtrl:s,prjCtrl:n}=ve(),i=n.getAppInstallDir()+`/${t.key}/${t.icon}`;await s.CreateShortcut(t.key,s.profile.exePath,i)&&s.TrayNotice({context:`${t.name}快捷方式创建成功!`})}}const se=new Uint8Array(0),Ke=new TextEncoder,ae=new TextDecoder;function Du(...r){let e=0;for(let n=0;n<r.length;n++)e+=r[n].length;const t=new Uint8Array(e);let s=0;for(let n=0;n<r.length;n++)t.set(r[n],s),s+=r[n].length;return t}function jt(...r){const e=[];for(let t=0;t<r.length;t++)e.push(Ke.encode(r[t]));return e.length===0?se:e.length===1?e[0]:Du(...e)}function li(r){return!r||r.length===0?"":ae.decode(r)}const hi="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",fi=36,qu=0xcfd41b9100000,di=33,Bu=333,pi=12+10;function Hu(r){for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*255)}function Ju(r){var e;(e=globalThis==null?void 0:globalThis.crypto)!=null&&e.getRandomValues?globalThis.crypto.getRandomValues(r):Hu(r)}class zu{constructor(){c(this,"buf");c(this,"seq");c(this,"inc");this.buf=new Uint8Array(pi),this.init()}init(){this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(Math.random()*qu),this.inc=Math.floor(Math.random()*(Bu-di)+di)}setPre(){const e=new Uint8Array(12);Ju(e);for(let t=0;t<12;t++){const s=e[t]%36;this.buf[t]=hi.charCodeAt(s)}}fillSeq(){let e=this.seq;for(let t=pi-1;t>=12;t--)this.buf[t]=hi.charCodeAt(e%fi),e=Math.floor(e/fi)}next(){return this.seq+=this.inc,this.seq>0xcfd41b9100000&&(this.setPre(),this.initSeqAndInc()),this.fillSeq(),String.fromCharCode.apply(String,this.buf)}reset(){this.init()}}const Ht=new zu;var Re;(function(r){r.Disconnect="disconnect",r.Reconnect="reconnect",r.Update="update",r.LDM="ldm",r.Error="error"})(Re||(Re={}));var ct;(function(r){r.Reconnecting="reconnecting",r.PingTimer="pingTimer",r.StaleConnection="staleConnection",r.ClientInitiatedReconnect="client initiated reconnect"})(ct||(ct={}));var P;(function(r){r.ApiError="BAD API",r.BadAuthentication="BAD_AUTHENTICATION",r.BadCreds="BAD_CREDS",r.BadHeader="BAD_HEADER",r.BadJson="BAD_JSON",r.BadPayload="BAD_PAYLOAD",r.BadSubject="BAD_SUBJECT",r.Cancelled="CANCELLED",r.ConnectionClosed="CONNECTION_CLOSED",r.ConnectionDraining="CONNECTION_DRAINING",r.ConnectionRefused="CONNECTION_REFUSED",r.ConnectionTimeout="CONNECTION_TIMEOUT",r.Disconnect="DISCONNECT",r.InvalidOption="INVALID_OPTION",r.InvalidPayload="INVALID_PAYLOAD",r.MaxPayloadExceeded="MAX_PAYLOAD_EXCEEDED",r.NoResponders="503",r.NotFunction="NOT_FUNC",r.RequestError="REQUEST_ERROR",r.ServerOptionNotAvailable="SERVER_OPT_NA",r.SubClosed="SUB_CLOSED",r.SubDraining="SUB_DRAINING",r.Timeout="TIMEOUT",r.Tls="TLS",r.Unknown="UNKNOWN_ERROR",r.WssRequired="WSS_REQUIRED",r.JetStreamInvalidAck="JESTREAM_INVALID_ACK",r.JetStream404NoMessages="404",r.JetStream408RequestTimeout="408",r.JetStream409MaxAckPendingExceeded="409",r.JetStream409="409",r.JetStreamNotEnabled="503",r.JetStreamIdleHeartBeat="IDLE_HEARTBEAT",r.AuthorizationViolation="AUTHORIZATION_VIOLATION",r.AuthenticationExpired="AUTHENTICATION_EXPIRED",r.ProtocolError="NATS_PROTOCOL_ERR",r.PermissionsViolation="PERMISSIONS_VIOLATION",r.AuthenticationTimeout="AUTHENTICATION_TIMEOUT"})(P||(P={}));function Gu(r){return typeof r.code=="string"}class vo{constructor(){c(this,"messages");this.messages=new Map,this.messages.set(P.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(P.BadJson,"Bad JSON"),this.messages.set(P.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return Vu.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}const Vu=new vo;class j extends Error{constructor(t,s,n){super(t);c(this,"name");c(this,"message");c(this,"code");c(this,"permissionContext");c(this,"chainedError");c(this,"api_error");this.name="NatsError",this.message=t,this.code=s,this.chainedError=n}static errorForCode(t,s){const n=vo.getMessage(t);return new j(n,t,s)}isAuthError(){return this.code===P.AuthenticationExpired||this.code===P.AuthorizationViolation}isAuthTimeout(){return this.code===P.AuthenticationTimeout}isPermissionError(){return this.code===P.PermissionsViolation}isProtocolError(){return this.code===P.ProtocolError}isJetStreamError(){return this.api_error!==void 0}jsError(){return this.api_error?this.api_error:null}}var oe;(function(r){r[r.Exact=0]="Exact",r[r.CanonicalMIME=1]="CanonicalMIME",r[r.IgnoreCase=2]="IgnoreCase"})(oe||(oe={}));var Se;(function(r){r.Timer="timer",r.Count="count",r.JitterTimer="jitterTimer",r.SentinelMsg="sentinelMsg"})(Se||(Se={}));var It;(function(r){r.STATS="io.nats.micro.v1.stats_response",r.INFO="io.nats.micro.v1.info_response",r.PING="io.nats.micro.v1.ping_response"})(It||(It={}));const yr="Nats-Service-Error",wr="Nats-Service-Error-Code";class xr extends Error{constructor(t,s){super(s);c(this,"code");this.code=t}static isServiceError(t){return xr.toServiceError(t)!==null}static toServiceError(t){var n,i;const s=((n=t==null?void 0:t.headers)==null?void 0:n.get(wr))||"";if(s!==""){const o=parseInt(s)||400,a=((i=t==null?void 0:t.headers)==null?void 0:i.get(yr))||"";return new xr(o,a.length?a:s)}return null}}function Te(r=""){if(r=r||"_INBOX",typeof r!="string")throw new Error("prefix must be a string");return r.split(".").forEach(e=>{if(e==="*"||e===">")throw new Error(`inbox prefixes cannot have wildcards '${r}'`)}),`${r}.${Ht.next()}`}const js="127.0.0.1";var De;(function(r){r.PING="PING",r.STATS="STATS",r.INFO="INFO"})(De||(De={}));function Mr(r,...e){for(let t=0;t<e.length;t++){const s=e[t];Object.keys(s).forEach(function(n){r[n]=s[n]})}return r}function or(r){const e="␍",t="␊";return ae.decode(r).replace(/\n/g,t).replace(/\r/g,e)}function dt(r,e=!0){const t=e?j.errorForCode(P.Timeout):null;let s,n;const i=new Promise((o,a)=>{s={cancel:()=>{n&&clearTimeout(n)}},n=setTimeout(()=>{a(t===null?j.errorForCode(P.Timeout):t)},r)});return Object.assign(i,s)}function Jt(r=0){return new Promise(e=>{setTimeout(()=>{e()},r)})}function B(){let r={};const e=new Promise((t,s)=>{r={resolve:t,reject:s}});return Object.assign(e,r)}function So(r){for(let e=r.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}return r}function Wu(r){return r===0?0:Math.floor(r/2+Math.random()*r)}function Eo(r=[0,250,250,500,500,3e3,5e3]){Array.isArray(r)||(r=[0,250,250,500,500,3e3,5e3]);const e=r.length-1;return{backoff(t){return Wu(t>e?r[e]:r[t])}}}class pt{constructor(){c(this,"buffers");c(this,"byteLength");this.buffers=[],this.byteLength=0}static concat(...e){let t=0;for(let i=0;i<e.length;i++)t+=e[i].length;const s=new Uint8Array(t);let n=0;for(let i=0;i<e.length;i++)s.set(e[i],n),n+=e[i].length;return s}static fromAscii(e){return e||(e=""),Ke.encode(e)}static toAscii(e){return ae.decode(e)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){const e=new Uint8Array(this.byteLength);let t=0;for(let s=0;s<this.buffers.length;s++)e.set(this.buffers[s],t),t+=this.buffers[s].length;this.buffers.length=0,this.buffers.push(e)}}shift(){if(this.buffers.length){const e=this.buffers.shift();if(e)return this.byteLength-=e.length,e}return new Uint8Array(0)}drain(e){if(this.buffers.length){this.pack();const t=this.buffers.pop();if(t){const s=this.byteLength;(e===void 0||e>s)&&(e=s);const n=t.subarray(0,e);return s>e&&this.buffers.push(t.subarray(e)),this.byteLength=s-e,n}}return new Uint8Array(0)}fill(e,...t){e&&(this.buffers.push(e),this.byteLength+=e.length);for(let s=0;s<t.length;s++)t[s]&&t[s].length&&(this.buffers.push(t[s]),this.byteLength+=t[s].length)}peek(){return this.buffers.length?(this.pack(),this.buffers[0]):new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}let ce;function Yu(r){ce=r}function Ao(){return ce!==void 0&&ce.defaultPort!==void 0?ce.defaultPort:4222}function ms(){return ce!==void 0&&ce.urlParseFn?ce.urlParseFn:void 0}function Ku(){if(!ce||typeof ce.factory!="function")throw new Error("transport fn is not set");return ce.factory()}function Po(){return ce!==void 0&&ce.dnsResolveFn?ce.dnsResolveFn:void 0}const pr=`\r
- `,vr=pt.fromAscii(pr),Xu=new Uint8Array(vr)[0],Zu=new Uint8Array(vr)[1];function Qu(r){for(let e=0;e<r.length;e++){const t=e+1;if(r.byteLength>t&&r[e]===Xu&&r[t]===Zu)return t+1}return 0}function el(r){const e=Qu(r);if(e>0){const s=new Uint8Array(r).slice(0,e);return ae.decode(s)}return""}const tl=4,Oo=48,rl=65,sl=97;function nl(r,e,t,s){const n=new Uint8Array(16);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((o,a)=>{n[a]=o}),n[12]=r,n[13]=e,n[14]=t,n[15]=s,n}function Is(r){return il(r)!==void 0}function il(r){for(let e=0;e<r.length;e++)switch(r[e]){case".":return Co(r);case":":return ol(r)}}function Co(r){const e=new Uint8Array(4);for(let t=0;t<4;t++){if(r.length===0)return;if(t>0){if(r[0]!==".")return;r=r.substring(1)}const{n:s,c:n,ok:i}=al(r);if(!i||s>255)return;r=r.substring(n),e[t]=s}return nl(e[0],e[1],e[2],e[3])}function ol(r){const e=new Uint8Array(16);let t=-1;if(r.length>=2&&r[0]===":"&&r[1]===":"&&(t=0,r=r.substring(2),r.length===0))return e;let s=0;for(;s<16;){const{n,c:i,ok:o}=cl(r);if(!o||n>65535)return;if(i<r.length&&r[i]==="."){if(t<0&&s!=16-4||s+4>16)return;const a=Co(r);if(a===void 0)return;e[s]=a[12],e[s+1]=a[13],e[s+2]=a[14],e[s+3]=a[15],r="",s+=tl;break}if(e[s]=n>>8,e[s+1]=n,s+=2,r=r.substring(i),r.length===0)break;if(r[0]!==":"||r.length==1)return;if(r=r.substring(1),r[0]===":"){if(t>=0)return;if(t=s,r=r.substring(1),r.length===0)break}}if(r.length===0){if(s<16){if(t<0)return;const n=16-s;for(let i=s-1;i>=t;i--)e[i+n]=e[i];for(let i=t+n-1;i>=t;i--)e[i]=0}else if(t>=0)return;return e}}function al(r){let e=0,t=0;for(e=0;e<r.length&&48<=r.charCodeAt(e)&&r.charCodeAt(e)<=57;e++)if(t=t*10+(r.charCodeAt(e)-Oo),t>=16777215)return{n:16777215,c:e,ok:!1};return e===0?{n:0,c:0,ok:!1}:{n:t,c:e,ok:!0}}function cl(r){let e=0,t=0;for(t=0;t<r.length;t++){if(48<=r.charCodeAt(t)&&r.charCodeAt(t)<=57)e*=16,e+=r.charCodeAt(t)-Oo;else if(97<=r.charCodeAt(t)&&r.charCodeAt(t)<=102)e*=16,e+=r.charCodeAt(t)-sl+10;else if(65<=r.charCodeAt(t)&&r.charCodeAt(t)<=70)e*=16,e+=r.charCodeAt(t)-rl+10;else break;if(e>=16777215)return{n:0,c:t,ok:!1}}return t===0?{n:0,c:t,ok:!1}:{n:e,c:t,ok:!0}}function ul(r){return r.indexOf(".")!==-1?!0:r.indexOf("[")!==-1||r.indexOf("::")!==-1?!1:r.split(":").length<=2}function Ts(r){return!ul(r)}function ll(r){const e="::FFFF:",t=r.toUpperCase().indexOf(e);if(t!==-1&&r.indexOf(".")!==-1){let s=r.substring(t+e.length);return s=s.replace("[",""),s.replace("]","")}return r}function hl(r){r=r.trim(),r.match(/^(.*:\/\/)(.*)/m)&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2")),r=ll(r),Ts(r)&&r.indexOf("[")===-1&&(r=`[${r}]`);const e=Ts(r)?r.match(/(]:)(\d+)/):r.match(/(:)(\d+)/),t=e&&e.length===3&&e[1]&&e[2]?parseInt(e[2]):4222,s=t===80?"https":"http",n=new URL(`${s}://${r}`);n.port=`${t}`;let i=n.hostname;return i.charAt(0)==="["&&(i=i.substring(1,i.length-1)),{listen:n.host,hostname:i,port:t}}class Tt{constructor(e,t=!1){c(this,"src");c(this,"listen");c(this,"hostname");c(this,"port");c(this,"didConnect");c(this,"reconnects");c(this,"lastConnect");c(this,"gossiped");c(this,"tlsName");c(this,"resolves");this.src=e,this.tlsName="";const s=hl(e);this.listen=s.listen,this.hostname=s.hostname,this.port=s.port,this.didConnect=!1,this.reconnects=0,this.lastConnect=0,this.gossiped=t}toString(){return this.listen}async resolve(e){if(!e.fn)return[this];const t=[];if(Is(this.hostname))return[this];{const s=await e.fn(this.hostname);e.debug&&console.log(`resolve ${this.hostname} = ${s.join(",")}`);for(const n of s){const i=this.port===80?"https":"http",o=new URL(`${i}://${Ts(n)?"["+n+"]":n}`);o.port=`${this.port}`;const a=new Tt(o.host,!1);a.tlsName=this.hostname,t.push(a)}}return e.randomize&&So(t),this.resolves=t,t}}class fl{constructor(e=[],t={}){c(this,"firstSelect");c(this,"servers");c(this,"currentServer");c(this,"tlsName");c(this,"randomize");this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=t.randomize||!1;const s=ms();e&&(e.forEach(n=>{n=s?s(n):n,this.servers.push(new Tt(n))}),this.randomize&&(this.servers=So(this.servers))),this.servers.length===0&&this.addServer(`${js}:${Ao()}`,!1),this.currentServer=this.servers[0]}clear(){this.servers.length=0}updateTLSName(){const e=this.getCurrentServer();Is(e.hostname)||(this.tlsName=e.hostname,this.servers.forEach(t=>{t.gossiped&&(t.tlsName=this.tlsName)}))}getCurrentServer(){return this.currentServer}addServer(e,t=!1){const s=ms();e=s?s(e):e;const n=new Tt(e,t);Is(n.hostname)&&(n.tlsName=this.tlsName),this.servers.push(n)}selectServer(){if(this.firstSelect)return this.firstSelect=!1,this.currentServer;const e=this.servers.shift();return e&&(this.servers.push(e),this.currentServer=e),e}removeCurrentServer(){this.removeServer(this.currentServer)}removeServer(e){if(e){const t=this.servers.indexOf(e);this.servers.splice(t,1)}}length(){return this.servers.length}next(){return this.servers.length?this.servers[0]:void 0}getServers(){return this.servers}update(e){const t=[];let s=[];const n=ms(),i=new Map;e.connect_urls&&e.connect_urls.length>0&&e.connect_urls.forEach(a=>{a=n?n(a):a;const u=new Tt(a,!0);i.set(a,u)});const o=[];return this.servers.forEach((a,u)=>{const h=a.listen;a.gossiped&&this.currentServer.listen!==h&&i.get(h)===void 0&&o.push(u),i.delete(h)}),o.reverse(),o.forEach(a=>{const u=this.servers.splice(a,1);s=s.concat(u[0].listen)}),i.forEach((a,u)=>{this.servers.push(a),t.push(u)}),{added:t,deleted:s}}}class Y{constructor(){c(this,"inflight");c(this,"processed");c(this,"received");c(this,"noIterator");c(this,"iterClosed");c(this,"done");c(this,"signal");c(this,"yields");c(this,"filtered");c(this,"pendingFiltered");c(this,"ingestionFilterFn");c(this,"protocolFilterFn");c(this,"dispatchedFn");c(this,"ctx");c(this,"_data");c(this,"err");c(this,"time");c(this,"yielding");this.inflight=0,this.filtered=0,this.pendingFiltered=0,this.processed=0,this.received=0,this.noIterator=!1,this.done=!1,this.signal=B(),this.yields=[],this.iterClosed=B(),this.time=0,this.yielding=!1}[Symbol.asyncIterator](){return this.iterate()}push(e){if(this.done)return;if(typeof e=="function"){this.yields.push(e),this.signal.resolve();return}const{ingest:t,protocol:s}=this.ingestionFilterFn?this.ingestionFilterFn(e,this.ctx||this):{ingest:!0,protocol:!1};t&&(s&&(this.filtered++,this.pendingFiltered++),this.yields.push(e),this.signal.resolve())}async*iterate(){if(this.noIterator)throw new j("unsupported iterator",P.ApiError);if(this.yielding)throw new j("already yielding",P.ApiError);this.yielding=!0;try{for(;;){if(this.yields.length===0&&await this.signal,this.err)throw this.err;const e=this.yields;this.inflight=e.length,this.yields=[];for(let t=0;t<e.length;t++){if(typeof e[t]=="function"){const n=e[t];try{n()}catch(i){throw i}if(this.err)throw this.err;continue}if(this.protocolFilterFn?this.protocolFilterFn(e[t]):!0){this.processed++;const n=Date.now();yield e[t],this.time=Date.now()-n,this.dispatchedFn&&e[t]&&this.dispatchedFn(e[t])}else this.pendingFiltered--;this.inflight--}if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=B())}}finally{this.stop()}}stop(e){this.done||(this.err=e,this.done=!0,this.signal.resolve(),this.iterClosed.resolve())}getProcessed(){return this.noIterator?this.received:this.processed}getPending(){return this.yields.length+this.inflight-this.pendingFiltered}getReceived(){return this.received-this.filtered}}function mi(r){let s=!0;const n=new Array(r.length);for(let i=0;i<r.length;i++){let o=r.charCodeAt(i);if(o===58||o<33||o>126)throw new j(`'${r[i]}' is not a valid character for a header key`,P.BadHeader);s&&97<=o&&o<=122?o-=32:!s&&65<=o&&o<=90&&(o+=32),n[i]=o,s=o==45}return String.fromCharCode(...n)}function Ne(r=0,e=""){if(r===0&&e!==""||r>0&&e==="")throw new Error("setting status requires both code and description");return new qe(r,e)}const bs="NATS/1.0";class qe{constructor(e=0,t=""){c(this,"_code");c(this,"headers");c(this,"_description");this._code=e,this._description=t,this.headers=new Map}[Symbol.iterator](){return this.headers.entries()}size(){return this.headers.size}equals(e){if(e&&this.headers.size===e.headers.size&&this._code===e._code){for(const[t,s]of this.headers){const n=e.values(t);if(s.length!==n.length)return!1;const i=[...s].sort(),o=[...n].sort();for(let a=0;a<i.length;a++)if(i[a]!==o[a])return!1}return!0}return!1}static decode(e){const t=new qe,n=ae.decode(e).split(`\r
- `),i=n[0];if(i!==bs){let o=i.replace(bs,"").trim();if(o.length>0){t._code=parseInt(o,10),isNaN(t._code)&&(t._code=0);const a=t._code.toString();o=o.replace(a,""),t._description=o.trim()}}return n.length>=1&&n.slice(1).map(o=>{if(o){const a=o.indexOf(":");if(a>-1){const u=o.slice(0,a),h=o.slice(a+1).trim();t.append(u,h)}}}),t}toString(){if(this.headers.size===0&&this._code===0)return"";let e=bs;this._code>0&&this._description!==""&&(e+=` ${this._code} ${this._description}`);for(const[t,s]of this.headers)for(let n=0;n<s.length;n++)e=`${e}\r
- ${t}: ${s[n]}`;return`${e}\r
- \r
- `}encode(){return Ke.encode(this.toString())}static validHeaderValue(e){if(/[\r\n]/.test(e))throw new j("invalid header value - \\r and \\n are not allowed.",P.BadHeader);return e.trim()}keys(){const e=[];for(const t of this.headers.keys())e.push(t);return e}findKeys(e,t=oe.Exact){const s=this.keys();switch(t){case oe.Exact:return s.filter(n=>n===e);case oe.CanonicalMIME:return e=mi(e),s.filter(n=>n===e);default:{const n=e.toLowerCase();return s.filter(i=>n===i.toLowerCase())}}}get(e,t=oe.Exact){const s=this.findKeys(e,t);if(s.length){const n=this.headers.get(s[0]);if(n)return Array.isArray(n)?n[0]:n}return""}last(e,t=oe.Exact){const s=this.findKeys(e,t);if(s.length){const n=this.headers.get(s[0]);if(n)return Array.isArray(n)?n[n.length-1]:n}return""}has(e,t=oe.Exact){return this.findKeys(e,t).length>0}set(e,t,s=oe.Exact){this.delete(e,s),this.append(e,t,s)}append(e,t,s=oe.Exact){const n=mi(e);s===oe.CanonicalMIME&&(e=n);const i=this.findKeys(e,s);e=i.length>0?i[0]:e;const o=qe.validHeaderValue(t);let a=this.headers.get(e);a||(a=[],this.headers.set(e,a)),a.push(o)}values(e,t=oe.Exact){const s=[];return this.findKeys(e,t).forEach(i=>{const o=this.headers.get(i);o&&s.push(...o)}),s}delete(e,t=oe.Exact){this.findKeys(e,t).forEach(n=>{this.headers.delete(n)})}get hasError(){return this._code>=300}get status(){return`${this._code} ${this._description}`.trim()}toRecord(){const e={};return this.keys().forEach(t=>{e[t]=this.values(t)}),e}get code(){return this._code}get description(){return this._description}static fromRecord(e){const t=new qe;for(const s in e)t.headers.set(s,e[s]);return t}}function Sr(){return{encode(r){return Ke.encode(r)},decode(r){return ae.decode(r)}}}function ye(r){return{encode(e){try{return e===void 0&&(e=null),Ke.encode(JSON.stringify(e))}catch(t){throw j.errorForCode(P.BadJson,t)}},decode(e){try{return JSON.parse(ae.decode(e),r)}catch(t){throw j.errorForCode(P.BadJson,t)}}}}function ko(r){var e;return r&&r.data.length===0&&((e=r.headers)==null?void 0:e.code)===503?j.errorForCode(P.NoResponders):null}class Zs{constructor(e,t,s){c(this,"_headers");c(this,"_msg");c(this,"_rdata");c(this,"_reply");c(this,"_subject");c(this,"publisher");this._msg=e,this._rdata=t,this.publisher=s}get subject(){return this._subject?this._subject:(this._subject=ae.decode(this._msg.subject),this._subject)}get reply(){return this._reply?this._reply:(this._reply=ae.decode(this._msg.reply),this._reply)}get sid(){return this._msg.sid}get headers(){if(this._msg.hdr>-1&&!this._headers){const e=this._rdata.subarray(0,this._msg.hdr);this._headers=qe.decode(e)}return this._headers}get data(){return this._rdata?this._msg.hdr>-1?this._rdata.subarray(this._msg.hdr):this._rdata:new Uint8Array(0)}respond(e=se,t){return this.reply?(this.publisher.publish(this.reply,e,t),!0):!1}size(){var n;const e=this._msg.subject.length,t=((n=this._msg.reply)==null?void 0:n.length)||0,s=this._msg.size===-1?0:this._msg.size;return e+t+s}json(e){return ye(e).decode(this.data)}string(){return ae.decode(this.data)}}c(Zs,"jc");class dl{constructor(){c(this,"baseInbox");c(this,"reqs");this.reqs=new Map}size(){return this.reqs.size}init(e){return this.baseInbox=`${Te(e)}.`,this.baseInbox}add(e){isNaN(e.received)||(e.received=0),this.reqs.set(e.token,e)}get(e){return this.reqs.get(e)}cancel(e){this.reqs.delete(e.token)}getToken(e){const t=e.subject||"";return t.indexOf(this.baseInbox)===0?t.substring(this.baseInbox.length):null}all(){return Array.from(this.reqs.values())}handleError(e,t){if(t&&t.permissionContext){if(e)return this.all().forEach(n=>{n.resolver(t,{})}),!0;const s=t.permissionContext;if(s.operation==="publish"){const n=this.all().find(i=>i.requestSubject===s.subject);if(n)return n.resolver(t,{}),!0}}return!1}dispatcher(){return(e,t)=>{const s=this.getToken(t);if(s){const n=this.get(s);n&&(e===null&&t.headers&&(e=ko(t)),n.resolver(e,t))}}}close(){const e=j.errorForCode(P.Timeout);this.reqs.forEach(t=>{t.resolver(e,{})})}}class pl{constructor(e,t,s){c(this,"ph");c(this,"interval");c(this,"maxOut");c(this,"timer");c(this,"pendings");this.ph=e,this.interval=t,this.maxOut=s,this.pendings=[]}start(){this.cancel(),this._schedule()}cancel(e){this.timer&&(clearTimeout(this.timer),this.timer=void 0),this._reset(),e&&this.ph.disconnect()}_schedule(){this.timer=setTimeout(()=>{if(this.ph.dispatchStatus({type:ct.PingTimer,data:`${this.pendings.length+1}`}),this.pendings.length===this.maxOut){this.cancel(!0);return}const e=B();this.ph.flush(e).then(()=>{this._reset()}).catch(()=>{this.cancel()}),this.pendings.push(e),this._schedule()},this.interval)}_reset(){this.pendings=this.pendings.filter(e=>(e.resolve(),!1))}}class ml extends Error{constructor(e){super(e),this.name="AssertionError"}}function bl(r,e="Assertion failed."){if(!r)throw new ml(e)}const bi=32*1024,gs=2**32-2;function ar(r,e,t=0){const s=e.byteLength-t;return r.byteLength>s&&(r=r.subarray(0,s)),e.set(r,t),r.byteLength}class _s{constructor(e){c(this,"_buf");c(this,"_off");if(this._off=0,e==null){this._buf=new Uint8Array(0);return}this._buf=new Uint8Array(e)}bytes(e={copy:!0}){return e.copy===!1?this._buf.subarray(this._off):this._buf.slice(this._off)}empty(){return this._buf.byteLength<=this._off}get length(){return this._buf.byteLength-this._off}get capacity(){return this._buf.buffer.byteLength}truncate(e){if(e===0){this.reset();return}if(e<0||e>this.length)throw Error("bytes.Buffer: truncation out of range");this._reslice(this._off+e)}reset(){this._reslice(0),this._off=0}_tryGrowByReslice(e){const t=this._buf.byteLength;return e<=this.capacity-t?(this._reslice(t+e),t):-1}_reslice(e){bl(e<=this._buf.buffer.byteLength),this._buf=new Uint8Array(this._buf.buffer,0,e)}readByte(){const e=new Uint8Array(1);return this.read(e)?e[0]:null}read(e){if(this.empty())return this.reset(),e.byteLength===0?0:null;const t=ar(this._buf.subarray(this._off),e);return this._off+=t,t}writeByte(e){return this.write(Uint8Array.of(e))}writeString(e){return this.write(Ke.encode(e))}write(e){const t=this._grow(e.byteLength);return ar(e,this._buf,t)}_grow(e){const t=this.length;t===0&&this._off!==0&&this.reset();const s=this._tryGrowByReslice(e);if(s>=0)return s;const n=this.capacity;if(e<=Math.floor(n/2)-t)ar(this._buf.subarray(this._off),this._buf);else{if(n+e>gs)throw new Error("The buffer cannot be grown beyond the maximum size.");{const i=new Uint8Array(Math.min(2*n+e,gs));ar(this._buf.subarray(this._off),i),this._buf=i}}return this._off=0,this._reslice(Math.min(t+e,gs)),t}grow(e){if(e<0)throw Error("Buffer._grow: negative count");const t=this._grow(e);this._reslice(t)}readFrom(e){let t=0;const s=new Uint8Array(bi);for(;;){const n=this.capacity-this.length<bi,i=n?s:new Uint8Array(this._buf.buffer,this.length),o=e.read(i);if(o===null)return t;n?this.write(i.subarray(0,o)):this._reslice(this.length+o),t+=o}}}var Z;(function(r){r[r.OK=0]="OK",r[r.ERR=1]="ERR",r[r.MSG=2]="MSG",r[r.INFO=3]="INFO",r[r.PING=4]="PING",r[r.PONG=5]="PONG"})(Z||(Z={}));function gi(){const r={};return r.sid=-1,r.hdr=-1,r.size=-1,r}const gl=48;class _i{constructor(e){c(this,"dispatcher");c(this,"state");c(this,"as");c(this,"drop");c(this,"hdr");c(this,"ma");c(this,"argBuf");c(this,"msgBuf");this.dispatcher=e,this.state=O.OP_START,this.as=0,this.drop=0,this.hdr=0}parse(e){let t;for(t=0;t<e.length;t++){const s=e[t];switch(this.state){case O.OP_START:switch(s){case C.M:case C.m:this.state=O.OP_M,this.hdr=-1,this.ma=gi();break;case C.H:case C.h:this.state=O.OP_H,this.hdr=0,this.ma=gi();break;case C.P:case C.p:this.state=O.OP_P;break;case C.PLUS:this.state=O.OP_PLUS;break;case C.MINUS:this.state=O.OP_MINUS;break;case C.I:case C.i:this.state=O.OP_I;break;default:throw this.fail(e.subarray(t))}break;case O.OP_H:switch(s){case C.M:case C.m:this.state=O.OP_M;break;default:throw this.fail(e.subarray(t))}break;case O.OP_M:switch(s){case C.S:case C.s:this.state=O.OP_MS;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MS:switch(s){case C.G:case C.g:this.state=O.OP_MSG;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MSG:switch(s){case C.SPACE:case C.TAB:this.state=O.OP_MSG_SPC;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MSG_SPC:switch(s){case C.SPACE:case C.TAB:continue;default:this.state=O.MSG_ARG,this.as=t}break;case O.MSG_ARG:switch(s){case C.CR:this.drop=1;break;case C.NL:{const n=this.argBuf?this.argBuf.bytes():e.subarray(this.as,t-this.drop);this.processMsgArgs(n),this.drop=0,this.as=t+1,this.state=O.MSG_PAYLOAD,t=this.as+this.ma.size-1;break}default:this.argBuf&&this.argBuf.writeByte(s)}break;case O.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){const n=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:Z.MSG,msg:this.ma,data:n}),this.argBuf=void 0,this.msgBuf=void 0,this.state=O.MSG_END}else{let n=this.ma.size-this.msgBuf.length;const i=e.length-t;i<n&&(n=i),n>0?(this.msgBuf.write(e.subarray(t,t+n)),t=t+n-1):this.msgBuf.writeByte(s)}else t-this.as>=this.ma.size&&(this.dispatcher.push({kind:Z.MSG,msg:this.ma,data:e.subarray(this.as,t)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=O.MSG_END);break;case O.MSG_END:switch(s){case C.NL:this.drop=0,this.as=t+1,this.state=O.OP_START;break;default:continue}break;case O.OP_PLUS:switch(s){case C.O:case C.o:this.state=O.OP_PLUS_O;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PLUS_O:switch(s){case C.K:case C.k:this.state=O.OP_PLUS_OK;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PLUS_OK:switch(s){case C.NL:this.dispatcher.push({kind:Z.OK}),this.drop=0,this.state=O.OP_START;break}break;case O.OP_MINUS:switch(s){case C.E:case C.e:this.state=O.OP_MINUS_E;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MINUS_E:switch(s){case C.R:case C.r:this.state=O.OP_MINUS_ER;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MINUS_ER:switch(s){case C.R:case C.r:this.state=O.OP_MINUS_ERR;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MINUS_ERR:switch(s){case C.SPACE:case C.TAB:this.state=O.OP_MINUS_ERR_SPC;break;default:throw this.fail(e.subarray(t))}break;case O.OP_MINUS_ERR_SPC:switch(s){case C.SPACE:case C.TAB:continue;default:this.state=O.MINUS_ERR_ARG,this.as=t}break;case O.MINUS_ERR_ARG:switch(s){case C.CR:this.drop=1;break;case C.NL:{let n;this.argBuf?(n=this.argBuf.bytes(),this.argBuf=void 0):n=e.subarray(this.as,t-this.drop),this.dispatcher.push({kind:Z.ERR,data:n}),this.drop=0,this.as=t+1,this.state=O.OP_START;break}default:this.argBuf&&this.argBuf.write(Uint8Array.of(s))}break;case O.OP_P:switch(s){case C.I:case C.i:this.state=O.OP_PI;break;case C.O:case C.o:this.state=O.OP_PO;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PO:switch(s){case C.N:case C.n:this.state=O.OP_PON;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PON:switch(s){case C.G:case C.g:this.state=O.OP_PONG;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PONG:switch(s){case C.NL:this.dispatcher.push({kind:Z.PONG}),this.drop=0,this.state=O.OP_START;break}break;case O.OP_PI:switch(s){case C.N:case C.n:this.state=O.OP_PIN;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PIN:switch(s){case C.G:case C.g:this.state=O.OP_PING;break;default:throw this.fail(e.subarray(t))}break;case O.OP_PING:switch(s){case C.NL:this.dispatcher.push({kind:Z.PING}),this.drop=0,this.state=O.OP_START;break}break;case O.OP_I:switch(s){case C.N:case C.n:this.state=O.OP_IN;break;default:throw this.fail(e.subarray(t))}break;case O.OP_IN:switch(s){case C.F:case C.f:this.state=O.OP_INF;break;default:throw this.fail(e.subarray(t))}break;case O.OP_INF:switch(s){case C.O:case C.o:this.state=O.OP_INFO;break;default:throw this.fail(e.subarray(t))}break;case O.OP_INFO:switch(s){case C.SPACE:case C.TAB:this.state=O.OP_INFO_SPC;break;default:throw this.fail(e.subarray(t))}break;case O.OP_INFO_SPC:switch(s){case C.SPACE:case C.TAB:continue;default:this.state=O.INFO_ARG,this.as=t}break;case O.INFO_ARG:switch(s){case C.CR:this.drop=1;break;case C.NL:{let n;this.argBuf?(n=this.argBuf.bytes(),this.argBuf=void 0):n=e.subarray(this.as,t-this.drop),this.dispatcher.push({kind:Z.INFO,data:n}),this.drop=0,this.as=t+1,this.state=O.OP_START;break}default:this.argBuf&&this.argBuf.writeByte(s)}break;default:throw this.fail(e.subarray(t))}}(this.state===O.MSG_ARG||this.state===O.MINUS_ERR_ARG||this.state===O.INFO_ARG)&&!this.argBuf&&(this.argBuf=new _s(e.subarray(this.as,t-this.drop))),this.state===O.MSG_PAYLOAD&&!this.msgBuf&&(this.argBuf||this.cloneMsgArg(),this.msgBuf=new _s(e.subarray(this.as)))}cloneMsgArg(){const e=this.ma.subject.length,t=this.ma.reply?this.ma.reply.length:0,s=new Uint8Array(e+t);s.set(this.ma.subject),this.ma.reply&&s.set(this.ma.reply,e),this.argBuf=new _s(s),this.ma.subject=s.subarray(0,e),this.ma.reply&&(this.ma.reply=s.subarray(e))}processMsgArgs(e){if(this.hdr>=0)return this.processHeaderMsgArgs(e);const t=[];let s=-1;for(let n=0;n<e.length;n++)switch(e[n]){case C.SPACE:case C.TAB:case C.CR:case C.NL:s>=0&&(t.push(e.subarray(s,n)),s=-1);break;default:s<0&&(s=n)}switch(s>=0&&t.push(e.subarray(s)),t.length){case 3:this.ma.subject=t[0],this.ma.sid=this.protoParseInt(t[1]),this.ma.reply=void 0,this.ma.size=this.protoParseInt(t[2]);break;case 4:this.ma.subject=t[0],this.ma.sid=this.protoParseInt(t[1]),this.ma.reply=t[2],this.ma.size=this.protoParseInt(t[3]);break;default:throw this.fail(e,"processMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail(e,"processMsgArgs Bad or Missing Sid Error");if(this.ma.size<0)throw this.fail(e,"processMsgArgs Bad or Missing Size Error")}fail(e,t=""){return t?t=`${t} [${this.state}]`:t=`parse error [${this.state}]`,new Error(`${t}: ${ae.decode(e)}`)}processHeaderMsgArgs(e){const t=[];let s=-1;for(let n=0;n<e.length;n++)switch(e[n]){case C.SPACE:case C.TAB:case C.CR:case C.NL:s>=0&&(t.push(e.subarray(s,n)),s=-1);break;default:s<0&&(s=n)}switch(s>=0&&t.push(e.subarray(s)),t.length){case 4:this.ma.subject=t[0],this.ma.sid=this.protoParseInt(t[1]),this.ma.reply=void 0,this.ma.hdr=this.protoParseInt(t[2]),this.ma.size=this.protoParseInt(t[3]);break;case 5:this.ma.subject=t[0],this.ma.sid=this.protoParseInt(t[1]),this.ma.reply=t[2],this.ma.hdr=this.protoParseInt(t[3]),this.ma.size=this.protoParseInt(t[4]);break;default:throw this.fail(e,"processHeaderMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail(e,"processHeaderMsgArgs Bad or Missing Sid Error");if(this.ma.hdr<0||this.ma.hdr>this.ma.size)throw this.fail(e,"processHeaderMsgArgs Bad or Missing Header Size Error");if(this.ma.size<0)throw this.fail(e,"processHeaderMsgArgs Bad or Missing Size Error")}protoParseInt(e){if(e.length===0)return-1;let t=0;for(let s=0;s<e.length;s++){if(e[s]<48||e[s]>57)return-1;t=t*10+(e[s]-gl)}return t}}var O;(function(r){r[r.OP_START=0]="OP_START",r[r.OP_PLUS=1]="OP_PLUS",r[r.OP_PLUS_O=2]="OP_PLUS_O",r[r.OP_PLUS_OK=3]="OP_PLUS_OK",r[r.OP_MINUS=4]="OP_MINUS",r[r.OP_MINUS_E=5]="OP_MINUS_E",r[r.OP_MINUS_ER=6]="OP_MINUS_ER",r[r.OP_MINUS_ERR=7]="OP_MINUS_ERR",r[r.OP_MINUS_ERR_SPC=8]="OP_MINUS_ERR_SPC",r[r.MINUS_ERR_ARG=9]="MINUS_ERR_ARG",r[r.OP_M=10]="OP_M",r[r.OP_MS=11]="OP_MS",r[r.OP_MSG=12]="OP_MSG",r[r.OP_MSG_SPC=13]="OP_MSG_SPC",r[r.MSG_ARG=14]="MSG_ARG",r[r.MSG_PAYLOAD=15]="MSG_PAYLOAD",r[r.MSG_END=16]="MSG_END",r[r.OP_H=17]="OP_H",r[r.OP_P=18]="OP_P",r[r.OP_PI=19]="OP_PI",r[r.OP_PIN=20]="OP_PIN",r[r.OP_PING=21]="OP_PING",r[r.OP_PO=22]="OP_PO",r[r.OP_PON=23]="OP_PON",r[r.OP_PONG=24]="OP_PONG",r[r.OP_I=25]="OP_I",r[r.OP_IN=26]="OP_IN",r[r.OP_INF=27]="OP_INF",r[r.OP_INFO=28]="OP_INFO",r[r.OP_INFO_SPC=29]="OP_INFO_SPC",r[r.INFO_ARG=30]="INFO_ARG"})(O||(O={}));var C;(function(r){r[r.CR="\r".charCodeAt(0)]="CR",r[r.E="E".charCodeAt(0)]="E",r[r.e="e".charCodeAt(0)]="e",r[r.F="F".charCodeAt(0)]="F",r[r.f="f".charCodeAt(0)]="f",r[r.G="G".charCodeAt(0)]="G",r[r.g="g".charCodeAt(0)]="g",r[r.H="H".charCodeAt(0)]="H",r[r.h="h".charCodeAt(0)]="h",r[r.I="I".charCodeAt(0)]="I",r[r.i="i".charCodeAt(0)]="i",r[r.K="K".charCodeAt(0)]="K",r[r.k="k".charCodeAt(0)]="k",r[r.M="M".charCodeAt(0)]="M",r[r.m="m".charCodeAt(0)]="m",r[r.MINUS="-".charCodeAt(0)]="MINUS",r[r.N="N".charCodeAt(0)]="N",r[r.n="n".charCodeAt(0)]="n",r[r.NL=`
- `.charCodeAt(0)]="NL",r[r.O="O".charCodeAt(0)]="O",r[r.o="o".charCodeAt(0)]="o",r[r.P="P".charCodeAt(0)]="P",r[r.p="p".charCodeAt(0)]="p",r[r.PLUS="+".charCodeAt(0)]="PLUS",r[r.R="R".charCodeAt(0)]="R",r[r.r="r".charCodeAt(0)]="r",r[r.S="S".charCodeAt(0)]="S",r[r.s="s".charCodeAt(0)]="s",r[r.SPACE=" ".charCodeAt(0)]="SPACE",r[r.TAB=" ".charCodeAt(0)]="TAB"})(C||(C={}));function We(r=""){const e=r.match(/(\d+).(\d+).(\d+)/);if(e)return{major:parseInt(e[1]),minor:parseInt(e[2]),micro:parseInt(e[3])};throw new Error(`'${r}' is not a semver value`)}function Ns(r,e){return r.major<e.major?-1:r.major>e.major?1:r.minor<e.minor?-1:r.minor>e.minor?1:r.micro<e.micro?-1:r.micro>e.micro?1:0}var L;(function(r){r.JS_KV="js_kv",r.JS_OBJECTSTORE="js_objectstore",r.JS_PULL_MAX_BYTES="js_pull_max_bytes",r.JS_NEW_CONSUMER_CREATE_API="js_new_consumer_create",r.JS_ALLOW_DIRECT="js_allow_direct",r.JS_MULTIPLE_CONSUMER_FILTER="js_multiple_consumer_filter",r.JS_SIMPLIFICATION="js_simplification",r.JS_STREAM_CONSUMER_METADATA="js_stream_consumer_metadata",r.JS_CONSUMER_FILTER_SUBJECTS="js_consumer_filter_subjects",r.JS_STREAM_FIRST_SEQ="js_stream_first_seq",r.JS_STREAM_SUBJECT_TRANSFORM="js_stream_subject_transform",r.JS_STREAM_SOURCE_SUBJECT_TRANSFORM="js_stream_source_subject_transform",r.JS_STREAM_COMPRESSION="js_stream_compression",r.JS_DEFAULT_CONSUMER_LIMITS="js_default_consumer_limits"})(L||(L={}));class _l{constructor(e){c(this,"server");c(this,"features");c(this,"disabled");this.features=new Map,this.disabled=[],this.update(e)}resetDisabled(){this.disabled.length=0,this.update(this.server)}disable(e){this.disabled.push(e),this.update(this.server)}isDisabled(e){return this.disabled.indexOf(e)!==-1}update(e){typeof e=="string"&&(e=We(e)),this.server=e,this.set(L.JS_KV,"2.6.2"),this.set(L.JS_OBJECTSTORE,"2.6.3"),this.set(L.JS_PULL_MAX_BYTES,"2.8.3"),this.set(L.JS_NEW_CONSUMER_CREATE_API,"2.9.0"),this.set(L.JS_ALLOW_DIRECT,"2.9.0"),this.set(L.JS_MULTIPLE_CONSUMER_FILTER,"2.10.0"),this.set(L.JS_SIMPLIFICATION,"2.9.4"),this.set(L.JS_STREAM_CONSUMER_METADATA,"2.10.0"),this.set(L.JS_CONSUMER_FILTER_SUBJECTS,"2.10.0"),this.set(L.JS_STREAM_FIRST_SEQ,"2.10.0"),this.set(L.JS_STREAM_SUBJECT_TRANSFORM,"2.10.0"),this.set(L.JS_STREAM_SOURCE_SUBJECT_TRANSFORM,"2.10.0"),this.set(L.JS_STREAM_COMPRESSION,"2.10.0"),this.set(L.JS_DEFAULT_CONSUMER_LIMITS,"2.10.0"),this.disabled.forEach(t=>{this.features.delete(t)})}set(e,t){this.features.set(e,{min:t,ok:Ns(this.server,We(t))>=0})}get(e){return this.features.get(e)||{min:"unknown",ok:!1}}supports(e){var t;return((t=this.get(e))==null?void 0:t.ok)||!1}require(e){return typeof e=="string"&&(e=We(e)),Ns(this.server,e)>=0}}(function(r){var e=function(l,d){this.hi=l|0,this.lo=d|0},t=function(l){var d,f=new Float64Array(16);if(l)for(d=0;d<l.length;d++)f[d]=l[d];return f},s=function(){throw new Error("no PRNG")},n=new Uint8Array(16),i=new Uint8Array(32);i[0]=9;var o=t(),a=t([1]),u=t([56129,1]),h=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),p=t([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),g=t([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),b=t([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),w=t([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function A(l,d){return l<<d|l>>>32-d}function k(l,d){var f=l[d+3]&255;return f=f<<8|l[d+2]&255,f=f<<8|l[d+1]&255,f<<8|l[d+0]&255}function R(l,d){var f=l[d]<<24|l[d+1]<<16|l[d+2]<<8|l[d+3],m=l[d+4]<<24|l[d+5]<<16|l[d+6]<<8|l[d+7];return new e(f,m)}function U(l,d,f){var m;for(m=0;m<4;m++)l[d+m]=f&255,f>>>=8}function N(l,d,f){l[d]=f.hi>>24&255,l[d+1]=f.hi>>16&255,l[d+2]=f.hi>>8&255,l[d+3]=f.hi&255,l[d+4]=f.lo>>24&255,l[d+5]=f.lo>>16&255,l[d+6]=f.lo>>8&255,l[d+7]=f.lo&255}function M(l,d,f,m,_){var y,S=0;for(y=0;y<_;y++)S|=l[d+y]^f[m+y];return(1&S-1>>>8)-1}function J(l,d,f,m){return M(l,d,f,m,16)}function T(l,d,f,m){return M(l,d,f,m,32)}function Me(l,d,f,m,_){var y=new Uint32Array(16),S=new Uint32Array(16),E=new Uint32Array(16),x=new Uint32Array(4),v,I,F;for(v=0;v<4;v++)S[5*v]=k(m,4*v),S[1+v]=k(f,4*v),S[6+v]=k(d,4*v),S[11+v]=k(f,16+4*v);for(v=0;v<16;v++)E[v]=S[v];for(v=0;v<20;v++){for(I=0;I<4;I++){for(F=0;F<4;F++)x[F]=S[(5*I+4*F)%16];for(x[1]^=A(x[0]+x[3]|0,7),x[2]^=A(x[1]+x[0]|0,9),x[3]^=A(x[2]+x[1]|0,13),x[0]^=A(x[3]+x[2]|0,18),F=0;F<4;F++)y[4*I+(I+F)%4]=x[F]}for(F=0;F<16;F++)S[F]=y[F]}if(_){for(v=0;v<16;v++)S[v]=S[v]+E[v]|0;for(v=0;v<4;v++)S[5*v]=S[5*v]-k(m,4*v)|0,S[6+v]=S[6+v]-k(d,4*v)|0;for(v=0;v<4;v++)U(l,4*v,S[5*v]),U(l,16+4*v,S[6+v])}else for(v=0;v<16;v++)U(l,4*v,S[v]+E[v]|0)}function Xe(l,d,f,m){return Me(l,d,f,m,!1),0}function de(l,d,f,m){return Me(l,d,f,m,!0),0}var ee=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function Ae(l,d,f,m,_,y,S){var E=new Uint8Array(16),x=new Uint8Array(64),v,I;if(!_)return 0;for(I=0;I<16;I++)E[I]=0;for(I=0;I<8;I++)E[I]=y[I];for(;_>=64;){for(Xe(x,E,S,ee),I=0;I<64;I++)l[d+I]=(f?f[m+I]:0)^x[I];for(v=1,I=8;I<16;I++)v=v+(E[I]&255)|0,E[I]=v&255,v>>>=8;_-=64,d+=64,f&&(m+=64)}if(_>0)for(Xe(x,E,S,ee),I=0;I<_;I++)l[d+I]=(f?f[m+I]:0)^x[I];return 0}function Ue(l,d,f,m,_){return Ae(l,d,null,0,f,m,_)}function z(l,d,f,m,_){var y=new Uint8Array(32);return de(y,m,_,ee),Ue(l,d,f,m.subarray(16),y)}function ue(l,d,f,m,_,y,S){var E=new Uint8Array(32);return de(E,y,S,ee),Ae(l,d,f,m,_,y.subarray(16),E)}function X(l,d){var f,m=0;for(f=0;f<17;f++)m=m+(l[f]+d[f]|0)|0,l[f]=m&255,m>>>=8}var $r=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]);function Je(l,d,f,m,_,y){var S,E,x,v,I=new Uint32Array(17),F=new Uint32Array(17),D=new Uint32Array(17),be=new Uint32Array(17),rt=new Uint32Array(17);for(x=0;x<17;x++)F[x]=D[x]=0;for(x=0;x<16;x++)F[x]=y[x];for(F[3]&=15,F[4]&=252,F[7]&=15,F[8]&=252,F[11]&=15,F[12]&=252,F[15]&=15;_>0;){for(x=0;x<17;x++)be[x]=0;for(x=0;x<16&&x<_;++x)be[x]=f[m+x];for(be[x]=1,m+=x,_-=x,X(D,be),E=0;E<17;E++)for(I[E]=0,x=0;x<17;x++)I[E]=I[E]+D[x]*(x<=E?F[E-x]:320*F[E+17-x]|0)|0|0;for(E=0;E<17;E++)D[E]=I[E];for(v=0,x=0;x<16;x++)v=v+D[x]|0,D[x]=v&255,v>>>=8;for(v=v+D[16]|0,D[16]=v&3,v=5*(v>>>2)|0,x=0;x<16;x++)v=v+D[x]|0,D[x]=v&255,v>>>=8;v=v+D[16]|0,D[16]=v}for(x=0;x<17;x++)rt[x]=D[x];for(X(D,$r),S=-(D[16]>>>7)|0,x=0;x<17;x++)D[x]^=S&(rt[x]^D[x]);for(x=0;x<16;x++)be[x]=y[x+16];for(be[16]=0,X(D,be),x=0;x<16;x++)l[d+x]=D[x];return 0}function cn(l,d,f,m,_,y){var S=new Uint8Array(16);return Je(S,0,f,m,_,y),J(l,d,S,0)}function Fr(l,d,f,m,_){var y;if(f<32)return-1;for(ue(l,0,d,0,f,m,_),Je(l,16,l,32,f-32,l),y=0;y<16;y++)l[y]=0;return 0}function Lr(l,d,f,m,_){var y,S=new Uint8Array(32);if(f<32||(z(S,0,32,m,_),cn(d,16,d,32,f-32,S)!==0))return-1;for(ue(l,0,d,0,f,m,_),y=0;y<32;y++)l[y]=0;return 0}function Pe(l,d){var f;for(f=0;f<16;f++)l[f]=d[f]|0}function yt(l){var d,f;for(f=0;f<16;f++)l[f]+=65536,d=Math.floor(l[f]/65536),l[(f+1)*(f<15?1:0)]+=d-1+37*(d-1)*(f===15?1:0),l[f]-=d*65536}function Ze(l,d,f){for(var m,_=~(f-1),y=0;y<16;y++)m=_&(l[y]^d[y]),l[y]^=m,d[y]^=m}function Qe(l,d){var f,m,_,y=t(),S=t();for(f=0;f<16;f++)S[f]=d[f];for(yt(S),yt(S),yt(S),m=0;m<2;m++){for(y[0]=S[0]-65517,f=1;f<15;f++)y[f]=S[f]-65535-(y[f-1]>>16&1),y[f-1]&=65535;y[15]=S[15]-32767-(y[14]>>16&1),_=y[15]>>16&1,y[14]&=65535,Ze(S,y,1-_)}for(f=0;f<16;f++)l[2*f]=S[f]&255,l[2*f+1]=S[f]>>8}function un(l,d){var f=new Uint8Array(32),m=new Uint8Array(32);return Qe(f,l),Qe(m,d),T(f,0,m,0)}function ln(l){var d=new Uint8Array(32);return Qe(d,l),d[0]&1}function Dr(l,d){var f;for(f=0;f<16;f++)l[f]=d[2*f]+(d[2*f+1]<<8);l[15]&=32767}function pe(l,d,f){var m;for(m=0;m<16;m++)l[m]=d[m]+f[m]|0}function me(l,d,f){var m;for(m=0;m<16;m++)l[m]=d[m]-f[m]|0}function $(l,d,f){var m,_,y=new Float64Array(31);for(m=0;m<31;m++)y[m]=0;for(m=0;m<16;m++)for(_=0;_<16;_++)y[m+_]+=d[m]*f[_];for(m=0;m<15;m++)y[m]+=38*y[m+16];for(m=0;m<16;m++)l[m]=y[m];yt(l),yt(l)}function le(l,d){$(l,d,d)}function hn(l,d){var f=t(),m;for(m=0;m<16;m++)f[m]=d[m];for(m=253;m>=0;m--)le(f,f),m!==2&&m!==4&&$(f,f,d);for(m=0;m<16;m++)l[m]=f[m]}function fn(l,d){var f=t(),m;for(m=0;m<16;m++)f[m]=d[m];for(m=250;m>=0;m--)le(f,f),m!==1&&$(f,f,d);for(m=0;m<16;m++)l[m]=f[m]}function Vt(l,d,f){var m=new Uint8Array(32),_=new Float64Array(80),y,S,E=t(),x=t(),v=t(),I=t(),F=t(),D=t();for(S=0;S<31;S++)m[S]=d[S];for(m[31]=d[31]&127|64,m[0]&=248,Dr(_,f),S=0;S<16;S++)x[S]=_[S],I[S]=E[S]=v[S]=0;for(E[0]=I[0]=1,S=254;S>=0;--S)y=m[S>>>3]>>>(S&7)&1,Ze(E,x,y),Ze(v,I,y),pe(F,E,v),me(E,E,v),pe(v,x,I),me(x,x,I),le(I,F),le(D,E),$(E,v,E),$(v,x,F),pe(F,E,v),me(E,E,v),le(x,E),me(v,I,D),$(E,v,u),pe(E,E,I),$(v,v,E),$(E,I,D),$(I,x,_),le(x,F),Ze(E,x,y),Ze(v,I,y);for(S=0;S<16;S++)_[S+16]=E[S],_[S+32]=v[S],_[S+48]=x[S],_[S+64]=I[S];var be=_.subarray(32),rt=_.subarray(16);return hn(be,be),$(rt,rt,be),Qe(l,rt),0}function Wt(l,d){return Vt(l,d,i)}function dn(l,d){return s(d,32),Wt(l,d)}function Yt(l,d,f){var m=new Uint8Array(32);return Vt(m,f,d),de(l,n,m,ee)}var pn=Fr,Go=Lr;function Vo(l,d,f,m,_,y){var S=new Uint8Array(32);return Yt(S,_,y),pn(l,d,f,m,S)}function Wo(l,d,f,m,_,y){var S=new Uint8Array(32);return Yt(S,_,y),Go(l,d,f,m,S)}function wt(){var l=0,d=0,f=0,m=0,_=65535,y,S,E;for(E=0;E<arguments.length;E++)y=arguments[E].lo,S=arguments[E].hi,l+=y&_,d+=y>>>16,f+=S&_,m+=S>>>16;return d+=l>>>16,f+=d>>>16,m+=f>>>16,new e(f&_|m<<16,l&_|d<<16)}function mn(l,d){return new e(l.hi>>>d,l.lo>>>d|l.hi<<32-d)}function Kt(){var l=0,d=0,f;for(f=0;f<arguments.length;f++)l^=arguments[f].lo,d^=arguments[f].hi;return new e(d,l)}function we(l,d){var f,m,_=32-d;return d<32?(f=l.hi>>>d|l.lo<<_,m=l.lo>>>d|l.hi<<_):d<64&&(f=l.lo>>>d|l.hi<<_,m=l.hi>>>d|l.lo<<_),new e(f,m)}function Yo(l,d,f){var m=l.hi&d.hi^~l.hi&f.hi,_=l.lo&d.lo^~l.lo&f.lo;return new e(m,_)}function Ko(l,d,f){var m=l.hi&d.hi^l.hi&f.hi^d.hi&f.hi,_=l.lo&d.lo^l.lo&f.lo^d.lo&f.lo;return new e(m,_)}function Xo(l){return Kt(we(l,28),we(l,34),we(l,39))}function Zo(l){return Kt(we(l,14),we(l,18),we(l,41))}function Qo(l){return Kt(we(l,1),we(l,8),mn(l,7))}function ea(l){return Kt(we(l,19),we(l,61),mn(l,6))}var ta=[new e(1116352408,3609767458),new e(1899447441,602891725),new e(3049323471,3964484399),new e(3921009573,2173295548),new e(961987163,4081628472),new e(1508970993,3053834265),new e(2453635748,2937671579),new e(2870763221,3664609560),new e(3624381080,2734883394),new e(310598401,1164996542),new e(607225278,1323610764),new e(1426881987,3590304994),new e(1925078388,4068182383),new e(2162078206,991336113),new e(2614888103,633803317),new e(3248222580,3479774868),new e(3835390401,2666613458),new e(4022224774,944711139),new e(264347078,2341262773),new e(604807628,2007800933),new e(770255983,1495990901),new e(1249150122,1856431235),new e(1555081692,3175218132),new e(1996064986,2198950837),new e(2554220882,3999719339),new e(2821834349,766784016),new e(2952996808,2566594879),new e(3210313671,3203337956),new e(3336571891,1034457026),new e(3584528711,2466948901),new e(113926993,3758326383),new e(338241895,168717936),new e(666307205,1188179964),new e(773529912,1546045734),new e(1294757372,1522805485),new e(1396182291,2643833823),new e(1695183700,2343527390),new e(1986661051,1014477480),new e(2177026350,1206759142),new e(2456956037,344077627),new e(2730485921,1290863460),new e(2820302411,3158454273),new e(3259730800,3505952657),new e(3345764771,106217008),new e(3516065817,3606008344),new e(3600352804,1432725776),new e(4094571909,1467031594),new e(275423344,851169720),new e(430227734,3100823752),new e(506948616,1363258195),new e(659060556,3750685593),new e(883997877,3785050280),new e(958139571,3318307427),new e(1322822218,3812723403),new e(1537002063,2003034995),new e(1747873779,3602036899),new e(1955562222,1575990012),new e(2024104815,1125592928),new e(2227730452,2716904306),new e(2361852424,442776044),new e(2428436474,593698344),new e(2756734187,3733110249),new e(3204031479,2999351573),new e(3329325298,3815920427),new e(3391569614,3928383900),new e(3515267271,566280711),new e(3940187606,3454069534),new e(4118630271,4000239992),new e(116418474,1914138554),new e(174292421,2731055270),new e(289380356,3203993006),new e(460393269,320620315),new e(685471733,587496836),new e(852142971,1086792851),new e(1017036298,365543100),new e(1126000580,2618297676),new e(1288033470,3409855158),new e(1501505948,4234509866),new e(1607167915,987167468),new e(1816402316,1246189591)];function bn(l,d,f){var m=[],_=[],y=[],S=[],E,x,v;for(x=0;x<8;x++)m[x]=y[x]=R(l,8*x);for(var I=0;f>=128;){for(x=0;x<16;x++)S[x]=R(d,8*x+I);for(x=0;x<80;x++){for(v=0;v<8;v++)_[v]=y[v];for(E=wt(y[7],Zo(y[4]),Yo(y[4],y[5],y[6]),ta[x],S[x%16]),_[7]=wt(E,Xo(y[0]),Ko(y[0],y[1],y[2])),_[3]=wt(_[3],E),v=0;v<8;v++)y[(v+1)%8]=_[v];if(x%16===15)for(v=0;v<16;v++)S[v]=wt(S[v],S[(v+9)%16],Qo(S[(v+1)%16]),ea(S[(v+14)%16]))}for(x=0;x<8;x++)y[x]=wt(y[x],m[x]),m[x]=y[x];I+=128,f-=128}for(x=0;x<8;x++)N(l,8*x,m[x]);return f}var ra=new Uint8Array([106,9,230,103,243,188,201,8,187,103,174,133,132,202,167,59,60,110,243,114,254,148,248,43,165,79,245,58,95,29,54,241,81,14,82,127,173,230,130,209,155,5,104,140,43,62,108,31,31,131,217,171,251,65,189,107,91,224,205,25,19,126,33,121]);function ze(l,d,f){var m=new Uint8Array(64),_=new Uint8Array(256),y,S=f;for(y=0;y<64;y++)m[y]=ra[y];for(bn(m,d,f),f%=128,y=0;y<256;y++)_[y]=0;for(y=0;y<f;y++)_[y]=d[S-f+y];for(_[f]=128,f=256-128*(f<112?1:0),_[f-9]=0,N(_,f-8,new e(S/536870912|0,S<<3)),bn(m,_,f),y=0;y<64;y++)l[y]=m[y];return 0}function Xt(l,d){var f=t(),m=t(),_=t(),y=t(),S=t(),E=t(),x=t(),v=t(),I=t();me(f,l[1],l[0]),me(I,d[1],d[0]),$(f,f,I),pe(m,l[0],l[1]),pe(I,d[0],d[1]),$(m,m,I),$(_,l[3],d[3]),$(_,_,p),$(y,l[2],d[2]),pe(y,y,y),me(S,m,f),me(E,y,_),pe(x,y,_),pe(v,m,f),$(l[0],S,E),$(l[1],v,x),$(l[2],x,E),$(l[3],S,v)}function gn(l,d,f){var m;for(m=0;m<4;m++)Ze(l[m],d[m],f)}function qr(l,d){var f=t(),m=t(),_=t();hn(_,d[2]),$(f,d[0],_),$(m,d[1],_),Qe(l,m),l[31]^=ln(f)<<7}function Br(l,d,f){var m,_;for(Pe(l[0],o),Pe(l[1],a),Pe(l[2],a),Pe(l[3],o),_=255;_>=0;--_)m=f[_/8|0]>>(_&7)&1,gn(l,d,m),Xt(d,l),Xt(l,l),gn(l,d,m)}function Zt(l,d){var f=[t(),t(),t(),t()];Pe(f[0],g),Pe(f[1],b),Pe(f[2],a),$(f[3],g,b),Br(l,f,d)}function Hr(l,d,f){var m=new Uint8Array(64),_=[t(),t(),t(),t()],y;for(f||s(d,32),ze(m,d,32),m[0]&=248,m[31]&=127,m[31]|=64,Zt(_,m),qr(l,_),y=0;y<32;y++)d[y+32]=l[y];return 0}var Qt=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 Jr(l,d){var f,m,_,y;for(m=63;m>=32;--m){for(f=0,_=m-32,y=m-12;_<y;++_)d[_]+=f-16*d[m]*Qt[_-(m-32)],f=Math.floor((d[_]+128)/256),d[_]-=f*256;d[_]+=f,d[m]=0}for(f=0,_=0;_<32;_++)d[_]+=f-(d[31]>>4)*Qt[_],f=d[_]>>8,d[_]&=255;for(_=0;_<32;_++)d[_]-=f*Qt[_];for(m=0;m<32;m++)d[m+1]+=d[m]>>8,l[m]=d[m]&255}function zr(l){var d=new Float64Array(64),f;for(f=0;f<64;f++)d[f]=l[f];for(f=0;f<64;f++)l[f]=0;Jr(l,d)}function _n(l,d,f,m){var _=new Uint8Array(64),y=new Uint8Array(64),S=new Uint8Array(64),E,x,v=new Float64Array(64),I=[t(),t(),t(),t()];ze(_,m,32),_[0]&=248,_[31]&=127,_[31]|=64;var F=f+64;for(E=0;E<f;E++)l[64+E]=d[E];for(E=0;E<32;E++)l[32+E]=_[32+E];for(ze(S,l.subarray(32),f+32),zr(S),Zt(I,S),qr(l,I),E=32;E<64;E++)l[E]=m[E];for(ze(y,l,f+64),zr(y),E=0;E<64;E++)v[E]=0;for(E=0;E<32;E++)v[E]=S[E];for(E=0;E<32;E++)for(x=0;x<32;x++)v[E+x]+=y[E]*_[x];return Jr(l.subarray(32),v),F}function sa(l,d){var f=t(),m=t(),_=t(),y=t(),S=t(),E=t(),x=t();return Pe(l[2],a),Dr(l[1],d),le(_,l[1]),$(y,_,h),me(_,_,l[2]),pe(y,l[2],y),le(S,y),le(E,S),$(x,E,S),$(f,x,_),$(f,f,y),fn(f,f),$(f,f,_),$(f,f,y),$(f,f,y),$(l[0],f,y),le(m,l[0]),$(m,m,y),un(m,_)&&$(l[0],l[0],w),le(m,l[0]),$(m,m,y),un(m,_)?-1:(ln(l[0])===d[31]>>7&&me(l[0],o,l[0]),$(l[3],l[0],l[1]),0)}function Gr(l,d,f,m){var _,y=new Uint8Array(32),S=new Uint8Array(64),E=[t(),t(),t(),t()],x=[t(),t(),t(),t()];if(f<64||sa(x,m))return-1;for(_=0;_<f;_++)l[_]=d[_];for(_=0;_<32;_++)l[_+32]=m[_];if(ze(S,l,f),zr(S),Br(E,x,S),Zt(x,d.subarray(32)),Xt(E,x),qr(y,E),f-=64,T(d,0,y,0)){for(_=0;_<f;_++)l[_]=0;return-1}for(_=0;_<f;_++)l[_]=d[_+64];return f}var Vr=32,er=24,xt=32,et=16,vt=32,tr=32,St=32,Et=32,Wr=32,yn=er,na=xt,ia=et,Oe=64,Ge=32,tt=64,Yr=32,Kr=64;r.lowlevel={crypto_core_hsalsa20:de,crypto_stream_xor:ue,crypto_stream:z,crypto_stream_salsa20_xor:Ae,crypto_stream_salsa20:Ue,crypto_onetimeauth:Je,crypto_onetimeauth_verify:cn,crypto_verify_16:J,crypto_verify_32:T,crypto_secretbox:Fr,crypto_secretbox_open:Lr,crypto_scalarmult:Vt,crypto_scalarmult_base:Wt,crypto_box_beforenm:Yt,crypto_box_afternm:pn,crypto_box:Vo,crypto_box_open:Wo,crypto_box_keypair:dn,crypto_hash:ze,crypto_sign:_n,crypto_sign_keypair:Hr,crypto_sign_open:Gr,crypto_secretbox_KEYBYTES:Vr,crypto_secretbox_NONCEBYTES:er,crypto_secretbox_ZEROBYTES:xt,crypto_secretbox_BOXZEROBYTES:et,crypto_scalarmult_BYTES:vt,crypto_scalarmult_SCALARBYTES:tr,crypto_box_PUBLICKEYBYTES:St,crypto_box_SECRETKEYBYTES:Et,crypto_box_BEFORENMBYTES:Wr,crypto_box_NONCEBYTES:yn,crypto_box_ZEROBYTES:na,crypto_box_BOXZEROBYTES:ia,crypto_sign_BYTES:Oe,crypto_sign_PUBLICKEYBYTES:Ge,crypto_sign_SECRETKEYBYTES:tt,crypto_sign_SEEDBYTES:Yr,crypto_hash_BYTES:Kr,gf:t,D:h,L:Qt,pack25519:Qe,unpack25519:Dr,M:$,A:pe,S:le,Z:me,pow2523:fn,add:Xt,set25519:Pe,modL:Jr,scalarmult:Br,scalarbase:Zt};function wn(l,d){if(l.length!==Vr)throw new Error("bad key size");if(d.length!==er)throw new Error("bad nonce size")}function oa(l,d){if(l.length!==St)throw new Error("bad public key size");if(d.length!==Et)throw new Error("bad secret key size")}function ne(){for(var l=0;l<arguments.length;l++)if(!(arguments[l]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function xn(l){for(var d=0;d<l.length;d++)l[d]=0}r.randomBytes=function(l){var d=new Uint8Array(l);return s(d,l),d},r.secretbox=function(l,d,f){ne(l,d,f),wn(f,d);for(var m=new Uint8Array(xt+l.length),_=new Uint8Array(m.length),y=0;y<l.length;y++)m[y+xt]=l[y];return Fr(_,m,m.length,d,f),_.subarray(et)},r.secretbox.open=function(l,d,f){ne(l,d,f),wn(f,d);for(var m=new Uint8Array(et+l.length),_=new Uint8Array(m.length),y=0;y<l.length;y++)m[y+et]=l[y];return m.length<32||Lr(_,m,m.length,d,f)!==0?null:_.subarray(xt)},r.secretbox.keyLength=Vr,r.secretbox.nonceLength=er,r.secretbox.overheadLength=et,r.scalarMult=function(l,d){if(ne(l,d),l.length!==tr)throw new Error("bad n size");if(d.length!==vt)throw new Error("bad p size");var f=new Uint8Array(vt);return Vt(f,l,d),f},r.scalarMult.base=function(l){if(ne(l),l.length!==tr)throw new Error("bad n size");var d=new Uint8Array(vt);return Wt(d,l),d},r.scalarMult.scalarLength=tr,r.scalarMult.groupElementLength=vt,r.box=function(l,d,f,m){var _=r.box.before(f,m);return r.secretbox(l,d,_)},r.box.before=function(l,d){ne(l,d),oa(l,d);var f=new Uint8Array(Wr);return Yt(f,l,d),f},r.box.after=r.secretbox,r.box.open=function(l,d,f,m){var _=r.box.before(f,m);return r.secretbox.open(l,d,_)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var l=new Uint8Array(St),d=new Uint8Array(Et);return dn(l,d),{publicKey:l,secretKey:d}},r.box.keyPair.fromSecretKey=function(l){if(ne(l),l.length!==Et)throw new Error("bad secret key size");var d=new Uint8Array(St);return Wt(d,l),{publicKey:d,secretKey:new Uint8Array(l)}},r.box.publicKeyLength=St,r.box.secretKeyLength=Et,r.box.sharedKeyLength=Wr,r.box.nonceLength=yn,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(l,d){if(ne(l,d),d.length!==tt)throw new Error("bad secret key size");var f=new Uint8Array(Oe+l.length);return _n(f,l,l.length,d),f},r.sign.open=function(l,d){if(ne(l,d),d.length!==Ge)throw new Error("bad public key size");var f=new Uint8Array(l.length),m=Gr(f,l,l.length,d);if(m<0)return null;for(var _=new Uint8Array(m),y=0;y<_.length;y++)_[y]=f[y];return _},r.sign.detached=function(l,d){for(var f=r.sign(l,d),m=new Uint8Array(Oe),_=0;_<m.length;_++)m[_]=f[_];return m},r.sign.detached.verify=function(l,d,f){if(ne(l,d,f),d.length!==Oe)throw new Error("bad signature size");if(f.length!==Ge)throw new Error("bad public key size");var m=new Uint8Array(Oe+l.length),_=new Uint8Array(Oe+l.length),y;for(y=0;y<Oe;y++)m[y]=d[y];for(y=0;y<l.length;y++)m[y+Oe]=l[y];return Gr(_,m,m.length,f)>=0},r.sign.keyPair=function(){var l=new Uint8Array(Ge),d=new Uint8Array(tt);return Hr(l,d),{publicKey:l,secretKey:d}},r.sign.keyPair.fromSecretKey=function(l){if(ne(l),l.length!==tt)throw new Error("bad secret key size");for(var d=new Uint8Array(Ge),f=0;f<d.length;f++)d[f]=l[32+f];return{publicKey:d,secretKey:new Uint8Array(l)}},r.sign.keyPair.fromSeed=function(l){if(ne(l),l.length!==Yr)throw new Error("bad seed size");for(var d=new Uint8Array(Ge),f=new Uint8Array(tt),m=0;m<32;m++)f[m]=l[m];return Hr(d,f,!0),{publicKey:d,secretKey:f}},r.sign.publicKeyLength=Ge,r.sign.secretKeyLength=tt,r.sign.seedLength=Yr,r.sign.signatureLength=Oe,r.hash=function(l){ne(l);var d=new Uint8Array(Kr);return ze(d,l,l.length),d},r.hash.hashLength=Kr,r.verify=function(l,d){return ne(l,d),l.length===0||d.length===0||l.length!==d.length?!1:M(l,0,d,0,l.length)===0},r.setPRNG=function(l){s=l},function(){var l=typeof globalThis<"u"?globalThis.crypto||globalThis.msCrypto:null;if(l&&l.getRandomValues){var d=65536;r.setPRNG(function(f,m){var _,y=new Uint8Array(m);for(_=0;_<m;_+=d)l.getRandomValues(y.subarray(_,_+Math.min(m-_,d)));for(_=0;_<m;_++)f[_]=y[_];xn(y)})}else typeof require<"u"&&(l=require("crypto"),l&&l.randomBytes&&r.setPRNG(function(f,m){var _,y=l.randomBytes(m);for(_=0;_<m;_++)f[_]=y[_];xn(y)}))}()})(typeof module<"u"&&module.exports?module.exports:globalThis.nacl=globalThis.nacl||{});const cr=typeof module<"u"&&module.exports?module.exports:globalThis.nacl;cr.sign.keyPair.fromSeed,cr.sign.detached,cr.sign.detached.verify,cr.randomBytes;var yi;(function(r){r.InvalidPrefixByte="nkeys: invalid prefix byte",r.InvalidKey="nkeys: invalid key",r.InvalidPublicKey="nkeys: invalid public key",r.InvalidSeedLen="nkeys: invalid seed length",r.InvalidSeed="nkeys: invalid seed",r.InvalidEncoding="nkeys: invalid encoded key",r.InvalidSignature="nkeys: signature verification failed",r.CannotSign="nkeys: cannot sign, no private key available",r.PublicKeyOnly="nkeys: no seed or private key available",r.InvalidChecksum="nkeys: invalid checksum",r.SerializationError="nkeys: serialization error",r.ApiError="nkeys: api error",r.ClearedPair="nkeys: pair is cleared"})(yi||(yi={}));var wi;(function(r){r[r.Seed=144]="Seed",r[r.Private=120]="Private",r[r.Operator=112]="Operator",r[r.Server=104]="Server",r[r.Cluster=16]="Cluster",r[r.Account=0]="Account",r[r.User=160]="User"})(wi||(wi={}));function yl(r){return e=>{let t={};return r.forEach(s=>{const n=s(e)||{};t=Object.assign(t,n)}),t}}function wl(){return()=>{}}function xl(r,e){return()=>{const t=typeof r=="function"?r():r,s=typeof e=="function"?e():e;return{user:t,pass:s}}}function vl(r){return()=>({auth_token:typeof r=="function"?r():r})}const Ro=2*60*1e3,Sl=2,jo=2*1e3;function El(){return{maxPingOut:2,maxReconnectAttempts:10,noRandomize:!1,pedantic:!1,pingInterval:Ro,reconnect:!0,reconnectJitter:100,reconnectJitterTLS:1e3,reconnectTimeWait:jo,tls:void 0,verbose:!1,waitOnFirstConnect:!1,ignoreAuthErrorAbort:!1}}function Al(r){const e=[];return typeof r.authenticator=="function"&&e.push(r.authenticator),Array.isArray(r.authenticator)&&e.push(...r.authenticator),r.token&&e.push(vl(r.token)),r.user&&e.push(xl(r.user,r.pass)),e.length===0?wl():yl(e)}function Pl(r){const e=`${js}:${Ao()}`;if(r=r||{servers:[e]},r.servers=r.servers||[],typeof r.servers=="string"&&(r.servers=[r.servers]),r.servers.length>0&&r.port)throw new j("port and servers options are mutually exclusive",P.InvalidOption);r.servers.length===0&&r.port&&(r.servers=[`${js}:${r.port}`]),r.servers&&r.servers.length===0&&(r.servers=[e]);const t=Mr(El(),r);if(t.authenticator=Al(t),["reconnectDelayHandler","authenticator"].forEach(s=>{if(t[s]&&typeof t[s]!="function")throw new j(`${s} option should be a function`,P.NotFunction)}),t.reconnectDelayHandler||(t.reconnectDelayHandler=()=>{let s=t.tls?t.reconnectJitterTLS:t.reconnectJitter;return s&&(s++,s=Math.floor(Math.random()*s)),t.reconnectTimeWait+s}),t.inboxPrefix)try{Te(t.inboxPrefix)}catch(s){throw new j(s.message,P.ApiError)}if(t.resolve&&typeof Po()!="function")throw new j("'resolve' is not supported on this client",P.InvalidOption);return t}function Ol(r,e){const{proto:t,tls_required:s,tls_available:n}=r;if((t===void 0||t<1)&&e.noEcho)throw new j("noEcho",P.ServerOptionNotAvailable);const i=s||n||!1;if(e.tls&&!i)throw new j("tls",P.ServerOptionNotAvailable)}const Cl=1024*32,kl=/^INFO\s+([^\r\n]+)\r\n/i,Rl=jt(`PONG\r
- `),xi=jt(`PING\r
- `);class jl{constructor(e,t,s){c(this,"echo");c(this,"no_responders");c(this,"protocol");c(this,"verbose");c(this,"pedantic");c(this,"jwt");c(this,"nkey");c(this,"sig");c(this,"user");c(this,"pass");c(this,"auth_token");c(this,"tls_required");c(this,"name");c(this,"lang");c(this,"version");c(this,"headers");this.protocol=1,this.version=e.version,this.lang=e.lang,this.echo=t.noEcho?!1:void 0,this.verbose=t.verbose,this.pedantic=t.pedantic,this.tls_required=t.tls?!0:void 0,this.name=t.name;const n=(t&&typeof t.authenticator=="function"?t.authenticator(s):{})||{};Mr(this,n)}}class Io extends Y{constructor(t,s,n={}){var o;super();c(this,"sid");c(this,"queue");c(this,"draining");c(this,"max");c(this,"subject");c(this,"drained");c(this,"protocol");c(this,"timer");c(this,"info");c(this,"cleanupFn");c(this,"closed");c(this,"requestSubject");Mr(this,n),this.protocol=t,this.subject=s,this.draining=!1,this.noIterator=typeof n.callback=="function",this.closed=B();const i=!((o=t.options)!=null&&o.noAsyncTraces);n.timeout&&(this.timer=dt(n.timeout,i),this.timer.then(()=>{this.timer=void 0}).catch(a=>{this.stop(a),this.noIterator&&this.callback(a,{})})),this.noIterator||this.iterClosed.then(()=>{this.closed.resolve(),this.unsubscribe()})}setPrePostHandlers(t){if(this.noIterator){const s=this.callback,n=t.ingestionFilterFn?t.ingestionFilterFn:()=>({ingest:!0,protocol:!1}),i=t.protocolFilterFn?t.protocolFilterFn:()=>!0,o=t.dispatchedFn?t.dispatchedFn:()=>{};this.callback=(a,u)=>{const{ingest:h}=n(u);h&&i(u)&&(s(a,u),o(u))}}else this.protocolFilterFn=t.protocolFilterFn,this.dispatchedFn=t.dispatchedFn}callback(t,s){this.cancelTimeout(),t?this.stop(t):this.push(s)}close(){if(!this.isClosed()){this.cancelTimeout();const t=()=>{if(this.stop(),this.cleanupFn)try{this.cleanupFn(this,this.info)}catch{}this.closed.resolve()};this.noIterator?t():this.push(t)}}unsubscribe(t){this.protocol.unsubscribe(this,t)}cancelTimeout(){this.timer&&(this.timer.cancel(),this.timer=void 0)}drain(){return this.protocol.isClosed()?Promise.reject(j.errorForCode(P.ConnectionClosed)):this.isClosed()?Promise.reject(j.errorForCode(P.SubClosed)):(this.drained||(this.draining=!0,this.protocol.unsub(this),this.drained=this.protocol.flush(B()).then(()=>{this.protocol.subscriptions.cancel(this)}).catch(()=>{this.protocol.subscriptions.cancel(this)})),this.drained)}isDraining(){return this.draining}isClosed(){return this.done}getSubject(){return this.subject}getMax(){return this.max}getID(){return this.sid}}class Il{constructor(){c(this,"mux");c(this,"subs");c(this,"sidCounter");this.sidCounter=0,this.mux=null,this.subs=new Map}size(){return this.subs.size}add(e){return this.sidCounter++,e.sid=this.sidCounter,this.subs.set(e.sid,e),e}setMux(e){return this.mux=e,e}getMux(){return this.mux}get(e){return this.subs.get(e)}resub(e){return this.sidCounter++,this.subs.delete(e.sid),e.sid=this.sidCounter,this.subs.set(e.sid,e),e}all(){return Array.from(this.subs.values())}cancel(e){e&&(e.close(),this.subs.delete(e.sid))}handleError(e){if(e&&e.permissionContext){const t=e.permissionContext,s=this.all();let n;if(t.operation==="subscription"&&(n=s.find(i=>i.subject===t.subject)),t.operation==="publish"&&(n=s.find(i=>i.requestSubject===t.subject)),n)return n.callback(e,{}),n.close(),this.subs.delete(n.sid),n!==this.mux}return!1}close(){this.subs.forEach(e=>{e.close()})}}class Er{constructor(e,t){c(this,"connected");c(this,"connectedOnce");c(this,"infoReceived");c(this,"info");c(this,"muxSubscriptions");c(this,"options");c(this,"outbound");c(this,"pongs");c(this,"subscriptions");c(this,"transport");c(this,"noMorePublishing");c(this,"connectError");c(this,"publisher");c(this,"_closed");c(this,"closed");c(this,"listeners");c(this,"heartbeats");c(this,"parser");c(this,"outMsgs");c(this,"inMsgs");c(this,"outBytes");c(this,"inBytes");c(this,"pendingLimit");c(this,"lastError");c(this,"abortReconnect");c(this,"servers");c(this,"server");c(this,"features");c(this,"connectPromise");this._closed=!1,this.connected=!1,this.connectedOnce=!1,this.infoReceived=!1,this.noMorePublishing=!1,this.abortReconnect=!1,this.listeners=[],this.pendingLimit=Cl,this.outMsgs=0,this.inMsgs=0,this.outBytes=0,this.inBytes=0,this.options=e,this.publisher=t,this.subscriptions=new Il,this.muxSubscriptions=new dl,this.outbound=new pt,this.pongs=[],this.pendingLimit=e.pendingLimit||this.pendingLimit,this.features=new _l({major:0,minor:0,micro:0}),this.connectPromise=null;const s=typeof e.servers=="string"?[e.servers]:e.servers;this.servers=new fl(s,{randomize:!e.noRandomize}),this.closed=B(),this.parser=new _i(this),this.heartbeats=new pl(this,this.options.pingInterval||Ro,this.options.maxPingOut||Sl)}resetOutbound(){this.outbound.reset();const e=this.pongs;this.pongs=[];const t=j.errorForCode(P.Disconnect);t.stack="",e.forEach(s=>{s.reject(t)}),this.parser=new _i(this),this.infoReceived=!1}dispatchStatus(e){this.listeners.forEach(t=>{t.push(e)})}status(){const e=new Y;return this.listeners.push(e),e}prepare(){this.transport&&this.transport.discard(),this.info=void 0,this.resetOutbound();const e=B();return e.catch(()=>{}),this.pongs.unshift(e),this.connectError=t=>{e.reject(t)},this.transport=Ku(),this.transport.closed().then(async t=>{if(this.connected=!1,!this.isClosed()){await this.disconnected(this.transport.closeError||this.lastError);return}}),e}disconnect(){this.dispatchStatus({type:ct.StaleConnection,data:""}),this.transport.disconnect()}reconnect(){return this.connected&&(this.dispatchStatus({type:ct.ClientInitiatedReconnect,data:""}),this.transport.disconnect()),Promise.resolve()}async disconnected(e){this.dispatchStatus({type:Re.Disconnect,data:this.servers.getCurrentServer().toString()}),this.options.reconnect?await this.dialLoop().then(()=>{var t;this.dispatchStatus({type:Re.Reconnect,data:this.servers.getCurrentServer().toString()}),((t=this.lastError)==null?void 0:t.code)===P.AuthenticationExpired&&(this.lastError=void 0)}).catch(t=>{this._close(t)}):await this._close(e)}async dial(e){const t=this.prepare();let s;try{s=dt(this.options.timeout||2e4);const n=this.transport.connect(e,this.options);await Promise.race([n,s]),(async()=>{try{for await(const i of this.transport)this.parser.parse(i)}catch(i){console.log("reader closed",i)}})().then()}catch(n){t.reject(n)}try{await Promise.race([s,t]),s&&s.cancel(),this.connected=!0,this.connectError=void 0,this.sendSubscriptions(),this.connectedOnce=!0,this.server.didConnect=!0,this.server.reconnects=0,this.flushPending(),this.heartbeats.start()}catch(n){throw s&&s.cancel(),await this.transport.close(n),n}}async _doDial(e){const t=await e.resolve({fn:Po(),debug:this.options.debug,randomize:!this.options.noRandomize});let s=null;for(const n of t)try{s=null,this.dispatchStatus({type:ct.Reconnecting,data:n.toString()}),await this.dial(n);return}catch(i){s=i}throw s}dialLoop(){return this.connectPromise===null&&(this.connectPromise=this.dodialLoop(),this.connectPromise.then(()=>{}).catch(()=>{}).finally(()=>{this.connectPromise=null})),this.connectPromise}async dodialLoop(){let e;for(;;){this._closed&&this.servers.clear();const t=this.options.reconnectDelayHandler?this.options.reconnectDelayHandler():jo;let s=t;const n=this.selectServer();if(!n||this.abortReconnect)throw e||(this.lastError?this.lastError:j.errorForCode(P.ConnectionRefused));const i=Date.now();if(n.lastConnect===0||n.lastConnect+t<=i){n.lastConnect=Date.now();try{await this._doDial(n);break}catch(o){if(e=o,!this.connectedOnce){if(this.options.waitOnFirstConnect)continue;this.servers.removeCurrentServer()}n.reconnects++;const a=this.options.maxReconnectAttempts||0;a!==-1&&n.reconnects>=a&&this.servers.removeCurrentServer()}}else s=Math.min(s,n.lastConnect+t-i),await Jt(s)}}static async connect(e,t){const s=new Er(e,t);return await s.dialLoop(),s}static toError(e){const t=e?e.toLowerCase():"";if(t.indexOf("permissions violation")!==-1){const s=new j(e,P.PermissionsViolation),n=e.match(/(Publish|Subscription) to "(\S+)"/);return n&&(s.permissionContext={operation:n[1].toLowerCase(),subject:n[2]}),s}else return t.indexOf("authorization violation")!==-1?new j(e,P.AuthorizationViolation):t.indexOf("user authentication expired")!==-1?new j(e,P.AuthenticationExpired):t.indexOf("authentication timeout")!==-1?new j(e,P.AuthenticationTimeout):new j(e,P.ProtocolError)}processMsg(e,t){if(this.inMsgs++,this.inBytes+=t.length,!this.subscriptions.sidCounter)return;const s=this.subscriptions.get(e.sid);s&&(s.received+=1,s.callback&&s.callback(null,new Zs(e,t,this)),s.max!==void 0&&s.received>=s.max&&s.unsubscribe())}processError(e){const t=li(e),s=Er.toError(t),n={type:Re.Error,data:s.code};if(s.isPermissionError()){let i=!1;if(s.permissionContext){n.permissionContext=s.permissionContext;const o=this.subscriptions.getMux();i=(o==null?void 0:o.subject)===s.permissionContext.subject}this.subscriptions.handleError(s),this.muxSubscriptions.handleError(i,s),i&&this.subscriptions.setMux(null)}this.dispatchStatus(n),this.handleError(s)}handleError(e){e.isAuthError()?this.handleAuthError(e):e.isProtocolError()?this.lastError=e:e.isAuthTimeout()&&(this.lastError=e),e.isPermissionError()||(this.lastError=e)}handleAuthError(e){this.lastError&&e.code===this.lastError.code&&this.options.ignoreAuthErrorAbort===!1&&(this.abortReconnect=!0),this.connectError?this.connectError(e):this.disconnect()}processPing(){this.transport.send(Rl)}processPong(){const e=this.pongs.shift();e&&e.resolve()}processInfo(e){const t=JSON.parse(li(e));this.info=t;const s=this.options&&this.options.ignoreClusterUpdates?void 0:this.servers.update(t);if(!this.infoReceived){this.features.update(We(t.version)),this.infoReceived=!0,this.transport.isEncrypted()&&this.servers.updateTLSName();const{version:i,lang:o}=this.transport;try{const a=new jl({version:i,lang:o},this.options,t.nonce);t.headers&&(a.headers=!0,a.no_responders=!0);const u=JSON.stringify(a);this.transport.send(jt(`CONNECT ${u}${pr}`)),this.transport.send(xi)}catch(a){this._close(a)}}s&&this.dispatchStatus({type:Re.Update,data:s}),(t.ldm!==void 0?t.ldm:!1)&&this.dispatchStatus({type:Re.LDM,data:this.servers.getCurrentServer().toString()})}push(e){switch(e.kind){case Z.MSG:{const{msg:t,data:s}=e;this.processMsg(t,s);break}case Z.OK:break;case Z.ERR:this.processError(e.data);break;case Z.PING:this.processPing();break;case Z.PONG:this.processPong();break;case Z.INFO:this.processInfo(e.data);break}}sendCommand(e,...t){const s=this.outbound.length();let n;typeof e=="string"?n=jt(e):n=e,this.outbound.fill(n,...t),s===0?queueMicrotask(()=>{this.flushPending()}):this.outbound.size()>=this.pendingLimit&&this.flushPending()}publish(e,t=se,s){let n;if(t instanceof Uint8Array)n=t;else if(typeof t=="string")n=Ke.encode(t);else throw j.errorForCode(P.BadPayload);let i=n.length;s=s||{},s.reply=s.reply||"";let o=se,a=0;if(s.headers){if(this.info&&!this.info.headers)throw new j("headers",P.ServerOptionNotAvailable);o=s.headers.encode(),a=o.length,i=n.length+a}if(this.info&&i>this.info.max_payload)throw j.errorForCode(P.MaxPayloadExceeded);this.outBytes+=i,this.outMsgs++;let u;s.headers?(s.reply?u=`HPUB ${e} ${s.reply} ${a} ${i}\r
- `:u=`HPUB ${e} ${a} ${i}\r
- `,this.sendCommand(u,o,n,vr)):(s.reply?u=`PUB ${e} ${s.reply} ${i}\r
- `:u=`PUB ${e} ${i}\r
- `,this.sendCommand(u,n,vr))}request(e){return this.initMux(),this.muxSubscriptions.add(e),e}subscribe(e){return this.subscriptions.add(e),this._subunsub(e),e}_sub(e){e.queue?this.sendCommand(`SUB ${e.subject} ${e.queue} ${e.sid}\r
- `):this.sendCommand(`SUB ${e.subject} ${e.sid}\r
- `)}_subunsub(e){return this._sub(e),e.max&&this.unsubscribe(e,e.max),e}unsubscribe(e,t){this.unsub(e,t),(e.max===void 0||e.received>=e.max)&&this.subscriptions.cancel(e)}unsub(e,t){!e||this.isClosed()||(t?this.sendCommand(`UNSUB ${e.sid} ${t}\r
- `):this.sendCommand(`UNSUB ${e.sid}\r
- `),e.max=t)}resub(e,t){!e||this.isClosed()||(e.subject=t,this.subscriptions.resub(e),this._sub(e))}flush(e){return e||(e=B()),this.pongs.push(e),this.outbound.fill(xi),this.flushPending(),e}sendSubscriptions(){const e=[];this.subscriptions.all().forEach(t=>{const s=t;s.queue?e.push(`SUB ${s.subject} ${s.queue} ${s.sid}${pr}`):e.push(`SUB ${s.subject} ${s.sid}${pr}`)}),e.length&&this.transport.send(jt(e.join("")))}async _close(e){this._closed||(this.heartbeats.cancel(),this.connectError&&(this.connectError(e),this.connectError=void 0),this.muxSubscriptions.close(),this.subscriptions.close(),this.listeners.forEach(t=>{t.stop()}),this._closed=!0,await this.transport.close(e),await this.closed.resolve(e))}close(){return this._close()}isClosed(){return this._closed}drain(){const e=this.subscriptions.all(),t=[];return e.forEach(s=>{t.push(s.drain())}),Promise.all(t).then(async()=>(this.noMorePublishing=!0,await this.flush(),this.close())).catch(()=>{})}flushPending(){if(!(!this.infoReceived||!this.connected)&&this.outbound.size()){const e=this.outbound.drain();this.transport.send(e)}}initMux(){if(!this.subscriptions.getMux()){const t=this.muxSubscriptions.init(this.options.inboxPrefix),s=new Io(this,`${t}*`);s.callback=this.muxSubscriptions.dispatcher(),this.subscriptions.setMux(s),this.subscribe(s)}}selectServer(){const e=this.servers.selectServer();if(e!==void 0)return this.server=e,this.server}getServer(){return this.server}}class To{constructor(e,t,s=!0){c(this,"token");c(this,"received");c(this,"ctx");c(this,"requestSubject");c(this,"mux");this.mux=e,this.requestSubject=t,this.received=0,this.token=Ht.next(),s&&(this.ctx=new Error)}}class Tl extends To{constructor(t,s,n={maxWait:1e3}){super(t,s);c(this,"callback");c(this,"done");c(this,"timer");c(this,"max");c(this,"opts");if(this.opts=n,typeof this.opts.callback!="function")throw new Error("callback is required");this.callback=this.opts.callback,this.max=typeof n.maxMessages=="number"&&n.maxMessages>0?n.maxMessages:-1,this.done=B(),this.done.then(()=>{this.callback(null,null)}),this.timer=setTimeout(()=>{this.cancel()},n.maxWait)}cancel(t){t&&this.callback(t,null),clearTimeout(this.timer),this.mux.cancel(this),this.done.resolve()}resolver(t,s){t?(this.ctx&&(t.stack+=`
- ${this.ctx.stack}`),this.cancel(t)):(this.callback(null,s),this.opts.strategy===Se.Count&&(this.max--,this.max===0&&this.cancel()),this.opts.strategy===Se.JitterTimer&&(clearTimeout(this.timer),this.timer=setTimeout(()=>{this.cancel()},this.opts.jitter||300)),this.opts.strategy===Se.SentinelMsg&&s&&s.data.length===0&&this.cancel())}}class No extends To{constructor(t,s,n={timeout:1e3},i=!0){super(t,s,i);c(this,"deferred");c(this,"timer");this.deferred=B(),this.timer=dt(n.timeout,i)}resolver(t,s){this.timer&&this.timer.cancel(),t?(this.ctx&&(t.stack+=`
- ${this.ctx.stack}`),this.deferred.reject(t)):this.deferred.resolve(s),this.cancel()}cancel(t){this.timer&&this.timer.cancel(),this.mux.cancel(this),this.deferred.reject(t||j.errorForCode(P.Cancelled))}}function ut(r){return Qs("durable",r)}function te(r){return Qs("stream",r)}function Qs(r,e=""){if(e==="")throw Error(`${r} name required`);return[".","*",">","/","\\"," "," ",`
- `,"\r"].forEach(s=>{if(e.indexOf(s)!==-1){switch(s){case`
- `:s="\\n";break;case"\r":s="\\r";break;case" ":s="\\t";break}throw Error(`invalid ${r} name - ${r} name cannot contain '${s}'`)}}),""}function Ct(r,e=""){if(e==="")throw Error(`${r} name required`);const t=Nl(e);if(t.length)throw new Error(`invalid ${r} name - ${r} name ${t}`)}function Nl(r=""){if(r==="")throw Error("name required");const e=/^[-\w]+$/g;if(r.match(e)===null){for(const s of r.split(""))if(s.match(e)===null)return`cannot contain '${s}'`}return""}function q(r){return r*1e6}function en(r){return Math.floor(r/1e6)}function Ms(r){if(r.data.length>0)return!1;const e=r.headers;return e?e.code>=100&&e.code<200:!1}function Us(r){var e;return Ms(r)&&((e=r.headers)==null?void 0:e.description)==="Idle Heartbeat"}function Ml(r,e,t){const s=Ne(r,e),n={hdr:1,sid:0,size:0},i=new Zs(n,se,{});return i._headers=s,i._subject=t,i}function lt(r){if(r.data.length!==0)return null;const e=r.headers;return e?Mo(e.code,e.description):null}var fe;(function(r){r.MaxBatchExceeded="exceeded maxrequestbatch of",r.MaxExpiresExceeded="exceeded maxrequestexpires of",r.MaxBytesExceeded="exceeded maxrequestmaxbytes of",r.MaxMessageSizeExceeded="message size exceeds maxbytes",r.PushConsumer="consumer is push based",r.MaxWaitingExceeded="exceeded maxwaiting",r.IdleHeartbeatMissed="idle heartbeats missed",r.ConsumerDeleted="consumer deleted"})(fe||(fe={}));function Ul(r){return r.code!==P.JetStream409?!1:[fe.MaxBatchExceeded,fe.MaxExpiresExceeded,fe.MaxBytesExceeded,fe.MaxMessageSizeExceeded,fe.PushConsumer,fe.IdleHeartbeatMissed,fe.ConsumerDeleted].find(t=>r.message.indexOf(t)!==-1)!==void 0}function Mo(r,e=""){if(r<300)return null;switch(e=e.toLowerCase(),r){case 404:return new j(e,P.JetStream404NoMessages);case 408:return new j(e,P.JetStream408RequestTimeout);case 409:{const t=e.startsWith(fe.IdleHeartbeatMissed)?P.JetStreamIdleHeartBeat:P.JetStream409;return new j(e,t)}case 503:return j.errorForCode(P.JetStreamNotEnabled,new Error(e));default:return e===""&&(e=P.Unknown),new j(e,`${r}`)}}const $l="$JS.API";function Fl(r){return r=r||{},r.domain&&(r.apiPrefix=`$JS.${r.domain}.API`,delete r.domain),Mr({apiPrefix:$l,timeout:5e3},r)}class zt{constructor(e,t){c(this,"nc");c(this,"opts");c(this,"prefix");c(this,"timeout");c(this,"jc");this.nc=e,this.opts=Fl(t),this._parseOpts(),this.prefix=this.opts.apiPrefix,this.timeout=this.opts.timeout,this.jc=ye()}getOptions(){return Object.assign({},this.opts)}_parseOpts(){let e=this.opts.apiPrefix;if(!e||e.length===0)throw new Error("invalid empty prefix");e[e.length-1]==="."&&(e=e.substr(0,e.length-1)),this.opts.apiPrefix=e}async _request(e,t=null,s){s=s||{},s.timeout=this.timeout;let n=se;t&&(n=this.jc.encode(t));const i=await this.nc.request(e,n,s);return this.parseJsResponse(i)}async findStream(e){const t={subject:e},n=await this._request(`${this.prefix}.STREAM.NAMES`,t);if(!n.streams||n.streams.length!==1)throw new Error("no stream matches subject");return n.streams[0]}getConnection(){return this.nc}parseJsResponse(e){const t=this.jc.decode(e.data),s=t;if(s.error){const n=Mo(s.error.code,s.error.description);if(n!==null)throw n.api_error=s.error,n}return t}}class Ll{static encode(e){if(typeof e=="string")return btoa(e);const t=Array.from(e);return btoa(String.fromCharCode(...t))}static decode(e,t=!1){const s=atob(e);return t?Uint8Array.from(s,n=>n.charCodeAt(0)):s}}class Nt{static encode(e){return Nt.toB64URLEncoding(Ll.encode(e))}static decode(e,t=!1){return Nt.decode(Nt.fromB64URLEncoding(e),t)}static toB64URLEncoding(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}static fromB64URLEncoding(e){return e.replace(/_/g,"/").replace(/-/g,"+")}}var $s;(function(r){r.Limits="limits",r.Interest="interest",r.Workqueue="workqueue"})($s||($s={}));var $t;(function(r){r.Old="old",r.New="new"})($t||($t={}));var Fs;(function(r){r.File="file",r.Memory="memory"})(Fs||(Fs={}));var H;(function(r){r.All="all",r.Last="last",r.New="new",r.StartSequence="by_start_sequence",r.StartTime="by_start_time",r.LastPerSubject="last_per_subject"})(H||(H={}));var V;(function(r){r.None="none",r.All="all",r.Explicit="explicit",r.NotSet=""})(V||(V={}));var mt;(function(r){r.Instant="instant",r.Original="original"})(mt||(mt={}));var He;(function(r){r.None="none",r.S2="s2"})(He||(He={}));var Ar;(function(r){r.CreateOrUpdate="",r.Update="update",r.Create="create"})(Ar||(Ar={}));function Dl(r,e={}){return Object.assign({name:r,deliver_policy:H.All,ack_policy:V.Explicit,ack_wait:q(30*1e3),replay_policy:mt.Instant},e)}var vi;(function(r){r.API="api_audit",r.StreamAction="stream_action",r.ConsumerAction="consumer_action",r.SnapshotCreate="snapshot_create",r.SnapshotComplete="snapshot_complete",r.RestoreCreate="restore_create",r.RestoreComplete="restore_complete",r.MaxDeliver="max_deliver",r.Terminated="terminated",r.Ack="consumer_ack",r.StreamLeaderElected="stream_leader_elected",r.StreamQuorumLost="stream_quorum_lost",r.ConsumerLeaderElected="consumer_leader_elected",r.ConsumerQuorumLost="consumer_quorum_lost"})(vi||(vi={}));var Q;(function(r){r.StreamSourceHdr="Nats-Stream-Source",r.LastConsumerSeqHdr="Nats-Last-Consumer",r.LastStreamSeqHdr="Nats-Last-Stream",r.ConsumerStalledHdr="Nats-Consumer-Stalled",r.MessageSizeHdr="Nats-Msg-Size",r.RollupHdr="Nats-Rollup",r.RollupValueSubject="sub",r.RollupValueAll="all",r.PendingMessagesHdr="Nats-Pending-Messages",r.PendingBytesHdr="Nats-Pending-Bytes"})(Q||(Q={}));var _e;(function(r){r.LastValue="",r.AllHistory="history",r.UpdatesOnly="updates"})(_e||(_e={}));var ot;(function(r){r.Stream="Nats-Stream",r.Sequence="Nats-Sequence",r.TimeStamp="Nats-Time-Stamp",r.Subject="Nats-Subject"})(ot||(ot={}));var Si;(function(r){r.Stream="Nats-Stream",r.Subject="Nats-Subject",r.Sequence="Nats-Sequence",r.LastSequence="Nats-Last-Sequence",r.Size="Nats-Msg-Size"})(Si||(Si={}));const he="KV_";class ql{constructor(e){c(this,"config");c(this,"ordered");c(this,"mack");c(this,"stream");c(this,"callbackFn");c(this,"max");c(this,"qname");c(this,"isBind");c(this,"filters");this.stream="",this.mack=!1,this.ordered=!1,this.config=Dl("",e||{})}getOpts(){var t;const e={};if(e.config=Object.assign({},this.config),e.config.filter_subject&&(this.filterSubject(e.config.filter_subject),e.config.filter_subject=void 0),e.config.filter_subjects&&((t=e.config.filter_subjects)==null||t.forEach(s=>{this.filterSubject(s)}),e.config.filter_subjects=void 0),e.mack=this.mack,e.stream=this.stream,e.callbackFn=this.callbackFn,e.max=this.max,e.queue=this.qname,e.ordered=this.ordered,e.config.ack_policy=e.ordered?V.None:e.config.ack_policy,e.isBind=e.isBind||!1,this.filters)switch(this.filters.length){case 0:break;case 1:e.config.filter_subject=this.filters[0];break;default:e.config.filter_subjects=this.filters}return e}description(e){return this.config.description=e,this}deliverTo(e){return this.config.deliver_subject=e,this}durable(e){return ut(e),this.config.durable_name=e,this}startSequence(e){if(e<=0)throw new Error("sequence must be greater than 0");return this.config.deliver_policy=H.StartSequence,this.config.opt_start_seq=e,this}startTime(e){return this.config.deliver_policy=H.StartTime,this.config.opt_start_time=e.toISOString(),this}deliverAll(){return this.config.deliver_policy=H.All,this}deliverLastPerSubject(){return this.config.deliver_policy=H.LastPerSubject,this}deliverLast(){return this.config.deliver_policy=H.Last,this}deliverNew(){return this.config.deliver_policy=H.New,this}startAtTimeDelta(e){return this.startTime(new Date(Date.now()-e)),this}headersOnly(){return this.config.headers_only=!0,this}ackNone(){return this.config.ack_policy=V.None,this}ackAll(){return this.config.ack_policy=V.All,this}ackExplicit(){return this.config.ack_policy=V.Explicit,this}ackWait(e){return this.config.ack_wait=q(e),this}maxDeliver(e){return this.config.max_deliver=e,this}filterSubject(e){return this.filters=this.filters||[],this.filters.push(e),this}replayInstantly(){return this.config.replay_policy=mt.Instant,this}replayOriginal(){return this.config.replay_policy=mt.Original,this}sample(e){if(e=Math.trunc(e),e<0||e>100)throw new Error("value must be between 0-100");return this.config.sample_freq=`${e}%`,this}limit(e){return this.config.rate_limit_bps=e,this}maxWaiting(e){return this.config.max_waiting=e,this}maxAckPending(e){return this.config.max_ack_pending=e,this}idleHeartbeat(e){return this.config.idle_heartbeat=q(e),this}flowControl(){return this.config.flow_control=!0,this}deliverGroup(e){return this.queue(e),this}manualAck(){return this.mack=!0,this}maxMessages(e){return this.max=e,this}callback(e){return this.callbackFn=e,this}queue(e){return this.qname=e,this.config.deliver_group=e,this}orderedConsumer(){return this.ordered=!0,this}bind(e,t){return this.stream=e,this.config.durable_name=t,this.isBind=!0,this}bindStream(e){return this.stream=e,this}inactiveEphemeralThreshold(e){return this.config.inactive_threshold=q(e),this}maxPullBatch(e){return this.config.max_batch=e,this}maxPullRequestExpires(e){return this.config.max_expires=q(e),this}memory(){return this.config.mem_storage=!0,this}numReplicas(e){return this.config.num_replicas=e,this}}function Be(r){return new ql(r)}function Ei(r){return typeof r.getOpts=="function"}function Ai(r){const e=r.length;let t=r.indexOf("=");t===-1&&(t=e);const s=t===e?0:4-t%4;return[t,s]}function Bl(r,e,t=!1){function s(o,a){return Math.floor((o+a)*3/4-a)}function n(o){return r[o>>18&63]+r[o>>12&63]+r[o>>6&63]+r[o&63]}function i(o,a,u){const h=new Array((u-a)/3);for(let p=a,g=0;p<u;p+=3)h[g++]=n((o[p]<<16)+(o[p+1]<<8)+o[p+2]);return h.join("")}return{byteLength(o){return s.apply(null,Ai(o))},toUint8Array(o){const[a,u]=Ai(o),h=new Uint8Array(s(a,u)),p=u?a-4:a;let g,b=0,w;for(w=0;w<p;w+=4)g=e[o.charCodeAt(w)]<<18|e[o.charCodeAt(w+1)]<<12|e[o.charCodeAt(w+2)]<<6|e[o.charCodeAt(w+3)],h[b++]=g>>16&255,h[b++]=g>>8&255,h[b++]=g&255;return u===2?(g=e[o.charCodeAt(w)]<<2|e[o.charCodeAt(w+1)]>>4,h[b++]=g&255):u===1&&(g=e[o.charCodeAt(w)]<<10|e[o.charCodeAt(w+1)]<<4|e[o.charCodeAt(w+2)]>>2,h[b++]=g>>8&255,h[b++]=g&255),h},fromUint8Array(o){const u=o.length,h=u%3,p=u-h,g=new Array(Math.ceil(p/16383)+(h?1:0));let b=0,w;for(let k=0;k<p;k+=16383)w=k+16383,g[b++]=i(o,k,w>p?p:w);let A;return h===1?(A=o[p],g[b]=r[A>>2]+r[A<<4&63],t||(g[b]+="==")):h===2&&(A=o[p]<<8|o[p+1]&255,g[b]=r[A>>10]+r[A>>4&63]+r[A<<2&63],t||(g[b]+="=")),g.join("")}}}const Uo=[],$o=[],ys="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";for(let r=0,e=ys.length;r<e;++r)Uo[r]=ys[r],$o[ys.charCodeAt(r)]=r;const{byteLength:zh,toUint8Array:Hl,fromUint8Array:Jl}=Bl(Uo,$o,!0),zl=new TextDecoder,Gl=new TextEncoder;function Vl(r){return r.reduce((e,t)=>`${e}${t<16?"0":""}${t.toString(16)}`,"")}function Wl(r){const e=r.length;if(e%2||!/^[0-9a-fA-F]+$/.test(r))throw new TypeError("Invalid hex string.");r=r.toLowerCase();const t=new Uint8Array(Math.floor(e/2)),s=e/2;for(let n=0;n<s;++n)t[n]=parseInt(r.substr(n*2,2),16);return t}function Yl(r,e="utf8"){if(/^utf-?8$/i.test(e))return zl.decode(r);if(/^base64$/i.test(e))return Jl(r);if(/^hex(?:adecimal)?$/i.test(e))return Vl(r);throw new TypeError("Unsupported string encoding.")}function Kl(r,e="utf8"){if(/^utf-?8$/i.test(e))return Gl.encode(r);if(/^base64$/i.test(e))return Hl(r);if(/^hex(?:adecimal)?$/i.test(e))return Wl(r);throw new TypeError("Unsupported string encoding.")}class Pi{constructor(){c(this,"hashSize",32);c(this,"_buf");c(this,"_bufIdx");c(this,"_count");c(this,"_K");c(this,"_H");c(this,"_finalized");this._buf=new Uint8Array(64),this._K=new Uint32Array([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]),this.init()}init(){return this._H=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),this._bufIdx=0,this._count=new Uint32Array(2),this._buf.fill(0),this._finalized=!1,this}update(e,t){if(e===null)throw new TypeError("msg must be a string or Uint8Array.");typeof e=="string"&&(e=Kl(e,t));for(let n=0,i=e.length;n<i;n++)this._buf[this._bufIdx++]=e[n],this._bufIdx===64&&(this._transform(),this._bufIdx=0);const s=this._count;return(s[0]+=e.length<<3)<e.length<<3&&s[1]++,s[1]+=e.length>>>29,this}digest(e){if(this._finalized)throw new Error("digest has already been called.");this._finalized=!0;const t=this._buf;let s=this._bufIdx;for(t[s++]=128;s!==56;)s===64&&(this._transform(),s=0),t[s++]=0;const n=this._count;t[56]=n[1]>>>24&255,t[57]=n[1]>>>16&255,t[58]=n[1]>>>8&255,t[59]=n[1]>>>0&255,t[60]=n[0]>>>24&255,t[61]=n[0]>>>16&255,t[62]=n[0]>>>8&255,t[63]=n[0]>>>0&255,this._transform();const i=new Uint8Array(32);for(let o=0;o<8;o++)i[(o<<2)+0]=this._H[o]>>>24&255,i[(o<<2)+1]=this._H[o]>>>16&255,i[(o<<2)+2]=this._H[o]>>>8&255,i[(o<<2)+3]=this._H[o]>>>0&255;return this.init(),e?Yl(i,e):i}_transform(){const e=this._H;let t=e[0],s=e[1],n=e[2],i=e[3],o=e[4],a=e[5],u=e[6],h=e[7];const p=new Uint32Array(16);let g;for(g=0;g<16;g++)p[g]=this._buf[(g<<2)+3]|this._buf[(g<<2)+2]<<8|this._buf[(g<<2)+1]<<16|this._buf[g<<2]<<24;for(g=0;g<64;g++){let b;if(g<16)b=p[g];else{let w=p[g+1&15],A=p[g+14&15];b=p[g&15]=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+p[g&15]+p[g+9&15]|0}b=b+h+(o>>>6^o>>>11^o>>>25^o<<26^o<<21^o<<7)+(u^o&(a^u))+this._K[g]|0,h=u,u=a,a=o,o=i+b,i=n,n=s,s=t,t=b+(s&n^i&(s^n))+(s>>>2^s>>>13^s>>>22^s<<30^s<<19^s<<10)|0}e[0]=e[0]+t|0,e[1]=e[1]+s|0,e[2]=e[2]+n|0,e[3]=e[3]+i|0,e[4]=e[4]+o|0,e[5]=e[5]+a|0,e[6]=e[6]+u|0,e[7]=e[7]+h|0}}class kt{constructor(e,t,s,n){c(this,"err");c(this,"offset");c(this,"pageInfo");c(this,"subject");c(this,"jsm");c(this,"filter");c(this,"payload");if(!e)throw new Error("subject is required");this.subject=e,this.jsm=s,this.offset=0,this.pageInfo={},this.filter=t,this.payload=n||{}}async next(){if(this.err)return[];if(this.pageInfo&&this.offset>=this.pageInfo.total)return[];const e={offset:this.offset};this.payload&&Object.assign(e,this.payload);try{const t=await this.jsm._request(this.subject,e,{timeout:this.jsm.timeout});return this.pageInfo=t,this.offset+=this.countResponse(t),this.filter(t)}catch(t){throw this.err=t,t}}countResponse(e){var t;switch(e==null?void 0:e.type){case"io.nats.jetstream.api.v1.stream_names_response":case"io.nats.jetstream.api.v1.stream_list_response":return e.streams.length;case"io.nats.jetstream.api.v1.consumer_list_response":return e.consumers.length;default:return console.error(`jslister.ts: unknown API response for paged output: ${e==null?void 0:e.type}`),((t=e.streams)==null?void 0:t.length)||0}return 0}async*[Symbol.asyncIterator](){let e=await this.next();for(;e.length>0;){for(const t of e)yield t;e=await this.next()}}}class tn extends zt{constructor(e,t){super(e,t)}async add(e,t,s=Ar.Create){if(te(e),t.deliver_group&&t.flow_control)throw new Error("jetstream flow control is not supported with queue groups");if(t.deliver_group&&t.idle_heartbeat)throw new Error("jetstream idle heartbeat is not supported with queue groups");const n={};n.config=t,n.stream_name=e,n.action=s,n.config.durable_name&&ut(n.config.durable_name);const i=this.nc;let{min:o,ok:a}=i.features.get(L.JS_NEW_CONSUMER_CREATE_API);const u=t.name===""?void 0:t.name;if(u&&!a)throw new Error(`consumer 'name' requires server ${o}`);if(u)try{Qs("name",u)}catch(b){const w=b.message,A=w.indexOf("cannot contain");throw A!==-1?new Error(`consumer 'name' ${w.substring(A)}`):b}let h,p="";if(Array.isArray(t.filter_subjects)){const{min:b,ok:w}=i.features.get(L.JS_MULTIPLE_CONSUMER_FILTER);if(!w)throw new Error(`consumer 'filter_subjects' requires server ${b}`);a=!1}if(t.metadata){const{min:b,ok:w}=i.features.get(L.JS_STREAM_CONSUMER_METADATA);if(!w)throw new Error(`consumer 'metadata' requires server ${b}`)}if(a&&(p=t.name??t.durable_name??""),p!==""){let b=t.filter_subject??void 0;b===">"&&(b=void 0),h=b!==void 0?`${this.prefix}.CONSUMER.CREATE.${e}.${p}.${b}`:`${this.prefix}.CONSUMER.CREATE.${e}.${p}`}else h=t.durable_name?`${this.prefix}.CONSUMER.DURABLE.CREATE.${e}.${t.durable_name}`:`${this.prefix}.CONSUMER.CREATE.${e}`;return await this._request(h,n)}async update(e,t,s){const n=await this.info(e,t),i=s;return this.add(e,Object.assign(n.config,i),Ar.Update)}async info(e,t){return te(e),ut(t),await this._request(`${this.prefix}.CONSUMER.INFO.${e}.${t}`)}async delete(e,t){return te(e),ut(t),(await this._request(`${this.prefix}.CONSUMER.DELETE.${e}.${t}`)).success}list(e){te(e);const t=n=>n.consumers,s=`${this.prefix}.CONSUMER.LIST.${e}`;return new kt(s,t,this)}}const Oi=Uint8Array.of(43,65,67,75),Xl=Uint8Array.of(45,78,65,75),Pt=Uint8Array.of(43,87,80,73),Zl=Uint8Array.of(43,78,88,84),Ql=Uint8Array.of(43,84,69,82,77),eh=Uint8Array.of(32);function Ft(r){return new rh(r)}function th(r){const e=r.split(".");if(e.length===9&&e.splice(2,0,"_",""),e.length<11||e[0]!=="$JS"||e[1]!=="ACK")throw new Error("not js message");const t={};return t.domain=e[2]==="_"?"":e[2],t.account_hash=e[3],t.stream=e[4],t.consumer=e[5],t.redeliveryCount=parseInt(e[6],10),t.redelivered=t.redeliveryCount>1,t.streamSequence=parseInt(e[7],10),t.deliverySequence=parseInt(e[8],10),t.timestampNanos=parseInt(e[9],10),t.pending=parseInt(e[10],10),t}class rh{constructor(e){c(this,"msg");c(this,"di");c(this,"didAck");this.msg=e,this.didAck=!1}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){return this.di||(this.di=th(this.reply)),this.di}get redelivered(){return this.info.redeliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}doAck(e){this.didAck||(this.didAck=!this.isWIP(e),this.msg.respond(e))}isWIP(e){return e.length===4&&e[0]===Pt[0]&&e[1]===Pt[1]&&e[2]===Pt[2]&&e[3]===Pt[3]}async ackAck(){var e;if(!this.didAck&&(this.didAck=!0,this.msg.reply)){const s=this.msg.publisher,n=!((e=s.options)!=null&&e.noAsyncTraces),i=new No(s.muxSubscriptions,this.msg.reply,{timeout:1e3},n);s.request(i);try{s.publish(this.msg.reply,Oi,{reply:`${s.muxSubscriptions.baseInbox}${i.token}`})}catch(o){i.cancel(o)}try{return await Promise.race([i.timer,i.deferred]),!0}catch(o){i.cancel(o)}}return!1}ack(){this.doAck(Oi)}nak(e){let t=Xl;e&&(t=Sr().encode(`-NAK ${JSON.stringify({delay:q(e)})}`)),this.doAck(t)}working(){this.doAck(Pt)}next(e,t={batch:1}){const s={};s.batch=t.batch||1,s.no_wait=t.no_wait||!1,t.expires&&t.expires>0&&(s.expires=q(t.expires));const n=ye().encode(s),i=pt.concat(Zl,eh,n),o=e?{reply:e}:void 0;this.msg.respond(i,o)}term(e=""){let t=Ql;(e==null?void 0:e.length)>0&&(t=Sr().encode(`+TERM ${e}`)),this.doAck(t)}json(){return this.msg.json()}string(){return this.msg.string()}}function it(r,e,t=!1){if(t===!0&&!r)throw j.errorForCode(P.ApiError,new Error(`${e} is not a function`));if(r&&typeof r!="function")throw j.errorForCode(P.ApiError,new Error(`${e} is not a function`))}class sh extends Y{constructor(t,s,n){super();c(this,"sub");c(this,"adapter");c(this,"subIterDone");it(n.adapter,"adapter",!0),this.adapter=n.adapter,n.callback&&it(n.callback,"callback"),this.noIterator=typeof n.callback=="function",n.ingestionFilterFn&&(it(n.ingestionFilterFn,"ingestionFilterFn"),this.ingestionFilterFn=n.ingestionFilterFn),n.protocolFilterFn&&(it(n.protocolFilterFn,"protocolFilterFn"),this.protocolFilterFn=n.protocolFilterFn),n.dispatchedFn&&(it(n.dispatchedFn,"dispatchedFn"),this.dispatchedFn=n.dispatchedFn),n.cleanupFn&&it(n.cleanupFn,"cleanupFn");let i=(p,g)=>{this.callback(p,g)};if(n.callback){const p=n.callback;i=(g,b)=>{const[w,A]=this.adapter(g,b);if(w){p(w,null);return}const{ingest:k}=this.ingestionFilterFn?this.ingestionFilterFn(A,this):{ingest:!0};k&&(!this.protocolFilterFn||this.protocolFilterFn(A))&&(p(w,A),this.dispatchedFn&&A&&this.dispatchedFn(A))}}const{max:o,queue:a,timeout:u}=n,h={queue:a,timeout:u,callback:i};o&&o>0&&(h.max=o),this.sub=t.subscribe(s,h),n.cleanupFn&&(this.sub.cleanupFn=n.cleanupFn),this.noIterator||this.iterClosed.then(()=>{this.unsubscribe()}),this.subIterDone=B(),Promise.all([this.sub.closed,this.iterClosed]).then(()=>{this.subIterDone.resolve()}).catch(()=>{this.subIterDone.resolve()}),(async p=>{await p.closed,this.stop()})(this.sub).then().catch()}unsubscribe(t){this.sub.unsubscribe(t)}drain(){return this.sub.drain()}isDraining(){return this.sub.isDraining()}isClosed(){return this.sub.isClosed()}callback(t,s){this.sub.cancelTimeout();const[n,i]=this.adapter(t,s);n&&this.stop(n),i&&this.push(i)}getSubject(){return this.sub.getSubject()}getReceived(){return this.sub.getReceived()}getProcessed(){return this.sub.getProcessed()}getPending(){return this.sub.getPending()}getID(){return this.sub.getID()}getMax(){return this.sub.getMax()}get closed(){return this.sub.closed}}class rn{constructor(e,t,s={maxOut:2}){c(this,"interval");c(this,"maxOut");c(this,"cancelAfter");c(this,"timer");c(this,"autoCancelTimer");c(this,"last");c(this,"missed");c(this,"count");c(this,"callback");this.interval=e,this.maxOut=(s==null?void 0:s.maxOut)||2,this.cancelAfter=(s==null?void 0:s.cancelAfter)||0,this.last=Date.now(),this.missed=0,this.count=0,this.callback=t,this._schedule()}cancel(){this.autoCancelTimer&&clearTimeout(this.autoCancelTimer),this.timer&&clearInterval(this.timer),this.timer=0,this.autoCancelTimer=0}work(){this.last=Date.now(),this.missed=0}_change(e,t=0,s=2){this.interval=e,this.maxOut=s,this.cancelAfter=t,this.restart()}restart(){this.cancel(),this._schedule()}_schedule(){this.cancelAfter>0&&(this.autoCancelTimer=setTimeout(()=>{this.cancel()},this.cancelAfter)),this.timer=setInterval(()=>{if(this.count++,Date.now()-this.last>this.interval&&this.missed++,this.missed>=this.maxOut)try{this.callback(this.missed)===!0&&this.cancel()}catch(e){console.log(e)}},this.interval)}}var xe;(function(r){r[r.Unset=-1]="Unset",r[r.Consume=0]="Consume",r[r.Fetch=1]="Fetch"})(xe||(xe={}));var bt;(function(r){r.HeartbeatsMissed="heartbeats_missed",r.ConsumerNotFound="consumer_not_found",r.OrderedConsumerRecreated="ordered_consumer_recreated"})(bt||(bt={}));var Mt;(function(r){r.DebugEvent="debug",r.Discard="discard",r.Next="next"})(Mt||(Mt={}));class ws extends Y{constructor(t,s,n=!1){super();c(this,"consumer");c(this,"opts");c(this,"sub");c(this,"monitor");c(this,"pending");c(this,"inbox");c(this,"refilling");c(this,"stack");c(this,"pong");c(this,"callback");c(this,"timeout");c(this,"cleanupHandler");c(this,"listeners");c(this,"statusIterator");c(this,"forOrderedConsumer");c(this,"resetHandler");this.consumer=t,this.opts=this.parseOptions(s,n),this.callback=s.callback||null,this.noIterator=typeof this.callback=="function",this.monitor=null,this.pong=null,this.pending={msgs:0,bytes:0,requests:0},this.refilling=n,this.stack=new Error().stack.split(`
- `).slice(1).join(`
- `),this.timeout=null,this.inbox=Te(t.api.nc.options.inboxPrefix),this.listeners=[],this.forOrderedConsumer=!1,this.start()}start(){const{max_messages:t,max_bytes:s,idle_heartbeat:n,threshold_bytes:i,threshold_messages:o}=this.opts;this.closed().then(()=>{if(this.cleanupHandler)try{this.cleanupHandler()}catch{}});const{sub:a}=this;a&&a.unsubscribe(),this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(u,h)=>{var g,b,w,A;if(u){this.stop();return}if((g=this.monitor)==null||g.work(),h.subject===this.inbox){if(Us(h))return;const k=(b=h.headers)==null?void 0:b.code,R=((A=(w=h.headers)==null?void 0:w.description)==null?void 0:A.toLowerCase())||"unknown",{msgsLeft:U,bytesLeft:N}=this.parseDiscard(h.headers);if(U>0||N>0)this.pending.msgs-=U,this.pending.bytes-=N,this.pending.requests--,this.notify(Mt.Discard,{msgsLeft:U,bytesLeft:N});else{const M=()=>{const J=new j(R,`${k}`);return J.stack+=`
- ${this.stack}`,J};if(k===400){const J=M();this._push(()=>{this.stop(J)})}else if(k===409&&R==="consumer deleted"){const J=M();this.stop(J)}else this.notify(Mt.DebugEvent,`${k} ${R}`)}}else this._push(Ft(h)),this.received++,this.pending.msgs&&this.pending.msgs--,this.pending.bytes&&(this.pending.bytes-=h.size());if(this.pending.msgs===0&&this.pending.bytes===0&&(this.pending.requests=0),this.refilling){if(t&&this.pending.msgs<=o||s&&this.pending.bytes<=i){const k=this.pullOptions();this.pull(k)}}else this.pending.requests===0&&this._push(()=>{this.stop()})}}),this.sub.closed.then(()=>{this.sub.draining&&this._push(()=>{this.stop()})}),n&&(this.monitor=new rn(n,u=>(this.notify(bt.HeartbeatsMissed,u),this.resetPending().then(()=>{}).catch(()=>{}),!1),{maxOut:2})),(async()=>{var h;const u=this.consumer.api.nc.status();this.statusIterator=u;for await(const p of u)switch(p.type){case Re.Disconnect:(h=this.monitor)==null||h.cancel();break;case Re.Reconnect:this.resetPending().then(g=>{var b;g&&((b=this.monitor)==null||b.restart())}).catch(()=>{});break}})(),this.pull(this.pullOptions())}_push(t){if(!this.callback)super.push(t);else{const s=typeof t=="function"?t:null;try{s?s():this.callback(t)}catch(n){this.stop(n)}}}notify(t,s){this.listeners.length>0&&this.listeners.forEach(n=>{n.done||n.push({type:t,data:s})})}async resetPending(){let t=0;const s=Eo();let n=0;for(;;){if(this.consumer.api.nc.isClosed())return console.error("aborting resetPending - connection is closed"),!1;try{return await this.consumer.info(),t=0,this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),!0}catch(i){if(i.message==="consumer not found"){if(t++,this.notify(bt.ConsumerNotFound,t),this.resetHandler)try{this.resetHandler()}catch{}if(this.forOrderedConsumer)return!1}else t=0;const o=s.backoff(n);await Promise.race([Jt(o),this.consumer.api.nc.closed()]),n++}}}pull(t){this.pending.bytes+=t.max_bytes??0,this.pending.msgs+=t.batch??0,this.pending.requests++;const s=this.consumer.api.nc;this._push(()=>{s.publish(`${this.consumer.api.prefix}.CONSUMER.MSG.NEXT.${this.consumer.stream}.${this.consumer.name}`,this.consumer.api.jc.encode(t),{reply:this.inbox}),this.notify(Mt.Next,t)})}pullOptions(){const t=this.opts.max_messages-this.pending.msgs,s=this.opts.max_bytes-this.pending.bytes,n=q(this.opts.idle_heartbeat),i=q(this.opts.expires);return{batch:t,max_bytes:s,idle_heartbeat:n,expires:i}}parseDiscard(t){const s={msgsLeft:0,bytesLeft:0},n=t==null?void 0:t.get(Q.PendingMessagesHdr);n&&(s.msgsLeft=parseInt(n));const i=t==null?void 0:t.get(Q.PendingBytesHdr);return i&&(s.bytesLeft=parseInt(i)),s}trackTimeout(t){this.timeout=t}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}clearTimers(){var t,s;(t=this.monitor)==null||t.cancel(),this.monitor=null,(s=this.timeout)==null||s.cancel(),this.timeout=null}setCleanupHandler(t){this.cleanupHandler=t}stop(t){var s,n;(s=this.sub)==null||s.unsubscribe(),this.clearTimers(),(n=this.statusIterator)==null||n.stop(),this._push(()=>{super.stop(t),this.listeners.forEach(i=>{i.stop()})})}parseOptions(t,s=!1){const n=t||{};if(n.max_messages=n.max_messages||0,n.max_bytes=n.max_bytes||0,n.max_messages!==0&&n.max_bytes!==0)throw new Error("only specify one of max_messages or max_bytes");if(n.max_messages===0&&(n.max_messages=100),n.expires=n.expires||3e4,n.expires<1e3)throw new Error("expires should be at least 1000ms");if(n.idle_heartbeat=n.idle_heartbeat||n.expires/2,n.idle_heartbeat=n.idle_heartbeat>3e4?3e4:n.idle_heartbeat,s){const i=Math.round(n.max_messages*.75)||1;n.threshold_messages=n.threshold_messages||i;const o=Math.round(n.max_bytes*.75)||1;n.threshold_bytes=n.threshold_bytes||o}return n}status(){const t=new Y;return this.listeners.push(t),Promise.resolve(t)}}class Ci extends Y{constructor(){super();c(this,"src");c(this,"listeners");this.listeners=[]}setSource(t){this.src&&(this.src.resetHandler=void 0,this.src.setCleanupHandler(),this.src.stop()),this.src=t,this.src.setCleanupHandler(()=>{this.close().catch()}),(async()=>{const s=await this.src.status();for await(const n of s)this.notify(n.type,n.data)})().catch(()=>{})}notify(t,s){this.listeners.length>0&&this.listeners.forEach(n=>{n.done||n.push({type:t,data:s})})}stop(t){var s;(s=this.src)==null||s.stop(t),super.stop(t),this.listeners.forEach(n=>{n.stop()})}close(){return this.stop(),this.iterClosed}status(){const t=new Y;return this.listeners.push(t),Promise.resolve(t)}}class Fo{constructor(e,t){c(this,"api");c(this,"_info");c(this,"stream");c(this,"name");this.api=e,this._info=t,this.stream=t.stream_name,this.name=t.name}consume(e={max_messages:100,expires:3e4}){return Promise.resolve(new ws(this,e,!0))}fetch(e={max_messages:100,expires:3e4}){const t=new ws(this,e,!1),s=Math.round(t.opts.expires*1.05),n=dt(s);return t.closed().then(()=>{n.cancel()}),n.catch(()=>{t.close().catch()}),t.trackTimeout(n),Promise.resolve(t)}next(e={expires:3e4}){const t=B(),s=e;s.max_messages=1;const n=new ws(this,s,!1),i=Math.round(n.opts.expires*1.05);i>=6e4&&(async()=>{for await(const a of await n.status())if(a.type===bt.HeartbeatsMissed&&a.data>=2){t.reject(new Error("consumer missed heartbeats"));break}})().catch(),(async()=>{for await(const a of n){t.resolve(a);break}})().catch();const o=dt(i);return n.closed().then(()=>{t.resolve(null),o.cancel()}).catch(a=>{t.reject(a)}),o.catch(a=>{t.resolve(null),n.close().catch()}),n.trackTimeout(o),t}delete(){const{stream_name:e,name:t}=this._info;return this.api.delete(e,t)}info(e=!1){if(e)return Promise.resolve(this._info);const{stream_name:t,name:s}=this._info;return this.api.info(t,s).then(n=>(this._info=n,this._info))}}class nh{constructor(e,t,s={}){c(this,"api");c(this,"consumerOpts");c(this,"consumer");c(this,"opts");c(this,"cursor");c(this,"stream");c(this,"namePrefix");c(this,"serial");c(this,"currentConsumer");c(this,"userCallback");c(this,"iter");c(this,"type");c(this,"startSeq");this.api=e,this.stream=t,this.cursor={stream_seq:1,deliver_seq:0},this.namePrefix=Ht.next(),this.serial=0,this.currentConsumer=null,this.userCallback=null,this.iter=null,this.type=xe.Unset,this.consumerOpts=s,this.startSeq=this.consumerOpts.opt_start_seq||0,this.cursor.stream_seq=this.startSeq>0?this.startSeq-1:0}getConsumerOpts(e){this.serial++;const t=`${this.namePrefix}_${this.serial}`;e=e===0?1:e;const s={name:t,deliver_policy:H.StartSequence,opt_start_seq:e,ack_policy:V.None,inactive_threshold:q(5*60*1e3),num_replicas:1};return this.consumerOpts.headers_only===!0&&(s.headers_only=!0),Array.isArray(this.consumerOpts.filterSubjects)&&(s.filter_subjects=this.consumerOpts.filterSubjects),typeof this.consumerOpts.filterSubjects=="string"&&(s.filter_subject=this.consumerOpts.filterSubjects),e===this.startSeq+1&&(s.deliver_policy=this.consumerOpts.deliver_policy||H.StartSequence,(this.consumerOpts.deliver_policy===H.LastPerSubject||this.consumerOpts.deliver_policy===H.New||this.consumerOpts.deliver_policy===H.Last)&&(delete s.opt_start_seq,s.deliver_policy=this.consumerOpts.deliver_policy),s.deliver_policy===H.LastPerSubject&&typeof s.filter_subjects>"u"&&typeof s.filter_subject>"u"&&(s.filter_subject=">"),this.consumerOpts.opt_start_time&&(delete s.opt_start_seq,s.deliver_policy=H.StartTime,s.opt_start_time=this.consumerOpts.opt_start_time),this.consumerOpts.inactive_threshold&&(s.inactive_threshold=q(this.consumerOpts.inactive_threshold))),s}async resetConsumer(e=0){var i,o;(i=this.consumer)==null||i.delete().catch(()=>{}),e=e===0?1:e,this.cursor.deliver_seq=0;const t=this.getConsumerOpts(e);t.max_deliver=1,t.mem_storage=!0;const s=Eo();let n;for(let a=0;;a++)try{n=await this.api.add(this.stream,t),(o=this.iter)==null||o.notify(bt.OrderedConsumerRecreated,n.name);break}catch(u){if(e===0&&a>=30)throw u;await Jt(s.backoff(a+1))}return n}internalHandler(e){return t=>{var n;if(this.serial!==e)return;const s=t.info.deliverySequence;if(s!==this.cursor.deliver_seq+1){this.reset(this.opts);return}this.cursor.deliver_seq=s,this.cursor.stream_seq=t.info.streamSequence,this.userCallback?this.userCallback(t):(n=this.iter)==null||n.push(t)}}async reset(e={max_messages:100,expires:3e4},t=!1){this.currentConsumer=await this.resetConsumer(this.cursor.stream_seq+1),this.iter===null&&(this.iter=new Ci),this.consumer=new Fo(this.api,this.currentConsumer);const s=e;s.callback=this.internalHandler(this.serial);let n=null;if(this.type===xe.Fetch&&t)n=await this.consumer.fetch(e);else if(this.type===xe.Consume)n=await this.consumer.consume(e);else return Promise.reject("reset called with unset consumer type");const i=n;return i.forOrderedConsumer=!0,i.resetHandler=()=>{this.reset(this.opts)},this.iter.setSource(i),this.iter}consume(e={max_messages:100,expires:3e4}){if(this.type===xe.Fetch)return Promise.reject(new Error("ordered consumer initialized as fetch"));if(this.type===xe.Consume)return Promise.reject(new Error("ordered consumer doesn't support concurrent consume"));const{callback:t}=e;return t&&(this.userCallback=t),this.type=xe.Consume,this.opts=e,this.reset(e)}fetch(e={max_messages:100,expires:3e4}){var s;if(this.type===xe.Consume)return Promise.reject(new Error("ordered consumer already initialized as consume"));if(((s=this.iter)==null?void 0:s.done)===!1)return Promise.reject(new Error("ordered consumer doesn't support concurrent fetch"));const{callback:t}=e;return t&&(this.userCallback=t),this.type=xe.Fetch,this.opts=e,this.iter=new Ci,this.reset(e,!0)}async next(e={expires:3e4}){const t=B(),s=e;return s.max_messages=1,s.callback=i=>{this.userCallback=null,t.resolve(i)},(await this.fetch(s)).iterClosed.then(()=>{t.resolve(null)}).catch(i=>{t.reject(i)}),t}delete(){return this.currentConsumer?this.api.delete(this.stream,this.currentConsumer.name).then(e=>Promise.resolve(e)).catch(e=>Promise.reject(e)).finally(()=>{this.currentConsumer=null}):Promise.resolve(!1)}async info(e){return this.currentConsumer==null?(this.currentConsumer=await this.resetConsumer(this.serial),Promise.resolve(this.currentConsumer)):e&&this.currentConsumer?Promise.resolve(this.currentConsumer):this.api.info(this.stream,this.currentConsumer.name)}}function ur(r){if(r===void 0)return;const{domain:e}=r;if(e===void 0)return r;const t=Object.assign({},r);if(delete t.domain,e==="")return t;if(t.external)throw new Error("domain and external are both set");return t.external={api:`$JS.${e}.API`},t}var je;const sn="OBJ_";class Lo{constructor(e){c(this,"api");c(this,"notified");this.api=e,this.notified=!1}checkVersion(){const e=this.api.nc.features.get(L.JS_SIMPLIFICATION);return e.ok?Promise.resolve():Promise.reject(new Error(`consumers framework is only supported on servers ${e.min} or better`))}async get(e,t={}){return typeof t=="object"?this.ordered(e,t):(await this.checkVersion(),this.api.info(e,t).then(s=>s.config.deliver_subject!==void 0?Promise.reject(new Error("push consumer not supported")):new Fo(this.api,s)).catch(s=>Promise.reject(s)))}async ordered(e,t){await this.checkVersion();const s=this.api;return new nn(s.nc,s.opts).info(e).then(i=>Promise.resolve(new nh(this.api,e,t))).catch(i=>Promise.reject(i))}}class Ur{constructor(e,t){c(this,"api");c(this,"_info");this.api=e,this._info=t}get name(){return this._info.config.name}alternates(){return this.info().then(e=>e.alternates?e.alternates:[])}async best(){if(await this.info(),this._info.alternates){const e=await this.api.info(this._info.alternates[0].name);return new Ur(this.api,e)}else return this}info(e=!1,t){return e?Promise.resolve(this._info):this.api.info(this.name,t).then(s=>(this._info=s,this._info))}getConsumer(e){return new Lo(new tn(this.api.nc,this.api.opts)).get(this.name,e)}getMessage(e){return this.api.getMessage(this.name,e)}deleteMessage(e,t){return this.api.deleteMessage(this.name,e,t)}}function Do(){return{key:{encode(r){return r},decode(r){return r}},value:{encode(r){return r},decode(r){return r}}}}function ih(){return{replicas:1,history:1,timeout:2e3,maxBucketSize:-1,maxValueSize:-1,codec:Do(),storage:Fs.File}}const Pr="KV-Operation",ki="$KV",oh=/^[-/=.\w]+$/,ah=/^[-/=.>*\w]+$/,ch=/^[-\w]+$/;function uh(r){if(r.startsWith(".")||r.endsWith(".")||!oh.test(r))throw new Error(`invalid key: ${r}`)}function lh(r){if(r.startsWith(".")||r.endsWith(".")||!ah.test(r))throw new Error(`invalid key: ${r}`)}function hh(r){if(r.startsWith(".")||r.endsWith("."))throw new Error(`invalid key: ${r}`);const e=r.split(".");let t=!1;for(let s=0;s<e.length;s++)switch(e[s]){case"*":t=!0;break;case">":if(s!==e.length-1)throw new Error(`invalid key: ${r}`);t=!0;break}return t}function mr(r){if(!ch.test(r))throw new Error(`invalid bucket name: ${r}`)}(function(r){r.MsgIdHdr="Nats-Msg-Id",r.ExpectedStreamHdr="Nats-Expected-Stream",r.ExpectedLastSeqHdr="Nats-Expected-Last-Sequence",r.ExpectedLastMsgIdHdr="Nats-Expected-Last-Msg-Id",r.ExpectedLastSubjectSequenceHdr="Nats-Expected-Last-Subject-Sequence"})(je||(je={}));class Lt{constructor(e,t,s){c(this,"js");c(this,"jsm");c(this,"stream");c(this,"bucket");c(this,"direct");c(this,"codec");c(this,"prefix");c(this,"editPrefix");c(this,"useJsPrefix");c(this,"_prefixLen");c(this,"validateKey",uh);c(this,"validateSearchKey",lh);c(this,"hasWildcards",hh);mr(e),this.js=t,this.jsm=s,this.bucket=e,this.prefix=ki,this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create(e,t,s={}){mr(t);const n=await e.jetstreamManager(),i=new Lt(t,e,n);return await i.init(s),i}static async bind(e,t,s={}){const n=await e.jetstreamManager(),i=await n.streams.info(`${he}${t}`);mr(i.config.name);const o=new Lt(t,e,n);return Object.assign(o,i),o.codec=s.codec||Do(),o.direct=i.config.allow_direct??!1,o.initializePrefixes(i),o}async init(e={}){const t=Object.assign(ih(),e);this.codec=t.codec;const s={};this.stream=s.name=e.streamName??this.bucketName(),s.retention=$s.Limits,s.max_msgs_per_subject=t.history,t.maxBucketSize&&(t.max_bytes=t.maxBucketSize),t.max_bytes&&(s.max_bytes=t.max_bytes),s.max_msg_size=t.maxValueSize,s.storage=t.storage;const n=e.placementCluster??"";if(n&&(e.placement={},e.placement.cluster=n,e.placement.tags=[]),e.placement&&(s.placement=e.placement),e.republish&&(s.republish=e.republish),e.description&&(s.description=e.description),e.mirror){const g=Object.assign({},e.mirror);g.name.startsWith(he)||(g.name=`${he}${g.name}`),s.mirror=g,s.mirror_direct=!0}else if(e.sources){const g=e.sources.map(b=>{const w=Object.assign({},b);w.name.startsWith(he)||(w.name=`${he}${w.name}`)});s.sources=g}else s.subjects=[this.subjectForBucket()];e.metadata&&(s.metadata=e.metadata),typeof e.compression=="boolean"&&(s.compression=e.compression?He.S2:He.None);const i=this.js.nc,o=i.getServerVersion(),a=o?Ns(o,We("2.7.2"))>=0:!1;s.discard=a?$t.New:$t.Old;const{ok:u,min:h}=i.features.get(L.JS_ALLOW_DIRECT);if(!u&&e.allow_direct===!0){const g=o?`${o.major}.${o.minor}.${o.micro}`:"unknown";return Promise.reject(new Error(`allow_direct is not available on server version ${g} - requires ${h}`))}e.allow_direct=typeof e.allow_direct=="boolean"?e.allow_direct:u,s.allow_direct=e.allow_direct,this.direct=s.allow_direct,s.num_replicas=t.replicas,t.ttl&&(s.max_age=q(t.ttl)),s.allow_rollup_hdrs=!0;let p;try{p=await this.jsm.streams.info(s.name),!p.config.allow_direct&&this.direct===!0&&(this.direct=!1)}catch(g){if(g.message==="stream not found")p=await this.jsm.streams.add(s);else throw g}this.initializePrefixes(p)}initializePrefixes(e){this._prefixLen=0,this.prefix=`$KV.${this.bucket}`,this.useJsPrefix=this.js.apiPrefix!=="$JS.API";const{mirror:t}=e.config;if(t){let s=t.name;if(s.startsWith(he)&&(s=s.substring(he.length)),t.external&&t.external.api!==""){const n=t.name.substring(he.length);this.useJsPrefix=!1,this.prefix=`$KV.${n}`,this.editPrefix=`${t.external.api}.$KV.${s}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${he}${this.bucket}`}subjectForBucket(){return`${this.prefix}.${this.bucket}.>`}subjectForKey(e,t=!1){const s=[];return t?(this.useJsPrefix&&s.push(this.js.apiPrefix),this.editPrefix!==""?s.push(this.editPrefix):s.push(this.prefix)):this.prefix&&s.push(this.prefix),s.push(e),s.join(".")}fullKeyName(e){return this.prefix!==""?`${this.prefix}.${e}`:`${ki}.${this.bucket}.${e}`}get prefixLen(){return this._prefixLen===0&&(this._prefixLen=this.prefix.length+1),this._prefixLen}encodeKey(e){const t=[];for(const s of e.split("."))switch(s){case">":case"*":t.push(s);break;default:t.push(this.codec.key.encode(s));break}return t.join(".")}decodeKey(e){const t=[];for(const s of e.split("."))switch(s){case">":case"*":t.push(s);break;default:t.push(this.codec.key.decode(s));break}return t.join(".")}close(){return Promise.resolve()}dataLen(e,t){const s=t&&t.get(Q.MessageSizeHdr)||"";return s!==""?parseInt(s,10):e.length}smToEntry(e){return new mh(this.bucket,this.prefixLen,e)}jmToEntry(e){const t=this.decodeKey(e.subject.substring(this.prefixLen));return new bh(this.bucket,t,e)}async create(e,t){var i;let s;try{const o=await this.put(e,t,{previousSeq:0});return Promise.resolve(o)}catch(o){if(s=o,((i=o==null?void 0:o.api_error)==null?void 0:i.err_code)!==10071)return Promise.reject(o)}let n=0;try{const o=await this.get(e);return(o==null?void 0:o.operation)==="DEL"||(o==null?void 0:o.operation)==="PURGE"?(n=o!==null?o.revision:0,this.update(e,t,n)):Promise.reject(s)}catch(o){return Promise.reject(o)}}update(e,t,s){if(s<=0)throw new Error("version must be greater than 0");return this.put(e,t,{previousSeq:s})}async put(e,t,s={}){var o,a;const n=this.encodeKey(e);this.validateKey(n);const i={};if(s.previousSeq!==void 0){const u=Ne();i.headers=u,u.set(je.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`)}try{return(await this.js.publish(this.subjectForKey(n,!0),t,i)).seq}catch(u){const h=u;return h.isJetStreamError()?(h.message=(o=h.api_error)==null?void 0:o.description,h.code=`${(a=h.api_error)==null?void 0:a.code}`,Promise.reject(h)):Promise.reject(u)}}async get(e,t){const s=this.encodeKey(e);this.validateKey(s);let n={last_by_subj:this.subjectForKey(s)};t&&t.revision>0&&(n={seq:t.revision});let i;try{this.direct?i=await this.jsm.direct.getMessage(this.bucketName(),n):i=await this.jsm.streams.getMessage(this.bucketName(),n);const o=this.smToEntry(i);return o.key!==s?null:o}catch(o){if(o.code===P.JetStream404NoMessages)return null;throw o}}purge(e){return this._deleteOrPurge(e,"PURGE")}delete(e){return this._deleteOrPurge(e,"DEL")}async purgeDeletes(e=30*60*1e3){const t=B(),s=[],n=await this.watch({key:">",initializedFn:()=>{t.resolve()}});(async()=>{for await(const u of n)(u.operation==="DEL"||u.operation==="PURGE")&&s.push(u)})().then(),await t,n.stop();const i=Date.now()-e,o=s.map(u=>{const h=this.subjectForKey(u.key);return u.created.getTime()>=i?this.jsm.streams.purge(this.stream,{filter:h,keep:1}):this.jsm.streams.purge(this.stream,{filter:h,keep:0})}),a=await Promise.all(o);return a.unshift({success:!0,purged:0}),a.reduce((u,h)=>(u.purged+=h.purged,u))}async _deleteOrPurge(e,t){if(!this.hasWildcards(e))return this._doDeleteOrPurge(e,t);const s=await this.keys(e),n=[];for await(const i of s)n.push(this._doDeleteOrPurge(i,t)),n.length===100&&(await Promise.all(n),n.length=0);n.length>0&&await Promise.all(n)}async _doDeleteOrPurge(e,t){const s=this.encodeKey(e);this.validateKey(s);const n=Ne();n.set(Pr,t),t==="PURGE"&&n.set(Q.RollupHdr,Q.RollupValueSubject),await this.js.publish(this.subjectForKey(s,!0),se,{headers:n})}_buildCC(e,t,s={}){const n=this.encodeKey(e);this.validateSearchKey(e);let i=H.LastPerSubject;return t===_e.AllHistory&&(i=H.All),t===_e.UpdatesOnly&&(i=H.New),Object.assign({deliver_policy:i,ack_policy:V.None,filter_subject:this.fullKeyName(n),flow_control:!0,idle_heartbeat:q(5*1e3)},s)}remove(e){return this.purge(e)}async history(e={}){const t=e.key??">",s=new Y,n={};n.headers_only=e.headers_only||!1;let i;i=()=>{s.stop()};let o=0;const a=this._buildCC(t,_e.AllHistory,n),u=a.filter_subject,h=Be(a);h.bindStream(this.stream),h.orderedConsumer(),h.callback((g,b)=>{if(g){s.stop(g);return}if(b){const w=this.jmToEntry(b);s.push(w),s.received++,(i&&o>0&&s.received>=o||b.info.pending===0)&&(s.push(i),i=void 0)}});const p=await this.js.subscribe(u,h);if(i){const{info:{last:g}}=p,b=g.num_pending+g.delivered.consumer_seq;if(b===0||s.received>=b)try{i()}catch(w){s.stop(w)}finally{i=void 0}else o=b}return s._data=p,s.iterClosed.then(()=>{p.unsubscribe()}),p.closed.then(()=>{s.stop()}).catch(g=>{s.stop(g)}),s}async watch(e={}){const t=e.key??">",s=new Y,n={};n.headers_only=e.headers_only||!1;let i=_e.LastValue;e.include===_e.AllHistory?i=_e.AllHistory:e.include===_e.UpdatesOnly&&(i=_e.UpdatesOnly);const o=e.ignoreDeletes===!0;let a=e.initializedFn,u=0;const h=this._buildCC(t,i,n),p=h.filter_subject,g=Be(h);g.bindStream(this.stream),g.orderedConsumer(),g.callback((w,A)=>{if(w){s.stop(w);return}if(A){const k=this.jmToEntry(A);if(o&&k.operation==="DEL")return;s.push(k),s.received++,a&&(u>0&&s.received>=u||A.info.pending===0)&&(s.push(a),a=void 0)}});const b=await this.js.subscribe(p,g);if(a){const{info:{last:w}}=b,A=w.num_pending+w.delivered.consumer_seq;if(A===0||s.received>=A)try{a()}catch(k){s.stop(k)}finally{a=void 0}else u=A}return s._data=b,s.iterClosed.then(()=>{b.unsubscribe()}),b.closed.then(()=>{s.stop()}).catch(w=>{s.stop(w)}),s}async keys(e=">"){const t=new Y,s=this._buildCC(e,_e.LastValue,{headers_only:!0}),n=s.filter_subject,i=Be(s);i.bindStream(this.stream),i.orderedConsumer();const o=await this.js.subscribe(n,i);return(async()=>{var u;for await(const h of o){const p=(u=h.headers)==null?void 0:u.get(Pr);if(p!=="DEL"&&p!=="PURGE"){const g=this.decodeKey(h.subject.substring(this.prefixLen));t.push(g)}h.info.pending===0&&o.unsubscribe()}})().then(()=>{t.stop()}).catch(u=>{t.stop(u)}),o.info.last.num_pending===0&&o.unsubscribe(),t}purgeBucket(e){return this.jsm.streams.purge(this.bucketName(),e)}destroy(){return this.jsm.streams.delete(this.bucketName())}async status(){var i;const t=((i=this.js.nc.info)==null?void 0:i.cluster)??"",s=this.bucketName(),n=await this.jsm.streams.info(s);return new qo(n,t)}}class qo{constructor(e,t=""){c(this,"si");c(this,"cluster");this.si=e,this.cluster=t}get bucket(){return this.si.config.name.startsWith(he)?this.si.config.name.substring(he.length):this.si.config.name}get values(){return this.si.state.messages}get history(){return this.si.config.max_msgs_per_subject}get ttl(){return en(this.si.config.max_age)}get bucket_location(){return this.cluster}get backingStore(){return this.si.config.storage}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get description(){return this.si.config.description??""}get maxBucketSize(){return this.si.config.max_bytes}get maxValueSize(){return this.si.config.max_msg_size}get max_bytes(){return this.si.config.max_bytes}get placement(){return this.si.config.placement||{cluster:"",tags:[]}}get placementCluster(){var e;return((e=this.si.config.placement)==null?void 0:e.cluster)??""}get republish(){return this.si.config.republish??{src:"",dest:""}}get streamInfo(){return this.si}get size(){return this.si.state.bytes}get metadata(){return this.si.config.metadata??{}}get compression(){return this.si.config.compression?this.si.config.compression!==He.None:!1}}const Ri="SHA-256=";function fh(r){return mr(r),`${sn}${r}`}function dh(r){return r.startsWith(sn)?r.substring(4):r}class Ls{constructor(e){c(this,"si");c(this,"backingStore");this.si=e,this.backingStore="JetStream"}get bucket(){return dh(this.si.config.name)}get description(){return this.si.config.description??""}get ttl(){return this.si.config.max_age}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get sealed(){return this.si.config.sealed}get size(){return this.si.state.bytes}get streamInfo(){return this.si}get metadata(){return this.si.config.metadata}get compression(){return this.si.config.compression?this.si.config.compression!==He.None:!1}}class nn extends zt{constructor(e,t){super(e,t)}checkStreamConfigVersions(e){const t=this.nc;if(e.metadata){const{min:n,ok:i}=t.features.get(L.JS_STREAM_CONSUMER_METADATA);if(!i)throw new Error(`stream 'metadata' requires server ${n}`)}if(e.first_seq){const{min:n,ok:i}=t.features.get(L.JS_STREAM_FIRST_SEQ);if(!i)throw new Error(`stream 'first_seq' requires server ${n}`)}if(e.subject_transform){const{min:n,ok:i}=t.features.get(L.JS_STREAM_SUBJECT_TRANSFORM);if(!i)throw new Error(`stream 'subject_transform' requires server ${n}`)}if(e.compression){const{min:n,ok:i}=t.features.get(L.JS_STREAM_COMPRESSION);if(!i)throw new Error(`stream 'compression' requires server ${n}`)}if(e.consumer_limits){const{min:n,ok:i}=t.features.get(L.JS_DEFAULT_CONSUMER_LIMITS);if(!i)throw new Error(`stream 'consumer_limits' requires server ${n}`)}function s(n,i){var a;if((((a=i.subject_transforms)==null?void 0:a.length)||0)>0){const{min:u,ok:h}=t.features.get(L.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!h)throw new Error(`${n} 'subject_transforms' requires server ${u}`)}}e.sources&&e.sources.forEach(n=>{s("stream sources",n)}),e.mirror&&s("stream mirror",e.mirror)}async add(e={}){var n;this.checkStreamConfigVersions(e),te(e.name),e.mirror=ur(e.mirror),e.sources=(n=e.sources)==null?void 0:n.map(ur);const s=await this._request(`${this.prefix}.STREAM.CREATE.${e.name}`,e);return this._fixInfo(s),s}async delete(e){return te(e),(await this._request(`${this.prefix}.STREAM.DELETE.${e}`)).success}async update(e,t={}){var a;if(typeof e=="object"){const u=e;e=u.name,t=u,console.trace("\x1B[33m >> streams.update(config: StreamConfig) api changed to streams.update(name: string, config: StreamUpdateConfig) - this shim will be removed - update your code. \x1B[0m")}this.checkStreamConfigVersions(t),te(e);const s=await this.info(e),n=Object.assign(s.config,t);n.mirror=ur(n.mirror),n.sources=(a=n.sources)==null?void 0:a.map(ur);const o=await this._request(`${this.prefix}.STREAM.UPDATE.${e}`,n);return this._fixInfo(o),o}async info(e,t){te(e);const s=`${this.prefix}.STREAM.INFO.${e}`;let i=await this._request(s,t),{total:o,limit:a}=i,u=i.state.subjects?Object.getOwnPropertyNames(i.state.subjects).length:1;if(o&&o>u){const h=[i],p=t||{};let g=0;for(;o>u;){g++,p.offset=a*g;const w=await this._request(s,p);o=w.total,h.push(w);const A=Object.getOwnPropertyNames(w.state.subjects).length;if(u+=A,A<a)break}let b={};for(let w=0;w<h.length;w++)i=h[w],i.state.subjects&&(b=Object.assign(b,i.state.subjects));i.offset=0,i.total=0,i.limit=0,i.state.subjects=b}return this._fixInfo(i),i}list(e=""){const t=e!=null&&e.length?{subject:e}:{},s=i=>{const o=i;return o.streams.forEach(a=>{this._fixInfo(a)}),o.streams},n=`${this.prefix}.STREAM.LIST`;return new kt(n,s,this,t)}_fixInfo(e){e.config.sealed=e.config.sealed||!1,e.config.deny_delete=e.config.deny_delete||!1,e.config.deny_purge=e.config.deny_purge||!1,e.config.allow_rollup_hdrs=e.config.allow_rollup_hdrs||!1}async purge(e,t){if(t){const{keep:n,seq:i}=t;if(typeof n=="number"&&typeof i=="number")throw new Error("can specify one of keep or seq")}return te(e),await this._request(`${this.prefix}.STREAM.PURGE.${e}`,t)}async deleteMessage(e,t,s=!0){te(e);const n={seq:t};return s||(n.no_erase=!0),(await this._request(`${this.prefix}.STREAM.MSG.DELETE.${e}`,n)).success}async getMessage(e,t){te(e);const n=await this._request(`${this.prefix}.STREAM.MSG.GET.${e}`,t);return new Bo(n)}find(e){return this.findStream(e)}listKvs(){const e=s=>{var u;const i=s.streams.filter(h=>h.config.name.startsWith(he));i.forEach(h=>{this._fixInfo(h)});let o="";return i.length&&(o=((u=this.nc.info)==null?void 0:u.cluster)??""),i.map(h=>new qo(h,o))},t=`${this.prefix}.STREAM.LIST`;return new kt(t,e,this)}listObjectStores(){const e=s=>{const i=s.streams.filter(a=>a.config.name.startsWith(sn));return i.forEach(a=>{this._fixInfo(a)}),i.map(a=>new Ls(a))},t=`${this.prefix}.STREAM.LIST`;return new kt(t,e,this)}names(e=""){const t=e!=null&&e.length?{subject:e}:{},s=i=>i.streams,n=`${this.prefix}.STREAM.NAMES`;return new kt(n,s,this,t)}async get(e){const t=await this.info(e);return Promise.resolve(new Ur(this,t))}}class Bo{constructor(e){c(this,"_header");c(this,"smr");this.smr=e}get subject(){return this.smr.message.subject}get seq(){return this.smr.message.seq}get timestamp(){return this.smr.message.time}get time(){return new Date(Date.parse(this.timestamp))}get data(){return this.smr.message.data?this._parse(this.smr.message.data):se}get header(){if(!this._header)if(this.smr.message.hdrs){const e=this._parse(this.smr.message.hdrs);this._header=qe.decode(e)}else this._header=Ne();return this._header}_parse(e){const t=atob(e),s=t.length,n=new Uint8Array(s);for(let i=0;i<s;i++)n[i]=t.charCodeAt(i);return n}json(e){return ye(e).decode(this.data)}string(){return ae.decode(this.data)}}c(Bo,"jc");class ph{constructor(e){c(this,"api");this.api=e}get(e){return this.api.info(e).then(t=>new Ur(this.api,t))}}class mh{constructor(e,t,s){c(this,"bucket");c(this,"sm");c(this,"prefixLen");this.bucket=e,this.prefixLen=t,this.sm=s}get key(){return this.sm.subject.substring(this.prefixLen)}get value(){return this.sm.data}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){return this.sm.header.get(Pr)||"PUT"}get length(){const e=this.sm.header.get(Q.MessageSizeHdr)||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class bh{constructor(e,t,s){c(this,"bucket");c(this,"key");c(this,"sm");this.bucket=e,this.key=t,this.sm=s}get value(){return this.sm.data}get created(){return new Date(en(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var e;return((e=this.sm.headers)==null?void 0:e.get(Pr))||"PUT"}get delta(){return this.sm.info.pending}get length(){var t;const e=((t=this.sm.headers)==null?void 0:t.get(Q.MessageSizeHdr))||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class xs{constructor(e){c(this,"info");c(this,"hdrs");this.info=e}get name(){return this.info.name}get description(){return this.info.description??""}get headers(){return this.hdrs||(this.hdrs=qe.fromRecord(this.info.headers||{})),this.hdrs}get options(){return this.info.options}get bucket(){return this.info.bucket}get chunks(){return this.info.chunks}get deleted(){return this.info.deleted??!1}get digest(){return this.info.digest}get mtime(){return this.info.mtime}get nuid(){return this.info.nuid}get size(){return this.info.size}get revision(){return this.info.revision}get metadata(){return this.info.metadata||{}}isLink(){var e,t;return((e=this.info.options)==null?void 0:e.link)!==void 0&&((t=this.info.options)==null?void 0:t.link)!==null}}function ji(r){const e={name:r.name,description:r.description??"",options:r.options,metadata:r.metadata};if(r.headers){const t=r.headers;e.headers=t.toRecord()}return e}function gh(){return new ReadableStream({pull(r){r.enqueue(new Uint8Array(0)),r.close()}})}class Ut{constructor(e,t,s){c(this,"jsm");c(this,"js");c(this,"stream");c(this,"name");this.name=e,this.jsm=t,this.js=s}_checkNotEmpty(e){return!e||e.length===0?{name:e,error:new Error("name cannot be empty")}:{name:e}}async info(e){const t=await this.rawInfo(e);return t?new xs(t):null}async list(){const e=[],t=await this.watch({ignoreDeletes:!0,includeHistory:!0});for await(const s of t){if(s===null)break;e.push(s)}return Promise.resolve(e)}async rawInfo(e){const{name:t,error:s}=this._checkNotEmpty(e);if(s)return Promise.reject(s);const n=this._metaSubject(t);try{const i=await this.jsm.streams.getMessage(this.stream,{last_by_subj:n}),a=ye().decode(i.data);return a.revision=i.seq,a}catch(i){return i.code==="404"?null:Promise.reject(i)}}async _si(e){try{return await this.jsm.streams.info(this.stream,e)}catch(t){return t.code==="404"?null:Promise.reject(t)}}async seal(){let e=await this._si();return e===null?Promise.reject(new Error("object store not found")):(e.config.sealed=!0,e=await this.jsm.streams.update(this.stream,e.config),Promise.resolve(new Ls(e)))}async status(e){const t=await this._si(e);return t===null?Promise.reject(new Error("object store not found")):Promise.resolve(new Ls(t))}destroy(){return this.jsm.streams.delete(this.stream)}async _put(e,t,s){var J;const n=this.js.getOptions();s=s||{timeout:n.timeout},s.timeout=s.timeout||n.timeout,s.previousRevision=s.previousRevision??void 0;const{timeout:i,previousRevision:o}=s,a=this.js.nc.info,u=(a==null?void 0:a.max_payload)||1024;e=e||{},e.options=e.options||{};let h=((J=e.options)==null?void 0:J.max_chunk_size)||128*1024;h=h>u?u:h,e.options.max_chunk_size=h;const p=await this.info(e.name),{name:g,error:b}=this._checkNotEmpty(e.name);if(b)return Promise.reject(b);const w=Ht.next(),A=this._chunkSubject(w),k=this._metaSubject(g),R=Object.assign({bucket:this.name,nuid:w,size:0,chunks:0},ji(e)),U=B(),N=[],M=new pt;try{const T=t?t.getReader():null,Me=new Pi;for(;;){const{done:Xe,value:de}=T?await T.read():{done:!0,value:void 0};if(Xe){if(M.size()>0){const X=M.drain();Me.update(X),R.chunks++,R.size+=X.length,N.push(this.js.publish(A,X,{timeout:i}))}await Promise.all(N),N.length=0,R.mtime=new Date().toISOString();const ee=Me.digest("base64"),Ae=ee.length%3,Ue=Ae>0?"=".repeat(Ae):"";R.digest=`${Ri}${ee}${Ue}`,R.deleted=!1;const z=Ne();typeof o=="number"&&z.set(je.ExpectedLastSubjectSequenceHdr,`${o}`),z.set(Q.RollupHdr,Q.RollupValueSubject);const ue=await this.js.publish(k,ye().encode(R),{headers:z,timeout:i});if(R.revision=ue.seq,p)try{await this.jsm.streams.purge(this.stream,{filter:`$O.${this.name}.C.${p.nuid}`})}catch{}U.resolve(new xs(R));break}if(de)for(M.fill(de);M.size()>h;){R.chunks++,R.size+=h;const ee=M.drain(e.options.max_chunk_size);Me.update(ee),N.push(this.js.publish(A,ee,{timeout:i}))}}}catch(T){await this.jsm.streams.purge(this.stream,{filter:A}),U.reject(T)}return U}putBlob(e,t,s){function n(i){return new ReadableStream({pull(o){o.enqueue(i),o.close()}})}return t===null&&(t=new Uint8Array(0)),this.put(e,n(t),s)}put(e,t,s){var n;return(n=e==null?void 0:e.options)!=null&&n.link?Promise.reject(new Error("link cannot be set when putting the object in bucket")):this._put(e,t,s)}async getBlob(e){async function t(i){const o=new pt,a=i.getReader();for(;;){const{done:u,value:h}=await a.read();if(u)return o.drain();h&&h.length&&o.fill(h)}}const s=await this.get(e);if(s===null)return Promise.resolve(null);const n=await Promise.all([s.error,t(s.data)]);return n[0]?Promise.reject(n[0]):Promise.resolve(n[1])}async get(e){const t=await this.rawInfo(e);if(t===null||t.deleted)return Promise.resolve(null);if(t.options&&t.options.link){const p=t.options.link.name||"";if(p==="")throw new Error("link is a bucket");return(t.options.link.bucket!==this.name?await Ut.create(this.js,t.options.link.bucket):this).get(p)}const s=B(),n={info:new xs(t),error:s};if(t.size===0)return n.data=gh(),s.resolve(null),Promise.resolve(n);let i;const o=Be();o.orderedConsumer();const a=new Pi,u=`$O.${this.name}.C.${t.nuid}`,h=await this.js.subscribe(u,o);return(async()=>{for await(const p of h)if(p.data.length>0&&(a.update(p.data),i.enqueue(p.data)),p.info.pending===0){const g=a.digest("base64"),b=g.length%3,w=b>0?"=".repeat(b):"",A=`${Ri}${g}${w}`;A!==t.digest?i.error(new Error(`received a corrupt object, digests do not match received: ${t.digest} calculated ${A}`)):i.close(),h.unsubscribe()}})().then(()=>{s.resolve()}).catch(p=>{i.error(p),s.reject(p)}),n.data=new ReadableStream({start(p){i=p},cancel(){h.unsubscribe()}}),n}linkStore(e,t){if(!(t instanceof Ut))return Promise.reject("bucket required");const s=t,{name:n,error:i}=this._checkNotEmpty(e);if(i)return Promise.reject(i);const o={name:n,options:{link:{bucket:s.name}}};return this._put(o,null)}async link(e,t){const{name:s,error:n}=this._checkNotEmpty(e);if(n)return Promise.reject(n);if(t.deleted)return Promise.reject(new Error("src object is deleted"));if(t.isLink())return Promise.reject(new Error("src object is a link"));const i=await this.rawInfo(e);if(i!==null&&!i.deleted)return Promise.reject(new Error("an object already exists with that name"));const o={bucket:t.bucket,name:t.name},a={name:s,bucket:t.bucket,options:{link:o}};await this.js.publish(this._metaSubject(e),JSON.stringify(a));const u=await this.info(e);return Promise.resolve(u)}async delete(e){const t=await this.rawInfo(e);if(t===null)return Promise.resolve({purged:0,success:!1});t.deleted=!0,t.size=0,t.chunks=0,t.digest="";const s=ye(),n=Ne();return n.set(Q.RollupHdr,Q.RollupValueSubject),await this.js.publish(this._metaSubject(t.name),s.encode(t),{headers:n}),this.jsm.streams.purge(this.stream,{filter:this._chunkSubject(t.nuid)})}async update(e,t={}){const s=await this.rawInfo(e);if(s===null)return Promise.reject(new Error("object not found"));if(s.deleted)return Promise.reject(new Error("cannot update meta for a deleted object"));t.name=t.name??s.name;const{name:n,error:i}=this._checkNotEmpty(t.name);if(i)return Promise.reject(i);if(e!==t.name){const u=await this.info(t.name);if(u&&!u.deleted)return Promise.reject(new Error("an object already exists with that name"))}t.name=n;const o=Object.assign({},s,ji(t)),a=await this.js.publish(this._metaSubject(o.name),JSON.stringify(o));return e!==t.name&&await this.jsm.streams.purge(this.stream,{filter:this._metaSubject(e)}),Promise.resolve(a)}async watch(e={}){e.includeHistory=e.includeHistory??!1,e.ignoreDeletes=e.ignoreDeletes??!1;let t=!1;const s=new Y,n=this._metaSubjectAll();try{await this.jsm.streams.getMessage(this.stream,{last_by_subj:n})}catch(u){u.code==="404"?(s.push(null),t=!0):s.stop(u)}const i=ye(),o=Be();o.orderedConsumer(),e.includeHistory?o.deliverLastPerSubject():(t=!0,o.deliverNew()),o.callback((u,h)=>{var p;if(u){s.stop(u);return}if(h!==null){const g=i.decode(h.data);g.deleted&&e.ignoreDeletes===!0||s.push(g),((p=h.info)==null?void 0:p.pending)===0&&!t&&(t=!0,s.push(null))}});const a=await this.js.subscribe(n,o);return s._data=a,s.iterClosed.then(()=>{a.unsubscribe()}),a.closed.then(()=>{s.stop()}).catch(u=>{s.stop(u)}),s}_chunkSubject(e){return`$O.${this.name}.C.${e}`}_metaSubject(e){return`$O.${this.name}.M.${Nt.encode(e)}`}_metaSubjectAll(){return`$O.${this.name}.M.>`}async init(e={}){try{this.stream=fh(this.name)}catch(n){return Promise.reject(n)}const t=(e==null?void 0:e.ttl)||0;delete e.ttl;const s=Object.assign({max_age:t},e);s.name=this.stream,s.allow_direct=!0,s.allow_rollup_hdrs=!0,s.discard=$t.New,s.subjects=[`$O.${this.name}.C.>`,`$O.${this.name}.M.>`],e.placement&&(s.placement=e.placement),e.metadata&&(s.metadata=e.metadata),typeof e.compression=="boolean"&&(s.compression=e.compression?He.S2:He.None);try{await this.jsm.streams.info(s.name)}catch(n){n.message==="stream not found"&&await this.jsm.streams.add(s)}}static async create(e,t,s={}){const n=await e.jetstreamManager(),i=new Ut(t,n,e);return await i.init(s),Promise.resolve(i)}}class _h{constructor(e){c(this,"js");c(this,"jsm");this.js=e}kv(e,t={}){const s=this.js,{ok:n,min:i}=s.nc.features.get(L.JS_KV);return n?t.bindOnly?Lt.bind(this.js,e):Lt.create(this.js,e,t):Promise.reject(new Error(`kv is only supported on servers ${i} or better`))}os(e,t={}){var o;if(typeof((o=crypto==null?void 0:crypto.subtle)==null?void 0:o.digest)!="function")return Promise.reject(new Error("objectstore: unable to calculate hashes - crypto.subtle.digest with sha256 support is required"));const s=this.js,{ok:n,min:i}=s.nc.features.get(L.JS_OBJECTSTORE);return n?Ut.create(this.js,e,t):Promise.reject(new Error(`objectstore is only supported on servers ${i} or better`))}}class on extends zt{constructor(t,s){super(t,s);c(this,"consumers");c(this,"streams");c(this,"consumerAPI");c(this,"streamAPI");this.consumerAPI=new tn(t,s),this.streamAPI=new nn(t,s),this.consumers=new Lo(this.consumerAPI),this.streams=new ph(this.streamAPI)}jetstreamManager(t){const s=Object.assign({checkAPI:t},this.opts);return this.nc.jetstreamManager(s)}get apiPrefix(){return this.prefix}get views(){return new _h(this)}async publish(t,s=se,n){n=n||{},n.expect=n.expect||{};const i=(n==null?void 0:n.headers)||Ne();n&&(n.msgID&&i.set(je.MsgIdHdr,n.msgID),n.expect.lastMsgID&&i.set(je.ExpectedLastMsgIdHdr,n.expect.lastMsgID),n.expect.streamName&&i.set(je.ExpectedStreamHdr,n.expect.streamName),typeof n.expect.lastSequence=="number"&&i.set(je.ExpectedLastSeqHdr,`${n.expect.lastSequence}`),typeof n.expect.lastSubjectSequence=="number"&&i.set(je.ExpectedLastSubjectSequenceHdr,`${n.expect.lastSubjectSequence}`));const o=n.timeout||this.timeout,a={};o&&(a.timeout=o),n&&(a.headers=i);let{retries:u,retry_delay:h}=n;u=u||1,h=h||250;let p;for(let b=0;b<u;b++)try{p=await this.nc.request(t,s,a);break}catch(w){if(w.code==="503"&&b+1<u)await Jt(h);else throw w}const g=this.parseJsResponse(p);if(g.stream==="")throw j.errorForCode(P.JetStreamInvalidAck);return g.duplicate=g.duplicate?g.duplicate:!1,g}async pull(t,s,n=0){te(t),ut(s);let i=this.timeout;n>i&&(i=n),n=n<0?0:q(n);const o={batch:1,no_wait:n===0,expires:n},a=await this.nc.request(`${this.prefix}.CONSUMER.MSG.NEXT.${t}.${s}`,this.jc.encode(o),{noMux:!0,timeout:i}),u=lt(a);if(u)throw u;return Ft(a)}fetch(t,s,n={}){te(t),ut(s);let i=null;const o=(n.max_bytes??0)>0;let a=0;const u=o?n.max_bytes:0;let h=null;const p={};if(p.batch=n.batch||1,u){const N=this.nc.features.get(L.JS_PULL_MAX_BYTES);if(!N.ok)throw new Error(`max_bytes is only supported on servers ${N.min} or better`);p.max_bytes=u}p.no_wait=n.no_wait||!1,p.no_wait&&p.expires&&(p.expires=0);const g=n.expires||0;if(g&&(p.expires=q(g)),g===0&&p.no_wait===!1)throw new Error("expires or no_wait is required");const b=n.idle_heartbeat||0;b&&(p.idle_heartbeat=q(b),n.delay_heartbeat===!0&&(p.idle_heartbeat=q(b*4)));const w=new Y,A=p.batch;let k=0;w.protocolFilterFn=(N,M=!1)=>Us(N.msg)?(h==null||h.work(),!1):!0,w.dispatchedFn=N=>{if(N){if(o&&(a+=N.data.length),k++,i&&N.info.pending===0)return;(w.getPending()===1&&N.info.pending===0||A===k||u>0&&a>=u)&&w.stop()}};const R=Te(this.nc.options.inboxPrefix),U=this.nc.subscribe(R,{max:n.batch,callback:(N,M)=>{N===null&&(N=lt(M)),N!==null?(i&&(i.cancel(),i=null),Gu(N)?w.stop(Jo(N)===null?void 0:N):w.stop(N)):(h==null||h.work(),w.received++,w.push(Ft(M)))}});return g&&(i=dt(g),i.catch(()=>{U.isClosed()||(U.drain().catch(()=>{}),i=null),h&&h.cancel()})),(async()=>{try{b&&(h=new rn(b,N=>(w.push(()=>{w.err=new j(`${fe.IdleHeartbeatMissed}: ${N}`,P.JetStreamIdleHeartBeat)}),!0)))}catch{}await U.closed,i!==null&&(i.cancel(),i=null),h&&h.cancel(),w.stop()})().catch(),this.nc.publish(`${this.prefix}.CONSUMER.MSG.NEXT.${t}.${s}`,this.jc.encode(p),{reply:R}),w}async pullSubscribe(t,s=Be()){const n=await this._processOptions(t,s);if(n.ordered)throw new Error("pull subscribers cannot be be ordered");if(n.config.deliver_subject)throw new Error("consumer info specifies deliver_subject - pull consumers cannot have deliver_subject set");const i=n.config.ack_policy;if(i===V.None||i===V.All)throw new Error("ack policy for pull consumers must be explicit");const o=this._buildTypedSubscriptionOpts(n),a=new yh(this,n.deliver,o);a.info=n;try{await this._maybeCreateConsumer(n)}catch(u){throw a.unsubscribe(),u}return a}async subscribe(t,s=Be()){const n=await this._processOptions(t,s);if(!n.isBind&&!n.config.deliver_subject)throw new Error("push consumer requires deliver_subject");const i=this._buildTypedSubscriptionOpts(n),o=new Ho(this,n.deliver,i);o.info=n;try{await this._maybeCreateConsumer(n)}catch(a){throw o.unsubscribe(),a}return o._maybeSetupHbMonitoring(),o}async _processOptions(t,s=Be()){const n=Ei(s)?s.getOpts():s;if(n.isBind=Ei(s)?s.isBind:!1,n.flow_control={heartbeat_count:0,fc_count:0,consumer_restarts:0},n.ordered){if(n.ordered_consumer_sequence={stream_seq:0,delivery_seq:0},n.config.ack_policy!==V.NotSet&&n.config.ack_policy!==V.None)throw new j("ordered consumer: ack_policy can only be set to 'none'",P.ApiError);if(n.config.durable_name&&n.config.durable_name.length>0)throw new j("ordered consumer: durable_name cannot be set",P.ApiError);if(n.config.deliver_subject&&n.config.deliver_subject.length>0)throw new j("ordered consumer: deliver_subject cannot be set",P.ApiError);if(n.config.max_deliver!==void 0&&n.config.max_deliver>1)throw new j("ordered consumer: max_deliver cannot be set",P.ApiError);if(n.config.deliver_group&&n.config.deliver_group.length>0)throw new j("ordered consumer: deliver_group cannot be set",P.ApiError);n.config.deliver_subject=Te(this.nc.options.inboxPrefix),n.config.ack_policy=V.None,n.config.max_deliver=1,n.config.flow_control=!0,n.config.idle_heartbeat=n.config.idle_heartbeat||q(5e3),n.config.ack_wait=q(22*60*60*1e3),n.config.mem_storage=!0,n.config.num_replicas=1}if(n.config.ack_policy===V.NotSet&&(n.config.ack_policy=V.All),n.api=this,n.config=n.config||{},n.stream=n.stream?n.stream:await this.findStream(t),n.attached=!1,n.config.durable_name)try{const i=await this.consumerAPI.info(n.stream,n.config.durable_name);if(i){if(i.config.filter_subject&&i.config.filter_subject!==t)throw new Error("subject does not match consumer");const o=n.config.deliver_group??"";if(o===""&&i.push_bound===!0)throw new Error("duplicate subscription");const a=i.config.deliver_group??"";if(o!==a)throw a===""?new Error("durable requires no queue group"):new Error(`durable requires queue group '${a}'`);n.last=i,n.config=i.config,n.attached=!0,n.config.durable_name||(n.name=i.name)}}catch(i){if(i.code!=="404")throw i}return!n.attached&&n.config.filter_subject===void 0&&n.config.filter_subjects===void 0&&(n.config.filter_subject=t),n.deliver=n.config.deliver_subject||Te(this.nc.options.inboxPrefix),n}_buildTypedSubscriptionOpts(t){const s={};return s.adapter=wh(t.callbackFn===void 0),s.ingestionFilterFn=on.ingestionFn(t.ordered),s.protocolFilterFn=(n,i=!1)=>{const o=n;return Ms(o.msg)?(i||o.msg.respond(),!1):!0},!t.mack&&t.config.ack_policy!==V.None&&(s.dispatchedFn=Sh),t.callbackFn&&(s.callback=t.callbackFn),s.max=t.max||0,s.queue=t.queue,s}async _maybeCreateConsumer(t){if(t.attached)return;if(t.isBind)throw new Error(`unable to bind - durable consumer ${t.config.durable_name} doesn't exist in ${t.stream}`);t.config=Object.assign({deliver_policy:H.All,ack_policy:V.Explicit,ack_wait:q(30*1e3),replay_policy:mt.Instant},t.config);const s=await this.consumerAPI.add(t.stream,t.config);if(Array.isArray(t.config.filter_subjects&&!Array.isArray(s.config.filter_subjects)))throw new Error("jetstream server doesn't support consumers with multiple filter subjects");t.name=s.name,t.config=s.config,t.last=s}static ingestionFn(t){return(s,n)=>{var u;const i=n;if(!s)return{ingest:!1,protocol:!1};const o=s;if(lt(o.msg)||(u=i.monitor)==null||u.work(),Us(o.msg)){const h=t?i._checkHbOrderConsumer(o.msg):!0;return t||i.info.flow_control.heartbeat_count++,{ingest:h,protocol:!0}}else if(Ms(o.msg))return i.info.flow_control.fc_count++,{ingest:!0,protocol:!0};return{ingest:t?i._checkOrderedConsumer(s):!0,protocol:!1}}}}class Ho extends sh{constructor(t,s,n){super(t.nc,s,n);c(this,"js");c(this,"monitor");this.js=t,this.monitor=null,this.sub.closed.then(()=>{this.monitor&&this.monitor.cancel()})}set info(t){this.sub.info=t}get info(){return this.sub.info}_resetOrderedConsumer(t){if(this.info===null||this.sub.isClosed())return;const s=Te(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const i=this.info;i.ordered_consumer_sequence.delivery_seq=0,i.flow_control.heartbeat_count=0,i.flow_control.fc_count=0,i.flow_control.consumer_restarts++,i.deliver=s,i.config.deliver_subject=s,i.config.deliver_policy=H.StartSequence,i.config.opt_start_seq=t;const o={};o.stream_name=this.info.stream,o.config=i.config;const a=`${i.api.prefix}.CONSUMER.CREATE.${i.stream}`;this.js._request(a,o).then(u=>{const h=u;this.info.config=h.config,this.info.name=h.name}).catch(u=>{const h=new j(`unable to recreate ordered consumer ${i.stream} at seq ${t}`,P.RequestError,u);this.sub.callback(h,{})})}_maybeSetupHbMonitoring(){var s,n;const t=((n=(s=this.info)==null?void 0:s.config)==null?void 0:n.idle_heartbeat)||0;t&&this._setupHbMonitoring(en(t))}_setupHbMonitoring(t,s=0){const n={cancelAfter:0,maxOut:2};s&&(n.cancelAfter=s);const i=this.sub,o=a=>{var p,g,b;const u=Ml(409,`${fe.IdleHeartbeatMissed}: ${a}`,this.sub.subject);if(!((p=this.info)==null?void 0:p.ordered))this.sub.callback(null,u);else{if(!this.js.nc.protocol.connected)return!1;const w=((b=(g=this.info)==null?void 0:g.ordered_consumer_sequence)==null?void 0:b.stream_seq)||0;return this._resetOrderedConsumer(w+1),!1}return!i.noIterator};this.monitor=new rn(t,o,n)}_checkHbOrderConsumer(t){const s=t.headers.get(Q.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const n=parseInt(t.headers.get(Q.LastConsumerSeqHdr),10),i=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,n!==i.delivery_seq&&this._resetOrderedConsumer(i.stream_seq+1),!1}_checkOrderedConsumer(t){const s=this.info.ordered_consumer_sequence,n=t.info.streamSequence,i=t.info.deliverySequence;return i!=s.delivery_seq+1?(this._resetOrderedConsumer(s.stream_seq+1),!1):(s.delivery_seq=i,s.stream_seq=n,!0)}async destroy(){this.isClosed()||await this.drain();const t=this.sub.info,s=t.config.durable_name||t.name,n=`${t.api.prefix}.CONSUMER.DELETE.${t.stream}.${s}`;await t.api._request(n)}async consumerInfo(){const t=this.sub.info,s=t.config.durable_name||t.name,n=`${t.api.prefix}.CONSUMER.INFO.${t.stream}.${s}`,i=await t.api._request(n);return t.last=i,i}}class yh extends Ho{constructor(e,t,s){super(e,t,s)}pull(e={batch:1}){const{stream:t,config:s,name:n}=this.sub.info,i=s.durable_name??n,o={};if(o.batch=e.batch||1,o.no_wait=e.no_wait||!1,(e.max_bytes??0)>0){const h=this.js.nc.features.get(L.JS_PULL_MAX_BYTES);if(!h.ok)throw new Error(`max_bytes is only supported on servers ${h.min} or better`);o.max_bytes=e.max_bytes}let a=0;e.expires&&e.expires>0&&(a=e.expires,o.expires=q(a));let u=0;if(e.idle_heartbeat&&e.idle_heartbeat>0&&(u=e.idle_heartbeat,o.idle_heartbeat=q(u)),u&&a===0)throw new Error("idle_heartbeat requires expires");if(u>a)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),a&&u&&(this.monitor?this.monitor._change(u,a):this._setupHbMonitoring(u,a));const h=this.info.api,p=`${h.prefix}.CONSUMER.MSG.NEXT.${t}.${i}`,g=this.sub.subject;h.nc.publish(p,h.jc.encode(o),{reply:g})}}}function wh(r){return r?vh:xh}function xh(r,e){return r?[r,null]:(r=lt(e),r?[r,null]:[null,Ft(e)])}function vh(r,e){if(r)return[r,null];const t=lt(e);return t!==null?[Jo(t),null]:[null,Ft(e)]}function Jo(r){if(r!==null)switch(r.code){case P.JetStream404NoMessages:case P.JetStream408RequestTimeout:return null;case P.JetStream409:return Ul(r)?r:null;default:return r}return null}function Sh(r){r&&r.ack()}class Eh extends zt{constructor(e,t){super(e,t)}async getMessage(e,t){te(e);let s=t;const{last_by_subj:n}=s;n&&(s=null);const i=s?this.jc.encode(s):se,o=this.opts.apiPrefix||"$JS.API",a=n?`${o}.DIRECT.GET.${e}.${n}`:`${o}.DIRECT.GET.${e}`,u=await this.nc.request(a,i),h=lt(u);if(h)return Promise.reject(h);const p=new zo(u);return Promise.resolve(p)}}class zo{constructor(e){c(this,"data");c(this,"header");if(!e.headers)throw new Error("headers expected");this.data=e.data,this.header=e.headers}get subject(){return this.header.last(ot.Subject)}get seq(){const e=this.header.last(ot.Sequence);return typeof e=="string"?parseInt(e):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(ot.TimeStamp)}get stream(){return this.header.last(ot.Stream)}json(e){return ye(e).decode(this.data)}string(){return ae.decode(this.data)}}c(zo,"jc");class Ah extends zt{constructor(t,s){super(t,s);c(this,"streams");c(this,"consumers");c(this,"direct");this.streams=new nn(t,s),this.consumers=new tn(t,s),this.direct=new Eh(t,s)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return this.nc.jetstream(this.getOptions())}advisories(){const t=new Y;return this.nc.subscribe("$JS.EVENT.ADVISORY.>",{callback:(s,n)=>{if(s)throw s;try{const i=this.parseJsResponse(n),o=i.type.split("."),a=o[o.length-1];t.push({kind:a,data:i})}catch(i){t.stop(i)}}}),t}}const Ph="$SRV";class Ii{constructor(e){c(this,"msg");this.msg=e}get data(){return this.msg.data}get sid(){return this.msg.sid}get subject(){return this.msg.subject}get reply(){return this.msg.reply||""}get headers(){return this.msg.headers}respond(e,t){return this.msg.respond(e,t)}respondError(e,t,s,n){var i,o;return n=n||{},n.headers=n.headers||Ne(),(i=n.headers)==null||i.set(wr,`${e}`),(o=n.headers)==null||o.set(yr,t),this.msg.respond(s,n)}json(e){return this.msg.json(e)}string(){return this.msg.string()}}class Dt{constructor(e,t="",s=""){c(this,"subject");c(this,"queue");c(this,"srv");t!==""&&Ch("service group",t);let n="";if(e instanceof Gt)this.srv=e,n="";else if(e instanceof Dt){const i=e;this.srv=i.srv,s===""&&i.queue!==""&&(s=i.queue),n=i.subject}else throw new Error("unknown ServiceGroup type");this.subject=this.calcSubject(n,t),this.queue=s}calcSubject(e,t=""){return t===""?e:e!==""?`${e}.${t}`:t}addEndpoint(e="",t){t=t||{subject:e};const s=typeof t=="function"?{handler:t,subject:e}:t;Ct("endpoint",e);let{subject:n,handler:i,metadata:o,queue:a}=s;n=n||e,a=a||this.queue,Oh("endpoint subject",n),n=this.calcSubject(this.subject,n);const u={name:e,subject:n,queue:a,handler:i,metadata:o};return this.srv._addEndpoint(u)}addGroup(e="",t=""){return new Dt(this,e,t)}}function Oh(r,e){if(e==="")throw new Error(`${r} cannot be empty`);if(e.indexOf(" ")!==-1)throw new Error(`${r} cannot contain spaces: '${e}'`);const t=e.split(".");t.forEach((s,n)=>{if(s===">"&&n!==t.length-1)throw new Error(`${r} cannot have internal '>': '${e}'`)})}function Ch(r,e){if(e.indexOf(" ")!==-1)throw new Error(`${r} cannot contain spaces: '${e}'`);e.split(".").forEach(s=>{if(s===">")throw new Error(`${r} name cannot contain internal '>': '${e}'`)})}class Gt{constructor(e,t={name:"",version:""}){c(this,"nc");c(this,"_id");c(this,"config");c(this,"handlers");c(this,"internal");c(this,"_stopped");c(this,"_done");c(this,"started");this.nc=e,this.config=Object.assign({},t),this.config.queue||(this.config.queue="q"),Ct("name",this.config.name),Ct("queue",this.config.queue),We(this.config.version),this._id=Ht.next(),this.internal=[],this._done=B(),this._stopped=!1,this.handlers=[],this.started=new Date().toISOString(),this.reset(),this.nc.closed().then(()=>{this.close().catch()}).catch(s=>{this.close(s).catch()})}static controlSubject(e,t="",s="",n){const i=n??Ph;return t===""&&s===""?`${i}.${e}`:(Ct("control subject name",t),s!==""?(Ct("control subject id",s),`${i}.${e}.${t}.${s}`):`${i}.${e}.${t}`)}get subjects(){return this.handlers.filter(e=>e.internal===!1).map(e=>e.subject)}get id(){return this._id}get name(){return this.config.name}get description(){return this.config.description??""}get version(){return this.config.version}get metadata(){return this.config.metadata}errorToHeader(e){const t=Ne();if(e instanceof xr){const s=e;t.set(yr,s.message),t.set(wr,`${s.code}`)}else t.set(yr,e.message),t.set(wr,"500");return t}setupHandler(e,t=!1){const s=t?"":e.queue?e.queue:this.config.queue,{name:n,subject:i,handler:o}=e,a=e;a.internal=t,t&&this.internal.push(a),a.stats=new kh(n,i,s),a.queue=s;const u=o?(h,p)=>{if(h){this.close(h);return}const g=Date.now();try{o(h,new Ii(p))}catch(b){a.stats.countError(b),p==null||p.respond(se,{headers:this.errorToHeader(b)})}finally{a.stats.countLatency(g)}}:void 0;return a.sub=this.nc.subscribe(i,{callback:u,queue:s}),a.sub.closed.then(()=>{this._stopped||this.close(new Error(`required subscription ${e.subject} stopped`)).catch()}).catch(h=>{if(!this._stopped){const p=new Error(`required subscription ${e.subject} errored: ${h.message}`);p.stack=h.stack,this.close(p).catch()}}),a}info(){return{type:It.INFO,name:this.name,id:this.id,version:this.version,description:this.description,metadata:this.metadata,endpoints:this.endpoints()}}endpoints(){return this.handlers.map(e=>{const{subject:t,metadata:s,name:n,queue:i}=e;return{subject:t,metadata:s,name:n,queue_group:i}})}async stats(){const e=[];for(const t of this.handlers){if(typeof this.config.statsHandler=="function")try{t.stats.data=await this.config.statsHandler(t)}catch(s){t.stats.countError(s)}e.push(t.stats.stats(t.qi))}return{type:It.STATS,name:this.name,id:this.id,version:this.version,started:this.started,metadata:this.metadata,endpoints:e}}addInternalHandler(e,t){const s=`${e}`.toUpperCase();this._doAddInternalHandler(`${s}-all`,e,t),this._doAddInternalHandler(`${s}-kind`,e,t,this.name),this._doAddInternalHandler(`${s}`,e,t,this.name,this.id)}_doAddInternalHandler(e,t,s,n="",i=""){const o={};o.name=e,o.subject=Gt.controlSubject(t,n,i),o.handler=s,this.setupHandler(o,!0)}start(){const e=ye(),t=(o,a)=>o?(this.close(o),Promise.reject(o)):this.stats().then(u=>(a==null||a.respond(e.encode(u)),Promise.resolve())),s=(o,a)=>o?(this.close(o),Promise.reject(o)):(a==null||a.respond(e.encode(this.info())),Promise.resolve()),n=e.encode(this.ping()),i=(o,a)=>o?(this.close(o).then().catch(),Promise.reject(o)):(a.respond(n),Promise.resolve());return this.addInternalHandler(De.PING,i),this.addInternalHandler(De.STATS,t),this.addInternalHandler(De.INFO,s),this.handlers.forEach(o=>{const{subject:a}=o;typeof a=="string"&&o.handler!==null&&this.setupHandler(o)}),Promise.resolve(this)}close(e){if(this._stopped)return this._done;this._stopped=!0;let t=[];return this.nc.isClosed()||(t=this.handlers.concat(this.internal).map(s=>s.sub.drain())),Promise.allSettled(t).then(()=>{this._done.resolve(e||null)}),this._done}get stopped(){return this._done}get isStopped(){return this._stopped}stop(e){return this.close(e)}ping(){return{type:It.PING,name:this.name,id:this.id,version:this.version,metadata:this.metadata}}reset(){if(this.started=new Date().toISOString(),this.handlers)for(const e of this.handlers)e.stats.reset(e.qi)}addGroup(e,t){return new Dt(this,e,t)}addEndpoint(e,t){return new Dt(this).addEndpoint(e,t)}_addEndpoint(e){const t=new Y;t.noIterator=typeof e.handler=="function",t.noIterator||(e.handler=(n,i)=>{n?this.stop(n).catch():t.push(new Ii(i))},t.iterClosed.then(()=>{this.close().catch()}));const s=this.setupHandler(e,!1);return s.qi=t,this.handlers.push(s),t}}class kh{constructor(e,t,s=""){c(this,"name");c(this,"subject");c(this,"average_processing_time");c(this,"num_requests");c(this,"processing_time");c(this,"num_errors");c(this,"last_error");c(this,"data");c(this,"metadata");c(this,"queue");this.name=e,this.subject=t,this.average_processing_time=0,this.num_errors=0,this.num_requests=0,this.processing_time=0,this.queue=s}reset(e){this.num_requests=0,this.processing_time=0,this.average_processing_time=0,this.num_errors=0,this.last_error=void 0,this.data=void 0;const t=e;t&&(t.time=0,t.processed=0)}countLatency(e){this.num_requests++,this.processing_time+=q(Date.now()-e),this.average_processing_time=Math.round(this.processing_time/this.num_requests)}countError(e){this.num_errors++,this.last_error=e.message}_stats(){const{name:e,subject:t,average_processing_time:s,num_errors:n,num_requests:i,processing_time:o,last_error:a,data:u,queue:h}=this;return{name:e,subject:t,average_processing_time:s,num_errors:n,num_requests:i,processing_time:o,last_error:a,data:u,queue_group:h}}stats(e){const t=e;return(t==null?void 0:t.noIterator)===!1&&(this.processing_time=t.time,this.num_requests=t.processed,this.average_processing_time=this.processing_time>0&&this.num_requests>0?this.processing_time/this.num_requests:0),this._stats()}}class Rh{constructor(e,t={strategy:Se.JitterTimer,maxWait:2e3},s){c(this,"nc");c(this,"prefix");c(this,"opts");this.nc=e,this.prefix=s,this.opts=t}ping(e="",t=""){return this.q(De.PING,e,t)}stats(e="",t=""){return this.q(De.STATS,e,t)}info(e="",t=""){return this.q(De.INFO,e,t)}async q(e,t="",s=""){const n=new Y,i=ye(),o=Gt.controlSubject(e,t,s,this.prefix),a=await this.nc.requestMany(o,se,this.opts);return(async()=>{for await(const u of a)try{const h=i.decode(u.data);n.push(h)}catch(h){n.push(()=>{n.stop(h)})}n.push(()=>{n.stop()})})().catch(u=>{n.stop(u)}),n}}class an{constructor(e){c(this,"options");c(this,"protocol");c(this,"draining");c(this,"listeners");c(this,"_services");this.draining=!1,this.options=Pl(e),this.listeners=[]}static connect(e={}){return new Promise((t,s)=>{const n=new an(e);Er.connect(n.options,n).then(i=>{n.protocol=i,async function(){for await(const o of i.status())n.listeners.forEach(a=>{a.push(o)})}(),t(n)}).catch(i=>{s(i)})})}closed(){return this.protocol.closed}async close(){await this.protocol.close()}_check(e,t,s){if(this.isClosed())throw j.errorForCode(P.ConnectionClosed);if(t&&this.isDraining()||s&&this.protocol.noMorePublishing)throw j.errorForCode(P.ConnectionDraining);if(e=e||"",e.length===0)throw j.errorForCode(P.BadSubject)}publish(e,t,s){this._check(e,!1,!0),this.protocol.publish(e,t,s)}subscribe(e,t={}){this._check(e,!0,!1);const s=new Io(this.protocol,e,t);return this.protocol.subscribe(s),s}_resub(e,t,s){this._check(t,!0,!1);const n=e;n.max=s,s&&(n.max=s+n.received),this.protocol.resub(n,t)}requestMany(e,t=se,s={maxWait:1e3,maxMessages:-1}){const n=!this.protocol.options.noAsyncTraces;try{this._check(e,!0,!0)}catch(u){return Promise.reject(u)}if(s.strategy=s.strategy||Se.Timer,s.maxWait=s.maxWait||1e3,s.maxWait<1)return Promise.reject(new j("timeout",P.InvalidOption));const i=new Y;function o(u){i.push(()=>{i.stop(u)})}function a(u,h){u||h===null?o(u===null?void 0:u):i.push(h)}if(s.noMux){const u=n?new Error().stack:null;let h=typeof s.maxMessages=="number"&&s.maxMessages>0?s.maxMessages:-1;const p=this.subscribe(Te(this.options.inboxPrefix),{callback:(A,k)=>{var R,U;if(((R=k==null?void 0:k.data)==null?void 0:R.length)===0&&((U=k==null?void 0:k.headers)==null?void 0:U.status)===P.NoResponders&&(A=j.errorForCode(P.NoResponders)),A){u&&(A.stack+=`
- ${u}`),g(A);return}a(null,k),s.strategy===Se.Count&&(h--,h===0&&g()),s.strategy===Se.JitterTimer&&(w(),b=setTimeout(()=>{g()},300)),s.strategy===Se.SentinelMsg&&k&&k.data.length===0&&g()}});p.closed.then(()=>{o()}).catch(A=>{i.stop(A)});const g=A=>{A&&i.push(()=>{throw A}),w(),p.drain().then(()=>{o()}).catch(k=>{o()})};i.iterClosed.then(()=>{w(),p==null||p.unsubscribe()}).catch(A=>{w(),p==null||p.unsubscribe()});try{this.publish(e,t,{reply:p.getSubject()})}catch(A){g(A)}let b=setTimeout(()=>{g()},s.maxWait);const w=()=>{b&&clearTimeout(b)}}else{const u=s;u.callback=a,i.iterClosed.then(()=>{h.cancel()}).catch(p=>{h.cancel(p)});const h=new Tl(this.protocol.muxSubscriptions,e,u);this.protocol.request(h);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${h.token}`,headers:s.headers})}catch(p){h.cancel(p)}}return Promise.resolve(i)}request(e,t,s={timeout:1e3,noMux:!1}){try{this._check(e,!0,!0)}catch(i){return Promise.reject(i)}const n=!this.protocol.options.noAsyncTraces;if(s.timeout=s.timeout||1e3,s.timeout<1)return Promise.reject(new j("timeout",P.InvalidOption));if(!s.noMux&&s.reply)return Promise.reject(new j("reply can only be used with noMux",P.InvalidOption));if(s.noMux){const i=s.reply?s.reply:Te(this.options.inboxPrefix),o=B(),a=n?new Error:null,u=this.subscribe(i,{max:1,timeout:s.timeout,callback:(h,p)=>{h?(a&&h.code!==P.Timeout&&(h.stack+=`
- ${a.stack}`),o.reject(h)):(h=ko(p),h?(a&&(h.stack+=`
- ${a.stack}`),o.reject(h)):o.resolve(p))}});return u.requestSubject=e,this.protocol.publish(e,t,{reply:i,headers:s.headers}),o}else{const i=new No(this.protocol.muxSubscriptions,e,s,n);this.protocol.request(i);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${i.token}`,headers:s.headers})}catch(a){i.cancel(a)}const o=Promise.race([i.timer,i.deferred]);return o.catch(()=>{i.cancel()}),o}}flush(){return this.isClosed()?Promise.reject(j.errorForCode(P.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(j.errorForCode(P.ConnectionClosed)):this.isDraining()?Promise.reject(j.errorForCode(P.ConnectionDraining)):(this.draining=!0,this.protocol.drain())}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){const e=this.protocol.getServer();return e?e.listen:""}status(){const e=new Y;return e.iterClosed.then(()=>{const t=this.listeners.indexOf(e);this.listeners.splice(t,1)}),this.listeners.push(e),e}get info(){return this.protocol.isClosed()?void 0:this.protocol.info}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(e={}){const t=new Ah(this,e);if(e.checkAPI!==!1)try{await t.getAccountInfo()}catch(s){const n=s;throw n.code===P.NoResponders&&(n.code=P.JetStreamNotEnabled),n}return t}jetstream(e={}){return new on(this,e)}getServerVersion(){const e=this.info;return e?We(e.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw j.errorForCode(P.Disconnect);const e=Date.now();return await this.flush(),Date.now()-e}get features(){return this.protocol.features}get services(){return this._services||(this._services=new jh(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(j.errorForCode(P.ConnectionClosed)):this.isDraining()?Promise.reject(j.errorForCode(P.ConnectionDraining)):this.protocol.reconnect()}}class jh{constructor(e){c(this,"nc");this.nc=e}add(e){try{return new Gt(this.nc,e).start()}catch(t){return Promise.reject(t)}}client(e,t){return new Rh(this.nc,e,t)}}const Ih="1.19.1",Th="nats.ws";class Nh{constructor(){c(this,"version");c(this,"lang");c(this,"closeError");c(this,"connected");c(this,"done");c(this,"socket");c(this,"options");c(this,"socketClosed");c(this,"encrypted");c(this,"peeked");c(this,"yields");c(this,"signal");c(this,"closedNotification");this.version=Ih,this.lang=Th,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=B(),this.closedNotification=B()}async connect(e,t){const s=B();if(t.tls)return s.reject(new j("tls",P.InvalidOption)),s;this.options=t;const n=e.src;if(t.wsFactory){const{socket:i,encrypted:o}=await t.wsFactory(e.src,t);this.socket=i,this.encrypted=o}else this.encrypted=n.indexOf("wss://")===0,this.socket=new WebSocket(n);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=i=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(i.data)),this.peeked){this.signal.resolve();return}const o=pt.concat(...this.yields),a=el(o);if(a!==""){const u=kl.exec(a);if(!u){t.debug&&console.error("!!!",or(o)),s.reject(new Error("unexpected response from server"));return}try{const h=JSON.parse(u[1]);Ol(h,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(h){s.reject(h);return}}},this.socket.onclose=i=>{if(this.isDiscarded())return;this.socketClosed=!0;let o;this.done||(i.wasClean||(o=new Error(i.reason)),this._closed(o))},this.socket.onerror=i=>{if(this.isDiscarded())return;const o=i,a=new j(o.message,P.Unknown,new Error(o.error));s.reject(a)},s}disconnect(){this._closed(void 0,!0)}async _closed(e,t=!0){if(!this.isDiscarded()&&this.connected&&!this.done){if(this.closeError=e,!e)for(;!this.socketClosed&&this.socket.bufferedAmount>0;)await Jt(100);this.done=!0;try{this.socket.close(e?1002:1e3,e?e.message:void 0)}catch{}t&&this.closedNotification.resolve(e)}}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){for(;;){if(this.isDiscarded())return;this.yields.length===0&&await this.signal;const e=this.yields;this.yields=[];for(let t=0;t<e.length;t++)this.options.debug&&console.info(`> ${or(e[t])}`),yield e[t];if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=B())}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(!this.isDiscarded())try{this.socket.send(e.buffer),this.options.debug&&console.info(`< ${or(e)}`);return}catch(t){this.options.debug&&console.error(`!!! ${or(e)}: ${t}`)}}close(e){return this._closed(e,!1)}closed(){return this.closedNotification}isDiscarded(){return this.done?(this.discard(),!0):!1}discard(){var e;this.done=!0;try{(e=this.socket)==null||e.close()}catch{}}}function Mh(r){/^(.*:\/\/)(.*)/.test(r)||(r=`https://${r}`);let t=new URL(r);const s=t.protocol.toLowerCase();s!=="https:"&&s!=="http"&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2"),t=new URL(`http://${r}`));let n,i;const o=t.hostname,a=t.pathname,u=t.search||"";switch(s){case"http:":case"ws:":case"nats:":i=t.port||"80",n="ws:";break;default:i=t.port||"443",n="wss:";break}return`${n}//${o}:${i}${a}${u}`}function Uh(r={}){return Yu({defaultPort:443,urlParseFn:Mh,factory:()=>new Nh}),an.connect(r)}class $h extends Tr{constructor(){super(...arguments);c(this,"_conn");c(this,"_isConned",!1);c(this,"_startInit",!1)}async onReady(){await this.initConn()}async initConn(){if(this._startInit)return;this._startInit=!0,ke.showLoading("服务连接中...");const{deviceCtrl:t}=ve(),s=await t.GetNatsProfile(),n=`nats://${s.ip}:${s.wsPort}`;console.log("ws host=>",n);let i=!1;try{this._conn=await Uh({servers:n}),this._isConned=!!this._conn,i=!0}catch(o){console.log(o),ke.messageError("连接失败!")}return ke.hideLoading(),this._startInit=!1,i}async GetConn(){return this._conn}async subscribe(t,s,n={}){if(!this._isConned){console.error("建立连接失败");return}const i=Sr(),o=this._conn.subscribe(t,n);return(async()=>{for await(const a of o){const u=i.decode(a.data);console.log(t,"=>recieved");try{if(u&&u[0]=="{"){const h=JSON.parse(u);s(h)}else s(u)}catch(h){console.log(t,"=>recieved json parse eror",u),console.log(h)}}console.log(t,"subscription closed")})(),function(){o.unsubscribe()}}async requestApi(t,s,n){const i=await this.request(t,s,n);if(console.log("request api=>",i),i.error||i.result.ErrorNo&&i.result.ErrorNo!=200){ke.messageError(i.error||i.result.ErrorDesc);return}try{const o=i.result.Result;return o?o[0]!="{"&&o[0]!="["?o:JSON.parse(o):void 0}catch(o){console.log(i),console.error(o)}}async request(t,s,n){const i={error:"",result:null};if(!this._isConned)return console.error("建立连接失败"),i.error="建立连接失败",ke.showConfirm({title:"数据请求失败",content:"请求数据失败,请重新启动后再试",type:"danger"}),i;const o=Sr();try{let a=se;s&&(typeof s!="string"?a=o.encode(JSON.stringify(s)):a=o.encode(s));const u={timeout:5e3};n&&(u.timeout=n);const h=await this._conn.request(t,a,u);let p=o.decode(h.data);try{p=JSON.parse(p),console.log("m=>",p)}catch(g){console.log(g)}i.result=p}catch(a){console.error(a),i.error=a.message||"请求"+t+"出错",i.error=="503"&&(i.error="网路异常,请重启服务")}return i}close(){if(this._isConned)return this._conn.close()}}const Or={prjCtrl:new Su,deviceCtrl:new vu,installCtrl:new Lu,natsCtrl:new $h};let vs=["deviceCtrl","natsCtrl","prjCtrl","installCtrl"],Fh=Object.keys(Or),Ti=[];async function Lh(){console.log("begin init ");let r=vs.length;for(let t=0;t<r;t++)await Or[vs[t]].onReady();const e=Fh.slice(0);for(;r--;)vs.indexOf(e[r])!=-1&&e.splice(r,1);if(Ti.length>0)for(r=e.length;r--;)Ti.indexOf(e[r])!=-1&&e.splice(r,1);e.forEach(t=>{Or[t].onReady()}),console.log("end init")}function ve(){return Or}const Dh=Ni(()=>{const r=Mi({loading:!0});try{Lh().then(()=>{r.loading=!1})}catch{r.loading=!0,alert("控制器初始化失败! 请在app中打开当前页面")}return()=>r.loading?Ve("div",{class:"pt-40px text-center"},[Ve(fa,{tip:"初始加载中..."},null)]):Ve(pa,null,{default:()=>[Ve(da("router-view"),null,null)]})}),qh=ma({history:ba(),routes:[{path:"/",name:"home",component:()=>Sn(()=>import("./index-882648bf.js"),["./index-882648bf.js","./image-e1abec51.js","./main-74e469cd.js","./main-d90e89fb.css","./index-04db8a5f.js","./index-1286a279.js","./useFlexGapSupport-72f2e7e7.js","./index-3e4388d8.js","./Col-b8673fb6.js","./index-d982d687.js","./index-149ee1ea.css"],import.meta.url)},{path:"/404",name:"404",component:()=>Sn(()=>import("./index-764dc91b.js"),["./index-764dc91b.js","./main-74e469cd.js","./main-d90e89fb.css"],import.meta.url)},{path:"/:catchAll(.*)",redirect:"/404"}]});ga(Dh).use(qh).use(_a()).mount("#app");export{ve as u};
|