@jokio/sdk 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,18 @@
1
1
  (function(ye,Q){typeof exports=="object"&&typeof module<"u"?Q(exports):typeof define=="function"&&define.amd?define(["exports"],Q):(ye=typeof globalThis<"u"?globalThis:ye||self,Q(ye["@jokio/sdk"]={}))})(this,function(ye){"use strict";var ma=Object.defineProperty;var ba=(ye,Q,qe)=>Q in ye?ma(ye,Q,{enumerable:!0,configurable:!0,writable:!0,value:qe}):ye[Q]=qe;var h=(ye,Q,qe)=>ba(ye,typeof Q!="symbol"?Q+"":Q,qe);function Q(r){const e=new Uint8Array(r);let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qe(r){const e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,s=e.padEnd(e.length+t,"="),i=atob(s),n=new ArrayBuffer(i.length),o=new Uint8Array(n);for(let a=0;a<i.length;a++)o[a]=i.charCodeAt(a);return n}function ps(){return xi.stubThis((globalThis==null?void 0:globalThis.PublicKeyCredential)!==void 0&&typeof globalThis.PublicKeyCredential=="function")}const xi={stubThis:r=>r};function ar(r){const{id:e}=r;return{...r,id:qe(e),transports:r.transports}}function cr(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}class le extends Error{constructor({message:e,code:t,cause:s,name:i}){super(e,{cause:s}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i??s.name,this.code=t}}function Si({error:r,options:e}){var s,i,n;const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new le({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else if(r.name==="ConstraintError"){if(((s=t.authenticatorSelection)==null?void 0:s.requireResidentKey)===!0)return new le({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:r});if(e.mediation==="conditional"&&((i=t.authenticatorSelection)==null?void 0:i.userVerification)==="required")return new le({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:r});if(((n=t.authenticatorSelection)==null?void 0:n.userVerification)==="required")return new le({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:r})}else{if(r.name==="InvalidStateError")return new le({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new le({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="NotSupportedError")return t.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new le({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new le({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:r});if(r.name==="SecurityError"){const o=globalThis.location.hostname;if(cr(o)){if(t.rp.id!==o)return new le({message:`The RP ID "${t.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new le({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="TypeError"){if(t.user.id.byteLength<1||t.user.id.byteLength>64)return new le({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:r})}else if(r.name==="UnknownError")return new le({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}class vi{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const hr=new vi,Ei=["cross-platform","platform"];function ur(r){if(r&&!(Ei.indexOf(r)<0))return r}async function Ai(r){var I;!r.optionsJSON&&r.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});const{optionsJSON:e,useAutoRegister:t=!1}=r;if(!ps())throw new Error("WebAuthn is not supported in this browser");const s={...e,challenge:qe(e.challenge),user:{...e.user,id:qe(e.user.id)},excludeCredentials:(I=e.excludeCredentials)==null?void 0:I.map(ar)},i={};t&&(i.mediation="conditional"),i.publicKey=s,i.signal=hr.createNewAbortSignal();let n;try{n=await navigator.credentials.create(i)}catch(T){throw Si({error:T,options:i})}if(!n)throw new Error("Registration was not completed");const{id:o,rawId:a,response:f,type:p}=n;let g;typeof f.getTransports=="function"&&(g=f.getTransports());let y;if(typeof f.getPublicKeyAlgorithm=="function")try{y=f.getPublicKeyAlgorithm()}catch(T){ms("getPublicKeyAlgorithm()",T)}let x;if(typeof f.getPublicKey=="function")try{const T=f.getPublicKey();T!==null&&(x=Q(T))}catch(T){ms("getPublicKey()",T)}let A;if(typeof f.getAuthenticatorData=="function")try{A=Q(f.getAuthenticatorData())}catch(T){ms("getAuthenticatorData()",T)}return{id:o,rawId:Q(a),response:{attestationObject:Q(f.attestationObject),clientDataJSON:Q(f.clientDataJSON),transports:g,publicKeyAlgorithm:y,publicKey:x,authenticatorData:A},type:p,clientExtensionResults:n.getClientExtensionResults(),authenticatorAttachment:ur(n.authenticatorAttachment)}}function ms(r,e){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${r}. You should report this error to them.
2
- `,e)}function Pi(){if(!ps())return bs.stubThis(new Promise(e=>e(!1)));const r=globalThis.PublicKeyCredential;return(r==null?void 0:r.isConditionalMediationAvailable)===void 0?bs.stubThis(new Promise(e=>e(!1))):bs.stubThis(r.isConditionalMediationAvailable())}const bs={stubThis:r=>r};function ki({error:r,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new le({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new le({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=globalThis.location.hostname;if(cr(s)){if(t.rpId!==s)return new le({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new le({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new le({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}async function Oi(r){var A,I;!r.optionsJSON&&r.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});const{optionsJSON:e,useBrowserAutofill:t=!1,verifyBrowserAutofillInput:s=!0}=r;if(!ps())throw new Error("WebAuthn is not supported in this browser");let i;((A=e.allowCredentials)==null?void 0:A.length)!==0&&(i=(I=e.allowCredentials)==null?void 0:I.map(ar));const n={...e,challenge:qe(e.challenge),allowCredentials:i},o={};if(t){if(!await Pi())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&s)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation="conditional",n.allowCredentials=[]}o.publicKey=n,o.signal=hr.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(T){throw ki({error:T,options:o})}if(!a)throw new Error("Authentication was not completed");const{id:f,rawId:p,response:g,type:y}=a;let x;return g.userHandle&&(x=Q(g.userHandle)),{id:f,rawId:Q(p),response:{authenticatorData:Q(g.authenticatorData),clientDataJSON:Q(g.clientDataJSON),signature:Q(g.signature),userHandle:x},type:y,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:ur(a.authenticatorAttachment)}}const gt="ACCESS_TOKEN",lr="SESSION_SEED",Ze="LAST_AUTH_DATA";class fr{constructor(e){h(this,"onUserDataUpdate");h(this,"isAuthenticated");h(this,"isAuthenticatedResolver",()=>{});this.options=e,this.isAuthenticated=new Promise(t=>this.isAuthenticatedResolver=t)}get url(){return this.options.authUrl}async init(){var t,s;const e=localStorage.getItem(Ze);if(e)try{const i=JSON.parse(e);(t=this.onUserDataUpdate)==null||t.call(this,i),this.isAuthenticatedResolver()}catch{}else{const i=await this.me();await this.options.storage.setItem(Ze,i),(s=this.onUserDataUpdate)==null||s.call(this,i),this.isAuthenticatedResolver()}}async me(){return await fetch(this.options.authUrl+"/me",{credentials:"include"}).then(t=>t.json())}async requestEmailLogin(e,t=location.href){return await fetch(this.options.authUrl+`/email-verification-request/${e}?returnUrl=${t}`,{credentials:"include"}).then(_t)}async completeEmailLogin(e,t){var i;const s=await fetch(this.options.authUrl+`/email-verification-complete/${e}/${t}`,{credentials:"include"}).then(_t);return await this.options.storage.setItem(gt,s.accessToken),await this.options.storage.setItem(Ze,s.jwtData),(i=this.onUserDataUpdate)==null||i.call(this,s.jwtData),s.jwtData}async requestPasskeyLogin(e={}){var f,p;const{displayName:t="",isRegistration:s=!1,addAsAdditionalDevice:i=!1}=e,n=await fetch(this.options.authUrl+`/webauth-challenge-request?registration=${s?"true":""}&displayName=${t}`,{credentials:"include"}).then(_t);let o;try{(f=n.user)!=null&&f.id?o=await Ai({optionsJSON:n}):o=await Oi({optionsJSON:n})}catch(g){throw g.name==="InvalidStateError"?alert("Error: Authenticator was probably already registered by user"):alert(g.message),g}const a=await fetch(this.options.authUrl+`/webauth-challenge-complete?displayName=${t}&addAsAdditionalDevice=${i?"true":""}`,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},credentials:"include"}).then(_t);return await this.options.storage.setItem(gt,a.accessToken),await this.options.storage.setItem(Ze,a.jwtData),(p=this.onUserDataUpdate)==null||p.call(this,a.jwtData),a.jwtData}async guestLogin(){var t;const e=await fetch(this.options.authUrl+"/guest-session").then(_t);return await this.options.storage.setItem(gt,e.accessToken),await this.options.storage.setItem(lr,e.sessionSeed),await this.options.storage.setItem(Ze,e.jwtData),(t=this.onUserDataUpdate)==null||t.call(this,e.jwtData),e.jwtData}signOut(){var e;this.options.storage.removeItem(gt),this.options.storage.removeItem(Ze),(e=this.onUserDataUpdate)==null||e.call(this,null)}getLastLoginData(){return this.options.storage.getItem(Ze)}getAccessToken(){return this.options.storage.getItem(gt)}getSessionSeed(){return this.options.storage.getItem(lr)}}const _t=async r=>{const e=await r.json();if(!r.ok)throw new Error(e.message);return e},gs=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),dr=r=>new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16))),pr=r=>btoa(String.fromCharCode(...new Uint8Array(r))),Ci=r=>Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer,Ii=async r=>await crypto.subtle.digest("SHA-256",r),ji=new TextEncoder;class Ri{async createSessionKeyPair(){return await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey","deriveBits"])}async exportPublicKey(e){const t=await crypto.subtle.exportKey("spki",e);return pr(t)}async deriveAESKey(e,t){const s=Ci(t),i=await crypto.subtle.importKey("spki",s,{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveKey({name:"ECDH",public:i},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async exportRawKey(e){const t=await crypto.subtle.exportKey("raw",e);return gs(new Uint8Array(t))}async encrypt(e,t){const s=crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},t,i);return`${gs(new Uint8Array(n))}_${gs(s)}`}async decrypt(e,t){const s=e.split("_"),i=dr(s[0]).buffer,n=dr(s[1]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},t,i);return new TextDecoder().decode(o)}async hashString(e){const t=await Ii(ji.encode(e).buffer);return pr(t)}}const we=new Uint8Array(0),He=new TextEncoder,xe=new TextDecoder;function Ni(...r){let e=0;for(let i=0;i<r.length;i++)e+=r[i].length;const t=new Uint8Array(e);let s=0;for(let i=0;i<r.length;i++)t.set(r[i],s),s+=r[i].length;return t}function yt(...r){const e=[];for(let t=0;t<r.length;t++)e.push(He.encode(r[t]));return e.length===0?we:e.length===1?e[0]:Ni(...e)}function mr(r){return!r||r.length===0?"":xe.decode(r)}const br="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",gr=36,Ti=0xcfd41b9100000,_r=33,Mi=333,yr=22;function Ui(r){for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*255)}function $i(r){var e;(e=globalThis==null?void 0:globalThis.crypto)!=null&&e.getRandomValues?globalThis.crypto.getRandomValues(r):Ui(r)}class Li{constructor(){h(this,"buf");h(this,"seq");h(this,"inc");h(this,"inited");this.buf=new Uint8Array(yr),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(Math.random()*Ti),this.inc=Math.floor(Math.random()*(Mi-_r)+_r)}setPre(){const e=new Uint8Array(12);$i(e);for(let t=0;t<12;t++){const s=e[t]%36;this.buf[t]=br.charCodeAt(s)}}fillSeq(){let e=this.seq;for(let t=yr-1;t>=12;t--)this.buf[t]=br.charCodeAt(e%gr),e=Math.floor(e/gr)}next(){return this.inited||this.init(),this.seq+=this.inc,this.seq>0xcfd41b9100000&&(this.setPre(),this.initSeqAndInc()),this.fillSeq(),String.fromCharCode.apply(String,this.buf)}reset(){this.init()}}const Je=new Li;var Pe;(function(r){r.Disconnect="disconnect",r.Reconnect="reconnect",r.Update="update",r.LDM="ldm",r.Error="error"})(Pe||(Pe={}));var Ke;(function(r){r.Reconnecting="reconnecting",r.PingTimer="pingTimer",r.StaleConnection="staleConnection",r.ClientInitiatedReconnect="client initiated reconnect"})(Ke||(Ke={}));var k;(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",r.AccountExpired="ACCOUNT_EXPIRED"})(k||(k={}));function qi(r){return typeof r.code=="string"}class wr{constructor(){h(this,"messages");this.messages=new Map,this.messages.set(k.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(k.BadJson,"Bad JSON"),this.messages.set(k.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return Fi.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}const Fi=new wr;class N extends Error{constructor(t,s,i){super(t);h(this,"name");h(this,"message");h(this,"code");h(this,"permissionContext");h(this,"chainedError");h(this,"api_error");this.name="NatsError",this.message=t,this.code=s,this.chainedError=i}static errorForCode(t,s){const i=wr.getMessage(t);return new N(i,t,s)}isAuthError(){return this.code===k.AuthenticationExpired||this.code===k.AuthorizationViolation||this.code===k.AccountExpired}isAuthTimeout(){return this.code===k.AuthenticationTimeout}isPermissionError(){return this.code===k.PermissionsViolation}isProtocolError(){return this.code===k.ProtocolError}isJetStreamError(){return this.api_error!==void 0}jsError(){return this.api_error?this.api_error:null}}var Se;(function(r){r[r.Exact=0]="Exact",r[r.CanonicalMIME=1]="CanonicalMIME",r[r.IgnoreCase=2]="IgnoreCase"})(Se||(Se={}));var je;(function(r){r.Timer="timer",r.Count="count",r.JitterTimer="jitterTimer",r.SentinelMsg="sentinelMsg"})(je||(je={}));var wt;(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"})(wt||(wt={}));const Lt="Nats-Service-Error",qt="Nats-Service-Error-Code";class Ft extends Error{constructor(t,s){super(s);h(this,"code");this.code=t}static isServiceError(t){return Ft.toServiceError(t)!==null}static toServiceError(t){var i,n;const s=((i=t==null?void 0:t.headers)==null?void 0:i.get(qt))||"";if(s!==""){const o=parseInt(s)||400,a=((n=t==null?void 0:t.headers)==null?void 0:n.get(Lt))||"";return new Ft(o,a.length?a:s)}return null}}function Fe(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}.${Je.next()}`}const _s="127.0.0.1";var ze;(function(r){r.PING="PING",r.STATS="STATS",r.INFO="INFO"})(ze||(ze={}));function Bt(r,...e){for(let t=0;t<e.length;t++){const s=e[t];Object.keys(s).forEach(function(i){r[i]=s[i]})}return r}function Dt(r){return xe.decode(r).replace(/\n/g,"␊").replace(/\r/g,"␍")}function st(r,e=!0){const t=e?N.errorForCode(k.Timeout):null;let s,i;const n=new Promise((o,a)=>{s={cancel:()=>{i&&clearTimeout(i)}},i=setTimeout(()=>{a(t===null?N.errorForCode(k.Timeout):t)},r)});return Object.assign(n,s)}function rt(r=0){let e;const t=new Promise(s=>{const i=setTimeout(()=>{s()},r);e={cancel:()=>{i&&clearTimeout(i)}}});return Object.assign(t,e)}function V(){let r={};const e=new Promise((t,s)=>{r={resolve:t,reject:s}});return Object.assign(e,r)}function xr(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 Bi(r){return r===0?0:Math.floor(r/2+Math.random()*r)}function ys(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 Bi(t>e?r[e]:r[t])}}}function W(r){return r*1e6}function ws(r){return Math.floor(r/1e6)}function Sr(r){let s=!0;const i=new Array(r.length);for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);if(o===58||o<33||o>126)throw new N(`'${r[n]}' is not a valid character for a header key`,k.BadHeader);s&&97<=o&&o<=122?o-=32:!s&&65<=o&&o<=90&&(o+=32),i[n]=o,s=o==45}return String.fromCharCode(...i)}function Be(r=0,e=""){if(r===0&&e!==""||r>0&&e==="")throw new Error("setting status requires both code and description");return new Ge(r,e)}const xs="NATS/1.0";class Ge{constructor(e=0,t=""){h(this,"_code");h(this,"headers");h(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 i=e.values(t);if(s.length!==i.length)return!1;const n=[...s].sort(),o=[...i].sort();for(let a=0;a<n.length;a++)if(n[a]!==o[a])return!1}return!0}return!1}static decode(e){const t=new Ge,i=xe.decode(e).split(`\r
2
+ `,e)}function Pi(){if(!ps())return bs.stubThis(new Promise(e=>e(!1)));const r=globalThis.PublicKeyCredential;return(r==null?void 0:r.isConditionalMediationAvailable)===void 0?bs.stubThis(new Promise(e=>e(!1))):bs.stubThis(r.isConditionalMediationAvailable())}const bs={stubThis:r=>r};function ki({error:r,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new le({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new le({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=globalThis.location.hostname;if(cr(s)){if(t.rpId!==s)return new le({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new le({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new le({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}async function Oi(r){var A,I;!r.optionsJSON&&r.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});const{optionsJSON:e,useBrowserAutofill:t=!1,verifyBrowserAutofillInput:s=!0}=r;if(!ps())throw new Error("WebAuthn is not supported in this browser");let i;((A=e.allowCredentials)==null?void 0:A.length)!==0&&(i=(I=e.allowCredentials)==null?void 0:I.map(ar));const n={...e,challenge:qe(e.challenge),allowCredentials:i},o={};if(t){if(!await Pi())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&s)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation="conditional",n.allowCredentials=[]}o.publicKey=n,o.signal=hr.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(T){throw ki({error:T,options:o})}if(!a)throw new Error("Authentication was not completed");const{id:f,rawId:p,response:g,type:y}=a;let x;return g.userHandle&&(x=Q(g.userHandle)),{id:f,rawId:Q(p),response:{authenticatorData:Q(g.authenticatorData),clientDataJSON:Q(g.clientDataJSON),signature:Q(g.signature),userHandle:x},type:y,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:ur(a.authenticatorAttachment)}}const bt="ACCESS_TOKEN",lr="SESSION_SEED",gt="LAST_AUTH_DATA";class fr{constructor(e){h(this,"onUserDataUpdate");this.options=e}get url(){return this.options.authUrl}async me(){return await fetch(this.options.authUrl+"/me",{headers:await this.getAuthHeader()}).then(t=>t.json())}async requestEmailLogin(e,t=location.href){return await fetch(this.options.authUrl+`/email-verification-request/${e}?returnUrl=${t}`,{headers:await this.getAuthHeader()}).then(_t)}async completeEmailLogin(e,t){var i;const s=await fetch(this.options.authUrl+`/email-verification-complete/${e}/${t}`,{headers:await this.getAuthHeader()}).then(_t);return await this.options.storage.setItem(bt,s.accessToken),await this.options.storage.setItem(gt,s.jwtData),(i=this.onUserDataUpdate)==null||i.call(this,s.jwtData),s.jwtData}async requestPasskeyLogin(e={}){var f,p;const{displayName:t="",isRegistration:s=!1,addAsAdditionalDevice:i=!1}=e,n=await fetch(this.options.authUrl+`/webauth-challenge-request?registration=${s?"true":""}&displayName=${t}`,{headers:await this.getAuthHeader()}).then(_t);let o;try{(f=n.user)!=null&&f.id?o=await Ai({optionsJSON:n}):o=await Oi({optionsJSON:n})}catch(g){throw g.name==="InvalidStateError"?alert("Error: Authenticator was probably already registered by user"):alert(g.message),g}const a=await fetch(this.options.authUrl+`/webauth-challenge-complete?displayName=${t}&addAsAdditionalDevice=${i?"true":""}`,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json",...await this.getAuthHeader()}}).then(_t);return await this.options.storage.setItem(bt,a.accessToken),await this.options.storage.setItem(gt,a.jwtData),(p=this.onUserDataUpdate)==null||p.call(this,a.jwtData),a.jwtData}async guestLogin(){var t;const e=await fetch(this.options.authUrl+"/guest-session").then(_t);return await this.options.storage.setItem(bt,e.accessToken),await this.options.storage.setItem(lr,e.sessionSeed),await this.options.storage.setItem(gt,e.jwtData),(t=this.onUserDataUpdate)==null||t.call(this,e.jwtData),e.jwtData}signOut(){var e;this.options.storage.removeItem(bt),this.options.storage.removeItem(gt),(e=this.onUserDataUpdate)==null||e.call(this,null)}getLastLoginData(){return this.options.storage.getItem(gt)}getAccessToken(){return this.options.storage.getItem(bt)}getSessionSeed(){return this.options.storage.getItem(lr)}async getAuthHeader(){const e=await this.getAccessToken();if(e)return{authorization:"bearer "+e}}}const _t=async r=>{const e=await r.json();if(!r.ok)throw new Error(e.message);return e},gs=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),dr=r=>new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16))),pr=r=>btoa(String.fromCharCode(...new Uint8Array(r))),Ci=r=>Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer,Ii=async r=>await crypto.subtle.digest("SHA-256",r),ji=new TextEncoder;class Ri{async createSessionKeyPair(){return await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey","deriveBits"])}async exportPublicKey(e){const t=await crypto.subtle.exportKey("spki",e);return pr(t)}async deriveAESKey(e,t){const s=Ci(t),i=await crypto.subtle.importKey("spki",s,{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveKey({name:"ECDH",public:i},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async exportRawKey(e){const t=await crypto.subtle.exportKey("raw",e);return gs(new Uint8Array(t))}async encrypt(e,t){const s=crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},t,i);return`${gs(new Uint8Array(n))}_${gs(s)}`}async decrypt(e,t){const s=e.split("_"),i=dr(s[0]).buffer,n=dr(s[1]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},t,i);return new TextDecoder().decode(o)}async hashString(e){const t=await Ii(ji.encode(e).buffer);return pr(t)}}const we=new Uint8Array(0),He=new TextEncoder,xe=new TextDecoder;function Ni(...r){let e=0;for(let i=0;i<r.length;i++)e+=r[i].length;const t=new Uint8Array(e);let s=0;for(let i=0;i<r.length;i++)t.set(r[i],s),s+=r[i].length;return t}function yt(...r){const e=[];for(let t=0;t<r.length;t++)e.push(He.encode(r[t]));return e.length===0?we:e.length===1?e[0]:Ni(...e)}function mr(r){return!r||r.length===0?"":xe.decode(r)}const br="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",gr=36,Ti=0xcfd41b9100000,_r=33,Mi=333,yr=22;function Ui(r){for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*255)}function $i(r){var e;(e=globalThis==null?void 0:globalThis.crypto)!=null&&e.getRandomValues?globalThis.crypto.getRandomValues(r):Ui(r)}class Li{constructor(){h(this,"buf");h(this,"seq");h(this,"inc");h(this,"inited");this.buf=new Uint8Array(yr),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(Math.random()*Ti),this.inc=Math.floor(Math.random()*(Mi-_r)+_r)}setPre(){const e=new Uint8Array(12);$i(e);for(let t=0;t<12;t++){const s=e[t]%36;this.buf[t]=br.charCodeAt(s)}}fillSeq(){let e=this.seq;for(let t=yr-1;t>=12;t--)this.buf[t]=br.charCodeAt(e%gr),e=Math.floor(e/gr)}next(){return this.inited||this.init(),this.seq+=this.inc,this.seq>0xcfd41b9100000&&(this.setPre(),this.initSeqAndInc()),this.fillSeq(),String.fromCharCode.apply(String,this.buf)}reset(){this.init()}}const Je=new Li;var Pe;(function(r){r.Disconnect="disconnect",r.Reconnect="reconnect",r.Update="update",r.LDM="ldm",r.Error="error"})(Pe||(Pe={}));var Ke;(function(r){r.Reconnecting="reconnecting",r.PingTimer="pingTimer",r.StaleConnection="staleConnection",r.ClientInitiatedReconnect="client initiated reconnect"})(Ke||(Ke={}));var k;(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",r.AccountExpired="ACCOUNT_EXPIRED"})(k||(k={}));function qi(r){return typeof r.code=="string"}class wr{constructor(){h(this,"messages");this.messages=new Map,this.messages.set(k.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(k.BadJson,"Bad JSON"),this.messages.set(k.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return Fi.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}const Fi=new wr;class N extends Error{constructor(t,s,i){super(t);h(this,"name");h(this,"message");h(this,"code");h(this,"permissionContext");h(this,"chainedError");h(this,"api_error");this.name="NatsError",this.message=t,this.code=s,this.chainedError=i}static errorForCode(t,s){const i=wr.getMessage(t);return new N(i,t,s)}isAuthError(){return this.code===k.AuthenticationExpired||this.code===k.AuthorizationViolation||this.code===k.AccountExpired}isAuthTimeout(){return this.code===k.AuthenticationTimeout}isPermissionError(){return this.code===k.PermissionsViolation}isProtocolError(){return this.code===k.ProtocolError}isJetStreamError(){return this.api_error!==void 0}jsError(){return this.api_error?this.api_error:null}}var Se;(function(r){r[r.Exact=0]="Exact",r[r.CanonicalMIME=1]="CanonicalMIME",r[r.IgnoreCase=2]="IgnoreCase"})(Se||(Se={}));var je;(function(r){r.Timer="timer",r.Count="count",r.JitterTimer="jitterTimer",r.SentinelMsg="sentinelMsg"})(je||(je={}));var wt;(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"})(wt||(wt={}));const Lt="Nats-Service-Error",qt="Nats-Service-Error-Code";class Ft extends Error{constructor(t,s){super(s);h(this,"code");this.code=t}static isServiceError(t){return Ft.toServiceError(t)!==null}static toServiceError(t){var i,n;const s=((i=t==null?void 0:t.headers)==null?void 0:i.get(qt))||"";if(s!==""){const o=parseInt(s)||400,a=((n=t==null?void 0:t.headers)==null?void 0:n.get(Lt))||"";return new Ft(o,a.length?a:s)}return null}}function Fe(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}.${Je.next()}`}const _s="127.0.0.1";var ze;(function(r){r.PING="PING",r.STATS="STATS",r.INFO="INFO"})(ze||(ze={}));function Bt(r,...e){for(let t=0;t<e.length;t++){const s=e[t];Object.keys(s).forEach(function(i){r[i]=s[i]})}return r}function Dt(r){return xe.decode(r).replace(/\n/g,"␊").replace(/\r/g,"␍")}function tt(r,e=!0){const t=e?N.errorForCode(k.Timeout):null;let s,i;const n=new Promise((o,a)=>{s={cancel:()=>{i&&clearTimeout(i)}},i=setTimeout(()=>{a(t===null?N.errorForCode(k.Timeout):t)},r)});return Object.assign(n,s)}function st(r=0){let e;const t=new Promise(s=>{const i=setTimeout(()=>{s()},r);e={cancel:()=>{i&&clearTimeout(i)}}});return Object.assign(t,e)}function V(){let r={};const e=new Promise((t,s)=>{r={resolve:t,reject:s}});return Object.assign(e,r)}function xr(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 Bi(r){return r===0?0:Math.floor(r/2+Math.random()*r)}function ys(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 Bi(t>e?r[e]:r[t])}}}function W(r){return r*1e6}function ws(r){return Math.floor(r/1e6)}function Sr(r){let s=!0;const i=new Array(r.length);for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);if(o===58||o<33||o>126)throw new N(`'${r[n]}' is not a valid character for a header key`,k.BadHeader);s&&97<=o&&o<=122?o-=32:!s&&65<=o&&o<=90&&(o+=32),i[n]=o,s=o==45}return String.fromCharCode(...i)}function Be(r=0,e=""){if(r===0&&e!==""||r>0&&e==="")throw new Error("setting status requires both code and description");return new Ge(r,e)}const xs="NATS/1.0";class Ge{constructor(e=0,t=""){h(this,"_code");h(this,"headers");h(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 i=e.values(t);if(s.length!==i.length)return!1;const n=[...s].sort(),o=[...i].sort();for(let a=0;a<n.length;a++)if(n[a]!==o[a])return!1}return!0}return!1}static decode(e){const t=new Ge,i=xe.decode(e).split(`\r
3
3
  `),n=i[0];if(n!==xs){let o=n.replace(xs,"").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 i.length>=1&&i.slice(1).map(o=>{if(o){const a=o.indexOf(":");if(a>-1){const f=o.slice(0,a),p=o.slice(a+1).trim();t.append(f,p)}}}),t}toString(){if(this.headers.size===0&&this._code===0)return"";let e=xs;this._code>0&&this._description!==""&&(e+=` ${this._code} ${this._description}`);for(const[t,s]of this.headers)for(let i=0;i<s.length;i++)e=`${e}\r
4
4
  ${t}: ${s[i]}`;return`${e}\r
5
5
  \r
6
- `}encode(){return He.encode(this.toString())}static validHeaderValue(e){if(/[\r\n]/.test(e))throw new N("invalid header value - \\r and \\n are not allowed.",k.BadHeader);return e.trim()}keys(){const e=[];for(const t of this.headers.keys())e.push(t);return e}findKeys(e,t=Se.Exact){const s=this.keys();switch(t){case Se.Exact:return s.filter(i=>i===e);case Se.CanonicalMIME:return e=Sr(e),s.filter(i=>i===e);default:{const i=e.toLowerCase();return s.filter(n=>i===n.toLowerCase())}}}get(e,t=Se.Exact){const s=this.findKeys(e,t);if(s.length){const i=this.headers.get(s[0]);if(i)return Array.isArray(i)?i[0]:i}return""}last(e,t=Se.Exact){const s=this.findKeys(e,t);if(s.length){const i=this.headers.get(s[0]);if(i)return Array.isArray(i)?i[i.length-1]:i}return""}has(e,t=Se.Exact){return this.findKeys(e,t).length>0}set(e,t,s=Se.Exact){this.delete(e,s),this.append(e,t,s)}append(e,t,s=Se.Exact){const i=Sr(e);s===Se.CanonicalMIME&&(e=i);const n=this.findKeys(e,s);e=n.length>0?n[0]:e;const o=Ge.validHeaderValue(t);let a=this.headers.get(e);a||(a=[],this.headers.set(e,a)),a.push(o)}values(e,t=Se.Exact){const s=[];return this.findKeys(e,t).forEach(n=>{const o=this.headers.get(n);o&&s.push(...o)}),s}delete(e,t=Se.Exact){this.findKeys(e,t).forEach(i=>{this.headers.delete(i)})}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 Ge;for(const s in e)t.headers.set(s,e[s]);return t}}function Ss(){return{encode(r){return He.encode(r)},decode(r){return xe.decode(r)}}}function ke(r){return{encode(e){try{return e===void 0&&(e=null),He.encode(JSON.stringify(e))}catch(t){throw N.errorForCode(k.BadJson,t)}},decode(e){try{return JSON.parse(xe.decode(e),r)}catch(t){throw N.errorForCode(k.BadJson,t)}}}}function vr(r){var e;return r&&r.data.length===0&&((e=r.headers)==null?void 0:e.code)===503?N.errorForCode(k.NoResponders):null}class vs{constructor(e,t,s){h(this,"_headers");h(this,"_msg");h(this,"_rdata");h(this,"_reply");h(this,"_subject");h(this,"publisher");this._msg=e,this._rdata=t,this.publisher=s}get subject(){return this._subject?this._subject:(this._subject=xe.decode(this._msg.subject),this._subject)}get reply(){return this._reply?this._reply:(this._reply=xe.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=Ge.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=we,t){return this.reply?(this.publisher.publish(this.reply,e,t),!0):!1}size(){var i;const e=this._msg.subject.length,t=((i=this._msg.reply)==null?void 0:i.length)||0,s=this._msg.size===-1?0:this._msg.size;return e+t+s}json(e){return ke(e).decode(this.data)}string(){return xe.decode(this.data)}requestInfo(){var t;const e=(t=this.headers)==null?void 0:t.get("Nats-Request-Info");return e?JSON.parse(e,function(s,i){return(s==="start"||s==="stop")&&i!==""?new Date(Date.parse(i)):i}):null}}h(vs,"jc");function it(r){return Ht("durable",r)}function pe(r){return Ht("stream",r)}function Ht(r,e=""){if(e==="")throw Error(`${r} name required`);return[".","*",">","/","\\"," "," ",`
6
+ `}encode(){return He.encode(this.toString())}static validHeaderValue(e){if(/[\r\n]/.test(e))throw new N("invalid header value - \\r and \\n are not allowed.",k.BadHeader);return e.trim()}keys(){const e=[];for(const t of this.headers.keys())e.push(t);return e}findKeys(e,t=Se.Exact){const s=this.keys();switch(t){case Se.Exact:return s.filter(i=>i===e);case Se.CanonicalMIME:return e=Sr(e),s.filter(i=>i===e);default:{const i=e.toLowerCase();return s.filter(n=>i===n.toLowerCase())}}}get(e,t=Se.Exact){const s=this.findKeys(e,t);if(s.length){const i=this.headers.get(s[0]);if(i)return Array.isArray(i)?i[0]:i}return""}last(e,t=Se.Exact){const s=this.findKeys(e,t);if(s.length){const i=this.headers.get(s[0]);if(i)return Array.isArray(i)?i[i.length-1]:i}return""}has(e,t=Se.Exact){return this.findKeys(e,t).length>0}set(e,t,s=Se.Exact){this.delete(e,s),this.append(e,t,s)}append(e,t,s=Se.Exact){const i=Sr(e);s===Se.CanonicalMIME&&(e=i);const n=this.findKeys(e,s);e=n.length>0?n[0]:e;const o=Ge.validHeaderValue(t);let a=this.headers.get(e);a||(a=[],this.headers.set(e,a)),a.push(o)}values(e,t=Se.Exact){const s=[];return this.findKeys(e,t).forEach(n=>{const o=this.headers.get(n);o&&s.push(...o)}),s}delete(e,t=Se.Exact){this.findKeys(e,t).forEach(i=>{this.headers.delete(i)})}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 Ge;for(const s in e)t.headers.set(s,e[s]);return t}}function Ss(){return{encode(r){return He.encode(r)},decode(r){return xe.decode(r)}}}function ke(r){return{encode(e){try{return e===void 0&&(e=null),He.encode(JSON.stringify(e))}catch(t){throw N.errorForCode(k.BadJson,t)}},decode(e){try{return JSON.parse(xe.decode(e),r)}catch(t){throw N.errorForCode(k.BadJson,t)}}}}function vr(r){var e;return r&&r.data.length===0&&((e=r.headers)==null?void 0:e.code)===503?N.errorForCode(k.NoResponders):null}class vs{constructor(e,t,s){h(this,"_headers");h(this,"_msg");h(this,"_rdata");h(this,"_reply");h(this,"_subject");h(this,"publisher");this._msg=e,this._rdata=t,this.publisher=s}get subject(){return this._subject?this._subject:(this._subject=xe.decode(this._msg.subject),this._subject)}get reply(){return this._reply?this._reply:(this._reply=xe.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=Ge.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=we,t){return this.reply?(this.publisher.publish(this.reply,e,t),!0):!1}size(){var i;const e=this._msg.subject.length,t=((i=this._msg.reply)==null?void 0:i.length)||0,s=this._msg.size===-1?0:this._msg.size;return e+t+s}json(e){return ke(e).decode(this.data)}string(){return xe.decode(this.data)}requestInfo(){var t;const e=(t=this.headers)==null?void 0:t.get("Nats-Request-Info");return e?JSON.parse(e,function(s,i){return(s==="start"||s==="stop")&&i!==""?new Date(Date.parse(i)):i}):null}}h(vs,"jc");function rt(r){return Ht("durable",r)}function pe(r){return Ht("stream",r)}function Ht(r,e=""){if(e==="")throw Error(`${r} name required`);return[".","*",">","/","\\"," "," ",`
7
7
  `,"\r"].forEach(s=>{if(e.indexOf(s)!==-1){switch(s){case`
8
- `:s="\\n";break;case"\r":s="\\r";break;case" ":s="\\t";break}throw Error(`invalid ${r} name - ${r} name cannot contain '${s}'`)}}),""}function xt(r,e=""){if(e==="")throw Error(`${r} name required`);const t=Di(e);if(t.length)throw new Error(`invalid ${r} name - ${r} name ${t}`)}function Di(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 Es(r){if(r.data.length>0)return!1;const e=r.headers;return e?e.code>=100&&e.code<200:!1}function As(r){var e;return Es(r)&&((e=r.headers)==null?void 0:e.description)==="Idle Heartbeat"}function Hi(r,e,t){const s=Be(r,e),i={hdr:1,sid:0,size:0},n=new vs(i,we,{});return n._headers=s,n._subject=t,n}function nt(r){if(r.data.length!==0)return null;const e=r.headers;return e?Er(e.code,e.description):null}var Oe;(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"})(Oe||(Oe={}));function Ji(r){return r.code!==k.JetStream409?!1:[Oe.MaxBatchExceeded,Oe.MaxExpiresExceeded,Oe.MaxBytesExceeded,Oe.MaxMessageSizeExceeded,Oe.PushConsumer,Oe.IdleHeartbeatMissed,Oe.ConsumerDeleted].find(t=>r.message.indexOf(t)!==-1)!==void 0}function Er(r,e=""){if(r<300)return null;switch(e=e.toLowerCase(),r){case 404:return new N(e,k.JetStream404NoMessages);case 408:return new N(e,k.JetStream408RequestTimeout);case 409:{const t=e.startsWith(Oe.IdleHeartbeatMissed)?k.JetStreamIdleHeartBeat:k.JetStream409;return new N(e,t)}case 503:return N.errorForCode(k.JetStreamNotEnabled,new Error(e));default:return e===""&&(e=k.Unknown),new N(e,`${r}`)}}class oe{constructor(){h(this,"inflight");h(this,"processed");h(this,"received");h(this,"noIterator");h(this,"iterClosed");h(this,"done");h(this,"signal");h(this,"yields");h(this,"filtered");h(this,"pendingFiltered");h(this,"ingestionFilterFn");h(this,"protocolFilterFn");h(this,"dispatchedFn");h(this,"ctx");h(this,"_data");h(this,"err");h(this,"time");h(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=V(),this.yields=[],this.iterClosed=V(),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 N("unsupported iterator",k.ApiError);if(this.yielding)throw new N("already yielding",k.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 i=e[t];try{i()}catch(n){throw n}if(this.err)throw this.err;continue}if(this.protocolFilterFn?this.protocolFilterFn(e[t]):!0){this.processed++;const i=Date.now();yield e[t],this.time=Date.now()-i,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=V())}}finally{this.stop()}}stop(e){this.done||(this.err=e,this.done=!0,this.signal.resolve(),this.iterClosed.resolve(e))}getProcessed(){return this.noIterator?this.received:this.processed}getPending(){return this.yields.length+this.inflight-this.pendingFiltered}getReceived(){return this.received-this.filtered}}class Ps{constructor(e,t,s={maxOut:2}){h(this,"interval");h(this,"maxOut");h(this,"cancelAfter");h(this,"timer");h(this,"autoCancelTimer");h(this,"last");h(this,"missed");h(this,"count");h(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,this.missed=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 ks;(function(r){r.Limits="limits",r.Interest="interest",r.Workqueue="workqueue"})(ks||(ks={}));var St;(function(r){r.Old="old",r.New="new"})(St||(St={}));var Os;(function(r){r.File="file",r.Memory="memory"})(Os||(Os={}));var te;(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"})(te||(te={}));var ae;(function(r){r.None="none",r.All="all",r.Explicit="explicit",r.NotSet=""})(ae||(ae={}));var ot;(function(r){r.Instant="instant",r.Original="original"})(ot||(ot={}));var Ve;(function(r){r.None="none",r.S2="s2"})(Ve||(Ve={}));var Jt;(function(r){r.CreateOrUpdate="",r.Update="update",r.Create="create"})(Jt||(Jt={}));function Ki(r,e={}){return Object.assign({name:r,deliver_policy:te.All,ack_policy:ae.Explicit,ack_wait:W(30*1e3),replay_policy:ot.Instant},e)}var Ar;(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"})(Ar||(Ar={}));var me;(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"})(me||(me={}));var Re;(function(r){r.LastValue="",r.AllHistory="history",r.UpdatesOnly="updates"})(Re||(Re={}));var at;(function(r){r.Stream="Nats-Stream",r.Sequence="Nats-Sequence",r.TimeStamp="Nats-Time-Stamp",r.Subject="Nats-Subject"})(at||(at={}));var Pr;(function(r){r.Stream="Nats-Stream",r.Subject="Nats-Subject",r.Sequence="Nats-Sequence",r.LastSequence="Nats-Last-Sequence",r.Size="Nats-Msg-Size"})(Pr||(Pr={}));const ve="KV_";class zi{constructor(e){h(this,"config");h(this,"ordered");h(this,"mack");h(this,"stream");h(this,"callbackFn");h(this,"max");h(this,"qname");h(this,"isBind");h(this,"filters");this.stream="",this.mack=!1,this.ordered=!1,this.config=Ki("",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?ae.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 it(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=te.StartSequence,this.config.opt_start_seq=e,this}startTime(e){return this.config.deliver_policy=te.StartTime,this.config.opt_start_time=e.toISOString(),this}deliverAll(){return this.config.deliver_policy=te.All,this}deliverLastPerSubject(){return this.config.deliver_policy=te.LastPerSubject,this}deliverLast(){return this.config.deliver_policy=te.Last,this}deliverNew(){return this.config.deliver_policy=te.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=ae.None,this}ackAll(){return this.config.ack_policy=ae.All,this}ackExplicit(){return this.config.ack_policy=ae.Explicit,this}ackWait(e){return this.config.ack_wait=W(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=ot.Instant,this}replayOriginal(){return this.config.replay_policy=ot.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=W(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=W(e),this}maxPullBatch(e){return this.config.max_batch=e,this}maxPullRequestExpires(e){return this.config.max_expires=W(e),this}memory(){return this.config.mem_storage=!0,this}numReplicas(e){return this.config.num_replicas=e,this}consumerName(e){return this.config.name=e,this}}function We(r){return new zi(r)}function kr(r){return typeof r.getOpts=="function"}class Gi{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,i=>i.charCodeAt(0)):s}}class ct{static encode(e){return ct.toB64URLEncoding(Gi.encode(e))}static decode(e,t=!1){return ct.decode(ct.fromB64URLEncoding(e),t)}static toB64URLEncoding(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}static fromB64URLEncoding(e){return e.replace(/_/g,"/").replace(/-/g,"+")}}class ht{constructor(){h(this,"buffers");h(this,"byteLength");this.buffers=[],this.byteLength=0}static concat(...e){let t=0;for(let n=0;n<e.length;n++)t+=e[n].length;const s=new Uint8Array(t);let i=0;for(let n=0;n<e.length;n++)s.set(e[n],i),i+=e[n].length;return s}static fromAscii(e){return e||(e=""),He.encode(e)}static toAscii(e){return xe.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 i=t.subarray(0,e);return s>e&&this.buffers.push(t.subarray(e)),this.byteLength=s-e,i}}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}}function Vi(r,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(s){if(s!=="default"&&!(s in r)){var i=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(r,s,i.get?i:{enumerable:!0,get:function(){return t[s]}})}})}),Object.freeze(r)}var Wi=typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{},vt=Wi.performance||{};vt.now||vt.mozNow||vt.msNow||vt.oNow||vt.webkitNow;var Or={versions:{}},Yi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Xi(r){if(r.__esModule)return r;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(r).forEach(function(t){var s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:function(){return r[t]}})}),e}var Cs,Kt={exports:{}},Cr={},Ir=Xi(Vi({__proto__:null,default:Cr},[Cr]));Cs=Kt,function(){var r="input is invalid type",e=typeof window=="object",t=e?window:{};t.JS_SHA256_NO_WINDOW&&(e=!1);var s=!e&&typeof self=="object",i=!t.JS_SHA256_NO_NODE_JS&&Or.versions&&Or.versions.node;i?t=Yi:s&&(t=self);var n=!t.JS_SHA256_NO_COMMON_JS&&Cs.exports,o=!t.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",a="0123456789abcdef".split(""),f=[-2147483648,8388608,32768,128],p=[24,16,8,0],g=[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],y=["hex","array","digest","arrayBuffer"],x=[];!t.JS_SHA256_NO_NODE_JS&&Array.isArray||(Array.isArray=function(w){return Object.prototype.toString.call(w)==="[object Array]"}),!o||!t.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(w){return typeof w=="object"&&w.buffer&&w.buffer.constructor===ArrayBuffer});var A=function(w,j){return function(F){return new L(j,!0).update(F)[w]()}},I=function(w){var j=A("hex",w);i&&(j=T(j,w)),j.create=function(){return new L(w)},j.update=function(P){return j.create().update(P)};for(var F=0;F<y.length;++F){var R=y[F];j[R]=A(R,w)}return j},T=function(w,j){var F,R=Ir,P=Ir.Buffer,U=j?"sha224":"sha256";return F=P.from&&!t.JS_SHA256_NO_BUFFER_FROM?P.from:function(q){return new P(q)},function(q){if(typeof q=="string")return R.createHash(U).update(q,"utf8").digest("hex");if(q==null)throw new Error(r);return q.constructor===ArrayBuffer&&(q=new Uint8Array(q)),Array.isArray(q)||ArrayBuffer.isView(q)||q.constructor===P?R.createHash(U).update(F(q)).digest("hex"):w(q)}},J=function(w,j){return function(F,R){return new ee(F,j,!0).update(R)[w]()}},se=function(w){var j=J("hex",w);j.create=function(P){return new ee(P,w)},j.update=function(P,U){return j.create(P).update(U)};for(var F=0;F<y.length;++F){var R=y[F];j[R]=J(R,w)}return j};function L(w,j){j?(x[0]=x[16]=x[1]=x[2]=x[3]=x[4]=x[5]=x[6]=x[7]=x[8]=x[9]=x[10]=x[11]=x[12]=x[13]=x[14]=x[15]=0,this.blocks=x):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],w?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=w}function ee(w,j,F){var R,P=typeof w;if(P==="string"){var U,q=[],$=w.length,Y=0;for(R=0;R<$;++R)(U=w.charCodeAt(R))<128?q[Y++]=U:U<2048?(q[Y++]=192|U>>>6,q[Y++]=128|63&U):U<55296||U>=57344?(q[Y++]=224|U>>>12,q[Y++]=128|U>>>6&63,q[Y++]=128|63&U):(U=65536+((1023&U)<<10|1023&w.charCodeAt(++R)),q[Y++]=240|U>>>18,q[Y++]=128|U>>>12&63,q[Y++]=128|U>>>6&63,q[Y++]=128|63&U);w=q}else{if(P!=="object")throw new Error(r);if(w===null)throw new Error(r);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!(Array.isArray(w)||o&&ArrayBuffer.isView(w)))throw new Error(r)}w.length>64&&(w=new L(j,!0).update(w).array());var ie=[],ce=[];for(R=0;R<64;++R){var ne=w[R]||0;ie[R]=92^ne,ce[R]=54^ne}L.call(this,j,F),this.update(ce),this.oKeyPad=ie,this.inner=!0,this.sharedMemory=F}L.prototype.update=function(w){if(!this.finalized){var j,F=typeof w;if(F!=="string"){if(F!=="object")throw new Error(r);if(w===null)throw new Error(r);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!(Array.isArray(w)||o&&ArrayBuffer.isView(w)))throw new Error(r);j=!0}for(var R,P,U=0,q=w.length,$=this.blocks;U<q;){if(this.hashed&&(this.hashed=!1,$[0]=this.block,this.block=$[16]=$[1]=$[2]=$[3]=$[4]=$[5]=$[6]=$[7]=$[8]=$[9]=$[10]=$[11]=$[12]=$[13]=$[14]=$[15]=0),j)for(P=this.start;U<q&&P<64;++U)$[P>>>2]|=w[U]<<p[3&P++];else for(P=this.start;U<q&&P<64;++U)(R=w.charCodeAt(U))<128?$[P>>>2]|=R<<p[3&P++]:R<2048?($[P>>>2]|=(192|R>>>6)<<p[3&P++],$[P>>>2]|=(128|63&R)<<p[3&P++]):R<55296||R>=57344?($[P>>>2]|=(224|R>>>12)<<p[3&P++],$[P>>>2]|=(128|R>>>6&63)<<p[3&P++],$[P>>>2]|=(128|63&R)<<p[3&P++]):(R=65536+((1023&R)<<10|1023&w.charCodeAt(++U)),$[P>>>2]|=(240|R>>>18)<<p[3&P++],$[P>>>2]|=(128|R>>>12&63)<<p[3&P++],$[P>>>2]|=(128|R>>>6&63)<<p[3&P++],$[P>>>2]|=(128|63&R)<<p[3&P++]);this.lastByteIndex=P,this.bytes+=P-this.start,P>=64?(this.block=$[16],this.start=P-64,this.hash(),this.hashed=!0):this.start=P}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this}},L.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var w=this.blocks,j=this.lastByteIndex;w[16]=this.block,w[j>>>2]|=f[3&j],this.block=w[16],j>=56&&(this.hashed||this.hash(),w[0]=this.block,w[16]=w[1]=w[2]=w[3]=w[4]=w[5]=w[6]=w[7]=w[8]=w[9]=w[10]=w[11]=w[12]=w[13]=w[14]=w[15]=0),w[14]=this.hBytes<<3|this.bytes>>>29,w[15]=this.bytes<<3,this.hash()}},L.prototype.hash=function(){var w,j,F,R,P,U,q,$,Y,ie=this.h0,ce=this.h1,ne=this.h2,he=this.h3,fe=this.h4,de=this.h5,X=this.h6,re=this.h7,ue=this.blocks;for(w=16;w<64;++w)j=((P=ue[w-15])>>>7|P<<25)^(P>>>18|P<<14)^P>>>3,F=((P=ue[w-2])>>>17|P<<15)^(P>>>19|P<<13)^P>>>10,ue[w]=ue[w-16]+j+ue[w-7]+F|0;for(Y=ce&ne,w=0;w<64;w+=4)this.first?(this.is224?(U=300032,re=(P=ue[0]-1413257819)-150054599|0,he=P+24177077|0):(U=704751109,re=(P=ue[0]-210244248)-1521486534|0,he=P+143694565|0),this.first=!1):(j=(ie>>>2|ie<<30)^(ie>>>13|ie<<19)^(ie>>>22|ie<<10),R=(U=ie&ce)^ie&ne^Y,re=he+(P=re+(F=(fe>>>6|fe<<26)^(fe>>>11|fe<<21)^(fe>>>25|fe<<7))+(fe&de^~fe&X)+g[w]+ue[w])|0,he=P+(j+R)|0),j=(he>>>2|he<<30)^(he>>>13|he<<19)^(he>>>22|he<<10),R=(q=he&ie)^he&ce^U,X=ne+(P=X+(F=(re>>>6|re<<26)^(re>>>11|re<<21)^(re>>>25|re<<7))+(re&fe^~re&de)+g[w+1]+ue[w+1])|0,j=((ne=P+(j+R)|0)>>>2|ne<<30)^(ne>>>13|ne<<19)^(ne>>>22|ne<<10),R=($=ne&he)^ne&ie^q,de=ce+(P=de+(F=(X>>>6|X<<26)^(X>>>11|X<<21)^(X>>>25|X<<7))+(X&re^~X&fe)+g[w+2]+ue[w+2])|0,j=((ce=P+(j+R)|0)>>>2|ce<<30)^(ce>>>13|ce<<19)^(ce>>>22|ce<<10),R=(Y=ce&ne)^ce&he^$,fe=ie+(P=fe+(F=(de>>>6|de<<26)^(de>>>11|de<<21)^(de>>>25|de<<7))+(de&X^~de&re)+g[w+3]+ue[w+3])|0,ie=P+(j+R)|0,this.chromeBugWorkAround=!0;this.h0=this.h0+ie|0,this.h1=this.h1+ce|0,this.h2=this.h2+ne|0,this.h3=this.h3+he|0,this.h4=this.h4+fe|0,this.h5=this.h5+de|0,this.h6=this.h6+X|0,this.h7=this.h7+re|0},L.prototype.hex=function(){this.finalize();var w=this.h0,j=this.h1,F=this.h2,R=this.h3,P=this.h4,U=this.h5,q=this.h6,$=this.h7,Y=a[w>>>28&15]+a[w>>>24&15]+a[w>>>20&15]+a[w>>>16&15]+a[w>>>12&15]+a[w>>>8&15]+a[w>>>4&15]+a[15&w]+a[j>>>28&15]+a[j>>>24&15]+a[j>>>20&15]+a[j>>>16&15]+a[j>>>12&15]+a[j>>>8&15]+a[j>>>4&15]+a[15&j]+a[F>>>28&15]+a[F>>>24&15]+a[F>>>20&15]+a[F>>>16&15]+a[F>>>12&15]+a[F>>>8&15]+a[F>>>4&15]+a[15&F]+a[R>>>28&15]+a[R>>>24&15]+a[R>>>20&15]+a[R>>>16&15]+a[R>>>12&15]+a[R>>>8&15]+a[R>>>4&15]+a[15&R]+a[P>>>28&15]+a[P>>>24&15]+a[P>>>20&15]+a[P>>>16&15]+a[P>>>12&15]+a[P>>>8&15]+a[P>>>4&15]+a[15&P]+a[U>>>28&15]+a[U>>>24&15]+a[U>>>20&15]+a[U>>>16&15]+a[U>>>12&15]+a[U>>>8&15]+a[U>>>4&15]+a[15&U]+a[q>>>28&15]+a[q>>>24&15]+a[q>>>20&15]+a[q>>>16&15]+a[q>>>12&15]+a[q>>>8&15]+a[q>>>4&15]+a[15&q];return this.is224||(Y+=a[$>>>28&15]+a[$>>>24&15]+a[$>>>20&15]+a[$>>>16&15]+a[$>>>12&15]+a[$>>>8&15]+a[$>>>4&15]+a[15&$]),Y},L.prototype.toString=L.prototype.hex,L.prototype.digest=function(){this.finalize();var w=this.h0,j=this.h1,F=this.h2,R=this.h3,P=this.h4,U=this.h5,q=this.h6,$=this.h7,Y=[w>>>24&255,w>>>16&255,w>>>8&255,255&w,j>>>24&255,j>>>16&255,j>>>8&255,255&j,F>>>24&255,F>>>16&255,F>>>8&255,255&F,R>>>24&255,R>>>16&255,R>>>8&255,255&R,P>>>24&255,P>>>16&255,P>>>8&255,255&P,U>>>24&255,U>>>16&255,U>>>8&255,255&U,q>>>24&255,q>>>16&255,q>>>8&255,255&q];return this.is224||Y.push($>>>24&255,$>>>16&255,$>>>8&255,255&$),Y},L.prototype.array=L.prototype.digest,L.prototype.arrayBuffer=function(){this.finalize();var w=new ArrayBuffer(this.is224?28:32),j=new DataView(w);return j.setUint32(0,this.h0),j.setUint32(4,this.h1),j.setUint32(8,this.h2),j.setUint32(12,this.h3),j.setUint32(16,this.h4),j.setUint32(20,this.h5),j.setUint32(24,this.h6),this.is224||j.setUint32(28,this.h7),w},ee.prototype=new L,ee.prototype.finalize=function(){if(L.prototype.finalize.call(this),this.inner){this.inner=!1;var w=this.array();L.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(w),L.prototype.finalize.call(this)}};var _e=I();_e.sha256=_e,_e.sha224=I(!0),_e.sha256.hmac=se(),_e.sha224.hmac=se(!0),n?Cs.exports=_e:(t.sha256=_e.sha256,t.sha224=_e.sha224)}(),Kt.exports,Kt.exports.sha224;var jr=Kt.exports.sha256;function Is(r){return rn(r)}function Zi(r){if(!/^[0-9A-Fa-f]+$/.test(r))return!1;const t=/^[0-9A-F]+$/.test(r),s=/^[0-9a-f]+$/.test(r);return t||s?r.length%2===0:!1}function Qi(r){return/^[A-Za-z0-9\-_]*(={0,2})?$/.test(r)||/^[A-Za-z0-9+/]*(={0,2})?$/.test(r)}function en(r){return Zi(r)?"hex":Qi(r)?"b64":""}function tn(r){if(r.length%2!==0)throw new Error("hex string must have an even length");const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.substring(t,t+2),16);return e}function sn(r){r=r.replace(/-/g,"+"),r=r.replace(/_/g,"/");const e=atob(r);return Uint8Array.from(e,t=>t.charCodeAt(0))}function rn(r){switch(en(r)){case"hex":return tn(r);case"b64":return sn(r)}return null}function nn(r,e){const t=typeof r=="string"?Is(r):r,s=typeof e=="string"?Is(e):e;if(t===null||s===null||t.length!==s.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==s[i])return!1;return!0}class Rr{constructor(e,t,s=!0){h(this,"token");h(this,"received");h(this,"ctx");h(this,"requestSubject");h(this,"mux");this.mux=e,this.requestSubject=t,this.received=0,this.token=Je.next(),s&&(this.ctx=new Error)}}class on extends Rr{constructor(t,s,i={maxWait:1e3}){super(t,s);h(this,"callback");h(this,"done");h(this,"timer");h(this,"max");h(this,"opts");if(this.opts=i,typeof this.opts.callback!="function")throw new Error("callback is required");this.callback=this.opts.callback,this.max=typeof i.maxMessages=="number"&&i.maxMessages>0?i.maxMessages:-1,this.done=V(),this.done.then(()=>{this.callback(null,null)}),this.timer=setTimeout(()=>{this.cancel()},i.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+=`
8
+ `:s="\\n";break;case"\r":s="\\r";break;case" ":s="\\t";break}throw Error(`invalid ${r} name - ${r} name cannot contain '${s}'`)}}),""}function xt(r,e=""){if(e==="")throw Error(`${r} name required`);const t=Di(e);if(t.length)throw new Error(`invalid ${r} name - ${r} name ${t}`)}function Di(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 Es(r){if(r.data.length>0)return!1;const e=r.headers;return e?e.code>=100&&e.code<200:!1}function As(r){var e;return Es(r)&&((e=r.headers)==null?void 0:e.description)==="Idle Heartbeat"}function Hi(r,e,t){const s=Be(r,e),i={hdr:1,sid:0,size:0},n=new vs(i,we,{});return n._headers=s,n._subject=t,n}function it(r){if(r.data.length!==0)return null;const e=r.headers;return e?Er(e.code,e.description):null}var Oe;(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"})(Oe||(Oe={}));function Ji(r){return r.code!==k.JetStream409?!1:[Oe.MaxBatchExceeded,Oe.MaxExpiresExceeded,Oe.MaxBytesExceeded,Oe.MaxMessageSizeExceeded,Oe.PushConsumer,Oe.IdleHeartbeatMissed,Oe.ConsumerDeleted].find(t=>r.message.indexOf(t)!==-1)!==void 0}function Er(r,e=""){if(r<300)return null;switch(e=e.toLowerCase(),r){case 404:return new N(e,k.JetStream404NoMessages);case 408:return new N(e,k.JetStream408RequestTimeout);case 409:{const t=e.startsWith(Oe.IdleHeartbeatMissed)?k.JetStreamIdleHeartBeat:k.JetStream409;return new N(e,t)}case 503:return N.errorForCode(k.JetStreamNotEnabled,new Error(e));default:return e===""&&(e=k.Unknown),new N(e,`${r}`)}}class oe{constructor(){h(this,"inflight");h(this,"processed");h(this,"received");h(this,"noIterator");h(this,"iterClosed");h(this,"done");h(this,"signal");h(this,"yields");h(this,"filtered");h(this,"pendingFiltered");h(this,"ingestionFilterFn");h(this,"protocolFilterFn");h(this,"dispatchedFn");h(this,"ctx");h(this,"_data");h(this,"err");h(this,"time");h(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=V(),this.yields=[],this.iterClosed=V(),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 N("unsupported iterator",k.ApiError);if(this.yielding)throw new N("already yielding",k.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 i=e[t];try{i()}catch(n){throw n}if(this.err)throw this.err;continue}if(this.protocolFilterFn?this.protocolFilterFn(e[t]):!0){this.processed++;const i=Date.now();yield e[t],this.time=Date.now()-i,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=V())}}finally{this.stop()}}stop(e){this.done||(this.err=e,this.done=!0,this.signal.resolve(),this.iterClosed.resolve(e))}getProcessed(){return this.noIterator?this.received:this.processed}getPending(){return this.yields.length+this.inflight-this.pendingFiltered}getReceived(){return this.received-this.filtered}}class Ps{constructor(e,t,s={maxOut:2}){h(this,"interval");h(this,"maxOut");h(this,"cancelAfter");h(this,"timer");h(this,"autoCancelTimer");h(this,"last");h(this,"missed");h(this,"count");h(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,this.missed=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 ks;(function(r){r.Limits="limits",r.Interest="interest",r.Workqueue="workqueue"})(ks||(ks={}));var St;(function(r){r.Old="old",r.New="new"})(St||(St={}));var Os;(function(r){r.File="file",r.Memory="memory"})(Os||(Os={}));var te;(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"})(te||(te={}));var ae;(function(r){r.None="none",r.All="all",r.Explicit="explicit",r.NotSet=""})(ae||(ae={}));var nt;(function(r){r.Instant="instant",r.Original="original"})(nt||(nt={}));var Ve;(function(r){r.None="none",r.S2="s2"})(Ve||(Ve={}));var Jt;(function(r){r.CreateOrUpdate="",r.Update="update",r.Create="create"})(Jt||(Jt={}));function Ki(r,e={}){return Object.assign({name:r,deliver_policy:te.All,ack_policy:ae.Explicit,ack_wait:W(30*1e3),replay_policy:nt.Instant},e)}var Ar;(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"})(Ar||(Ar={}));var me;(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"})(me||(me={}));var Re;(function(r){r.LastValue="",r.AllHistory="history",r.UpdatesOnly="updates"})(Re||(Re={}));var ot;(function(r){r.Stream="Nats-Stream",r.Sequence="Nats-Sequence",r.TimeStamp="Nats-Time-Stamp",r.Subject="Nats-Subject"})(ot||(ot={}));var Pr;(function(r){r.Stream="Nats-Stream",r.Subject="Nats-Subject",r.Sequence="Nats-Sequence",r.LastSequence="Nats-Last-Sequence",r.Size="Nats-Msg-Size"})(Pr||(Pr={}));const ve="KV_";class zi{constructor(e){h(this,"config");h(this,"ordered");h(this,"mack");h(this,"stream");h(this,"callbackFn");h(this,"max");h(this,"qname");h(this,"isBind");h(this,"filters");this.stream="",this.mack=!1,this.ordered=!1,this.config=Ki("",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?ae.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 rt(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=te.StartSequence,this.config.opt_start_seq=e,this}startTime(e){return this.config.deliver_policy=te.StartTime,this.config.opt_start_time=e.toISOString(),this}deliverAll(){return this.config.deliver_policy=te.All,this}deliverLastPerSubject(){return this.config.deliver_policy=te.LastPerSubject,this}deliverLast(){return this.config.deliver_policy=te.Last,this}deliverNew(){return this.config.deliver_policy=te.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=ae.None,this}ackAll(){return this.config.ack_policy=ae.All,this}ackExplicit(){return this.config.ack_policy=ae.Explicit,this}ackWait(e){return this.config.ack_wait=W(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=nt.Instant,this}replayOriginal(){return this.config.replay_policy=nt.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=W(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=W(e),this}maxPullBatch(e){return this.config.max_batch=e,this}maxPullRequestExpires(e){return this.config.max_expires=W(e),this}memory(){return this.config.mem_storage=!0,this}numReplicas(e){return this.config.num_replicas=e,this}consumerName(e){return this.config.name=e,this}}function We(r){return new zi(r)}function kr(r){return typeof r.getOpts=="function"}class Gi{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,i=>i.charCodeAt(0)):s}}class at{static encode(e){return at.toB64URLEncoding(Gi.encode(e))}static decode(e,t=!1){return at.decode(at.fromB64URLEncoding(e),t)}static toB64URLEncoding(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}static fromB64URLEncoding(e){return e.replace(/_/g,"/").replace(/-/g,"+")}}class ct{constructor(){h(this,"buffers");h(this,"byteLength");this.buffers=[],this.byteLength=0}static concat(...e){let t=0;for(let n=0;n<e.length;n++)t+=e[n].length;const s=new Uint8Array(t);let i=0;for(let n=0;n<e.length;n++)s.set(e[n],i),i+=e[n].length;return s}static fromAscii(e){return e||(e=""),He.encode(e)}static toAscii(e){return xe.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 i=t.subarray(0,e);return s>e&&this.buffers.push(t.subarray(e)),this.byteLength=s-e,i}}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}}function Vi(r,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(s){if(s!=="default"&&!(s in r)){var i=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(r,s,i.get?i:{enumerable:!0,get:function(){return t[s]}})}})}),Object.freeze(r)}var Wi=typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{},vt=Wi.performance||{};vt.now||vt.mozNow||vt.msNow||vt.oNow||vt.webkitNow;var Or={versions:{}},Yi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Xi(r){if(r.__esModule)return r;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(r).forEach(function(t){var s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:function(){return r[t]}})}),e}var Cs,Kt={exports:{}},Cr={},Ir=Xi(Vi({__proto__:null,default:Cr},[Cr]));Cs=Kt,function(){var r="input is invalid type",e=typeof window=="object",t=e?window:{};t.JS_SHA256_NO_WINDOW&&(e=!1);var s=!e&&typeof self=="object",i=!t.JS_SHA256_NO_NODE_JS&&Or.versions&&Or.versions.node;i?t=Yi:s&&(t=self);var n=!t.JS_SHA256_NO_COMMON_JS&&Cs.exports,o=!t.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",a="0123456789abcdef".split(""),f=[-2147483648,8388608,32768,128],p=[24,16,8,0],g=[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],y=["hex","array","digest","arrayBuffer"],x=[];!t.JS_SHA256_NO_NODE_JS&&Array.isArray||(Array.isArray=function(w){return Object.prototype.toString.call(w)==="[object Array]"}),!o||!t.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(w){return typeof w=="object"&&w.buffer&&w.buffer.constructor===ArrayBuffer});var A=function(w,j){return function(F){return new L(j,!0).update(F)[w]()}},I=function(w){var j=A("hex",w);i&&(j=T(j,w)),j.create=function(){return new L(w)},j.update=function(P){return j.create().update(P)};for(var F=0;F<y.length;++F){var R=y[F];j[R]=A(R,w)}return j},T=function(w,j){var F,R=Ir,P=Ir.Buffer,U=j?"sha224":"sha256";return F=P.from&&!t.JS_SHA256_NO_BUFFER_FROM?P.from:function(q){return new P(q)},function(q){if(typeof q=="string")return R.createHash(U).update(q,"utf8").digest("hex");if(q==null)throw new Error(r);return q.constructor===ArrayBuffer&&(q=new Uint8Array(q)),Array.isArray(q)||ArrayBuffer.isView(q)||q.constructor===P?R.createHash(U).update(F(q)).digest("hex"):w(q)}},J=function(w,j){return function(F,R){return new ee(F,j,!0).update(R)[w]()}},se=function(w){var j=J("hex",w);j.create=function(P){return new ee(P,w)},j.update=function(P,U){return j.create(P).update(U)};for(var F=0;F<y.length;++F){var R=y[F];j[R]=J(R,w)}return j};function L(w,j){j?(x[0]=x[16]=x[1]=x[2]=x[3]=x[4]=x[5]=x[6]=x[7]=x[8]=x[9]=x[10]=x[11]=x[12]=x[13]=x[14]=x[15]=0,this.blocks=x):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],w?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=w}function ee(w,j,F){var R,P=typeof w;if(P==="string"){var U,q=[],$=w.length,Y=0;for(R=0;R<$;++R)(U=w.charCodeAt(R))<128?q[Y++]=U:U<2048?(q[Y++]=192|U>>>6,q[Y++]=128|63&U):U<55296||U>=57344?(q[Y++]=224|U>>>12,q[Y++]=128|U>>>6&63,q[Y++]=128|63&U):(U=65536+((1023&U)<<10|1023&w.charCodeAt(++R)),q[Y++]=240|U>>>18,q[Y++]=128|U>>>12&63,q[Y++]=128|U>>>6&63,q[Y++]=128|63&U);w=q}else{if(P!=="object")throw new Error(r);if(w===null)throw new Error(r);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!(Array.isArray(w)||o&&ArrayBuffer.isView(w)))throw new Error(r)}w.length>64&&(w=new L(j,!0).update(w).array());var ie=[],ce=[];for(R=0;R<64;++R){var ne=w[R]||0;ie[R]=92^ne,ce[R]=54^ne}L.call(this,j,F),this.update(ce),this.oKeyPad=ie,this.inner=!0,this.sharedMemory=F}L.prototype.update=function(w){if(!this.finalized){var j,F=typeof w;if(F!=="string"){if(F!=="object")throw new Error(r);if(w===null)throw new Error(r);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!(Array.isArray(w)||o&&ArrayBuffer.isView(w)))throw new Error(r);j=!0}for(var R,P,U=0,q=w.length,$=this.blocks;U<q;){if(this.hashed&&(this.hashed=!1,$[0]=this.block,this.block=$[16]=$[1]=$[2]=$[3]=$[4]=$[5]=$[6]=$[7]=$[8]=$[9]=$[10]=$[11]=$[12]=$[13]=$[14]=$[15]=0),j)for(P=this.start;U<q&&P<64;++U)$[P>>>2]|=w[U]<<p[3&P++];else for(P=this.start;U<q&&P<64;++U)(R=w.charCodeAt(U))<128?$[P>>>2]|=R<<p[3&P++]:R<2048?($[P>>>2]|=(192|R>>>6)<<p[3&P++],$[P>>>2]|=(128|63&R)<<p[3&P++]):R<55296||R>=57344?($[P>>>2]|=(224|R>>>12)<<p[3&P++],$[P>>>2]|=(128|R>>>6&63)<<p[3&P++],$[P>>>2]|=(128|63&R)<<p[3&P++]):(R=65536+((1023&R)<<10|1023&w.charCodeAt(++U)),$[P>>>2]|=(240|R>>>18)<<p[3&P++],$[P>>>2]|=(128|R>>>12&63)<<p[3&P++],$[P>>>2]|=(128|R>>>6&63)<<p[3&P++],$[P>>>2]|=(128|63&R)<<p[3&P++]);this.lastByteIndex=P,this.bytes+=P-this.start,P>=64?(this.block=$[16],this.start=P-64,this.hash(),this.hashed=!0):this.start=P}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this}},L.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var w=this.blocks,j=this.lastByteIndex;w[16]=this.block,w[j>>>2]|=f[3&j],this.block=w[16],j>=56&&(this.hashed||this.hash(),w[0]=this.block,w[16]=w[1]=w[2]=w[3]=w[4]=w[5]=w[6]=w[7]=w[8]=w[9]=w[10]=w[11]=w[12]=w[13]=w[14]=w[15]=0),w[14]=this.hBytes<<3|this.bytes>>>29,w[15]=this.bytes<<3,this.hash()}},L.prototype.hash=function(){var w,j,F,R,P,U,q,$,Y,ie=this.h0,ce=this.h1,ne=this.h2,he=this.h3,fe=this.h4,de=this.h5,X=this.h6,re=this.h7,ue=this.blocks;for(w=16;w<64;++w)j=((P=ue[w-15])>>>7|P<<25)^(P>>>18|P<<14)^P>>>3,F=((P=ue[w-2])>>>17|P<<15)^(P>>>19|P<<13)^P>>>10,ue[w]=ue[w-16]+j+ue[w-7]+F|0;for(Y=ce&ne,w=0;w<64;w+=4)this.first?(this.is224?(U=300032,re=(P=ue[0]-1413257819)-150054599|0,he=P+24177077|0):(U=704751109,re=(P=ue[0]-210244248)-1521486534|0,he=P+143694565|0),this.first=!1):(j=(ie>>>2|ie<<30)^(ie>>>13|ie<<19)^(ie>>>22|ie<<10),R=(U=ie&ce)^ie&ne^Y,re=he+(P=re+(F=(fe>>>6|fe<<26)^(fe>>>11|fe<<21)^(fe>>>25|fe<<7))+(fe&de^~fe&X)+g[w]+ue[w])|0,he=P+(j+R)|0),j=(he>>>2|he<<30)^(he>>>13|he<<19)^(he>>>22|he<<10),R=(q=he&ie)^he&ce^U,X=ne+(P=X+(F=(re>>>6|re<<26)^(re>>>11|re<<21)^(re>>>25|re<<7))+(re&fe^~re&de)+g[w+1]+ue[w+1])|0,j=((ne=P+(j+R)|0)>>>2|ne<<30)^(ne>>>13|ne<<19)^(ne>>>22|ne<<10),R=($=ne&he)^ne&ie^q,de=ce+(P=de+(F=(X>>>6|X<<26)^(X>>>11|X<<21)^(X>>>25|X<<7))+(X&re^~X&fe)+g[w+2]+ue[w+2])|0,j=((ce=P+(j+R)|0)>>>2|ce<<30)^(ce>>>13|ce<<19)^(ce>>>22|ce<<10),R=(Y=ce&ne)^ce&he^$,fe=ie+(P=fe+(F=(de>>>6|de<<26)^(de>>>11|de<<21)^(de>>>25|de<<7))+(de&X^~de&re)+g[w+3]+ue[w+3])|0,ie=P+(j+R)|0,this.chromeBugWorkAround=!0;this.h0=this.h0+ie|0,this.h1=this.h1+ce|0,this.h2=this.h2+ne|0,this.h3=this.h3+he|0,this.h4=this.h4+fe|0,this.h5=this.h5+de|0,this.h6=this.h6+X|0,this.h7=this.h7+re|0},L.prototype.hex=function(){this.finalize();var w=this.h0,j=this.h1,F=this.h2,R=this.h3,P=this.h4,U=this.h5,q=this.h6,$=this.h7,Y=a[w>>>28&15]+a[w>>>24&15]+a[w>>>20&15]+a[w>>>16&15]+a[w>>>12&15]+a[w>>>8&15]+a[w>>>4&15]+a[15&w]+a[j>>>28&15]+a[j>>>24&15]+a[j>>>20&15]+a[j>>>16&15]+a[j>>>12&15]+a[j>>>8&15]+a[j>>>4&15]+a[15&j]+a[F>>>28&15]+a[F>>>24&15]+a[F>>>20&15]+a[F>>>16&15]+a[F>>>12&15]+a[F>>>8&15]+a[F>>>4&15]+a[15&F]+a[R>>>28&15]+a[R>>>24&15]+a[R>>>20&15]+a[R>>>16&15]+a[R>>>12&15]+a[R>>>8&15]+a[R>>>4&15]+a[15&R]+a[P>>>28&15]+a[P>>>24&15]+a[P>>>20&15]+a[P>>>16&15]+a[P>>>12&15]+a[P>>>8&15]+a[P>>>4&15]+a[15&P]+a[U>>>28&15]+a[U>>>24&15]+a[U>>>20&15]+a[U>>>16&15]+a[U>>>12&15]+a[U>>>8&15]+a[U>>>4&15]+a[15&U]+a[q>>>28&15]+a[q>>>24&15]+a[q>>>20&15]+a[q>>>16&15]+a[q>>>12&15]+a[q>>>8&15]+a[q>>>4&15]+a[15&q];return this.is224||(Y+=a[$>>>28&15]+a[$>>>24&15]+a[$>>>20&15]+a[$>>>16&15]+a[$>>>12&15]+a[$>>>8&15]+a[$>>>4&15]+a[15&$]),Y},L.prototype.toString=L.prototype.hex,L.prototype.digest=function(){this.finalize();var w=this.h0,j=this.h1,F=this.h2,R=this.h3,P=this.h4,U=this.h5,q=this.h6,$=this.h7,Y=[w>>>24&255,w>>>16&255,w>>>8&255,255&w,j>>>24&255,j>>>16&255,j>>>8&255,255&j,F>>>24&255,F>>>16&255,F>>>8&255,255&F,R>>>24&255,R>>>16&255,R>>>8&255,255&R,P>>>24&255,P>>>16&255,P>>>8&255,255&P,U>>>24&255,U>>>16&255,U>>>8&255,255&U,q>>>24&255,q>>>16&255,q>>>8&255,255&q];return this.is224||Y.push($>>>24&255,$>>>16&255,$>>>8&255,255&$),Y},L.prototype.array=L.prototype.digest,L.prototype.arrayBuffer=function(){this.finalize();var w=new ArrayBuffer(this.is224?28:32),j=new DataView(w);return j.setUint32(0,this.h0),j.setUint32(4,this.h1),j.setUint32(8,this.h2),j.setUint32(12,this.h3),j.setUint32(16,this.h4),j.setUint32(20,this.h5),j.setUint32(24,this.h6),this.is224||j.setUint32(28,this.h7),w},ee.prototype=new L,ee.prototype.finalize=function(){if(L.prototype.finalize.call(this),this.inner){this.inner=!1;var w=this.array();L.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(w),L.prototype.finalize.call(this)}};var _e=I();_e.sha256=_e,_e.sha224=I(!0),_e.sha256.hmac=se(),_e.sha224.hmac=se(!0),n?Cs.exports=_e:(t.sha256=_e.sha256,t.sha224=_e.sha224)}(),Kt.exports,Kt.exports.sha224;var jr=Kt.exports.sha256;function Is(r){return rn(r)}function Zi(r){if(!/^[0-9A-Fa-f]+$/.test(r))return!1;const t=/^[0-9A-F]+$/.test(r),s=/^[0-9a-f]+$/.test(r);return t||s?r.length%2===0:!1}function Qi(r){return/^[A-Za-z0-9\-_]*(={0,2})?$/.test(r)||/^[A-Za-z0-9+/]*(={0,2})?$/.test(r)}function en(r){return Zi(r)?"hex":Qi(r)?"b64":""}function tn(r){if(r.length%2!==0)throw new Error("hex string must have an even length");const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.substring(t,t+2),16);return e}function sn(r){r=r.replace(/-/g,"+"),r=r.replace(/_/g,"/");const e=atob(r);return Uint8Array.from(e,t=>t.charCodeAt(0))}function rn(r){switch(en(r)){case"hex":return tn(r);case"b64":return sn(r)}return null}function nn(r,e){const t=typeof r=="string"?Is(r):r,s=typeof e=="string"?Is(e):e;if(t===null||s===null||t.length!==s.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==s[i])return!1;return!0}class Rr{constructor(e,t,s=!0){h(this,"token");h(this,"received");h(this,"ctx");h(this,"requestSubject");h(this,"mux");this.mux=e,this.requestSubject=t,this.received=0,this.token=Je.next(),s&&(this.ctx=new Error)}}class on extends Rr{constructor(t,s,i={maxWait:1e3}){super(t,s);h(this,"callback");h(this,"done");h(this,"timer");h(this,"max");h(this,"opts");if(this.opts=i,typeof this.opts.callback!="function")throw new Error("callback is required");this.callback=this.opts.callback,this.max=typeof i.maxMessages=="number"&&i.maxMessages>0?i.maxMessages:-1,this.done=V(),this.done.then(()=>{this.callback(null,null)}),this.timer=setTimeout(()=>{this.cancel()},i.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+=`
9
9
 
10
- ${this.ctx.stack}`),this.cancel(t)):(this.callback(null,s),this.opts.strategy===je.Count&&(this.max--,this.max===0&&this.cancel()),this.opts.strategy===je.JitterTimer&&(clearTimeout(this.timer),this.timer=setTimeout(()=>{this.cancel()},this.opts.jitter||300)),this.opts.strategy===je.SentinelMsg&&s&&s.data.length===0&&this.cancel())}}class Nr extends Rr{constructor(t,s,i={timeout:1e3},n=!0){super(t,s,n);h(this,"deferred");h(this,"timer");this.deferred=V(),this.timer=st(i.timeout,n)}resolver(t,s){this.timer&&this.timer.cancel(),t?(this.ctx&&(t.stack+=`
10
+ ${this.ctx.stack}`),this.cancel(t)):(this.callback(null,s),this.opts.strategy===je.Count&&(this.max--,this.max===0&&this.cancel()),this.opts.strategy===je.JitterTimer&&(clearTimeout(this.timer),this.timer=setTimeout(()=>{this.cancel()},this.opts.jitter||300)),this.opts.strategy===je.SentinelMsg&&s&&s.data.length===0&&this.cancel())}}class Nr extends Rr{constructor(t,s,i={timeout:1e3},n=!0){super(t,s,n);h(this,"deferred");h(this,"timer");this.deferred=V(),this.timer=tt(i.timeout,n)}resolver(t,s){this.timer&&this.timer.cancel(),t?(this.ctx&&(t.stack+=`
11
11
 
12
- ${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||N.errorForCode(k.Cancelled))}}const an="$JS.API";function cn(r){return r=r||{},r.domain&&(r.apiPrefix=`$JS.${r.domain}.API`,delete r.domain),Bt({apiPrefix:an,timeout:5e3},r)}class Et{constructor(e,t){h(this,"nc");h(this,"opts");h(this,"prefix");h(this,"timeout");h(this,"jc");this.nc=e,this.opts=cn(t),this._parseOpts(),this.prefix=this.opts.apiPrefix,this.timeout=this.opts.timeout,this.jc=ke()}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 i=we;t&&(i=this.jc.encode(t));let{retries:n}=s;n=n||1,n=n===-1?Number.MAX_SAFE_INTEGER:n;const o=ys();for(let a=0;a<n;a++)try{const f=await this.nc.request(e,i,s);return this.parseJsResponse(f)}catch(f){const p=f;if((p.code==="503"||p.code===k.Timeout)&&a+1<n)await rt(o.backoff(a));else throw f}}async findStream(e){const t={subject:e},i=await this._request(`${this.prefix}.STREAM.NAMES`,t);if(!i.streams||i.streams.length!==1)throw new Error("no stream matches subject");return i.streams[0]}getConnection(){return this.nc}parseJsResponse(e){const t=this.jc.decode(e.data),s=t;if(s.error){const i=Er(s.error.code,s.error.description);if(i!==null)throw i.api_error=s.error,i}return t}}class At{constructor(e,t,s,i){h(this,"err");h(this,"offset");h(this,"pageInfo");h(this,"subject");h(this,"jsm");h(this,"filter");h(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=i||{}}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});this.pageInfo=t;const s=this.countResponse(t);return s===0?[]:(this.offset+=s,this.filter(t))}catch(t){throw this.err=t,t}}countResponse(e){var t,s,i;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((t=e.streams)==null?void 0:t.length)||0;case"io.nats.jetstream.api.v1.consumer_list_response":return((s=e.consumers)==null?void 0:s.length)||0;default:return console.error(`jslister.ts: unknown API response for paged output: ${e==null?void 0:e.type}`),((i=e.streams)==null?void 0:i.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()}}}function Qe(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 js(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 H;(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",r.JS_BATCH_DIRECT_GET="js_batch_direct_get"})(H||(H={}));class hn{constructor(e){h(this,"server");h(this,"features");h(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=Qe(e)),this.server=e,this.set(H.JS_KV,"2.6.2"),this.set(H.JS_OBJECTSTORE,"2.6.3"),this.set(H.JS_PULL_MAX_BYTES,"2.8.3"),this.set(H.JS_NEW_CONSUMER_CREATE_API,"2.9.0"),this.set(H.JS_ALLOW_DIRECT,"2.9.0"),this.set(H.JS_MULTIPLE_CONSUMER_FILTER,"2.10.0"),this.set(H.JS_SIMPLIFICATION,"2.9.4"),this.set(H.JS_STREAM_CONSUMER_METADATA,"2.10.0"),this.set(H.JS_CONSUMER_FILTER_SUBJECTS,"2.10.0"),this.set(H.JS_STREAM_FIRST_SEQ,"2.10.0"),this.set(H.JS_STREAM_SUBJECT_TRANSFORM,"2.10.0"),this.set(H.JS_STREAM_SOURCE_SUBJECT_TRANSFORM,"2.10.0"),this.set(H.JS_STREAM_COMPRESSION,"2.10.0"),this.set(H.JS_DEFAULT_CONSUMER_LIMITS,"2.10.0"),this.set(H.JS_BATCH_DIRECT_GET,"2.11.0"),this.disabled.forEach(t=>{this.features.delete(t)})}set(e,t){this.features.set(e,{min:t,ok:js(this.server,Qe(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=Qe(e)),js(this.server,e)>=0}}class zt extends Et{constructor(e,t){super(e,t)}async add(e,t,s=Jt.Create){if(pe(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 i={};i.config=t,i.stream_name=e,i.action=s,i.config.durable_name&&it(i.config.durable_name);const n=this.nc;let{min:o,ok:a}=n.features.get(H.JS_NEW_CONSUMER_CREATE_API);const f=t.name===""?void 0:t.name;if(f&&!a)throw new Error(`consumer 'name' requires server ${o}`);if(f)try{Ht("name",f)}catch(x){const A=x.message,I=A.indexOf("cannot contain");throw I!==-1?new Error(`consumer 'name' ${A.substring(I)}`):x}let p,g="";if(Array.isArray(t.filter_subjects)){const{min:x,ok:A}=n.features.get(H.JS_MULTIPLE_CONSUMER_FILTER);if(!A)throw new Error(`consumer 'filter_subjects' requires server ${x}`);a=!1}if(t.metadata){const{min:x,ok:A}=n.features.get(H.JS_STREAM_CONSUMER_METADATA);if(!A)throw new Error(`consumer 'metadata' requires server ${x}`)}if(a&&(g=t.name??t.durable_name??""),g!==""){let x=t.filter_subject??void 0;x===">"&&(x=void 0),p=x!==void 0?`${this.prefix}.CONSUMER.CREATE.${e}.${g}.${x}`:`${this.prefix}.CONSUMER.CREATE.${e}.${g}`}else p=t.durable_name?`${this.prefix}.CONSUMER.DURABLE.CREATE.${e}.${t.durable_name}`:`${this.prefix}.CONSUMER.CREATE.${e}`;return await this._request(p,i)}async update(e,t,s){const i=await this.info(e,t),n=s;return this.add(e,Object.assign(i.config,n),Jt.Update)}async info(e,t){return pe(e),it(t),await this._request(`${this.prefix}.CONSUMER.INFO.${e}.${t}`)}async delete(e,t){return pe(e),it(t),(await this._request(`${this.prefix}.CONSUMER.DELETE.${e}.${t}`)).success}list(e){pe(e);const t=i=>i.consumers,s=`${this.prefix}.CONSUMER.LIST.${e}`;return new At(s,t,this)}pause(e,t,s){const i=`${this.prefix}.CONSUMER.PAUSE.${e}.${t}`,n={pause_until:s.toISOString()};return this._request(i,n)}resume(e,t){return this.pause(e,t,new Date(0))}}function ut(r,e,t=!1){if(t===!0&&!r)throw N.errorForCode(k.ApiError,new Error(`${e} is not a function`));if(r&&typeof r!="function")throw N.errorForCode(k.ApiError,new Error(`${e} is not a function`))}class un extends oe{constructor(t,s,i){super();h(this,"sub");h(this,"adapter");h(this,"subIterDone");ut(i.adapter,"adapter",!0),this.adapter=i.adapter,i.callback&&ut(i.callback,"callback"),this.noIterator=typeof i.callback=="function",i.ingestionFilterFn&&(ut(i.ingestionFilterFn,"ingestionFilterFn"),this.ingestionFilterFn=i.ingestionFilterFn),i.protocolFilterFn&&(ut(i.protocolFilterFn,"protocolFilterFn"),this.protocolFilterFn=i.protocolFilterFn),i.dispatchedFn&&(ut(i.dispatchedFn,"dispatchedFn"),this.dispatchedFn=i.dispatchedFn),i.cleanupFn&&ut(i.cleanupFn,"cleanupFn");let n=(g,y)=>{this.callback(g,y)};if(i.callback){const g=i.callback;n=(y,x)=>{const[A,I]=this.adapter(y,x);if(A){g(A,null);return}const{ingest:T}=this.ingestionFilterFn?this.ingestionFilterFn(I,this):{ingest:!0};T&&(!this.protocolFilterFn||this.protocolFilterFn(I))&&(g(A,I),this.dispatchedFn&&I&&this.dispatchedFn(I))}}const{max:o,queue:a,timeout:f}=i,p={queue:a,timeout:f,callback:n};o&&o>0&&(p.max=o),this.sub=t.subscribe(s,p),i.cleanupFn&&(this.sub.cleanupFn=i.cleanupFn),this.noIterator||this.iterClosed.then(()=>{this.unsubscribe()}),this.subIterDone=V(),Promise.all([this.sub.closed,this.iterClosed]).then(()=>{this.subIterDone.resolve()}).catch(()=>{this.subIterDone.resolve()}),(async g=>{await g.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[i,n]=this.adapter(t,s);i&&this.stop(i),n&&this.push(n)}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}}let Ee;function ln(r){Ee=r}function Tr(){return Ee!==void 0&&Ee.defaultPort!==void 0?Ee.defaultPort:4222}function Rs(){return Ee!==void 0&&Ee.urlParseFn?Ee.urlParseFn:void 0}function fn(){if(!Ee||typeof Ee.factory!="function")throw new Error("transport fn is not set");return Ee.factory()}function Ns(){return Ee!==void 0&&Ee.dnsResolveFn?Ee.dnsResolveFn:void 0}const Gt=`\r
13
- `,Vt=ht.fromAscii(Gt),dn=new Uint8Array(Vt)[0],pn=new Uint8Array(Vt)[1];function mn(r){for(let e=0;e<r.length;e++){const t=e+1;if(r.byteLength>t&&r[e]===dn&&r[t]===pn)return t+1}return 0}function bn(r){const e=mn(r);if(e>0){const s=new Uint8Array(r).slice(0,e);return xe.decode(s)}return""}const gn=4,Mr=48,_n=65,yn=97;function wn(r,e,t,s){const i=new Uint8Array(16);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((o,a)=>{i[a]=o}),i[12]=r,i[13]=e,i[14]=t,i[15]=s,i}function Ts(r){return xn(r)!==void 0}function xn(r){for(let e=0;e<r.length;e++)switch(r[e]){case".":return Ur(r);case":":return Sn(r)}}function Ur(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:i,ok:n}=vn(r);if(!n||s>255)return;r=r.substring(i),e[t]=s}return wn(e[0],e[1],e[2],e[3])}function Sn(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:i,c:n,ok:o}=En(r);if(!o||i>65535)return;if(n<r.length&&r[n]==="."){if(t<0&&s!=12||s+4>16)return;const a=Ur(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+=gn;break}if(e[s]=i>>8,e[s+1]=i,s+=2,r=r.substring(n),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 i=16-s;for(let n=s-1;n>=t;n--)e[n+i]=e[n];for(let n=t+i-1;n>=t;n--)e[n]=0}else if(t>=0)return;return e}}function vn(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)-Mr),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 En(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)-Mr;else if(97<=r.charCodeAt(t)&&r.charCodeAt(t)<=102)e*=16,e+=r.charCodeAt(t)-yn+10;else if(65<=r.charCodeAt(t)&&r.charCodeAt(t)<=70)e*=16,e+=r.charCodeAt(t)-_n+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 An(r){return r.indexOf("[")!==-1||r.indexOf("::")!==-1?!1:r.indexOf(".")!==-1||r.split(":").length<=2}function Ms(r){return!An(r)}function Pn(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 kn(r){r=r.trim(),r.match(/^(.*:\/\/)(.*)/m)&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2")),r=Pn(r),Ms(r)&&r.indexOf("[")===-1&&(r=`[${r}]`);const e=Ms(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",i=new URL(`${s}://${r}`);i.port=`${t}`;let n=i.hostname;return n.charAt(0)==="["&&(n=n.substring(1,n.length-1)),{listen:i.host,hostname:n,port:t}}class Pt{constructor(e,t=!1){h(this,"src");h(this,"listen");h(this,"hostname");h(this,"port");h(this,"didConnect");h(this,"reconnects");h(this,"lastConnect");h(this,"gossiped");h(this,"tlsName");h(this,"resolves");this.src=e,this.tlsName="";const s=kn(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||e.resolve===!1)return[this];const t=[];if(Ts(this.hostname))return[this];{const s=await e.fn(this.hostname);e.debug&&console.log(`resolve ${this.hostname} = ${s.join(",")}`);for(const i of s){const n=this.port===80?"https":"http",o=new URL(`${n}://${Ms(i)?"["+i+"]":i}`);o.port=`${this.port}`;const a=new Pt(o.host,!1);a.tlsName=this.hostname,t.push(a)}}return e.randomize&&xr(t),this.resolves=t,t}}class On{constructor(e=[],t={}){h(this,"firstSelect");h(this,"servers");h(this,"currentServer");h(this,"tlsName");h(this,"randomize");this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=t.randomize||!1;const s=Rs();e&&(e.forEach(i=>{i=s?s(i):i,this.servers.push(new Pt(i))}),this.randomize&&(this.servers=xr(this.servers))),this.servers.length===0&&this.addServer(`${_s}:${Tr()}`,!1),this.currentServer=this.servers[0]}clear(){this.servers.length=0}updateTLSName(){const e=this.getCurrentServer();Ts(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=Rs();e=s?s(e):e;const i=new Pt(e,t);Ts(i.hostname)&&(i.tlsName=this.tlsName),this.servers.push(i)}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,t){const s=[];let i=[];const n=Rs(),o=new Map;e.connect_urls&&e.connect_urls.length>0&&e.connect_urls.forEach(f=>{f=n?n(f,t):f;const p=new Pt(f,!0);o.set(f,p)});const a=[];return this.servers.forEach((f,p)=>{const g=f.listen;f.gossiped&&this.currentServer.listen!==g&&o.get(g)===void 0&&a.push(p),o.delete(g)}),a.reverse(),a.forEach(f=>{const p=this.servers.splice(f,1);i=i.concat(p[0].listen)}),o.forEach((f,p)=>{this.servers.push(f),s.push(p)}),{added:s,deleted:i}}}class Cn{constructor(){h(this,"baseInbox");h(this,"reqs");this.reqs=new Map}size(){return this.reqs.size}init(e){return this.baseInbox=`${Fe(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(i=>{i.resolver(t,{})}),!0;const s=t.permissionContext;if(s.operation==="publish"){const i=this.all().find(n=>n.requestSubject===s.subject);if(i)return i.resolver(t,{}),!0}}return!1}dispatcher(){return(e,t)=>{const s=this.getToken(t);if(s){const i=this.get(s);i&&(e===null&&t.headers&&(e=vr(t)),i.resolver(e,t))}}}close(){const e=N.errorForCode(k.Timeout);this.reqs.forEach(t=>{t.resolver(e,{})})}}class In{constructor(e,t,s){h(this,"ph");h(this,"interval");h(this,"maxOut");h(this,"timer");h(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:Ke.PingTimer,data:`${this.pendings.length+1}`}),this.pendings.length===this.maxOut){this.cancel(!0);return}const e=V();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 jn extends Error{constructor(e){super(e),this.name="AssertionError"}}function Rn(r,e="Assertion failed."){if(!r)throw new jn(e)}const $r=32*1024,Us=2**32-2;function Wt(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){h(this,"_buf");h(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){Rn(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=Wt(this._buf.subarray(this._off),e);return this._off+=t,t}writeByte(e){return this.write(Uint8Array.of(e))}writeString(e){return this.write(He.encode(e))}write(e){const t=this._grow(e.byteLength);return Wt(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 i=this.capacity;if(e<=Math.floor(i/2)-t)Wt(this._buf.subarray(this._off),this._buf);else{if(i+e>Us)throw new Error("The buffer cannot be grown beyond the maximum size.");{const n=new Uint8Array(Math.min(2*i+e,Us));Wt(this._buf.subarray(this._off),n),this._buf=n}}return this._off=0,this._reslice(Math.min(t+e,Us)),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($r);for(;;){const i=this.capacity-this.length<$r,n=i?s:new Uint8Array(this._buf.buffer,this.length),o=e.read(n);if(o===null)return t;i?this.write(n.subarray(0,o)):this._reslice(this.length+o),t+=o}}}var be;(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"})(be||(be={}));function Lr(){const r={};return r.sid=-1,r.hdr=-1,r.size=-1,r}const Nn=48;class qr{constructor(e){h(this,"dispatcher");h(this,"state");h(this,"as");h(this,"drop");h(this,"hdr");h(this,"ma");h(this,"argBuf");h(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=Lr();break;case C.H:case C.h:this.state=O.OP_H,this.hdr=0,this.ma=Lr();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 i=this.argBuf?this.argBuf.bytes():e.subarray(this.as,t-this.drop);this.processMsgArgs(i),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 i=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:be.MSG,msg:this.ma,data:i}),this.argBuf=void 0,this.msgBuf=void 0,this.state=O.MSG_END}else{let i=this.ma.size-this.msgBuf.length;const n=e.length-t;n<i&&(i=n),i>0?(this.msgBuf.write(e.subarray(t,t+i)),t=t+i-1):this.msgBuf.writeByte(s)}else t-this.as>=this.ma.size&&(this.dispatcher.push({kind:be.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:be.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 i;this.argBuf?(i=this.argBuf.bytes(),this.argBuf=void 0):i=e.subarray(this.as,t-this.drop),this.dispatcher.push({kind:be.ERR,data:i}),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:be.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:be.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 i;this.argBuf?(i=this.argBuf.bytes(),this.argBuf=void 0):i=e.subarray(this.as,t-this.drop),this.dispatcher.push({kind:be.INFO,data:i}),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 i=0;i<e.length;i++)switch(e[i]){case C.SPACE:case C.TAB:case C.CR:case C.NL:s>=0&&(t.push(e.subarray(s,i)),s=-1);break;default:s<0&&(s=i)}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}: ${xe.decode(e)}`)}processHeaderMsgArgs(e){const t=[];let s=-1;for(let i=0;i<e.length;i++)switch(e[i]){case C.SPACE:case C.TAB:case C.CR:case C.NL:s>=0&&(t.push(e.subarray(s,i)),s=-1);break;default:s<0&&(s=i)}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]-Nn)}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=13]="CR",r[r.E=69]="E",r[r.e=101]="e",r[r.F=70]="F",r[r.f=102]="f",r[r.G=71]="G",r[r.g=103]="g",r[r.H=72]="H",r[r.h=104]="h",r[r.I=73]="I",r[r.i=105]="i",r[r.K=75]="K",r[r.k=107]="k",r[r.M=77]="M",r[r.m=109]="m",r[r.MINUS=45]="MINUS",r[r.N=78]="N",r[r.n=110]="n",r[r.NL=10]="NL",r[r.O=79]="O",r[r.o=111]="o",r[r.P=80]="P",r[r.p=112]="p",r[r.PLUS=43]="PLUS",r[r.R=82]="R",r[r.r=114]="r",r[r.S=83]="S",r[r.s=115]="s",r[r.SPACE=32]="SPACE",r[r.TAB=9]="TAB"})(C||(C={})),function(r){var e=function(c,l){this.hi=c|0,this.lo=l|0},t=function(c){var l,u=new Float64Array(16);if(c)for(l=0;l<c.length;l++)u[l]=c[l];return u},s=function(){throw new Error("no PRNG")},i=new Uint8Array(16),n=new Uint8Array(32);n[0]=9;var o=t(),a=t([1]),f=t([56129,1]),p=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),g=t([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),y=t([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),x=t([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),A=t([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function I(c,l){return c<<l|c>>>32-l}function T(c,l){var u=c[l+3]&255;return u=u<<8|c[l+2]&255,u=u<<8|c[l+1]&255,u<<8|c[l+0]&255}function J(c,l){var u=c[l]<<24|c[l+1]<<16|c[l+2]<<8|c[l+3],d=c[l+4]<<24|c[l+5]<<16|c[l+6]<<8|c[l+7];return new e(u,d)}function se(c,l,u){var d;for(d=0;d<4;d++)c[l+d]=u&255,u>>>=8}function L(c,l,u){c[l]=u.hi>>24&255,c[l+1]=u.hi>>16&255,c[l+2]=u.hi>>8&255,c[l+3]=u.hi&255,c[l+4]=u.lo>>24&255,c[l+5]=u.lo>>16&255,c[l+6]=u.lo>>8&255,c[l+7]=u.lo&255}function ee(c,l,u,d,m){var b,v=0;for(b=0;b<m;b++)v|=c[l+b]^u[d+b];return(1&v-1>>>8)-1}function _e(c,l,u,d){return ee(c,l,u,d,16)}function w(c,l,u,d){return ee(c,l,u,d,32)}function j(c,l,u,d,m){var b=new Uint32Array(16),v=new Uint32Array(16),E=new Uint32Array(16),_=new Uint32Array(4),S,M,D;for(S=0;S<4;S++)v[5*S]=T(d,4*S),v[1+S]=T(u,4*S),v[6+S]=T(l,4*S),v[11+S]=T(u,16+4*S);for(S=0;S<16;S++)E[S]=v[S];for(S=0;S<20;S++){for(M=0;M<4;M++){for(D=0;D<4;D++)_[D]=v[(5*M+4*D)%16];for(_[1]^=I(_[0]+_[3]|0,7),_[2]^=I(_[1]+_[0]|0,9),_[3]^=I(_[2]+_[1]|0,13),_[0]^=I(_[3]+_[2]|0,18),D=0;D<4;D++)b[4*M+(M+D)%4]=_[D]}for(D=0;D<16;D++)v[D]=b[D]}if(m){for(S=0;S<16;S++)v[S]=v[S]+E[S]|0;for(S=0;S<4;S++)v[5*S]=v[5*S]-T(d,4*S)|0,v[6+S]=v[6+S]-T(l,4*S)|0;for(S=0;S<4;S++)se(c,4*S,v[5*S]),se(c,16+4*S,v[6+S])}else for(S=0;S<16;S++)se(c,4*S,v[S]+E[S]|0)}function F(c,l,u,d){return j(c,l,u,d,!1),0}function R(c,l,u,d){return j(c,l,u,d,!0),0}var P=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function U(c,l,u,d,m,b,v){var E=new Uint8Array(16),_=new Uint8Array(64),S,M;if(!m)return 0;for(M=0;M<16;M++)E[M]=0;for(M=0;M<8;M++)E[M]=b[M];for(;m>=64;){for(F(_,E,v,P),M=0;M<64;M++)c[l+M]=(u?u[d+M]:0)^_[M];for(S=1,M=8;M<16;M++)S=S+(E[M]&255)|0,E[M]=S&255,S>>>=8;m-=64,l+=64,u&&(d+=64)}if(m>0)for(F(_,E,v,P),M=0;M<m;M++)c[l+M]=(u?u[d+M]:0)^_[M];return 0}function q(c,l,u,d,m){return U(c,l,null,0,u,d,m)}function $(c,l,u,d,m){var b=new Uint8Array(32);return R(b,d,m,P),q(c,l,u,d.subarray(16),b)}function Y(c,l,u,d,m,b,v){var E=new Uint8Array(32);return R(E,b,v,P),U(c,l,u,d,m,b.subarray(16),E)}function ie(c,l){var u,d=0;for(u=0;u<17;u++)d=d+(c[u]+l[u]|0)|0,c[u]=d&255,d>>>=8}var ce=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]);function ne(c,l,u,d,m,b){var v,E,_,S,M=new Uint32Array(17),D=new Uint32Array(17),Z=new Uint32Array(17),Me=new Uint32Array(17),bt=new Uint32Array(17);for(_=0;_<17;_++)D[_]=Z[_]=0;for(_=0;_<16;_++)D[_]=b[_];for(D[3]&=15,D[4]&=252,D[7]&=15,D[8]&=252,D[11]&=15,D[12]&=252,D[15]&=15;m>0;){for(_=0;_<17;_++)Me[_]=0;for(_=0;_<16&&_<m;++_)Me[_]=u[d+_];for(Me[_]=1,d+=_,m-=_,ie(Z,Me),E=0;E<17;E++)for(M[E]=0,_=0;_<17;_++)M[E]=M[E]+Z[_]*(_<=E?D[E-_]:320*D[E+17-_]|0)|0|0;for(E=0;E<17;E++)Z[E]=M[E];for(S=0,_=0;_<16;_++)S=S+Z[_]|0,Z[_]=S&255,S>>>=8;for(S=S+Z[16]|0,Z[16]=S&3,S=5*(S>>>2)|0,_=0;_<16;_++)S=S+Z[_]|0,Z[_]=S&255,S>>>=8;S=S+Z[16]|0,Z[16]=S}for(_=0;_<17;_++)bt[_]=Z[_];for(ie(Z,ce),v=-(Z[16]>>>7)|0,_=0;_<17;_++)Z[_]^=v&(bt[_]^Z[_]);for(_=0;_<16;_++)Me[_]=b[_+16];for(Me[16]=0,ie(Z,Me),_=0;_<16;_++)c[l+_]=Z[_];return 0}function he(c,l,u,d,m,b){var v=new Uint8Array(16);return ne(v,0,u,d,m,b),_e(c,l,v,0)}function fe(c,l,u,d,m){var b;if(u<32)return-1;for(Y(c,0,l,0,u,d,m),ne(c,16,c,32,u-32,c),b=0;b<16;b++)c[b]=0;return 0}function de(c,l,u,d,m){var b,v=new Uint8Array(32);if(u<32||($(v,0,32,d,m),he(l,16,l,32,u-32,v)!==0))return-1;for(Y(c,0,l,0,u,d,m),b=0;b<32;b++)c[b]=0;return 0}function X(c,l){var u;for(u=0;u<16;u++)c[u]=l[u]|0}function re(c){var l,u;for(u=0;u<16;u++)c[u]+=65536,l=Math.floor(c[u]/65536),c[(u+1)*(u<15?1:0)]+=l-1+37*(l-1)*(u===15?1:0),c[u]-=l*65536}function ue(c,l,u){for(var d,m=~(u-1),b=0;b<16;b++)d=m&(c[b]^l[b]),c[b]^=d,l[b]^=d}function dt(c,l){var u,d,m,b=t(),v=t();for(u=0;u<16;u++)v[u]=l[u];for(re(v),re(v),re(v),d=0;d<2;d++){for(b[0]=v[0]-65517,u=1;u<15;u++)b[u]=v[u]-65535-(b[u-1]>>16&1),b[u-1]&=65535;b[15]=v[15]-32767-(b[14]>>16&1),m=b[15]>>16&1,b[14]&=65535,ue(v,b,1-m)}for(u=0;u<16;u++)c[2*u]=v[u]&255,c[2*u+1]=v[u]>>8}function ci(c,l){var u=new Uint8Array(32),d=new Uint8Array(32);return dt(u,c),dt(d,l),w(u,0,d,0)}function hi(c){var l=new Uint8Array(32);return dt(l,c),l[0]&1}function Ys(c,l){var u;for(u=0;u<16;u++)c[u]=l[2*u]+(l[2*u+1]<<8);c[15]&=32767}function Ne(c,l,u){var d;for(d=0;d<16;d++)c[d]=l[d]+u[d]|0}function Te(c,l,u){var d;for(d=0;d<16;d++)c[d]=l[d]-u[d]|0}function B(c,l,u){var d,m,b=new Float64Array(31);for(d=0;d<31;d++)b[d]=0;for(d=0;d<16;d++)for(m=0;m<16;m++)b[d+m]+=l[d]*u[m];for(d=0;d<15;d++)b[d]+=38*b[d+16];for(d=0;d<16;d++)c[d]=b[d];re(c),re(c)}function Ie(c,l){B(c,l,l)}function ui(c,l){var u=t(),d;for(d=0;d<16;d++)u[d]=l[d];for(d=253;d>=0;d--)Ie(u,u),d!==2&&d!==4&&B(u,u,l);for(d=0;d<16;d++)c[d]=u[d]}function li(c,l){var u=t(),d;for(d=0;d<16;d++)u[d]=l[d];for(d=250;d>=0;d--)Ie(u,u),d!==1&&B(u,u,l);for(d=0;d<16;d++)c[d]=u[d]}function ns(c,l,u){var d=new Uint8Array(32),m=new Float64Array(80),b,v,E=t(),_=t(),S=t(),M=t(),D=t(),Z=t();for(v=0;v<31;v++)d[v]=l[v];for(d[31]=l[31]&127|64,d[0]&=248,Ys(m,u),v=0;v<16;v++)_[v]=m[v],M[v]=E[v]=S[v]=0;for(E[0]=M[0]=1,v=254;v>=0;--v)b=d[v>>>3]>>>(v&7)&1,ue(E,_,b),ue(S,M,b),Ne(D,E,S),Te(E,E,S),Ne(S,_,M),Te(_,_,M),Ie(M,D),Ie(Z,E),B(E,S,E),B(S,_,D),Ne(D,E,S),Te(E,E,S),Ie(_,E),Te(S,M,Z),B(E,S,f),Ne(E,E,M),B(S,S,E),B(E,M,Z),B(M,_,m),Ie(_,D),ue(E,_,b),ue(S,M,b);for(v=0;v<16;v++)m[v+16]=E[v],m[v+32]=S[v],m[v+48]=_[v],m[v+64]=M[v];var Me=m.subarray(32),bt=m.subarray(16);return ui(Me,Me),B(bt,bt,Me),dt(c,bt),0}function os(c,l){return ns(c,l,n)}function fi(c,l){return s(l,32),os(c,l)}function as(c,l,u){var d=new Uint8Array(32);return ns(d,u,l),R(c,i,d,P)}var di=fe,ea=de;function ta(c,l,u,d,m,b){var v=new Uint8Array(32);return as(v,m,b),di(c,l,u,d,v)}function sa(c,l,u,d,m,b){var v=new Uint8Array(32);return as(v,m,b),ea(c,l,u,d,v)}function Nt(){var c=0,l=0,u=0,d=0,m=65535,b,v,E;for(E=0;E<arguments.length;E++)b=arguments[E].lo,v=arguments[E].hi,c+=b&m,l+=b>>>16,u+=v&m,d+=v>>>16;return l+=c>>>16,u+=l>>>16,d+=u>>>16,new e(u&m|d<<16,c&m|l<<16)}function pi(c,l){return new e(c.hi>>>l,c.lo>>>l|c.hi<<32-l)}function cs(){var c=0,l=0,u;for(u=0;u<arguments.length;u++)c^=arguments[u].lo,l^=arguments[u].hi;return new e(l,c)}function Le(c,l){var u,d,m=32-l;return l<32?(u=c.hi>>>l|c.lo<<m,d=c.lo>>>l|c.hi<<m):l<64&&(u=c.lo>>>l|c.hi<<m,d=c.hi>>>l|c.lo<<m),new e(u,d)}function ra(c,l,u){var d=c.hi&l.hi^~c.hi&u.hi,m=c.lo&l.lo^~c.lo&u.lo;return new e(d,m)}function ia(c,l,u){var d=c.hi&l.hi^c.hi&u.hi^l.hi&u.hi,m=c.lo&l.lo^c.lo&u.lo^l.lo&u.lo;return new e(d,m)}function na(c){return cs(Le(c,28),Le(c,34),Le(c,39))}function oa(c){return cs(Le(c,14),Le(c,18),Le(c,41))}function aa(c){return cs(Le(c,1),Le(c,8),pi(c,7))}function ca(c){return cs(Le(c,19),Le(c,61),pi(c,6))}var ha=[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 mi(c,l,u){var d=[],m=[],b=[],v=[],E,_,S;for(_=0;_<8;_++)d[_]=b[_]=J(c,8*_);for(var M=0;u>=128;){for(_=0;_<16;_++)v[_]=J(l,8*_+M);for(_=0;_<80;_++){for(S=0;S<8;S++)m[S]=b[S];for(E=Nt(b[7],oa(b[4]),ra(b[4],b[5],b[6]),ha[_],v[_%16]),m[7]=Nt(E,na(b[0]),ia(b[0],b[1],b[2])),m[3]=Nt(m[3],E),S=0;S<8;S++)b[(S+1)%8]=m[S];if(_%16===15)for(S=0;S<16;S++)v[S]=Nt(v[S],v[(S+9)%16],aa(v[(S+1)%16]),ca(v[(S+14)%16]))}for(_=0;_<8;_++)b[_]=Nt(b[_],d[_]),d[_]=b[_];M+=128,u-=128}for(_=0;_<8;_++)L(c,8*_,d[_]);return u}var ua=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 et(c,l,u){var d=new Uint8Array(64),m=new Uint8Array(256),b,v=u;for(b=0;b<64;b++)d[b]=ua[b];for(mi(d,l,u),u%=128,b=0;b<256;b++)m[b]=0;for(b=0;b<u;b++)m[b]=l[v-u+b];for(m[u]=128,u=256-128*(u<112?1:0),m[u-9]=0,L(m,u-8,new e(v/536870912|0,v<<3)),mi(d,m,u),b=0;b<64;b++)c[b]=d[b];return 0}function hs(c,l){var u=t(),d=t(),m=t(),b=t(),v=t(),E=t(),_=t(),S=t(),M=t();Te(u,c[1],c[0]),Te(M,l[1],l[0]),B(u,u,M),Ne(d,c[0],c[1]),Ne(M,l[0],l[1]),B(d,d,M),B(m,c[3],l[3]),B(m,m,g),B(b,c[2],l[2]),Ne(b,b,b),Te(v,d,u),Te(E,b,m),Ne(_,b,m),Ne(S,d,u),B(c[0],v,E),B(c[1],S,_),B(c[2],_,E),B(c[3],v,S)}function bi(c,l,u){var d;for(d=0;d<4;d++)ue(c[d],l[d],u)}function Xs(c,l){var u=t(),d=t(),m=t();ui(m,l[2]),B(u,l[0],m),B(d,l[1],m),dt(c,d),c[31]^=hi(u)<<7}function Zs(c,l,u){var d,m;for(X(c[0],o),X(c[1],a),X(c[2],a),X(c[3],o),m=255;m>=0;--m)d=u[m/8|0]>>(m&7)&1,bi(c,l,d),hs(l,c),hs(c,c),bi(c,l,d)}function us(c,l){var u=[t(),t(),t(),t()];X(u[0],y),X(u[1],x),X(u[2],a),B(u[3],y,x),Zs(c,u,l)}function Qs(c,l,u){var d=new Uint8Array(64),m=[t(),t(),t(),t()],b;for(u||s(l,32),et(d,l,32),d[0]&=248,d[31]&=127,d[31]|=64,us(m,d),Xs(c,m),b=0;b<32;b++)l[b+32]=c[b];return 0}var ls=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 er(c,l){var u,d,m,b;for(d=63;d>=32;--d){for(u=0,m=d-32,b=d-12;m<b;++m)l[m]+=u-16*l[d]*ls[m-(d-32)],u=Math.floor((l[m]+128)/256),l[m]-=u*256;l[m]+=u,l[d]=0}for(u=0,m=0;m<32;m++)l[m]+=u-(l[31]>>4)*ls[m],u=l[m]>>8,l[m]&=255;for(m=0;m<32;m++)l[m]-=u*ls[m];for(d=0;d<32;d++)l[d+1]+=l[d]>>8,c[d]=l[d]&255}function tr(c){var l=new Float64Array(64),u;for(u=0;u<64;u++)l[u]=c[u];for(u=0;u<64;u++)c[u]=0;er(c,l)}function gi(c,l,u,d){var m=new Uint8Array(64),b=new Uint8Array(64),v=new Uint8Array(64),E,_,S=new Float64Array(64),M=[t(),t(),t(),t()];et(m,d,32),m[0]&=248,m[31]&=127,m[31]|=64;var D=u+64;for(E=0;E<u;E++)c[64+E]=l[E];for(E=0;E<32;E++)c[32+E]=m[32+E];for(et(v,c.subarray(32),u+32),tr(v),us(M,v),Xs(c,M),E=32;E<64;E++)c[E]=d[E];for(et(b,c,u+64),tr(b),E=0;E<64;E++)S[E]=0;for(E=0;E<32;E++)S[E]=v[E];for(E=0;E<32;E++)for(_=0;_<32;_++)S[E+_]+=b[E]*m[_];return er(c.subarray(32),S),D}function la(c,l){var u=t(),d=t(),m=t(),b=t(),v=t(),E=t(),_=t();return X(c[2],a),Ys(c[1],l),Ie(m,c[1]),B(b,m,p),Te(m,m,c[2]),Ne(b,c[2],b),Ie(v,b),Ie(E,v),B(_,E,v),B(u,_,m),B(u,u,b),li(u,u),B(u,u,m),B(u,u,b),B(u,u,b),B(c[0],u,b),Ie(d,c[0]),B(d,d,b),ci(d,m)&&B(c[0],c[0],A),Ie(d,c[0]),B(d,d,b),ci(d,m)?-1:(hi(c[0])===l[31]>>7&&Te(c[0],o,c[0]),B(c[3],c[0],c[1]),0)}function sr(c,l,u,d){var m,b=new Uint8Array(32),v=new Uint8Array(64),E=[t(),t(),t(),t()],_=[t(),t(),t(),t()];if(u<64||la(_,d))return-1;for(m=0;m<u;m++)c[m]=l[m];for(m=0;m<32;m++)c[m+32]=d[m];if(et(v,c,u),tr(v),Zs(E,_,v),us(_,l.subarray(32)),hs(E,_),Xs(b,E),u-=64,w(l,0,b,0)){for(m=0;m<u;m++)c[m]=0;return-1}for(m=0;m<u;m++)c[m]=l[m+64];return u}var rr=32,fs=24,Tt=32,pt=16,Mt=32,ds=32,Ut=32,$t=32,ir=32,_i=fs,fa=Tt,da=pt,De=64,tt=32,mt=64,nr=32,or=64;r.lowlevel={crypto_core_hsalsa20:R,crypto_stream_xor:Y,crypto_stream:$,crypto_stream_salsa20_xor:U,crypto_stream_salsa20:q,crypto_onetimeauth:ne,crypto_onetimeauth_verify:he,crypto_verify_16:_e,crypto_verify_32:w,crypto_secretbox:fe,crypto_secretbox_open:de,crypto_scalarmult:ns,crypto_scalarmult_base:os,crypto_box_beforenm:as,crypto_box_afternm:di,crypto_box:ta,crypto_box_open:sa,crypto_box_keypair:fi,crypto_hash:et,crypto_sign:gi,crypto_sign_keypair:Qs,crypto_sign_open:sr,crypto_secretbox_KEYBYTES:rr,crypto_secretbox_NONCEBYTES:fs,crypto_secretbox_ZEROBYTES:Tt,crypto_secretbox_BOXZEROBYTES:pt,crypto_scalarmult_BYTES:Mt,crypto_scalarmult_SCALARBYTES:ds,crypto_box_PUBLICKEYBYTES:Ut,crypto_box_SECRETKEYBYTES:$t,crypto_box_BEFORENMBYTES:ir,crypto_box_NONCEBYTES:_i,crypto_box_ZEROBYTES:fa,crypto_box_BOXZEROBYTES:da,crypto_sign_BYTES:De,crypto_sign_PUBLICKEYBYTES:tt,crypto_sign_SECRETKEYBYTES:mt,crypto_sign_SEEDBYTES:nr,crypto_hash_BYTES:or,gf:t,D:p,L:ls,pack25519:dt,unpack25519:Ys,M:B,A:Ne,S:Ie,Z:Te,pow2523:li,add:hs,set25519:X,modL:er,scalarmult:Zs,scalarbase:us};function yi(c,l){if(c.length!==rr)throw new Error("bad key size");if(l.length!==fs)throw new Error("bad nonce size")}function pa(c,l){if(c.length!==Ut)throw new Error("bad public key size");if(l.length!==$t)throw new Error("bad secret key size")}function Ae(){for(var c=0;c<arguments.length;c++)if(!(arguments[c]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function wi(c){for(var l=0;l<c.length;l++)c[l]=0}r.randomBytes=function(c){var l=new Uint8Array(c);return s(l,c),l},r.secretbox=function(c,l,u){Ae(c,l,u),yi(u,l);for(var d=new Uint8Array(Tt+c.length),m=new Uint8Array(d.length),b=0;b<c.length;b++)d[b+Tt]=c[b];return fe(m,d,d.length,l,u),m.subarray(pt)},r.secretbox.open=function(c,l,u){Ae(c,l,u),yi(u,l);for(var d=new Uint8Array(pt+c.length),m=new Uint8Array(d.length),b=0;b<c.length;b++)d[b+pt]=c[b];return d.length<32||de(m,d,d.length,l,u)!==0?null:m.subarray(Tt)},r.secretbox.keyLength=rr,r.secretbox.nonceLength=fs,r.secretbox.overheadLength=pt,r.scalarMult=function(c,l){if(Ae(c,l),c.length!==ds)throw new Error("bad n size");if(l.length!==Mt)throw new Error("bad p size");var u=new Uint8Array(Mt);return ns(u,c,l),u},r.scalarMult.base=function(c){if(Ae(c),c.length!==ds)throw new Error("bad n size");var l=new Uint8Array(Mt);return os(l,c),l},r.scalarMult.scalarLength=ds,r.scalarMult.groupElementLength=Mt,r.box=function(c,l,u,d){var m=r.box.before(u,d);return r.secretbox(c,l,m)},r.box.before=function(c,l){Ae(c,l),pa(c,l);var u=new Uint8Array(ir);return as(u,c,l),u},r.box.after=r.secretbox,r.box.open=function(c,l,u,d){var m=r.box.before(u,d);return r.secretbox.open(c,l,m)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var c=new Uint8Array(Ut),l=new Uint8Array($t);return fi(c,l),{publicKey:c,secretKey:l}},r.box.keyPair.fromSecretKey=function(c){if(Ae(c),c.length!==$t)throw new Error("bad secret key size");var l=new Uint8Array(Ut);return os(l,c),{publicKey:l,secretKey:new Uint8Array(c)}},r.box.publicKeyLength=Ut,r.box.secretKeyLength=$t,r.box.sharedKeyLength=ir,r.box.nonceLength=_i,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(c,l){if(Ae(c,l),l.length!==mt)throw new Error("bad secret key size");var u=new Uint8Array(De+c.length);return gi(u,c,c.length,l),u},r.sign.open=function(c,l){if(Ae(c,l),l.length!==tt)throw new Error("bad public key size");var u=new Uint8Array(c.length),d=sr(u,c,c.length,l);if(d<0)return null;for(var m=new Uint8Array(d),b=0;b<m.length;b++)m[b]=u[b];return m},r.sign.detached=function(c,l){for(var u=r.sign(c,l),d=new Uint8Array(De),m=0;m<d.length;m++)d[m]=u[m];return d},r.sign.detached.verify=function(c,l,u){if(Ae(c,l,u),l.length!==De)throw new Error("bad signature size");if(u.length!==tt)throw new Error("bad public key size");var d=new Uint8Array(De+c.length),m=new Uint8Array(De+c.length),b;for(b=0;b<De;b++)d[b]=l[b];for(b=0;b<c.length;b++)d[b+De]=c[b];return sr(m,d,d.length,u)>=0},r.sign.keyPair=function(){var c=new Uint8Array(tt),l=new Uint8Array(mt);return Qs(c,l),{publicKey:c,secretKey:l}},r.sign.keyPair.fromSecretKey=function(c){if(Ae(c),c.length!==mt)throw new Error("bad secret key size");for(var l=new Uint8Array(tt),u=0;u<l.length;u++)l[u]=c[32+u];return{publicKey:l,secretKey:new Uint8Array(c)}},r.sign.keyPair.fromSeed=function(c){if(Ae(c),c.length!==nr)throw new Error("bad seed size");for(var l=new Uint8Array(tt),u=new Uint8Array(mt),d=0;d<32;d++)u[d]=c[d];return Qs(l,u,!0),{publicKey:l,secretKey:u}},r.sign.publicKeyLength=tt,r.sign.secretKeyLength=mt,r.sign.seedLength=nr,r.sign.signatureLength=De,r.hash=function(c){Ae(c);var l=new Uint8Array(or);return et(l,c,c.length),l},r.hash.hashLength=or,r.verify=function(c,l){return Ae(c,l),c.length===0||l.length===0||c.length!==l.length?!1:ee(c,0,l,0,c.length)===0},r.setPRNG=function(c){s=c},function(){var c=typeof globalThis<"u"?globalThis.crypto||globalThis.msCrypto:null;if(c&&c.getRandomValues){var l=65536;r.setPRNG(function(u,d){var m,b=new Uint8Array(d);for(m=0;m<d;m+=l)c.getRandomValues(b.subarray(m,m+Math.min(d-m,l)));for(m=0;m<d;m++)u[m]=b[m];wi(b)})}else typeof require<"u"&&(crypto = window.crypto || globalThis.crypto,c&&c.randomBytes&&r.setPRNG(function(u,d){var m,b=c.randomBytes(d);for(m=0;m<d;m++)u[m]=b[m];wi(b)}))}()}(typeof module<"u"&&module.exports?module.exports:globalThis.nacl=globalThis.nacl||{});const Yt=typeof module<"u"&&module.exports?module.exports:globalThis.nacl,Tn={fromSeed:Yt.sign.keyPair.fromSeed,sign:Yt.sign.detached,verify:Yt.sign.detached.verify,randomBytes:Yt.randomBytes};let Fr;function Mn(r){Fr=r}function Ye(){return Fr}const Un=new Uint16Array([0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920]);class Xt{static checksum(e){let t=0;for(let s=0;s<e.byteLength;s++){let i=e[s];t=t<<8&65535^Un[(t>>8^i)&255]}return t}static validate(e,t){return Xt.checksum(e)==t}}const Ls="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";class Br{static encode(e){let t=0,s=0,i=new Uint8Array(e),n=new Uint8Array(e.byteLength*2),o=0;for(let a=0;a<i.byteLength;a++)for(s=s<<8|i[a],t+=8;t>=5;){let f=s>>>t-5&31;n[o++]=Ls.charAt(f).charCodeAt(0),t-=5}if(t>0){let a=s<<5-t&31;n[o++]=Ls.charAt(a).charCodeAt(0)}return n.slice(0,o)}static decode(e){let t=0,s=0,i=0,n=new Uint8Array(e),o=new Uint8Array(n.byteLength*5/8|0);for(let a=0;a<n.byteLength;a++){let f=String.fromCharCode(n[a]),p=Ls.indexOf(f);if(p===-1)throw new Error("Illegal Base32 character: "+n[a]);s=s<<5|p,t+=5,t>=8&&(o[i++]=s>>>t-8&255,t-=8)}return o.slice(0,i)}}class z extends Error{constructor(t,s){super(t);h(this,"name");h(this,"code");h(this,"chainedError");this.name="NKeysError",this.code=t,this.chainedError=s}}function $n(){return Zt(G.Operator)}function Ln(){return Zt(G.Account)}function qn(){return Zt(G.User)}var K;(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"})(K||(K={}));var G;(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"})(G||(G={}));class lt{static isValidPublicPrefix(e){return e==G.Server||e==G.Operator||e==G.Cluster||e==G.Account||e==G.User}static startsWithValidPrefix(e){let t=e[0];return t=="S"||t=="P"||t=="O"||t=="N"||t=="C"||t=="A"||t=="U"}static isValidPrefix(e){return this.parsePrefix(e)!=-1}static parsePrefix(e){switch(e){case G.Seed:return G.Seed;case G.Private:return G.Private;case G.Operator:return G.Operator;case G.Server:return G.Server;case G.Cluster:return G.Cluster;case G.Account:return G.Account;case G.User:return G.User;default:return-1}}}class ge{static encode(e,t){if(!t||!(t instanceof Uint8Array))throw new z(K.SerializationError);if(!lt.isValidPrefix(e))throw new z(K.InvalidPrefixByte);return ge._encode(!1,e,t)}static encodeSeed(e,t){if(!t)throw new z(K.ApiError);if(!lt.isValidPublicPrefix(e))throw new z(K.InvalidPrefixByte);if(t.byteLength!==32)throw new z(K.InvalidSeedLen);return ge._encode(!0,e,t)}static decode(e,t){if(!lt.isValidPrefix(e))throw new z(K.InvalidPrefixByte);const s=ge._decode(t);if(s[0]!==e)throw new z(K.InvalidPrefixByte);return s.slice(1)}static decodeSeed(e){const t=ge._decode(e),s=ge._decodePrefix(t);if(s[0]!=G.Seed)throw new z(K.InvalidSeed);if(!lt.isValidPublicPrefix(s[1]))throw new z(K.InvalidPrefixByte);return{buf:t.slice(2),prefix:s[1]}}static _encode(e,t,s){const i=e?2:1,n=s.byteLength,o=i+n+2,a=i+n,f=new Uint8Array(o);if(e){const y=ge._encodePrefix(G.Seed,t);f.set(y)}else f[0]=t;f.set(s,i);const p=Xt.checksum(f.slice(0,a));return new DataView(f.buffer).setUint16(a,p,!0),Br.encode(f)}static _decode(e){if(e.byteLength<4)throw new z(K.InvalidEncoding);let t;try{t=Br.decode(e)}catch(a){throw new z(K.InvalidEncoding,a)}const s=t.byteLength-2,n=new DataView(t.buffer).getUint16(s,!0),o=t.slice(0,s);if(!Xt.validate(o,n))throw new z(K.InvalidChecksum);return o}static _encodePrefix(e,t){const s=e|t>>5,i=(t&31)<<3;return new Uint8Array([s,i])}static _decodePrefix(e){const t=e[0]&248,s=(e[0]&7)<<5|(e[1]&248)>>3;return new Uint8Array([t,s])}}class Dr{constructor(e){h(this,"seed");this.seed=e}getRawSeed(){if(!this.seed)throw new z(K.ClearedPair);return ge.decodeSeed(this.seed).buf}getSeed(){if(!this.seed)throw new z(K.ClearedPair);return this.seed}getPublicKey(){if(!this.seed)throw new z(K.ClearedPair);const e=ge.decodeSeed(this.seed),t=Ye().fromSeed(this.getRawSeed()),s=ge.encode(e.prefix,t.publicKey);return new TextDecoder().decode(s)}getPrivateKey(){if(!this.seed)throw new z(K.ClearedPair);const e=Ye().fromSeed(this.getRawSeed());return ge.encode(G.Private,e.secretKey)}sign(e){if(!this.seed)throw new z(K.ClearedPair);const t=Ye().fromSeed(this.getRawSeed());return Ye().sign(e,t.secretKey)}verify(e,t){if(!this.seed)throw new z(K.ClearedPair);const s=Ye().fromSeed(this.getRawSeed());return Ye().verify(e,t,s.publicKey)}clear(){this.seed&&(this.seed.fill(0),this.seed=void 0)}}function Zt(r){const e=Ye().randomBytes(32);let t=ge.encodeSeed(r,new Uint8Array(e));return new Dr(t)}class Fn{constructor(e){h(this,"publicKey");this.publicKey=e}getPublicKey(){if(!this.publicKey)throw new z(K.ClearedPair);return new TextDecoder().decode(this.publicKey)}getPrivateKey(){throw this.publicKey?new z(K.PublicKeyOnly):new z(K.ClearedPair)}getSeed(){throw this.publicKey?new z(K.PublicKeyOnly):new z(K.ClearedPair)}sign(e){throw this.publicKey?new z(K.CannotSign):new z(K.ClearedPair)}verify(e,t){if(!this.publicKey)throw new z(K.ClearedPair);let s=ge._decode(this.publicKey);return Ye().verify(e,t,s.slice(1))}clear(){this.publicKey&&(this.publicKey.fill(0),this.publicKey=void 0)}}function Bn(r){const e=new TextEncoder().encode(r),t=ge._decode(e),s=lt.parsePrefix(t[0]);if(lt.isValidPublicPrefix(s))return new Fn(e);throw new z(K.InvalidPublicKey)}function Dn(r){return ge.decodeSeed(r),new Dr(r)}function Hn(r){return btoa(String.fromCharCode(...r))}function Jn(r){const e=atob(r),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}Mn(Tn);const Hr={createAccount:Ln,createOperator:$n,createPair:Zt,createUser:qn,fromPublic:Bn,fromSeed:Dn,NKeysError:z,NKeysErrorCode:K,Prefix:G,decode:Jn,encode:Hn};function Kn(r){return e=>{let t={};return r.forEach(s=>{const i=s(e)||{};t=Object.assign(t,i)}),t}}function zn(){return()=>{}}function Gn(r,e){return()=>{const t=typeof r=="function"?r():r,s=typeof e=="function"?e():e;return{user:t,pass:s}}}function Vn(r){return()=>({auth_token:typeof r=="function"?r():r})}function Wn(r){return e=>{const t=typeof r=="function"?r():r,s=t?Hr.fromSeed(t):void 0,i=s?s.getPublicKey():"",n=He.encode(e||""),o=s!==void 0&&e?s.sign(n):void 0,a=o?Hr.encode(o):"";return{nkey:i,sig:a}}}function Yn(r,e){return t=>{const s=typeof r=="function"?r():r,i=Wn(e),{nkey:n,sig:o}=i(t);return{jwt:s,nkey:n,sig:o}}}const Jr=2*60*1e3,Xn=2,Kr=2*1e3;function Zn(){return{maxPingOut:2,maxReconnectAttempts:10,noRandomize:!1,pedantic:!1,pingInterval:Jr,reconnect:!0,reconnectJitter:100,reconnectJitterTLS:1e3,reconnectTimeWait:Kr,tls:void 0,verbose:!1,waitOnFirstConnect:!1,ignoreAuthErrorAbort:!1}}function Qn(r){const e=[];return typeof r.authenticator=="function"&&e.push(r.authenticator),Array.isArray(r.authenticator)&&e.push(...r.authenticator),r.token&&e.push(Vn(r.token)),r.user&&e.push(Gn(r.user,r.pass)),e.length===0?zn():Kn(e)}function eo(r){const e=`${_s}:${Tr()}`;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 N("port and servers options are mutually exclusive",k.InvalidOption);r.servers.length===0&&r.port&&(r.servers=[`${_s}:${r.port}`]),r.servers&&r.servers.length===0&&(r.servers=[e]);const t=Bt(Zn(),r);if(t.authenticator=Qn(t),["reconnectDelayHandler","authenticator"].forEach(s=>{if(t[s]&&typeof t[s]!="function")throw new N(`${s} option should be a function`,k.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{Fe(t.inboxPrefix)}catch(s){throw new N(s.message,k.ApiError)}if(t.resolve===void 0&&(t.resolve=typeof Ns()=="function"),t.resolve&&typeof Ns()!="function")throw new N("'resolve' is not supported on this client",k.InvalidOption);return t}function to(r,e){const{proto:t,tls_required:s,tls_available:i}=r;if((t===void 0||t<1)&&e.noEcho)throw new N("noEcho",k.ServerOptionNotAvailable);const n=s||i||!1;if(e.tls&&!n)throw new N("tls",k.ServerOptionNotAvailable)}const so=1024*32,ro=/^INFO\s+([^\r\n]+)\r\n/i,io=yt(`PONG\r
12
+ ${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||N.errorForCode(k.Cancelled))}}const an="$JS.API";function cn(r){return r=r||{},r.domain&&(r.apiPrefix=`$JS.${r.domain}.API`,delete r.domain),Bt({apiPrefix:an,timeout:5e3},r)}class Et{constructor(e,t){h(this,"nc");h(this,"opts");h(this,"prefix");h(this,"timeout");h(this,"jc");this.nc=e,this.opts=cn(t),this._parseOpts(),this.prefix=this.opts.apiPrefix,this.timeout=this.opts.timeout,this.jc=ke()}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 i=we;t&&(i=this.jc.encode(t));let{retries:n}=s;n=n||1,n=n===-1?Number.MAX_SAFE_INTEGER:n;const o=ys();for(let a=0;a<n;a++)try{const f=await this.nc.request(e,i,s);return this.parseJsResponse(f)}catch(f){const p=f;if((p.code==="503"||p.code===k.Timeout)&&a+1<n)await st(o.backoff(a));else throw f}}async findStream(e){const t={subject:e},i=await this._request(`${this.prefix}.STREAM.NAMES`,t);if(!i.streams||i.streams.length!==1)throw new Error("no stream matches subject");return i.streams[0]}getConnection(){return this.nc}parseJsResponse(e){const t=this.jc.decode(e.data),s=t;if(s.error){const i=Er(s.error.code,s.error.description);if(i!==null)throw i.api_error=s.error,i}return t}}class At{constructor(e,t,s,i){h(this,"err");h(this,"offset");h(this,"pageInfo");h(this,"subject");h(this,"jsm");h(this,"filter");h(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=i||{}}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});this.pageInfo=t;const s=this.countResponse(t);return s===0?[]:(this.offset+=s,this.filter(t))}catch(t){throw this.err=t,t}}countResponse(e){var t,s,i;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((t=e.streams)==null?void 0:t.length)||0;case"io.nats.jetstream.api.v1.consumer_list_response":return((s=e.consumers)==null?void 0:s.length)||0;default:return console.error(`jslister.ts: unknown API response for paged output: ${e==null?void 0:e.type}`),((i=e.streams)==null?void 0:i.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()}}}function Ze(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 js(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 H;(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",r.JS_BATCH_DIRECT_GET="js_batch_direct_get"})(H||(H={}));class hn{constructor(e){h(this,"server");h(this,"features");h(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=Ze(e)),this.server=e,this.set(H.JS_KV,"2.6.2"),this.set(H.JS_OBJECTSTORE,"2.6.3"),this.set(H.JS_PULL_MAX_BYTES,"2.8.3"),this.set(H.JS_NEW_CONSUMER_CREATE_API,"2.9.0"),this.set(H.JS_ALLOW_DIRECT,"2.9.0"),this.set(H.JS_MULTIPLE_CONSUMER_FILTER,"2.10.0"),this.set(H.JS_SIMPLIFICATION,"2.9.4"),this.set(H.JS_STREAM_CONSUMER_METADATA,"2.10.0"),this.set(H.JS_CONSUMER_FILTER_SUBJECTS,"2.10.0"),this.set(H.JS_STREAM_FIRST_SEQ,"2.10.0"),this.set(H.JS_STREAM_SUBJECT_TRANSFORM,"2.10.0"),this.set(H.JS_STREAM_SOURCE_SUBJECT_TRANSFORM,"2.10.0"),this.set(H.JS_STREAM_COMPRESSION,"2.10.0"),this.set(H.JS_DEFAULT_CONSUMER_LIMITS,"2.10.0"),this.set(H.JS_BATCH_DIRECT_GET,"2.11.0"),this.disabled.forEach(t=>{this.features.delete(t)})}set(e,t){this.features.set(e,{min:t,ok:js(this.server,Ze(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=Ze(e)),js(this.server,e)>=0}}class zt extends Et{constructor(e,t){super(e,t)}async add(e,t,s=Jt.Create){if(pe(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 i={};i.config=t,i.stream_name=e,i.action=s,i.config.durable_name&&rt(i.config.durable_name);const n=this.nc;let{min:o,ok:a}=n.features.get(H.JS_NEW_CONSUMER_CREATE_API);const f=t.name===""?void 0:t.name;if(f&&!a)throw new Error(`consumer 'name' requires server ${o}`);if(f)try{Ht("name",f)}catch(x){const A=x.message,I=A.indexOf("cannot contain");throw I!==-1?new Error(`consumer 'name' ${A.substring(I)}`):x}let p,g="";if(Array.isArray(t.filter_subjects)){const{min:x,ok:A}=n.features.get(H.JS_MULTIPLE_CONSUMER_FILTER);if(!A)throw new Error(`consumer 'filter_subjects' requires server ${x}`);a=!1}if(t.metadata){const{min:x,ok:A}=n.features.get(H.JS_STREAM_CONSUMER_METADATA);if(!A)throw new Error(`consumer 'metadata' requires server ${x}`)}if(a&&(g=t.name??t.durable_name??""),g!==""){let x=t.filter_subject??void 0;x===">"&&(x=void 0),p=x!==void 0?`${this.prefix}.CONSUMER.CREATE.${e}.${g}.${x}`:`${this.prefix}.CONSUMER.CREATE.${e}.${g}`}else p=t.durable_name?`${this.prefix}.CONSUMER.DURABLE.CREATE.${e}.${t.durable_name}`:`${this.prefix}.CONSUMER.CREATE.${e}`;return await this._request(p,i)}async update(e,t,s){const i=await this.info(e,t),n=s;return this.add(e,Object.assign(i.config,n),Jt.Update)}async info(e,t){return pe(e),rt(t),await this._request(`${this.prefix}.CONSUMER.INFO.${e}.${t}`)}async delete(e,t){return pe(e),rt(t),(await this._request(`${this.prefix}.CONSUMER.DELETE.${e}.${t}`)).success}list(e){pe(e);const t=i=>i.consumers,s=`${this.prefix}.CONSUMER.LIST.${e}`;return new At(s,t,this)}pause(e,t,s){const i=`${this.prefix}.CONSUMER.PAUSE.${e}.${t}`,n={pause_until:s.toISOString()};return this._request(i,n)}resume(e,t){return this.pause(e,t,new Date(0))}}function ht(r,e,t=!1){if(t===!0&&!r)throw N.errorForCode(k.ApiError,new Error(`${e} is not a function`));if(r&&typeof r!="function")throw N.errorForCode(k.ApiError,new Error(`${e} is not a function`))}class un extends oe{constructor(t,s,i){super();h(this,"sub");h(this,"adapter");h(this,"subIterDone");ht(i.adapter,"adapter",!0),this.adapter=i.adapter,i.callback&&ht(i.callback,"callback"),this.noIterator=typeof i.callback=="function",i.ingestionFilterFn&&(ht(i.ingestionFilterFn,"ingestionFilterFn"),this.ingestionFilterFn=i.ingestionFilterFn),i.protocolFilterFn&&(ht(i.protocolFilterFn,"protocolFilterFn"),this.protocolFilterFn=i.protocolFilterFn),i.dispatchedFn&&(ht(i.dispatchedFn,"dispatchedFn"),this.dispatchedFn=i.dispatchedFn),i.cleanupFn&&ht(i.cleanupFn,"cleanupFn");let n=(g,y)=>{this.callback(g,y)};if(i.callback){const g=i.callback;n=(y,x)=>{const[A,I]=this.adapter(y,x);if(A){g(A,null);return}const{ingest:T}=this.ingestionFilterFn?this.ingestionFilterFn(I,this):{ingest:!0};T&&(!this.protocolFilterFn||this.protocolFilterFn(I))&&(g(A,I),this.dispatchedFn&&I&&this.dispatchedFn(I))}}const{max:o,queue:a,timeout:f}=i,p={queue:a,timeout:f,callback:n};o&&o>0&&(p.max=o),this.sub=t.subscribe(s,p),i.cleanupFn&&(this.sub.cleanupFn=i.cleanupFn),this.noIterator||this.iterClosed.then(()=>{this.unsubscribe()}),this.subIterDone=V(),Promise.all([this.sub.closed,this.iterClosed]).then(()=>{this.subIterDone.resolve()}).catch(()=>{this.subIterDone.resolve()}),(async g=>{await g.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[i,n]=this.adapter(t,s);i&&this.stop(i),n&&this.push(n)}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}}let Ee;function ln(r){Ee=r}function Tr(){return Ee!==void 0&&Ee.defaultPort!==void 0?Ee.defaultPort:4222}function Rs(){return Ee!==void 0&&Ee.urlParseFn?Ee.urlParseFn:void 0}function fn(){if(!Ee||typeof Ee.factory!="function")throw new Error("transport fn is not set");return Ee.factory()}function Ns(){return Ee!==void 0&&Ee.dnsResolveFn?Ee.dnsResolveFn:void 0}const Gt=`\r
13
+ `,Vt=ct.fromAscii(Gt),dn=new Uint8Array(Vt)[0],pn=new Uint8Array(Vt)[1];function mn(r){for(let e=0;e<r.length;e++){const t=e+1;if(r.byteLength>t&&r[e]===dn&&r[t]===pn)return t+1}return 0}function bn(r){const e=mn(r);if(e>0){const s=new Uint8Array(r).slice(0,e);return xe.decode(s)}return""}const gn=4,Mr=48,_n=65,yn=97;function wn(r,e,t,s){const i=new Uint8Array(16);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((o,a)=>{i[a]=o}),i[12]=r,i[13]=e,i[14]=t,i[15]=s,i}function Ts(r){return xn(r)!==void 0}function xn(r){for(let e=0;e<r.length;e++)switch(r[e]){case".":return Ur(r);case":":return Sn(r)}}function Ur(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:i,ok:n}=vn(r);if(!n||s>255)return;r=r.substring(i),e[t]=s}return wn(e[0],e[1],e[2],e[3])}function Sn(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:i,c:n,ok:o}=En(r);if(!o||i>65535)return;if(n<r.length&&r[n]==="."){if(t<0&&s!=12||s+4>16)return;const a=Ur(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+=gn;break}if(e[s]=i>>8,e[s+1]=i,s+=2,r=r.substring(n),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 i=16-s;for(let n=s-1;n>=t;n--)e[n+i]=e[n];for(let n=t+i-1;n>=t;n--)e[n]=0}else if(t>=0)return;return e}}function vn(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)-Mr),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 En(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)-Mr;else if(97<=r.charCodeAt(t)&&r.charCodeAt(t)<=102)e*=16,e+=r.charCodeAt(t)-yn+10;else if(65<=r.charCodeAt(t)&&r.charCodeAt(t)<=70)e*=16,e+=r.charCodeAt(t)-_n+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 An(r){return r.indexOf("[")!==-1||r.indexOf("::")!==-1?!1:r.indexOf(".")!==-1||r.split(":").length<=2}function Ms(r){return!An(r)}function Pn(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 kn(r){r=r.trim(),r.match(/^(.*:\/\/)(.*)/m)&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2")),r=Pn(r),Ms(r)&&r.indexOf("[")===-1&&(r=`[${r}]`);const e=Ms(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",i=new URL(`${s}://${r}`);i.port=`${t}`;let n=i.hostname;return n.charAt(0)==="["&&(n=n.substring(1,n.length-1)),{listen:i.host,hostname:n,port:t}}class Pt{constructor(e,t=!1){h(this,"src");h(this,"listen");h(this,"hostname");h(this,"port");h(this,"didConnect");h(this,"reconnects");h(this,"lastConnect");h(this,"gossiped");h(this,"tlsName");h(this,"resolves");this.src=e,this.tlsName="";const s=kn(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||e.resolve===!1)return[this];const t=[];if(Ts(this.hostname))return[this];{const s=await e.fn(this.hostname);e.debug&&console.log(`resolve ${this.hostname} = ${s.join(",")}`);for(const i of s){const n=this.port===80?"https":"http",o=new URL(`${n}://${Ms(i)?"["+i+"]":i}`);o.port=`${this.port}`;const a=new Pt(o.host,!1);a.tlsName=this.hostname,t.push(a)}}return e.randomize&&xr(t),this.resolves=t,t}}class On{constructor(e=[],t={}){h(this,"firstSelect");h(this,"servers");h(this,"currentServer");h(this,"tlsName");h(this,"randomize");this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=t.randomize||!1;const s=Rs();e&&(e.forEach(i=>{i=s?s(i):i,this.servers.push(new Pt(i))}),this.randomize&&(this.servers=xr(this.servers))),this.servers.length===0&&this.addServer(`${_s}:${Tr()}`,!1),this.currentServer=this.servers[0]}clear(){this.servers.length=0}updateTLSName(){const e=this.getCurrentServer();Ts(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=Rs();e=s?s(e):e;const i=new Pt(e,t);Ts(i.hostname)&&(i.tlsName=this.tlsName),this.servers.push(i)}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,t){const s=[];let i=[];const n=Rs(),o=new Map;e.connect_urls&&e.connect_urls.length>0&&e.connect_urls.forEach(f=>{f=n?n(f,t):f;const p=new Pt(f,!0);o.set(f,p)});const a=[];return this.servers.forEach((f,p)=>{const g=f.listen;f.gossiped&&this.currentServer.listen!==g&&o.get(g)===void 0&&a.push(p),o.delete(g)}),a.reverse(),a.forEach(f=>{const p=this.servers.splice(f,1);i=i.concat(p[0].listen)}),o.forEach((f,p)=>{this.servers.push(f),s.push(p)}),{added:s,deleted:i}}}class Cn{constructor(){h(this,"baseInbox");h(this,"reqs");this.reqs=new Map}size(){return this.reqs.size}init(e){return this.baseInbox=`${Fe(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(i=>{i.resolver(t,{})}),!0;const s=t.permissionContext;if(s.operation==="publish"){const i=this.all().find(n=>n.requestSubject===s.subject);if(i)return i.resolver(t,{}),!0}}return!1}dispatcher(){return(e,t)=>{const s=this.getToken(t);if(s){const i=this.get(s);i&&(e===null&&t.headers&&(e=vr(t)),i.resolver(e,t))}}}close(){const e=N.errorForCode(k.Timeout);this.reqs.forEach(t=>{t.resolver(e,{})})}}class In{constructor(e,t,s){h(this,"ph");h(this,"interval");h(this,"maxOut");h(this,"timer");h(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:Ke.PingTimer,data:`${this.pendings.length+1}`}),this.pendings.length===this.maxOut){this.cancel(!0);return}const e=V();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 jn extends Error{constructor(e){super(e),this.name="AssertionError"}}function Rn(r,e="Assertion failed."){if(!r)throw new jn(e)}const $r=32*1024,Us=2**32-2;function Wt(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){h(this,"_buf");h(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){Rn(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=Wt(this._buf.subarray(this._off),e);return this._off+=t,t}writeByte(e){return this.write(Uint8Array.of(e))}writeString(e){return this.write(He.encode(e))}write(e){const t=this._grow(e.byteLength);return Wt(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 i=this.capacity;if(e<=Math.floor(i/2)-t)Wt(this._buf.subarray(this._off),this._buf);else{if(i+e>Us)throw new Error("The buffer cannot be grown beyond the maximum size.");{const n=new Uint8Array(Math.min(2*i+e,Us));Wt(this._buf.subarray(this._off),n),this._buf=n}}return this._off=0,this._reslice(Math.min(t+e,Us)),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($r);for(;;){const i=this.capacity-this.length<$r,n=i?s:new Uint8Array(this._buf.buffer,this.length),o=e.read(n);if(o===null)return t;i?this.write(n.subarray(0,o)):this._reslice(this.length+o),t+=o}}}var be;(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"})(be||(be={}));function Lr(){const r={};return r.sid=-1,r.hdr=-1,r.size=-1,r}const Nn=48;class qr{constructor(e){h(this,"dispatcher");h(this,"state");h(this,"as");h(this,"drop");h(this,"hdr");h(this,"ma");h(this,"argBuf");h(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=Lr();break;case C.H:case C.h:this.state=O.OP_H,this.hdr=0,this.ma=Lr();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 i=this.argBuf?this.argBuf.bytes():e.subarray(this.as,t-this.drop);this.processMsgArgs(i),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 i=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:be.MSG,msg:this.ma,data:i}),this.argBuf=void 0,this.msgBuf=void 0,this.state=O.MSG_END}else{let i=this.ma.size-this.msgBuf.length;const n=e.length-t;n<i&&(i=n),i>0?(this.msgBuf.write(e.subarray(t,t+i)),t=t+i-1):this.msgBuf.writeByte(s)}else t-this.as>=this.ma.size&&(this.dispatcher.push({kind:be.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:be.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 i;this.argBuf?(i=this.argBuf.bytes(),this.argBuf=void 0):i=e.subarray(this.as,t-this.drop),this.dispatcher.push({kind:be.ERR,data:i}),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:be.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:be.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 i;this.argBuf?(i=this.argBuf.bytes(),this.argBuf=void 0):i=e.subarray(this.as,t-this.drop),this.dispatcher.push({kind:be.INFO,data:i}),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 i=0;i<e.length;i++)switch(e[i]){case C.SPACE:case C.TAB:case C.CR:case C.NL:s>=0&&(t.push(e.subarray(s,i)),s=-1);break;default:s<0&&(s=i)}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}: ${xe.decode(e)}`)}processHeaderMsgArgs(e){const t=[];let s=-1;for(let i=0;i<e.length;i++)switch(e[i]){case C.SPACE:case C.TAB:case C.CR:case C.NL:s>=0&&(t.push(e.subarray(s,i)),s=-1);break;default:s<0&&(s=i)}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]-Nn)}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=13]="CR",r[r.E=69]="E",r[r.e=101]="e",r[r.F=70]="F",r[r.f=102]="f",r[r.G=71]="G",r[r.g=103]="g",r[r.H=72]="H",r[r.h=104]="h",r[r.I=73]="I",r[r.i=105]="i",r[r.K=75]="K",r[r.k=107]="k",r[r.M=77]="M",r[r.m=109]="m",r[r.MINUS=45]="MINUS",r[r.N=78]="N",r[r.n=110]="n",r[r.NL=10]="NL",r[r.O=79]="O",r[r.o=111]="o",r[r.P=80]="P",r[r.p=112]="p",r[r.PLUS=43]="PLUS",r[r.R=82]="R",r[r.r=114]="r",r[r.S=83]="S",r[r.s=115]="s",r[r.SPACE=32]="SPACE",r[r.TAB=9]="TAB"})(C||(C={})),function(r){var e=function(c,l){this.hi=c|0,this.lo=l|0},t=function(c){var l,u=new Float64Array(16);if(c)for(l=0;l<c.length;l++)u[l]=c[l];return u},s=function(){throw new Error("no PRNG")},i=new Uint8Array(16),n=new Uint8Array(32);n[0]=9;var o=t(),a=t([1]),f=t([56129,1]),p=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),g=t([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),y=t([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),x=t([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),A=t([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function I(c,l){return c<<l|c>>>32-l}function T(c,l){var u=c[l+3]&255;return u=u<<8|c[l+2]&255,u=u<<8|c[l+1]&255,u<<8|c[l+0]&255}function J(c,l){var u=c[l]<<24|c[l+1]<<16|c[l+2]<<8|c[l+3],d=c[l+4]<<24|c[l+5]<<16|c[l+6]<<8|c[l+7];return new e(u,d)}function se(c,l,u){var d;for(d=0;d<4;d++)c[l+d]=u&255,u>>>=8}function L(c,l,u){c[l]=u.hi>>24&255,c[l+1]=u.hi>>16&255,c[l+2]=u.hi>>8&255,c[l+3]=u.hi&255,c[l+4]=u.lo>>24&255,c[l+5]=u.lo>>16&255,c[l+6]=u.lo>>8&255,c[l+7]=u.lo&255}function ee(c,l,u,d,m){var b,v=0;for(b=0;b<m;b++)v|=c[l+b]^u[d+b];return(1&v-1>>>8)-1}function _e(c,l,u,d){return ee(c,l,u,d,16)}function w(c,l,u,d){return ee(c,l,u,d,32)}function j(c,l,u,d,m){var b=new Uint32Array(16),v=new Uint32Array(16),E=new Uint32Array(16),_=new Uint32Array(4),S,M,D;for(S=0;S<4;S++)v[5*S]=T(d,4*S),v[1+S]=T(u,4*S),v[6+S]=T(l,4*S),v[11+S]=T(u,16+4*S);for(S=0;S<16;S++)E[S]=v[S];for(S=0;S<20;S++){for(M=0;M<4;M++){for(D=0;D<4;D++)_[D]=v[(5*M+4*D)%16];for(_[1]^=I(_[0]+_[3]|0,7),_[2]^=I(_[1]+_[0]|0,9),_[3]^=I(_[2]+_[1]|0,13),_[0]^=I(_[3]+_[2]|0,18),D=0;D<4;D++)b[4*M+(M+D)%4]=_[D]}for(D=0;D<16;D++)v[D]=b[D]}if(m){for(S=0;S<16;S++)v[S]=v[S]+E[S]|0;for(S=0;S<4;S++)v[5*S]=v[5*S]-T(d,4*S)|0,v[6+S]=v[6+S]-T(l,4*S)|0;for(S=0;S<4;S++)se(c,4*S,v[5*S]),se(c,16+4*S,v[6+S])}else for(S=0;S<16;S++)se(c,4*S,v[S]+E[S]|0)}function F(c,l,u,d){return j(c,l,u,d,!1),0}function R(c,l,u,d){return j(c,l,u,d,!0),0}var P=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function U(c,l,u,d,m,b,v){var E=new Uint8Array(16),_=new Uint8Array(64),S,M;if(!m)return 0;for(M=0;M<16;M++)E[M]=0;for(M=0;M<8;M++)E[M]=b[M];for(;m>=64;){for(F(_,E,v,P),M=0;M<64;M++)c[l+M]=(u?u[d+M]:0)^_[M];for(S=1,M=8;M<16;M++)S=S+(E[M]&255)|0,E[M]=S&255,S>>>=8;m-=64,l+=64,u&&(d+=64)}if(m>0)for(F(_,E,v,P),M=0;M<m;M++)c[l+M]=(u?u[d+M]:0)^_[M];return 0}function q(c,l,u,d,m){return U(c,l,null,0,u,d,m)}function $(c,l,u,d,m){var b=new Uint8Array(32);return R(b,d,m,P),q(c,l,u,d.subarray(16),b)}function Y(c,l,u,d,m,b,v){var E=new Uint8Array(32);return R(E,b,v,P),U(c,l,u,d,m,b.subarray(16),E)}function ie(c,l){var u,d=0;for(u=0;u<17;u++)d=d+(c[u]+l[u]|0)|0,c[u]=d&255,d>>>=8}var ce=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]);function ne(c,l,u,d,m,b){var v,E,_,S,M=new Uint32Array(17),D=new Uint32Array(17),Z=new Uint32Array(17),Me=new Uint32Array(17),mt=new Uint32Array(17);for(_=0;_<17;_++)D[_]=Z[_]=0;for(_=0;_<16;_++)D[_]=b[_];for(D[3]&=15,D[4]&=252,D[7]&=15,D[8]&=252,D[11]&=15,D[12]&=252,D[15]&=15;m>0;){for(_=0;_<17;_++)Me[_]=0;for(_=0;_<16&&_<m;++_)Me[_]=u[d+_];for(Me[_]=1,d+=_,m-=_,ie(Z,Me),E=0;E<17;E++)for(M[E]=0,_=0;_<17;_++)M[E]=M[E]+Z[_]*(_<=E?D[E-_]:320*D[E+17-_]|0)|0|0;for(E=0;E<17;E++)Z[E]=M[E];for(S=0,_=0;_<16;_++)S=S+Z[_]|0,Z[_]=S&255,S>>>=8;for(S=S+Z[16]|0,Z[16]=S&3,S=5*(S>>>2)|0,_=0;_<16;_++)S=S+Z[_]|0,Z[_]=S&255,S>>>=8;S=S+Z[16]|0,Z[16]=S}for(_=0;_<17;_++)mt[_]=Z[_];for(ie(Z,ce),v=-(Z[16]>>>7)|0,_=0;_<17;_++)Z[_]^=v&(mt[_]^Z[_]);for(_=0;_<16;_++)Me[_]=b[_+16];for(Me[16]=0,ie(Z,Me),_=0;_<16;_++)c[l+_]=Z[_];return 0}function he(c,l,u,d,m,b){var v=new Uint8Array(16);return ne(v,0,u,d,m,b),_e(c,l,v,0)}function fe(c,l,u,d,m){var b;if(u<32)return-1;for(Y(c,0,l,0,u,d,m),ne(c,16,c,32,u-32,c),b=0;b<16;b++)c[b]=0;return 0}function de(c,l,u,d,m){var b,v=new Uint8Array(32);if(u<32||($(v,0,32,d,m),he(l,16,l,32,u-32,v)!==0))return-1;for(Y(c,0,l,0,u,d,m),b=0;b<32;b++)c[b]=0;return 0}function X(c,l){var u;for(u=0;u<16;u++)c[u]=l[u]|0}function re(c){var l,u;for(u=0;u<16;u++)c[u]+=65536,l=Math.floor(c[u]/65536),c[(u+1)*(u<15?1:0)]+=l-1+37*(l-1)*(u===15?1:0),c[u]-=l*65536}function ue(c,l,u){for(var d,m=~(u-1),b=0;b<16;b++)d=m&(c[b]^l[b]),c[b]^=d,l[b]^=d}function ft(c,l){var u,d,m,b=t(),v=t();for(u=0;u<16;u++)v[u]=l[u];for(re(v),re(v),re(v),d=0;d<2;d++){for(b[0]=v[0]-65517,u=1;u<15;u++)b[u]=v[u]-65535-(b[u-1]>>16&1),b[u-1]&=65535;b[15]=v[15]-32767-(b[14]>>16&1),m=b[15]>>16&1,b[14]&=65535,ue(v,b,1-m)}for(u=0;u<16;u++)c[2*u]=v[u]&255,c[2*u+1]=v[u]>>8}function ci(c,l){var u=new Uint8Array(32),d=new Uint8Array(32);return ft(u,c),ft(d,l),w(u,0,d,0)}function hi(c){var l=new Uint8Array(32);return ft(l,c),l[0]&1}function Ys(c,l){var u;for(u=0;u<16;u++)c[u]=l[2*u]+(l[2*u+1]<<8);c[15]&=32767}function Ne(c,l,u){var d;for(d=0;d<16;d++)c[d]=l[d]+u[d]|0}function Te(c,l,u){var d;for(d=0;d<16;d++)c[d]=l[d]-u[d]|0}function B(c,l,u){var d,m,b=new Float64Array(31);for(d=0;d<31;d++)b[d]=0;for(d=0;d<16;d++)for(m=0;m<16;m++)b[d+m]+=l[d]*u[m];for(d=0;d<15;d++)b[d]+=38*b[d+16];for(d=0;d<16;d++)c[d]=b[d];re(c),re(c)}function Ie(c,l){B(c,l,l)}function ui(c,l){var u=t(),d;for(d=0;d<16;d++)u[d]=l[d];for(d=253;d>=0;d--)Ie(u,u),d!==2&&d!==4&&B(u,u,l);for(d=0;d<16;d++)c[d]=u[d]}function li(c,l){var u=t(),d;for(d=0;d<16;d++)u[d]=l[d];for(d=250;d>=0;d--)Ie(u,u),d!==1&&B(u,u,l);for(d=0;d<16;d++)c[d]=u[d]}function ns(c,l,u){var d=new Uint8Array(32),m=new Float64Array(80),b,v,E=t(),_=t(),S=t(),M=t(),D=t(),Z=t();for(v=0;v<31;v++)d[v]=l[v];for(d[31]=l[31]&127|64,d[0]&=248,Ys(m,u),v=0;v<16;v++)_[v]=m[v],M[v]=E[v]=S[v]=0;for(E[0]=M[0]=1,v=254;v>=0;--v)b=d[v>>>3]>>>(v&7)&1,ue(E,_,b),ue(S,M,b),Ne(D,E,S),Te(E,E,S),Ne(S,_,M),Te(_,_,M),Ie(M,D),Ie(Z,E),B(E,S,E),B(S,_,D),Ne(D,E,S),Te(E,E,S),Ie(_,E),Te(S,M,Z),B(E,S,f),Ne(E,E,M),B(S,S,E),B(E,M,Z),B(M,_,m),Ie(_,D),ue(E,_,b),ue(S,M,b);for(v=0;v<16;v++)m[v+16]=E[v],m[v+32]=S[v],m[v+48]=_[v],m[v+64]=M[v];var Me=m.subarray(32),mt=m.subarray(16);return ui(Me,Me),B(mt,mt,Me),ft(c,mt),0}function os(c,l){return ns(c,l,n)}function fi(c,l){return s(l,32),os(c,l)}function as(c,l,u){var d=new Uint8Array(32);return ns(d,u,l),R(c,i,d,P)}var di=fe,ea=de;function ta(c,l,u,d,m,b){var v=new Uint8Array(32);return as(v,m,b),di(c,l,u,d,v)}function sa(c,l,u,d,m,b){var v=new Uint8Array(32);return as(v,m,b),ea(c,l,u,d,v)}function Nt(){var c=0,l=0,u=0,d=0,m=65535,b,v,E;for(E=0;E<arguments.length;E++)b=arguments[E].lo,v=arguments[E].hi,c+=b&m,l+=b>>>16,u+=v&m,d+=v>>>16;return l+=c>>>16,u+=l>>>16,d+=u>>>16,new e(u&m|d<<16,c&m|l<<16)}function pi(c,l){return new e(c.hi>>>l,c.lo>>>l|c.hi<<32-l)}function cs(){var c=0,l=0,u;for(u=0;u<arguments.length;u++)c^=arguments[u].lo,l^=arguments[u].hi;return new e(l,c)}function Le(c,l){var u,d,m=32-l;return l<32?(u=c.hi>>>l|c.lo<<m,d=c.lo>>>l|c.hi<<m):l<64&&(u=c.lo>>>l|c.hi<<m,d=c.hi>>>l|c.lo<<m),new e(u,d)}function ra(c,l,u){var d=c.hi&l.hi^~c.hi&u.hi,m=c.lo&l.lo^~c.lo&u.lo;return new e(d,m)}function ia(c,l,u){var d=c.hi&l.hi^c.hi&u.hi^l.hi&u.hi,m=c.lo&l.lo^c.lo&u.lo^l.lo&u.lo;return new e(d,m)}function na(c){return cs(Le(c,28),Le(c,34),Le(c,39))}function oa(c){return cs(Le(c,14),Le(c,18),Le(c,41))}function aa(c){return cs(Le(c,1),Le(c,8),pi(c,7))}function ca(c){return cs(Le(c,19),Le(c,61),pi(c,6))}var ha=[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 mi(c,l,u){var d=[],m=[],b=[],v=[],E,_,S;for(_=0;_<8;_++)d[_]=b[_]=J(c,8*_);for(var M=0;u>=128;){for(_=0;_<16;_++)v[_]=J(l,8*_+M);for(_=0;_<80;_++){for(S=0;S<8;S++)m[S]=b[S];for(E=Nt(b[7],oa(b[4]),ra(b[4],b[5],b[6]),ha[_],v[_%16]),m[7]=Nt(E,na(b[0]),ia(b[0],b[1],b[2])),m[3]=Nt(m[3],E),S=0;S<8;S++)b[(S+1)%8]=m[S];if(_%16===15)for(S=0;S<16;S++)v[S]=Nt(v[S],v[(S+9)%16],aa(v[(S+1)%16]),ca(v[(S+14)%16]))}for(_=0;_<8;_++)b[_]=Nt(b[_],d[_]),d[_]=b[_];M+=128,u-=128}for(_=0;_<8;_++)L(c,8*_,d[_]);return u}var ua=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 Qe(c,l,u){var d=new Uint8Array(64),m=new Uint8Array(256),b,v=u;for(b=0;b<64;b++)d[b]=ua[b];for(mi(d,l,u),u%=128,b=0;b<256;b++)m[b]=0;for(b=0;b<u;b++)m[b]=l[v-u+b];for(m[u]=128,u=256-128*(u<112?1:0),m[u-9]=0,L(m,u-8,new e(v/536870912|0,v<<3)),mi(d,m,u),b=0;b<64;b++)c[b]=d[b];return 0}function hs(c,l){var u=t(),d=t(),m=t(),b=t(),v=t(),E=t(),_=t(),S=t(),M=t();Te(u,c[1],c[0]),Te(M,l[1],l[0]),B(u,u,M),Ne(d,c[0],c[1]),Ne(M,l[0],l[1]),B(d,d,M),B(m,c[3],l[3]),B(m,m,g),B(b,c[2],l[2]),Ne(b,b,b),Te(v,d,u),Te(E,b,m),Ne(_,b,m),Ne(S,d,u),B(c[0],v,E),B(c[1],S,_),B(c[2],_,E),B(c[3],v,S)}function bi(c,l,u){var d;for(d=0;d<4;d++)ue(c[d],l[d],u)}function Xs(c,l){var u=t(),d=t(),m=t();ui(m,l[2]),B(u,l[0],m),B(d,l[1],m),ft(c,d),c[31]^=hi(u)<<7}function Zs(c,l,u){var d,m;for(X(c[0],o),X(c[1],a),X(c[2],a),X(c[3],o),m=255;m>=0;--m)d=u[m/8|0]>>(m&7)&1,bi(c,l,d),hs(l,c),hs(c,c),bi(c,l,d)}function us(c,l){var u=[t(),t(),t(),t()];X(u[0],y),X(u[1],x),X(u[2],a),B(u[3],y,x),Zs(c,u,l)}function Qs(c,l,u){var d=new Uint8Array(64),m=[t(),t(),t(),t()],b;for(u||s(l,32),Qe(d,l,32),d[0]&=248,d[31]&=127,d[31]|=64,us(m,d),Xs(c,m),b=0;b<32;b++)l[b+32]=c[b];return 0}var ls=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 er(c,l){var u,d,m,b;for(d=63;d>=32;--d){for(u=0,m=d-32,b=d-12;m<b;++m)l[m]+=u-16*l[d]*ls[m-(d-32)],u=Math.floor((l[m]+128)/256),l[m]-=u*256;l[m]+=u,l[d]=0}for(u=0,m=0;m<32;m++)l[m]+=u-(l[31]>>4)*ls[m],u=l[m]>>8,l[m]&=255;for(m=0;m<32;m++)l[m]-=u*ls[m];for(d=0;d<32;d++)l[d+1]+=l[d]>>8,c[d]=l[d]&255}function tr(c){var l=new Float64Array(64),u;for(u=0;u<64;u++)l[u]=c[u];for(u=0;u<64;u++)c[u]=0;er(c,l)}function gi(c,l,u,d){var m=new Uint8Array(64),b=new Uint8Array(64),v=new Uint8Array(64),E,_,S=new Float64Array(64),M=[t(),t(),t(),t()];Qe(m,d,32),m[0]&=248,m[31]&=127,m[31]|=64;var D=u+64;for(E=0;E<u;E++)c[64+E]=l[E];for(E=0;E<32;E++)c[32+E]=m[32+E];for(Qe(v,c.subarray(32),u+32),tr(v),us(M,v),Xs(c,M),E=32;E<64;E++)c[E]=d[E];for(Qe(b,c,u+64),tr(b),E=0;E<64;E++)S[E]=0;for(E=0;E<32;E++)S[E]=v[E];for(E=0;E<32;E++)for(_=0;_<32;_++)S[E+_]+=b[E]*m[_];return er(c.subarray(32),S),D}function la(c,l){var u=t(),d=t(),m=t(),b=t(),v=t(),E=t(),_=t();return X(c[2],a),Ys(c[1],l),Ie(m,c[1]),B(b,m,p),Te(m,m,c[2]),Ne(b,c[2],b),Ie(v,b),Ie(E,v),B(_,E,v),B(u,_,m),B(u,u,b),li(u,u),B(u,u,m),B(u,u,b),B(u,u,b),B(c[0],u,b),Ie(d,c[0]),B(d,d,b),ci(d,m)&&B(c[0],c[0],A),Ie(d,c[0]),B(d,d,b),ci(d,m)?-1:(hi(c[0])===l[31]>>7&&Te(c[0],o,c[0]),B(c[3],c[0],c[1]),0)}function sr(c,l,u,d){var m,b=new Uint8Array(32),v=new Uint8Array(64),E=[t(),t(),t(),t()],_=[t(),t(),t(),t()];if(u<64||la(_,d))return-1;for(m=0;m<u;m++)c[m]=l[m];for(m=0;m<32;m++)c[m+32]=d[m];if(Qe(v,c,u),tr(v),Zs(E,_,v),us(_,l.subarray(32)),hs(E,_),Xs(b,E),u-=64,w(l,0,b,0)){for(m=0;m<u;m++)c[m]=0;return-1}for(m=0;m<u;m++)c[m]=l[m+64];return u}var rr=32,fs=24,Tt=32,dt=16,Mt=32,ds=32,Ut=32,$t=32,ir=32,_i=fs,fa=Tt,da=dt,De=64,et=32,pt=64,nr=32,or=64;r.lowlevel={crypto_core_hsalsa20:R,crypto_stream_xor:Y,crypto_stream:$,crypto_stream_salsa20_xor:U,crypto_stream_salsa20:q,crypto_onetimeauth:ne,crypto_onetimeauth_verify:he,crypto_verify_16:_e,crypto_verify_32:w,crypto_secretbox:fe,crypto_secretbox_open:de,crypto_scalarmult:ns,crypto_scalarmult_base:os,crypto_box_beforenm:as,crypto_box_afternm:di,crypto_box:ta,crypto_box_open:sa,crypto_box_keypair:fi,crypto_hash:Qe,crypto_sign:gi,crypto_sign_keypair:Qs,crypto_sign_open:sr,crypto_secretbox_KEYBYTES:rr,crypto_secretbox_NONCEBYTES:fs,crypto_secretbox_ZEROBYTES:Tt,crypto_secretbox_BOXZEROBYTES:dt,crypto_scalarmult_BYTES:Mt,crypto_scalarmult_SCALARBYTES:ds,crypto_box_PUBLICKEYBYTES:Ut,crypto_box_SECRETKEYBYTES:$t,crypto_box_BEFORENMBYTES:ir,crypto_box_NONCEBYTES:_i,crypto_box_ZEROBYTES:fa,crypto_box_BOXZEROBYTES:da,crypto_sign_BYTES:De,crypto_sign_PUBLICKEYBYTES:et,crypto_sign_SECRETKEYBYTES:pt,crypto_sign_SEEDBYTES:nr,crypto_hash_BYTES:or,gf:t,D:p,L:ls,pack25519:ft,unpack25519:Ys,M:B,A:Ne,S:Ie,Z:Te,pow2523:li,add:hs,set25519:X,modL:er,scalarmult:Zs,scalarbase:us};function yi(c,l){if(c.length!==rr)throw new Error("bad key size");if(l.length!==fs)throw new Error("bad nonce size")}function pa(c,l){if(c.length!==Ut)throw new Error("bad public key size");if(l.length!==$t)throw new Error("bad secret key size")}function Ae(){for(var c=0;c<arguments.length;c++)if(!(arguments[c]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function wi(c){for(var l=0;l<c.length;l++)c[l]=0}r.randomBytes=function(c){var l=new Uint8Array(c);return s(l,c),l},r.secretbox=function(c,l,u){Ae(c,l,u),yi(u,l);for(var d=new Uint8Array(Tt+c.length),m=new Uint8Array(d.length),b=0;b<c.length;b++)d[b+Tt]=c[b];return fe(m,d,d.length,l,u),m.subarray(dt)},r.secretbox.open=function(c,l,u){Ae(c,l,u),yi(u,l);for(var d=new Uint8Array(dt+c.length),m=new Uint8Array(d.length),b=0;b<c.length;b++)d[b+dt]=c[b];return d.length<32||de(m,d,d.length,l,u)!==0?null:m.subarray(Tt)},r.secretbox.keyLength=rr,r.secretbox.nonceLength=fs,r.secretbox.overheadLength=dt,r.scalarMult=function(c,l){if(Ae(c,l),c.length!==ds)throw new Error("bad n size");if(l.length!==Mt)throw new Error("bad p size");var u=new Uint8Array(Mt);return ns(u,c,l),u},r.scalarMult.base=function(c){if(Ae(c),c.length!==ds)throw new Error("bad n size");var l=new Uint8Array(Mt);return os(l,c),l},r.scalarMult.scalarLength=ds,r.scalarMult.groupElementLength=Mt,r.box=function(c,l,u,d){var m=r.box.before(u,d);return r.secretbox(c,l,m)},r.box.before=function(c,l){Ae(c,l),pa(c,l);var u=new Uint8Array(ir);return as(u,c,l),u},r.box.after=r.secretbox,r.box.open=function(c,l,u,d){var m=r.box.before(u,d);return r.secretbox.open(c,l,m)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var c=new Uint8Array(Ut),l=new Uint8Array($t);return fi(c,l),{publicKey:c,secretKey:l}},r.box.keyPair.fromSecretKey=function(c){if(Ae(c),c.length!==$t)throw new Error("bad secret key size");var l=new Uint8Array(Ut);return os(l,c),{publicKey:l,secretKey:new Uint8Array(c)}},r.box.publicKeyLength=Ut,r.box.secretKeyLength=$t,r.box.sharedKeyLength=ir,r.box.nonceLength=_i,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(c,l){if(Ae(c,l),l.length!==pt)throw new Error("bad secret key size");var u=new Uint8Array(De+c.length);return gi(u,c,c.length,l),u},r.sign.open=function(c,l){if(Ae(c,l),l.length!==et)throw new Error("bad public key size");var u=new Uint8Array(c.length),d=sr(u,c,c.length,l);if(d<0)return null;for(var m=new Uint8Array(d),b=0;b<m.length;b++)m[b]=u[b];return m},r.sign.detached=function(c,l){for(var u=r.sign(c,l),d=new Uint8Array(De),m=0;m<d.length;m++)d[m]=u[m];return d},r.sign.detached.verify=function(c,l,u){if(Ae(c,l,u),l.length!==De)throw new Error("bad signature size");if(u.length!==et)throw new Error("bad public key size");var d=new Uint8Array(De+c.length),m=new Uint8Array(De+c.length),b;for(b=0;b<De;b++)d[b]=l[b];for(b=0;b<c.length;b++)d[b+De]=c[b];return sr(m,d,d.length,u)>=0},r.sign.keyPair=function(){var c=new Uint8Array(et),l=new Uint8Array(pt);return Qs(c,l),{publicKey:c,secretKey:l}},r.sign.keyPair.fromSecretKey=function(c){if(Ae(c),c.length!==pt)throw new Error("bad secret key size");for(var l=new Uint8Array(et),u=0;u<l.length;u++)l[u]=c[32+u];return{publicKey:l,secretKey:new Uint8Array(c)}},r.sign.keyPair.fromSeed=function(c){if(Ae(c),c.length!==nr)throw new Error("bad seed size");for(var l=new Uint8Array(et),u=new Uint8Array(pt),d=0;d<32;d++)u[d]=c[d];return Qs(l,u,!0),{publicKey:l,secretKey:u}},r.sign.publicKeyLength=et,r.sign.secretKeyLength=pt,r.sign.seedLength=nr,r.sign.signatureLength=De,r.hash=function(c){Ae(c);var l=new Uint8Array(or);return Qe(l,c,c.length),l},r.hash.hashLength=or,r.verify=function(c,l){return Ae(c,l),c.length===0||l.length===0||c.length!==l.length?!1:ee(c,0,l,0,c.length)===0},r.setPRNG=function(c){s=c},function(){var c=typeof globalThis<"u"?globalThis.crypto||globalThis.msCrypto:null;if(c&&c.getRandomValues){var l=65536;r.setPRNG(function(u,d){var m,b=new Uint8Array(d);for(m=0;m<d;m+=l)c.getRandomValues(b.subarray(m,m+Math.min(d-m,l)));for(m=0;m<d;m++)u[m]=b[m];wi(b)})}else typeof require<"u"&&(crypto = window.crypto || globalThis.crypto,c&&c.randomBytes&&r.setPRNG(function(u,d){var m,b=c.randomBytes(d);for(m=0;m<d;m++)u[m]=b[m];wi(b)}))}()}(typeof module<"u"&&module.exports?module.exports:globalThis.nacl=globalThis.nacl||{});const Yt=typeof module<"u"&&module.exports?module.exports:globalThis.nacl,Tn={fromSeed:Yt.sign.keyPair.fromSeed,sign:Yt.sign.detached,verify:Yt.sign.detached.verify,randomBytes:Yt.randomBytes};let Fr;function Mn(r){Fr=r}function Ye(){return Fr}const Un=new Uint16Array([0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920]);class Xt{static checksum(e){let t=0;for(let s=0;s<e.byteLength;s++){let i=e[s];t=t<<8&65535^Un[(t>>8^i)&255]}return t}static validate(e,t){return Xt.checksum(e)==t}}const Ls="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";class Br{static encode(e){let t=0,s=0,i=new Uint8Array(e),n=new Uint8Array(e.byteLength*2),o=0;for(let a=0;a<i.byteLength;a++)for(s=s<<8|i[a],t+=8;t>=5;){let f=s>>>t-5&31;n[o++]=Ls.charAt(f).charCodeAt(0),t-=5}if(t>0){let a=s<<5-t&31;n[o++]=Ls.charAt(a).charCodeAt(0)}return n.slice(0,o)}static decode(e){let t=0,s=0,i=0,n=new Uint8Array(e),o=new Uint8Array(n.byteLength*5/8|0);for(let a=0;a<n.byteLength;a++){let f=String.fromCharCode(n[a]),p=Ls.indexOf(f);if(p===-1)throw new Error("Illegal Base32 character: "+n[a]);s=s<<5|p,t+=5,t>=8&&(o[i++]=s>>>t-8&255,t-=8)}return o.slice(0,i)}}class z extends Error{constructor(t,s){super(t);h(this,"name");h(this,"code");h(this,"chainedError");this.name="NKeysError",this.code=t,this.chainedError=s}}function $n(){return Zt(G.Operator)}function Ln(){return Zt(G.Account)}function qn(){return Zt(G.User)}var K;(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"})(K||(K={}));var G;(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"})(G||(G={}));class ut{static isValidPublicPrefix(e){return e==G.Server||e==G.Operator||e==G.Cluster||e==G.Account||e==G.User}static startsWithValidPrefix(e){let t=e[0];return t=="S"||t=="P"||t=="O"||t=="N"||t=="C"||t=="A"||t=="U"}static isValidPrefix(e){return this.parsePrefix(e)!=-1}static parsePrefix(e){switch(e){case G.Seed:return G.Seed;case G.Private:return G.Private;case G.Operator:return G.Operator;case G.Server:return G.Server;case G.Cluster:return G.Cluster;case G.Account:return G.Account;case G.User:return G.User;default:return-1}}}class ge{static encode(e,t){if(!t||!(t instanceof Uint8Array))throw new z(K.SerializationError);if(!ut.isValidPrefix(e))throw new z(K.InvalidPrefixByte);return ge._encode(!1,e,t)}static encodeSeed(e,t){if(!t)throw new z(K.ApiError);if(!ut.isValidPublicPrefix(e))throw new z(K.InvalidPrefixByte);if(t.byteLength!==32)throw new z(K.InvalidSeedLen);return ge._encode(!0,e,t)}static decode(e,t){if(!ut.isValidPrefix(e))throw new z(K.InvalidPrefixByte);const s=ge._decode(t);if(s[0]!==e)throw new z(K.InvalidPrefixByte);return s.slice(1)}static decodeSeed(e){const t=ge._decode(e),s=ge._decodePrefix(t);if(s[0]!=G.Seed)throw new z(K.InvalidSeed);if(!ut.isValidPublicPrefix(s[1]))throw new z(K.InvalidPrefixByte);return{buf:t.slice(2),prefix:s[1]}}static _encode(e,t,s){const i=e?2:1,n=s.byteLength,o=i+n+2,a=i+n,f=new Uint8Array(o);if(e){const y=ge._encodePrefix(G.Seed,t);f.set(y)}else f[0]=t;f.set(s,i);const p=Xt.checksum(f.slice(0,a));return new DataView(f.buffer).setUint16(a,p,!0),Br.encode(f)}static _decode(e){if(e.byteLength<4)throw new z(K.InvalidEncoding);let t;try{t=Br.decode(e)}catch(a){throw new z(K.InvalidEncoding,a)}const s=t.byteLength-2,n=new DataView(t.buffer).getUint16(s,!0),o=t.slice(0,s);if(!Xt.validate(o,n))throw new z(K.InvalidChecksum);return o}static _encodePrefix(e,t){const s=e|t>>5,i=(t&31)<<3;return new Uint8Array([s,i])}static _decodePrefix(e){const t=e[0]&248,s=(e[0]&7)<<5|(e[1]&248)>>3;return new Uint8Array([t,s])}}class Dr{constructor(e){h(this,"seed");this.seed=e}getRawSeed(){if(!this.seed)throw new z(K.ClearedPair);return ge.decodeSeed(this.seed).buf}getSeed(){if(!this.seed)throw new z(K.ClearedPair);return this.seed}getPublicKey(){if(!this.seed)throw new z(K.ClearedPair);const e=ge.decodeSeed(this.seed),t=Ye().fromSeed(this.getRawSeed()),s=ge.encode(e.prefix,t.publicKey);return new TextDecoder().decode(s)}getPrivateKey(){if(!this.seed)throw new z(K.ClearedPair);const e=Ye().fromSeed(this.getRawSeed());return ge.encode(G.Private,e.secretKey)}sign(e){if(!this.seed)throw new z(K.ClearedPair);const t=Ye().fromSeed(this.getRawSeed());return Ye().sign(e,t.secretKey)}verify(e,t){if(!this.seed)throw new z(K.ClearedPair);const s=Ye().fromSeed(this.getRawSeed());return Ye().verify(e,t,s.publicKey)}clear(){this.seed&&(this.seed.fill(0),this.seed=void 0)}}function Zt(r){const e=Ye().randomBytes(32);let t=ge.encodeSeed(r,new Uint8Array(e));return new Dr(t)}class Fn{constructor(e){h(this,"publicKey");this.publicKey=e}getPublicKey(){if(!this.publicKey)throw new z(K.ClearedPair);return new TextDecoder().decode(this.publicKey)}getPrivateKey(){throw this.publicKey?new z(K.PublicKeyOnly):new z(K.ClearedPair)}getSeed(){throw this.publicKey?new z(K.PublicKeyOnly):new z(K.ClearedPair)}sign(e){throw this.publicKey?new z(K.CannotSign):new z(K.ClearedPair)}verify(e,t){if(!this.publicKey)throw new z(K.ClearedPair);let s=ge._decode(this.publicKey);return Ye().verify(e,t,s.slice(1))}clear(){this.publicKey&&(this.publicKey.fill(0),this.publicKey=void 0)}}function Bn(r){const e=new TextEncoder().encode(r),t=ge._decode(e),s=ut.parsePrefix(t[0]);if(ut.isValidPublicPrefix(s))return new Fn(e);throw new z(K.InvalidPublicKey)}function Dn(r){return ge.decodeSeed(r),new Dr(r)}function Hn(r){return btoa(String.fromCharCode(...r))}function Jn(r){const e=atob(r),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}Mn(Tn);const Hr={createAccount:Ln,createOperator:$n,createPair:Zt,createUser:qn,fromPublic:Bn,fromSeed:Dn,NKeysError:z,NKeysErrorCode:K,Prefix:G,decode:Jn,encode:Hn};function Kn(r){return e=>{let t={};return r.forEach(s=>{const i=s(e)||{};t=Object.assign(t,i)}),t}}function zn(){return()=>{}}function Gn(r,e){return()=>{const t=typeof r=="function"?r():r,s=typeof e=="function"?e():e;return{user:t,pass:s}}}function Vn(r){return()=>({auth_token:typeof r=="function"?r():r})}function Wn(r){return e=>{const t=typeof r=="function"?r():r,s=t?Hr.fromSeed(t):void 0,i=s?s.getPublicKey():"",n=He.encode(e||""),o=s!==void 0&&e?s.sign(n):void 0,a=o?Hr.encode(o):"";return{nkey:i,sig:a}}}function Yn(r,e){return t=>{const s=typeof r=="function"?r():r,i=Wn(e),{nkey:n,sig:o}=i(t);return{jwt:s,nkey:n,sig:o}}}const Jr=2*60*1e3,Xn=2,Kr=2*1e3;function Zn(){return{maxPingOut:2,maxReconnectAttempts:10,noRandomize:!1,pedantic:!1,pingInterval:Jr,reconnect:!0,reconnectJitter:100,reconnectJitterTLS:1e3,reconnectTimeWait:Kr,tls:void 0,verbose:!1,waitOnFirstConnect:!1,ignoreAuthErrorAbort:!1}}function Qn(r){const e=[];return typeof r.authenticator=="function"&&e.push(r.authenticator),Array.isArray(r.authenticator)&&e.push(...r.authenticator),r.token&&e.push(Vn(r.token)),r.user&&e.push(Gn(r.user,r.pass)),e.length===0?zn():Kn(e)}function eo(r){const e=`${_s}:${Tr()}`;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 N("port and servers options are mutually exclusive",k.InvalidOption);r.servers.length===0&&r.port&&(r.servers=[`${_s}:${r.port}`]),r.servers&&r.servers.length===0&&(r.servers=[e]);const t=Bt(Zn(),r);if(t.authenticator=Qn(t),["reconnectDelayHandler","authenticator"].forEach(s=>{if(t[s]&&typeof t[s]!="function")throw new N(`${s} option should be a function`,k.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{Fe(t.inboxPrefix)}catch(s){throw new N(s.message,k.ApiError)}if(t.resolve===void 0&&(t.resolve=typeof Ns()=="function"),t.resolve&&typeof Ns()!="function")throw new N("'resolve' is not supported on this client",k.InvalidOption);return t}function to(r,e){const{proto:t,tls_required:s,tls_available:i}=r;if((t===void 0||t<1)&&e.noEcho)throw new N("noEcho",k.ServerOptionNotAvailable);const n=s||i||!1;if(e.tls&&!n)throw new N("tls",k.ServerOptionNotAvailable)}const so=1024*32,ro=/^INFO\s+([^\r\n]+)\r\n/i,io=yt(`PONG\r
14
14
  `),zr=yt(`PING\r
15
- `);class no{constructor(e,t,s){h(this,"echo");h(this,"no_responders");h(this,"protocol");h(this,"verbose");h(this,"pedantic");h(this,"jwt");h(this,"nkey");h(this,"sig");h(this,"user");h(this,"pass");h(this,"auth_token");h(this,"tls_required");h(this,"name");h(this,"lang");h(this,"version");h(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 i=(t&&typeof t.authenticator=="function"?t.authenticator(s):{})||{};Bt(this,i)}}class Gr extends oe{constructor(t,s,i={}){var o;super();h(this,"sid");h(this,"queue");h(this,"draining");h(this,"max");h(this,"subject");h(this,"drained");h(this,"protocol");h(this,"timer");h(this,"info");h(this,"cleanupFn");h(this,"closed");h(this,"requestSubject");Bt(this,i),this.protocol=t,this.subject=s,this.draining=!1,this.noIterator=typeof i.callback=="function",this.closed=V();const n=!((o=t.options)!=null&&o.noAsyncTraces);i.timeout&&(this.timer=st(i.timeout,n),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,i=t.ingestionFilterFn?t.ingestionFilterFn:()=>({ingest:!0,protocol:!1}),n=t.protocolFilterFn?t.protocolFilterFn:()=>!0,o=t.dispatchedFn?t.dispatchedFn:()=>{};this.callback=(a,f)=>{const{ingest:p}=i(f);p&&n(f)&&(s(a,f),o(f))}}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(N.errorForCode(k.ConnectionClosed)):this.isClosed()?Promise.reject(N.errorForCode(k.SubClosed)):(this.drained||(this.draining=!0,this.protocol.unsub(this),this.drained=this.protocol.flush(V()).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 oo{constructor(){h(this,"mux");h(this,"subs");h(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 i;if(t.operation==="subscription"&&(i=s.find(n=>n.subject===t.subject&&n.queue===t.queue)),t.operation==="publish"&&(i=s.find(n=>n.requestSubject===t.subject)),i)return i.callback(e,{}),i.close(),this.subs.delete(i.sid),i!==this.mux}return!1}close(){this.subs.forEach(e=>{e.close()})}}class Qt{constructor(e,t){h(this,"connected");h(this,"connectedOnce");h(this,"infoReceived");h(this,"info");h(this,"muxSubscriptions");h(this,"options");h(this,"outbound");h(this,"pongs");h(this,"subscriptions");h(this,"transport");h(this,"noMorePublishing");h(this,"connectError");h(this,"publisher");h(this,"_closed");h(this,"closed");h(this,"listeners");h(this,"heartbeats");h(this,"parser");h(this,"outMsgs");h(this,"inMsgs");h(this,"outBytes");h(this,"inBytes");h(this,"pendingLimit");h(this,"lastError");h(this,"abortReconnect");h(this,"whyClosed");h(this,"servers");h(this,"server");h(this,"features");h(this,"connectPromise");this._closed=!1,this.connected=!1,this.connectedOnce=!1,this.infoReceived=!1,this.noMorePublishing=!1,this.abortReconnect=!1,this.listeners=[],this.pendingLimit=so,this.outMsgs=0,this.inMsgs=0,this.outBytes=0,this.inBytes=0,this.options=e,this.publisher=t,this.subscriptions=new oo,this.muxSubscriptions=new Cn,this.outbound=new ht,this.pongs=[],this.whyClosed="",this.pendingLimit=e.pendingLimit||this.pendingLimit,this.features=new hn({major:0,minor:0,micro:0}),this.connectPromise=null;const s=typeof e.servers=="string"?[e.servers]:e.servers;this.servers=new On(s,{randomize:!e.noRandomize}),this.closed=V(),this.parser=new qr(this),this.heartbeats=new In(this,this.options.pingInterval||Jr,this.options.maxPingOut||Xn)}resetOutbound(){this.outbound.reset();const e=this.pongs;this.pongs=[];const t=N.errorForCode(k.Disconnect);t.stack="",e.forEach(s=>{s.reject(t)}),this.parser=new qr(this),this.infoReceived=!1}dispatchStatus(e){this.listeners.forEach(t=>{t.push(e)})}status(){const e=new oe;return this.listeners.push(e),e}prepare(){this.transport&&this.transport.discard(),this.info=void 0,this.resetOutbound();const e=V();return e.catch(()=>{}),this.pongs.unshift(e),this.connectError=t=>{e.reject(t)},this.transport=fn(),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:Ke.StaleConnection,data:""}),this.transport.disconnect()}reconnect(){return this.connected&&(this.dispatchStatus({type:Ke.ClientInitiatedReconnect,data:""}),this.transport.disconnect()),Promise.resolve()}async disconnected(e){this.dispatchStatus({type:Pe.Disconnect,data:this.servers.getCurrentServer().toString()}),this.options.reconnect?await this.dialLoop().then(()=>{var t;this.dispatchStatus({type:Pe.Reconnect,data:this.servers.getCurrentServer().toString()}),((t=this.lastError)==null?void 0:t.code)===k.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=st(this.options.timeout||2e4);const i=this.transport.connect(e,this.options);await Promise.race([i,s]),(async()=>{try{for await(const n of this.transport)this.parser.parse(n)}catch(n){console.log("reader closed",n)}})().then()}catch(i){t.reject(i)}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(i){throw s&&s.cancel(),await this.transport.close(i),i}}async _doDial(e){const{resolve:t}=this.options,s=await e.resolve({fn:Ns(),debug:this.options.debug,randomize:!this.options.noRandomize,resolve:t});let i=null;for(const n of s)try{i=null,this.dispatchStatus({type:Ke.Reconnecting,data:n.toString()}),await this.dial(n);return}catch(o){i=o}throw i}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():Kr;let s=t;const i=this.selectServer();if(!i||this.abortReconnect)throw e||(this.lastError?this.lastError:N.errorForCode(k.ConnectionRefused));const n=Date.now();if(i.lastConnect===0||i.lastConnect+t<=n){i.lastConnect=Date.now();try{await this._doDial(i);break}catch(o){if(e=o,!this.connectedOnce){if(this.options.waitOnFirstConnect)continue;this.servers.removeCurrentServer()}i.reconnects++;const a=this.options.maxReconnectAttempts||0;a!==-1&&i.reconnects>=a&&this.servers.removeCurrentServer()}}else s=Math.min(s,i.lastConnect+t-n),await rt(s)}}static async connect(e,t){const s=new Qt(e,t);return await s.dialLoop(),s}static toError(e){const t=e?e.toLowerCase():"";if(t.indexOf("permissions violation")!==-1){const s=new N(e,k.PermissionsViolation),i=e.match(/(Publish|Subscription) to "(\S+)"/);if(i){s.permissionContext={operation:i[1].toLowerCase(),subject:i[2],queue:void 0};const n=e.match(/using queue "(\S+)"/);n&&(s.permissionContext.queue=n[1])}return s}else return t.indexOf("authorization violation")!==-1?new N(e,k.AuthorizationViolation):t.indexOf("user authentication expired")!==-1?new N(e,k.AuthenticationExpired):t.indexOf("account authentication expired")!=-1?new N(e,k.AccountExpired):t.indexOf("authentication timeout")!==-1?new N(e,k.AuthenticationTimeout):new N(e,k.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 vs(e,t,this)),s.max!==void 0&&s.received>=s.max&&s.unsubscribe())}processError(e){const t=mr(e),s=Qt.toError(t),i={type:Pe.Error,data:s.code};if(s.isPermissionError()){let n=!1;if(s.permissionContext){i.permissionContext=s.permissionContext;const o=this.subscriptions.getMux();n=(o==null?void 0:o.subject)===s.permissionContext.subject}this.subscriptions.handleError(s),this.muxSubscriptions.handleError(n,s),n&&this.subscriptions.setMux(null)}this.dispatchStatus(i),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(io)}processPong(){const e=this.pongs.shift();e&&e.resolve()}processInfo(e){const t=JSON.parse(mr(e));this.info=t;const s=this.options&&this.options.ignoreClusterUpdates?void 0:this.servers.update(t,this.transport.isEncrypted());if(!this.infoReceived){this.features.update(Qe(t.version)),this.infoReceived=!0,this.transport.isEncrypted()&&this.servers.updateTLSName();const{version:n,lang:o}=this.transport;try{const a=new no({version:n,lang:o},this.options,t.nonce);t.headers&&(a.headers=!0,a.no_responders=!0);const f=JSON.stringify(a);this.transport.send(yt(`CONNECT ${f}${Gt}`)),this.transport.send(zr)}catch(a){this._close(a)}}s&&this.dispatchStatus({type:Pe.Update,data:s}),(t.ldm!==void 0?t.ldm:!1)&&this.dispatchStatus({type:Pe.LDM,data:this.servers.getCurrentServer().toString()})}push(e){switch(e.kind){case be.MSG:{const{msg:t,data:s}=e;this.processMsg(t,s);break}case be.OK:break;case be.ERR:this.processError(e.data);break;case be.PING:this.processPing();break;case be.PONG:this.processPong();break;case be.INFO:this.processInfo(e.data);break}}sendCommand(e,...t){const s=this.outbound.length();let i;typeof e=="string"?i=yt(e):i=e,this.outbound.fill(i,...t),s===0?queueMicrotask(()=>{this.flushPending()}):this.outbound.size()>=this.pendingLimit&&this.flushPending()}publish(e,t=we,s){let i;if(t instanceof Uint8Array)i=t;else if(typeof t=="string")i=He.encode(t);else throw N.errorForCode(k.BadPayload);let n=i.length;s=s||{},s.reply=s.reply||"";let o=we,a=0;if(s.headers){if(this.info&&!this.info.headers)throw new N("headers",k.ServerOptionNotAvailable);o=s.headers.encode(),a=o.length,n=i.length+a}if(this.info&&n>this.info.max_payload)throw N.errorForCode(k.MaxPayloadExceeded);this.outBytes+=n,this.outMsgs++;let f;s.headers?(s.reply?f=`HPUB ${e} ${s.reply} ${a} ${n}\r
15
+ `);class no{constructor(e,t,s){h(this,"echo");h(this,"no_responders");h(this,"protocol");h(this,"verbose");h(this,"pedantic");h(this,"jwt");h(this,"nkey");h(this,"sig");h(this,"user");h(this,"pass");h(this,"auth_token");h(this,"tls_required");h(this,"name");h(this,"lang");h(this,"version");h(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 i=(t&&typeof t.authenticator=="function"?t.authenticator(s):{})||{};Bt(this,i)}}class Gr extends oe{constructor(t,s,i={}){var o;super();h(this,"sid");h(this,"queue");h(this,"draining");h(this,"max");h(this,"subject");h(this,"drained");h(this,"protocol");h(this,"timer");h(this,"info");h(this,"cleanupFn");h(this,"closed");h(this,"requestSubject");Bt(this,i),this.protocol=t,this.subject=s,this.draining=!1,this.noIterator=typeof i.callback=="function",this.closed=V();const n=!((o=t.options)!=null&&o.noAsyncTraces);i.timeout&&(this.timer=tt(i.timeout,n),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,i=t.ingestionFilterFn?t.ingestionFilterFn:()=>({ingest:!0,protocol:!1}),n=t.protocolFilterFn?t.protocolFilterFn:()=>!0,o=t.dispatchedFn?t.dispatchedFn:()=>{};this.callback=(a,f)=>{const{ingest:p}=i(f);p&&n(f)&&(s(a,f),o(f))}}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(N.errorForCode(k.ConnectionClosed)):this.isClosed()?Promise.reject(N.errorForCode(k.SubClosed)):(this.drained||(this.draining=!0,this.protocol.unsub(this),this.drained=this.protocol.flush(V()).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 oo{constructor(){h(this,"mux");h(this,"subs");h(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 i;if(t.operation==="subscription"&&(i=s.find(n=>n.subject===t.subject&&n.queue===t.queue)),t.operation==="publish"&&(i=s.find(n=>n.requestSubject===t.subject)),i)return i.callback(e,{}),i.close(),this.subs.delete(i.sid),i!==this.mux}return!1}close(){this.subs.forEach(e=>{e.close()})}}class Qt{constructor(e,t){h(this,"connected");h(this,"connectedOnce");h(this,"infoReceived");h(this,"info");h(this,"muxSubscriptions");h(this,"options");h(this,"outbound");h(this,"pongs");h(this,"subscriptions");h(this,"transport");h(this,"noMorePublishing");h(this,"connectError");h(this,"publisher");h(this,"_closed");h(this,"closed");h(this,"listeners");h(this,"heartbeats");h(this,"parser");h(this,"outMsgs");h(this,"inMsgs");h(this,"outBytes");h(this,"inBytes");h(this,"pendingLimit");h(this,"lastError");h(this,"abortReconnect");h(this,"whyClosed");h(this,"servers");h(this,"server");h(this,"features");h(this,"connectPromise");this._closed=!1,this.connected=!1,this.connectedOnce=!1,this.infoReceived=!1,this.noMorePublishing=!1,this.abortReconnect=!1,this.listeners=[],this.pendingLimit=so,this.outMsgs=0,this.inMsgs=0,this.outBytes=0,this.inBytes=0,this.options=e,this.publisher=t,this.subscriptions=new oo,this.muxSubscriptions=new Cn,this.outbound=new ct,this.pongs=[],this.whyClosed="",this.pendingLimit=e.pendingLimit||this.pendingLimit,this.features=new hn({major:0,minor:0,micro:0}),this.connectPromise=null;const s=typeof e.servers=="string"?[e.servers]:e.servers;this.servers=new On(s,{randomize:!e.noRandomize}),this.closed=V(),this.parser=new qr(this),this.heartbeats=new In(this,this.options.pingInterval||Jr,this.options.maxPingOut||Xn)}resetOutbound(){this.outbound.reset();const e=this.pongs;this.pongs=[];const t=N.errorForCode(k.Disconnect);t.stack="",e.forEach(s=>{s.reject(t)}),this.parser=new qr(this),this.infoReceived=!1}dispatchStatus(e){this.listeners.forEach(t=>{t.push(e)})}status(){const e=new oe;return this.listeners.push(e),e}prepare(){this.transport&&this.transport.discard(),this.info=void 0,this.resetOutbound();const e=V();return e.catch(()=>{}),this.pongs.unshift(e),this.connectError=t=>{e.reject(t)},this.transport=fn(),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:Ke.StaleConnection,data:""}),this.transport.disconnect()}reconnect(){return this.connected&&(this.dispatchStatus({type:Ke.ClientInitiatedReconnect,data:""}),this.transport.disconnect()),Promise.resolve()}async disconnected(e){this.dispatchStatus({type:Pe.Disconnect,data:this.servers.getCurrentServer().toString()}),this.options.reconnect?await this.dialLoop().then(()=>{var t;this.dispatchStatus({type:Pe.Reconnect,data:this.servers.getCurrentServer().toString()}),((t=this.lastError)==null?void 0:t.code)===k.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=tt(this.options.timeout||2e4);const i=this.transport.connect(e,this.options);await Promise.race([i,s]),(async()=>{try{for await(const n of this.transport)this.parser.parse(n)}catch(n){console.log("reader closed",n)}})().then()}catch(i){t.reject(i)}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(i){throw s&&s.cancel(),await this.transport.close(i),i}}async _doDial(e){const{resolve:t}=this.options,s=await e.resolve({fn:Ns(),debug:this.options.debug,randomize:!this.options.noRandomize,resolve:t});let i=null;for(const n of s)try{i=null,this.dispatchStatus({type:Ke.Reconnecting,data:n.toString()}),await this.dial(n);return}catch(o){i=o}throw i}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():Kr;let s=t;const i=this.selectServer();if(!i||this.abortReconnect)throw e||(this.lastError?this.lastError:N.errorForCode(k.ConnectionRefused));const n=Date.now();if(i.lastConnect===0||i.lastConnect+t<=n){i.lastConnect=Date.now();try{await this._doDial(i);break}catch(o){if(e=o,!this.connectedOnce){if(this.options.waitOnFirstConnect)continue;this.servers.removeCurrentServer()}i.reconnects++;const a=this.options.maxReconnectAttempts||0;a!==-1&&i.reconnects>=a&&this.servers.removeCurrentServer()}}else s=Math.min(s,i.lastConnect+t-n),await st(s)}}static async connect(e,t){const s=new Qt(e,t);return await s.dialLoop(),s}static toError(e){const t=e?e.toLowerCase():"";if(t.indexOf("permissions violation")!==-1){const s=new N(e,k.PermissionsViolation),i=e.match(/(Publish|Subscription) to "(\S+)"/);if(i){s.permissionContext={operation:i[1].toLowerCase(),subject:i[2],queue:void 0};const n=e.match(/using queue "(\S+)"/);n&&(s.permissionContext.queue=n[1])}return s}else return t.indexOf("authorization violation")!==-1?new N(e,k.AuthorizationViolation):t.indexOf("user authentication expired")!==-1?new N(e,k.AuthenticationExpired):t.indexOf("account authentication expired")!=-1?new N(e,k.AccountExpired):t.indexOf("authentication timeout")!==-1?new N(e,k.AuthenticationTimeout):new N(e,k.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 vs(e,t,this)),s.max!==void 0&&s.received>=s.max&&s.unsubscribe())}processError(e){const t=mr(e),s=Qt.toError(t),i={type:Pe.Error,data:s.code};if(s.isPermissionError()){let n=!1;if(s.permissionContext){i.permissionContext=s.permissionContext;const o=this.subscriptions.getMux();n=(o==null?void 0:o.subject)===s.permissionContext.subject}this.subscriptions.handleError(s),this.muxSubscriptions.handleError(n,s),n&&this.subscriptions.setMux(null)}this.dispatchStatus(i),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(io)}processPong(){const e=this.pongs.shift();e&&e.resolve()}processInfo(e){const t=JSON.parse(mr(e));this.info=t;const s=this.options&&this.options.ignoreClusterUpdates?void 0:this.servers.update(t,this.transport.isEncrypted());if(!this.infoReceived){this.features.update(Ze(t.version)),this.infoReceived=!0,this.transport.isEncrypted()&&this.servers.updateTLSName();const{version:n,lang:o}=this.transport;try{const a=new no({version:n,lang:o},this.options,t.nonce);t.headers&&(a.headers=!0,a.no_responders=!0);const f=JSON.stringify(a);this.transport.send(yt(`CONNECT ${f}${Gt}`)),this.transport.send(zr)}catch(a){this._close(a)}}s&&this.dispatchStatus({type:Pe.Update,data:s}),(t.ldm!==void 0?t.ldm:!1)&&this.dispatchStatus({type:Pe.LDM,data:this.servers.getCurrentServer().toString()})}push(e){switch(e.kind){case be.MSG:{const{msg:t,data:s}=e;this.processMsg(t,s);break}case be.OK:break;case be.ERR:this.processError(e.data);break;case be.PING:this.processPing();break;case be.PONG:this.processPong();break;case be.INFO:this.processInfo(e.data);break}}sendCommand(e,...t){const s=this.outbound.length();let i;typeof e=="string"?i=yt(e):i=e,this.outbound.fill(i,...t),s===0?queueMicrotask(()=>{this.flushPending()}):this.outbound.size()>=this.pendingLimit&&this.flushPending()}publish(e,t=we,s){let i;if(t instanceof Uint8Array)i=t;else if(typeof t=="string")i=He.encode(t);else throw N.errorForCode(k.BadPayload);let n=i.length;s=s||{},s.reply=s.reply||"";let o=we,a=0;if(s.headers){if(this.info&&!this.info.headers)throw new N("headers",k.ServerOptionNotAvailable);o=s.headers.encode(),a=o.length,n=i.length+a}if(this.info&&n>this.info.max_payload)throw N.errorForCode(k.MaxPayloadExceeded);this.outBytes+=n,this.outMsgs++;let f;s.headers?(s.reply?f=`HPUB ${e} ${s.reply} ${a} ${n}\r
16
16
  `:f=`HPUB ${e} ${a} ${n}\r
17
17
  `,this.sendCommand(f,o,i,Vt)):(s.reply?f=`PUB ${e} ${s.reply} ${n}\r
18
18
  `:f=`PUB ${e} ${n}\r
@@ -20,13 +20,13 @@ ${this.ctx.stack}`),this.deferred.reject(t)):this.deferred.resolve(s),this.cance
20
20
  `):this.sendCommand(`SUB ${e.subject} ${e.sid}\r
21
21
  `)}_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
22
22
  `):this.sendCommand(`UNSUB ${e.sid}\r
23
- `),e.max=t)}resub(e,t){!e||this.isClosed()||(this.unsub(e),e.subject=t,this.subscriptions.resub(e),this._sub(e))}flush(e){return e||(e=V()),this.pongs.push(e),this.outbound.fill(zr),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}${Gt}`):e.push(`SUB ${s.subject} ${s.sid}${Gt}`)}),e.length&&this.transport.send(yt(e.join("")))}async _close(e){this._closed||(this.whyClosed=new Error("close trace").stack||"",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 Gr(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}}const ao="$SRV";class Vr{constructor(e){h(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,i){var n,o;return i=i||{},i.headers=i.headers||Be(),(n=i.headers)==null||n.set(qt,`${e}`),(o=i.headers)==null||o.set(Lt,t),this.msg.respond(s,i)}json(e){return this.msg.json(e)}string(){return this.msg.string()}}class kt{constructor(e,t="",s=""){h(this,"subject");h(this,"queue");h(this,"srv");t!==""&&ho("service group",t);let i="";if(e instanceof Ot)this.srv=e,i="";else if(e instanceof kt){const n=e;this.srv=n.srv,s===""&&n.queue!==""&&(s=n.queue),i=n.subject}else throw new Error("unknown ServiceGroup type");this.subject=this.calcSubject(i,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;xt("endpoint",e);let{subject:i,handler:n,metadata:o,queue:a}=s;i=i||e,a=a||this.queue,co("endpoint subject",i),i=this.calcSubject(this.subject,i);const f={name:e,subject:i,queue:a,handler:n,metadata:o};return this.srv._addEndpoint(f)}addGroup(e="",t=""){return new kt(this,e,t)}}function co(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,i)=>{if(s===">"&&i!==t.length-1)throw new Error(`${r} cannot have internal '>': '${e}'`)})}function ho(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 Ot{constructor(e,t={name:"",version:""}){h(this,"nc");h(this,"_id");h(this,"config");h(this,"handlers");h(this,"internal");h(this,"_stopped");h(this,"_done");h(this,"started");this.nc=e,this.config=Object.assign({},t),this.config.queue||(this.config.queue="q"),xt("name",this.config.name),xt("queue",this.config.queue),Qe(this.config.version),this._id=Je.next(),this.internal=[],this._done=V(),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="",i){const n=i??ao;return t===""&&s===""?`${n}.${e}`:(xt("control subject name",t),s!==""?(xt("control subject id",s),`${n}.${e}.${t}.${s}`):`${n}.${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=Be();if(e instanceof Ft){const s=e;t.set(Lt,s.message),t.set(qt,`${s.code}`)}else t.set(Lt,e.message),t.set(qt,"500");return t}setupHandler(e,t=!1){const s=t?"":e.queue?e.queue:this.config.queue,{name:i,subject:n,handler:o}=e,a=e;a.internal=t,t&&this.internal.push(a),a.stats=new uo(i,n,s),a.queue=s;const f=o?(p,g)=>{if(p){this.close(p);return}const y=Date.now();try{o(p,new Vr(g))}catch(x){a.stats.countError(x),g==null||g.respond(we,{headers:this.errorToHeader(x)})}finally{a.stats.countLatency(y)}}:void 0;return a.sub=this.nc.subscribe(n,{callback:f,queue:s}),a.sub.closed.then(()=>{this._stopped||this.close(new Error(`required subscription ${e.subject} stopped`)).catch()}).catch(p=>{if(!this._stopped){const g=new Error(`required subscription ${e.subject} errored: ${p.message}`);g.stack=p.stack,this.close(g).catch()}}),a}info(){return{type:wt.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:i,queue:n}=e;return{subject:t,metadata:s,name:i,queue_group:n}})}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:wt.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,i="",n=""){const o={};o.name=e,o.subject=Ot.controlSubject(t,i,n),o.handler=s,this.setupHandler(o,!0)}start(){const e=ke(),t=(o,a)=>o?(this.close(o),Promise.reject(o)):this.stats().then(f=>(a==null||a.respond(e.encode(f)),Promise.resolve())),s=(o,a)=>o?(this.close(o),Promise.reject(o)):(a==null||a.respond(e.encode(this.info())),Promise.resolve()),i=e.encode(this.ping()),n=(o,a)=>o?(this.close(o).then().catch(),Promise.reject(o)):(a.respond(i),Promise.resolve());return this.addInternalHandler(ze.PING,n),this.addInternalHandler(ze.STATS,t),this.addInternalHandler(ze.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:wt.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 kt(this,e,t)}addEndpoint(e,t){return new kt(this).addEndpoint(e,t)}_addEndpoint(e){const t=new oe;t.noIterator=typeof e.handler=="function",t.noIterator||(e.handler=(i,n)=>{i?this.stop(i).catch():t.push(new Vr(n))},t.iterClosed.then(()=>{this.close().catch()}));const s=this.setupHandler(e,!1);return s.qi=t,this.handlers.push(s),t}}class uo{constructor(e,t,s=""){h(this,"name");h(this,"subject");h(this,"average_processing_time");h(this,"num_requests");h(this,"processing_time");h(this,"num_errors");h(this,"last_error");h(this,"data");h(this,"metadata");h(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+=W(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:i,num_requests:n,processing_time:o,last_error:a,data:f,queue:p}=this;return{name:e,subject:t,average_processing_time:s,num_errors:i,num_requests:n,processing_time:o,last_error:a,data:f,queue_group:p}}stats(e){const t=e;return(t==null?void 0:t.noIterator)===!1&&(this.processing_time=W(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 lo{constructor(e,t={strategy:je.JitterTimer,maxWait:2e3},s){h(this,"nc");h(this,"prefix");h(this,"opts");this.nc=e,this.prefix=s,this.opts=t}ping(e="",t=""){return this.q(ze.PING,e,t)}stats(e="",t=""){return this.q(ze.STATS,e,t)}info(e="",t=""){return this.q(ze.INFO,e,t)}async q(e,t="",s=""){const i=new oe,n=ke(),o=Ot.controlSubject(e,t,s,this.prefix),a=await this.nc.requestMany(o,we,this.opts);return(async()=>{for await(const f of a)try{const p=n.decode(f.data);i.push(p)}catch(p){i.push(()=>{i.stop(p)})}i.push(()=>{i.stop()})})().catch(f=>{i.stop(f)}),i}}function Wr(){return{key:{encode(r){return r},decode(r){return r}},value:{encode(r){return r},decode(r){return r}}}}function fo(){return{replicas:1,history:1,timeout:2e3,max_bytes:-1,maxValueSize:-1,codec:Wr(),storage:Os.File}}const es="KV-Operation",Yr="$KV",po=/^[-/=.\w]+$/,mo=/^[-/=.>*\w]+$/,bo=/^[-\w]+$/;function go(r){if(r.startsWith(".")||r.endsWith(".")||!po.test(r))throw new Error(`invalid key: ${r}`)}function _o(r){if(r.startsWith(".")||r.endsWith(".")||!mo.test(r))throw new Error(`invalid key: ${r}`)}function yo(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 ts(r){if(!bo.test(r))throw new Error(`invalid bucket name: ${r}`)}var Ue;(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"})(Ue||(Ue={}));class Ct{constructor(e,t,s){h(this,"js");h(this,"jsm");h(this,"stream");h(this,"bucket");h(this,"direct");h(this,"codec");h(this,"prefix");h(this,"editPrefix");h(this,"useJsPrefix");h(this,"_prefixLen");h(this,"validateKey",go);h(this,"validateSearchKey",_o);h(this,"hasWildcards",yo);ts(e),this.js=t,this.jsm=s,this.bucket=e,this.prefix=Yr,this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create(e,t,s={}){ts(t);const i=await e.jetstreamManager(),n=new Ct(t,e,i);return await n.init(s),n}static async bind(e,t,s={}){const i=await e.jetstreamManager(),n={config:{allow_direct:s.allow_direct}};ts(t);const o=new Ct(t,e,i);return n.config.name=s.streamName??o.bucketName(),Object.assign(o,n),o.stream=n.config.name,o.codec=s.codec||Wr(),o.direct=n.config.allow_direct??!1,o.initializePrefixes(n),o}async init(e={}){const t=Object.assign(fo(),e);this.codec=t.codec;const s={};this.stream=s.name=e.streamName??this.bucketName(),s.retention=ks.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 i=e.placementCluster??"";if(i&&(e.placement={},e.placement.cluster=i,e.placement.tags=[]),e.placement&&(s.placement=e.placement),e.republish&&(s.republish=e.republish),e.description&&(s.description=e.description),e.mirror){const y=Object.assign({},e.mirror);y.name.startsWith(ve)||(y.name=`${ve}${y.name}`),s.mirror=y,s.mirror_direct=!0}else if(e.sources){const y=e.sources.map(x=>{const A=Object.assign({},x),I=A.name.startsWith(ve)?A.name.substring(ve.length):A.name;return A.name.startsWith(ve)||(A.name=`${ve}${A.name}`),!x.external&&I!==this.bucket&&(A.subject_transforms=[{src:`$KV.${I}.>`,dest:`$KV.${this.bucket}.>`}]),A});s.sources=y,s.subjects=[this.subjectForBucket()]}else s.subjects=[this.subjectForBucket()];e.metadata&&(s.metadata=e.metadata),typeof e.compression=="boolean"&&(s.compression=e.compression?Ve.S2:Ve.None);const n=this.js.nc,o=n.getServerVersion(),a=o?js(o,Qe("2.7.2"))>=0:!1;s.discard=a?St.New:St.Old;const{ok:f,min:p}=n.features.get(H.JS_ALLOW_DIRECT);if(!f&&e.allow_direct===!0){const y=o?`${o.major}.${o.minor}.${o.micro}`:"unknown";return Promise.reject(new Error(`allow_direct is not available on server version ${y} - requires ${p}`))}e.allow_direct=typeof e.allow_direct=="boolean"?e.allow_direct:f,s.allow_direct=e.allow_direct,this.direct=s.allow_direct,s.num_replicas=t.replicas,t.ttl&&(s.max_age=W(t.ttl)),s.allow_rollup_hdrs=!0;let g;try{g=await this.jsm.streams.info(s.name),!g.config.allow_direct&&this.direct===!0&&(this.direct=!1)}catch(y){if(y.message==="stream not found")g=await this.jsm.streams.add(s);else throw y}this.initializePrefixes(g)}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(ve)&&(s=s.substring(ve.length)),t.external&&t.external.api!==""){const i=t.name.substring(ve.length);this.useJsPrefix=!1,this.prefix=`$KV.${i}`,this.editPrefix=`${t.external.api}.$KV.${s}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${ve}${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}`:`${Yr}.${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(me.MessageSizeHdr)||"";return s!==""?parseInt(s,10):e.length}smToEntry(e){return new To(this.bucket,this.prefixLen,e)}jmToEntry(e){const t=this.decodeKey(e.subject.substring(this.prefixLen));return new Mo(this.bucket,t,e)}async create(e,t){var n;let s;try{const o=await this.put(e,t,{previousSeq:0});return Promise.resolve(o)}catch(o){if(s=o,((n=o==null?void 0:o.api_error)==null?void 0:n.err_code)!==10071)return Promise.reject(o)}let i=0;try{const o=await this.get(e);return(o==null?void 0:o.operation)==="DEL"||(o==null?void 0:o.operation)==="PURGE"?(i=o!==null?o.revision:0,this.update(e,t,i)):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 i=this.encodeKey(e);this.validateKey(i);const n={};if(s.previousSeq!==void 0){const f=Be();n.headers=f,f.set(Ue.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`)}try{return(await this.js.publish(this.subjectForKey(i,!0),t,n)).seq}catch(f){const p=f;return p.isJetStreamError()?(p.message=(o=p.api_error)==null?void 0:o.description,p.code=`${(a=p.api_error)==null?void 0:a.code}`,Promise.reject(p)):Promise.reject(f)}}async get(e,t){const s=this.encodeKey(e);this.validateKey(s);let i={last_by_subj:this.subjectForKey(s)};t&&t.revision>0&&(i={seq:t.revision});let n;try{this.direct?n=await this.jsm.direct.getMessage(this.bucketName(),i):n=await this.jsm.streams.getMessage(this.bucketName(),i);const o=this.smToEntry(n);return o.key!==s?null:o}catch(o){if(o.code===k.JetStream404NoMessages)return null;throw o}}purge(e,t){return this._deleteOrPurge(e,"PURGE",t)}delete(e,t){return this._deleteOrPurge(e,"DEL",t)}async purgeDeletes(e=30*60*1e3){const t=V(),s=[],i=await this.watch({key:">",initializedFn:()=>{t.resolve()}});(async()=>{for await(const f of i)(f.operation==="DEL"||f.operation==="PURGE")&&s.push(f)})().then(),await t,i.stop();const n=Date.now()-e,o=s.map(f=>{const p=this.subjectForKey(f.key);return f.created.getTime()>=n?this.jsm.streams.purge(this.stream,{filter:p,keep:1}):this.jsm.streams.purge(this.stream,{filter:p,keep:0})}),a=await Promise.all(o);return a.unshift({success:!0,purged:0}),a.reduce((f,p)=>(f.purged+=p.purged,f))}async _deleteOrPurge(e,t,s){if(!this.hasWildcards(e))return this._doDeleteOrPurge(e,t,s);const i=await this.keys(e),n=[];for await(const o of i)n.push(this._doDeleteOrPurge(o,t)),n.length===100&&(await Promise.all(n),n.length=0);n.length>0&&await Promise.all(n)}async _doDeleteOrPurge(e,t,s){const i=this.encodeKey(e);this.validateKey(i);const n=Be();n.set(es,t),t==="PURGE"&&n.set(me.RollupHdr,me.RollupValueSubject),s!=null&&s.previousSeq&&n.set(Ue.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`),await this.js.publish(this.subjectForKey(i,!0),we,{headers:n})}_buildCC(e,t,s={}){let n=(Array.isArray(e)?e:[e]).map(f=>{const p=this.encodeKey(f);return this.validateSearchKey(f),this.fullKeyName(p)}),o=te.LastPerSubject;t===Re.AllHistory&&(o=te.All),t===Re.UpdatesOnly&&(o=te.New);let a;return n.length===1&&(a=n[0],n=void 0),Object.assign({deliver_policy:o,ack_policy:ae.None,filter_subjects:n,filter_subject:a,flow_control:!0,idle_heartbeat:W(5*1e3)},s)}remove(e){return this.purge(e)}async history(e={}){const t=e.key??">",s=new oe,i={};i.headers_only=e.headers_only||!1;let n;n=()=>{s.stop()};let o=0;const a=this._buildCC(t,Re.AllHistory,i),f=a.filter_subject,p=We(a);p.bindStream(this.stream),p.orderedConsumer(),p.callback((y,x)=>{if(y){s.stop(y);return}if(x){const A=this.jmToEntry(x);s.push(A),s.received++,(n&&o>0&&s.received>=o||x.info.pending===0)&&(s.push(n),n=void 0)}});const g=await this.js.subscribe(f,p);if(n){const{info:{last:y}}=g,x=y.num_pending+y.delivered.consumer_seq;if(x===0||s.received>=x)try{n()}catch(A){s.stop(A)}finally{n=void 0}else o=x}return s._data=g,s.iterClosed.then(()=>{g.unsubscribe()}),g.closed.then(()=>{s.stop()}).catch(y=>{s.stop(y)}),s}canSetWatcherName(){const t=this.js.nc,{ok:s}=t.features.get(H.JS_NEW_CONSUMER_CREATE_API);return s}async watch(e={}){const t=e.key??">",s=new oe,i={};i.headers_only=e.headers_only||!1;let n=Re.LastValue;e.include===Re.AllHistory?n=Re.AllHistory:e.include===Re.UpdatesOnly&&(n=Re.UpdatesOnly);const o=e.ignoreDeletes===!0;let a=e.initializedFn,f=0;const p=this._buildCC(t,n,i),g=p.filter_subject,y=We(p);this.canSetWatcherName()&&y.consumerName(Je.next()),y.bindStream(this.stream),e.resumeFromRevision&&e.resumeFromRevision>0&&y.startSequence(e.resumeFromRevision),y.orderedConsumer(),y.callback((A,I)=>{if(A){s.stop(A);return}if(I){const T=this.jmToEntry(I);if(o&&T.operation==="DEL")return;s.push(T),s.received++,a&&(f>0&&s.received>=f||I.info.pending===0)&&(s.push(a),a=void 0)}});const x=await this.js.subscribe(g,y);if(a){const{info:{last:A}}=x,I=A.num_pending+A.delivered.consumer_seq;if(I===0||s.received>=I)try{a()}catch(T){s.stop(T)}finally{a=void 0}else f=I}return s._data=x,s.iterClosed.then(()=>{x.unsubscribe()}),x.closed.then(()=>{s.stop()}).catch(A=>{s.stop(A)}),s}async keys(e=">"){const t=new oe,s=this._buildCC(e,Re.LastValue,{headers_only:!0}),i=Array.isArray(e)?">":s.filter_subject,n=We(s);n.bindStream(this.stream),n.orderedConsumer();const o=await this.js.subscribe(i,n);return(async()=>{var f;for await(const p of o){const g=(f=p.headers)==null?void 0:f.get(es);if(g!=="DEL"&&g!=="PURGE"){const y=this.decodeKey(p.subject.substring(this.prefixLen));t.push(y)}p.info.pending===0&&o.unsubscribe()}})().then(()=>{t.stop()}).catch(f=>{t.stop(f)}),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 n;const t=((n=this.js.nc.info)==null?void 0:n.cluster)??"",s=this.bucketName(),i=await this.jsm.streams.info(s);return new Xr(i,t)}}class Xr{constructor(e,t=""){h(this,"si");h(this,"cluster");this.si=e,this.cluster=t}get bucket(){return this.si.config.name.startsWith(ve)?this.si.config.name.substring(ve.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 ws(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!==Ve.None:!1}}const qs="OBJ_",Zr="SHA-256=";function wo(r){return ts(r),`${qs}${r}`}function xo(r){return r.startsWith(qs)?r.substring(4):r}class Fs{constructor(e){h(this,"si");h(this,"backingStore");this.si=e,this.backingStore="JetStream"}get bucket(){return xo(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!==Ve.None:!1}}function ss(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 Ce;(function(r){r[r.Unset=-1]="Unset",r[r.Consume=0]="Consume",r[r.Fetch=1]="Fetch"})(Ce||(Ce={}));var $e;(function(r){r.HeartbeatsMissed="heartbeats_missed",r.ConsumerNotFound="consumer_not_found",r.StreamNotFound="stream_not_found",r.ConsumerDeleted="consumer_deleted",r.OrderedConsumerRecreated="ordered_consumer_recreated",r.NoResponders="no_responders"})($e||($e={}));var ft;(function(r){r.DebugEvent="debug",r.Discard="discard",r.Reset="reset",r.Next="next"})(ft||(ft={}));const Qr=Uint8Array.of(43,65,67,75),So=Uint8Array.of(45,78,65,75),It=Uint8Array.of(43,87,80,73),vo=Uint8Array.of(43,78,88,84),Eo=Uint8Array.of(43,84,69,82,77),Ao=Uint8Array.of(32);function jt(r,e=5e3){return new Do(r,e)}class Bs extends oe{constructor(t,s,i=!1){super();h(this,"consumer");h(this,"opts");h(this,"sub");h(this,"monitor");h(this,"pending");h(this,"inbox");h(this,"refilling");h(this,"pong");h(this,"callback");h(this,"timeout");h(this,"cleanupHandler");h(this,"listeners");h(this,"statusIterator");h(this,"forOrderedConsumer");h(this,"resetHandler");h(this,"abortOnMissingResource");h(this,"bind");h(this,"inBackOff");this.consumer=t;const n=s;this.opts=this.parseOptions(s,i),this.callback=n.callback||null,this.noIterator=typeof this.callback=="function",this.monitor=null,this.pong=null,this.pending={msgs:0,bytes:0,requests:0},this.refilling=i,this.timeout=null,this.inbox=Fe(t.api.nc.options.inboxPrefix),this.listeners=[],this.forOrderedConsumer=!1,this.abortOnMissingResource=n.abort_on_missing_resource===!0,this.bind=n.bind===!0,this.inBackOff=!1,this.start()}start(){const{max_messages:t,max_bytes:s,idle_heartbeat:i,threshold_bytes:n,threshold_messages:o}=this.opts;this.closed().then(f=>{if(this.cleanupHandler)try{this.cleanupHandler(f)}catch{}});const{sub:a}=this;a&&a.unsubscribe(),this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(f,p)=>{var y,x,A,I;if(f){this.stop(f);return}if((y=this.monitor)==null||y.work(),p.subject===this.inbox){if(As(p))return;const T=(x=p.headers)==null?void 0:x.code,J=((I=(A=p.headers)==null?void 0:A.description)==null?void 0:I.toLowerCase())||"unknown",{msgsLeft:se,bytesLeft:L}=this.parseDiscard(p.headers);if(se>0||L>0)this.pending.msgs-=se,this.pending.bytes-=L,this.pending.requests--,this.notify(ft.Discard,{msgsLeft:se,bytesLeft:L});else if(T===400){this.stop(new N(J,`${T}`));return}else if(T===409&&J==="consumer deleted"){if(this.notify($e.ConsumerDeleted,`${T} ${J}`),!this.refilling||this.abortOnMissingResource){const ee=new N(J,`${T}`);this.stop(ee);return}}else if(T===503){if(this.notify($e.NoResponders,`${T} No Responders`),!this.refilling||this.abortOnMissingResource){const ee=new N("no responders",`${T}`);this.stop(ee);return}}else this.notify(ft.DebugEvent,`${T} ${J}`)}else this._push(jt(p,this.consumer.api.timeout)),this.received++,this.pending.msgs&&this.pending.msgs--,this.pending.bytes&&(this.pending.bytes-=p.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<=n){const T=this.pullOptions();this.pull(T)}}else this.pending.requests===0&&this._push(()=>{this.stop()})}}),this.sub.closed.then(()=>{this.sub.draining&&this._push(()=>{this.stop()})}),i&&(this.monitor=new Ps(i,f=>(this.notify($e.HeartbeatsMissed,f),this.resetPending().then(()=>{}).catch(()=>{}),!1),{maxOut:2})),(async()=>{var p;const f=this.consumer.api.nc.status();this.statusIterator=f;for await(const g of f)switch(g.type){case Pe.Disconnect:(p=this.monitor)==null||p.cancel();break;case Pe.Reconnect:this.resetPending().then(y=>{var x;y&&((x=this.monitor)==null||x.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(i){this.stop(i)}}}notify(t,s){this.listeners.length>0&&this.listeners.forEach(i=>{i.done||i.push({type:t,data:s})})}resetPending(){return this.bind?this.resetPendingNoInfo():this.resetPendingWithInfo()}resetPendingNoInfo(){return this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),Promise.resolve(!0)}async resetPendingWithInfo(){if(this.inBackOff)return!1;let t=0,s=0;const i=ys([this.opts.expires]);let n=0;for(;;){if(this.done)return!1;if(this.consumer.api.nc.isClosed())return console.error("aborting resetPending - connection is closed"),!1;try{return await this.consumer.info(),this.inBackOff=!1,t=0,this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),!0}catch(o){if(o.message==="stream not found"){if(s++,this.notify($e.StreamNotFound,s),!this.refilling||this.abortOnMissingResource)return this.stop(o),!1}else if(o.message==="consumer not found"){if(t++,this.notify($e.ConsumerNotFound,t),this.resetHandler)try{this.resetHandler()}catch{}if(!this.refilling||this.abortOnMissingResource)return this.stop(o),!1;if(this.forOrderedConsumer)return!1}else t=0,s=0;this.inBackOff=!0;const a=i.backoff(n),f=rt(a);await Promise.race([f,this.consumer.api.nc.closed()]),f.cancel(),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(ft.Next,t)})}pullOptions(){const t=this.opts.max_messages-this.pending.msgs,s=this.opts.max_bytes-this.pending.bytes,i=W(this.opts.idle_heartbeat),n=W(this.opts.expires);return{batch:t,max_bytes:s,idle_heartbeat:i,expires:n}}parseDiscard(t){const s={msgsLeft:0,bytesLeft:0},i=t==null?void 0:t.get(me.PendingMessagesHdr);i&&(s.msgsLeft=parseInt(i));const n=t==null?void 0:t.get(me.PendingBytesHdr);return n&&(s.bytesLeft=parseInt(n)),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,i;this.done||((s=this.sub)==null||s.unsubscribe(),this.clearTimers(),(i=this.statusIterator)==null||i.stop(),this._push(()=>{super.stop(t),this.listeners.forEach(n=>{n.stop()})}))}parseOptions(t,s=!1){const i=t||{};if(i.max_messages=i.max_messages||0,i.max_bytes=i.max_bytes||0,i.max_messages!==0&&i.max_bytes!==0)throw new Error("only specify one of max_messages or max_bytes");if(i.max_messages===0&&(i.max_messages=100),i.expires=i.expires||3e4,i.expires<1e3)throw new Error("expires should be at least 1000ms");if(i.idle_heartbeat=i.idle_heartbeat||i.expires/2,i.idle_heartbeat=i.idle_heartbeat>3e4?3e4:i.idle_heartbeat,s){const n=Math.round(i.max_messages*.75)||1;i.threshold_messages=i.threshold_messages||n;const o=Math.round(i.max_bytes*.75)||1;i.threshold_bytes=i.threshold_bytes||o}return i}status(){const t=new oe;return this.listeners.push(t),Promise.resolve(t)}}class Po extends oe{constructor(){super();h(this,"src");h(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(s=>{this.stop(s||void 0)}),(async()=>{const s=await this.src.status();for await(const i of s)this.notify(i.type,i.data)})().catch(()=>{})}notify(t,s){this.listeners.length>0&&this.listeners.forEach(i=>{i.done||i.push({type:t,data:s})})}stop(t){var s;this.done||((s=this.src)==null||s.stop(t),super.stop(t),this.listeners.forEach(i=>{i.stop()}))}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}status(){const t=new oe;return this.listeners.push(t),Promise.resolve(t)}}class Ds{constructor(e,t){h(this,"api");h(this,"_info");h(this,"stream");h(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 Bs(this,e,!0))}fetch(e={max_messages:100,expires:3e4}){const t=new Bs(this,e,!1),s=Math.round(t.opts.expires*1.05),i=st(s);return t.closed().catch(()=>{}).finally(()=>{i.cancel()}),i.catch(()=>{t.close().catch()}),t.trackTimeout(i),Promise.resolve(t)}next(e={expires:3e4}){const t=V(),s=e;s.max_messages=1;const i=new Bs(this,s,!1),n=Math.round(i.opts.expires*1.05);n>=6e4&&(async()=>{for await(const a of await i.status())if(a.type===$e.HeartbeatsMissed&&a.data>=2){t.reject(new Error("consumer missed heartbeats"));break}})().catch(),(async()=>{for await(const a of i){t.resolve(a);break}})().catch(()=>{});const o=st(n);return i.closed().then(a=>{a?t.reject(a):t.resolve(null)}).catch(a=>{t.reject(a)}).finally(()=>{o.cancel()}),o.catch(a=>{t.resolve(null),i.close().catch()}),i.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(i=>(this._info=i,this._info))}}class ko{constructor(e,t,s={}){h(this,"api");h(this,"consumerOpts");h(this,"consumer");h(this,"opts");h(this,"cursor");h(this,"stream");h(this,"namePrefix");h(this,"serial");h(this,"currentConsumer");h(this,"userCallback");h(this,"iter");h(this,"type");h(this,"startSeq");h(this,"maxInitialReset");this.api=e,this.stream=t,this.cursor={stream_seq:1,deliver_seq:0},this.namePrefix=Je.next(),typeof s.name_prefix=="string"&&(Ht("name_prefix",s.name_prefix),this.namePrefix=s.name_prefix+this.namePrefix),this.serial=0,this.currentConsumer=null,this.userCallback=null,this.iter=null,this.type=Ce.Unset,this.consumerOpts=s,this.maxInitialReset=30,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:te.StartSequence,opt_start_seq:e,ack_policy:ae.None,inactive_threshold:W(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),this.consumerOpts.replay_policy&&(s.replay_policy=this.consumerOpts.replay_policy),e===this.startSeq+1&&(s.deliver_policy=this.consumerOpts.deliver_policy||te.StartSequence,(this.consumerOpts.deliver_policy===te.LastPerSubject||this.consumerOpts.deliver_policy===te.New||this.consumerOpts.deliver_policy===te.Last)&&(delete s.opt_start_seq,s.deliver_policy=this.consumerOpts.deliver_policy),s.deliver_policy===te.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=te.StartTime,s.opt_start_time=this.consumerOpts.opt_start_time),this.consumerOpts.inactive_threshold&&(s.inactive_threshold=W(this.consumerOpts.inactive_threshold))),s}async resetConsumer(e=0){var o,a,f,p,g;Je.next();const t=this.serial===0;(o=this.consumer)==null||o.delete().catch(()=>{}),e=e===0?1:e,this.cursor.deliver_seq=0;const s=this.getConsumerOpts(e);s.max_deliver=1,s.mem_storage=!0;const i=ys([((a=this.opts)==null?void 0:a.expires)||3e4]);let n;for(let y=0;;y++)try{n=await this.api.add(this.stream,s),(f=this.iter)==null||f.notify($e.OrderedConsumerRecreated,n.name);break}catch(x){if(x.message==="stream not found"&&((p=this.iter)==null||p.notify($e.StreamNotFound,y),this.type===Ce.Fetch||this.opts.abort_on_missing_resource===!0))return(g=this.iter)==null||g.stop(x),Promise.reject(x);if(t&&y>=this.maxInitialReset)throw x;await rt(i.backoff(y+1))}return n}internalHandler(e){return t=>{var i;if(this.serial!==e)return;const s=t.info.deliverySequence;if(s!==this.cursor.deliver_seq+1){this.notifyOrderedResetAndReset();return}this.cursor.deliver_seq=s,this.cursor.stream_seq=t.info.streamSequence,this.userCallback?this.userCallback(t):(i=this.iter)==null||i.push(t)}}async reset(e={max_messages:100,expires:3e4},t){var f,p;t=t||{};const s=t.fromFetch||!1,i=t.orderedReset||!1;if(this.type===Ce.Fetch&&i){(f=this.iter)==null||f.src.stop(),await((p=this.iter)==null?void 0:p.closed()),this.currentConsumer=null;return}(this.currentConsumer===null||i)&&(this.currentConsumer=await this.resetConsumer(this.cursor.stream_seq+1)),(this.iter===null||s)&&(this.iter=new Po),this.consumer=new Ds(this.api,this.currentConsumer);const n=e;n.callback=this.internalHandler(this.serial);let o=null;this.type===Ce.Fetch&&s?o=await this.consumer.fetch(e):this.type===Ce.Consume&&(o=await this.consumer.consume(e));const a=o;a.forOrderedConsumer=!0,a.resetHandler=()=>{this.notifyOrderedResetAndReset()},this.iter.setSource(a)}notifyOrderedResetAndReset(){var e;(e=this.iter)==null||e.notify(ft.Reset,""),this.reset(this.opts,{orderedReset:!0})}async consume(e={max_messages:100,expires:3e4}){if(e.bind)return Promise.reject(new Error("bind is not supported"));if(this.type===Ce.Fetch)return Promise.reject(new Error("ordered consumer initialized as fetch"));if(this.type===Ce.Consume)return Promise.reject(new Error("ordered consumer doesn't support concurrent consume"));const{callback:s}=e;return s&&(this.userCallback=s),this.type=Ce.Consume,this.opts=e,await this.reset(e),this.iter}async fetch(e={max_messages:100,expires:3e4}){var i;if(e.bind)return Promise.reject(new Error("bind is not supported"));if(this.type===Ce.Consume)return Promise.reject(new Error("ordered consumer already initialized as consume"));if(((i=this.iter)==null?void 0:i.done)===!1)return Promise.reject(new Error("ordered consumer doesn't support concurrent fetch"));const{callback:s}=e;return s&&(this.userCallback=s),this.type=Ce.Fetch,this.opts=e,await this.reset(e,{fromFetch:!0}),this.iter}async next(e={expires:3e4}){const t=e;if(t.bind)return Promise.reject(new Error("bind is not supported"));t.max_messages=1;const s=V();return t.callback=n=>{this.userCallback=null,s.resolve(n)},(await this.fetch(t)).iterClosed.then(n=>{n&&s.reject(n),s.resolve(null)}).catch(n=>{s.reject(n)}),s}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.startSeq),Promise.resolve(this.currentConsumer)):e&&this.currentConsumer?Promise.resolve(this.currentConsumer):this.api.info(this.stream,this.currentConsumer.name)}}class Hs{constructor(e){h(this,"api");h(this,"notified");this.api=e,this.notified=!1}checkVersion(){const e=this.api.nc.features.get(H.JS_SIMPLIFICATION);return e.ok?Promise.resolve():Promise.reject(new Error(`consumers framework is only supported on servers ${e.min} or better`))}getPullConsumerFor(e){if(e.config.deliver_subject!==void 0)throw new Error("push consumer not supported");return new Ds(this.api,e)}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 Ds(this.api,s)).catch(s=>Promise.reject(s)))}async ordered(e,t){await this.checkVersion();const s=this.api;return new Js(s.nc,s.opts).info(e).then(n=>Promise.resolve(new ko(this.api,e,t))).catch(n=>Promise.reject(n))}}class rs{constructor(e,t){h(this,"api");h(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 rs(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))}getConsumerFromInfo(e){return new Hs(new zt(this.api.nc,this.api.opts)).getPullConsumerFor(e)}getConsumer(e){return new Hs(new zt(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)}}class Js extends Et{constructor(e,t){super(e,t)}checkStreamConfigVersions(e){const t=this.nc;if(e.metadata){const{min:i,ok:n}=t.features.get(H.JS_STREAM_CONSUMER_METADATA);if(!n)throw new Error(`stream 'metadata' requires server ${i}`)}if(e.first_seq){const{min:i,ok:n}=t.features.get(H.JS_STREAM_FIRST_SEQ);if(!n)throw new Error(`stream 'first_seq' requires server ${i}`)}if(e.subject_transform){const{min:i,ok:n}=t.features.get(H.JS_STREAM_SUBJECT_TRANSFORM);if(!n)throw new Error(`stream 'subject_transform' requires server ${i}`)}if(e.compression){const{min:i,ok:n}=t.features.get(H.JS_STREAM_COMPRESSION);if(!n)throw new Error(`stream 'compression' requires server ${i}`)}if(e.consumer_limits){const{min:i,ok:n}=t.features.get(H.JS_DEFAULT_CONSUMER_LIMITS);if(!n)throw new Error(`stream 'consumer_limits' requires server ${i}`)}function s(i,n){var a;if((((a=n==null?void 0:n.subject_transforms)==null?void 0:a.length)||0)>0){const{min:f,ok:p}=t.features.get(H.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!p)throw new Error(`${i} 'subject_transforms' requires server ${f}`)}}e.sources&&e.sources.forEach(i=>{s("stream sources",i)}),e.mirror&&s("stream mirror",e.mirror)}async add(e={}){var i;this.checkStreamConfigVersions(e),pe(e.name),e.mirror=ss(e.mirror),e.sources=(i=e.sources)==null?void 0:i.map(ss);const s=await this._request(`${this.prefix}.STREAM.CREATE.${e.name}`,e);return this._fixInfo(s),s}async delete(e){return pe(e),(await this._request(`${this.prefix}.STREAM.DELETE.${e}`)).success}async update(e,t={}){var a;if(typeof e=="object"){const f=e;e=f.name,t=f,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),pe(e);const s=await this.info(e),i=Object.assign(s.config,t);i.mirror=ss(i.mirror),i.sources=(a=i.sources)==null?void 0:a.map(ss);const o=await this._request(`${this.prefix}.STREAM.UPDATE.${e}`,i);return this._fixInfo(o),o}async info(e,t){pe(e);const s=`${this.prefix}.STREAM.INFO.${e}`;let n=await this._request(s,t),{total:o,limit:a}=n,f=n.state.subjects?Object.getOwnPropertyNames(n.state.subjects).length:1;if(o&&o>f){const p=[n],g=t||{};let y=0;for(;o>f;){y++,g.offset=a*y;const A=await this._request(s,g);o=A.total,p.push(A);const I=Object.getOwnPropertyNames(A.state.subjects).length;if(f+=I,I<a)break}let x={};for(let A=0;A<p.length;A++)n=p[A],n.state.subjects&&(x=Object.assign(x,n.state.subjects));n.offset=0,n.total=0,n.limit=0,n.state.subjects=x}return this._fixInfo(n),n}list(e=""){const t=e!=null&&e.length?{subject:e}:{},s=n=>{const o=n;return o.streams.forEach(a=>{this._fixInfo(a)}),o.streams},i=`${this.prefix}.STREAM.LIST`;return new At(i,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:i,seq:n}=t;if(typeof i=="number"&&typeof n=="number")throw new Error("can specify one of keep or seq")}return pe(e),await this._request(`${this.prefix}.STREAM.PURGE.${e}`,t)}async deleteMessage(e,t,s=!0){pe(e);const i={seq:t};return s||(i.no_erase=!0),(await this._request(`${this.prefix}.STREAM.MSG.DELETE.${e}`,i)).success}async getMessage(e,t){pe(e);const i=await this._request(`${this.prefix}.STREAM.MSG.GET.${e}`,t);return new ei(i)}find(e){return this.findStream(e)}listKvs(){const e=s=>{var f;const n=s.streams.filter(p=>p.config.name.startsWith(ve));n.forEach(p=>{this._fixInfo(p)});let o="";return n.length&&(o=((f=this.nc.info)==null?void 0:f.cluster)??""),n.map(p=>new Xr(p,o))},t=`${this.prefix}.STREAM.LIST`;return new At(t,e,this)}listObjectStores(){const e=s=>{const n=s.streams.filter(a=>a.config.name.startsWith(qs));return n.forEach(a=>{this._fixInfo(a)}),n.map(a=>new Fs(a))},t=`${this.prefix}.STREAM.LIST`;return new At(t,e,this)}names(e=""){const t=e!=null&&e.length?{subject:e}:{},s=n=>n.streams,i=`${this.prefix}.STREAM.NAMES`;return new At(i,s,this,t)}async get(e){const t=await this.info(e);return Promise.resolve(new rs(this,t))}}class Oo extends Et{constructor(e,t){super(e,t)}async getMessage(e,t){pe(e);let s=t;const{last_by_subj:i}=s;i&&(s=null);const n=s?this.jc.encode(s):we,o=this.opts.apiPrefix||"$JS.API",a=i?`${o}.DIRECT.GET.${e}.${i}`:`${o}.DIRECT.GET.${e}`,f=await this.nc.request(a,n,{timeout:this.timeout}),p=nt(f);if(p)return Promise.reject(p);const g=new Ks(f);return Promise.resolve(g)}async getBatch(e,t){pe(e);const i=`${this.opts.apiPrefix||"$JS.API"}.DIRECT.GET.${e}`;if(!Array.isArray(t.multi_last)||t.multi_last.length===0)return Promise.reject("multi_last is required");const n=JSON.stringify(t,(f,p)=>f==="up_to_time"&&p instanceof Date?p.toISOString():p),o=new oe,a=await this.nc.requestMany(i,n,{strategy:je.SentinelMsg});return(async()=>{var y,x,A;let f=!1,p=!1,g;for await(const I of a){if(!f){f=!0;const T=((y=I.headers)==null?void 0:y.code)||0;if(T!==0&&T<200||T>299){g=(x=I.headers)==null?void 0:x.description.toLowerCase();break}if(((A=I.headers)==null?void 0:A.get("Nats-Num-Pending"))===""){p=!0;break}}if(I.data.length===0)break;o.push(new Ks(I))}o.push(()=>{if(p)throw new Error("batch direct get not supported by the server");if(g)throw new Error(`bad request: ${g}`);o.stop()})})(),Promise.resolve(o)}}class Ks{constructor(e){h(this,"data");h(this,"header");if(!e.headers)throw new Error("headers expected");this.data=e.data,this.header=e.headers}get subject(){return this.header.last(at.Subject)}get seq(){const e=this.header.last(at.Sequence);return typeof e=="string"?parseInt(e):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(at.TimeStamp)}get stream(){return this.header.last(at.Stream)}json(e){return ke(e).decode(this.data)}string(){return xe.decode(this.data)}}h(Ks,"jc");class Co extends Et{constructor(t,s){super(t,s);h(this,"streams");h(this,"consumers");h(this,"direct");this.streams=new Js(t,s),this.consumers=new zt(t,s),this.direct=new Oo(t,s)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return this.nc.jetstream(this.getOptions())}advisories(){const t=new oe;return this.nc.subscribe("$JS.EVENT.ADVISORY.>",{callback:(s,i)=>{if(s)throw s;try{const n=this.parseJsResponse(i),o=n.type.split("."),a=o[o.length-1];t.push({kind:a,data:n})}catch(n){t.stop(n)}}}),t}}class ei{constructor(e){h(this,"_header");h(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):we}get header(){if(!this._header)if(this.smr.message.hdrs){const e=this._parse(this.smr.message.hdrs);this._header=Ge.decode(e)}else this._header=Be();return this._header}_parse(e){const t=atob(e),s=t.length,i=new Uint8Array(s);for(let n=0;n<s;n++)i[n]=t.charCodeAt(n);return i}json(e){return ke(e).decode(this.data)}string(){return xe.decode(this.data)}}h(ei,"jc");class Io{constructor(e){h(this,"api");this.api=e}get(e){return this.api.info(e).then(t=>new rs(this.api,t))}}class zs{constructor(e){h(this,"info");h(this,"hdrs");this.info=e}get name(){return this.info.name}get description(){return this.info.description??""}get headers(){return this.hdrs||(this.hdrs=Ge.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 ti(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 jo(){return new ReadableStream({pull(r){r.enqueue(new Uint8Array(0)),r.close()}})}class Rt{constructor(e,t,s){h(this,"jsm");h(this,"js");h(this,"stream");h(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 zs(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 i=this._metaSubject(t);try{const n=await this.jsm.streams.getMessage(this.stream,{last_by_subj:i}),a=ke().decode(n.data);return a.revision=n.seq,a}catch(n){return n.code==="404"?null:Promise.reject(n)}}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 Fs(e)))}async status(e){const t=await this._si(e);return t===null?Promise.reject(new Error("object store not found")):Promise.resolve(new Fs(t))}destroy(){return this.jsm.streams.delete(this.stream)}async _put(e,t,s){var _e;const i=this.js.getOptions();s=s||{timeout:i.timeout},s.timeout=s.timeout||i.timeout,s.previousRevision=s.previousRevision??void 0;const{timeout:n,previousRevision:o}=s,a=this.js.nc.info,f=(a==null?void 0:a.max_payload)||1024;e=e||{},e.options=e.options||{};let p=((_e=e.options)==null?void 0:_e.max_chunk_size)||128*1024;p=p>f?f:p,e.options.max_chunk_size=p;const g=await this.info(e.name),{name:y,error:x}=this._checkNotEmpty(e.name);if(x)return Promise.reject(x);const A=Je.next(),I=this._chunkSubject(A),T=this._metaSubject(y),J=Object.assign({bucket:this.name,nuid:A,size:0,chunks:0},ti(e)),se=V(),L=[],ee=new ht;try{const w=t?t.getReader():null,j=jr.create();for(;;){const{done:F,value:R}=w?await w.read():{done:!0,value:void 0};if(F){if(ee.size()>0){const $=ee.drain();j.update($),J.chunks++,J.size+=$.length,L.push(this.js.publish(I,$,{timeout:n}))}await Promise.all(L),L.length=0,J.mtime=new Date().toISOString();const P=ct.encode(j.digest());J.digest=`${Zr}${P}`,J.deleted=!1;const U=Be();typeof o=="number"&&U.set(Ue.ExpectedLastSubjectSequenceHdr,`${o}`),U.set(me.RollupHdr,me.RollupValueSubject);const q=await this.js.publish(T,ke().encode(J),{headers:U,timeout:n});if(J.revision=q.seq,g)try{await this.jsm.streams.purge(this.stream,{filter:`$O.${this.name}.C.${g.nuid}`})}catch{}se.resolve(new zs(J));break}if(R)for(ee.fill(R);ee.size()>p;){J.chunks++,J.size+=p;const P=ee.drain(e.options.max_chunk_size);j.update(P),L.push(this.js.publish(I,P,{timeout:n}))}}}catch(w){await this.jsm.streams.purge(this.stream,{filter:I}),se.reject(w)}return se}putBlob(e,t,s){function i(n){return new ReadableStream({pull(o){o.enqueue(n),o.close()}})}return t===null&&(t=new Uint8Array(0)),this.put(e,i(t),s)}put(e,t,s){var i;return(i=e==null?void 0:e.options)!=null&&i.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(n){const o=new ht,a=n.getReader();for(;;){const{done:f,value:p}=await a.read();if(f)return o.drain();p&&p.length&&o.fill(p)}}const s=await this.get(e);if(s===null)return Promise.resolve(null);const i=await Promise.all([s.error,t(s.data)]);return i[0]?Promise.reject(i[0]):Promise.resolve(i[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 y=t.options.link.name||"";if(y==="")throw new Error("link is a bucket");return(t.options.link.bucket!==this.name?await Rt.create(this.js,t.options.link.bucket):this).get(y)}if(!t.digest.startsWith(Zr))return Promise.reject(new Error(`unknown digest type: ${t.digest}`));const s=Is(t.digest.substring(8));if(s===null)return Promise.reject(new Error(`unable to parse digest: ${t.digest}`));const i=V(),n={info:new zs(t),error:i};if(t.size===0)return n.data=jo(),i.resolve(null),Promise.resolve(n);let o;const a=We();a.orderedConsumer();const f=jr.create(),p=`$O.${this.name}.C.${t.nuid}`,g=await this.js.subscribe(p,a);return(async()=>{for await(const y of g)y.data.length>0&&(f.update(y.data),o.enqueue(y.data)),y.info.pending===0&&(nn(s,f.digest())?o.close():o.error(new Error(`received a corrupt object, digests do not match received: ${t.digest} calculated ${s}`)),g.unsubscribe())})().then(()=>{i.resolve()}).catch(y=>{o.error(y),i.reject(y)}),n.data=new ReadableStream({start(y){o=y},cancel(){g.unsubscribe()}}),n}linkStore(e,t){if(!(t instanceof Rt))return Promise.reject("bucket required");const s=t,{name:i,error:n}=this._checkNotEmpty(e);if(n)return Promise.reject(n);const o={name:i,options:{link:{bucket:s.name}}};return this._put(o,null)}async link(e,t){const{name:s,error:i}=this._checkNotEmpty(e);if(i)return Promise.reject(i);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 n=await this.rawInfo(e);if(n!==null&&!n.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 f=await this.info(e);return Promise.resolve(f)}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=ke(),i=Be();return i.set(me.RollupHdr,me.RollupValueSubject),await this.js.publish(this._metaSubject(t.name),s.encode(t),{headers:i}),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:i,error:n}=this._checkNotEmpty(t.name);if(n)return Promise.reject(n);if(e!==t.name){const f=await this.info(t.name);if(f&&!f.deleted)return Promise.reject(new Error("an object already exists with that name"))}t.name=i;const o=Object.assign({},s,ti(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 oe,i=this._metaSubjectAll();try{await this.jsm.streams.getMessage(this.stream,{last_by_subj:i})}catch(f){f.code==="404"?(s.push(null),t=!0):s.stop(f)}const n=ke(),o=We();o.orderedConsumer(),e.includeHistory?o.deliverLastPerSubject():(t=!0,o.deliverNew()),o.callback((f,p)=>{var g;if(f){s.stop(f);return}if(p!==null){const y=n.decode(p.data);y.deleted&&e.ignoreDeletes===!0||s.push(y),((g=p.info)==null?void 0:g.pending)===0&&!t&&(t=!0,s.push(null))}});const a=await this.js.subscribe(i,o);return s._data=a,s.iterClosed.then(()=>{a.unsubscribe()}),a.closed.then(()=>{s.stop()}).catch(f=>{s.stop(f)}),s}_chunkSubject(e){return`$O.${this.name}.C.${e}`}_metaSubject(e){return`$O.${this.name}.M.${ct.encode(e)}`}_metaSubjectAll(){return`$O.${this.name}.M.>`}async init(e={}){try{this.stream=wo(this.name)}catch(i){return Promise.reject(i)}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.num_replicas=e.replicas??1,s.allow_direct=!0,s.allow_rollup_hdrs=!0,s.discard=St.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?Ve.S2:Ve.None);try{await this.jsm.streams.info(s.name)}catch(i){i.message==="stream not found"&&await this.jsm.streams.add(s)}}static async create(e,t,s={}){const i=await e.jetstreamManager(),n=new Rt(t,i,e);return await n.init(s),Promise.resolve(n)}}class Ro{constructor(e){h(this,"js");this.js=e}kv(e,t={}){const s=this.js,{ok:i,min:n}=s.nc.features.get(H.JS_KV);return i?t.bindOnly?Ct.bind(this.js,e,t):Ct.create(this.js,e,t):Promise.reject(new Error(`kv is only supported on servers ${n} 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:i,min:n}=s.nc.features.get(H.JS_OBJECTSTORE);return i?Rt.create(this.js,e,t):Promise.reject(new Error(`objectstore is only supported on servers ${n} or better`))}}class Gs extends Et{constructor(t,s){super(t,s);h(this,"consumers");h(this,"streams");h(this,"consumerAPI");h(this,"streamAPI");this.consumerAPI=new zt(t,s),this.streamAPI=new Js(t,s),this.consumers=new Hs(this.consumerAPI),this.streams=new Io(this.streamAPI)}jetstreamManager(t){t===void 0&&(t=this.opts.checkAPI);const s=Object.assign({},this.opts,{checkAPI:t});return this.nc.jetstreamManager(s)}get apiPrefix(){return this.prefix}get views(){return new Ro(this)}async publish(t,s=we,i){i=i||{},i.expect=i.expect||{};const n=(i==null?void 0:i.headers)||Be();i&&(i.msgID&&n.set(Ue.MsgIdHdr,i.msgID),i.expect.lastMsgID&&n.set(Ue.ExpectedLastMsgIdHdr,i.expect.lastMsgID),i.expect.streamName&&n.set(Ue.ExpectedStreamHdr,i.expect.streamName),typeof i.expect.lastSequence=="number"&&n.set(Ue.ExpectedLastSeqHdr,`${i.expect.lastSequence}`),typeof i.expect.lastSubjectSequence=="number"&&n.set(Ue.ExpectedLastSubjectSequenceHdr,`${i.expect.lastSubjectSequence}`));const o=i.timeout||this.timeout,a={};o&&(a.timeout=o),i&&(a.headers=n);let{retries:f,retry_delay:p}=i;f=f||1,p=p||250;let g;for(let x=0;x<f;x++)try{g=await this.nc.request(t,s,a);break}catch(A){if(A.code==="503"&&x+1<f)await rt(p);else throw A}const y=this.parseJsResponse(g);if(y.stream==="")throw N.errorForCode(k.JetStreamInvalidAck);return y.duplicate=y.duplicate?y.duplicate:!1,y}async pull(t,s,i=0){pe(t),it(s);let n=this.timeout;i>n&&(n=i),i=i<0?0:W(i);const o={batch:1,no_wait:i===0,expires:i},a=await this.nc.request(`${this.prefix}.CONSUMER.MSG.NEXT.${t}.${s}`,this.jc.encode(o),{noMux:!0,timeout:n}),f=nt(a);if(f)throw f;return jt(a,this.timeout)}fetch(t,s,i={}){pe(t),it(s);let n=null;const o=(i.max_bytes??0)>0;let a=0;const f=o?i.max_bytes:0;let p=null;const g={};if(g.batch=i.batch||1,f){const L=this.nc.features.get(H.JS_PULL_MAX_BYTES);if(!L.ok)throw new Error(`max_bytes is only supported on servers ${L.min} or better`);g.max_bytes=f}g.no_wait=i.no_wait||!1,g.no_wait&&g.expires&&(g.expires=0);const y=i.expires||0;if(y&&(g.expires=W(y)),y===0&&g.no_wait===!1)throw new Error("expires or no_wait is required");const x=i.idle_heartbeat||0;x&&(g.idle_heartbeat=W(x),i.delay_heartbeat===!0&&(g.idle_heartbeat=W(x*4)));const A=new oe,I=g.batch;let T=0;A.protocolFilterFn=(L,ee=!1)=>As(L.msg)?(p==null||p.work(),!1):!0,A.dispatchedFn=L=>{if(L){if(o&&(a+=L.data.length),T++,n&&L.info.pending===0)return;(A.getPending()===1&&L.info.pending===0||I===T||f>0&&a>=f)&&A.stop()}};const J=Fe(this.nc.options.inboxPrefix),se=this.nc.subscribe(J,{max:i.batch,callback:(L,ee)=>{L===null&&(L=nt(ee)),L!==null?(n&&(n.cancel(),n=null),qi(L)?A.stop(ri(L)===null?void 0:L):A.stop(L)):(p==null||p.work(),A.received++,A.push(jt(ee,this.timeout)))}});return y&&(n=st(y),n.catch(()=>{se.isClosed()||(se.drain().catch(()=>{}),n=null),p&&p.cancel()})),(async()=>{try{x&&(p=new Ps(x,L=>(A.push(()=>{A.err=new N(`${Oe.IdleHeartbeatMissed}: ${L}`,k.JetStreamIdleHeartBeat)}),!0)))}catch{}await se.closed,n!==null&&(n.cancel(),n=null),p&&p.cancel(),A.stop()})().catch(),this.nc.publish(`${this.prefix}.CONSUMER.MSG.NEXT.${t}.${s}`,this.jc.encode(g),{reply:J}),A}async pullSubscribe(t,s=We()){const i=await this._processOptions(t,s);if(i.ordered)throw new Error("pull subscribers cannot be be ordered");if(i.config.deliver_subject)throw new Error("consumer info specifies deliver_subject - pull consumers cannot have deliver_subject set");const n=i.config.ack_policy;if(n===ae.None||n===ae.All)throw new Error("ack policy for pull consumers must be explicit");const o=this._buildTypedSubscriptionOpts(i),a=new Uo(this,i.deliver,o);a.info=i;try{await this._maybeCreateConsumer(i)}catch(f){throw a.unsubscribe(),f}return a}async subscribe(t,s=We()){const i=await this._processOptions(t,s);if(!i.isBind&&!i.config.deliver_subject)throw new Error("push consumer requires deliver_subject");const n=this._buildTypedSubscriptionOpts(i),o=new si(this,i.deliver,n);o.info=i;try{await this._maybeCreateConsumer(i)}catch(a){throw o.unsubscribe(),a}return o._maybeSetupHbMonitoring(),o}async _processOptions(t,s=We()){const i=kr(s)?s.getOpts():s;if(i.isBind=kr(s)?s.isBind:!1,i.flow_control={heartbeat_count:0,fc_count:0,consumer_restarts:0},i.ordered){if(i.ordered_consumer_sequence={stream_seq:0,delivery_seq:0},i.config.ack_policy!==ae.NotSet&&i.config.ack_policy!==ae.None)throw new N("ordered consumer: ack_policy can only be set to 'none'",k.ApiError);if(i.config.durable_name&&i.config.durable_name.length>0)throw new N("ordered consumer: durable_name cannot be set",k.ApiError);if(i.config.deliver_subject&&i.config.deliver_subject.length>0)throw new N("ordered consumer: deliver_subject cannot be set",k.ApiError);if(i.config.max_deliver!==void 0&&i.config.max_deliver>1)throw new N("ordered consumer: max_deliver cannot be set",k.ApiError);if(i.config.deliver_group&&i.config.deliver_group.length>0)throw new N("ordered consumer: deliver_group cannot be set",k.ApiError);i.config.deliver_subject=Fe(this.nc.options.inboxPrefix),i.config.ack_policy=ae.None,i.config.max_deliver=1,i.config.flow_control=!0,i.config.idle_heartbeat=i.config.idle_heartbeat||W(5e3),i.config.ack_wait=W(22*60*60*1e3),i.config.mem_storage=!0,i.config.num_replicas=1}if(i.config.ack_policy===ae.NotSet&&(i.config.ack_policy=ae.All),i.api=this,i.config=i.config||{},i.stream=i.stream?i.stream:await this.findStream(t),i.attached=!1,i.config.durable_name)try{const n=await this.consumerAPI.info(i.stream,i.config.durable_name);if(n){if(n.config.filter_subject&&n.config.filter_subject!==t)throw new Error("subject does not match consumer");const o=i.config.deliver_group??"";if(o===""&&n.push_bound===!0)throw new Error("duplicate subscription");const a=n.config.deliver_group??"";if(o!==a)throw a===""?new Error("durable requires no queue group"):new Error(`durable requires queue group '${a}'`);i.last=n,i.config=n.config,i.attached=!0,i.config.durable_name||(i.name=n.name)}}catch(n){if(n.code!=="404")throw n}return!i.attached&&i.config.filter_subject===void 0&&i.config.filter_subjects===void 0&&(i.config.filter_subject=t),i.deliver=i.config.deliver_subject||Fe(this.nc.options.inboxPrefix),i}_buildTypedSubscriptionOpts(t){const s={};return s.adapter=$o(t.callbackFn===void 0,this.timeout),s.ingestionFilterFn=Gs.ingestionFn(t.ordered),s.protocolFilterFn=(i,n=!1)=>{const o=i;return Es(o.msg)?(n||o.msg.respond(),!1):!0},!t.mack&&t.config.ack_policy!==ae.None&&(s.dispatchedFn=Fo),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:te.All,ack_policy:ae.Explicit,ack_wait:W(30*1e3),replay_policy:ot.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,i)=>{var f;const n=i;if(!s)return{ingest:!1,protocol:!1};const o=s;if(nt(o.msg)||(f=n.monitor)==null||f.work(),As(o.msg)){const p=t?n._checkHbOrderConsumer(o.msg):!0;return t||n.info.flow_control.heartbeat_count++,{ingest:p,protocol:!0}}else if(Es(o.msg))return n.info.flow_control.fc_count++,{ingest:!0,protocol:!0};return{ingest:t?n._checkOrderedConsumer(s):!0,protocol:!1}}}}class Vs{constructor(e){h(this,"options");h(this,"protocol");h(this,"draining");h(this,"listeners");h(this,"_services");this.draining=!1,this.options=eo(e),this.listeners=[]}static connect(e={}){return new Promise((t,s)=>{const i=new Vs(e);Qt.connect(i.options,i).then(n=>{i.protocol=n,async function(){for await(const o of n.status())i.listeners.forEach(a=>{a.push(o)})}(),t(i)}).catch(n=>{s(n)})})}closed(){return this.protocol.closed}async close(){await this.protocol.close()}_check(e,t,s){if(this.isClosed())throw N.errorForCode(k.ConnectionClosed);if(t&&this.isDraining()||s&&this.protocol.noMorePublishing)throw N.errorForCode(k.ConnectionDraining);if(e=e||"",e.length===0)throw N.errorForCode(k.BadSubject)}publish(e,t,s){this._check(e,!1,!0),this.protocol.publish(e,t,s)}publishMessage(e){return this.publish(e.subject,e.data,{reply:e.reply,headers:e.headers})}respondMessage(e){return e.reply?(this.publish(e.reply,e.data,{reply:e.reply,headers:e.headers}),!0):!1}subscribe(e,t={}){this._check(e,!0,!1);const s=new Gr(this.protocol,e,t);return this.protocol.subscribe(s),s}_resub(e,t,s){this._check(t,!0,!1);const i=e;i.max=s,s&&(i.max=s+i.received),this.protocol.resub(i,t)}requestMany(e,t=we,s={maxWait:1e3,maxMessages:-1}){const i=!this.protocol.options.noAsyncTraces;try{this._check(e,!0,!0)}catch(f){return Promise.reject(f)}if(s.strategy=s.strategy||je.Timer,s.maxWait=s.maxWait||1e3,s.maxWait<1)return Promise.reject(new N("timeout",k.InvalidOption));const n=new oe;function o(f){n.push(()=>{n.stop(f)})}function a(f,p){f||p===null?o(f===null?void 0:f):n.push(p)}if(s.noMux){const f=i?new Error().stack:null;let p=typeof s.maxMessages=="number"&&s.maxMessages>0?s.maxMessages:-1;const g=this.subscribe(Fe(this.options.inboxPrefix),{callback:(I,T)=>{var J,se;if(((J=T==null?void 0:T.data)==null?void 0:J.length)===0&&((se=T==null?void 0:T.headers)==null?void 0:se.status)===k.NoResponders&&(I=N.errorForCode(k.NoResponders)),I){f&&(I.stack+=`
23
+ `),e.max=t)}resub(e,t){!e||this.isClosed()||(this.unsub(e),e.subject=t,this.subscriptions.resub(e),this._sub(e))}flush(e){return e||(e=V()),this.pongs.push(e),this.outbound.fill(zr),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}${Gt}`):e.push(`SUB ${s.subject} ${s.sid}${Gt}`)}),e.length&&this.transport.send(yt(e.join("")))}async _close(e){this._closed||(this.whyClosed=new Error("close trace").stack||"",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 Gr(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}}const ao="$SRV";class Vr{constructor(e){h(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,i){var n,o;return i=i||{},i.headers=i.headers||Be(),(n=i.headers)==null||n.set(qt,`${e}`),(o=i.headers)==null||o.set(Lt,t),this.msg.respond(s,i)}json(e){return this.msg.json(e)}string(){return this.msg.string()}}class kt{constructor(e,t="",s=""){h(this,"subject");h(this,"queue");h(this,"srv");t!==""&&ho("service group",t);let i="";if(e instanceof Ot)this.srv=e,i="";else if(e instanceof kt){const n=e;this.srv=n.srv,s===""&&n.queue!==""&&(s=n.queue),i=n.subject}else throw new Error("unknown ServiceGroup type");this.subject=this.calcSubject(i,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;xt("endpoint",e);let{subject:i,handler:n,metadata:o,queue:a}=s;i=i||e,a=a||this.queue,co("endpoint subject",i),i=this.calcSubject(this.subject,i);const f={name:e,subject:i,queue:a,handler:n,metadata:o};return this.srv._addEndpoint(f)}addGroup(e="",t=""){return new kt(this,e,t)}}function co(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,i)=>{if(s===">"&&i!==t.length-1)throw new Error(`${r} cannot have internal '>': '${e}'`)})}function ho(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 Ot{constructor(e,t={name:"",version:""}){h(this,"nc");h(this,"_id");h(this,"config");h(this,"handlers");h(this,"internal");h(this,"_stopped");h(this,"_done");h(this,"started");this.nc=e,this.config=Object.assign({},t),this.config.queue||(this.config.queue="q"),xt("name",this.config.name),xt("queue",this.config.queue),Ze(this.config.version),this._id=Je.next(),this.internal=[],this._done=V(),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="",i){const n=i??ao;return t===""&&s===""?`${n}.${e}`:(xt("control subject name",t),s!==""?(xt("control subject id",s),`${n}.${e}.${t}.${s}`):`${n}.${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=Be();if(e instanceof Ft){const s=e;t.set(Lt,s.message),t.set(qt,`${s.code}`)}else t.set(Lt,e.message),t.set(qt,"500");return t}setupHandler(e,t=!1){const s=t?"":e.queue?e.queue:this.config.queue,{name:i,subject:n,handler:o}=e,a=e;a.internal=t,t&&this.internal.push(a),a.stats=new uo(i,n,s),a.queue=s;const f=o?(p,g)=>{if(p){this.close(p);return}const y=Date.now();try{o(p,new Vr(g))}catch(x){a.stats.countError(x),g==null||g.respond(we,{headers:this.errorToHeader(x)})}finally{a.stats.countLatency(y)}}:void 0;return a.sub=this.nc.subscribe(n,{callback:f,queue:s}),a.sub.closed.then(()=>{this._stopped||this.close(new Error(`required subscription ${e.subject} stopped`)).catch()}).catch(p=>{if(!this._stopped){const g=new Error(`required subscription ${e.subject} errored: ${p.message}`);g.stack=p.stack,this.close(g).catch()}}),a}info(){return{type:wt.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:i,queue:n}=e;return{subject:t,metadata:s,name:i,queue_group:n}})}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:wt.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,i="",n=""){const o={};o.name=e,o.subject=Ot.controlSubject(t,i,n),o.handler=s,this.setupHandler(o,!0)}start(){const e=ke(),t=(o,a)=>o?(this.close(o),Promise.reject(o)):this.stats().then(f=>(a==null||a.respond(e.encode(f)),Promise.resolve())),s=(o,a)=>o?(this.close(o),Promise.reject(o)):(a==null||a.respond(e.encode(this.info())),Promise.resolve()),i=e.encode(this.ping()),n=(o,a)=>o?(this.close(o).then().catch(),Promise.reject(o)):(a.respond(i),Promise.resolve());return this.addInternalHandler(ze.PING,n),this.addInternalHandler(ze.STATS,t),this.addInternalHandler(ze.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:wt.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 kt(this,e,t)}addEndpoint(e,t){return new kt(this).addEndpoint(e,t)}_addEndpoint(e){const t=new oe;t.noIterator=typeof e.handler=="function",t.noIterator||(e.handler=(i,n)=>{i?this.stop(i).catch():t.push(new Vr(n))},t.iterClosed.then(()=>{this.close().catch()}));const s=this.setupHandler(e,!1);return s.qi=t,this.handlers.push(s),t}}class uo{constructor(e,t,s=""){h(this,"name");h(this,"subject");h(this,"average_processing_time");h(this,"num_requests");h(this,"processing_time");h(this,"num_errors");h(this,"last_error");h(this,"data");h(this,"metadata");h(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+=W(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:i,num_requests:n,processing_time:o,last_error:a,data:f,queue:p}=this;return{name:e,subject:t,average_processing_time:s,num_errors:i,num_requests:n,processing_time:o,last_error:a,data:f,queue_group:p}}stats(e){const t=e;return(t==null?void 0:t.noIterator)===!1&&(this.processing_time=W(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 lo{constructor(e,t={strategy:je.JitterTimer,maxWait:2e3},s){h(this,"nc");h(this,"prefix");h(this,"opts");this.nc=e,this.prefix=s,this.opts=t}ping(e="",t=""){return this.q(ze.PING,e,t)}stats(e="",t=""){return this.q(ze.STATS,e,t)}info(e="",t=""){return this.q(ze.INFO,e,t)}async q(e,t="",s=""){const i=new oe,n=ke(),o=Ot.controlSubject(e,t,s,this.prefix),a=await this.nc.requestMany(o,we,this.opts);return(async()=>{for await(const f of a)try{const p=n.decode(f.data);i.push(p)}catch(p){i.push(()=>{i.stop(p)})}i.push(()=>{i.stop()})})().catch(f=>{i.stop(f)}),i}}function Wr(){return{key:{encode(r){return r},decode(r){return r}},value:{encode(r){return r},decode(r){return r}}}}function fo(){return{replicas:1,history:1,timeout:2e3,max_bytes:-1,maxValueSize:-1,codec:Wr(),storage:Os.File}}const es="KV-Operation",Yr="$KV",po=/^[-/=.\w]+$/,mo=/^[-/=.>*\w]+$/,bo=/^[-\w]+$/;function go(r){if(r.startsWith(".")||r.endsWith(".")||!po.test(r))throw new Error(`invalid key: ${r}`)}function _o(r){if(r.startsWith(".")||r.endsWith(".")||!mo.test(r))throw new Error(`invalid key: ${r}`)}function yo(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 ts(r){if(!bo.test(r))throw new Error(`invalid bucket name: ${r}`)}var Ue;(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"})(Ue||(Ue={}));class Ct{constructor(e,t,s){h(this,"js");h(this,"jsm");h(this,"stream");h(this,"bucket");h(this,"direct");h(this,"codec");h(this,"prefix");h(this,"editPrefix");h(this,"useJsPrefix");h(this,"_prefixLen");h(this,"validateKey",go);h(this,"validateSearchKey",_o);h(this,"hasWildcards",yo);ts(e),this.js=t,this.jsm=s,this.bucket=e,this.prefix=Yr,this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create(e,t,s={}){ts(t);const i=await e.jetstreamManager(),n=new Ct(t,e,i);return await n.init(s),n}static async bind(e,t,s={}){const i=await e.jetstreamManager(),n={config:{allow_direct:s.allow_direct}};ts(t);const o=new Ct(t,e,i);return n.config.name=s.streamName??o.bucketName(),Object.assign(o,n),o.stream=n.config.name,o.codec=s.codec||Wr(),o.direct=n.config.allow_direct??!1,o.initializePrefixes(n),o}async init(e={}){const t=Object.assign(fo(),e);this.codec=t.codec;const s={};this.stream=s.name=e.streamName??this.bucketName(),s.retention=ks.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 i=e.placementCluster??"";if(i&&(e.placement={},e.placement.cluster=i,e.placement.tags=[]),e.placement&&(s.placement=e.placement),e.republish&&(s.republish=e.republish),e.description&&(s.description=e.description),e.mirror){const y=Object.assign({},e.mirror);y.name.startsWith(ve)||(y.name=`${ve}${y.name}`),s.mirror=y,s.mirror_direct=!0}else if(e.sources){const y=e.sources.map(x=>{const A=Object.assign({},x),I=A.name.startsWith(ve)?A.name.substring(ve.length):A.name;return A.name.startsWith(ve)||(A.name=`${ve}${A.name}`),!x.external&&I!==this.bucket&&(A.subject_transforms=[{src:`$KV.${I}.>`,dest:`$KV.${this.bucket}.>`}]),A});s.sources=y,s.subjects=[this.subjectForBucket()]}else s.subjects=[this.subjectForBucket()];e.metadata&&(s.metadata=e.metadata),typeof e.compression=="boolean"&&(s.compression=e.compression?Ve.S2:Ve.None);const n=this.js.nc,o=n.getServerVersion(),a=o?js(o,Ze("2.7.2"))>=0:!1;s.discard=a?St.New:St.Old;const{ok:f,min:p}=n.features.get(H.JS_ALLOW_DIRECT);if(!f&&e.allow_direct===!0){const y=o?`${o.major}.${o.minor}.${o.micro}`:"unknown";return Promise.reject(new Error(`allow_direct is not available on server version ${y} - requires ${p}`))}e.allow_direct=typeof e.allow_direct=="boolean"?e.allow_direct:f,s.allow_direct=e.allow_direct,this.direct=s.allow_direct,s.num_replicas=t.replicas,t.ttl&&(s.max_age=W(t.ttl)),s.allow_rollup_hdrs=!0;let g;try{g=await this.jsm.streams.info(s.name),!g.config.allow_direct&&this.direct===!0&&(this.direct=!1)}catch(y){if(y.message==="stream not found")g=await this.jsm.streams.add(s);else throw y}this.initializePrefixes(g)}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(ve)&&(s=s.substring(ve.length)),t.external&&t.external.api!==""){const i=t.name.substring(ve.length);this.useJsPrefix=!1,this.prefix=`$KV.${i}`,this.editPrefix=`${t.external.api}.$KV.${s}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${ve}${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}`:`${Yr}.${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(me.MessageSizeHdr)||"";return s!==""?parseInt(s,10):e.length}smToEntry(e){return new To(this.bucket,this.prefixLen,e)}jmToEntry(e){const t=this.decodeKey(e.subject.substring(this.prefixLen));return new Mo(this.bucket,t,e)}async create(e,t){var n;let s;try{const o=await this.put(e,t,{previousSeq:0});return Promise.resolve(o)}catch(o){if(s=o,((n=o==null?void 0:o.api_error)==null?void 0:n.err_code)!==10071)return Promise.reject(o)}let i=0;try{const o=await this.get(e);return(o==null?void 0:o.operation)==="DEL"||(o==null?void 0:o.operation)==="PURGE"?(i=o!==null?o.revision:0,this.update(e,t,i)):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 i=this.encodeKey(e);this.validateKey(i);const n={};if(s.previousSeq!==void 0){const f=Be();n.headers=f,f.set(Ue.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`)}try{return(await this.js.publish(this.subjectForKey(i,!0),t,n)).seq}catch(f){const p=f;return p.isJetStreamError()?(p.message=(o=p.api_error)==null?void 0:o.description,p.code=`${(a=p.api_error)==null?void 0:a.code}`,Promise.reject(p)):Promise.reject(f)}}async get(e,t){const s=this.encodeKey(e);this.validateKey(s);let i={last_by_subj:this.subjectForKey(s)};t&&t.revision>0&&(i={seq:t.revision});let n;try{this.direct?n=await this.jsm.direct.getMessage(this.bucketName(),i):n=await this.jsm.streams.getMessage(this.bucketName(),i);const o=this.smToEntry(n);return o.key!==s?null:o}catch(o){if(o.code===k.JetStream404NoMessages)return null;throw o}}purge(e,t){return this._deleteOrPurge(e,"PURGE",t)}delete(e,t){return this._deleteOrPurge(e,"DEL",t)}async purgeDeletes(e=30*60*1e3){const t=V(),s=[],i=await this.watch({key:">",initializedFn:()=>{t.resolve()}});(async()=>{for await(const f of i)(f.operation==="DEL"||f.operation==="PURGE")&&s.push(f)})().then(),await t,i.stop();const n=Date.now()-e,o=s.map(f=>{const p=this.subjectForKey(f.key);return f.created.getTime()>=n?this.jsm.streams.purge(this.stream,{filter:p,keep:1}):this.jsm.streams.purge(this.stream,{filter:p,keep:0})}),a=await Promise.all(o);return a.unshift({success:!0,purged:0}),a.reduce((f,p)=>(f.purged+=p.purged,f))}async _deleteOrPurge(e,t,s){if(!this.hasWildcards(e))return this._doDeleteOrPurge(e,t,s);const i=await this.keys(e),n=[];for await(const o of i)n.push(this._doDeleteOrPurge(o,t)),n.length===100&&(await Promise.all(n),n.length=0);n.length>0&&await Promise.all(n)}async _doDeleteOrPurge(e,t,s){const i=this.encodeKey(e);this.validateKey(i);const n=Be();n.set(es,t),t==="PURGE"&&n.set(me.RollupHdr,me.RollupValueSubject),s!=null&&s.previousSeq&&n.set(Ue.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`),await this.js.publish(this.subjectForKey(i,!0),we,{headers:n})}_buildCC(e,t,s={}){let n=(Array.isArray(e)?e:[e]).map(f=>{const p=this.encodeKey(f);return this.validateSearchKey(f),this.fullKeyName(p)}),o=te.LastPerSubject;t===Re.AllHistory&&(o=te.All),t===Re.UpdatesOnly&&(o=te.New);let a;return n.length===1&&(a=n[0],n=void 0),Object.assign({deliver_policy:o,ack_policy:ae.None,filter_subjects:n,filter_subject:a,flow_control:!0,idle_heartbeat:W(5*1e3)},s)}remove(e){return this.purge(e)}async history(e={}){const t=e.key??">",s=new oe,i={};i.headers_only=e.headers_only||!1;let n;n=()=>{s.stop()};let o=0;const a=this._buildCC(t,Re.AllHistory,i),f=a.filter_subject,p=We(a);p.bindStream(this.stream),p.orderedConsumer(),p.callback((y,x)=>{if(y){s.stop(y);return}if(x){const A=this.jmToEntry(x);s.push(A),s.received++,(n&&o>0&&s.received>=o||x.info.pending===0)&&(s.push(n),n=void 0)}});const g=await this.js.subscribe(f,p);if(n){const{info:{last:y}}=g,x=y.num_pending+y.delivered.consumer_seq;if(x===0||s.received>=x)try{n()}catch(A){s.stop(A)}finally{n=void 0}else o=x}return s._data=g,s.iterClosed.then(()=>{g.unsubscribe()}),g.closed.then(()=>{s.stop()}).catch(y=>{s.stop(y)}),s}canSetWatcherName(){const t=this.js.nc,{ok:s}=t.features.get(H.JS_NEW_CONSUMER_CREATE_API);return s}async watch(e={}){const t=e.key??">",s=new oe,i={};i.headers_only=e.headers_only||!1;let n=Re.LastValue;e.include===Re.AllHistory?n=Re.AllHistory:e.include===Re.UpdatesOnly&&(n=Re.UpdatesOnly);const o=e.ignoreDeletes===!0;let a=e.initializedFn,f=0;const p=this._buildCC(t,n,i),g=p.filter_subject,y=We(p);this.canSetWatcherName()&&y.consumerName(Je.next()),y.bindStream(this.stream),e.resumeFromRevision&&e.resumeFromRevision>0&&y.startSequence(e.resumeFromRevision),y.orderedConsumer(),y.callback((A,I)=>{if(A){s.stop(A);return}if(I){const T=this.jmToEntry(I);if(o&&T.operation==="DEL")return;s.push(T),s.received++,a&&(f>0&&s.received>=f||I.info.pending===0)&&(s.push(a),a=void 0)}});const x=await this.js.subscribe(g,y);if(a){const{info:{last:A}}=x,I=A.num_pending+A.delivered.consumer_seq;if(I===0||s.received>=I)try{a()}catch(T){s.stop(T)}finally{a=void 0}else f=I}return s._data=x,s.iterClosed.then(()=>{x.unsubscribe()}),x.closed.then(()=>{s.stop()}).catch(A=>{s.stop(A)}),s}async keys(e=">"){const t=new oe,s=this._buildCC(e,Re.LastValue,{headers_only:!0}),i=Array.isArray(e)?">":s.filter_subject,n=We(s);n.bindStream(this.stream),n.orderedConsumer();const o=await this.js.subscribe(i,n);return(async()=>{var f;for await(const p of o){const g=(f=p.headers)==null?void 0:f.get(es);if(g!=="DEL"&&g!=="PURGE"){const y=this.decodeKey(p.subject.substring(this.prefixLen));t.push(y)}p.info.pending===0&&o.unsubscribe()}})().then(()=>{t.stop()}).catch(f=>{t.stop(f)}),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 n;const t=((n=this.js.nc.info)==null?void 0:n.cluster)??"",s=this.bucketName(),i=await this.jsm.streams.info(s);return new Xr(i,t)}}class Xr{constructor(e,t=""){h(this,"si");h(this,"cluster");this.si=e,this.cluster=t}get bucket(){return this.si.config.name.startsWith(ve)?this.si.config.name.substring(ve.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 ws(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!==Ve.None:!1}}const qs="OBJ_",Zr="SHA-256=";function wo(r){return ts(r),`${qs}${r}`}function xo(r){return r.startsWith(qs)?r.substring(4):r}class Fs{constructor(e){h(this,"si");h(this,"backingStore");this.si=e,this.backingStore="JetStream"}get bucket(){return xo(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!==Ve.None:!1}}function ss(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 Ce;(function(r){r[r.Unset=-1]="Unset",r[r.Consume=0]="Consume",r[r.Fetch=1]="Fetch"})(Ce||(Ce={}));var $e;(function(r){r.HeartbeatsMissed="heartbeats_missed",r.ConsumerNotFound="consumer_not_found",r.StreamNotFound="stream_not_found",r.ConsumerDeleted="consumer_deleted",r.OrderedConsumerRecreated="ordered_consumer_recreated",r.NoResponders="no_responders"})($e||($e={}));var lt;(function(r){r.DebugEvent="debug",r.Discard="discard",r.Reset="reset",r.Next="next"})(lt||(lt={}));const Qr=Uint8Array.of(43,65,67,75),So=Uint8Array.of(45,78,65,75),It=Uint8Array.of(43,87,80,73),vo=Uint8Array.of(43,78,88,84),Eo=Uint8Array.of(43,84,69,82,77),Ao=Uint8Array.of(32);function jt(r,e=5e3){return new Do(r,e)}class Bs extends oe{constructor(t,s,i=!1){super();h(this,"consumer");h(this,"opts");h(this,"sub");h(this,"monitor");h(this,"pending");h(this,"inbox");h(this,"refilling");h(this,"pong");h(this,"callback");h(this,"timeout");h(this,"cleanupHandler");h(this,"listeners");h(this,"statusIterator");h(this,"forOrderedConsumer");h(this,"resetHandler");h(this,"abortOnMissingResource");h(this,"bind");h(this,"inBackOff");this.consumer=t;const n=s;this.opts=this.parseOptions(s,i),this.callback=n.callback||null,this.noIterator=typeof this.callback=="function",this.monitor=null,this.pong=null,this.pending={msgs:0,bytes:0,requests:0},this.refilling=i,this.timeout=null,this.inbox=Fe(t.api.nc.options.inboxPrefix),this.listeners=[],this.forOrderedConsumer=!1,this.abortOnMissingResource=n.abort_on_missing_resource===!0,this.bind=n.bind===!0,this.inBackOff=!1,this.start()}start(){const{max_messages:t,max_bytes:s,idle_heartbeat:i,threshold_bytes:n,threshold_messages:o}=this.opts;this.closed().then(f=>{if(this.cleanupHandler)try{this.cleanupHandler(f)}catch{}});const{sub:a}=this;a&&a.unsubscribe(),this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(f,p)=>{var y,x,A,I;if(f){this.stop(f);return}if((y=this.monitor)==null||y.work(),p.subject===this.inbox){if(As(p))return;const T=(x=p.headers)==null?void 0:x.code,J=((I=(A=p.headers)==null?void 0:A.description)==null?void 0:I.toLowerCase())||"unknown",{msgsLeft:se,bytesLeft:L}=this.parseDiscard(p.headers);if(se>0||L>0)this.pending.msgs-=se,this.pending.bytes-=L,this.pending.requests--,this.notify(lt.Discard,{msgsLeft:se,bytesLeft:L});else if(T===400){this.stop(new N(J,`${T}`));return}else if(T===409&&J==="consumer deleted"){if(this.notify($e.ConsumerDeleted,`${T} ${J}`),!this.refilling||this.abortOnMissingResource){const ee=new N(J,`${T}`);this.stop(ee);return}}else if(T===503){if(this.notify($e.NoResponders,`${T} No Responders`),!this.refilling||this.abortOnMissingResource){const ee=new N("no responders",`${T}`);this.stop(ee);return}}else this.notify(lt.DebugEvent,`${T} ${J}`)}else this._push(jt(p,this.consumer.api.timeout)),this.received++,this.pending.msgs&&this.pending.msgs--,this.pending.bytes&&(this.pending.bytes-=p.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<=n){const T=this.pullOptions();this.pull(T)}}else this.pending.requests===0&&this._push(()=>{this.stop()})}}),this.sub.closed.then(()=>{this.sub.draining&&this._push(()=>{this.stop()})}),i&&(this.monitor=new Ps(i,f=>(this.notify($e.HeartbeatsMissed,f),this.resetPending().then(()=>{}).catch(()=>{}),!1),{maxOut:2})),(async()=>{var p;const f=this.consumer.api.nc.status();this.statusIterator=f;for await(const g of f)switch(g.type){case Pe.Disconnect:(p=this.monitor)==null||p.cancel();break;case Pe.Reconnect:this.resetPending().then(y=>{var x;y&&((x=this.monitor)==null||x.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(i){this.stop(i)}}}notify(t,s){this.listeners.length>0&&this.listeners.forEach(i=>{i.done||i.push({type:t,data:s})})}resetPending(){return this.bind?this.resetPendingNoInfo():this.resetPendingWithInfo()}resetPendingNoInfo(){return this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),Promise.resolve(!0)}async resetPendingWithInfo(){if(this.inBackOff)return!1;let t=0,s=0;const i=ys([this.opts.expires]);let n=0;for(;;){if(this.done)return!1;if(this.consumer.api.nc.isClosed())return console.error("aborting resetPending - connection is closed"),!1;try{return await this.consumer.info(),this.inBackOff=!1,t=0,this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),!0}catch(o){if(o.message==="stream not found"){if(s++,this.notify($e.StreamNotFound,s),!this.refilling||this.abortOnMissingResource)return this.stop(o),!1}else if(o.message==="consumer not found"){if(t++,this.notify($e.ConsumerNotFound,t),this.resetHandler)try{this.resetHandler()}catch{}if(!this.refilling||this.abortOnMissingResource)return this.stop(o),!1;if(this.forOrderedConsumer)return!1}else t=0,s=0;this.inBackOff=!0;const a=i.backoff(n),f=st(a);await Promise.race([f,this.consumer.api.nc.closed()]),f.cancel(),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(lt.Next,t)})}pullOptions(){const t=this.opts.max_messages-this.pending.msgs,s=this.opts.max_bytes-this.pending.bytes,i=W(this.opts.idle_heartbeat),n=W(this.opts.expires);return{batch:t,max_bytes:s,idle_heartbeat:i,expires:n}}parseDiscard(t){const s={msgsLeft:0,bytesLeft:0},i=t==null?void 0:t.get(me.PendingMessagesHdr);i&&(s.msgsLeft=parseInt(i));const n=t==null?void 0:t.get(me.PendingBytesHdr);return n&&(s.bytesLeft=parseInt(n)),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,i;this.done||((s=this.sub)==null||s.unsubscribe(),this.clearTimers(),(i=this.statusIterator)==null||i.stop(),this._push(()=>{super.stop(t),this.listeners.forEach(n=>{n.stop()})}))}parseOptions(t,s=!1){const i=t||{};if(i.max_messages=i.max_messages||0,i.max_bytes=i.max_bytes||0,i.max_messages!==0&&i.max_bytes!==0)throw new Error("only specify one of max_messages or max_bytes");if(i.max_messages===0&&(i.max_messages=100),i.expires=i.expires||3e4,i.expires<1e3)throw new Error("expires should be at least 1000ms");if(i.idle_heartbeat=i.idle_heartbeat||i.expires/2,i.idle_heartbeat=i.idle_heartbeat>3e4?3e4:i.idle_heartbeat,s){const n=Math.round(i.max_messages*.75)||1;i.threshold_messages=i.threshold_messages||n;const o=Math.round(i.max_bytes*.75)||1;i.threshold_bytes=i.threshold_bytes||o}return i}status(){const t=new oe;return this.listeners.push(t),Promise.resolve(t)}}class Po extends oe{constructor(){super();h(this,"src");h(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(s=>{this.stop(s||void 0)}),(async()=>{const s=await this.src.status();for await(const i of s)this.notify(i.type,i.data)})().catch(()=>{})}notify(t,s){this.listeners.length>0&&this.listeners.forEach(i=>{i.done||i.push({type:t,data:s})})}stop(t){var s;this.done||((s=this.src)==null||s.stop(t),super.stop(t),this.listeners.forEach(i=>{i.stop()}))}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}status(){const t=new oe;return this.listeners.push(t),Promise.resolve(t)}}class Ds{constructor(e,t){h(this,"api");h(this,"_info");h(this,"stream");h(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 Bs(this,e,!0))}fetch(e={max_messages:100,expires:3e4}){const t=new Bs(this,e,!1),s=Math.round(t.opts.expires*1.05),i=tt(s);return t.closed().catch(()=>{}).finally(()=>{i.cancel()}),i.catch(()=>{t.close().catch()}),t.trackTimeout(i),Promise.resolve(t)}next(e={expires:3e4}){const t=V(),s=e;s.max_messages=1;const i=new Bs(this,s,!1),n=Math.round(i.opts.expires*1.05);n>=6e4&&(async()=>{for await(const a of await i.status())if(a.type===$e.HeartbeatsMissed&&a.data>=2){t.reject(new Error("consumer missed heartbeats"));break}})().catch(),(async()=>{for await(const a of i){t.resolve(a);break}})().catch(()=>{});const o=tt(n);return i.closed().then(a=>{a?t.reject(a):t.resolve(null)}).catch(a=>{t.reject(a)}).finally(()=>{o.cancel()}),o.catch(a=>{t.resolve(null),i.close().catch()}),i.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(i=>(this._info=i,this._info))}}class ko{constructor(e,t,s={}){h(this,"api");h(this,"consumerOpts");h(this,"consumer");h(this,"opts");h(this,"cursor");h(this,"stream");h(this,"namePrefix");h(this,"serial");h(this,"currentConsumer");h(this,"userCallback");h(this,"iter");h(this,"type");h(this,"startSeq");h(this,"maxInitialReset");this.api=e,this.stream=t,this.cursor={stream_seq:1,deliver_seq:0},this.namePrefix=Je.next(),typeof s.name_prefix=="string"&&(Ht("name_prefix",s.name_prefix),this.namePrefix=s.name_prefix+this.namePrefix),this.serial=0,this.currentConsumer=null,this.userCallback=null,this.iter=null,this.type=Ce.Unset,this.consumerOpts=s,this.maxInitialReset=30,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:te.StartSequence,opt_start_seq:e,ack_policy:ae.None,inactive_threshold:W(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),this.consumerOpts.replay_policy&&(s.replay_policy=this.consumerOpts.replay_policy),e===this.startSeq+1&&(s.deliver_policy=this.consumerOpts.deliver_policy||te.StartSequence,(this.consumerOpts.deliver_policy===te.LastPerSubject||this.consumerOpts.deliver_policy===te.New||this.consumerOpts.deliver_policy===te.Last)&&(delete s.opt_start_seq,s.deliver_policy=this.consumerOpts.deliver_policy),s.deliver_policy===te.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=te.StartTime,s.opt_start_time=this.consumerOpts.opt_start_time),this.consumerOpts.inactive_threshold&&(s.inactive_threshold=W(this.consumerOpts.inactive_threshold))),s}async resetConsumer(e=0){var o,a,f,p,g;Je.next();const t=this.serial===0;(o=this.consumer)==null||o.delete().catch(()=>{}),e=e===0?1:e,this.cursor.deliver_seq=0;const s=this.getConsumerOpts(e);s.max_deliver=1,s.mem_storage=!0;const i=ys([((a=this.opts)==null?void 0:a.expires)||3e4]);let n;for(let y=0;;y++)try{n=await this.api.add(this.stream,s),(f=this.iter)==null||f.notify($e.OrderedConsumerRecreated,n.name);break}catch(x){if(x.message==="stream not found"&&((p=this.iter)==null||p.notify($e.StreamNotFound,y),this.type===Ce.Fetch||this.opts.abort_on_missing_resource===!0))return(g=this.iter)==null||g.stop(x),Promise.reject(x);if(t&&y>=this.maxInitialReset)throw x;await st(i.backoff(y+1))}return n}internalHandler(e){return t=>{var i;if(this.serial!==e)return;const s=t.info.deliverySequence;if(s!==this.cursor.deliver_seq+1){this.notifyOrderedResetAndReset();return}this.cursor.deliver_seq=s,this.cursor.stream_seq=t.info.streamSequence,this.userCallback?this.userCallback(t):(i=this.iter)==null||i.push(t)}}async reset(e={max_messages:100,expires:3e4},t){var f,p;t=t||{};const s=t.fromFetch||!1,i=t.orderedReset||!1;if(this.type===Ce.Fetch&&i){(f=this.iter)==null||f.src.stop(),await((p=this.iter)==null?void 0:p.closed()),this.currentConsumer=null;return}(this.currentConsumer===null||i)&&(this.currentConsumer=await this.resetConsumer(this.cursor.stream_seq+1)),(this.iter===null||s)&&(this.iter=new Po),this.consumer=new Ds(this.api,this.currentConsumer);const n=e;n.callback=this.internalHandler(this.serial);let o=null;this.type===Ce.Fetch&&s?o=await this.consumer.fetch(e):this.type===Ce.Consume&&(o=await this.consumer.consume(e));const a=o;a.forOrderedConsumer=!0,a.resetHandler=()=>{this.notifyOrderedResetAndReset()},this.iter.setSource(a)}notifyOrderedResetAndReset(){var e;(e=this.iter)==null||e.notify(lt.Reset,""),this.reset(this.opts,{orderedReset:!0})}async consume(e={max_messages:100,expires:3e4}){if(e.bind)return Promise.reject(new Error("bind is not supported"));if(this.type===Ce.Fetch)return Promise.reject(new Error("ordered consumer initialized as fetch"));if(this.type===Ce.Consume)return Promise.reject(new Error("ordered consumer doesn't support concurrent consume"));const{callback:s}=e;return s&&(this.userCallback=s),this.type=Ce.Consume,this.opts=e,await this.reset(e),this.iter}async fetch(e={max_messages:100,expires:3e4}){var i;if(e.bind)return Promise.reject(new Error("bind is not supported"));if(this.type===Ce.Consume)return Promise.reject(new Error("ordered consumer already initialized as consume"));if(((i=this.iter)==null?void 0:i.done)===!1)return Promise.reject(new Error("ordered consumer doesn't support concurrent fetch"));const{callback:s}=e;return s&&(this.userCallback=s),this.type=Ce.Fetch,this.opts=e,await this.reset(e,{fromFetch:!0}),this.iter}async next(e={expires:3e4}){const t=e;if(t.bind)return Promise.reject(new Error("bind is not supported"));t.max_messages=1;const s=V();return t.callback=n=>{this.userCallback=null,s.resolve(n)},(await this.fetch(t)).iterClosed.then(n=>{n&&s.reject(n),s.resolve(null)}).catch(n=>{s.reject(n)}),s}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.startSeq),Promise.resolve(this.currentConsumer)):e&&this.currentConsumer?Promise.resolve(this.currentConsumer):this.api.info(this.stream,this.currentConsumer.name)}}class Hs{constructor(e){h(this,"api");h(this,"notified");this.api=e,this.notified=!1}checkVersion(){const e=this.api.nc.features.get(H.JS_SIMPLIFICATION);return e.ok?Promise.resolve():Promise.reject(new Error(`consumers framework is only supported on servers ${e.min} or better`))}getPullConsumerFor(e){if(e.config.deliver_subject!==void 0)throw new Error("push consumer not supported");return new Ds(this.api,e)}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 Ds(this.api,s)).catch(s=>Promise.reject(s)))}async ordered(e,t){await this.checkVersion();const s=this.api;return new Js(s.nc,s.opts).info(e).then(n=>Promise.resolve(new ko(this.api,e,t))).catch(n=>Promise.reject(n))}}class rs{constructor(e,t){h(this,"api");h(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 rs(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))}getConsumerFromInfo(e){return new Hs(new zt(this.api.nc,this.api.opts)).getPullConsumerFor(e)}getConsumer(e){return new Hs(new zt(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)}}class Js extends Et{constructor(e,t){super(e,t)}checkStreamConfigVersions(e){const t=this.nc;if(e.metadata){const{min:i,ok:n}=t.features.get(H.JS_STREAM_CONSUMER_METADATA);if(!n)throw new Error(`stream 'metadata' requires server ${i}`)}if(e.first_seq){const{min:i,ok:n}=t.features.get(H.JS_STREAM_FIRST_SEQ);if(!n)throw new Error(`stream 'first_seq' requires server ${i}`)}if(e.subject_transform){const{min:i,ok:n}=t.features.get(H.JS_STREAM_SUBJECT_TRANSFORM);if(!n)throw new Error(`stream 'subject_transform' requires server ${i}`)}if(e.compression){const{min:i,ok:n}=t.features.get(H.JS_STREAM_COMPRESSION);if(!n)throw new Error(`stream 'compression' requires server ${i}`)}if(e.consumer_limits){const{min:i,ok:n}=t.features.get(H.JS_DEFAULT_CONSUMER_LIMITS);if(!n)throw new Error(`stream 'consumer_limits' requires server ${i}`)}function s(i,n){var a;if((((a=n==null?void 0:n.subject_transforms)==null?void 0:a.length)||0)>0){const{min:f,ok:p}=t.features.get(H.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!p)throw new Error(`${i} 'subject_transforms' requires server ${f}`)}}e.sources&&e.sources.forEach(i=>{s("stream sources",i)}),e.mirror&&s("stream mirror",e.mirror)}async add(e={}){var i;this.checkStreamConfigVersions(e),pe(e.name),e.mirror=ss(e.mirror),e.sources=(i=e.sources)==null?void 0:i.map(ss);const s=await this._request(`${this.prefix}.STREAM.CREATE.${e.name}`,e);return this._fixInfo(s),s}async delete(e){return pe(e),(await this._request(`${this.prefix}.STREAM.DELETE.${e}`)).success}async update(e,t={}){var a;if(typeof e=="object"){const f=e;e=f.name,t=f,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),pe(e);const s=await this.info(e),i=Object.assign(s.config,t);i.mirror=ss(i.mirror),i.sources=(a=i.sources)==null?void 0:a.map(ss);const o=await this._request(`${this.prefix}.STREAM.UPDATE.${e}`,i);return this._fixInfo(o),o}async info(e,t){pe(e);const s=`${this.prefix}.STREAM.INFO.${e}`;let n=await this._request(s,t),{total:o,limit:a}=n,f=n.state.subjects?Object.getOwnPropertyNames(n.state.subjects).length:1;if(o&&o>f){const p=[n],g=t||{};let y=0;for(;o>f;){y++,g.offset=a*y;const A=await this._request(s,g);o=A.total,p.push(A);const I=Object.getOwnPropertyNames(A.state.subjects).length;if(f+=I,I<a)break}let x={};for(let A=0;A<p.length;A++)n=p[A],n.state.subjects&&(x=Object.assign(x,n.state.subjects));n.offset=0,n.total=0,n.limit=0,n.state.subjects=x}return this._fixInfo(n),n}list(e=""){const t=e!=null&&e.length?{subject:e}:{},s=n=>{const o=n;return o.streams.forEach(a=>{this._fixInfo(a)}),o.streams},i=`${this.prefix}.STREAM.LIST`;return new At(i,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:i,seq:n}=t;if(typeof i=="number"&&typeof n=="number")throw new Error("can specify one of keep or seq")}return pe(e),await this._request(`${this.prefix}.STREAM.PURGE.${e}`,t)}async deleteMessage(e,t,s=!0){pe(e);const i={seq:t};return s||(i.no_erase=!0),(await this._request(`${this.prefix}.STREAM.MSG.DELETE.${e}`,i)).success}async getMessage(e,t){pe(e);const i=await this._request(`${this.prefix}.STREAM.MSG.GET.${e}`,t);return new ei(i)}find(e){return this.findStream(e)}listKvs(){const e=s=>{var f;const n=s.streams.filter(p=>p.config.name.startsWith(ve));n.forEach(p=>{this._fixInfo(p)});let o="";return n.length&&(o=((f=this.nc.info)==null?void 0:f.cluster)??""),n.map(p=>new Xr(p,o))},t=`${this.prefix}.STREAM.LIST`;return new At(t,e,this)}listObjectStores(){const e=s=>{const n=s.streams.filter(a=>a.config.name.startsWith(qs));return n.forEach(a=>{this._fixInfo(a)}),n.map(a=>new Fs(a))},t=`${this.prefix}.STREAM.LIST`;return new At(t,e,this)}names(e=""){const t=e!=null&&e.length?{subject:e}:{},s=n=>n.streams,i=`${this.prefix}.STREAM.NAMES`;return new At(i,s,this,t)}async get(e){const t=await this.info(e);return Promise.resolve(new rs(this,t))}}class Oo extends Et{constructor(e,t){super(e,t)}async getMessage(e,t){pe(e);let s=t;const{last_by_subj:i}=s;i&&(s=null);const n=s?this.jc.encode(s):we,o=this.opts.apiPrefix||"$JS.API",a=i?`${o}.DIRECT.GET.${e}.${i}`:`${o}.DIRECT.GET.${e}`,f=await this.nc.request(a,n,{timeout:this.timeout}),p=it(f);if(p)return Promise.reject(p);const g=new Ks(f);return Promise.resolve(g)}async getBatch(e,t){pe(e);const i=`${this.opts.apiPrefix||"$JS.API"}.DIRECT.GET.${e}`;if(!Array.isArray(t.multi_last)||t.multi_last.length===0)return Promise.reject("multi_last is required");const n=JSON.stringify(t,(f,p)=>f==="up_to_time"&&p instanceof Date?p.toISOString():p),o=new oe,a=await this.nc.requestMany(i,n,{strategy:je.SentinelMsg});return(async()=>{var y,x,A;let f=!1,p=!1,g;for await(const I of a){if(!f){f=!0;const T=((y=I.headers)==null?void 0:y.code)||0;if(T!==0&&T<200||T>299){g=(x=I.headers)==null?void 0:x.description.toLowerCase();break}if(((A=I.headers)==null?void 0:A.get("Nats-Num-Pending"))===""){p=!0;break}}if(I.data.length===0)break;o.push(new Ks(I))}o.push(()=>{if(p)throw new Error("batch direct get not supported by the server");if(g)throw new Error(`bad request: ${g}`);o.stop()})})(),Promise.resolve(o)}}class Ks{constructor(e){h(this,"data");h(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 ke(e).decode(this.data)}string(){return xe.decode(this.data)}}h(Ks,"jc");class Co extends Et{constructor(t,s){super(t,s);h(this,"streams");h(this,"consumers");h(this,"direct");this.streams=new Js(t,s),this.consumers=new zt(t,s),this.direct=new Oo(t,s)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return this.nc.jetstream(this.getOptions())}advisories(){const t=new oe;return this.nc.subscribe("$JS.EVENT.ADVISORY.>",{callback:(s,i)=>{if(s)throw s;try{const n=this.parseJsResponse(i),o=n.type.split("."),a=o[o.length-1];t.push({kind:a,data:n})}catch(n){t.stop(n)}}}),t}}class ei{constructor(e){h(this,"_header");h(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):we}get header(){if(!this._header)if(this.smr.message.hdrs){const e=this._parse(this.smr.message.hdrs);this._header=Ge.decode(e)}else this._header=Be();return this._header}_parse(e){const t=atob(e),s=t.length,i=new Uint8Array(s);for(let n=0;n<s;n++)i[n]=t.charCodeAt(n);return i}json(e){return ke(e).decode(this.data)}string(){return xe.decode(this.data)}}h(ei,"jc");class Io{constructor(e){h(this,"api");this.api=e}get(e){return this.api.info(e).then(t=>new rs(this.api,t))}}class zs{constructor(e){h(this,"info");h(this,"hdrs");this.info=e}get name(){return this.info.name}get description(){return this.info.description??""}get headers(){return this.hdrs||(this.hdrs=Ge.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 ti(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 jo(){return new ReadableStream({pull(r){r.enqueue(new Uint8Array(0)),r.close()}})}class Rt{constructor(e,t,s){h(this,"jsm");h(this,"js");h(this,"stream");h(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 zs(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 i=this._metaSubject(t);try{const n=await this.jsm.streams.getMessage(this.stream,{last_by_subj:i}),a=ke().decode(n.data);return a.revision=n.seq,a}catch(n){return n.code==="404"?null:Promise.reject(n)}}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 Fs(e)))}async status(e){const t=await this._si(e);return t===null?Promise.reject(new Error("object store not found")):Promise.resolve(new Fs(t))}destroy(){return this.jsm.streams.delete(this.stream)}async _put(e,t,s){var _e;const i=this.js.getOptions();s=s||{timeout:i.timeout},s.timeout=s.timeout||i.timeout,s.previousRevision=s.previousRevision??void 0;const{timeout:n,previousRevision:o}=s,a=this.js.nc.info,f=(a==null?void 0:a.max_payload)||1024;e=e||{},e.options=e.options||{};let p=((_e=e.options)==null?void 0:_e.max_chunk_size)||128*1024;p=p>f?f:p,e.options.max_chunk_size=p;const g=await this.info(e.name),{name:y,error:x}=this._checkNotEmpty(e.name);if(x)return Promise.reject(x);const A=Je.next(),I=this._chunkSubject(A),T=this._metaSubject(y),J=Object.assign({bucket:this.name,nuid:A,size:0,chunks:0},ti(e)),se=V(),L=[],ee=new ct;try{const w=t?t.getReader():null,j=jr.create();for(;;){const{done:F,value:R}=w?await w.read():{done:!0,value:void 0};if(F){if(ee.size()>0){const $=ee.drain();j.update($),J.chunks++,J.size+=$.length,L.push(this.js.publish(I,$,{timeout:n}))}await Promise.all(L),L.length=0,J.mtime=new Date().toISOString();const P=at.encode(j.digest());J.digest=`${Zr}${P}`,J.deleted=!1;const U=Be();typeof o=="number"&&U.set(Ue.ExpectedLastSubjectSequenceHdr,`${o}`),U.set(me.RollupHdr,me.RollupValueSubject);const q=await this.js.publish(T,ke().encode(J),{headers:U,timeout:n});if(J.revision=q.seq,g)try{await this.jsm.streams.purge(this.stream,{filter:`$O.${this.name}.C.${g.nuid}`})}catch{}se.resolve(new zs(J));break}if(R)for(ee.fill(R);ee.size()>p;){J.chunks++,J.size+=p;const P=ee.drain(e.options.max_chunk_size);j.update(P),L.push(this.js.publish(I,P,{timeout:n}))}}}catch(w){await this.jsm.streams.purge(this.stream,{filter:I}),se.reject(w)}return se}putBlob(e,t,s){function i(n){return new ReadableStream({pull(o){o.enqueue(n),o.close()}})}return t===null&&(t=new Uint8Array(0)),this.put(e,i(t),s)}put(e,t,s){var i;return(i=e==null?void 0:e.options)!=null&&i.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(n){const o=new ct,a=n.getReader();for(;;){const{done:f,value:p}=await a.read();if(f)return o.drain();p&&p.length&&o.fill(p)}}const s=await this.get(e);if(s===null)return Promise.resolve(null);const i=await Promise.all([s.error,t(s.data)]);return i[0]?Promise.reject(i[0]):Promise.resolve(i[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 y=t.options.link.name||"";if(y==="")throw new Error("link is a bucket");return(t.options.link.bucket!==this.name?await Rt.create(this.js,t.options.link.bucket):this).get(y)}if(!t.digest.startsWith(Zr))return Promise.reject(new Error(`unknown digest type: ${t.digest}`));const s=Is(t.digest.substring(8));if(s===null)return Promise.reject(new Error(`unable to parse digest: ${t.digest}`));const i=V(),n={info:new zs(t),error:i};if(t.size===0)return n.data=jo(),i.resolve(null),Promise.resolve(n);let o;const a=We();a.orderedConsumer();const f=jr.create(),p=`$O.${this.name}.C.${t.nuid}`,g=await this.js.subscribe(p,a);return(async()=>{for await(const y of g)y.data.length>0&&(f.update(y.data),o.enqueue(y.data)),y.info.pending===0&&(nn(s,f.digest())?o.close():o.error(new Error(`received a corrupt object, digests do not match received: ${t.digest} calculated ${s}`)),g.unsubscribe())})().then(()=>{i.resolve()}).catch(y=>{o.error(y),i.reject(y)}),n.data=new ReadableStream({start(y){o=y},cancel(){g.unsubscribe()}}),n}linkStore(e,t){if(!(t instanceof Rt))return Promise.reject("bucket required");const s=t,{name:i,error:n}=this._checkNotEmpty(e);if(n)return Promise.reject(n);const o={name:i,options:{link:{bucket:s.name}}};return this._put(o,null)}async link(e,t){const{name:s,error:i}=this._checkNotEmpty(e);if(i)return Promise.reject(i);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 n=await this.rawInfo(e);if(n!==null&&!n.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 f=await this.info(e);return Promise.resolve(f)}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=ke(),i=Be();return i.set(me.RollupHdr,me.RollupValueSubject),await this.js.publish(this._metaSubject(t.name),s.encode(t),{headers:i}),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:i,error:n}=this._checkNotEmpty(t.name);if(n)return Promise.reject(n);if(e!==t.name){const f=await this.info(t.name);if(f&&!f.deleted)return Promise.reject(new Error("an object already exists with that name"))}t.name=i;const o=Object.assign({},s,ti(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 oe,i=this._metaSubjectAll();try{await this.jsm.streams.getMessage(this.stream,{last_by_subj:i})}catch(f){f.code==="404"?(s.push(null),t=!0):s.stop(f)}const n=ke(),o=We();o.orderedConsumer(),e.includeHistory?o.deliverLastPerSubject():(t=!0,o.deliverNew()),o.callback((f,p)=>{var g;if(f){s.stop(f);return}if(p!==null){const y=n.decode(p.data);y.deleted&&e.ignoreDeletes===!0||s.push(y),((g=p.info)==null?void 0:g.pending)===0&&!t&&(t=!0,s.push(null))}});const a=await this.js.subscribe(i,o);return s._data=a,s.iterClosed.then(()=>{a.unsubscribe()}),a.closed.then(()=>{s.stop()}).catch(f=>{s.stop(f)}),s}_chunkSubject(e){return`$O.${this.name}.C.${e}`}_metaSubject(e){return`$O.${this.name}.M.${at.encode(e)}`}_metaSubjectAll(){return`$O.${this.name}.M.>`}async init(e={}){try{this.stream=wo(this.name)}catch(i){return Promise.reject(i)}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.num_replicas=e.replicas??1,s.allow_direct=!0,s.allow_rollup_hdrs=!0,s.discard=St.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?Ve.S2:Ve.None);try{await this.jsm.streams.info(s.name)}catch(i){i.message==="stream not found"&&await this.jsm.streams.add(s)}}static async create(e,t,s={}){const i=await e.jetstreamManager(),n=new Rt(t,i,e);return await n.init(s),Promise.resolve(n)}}class Ro{constructor(e){h(this,"js");this.js=e}kv(e,t={}){const s=this.js,{ok:i,min:n}=s.nc.features.get(H.JS_KV);return i?t.bindOnly?Ct.bind(this.js,e,t):Ct.create(this.js,e,t):Promise.reject(new Error(`kv is only supported on servers ${n} 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:i,min:n}=s.nc.features.get(H.JS_OBJECTSTORE);return i?Rt.create(this.js,e,t):Promise.reject(new Error(`objectstore is only supported on servers ${n} or better`))}}class Gs extends Et{constructor(t,s){super(t,s);h(this,"consumers");h(this,"streams");h(this,"consumerAPI");h(this,"streamAPI");this.consumerAPI=new zt(t,s),this.streamAPI=new Js(t,s),this.consumers=new Hs(this.consumerAPI),this.streams=new Io(this.streamAPI)}jetstreamManager(t){t===void 0&&(t=this.opts.checkAPI);const s=Object.assign({},this.opts,{checkAPI:t});return this.nc.jetstreamManager(s)}get apiPrefix(){return this.prefix}get views(){return new Ro(this)}async publish(t,s=we,i){i=i||{},i.expect=i.expect||{};const n=(i==null?void 0:i.headers)||Be();i&&(i.msgID&&n.set(Ue.MsgIdHdr,i.msgID),i.expect.lastMsgID&&n.set(Ue.ExpectedLastMsgIdHdr,i.expect.lastMsgID),i.expect.streamName&&n.set(Ue.ExpectedStreamHdr,i.expect.streamName),typeof i.expect.lastSequence=="number"&&n.set(Ue.ExpectedLastSeqHdr,`${i.expect.lastSequence}`),typeof i.expect.lastSubjectSequence=="number"&&n.set(Ue.ExpectedLastSubjectSequenceHdr,`${i.expect.lastSubjectSequence}`));const o=i.timeout||this.timeout,a={};o&&(a.timeout=o),i&&(a.headers=n);let{retries:f,retry_delay:p}=i;f=f||1,p=p||250;let g;for(let x=0;x<f;x++)try{g=await this.nc.request(t,s,a);break}catch(A){if(A.code==="503"&&x+1<f)await st(p);else throw A}const y=this.parseJsResponse(g);if(y.stream==="")throw N.errorForCode(k.JetStreamInvalidAck);return y.duplicate=y.duplicate?y.duplicate:!1,y}async pull(t,s,i=0){pe(t),rt(s);let n=this.timeout;i>n&&(n=i),i=i<0?0:W(i);const o={batch:1,no_wait:i===0,expires:i},a=await this.nc.request(`${this.prefix}.CONSUMER.MSG.NEXT.${t}.${s}`,this.jc.encode(o),{noMux:!0,timeout:n}),f=it(a);if(f)throw f;return jt(a,this.timeout)}fetch(t,s,i={}){pe(t),rt(s);let n=null;const o=(i.max_bytes??0)>0;let a=0;const f=o?i.max_bytes:0;let p=null;const g={};if(g.batch=i.batch||1,f){const L=this.nc.features.get(H.JS_PULL_MAX_BYTES);if(!L.ok)throw new Error(`max_bytes is only supported on servers ${L.min} or better`);g.max_bytes=f}g.no_wait=i.no_wait||!1,g.no_wait&&g.expires&&(g.expires=0);const y=i.expires||0;if(y&&(g.expires=W(y)),y===0&&g.no_wait===!1)throw new Error("expires or no_wait is required");const x=i.idle_heartbeat||0;x&&(g.idle_heartbeat=W(x),i.delay_heartbeat===!0&&(g.idle_heartbeat=W(x*4)));const A=new oe,I=g.batch;let T=0;A.protocolFilterFn=(L,ee=!1)=>As(L.msg)?(p==null||p.work(),!1):!0,A.dispatchedFn=L=>{if(L){if(o&&(a+=L.data.length),T++,n&&L.info.pending===0)return;(A.getPending()===1&&L.info.pending===0||I===T||f>0&&a>=f)&&A.stop()}};const J=Fe(this.nc.options.inboxPrefix),se=this.nc.subscribe(J,{max:i.batch,callback:(L,ee)=>{L===null&&(L=it(ee)),L!==null?(n&&(n.cancel(),n=null),qi(L)?A.stop(ri(L)===null?void 0:L):A.stop(L)):(p==null||p.work(),A.received++,A.push(jt(ee,this.timeout)))}});return y&&(n=tt(y),n.catch(()=>{se.isClosed()||(se.drain().catch(()=>{}),n=null),p&&p.cancel()})),(async()=>{try{x&&(p=new Ps(x,L=>(A.push(()=>{A.err=new N(`${Oe.IdleHeartbeatMissed}: ${L}`,k.JetStreamIdleHeartBeat)}),!0)))}catch{}await se.closed,n!==null&&(n.cancel(),n=null),p&&p.cancel(),A.stop()})().catch(),this.nc.publish(`${this.prefix}.CONSUMER.MSG.NEXT.${t}.${s}`,this.jc.encode(g),{reply:J}),A}async pullSubscribe(t,s=We()){const i=await this._processOptions(t,s);if(i.ordered)throw new Error("pull subscribers cannot be be ordered");if(i.config.deliver_subject)throw new Error("consumer info specifies deliver_subject - pull consumers cannot have deliver_subject set");const n=i.config.ack_policy;if(n===ae.None||n===ae.All)throw new Error("ack policy for pull consumers must be explicit");const o=this._buildTypedSubscriptionOpts(i),a=new Uo(this,i.deliver,o);a.info=i;try{await this._maybeCreateConsumer(i)}catch(f){throw a.unsubscribe(),f}return a}async subscribe(t,s=We()){const i=await this._processOptions(t,s);if(!i.isBind&&!i.config.deliver_subject)throw new Error("push consumer requires deliver_subject");const n=this._buildTypedSubscriptionOpts(i),o=new si(this,i.deliver,n);o.info=i;try{await this._maybeCreateConsumer(i)}catch(a){throw o.unsubscribe(),a}return o._maybeSetupHbMonitoring(),o}async _processOptions(t,s=We()){const i=kr(s)?s.getOpts():s;if(i.isBind=kr(s)?s.isBind:!1,i.flow_control={heartbeat_count:0,fc_count:0,consumer_restarts:0},i.ordered){if(i.ordered_consumer_sequence={stream_seq:0,delivery_seq:0},i.config.ack_policy!==ae.NotSet&&i.config.ack_policy!==ae.None)throw new N("ordered consumer: ack_policy can only be set to 'none'",k.ApiError);if(i.config.durable_name&&i.config.durable_name.length>0)throw new N("ordered consumer: durable_name cannot be set",k.ApiError);if(i.config.deliver_subject&&i.config.deliver_subject.length>0)throw new N("ordered consumer: deliver_subject cannot be set",k.ApiError);if(i.config.max_deliver!==void 0&&i.config.max_deliver>1)throw new N("ordered consumer: max_deliver cannot be set",k.ApiError);if(i.config.deliver_group&&i.config.deliver_group.length>0)throw new N("ordered consumer: deliver_group cannot be set",k.ApiError);i.config.deliver_subject=Fe(this.nc.options.inboxPrefix),i.config.ack_policy=ae.None,i.config.max_deliver=1,i.config.flow_control=!0,i.config.idle_heartbeat=i.config.idle_heartbeat||W(5e3),i.config.ack_wait=W(22*60*60*1e3),i.config.mem_storage=!0,i.config.num_replicas=1}if(i.config.ack_policy===ae.NotSet&&(i.config.ack_policy=ae.All),i.api=this,i.config=i.config||{},i.stream=i.stream?i.stream:await this.findStream(t),i.attached=!1,i.config.durable_name)try{const n=await this.consumerAPI.info(i.stream,i.config.durable_name);if(n){if(n.config.filter_subject&&n.config.filter_subject!==t)throw new Error("subject does not match consumer");const o=i.config.deliver_group??"";if(o===""&&n.push_bound===!0)throw new Error("duplicate subscription");const a=n.config.deliver_group??"";if(o!==a)throw a===""?new Error("durable requires no queue group"):new Error(`durable requires queue group '${a}'`);i.last=n,i.config=n.config,i.attached=!0,i.config.durable_name||(i.name=n.name)}}catch(n){if(n.code!=="404")throw n}return!i.attached&&i.config.filter_subject===void 0&&i.config.filter_subjects===void 0&&(i.config.filter_subject=t),i.deliver=i.config.deliver_subject||Fe(this.nc.options.inboxPrefix),i}_buildTypedSubscriptionOpts(t){const s={};return s.adapter=$o(t.callbackFn===void 0,this.timeout),s.ingestionFilterFn=Gs.ingestionFn(t.ordered),s.protocolFilterFn=(i,n=!1)=>{const o=i;return Es(o.msg)?(n||o.msg.respond(),!1):!0},!t.mack&&t.config.ack_policy!==ae.None&&(s.dispatchedFn=Fo),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:te.All,ack_policy:ae.Explicit,ack_wait:W(30*1e3),replay_policy:nt.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,i)=>{var f;const n=i;if(!s)return{ingest:!1,protocol:!1};const o=s;if(it(o.msg)||(f=n.monitor)==null||f.work(),As(o.msg)){const p=t?n._checkHbOrderConsumer(o.msg):!0;return t||n.info.flow_control.heartbeat_count++,{ingest:p,protocol:!0}}else if(Es(o.msg))return n.info.flow_control.fc_count++,{ingest:!0,protocol:!0};return{ingest:t?n._checkOrderedConsumer(s):!0,protocol:!1}}}}class Vs{constructor(e){h(this,"options");h(this,"protocol");h(this,"draining");h(this,"listeners");h(this,"_services");this.draining=!1,this.options=eo(e),this.listeners=[]}static connect(e={}){return new Promise((t,s)=>{const i=new Vs(e);Qt.connect(i.options,i).then(n=>{i.protocol=n,async function(){for await(const o of n.status())i.listeners.forEach(a=>{a.push(o)})}(),t(i)}).catch(n=>{s(n)})})}closed(){return this.protocol.closed}async close(){await this.protocol.close()}_check(e,t,s){if(this.isClosed())throw N.errorForCode(k.ConnectionClosed);if(t&&this.isDraining()||s&&this.protocol.noMorePublishing)throw N.errorForCode(k.ConnectionDraining);if(e=e||"",e.length===0)throw N.errorForCode(k.BadSubject)}publish(e,t,s){this._check(e,!1,!0),this.protocol.publish(e,t,s)}publishMessage(e){return this.publish(e.subject,e.data,{reply:e.reply,headers:e.headers})}respondMessage(e){return e.reply?(this.publish(e.reply,e.data,{reply:e.reply,headers:e.headers}),!0):!1}subscribe(e,t={}){this._check(e,!0,!1);const s=new Gr(this.protocol,e,t);return this.protocol.subscribe(s),s}_resub(e,t,s){this._check(t,!0,!1);const i=e;i.max=s,s&&(i.max=s+i.received),this.protocol.resub(i,t)}requestMany(e,t=we,s={maxWait:1e3,maxMessages:-1}){const i=!this.protocol.options.noAsyncTraces;try{this._check(e,!0,!0)}catch(f){return Promise.reject(f)}if(s.strategy=s.strategy||je.Timer,s.maxWait=s.maxWait||1e3,s.maxWait<1)return Promise.reject(new N("timeout",k.InvalidOption));const n=new oe;function o(f){n.push(()=>{n.stop(f)})}function a(f,p){f||p===null?o(f===null?void 0:f):n.push(p)}if(s.noMux){const f=i?new Error().stack:null;let p=typeof s.maxMessages=="number"&&s.maxMessages>0?s.maxMessages:-1;const g=this.subscribe(Fe(this.options.inboxPrefix),{callback:(I,T)=>{var J,se;if(((J=T==null?void 0:T.data)==null?void 0:J.length)===0&&((se=T==null?void 0:T.headers)==null?void 0:se.status)===k.NoResponders&&(I=N.errorForCode(k.NoResponders)),I){f&&(I.stack+=`
24
24
 
25
25
  ${f}`),y(I);return}a(null,T),s.strategy===je.Count&&(p--,p===0&&y()),s.strategy===je.JitterTimer&&(A(),x=setTimeout(()=>{y()},300)),s.strategy===je.SentinelMsg&&T&&T.data.length===0&&y()}});g.requestSubject=e,g.closed.then(()=>{o()}).catch(I=>{n.stop(I)});const y=I=>{I&&n.push(()=>{throw I}),A(),g.drain().then(()=>{o()}).catch(T=>{o()})};n.iterClosed.then(()=>{A(),g==null||g.unsubscribe()}).catch(I=>{A(),g==null||g.unsubscribe()});try{this.publish(e,t,{reply:g.getSubject()})}catch(I){y(I)}let x=setTimeout(()=>{y()},s.maxWait);const A=()=>{x&&clearTimeout(x)}}else{const f=s;f.callback=a,n.iterClosed.then(()=>{p.cancel()}).catch(g=>{p.cancel(g)});const p=new on(this.protocol.muxSubscriptions,e,f);this.protocol.request(p);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${p.token}`,headers:s.headers})}catch(g){p.cancel(g)}}return Promise.resolve(n)}request(e,t,s={timeout:1e3,noMux:!1}){try{this._check(e,!0,!0)}catch(n){return Promise.reject(n)}const i=!this.protocol.options.noAsyncTraces;if(s.timeout=s.timeout||1e3,s.timeout<1)return Promise.reject(new N("timeout",k.InvalidOption));if(!s.noMux&&s.reply)return Promise.reject(new N("reply can only be used with noMux",k.InvalidOption));if(s.noMux){const n=s.reply?s.reply:Fe(this.options.inboxPrefix),o=V(),a=i?new Error:null,f=this.subscribe(n,{max:1,timeout:s.timeout,callback:(p,g)=>{p?(a&&p.code!==k.Timeout&&(p.stack+=`
26
26
 
27
27
  ${a.stack}`),f.unsubscribe(),o.reject(p)):(p=vr(g),p?(a&&(p.stack+=`
28
28
 
29
- ${a.stack}`),o.reject(p)):o.resolve(g))}});return f.requestSubject=e,this.protocol.publish(e,t,{reply:n,headers:s.headers}),o}else{const n=new Nr(this.protocol.muxSubscriptions,e,s,i);this.protocol.request(n);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${n.token}`,headers:s.headers})}catch(a){n.cancel(a)}const o=Promise.race([n.timer,n.deferred]);return o.catch(()=>{n.cancel()}),o}}flush(){return this.isClosed()?Promise.reject(N.errorForCode(k.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(N.errorForCode(k.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(k.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 oe;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}async context(){return(await this.request("$SYS.REQ.USER.INFO")).json((t,s)=>t==="time"?new Date(Date.parse(s)):s)}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(e={}){const t=new Co(this,e);if(e.checkAPI!==!1)try{await t.getAccountInfo()}catch(s){const i=s;throw i.code===k.NoResponders&&(i.code=k.JetStreamNotEnabled),i}return t}jetstream(e={}){return new Gs(this,e)}getServerVersion(){const e=this.info;return e?Qe(e.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw N.errorForCode(k.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 No(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(N.errorForCode(k.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(k.ConnectionDraining)):this.protocol.reconnect()}}class No{constructor(e){h(this,"nc");this.nc=e}add(e){try{return new Ot(this.nc,e).start()}catch(t){return Promise.reject(t)}}client(e,t){return new lo(this.nc,e,t)}}class To{constructor(e,t,s){h(this,"bucket");h(this,"sm");h(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(es)||"PUT"}get length(){const e=this.sm.header.get(me.MessageSizeHdr)||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Mo{constructor(e,t,s){h(this,"bucket");h(this,"key");h(this,"sm");this.bucket=e,this.key=t,this.sm=s}get value(){return this.sm.data}get created(){return new Date(ws(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var e;return((e=this.sm.headers)==null?void 0:e.get(es))||"PUT"}get delta(){return this.sm.info.pending}get length(){var t;const e=((t=this.sm.headers)==null?void 0:t.get(me.MessageSizeHdr))||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class si extends un{constructor(t,s,i){super(t.nc,s,i);h(this,"js");h(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=Fe(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const n=this.info;n.config.name=Je.next(),n.ordered_consumer_sequence.delivery_seq=0,n.flow_control.heartbeat_count=0,n.flow_control.fc_count=0,n.flow_control.consumer_restarts++,n.deliver=s,n.config.deliver_subject=s,n.config.deliver_policy=te.StartSequence,n.config.opt_start_seq=t;const o={};o.stream_name=this.info.stream,o.config=n.config;const a=`${n.api.prefix}.CONSUMER.CREATE.${n.stream}`;this.js._request(a,o,{retries:-1}).then(f=>{const p=f,g=this.sub.info;g.last=p,this.info.config=p.config,this.info.name=p.name}).catch(f=>{const p=new N(`unable to recreate ordered consumer ${n.stream} at seq ${t}`,k.RequestError,f);this.sub.callback(p,{})})}_maybeSetupHbMonitoring(){var s,i;const t=((i=(s=this.info)==null?void 0:s.config)==null?void 0:i.idle_heartbeat)||0;t&&this._setupHbMonitoring(ws(t))}_setupHbMonitoring(t,s=0){const i={cancelAfter:0,maxOut:2};s&&(i.cancelAfter=s);const n=this.sub,o=a=>{var g,y,x,A;const f=Hi(409,`${Oe.IdleHeartbeatMissed}: ${a}`,this.sub.subject);if(!((g=this.info)==null?void 0:g.ordered))this.sub.callback(null,f);else{if(!this.js.nc.protocol.connected)return!1;const I=((x=(y=this.info)==null?void 0:y.ordered_consumer_sequence)==null?void 0:x.stream_seq)||0;return this._resetOrderedConsumer(I+1),(A=this.monitor)==null||A.restart(),!1}return!n.noIterator};this.monitor=new Ps(t,o,i)}_checkHbOrderConsumer(t){const s=t.headers.get(me.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const i=parseInt(t.headers.get(me.LastConsumerSeqHdr),10),n=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,i!==n.delivery_seq&&this._resetOrderedConsumer(n.stream_seq+1),!1}_checkOrderedConsumer(t){const s=this.info.ordered_consumer_sequence,i=t.info.streamSequence,n=t.info.deliverySequence;return n!=s.delivery_seq+1?(this._resetOrderedConsumer(s.stream_seq+1),!1):(s.delivery_seq=n,s.stream_seq=i,!0)}async destroy(){this.isClosed()||await this.drain();const t=this.sub.info,s=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.DELETE.${t.stream}.${s}`;await t.api._request(i)}async consumerInfo(){const t=this.sub.info,s=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.INFO.${t.stream}.${s}`,n=await t.api._request(i);return t.last=n,n}}class Uo extends si{constructor(e,t,s){super(e,t,s)}pull(e={batch:1}){const{stream:t,config:s,name:i}=this.sub.info,n=s.durable_name??i,o={};if(o.batch=e.batch||1,o.no_wait=e.no_wait||!1,(e.max_bytes??0)>0){const p=this.js.nc.features.get(H.JS_PULL_MAX_BYTES);if(!p.ok)throw new Error(`max_bytes is only supported on servers ${p.min} or better`);o.max_bytes=e.max_bytes}let a=0;e.expires&&e.expires>0&&(a=e.expires,o.expires=W(a));let f=0;if(e.idle_heartbeat&&e.idle_heartbeat>0&&(f=e.idle_heartbeat,o.idle_heartbeat=W(f)),f&&a===0)throw new Error("idle_heartbeat requires expires");if(f>a)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),a&&f&&(this.monitor?this.monitor._change(f,a):this._setupHbMonitoring(f,a));const p=this.info.api,g=`${p.prefix}.CONSUMER.MSG.NEXT.${t}.${n}`,y=this.sub.subject;p.nc.publish(g,p.jc.encode(o),{reply:y})}}}function $o(r,e){return r?qo(e):Lo(e)}function Lo(r){return(e,t)=>e?[e,null]:(e=nt(t),e?[e,null]:[null,jt(t,r)])}function qo(r){return(e,t)=>{if(e)return[e,null];const s=nt(t);return s!==null?[ri(s),null]:[null,jt(t,r)]}}function ri(r){if(r!==null)switch(r.code){case k.JetStream404NoMessages:case k.JetStream408RequestTimeout:return null;case k.JetStream409:return Ji(r)?r:null;default:return r}return null}function Fo(r){r&&r.ack()}function Bo(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.deliveryCount=parseInt(e[6],10),t.redeliveryCount=t.deliveryCount,t.redelivered=t.deliveryCount>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 Do{constructor(e,t){h(this,"msg");h(this,"di");h(this,"didAck");h(this,"timeout");this.msg=e,this.didAck=!1,this.timeout=t}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=Bo(this.reply)),this.di}get redelivered(){return this.info.deliveryCount>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]===It[0]&&e[1]===It[1]&&e[2]===It[2]&&e[3]===It[3]}async ackAck(e){var s;e=e||{},e.timeout=e.timeout||this.timeout;const t=V();if(this.didAck)t.resolve(!1);else if(this.didAck=!0,this.msg.reply){const n=this.msg.publisher,o=!((s=n.options)!=null&&s.noAsyncTraces),a=new Nr(n.muxSubscriptions,this.msg.reply,{timeout:e.timeout},o);n.request(a);try{n.publish(this.msg.reply,Qr,{reply:`${n.muxSubscriptions.baseInbox}${a.token}`})}catch(f){a.cancel(f)}try{await Promise.race([a.timer,a.deferred]),t.resolve(!0)}catch(f){a.cancel(f),t.reject(f)}}else t.resolve(!1);return t}ack(){this.doAck(Qr)}nak(e){let t=So;e&&(t=Ss().encode(`-NAK ${JSON.stringify({delay:W(e)})}`)),this.doAck(t)}working(){this.doAck(It)}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=W(t.expires));const i=ke().encode(s),n=ht.concat(vo,Ao,i),o=e?{reply:e}:void 0;this.msg.respond(n,o)}term(e=""){let t=Eo;(e==null?void 0:e.length)>0&&(t=Ss().encode(`+TERM ${e}`)),this.doAck(t)}json(){return this.msg.json()}string(){return this.msg.string()}}const Ho="1.30.3",Jo="nats.ws";class Ko{constructor(){h(this,"version");h(this,"lang");h(this,"closeError");h(this,"connected");h(this,"done");h(this,"socket");h(this,"options");h(this,"socketClosed");h(this,"encrypted");h(this,"peeked");h(this,"yields");h(this,"signal");h(this,"closedNotification");this.version=Ho,this.lang=Jo,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=V(),this.closedNotification=V()}async connect(e,t){const s=V();if(t.tls)return s.reject(new N("tls",k.InvalidOption)),s;this.options=t;const i=e.src;if(t.wsFactory){const{socket:n,encrypted:o}=await t.wsFactory(e.src,t);this.socket=n,this.encrypted=o}else this.encrypted=i.indexOf("wss://")===0,this.socket=new WebSocket(i);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=n=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(n.data)),this.peeked){this.signal.resolve();return}const o=ht.concat(...this.yields),a=bn(o);if(a!==""){const f=ro.exec(a);if(!f){t.debug&&console.error("!!!",Dt(o)),s.reject(new Error("unexpected response from server"));return}try{const p=JSON.parse(f[1]);to(p,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(p){s.reject(p);return}}},this.socket.onclose=n=>{if(this.isDiscarded())return;this.socketClosed=!0;let o;this.done||(n.wasClean||(o=new Error(n.reason)),this._closed(o))},this.socket.onerror=n=>{if(this.isDiscarded())return;const o=n,a=new N(o.message,k.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 rt(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(`> ${Dt(e[t])}`),yield e[t];if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=V())}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(!this.isDiscarded())try{this.socket.send(e.buffer),this.options.debug&&console.info(`< ${Dt(e)}`);return}catch(t){this.options.debug&&console.error(`!!! ${Dt(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 zo(r,e){/^(.*:\/\/)(.*)/.test(r)||(typeof e=="boolean"?r=`${e===!0?"https":"http"}://${r}`:r=`https://${r}`);let s=new URL(r);const i=s.protocol.toLowerCase();i==="ws:"&&(e=!1),i==="wss:"&&(e=!0),i!=="https:"&&i!=="http"&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2"),s=new URL(`http://${r}`));let n,o;const a=s.hostname,f=s.pathname,p=s.search||"";switch(i){case"http:":case"ws:":case"nats:":o=s.port||"80",n="ws:";break;case"https:":case"wss:":case"tls:":o=s.port||"443",n="wss:";break;default:o=s.port||e===!0?"443":"80",n=e===!0?"wss:":"ws:";break}return`${n}//${a}:${o}${f}${p}`}function Go(r={}){return ln({defaultPort:443,urlParseFn:zo,factory:()=>new Ko}),Vs.connect(r)}const Xe=ke();class Ws{constructor(e){h(this,"onStatusChange");h(this,"nc");h(this,"sessionId","");h(this,"userId","");h(this,"globalPrefix","");h(this,"resolveConnected",e=>{});h(this,"isConnected",new Promise(e=>this.resolveConnected=e));this.config=e}get url(){return this.config.natsUrl}async connect(e={}){var x;const{natsWsUrls:t,user:s,prefix:i,accessToken:n,sessionSeed:o}=e,a=t??[this.config.natsUrl],f=n??await this.config.auth.getAccessToken();if(!f)throw new Error("Please provide auth token");const p=o??await this.config.auth.getSessionSeed();if(!p)throw new Error("Please provide session seed");const g=Ss();this.nc=await Go({servers:a,authenticator:Yn(f,g.encode(p))});const y=s??await this.config.auth.getLastLoginData();if(!y)throw new Error("Please authenticate first by calling `auth` apis");this.userId=y.userId,this.sessionId=y.sessionId,this.globalPrefix=i??"",this.resolveConnected(!0),(x=this.onStatusChange)==null||x.call(this,!0),console.log("[nats] connected.",this.globalPrefix?`(prefix: ${this.globalPrefix})`:""),(async()=>{var A,I;for await(const T of this.nc.status())switch(T.type!==Ke.PingTimer&&console.log("[nats] connection status:",T.type),T.type){case Pe.Reconnect:(A=this.onStatusChange)==null||A.call(this,!0);break;case Pe.Disconnect:case Pe.Error:case Ke.Reconnecting:(I=this.onStatusChange)==null||I.call(this,!1);break}})()}async disconnect(){var e,t;await((e=this.nc)==null?void 0:e.drain()),await((t=this.nc)==null?void 0:t.close())}async publish(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");try{const s=this.buildSubject(e);console.debug("[nats]>>",s),this.nc.publish(s,Xe.encode(t))}catch(s){throw console.error("[nats] publish failed:",s),s}}async call(e,t,s){var a;if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=this.buildSubject(e);console.debug("[nats]>>",i);const n=await this.nc.request(i,Xe.encode(t),{timeout:(s==null?void 0:s.timeoutInMs)??5e3}),o=Xe.decode(n.data);if(o.error)throw new Error(o.error.message);if((a=o.payload)!=null&&a.errorData)throw new Error(o.payload.errorData.message);return o.data??o.payload}async on(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=(this.globalPrefix?`${this.globalPrefix}.`:"")+e+".>",n=this.nc.subscribe(i);return(async()=>{for await(const o of n)try{console.debug("[nats]<<",o.subject);const a=o.subject.split(".");if(this.globalPrefix&&a[0]!==this.globalPrefix){console.log("[nats]","Skipped - "+o.subject);continue}a[0]==="dev"&&a.shift();const f=a.slice(0,a.length-2).join("."),p=a[a.length-2],g=a[a.length-1],y=Xe.decode(o.data);t(y,{subject:f,userId:p,sessionId:g})}catch(a){console.error("[nats] subscribe error",a)}})(),()=>n.unsubscribe()}async handler(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=(this.globalPrefix?`${this.globalPrefix}.`:"")+e+".>",n=this.nc.subscribe(i);return(async()=>{for await(const o of n)try{console.debug("[nats]<<",o.subject);const a=o.subject.split(".");if(this.globalPrefix&&a[0]!==this.globalPrefix){console.log("[nats]","Skipped - "+o.subject);continue}a[0]==="dev"&&a.shift();const f=a.slice(0,a.length-2).join("."),p=a[a.length-2],g=a[a.length-1],y=Xe.decode(o.data);try{const x=await t(y,{subject:f,userId:p,sessionId:g});o.reply&&o.respond(Xe.encode({data:x}))}catch(x){console.error("[nats] handle",x),o.reply&&o.respond(Xe.encode({error:{message:x.message}}))}}catch(a){console.error("[nats] handle",a),o.reply&&o.respond(Xe.encode({error:{message:a.message}}))}})(),()=>n.unsubscribe()}buildSubject(e){return[this.globalPrefix,e,this.userId,this.sessionId].filter(t=>t).join(".")}}class ii{async setItem(e,t){if(!t)return this.removeItem(e);localStorage.setItem(e,JSON.stringify(t))}async getItem(e){const t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async removeItem(e){localStorage.removeItem(e)}}function ni(r){const e=new Blob([r],{type:"audio/mpeg"}),t=URL.createObjectURL(e),s=new Audio;return s.src=t,s.onended=()=>{URL.revokeObjectURL(t)},s}class Vo{async getAudioBuffer(e,t,s){const i=[],n=crypto.randomUUID();return new Promise((o,a)=>{const f=new WebSocket(`${is.WSS_URL}?trustedclienttoken=${is.TRUSTED_CLIENT_TOKEN}&ConnectionId=${n}`);f.binaryType="arraybuffer";const p=Yo(e,t,s);f.addEventListener("open",()=>{const g=Wo();f.send(g);const y=`X-RequestId:${n}\r
29
+ ${a.stack}`),o.reject(p)):o.resolve(g))}});return f.requestSubject=e,this.protocol.publish(e,t,{reply:n,headers:s.headers}),o}else{const n=new Nr(this.protocol.muxSubscriptions,e,s,i);this.protocol.request(n);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${n.token}`,headers:s.headers})}catch(a){n.cancel(a)}const o=Promise.race([n.timer,n.deferred]);return o.catch(()=>{n.cancel()}),o}}flush(){return this.isClosed()?Promise.reject(N.errorForCode(k.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(N.errorForCode(k.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(k.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 oe;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}async context(){return(await this.request("$SYS.REQ.USER.INFO")).json((t,s)=>t==="time"?new Date(Date.parse(s)):s)}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(e={}){const t=new Co(this,e);if(e.checkAPI!==!1)try{await t.getAccountInfo()}catch(s){const i=s;throw i.code===k.NoResponders&&(i.code=k.JetStreamNotEnabled),i}return t}jetstream(e={}){return new Gs(this,e)}getServerVersion(){const e=this.info;return e?Ze(e.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw N.errorForCode(k.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 No(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(N.errorForCode(k.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(k.ConnectionDraining)):this.protocol.reconnect()}}class No{constructor(e){h(this,"nc");this.nc=e}add(e){try{return new Ot(this.nc,e).start()}catch(t){return Promise.reject(t)}}client(e,t){return new lo(this.nc,e,t)}}class To{constructor(e,t,s){h(this,"bucket");h(this,"sm");h(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(es)||"PUT"}get length(){const e=this.sm.header.get(me.MessageSizeHdr)||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Mo{constructor(e,t,s){h(this,"bucket");h(this,"key");h(this,"sm");this.bucket=e,this.key=t,this.sm=s}get value(){return this.sm.data}get created(){return new Date(ws(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var e;return((e=this.sm.headers)==null?void 0:e.get(es))||"PUT"}get delta(){return this.sm.info.pending}get length(){var t;const e=((t=this.sm.headers)==null?void 0:t.get(me.MessageSizeHdr))||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class si extends un{constructor(t,s,i){super(t.nc,s,i);h(this,"js");h(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=Fe(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const n=this.info;n.config.name=Je.next(),n.ordered_consumer_sequence.delivery_seq=0,n.flow_control.heartbeat_count=0,n.flow_control.fc_count=0,n.flow_control.consumer_restarts++,n.deliver=s,n.config.deliver_subject=s,n.config.deliver_policy=te.StartSequence,n.config.opt_start_seq=t;const o={};o.stream_name=this.info.stream,o.config=n.config;const a=`${n.api.prefix}.CONSUMER.CREATE.${n.stream}`;this.js._request(a,o,{retries:-1}).then(f=>{const p=f,g=this.sub.info;g.last=p,this.info.config=p.config,this.info.name=p.name}).catch(f=>{const p=new N(`unable to recreate ordered consumer ${n.stream} at seq ${t}`,k.RequestError,f);this.sub.callback(p,{})})}_maybeSetupHbMonitoring(){var s,i;const t=((i=(s=this.info)==null?void 0:s.config)==null?void 0:i.idle_heartbeat)||0;t&&this._setupHbMonitoring(ws(t))}_setupHbMonitoring(t,s=0){const i={cancelAfter:0,maxOut:2};s&&(i.cancelAfter=s);const n=this.sub,o=a=>{var g,y,x,A;const f=Hi(409,`${Oe.IdleHeartbeatMissed}: ${a}`,this.sub.subject);if(!((g=this.info)==null?void 0:g.ordered))this.sub.callback(null,f);else{if(!this.js.nc.protocol.connected)return!1;const I=((x=(y=this.info)==null?void 0:y.ordered_consumer_sequence)==null?void 0:x.stream_seq)||0;return this._resetOrderedConsumer(I+1),(A=this.monitor)==null||A.restart(),!1}return!n.noIterator};this.monitor=new Ps(t,o,i)}_checkHbOrderConsumer(t){const s=t.headers.get(me.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const i=parseInt(t.headers.get(me.LastConsumerSeqHdr),10),n=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,i!==n.delivery_seq&&this._resetOrderedConsumer(n.stream_seq+1),!1}_checkOrderedConsumer(t){const s=this.info.ordered_consumer_sequence,i=t.info.streamSequence,n=t.info.deliverySequence;return n!=s.delivery_seq+1?(this._resetOrderedConsumer(s.stream_seq+1),!1):(s.delivery_seq=n,s.stream_seq=i,!0)}async destroy(){this.isClosed()||await this.drain();const t=this.sub.info,s=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.DELETE.${t.stream}.${s}`;await t.api._request(i)}async consumerInfo(){const t=this.sub.info,s=t.config.durable_name||t.name,i=`${t.api.prefix}.CONSUMER.INFO.${t.stream}.${s}`,n=await t.api._request(i);return t.last=n,n}}class Uo extends si{constructor(e,t,s){super(e,t,s)}pull(e={batch:1}){const{stream:t,config:s,name:i}=this.sub.info,n=s.durable_name??i,o={};if(o.batch=e.batch||1,o.no_wait=e.no_wait||!1,(e.max_bytes??0)>0){const p=this.js.nc.features.get(H.JS_PULL_MAX_BYTES);if(!p.ok)throw new Error(`max_bytes is only supported on servers ${p.min} or better`);o.max_bytes=e.max_bytes}let a=0;e.expires&&e.expires>0&&(a=e.expires,o.expires=W(a));let f=0;if(e.idle_heartbeat&&e.idle_heartbeat>0&&(f=e.idle_heartbeat,o.idle_heartbeat=W(f)),f&&a===0)throw new Error("idle_heartbeat requires expires");if(f>a)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),a&&f&&(this.monitor?this.monitor._change(f,a):this._setupHbMonitoring(f,a));const p=this.info.api,g=`${p.prefix}.CONSUMER.MSG.NEXT.${t}.${n}`,y=this.sub.subject;p.nc.publish(g,p.jc.encode(o),{reply:y})}}}function $o(r,e){return r?qo(e):Lo(e)}function Lo(r){return(e,t)=>e?[e,null]:(e=it(t),e?[e,null]:[null,jt(t,r)])}function qo(r){return(e,t)=>{if(e)return[e,null];const s=it(t);return s!==null?[ri(s),null]:[null,jt(t,r)]}}function ri(r){if(r!==null)switch(r.code){case k.JetStream404NoMessages:case k.JetStream408RequestTimeout:return null;case k.JetStream409:return Ji(r)?r:null;default:return r}return null}function Fo(r){r&&r.ack()}function Bo(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.deliveryCount=parseInt(e[6],10),t.redeliveryCount=t.deliveryCount,t.redelivered=t.deliveryCount>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 Do{constructor(e,t){h(this,"msg");h(this,"di");h(this,"didAck");h(this,"timeout");this.msg=e,this.didAck=!1,this.timeout=t}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=Bo(this.reply)),this.di}get redelivered(){return this.info.deliveryCount>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]===It[0]&&e[1]===It[1]&&e[2]===It[2]&&e[3]===It[3]}async ackAck(e){var s;e=e||{},e.timeout=e.timeout||this.timeout;const t=V();if(this.didAck)t.resolve(!1);else if(this.didAck=!0,this.msg.reply){const n=this.msg.publisher,o=!((s=n.options)!=null&&s.noAsyncTraces),a=new Nr(n.muxSubscriptions,this.msg.reply,{timeout:e.timeout},o);n.request(a);try{n.publish(this.msg.reply,Qr,{reply:`${n.muxSubscriptions.baseInbox}${a.token}`})}catch(f){a.cancel(f)}try{await Promise.race([a.timer,a.deferred]),t.resolve(!0)}catch(f){a.cancel(f),t.reject(f)}}else t.resolve(!1);return t}ack(){this.doAck(Qr)}nak(e){let t=So;e&&(t=Ss().encode(`-NAK ${JSON.stringify({delay:W(e)})}`)),this.doAck(t)}working(){this.doAck(It)}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=W(t.expires));const i=ke().encode(s),n=ct.concat(vo,Ao,i),o=e?{reply:e}:void 0;this.msg.respond(n,o)}term(e=""){let t=Eo;(e==null?void 0:e.length)>0&&(t=Ss().encode(`+TERM ${e}`)),this.doAck(t)}json(){return this.msg.json()}string(){return this.msg.string()}}const Ho="1.30.3",Jo="nats.ws";class Ko{constructor(){h(this,"version");h(this,"lang");h(this,"closeError");h(this,"connected");h(this,"done");h(this,"socket");h(this,"options");h(this,"socketClosed");h(this,"encrypted");h(this,"peeked");h(this,"yields");h(this,"signal");h(this,"closedNotification");this.version=Ho,this.lang=Jo,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=V(),this.closedNotification=V()}async connect(e,t){const s=V();if(t.tls)return s.reject(new N("tls",k.InvalidOption)),s;this.options=t;const i=e.src;if(t.wsFactory){const{socket:n,encrypted:o}=await t.wsFactory(e.src,t);this.socket=n,this.encrypted=o}else this.encrypted=i.indexOf("wss://")===0,this.socket=new WebSocket(i);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=n=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(n.data)),this.peeked){this.signal.resolve();return}const o=ct.concat(...this.yields),a=bn(o);if(a!==""){const f=ro.exec(a);if(!f){t.debug&&console.error("!!!",Dt(o)),s.reject(new Error("unexpected response from server"));return}try{const p=JSON.parse(f[1]);to(p,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(p){s.reject(p);return}}},this.socket.onclose=n=>{if(this.isDiscarded())return;this.socketClosed=!0;let o;this.done||(n.wasClean||(o=new Error(n.reason)),this._closed(o))},this.socket.onerror=n=>{if(this.isDiscarded())return;const o=n,a=new N(o.message,k.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 st(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(`> ${Dt(e[t])}`),yield e[t];if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=V())}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(!this.isDiscarded())try{this.socket.send(e.buffer),this.options.debug&&console.info(`< ${Dt(e)}`);return}catch(t){this.options.debug&&console.error(`!!! ${Dt(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 zo(r,e){/^(.*:\/\/)(.*)/.test(r)||(typeof e=="boolean"?r=`${e===!0?"https":"http"}://${r}`:r=`https://${r}`);let s=new URL(r);const i=s.protocol.toLowerCase();i==="ws:"&&(e=!1),i==="wss:"&&(e=!0),i!=="https:"&&i!=="http"&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2"),s=new URL(`http://${r}`));let n,o;const a=s.hostname,f=s.pathname,p=s.search||"";switch(i){case"http:":case"ws:":case"nats:":o=s.port||"80",n="ws:";break;case"https:":case"wss:":case"tls:":o=s.port||"443",n="wss:";break;default:o=s.port||e===!0?"443":"80",n=e===!0?"wss:":"ws:";break}return`${n}//${a}:${o}${f}${p}`}function Go(r={}){return ln({defaultPort:443,urlParseFn:zo,factory:()=>new Ko}),Vs.connect(r)}const Xe=ke();class Ws{constructor(e){h(this,"onStatusChange");h(this,"nc");h(this,"sessionId","");h(this,"userId","");h(this,"globalPrefix","");h(this,"resolveConnected",e=>{});h(this,"isConnected",new Promise(e=>this.resolveConnected=e));this.config=e}get url(){return this.config.natsUrl}async connect(e={}){var x;const{natsWsUrls:t,user:s,prefix:i,accessToken:n,sessionSeed:o}=e,a=t??[this.config.natsUrl],f=n??await this.config.auth.getAccessToken();if(!f)throw new Error("Please provide auth token");const p=o??await this.config.auth.getSessionSeed();if(!p)throw new Error("Please provide session seed");const g=Ss();this.nc=await Go({servers:a,authenticator:Yn(f,g.encode(p))});const y=s??await this.config.auth.getLastLoginData();if(!y)throw new Error("Please authenticate first by calling `auth` apis");this.userId=y.userId,this.sessionId=y.sessionId,this.globalPrefix=i??"",this.resolveConnected(!0),(x=this.onStatusChange)==null||x.call(this,!0),console.log("[nats] connected.",this.globalPrefix?`(prefix: ${this.globalPrefix})`:""),(async()=>{var A,I;for await(const T of this.nc.status())switch(T.type!==Ke.PingTimer&&console.log("[nats] connection status:",T.type),T.type){case Pe.Reconnect:(A=this.onStatusChange)==null||A.call(this,!0);break;case Pe.Disconnect:case Pe.Error:case Ke.Reconnecting:(I=this.onStatusChange)==null||I.call(this,!1);break}})()}async disconnect(){var e,t;await((e=this.nc)==null?void 0:e.drain()),await((t=this.nc)==null?void 0:t.close())}async publish(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");try{const s=this.buildSubject(e);console.debug("[nats]>>",s),this.nc.publish(s,Xe.encode(t))}catch(s){throw console.error("[nats] publish failed:",s),s}}async call(e,t,s){var a;if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=this.buildSubject(e);console.debug("[nats]>>",i);const n=await this.nc.request(i,Xe.encode(t),{timeout:(s==null?void 0:s.timeoutInMs)??5e3}),o=Xe.decode(n.data);if(o.error)throw new Error(o.error.message);if((a=o.payload)!=null&&a.errorData)throw new Error(o.payload.errorData.message);return o.data??o.payload}async on(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=(this.globalPrefix?`${this.globalPrefix}.`:"")+e+".>",n=this.nc.subscribe(i);return(async()=>{for await(const o of n)try{console.debug("[nats]<<",o.subject);const a=o.subject.split(".");if(this.globalPrefix&&a[0]!==this.globalPrefix){console.log("[nats]","Skipped - "+o.subject);continue}a[0]==="dev"&&a.shift();const f=a.slice(0,a.length-2).join("."),p=a[a.length-2],g=a[a.length-1],y=Xe.decode(o.data);t(y,{subject:f,userId:p,sessionId:g})}catch(a){console.error("[nats] subscribe error",a)}})(),()=>n.unsubscribe()}async handler(e,t){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");const i=(this.globalPrefix?`${this.globalPrefix}.`:"")+e+".>",n=this.nc.subscribe(i);return(async()=>{for await(const o of n)try{console.debug("[nats]<<",o.subject);const a=o.subject.split(".");if(this.globalPrefix&&a[0]!==this.globalPrefix){console.log("[nats]","Skipped - "+o.subject);continue}a[0]==="dev"&&a.shift();const f=a.slice(0,a.length-2).join("."),p=a[a.length-2],g=a[a.length-1],y=Xe.decode(o.data);try{const x=await t(y,{subject:f,userId:p,sessionId:g});o.reply&&o.respond(Xe.encode({data:x}))}catch(x){console.error("[nats] handle",x),o.reply&&o.respond(Xe.encode({error:{message:x.message}}))}}catch(a){console.error("[nats] handle",a),o.reply&&o.respond(Xe.encode({error:{message:a.message}}))}})(),()=>n.unsubscribe()}buildSubject(e){return[this.globalPrefix,e,this.userId,this.sessionId].filter(t=>t).join(".")}}class ii{async setItem(e,t){if(!t)return this.removeItem(e);localStorage.setItem(e,JSON.stringify(t))}async getItem(e){const t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async removeItem(e){localStorage.removeItem(e)}}function ni(r){const e=new Blob([r],{type:"audio/mpeg"}),t=URL.createObjectURL(e),s=new Audio;return s.src=t,s.onended=()=>{URL.revokeObjectURL(t)},s}class Vo{async getAudioBuffer(e,t,s){const i=[],n=crypto.randomUUID();return new Promise((o,a)=>{const f=new WebSocket(`${is.WSS_URL}?trustedclienttoken=${is.TRUSTED_CLIENT_TOKEN}&ConnectionId=${n}`);f.binaryType="arraybuffer";const p=Yo(e,t,s);f.addEventListener("open",()=>{const g=Wo();f.send(g);const y=`X-RequestId:${n}\r
30
30
  Content-Type:application/ssml+xml\r
31
31
  X-Timestamp:${new Date().toISOString()}Z\r
32
32
  Path:ssml\r