@jokio/sdk 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -5
- package/dist/jokio.sdk.umd.js +10 -10
- package/package-lock.json +1062 -0
- package/package.json +1 -1
- package/src/auth.service.ts +21 -8
- package/src/nats.service.ts +7 -5
- package/test/index.html +1 -1
- package/dist/auth.service.d.ts +0 -21
- package/dist/common/playAudioFromBuffer.d.ts +0 -1
- package/dist/crypto.service.d.ts +0 -9
- package/dist/index.d.ts +0 -18
- package/dist/index.html +0 -106
- package/dist/jokio.sdk.es.js +0 -8526
- package/dist/nats.service.d.ts +0 -45
- package/dist/tts.service.d.ts +0 -13
- package/dist/voicevoxTts.d.ts +0 -11
package/dist/jokio.sdk.umd.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
(function(me,Y){typeof exports=="object"&&typeof module<"u"?Y(exports):typeof define=="function"&&define.amd?define(["exports"],Y):(me=typeof globalThis<"u"?globalThis:me||self,Y(me["@jokio/sdk"]={}))})(this,function(me){"use strict";var Bo=Object.defineProperty;var Do=(me,Y,Me)=>Y in me?Bo(me,Y,{enumerable:!0,configurable:!0,writable:!0,value:Me}):me[Y]=Me;var h=(me,Y,Me)=>Do(me,typeof Y!="symbol"?Y+"":Y,Me);function Y(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 Me(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 ns(){return oi.stubThis((globalThis==null?void 0:globalThis.PublicKeyCredential)!==void 0&&typeof globalThis.PublicKeyCredential=="function")}const oi={stubThis:r=>r};function Xs(r){const{id:e}=r;return{...r,id:Me(e),transports:r.transports}}function Zs(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}class ce 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 ai({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 ce({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 ce({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 ce({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 ce({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 ce({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new ce({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 ce({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new ce({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(Zs(o)){if(t.rp.id!==o)return new ce({message:`The RP ID "${t.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ce({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 ce({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 ce({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 ci{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 Qs=new ci,hi=["cross-platform","platform"];function er(r){if(r&&!(hi.indexOf(r)<0))return r}async function ui(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(!ns())throw new Error("WebAuthn is not supported in this browser");const s={...e,challenge:Me(e.challenge),user:{...e.user,id:Me(e.user.id)},excludeCredentials:(I=e.excludeCredentials)==null?void 0:I.map(Xs)},i={};t&&(i.mediation="conditional"),i.publicKey=s,i.signal=Qs.createNewAbortSignal();let n;try{n=await navigator.credentials.create(i)}catch(T){throw ai({error:T,options:i})}if(!n)throw new Error("Registration was not completed");const{id:o,rawId:a,response:d,type:p}=n;let _;typeof d.getTransports=="function"&&(_=d.getTransports());let y;if(typeof d.getPublicKeyAlgorithm=="function")try{y=d.getPublicKeyAlgorithm()}catch(T){os("getPublicKeyAlgorithm()",T)}let x;if(typeof d.getPublicKey=="function")try{const T=d.getPublicKey();T!==null&&(x=Y(T))}catch(T){os("getPublicKey()",T)}let P;if(typeof d.getAuthenticatorData=="function")try{P=Y(d.getAuthenticatorData())}catch(T){os("getAuthenticatorData()",T)}return{id:o,rawId:Y(a),response:{attestationObject:Y(d.attestationObject),clientDataJSON:Y(d.clientDataJSON),transports:_,publicKeyAlgorithm:y,publicKey:x,authenticatorData:P},type:p,clientExtensionResults:n.getClientExtensionResults(),authenticatorAttachment:er(n.authenticatorAttachment)}}function os(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 li(){if(!ns())return as.stubThis(new Promise(e=>e(!1)));const r=globalThis.PublicKeyCredential;return(r==null?void 0:r.isConditionalMediationAvailable)===void 0?as.stubThis(new Promise(e=>e(!1))):as.stubThis(r.isConditionalMediationAvailable())}const as={stubThis:r=>r};function fi({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 ce({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new ce({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=globalThis.location.hostname;if(Zs(s)){if(t.rpId!==s)return new ce({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ce({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new ce({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 di(r){var P,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(!ns())throw new Error("WebAuthn is not supported in this browser");let i;((P=e.allowCredentials)==null?void 0:P.length)!==0&&(i=(I=e.allowCredentials)==null?void 0:I.map(Xs));const n={...e,challenge:Me(e.challenge),allowCredentials:i},o={};if(t){if(!await li())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=Qs.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(T){throw fi({error:T,options:o})}if(!a)throw new Error("Authentication was not completed");const{id:d,rawId:p,response:_,type:y}=a;let x;return _.userHandle&&(x=Y(_.userHandle)),{id:d,rawId:Y(p),response:{authenticatorData:Y(_.authenticatorData),clientDataJSON:Y(_.clientDataJSON),signature:Y(_.signature),userHandle:x},type:y,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:er(a.authenticatorAttachment)}}const ut="LAST_AUTH_DATA";class cs{constructor(e){this.config=e}async requestEmailLogin(e,t=location.href){return await fetch(this.config.authUrl+`/email-verification-request/${e}?returnUrl=${t}`,{credentials:"include"}).then(lt)}async completeEmailLogin(e,t){const s=await fetch(this.config.authUrl+`/email-verification-complete/${e}/${t}`,{credentials:"include"}).then(lt);return localStorage.setItem(ut,JSON.stringify(s)),s}async requestPasskeyLogin(e="",t=!1){var o;const s=await fetch(this.config.authUrl+`/webauth-challenge-request?registration=${e?"true":""}&displayName=${e}`,{credentials:"include"}).then(lt);let i;try{(o=s.user)!=null&&o.id?i=await ui({optionsJSON:s}):i=await di({optionsJSON:s})}catch(a){throw a.name==="InvalidStateError"?alert("Error: Authenticator was probably already registered by user"):alert(a.message),a}const n=await fetch(this.config.authUrl+`/webauth-challenge-complete?displayName=${e}&addAsAdditionalDevice=${t?"true":""}`,{method:"POST",body:JSON.stringify(i),headers:{"Content-Type":"application/json"},credentials:"include"}).then(lt);return localStorage.setItem(ut,JSON.stringify(n)),n}async guestSignIn(){const e=await fetch(this.config.authUrl+"/sign-out",{credentials:"include"}).then(lt);return localStorage.setItem(ut,JSON.stringify(e)),e}async clearLoginData(){localStorage.removeItem(ut)}getLastLoginData(){const e=localStorage.getItem(ut);if(!e)return null;try{return JSON.parse(e)||null}catch{return null}}}const lt=async r=>{const e=await r.json();if(!r.ok)throw new Error(e.message);return e},hs=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),tr=r=>new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16))),sr=r=>btoa(String.fromCharCode(...new Uint8Array(r))),pi=r=>Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer,mi=async r=>await crypto.subtle.digest("SHA-256",r),bi=new TextEncoder;class gi{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 sr(t)}async deriveAESKey(e,t){const s=pi(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 hs(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`${hs(new Uint8Array(n))}_${hs(s)}`}async decrypt(e,t){const s=e.split("_"),i=tr(s[0]).buffer,n=tr(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 mi(bi.encode(e).buffer);return sr(t)}}const be=new Uint8Array(0),Ge=new TextEncoder,ge=new TextDecoder;function _i(...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 ft(...r){const e=[];for(let t=0;t<r.length;t++)e.push(Ge.encode(r[t]));return e.length===0?be:e.length===1?e[0]:_i(...e)}function rr(r){return!r||r.length===0?"":ge.decode(r)}const ir="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",nr=36,yi=0xcfd41b9100000,or=33,wi=333,ar=22;function xi(r){for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*255)}function Si(r){var e;(e=globalThis==null?void 0:globalThis.crypto)!=null&&e.getRandomValues?globalThis.crypto.getRandomValues(r):xi(r)}class Ei{constructor(){h(this,"buf");h(this,"seq");h(this,"inc");h(this,"inited");this.buf=new Uint8Array(ar),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(Math.random()*yi),this.inc=Math.floor(Math.random()*(wi-or)+or)}setPre(){const e=new Uint8Array(12);Si(e);for(let t=0;t<12;t++){const s=e[t]%36;this.buf[t]=ir.charCodeAt(s)}}fillSeq(){let e=this.seq;for(let t=ar-1;t>=12;t--)this.buf[t]=ir.charCodeAt(e%nr),e=Math.floor(e/nr)}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 qe=new Ei;var Se;(function(r){r.Disconnect="disconnect",r.Reconnect="reconnect",r.Update="update",r.LDM="ldm",r.Error="error"})(Se||(Se={}));var Fe;(function(r){r.Reconnecting="reconnecting",r.PingTimer="pingTimer",r.StaleConnection="staleConnection",r.ClientInitiatedReconnect="client initiated reconnect"})(Fe||(Fe={}));var O;(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"})(O||(O={}));function vi(r){return typeof r.code=="string"}class cr{constructor(){h(this,"messages");this.messages=new Map,this.messages.set(O.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(O.BadJson,"Bad JSON"),this.messages.set(O.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return Ai.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}const Ai=new cr;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=cr.getMessage(t);return new N(i,t,s)}isAuthError(){return this.code===O.AuthenticationExpired||this.code===O.AuthorizationViolation||this.code===O.AccountExpired}isAuthTimeout(){return this.code===O.AuthenticationTimeout}isPermissionError(){return this.code===O.PermissionsViolation}isProtocolError(){return this.code===O.ProtocolError}isJetStreamError(){return this.api_error!==void 0}jsError(){return this.api_error?this.api_error:null}}var _e;(function(r){r[r.Exact=0]="Exact",r[r.CanonicalMIME=1]="CanonicalMIME",r[r.IgnoreCase=2]="IgnoreCase"})(_e||(_e={}));var Oe;(function(r){r.Timer="timer",r.Count="count",r.JitterTimer="jitterTimer",r.SentinelMsg="sentinelMsg"})(Oe||(Oe={}));var dt;(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"})(dt||(dt={}));const jt="Nats-Service-Error",Rt="Nats-Service-Error-Code";class Nt extends Error{constructor(t,s){super(s);h(this,"code");this.code=t}static isServiceError(t){return Nt.toServiceError(t)!==null}static toServiceError(t){var i,n;const s=((i=t==null?void 0:t.headers)==null?void 0:i.get(Rt))||"";if(s!==""){const o=parseInt(s)||400,a=((n=t==null?void 0:t.headers)==null?void 0:n.get(jt))||"";return new Nt(o,a.length?a:s)}return null}}function $e(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}.${qe.next()}`}const us="127.0.0.1";var Be;(function(r){r.PING="PING",r.STATS="STATS",r.INFO="INFO"})(Be||(Be={}));function Tt(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 Mt(r){return ge.decode(r).replace(/\n/g,"␊").replace(/\r/g,"␍")}function Ye(r,e=!0){const t=e?N.errorForCode(O.Timeout):null;let s,i;const n=new Promise((o,a)=>{s={cancel:()=>{i&&clearTimeout(i)}},i=setTimeout(()=>{a(t===null?N.errorForCode(O.Timeout):t)},r)});return Object.assign(n,s)}function Xe(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 z(){let r={};const e=new Promise((t,s)=>{r={resolve:t,reject:s}});return Object.assign(e,r)}function hr(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 Pi(r){return r===0?0:Math.floor(r/2+Math.random()*r)}function ls(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 Pi(t>e?r[e]:r[t])}}}function G(r){return r*1e6}function fs(r){return Math.floor(r/1e6)}function ur(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`,O.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 Ue(r=0,e=""){if(r===0&&e!==""||r>0&&e==="")throw new Error("setting status requires both code and description");return new De(r,e)}const ds="NATS/1.0";class De{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 De,i=ge.decode(e).split(`\r
|
|
2
|
+
`,e)}function li(){if(!ns())return as.stubThis(new Promise(e=>e(!1)));const r=globalThis.PublicKeyCredential;return(r==null?void 0:r.isConditionalMediationAvailable)===void 0?as.stubThis(new Promise(e=>e(!1))):as.stubThis(r.isConditionalMediationAvailable())}const as={stubThis:r=>r};function fi({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 ce({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new ce({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=globalThis.location.hostname;if(Zs(s)){if(t.rpId!==s)return new ce({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ce({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new ce({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 di(r){var P,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(!ns())throw new Error("WebAuthn is not supported in this browser");let i;((P=e.allowCredentials)==null?void 0:P.length)!==0&&(i=(I=e.allowCredentials)==null?void 0:I.map(Xs));const n={...e,challenge:Me(e.challenge),allowCredentials:i},o={};if(t){if(!await li())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=Qs.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(T){throw fi({error:T,options:o})}if(!a)throw new Error("Authentication was not completed");const{id:d,rawId:p,response:_,type:y}=a;let x;return _.userHandle&&(x=Y(_.userHandle)),{id:d,rawId:Y(p),response:{authenticatorData:Y(_.authenticatorData),clientDataJSON:Y(_.clientDataJSON),signature:Y(_.signature),userHandle:x},type:y,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:er(a.authenticatorAttachment)}}const ut="LAST_AUTH_DATA";class cs{constructor(e){this.config=e}async requestEmailLogin(e,t=location.href){return await fetch(this.config.authUrl+`/email-verification-request/${e}?returnUrl=${t}`,{credentials:"include"}).then(lt)}async completeEmailLogin(e,t){const s=await fetch(this.config.authUrl+`/email-verification-complete/${e}/${t}`,{credentials:"include"}).then(lt);return localStorage.setItem(ut,JSON.stringify(s)),s}async requestPasskeyLogin(e={}){var d;const{displayName:t="",isRegistration:s=!1,addAsAdditionalDevice:i=!1}=e,n=await fetch(this.config.authUrl+`/webauth-challenge-request?registration=${s?"true":""}&displayName=${t}`,{credentials:"include"}).then(lt);let o;try{(d=n.user)!=null&&d.id?o=await ui({optionsJSON:n}):o=await di({optionsJSON:n})}catch(p){throw p.name==="InvalidStateError"?alert("Error: Authenticator was probably already registered by user"):alert(p.message),p}const a=await fetch(this.config.authUrl+`/webauth-challenge-complete?displayName=${t}&addAsAdditionalDevice=${i?"true":""}`,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},credentials:"include"}).then(lt);return localStorage.setItem(ut,JSON.stringify(a)),a}async guestLogin(){const e=await fetch(this.config.authUrl+"/sign-out",{credentials:"include"}).then(lt);return localStorage.setItem(ut,JSON.stringify(e)),e}async clearLoginData(){localStorage.removeItem(ut)}getLastLoginData(){const e=localStorage.getItem(ut);if(!e)return null;try{return JSON.parse(e)||null}catch{return null}}}const lt=async r=>{const e=await r.json();if(!r.ok)throw new Error(e.message);return e},hs=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),tr=r=>new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16))),sr=r=>btoa(String.fromCharCode(...new Uint8Array(r))),pi=r=>Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer,mi=async r=>await crypto.subtle.digest("SHA-256",r),bi=new TextEncoder;class gi{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 sr(t)}async deriveAESKey(e,t){const s=pi(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 hs(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`${hs(new Uint8Array(n))}_${hs(s)}`}async decrypt(e,t){const s=e.split("_"),i=tr(s[0]).buffer,n=tr(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 mi(bi.encode(e).buffer);return sr(t)}}const be=new Uint8Array(0),Ge=new TextEncoder,ge=new TextDecoder;function _i(...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 ft(...r){const e=[];for(let t=0;t<r.length;t++)e.push(Ge.encode(r[t]));return e.length===0?be:e.length===1?e[0]:_i(...e)}function rr(r){return!r||r.length===0?"":ge.decode(r)}const ir="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",nr=36,yi=0xcfd41b9100000,or=33,wi=333,ar=22;function xi(r){for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*255)}function Si(r){var e;(e=globalThis==null?void 0:globalThis.crypto)!=null&&e.getRandomValues?globalThis.crypto.getRandomValues(r):xi(r)}class vi{constructor(){h(this,"buf");h(this,"seq");h(this,"inc");h(this,"inited");this.buf=new Uint8Array(ar),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(Math.random()*yi),this.inc=Math.floor(Math.random()*(wi-or)+or)}setPre(){const e=new Uint8Array(12);Si(e);for(let t=0;t<12;t++){const s=e[t]%36;this.buf[t]=ir.charCodeAt(s)}}fillSeq(){let e=this.seq;for(let t=ar-1;t>=12;t--)this.buf[t]=ir.charCodeAt(e%nr),e=Math.floor(e/nr)}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 qe=new vi;var Se;(function(r){r.Disconnect="disconnect",r.Reconnect="reconnect",r.Update="update",r.LDM="ldm",r.Error="error"})(Se||(Se={}));var Fe;(function(r){r.Reconnecting="reconnecting",r.PingTimer="pingTimer",r.StaleConnection="staleConnection",r.ClientInitiatedReconnect="client initiated reconnect"})(Fe||(Fe={}));var O;(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"})(O||(O={}));function Ei(r){return typeof r.code=="string"}class cr{constructor(){h(this,"messages");this.messages=new Map,this.messages.set(O.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(O.BadJson,"Bad JSON"),this.messages.set(O.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return Ai.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}const Ai=new cr;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=cr.getMessage(t);return new N(i,t,s)}isAuthError(){return this.code===O.AuthenticationExpired||this.code===O.AuthorizationViolation||this.code===O.AccountExpired}isAuthTimeout(){return this.code===O.AuthenticationTimeout}isPermissionError(){return this.code===O.PermissionsViolation}isProtocolError(){return this.code===O.ProtocolError}isJetStreamError(){return this.api_error!==void 0}jsError(){return this.api_error?this.api_error:null}}var _e;(function(r){r[r.Exact=0]="Exact",r[r.CanonicalMIME=1]="CanonicalMIME",r[r.IgnoreCase=2]="IgnoreCase"})(_e||(_e={}));var Oe;(function(r){r.Timer="timer",r.Count="count",r.JitterTimer="jitterTimer",r.SentinelMsg="sentinelMsg"})(Oe||(Oe={}));var dt;(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"})(dt||(dt={}));const jt="Nats-Service-Error",Rt="Nats-Service-Error-Code";class Nt extends Error{constructor(t,s){super(s);h(this,"code");this.code=t}static isServiceError(t){return Nt.toServiceError(t)!==null}static toServiceError(t){var i,n;const s=((i=t==null?void 0:t.headers)==null?void 0:i.get(Rt))||"";if(s!==""){const o=parseInt(s)||400,a=((n=t==null?void 0:t.headers)==null?void 0:n.get(jt))||"";return new Nt(o,a.length?a:s)}return null}}function $e(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}.${qe.next()}`}const us="127.0.0.1";var Be;(function(r){r.PING="PING",r.STATS="STATS",r.INFO="INFO"})(Be||(Be={}));function Tt(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 Mt(r){return ge.decode(r).replace(/\n/g,"␊").replace(/\r/g,"␍")}function Ye(r,e=!0){const t=e?N.errorForCode(O.Timeout):null;let s,i;const n=new Promise((o,a)=>{s={cancel:()=>{i&&clearTimeout(i)}},i=setTimeout(()=>{a(t===null?N.errorForCode(O.Timeout):t)},r)});return Object.assign(n,s)}function Xe(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 z(){let r={};const e=new Promise((t,s)=>{r={resolve:t,reject:s}});return Object.assign(e,r)}function hr(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 Pi(r){return r===0?0:Math.floor(r/2+Math.random()*r)}function ls(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 Pi(t>e?r[e]:r[t])}}}function G(r){return r*1e6}function fs(r){return Math.floor(r/1e6)}function ur(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`,O.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 Ue(r=0,e=""){if(r===0&&e!==""||r>0&&e==="")throw new Error("setting status requires both code and description");return new De(r,e)}const ds="NATS/1.0";class De{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 De,i=ge.decode(e).split(`\r
|
|
3
3
|
`),n=i[0];if(n!==ds){let o=n.replace(ds,"").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 d=o.slice(0,a),p=o.slice(a+1).trim();t.append(d,p)}}}),t}toString(){if(this.headers.size===0&&this._code===0)return"";let e=ds;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 Ge.encode(this.toString())}static validHeaderValue(e){if(/[\r\n]/.test(e))throw new N("invalid header value - \\r and \\n are not allowed.",O.BadHeader);return e.trim()}keys(){const e=[];for(const t of this.headers.keys())e.push(t);return e}findKeys(e,t=_e.Exact){const s=this.keys();switch(t){case _e.Exact:return s.filter(i=>i===e);case _e.CanonicalMIME:return e=ur(e),s.filter(i=>i===e);default:{const i=e.toLowerCase();return s.filter(n=>i===n.toLowerCase())}}}get(e,t=_e.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=_e.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=_e.Exact){return this.findKeys(e,t).length>0}set(e,t,s=_e.Exact){this.delete(e,s),this.append(e,t,s)}append(e,t,s=_e.Exact){const i=ur(e);s===_e.CanonicalMIME&&(e=i);const n=this.findKeys(e,s);e=n.length>0?n[0]:e;const o=De.validHeaderValue(t);let a=this.headers.get(e);a||(a=[],this.headers.set(e,a)),a.push(o)}values(e,t=_e.Exact){const s=[];return this.findKeys(e,t).forEach(n=>{const o=this.headers.get(n);o&&s.push(...o)}),s}delete(e,t=_e.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 De;for(const s in e)t.headers.set(s,e[s]);return t}}function lr(){return{encode(r){return Ge.encode(r)},decode(r){return ge.decode(r)}}}function
|
|
6
|
+
`}encode(){return Ge.encode(this.toString())}static validHeaderValue(e){if(/[\r\n]/.test(e))throw new N("invalid header value - \\r and \\n are not allowed.",O.BadHeader);return e.trim()}keys(){const e=[];for(const t of this.headers.keys())e.push(t);return e}findKeys(e,t=_e.Exact){const s=this.keys();switch(t){case _e.Exact:return s.filter(i=>i===e);case _e.CanonicalMIME:return e=ur(e),s.filter(i=>i===e);default:{const i=e.toLowerCase();return s.filter(n=>i===n.toLowerCase())}}}get(e,t=_e.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=_e.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=_e.Exact){return this.findKeys(e,t).length>0}set(e,t,s=_e.Exact){this.delete(e,s),this.append(e,t,s)}append(e,t,s=_e.Exact){const i=ur(e);s===_e.CanonicalMIME&&(e=i);const n=this.findKeys(e,s);e=n.length>0?n[0]:e;const o=De.validHeaderValue(t);let a=this.headers.get(e);a||(a=[],this.headers.set(e,a)),a.push(o)}values(e,t=_e.Exact){const s=[];return this.findKeys(e,t).forEach(n=>{const o=this.headers.get(n);o&&s.push(...o)}),s}delete(e,t=_e.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 De;for(const s in e)t.headers.set(s,e[s]);return t}}function lr(){return{encode(r){return Ge.encode(r)},decode(r){return ge.decode(r)}}}function ve(r){return{encode(e){try{return e===void 0&&(e=null),Ge.encode(JSON.stringify(e))}catch(t){throw N.errorForCode(O.BadJson,t)}},decode(e){try{return JSON.parse(ge.decode(e),r)}catch(t){throw N.errorForCode(O.BadJson,t)}}}}function fr(r){var e;return r&&r.data.length===0&&((e=r.headers)==null?void 0:e.code)===503?N.errorForCode(O.NoResponders):null}class ps{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=ge.decode(this._msg.subject),this._subject)}get reply(){return this._reply?this._reply:(this._reply=ge.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=De.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=be,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 ve(e).decode(this.data)}string(){return ge.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(ps,"jc");function Ze(r){return $t("durable",r)}function le(r){return $t("stream",r)}function $t(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 pt(r,e=""){if(e==="")throw Error(`${r} name required`);const t=Oi(e);if(t.length)throw new Error(`invalid ${r} name - ${r} name ${t}`)}function Oi(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 ms(r){if(r.data.length>0)return!1;const e=r.headers;return e?e.code>=100&&e.code<200:!1}function bs(r){var e;return ms(r)&&((e=r.headers)==null?void 0:e.description)==="Idle Heartbeat"}function ki(r,e,t){const s=Ue(r,e),i={hdr:1,sid:0,size:0},n=new ps(i,be,{});return n._headers=s,n._subject=t,n}function Qe(r){if(r.data.length!==0)return null;const e=r.headers;return e?dr(e.code,e.description):null}var ve;(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"})(ve||(ve={}));function Ci(r){return r.code!==O.JetStream409?!1:[ve.MaxBatchExceeded,ve.MaxExpiresExceeded,ve.MaxBytesExceeded,ve.MaxMessageSizeExceeded,ve.PushConsumer,ve.IdleHeartbeatMissed,ve.ConsumerDeleted].find(t=>r.message.indexOf(t)!==-1)!==void 0}function dr(r,e=""){if(r<300)return null;switch(e=e.toLowerCase(),r){case 404:return new N(e,O.JetStream404NoMessages);case 408:return new N(e,O.JetStream408RequestTimeout);case 409:{const t=e.startsWith(ve.IdleHeartbeatMissed)?O.JetStreamIdleHeartBeat:O.JetStream409;return new N(e,t)}case 503:return N.errorForCode(O.JetStreamNotEnabled,new Error(e));default:return e===""&&(e=O.Unknown),new N(e,`${r}`)}}class re{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=z(),this.yields=[],this.iterClosed=z(),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",O.ApiError);if(this.yielding)throw new N("already yielding",O.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=z())}}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 gs{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 _s;(function(r){r.Limits="limits",r.Interest="interest",r.Workqueue="workqueue"})(_s||(_s={}));var mt;(function(r){r.Old="old",r.New="new"})(mt||(mt={}));var ys;(function(r){r.File="file",r.Memory="memory"})(ys||(ys={}));var Z;(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"})(Z||(Z={}));var ie;(function(r){r.None="none",r.All="all",r.Explicit="explicit",r.NotSet=""})(ie||(ie={}));var et;(function(r){r.Instant="instant",r.Original="original"})(et||(et={}));var He;(function(r){r.None="none",r.S2="s2"})(He||(He={}));var Ut;(function(r){r.CreateOrUpdate="",r.Update="update",r.Create="create"})(Ut||(Ut={}));function Ii(r,e={}){return Object.assign({name:r,deliver_policy:Z.All,ack_policy:ie.Explicit,ack_wait:G(30*1e3),replay_policy:et.Instant},e)}var pr;(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"})(pr||(pr={}));var fe;(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"})(fe||(fe={}));var ke;(function(r){r.LastValue="",r.AllHistory="history",r.UpdatesOnly="updates"})(ke||(ke={}));var tt;(function(r){r.Stream="Nats-Stream",r.Sequence="Nats-Sequence",r.TimeStamp="Nats-Time-Stamp",r.Subject="Nats-Subject"})(tt||(tt={}));var mr;(function(r){r.Stream="Nats-Stream",r.Subject="Nats-Subject",r.Sequence="Nats-Sequence",r.LastSequence="Nats-Last-Sequence",r.Size="Nats-Msg-Size"})(mr||(mr={}));const ye="KV_";class ji{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=Ii("",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?ie.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 Ze(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=Z.StartSequence,this.config.opt_start_seq=e,this}startTime(e){return this.config.deliver_policy=Z.StartTime,this.config.opt_start_time=e.toISOString(),this}deliverAll(){return this.config.deliver_policy=Z.All,this}deliverLastPerSubject(){return this.config.deliver_policy=Z.LastPerSubject,this}deliverLast(){return this.config.deliver_policy=Z.Last,this}deliverNew(){return this.config.deliver_policy=Z.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=ie.None,this}ackAll(){return this.config.ack_policy=ie.All,this}ackExplicit(){return this.config.ack_policy=ie.Explicit,this}ackWait(e){return this.config.ack_wait=G(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=et.Instant,this}replayOriginal(){return this.config.replay_policy=et.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=G(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=G(e),this}maxPullBatch(e){return this.config.max_batch=e,this}maxPullRequestExpires(e){return this.config.max_expires=G(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 Je(r){return new ji(r)}function br(r){return typeof r.getOpts=="function"}class Ri{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 st{static encode(e){return st.toB64URLEncoding(Ri.encode(e))}static decode(e,t=!1){return st.decode(st.fromB64URLEncoding(e),t)}static toB64URLEncoding(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}static fromB64URLEncoding(e){return e.replace(/_/g,"/").replace(/-/g,"+")}}class rt{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=""),Ge.encode(e)}static toAscii(e){return ge.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 Ni(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 Ti=typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{},bt=Ti.performance||{};bt.now||bt.mozNow||bt.msNow||bt.oNow||bt.webkitNow;var gr={versions:{}},Mi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function $i(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 ws,Lt={exports:{}},_r={},yr=$i(Ni({__proto__:null,default:_r},[_r]));ws=Lt,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&&gr.versions&&gr.versions.node;i?t=Mi:s&&(t=self);var n=!t.JS_SHA256_NO_COMMON_JS&&ws.exports,o=!t.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",a="0123456789abcdef".split(""),d=[-2147483648,8388608,32768,128],p=[24,16,8,0],_=[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 P=function(w,j){return function(F){return new L(j,!0).update(F)[w]()}},I=function(w){var j=P("hex",w);i&&(j=T(j,w)),j.create=function(){return new L(w)},j.update=function(A){return j.create().update(A)};for(var F=0;F<y.length;++F){var R=y[F];j[R]=P(R,w)}return j},T=function(w,j){var F,R=yr,A=yr.Buffer,$=j?"sha224":"sha256";return F=A.from&&!t.JS_SHA256_NO_BUFFER_FROM?A.from:function(q){return new A(q)},function(q){if(typeof q=="string")return R.createHash($).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===A?R.createHash($).update(F(q)).digest("hex"):w(q)}},J=function(w,j){return function(F,R){return new X(F,j,!0).update(R)[w]()}},Q=function(w){var j=J("hex",w);j.create=function(A){return new X(A,w)},j.update=function(A,$){return j.create(A).update($)};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 X(w,j,F){var R,A=typeof w;if(A==="string"){var $,q=[],U=w.length,K=0;for(R=0;R<U;++R)($=w.charCodeAt(R))<128?q[K++]=$:$<2048?(q[K++]=192|$>>>6,q[K++]=128|63&$):$<55296||$>=57344?(q[K++]=224|$>>>12,q[K++]=128|$>>>6&63,q[K++]=128|63&$):($=65536+((1023&$)<<10|1023&w.charCodeAt(++R)),q[K++]=240|$>>>18,q[K++]=128|$>>>12&63,q[K++]=128|$>>>6&63,q[K++]=128|63&$);w=q}else{if(A!=="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 te=[],ne=[];for(R=0;R<64;++R){var se=w[R]||0;te[R]=92^se,ne[R]=54^se}L.call(this,j,F),this.update(ne),this.oKeyPad=te,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,A,$=0,q=w.length,U=this.blocks;$<q;){if(this.hashed&&(this.hashed=!1,U[0]=this.block,this.block=U[16]=U[1]=U[2]=U[3]=U[4]=U[5]=U[6]=U[7]=U[8]=U[9]=U[10]=U[11]=U[12]=U[13]=U[14]=U[15]=0),j)for(A=this.start;$<q&&A<64;++$)U[A>>>2]|=w[$]<<p[3&A++];else for(A=this.start;$<q&&A<64;++$)(R=w.charCodeAt($))<128?U[A>>>2]|=R<<p[3&A++]:R<2048?(U[A>>>2]|=(192|R>>>6)<<p[3&A++],U[A>>>2]|=(128|63&R)<<p[3&A++]):R<55296||R>=57344?(U[A>>>2]|=(224|R>>>12)<<p[3&A++],U[A>>>2]|=(128|R>>>6&63)<<p[3&A++],U[A>>>2]|=(128|63&R)<<p[3&A++]):(R=65536+((1023&R)<<10|1023&w.charCodeAt(++$)),U[A>>>2]|=(240|R>>>18)<<p[3&A++],U[A>>>2]|=(128|R>>>12&63)<<p[3&A++],U[A>>>2]|=(128|R>>>6&63)<<p[3&A++],U[A>>>2]|=(128|63&R)<<p[3&A++]);this.lastByteIndex=A,this.bytes+=A-this.start,A>=64?(this.block=U[16],this.start=A-64,this.hash(),this.hashed=!0):this.start=A}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]|=d[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,A,$,q,U,K,te=this.h0,ne=this.h1,se=this.h2,oe=this.h3,he=this.h4,ue=this.h5,V=this.h6,ee=this.h7,ae=this.blocks;for(w=16;w<64;++w)j=((A=ae[w-15])>>>7|A<<25)^(A>>>18|A<<14)^A>>>3,F=((A=ae[w-2])>>>17|A<<15)^(A>>>19|A<<13)^A>>>10,ae[w]=ae[w-16]+j+ae[w-7]+F|0;for(K=ne&se,w=0;w<64;w+=4)this.first?(this.is224?($=300032,ee=(A=ae[0]-1413257819)-150054599|0,oe=A+24177077|0):($=704751109,ee=(A=ae[0]-210244248)-1521486534|0,oe=A+143694565|0),this.first=!1):(j=(te>>>2|te<<30)^(te>>>13|te<<19)^(te>>>22|te<<10),R=($=te&ne)^te&se^K,ee=oe+(A=ee+(F=(he>>>6|he<<26)^(he>>>11|he<<21)^(he>>>25|he<<7))+(he&ue^~he&V)+_[w]+ae[w])|0,oe=A+(j+R)|0),j=(oe>>>2|oe<<30)^(oe>>>13|oe<<19)^(oe>>>22|oe<<10),R=(q=oe&te)^oe&ne^$,V=se+(A=V+(F=(ee>>>6|ee<<26)^(ee>>>11|ee<<21)^(ee>>>25|ee<<7))+(ee&he^~ee&ue)+_[w+1]+ae[w+1])|0,j=((se=A+(j+R)|0)>>>2|se<<30)^(se>>>13|se<<19)^(se>>>22|se<<10),R=(U=se&oe)^se&te^q,ue=ne+(A=ue+(F=(V>>>6|V<<26)^(V>>>11|V<<21)^(V>>>25|V<<7))+(V&ee^~V&he)+_[w+2]+ae[w+2])|0,j=((ne=A+(j+R)|0)>>>2|ne<<30)^(ne>>>13|ne<<19)^(ne>>>22|ne<<10),R=(K=ne&se)^ne&oe^U,he=te+(A=he+(F=(ue>>>6|ue<<26)^(ue>>>11|ue<<21)^(ue>>>25|ue<<7))+(ue&V^~ue&ee)+_[w+3]+ae[w+3])|0,te=A+(j+R)|0,this.chromeBugWorkAround=!0;this.h0=this.h0+te|0,this.h1=this.h1+ne|0,this.h2=this.h2+se|0,this.h3=this.h3+oe|0,this.h4=this.h4+he|0,this.h5=this.h5+ue|0,this.h6=this.h6+V|0,this.h7=this.h7+ee|0},L.prototype.hex=function(){this.finalize();var w=this.h0,j=this.h1,F=this.h2,R=this.h3,A=this.h4,$=this.h5,q=this.h6,U=this.h7,K=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[A>>>28&15]+a[A>>>24&15]+a[A>>>20&15]+a[A>>>16&15]+a[A>>>12&15]+a[A>>>8&15]+a[A>>>4&15]+a[15&A]+a[$>>>28&15]+a[$>>>24&15]+a[$>>>20&15]+a[$>>>16&15]+a[$>>>12&15]+a[$>>>8&15]+a[$>>>4&15]+a[15&$]+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||(K+=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]),K},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,A=this.h4,$=this.h5,q=this.h6,U=this.h7,K=[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,A>>>24&255,A>>>16&255,A>>>8&255,255&A,$>>>24&255,$>>>16&255,$>>>8&255,255&$,q>>>24&255,q>>>16&255,q>>>8&255,255&q];return this.is224||K.push(U>>>24&255,U>>>16&255,U>>>8&255,255&U),K},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},X.prototype=new L,X.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 pe=I();pe.sha256=pe,pe.sha224=I(!0),pe.sha256.hmac=Q(),pe.sha224.hmac=Q(!0),n?ws.exports=pe:(t.sha256=pe.sha256,t.sha224=pe.sha224)}(),Lt.exports,Lt.exports.sha224;var wr=Lt.exports.sha256;function xs(r){return Di(r)}function Ui(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 Li(r){return/^[A-Za-z0-9\-_]*(={0,2})?$/.test(r)||/^[A-Za-z0-9+/]*(={0,2})?$/.test(r)}function qi(r){return Ui(r)?"hex":Li(r)?"b64":""}function Fi(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 Bi(r){r=r.replace(/-/g,"+"),r=r.replace(/_/g,"/");const e=atob(r);return Uint8Array.from(e,t=>t.charCodeAt(0))}function Di(r){switch(qi(r)){case"hex":return Fi(r);case"b64":return Bi(r)}return null}function Hi(r,e){const t=typeof r=="string"?xs(r):r,s=typeof e=="string"?xs(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 xr{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=qe.next(),s&&(this.ctx=new Error)}}class Ji extends xr{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=z(),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 pt(r,e=""){if(e==="")throw Error(`${r} name required`);const t=Oi(e);if(t.length)throw new Error(`invalid ${r} name - ${r} name ${t}`)}function Oi(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 ms(r){if(r.data.length>0)return!1;const e=r.headers;return e?e.code>=100&&e.code<200:!1}function bs(r){var e;return ms(r)&&((e=r.headers)==null?void 0:e.description)==="Idle Heartbeat"}function ki(r,e,t){const s=Ue(r,e),i={hdr:1,sid:0,size:0},n=new ps(i,be,{});return n._headers=s,n._subject=t,n}function Qe(r){if(r.data.length!==0)return null;const e=r.headers;return e?dr(e.code,e.description):null}var Ee;(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"})(Ee||(Ee={}));function Ci(r){return r.code!==O.JetStream409?!1:[Ee.MaxBatchExceeded,Ee.MaxExpiresExceeded,Ee.MaxBytesExceeded,Ee.MaxMessageSizeExceeded,Ee.PushConsumer,Ee.IdleHeartbeatMissed,Ee.ConsumerDeleted].find(t=>r.message.indexOf(t)!==-1)!==void 0}function dr(r,e=""){if(r<300)return null;switch(e=e.toLowerCase(),r){case 404:return new N(e,O.JetStream404NoMessages);case 408:return new N(e,O.JetStream408RequestTimeout);case 409:{const t=e.startsWith(Ee.IdleHeartbeatMissed)?O.JetStreamIdleHeartBeat:O.JetStream409;return new N(e,t)}case 503:return N.errorForCode(O.JetStreamNotEnabled,new Error(e));default:return e===""&&(e=O.Unknown),new N(e,`${r}`)}}class re{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=z(),this.yields=[],this.iterClosed=z(),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",O.ApiError);if(this.yielding)throw new N("already yielding",O.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=z())}}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 gs{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 _s;(function(r){r.Limits="limits",r.Interest="interest",r.Workqueue="workqueue"})(_s||(_s={}));var mt;(function(r){r.Old="old",r.New="new"})(mt||(mt={}));var ys;(function(r){r.File="file",r.Memory="memory"})(ys||(ys={}));var Z;(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"})(Z||(Z={}));var ie;(function(r){r.None="none",r.All="all",r.Explicit="explicit",r.NotSet=""})(ie||(ie={}));var et;(function(r){r.Instant="instant",r.Original="original"})(et||(et={}));var He;(function(r){r.None="none",r.S2="s2"})(He||(He={}));var Ut;(function(r){r.CreateOrUpdate="",r.Update="update",r.Create="create"})(Ut||(Ut={}));function Ii(r,e={}){return Object.assign({name:r,deliver_policy:Z.All,ack_policy:ie.Explicit,ack_wait:G(30*1e3),replay_policy:et.Instant},e)}var pr;(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"})(pr||(pr={}));var fe;(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"})(fe||(fe={}));var ke;(function(r){r.LastValue="",r.AllHistory="history",r.UpdatesOnly="updates"})(ke||(ke={}));var tt;(function(r){r.Stream="Nats-Stream",r.Sequence="Nats-Sequence",r.TimeStamp="Nats-Time-Stamp",r.Subject="Nats-Subject"})(tt||(tt={}));var mr;(function(r){r.Stream="Nats-Stream",r.Subject="Nats-Subject",r.Sequence="Nats-Sequence",r.LastSequence="Nats-Last-Sequence",r.Size="Nats-Msg-Size"})(mr||(mr={}));const ye="KV_";class ji{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=Ii("",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?ie.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 Ze(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=Z.StartSequence,this.config.opt_start_seq=e,this}startTime(e){return this.config.deliver_policy=Z.StartTime,this.config.opt_start_time=e.toISOString(),this}deliverAll(){return this.config.deliver_policy=Z.All,this}deliverLastPerSubject(){return this.config.deliver_policy=Z.LastPerSubject,this}deliverLast(){return this.config.deliver_policy=Z.Last,this}deliverNew(){return this.config.deliver_policy=Z.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=ie.None,this}ackAll(){return this.config.ack_policy=ie.All,this}ackExplicit(){return this.config.ack_policy=ie.Explicit,this}ackWait(e){return this.config.ack_wait=G(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=et.Instant,this}replayOriginal(){return this.config.replay_policy=et.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=G(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=G(e),this}maxPullBatch(e){return this.config.max_batch=e,this}maxPullRequestExpires(e){return this.config.max_expires=G(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 Je(r){return new ji(r)}function br(r){return typeof r.getOpts=="function"}class Ri{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 st{static encode(e){return st.toB64URLEncoding(Ri.encode(e))}static decode(e,t=!1){return st.decode(st.fromB64URLEncoding(e),t)}static toB64URLEncoding(e){return e.replace(/\+/g,"-").replace(/\//g,"_")}static fromB64URLEncoding(e){return e.replace(/_/g,"/").replace(/-/g,"+")}}class rt{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=""),Ge.encode(e)}static toAscii(e){return ge.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 Ni(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 Ti=typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{},bt=Ti.performance||{};bt.now||bt.mozNow||bt.msNow||bt.oNow||bt.webkitNow;var gr={versions:{}},Mi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function $i(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 ws,Lt={exports:{}},_r={},yr=$i(Ni({__proto__:null,default:_r},[_r]));ws=Lt,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&&gr.versions&&gr.versions.node;i?t=Mi:s&&(t=self);var n=!t.JS_SHA256_NO_COMMON_JS&&ws.exports,o=!t.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",a="0123456789abcdef".split(""),d=[-2147483648,8388608,32768,128],p=[24,16,8,0],_=[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 P=function(w,j){return function(F){return new L(j,!0).update(F)[w]()}},I=function(w){var j=P("hex",w);i&&(j=T(j,w)),j.create=function(){return new L(w)},j.update=function(A){return j.create().update(A)};for(var F=0;F<y.length;++F){var R=y[F];j[R]=P(R,w)}return j},T=function(w,j){var F,R=yr,A=yr.Buffer,$=j?"sha224":"sha256";return F=A.from&&!t.JS_SHA256_NO_BUFFER_FROM?A.from:function(q){return new A(q)},function(q){if(typeof q=="string")return R.createHash($).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===A?R.createHash($).update(F(q)).digest("hex"):w(q)}},J=function(w,j){return function(F,R){return new X(F,j,!0).update(R)[w]()}},Q=function(w){var j=J("hex",w);j.create=function(A){return new X(A,w)},j.update=function(A,$){return j.create(A).update($)};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 X(w,j,F){var R,A=typeof w;if(A==="string"){var $,q=[],U=w.length,K=0;for(R=0;R<U;++R)($=w.charCodeAt(R))<128?q[K++]=$:$<2048?(q[K++]=192|$>>>6,q[K++]=128|63&$):$<55296||$>=57344?(q[K++]=224|$>>>12,q[K++]=128|$>>>6&63,q[K++]=128|63&$):($=65536+((1023&$)<<10|1023&w.charCodeAt(++R)),q[K++]=240|$>>>18,q[K++]=128|$>>>12&63,q[K++]=128|$>>>6&63,q[K++]=128|63&$);w=q}else{if(A!=="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 te=[],ne=[];for(R=0;R<64;++R){var se=w[R]||0;te[R]=92^se,ne[R]=54^se}L.call(this,j,F),this.update(ne),this.oKeyPad=te,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,A,$=0,q=w.length,U=this.blocks;$<q;){if(this.hashed&&(this.hashed=!1,U[0]=this.block,this.block=U[16]=U[1]=U[2]=U[3]=U[4]=U[5]=U[6]=U[7]=U[8]=U[9]=U[10]=U[11]=U[12]=U[13]=U[14]=U[15]=0),j)for(A=this.start;$<q&&A<64;++$)U[A>>>2]|=w[$]<<p[3&A++];else for(A=this.start;$<q&&A<64;++$)(R=w.charCodeAt($))<128?U[A>>>2]|=R<<p[3&A++]:R<2048?(U[A>>>2]|=(192|R>>>6)<<p[3&A++],U[A>>>2]|=(128|63&R)<<p[3&A++]):R<55296||R>=57344?(U[A>>>2]|=(224|R>>>12)<<p[3&A++],U[A>>>2]|=(128|R>>>6&63)<<p[3&A++],U[A>>>2]|=(128|63&R)<<p[3&A++]):(R=65536+((1023&R)<<10|1023&w.charCodeAt(++$)),U[A>>>2]|=(240|R>>>18)<<p[3&A++],U[A>>>2]|=(128|R>>>12&63)<<p[3&A++],U[A>>>2]|=(128|R>>>6&63)<<p[3&A++],U[A>>>2]|=(128|63&R)<<p[3&A++]);this.lastByteIndex=A,this.bytes+=A-this.start,A>=64?(this.block=U[16],this.start=A-64,this.hash(),this.hashed=!0):this.start=A}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]|=d[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,A,$,q,U,K,te=this.h0,ne=this.h1,se=this.h2,oe=this.h3,he=this.h4,ue=this.h5,V=this.h6,ee=this.h7,ae=this.blocks;for(w=16;w<64;++w)j=((A=ae[w-15])>>>7|A<<25)^(A>>>18|A<<14)^A>>>3,F=((A=ae[w-2])>>>17|A<<15)^(A>>>19|A<<13)^A>>>10,ae[w]=ae[w-16]+j+ae[w-7]+F|0;for(K=ne&se,w=0;w<64;w+=4)this.first?(this.is224?($=300032,ee=(A=ae[0]-1413257819)-150054599|0,oe=A+24177077|0):($=704751109,ee=(A=ae[0]-210244248)-1521486534|0,oe=A+143694565|0),this.first=!1):(j=(te>>>2|te<<30)^(te>>>13|te<<19)^(te>>>22|te<<10),R=($=te&ne)^te&se^K,ee=oe+(A=ee+(F=(he>>>6|he<<26)^(he>>>11|he<<21)^(he>>>25|he<<7))+(he&ue^~he&V)+_[w]+ae[w])|0,oe=A+(j+R)|0),j=(oe>>>2|oe<<30)^(oe>>>13|oe<<19)^(oe>>>22|oe<<10),R=(q=oe&te)^oe&ne^$,V=se+(A=V+(F=(ee>>>6|ee<<26)^(ee>>>11|ee<<21)^(ee>>>25|ee<<7))+(ee&he^~ee&ue)+_[w+1]+ae[w+1])|0,j=((se=A+(j+R)|0)>>>2|se<<30)^(se>>>13|se<<19)^(se>>>22|se<<10),R=(U=se&oe)^se&te^q,ue=ne+(A=ue+(F=(V>>>6|V<<26)^(V>>>11|V<<21)^(V>>>25|V<<7))+(V&ee^~V&he)+_[w+2]+ae[w+2])|0,j=((ne=A+(j+R)|0)>>>2|ne<<30)^(ne>>>13|ne<<19)^(ne>>>22|ne<<10),R=(K=ne&se)^ne&oe^U,he=te+(A=he+(F=(ue>>>6|ue<<26)^(ue>>>11|ue<<21)^(ue>>>25|ue<<7))+(ue&V^~ue&ee)+_[w+3]+ae[w+3])|0,te=A+(j+R)|0,this.chromeBugWorkAround=!0;this.h0=this.h0+te|0,this.h1=this.h1+ne|0,this.h2=this.h2+se|0,this.h3=this.h3+oe|0,this.h4=this.h4+he|0,this.h5=this.h5+ue|0,this.h6=this.h6+V|0,this.h7=this.h7+ee|0},L.prototype.hex=function(){this.finalize();var w=this.h0,j=this.h1,F=this.h2,R=this.h3,A=this.h4,$=this.h5,q=this.h6,U=this.h7,K=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[A>>>28&15]+a[A>>>24&15]+a[A>>>20&15]+a[A>>>16&15]+a[A>>>12&15]+a[A>>>8&15]+a[A>>>4&15]+a[15&A]+a[$>>>28&15]+a[$>>>24&15]+a[$>>>20&15]+a[$>>>16&15]+a[$>>>12&15]+a[$>>>8&15]+a[$>>>4&15]+a[15&$]+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||(K+=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]),K},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,A=this.h4,$=this.h5,q=this.h6,U=this.h7,K=[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,A>>>24&255,A>>>16&255,A>>>8&255,255&A,$>>>24&255,$>>>16&255,$>>>8&255,255&$,q>>>24&255,q>>>16&255,q>>>8&255,255&q];return this.is224||K.push(U>>>24&255,U>>>16&255,U>>>8&255,255&U),K},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},X.prototype=new L,X.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 pe=I();pe.sha256=pe,pe.sha224=I(!0),pe.sha256.hmac=Q(),pe.sha224.hmac=Q(!0),n?ws.exports=pe:(t.sha256=pe.sha256,t.sha224=pe.sha224)}(),Lt.exports,Lt.exports.sha224;var wr=Lt.exports.sha256;function xs(r){return Di(r)}function Ui(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 Li(r){return/^[A-Za-z0-9\-_]*(={0,2})?$/.test(r)||/^[A-Za-z0-9+/]*(={0,2})?$/.test(r)}function qi(r){return Ui(r)?"hex":Li(r)?"b64":""}function Fi(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 Bi(r){r=r.replace(/-/g,"+"),r=r.replace(/_/g,"/");const e=atob(r);return Uint8Array.from(e,t=>t.charCodeAt(0))}function Di(r){switch(qi(r)){case"hex":return Fi(r);case"b64":return Bi(r)}return null}function Hi(r,e){const t=typeof r=="string"?xs(r):r,s=typeof e=="string"?xs(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 xr{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=qe.next(),s&&(this.ctx=new Error)}}class Ji extends xr{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=z(),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
10
|
${this.ctx.stack}`),this.cancel(t)):(this.callback(null,s),this.opts.strategy===Oe.Count&&(this.max--,this.max===0&&this.cancel()),this.opts.strategy===Oe.JitterTimer&&(clearTimeout(this.timer),this.timer=setTimeout(()=>{this.cancel()},this.opts.jitter||300)),this.opts.strategy===Oe.SentinelMsg&&s&&s.data.length===0&&this.cancel())}}class Sr extends xr{constructor(t,s,i={timeout:1e3},n=!0){super(t,s,n);h(this,"deferred");h(this,"timer");this.deferred=z(),this.timer=Ye(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(O.Cancelled))}}const zi="$JS.API";function Gi(r){return r=r||{},r.domain&&(r.apiPrefix=`$JS.${r.domain}.API`,delete r.domain),Tt({apiPrefix:zi,timeout:5e3},r)}class gt{constructor(e,t){h(this,"nc");h(this,"opts");h(this,"prefix");h(this,"timeout");h(this,"jc");this.nc=e,this.opts=Gi(t),this._parseOpts(),this.prefix=this.opts.apiPrefix,this.timeout=this.opts.timeout,this.jc=
|
|
13
|
-
`,Bt=rt.fromAscii(Ft),Xi=new Uint8Array(Bt)[0],Zi=new Uint8Array(Bt)[1];function Qi(r){for(let e=0;e<r.length;e++){const t=e+1;if(r.byteLength>t&&r[e]===Xi&&r[t]===Zi)return t+1}return 0}function en(r){const e=Qi(r);if(e>0){const s=new Uint8Array(r).slice(0,e);return ge.decode(s)}return""}const tn=4,vr=48,sn=65,rn=97;function nn(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 As(r){return on(r)!==void 0}function on(r){for(let e=0;e<r.length;e++)switch(r[e]){case".":return Ar(r);case":":return an(r)}}function Ar(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}=cn(r);if(!n||s>255)return;r=r.substring(i),e[t]=s}return nn(e[0],e[1],e[2],e[3])}function an(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}=hn(r);if(!o||i>65535)return;if(n<r.length&&r[n]==="."){if(t<0&&s!=12||s+4>16)return;const a=Ar(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+=tn;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 cn(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)-vr),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 hn(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)-vr;else if(97<=r.charCodeAt(t)&&r.charCodeAt(t)<=102)e*=16,e+=r.charCodeAt(t)-rn+10;else if(65<=r.charCodeAt(t)&&r.charCodeAt(t)<=70)e*=16,e+=r.charCodeAt(t)-sn+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 un(r){return r.indexOf("[")!==-1||r.indexOf("::")!==-1?!1:r.indexOf(".")!==-1||r.split(":").length<=2}function Ps(r){return!un(r)}function ln(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 fn(r){r=r.trim(),r.match(/^(.*:\/\/)(.*)/m)&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2")),r=ln(r),Ps(r)&&r.indexOf("[")===-1&&(r=`[${r}]`);const e=Ps(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 yt{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=fn(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(As(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}://${Ps(i)?"["+i+"]":i}`);o.port=`${this.port}`;const a=new yt(o.host,!1);a.tlsName=this.hostname,t.push(a)}}return e.randomize&&hr(t),this.resolves=t,t}}class dn{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=Es();e&&(e.forEach(i=>{i=s?s(i):i,this.servers.push(new yt(i))}),this.randomize&&(this.servers=hr(this.servers))),this.servers.length===0&&this.addServer(`${us}:${Er()}`,!1),this.currentServer=this.servers[0]}clear(){this.servers.length=0}updateTLSName(){const e=this.getCurrentServer();As(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=Es();e=s?s(e):e;const i=new yt(e,t);As(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=Es(),o=new Map;e.connect_urls&&e.connect_urls.length>0&&e.connect_urls.forEach(d=>{d=n?n(d,t):d;const p=new yt(d,!0);o.set(d,p)});const a=[];return this.servers.forEach((d,p)=>{const _=d.listen;d.gossiped&&this.currentServer.listen!==_&&o.get(_)===void 0&&a.push(p),o.delete(_)}),a.reverse(),a.forEach(d=>{const p=this.servers.splice(d,1);i=i.concat(p[0].listen)}),o.forEach((d,p)=>{this.servers.push(d),s.push(p)}),{added:s,deleted:i}}}class pn{constructor(){h(this,"baseInbox");h(this,"reqs");this.reqs=new Map}size(){return this.reqs.size}init(e){return this.baseInbox=`${$e(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=fr(t)),i.resolver(e,t))}}}close(){const e=N.errorForCode(O.Timeout);this.reqs.forEach(t=>{t.resolver(e,{})})}}class mn{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:Fe.PingTimer,data:`${this.pendings.length+1}`}),this.pendings.length===this.maxOut){this.cancel(!0);return}const e=z();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 bn extends Error{constructor(e){super(e),this.name="AssertionError"}}function gn(r,e="Assertion failed."){if(!r)throw new bn(e)}const Pr=32*1024,Os=2**32-2;function Dt(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 ks{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){gn(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=Dt(this._buf.subarray(this._off),e);return this._off+=t,t}writeByte(e){return this.write(Uint8Array.of(e))}writeString(e){return this.write(Ge.encode(e))}write(e){const t=this._grow(e.byteLength);return Dt(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)Dt(this._buf.subarray(this._off),this._buf);else{if(i+e>Os)throw new Error("The buffer cannot be grown beyond the maximum size.");{const n=new Uint8Array(Math.min(2*i+e,Os));Dt(this._buf.subarray(this._off),n),this._buf=n}}return this._off=0,this._reslice(Math.min(t+e,Os)),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(Pr);for(;;){const i=this.capacity-this.length<Pr,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 de;(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"})(de||(de={}));function Or(){const r={};return r.sid=-1,r.hdr=-1,r.size=-1,r}const _n=48;class kr{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=k.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 k.OP_START:switch(s){case C.M:case C.m:this.state=k.OP_M,this.hdr=-1,this.ma=Or();break;case C.H:case C.h:this.state=k.OP_H,this.hdr=0,this.ma=Or();break;case C.P:case C.p:this.state=k.OP_P;break;case C.PLUS:this.state=k.OP_PLUS;break;case C.MINUS:this.state=k.OP_MINUS;break;case C.I:case C.i:this.state=k.OP_I;break;default:throw this.fail(e.subarray(t))}break;case k.OP_H:switch(s){case C.M:case C.m:this.state=k.OP_M;break;default:throw this.fail(e.subarray(t))}break;case k.OP_M:switch(s){case C.S:case C.s:this.state=k.OP_MS;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MS:switch(s){case C.G:case C.g:this.state=k.OP_MSG;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MSG:switch(s){case C.SPACE:case C.TAB:this.state=k.OP_MSG_SPC;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MSG_SPC:switch(s){case C.SPACE:case C.TAB:continue;default:this.state=k.MSG_ARG,this.as=t}break;case k.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=k.MSG_PAYLOAD,t=this.as+this.ma.size-1;break}default:this.argBuf&&this.argBuf.writeByte(s)}break;case k.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){const i=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:de.MSG,msg:this.ma,data:i}),this.argBuf=void 0,this.msgBuf=void 0,this.state=k.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:de.MSG,msg:this.ma,data:e.subarray(this.as,t)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=k.MSG_END);break;case k.MSG_END:switch(s){case C.NL:this.drop=0,this.as=t+1,this.state=k.OP_START;break;default:continue}break;case k.OP_PLUS:switch(s){case C.O:case C.o:this.state=k.OP_PLUS_O;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PLUS_O:switch(s){case C.K:case C.k:this.state=k.OP_PLUS_OK;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PLUS_OK:switch(s){case C.NL:this.dispatcher.push({kind:de.OK}),this.drop=0,this.state=k.OP_START;break}break;case k.OP_MINUS:switch(s){case C.E:case C.e:this.state=k.OP_MINUS_E;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MINUS_E:switch(s){case C.R:case C.r:this.state=k.OP_MINUS_ER;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MINUS_ER:switch(s){case C.R:case C.r:this.state=k.OP_MINUS_ERR;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MINUS_ERR:switch(s){case C.SPACE:case C.TAB:this.state=k.OP_MINUS_ERR_SPC;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MINUS_ERR_SPC:switch(s){case C.SPACE:case C.TAB:continue;default:this.state=k.MINUS_ERR_ARG,this.as=t}break;case k.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:de.ERR,data:i}),this.drop=0,this.as=t+1,this.state=k.OP_START;break}default:this.argBuf&&this.argBuf.write(Uint8Array.of(s))}break;case k.OP_P:switch(s){case C.I:case C.i:this.state=k.OP_PI;break;case C.O:case C.o:this.state=k.OP_PO;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PO:switch(s){case C.N:case C.n:this.state=k.OP_PON;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PON:switch(s){case C.G:case C.g:this.state=k.OP_PONG;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PONG:switch(s){case C.NL:this.dispatcher.push({kind:de.PONG}),this.drop=0,this.state=k.OP_START;break}break;case k.OP_PI:switch(s){case C.N:case C.n:this.state=k.OP_PIN;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PIN:switch(s){case C.G:case C.g:this.state=k.OP_PING;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PING:switch(s){case C.NL:this.dispatcher.push({kind:de.PING}),this.drop=0,this.state=k.OP_START;break}break;case k.OP_I:switch(s){case C.N:case C.n:this.state=k.OP_IN;break;default:throw this.fail(e.subarray(t))}break;case k.OP_IN:switch(s){case C.F:case C.f:this.state=k.OP_INF;break;default:throw this.fail(e.subarray(t))}break;case k.OP_INF:switch(s){case C.O:case C.o:this.state=k.OP_INFO;break;default:throw this.fail(e.subarray(t))}break;case k.OP_INFO:switch(s){case C.SPACE:case C.TAB:this.state=k.OP_INFO_SPC;break;default:throw this.fail(e.subarray(t))}break;case k.OP_INFO_SPC:switch(s){case C.SPACE:case C.TAB:continue;default:this.state=k.INFO_ARG,this.as=t}break;case k.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:de.INFO,data:i}),this.drop=0,this.as=t+1,this.state=k.OP_START;break}default:this.argBuf&&this.argBuf.writeByte(s)}break;default:throw this.fail(e.subarray(t))}}(this.state===k.MSG_ARG||this.state===k.MINUS_ERR_ARG||this.state===k.INFO_ARG)&&!this.argBuf&&(this.argBuf=new ks(e.subarray(this.as,t-this.drop))),this.state===k.MSG_PAYLOAD&&!this.msgBuf&&(this.argBuf||this.cloneMsgArg(),this.msgBuf=new ks(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 ks(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}: ${ge.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]-_n)}return t}}var k;(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"})(k||(k={}));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]),d=t([56129,1]),p=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),_=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]),P=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],f=c[l+4]<<24|c[l+5]<<16|c[l+6]<<8|c[l+7];return new e(u,f)}function Q(c,l,u){var f;for(f=0;f<4;f++)c[l+f]=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 X(c,l,u,f,m){var b,E=0;for(b=0;b<m;b++)E|=c[l+b]^u[f+b];return(1&E-1>>>8)-1}function pe(c,l,u,f){return X(c,l,u,f,16)}function w(c,l,u,f){return X(c,l,u,f,32)}function j(c,l,u,f,m){var b=new Uint32Array(16),E=new Uint32Array(16),v=new Uint32Array(16),g=new Uint32Array(4),S,M,D;for(S=0;S<4;S++)E[5*S]=T(f,4*S),E[1+S]=T(u,4*S),E[6+S]=T(l,4*S),E[11+S]=T(u,16+4*S);for(S=0;S<16;S++)v[S]=E[S];for(S=0;S<20;S++){for(M=0;M<4;M++){for(D=0;D<4;D++)g[D]=E[(5*M+4*D)%16];for(g[1]^=I(g[0]+g[3]|0,7),g[2]^=I(g[1]+g[0]|0,9),g[3]^=I(g[2]+g[1]|0,13),g[0]^=I(g[3]+g[2]|0,18),D=0;D<4;D++)b[4*M+(M+D)%4]=g[D]}for(D=0;D<16;D++)E[D]=b[D]}if(m){for(S=0;S<16;S++)E[S]=E[S]+v[S]|0;for(S=0;S<4;S++)E[5*S]=E[5*S]-T(f,4*S)|0,E[6+S]=E[6+S]-T(l,4*S)|0;for(S=0;S<4;S++)Q(c,4*S,E[5*S]),Q(c,16+4*S,E[6+S])}else for(S=0;S<16;S++)Q(c,4*S,E[S]+v[S]|0)}function F(c,l,u,f){return j(c,l,u,f,!1),0}function R(c,l,u,f){return j(c,l,u,f,!0),0}var A=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function $(c,l,u,f,m,b,E){var v=new Uint8Array(16),g=new Uint8Array(64),S,M;if(!m)return 0;for(M=0;M<16;M++)v[M]=0;for(M=0;M<8;M++)v[M]=b[M];for(;m>=64;){for(F(g,v,E,A),M=0;M<64;M++)c[l+M]=(u?u[f+M]:0)^g[M];for(S=1,M=8;M<16;M++)S=S+(v[M]&255)|0,v[M]=S&255,S>>>=8;m-=64,l+=64,u&&(f+=64)}if(m>0)for(F(g,v,E,A),M=0;M<m;M++)c[l+M]=(u?u[f+M]:0)^g[M];return 0}function q(c,l,u,f,m){return $(c,l,null,0,u,f,m)}function U(c,l,u,f,m){var b=new Uint8Array(32);return R(b,f,m,A),q(c,l,u,f.subarray(16),b)}function K(c,l,u,f,m,b,E){var v=new Uint8Array(32);return R(v,b,E,A),$(c,l,u,f,m,b.subarray(16),v)}function te(c,l){var u,f=0;for(u=0;u<17;u++)f=f+(c[u]+l[u]|0)|0,c[u]=f&255,f>>>=8}var ne=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]);function se(c,l,u,f,m,b){var E,v,g,S,M=new Uint32Array(17),D=new Uint32Array(17),W=new Uint32Array(17),je=new Uint32Array(17),ht=new Uint32Array(17);for(g=0;g<17;g++)D[g]=W[g]=0;for(g=0;g<16;g++)D[g]=b[g];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(g=0;g<17;g++)je[g]=0;for(g=0;g<16&&g<m;++g)je[g]=u[f+g];for(je[g]=1,f+=g,m-=g,te(W,je),v=0;v<17;v++)for(M[v]=0,g=0;g<17;g++)M[v]=M[v]+W[g]*(g<=v?D[v-g]:320*D[v+17-g]|0)|0|0;for(v=0;v<17;v++)W[v]=M[v];for(S=0,g=0;g<16;g++)S=S+W[g]|0,W[g]=S&255,S>>>=8;for(S=S+W[16]|0,W[16]=S&3,S=5*(S>>>2)|0,g=0;g<16;g++)S=S+W[g]|0,W[g]=S&255,S>>>=8;S=S+W[16]|0,W[16]=S}for(g=0;g<17;g++)ht[g]=W[g];for(te(W,ne),E=-(W[16]>>>7)|0,g=0;g<17;g++)W[g]^=E&(ht[g]^W[g]);for(g=0;g<16;g++)je[g]=b[g+16];for(je[16]=0,te(W,je),g=0;g<16;g++)c[l+g]=W[g];return 0}function oe(c,l,u,f,m,b){var E=new Uint8Array(16);return se(E,0,u,f,m,b),pe(c,l,E,0)}function he(c,l,u,f,m){var b;if(u<32)return-1;for(K(c,0,l,0,u,f,m),se(c,16,c,32,u-32,c),b=0;b<16;b++)c[b]=0;return 0}function ue(c,l,u,f,m){var b,E=new Uint8Array(32);if(u<32||(U(E,0,32,f,m),oe(l,16,l,32,u-32,E)!==0))return-1;for(K(c,0,l,0,u,f,m),b=0;b<32;b++)c[b]=0;return 0}function V(c,l){var u;for(u=0;u<16;u++)c[u]=l[u]|0}function ee(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 ae(c,l,u){for(var f,m=~(u-1),b=0;b<16;b++)f=m&(c[b]^l[b]),c[b]^=f,l[b]^=f}function ot(c,l){var u,f,m,b=t(),E=t();for(u=0;u<16;u++)E[u]=l[u];for(ee(E),ee(E),ee(E),f=0;f<2;f++){for(b[0]=E[0]-65517,u=1;u<15;u++)b[u]=E[u]-65535-(b[u-1]>>16&1),b[u-1]&=65535;b[15]=E[15]-32767-(b[14]>>16&1),m=b[15]>>16&1,b[14]&=65535,ae(E,b,1-m)}for(u=0;u<16;u++)c[2*u]=E[u]&255,c[2*u+1]=E[u]>>8}function Kr(c,l){var u=new Uint8Array(32),f=new Uint8Array(32);return ot(u,c),ot(f,l),w(u,0,f,0)}function Vr(c){var l=new Uint8Array(32);return ot(l,c),l[0]&1}function Fs(c,l){var u;for(u=0;u<16;u++)c[u]=l[2*u]+(l[2*u+1]<<8);c[15]&=32767}function Ce(c,l,u){var f;for(f=0;f<16;f++)c[f]=l[f]+u[f]|0}function Ie(c,l,u){var f;for(f=0;f<16;f++)c[f]=l[f]-u[f]|0}function B(c,l,u){var f,m,b=new Float64Array(31);for(f=0;f<31;f++)b[f]=0;for(f=0;f<16;f++)for(m=0;m<16;m++)b[f+m]+=l[f]*u[m];for(f=0;f<15;f++)b[f]+=38*b[f+16];for(f=0;f<16;f++)c[f]=b[f];ee(c),ee(c)}function Pe(c,l){B(c,l,l)}function Wr(c,l){var u=t(),f;for(f=0;f<16;f++)u[f]=l[f];for(f=253;f>=0;f--)Pe(u,u),f!==2&&f!==4&&B(u,u,l);for(f=0;f<16;f++)c[f]=u[f]}function Yr(c,l){var u=t(),f;for(f=0;f<16;f++)u[f]=l[f];for(f=250;f>=0;f--)Pe(u,u),f!==1&&B(u,u,l);for(f=0;f<16;f++)c[f]=u[f]}function Yt(c,l,u){var f=new Uint8Array(32),m=new Float64Array(80),b,E,v=t(),g=t(),S=t(),M=t(),D=t(),W=t();for(E=0;E<31;E++)f[E]=l[E];for(f[31]=l[31]&127|64,f[0]&=248,Fs(m,u),E=0;E<16;E++)g[E]=m[E],M[E]=v[E]=S[E]=0;for(v[0]=M[0]=1,E=254;E>=0;--E)b=f[E>>>3]>>>(E&7)&1,ae(v,g,b),ae(S,M,b),Ce(D,v,S),Ie(v,v,S),Ce(S,g,M),Ie(g,g,M),Pe(M,D),Pe(W,v),B(v,S,v),B(S,g,D),Ce(D,v,S),Ie(v,v,S),Pe(g,v),Ie(S,M,W),B(v,S,d),Ce(v,v,M),B(S,S,v),B(v,M,W),B(M,g,m),Pe(g,D),ae(v,g,b),ae(S,M,b);for(E=0;E<16;E++)m[E+16]=v[E],m[E+32]=S[E],m[E+48]=g[E],m[E+64]=M[E];var je=m.subarray(32),ht=m.subarray(16);return Wr(je,je),B(ht,ht,je),ot(c,ht),0}function Xt(c,l){return Yt(c,l,n)}function Xr(c,l){return s(l,32),Xt(c,l)}function Zt(c,l,u){var f=new Uint8Array(32);return Yt(f,u,l),R(c,i,f,A)}var Zr=he,Po=ue;function Oo(c,l,u,f,m,b){var E=new Uint8Array(32);return Zt(E,m,b),Zr(c,l,u,f,E)}function ko(c,l,u,f,m,b){var E=new Uint8Array(32);return Zt(E,m,b),Po(c,l,u,f,E)}function Pt(){var c=0,l=0,u=0,f=0,m=65535,b,E,v;for(v=0;v<arguments.length;v++)b=arguments[v].lo,E=arguments[v].hi,c+=b&m,l+=b>>>16,u+=E&m,f+=E>>>16;return l+=c>>>16,u+=l>>>16,f+=u>>>16,new e(u&m|f<<16,c&m|l<<16)}function Qr(c,l){return new e(c.hi>>>l,c.lo>>>l|c.hi<<32-l)}function Qt(){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 Te(c,l){var u,f,m=32-l;return l<32?(u=c.hi>>>l|c.lo<<m,f=c.lo>>>l|c.hi<<m):l<64&&(u=c.lo>>>l|c.hi<<m,f=c.hi>>>l|c.lo<<m),new e(u,f)}function Co(c,l,u){var f=c.hi&l.hi^~c.hi&u.hi,m=c.lo&l.lo^~c.lo&u.lo;return new e(f,m)}function Io(c,l,u){var f=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(f,m)}function jo(c){return Qt(Te(c,28),Te(c,34),Te(c,39))}function Ro(c){return Qt(Te(c,14),Te(c,18),Te(c,41))}function No(c){return Qt(Te(c,1),Te(c,8),Qr(c,7))}function To(c){return Qt(Te(c,19),Te(c,61),Qr(c,6))}var Mo=[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 ei(c,l,u){var f=[],m=[],b=[],E=[],v,g,S;for(g=0;g<8;g++)f[g]=b[g]=J(c,8*g);for(var M=0;u>=128;){for(g=0;g<16;g++)E[g]=J(l,8*g+M);for(g=0;g<80;g++){for(S=0;S<8;S++)m[S]=b[S];for(v=Pt(b[7],Ro(b[4]),Co(b[4],b[5],b[6]),Mo[g],E[g%16]),m[7]=Pt(v,jo(b[0]),Io(b[0],b[1],b[2])),m[3]=Pt(m[3],v),S=0;S<8;S++)b[(S+1)%8]=m[S];if(g%16===15)for(S=0;S<16;S++)E[S]=Pt(E[S],E[(S+9)%16],No(E[(S+1)%16]),To(E[(S+14)%16]))}for(g=0;g<8;g++)b[g]=Pt(b[g],f[g]),f[g]=b[g];M+=128,u-=128}for(g=0;g<8;g++)L(c,8*g,f[g]);return u}var $o=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 Ve(c,l,u){var f=new Uint8Array(64),m=new Uint8Array(256),b,E=u;for(b=0;b<64;b++)f[b]=$o[b];for(ei(f,l,u),u%=128,b=0;b<256;b++)m[b]=0;for(b=0;b<u;b++)m[b]=l[E-u+b];for(m[u]=128,u=256-128*(u<112?1:0),m[u-9]=0,L(m,u-8,new e(E/536870912|0,E<<3)),ei(f,m,u),b=0;b<64;b++)c[b]=f[b];return 0}function es(c,l){var u=t(),f=t(),m=t(),b=t(),E=t(),v=t(),g=t(),S=t(),M=t();Ie(u,c[1],c[0]),Ie(M,l[1],l[0]),B(u,u,M),Ce(f,c[0],c[1]),Ce(M,l[0],l[1]),B(f,f,M),B(m,c[3],l[3]),B(m,m,_),B(b,c[2],l[2]),Ce(b,b,b),Ie(E,f,u),Ie(v,b,m),Ce(g,b,m),Ce(S,f,u),B(c[0],E,v),B(c[1],S,g),B(c[2],g,v),B(c[3],E,S)}function ti(c,l,u){var f;for(f=0;f<4;f++)ae(c[f],l[f],u)}function Bs(c,l){var u=t(),f=t(),m=t();Wr(m,l[2]),B(u,l[0],m),B(f,l[1],m),ot(c,f),c[31]^=Vr(u)<<7}function Ds(c,l,u){var f,m;for(V(c[0],o),V(c[1],a),V(c[2],a),V(c[3],o),m=255;m>=0;--m)f=u[m/8|0]>>(m&7)&1,ti(c,l,f),es(l,c),es(c,c),ti(c,l,f)}function ts(c,l){var u=[t(),t(),t(),t()];V(u[0],y),V(u[1],x),V(u[2],a),B(u[3],y,x),Ds(c,u,l)}function Hs(c,l,u){var f=new Uint8Array(64),m=[t(),t(),t(),t()],b;for(u||s(l,32),Ve(f,l,32),f[0]&=248,f[31]&=127,f[31]|=64,ts(m,f),Bs(c,m),b=0;b<32;b++)l[b+32]=c[b];return 0}var ss=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 Js(c,l){var u,f,m,b;for(f=63;f>=32;--f){for(u=0,m=f-32,b=f-12;m<b;++m)l[m]+=u-16*l[f]*ss[m-(f-32)],u=Math.floor((l[m]+128)/256),l[m]-=u*256;l[m]+=u,l[f]=0}for(u=0,m=0;m<32;m++)l[m]+=u-(l[31]>>4)*ss[m],u=l[m]>>8,l[m]&=255;for(m=0;m<32;m++)l[m]-=u*ss[m];for(f=0;f<32;f++)l[f+1]+=l[f]>>8,c[f]=l[f]&255}function zs(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;Js(c,l)}function si(c,l,u,f){var m=new Uint8Array(64),b=new Uint8Array(64),E=new Uint8Array(64),v,g,S=new Float64Array(64),M=[t(),t(),t(),t()];Ve(m,f,32),m[0]&=248,m[31]&=127,m[31]|=64;var D=u+64;for(v=0;v<u;v++)c[64+v]=l[v];for(v=0;v<32;v++)c[32+v]=m[32+v];for(Ve(E,c.subarray(32),u+32),zs(E),ts(M,E),Bs(c,M),v=32;v<64;v++)c[v]=f[v];for(Ve(b,c,u+64),zs(b),v=0;v<64;v++)S[v]=0;for(v=0;v<32;v++)S[v]=E[v];for(v=0;v<32;v++)for(g=0;g<32;g++)S[v+g]+=b[v]*m[g];return Js(c.subarray(32),S),D}function Uo(c,l){var u=t(),f=t(),m=t(),b=t(),E=t(),v=t(),g=t();return V(c[2],a),Fs(c[1],l),Pe(m,c[1]),B(b,m,p),Ie(m,m,c[2]),Ce(b,c[2],b),Pe(E,b),Pe(v,E),B(g,v,E),B(u,g,m),B(u,u,b),Yr(u,u),B(u,u,m),B(u,u,b),B(u,u,b),B(c[0],u,b),Pe(f,c[0]),B(f,f,b),Kr(f,m)&&B(c[0],c[0],P),Pe(f,c[0]),B(f,f,b),Kr(f,m)?-1:(Vr(c[0])===l[31]>>7&&Ie(c[0],o,c[0]),B(c[3],c[0],c[1]),0)}function Gs(c,l,u,f){var m,b=new Uint8Array(32),E=new Uint8Array(64),v=[t(),t(),t(),t()],g=[t(),t(),t(),t()];if(u<64||Uo(g,f))return-1;for(m=0;m<u;m++)c[m]=l[m];for(m=0;m<32;m++)c[m+32]=f[m];if(Ve(E,c,u),zs(E),Ds(v,g,E),ts(g,l.subarray(32)),es(v,g),Bs(b,v),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 Ks=32,rs=24,Ot=32,at=16,kt=32,is=32,Ct=32,It=32,Vs=32,ri=rs,Lo=Ot,qo=at,Le=64,We=32,ct=64,Ws=32,Ys=64;r.lowlevel={crypto_core_hsalsa20:R,crypto_stream_xor:K,crypto_stream:U,crypto_stream_salsa20_xor:$,crypto_stream_salsa20:q,crypto_onetimeauth:se,crypto_onetimeauth_verify:oe,crypto_verify_16:pe,crypto_verify_32:w,crypto_secretbox:he,crypto_secretbox_open:ue,crypto_scalarmult:Yt,crypto_scalarmult_base:Xt,crypto_box_beforenm:Zt,crypto_box_afternm:Zr,crypto_box:Oo,crypto_box_open:ko,crypto_box_keypair:Xr,crypto_hash:Ve,crypto_sign:si,crypto_sign_keypair:Hs,crypto_sign_open:Gs,crypto_secretbox_KEYBYTES:Ks,crypto_secretbox_NONCEBYTES:rs,crypto_secretbox_ZEROBYTES:Ot,crypto_secretbox_BOXZEROBYTES:at,crypto_scalarmult_BYTES:kt,crypto_scalarmult_SCALARBYTES:is,crypto_box_PUBLICKEYBYTES:Ct,crypto_box_SECRETKEYBYTES:It,crypto_box_BEFORENMBYTES:Vs,crypto_box_NONCEBYTES:ri,crypto_box_ZEROBYTES:Lo,crypto_box_BOXZEROBYTES:qo,crypto_sign_BYTES:Le,crypto_sign_PUBLICKEYBYTES:We,crypto_sign_SECRETKEYBYTES:ct,crypto_sign_SEEDBYTES:Ws,crypto_hash_BYTES:Ys,gf:t,D:p,L:ss,pack25519:ot,unpack25519:Fs,M:B,A:Ce,S:Pe,Z:Ie,pow2523:Yr,add:es,set25519:V,modL:Js,scalarmult:Ds,scalarbase:ts};function ii(c,l){if(c.length!==Ks)throw new Error("bad key size");if(l.length!==rs)throw new Error("bad nonce size")}function Fo(c,l){if(c.length!==Ct)throw new Error("bad public key size");if(l.length!==It)throw new Error("bad secret key size")}function xe(){for(var c=0;c<arguments.length;c++)if(!(arguments[c]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function ni(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){xe(c,l,u),ii(u,l);for(var f=new Uint8Array(Ot+c.length),m=new Uint8Array(f.length),b=0;b<c.length;b++)f[b+Ot]=c[b];return he(m,f,f.length,l,u),m.subarray(at)},r.secretbox.open=function(c,l,u){xe(c,l,u),ii(u,l);for(var f=new Uint8Array(at+c.length),m=new Uint8Array(f.length),b=0;b<c.length;b++)f[b+at]=c[b];return f.length<32||ue(m,f,f.length,l,u)!==0?null:m.subarray(Ot)},r.secretbox.keyLength=Ks,r.secretbox.nonceLength=rs,r.secretbox.overheadLength=at,r.scalarMult=function(c,l){if(xe(c,l),c.length!==is)throw new Error("bad n size");if(l.length!==kt)throw new Error("bad p size");var u=new Uint8Array(kt);return Yt(u,c,l),u},r.scalarMult.base=function(c){if(xe(c),c.length!==is)throw new Error("bad n size");var l=new Uint8Array(kt);return Xt(l,c),l},r.scalarMult.scalarLength=is,r.scalarMult.groupElementLength=kt,r.box=function(c,l,u,f){var m=r.box.before(u,f);return r.secretbox(c,l,m)},r.box.before=function(c,l){xe(c,l),Fo(c,l);var u=new Uint8Array(Vs);return Zt(u,c,l),u},r.box.after=r.secretbox,r.box.open=function(c,l,u,f){var m=r.box.before(u,f);return r.secretbox.open(c,l,m)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var c=new Uint8Array(Ct),l=new Uint8Array(It);return Xr(c,l),{publicKey:c,secretKey:l}},r.box.keyPair.fromSecretKey=function(c){if(xe(c),c.length!==It)throw new Error("bad secret key size");var l=new Uint8Array(Ct);return Xt(l,c),{publicKey:l,secretKey:new Uint8Array(c)}},r.box.publicKeyLength=Ct,r.box.secretKeyLength=It,r.box.sharedKeyLength=Vs,r.box.nonceLength=ri,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(c,l){if(xe(c,l),l.length!==ct)throw new Error("bad secret key size");var u=new Uint8Array(Le+c.length);return si(u,c,c.length,l),u},r.sign.open=function(c,l){if(xe(c,l),l.length!==We)throw new Error("bad public key size");var u=new Uint8Array(c.length),f=Gs(u,c,c.length,l);if(f<0)return null;for(var m=new Uint8Array(f),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),f=new Uint8Array(Le),m=0;m<f.length;m++)f[m]=u[m];return f},r.sign.detached.verify=function(c,l,u){if(xe(c,l,u),l.length!==Le)throw new Error("bad signature size");if(u.length!==We)throw new Error("bad public key size");var f=new Uint8Array(Le+c.length),m=new Uint8Array(Le+c.length),b;for(b=0;b<Le;b++)f[b]=l[b];for(b=0;b<c.length;b++)f[b+Le]=c[b];return Gs(m,f,f.length,u)>=0},r.sign.keyPair=function(){var c=new Uint8Array(We),l=new Uint8Array(ct);return Hs(c,l),{publicKey:c,secretKey:l}},r.sign.keyPair.fromSecretKey=function(c){if(xe(c),c.length!==ct)throw new Error("bad secret key size");for(var l=new Uint8Array(We),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(xe(c),c.length!==Ws)throw new Error("bad seed size");for(var l=new Uint8Array(We),u=new Uint8Array(ct),f=0;f<32;f++)u[f]=c[f];return Hs(l,u,!0),{publicKey:l,secretKey:u}},r.sign.publicKeyLength=We,r.sign.secretKeyLength=ct,r.sign.seedLength=Ws,r.sign.signatureLength=Le,r.hash=function(c){xe(c);var l=new Uint8Array(Ys);return Ve(l,c,c.length),l},r.hash.hashLength=Ys,r.verify=function(c,l){return xe(c,l),c.length===0||l.length===0||c.length!==l.length?!1:X(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,f){var m,b=new Uint8Array(f);for(m=0;m<f;m+=l)c.getRandomValues(b.subarray(m,m+Math.min(f-m,l)));for(m=0;m<f;m++)u[m]=b[m];ni(b)})}else typeof require<"u"&&(c=require("crypto"),c&&c.randomBytes&&r.setPRNG(function(u,f){var m,b=c.randomBytes(f);for(m=0;m<f;m++)u[m]=b[m];ni(b)}))}()}(typeof module<"u"&&module.exports?module.exports:globalThis.nacl=globalThis.nacl||{});const Ht=typeof module<"u"&&module.exports?module.exports:globalThis.nacl;Ht.sign.keyPair.fromSeed,Ht.sign.detached,Ht.sign.detached.verify,Ht.randomBytes;var Cr;(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"})(Cr||(Cr={}));var Ir;(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"})(Ir||(Ir={}));function yn(r){return e=>{let t={};return r.forEach(s=>{const i=s(e)||{};t=Object.assign(t,i)}),t}}function wn(){return()=>{}}function xn(r,e){return()=>{const t=typeof r=="function"?r():r,s=typeof e=="function"?e():e;return{user:t,pass:s}}}function Sn(r){return()=>({auth_token:typeof r=="function"?r():r})}const jr=2*60*1e3,En=2,Rr=2*1e3;function vn(){return{maxPingOut:2,maxReconnectAttempts:10,noRandomize:!1,pedantic:!1,pingInterval:jr,reconnect:!0,reconnectJitter:100,reconnectJitterTLS:1e3,reconnectTimeWait:Rr,tls:void 0,verbose:!1,waitOnFirstConnect:!1,ignoreAuthErrorAbort:!1}}function An(r){const e=[];return typeof r.authenticator=="function"&&e.push(r.authenticator),Array.isArray(r.authenticator)&&e.push(...r.authenticator),r.token&&e.push(Sn(r.token)),r.user&&e.push(xn(r.user,r.pass)),e.length===0?wn():yn(e)}function Pn(r){const e=`${us}:${Er()}`;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",O.InvalidOption);r.servers.length===0&&r.port&&(r.servers=[`${us}:${r.port}`]),r.servers&&r.servers.length===0&&(r.servers=[e]);const t=Tt(vn(),r);if(t.authenticator=An(t),["reconnectDelayHandler","authenticator"].forEach(s=>{if(t[s]&&typeof t[s]!="function")throw new N(`${s} option should be a function`,O.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{$e(t.inboxPrefix)}catch(s){throw new N(s.message,O.ApiError)}if(t.resolve===void 0&&(t.resolve=typeof vs()=="function"),t.resolve&&typeof vs()!="function")throw new N("'resolve' is not supported on this client",O.InvalidOption);return t}function On(r,e){const{proto:t,tls_required:s,tls_available:i}=r;if((t===void 0||t<1)&&e.noEcho)throw new N("noEcho",O.ServerOptionNotAvailable);const n=s||i||!1;if(e.tls&&!n)throw new N("tls",O.ServerOptionNotAvailable)}const kn=1024*32,Cn=/^INFO\s+([^\r\n]+)\r\n/i,In=ft(`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(O.Cancelled))}}const zi="$JS.API";function Gi(r){return r=r||{},r.domain&&(r.apiPrefix=`$JS.${r.domain}.API`,delete r.domain),Tt({apiPrefix:zi,timeout:5e3},r)}class gt{constructor(e,t){h(this,"nc");h(this,"opts");h(this,"prefix");h(this,"timeout");h(this,"jc");this.nc=e,this.opts=Gi(t),this._parseOpts(),this.prefix=this.opts.apiPrefix,this.timeout=this.opts.timeout,this.jc=ve()}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=be;t&&(i=this.jc.encode(t));let{retries:n}=s;n=n||1,n=n===-1?Number.MAX_SAFE_INTEGER:n;const o=ls();for(let a=0;a<n;a++)try{const d=await this.nc.request(e,i,s);return this.parseJsResponse(d)}catch(d){const p=d;if((p.code==="503"||p.code===O.Timeout)&&a+1<n)await Xe(o.backoff(a));else throw d}}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=dr(s.error.code,s.error.description);if(i!==null)throw i.api_error=s.error,i}return t}}class _t{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 Ke(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 Ss(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 Ki{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=Ke(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:Ss(this.server,Ke(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=Ke(e)),Ss(this.server,e)>=0}}class qt extends gt{constructor(e,t){super(e,t)}async add(e,t,s=Ut.Create){if(le(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&&Ze(i.config.durable_name);const n=this.nc;let{min:o,ok:a}=n.features.get(H.JS_NEW_CONSUMER_CREATE_API);const d=t.name===""?void 0:t.name;if(d&&!a)throw new Error(`consumer 'name' requires server ${o}`);if(d)try{$t("name",d)}catch(x){const P=x.message,I=P.indexOf("cannot contain");throw I!==-1?new Error(`consumer 'name' ${P.substring(I)}`):x}let p,_="";if(Array.isArray(t.filter_subjects)){const{min:x,ok:P}=n.features.get(H.JS_MULTIPLE_CONSUMER_FILTER);if(!P)throw new Error(`consumer 'filter_subjects' requires server ${x}`);a=!1}if(t.metadata){const{min:x,ok:P}=n.features.get(H.JS_STREAM_CONSUMER_METADATA);if(!P)throw new Error(`consumer 'metadata' requires server ${x}`)}if(a&&(_=t.name??t.durable_name??""),_!==""){let x=t.filter_subject??void 0;x===">"&&(x=void 0),p=x!==void 0?`${this.prefix}.CONSUMER.CREATE.${e}.${_}.${x}`:`${this.prefix}.CONSUMER.CREATE.${e}.${_}`}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),Ut.Update)}async info(e,t){return le(e),Ze(t),await this._request(`${this.prefix}.CONSUMER.INFO.${e}.${t}`)}async delete(e,t){return le(e),Ze(t),(await this._request(`${this.prefix}.CONSUMER.DELETE.${e}.${t}`)).success}list(e){le(e);const t=i=>i.consumers,s=`${this.prefix}.CONSUMER.LIST.${e}`;return new _t(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 it(r,e,t=!1){if(t===!0&&!r)throw N.errorForCode(O.ApiError,new Error(`${e} is not a function`));if(r&&typeof r!="function")throw N.errorForCode(O.ApiError,new Error(`${e} is not a function`))}class Vi extends re{constructor(t,s,i){super();h(this,"sub");h(this,"adapter");h(this,"subIterDone");it(i.adapter,"adapter",!0),this.adapter=i.adapter,i.callback&&it(i.callback,"callback"),this.noIterator=typeof i.callback=="function",i.ingestionFilterFn&&(it(i.ingestionFilterFn,"ingestionFilterFn"),this.ingestionFilterFn=i.ingestionFilterFn),i.protocolFilterFn&&(it(i.protocolFilterFn,"protocolFilterFn"),this.protocolFilterFn=i.protocolFilterFn),i.dispatchedFn&&(it(i.dispatchedFn,"dispatchedFn"),this.dispatchedFn=i.dispatchedFn),i.cleanupFn&&it(i.cleanupFn,"cleanupFn");let n=(_,y)=>{this.callback(_,y)};if(i.callback){const _=i.callback;n=(y,x)=>{const[P,I]=this.adapter(y,x);if(P){_(P,null);return}const{ingest:T}=this.ingestionFilterFn?this.ingestionFilterFn(I,this):{ingest:!0};T&&(!this.protocolFilterFn||this.protocolFilterFn(I))&&(_(P,I),this.dispatchedFn&&I&&this.dispatchedFn(I))}}const{max:o,queue:a,timeout:d}=i,p={queue:a,timeout:d,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=z(),Promise.all([this.sub.closed,this.iterClosed]).then(()=>{this.subIterDone.resolve()}).catch(()=>{this.subIterDone.resolve()}),(async _=>{await _.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 we;function Wi(r){we=r}function vr(){return we!==void 0&&we.defaultPort!==void 0?we.defaultPort:4222}function vs(){return we!==void 0&&we.urlParseFn?we.urlParseFn:void 0}function Yi(){if(!we||typeof we.factory!="function")throw new Error("transport fn is not set");return we.factory()}function Es(){return we!==void 0&&we.dnsResolveFn?we.dnsResolveFn:void 0}const Ft=`\r
|
|
13
|
+
`,Bt=rt.fromAscii(Ft),Xi=new Uint8Array(Bt)[0],Zi=new Uint8Array(Bt)[1];function Qi(r){for(let e=0;e<r.length;e++){const t=e+1;if(r.byteLength>t&&r[e]===Xi&&r[t]===Zi)return t+1}return 0}function en(r){const e=Qi(r);if(e>0){const s=new Uint8Array(r).slice(0,e);return ge.decode(s)}return""}const tn=4,Er=48,sn=65,rn=97;function nn(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 As(r){return on(r)!==void 0}function on(r){for(let e=0;e<r.length;e++)switch(r[e]){case".":return Ar(r);case":":return an(r)}}function Ar(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}=cn(r);if(!n||s>255)return;r=r.substring(i),e[t]=s}return nn(e[0],e[1],e[2],e[3])}function an(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}=hn(r);if(!o||i>65535)return;if(n<r.length&&r[n]==="."){if(t<0&&s!=12||s+4>16)return;const a=Ar(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+=tn;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 cn(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)-Er),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 hn(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)-Er;else if(97<=r.charCodeAt(t)&&r.charCodeAt(t)<=102)e*=16,e+=r.charCodeAt(t)-rn+10;else if(65<=r.charCodeAt(t)&&r.charCodeAt(t)<=70)e*=16,e+=r.charCodeAt(t)-sn+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 un(r){return r.indexOf("[")!==-1||r.indexOf("::")!==-1?!1:r.indexOf(".")!==-1||r.split(":").length<=2}function Ps(r){return!un(r)}function ln(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 fn(r){r=r.trim(),r.match(/^(.*:\/\/)(.*)/m)&&(r=r.replace(/^(.*:\/\/)(.*)/gm,"$2")),r=ln(r),Ps(r)&&r.indexOf("[")===-1&&(r=`[${r}]`);const e=Ps(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 yt{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=fn(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(As(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}://${Ps(i)?"["+i+"]":i}`);o.port=`${this.port}`;const a=new yt(o.host,!1);a.tlsName=this.hostname,t.push(a)}}return e.randomize&&hr(t),this.resolves=t,t}}class dn{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=vs();e&&(e.forEach(i=>{i=s?s(i):i,this.servers.push(new yt(i))}),this.randomize&&(this.servers=hr(this.servers))),this.servers.length===0&&this.addServer(`${us}:${vr()}`,!1),this.currentServer=this.servers[0]}clear(){this.servers.length=0}updateTLSName(){const e=this.getCurrentServer();As(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=vs();e=s?s(e):e;const i=new yt(e,t);As(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=vs(),o=new Map;e.connect_urls&&e.connect_urls.length>0&&e.connect_urls.forEach(d=>{d=n?n(d,t):d;const p=new yt(d,!0);o.set(d,p)});const a=[];return this.servers.forEach((d,p)=>{const _=d.listen;d.gossiped&&this.currentServer.listen!==_&&o.get(_)===void 0&&a.push(p),o.delete(_)}),a.reverse(),a.forEach(d=>{const p=this.servers.splice(d,1);i=i.concat(p[0].listen)}),o.forEach((d,p)=>{this.servers.push(d),s.push(p)}),{added:s,deleted:i}}}class pn{constructor(){h(this,"baseInbox");h(this,"reqs");this.reqs=new Map}size(){return this.reqs.size}init(e){return this.baseInbox=`${$e(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=fr(t)),i.resolver(e,t))}}}close(){const e=N.errorForCode(O.Timeout);this.reqs.forEach(t=>{t.resolver(e,{})})}}class mn{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:Fe.PingTimer,data:`${this.pendings.length+1}`}),this.pendings.length===this.maxOut){this.cancel(!0);return}const e=z();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 bn extends Error{constructor(e){super(e),this.name="AssertionError"}}function gn(r,e="Assertion failed."){if(!r)throw new bn(e)}const Pr=32*1024,Os=2**32-2;function Dt(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 ks{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){gn(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=Dt(this._buf.subarray(this._off),e);return this._off+=t,t}writeByte(e){return this.write(Uint8Array.of(e))}writeString(e){return this.write(Ge.encode(e))}write(e){const t=this._grow(e.byteLength);return Dt(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)Dt(this._buf.subarray(this._off),this._buf);else{if(i+e>Os)throw new Error("The buffer cannot be grown beyond the maximum size.");{const n=new Uint8Array(Math.min(2*i+e,Os));Dt(this._buf.subarray(this._off),n),this._buf=n}}return this._off=0,this._reslice(Math.min(t+e,Os)),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(Pr);for(;;){const i=this.capacity-this.length<Pr,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 de;(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"})(de||(de={}));function Or(){const r={};return r.sid=-1,r.hdr=-1,r.size=-1,r}const _n=48;class kr{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=k.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 k.OP_START:switch(s){case C.M:case C.m:this.state=k.OP_M,this.hdr=-1,this.ma=Or();break;case C.H:case C.h:this.state=k.OP_H,this.hdr=0,this.ma=Or();break;case C.P:case C.p:this.state=k.OP_P;break;case C.PLUS:this.state=k.OP_PLUS;break;case C.MINUS:this.state=k.OP_MINUS;break;case C.I:case C.i:this.state=k.OP_I;break;default:throw this.fail(e.subarray(t))}break;case k.OP_H:switch(s){case C.M:case C.m:this.state=k.OP_M;break;default:throw this.fail(e.subarray(t))}break;case k.OP_M:switch(s){case C.S:case C.s:this.state=k.OP_MS;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MS:switch(s){case C.G:case C.g:this.state=k.OP_MSG;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MSG:switch(s){case C.SPACE:case C.TAB:this.state=k.OP_MSG_SPC;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MSG_SPC:switch(s){case C.SPACE:case C.TAB:continue;default:this.state=k.MSG_ARG,this.as=t}break;case k.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=k.MSG_PAYLOAD,t=this.as+this.ma.size-1;break}default:this.argBuf&&this.argBuf.writeByte(s)}break;case k.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){const i=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:de.MSG,msg:this.ma,data:i}),this.argBuf=void 0,this.msgBuf=void 0,this.state=k.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:de.MSG,msg:this.ma,data:e.subarray(this.as,t)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=k.MSG_END);break;case k.MSG_END:switch(s){case C.NL:this.drop=0,this.as=t+1,this.state=k.OP_START;break;default:continue}break;case k.OP_PLUS:switch(s){case C.O:case C.o:this.state=k.OP_PLUS_O;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PLUS_O:switch(s){case C.K:case C.k:this.state=k.OP_PLUS_OK;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PLUS_OK:switch(s){case C.NL:this.dispatcher.push({kind:de.OK}),this.drop=0,this.state=k.OP_START;break}break;case k.OP_MINUS:switch(s){case C.E:case C.e:this.state=k.OP_MINUS_E;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MINUS_E:switch(s){case C.R:case C.r:this.state=k.OP_MINUS_ER;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MINUS_ER:switch(s){case C.R:case C.r:this.state=k.OP_MINUS_ERR;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MINUS_ERR:switch(s){case C.SPACE:case C.TAB:this.state=k.OP_MINUS_ERR_SPC;break;default:throw this.fail(e.subarray(t))}break;case k.OP_MINUS_ERR_SPC:switch(s){case C.SPACE:case C.TAB:continue;default:this.state=k.MINUS_ERR_ARG,this.as=t}break;case k.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:de.ERR,data:i}),this.drop=0,this.as=t+1,this.state=k.OP_START;break}default:this.argBuf&&this.argBuf.write(Uint8Array.of(s))}break;case k.OP_P:switch(s){case C.I:case C.i:this.state=k.OP_PI;break;case C.O:case C.o:this.state=k.OP_PO;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PO:switch(s){case C.N:case C.n:this.state=k.OP_PON;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PON:switch(s){case C.G:case C.g:this.state=k.OP_PONG;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PONG:switch(s){case C.NL:this.dispatcher.push({kind:de.PONG}),this.drop=0,this.state=k.OP_START;break}break;case k.OP_PI:switch(s){case C.N:case C.n:this.state=k.OP_PIN;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PIN:switch(s){case C.G:case C.g:this.state=k.OP_PING;break;default:throw this.fail(e.subarray(t))}break;case k.OP_PING:switch(s){case C.NL:this.dispatcher.push({kind:de.PING}),this.drop=0,this.state=k.OP_START;break}break;case k.OP_I:switch(s){case C.N:case C.n:this.state=k.OP_IN;break;default:throw this.fail(e.subarray(t))}break;case k.OP_IN:switch(s){case C.F:case C.f:this.state=k.OP_INF;break;default:throw this.fail(e.subarray(t))}break;case k.OP_INF:switch(s){case C.O:case C.o:this.state=k.OP_INFO;break;default:throw this.fail(e.subarray(t))}break;case k.OP_INFO:switch(s){case C.SPACE:case C.TAB:this.state=k.OP_INFO_SPC;break;default:throw this.fail(e.subarray(t))}break;case k.OP_INFO_SPC:switch(s){case C.SPACE:case C.TAB:continue;default:this.state=k.INFO_ARG,this.as=t}break;case k.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:de.INFO,data:i}),this.drop=0,this.as=t+1,this.state=k.OP_START;break}default:this.argBuf&&this.argBuf.writeByte(s)}break;default:throw this.fail(e.subarray(t))}}(this.state===k.MSG_ARG||this.state===k.MINUS_ERR_ARG||this.state===k.INFO_ARG)&&!this.argBuf&&(this.argBuf=new ks(e.subarray(this.as,t-this.drop))),this.state===k.MSG_PAYLOAD&&!this.msgBuf&&(this.argBuf||this.cloneMsgArg(),this.msgBuf=new ks(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 ks(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}: ${ge.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]-_n)}return t}}var k;(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"})(k||(k={}));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]),d=t([56129,1]),p=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),_=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]),P=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],f=c[l+4]<<24|c[l+5]<<16|c[l+6]<<8|c[l+7];return new e(u,f)}function Q(c,l,u){var f;for(f=0;f<4;f++)c[l+f]=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 X(c,l,u,f,m){var b,v=0;for(b=0;b<m;b++)v|=c[l+b]^u[f+b];return(1&v-1>>>8)-1}function pe(c,l,u,f){return X(c,l,u,f,16)}function w(c,l,u,f){return X(c,l,u,f,32)}function j(c,l,u,f,m){var b=new Uint32Array(16),v=new Uint32Array(16),E=new Uint32Array(16),g=new Uint32Array(4),S,M,D;for(S=0;S<4;S++)v[5*S]=T(f,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++)g[D]=v[(5*M+4*D)%16];for(g[1]^=I(g[0]+g[3]|0,7),g[2]^=I(g[1]+g[0]|0,9),g[3]^=I(g[2]+g[1]|0,13),g[0]^=I(g[3]+g[2]|0,18),D=0;D<4;D++)b[4*M+(M+D)%4]=g[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(f,4*S)|0,v[6+S]=v[6+S]-T(l,4*S)|0;for(S=0;S<4;S++)Q(c,4*S,v[5*S]),Q(c,16+4*S,v[6+S])}else for(S=0;S<16;S++)Q(c,4*S,v[S]+E[S]|0)}function F(c,l,u,f){return j(c,l,u,f,!1),0}function R(c,l,u,f){return j(c,l,u,f,!0),0}var A=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function $(c,l,u,f,m,b,v){var E=new Uint8Array(16),g=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(g,E,v,A),M=0;M<64;M++)c[l+M]=(u?u[f+M]:0)^g[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&&(f+=64)}if(m>0)for(F(g,E,v,A),M=0;M<m;M++)c[l+M]=(u?u[f+M]:0)^g[M];return 0}function q(c,l,u,f,m){return $(c,l,null,0,u,f,m)}function U(c,l,u,f,m){var b=new Uint8Array(32);return R(b,f,m,A),q(c,l,u,f.subarray(16),b)}function K(c,l,u,f,m,b,v){var E=new Uint8Array(32);return R(E,b,v,A),$(c,l,u,f,m,b.subarray(16),E)}function te(c,l){var u,f=0;for(u=0;u<17;u++)f=f+(c[u]+l[u]|0)|0,c[u]=f&255,f>>>=8}var ne=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]);function se(c,l,u,f,m,b){var v,E,g,S,M=new Uint32Array(17),D=new Uint32Array(17),W=new Uint32Array(17),je=new Uint32Array(17),ht=new Uint32Array(17);for(g=0;g<17;g++)D[g]=W[g]=0;for(g=0;g<16;g++)D[g]=b[g];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(g=0;g<17;g++)je[g]=0;for(g=0;g<16&&g<m;++g)je[g]=u[f+g];for(je[g]=1,f+=g,m-=g,te(W,je),E=0;E<17;E++)for(M[E]=0,g=0;g<17;g++)M[E]=M[E]+W[g]*(g<=E?D[E-g]:320*D[E+17-g]|0)|0|0;for(E=0;E<17;E++)W[E]=M[E];for(S=0,g=0;g<16;g++)S=S+W[g]|0,W[g]=S&255,S>>>=8;for(S=S+W[16]|0,W[16]=S&3,S=5*(S>>>2)|0,g=0;g<16;g++)S=S+W[g]|0,W[g]=S&255,S>>>=8;S=S+W[16]|0,W[16]=S}for(g=0;g<17;g++)ht[g]=W[g];for(te(W,ne),v=-(W[16]>>>7)|0,g=0;g<17;g++)W[g]^=v&(ht[g]^W[g]);for(g=0;g<16;g++)je[g]=b[g+16];for(je[16]=0,te(W,je),g=0;g<16;g++)c[l+g]=W[g];return 0}function oe(c,l,u,f,m,b){var v=new Uint8Array(16);return se(v,0,u,f,m,b),pe(c,l,v,0)}function he(c,l,u,f,m){var b;if(u<32)return-1;for(K(c,0,l,0,u,f,m),se(c,16,c,32,u-32,c),b=0;b<16;b++)c[b]=0;return 0}function ue(c,l,u,f,m){var b,v=new Uint8Array(32);if(u<32||(U(v,0,32,f,m),oe(l,16,l,32,u-32,v)!==0))return-1;for(K(c,0,l,0,u,f,m),b=0;b<32;b++)c[b]=0;return 0}function V(c,l){var u;for(u=0;u<16;u++)c[u]=l[u]|0}function ee(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 ae(c,l,u){for(var f,m=~(u-1),b=0;b<16;b++)f=m&(c[b]^l[b]),c[b]^=f,l[b]^=f}function ot(c,l){var u,f,m,b=t(),v=t();for(u=0;u<16;u++)v[u]=l[u];for(ee(v),ee(v),ee(v),f=0;f<2;f++){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,ae(v,b,1-m)}for(u=0;u<16;u++)c[2*u]=v[u]&255,c[2*u+1]=v[u]>>8}function Kr(c,l){var u=new Uint8Array(32),f=new Uint8Array(32);return ot(u,c),ot(f,l),w(u,0,f,0)}function Vr(c){var l=new Uint8Array(32);return ot(l,c),l[0]&1}function Fs(c,l){var u;for(u=0;u<16;u++)c[u]=l[2*u]+(l[2*u+1]<<8);c[15]&=32767}function Ce(c,l,u){var f;for(f=0;f<16;f++)c[f]=l[f]+u[f]|0}function Ie(c,l,u){var f;for(f=0;f<16;f++)c[f]=l[f]-u[f]|0}function B(c,l,u){var f,m,b=new Float64Array(31);for(f=0;f<31;f++)b[f]=0;for(f=0;f<16;f++)for(m=0;m<16;m++)b[f+m]+=l[f]*u[m];for(f=0;f<15;f++)b[f]+=38*b[f+16];for(f=0;f<16;f++)c[f]=b[f];ee(c),ee(c)}function Pe(c,l){B(c,l,l)}function Wr(c,l){var u=t(),f;for(f=0;f<16;f++)u[f]=l[f];for(f=253;f>=0;f--)Pe(u,u),f!==2&&f!==4&&B(u,u,l);for(f=0;f<16;f++)c[f]=u[f]}function Yr(c,l){var u=t(),f;for(f=0;f<16;f++)u[f]=l[f];for(f=250;f>=0;f--)Pe(u,u),f!==1&&B(u,u,l);for(f=0;f<16;f++)c[f]=u[f]}function Yt(c,l,u){var f=new Uint8Array(32),m=new Float64Array(80),b,v,E=t(),g=t(),S=t(),M=t(),D=t(),W=t();for(v=0;v<31;v++)f[v]=l[v];for(f[31]=l[31]&127|64,f[0]&=248,Fs(m,u),v=0;v<16;v++)g[v]=m[v],M[v]=E[v]=S[v]=0;for(E[0]=M[0]=1,v=254;v>=0;--v)b=f[v>>>3]>>>(v&7)&1,ae(E,g,b),ae(S,M,b),Ce(D,E,S),Ie(E,E,S),Ce(S,g,M),Ie(g,g,M),Pe(M,D),Pe(W,E),B(E,S,E),B(S,g,D),Ce(D,E,S),Ie(E,E,S),Pe(g,E),Ie(S,M,W),B(E,S,d),Ce(E,E,M),B(S,S,E),B(E,M,W),B(M,g,m),Pe(g,D),ae(E,g,b),ae(S,M,b);for(v=0;v<16;v++)m[v+16]=E[v],m[v+32]=S[v],m[v+48]=g[v],m[v+64]=M[v];var je=m.subarray(32),ht=m.subarray(16);return Wr(je,je),B(ht,ht,je),ot(c,ht),0}function Xt(c,l){return Yt(c,l,n)}function Xr(c,l){return s(l,32),Xt(c,l)}function Zt(c,l,u){var f=new Uint8Array(32);return Yt(f,u,l),R(c,i,f,A)}var Zr=he,Po=ue;function Oo(c,l,u,f,m,b){var v=new Uint8Array(32);return Zt(v,m,b),Zr(c,l,u,f,v)}function ko(c,l,u,f,m,b){var v=new Uint8Array(32);return Zt(v,m,b),Po(c,l,u,f,v)}function Pt(){var c=0,l=0,u=0,f=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,f+=v>>>16;return l+=c>>>16,u+=l>>>16,f+=u>>>16,new e(u&m|f<<16,c&m|l<<16)}function Qr(c,l){return new e(c.hi>>>l,c.lo>>>l|c.hi<<32-l)}function Qt(){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 Te(c,l){var u,f,m=32-l;return l<32?(u=c.hi>>>l|c.lo<<m,f=c.lo>>>l|c.hi<<m):l<64&&(u=c.lo>>>l|c.hi<<m,f=c.hi>>>l|c.lo<<m),new e(u,f)}function Co(c,l,u){var f=c.hi&l.hi^~c.hi&u.hi,m=c.lo&l.lo^~c.lo&u.lo;return new e(f,m)}function Io(c,l,u){var f=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(f,m)}function jo(c){return Qt(Te(c,28),Te(c,34),Te(c,39))}function Ro(c){return Qt(Te(c,14),Te(c,18),Te(c,41))}function No(c){return Qt(Te(c,1),Te(c,8),Qr(c,7))}function To(c){return Qt(Te(c,19),Te(c,61),Qr(c,6))}var Mo=[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 ei(c,l,u){var f=[],m=[],b=[],v=[],E,g,S;for(g=0;g<8;g++)f[g]=b[g]=J(c,8*g);for(var M=0;u>=128;){for(g=0;g<16;g++)v[g]=J(l,8*g+M);for(g=0;g<80;g++){for(S=0;S<8;S++)m[S]=b[S];for(E=Pt(b[7],Ro(b[4]),Co(b[4],b[5],b[6]),Mo[g],v[g%16]),m[7]=Pt(E,jo(b[0]),Io(b[0],b[1],b[2])),m[3]=Pt(m[3],E),S=0;S<8;S++)b[(S+1)%8]=m[S];if(g%16===15)for(S=0;S<16;S++)v[S]=Pt(v[S],v[(S+9)%16],No(v[(S+1)%16]),To(v[(S+14)%16]))}for(g=0;g<8;g++)b[g]=Pt(b[g],f[g]),f[g]=b[g];M+=128,u-=128}for(g=0;g<8;g++)L(c,8*g,f[g]);return u}var $o=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 Ve(c,l,u){var f=new Uint8Array(64),m=new Uint8Array(256),b,v=u;for(b=0;b<64;b++)f[b]=$o[b];for(ei(f,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)),ei(f,m,u),b=0;b<64;b++)c[b]=f[b];return 0}function es(c,l){var u=t(),f=t(),m=t(),b=t(),v=t(),E=t(),g=t(),S=t(),M=t();Ie(u,c[1],c[0]),Ie(M,l[1],l[0]),B(u,u,M),Ce(f,c[0],c[1]),Ce(M,l[0],l[1]),B(f,f,M),B(m,c[3],l[3]),B(m,m,_),B(b,c[2],l[2]),Ce(b,b,b),Ie(v,f,u),Ie(E,b,m),Ce(g,b,m),Ce(S,f,u),B(c[0],v,E),B(c[1],S,g),B(c[2],g,E),B(c[3],v,S)}function ti(c,l,u){var f;for(f=0;f<4;f++)ae(c[f],l[f],u)}function Bs(c,l){var u=t(),f=t(),m=t();Wr(m,l[2]),B(u,l[0],m),B(f,l[1],m),ot(c,f),c[31]^=Vr(u)<<7}function Ds(c,l,u){var f,m;for(V(c[0],o),V(c[1],a),V(c[2],a),V(c[3],o),m=255;m>=0;--m)f=u[m/8|0]>>(m&7)&1,ti(c,l,f),es(l,c),es(c,c),ti(c,l,f)}function ts(c,l){var u=[t(),t(),t(),t()];V(u[0],y),V(u[1],x),V(u[2],a),B(u[3],y,x),Ds(c,u,l)}function Hs(c,l,u){var f=new Uint8Array(64),m=[t(),t(),t(),t()],b;for(u||s(l,32),Ve(f,l,32),f[0]&=248,f[31]&=127,f[31]|=64,ts(m,f),Bs(c,m),b=0;b<32;b++)l[b+32]=c[b];return 0}var ss=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 Js(c,l){var u,f,m,b;for(f=63;f>=32;--f){for(u=0,m=f-32,b=f-12;m<b;++m)l[m]+=u-16*l[f]*ss[m-(f-32)],u=Math.floor((l[m]+128)/256),l[m]-=u*256;l[m]+=u,l[f]=0}for(u=0,m=0;m<32;m++)l[m]+=u-(l[31]>>4)*ss[m],u=l[m]>>8,l[m]&=255;for(m=0;m<32;m++)l[m]-=u*ss[m];for(f=0;f<32;f++)l[f+1]+=l[f]>>8,c[f]=l[f]&255}function zs(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;Js(c,l)}function si(c,l,u,f){var m=new Uint8Array(64),b=new Uint8Array(64),v=new Uint8Array(64),E,g,S=new Float64Array(64),M=[t(),t(),t(),t()];Ve(m,f,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(Ve(v,c.subarray(32),u+32),zs(v),ts(M,v),Bs(c,M),E=32;E<64;E++)c[E]=f[E];for(Ve(b,c,u+64),zs(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(g=0;g<32;g++)S[E+g]+=b[E]*m[g];return Js(c.subarray(32),S),D}function Uo(c,l){var u=t(),f=t(),m=t(),b=t(),v=t(),E=t(),g=t();return V(c[2],a),Fs(c[1],l),Pe(m,c[1]),B(b,m,p),Ie(m,m,c[2]),Ce(b,c[2],b),Pe(v,b),Pe(E,v),B(g,E,v),B(u,g,m),B(u,u,b),Yr(u,u),B(u,u,m),B(u,u,b),B(u,u,b),B(c[0],u,b),Pe(f,c[0]),B(f,f,b),Kr(f,m)&&B(c[0],c[0],P),Pe(f,c[0]),B(f,f,b),Kr(f,m)?-1:(Vr(c[0])===l[31]>>7&&Ie(c[0],o,c[0]),B(c[3],c[0],c[1]),0)}function Gs(c,l,u,f){var m,b=new Uint8Array(32),v=new Uint8Array(64),E=[t(),t(),t(),t()],g=[t(),t(),t(),t()];if(u<64||Uo(g,f))return-1;for(m=0;m<u;m++)c[m]=l[m];for(m=0;m<32;m++)c[m+32]=f[m];if(Ve(v,c,u),zs(v),Ds(E,g,v),ts(g,l.subarray(32)),es(E,g),Bs(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 Ks=32,rs=24,Ot=32,at=16,kt=32,is=32,Ct=32,It=32,Vs=32,ri=rs,Lo=Ot,qo=at,Le=64,We=32,ct=64,Ws=32,Ys=64;r.lowlevel={crypto_core_hsalsa20:R,crypto_stream_xor:K,crypto_stream:U,crypto_stream_salsa20_xor:$,crypto_stream_salsa20:q,crypto_onetimeauth:se,crypto_onetimeauth_verify:oe,crypto_verify_16:pe,crypto_verify_32:w,crypto_secretbox:he,crypto_secretbox_open:ue,crypto_scalarmult:Yt,crypto_scalarmult_base:Xt,crypto_box_beforenm:Zt,crypto_box_afternm:Zr,crypto_box:Oo,crypto_box_open:ko,crypto_box_keypair:Xr,crypto_hash:Ve,crypto_sign:si,crypto_sign_keypair:Hs,crypto_sign_open:Gs,crypto_secretbox_KEYBYTES:Ks,crypto_secretbox_NONCEBYTES:rs,crypto_secretbox_ZEROBYTES:Ot,crypto_secretbox_BOXZEROBYTES:at,crypto_scalarmult_BYTES:kt,crypto_scalarmult_SCALARBYTES:is,crypto_box_PUBLICKEYBYTES:Ct,crypto_box_SECRETKEYBYTES:It,crypto_box_BEFORENMBYTES:Vs,crypto_box_NONCEBYTES:ri,crypto_box_ZEROBYTES:Lo,crypto_box_BOXZEROBYTES:qo,crypto_sign_BYTES:Le,crypto_sign_PUBLICKEYBYTES:We,crypto_sign_SECRETKEYBYTES:ct,crypto_sign_SEEDBYTES:Ws,crypto_hash_BYTES:Ys,gf:t,D:p,L:ss,pack25519:ot,unpack25519:Fs,M:B,A:Ce,S:Pe,Z:Ie,pow2523:Yr,add:es,set25519:V,modL:Js,scalarmult:Ds,scalarbase:ts};function ii(c,l){if(c.length!==Ks)throw new Error("bad key size");if(l.length!==rs)throw new Error("bad nonce size")}function Fo(c,l){if(c.length!==Ct)throw new Error("bad public key size");if(l.length!==It)throw new Error("bad secret key size")}function xe(){for(var c=0;c<arguments.length;c++)if(!(arguments[c]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function ni(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){xe(c,l,u),ii(u,l);for(var f=new Uint8Array(Ot+c.length),m=new Uint8Array(f.length),b=0;b<c.length;b++)f[b+Ot]=c[b];return he(m,f,f.length,l,u),m.subarray(at)},r.secretbox.open=function(c,l,u){xe(c,l,u),ii(u,l);for(var f=new Uint8Array(at+c.length),m=new Uint8Array(f.length),b=0;b<c.length;b++)f[b+at]=c[b];return f.length<32||ue(m,f,f.length,l,u)!==0?null:m.subarray(Ot)},r.secretbox.keyLength=Ks,r.secretbox.nonceLength=rs,r.secretbox.overheadLength=at,r.scalarMult=function(c,l){if(xe(c,l),c.length!==is)throw new Error("bad n size");if(l.length!==kt)throw new Error("bad p size");var u=new Uint8Array(kt);return Yt(u,c,l),u},r.scalarMult.base=function(c){if(xe(c),c.length!==is)throw new Error("bad n size");var l=new Uint8Array(kt);return Xt(l,c),l},r.scalarMult.scalarLength=is,r.scalarMult.groupElementLength=kt,r.box=function(c,l,u,f){var m=r.box.before(u,f);return r.secretbox(c,l,m)},r.box.before=function(c,l){xe(c,l),Fo(c,l);var u=new Uint8Array(Vs);return Zt(u,c,l),u},r.box.after=r.secretbox,r.box.open=function(c,l,u,f){var m=r.box.before(u,f);return r.secretbox.open(c,l,m)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var c=new Uint8Array(Ct),l=new Uint8Array(It);return Xr(c,l),{publicKey:c,secretKey:l}},r.box.keyPair.fromSecretKey=function(c){if(xe(c),c.length!==It)throw new Error("bad secret key size");var l=new Uint8Array(Ct);return Xt(l,c),{publicKey:l,secretKey:new Uint8Array(c)}},r.box.publicKeyLength=Ct,r.box.secretKeyLength=It,r.box.sharedKeyLength=Vs,r.box.nonceLength=ri,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(c,l){if(xe(c,l),l.length!==ct)throw new Error("bad secret key size");var u=new Uint8Array(Le+c.length);return si(u,c,c.length,l),u},r.sign.open=function(c,l){if(xe(c,l),l.length!==We)throw new Error("bad public key size");var u=new Uint8Array(c.length),f=Gs(u,c,c.length,l);if(f<0)return null;for(var m=new Uint8Array(f),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),f=new Uint8Array(Le),m=0;m<f.length;m++)f[m]=u[m];return f},r.sign.detached.verify=function(c,l,u){if(xe(c,l,u),l.length!==Le)throw new Error("bad signature size");if(u.length!==We)throw new Error("bad public key size");var f=new Uint8Array(Le+c.length),m=new Uint8Array(Le+c.length),b;for(b=0;b<Le;b++)f[b]=l[b];for(b=0;b<c.length;b++)f[b+Le]=c[b];return Gs(m,f,f.length,u)>=0},r.sign.keyPair=function(){var c=new Uint8Array(We),l=new Uint8Array(ct);return Hs(c,l),{publicKey:c,secretKey:l}},r.sign.keyPair.fromSecretKey=function(c){if(xe(c),c.length!==ct)throw new Error("bad secret key size");for(var l=new Uint8Array(We),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(xe(c),c.length!==Ws)throw new Error("bad seed size");for(var l=new Uint8Array(We),u=new Uint8Array(ct),f=0;f<32;f++)u[f]=c[f];return Hs(l,u,!0),{publicKey:l,secretKey:u}},r.sign.publicKeyLength=We,r.sign.secretKeyLength=ct,r.sign.seedLength=Ws,r.sign.signatureLength=Le,r.hash=function(c){xe(c);var l=new Uint8Array(Ys);return Ve(l,c,c.length),l},r.hash.hashLength=Ys,r.verify=function(c,l){return xe(c,l),c.length===0||l.length===0||c.length!==l.length?!1:X(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,f){var m,b=new Uint8Array(f);for(m=0;m<f;m+=l)c.getRandomValues(b.subarray(m,m+Math.min(f-m,l)));for(m=0;m<f;m++)u[m]=b[m];ni(b)})}else typeof require<"u"&&(c=require("crypto"),c&&c.randomBytes&&r.setPRNG(function(u,f){var m,b=c.randomBytes(f);for(m=0;m<f;m++)u[m]=b[m];ni(b)}))}()}(typeof module<"u"&&module.exports?module.exports:globalThis.nacl=globalThis.nacl||{});const Ht=typeof module<"u"&&module.exports?module.exports:globalThis.nacl;Ht.sign.keyPair.fromSeed,Ht.sign.detached,Ht.sign.detached.verify,Ht.randomBytes;var Cr;(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"})(Cr||(Cr={}));var Ir;(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"})(Ir||(Ir={}));function yn(r){return e=>{let t={};return r.forEach(s=>{const i=s(e)||{};t=Object.assign(t,i)}),t}}function wn(){return()=>{}}function xn(r,e){return()=>{const t=typeof r=="function"?r():r,s=typeof e=="function"?e():e;return{user:t,pass:s}}}function Sn(r){return()=>({auth_token:typeof r=="function"?r():r})}const jr=2*60*1e3,vn=2,Rr=2*1e3;function En(){return{maxPingOut:2,maxReconnectAttempts:10,noRandomize:!1,pedantic:!1,pingInterval:jr,reconnect:!0,reconnectJitter:100,reconnectJitterTLS:1e3,reconnectTimeWait:Rr,tls:void 0,verbose:!1,waitOnFirstConnect:!1,ignoreAuthErrorAbort:!1}}function An(r){const e=[];return typeof r.authenticator=="function"&&e.push(r.authenticator),Array.isArray(r.authenticator)&&e.push(...r.authenticator),r.token&&e.push(Sn(r.token)),r.user&&e.push(xn(r.user,r.pass)),e.length===0?wn():yn(e)}function Pn(r){const e=`${us}:${vr()}`;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",O.InvalidOption);r.servers.length===0&&r.port&&(r.servers=[`${us}:${r.port}`]),r.servers&&r.servers.length===0&&(r.servers=[e]);const t=Tt(En(),r);if(t.authenticator=An(t),["reconnectDelayHandler","authenticator"].forEach(s=>{if(t[s]&&typeof t[s]!="function")throw new N(`${s} option should be a function`,O.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{$e(t.inboxPrefix)}catch(s){throw new N(s.message,O.ApiError)}if(t.resolve===void 0&&(t.resolve=typeof Es()=="function"),t.resolve&&typeof Es()!="function")throw new N("'resolve' is not supported on this client",O.InvalidOption);return t}function On(r,e){const{proto:t,tls_required:s,tls_available:i}=r;if((t===void 0||t<1)&&e.noEcho)throw new N("noEcho",O.ServerOptionNotAvailable);const n=s||i||!1;if(e.tls&&!n)throw new N("tls",O.ServerOptionNotAvailable)}const kn=1024*32,Cn=/^INFO\s+([^\r\n]+)\r\n/i,In=ft(`PONG\r
|
|
14
14
|
`),Nr=ft(`PING\r
|
|
15
|
-
`);class jn{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):{})||{};Tt(this,i)}}class Tr extends re{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");Tt(this,i),this.protocol=t,this.subject=s,this.draining=!1,this.noIterator=typeof i.callback=="function",this.closed=z();const n=!((o=t.options)!=null&&o.noAsyncTraces);i.timeout&&(this.timer=Ye(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,d)=>{const{ingest:p}=i(d);p&&n(d)&&(s(a,d),o(d))}}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(O.ConnectionClosed)):this.isClosed()?Promise.reject(N.errorForCode(O.SubClosed)):(this.drained||(this.draining=!0,this.protocol.unsub(this),this.drained=this.protocol.flush(z()).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 Rn{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 Jt{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=kn,this.outMsgs=0,this.inMsgs=0,this.outBytes=0,this.inBytes=0,this.options=e,this.publisher=t,this.subscriptions=new Rn,this.muxSubscriptions=new pn,this.outbound=new rt,this.pongs=[],this.whyClosed="",this.pendingLimit=e.pendingLimit||this.pendingLimit,this.features=new Ki({major:0,minor:0,micro:0}),this.connectPromise=null;const s=typeof e.servers=="string"?[e.servers]:e.servers;this.servers=new dn(s,{randomize:!e.noRandomize}),this.closed=z(),this.parser=new kr(this),this.heartbeats=new mn(this,this.options.pingInterval||jr,this.options.maxPingOut||En)}resetOutbound(){this.outbound.reset();const e=this.pongs;this.pongs=[];const t=N.errorForCode(O.Disconnect);t.stack="",e.forEach(s=>{s.reject(t)}),this.parser=new kr(this),this.infoReceived=!1}dispatchStatus(e){this.listeners.forEach(t=>{t.push(e)})}status(){const e=new re;return this.listeners.push(e),e}prepare(){this.transport&&this.transport.discard(),this.info=void 0,this.resetOutbound();const e=z();return e.catch(()=>{}),this.pongs.unshift(e),this.connectError=t=>{e.reject(t)},this.transport=Yi(),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:Fe.StaleConnection,data:""}),this.transport.disconnect()}reconnect(){return this.connected&&(this.dispatchStatus({type:Fe.ClientInitiatedReconnect,data:""}),this.transport.disconnect()),Promise.resolve()}async disconnected(e){this.dispatchStatus({type:Se.Disconnect,data:this.servers.getCurrentServer().toString()}),this.options.reconnect?await this.dialLoop().then(()=>{var t;this.dispatchStatus({type:Se.Reconnect,data:this.servers.getCurrentServer().toString()}),((t=this.lastError)==null?void 0:t.code)===O.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=Ye(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:vs(),debug:this.options.debug,randomize:!this.options.noRandomize,resolve:t});let i=null;for(const n of s)try{i=null,this.dispatchStatus({type:Fe.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():Rr;let s=t;const i=this.selectServer();if(!i||this.abortReconnect)throw e||(this.lastError?this.lastError:N.errorForCode(O.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 Xe(s)}}static async connect(e,t){const s=new Jt(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,O.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,O.AuthorizationViolation):t.indexOf("user authentication expired")!==-1?new N(e,O.AuthenticationExpired):t.indexOf("account authentication expired")!=-1?new N(e,O.AccountExpired):t.indexOf("authentication timeout")!==-1?new N(e,O.AuthenticationTimeout):new N(e,O.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 ps(e,t,this)),s.max!==void 0&&s.received>=s.max&&s.unsubscribe())}processError(e){const t=rr(e),s=Jt.toError(t),i={type:Se.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(In)}processPong(){const e=this.pongs.shift();e&&e.resolve()}processInfo(e){const t=JSON.parse(rr(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(Ke(t.version)),this.infoReceived=!0,this.transport.isEncrypted()&&this.servers.updateTLSName();const{version:n,lang:o}=this.transport;try{const a=new jn({version:n,lang:o},this.options,t.nonce);t.headers&&(a.headers=!0,a.no_responders=!0);const d=JSON.stringify(a);this.transport.send(ft(`CONNECT ${d}${Ft}`)),this.transport.send(Nr)}catch(a){this._close(a)}}s&&this.dispatchStatus({type:Se.Update,data:s}),(t.ldm!==void 0?t.ldm:!1)&&this.dispatchStatus({type:Se.LDM,data:this.servers.getCurrentServer().toString()})}push(e){switch(e.kind){case de.MSG:{const{msg:t,data:s}=e;this.processMsg(t,s);break}case de.OK:break;case de.ERR:this.processError(e.data);break;case de.PING:this.processPing();break;case de.PONG:this.processPong();break;case de.INFO:this.processInfo(e.data);break}}sendCommand(e,...t){const s=this.outbound.length();let i;typeof e=="string"?i=ft(e):i=e,this.outbound.fill(i,...t),s===0?queueMicrotask(()=>{this.flushPending()}):this.outbound.size()>=this.pendingLimit&&this.flushPending()}publish(e,t=be,s){let i;if(t instanceof Uint8Array)i=t;else if(typeof t=="string")i=Ge.encode(t);else throw N.errorForCode(O.BadPayload);let n=i.length;s=s||{},s.reply=s.reply||"";let o=be,a=0;if(s.headers){if(this.info&&!this.info.headers)throw new N("headers",O.ServerOptionNotAvailable);o=s.headers.encode(),a=o.length,n=i.length+a}if(this.info&&n>this.info.max_payload)throw N.errorForCode(O.MaxPayloadExceeded);this.outBytes+=n,this.outMsgs++;let d;s.headers?(s.reply?d=`HPUB ${e} ${s.reply} ${a} ${n}\r
|
|
15
|
+
`);class jn{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):{})||{};Tt(this,i)}}class Tr extends re{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");Tt(this,i),this.protocol=t,this.subject=s,this.draining=!1,this.noIterator=typeof i.callback=="function",this.closed=z();const n=!((o=t.options)!=null&&o.noAsyncTraces);i.timeout&&(this.timer=Ye(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,d)=>{const{ingest:p}=i(d);p&&n(d)&&(s(a,d),o(d))}}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(O.ConnectionClosed)):this.isClosed()?Promise.reject(N.errorForCode(O.SubClosed)):(this.drained||(this.draining=!0,this.protocol.unsub(this),this.drained=this.protocol.flush(z()).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 Rn{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 Jt{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=kn,this.outMsgs=0,this.inMsgs=0,this.outBytes=0,this.inBytes=0,this.options=e,this.publisher=t,this.subscriptions=new Rn,this.muxSubscriptions=new pn,this.outbound=new rt,this.pongs=[],this.whyClosed="",this.pendingLimit=e.pendingLimit||this.pendingLimit,this.features=new Ki({major:0,minor:0,micro:0}),this.connectPromise=null;const s=typeof e.servers=="string"?[e.servers]:e.servers;this.servers=new dn(s,{randomize:!e.noRandomize}),this.closed=z(),this.parser=new kr(this),this.heartbeats=new mn(this,this.options.pingInterval||jr,this.options.maxPingOut||vn)}resetOutbound(){this.outbound.reset();const e=this.pongs;this.pongs=[];const t=N.errorForCode(O.Disconnect);t.stack="",e.forEach(s=>{s.reject(t)}),this.parser=new kr(this),this.infoReceived=!1}dispatchStatus(e){this.listeners.forEach(t=>{t.push(e)})}status(){const e=new re;return this.listeners.push(e),e}prepare(){this.transport&&this.transport.discard(),this.info=void 0,this.resetOutbound();const e=z();return e.catch(()=>{}),this.pongs.unshift(e),this.connectError=t=>{e.reject(t)},this.transport=Yi(),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:Fe.StaleConnection,data:""}),this.transport.disconnect()}reconnect(){return this.connected&&(this.dispatchStatus({type:Fe.ClientInitiatedReconnect,data:""}),this.transport.disconnect()),Promise.resolve()}async disconnected(e){this.dispatchStatus({type:Se.Disconnect,data:this.servers.getCurrentServer().toString()}),this.options.reconnect?await this.dialLoop().then(()=>{var t;this.dispatchStatus({type:Se.Reconnect,data:this.servers.getCurrentServer().toString()}),((t=this.lastError)==null?void 0:t.code)===O.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=Ye(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:Es(),debug:this.options.debug,randomize:!this.options.noRandomize,resolve:t});let i=null;for(const n of s)try{i=null,this.dispatchStatus({type:Fe.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():Rr;let s=t;const i=this.selectServer();if(!i||this.abortReconnect)throw e||(this.lastError?this.lastError:N.errorForCode(O.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 Xe(s)}}static async connect(e,t){const s=new Jt(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,O.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,O.AuthorizationViolation):t.indexOf("user authentication expired")!==-1?new N(e,O.AuthenticationExpired):t.indexOf("account authentication expired")!=-1?new N(e,O.AccountExpired):t.indexOf("authentication timeout")!==-1?new N(e,O.AuthenticationTimeout):new N(e,O.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 ps(e,t,this)),s.max!==void 0&&s.received>=s.max&&s.unsubscribe())}processError(e){const t=rr(e),s=Jt.toError(t),i={type:Se.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(In)}processPong(){const e=this.pongs.shift();e&&e.resolve()}processInfo(e){const t=JSON.parse(rr(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(Ke(t.version)),this.infoReceived=!0,this.transport.isEncrypted()&&this.servers.updateTLSName();const{version:n,lang:o}=this.transport;try{const a=new jn({version:n,lang:o},this.options,t.nonce);t.headers&&(a.headers=!0,a.no_responders=!0);const d=JSON.stringify(a);this.transport.send(ft(`CONNECT ${d}${Ft}`)),this.transport.send(Nr)}catch(a){this._close(a)}}s&&this.dispatchStatus({type:Se.Update,data:s}),(t.ldm!==void 0?t.ldm:!1)&&this.dispatchStatus({type:Se.LDM,data:this.servers.getCurrentServer().toString()})}push(e){switch(e.kind){case de.MSG:{const{msg:t,data:s}=e;this.processMsg(t,s);break}case de.OK:break;case de.ERR:this.processError(e.data);break;case de.PING:this.processPing();break;case de.PONG:this.processPong();break;case de.INFO:this.processInfo(e.data);break}}sendCommand(e,...t){const s=this.outbound.length();let i;typeof e=="string"?i=ft(e):i=e,this.outbound.fill(i,...t),s===0?queueMicrotask(()=>{this.flushPending()}):this.outbound.size()>=this.pendingLimit&&this.flushPending()}publish(e,t=be,s){let i;if(t instanceof Uint8Array)i=t;else if(typeof t=="string")i=Ge.encode(t);else throw N.errorForCode(O.BadPayload);let n=i.length;s=s||{},s.reply=s.reply||"";let o=be,a=0;if(s.headers){if(this.info&&!this.info.headers)throw new N("headers",O.ServerOptionNotAvailable);o=s.headers.encode(),a=o.length,n=i.length+a}if(this.info&&n>this.info.max_payload)throw N.errorForCode(O.MaxPayloadExceeded);this.outBytes+=n,this.outMsgs++;let d;s.headers?(s.reply?d=`HPUB ${e} ${s.reply} ${a} ${n}\r
|
|
16
16
|
`:d=`HPUB ${e} ${a} ${n}\r
|
|
17
17
|
`,this.sendCommand(d,o,i,Bt)):(s.reply?d=`PUB ${e} ${s.reply} ${n}\r
|
|
18
18
|
`:d=`PUB ${e} ${n}\r
|
|
@@ -20,20 +20,20 @@ ${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=z()),this.pongs.push(e),this.outbound.fill(Nr),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}${Ft}`):e.push(`SUB ${s.subject} ${s.sid}${Ft}`)}),e.length&&this.transport.send(ft(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 Tr(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 Nn="$SRV";class Mr{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||Ue(),(n=i.headers)==null||n.set(Rt,`${e}`),(o=i.headers)==null||o.set(jt,t),this.msg.respond(s,i)}json(e){return this.msg.json(e)}string(){return this.msg.string()}}class wt{constructor(e,t="",s=""){h(this,"subject");h(this,"queue");h(this,"srv");t!==""&&Mn("service group",t);let i="";if(e instanceof xt)this.srv=e,i="";else if(e instanceof wt){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;pt("endpoint",e);let{subject:i,handler:n,metadata:o,queue:a}=s;i=i||e,a=a||this.queue,Tn("endpoint subject",i),i=this.calcSubject(this.subject,i);const d={name:e,subject:i,queue:a,handler:n,metadata:o};return this.srv._addEndpoint(d)}addGroup(e="",t=""){return new wt(this,e,t)}}function Tn(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 Mn(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 xt{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"),pt("name",this.config.name),pt("queue",this.config.queue),Ke(this.config.version),this._id=qe.next(),this.internal=[],this._done=z(),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??Nn;return t===""&&s===""?`${n}.${e}`:(pt("control subject name",t),s!==""?(pt("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=Ue();if(e instanceof Nt){const s=e;t.set(jt,s.message),t.set(Rt,`${s.code}`)}else t.set(jt,e.message),t.set(Rt,"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 $n(i,n,s),a.queue=s;const d=o?(p,_)=>{if(p){this.close(p);return}const y=Date.now();try{o(p,new Mr(_))}catch(x){a.stats.countError(x),_==null||_.respond(be,{headers:this.errorToHeader(x)})}finally{a.stats.countLatency(y)}}:void 0;return a.sub=this.nc.subscribe(n,{callback:d,queue:s}),a.sub.closed.then(()=>{this._stopped||this.close(new Error(`required subscription ${e.subject} stopped`)).catch()}).catch(p=>{if(!this._stopped){const _=new Error(`required subscription ${e.subject} errored: ${p.message}`);_.stack=p.stack,this.close(_).catch()}}),a}info(){return{type:dt.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:dt.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=xt.controlSubject(t,i,n),o.handler=s,this.setupHandler(o,!0)}start(){const e=Ee(),t=(o,a)=>o?(this.close(o),Promise.reject(o)):this.stats().then(d=>(a==null||a.respond(e.encode(d)),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(Be.PING,n),this.addInternalHandler(Be.STATS,t),this.addInternalHandler(Be.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:dt.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 wt(this,e,t)}addEndpoint(e,t){return new wt(this).addEndpoint(e,t)}_addEndpoint(e){const t=new re;t.noIterator=typeof e.handler=="function",t.noIterator||(e.handler=(i,n)=>{i?this.stop(i).catch():t.push(new Mr(n))},t.iterClosed.then(()=>{this.close().catch()}));const s=this.setupHandler(e,!1);return s.qi=t,this.handlers.push(s),t}}class $n{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+=G(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:d,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:d,queue_group:p}}stats(e){const t=e;return(t==null?void 0:t.noIterator)===!1&&(this.processing_time=G(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 Un{constructor(e,t={strategy:Oe.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(Be.PING,e,t)}stats(e="",t=""){return this.q(Be.STATS,e,t)}info(e="",t=""){return this.q(Be.INFO,e,t)}async q(e,t="",s=""){const i=new re,n=Ee(),o=xt.controlSubject(e,t,s,this.prefix),a=await this.nc.requestMany(o,be,this.opts);return(async()=>{for await(const d of a)try{const p=n.decode(d.data);i.push(p)}catch(p){i.push(()=>{i.stop(p)})}i.push(()=>{i.stop()})})().catch(d=>{i.stop(d)}),i}}function $r(){return{key:{encode(r){return r},decode(r){return r}},value:{encode(r){return r},decode(r){return r}}}}function Ln(){return{replicas:1,history:1,timeout:2e3,max_bytes:-1,maxValueSize:-1,codec:$r(),storage:ys.File}}const zt="KV-Operation",Ur="$KV",qn=/^[-/=.\w]+$/,Fn=/^[-/=.>*\w]+$/,Bn=/^[-\w]+$/;function Dn(r){if(r.startsWith(".")||r.endsWith(".")||!qn.test(r))throw new Error(`invalid key: ${r}`)}function Hn(r){if(r.startsWith(".")||r.endsWith(".")||!Fn.test(r))throw new Error(`invalid key: ${r}`)}function Jn(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 Gt(r){if(!Bn.test(r))throw new Error(`invalid bucket name: ${r}`)}var Re;(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"})(Re||(Re={}));class St{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",Dn);h(this,"validateSearchKey",Hn);h(this,"hasWildcards",Jn);Gt(e),this.js=t,this.jsm=s,this.bucket=e,this.prefix=Ur,this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create(e,t,s={}){Gt(t);const i=await e.jetstreamManager(),n=new St(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}};Gt(t);const o=new St(t,e,i);return n.config.name=s.streamName??o.bucketName(),Object.assign(o,n),o.stream=n.config.name,o.codec=s.codec||$r(),o.direct=n.config.allow_direct??!1,o.initializePrefixes(n),o}async init(e={}){const t=Object.assign(Ln(),e);this.codec=t.codec;const s={};this.stream=s.name=e.streamName??this.bucketName(),s.retention=_s.Limits,s.max_msgs_per_subject=t.history,t.maxBucketSize&&(t.max_bytes=t.maxBucketSize),t.max_bytes&&(s.max_bytes=t.max_bytes),s.max_msg_size=t.maxValueSize,s.storage=t.storage;const 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(ye)||(y.name=`${ye}${y.name}`),s.mirror=y,s.mirror_direct=!0}else if(e.sources){const y=e.sources.map(x=>{const P=Object.assign({},x),I=P.name.startsWith(ye)?P.name.substring(ye.length):P.name;return P.name.startsWith(ye)||(P.name=`${ye}${P.name}`),!x.external&&I!==this.bucket&&(P.subject_transforms=[{src:`$KV.${I}.>`,dest:`$KV.${this.bucket}.>`}]),P});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?He.S2:He.None);const n=this.js.nc,o=n.getServerVersion(),a=o?Ss(o,Ke("2.7.2"))>=0:!1;s.discard=a?mt.New:mt.Old;const{ok:d,min:p}=n.features.get(H.JS_ALLOW_DIRECT);if(!d&&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:d,s.allow_direct=e.allow_direct,this.direct=s.allow_direct,s.num_replicas=t.replicas,t.ttl&&(s.max_age=G(t.ttl)),s.allow_rollup_hdrs=!0;let _;try{_=await this.jsm.streams.info(s.name),!_.config.allow_direct&&this.direct===!0&&(this.direct=!1)}catch(y){if(y.message==="stream not found")_=await this.jsm.streams.add(s);else throw y}this.initializePrefixes(_)}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(ye)&&(s=s.substring(ye.length)),t.external&&t.external.api!==""){const i=t.name.substring(ye.length);this.useJsPrefix=!1,this.prefix=`$KV.${i}`,this.editPrefix=`${t.external.api}.$KV.${s}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${ye}${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}`:`${Ur}.${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(fe.MessageSizeHdr)||"";return s!==""?parseInt(s,10):e.length}smToEntry(e){return new no(this.bucket,this.prefixLen,e)}jmToEntry(e){const t=this.decodeKey(e.subject.substring(this.prefixLen));return new oo(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 d=Ue();n.headers=d,d.set(Re.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`)}try{return(await this.js.publish(this.subjectForKey(i,!0),t,n)).seq}catch(d){const p=d;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(d)}}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===O.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=z(),s=[],i=await this.watch({key:">",initializedFn:()=>{t.resolve()}});(async()=>{for await(const d of i)(d.operation==="DEL"||d.operation==="PURGE")&&s.push(d)})().then(),await t,i.stop();const n=Date.now()-e,o=s.map(d=>{const p=this.subjectForKey(d.key);return d.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((d,p)=>(d.purged+=p.purged,d))}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=Ue();n.set(zt,t),t==="PURGE"&&n.set(fe.RollupHdr,fe.RollupValueSubject),s!=null&&s.previousSeq&&n.set(Re.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`),await this.js.publish(this.subjectForKey(i,!0),be,{headers:n})}_buildCC(e,t,s={}){let n=(Array.isArray(e)?e:[e]).map(d=>{const p=this.encodeKey(d);return this.validateSearchKey(d),this.fullKeyName(p)}),o=Z.LastPerSubject;t===ke.AllHistory&&(o=Z.All),t===ke.UpdatesOnly&&(o=Z.New);let a;return n.length===1&&(a=n[0],n=void 0),Object.assign({deliver_policy:o,ack_policy:ie.None,filter_subjects:n,filter_subject:a,flow_control:!0,idle_heartbeat:G(5*1e3)},s)}remove(e){return this.purge(e)}async history(e={}){const t=e.key??">",s=new re,i={};i.headers_only=e.headers_only||!1;let n;n=()=>{s.stop()};let o=0;const a=this._buildCC(t,ke.AllHistory,i),d=a.filter_subject,p=Je(a);p.bindStream(this.stream),p.orderedConsumer(),p.callback((y,x)=>{if(y){s.stop(y);return}if(x){const P=this.jmToEntry(x);s.push(P),s.received++,(n&&o>0&&s.received>=o||x.info.pending===0)&&(s.push(n),n=void 0)}});const _=await this.js.subscribe(d,p);if(n){const{info:{last:y}}=_,x=y.num_pending+y.delivered.consumer_seq;if(x===0||s.received>=x)try{n()}catch(P){s.stop(P)}finally{n=void 0}else o=x}return s._data=_,s.iterClosed.then(()=>{_.unsubscribe()}),_.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 re,i={};i.headers_only=e.headers_only||!1;let n=ke.LastValue;e.include===ke.AllHistory?n=ke.AllHistory:e.include===ke.UpdatesOnly&&(n=ke.UpdatesOnly);const o=e.ignoreDeletes===!0;let a=e.initializedFn,d=0;const p=this._buildCC(t,n,i),_=p.filter_subject,y=Je(p);this.canSetWatcherName()&&y.consumerName(qe.next()),y.bindStream(this.stream),e.resumeFromRevision&&e.resumeFromRevision>0&&y.startSequence(e.resumeFromRevision),y.orderedConsumer(),y.callback((P,I)=>{if(P){s.stop(P);return}if(I){const T=this.jmToEntry(I);if(o&&T.operation==="DEL")return;s.push(T),s.received++,a&&(d>0&&s.received>=d||I.info.pending===0)&&(s.push(a),a=void 0)}});const x=await this.js.subscribe(_,y);if(a){const{info:{last:P}}=x,I=P.num_pending+P.delivered.consumer_seq;if(I===0||s.received>=I)try{a()}catch(T){s.stop(T)}finally{a=void 0}else d=I}return s._data=x,s.iterClosed.then(()=>{x.unsubscribe()}),x.closed.then(()=>{s.stop()}).catch(P=>{s.stop(P)}),s}async keys(e=">"){const t=new re,s=this._buildCC(e,ke.LastValue,{headers_only:!0}),i=Array.isArray(e)?">":s.filter_subject,n=Je(s);n.bindStream(this.stream),n.orderedConsumer();const o=await this.js.subscribe(i,n);return(async()=>{var d;for await(const p of o){const _=(d=p.headers)==null?void 0:d.get(zt);if(_!=="DEL"&&_!=="PURGE"){const y=this.decodeKey(p.subject.substring(this.prefixLen));t.push(y)}p.info.pending===0&&o.unsubscribe()}})().then(()=>{t.stop()}).catch(d=>{t.stop(d)}),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 Lr(i,t)}}class Lr{constructor(e,t=""){h(this,"si");h(this,"cluster");this.si=e,this.cluster=t}get bucket(){return this.si.config.name.startsWith(ye)?this.si.config.name.substring(ye.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 fs(this.si.config.max_age)}get bucket_location(){return this.cluster}get backingStore(){return this.si.config.storage}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get description(){return this.si.config.description??""}get maxBucketSize(){return this.si.config.max_bytes}get maxValueSize(){return this.si.config.max_msg_size}get max_bytes(){return this.si.config.max_bytes}get placement(){return this.si.config.placement||{cluster:"",tags:[]}}get placementCluster(){var e;return((e=this.si.config.placement)==null?void 0:e.cluster)??""}get republish(){return this.si.config.republish??{src:"",dest:""}}get streamInfo(){return this.si}get size(){return this.si.state.bytes}get metadata(){return this.si.config.metadata??{}}get compression(){return this.si.config.compression?this.si.config.compression!==He.None:!1}}const Cs="OBJ_",qr="SHA-256=";function zn(r){return Gt(r),`${Cs}${r}`}function Gn(r){return r.startsWith(Cs)?r.substring(4):r}class Is{constructor(e){h(this,"si");h(this,"backingStore");this.si=e,this.backingStore="JetStream"}get bucket(){return Gn(this.si.config.name)}get description(){return this.si.config.description??""}get ttl(){return this.si.config.max_age}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get sealed(){return this.si.config.sealed}get size(){return this.si.state.bytes}get streamInfo(){return this.si}get metadata(){return this.si.config.metadata}get compression(){return this.si.config.compression?this.si.config.compression!==He.None:!1}}function Kt(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 Ae;(function(r){r[r.Unset=-1]="Unset",r[r.Consume=0]="Consume",r[r.Fetch=1]="Fetch"})(Ae||(Ae={}));var Ne;(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"})(Ne||(Ne={}));var nt;(function(r){r.DebugEvent="debug",r.Discard="discard",r.Reset="reset",r.Next="next"})(nt||(nt={}));const Fr=Uint8Array.of(43,65,67,75),Kn=Uint8Array.of(45,78,65,75),Et=Uint8Array.of(43,87,80,73),Vn=Uint8Array.of(43,78,88,84),Wn=Uint8Array.of(43,84,69,82,77),Yn=Uint8Array.of(32);function vt(r,e=5e3){return new po(r,e)}class js extends re{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=$e(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(d=>{if(this.cleanupHandler)try{this.cleanupHandler(d)}catch{}});const{sub:a}=this;a&&a.unsubscribe(),this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(d,p)=>{var y,x,P,I;if(d){this.stop(d);return}if((y=this.monitor)==null||y.work(),p.subject===this.inbox){if(bs(p))return;const T=(x=p.headers)==null?void 0:x.code,J=((I=(P=p.headers)==null?void 0:P.description)==null?void 0:I.toLowerCase())||"unknown",{msgsLeft:Q,bytesLeft:L}=this.parseDiscard(p.headers);if(Q>0||L>0)this.pending.msgs-=Q,this.pending.bytes-=L,this.pending.requests--,this.notify(nt.Discard,{msgsLeft:Q,bytesLeft:L});else if(T===400){this.stop(new N(J,`${T}`));return}else if(T===409&&J==="consumer deleted"){if(this.notify(Ne.ConsumerDeleted,`${T} ${J}`),!this.refilling||this.abortOnMissingResource){const X=new N(J,`${T}`);this.stop(X);return}}else if(T===503){if(this.notify(Ne.NoResponders,`${T} No Responders`),!this.refilling||this.abortOnMissingResource){const X=new N("no responders",`${T}`);this.stop(X);return}}else this.notify(nt.DebugEvent,`${T} ${J}`)}else this._push(vt(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 gs(i,d=>(this.notify(Ne.HeartbeatsMissed,d),this.resetPending().then(()=>{}).catch(()=>{}),!1),{maxOut:2})),(async()=>{var p;const d=this.consumer.api.nc.status();this.statusIterator=d;for await(const _ of d)switch(_.type){case Se.Disconnect:(p=this.monitor)==null||p.cancel();break;case Se.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=ls([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(Ne.StreamNotFound,s),!this.refilling||this.abortOnMissingResource)return this.stop(o),!1}else if(o.message==="consumer not found"){if(t++,this.notify(Ne.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),d=Xe(a);await Promise.race([d,this.consumer.api.nc.closed()]),d.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(nt.Next,t)})}pullOptions(){const t=this.opts.max_messages-this.pending.msgs,s=this.opts.max_bytes-this.pending.bytes,i=G(this.opts.idle_heartbeat),n=G(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(fe.PendingMessagesHdr);i&&(s.msgsLeft=parseInt(i));const n=t==null?void 0:t.get(fe.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 re;return this.listeners.push(t),Promise.resolve(t)}}class Xn extends re{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 re;return this.listeners.push(t),Promise.resolve(t)}}class Rs{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 js(this,e,!0))}fetch(e={max_messages:100,expires:3e4}){const t=new js(this,e,!1),s=Math.round(t.opts.expires*1.05),i=Ye(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=z(),s=e;s.max_messages=1;const i=new js(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===Ne.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=Ye(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 Zn{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=qe.next(),typeof s.name_prefix=="string"&&($t("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=Ae.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:Z.StartSequence,opt_start_seq:e,ack_policy:ie.None,inactive_threshold:G(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||Z.StartSequence,(this.consumerOpts.deliver_policy===Z.LastPerSubject||this.consumerOpts.deliver_policy===Z.New||this.consumerOpts.deliver_policy===Z.Last)&&(delete s.opt_start_seq,s.deliver_policy=this.consumerOpts.deliver_policy),s.deliver_policy===Z.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=Z.StartTime,s.opt_start_time=this.consumerOpts.opt_start_time),this.consumerOpts.inactive_threshold&&(s.inactive_threshold=G(this.consumerOpts.inactive_threshold))),s}async resetConsumer(e=0){var o,a,d,p,_;qe.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=ls([((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),(d=this.iter)==null||d.notify(Ne.OrderedConsumerRecreated,n.name);break}catch(x){if(x.message==="stream not found"&&((p=this.iter)==null||p.notify(Ne.StreamNotFound,y),this.type===Ae.Fetch||this.opts.abort_on_missing_resource===!0))return(_=this.iter)==null||_.stop(x),Promise.reject(x);if(t&&y>=this.maxInitialReset)throw x;await Xe(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 d,p;t=t||{};const s=t.fromFetch||!1,i=t.orderedReset||!1;if(this.type===Ae.Fetch&&i){(d=this.iter)==null||d.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 Xn),this.consumer=new Rs(this.api,this.currentConsumer);const n=e;n.callback=this.internalHandler(this.serial);let o=null;this.type===Ae.Fetch&&s?o=await this.consumer.fetch(e):this.type===Ae.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(nt.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===Ae.Fetch)return Promise.reject(new Error("ordered consumer initialized as fetch"));if(this.type===Ae.Consume)return Promise.reject(new Error("ordered consumer doesn't support concurrent consume"));const{callback:s}=e;return s&&(this.userCallback=s),this.type=Ae.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===Ae.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=Ae.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=z();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 Ns{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 Rs(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 Rs(this.api,s)).catch(s=>Promise.reject(s)))}async ordered(e,t){await this.checkVersion();const s=this.api;return new Ts(s.nc,s.opts).info(e).then(n=>Promise.resolve(new Zn(this.api,e,t))).catch(n=>Promise.reject(n))}}class Vt{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 Vt(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 Ns(new qt(this.api.nc,this.api.opts)).getPullConsumerFor(e)}getConsumer(e){return new Ns(new qt(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 Ts extends gt{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:d,ok:p}=t.features.get(H.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!p)throw new Error(`${i} 'subject_transforms' requires server ${d}`)}}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),le(e.name),e.mirror=Kt(e.mirror),e.sources=(i=e.sources)==null?void 0:i.map(Kt);const s=await this._request(`${this.prefix}.STREAM.CREATE.${e.name}`,e);return this._fixInfo(s),s}async delete(e){return le(e),(await this._request(`${this.prefix}.STREAM.DELETE.${e}`)).success}async update(e,t={}){var a;if(typeof e=="object"){const d=e;e=d.name,t=d,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),le(e);const s=await this.info(e),i=Object.assign(s.config,t);i.mirror=Kt(i.mirror),i.sources=(a=i.sources)==null?void 0:a.map(Kt);const o=await this._request(`${this.prefix}.STREAM.UPDATE.${e}`,i);return this._fixInfo(o),o}async info(e,t){le(e);const s=`${this.prefix}.STREAM.INFO.${e}`;let n=await this._request(s,t),{total:o,limit:a}=n,d=n.state.subjects?Object.getOwnPropertyNames(n.state.subjects).length:1;if(o&&o>d){const p=[n],_=t||{};let y=0;for(;o>d;){y++,_.offset=a*y;const P=await this._request(s,_);o=P.total,p.push(P);const I=Object.getOwnPropertyNames(P.state.subjects).length;if(d+=I,I<a)break}let x={};for(let P=0;P<p.length;P++)n=p[P],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 _t(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 le(e),await this._request(`${this.prefix}.STREAM.PURGE.${e}`,t)}async deleteMessage(e,t,s=!0){le(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){le(e);const i=await this._request(`${this.prefix}.STREAM.MSG.GET.${e}`,t);return new Br(i)}find(e){return this.findStream(e)}listKvs(){const e=s=>{var d;const n=s.streams.filter(p=>p.config.name.startsWith(ye));n.forEach(p=>{this._fixInfo(p)});let o="";return n.length&&(o=((d=this.nc.info)==null?void 0:d.cluster)??""),n.map(p=>new Lr(p,o))},t=`${this.prefix}.STREAM.LIST`;return new _t(t,e,this)}listObjectStores(){const e=s=>{const n=s.streams.filter(a=>a.config.name.startsWith(Cs));return n.forEach(a=>{this._fixInfo(a)}),n.map(a=>new Is(a))},t=`${this.prefix}.STREAM.LIST`;return new _t(t,e,this)}names(e=""){const t=e!=null&&e.length?{subject:e}:{},s=n=>n.streams,i=`${this.prefix}.STREAM.NAMES`;return new _t(i,s,this,t)}async get(e){const t=await this.info(e);return Promise.resolve(new Vt(this,t))}}class Qn extends gt{constructor(e,t){super(e,t)}async getMessage(e,t){le(e);let s=t;const{last_by_subj:i}=s;i&&(s=null);const n=s?this.jc.encode(s):be,o=this.opts.apiPrefix||"$JS.API",a=i?`${o}.DIRECT.GET.${e}.${i}`:`${o}.DIRECT.GET.${e}`,d=await this.nc.request(a,n,{timeout:this.timeout}),p=Qe(d);if(p)return Promise.reject(p);const _=new Ms(d);return Promise.resolve(_)}async getBatch(e,t){le(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,(d,p)=>d==="up_to_time"&&p instanceof Date?p.toISOString():p),o=new re,a=await this.nc.requestMany(i,n,{strategy:Oe.SentinelMsg});return(async()=>{var y,x,P;let d=!1,p=!1,_;for await(const I of a){if(!d){d=!0;const T=((y=I.headers)==null?void 0:y.code)||0;if(T!==0&&T<200||T>299){_=(x=I.headers)==null?void 0:x.description.toLowerCase();break}if(((P=I.headers)==null?void 0:P.get("Nats-Num-Pending"))===""){p=!0;break}}if(I.data.length===0)break;o.push(new Ms(I))}o.push(()=>{if(p)throw new Error("batch direct get not supported by the server");if(_)throw new Error(`bad request: ${_}`);o.stop()})})(),Promise.resolve(o)}}class Ms{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(tt.Subject)}get seq(){const e=this.header.last(tt.Sequence);return typeof e=="string"?parseInt(e):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(tt.TimeStamp)}get stream(){return this.header.last(tt.Stream)}json(e){return Ee(e).decode(this.data)}string(){return ge.decode(this.data)}}h(Ms,"jc");class eo extends gt{constructor(t,s){super(t,s);h(this,"streams");h(this,"consumers");h(this,"direct");this.streams=new Ts(t,s),this.consumers=new qt(t,s),this.direct=new Qn(t,s)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return this.nc.jetstream(this.getOptions())}advisories(){const t=new re;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 Br{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):be}get header(){if(!this._header)if(this.smr.message.hdrs){const e=this._parse(this.smr.message.hdrs);this._header=De.decode(e)}else this._header=Ue();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 Ee(e).decode(this.data)}string(){return ge.decode(this.data)}}h(Br,"jc");class to{constructor(e){h(this,"api");this.api=e}get(e){return this.api.info(e).then(t=>new Vt(this.api,t))}}class $s{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=De.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 Dr(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 so(){return new ReadableStream({pull(r){r.enqueue(new Uint8Array(0)),r.close()}})}class At{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 $s(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=Ee().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 Is(e)))}async status(e){const t=await this._si(e);return t===null?Promise.reject(new Error("object store not found")):Promise.resolve(new Is(t))}destroy(){return this.jsm.streams.delete(this.stream)}async _put(e,t,s){var pe;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,d=(a==null?void 0:a.max_payload)||1024;e=e||{},e.options=e.options||{};let p=((pe=e.options)==null?void 0:pe.max_chunk_size)||128*1024;p=p>d?d:p,e.options.max_chunk_size=p;const _=await this.info(e.name),{name:y,error:x}=this._checkNotEmpty(e.name);if(x)return Promise.reject(x);const P=qe.next(),I=this._chunkSubject(P),T=this._metaSubject(y),J=Object.assign({bucket:this.name,nuid:P,size:0,chunks:0},Dr(e)),Q=z(),L=[],X=new rt;try{const w=t?t.getReader():null,j=wr.create();for(;;){const{done:F,value:R}=w?await w.read():{done:!0,value:void 0};if(F){if(X.size()>0){const U=X.drain();j.update(U),J.chunks++,J.size+=U.length,L.push(this.js.publish(I,U,{timeout:n}))}await Promise.all(L),L.length=0,J.mtime=new Date().toISOString();const A=st.encode(j.digest());J.digest=`${qr}${A}`,J.deleted=!1;const $=Ue();typeof o=="number"&&$.set(Re.ExpectedLastSubjectSequenceHdr,`${o}`),$.set(fe.RollupHdr,fe.RollupValueSubject);const q=await this.js.publish(T,Ee().encode(J),{headers:$,timeout:n});if(J.revision=q.seq,_)try{await this.jsm.streams.purge(this.stream,{filter:`$O.${this.name}.C.${_.nuid}`})}catch{}Q.resolve(new $s(J));break}if(R)for(X.fill(R);X.size()>p;){J.chunks++,J.size+=p;const A=X.drain(e.options.max_chunk_size);j.update(A),L.push(this.js.publish(I,A,{timeout:n}))}}}catch(w){await this.jsm.streams.purge(this.stream,{filter:I}),Q.reject(w)}return Q}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 rt,a=n.getReader();for(;;){const{done:d,value:p}=await a.read();if(d)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 At.create(this.js,t.options.link.bucket):this).get(y)}if(!t.digest.startsWith(qr))return Promise.reject(new Error(`unknown digest type: ${t.digest}`));const s=xs(t.digest.substring(8));if(s===null)return Promise.reject(new Error(`unable to parse digest: ${t.digest}`));const i=z(),n={info:new $s(t),error:i};if(t.size===0)return n.data=so(),i.resolve(null),Promise.resolve(n);let o;const a=Je();a.orderedConsumer();const d=wr.create(),p=`$O.${this.name}.C.${t.nuid}`,_=await this.js.subscribe(p,a);return(async()=>{for await(const y of _)y.data.length>0&&(d.update(y.data),o.enqueue(y.data)),y.info.pending===0&&(Hi(s,d.digest())?o.close():o.error(new Error(`received a corrupt object, digests do not match received: ${t.digest} calculated ${s}`)),_.unsubscribe())})().then(()=>{i.resolve()}).catch(y=>{o.error(y),i.reject(y)}),n.data=new ReadableStream({start(y){o=y},cancel(){_.unsubscribe()}}),n}linkStore(e,t){if(!(t instanceof At))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 d=await this.info(e);return Promise.resolve(d)}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=Ee(),i=Ue();return i.set(fe.RollupHdr,fe.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 d=await this.info(t.name);if(d&&!d.deleted)return Promise.reject(new Error("an object already exists with that name"))}t.name=i;const o=Object.assign({},s,Dr(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 re,i=this._metaSubjectAll();try{await this.jsm.streams.getMessage(this.stream,{last_by_subj:i})}catch(d){d.code==="404"?(s.push(null),t=!0):s.stop(d)}const n=Ee(),o=Je();o.orderedConsumer(),e.includeHistory?o.deliverLastPerSubject():(t=!0,o.deliverNew()),o.callback((d,p)=>{var _;if(d){s.stop(d);return}if(p!==null){const y=n.decode(p.data);y.deleted&&e.ignoreDeletes===!0||s.push(y),((_=p.info)==null?void 0:_.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(d=>{s.stop(d)}),s}_chunkSubject(e){return`$O.${this.name}.C.${e}`}_metaSubject(e){return`$O.${this.name}.M.${st.encode(e)}`}_metaSubjectAll(){return`$O.${this.name}.M.>`}async init(e={}){try{this.stream=zn(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=mt.New,s.subjects=[`$O.${this.name}.C.>`,`$O.${this.name}.M.>`],e.placement&&(s.placement=e.placement),e.metadata&&(s.metadata=e.metadata),typeof e.compression=="boolean"&&(s.compression=e.compression?He.S2:He.None);try{await this.jsm.streams.info(s.name)}catch(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 At(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?St.bind(this.js,e,t):St.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?At.create(this.js,e,t):Promise.reject(new Error(`objectstore is only supported on servers ${n} or better`))}}class Us extends gt{constructor(t,s){super(t,s);h(this,"consumers");h(this,"streams");h(this,"consumerAPI");h(this,"streamAPI");this.consumerAPI=new qt(t,s),this.streamAPI=new Ts(t,s),this.consumers=new Ns(this.consumerAPI),this.streams=new to(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=be,i){i=i||{},i.expect=i.expect||{};const n=(i==null?void 0:i.headers)||Ue();i&&(i.msgID&&n.set(Re.MsgIdHdr,i.msgID),i.expect.lastMsgID&&n.set(Re.ExpectedLastMsgIdHdr,i.expect.lastMsgID),i.expect.streamName&&n.set(Re.ExpectedStreamHdr,i.expect.streamName),typeof i.expect.lastSequence=="number"&&n.set(Re.ExpectedLastSeqHdr,`${i.expect.lastSequence}`),typeof i.expect.lastSubjectSequence=="number"&&n.set(Re.ExpectedLastSubjectSequenceHdr,`${i.expect.lastSubjectSequence}`));const o=i.timeout||this.timeout,a={};o&&(a.timeout=o),i&&(a.headers=n);let{retries:d,retry_delay:p}=i;d=d||1,p=p||250;let _;for(let x=0;x<d;x++)try{_=await this.nc.request(t,s,a);break}catch(P){if(P.code==="503"&&x+1<d)await Xe(p);else throw P}const y=this.parseJsResponse(_);if(y.stream==="")throw N.errorForCode(O.JetStreamInvalidAck);return y.duplicate=y.duplicate?y.duplicate:!1,y}async pull(t,s,i=0){le(t),Ze(s);let n=this.timeout;i>n&&(n=i),i=i<0?0:G(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}),d=Qe(a);if(d)throw d;return vt(a,this.timeout)}fetch(t,s,i={}){le(t),Ze(s);let n=null;const o=(i.max_bytes??0)>0;let a=0;const d=o?i.max_bytes:0;let p=null;const _={};if(_.batch=i.batch||1,d){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`);_.max_bytes=d}_.no_wait=i.no_wait||!1,_.no_wait&&_.expires&&(_.expires=0);const y=i.expires||0;if(y&&(_.expires=G(y)),y===0&&_.no_wait===!1)throw new Error("expires or no_wait is required");const x=i.idle_heartbeat||0;x&&(_.idle_heartbeat=G(x),i.delay_heartbeat===!0&&(_.idle_heartbeat=G(x*4)));const P=new re,I=_.batch;let T=0;P.protocolFilterFn=(L,X=!1)=>bs(L.msg)?(p==null||p.work(),!1):!0,P.dispatchedFn=L=>{if(L){if(o&&(a+=L.data.length),T++,n&&L.info.pending===0)return;(P.getPending()===1&&L.info.pending===0||I===T||d>0&&a>=d)&&P.stop()}};const J=$e(this.nc.options.inboxPrefix),Q=this.nc.subscribe(J,{max:i.batch,callback:(L,X)=>{L===null&&(L=Qe(X)),L!==null?(n&&(n.cancel(),n=null),vi(L)?P.stop(Jr(L)===null?void 0:L):P.stop(L)):(p==null||p.work(),P.received++,P.push(vt(X,this.timeout)))}});return y&&(n=Ye(y),n.catch(()=>{Q.isClosed()||(Q.drain().catch(()=>{}),n=null),p&&p.cancel()})),(async()=>{try{x&&(p=new gs(x,L=>(P.push(()=>{P.err=new N(`${ve.IdleHeartbeatMissed}: ${L}`,O.JetStreamIdleHeartBeat)}),!0)))}catch{}await Q.closed,n!==null&&(n.cancel(),n=null),p&&p.cancel(),P.stop()})().catch(),this.nc.publish(`${this.prefix}.CONSUMER.MSG.NEXT.${t}.${s}`,this.jc.encode(_),{reply:J}),P}async pullSubscribe(t,s=Je()){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===ie.None||n===ie.All)throw new Error("ack policy for pull consumers must be explicit");const o=this._buildTypedSubscriptionOpts(i),a=new ao(this,i.deliver,o);a.info=i;try{await this._maybeCreateConsumer(i)}catch(d){throw a.unsubscribe(),d}return a}async subscribe(t,s=Je()){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 Hr(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=Je()){const i=br(s)?s.getOpts():s;if(i.isBind=br(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!==ie.NotSet&&i.config.ack_policy!==ie.None)throw new N("ordered consumer: ack_policy can only be set to 'none'",O.ApiError);if(i.config.durable_name&&i.config.durable_name.length>0)throw new N("ordered consumer: durable_name cannot be set",O.ApiError);if(i.config.deliver_subject&&i.config.deliver_subject.length>0)throw new N("ordered consumer: deliver_subject cannot be set",O.ApiError);if(i.config.max_deliver!==void 0&&i.config.max_deliver>1)throw new N("ordered consumer: max_deliver cannot be set",O.ApiError);if(i.config.deliver_group&&i.config.deliver_group.length>0)throw new N("ordered consumer: deliver_group cannot be set",O.ApiError);i.config.deliver_subject=$e(this.nc.options.inboxPrefix),i.config.ack_policy=ie.None,i.config.max_deliver=1,i.config.flow_control=!0,i.config.idle_heartbeat=i.config.idle_heartbeat||G(5e3),i.config.ack_wait=G(22*60*60*1e3),i.config.mem_storage=!0,i.config.num_replicas=1}if(i.config.ack_policy===ie.NotSet&&(i.config.ack_policy=ie.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||$e(this.nc.options.inboxPrefix),i}_buildTypedSubscriptionOpts(t){const s={};return s.adapter=co(t.callbackFn===void 0,this.timeout),s.ingestionFilterFn=Us.ingestionFn(t.ordered),s.protocolFilterFn=(i,n=!1)=>{const o=i;return ms(o.msg)?(n||o.msg.respond(),!1):!0},!t.mack&&t.config.ack_policy!==ie.None&&(s.dispatchedFn=lo),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:Z.All,ack_policy:ie.Explicit,ack_wait:G(30*1e3),replay_policy:et.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 d;const n=i;if(!s)return{ingest:!1,protocol:!1};const o=s;if(Qe(o.msg)||(d=n.monitor)==null||d.work(),bs(o.msg)){const p=t?n._checkHbOrderConsumer(o.msg):!0;return t||n.info.flow_control.heartbeat_count++,{ingest:p,protocol:!0}}else if(ms(o.msg))return n.info.flow_control.fc_count++,{ingest:!0,protocol:!0};return{ingest:t?n._checkOrderedConsumer(s):!0,protocol:!1}}}}class Ls{constructor(e){h(this,"options");h(this,"protocol");h(this,"draining");h(this,"listeners");h(this,"_services");this.draining=!1,this.options=Pn(e),this.listeners=[]}static connect(e={}){return new Promise((t,s)=>{const i=new Ls(e);Jt.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(O.ConnectionClosed);if(t&&this.isDraining()||s&&this.protocol.noMorePublishing)throw N.errorForCode(O.ConnectionDraining);if(e=e||"",e.length===0)throw N.errorForCode(O.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 Tr(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=be,s={maxWait:1e3,maxMessages:-1}){const i=!this.protocol.options.noAsyncTraces;try{this._check(e,!0,!0)}catch(d){return Promise.reject(d)}if(s.strategy=s.strategy||Oe.Timer,s.maxWait=s.maxWait||1e3,s.maxWait<1)return Promise.reject(new N("timeout",O.InvalidOption));const n=new re;function o(d){n.push(()=>{n.stop(d)})}function a(d,p){d||p===null?o(d===null?void 0:d):n.push(p)}if(s.noMux){const d=i?new Error().stack:null;let p=typeof s.maxMessages=="number"&&s.maxMessages>0?s.maxMessages:-1;const _=this.subscribe($e(this.options.inboxPrefix),{callback:(I,T)=>{var J,Q;if(((J=T==null?void 0:T.data)==null?void 0:J.length)===0&&((Q=T==null?void 0:T.headers)==null?void 0:Q.status)===O.NoResponders&&(I=N.errorForCode(O.NoResponders)),I){d&&(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=z()),this.pongs.push(e),this.outbound.fill(Nr),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}${Ft}`):e.push(`SUB ${s.subject} ${s.sid}${Ft}`)}),e.length&&this.transport.send(ft(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 Tr(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 Nn="$SRV";class Mr{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||Ue(),(n=i.headers)==null||n.set(Rt,`${e}`),(o=i.headers)==null||o.set(jt,t),this.msg.respond(s,i)}json(e){return this.msg.json(e)}string(){return this.msg.string()}}class wt{constructor(e,t="",s=""){h(this,"subject");h(this,"queue");h(this,"srv");t!==""&&Mn("service group",t);let i="";if(e instanceof xt)this.srv=e,i="";else if(e instanceof wt){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;pt("endpoint",e);let{subject:i,handler:n,metadata:o,queue:a}=s;i=i||e,a=a||this.queue,Tn("endpoint subject",i),i=this.calcSubject(this.subject,i);const d={name:e,subject:i,queue:a,handler:n,metadata:o};return this.srv._addEndpoint(d)}addGroup(e="",t=""){return new wt(this,e,t)}}function Tn(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 Mn(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 xt{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"),pt("name",this.config.name),pt("queue",this.config.queue),Ke(this.config.version),this._id=qe.next(),this.internal=[],this._done=z(),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??Nn;return t===""&&s===""?`${n}.${e}`:(pt("control subject name",t),s!==""?(pt("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=Ue();if(e instanceof Nt){const s=e;t.set(jt,s.message),t.set(Rt,`${s.code}`)}else t.set(jt,e.message),t.set(Rt,"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 $n(i,n,s),a.queue=s;const d=o?(p,_)=>{if(p){this.close(p);return}const y=Date.now();try{o(p,new Mr(_))}catch(x){a.stats.countError(x),_==null||_.respond(be,{headers:this.errorToHeader(x)})}finally{a.stats.countLatency(y)}}:void 0;return a.sub=this.nc.subscribe(n,{callback:d,queue:s}),a.sub.closed.then(()=>{this._stopped||this.close(new Error(`required subscription ${e.subject} stopped`)).catch()}).catch(p=>{if(!this._stopped){const _=new Error(`required subscription ${e.subject} errored: ${p.message}`);_.stack=p.stack,this.close(_).catch()}}),a}info(){return{type:dt.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:dt.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=xt.controlSubject(t,i,n),o.handler=s,this.setupHandler(o,!0)}start(){const e=ve(),t=(o,a)=>o?(this.close(o),Promise.reject(o)):this.stats().then(d=>(a==null||a.respond(e.encode(d)),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(Be.PING,n),this.addInternalHandler(Be.STATS,t),this.addInternalHandler(Be.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:dt.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 wt(this,e,t)}addEndpoint(e,t){return new wt(this).addEndpoint(e,t)}_addEndpoint(e){const t=new re;t.noIterator=typeof e.handler=="function",t.noIterator||(e.handler=(i,n)=>{i?this.stop(i).catch():t.push(new Mr(n))},t.iterClosed.then(()=>{this.close().catch()}));const s=this.setupHandler(e,!1);return s.qi=t,this.handlers.push(s),t}}class $n{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+=G(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:d,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:d,queue_group:p}}stats(e){const t=e;return(t==null?void 0:t.noIterator)===!1&&(this.processing_time=G(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 Un{constructor(e,t={strategy:Oe.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(Be.PING,e,t)}stats(e="",t=""){return this.q(Be.STATS,e,t)}info(e="",t=""){return this.q(Be.INFO,e,t)}async q(e,t="",s=""){const i=new re,n=ve(),o=xt.controlSubject(e,t,s,this.prefix),a=await this.nc.requestMany(o,be,this.opts);return(async()=>{for await(const d of a)try{const p=n.decode(d.data);i.push(p)}catch(p){i.push(()=>{i.stop(p)})}i.push(()=>{i.stop()})})().catch(d=>{i.stop(d)}),i}}function $r(){return{key:{encode(r){return r},decode(r){return r}},value:{encode(r){return r},decode(r){return r}}}}function Ln(){return{replicas:1,history:1,timeout:2e3,max_bytes:-1,maxValueSize:-1,codec:$r(),storage:ys.File}}const zt="KV-Operation",Ur="$KV",qn=/^[-/=.\w]+$/,Fn=/^[-/=.>*\w]+$/,Bn=/^[-\w]+$/;function Dn(r){if(r.startsWith(".")||r.endsWith(".")||!qn.test(r))throw new Error(`invalid key: ${r}`)}function Hn(r){if(r.startsWith(".")||r.endsWith(".")||!Fn.test(r))throw new Error(`invalid key: ${r}`)}function Jn(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 Gt(r){if(!Bn.test(r))throw new Error(`invalid bucket name: ${r}`)}var Re;(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"})(Re||(Re={}));class St{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",Dn);h(this,"validateSearchKey",Hn);h(this,"hasWildcards",Jn);Gt(e),this.js=t,this.jsm=s,this.bucket=e,this.prefix=Ur,this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create(e,t,s={}){Gt(t);const i=await e.jetstreamManager(),n=new St(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}};Gt(t);const o=new St(t,e,i);return n.config.name=s.streamName??o.bucketName(),Object.assign(o,n),o.stream=n.config.name,o.codec=s.codec||$r(),o.direct=n.config.allow_direct??!1,o.initializePrefixes(n),o}async init(e={}){const t=Object.assign(Ln(),e);this.codec=t.codec;const s={};this.stream=s.name=e.streamName??this.bucketName(),s.retention=_s.Limits,s.max_msgs_per_subject=t.history,t.maxBucketSize&&(t.max_bytes=t.maxBucketSize),t.max_bytes&&(s.max_bytes=t.max_bytes),s.max_msg_size=t.maxValueSize,s.storage=t.storage;const 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(ye)||(y.name=`${ye}${y.name}`),s.mirror=y,s.mirror_direct=!0}else if(e.sources){const y=e.sources.map(x=>{const P=Object.assign({},x),I=P.name.startsWith(ye)?P.name.substring(ye.length):P.name;return P.name.startsWith(ye)||(P.name=`${ye}${P.name}`),!x.external&&I!==this.bucket&&(P.subject_transforms=[{src:`$KV.${I}.>`,dest:`$KV.${this.bucket}.>`}]),P});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?He.S2:He.None);const n=this.js.nc,o=n.getServerVersion(),a=o?Ss(o,Ke("2.7.2"))>=0:!1;s.discard=a?mt.New:mt.Old;const{ok:d,min:p}=n.features.get(H.JS_ALLOW_DIRECT);if(!d&&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:d,s.allow_direct=e.allow_direct,this.direct=s.allow_direct,s.num_replicas=t.replicas,t.ttl&&(s.max_age=G(t.ttl)),s.allow_rollup_hdrs=!0;let _;try{_=await this.jsm.streams.info(s.name),!_.config.allow_direct&&this.direct===!0&&(this.direct=!1)}catch(y){if(y.message==="stream not found")_=await this.jsm.streams.add(s);else throw y}this.initializePrefixes(_)}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(ye)&&(s=s.substring(ye.length)),t.external&&t.external.api!==""){const i=t.name.substring(ye.length);this.useJsPrefix=!1,this.prefix=`$KV.${i}`,this.editPrefix=`${t.external.api}.$KV.${s}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${ye}${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}`:`${Ur}.${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(fe.MessageSizeHdr)||"";return s!==""?parseInt(s,10):e.length}smToEntry(e){return new no(this.bucket,this.prefixLen,e)}jmToEntry(e){const t=this.decodeKey(e.subject.substring(this.prefixLen));return new oo(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 d=Ue();n.headers=d,d.set(Re.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`)}try{return(await this.js.publish(this.subjectForKey(i,!0),t,n)).seq}catch(d){const p=d;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(d)}}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===O.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=z(),s=[],i=await this.watch({key:">",initializedFn:()=>{t.resolve()}});(async()=>{for await(const d of i)(d.operation==="DEL"||d.operation==="PURGE")&&s.push(d)})().then(),await t,i.stop();const n=Date.now()-e,o=s.map(d=>{const p=this.subjectForKey(d.key);return d.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((d,p)=>(d.purged+=p.purged,d))}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=Ue();n.set(zt,t),t==="PURGE"&&n.set(fe.RollupHdr,fe.RollupValueSubject),s!=null&&s.previousSeq&&n.set(Re.ExpectedLastSubjectSequenceHdr,`${s.previousSeq}`),await this.js.publish(this.subjectForKey(i,!0),be,{headers:n})}_buildCC(e,t,s={}){let n=(Array.isArray(e)?e:[e]).map(d=>{const p=this.encodeKey(d);return this.validateSearchKey(d),this.fullKeyName(p)}),o=Z.LastPerSubject;t===ke.AllHistory&&(o=Z.All),t===ke.UpdatesOnly&&(o=Z.New);let a;return n.length===1&&(a=n[0],n=void 0),Object.assign({deliver_policy:o,ack_policy:ie.None,filter_subjects:n,filter_subject:a,flow_control:!0,idle_heartbeat:G(5*1e3)},s)}remove(e){return this.purge(e)}async history(e={}){const t=e.key??">",s=new re,i={};i.headers_only=e.headers_only||!1;let n;n=()=>{s.stop()};let o=0;const a=this._buildCC(t,ke.AllHistory,i),d=a.filter_subject,p=Je(a);p.bindStream(this.stream),p.orderedConsumer(),p.callback((y,x)=>{if(y){s.stop(y);return}if(x){const P=this.jmToEntry(x);s.push(P),s.received++,(n&&o>0&&s.received>=o||x.info.pending===0)&&(s.push(n),n=void 0)}});const _=await this.js.subscribe(d,p);if(n){const{info:{last:y}}=_,x=y.num_pending+y.delivered.consumer_seq;if(x===0||s.received>=x)try{n()}catch(P){s.stop(P)}finally{n=void 0}else o=x}return s._data=_,s.iterClosed.then(()=>{_.unsubscribe()}),_.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 re,i={};i.headers_only=e.headers_only||!1;let n=ke.LastValue;e.include===ke.AllHistory?n=ke.AllHistory:e.include===ke.UpdatesOnly&&(n=ke.UpdatesOnly);const o=e.ignoreDeletes===!0;let a=e.initializedFn,d=0;const p=this._buildCC(t,n,i),_=p.filter_subject,y=Je(p);this.canSetWatcherName()&&y.consumerName(qe.next()),y.bindStream(this.stream),e.resumeFromRevision&&e.resumeFromRevision>0&&y.startSequence(e.resumeFromRevision),y.orderedConsumer(),y.callback((P,I)=>{if(P){s.stop(P);return}if(I){const T=this.jmToEntry(I);if(o&&T.operation==="DEL")return;s.push(T),s.received++,a&&(d>0&&s.received>=d||I.info.pending===0)&&(s.push(a),a=void 0)}});const x=await this.js.subscribe(_,y);if(a){const{info:{last:P}}=x,I=P.num_pending+P.delivered.consumer_seq;if(I===0||s.received>=I)try{a()}catch(T){s.stop(T)}finally{a=void 0}else d=I}return s._data=x,s.iterClosed.then(()=>{x.unsubscribe()}),x.closed.then(()=>{s.stop()}).catch(P=>{s.stop(P)}),s}async keys(e=">"){const t=new re,s=this._buildCC(e,ke.LastValue,{headers_only:!0}),i=Array.isArray(e)?">":s.filter_subject,n=Je(s);n.bindStream(this.stream),n.orderedConsumer();const o=await this.js.subscribe(i,n);return(async()=>{var d;for await(const p of o){const _=(d=p.headers)==null?void 0:d.get(zt);if(_!=="DEL"&&_!=="PURGE"){const y=this.decodeKey(p.subject.substring(this.prefixLen));t.push(y)}p.info.pending===0&&o.unsubscribe()}})().then(()=>{t.stop()}).catch(d=>{t.stop(d)}),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 Lr(i,t)}}class Lr{constructor(e,t=""){h(this,"si");h(this,"cluster");this.si=e,this.cluster=t}get bucket(){return this.si.config.name.startsWith(ye)?this.si.config.name.substring(ye.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 fs(this.si.config.max_age)}get bucket_location(){return this.cluster}get backingStore(){return this.si.config.storage}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get description(){return this.si.config.description??""}get maxBucketSize(){return this.si.config.max_bytes}get maxValueSize(){return this.si.config.max_msg_size}get max_bytes(){return this.si.config.max_bytes}get placement(){return this.si.config.placement||{cluster:"",tags:[]}}get placementCluster(){var e;return((e=this.si.config.placement)==null?void 0:e.cluster)??""}get republish(){return this.si.config.republish??{src:"",dest:""}}get streamInfo(){return this.si}get size(){return this.si.state.bytes}get metadata(){return this.si.config.metadata??{}}get compression(){return this.si.config.compression?this.si.config.compression!==He.None:!1}}const Cs="OBJ_",qr="SHA-256=";function zn(r){return Gt(r),`${Cs}${r}`}function Gn(r){return r.startsWith(Cs)?r.substring(4):r}class Is{constructor(e){h(this,"si");h(this,"backingStore");this.si=e,this.backingStore="JetStream"}get bucket(){return Gn(this.si.config.name)}get description(){return this.si.config.description??""}get ttl(){return this.si.config.max_age}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get sealed(){return this.si.config.sealed}get size(){return this.si.state.bytes}get streamInfo(){return this.si}get metadata(){return this.si.config.metadata}get compression(){return this.si.config.compression?this.si.config.compression!==He.None:!1}}function Kt(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 Ae;(function(r){r[r.Unset=-1]="Unset",r[r.Consume=0]="Consume",r[r.Fetch=1]="Fetch"})(Ae||(Ae={}));var Ne;(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"})(Ne||(Ne={}));var nt;(function(r){r.DebugEvent="debug",r.Discard="discard",r.Reset="reset",r.Next="next"})(nt||(nt={}));const Fr=Uint8Array.of(43,65,67,75),Kn=Uint8Array.of(45,78,65,75),vt=Uint8Array.of(43,87,80,73),Vn=Uint8Array.of(43,78,88,84),Wn=Uint8Array.of(43,84,69,82,77),Yn=Uint8Array.of(32);function Et(r,e=5e3){return new po(r,e)}class js extends re{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=$e(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(d=>{if(this.cleanupHandler)try{this.cleanupHandler(d)}catch{}});const{sub:a}=this;a&&a.unsubscribe(),this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(d,p)=>{var y,x,P,I;if(d){this.stop(d);return}if((y=this.monitor)==null||y.work(),p.subject===this.inbox){if(bs(p))return;const T=(x=p.headers)==null?void 0:x.code,J=((I=(P=p.headers)==null?void 0:P.description)==null?void 0:I.toLowerCase())||"unknown",{msgsLeft:Q,bytesLeft:L}=this.parseDiscard(p.headers);if(Q>0||L>0)this.pending.msgs-=Q,this.pending.bytes-=L,this.pending.requests--,this.notify(nt.Discard,{msgsLeft:Q,bytesLeft:L});else if(T===400){this.stop(new N(J,`${T}`));return}else if(T===409&&J==="consumer deleted"){if(this.notify(Ne.ConsumerDeleted,`${T} ${J}`),!this.refilling||this.abortOnMissingResource){const X=new N(J,`${T}`);this.stop(X);return}}else if(T===503){if(this.notify(Ne.NoResponders,`${T} No Responders`),!this.refilling||this.abortOnMissingResource){const X=new N("no responders",`${T}`);this.stop(X);return}}else this.notify(nt.DebugEvent,`${T} ${J}`)}else this._push(Et(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 gs(i,d=>(this.notify(Ne.HeartbeatsMissed,d),this.resetPending().then(()=>{}).catch(()=>{}),!1),{maxOut:2})),(async()=>{var p;const d=this.consumer.api.nc.status();this.statusIterator=d;for await(const _ of d)switch(_.type){case Se.Disconnect:(p=this.monitor)==null||p.cancel();break;case Se.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=ls([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(Ne.StreamNotFound,s),!this.refilling||this.abortOnMissingResource)return this.stop(o),!1}else if(o.message==="consumer not found"){if(t++,this.notify(Ne.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),d=Xe(a);await Promise.race([d,this.consumer.api.nc.closed()]),d.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(nt.Next,t)})}pullOptions(){const t=this.opts.max_messages-this.pending.msgs,s=this.opts.max_bytes-this.pending.bytes,i=G(this.opts.idle_heartbeat),n=G(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(fe.PendingMessagesHdr);i&&(s.msgsLeft=parseInt(i));const n=t==null?void 0:t.get(fe.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 re;return this.listeners.push(t),Promise.resolve(t)}}class Xn extends re{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 re;return this.listeners.push(t),Promise.resolve(t)}}class Rs{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 js(this,e,!0))}fetch(e={max_messages:100,expires:3e4}){const t=new js(this,e,!1),s=Math.round(t.opts.expires*1.05),i=Ye(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=z(),s=e;s.max_messages=1;const i=new js(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===Ne.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=Ye(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 Zn{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=qe.next(),typeof s.name_prefix=="string"&&($t("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=Ae.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:Z.StartSequence,opt_start_seq:e,ack_policy:ie.None,inactive_threshold:G(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||Z.StartSequence,(this.consumerOpts.deliver_policy===Z.LastPerSubject||this.consumerOpts.deliver_policy===Z.New||this.consumerOpts.deliver_policy===Z.Last)&&(delete s.opt_start_seq,s.deliver_policy=this.consumerOpts.deliver_policy),s.deliver_policy===Z.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=Z.StartTime,s.opt_start_time=this.consumerOpts.opt_start_time),this.consumerOpts.inactive_threshold&&(s.inactive_threshold=G(this.consumerOpts.inactive_threshold))),s}async resetConsumer(e=0){var o,a,d,p,_;qe.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=ls([((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),(d=this.iter)==null||d.notify(Ne.OrderedConsumerRecreated,n.name);break}catch(x){if(x.message==="stream not found"&&((p=this.iter)==null||p.notify(Ne.StreamNotFound,y),this.type===Ae.Fetch||this.opts.abort_on_missing_resource===!0))return(_=this.iter)==null||_.stop(x),Promise.reject(x);if(t&&y>=this.maxInitialReset)throw x;await Xe(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 d,p;t=t||{};const s=t.fromFetch||!1,i=t.orderedReset||!1;if(this.type===Ae.Fetch&&i){(d=this.iter)==null||d.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 Xn),this.consumer=new Rs(this.api,this.currentConsumer);const n=e;n.callback=this.internalHandler(this.serial);let o=null;this.type===Ae.Fetch&&s?o=await this.consumer.fetch(e):this.type===Ae.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(nt.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===Ae.Fetch)return Promise.reject(new Error("ordered consumer initialized as fetch"));if(this.type===Ae.Consume)return Promise.reject(new Error("ordered consumer doesn't support concurrent consume"));const{callback:s}=e;return s&&(this.userCallback=s),this.type=Ae.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===Ae.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=Ae.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=z();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 Ns{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 Rs(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 Rs(this.api,s)).catch(s=>Promise.reject(s)))}async ordered(e,t){await this.checkVersion();const s=this.api;return new Ts(s.nc,s.opts).info(e).then(n=>Promise.resolve(new Zn(this.api,e,t))).catch(n=>Promise.reject(n))}}class Vt{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 Vt(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 Ns(new qt(this.api.nc,this.api.opts)).getPullConsumerFor(e)}getConsumer(e){return new Ns(new qt(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 Ts extends gt{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:d,ok:p}=t.features.get(H.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!p)throw new Error(`${i} 'subject_transforms' requires server ${d}`)}}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),le(e.name),e.mirror=Kt(e.mirror),e.sources=(i=e.sources)==null?void 0:i.map(Kt);const s=await this._request(`${this.prefix}.STREAM.CREATE.${e.name}`,e);return this._fixInfo(s),s}async delete(e){return le(e),(await this._request(`${this.prefix}.STREAM.DELETE.${e}`)).success}async update(e,t={}){var a;if(typeof e=="object"){const d=e;e=d.name,t=d,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),le(e);const s=await this.info(e),i=Object.assign(s.config,t);i.mirror=Kt(i.mirror),i.sources=(a=i.sources)==null?void 0:a.map(Kt);const o=await this._request(`${this.prefix}.STREAM.UPDATE.${e}`,i);return this._fixInfo(o),o}async info(e,t){le(e);const s=`${this.prefix}.STREAM.INFO.${e}`;let n=await this._request(s,t),{total:o,limit:a}=n,d=n.state.subjects?Object.getOwnPropertyNames(n.state.subjects).length:1;if(o&&o>d){const p=[n],_=t||{};let y=0;for(;o>d;){y++,_.offset=a*y;const P=await this._request(s,_);o=P.total,p.push(P);const I=Object.getOwnPropertyNames(P.state.subjects).length;if(d+=I,I<a)break}let x={};for(let P=0;P<p.length;P++)n=p[P],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 _t(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 le(e),await this._request(`${this.prefix}.STREAM.PURGE.${e}`,t)}async deleteMessage(e,t,s=!0){le(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){le(e);const i=await this._request(`${this.prefix}.STREAM.MSG.GET.${e}`,t);return new Br(i)}find(e){return this.findStream(e)}listKvs(){const e=s=>{var d;const n=s.streams.filter(p=>p.config.name.startsWith(ye));n.forEach(p=>{this._fixInfo(p)});let o="";return n.length&&(o=((d=this.nc.info)==null?void 0:d.cluster)??""),n.map(p=>new Lr(p,o))},t=`${this.prefix}.STREAM.LIST`;return new _t(t,e,this)}listObjectStores(){const e=s=>{const n=s.streams.filter(a=>a.config.name.startsWith(Cs));return n.forEach(a=>{this._fixInfo(a)}),n.map(a=>new Is(a))},t=`${this.prefix}.STREAM.LIST`;return new _t(t,e,this)}names(e=""){const t=e!=null&&e.length?{subject:e}:{},s=n=>n.streams,i=`${this.prefix}.STREAM.NAMES`;return new _t(i,s,this,t)}async get(e){const t=await this.info(e);return Promise.resolve(new Vt(this,t))}}class Qn extends gt{constructor(e,t){super(e,t)}async getMessage(e,t){le(e);let s=t;const{last_by_subj:i}=s;i&&(s=null);const n=s?this.jc.encode(s):be,o=this.opts.apiPrefix||"$JS.API",a=i?`${o}.DIRECT.GET.${e}.${i}`:`${o}.DIRECT.GET.${e}`,d=await this.nc.request(a,n,{timeout:this.timeout}),p=Qe(d);if(p)return Promise.reject(p);const _=new Ms(d);return Promise.resolve(_)}async getBatch(e,t){le(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,(d,p)=>d==="up_to_time"&&p instanceof Date?p.toISOString():p),o=new re,a=await this.nc.requestMany(i,n,{strategy:Oe.SentinelMsg});return(async()=>{var y,x,P;let d=!1,p=!1,_;for await(const I of a){if(!d){d=!0;const T=((y=I.headers)==null?void 0:y.code)||0;if(T!==0&&T<200||T>299){_=(x=I.headers)==null?void 0:x.description.toLowerCase();break}if(((P=I.headers)==null?void 0:P.get("Nats-Num-Pending"))===""){p=!0;break}}if(I.data.length===0)break;o.push(new Ms(I))}o.push(()=>{if(p)throw new Error("batch direct get not supported by the server");if(_)throw new Error(`bad request: ${_}`);o.stop()})})(),Promise.resolve(o)}}class Ms{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(tt.Subject)}get seq(){const e=this.header.last(tt.Sequence);return typeof e=="string"?parseInt(e):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(tt.TimeStamp)}get stream(){return this.header.last(tt.Stream)}json(e){return ve(e).decode(this.data)}string(){return ge.decode(this.data)}}h(Ms,"jc");class eo extends gt{constructor(t,s){super(t,s);h(this,"streams");h(this,"consumers");h(this,"direct");this.streams=new Ts(t,s),this.consumers=new qt(t,s),this.direct=new Qn(t,s)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return this.nc.jetstream(this.getOptions())}advisories(){const t=new re;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 Br{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):be}get header(){if(!this._header)if(this.smr.message.hdrs){const e=this._parse(this.smr.message.hdrs);this._header=De.decode(e)}else this._header=Ue();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 ve(e).decode(this.data)}string(){return ge.decode(this.data)}}h(Br,"jc");class to{constructor(e){h(this,"api");this.api=e}get(e){return this.api.info(e).then(t=>new Vt(this.api,t))}}class $s{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=De.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 Dr(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 so(){return new ReadableStream({pull(r){r.enqueue(new Uint8Array(0)),r.close()}})}class At{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 $s(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=ve().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 Is(e)))}async status(e){const t=await this._si(e);return t===null?Promise.reject(new Error("object store not found")):Promise.resolve(new Is(t))}destroy(){return this.jsm.streams.delete(this.stream)}async _put(e,t,s){var pe;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,d=(a==null?void 0:a.max_payload)||1024;e=e||{},e.options=e.options||{};let p=((pe=e.options)==null?void 0:pe.max_chunk_size)||128*1024;p=p>d?d:p,e.options.max_chunk_size=p;const _=await this.info(e.name),{name:y,error:x}=this._checkNotEmpty(e.name);if(x)return Promise.reject(x);const P=qe.next(),I=this._chunkSubject(P),T=this._metaSubject(y),J=Object.assign({bucket:this.name,nuid:P,size:0,chunks:0},Dr(e)),Q=z(),L=[],X=new rt;try{const w=t?t.getReader():null,j=wr.create();for(;;){const{done:F,value:R}=w?await w.read():{done:!0,value:void 0};if(F){if(X.size()>0){const U=X.drain();j.update(U),J.chunks++,J.size+=U.length,L.push(this.js.publish(I,U,{timeout:n}))}await Promise.all(L),L.length=0,J.mtime=new Date().toISOString();const A=st.encode(j.digest());J.digest=`${qr}${A}`,J.deleted=!1;const $=Ue();typeof o=="number"&&$.set(Re.ExpectedLastSubjectSequenceHdr,`${o}`),$.set(fe.RollupHdr,fe.RollupValueSubject);const q=await this.js.publish(T,ve().encode(J),{headers:$,timeout:n});if(J.revision=q.seq,_)try{await this.jsm.streams.purge(this.stream,{filter:`$O.${this.name}.C.${_.nuid}`})}catch{}Q.resolve(new $s(J));break}if(R)for(X.fill(R);X.size()>p;){J.chunks++,J.size+=p;const A=X.drain(e.options.max_chunk_size);j.update(A),L.push(this.js.publish(I,A,{timeout:n}))}}}catch(w){await this.jsm.streams.purge(this.stream,{filter:I}),Q.reject(w)}return Q}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 rt,a=n.getReader();for(;;){const{done:d,value:p}=await a.read();if(d)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 At.create(this.js,t.options.link.bucket):this).get(y)}if(!t.digest.startsWith(qr))return Promise.reject(new Error(`unknown digest type: ${t.digest}`));const s=xs(t.digest.substring(8));if(s===null)return Promise.reject(new Error(`unable to parse digest: ${t.digest}`));const i=z(),n={info:new $s(t),error:i};if(t.size===0)return n.data=so(),i.resolve(null),Promise.resolve(n);let o;const a=Je();a.orderedConsumer();const d=wr.create(),p=`$O.${this.name}.C.${t.nuid}`,_=await this.js.subscribe(p,a);return(async()=>{for await(const y of _)y.data.length>0&&(d.update(y.data),o.enqueue(y.data)),y.info.pending===0&&(Hi(s,d.digest())?o.close():o.error(new Error(`received a corrupt object, digests do not match received: ${t.digest} calculated ${s}`)),_.unsubscribe())})().then(()=>{i.resolve()}).catch(y=>{o.error(y),i.reject(y)}),n.data=new ReadableStream({start(y){o=y},cancel(){_.unsubscribe()}}),n}linkStore(e,t){if(!(t instanceof At))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 d=await this.info(e);return Promise.resolve(d)}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=ve(),i=Ue();return i.set(fe.RollupHdr,fe.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 d=await this.info(t.name);if(d&&!d.deleted)return Promise.reject(new Error("an object already exists with that name"))}t.name=i;const o=Object.assign({},s,Dr(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 re,i=this._metaSubjectAll();try{await this.jsm.streams.getMessage(this.stream,{last_by_subj:i})}catch(d){d.code==="404"?(s.push(null),t=!0):s.stop(d)}const n=ve(),o=Je();o.orderedConsumer(),e.includeHistory?o.deliverLastPerSubject():(t=!0,o.deliverNew()),o.callback((d,p)=>{var _;if(d){s.stop(d);return}if(p!==null){const y=n.decode(p.data);y.deleted&&e.ignoreDeletes===!0||s.push(y),((_=p.info)==null?void 0:_.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(d=>{s.stop(d)}),s}_chunkSubject(e){return`$O.${this.name}.C.${e}`}_metaSubject(e){return`$O.${this.name}.M.${st.encode(e)}`}_metaSubjectAll(){return`$O.${this.name}.M.>`}async init(e={}){try{this.stream=zn(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=mt.New,s.subjects=[`$O.${this.name}.C.>`,`$O.${this.name}.M.>`],e.placement&&(s.placement=e.placement),e.metadata&&(s.metadata=e.metadata),typeof e.compression=="boolean"&&(s.compression=e.compression?He.S2:He.None);try{await this.jsm.streams.info(s.name)}catch(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 At(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?St.bind(this.js,e,t):St.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?At.create(this.js,e,t):Promise.reject(new Error(`objectstore is only supported on servers ${n} or better`))}}class Us extends gt{constructor(t,s){super(t,s);h(this,"consumers");h(this,"streams");h(this,"consumerAPI");h(this,"streamAPI");this.consumerAPI=new qt(t,s),this.streamAPI=new Ts(t,s),this.consumers=new Ns(this.consumerAPI),this.streams=new to(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=be,i){i=i||{},i.expect=i.expect||{};const n=(i==null?void 0:i.headers)||Ue();i&&(i.msgID&&n.set(Re.MsgIdHdr,i.msgID),i.expect.lastMsgID&&n.set(Re.ExpectedLastMsgIdHdr,i.expect.lastMsgID),i.expect.streamName&&n.set(Re.ExpectedStreamHdr,i.expect.streamName),typeof i.expect.lastSequence=="number"&&n.set(Re.ExpectedLastSeqHdr,`${i.expect.lastSequence}`),typeof i.expect.lastSubjectSequence=="number"&&n.set(Re.ExpectedLastSubjectSequenceHdr,`${i.expect.lastSubjectSequence}`));const o=i.timeout||this.timeout,a={};o&&(a.timeout=o),i&&(a.headers=n);let{retries:d,retry_delay:p}=i;d=d||1,p=p||250;let _;for(let x=0;x<d;x++)try{_=await this.nc.request(t,s,a);break}catch(P){if(P.code==="503"&&x+1<d)await Xe(p);else throw P}const y=this.parseJsResponse(_);if(y.stream==="")throw N.errorForCode(O.JetStreamInvalidAck);return y.duplicate=y.duplicate?y.duplicate:!1,y}async pull(t,s,i=0){le(t),Ze(s);let n=this.timeout;i>n&&(n=i),i=i<0?0:G(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}),d=Qe(a);if(d)throw d;return Et(a,this.timeout)}fetch(t,s,i={}){le(t),Ze(s);let n=null;const o=(i.max_bytes??0)>0;let a=0;const d=o?i.max_bytes:0;let p=null;const _={};if(_.batch=i.batch||1,d){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`);_.max_bytes=d}_.no_wait=i.no_wait||!1,_.no_wait&&_.expires&&(_.expires=0);const y=i.expires||0;if(y&&(_.expires=G(y)),y===0&&_.no_wait===!1)throw new Error("expires or no_wait is required");const x=i.idle_heartbeat||0;x&&(_.idle_heartbeat=G(x),i.delay_heartbeat===!0&&(_.idle_heartbeat=G(x*4)));const P=new re,I=_.batch;let T=0;P.protocolFilterFn=(L,X=!1)=>bs(L.msg)?(p==null||p.work(),!1):!0,P.dispatchedFn=L=>{if(L){if(o&&(a+=L.data.length),T++,n&&L.info.pending===0)return;(P.getPending()===1&&L.info.pending===0||I===T||d>0&&a>=d)&&P.stop()}};const J=$e(this.nc.options.inboxPrefix),Q=this.nc.subscribe(J,{max:i.batch,callback:(L,X)=>{L===null&&(L=Qe(X)),L!==null?(n&&(n.cancel(),n=null),Ei(L)?P.stop(Jr(L)===null?void 0:L):P.stop(L)):(p==null||p.work(),P.received++,P.push(Et(X,this.timeout)))}});return y&&(n=Ye(y),n.catch(()=>{Q.isClosed()||(Q.drain().catch(()=>{}),n=null),p&&p.cancel()})),(async()=>{try{x&&(p=new gs(x,L=>(P.push(()=>{P.err=new N(`${Ee.IdleHeartbeatMissed}: ${L}`,O.JetStreamIdleHeartBeat)}),!0)))}catch{}await Q.closed,n!==null&&(n.cancel(),n=null),p&&p.cancel(),P.stop()})().catch(),this.nc.publish(`${this.prefix}.CONSUMER.MSG.NEXT.${t}.${s}`,this.jc.encode(_),{reply:J}),P}async pullSubscribe(t,s=Je()){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===ie.None||n===ie.All)throw new Error("ack policy for pull consumers must be explicit");const o=this._buildTypedSubscriptionOpts(i),a=new ao(this,i.deliver,o);a.info=i;try{await this._maybeCreateConsumer(i)}catch(d){throw a.unsubscribe(),d}return a}async subscribe(t,s=Je()){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 Hr(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=Je()){const i=br(s)?s.getOpts():s;if(i.isBind=br(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!==ie.NotSet&&i.config.ack_policy!==ie.None)throw new N("ordered consumer: ack_policy can only be set to 'none'",O.ApiError);if(i.config.durable_name&&i.config.durable_name.length>0)throw new N("ordered consumer: durable_name cannot be set",O.ApiError);if(i.config.deliver_subject&&i.config.deliver_subject.length>0)throw new N("ordered consumer: deliver_subject cannot be set",O.ApiError);if(i.config.max_deliver!==void 0&&i.config.max_deliver>1)throw new N("ordered consumer: max_deliver cannot be set",O.ApiError);if(i.config.deliver_group&&i.config.deliver_group.length>0)throw new N("ordered consumer: deliver_group cannot be set",O.ApiError);i.config.deliver_subject=$e(this.nc.options.inboxPrefix),i.config.ack_policy=ie.None,i.config.max_deliver=1,i.config.flow_control=!0,i.config.idle_heartbeat=i.config.idle_heartbeat||G(5e3),i.config.ack_wait=G(22*60*60*1e3),i.config.mem_storage=!0,i.config.num_replicas=1}if(i.config.ack_policy===ie.NotSet&&(i.config.ack_policy=ie.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||$e(this.nc.options.inboxPrefix),i}_buildTypedSubscriptionOpts(t){const s={};return s.adapter=co(t.callbackFn===void 0,this.timeout),s.ingestionFilterFn=Us.ingestionFn(t.ordered),s.protocolFilterFn=(i,n=!1)=>{const o=i;return ms(o.msg)?(n||o.msg.respond(),!1):!0},!t.mack&&t.config.ack_policy!==ie.None&&(s.dispatchedFn=lo),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:Z.All,ack_policy:ie.Explicit,ack_wait:G(30*1e3),replay_policy:et.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 d;const n=i;if(!s)return{ingest:!1,protocol:!1};const o=s;if(Qe(o.msg)||(d=n.monitor)==null||d.work(),bs(o.msg)){const p=t?n._checkHbOrderConsumer(o.msg):!0;return t||n.info.flow_control.heartbeat_count++,{ingest:p,protocol:!0}}else if(ms(o.msg))return n.info.flow_control.fc_count++,{ingest:!0,protocol:!0};return{ingest:t?n._checkOrderedConsumer(s):!0,protocol:!1}}}}class Ls{constructor(e){h(this,"options");h(this,"protocol");h(this,"draining");h(this,"listeners");h(this,"_services");this.draining=!1,this.options=Pn(e),this.listeners=[]}static connect(e={}){return new Promise((t,s)=>{const i=new Ls(e);Jt.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(O.ConnectionClosed);if(t&&this.isDraining()||s&&this.protocol.noMorePublishing)throw N.errorForCode(O.ConnectionDraining);if(e=e||"",e.length===0)throw N.errorForCode(O.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 Tr(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=be,s={maxWait:1e3,maxMessages:-1}){const i=!this.protocol.options.noAsyncTraces;try{this._check(e,!0,!0)}catch(d){return Promise.reject(d)}if(s.strategy=s.strategy||Oe.Timer,s.maxWait=s.maxWait||1e3,s.maxWait<1)return Promise.reject(new N("timeout",O.InvalidOption));const n=new re;function o(d){n.push(()=>{n.stop(d)})}function a(d,p){d||p===null?o(d===null?void 0:d):n.push(p)}if(s.noMux){const d=i?new Error().stack:null;let p=typeof s.maxMessages=="number"&&s.maxMessages>0?s.maxMessages:-1;const _=this.subscribe($e(this.options.inboxPrefix),{callback:(I,T)=>{var J,Q;if(((J=T==null?void 0:T.data)==null?void 0:J.length)===0&&((Q=T==null?void 0:T.headers)==null?void 0:Q.status)===O.NoResponders&&(I=N.errorForCode(O.NoResponders)),I){d&&(I.stack+=`
|
|
24
24
|
|
|
25
25
|
${d}`),y(I);return}a(null,T),s.strategy===Oe.Count&&(p--,p===0&&y()),s.strategy===Oe.JitterTimer&&(P(),x=setTimeout(()=>{y()},300)),s.strategy===Oe.SentinelMsg&&T&&T.data.length===0&&y()}});_.requestSubject=e,_.closed.then(()=>{o()}).catch(I=>{n.stop(I)});const y=I=>{I&&n.push(()=>{throw I}),P(),_.drain().then(()=>{o()}).catch(T=>{o()})};n.iterClosed.then(()=>{P(),_==null||_.unsubscribe()}).catch(I=>{P(),_==null||_.unsubscribe()});try{this.publish(e,t,{reply:_.getSubject()})}catch(I){y(I)}let x=setTimeout(()=>{y()},s.maxWait);const P=()=>{x&&clearTimeout(x)}}else{const d=s;d.callback=a,n.iterClosed.then(()=>{p.cancel()}).catch(_=>{p.cancel(_)});const p=new Ji(this.protocol.muxSubscriptions,e,d);this.protocol.request(p);try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${p.token}`,headers:s.headers})}catch(_){p.cancel(_)}}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",O.InvalidOption));if(!s.noMux&&s.reply)return Promise.reject(new N("reply can only be used with noMux",O.InvalidOption));if(s.noMux){const n=s.reply?s.reply:$e(this.options.inboxPrefix),o=z(),a=i?new Error:null,d=this.subscribe(n,{max:1,timeout:s.timeout,callback:(p,_)=>{p?(a&&p.code!==O.Timeout&&(p.stack+=`
|
|
26
26
|
|
|
27
27
|
${a.stack}`),d.unsubscribe(),o.reject(p)):(p=fr(_),p?(a&&(p.stack+=`
|
|
28
28
|
|
|
29
|
-
${a.stack}`),o.reject(p)):o.resolve(_))}});return d.requestSubject=e,this.protocol.publish(e,t,{reply:n,headers:s.headers}),o}else{const n=new Sr(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(O.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(N.errorForCode(O.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(O.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 re;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 eo(this,e);if(e.checkAPI!==!1)try{await t.getAccountInfo()}catch(s){const i=s;throw i.code===O.NoResponders&&(i.code=O.JetStreamNotEnabled),i}return t}jetstream(e={}){return new Us(this,e)}getServerVersion(){const e=this.info;return e?Ke(e.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw N.errorForCode(O.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 io(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(N.errorForCode(O.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(O.ConnectionDraining)):this.protocol.reconnect()}}class io{constructor(e){h(this,"nc");this.nc=e}add(e){try{return new xt(this.nc,e).start()}catch(t){return Promise.reject(t)}}client(e,t){return new Un(this.nc,e,t)}}class no{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(zt)||"PUT"}get length(){const e=this.sm.header.get(fe.MessageSizeHdr)||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class oo{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(fs(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var e;return((e=this.sm.headers)==null?void 0:e.get(zt))||"PUT"}get delta(){return this.sm.info.pending}get length(){var t;const e=((t=this.sm.headers)==null?void 0:t.get(fe.MessageSizeHdr))||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Hr extends Vi{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=$e(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const n=this.info;n.config.name=qe.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=Z.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(d=>{const p=d,_=this.sub.info;_.last=p,this.info.config=p.config,this.info.name=p.name}).catch(d=>{const p=new N(`unable to recreate ordered consumer ${n.stream} at seq ${t}`,O.RequestError,d);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(fs(t))}_setupHbMonitoring(t,s=0){const i={cancelAfter:0,maxOut:2};s&&(i.cancelAfter=s);const n=this.sub,o=a=>{var _,y,x,P;const d=ki(409,`${ve.IdleHeartbeatMissed}: ${a}`,this.sub.subject);if(!((_=this.info)==null?void 0:_.ordered))this.sub.callback(null,d);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),(P=this.monitor)==null||P.restart(),!1}return!n.noIterator};this.monitor=new gs(t,o,i)}_checkHbOrderConsumer(t){const s=t.headers.get(fe.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const i=parseInt(t.headers.get(fe.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 ao extends Hr{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=G(a));let d=0;if(e.idle_heartbeat&&e.idle_heartbeat>0&&(d=e.idle_heartbeat,o.idle_heartbeat=G(d)),d&&a===0)throw new Error("idle_heartbeat requires expires");if(d>a)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),a&&d&&(this.monitor?this.monitor._change(d,a):this._setupHbMonitoring(d,a));const p=this.info.api,_=`${p.prefix}.CONSUMER.MSG.NEXT.${t}.${n}`,y=this.sub.subject;p.nc.publish(_,p.jc.encode(o),{reply:y})}}}function co(r,e){return r?uo(e):ho(e)}function ho(r){return(e,t)=>e?[e,null]:(e=Qe(t),e?[e,null]:[null,vt(t,r)])}function uo(r){return(e,t)=>{if(e)return[e,null];const s=Qe(t);return s!==null?[Jr(s),null]:[null,vt(t,r)]}}function Jr(r){if(r!==null)switch(r.code){case O.JetStream404NoMessages:case O.JetStream408RequestTimeout:return null;case O.JetStream409:return Ci(r)?r:null;default:return r}return null}function lo(r){r&&r.ack()}function fo(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 po{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=fo(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]===Et[0]&&e[1]===Et[1]&&e[2]===Et[2]&&e[3]===Et[3]}async ackAck(e){var s;e=e||{},e.timeout=e.timeout||this.timeout;const t=z();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 Sr(n.muxSubscriptions,this.msg.reply,{timeout:e.timeout},o);n.request(a);try{n.publish(this.msg.reply,Fr,{reply:`${n.muxSubscriptions.baseInbox}${a.token}`})}catch(d){a.cancel(d)}try{await Promise.race([a.timer,a.deferred]),t.resolve(!0)}catch(d){a.cancel(d),t.reject(d)}}else t.resolve(!1);return t}ack(){this.doAck(Fr)}nak(e){let t=Kn;e&&(t=lr().encode(`-NAK ${JSON.stringify({delay:G(e)})}`)),this.doAck(t)}working(){this.doAck(Et)}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=G(t.expires));const i=Ee().encode(s),n=rt.concat(Vn,Yn,i),o=e?{reply:e}:void 0;this.msg.respond(n,o)}term(e=""){let t=Wn;(e==null?void 0:e.length)>0&&(t=lr().encode(`+TERM ${e}`)),this.doAck(t)}json(){return this.msg.json()}string(){return this.msg.string()}}const mo="1.30.3",bo="nats.ws";class go{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=mo,this.lang=bo,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=z(),this.closedNotification=z()}async connect(e,t){const s=z();if(t.tls)return s.reject(new N("tls",O.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=rt.concat(...this.yields),a=en(o);if(a!==""){const d=Cn.exec(a);if(!d){t.debug&&console.error("!!!",Mt(o)),s.reject(new Error("unexpected response from server"));return}try{const p=JSON.parse(d[1]);On(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,O.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 Xe(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(`> ${Mt(e[t])}`),yield e[t];if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=z())}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(!this.isDiscarded())try{this.socket.send(e.buffer),this.options.debug&&console.info(`< ${Mt(e)}`);return}catch(t){this.options.debug&&console.error(`!!! ${Mt(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 _o(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,d=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}${d}${p}`}function yo(r={}){return Wi({defaultPort:443,urlParseFn:_o,factory:()=>new go}),Ls.connect(r)}const ze=Ee();class qs{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}async connect(e){var a;const{natsWsServerUrls:t,user:s,prefix:i}=e,n=t??[this.config.natsUrl];this.nc=await yo({servers:n});const o=s??new cs({authUrl:""}).getLastLoginData();if(!o)throw new Error("Please authenticate first by calling `auth` apis");this.userId=o.userId,this.sessionId=o.sessionId,this.globalPrefix=i??"",this.resolveConnected(!0),(a=this.onStatusChange)==null||a.call(this,!0),console.log("[nats] connected.",this.globalPrefix?`(prefix: ${this.globalPrefix})`:""),(async()=>{var d,p;for await(const _ of this.nc.status())switch(_.type!==Fe.PingTimer&&console.log("[nats] connection status:",_.type),_.type){case Se.Reconnect:(d=this.onStatusChange)==null||d.call(this,!0);break;case Se.Disconnect:case Se.Error:case Fe.Reconnecting:(p=this.onStatusChange)==null||p.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,ze.encode(t))}catch(s){throw console.error("[nats] publish failed:",s),s}}async call(e,t,s){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");try{const i=this.buildSubject(e);console.debug("[nats]>>",i);const n=await this.nc.request(i,ze.encode(t),{timeout:(s==null?void 0:s.timeoutInMs)??5e3}),o=ze.decode(n.data);if(!o.ok)throw new Error(o.message);return o.data}catch(i){throw console.error("[nats] request failed:",i),new Error("Api call failed.")}}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 d=a.slice(0,a.length-2).join("."),p=a[a.length-2],_=a[a.length-1],y=ze.decode(o.data);t(y,{subject:d,userId:p,sessionId:_})}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 d=a.slice(0,a.length-2).join("."),p=a[a.length-2],_=a[a.length-1],y=ze.decode(o.data);try{const x=await t(y,{subject:d,userId:p,sessionId:_});o.reply&&o.respond(ze.encode({ok:!0,data:x}))}catch(x){console.error("[nats] handle",x),o.reply&&o.respond(ze.encode({ok:!1,message:x.message}))}}catch(a){console.error("[nats] handle",a),o.reply&&o.respond(ze.encode({ok:!1,message:a.message}))}})(),()=>n.unsubscribe()}buildSubject(e){return[this.globalPrefix,e,this.userId,this.sessionId].filter(t=>t).join(".")}}function zr(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 wo{async getAudioBuffer(e,t,s){const i=[],n=crypto.randomUUID();return new Promise((o,a)=>{const d=new WebSocket(`${Wt.WSS_URL}?trustedclienttoken=${Wt.TRUSTED_CLIENT_TOKEN}&ConnectionId=${n}`);d.binaryType="arraybuffer";const p=So(e,t,s);d.addEventListener("open",()=>{const _=xo();d.send(_);const y=`X-RequestId:${n}\r
|
|
29
|
+
${a.stack}`),o.reject(p)):o.resolve(_))}});return d.requestSubject=e,this.protocol.publish(e,t,{reply:n,headers:s.headers}),o}else{const n=new Sr(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(O.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(N.errorForCode(O.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(O.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 re;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 eo(this,e);if(e.checkAPI!==!1)try{await t.getAccountInfo()}catch(s){const i=s;throw i.code===O.NoResponders&&(i.code=O.JetStreamNotEnabled),i}return t}jetstream(e={}){return new Us(this,e)}getServerVersion(){const e=this.info;return e?Ke(e.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw N.errorForCode(O.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 io(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(N.errorForCode(O.ConnectionClosed)):this.isDraining()?Promise.reject(N.errorForCode(O.ConnectionDraining)):this.protocol.reconnect()}}class io{constructor(e){h(this,"nc");this.nc=e}add(e){try{return new xt(this.nc,e).start()}catch(t){return Promise.reject(t)}}client(e,t){return new Un(this.nc,e,t)}}class no{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(zt)||"PUT"}get length(){const e=this.sm.header.get(fe.MessageSizeHdr)||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class oo{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(fs(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var e;return((e=this.sm.headers)==null?void 0:e.get(zt))||"PUT"}get delta(){return this.sm.info.pending}get length(){var t;const e=((t=this.sm.headers)==null?void 0:t.get(fe.MessageSizeHdr))||"";return e!==""?parseInt(e,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Hr extends Vi{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=$e(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const n=this.info;n.config.name=qe.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=Z.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(d=>{const p=d,_=this.sub.info;_.last=p,this.info.config=p.config,this.info.name=p.name}).catch(d=>{const p=new N(`unable to recreate ordered consumer ${n.stream} at seq ${t}`,O.RequestError,d);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(fs(t))}_setupHbMonitoring(t,s=0){const i={cancelAfter:0,maxOut:2};s&&(i.cancelAfter=s);const n=this.sub,o=a=>{var _,y,x,P;const d=ki(409,`${Ee.IdleHeartbeatMissed}: ${a}`,this.sub.subject);if(!((_=this.info)==null?void 0:_.ordered))this.sub.callback(null,d);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),(P=this.monitor)==null||P.restart(),!1}return!n.noIterator};this.monitor=new gs(t,o,i)}_checkHbOrderConsumer(t){const s=t.headers.get(fe.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const i=parseInt(t.headers.get(fe.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 ao extends Hr{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=G(a));let d=0;if(e.idle_heartbeat&&e.idle_heartbeat>0&&(d=e.idle_heartbeat,o.idle_heartbeat=G(d)),d&&a===0)throw new Error("idle_heartbeat requires expires");if(d>a)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),a&&d&&(this.monitor?this.monitor._change(d,a):this._setupHbMonitoring(d,a));const p=this.info.api,_=`${p.prefix}.CONSUMER.MSG.NEXT.${t}.${n}`,y=this.sub.subject;p.nc.publish(_,p.jc.encode(o),{reply:y})}}}function co(r,e){return r?uo(e):ho(e)}function ho(r){return(e,t)=>e?[e,null]:(e=Qe(t),e?[e,null]:[null,Et(t,r)])}function uo(r){return(e,t)=>{if(e)return[e,null];const s=Qe(t);return s!==null?[Jr(s),null]:[null,Et(t,r)]}}function Jr(r){if(r!==null)switch(r.code){case O.JetStream404NoMessages:case O.JetStream408RequestTimeout:return null;case O.JetStream409:return Ci(r)?r:null;default:return r}return null}function lo(r){r&&r.ack()}function fo(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 po{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=fo(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]===vt[0]&&e[1]===vt[1]&&e[2]===vt[2]&&e[3]===vt[3]}async ackAck(e){var s;e=e||{},e.timeout=e.timeout||this.timeout;const t=z();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 Sr(n.muxSubscriptions,this.msg.reply,{timeout:e.timeout},o);n.request(a);try{n.publish(this.msg.reply,Fr,{reply:`${n.muxSubscriptions.baseInbox}${a.token}`})}catch(d){a.cancel(d)}try{await Promise.race([a.timer,a.deferred]),t.resolve(!0)}catch(d){a.cancel(d),t.reject(d)}}else t.resolve(!1);return t}ack(){this.doAck(Fr)}nak(e){let t=Kn;e&&(t=lr().encode(`-NAK ${JSON.stringify({delay:G(e)})}`)),this.doAck(t)}working(){this.doAck(vt)}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=G(t.expires));const i=ve().encode(s),n=rt.concat(Vn,Yn,i),o=e?{reply:e}:void 0;this.msg.respond(n,o)}term(e=""){let t=Wn;(e==null?void 0:e.length)>0&&(t=lr().encode(`+TERM ${e}`)),this.doAck(t)}json(){return this.msg.json()}string(){return this.msg.string()}}const mo="1.30.3",bo="nats.ws";class go{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=mo,this.lang=bo,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=z(),this.closedNotification=z()}async connect(e,t){const s=z();if(t.tls)return s.reject(new N("tls",O.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=rt.concat(...this.yields),a=en(o);if(a!==""){const d=Cn.exec(a);if(!d){t.debug&&console.error("!!!",Mt(o)),s.reject(new Error("unexpected response from server"));return}try{const p=JSON.parse(d[1]);On(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,O.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 Xe(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(`> ${Mt(e[t])}`),yield e[t];if(this.done)break;this.yields.length===0&&(e.length=0,this.yields=e,this.signal=z())}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(!this.isDiscarded())try{this.socket.send(e.buffer),this.options.debug&&console.info(`< ${Mt(e)}`);return}catch(t){this.options.debug&&console.error(`!!! ${Mt(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 _o(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,d=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}${d}${p}`}function yo(r={}){return Wi({defaultPort:443,urlParseFn:_o,factory:()=>new go}),Ls.connect(r)}const ze=ve();class qs{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}async connect(e={}){var a;const{natsWsServerUrls:t,user:s,prefix:i}=e,n=t??[this.config.natsUrl];this.nc=await yo({servers:n});const o=s??new cs({authUrl:""}).getLastLoginData();if(!o)throw new Error("Please authenticate first by calling `auth` apis");this.userId=o.userId,this.sessionId=o.sessionId,this.globalPrefix=i??"",this.resolveConnected(!0),(a=this.onStatusChange)==null||a.call(this,!0),console.log("[nats] connected.",this.globalPrefix?`(prefix: ${this.globalPrefix})`:""),(async()=>{var d,p;for await(const _ of this.nc.status())switch(_.type!==Fe.PingTimer&&console.log("[nats] connection status:",_.type),_.type){case Se.Reconnect:(d=this.onStatusChange)==null||d.call(this,!0);break;case Se.Disconnect:case Se.Error:case Fe.Reconnecting:(p=this.onStatusChange)==null||p.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,ze.encode(t))}catch(s){throw console.error("[nats] publish failed:",s),s}}async call(e,t,s){if(await this.isConnected,!this.nc)throw new Error("[nats] not connected");try{const i=this.buildSubject(e);console.debug("[nats]>>",i);const n=await this.nc.request(i,ze.encode(t),{timeout:(s==null?void 0:s.timeoutInMs)??5e3}),o=ze.decode(n.data);if(!o.ok)throw new Error(o.message);return o.data}catch(i){throw console.error("[nats] request failed:",i),new Error("Api call failed.")}}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 d=a.slice(0,a.length-2).join("."),p=a[a.length-2],_=a[a.length-1],y=ze.decode(o.data);t(y,{subject:d,userId:p,sessionId:_})}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 d=a.slice(0,a.length-2).join("."),p=a[a.length-2],_=a[a.length-1],y=ze.decode(o.data);try{const x=await t(y,{subject:d,userId:p,sessionId:_});o.reply&&o.respond(ze.encode({ok:!0,data:x}))}catch(x){console.error("[nats] handle",x),o.reply&&o.respond(ze.encode({ok:!1,message:x.message}))}}catch(a){console.error("[nats] handle",a),o.reply&&o.respond(ze.encode({ok:!1,message:a.message}))}})(),()=>n.unsubscribe()}buildSubject(e){return[this.globalPrefix,e,this.userId,this.sessionId].filter(t=>t).join(".")}}function zr(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 wo{async getAudioBuffer(e,t,s){const i=[],n=crypto.randomUUID();return new Promise((o,a)=>{const d=new WebSocket(`${Wt.WSS_URL}?trustedclienttoken=${Wt.TRUSTED_CLIENT_TOKEN}&ConnectionId=${n}`);d.binaryType="arraybuffer";const p=So(e,t,s);d.addEventListener("open",()=>{const _=xo();d.send(_);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
|
|
33
33
|
\r
|
|
34
34
|
`+p;d.send(y)}),d.addEventListener("message",_=>{const y=_.data;if(y instanceof ArrayBuffer){const x=new Uint8Array(y),P=new TextEncoder().encode(`Path:audio\r
|
|
35
|
-
`),I=
|
|
35
|
+
`),I=vo(x,P);if(I!==-1){const J=x.subarray(I+P.length);i.push(J)}new TextDecoder().decode(x).includes("Path:turn.end")&&d.close()}else y.includes("Path:turn.end")&&d.close()}),d.addEventListener("close",()=>{if(!i.length){a("No audio data available to save.");return}const _=i.reduce((P,I)=>P+I.length,0),y=new Uint8Array(_);let x=0;for(const P of i)y.set(P,x),x+=P.length;o(y.buffer)}),d.addEventListener("error",_=>{a(_)})})}async getAudio(e,t,s){return this.getAudioBuffer(e,t,s).then(i=>zr(i))}async getVoices(){return(await(await fetch(`${Wt.VOICES_URL}?trustedclienttoken=${Wt.TRUSTED_CLIENT_TOKEN}`)).json()).map(s=>({id:s.ShortName,locale:s.Locale,description:s.FriendlyName}))}}const Wt={TRUSTED_CLIENT_TOKEN:"6A5AA1D4EAFF4E9FB37E23D68491D6F4",WSS_URL:"wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1",VOICES_URL:"https://speech.platform.bing.com/consumer/speech/synthesize/readaloud/voices/list"},xo=()=>`X-Timestamp:${new Date().toISOString()}Z\r
|
|
36
36
|
Content-Type:application/json; charset=utf-8\r
|
|
37
37
|
Path:speech.config\r
|
|
38
38
|
\r
|
|
39
|
-
{"context":{"synthesis":{"audio":{"metadataoptions":{"sentenceBoundaryEnabled":false,"wordBoundaryEnabled":true},"outputFormat":"audio-24khz-48kbitrate-mono-mp3"}}}}`,So=(r,e,t={})=>{var o;t.pitch=(o=t.pitch)==null?void 0:o.replace("hz","Hz");const s=t.pitch||"0Hz",i=t.rate||"0%",n=t.volume||"0%";return`<speak version='1.0' xml:lang='en-US'><voice name='${e}'><prosody pitch='${s}' rate='${i}' volume='${n}'>${r}</prosody></voice></speak>`};function
|
|
39
|
+
{"context":{"synthesis":{"audio":{"metadataoptions":{"sentenceBoundaryEnabled":false,"wordBoundaryEnabled":true},"outputFormat":"audio-24khz-48kbitrate-mono-mp3"}}}}`,So=(r,e,t={})=>{var o;t.pitch=(o=t.pitch)==null?void 0:o.replace("hz","Hz");const s=t.pitch||"0Hz",i=t.rate||"0%",n=t.volume||"0%";return`<speak version='1.0' xml:lang='en-US'><voice name='${e}'><prosody pitch='${s}' rate='${i}' volume='${n}'>${r}</prosody></voice></speak>`};function vo(r,e){for(let t=0;t<=r.length-e.length;t++){let s=!0;for(let i=0;i<e.length;i++)if(r[t+i]!==e[i]){s=!1;break}if(s)return t}return-1}class Eo{constructor(e){this.config=e}async getAudioBuffer(e,t){const s=await fetch(`${this.config.voicevoxUrl}/audio_query?text=${encodeURIComponent(e)}&speaker=${t||3}`,{method:"POST",headers:{Accept:"application/json"}});if(!s.ok)throw new Error(`Audio query failed: ${s.statusText}`);const i=await s.json(),n=await fetch(`${this.config.voicevoxUrl}/synthesis?speaker=${t}`,{method:"POST",headers:{Accept:"audio/wav","Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.body)return null;const o=n.body.getReader(),a=[];for(;;){const{done:y,value:x}=await o.read();if(y)break;a.push(x)}const d=a.reduce((y,x)=>y+x.length,0),p=new Uint8Array(d);let _=0;for(const y of a)p.set(y,_),_+=y.length;return p.buffer}async getAudio(e,t){return this.getAudioBuffer(e,t).then(s=>s?zr(s):null)}async getVoices(){return(await fetch(`${this.config.voicevoxUrl}/speakers`).then(t=>t.json())).flatMap(t=>t.styles.map(s=>({id:s.id.toString(),locale:"ja-JP",description:`${t.name} - ${s.name}`})))}}const Gr={debug:!1,authUrl:"https://auth.jok.io",natsUrl:"https://natsx.jok.io"},Ao={setup(r){r.authUrl&&(this.auth=new cs({authUrl:r.authUrl})),r.natsUrl&&(this.nats=new qs({natsUrl:r.natsUrl}))},auth:new cs(Gr),tts:new wo,nats:new qs(Gr),crypto:new gi};me.NatsService=qs,me.VoicevoxTtsService=Eo,me.jok=Ao,Object.defineProperty(me,Symbol.toStringTag,{value:"Module"})});
|